在Rust中高效地写入多个字节 [英] Writing to multiple bytes efficiently in Rust

查看:315
本文介绍了在Rust中高效地写入多个字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Rust中使用原始指针,并试图将一个内存区域从一个地方复制到另一个地方.我已经成功地复制了内存,但是仅使用了for循环并使用指针的偏移量分别复制了每个字节.我无法弄清楚如何更有效地执行此操作,即作为一个字节字符串的单个副本,有人可以向我指出正确的方向吗?

I'm working with raw pointers in Rust and am trying to copy an area of memory from one place to another. I've got it successfully copying memory over, but only using a for loop and copying each byte individually using an offset of the pointer. I can't figure out how to do this more efficiently, i.e. as a single copy of a string of bytes, can anyone point me in the right direction?

fn copy_block_memory<T>(src: *const T, dst: *mut u8) {
    let src = src as *const u8;
    let size = mem::size_of::<T>();
    unsafe {
        let bytes = slice::from_raw_parts(src, size);
        for i in 0..size as isize {
            ptr::write(dst.offset(i), bytes[i as usize]);
        }
    }
}

推荐答案

正如评论中提到的@ker一样,它实际上是在标准库中构建的:

As @ker mentioned in the comments, this is actually built in the standard library:

  • std::ptr::copy is equivalent to C's memmove
  • std::ptr::copy_nonoverlapping is equivalent to C's memcpy

请注意,以Rust的方式移动对象(从而转移所有权)只是复制位,除非对象是Copy,否则您需要确保仅使用srcdst中的一个(和复制后).

Note that while in Rust's way of moving objects (and thus transferring ownership) is just copying bits, unless an object is Copy, you need to ensure that only one of src or dst is used (and dropped) after the copy.

这篇关于在Rust中高效地写入多个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆