core::intrinsics::copy_nonoverlapping_memoryUnstable
[-]
[+]
[src]
pub unsafe fn copy_nonoverlapping_memory<T>(dst: *mut T, src: *const T, count: uint)
Copies count * size_of<T> bytes from src to dst. The source
and destination may not overlap.
copy_nonoverlapping_memory is semantically equivalent to C's memcpy.
Safety
Beyond requiring that both regions of memory be allocated, it is Undefined Behaviour
for source and destination to overlap. Care must also be taken with the ownership of
src and dst. This method semantically moves the values of src into dst.
However it does not drop the contents of dst, or prevent the contents of src
from being dropped or used.
Examples
A safe swap function:
fn main() { use std::mem; use std::ptr; fn swap<T>(x: &mut T, y: &mut T) { unsafe { // Give ourselves some scratch space to work with let mut t: T = mem::uninitialized(); // Perform the swap, `&mut` pointers never alias ptr::copy_nonoverlapping_memory(&mut t, &*x, 1); ptr::copy_nonoverlapping_memory(x, &*y, 1); ptr::copy_nonoverlapping_memory(y, &t, 1); // y and t now point to the same thing, but we need to completely forget `tmp` // because it's no longer relevant. mem::forget(t); } } }use std::mem; use std::ptr; fn swap<T>(x: &mut T, y: &mut T) { unsafe { // Give ourselves some scratch space to work with let mut t: T = mem::uninitialized(); // Perform the swap, `&mut` pointers never alias ptr::copy_nonoverlapping_memory(&mut t, &*x, 1); ptr::copy_nonoverlapping_memory(x, &*y, 1); ptr::copy_nonoverlapping_memory(y, &t, 1); // y and t now point to the same thing, but we need to completely forget `tmp` // because it's no longer relevant. mem::forget(t); } }