std: Clean up the swap function a little

This commit is contained in:
Brian Anderson 2014-02-09 14:05:31 -08:00
parent 1b7733109d
commit 07c5e5d813
1 changed files with 5 additions and 8 deletions

View File

@ -26,19 +26,16 @@ pub fn id<T>(x: T) -> T { x }
pub fn swap<T>(x: &mut T, y: &mut T) {
unsafe {
// Give ourselves some scratch space to work with
let mut tmp: T = mem::uninit();
let t: *mut T = &mut tmp;
let mut t: T = mem::uninit();
// Perform the swap, `&mut` pointers never alias
let x_raw: *mut T = x;
let y_raw: *mut T = y;
ptr::copy_nonoverlapping_memory(t, &*x_raw, 1);
ptr::copy_nonoverlapping_memory(x, &*y_raw, 1);
ptr::copy_nonoverlapping_memory(y, &*t, 1);
ptr::copy_nonoverlapping_memory(&mut t, &*x, 1);
ptr::copy_nonoverlapping_memory(x, &*y, 1);
ptr::copy_nonoverlapping_memory(y, &t, 1);
// y and t now point to the same thing, but we need to completely forget `tmp`
// because it's no longer relevant.
cast::forget(tmp);
cast::forget(t);
}
}