std-function

Copy overlapping memory ranges

ptr::copy permits overlapping source and destination ranges. Count is measured in elements, not bytes. Prove alignment and valid read/write spans; byte copying does not automatically make duplicate resource ownership safe. For safe slices, prefer copy_within. Expected stdout (not executed): [1, 1, 2, 3] Common mistake: Using copy_nonoverlapping when the source and destination overlap.

Formal Syntax & Structure

rust syntaxrust
unsafe { std::ptr::copy(src, dst, count) }

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    let mut items = [1_u8, 2, 3, 4];    let p = items.as_mut_ptr();    // SAFETY: both three-element ranges are inside the same array; overlap is permitted.    unsafe { std::ptr::copy(p, p.add(1), 3); }    println!("{items:?}");}
Rust Reference