Writing to multiple bytes efficiently in Rust

旧城冷巷雨未停 提交于 2019-12-10 15:35:43

问题


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.



来源:https://stackoverflow.com/questions/35938561/writing-to-multiple-bytes-efficiently-in-rust

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!