pub unsafe fn copy<T>(src: *const T, dst: *mut T, count: usize)
Expand description
Copies count * size_of::<T>()
bytes from src
to dst
. The source
and destination may overlap.
If the source and destination will never overlap,
copy_nonoverlapping
can be used instead.
copy
is semantically equivalent to C’s memmove
, but with the argument
order swapped. Copying takes place as if the bytes were copied from src
to a temporary array and then copied from the array to dst
.
The copy is “untyped” in the sense that data may be uninitialized or otherwise violate the
requirements of T
. The initialization state is preserved exactly.
§Safety
Behavior is undefined if any of the following conditions are violated:
-
src
must be valid for reads ofcount * size_of::<T>()
bytes, and must remain valid even whendst
is written forcount * size_of::<T>()
bytes. (This means if the memory ranges overlap, the two pointers must not be subject to aliasing restrictions relative to each other.) -
dst
must be valid for writes ofcount * size_of::<T>()
bytes, and must remain valid even whensrc
is read forcount * size_of::<T>()
bytes. -
Both
src
anddst
must be properly aligned.
Like read
, copy
creates a bitwise copy of T
, regardless of
whether T
is Copy
. If T
is not Copy
, using both the values
in the region beginning at *src
and the region beginning at *dst
can
violate memory safety.
Note that even if the effectively copied size (count * size_of::<T>()
) is
0
, the pointers must be non-null and properly aligned.
§Examples
Efficiently create a Rust vector from an unsafe buffer:
use std::ptr;
/// # Safety
///
/// * `ptr` must be correctly aligned for its type and non-zero.
/// * `ptr` must be valid for reads of `elts` contiguous elements of type `T`.
/// * Those elements must not be used after calling this function unless `T: Copy`.
unsafe fn from_buf_raw<T>(ptr: *const T, elts: usize) -> Vec<T> {
let mut dst = Vec::with_capacity(elts);
// SAFETY: Our precondition ensures the source is aligned and valid,
// and `Vec::with_capacity` ensures that we have usable space to write them.
ptr::copy(ptr, dst.as_mut_ptr(), elts);
// SAFETY: We created it with this much capacity earlier,
// and the previous `copy` has initialized these elements.
dst.set_len(elts);
dst
}