@@ -70,18 +70,34 @@ impl Drop for AbortOnPanic {
70
70
}
71
71
}
72
72
73
+ /// Unsafe extension functions for `Vec<T>`
73
74
trait VecExtensions < T > {
74
- unsafe fn swap_remove_nonoverlapping_unchecked ( & mut self , index : usize ) ;
75
+ /// Removes an element from the vector and returns it.
76
+ ///
77
+ /// The removed element is replaced by the last element of the vector.
78
+ ///
79
+ /// This does not preserve ordering of the remaining elements, but is O(1). If you need to preserve the element order, use [`remove`] instead.
80
+ ///
81
+ /// Unlike [`swap_remove`], this does not panic if `index` is out of bounds.
82
+ ///
83
+ /// # Safety
84
+ /// `index < self.len() - 1` must be true.
85
+ ///
86
+ /// [`remove`]: alloc::vec::Vec::remove
87
+ /// [`swap_remove`]: alloc::vec::Vec::swap_remove
88
+ unsafe fn swap_remove_nonoverlapping_unchecked ( & mut self , index : usize ) -> T ;
75
89
}
76
90
77
91
impl < T > VecExtensions < T > for Vec < T > {
78
- unsafe fn swap_remove_nonoverlapping_unchecked ( & mut self , index : usize ) {
92
+ unsafe fn swap_remove_nonoverlapping_unchecked ( & mut self , index : usize ) -> T {
93
+ let value = core:: ptr:: read ( self . as_mut_ptr ( ) . add ( index) ) ;
79
94
let len = self . len ( ) ;
80
95
// We replace self[index] with the last element. Note that if the
81
96
// bounds check above succeeds there must be a last element (which
82
97
// can be self[index] itself).
83
98
let base_ptr = self . as_mut_ptr ( ) ;
84
99
core:: ptr:: copy_nonoverlapping ( base_ptr. add ( len - 1 ) , base_ptr. add ( index) , 1 ) ;
85
100
self . set_len ( len - 1 ) ;
101
+ value
86
102
}
87
103
}
0 commit comments