Writing to multiple bytes efficiently in Rust

2019-06-25 13:13发布

问题:

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]);
        }
    }
}

回答1:

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

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.