Overlapping Copy With copy_within

Shift bytes inside one slice with copy_within, which tolerates overlapping source and destination like memmove and panics only on out of range indices.

RustData Integrity

Code

rustsnippet
20 lines
fn main() {
    let mut bytes = [0u8; 8];
    bytes[..4].copy_from_slice(&[1, 2, 3, 4]);

    // 把前 4 个字节搬到偏移 2 处:源与目标重叠,copy_within 自己处理
    bytes.copy_within(0..4, 2);
    println!("after overlap copy: {bytes:?}");

    let mut label = *b"abcdefgh";
    // 把尾部三个字符搬到开头,剩余保持原位
    label.copy_within(5..8, 0);
    println!("moved tail: {:?}", std::str::from_utf8(&label).unwrap());

    // 目标区间越界会 panic,先按长度自查
    let n = 3;
    if n * 2 <= label.len() {
        label.copy_within(0..n, n);
        println!("shifted: {:?}", std::str::from_utf8(&label).unwrap());
    }
}

How it works

The working surface is the function main — everything else is wiring.

Points of care

  • The only prerequisite is the language toolchain itself.

Applying it

The main signature reads fn main()

Expect labeled output — after overlap copy:, moved tail:, shifted: — when the file runs.

Statements that matter

bytes[..4].copy_from_slice(&[1, 2, 3, 4]);
let mut label = *b"abcdefgh";
bytes.copy_within(0..4, 2);

Interactive Tools for This Topic

FAQ

What does Overlapping Copy With copy_within print when run?
Execute the whole file; each printed line is prefixed with a label like `after overlap copy:`, `moved tail:`, `shifted:`.