Function core::intrinsics::copy_nonoverlapping 1.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 must not overlap.
For regions of memory which might overlap, use copy instead.
copy_nonoverlapping is semantically equivalent to C's memcpy.
Safety
Behavior is undefined if any of the following conditions are violated:
-
The region of memory which begins at
srcand has a length ofcount * size_of::<T>()bytes must be both valid and initialized. -
The region of memory which begins at
dstand has a length ofcount * size_of::<T>()bytes must be valid (but may or may not be initialized). -
The two regions of memory must not overlap.
-
srcmust be properly aligned. -
dstmust be properly aligned.
Additionally, if T is not Copy, only the region at src or the
region at dst can be used or dropped after calling
copy_nonoverlapping. copy_nonoverlapping creates bitwise copies of
T, regardless of whether T: Copy, which can result in undefined
behavior if both copies are used.
Examples
Manually implement Vec::append:
use std::ptr; /// Moves all the elements of `src` into `dst`, leaving `src` empty. fn append<T>(dst: &mut Vec<T>, src: &mut Vec<T>) { let src_len = src.len(); let dst_len = dst.len(); // Ensure that `dst` has enough capacity to hold all of `src`. dst.reserve(src_len); unsafe { // The call to offset is always safe because `Vec` will never // allocate more than `isize::MAX` bytes. let dst = dst.as_mut_ptr().offset(dst_len as isize); let src = src.as_ptr(); // The two regions cannot overlap becuase mutable references do // not alias, and two different vectors cannot own the same // memory. ptr::copy_nonoverlapping(src, dst, src_len); } unsafe { // Truncate `src` without dropping its contents. src.set_len(0); // Notify `dst` that it now holds the contents of `src`. dst.set_len(dst_len + src_len); } } let mut a = vec!['r']; let mut b = vec!['u', 's', 't']; append(&mut a, &mut b); assert_eq!(a, &['r', 'u', 's', 't']); assert!(b.is_empty());Run