Function std::ptr::copy_nonoverlapping1.0.0[][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 to dst. The source and destination may not overlap.

copy_nonoverlapping is semantically equivalent to C's memcpy.


Beyond requiring that the program must be allowed to access both regions of memory, it is Undefined Behavior 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.


A safe swap function:

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 `t`
        // because it's no longer relevant.