Swap Whole Buffers With Swap With Slice

Exchange the contents of two slices in bulk with swap_with_slice, the double-buffer flip that copies nothing and needs no loops.

RustData Integrity

Code

rustsnippet
21 lines
fn main() {
    // Two rotating buffers: swap_with_slice exchanges contents in bulk
    let mut front = vec![1, 2, 3, 4];
    let mut back = vec![10, 20, 30, 40];

    front[..2].swap_with_slice(&mut back[..2]);
    println!("front: {front:?}");
    println!("back: {back:?}");

    // Lengths may differ: only the overlapping prefix is exchanged
    let mut a = [1u8, 2, 3];
    let mut b = [9u8; 5];
    a.swap_with_slice(&mut b);
    println!("a: {a:?}");
    println!("b: {b:?}");

    // Full-length swap is the common double-buffer flip
    a.swap_with_slice(&mut b[..3]);
    println!("a again: {a:?}");
    println!("b again: {b:?}");
}

The flow of the file

Everything happens inside the function main.

Watch out for

  • There is nothing to declare: the runtime ships every API this file touches.

Applying it

The signature in play: fn main()

Output lines are prefixed (front:, back:, a:), so the printed lines stay attributable to their steps.

Statements that matter

front[..2].swap_with_slice(&mut back[..2]);
let mut back = vec![10, 20, 30, 40];
let mut front = vec![1, 2, 3, 4];

Interactive Tools for This Topic

FAQ

What does Swap Whole Buffers With Swap With Slice print when run?
Execute the whole file; each printed line is prefixed with a label like `front:`, `back:`, `a:`.