5

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]);
        }
    }
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Harvey Adcock
  • 929
  • 1
  • 7
  • 16
  • 1
    LLVM (rustc's backend) will certainly detect such loops and optimise them to the fastest code possible. –  Mar 11 '16 at 11:04
  • 9
    you can use [std::ptr::copy](https://doc.rust-lang.org/std/ptr/fn.copy.html) or [std::ptr::copy_nonoverlapping](https://doc.rust-lang.org/std/ptr/fn.copy_nonoverlapping.html) (the latter probably, as you memory locations probably don't overlap (you need to guarantee this)) – oli_obk Mar 11 '16 at 11:25
  • 4
    @ker You should make that into an answer. – starblue Mar 11 '16 at 13:32

1 Answers1

7

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

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.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722