Skip to content

Commit 6faa295

Browse files
committed
Reimplemented Vec's swap_remove to not rely on pop.
1 parent 295768a commit 6faa295

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

src/liballoc/vec.rs

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

0 commit comments

Comments
 (0)