Skip to content

Commit 713abb8

Browse files
committed
Fix undefined behavior in Vec::swap_remove_unchecked()
1 parent f7eb544 commit 713abb8

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

src/vec.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -482,11 +482,11 @@ impl<T, const N: usize> Vec<T, N> {
482482
pub unsafe fn swap_remove_unchecked(&mut self, index: usize) -> T {
483483
let length = self.len();
484484
debug_assert!(index < length);
485-
ptr::swap(
486-
self.as_mut_slice().get_unchecked_mut(index),
487-
self.as_mut_slice().get_unchecked_mut(length - 1),
488-
);
489-
self.pop_unchecked()
485+
let value = ptr::read(self.as_ptr().add(index));
486+
let base_ptr = self.as_mut_ptr();
487+
ptr::copy(base_ptr.add(length - 1), base_ptr.add(index), 1);
488+
self.len -= 1;
489+
value
490490
}
491491

492492
/// Returns true if the vec is full

0 commit comments

Comments
 (0)