Writing to multiple bytes efficiently in Rust
Asked Answered
G

1

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]);
        }
    }
}
Gordie answered 11/3, 2016 at 11:2 Comment(3)
LLVM (rustc's backend) will certainly detect such loops and optimise them to the fastest code possible.Paly
you can use std::ptr::copy or std::ptr::copy_nonoverlapping (the latter probably, as you memory locations probably don't overlap (you need to guarantee this))Emend
@ker You should make that into an answer.Grigson
O
8

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.

Ozuna answered 11/3, 2016 at 11:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.