1
Fork 0

Reimplemented Vec's swap_remove to not rely on pop.

This commit is contained in:
Orson Peters 2018-07-09 06:13:58 +02:00
parent 295768ae8f
commit 6faa295cec

View file

@ -810,11 +810,13 @@ impl<T> Vec<T> {
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub fn swap_remove(&mut self, index: usize) -> T { pub fn swap_remove(&mut self, index: usize) -> T {
unsafe { unsafe {
// We replace self[index] with the last element. Note that this is // We replace self[index] with the last element. Note that if the
// safe even when index == self.len() - 1, as pop() only uses // bounds check on hole succeeds there must be a last element (which
// ptr::read and leaves the memory at self[index] untouched. // can be self[index] itself).
let hole: *mut T = &mut self[index]; let hole: *mut T = &mut self[index];
ptr::replace(hole, self.pop().unwrap()) let last = ptr::read(self.get_unchecked(self.len - 1));
self.len -= 1;
ptr::replace(hole, last)
} }
} }