We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 960f604 commit 295768aCopy full SHA for 295768a
src/liballoc/vec.rs
@@ -809,9 +809,13 @@ impl<T> Vec<T> {
809
#[inline]
810
#[stable(feature = "rust1", since = "1.0.0")]
811
pub fn swap_remove(&mut self, index: usize) -> T {
812
- let length = self.len();
813
- self.swap(index, length - 1);
814
- self.pop().unwrap()
+ unsafe {
+ // We replace self[index] with the last element. Note that this is
+ // safe even when index == self.len() - 1, as pop() only uses
815
+ // ptr::read and leaves the memory at self[index] untouched.
816
+ let hole: *mut T = &mut self[index];
817
+ ptr::replace(hole, self.pop().unwrap())
818
+ }
819
}
820
821
/// Inserts an element at position `index` within the vector, shifting all
0 commit comments