Function std::intrinsics::copy_nonoverlapping
[−]
[src]
pub unsafe extern "rust-intrinsic" fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize)
Copies count * size_of<T>
bytes from src
`srcto
` to dst
`dst`. The source
and destination may not overlap.
copy_nonoverlapping
is semantically equivalent to C's memcpy
`memcpy`.
Safety
Beyond requiring that the program must be allowed to access both regions
of memory, it is Undefined Behaviour for source and destination to
overlap. Care must also be taken with the ownership of src
`srcand
` and
dst
`dst. This method semantically moves the values of
srcinto
` into dst
`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(x, &mut t, 1); ptr::copy_nonoverlapping(y, x, 1); ptr::copy_nonoverlapping(&t, y, 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(x, &mut t, 1); ptr::copy_nonoverlapping(y, x, 1); ptr::copy_nonoverlapping(&t, y, 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); } }