Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does `std::mem::swap` work?

Tags:

memory

rust

swap

Swap the values at two mutable locations of the same type, without deinitialising or copying either one.

use std::mem;

let x = &mut 5;
let y = &mut 42;

mem::swap(x, y);

assert_eq!(42, *x);
assert_eq!(5, *y);

(From offical Rust doc)

How can two values be swapped without copying? How did the value 42 go from y to x? This shouldn't be possible.

like image 911
Kapichu Avatar asked Jul 03 '15 19:07

Kapichu


1 Answers

The function does actually make a copy internally: here is its source extracted from the documentation:

pub fn swap<T>(x: &mut T, y: &mut T) {
    unsafe {
        // Give ourselves some scratch space to work with
        let mut t: T = uninitialized();

        // Perform the swap, `&mut` pointers never alias
        ptr::copy_nonoverlapping(&*x, &mut t, 1);
        ptr::copy_nonoverlapping(&*y, x, 1);
        ptr::copy_nonoverlapping(&t, y, 1);

        // y and t now point to the same thing,
        // but we need to completely forget `t`
        // because it's no longer relevant.
        forget(t);
    }
}
like image 80
Levans Avatar answered Oct 19 '22 17:10

Levans