allocator_api2/vec/
drain.rs

1use core::fmt;
2use core::iter::FusedIterator;
3use core::mem::{self, size_of, ManuallyDrop};
4use core::ptr::{self, NonNull};
5use core::slice::{self};
6
7use crate::alloc::{Allocator, Global};
8
9use super::Vec;
10
11/// A draining iterator for `Vec<T>`.
12///
13/// This `struct` is created by [`Vec::drain`].
14/// See its documentation for more.
15///
16/// # Example
17///
18/// ```
19/// use allocator_api2::vec;
20///
21/// let mut v = vec![0, 1, 2];
22/// let iter: vec::Drain<_> = v.drain(..);
23/// ```
24pub struct Drain<'a, T: 'a, A: Allocator + 'a = Global> {
25    /// Index of tail to preserve
26    pub(super) tail_start: usize,
27    /// Length of tail
28    pub(super) tail_len: usize,
29    /// Current remaining range to remove
30    pub(super) iter: slice::Iter<'a, T>,
31    pub(super) vec: NonNull<Vec<T, A>>,
32}
33
34impl<T: fmt::Debug, A: Allocator> fmt::Debug for Drain<'_, T, A> {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
37    }
38}
39
40impl<'a, T, A: Allocator> Drain<'a, T, A> {
41    /// Returns the remaining items of this iterator as a slice.
42    ///
43    /// # Examples
44    ///
45    /// ```
46    /// use allocator_api2::vec;
47    ///
48    /// let mut vec = vec!['a', 'b', 'c'];
49    /// let mut drain = vec.drain(..);
50    /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']);
51    /// let _ = drain.next().unwrap();
52    /// assert_eq!(drain.as_slice(), &['b', 'c']);
53    /// ```
54    #[must_use]
55    #[inline(always)]
56    pub fn as_slice(&self) -> &[T] {
57        self.iter.as_slice()
58    }
59
60    /// Returns a reference to the underlying allocator.
61    #[must_use]
62    #[inline(always)]
63    pub fn allocator(&self) -> &A {
64        unsafe { self.vec.as_ref().allocator() }
65    }
66
67    /// Keep unyielded elements in the source `Vec`.
68    ///
69    /// # Examples
70    ///
71    /// ```
72    /// use allocator_api2::vec;
73    ///
74    /// let mut vec = vec!['a', 'b', 'c'];
75    /// let mut drain = vec.drain(..);
76    ///
77    /// assert_eq!(drain.next().unwrap(), 'a');
78    ///
79    /// // This call keeps 'b' and 'c' in the vec.
80    /// drain.keep_rest();
81    ///
82    /// // If we wouldn't call `keep_rest()`,
83    /// // `vec` would be empty.
84    /// assert_eq!(vec, ['b', 'c']);
85    /// ```
86    #[inline(always)]
87    pub fn keep_rest(self) {
88        // At this moment layout looks like this:
89        //
90        // [head] [yielded by next] [unyielded] [yielded by next_back] [tail]
91        //        ^-- start         \_________/-- unyielded_len        \____/-- self.tail_len
92        //                          ^-- unyielded_ptr                  ^-- tail
93        //
94        // Normally `Drop` impl would drop [unyielded] and then move [tail] to the `start`.
95        // Here we want to
96        // 1. Move [unyielded] to `start`
97        // 2. Move [tail] to a new start at `start + len(unyielded)`
98        // 3. Update length of the original vec to `len(head) + len(unyielded) + len(tail)`
99        //    a. In case of ZST, this is the only thing we want to do
100        // 4. Do *not* drop self, as everything is put in a consistent state already, there is nothing to do
101        let mut this = ManuallyDrop::new(self);
102
103        unsafe {
104            let source_vec = this.vec.as_mut();
105
106            let start = source_vec.len();
107            let tail = this.tail_start;
108
109            let unyielded_len = this.iter.len();
110            let unyielded_ptr = this.iter.as_slice().as_ptr();
111
112            // ZSTs have no identity, so we don't need to move them around.
113            let needs_move = mem::size_of::<T>() != 0;
114
115            if needs_move {
116                let start_ptr = source_vec.as_mut_ptr().add(start);
117
118                // memmove back unyielded elements
119                if unyielded_ptr != start_ptr {
120                    let src = unyielded_ptr;
121                    let dst = start_ptr;
122
123                    ptr::copy(src, dst, unyielded_len);
124                }
125
126                // memmove back untouched tail
127                if tail != (start + unyielded_len) {
128                    let src = source_vec.as_ptr().add(tail);
129                    let dst = start_ptr.add(unyielded_len);
130                    ptr::copy(src, dst, this.tail_len);
131                }
132            }
133
134            source_vec.set_len(start + unyielded_len + this.tail_len);
135        }
136    }
137}
138
139impl<'a, T, A: Allocator> AsRef<[T]> for Drain<'a, T, A> {
140    #[inline(always)]
141    fn as_ref(&self) -> &[T] {
142        self.as_slice()
143    }
144}
145
146unsafe impl<T: Sync, A: Sync + Allocator> Sync for Drain<'_, T, A> {}
147
148unsafe impl<T: Send, A: Send + Allocator> Send for Drain<'_, T, A> {}
149
150impl<T, A: Allocator> Iterator for Drain<'_, T, A> {
151    type Item = T;
152
153    #[inline(always)]
154    fn next(&mut self) -> Option<T> {
155        self.iter
156            .next()
157            .map(|elt| unsafe { ptr::read(elt as *const _) })
158    }
159
160    #[inline(always)]
161    fn size_hint(&self) -> (usize, Option<usize>) {
162        self.iter.size_hint()
163    }
164}
165
166impl<T, A: Allocator> DoubleEndedIterator for Drain<'_, T, A> {
167    #[inline(always)]
168    fn next_back(&mut self) -> Option<T> {
169        self.iter
170            .next_back()
171            .map(|elt| unsafe { ptr::read(elt as *const _) })
172    }
173}
174
175impl<T, A: Allocator> Drop for Drain<'_, T, A> {
176    #[inline]
177    fn drop(&mut self) {
178        /// Moves back the un-`Drain`ed elements to restore the original `Vec`.
179        struct DropGuard<'r, 'a, T, A: Allocator>(&'r mut Drain<'a, T, A>);
180
181        impl<'r, 'a, T, A: Allocator> Drop for DropGuard<'r, 'a, T, A> {
182            fn drop(&mut self) {
183                if self.0.tail_len > 0 {
184                    unsafe {
185                        let source_vec = self.0.vec.as_mut();
186                        // memmove back untouched tail, update to new length
187                        let start = source_vec.len();
188                        let tail = self.0.tail_start;
189                        if tail != start {
190                            let src = source_vec.as_ptr().add(tail);
191                            let dst = source_vec.as_mut_ptr().add(start);
192                            ptr::copy(src, dst, self.0.tail_len);
193                        }
194                        source_vec.set_len(start + self.0.tail_len);
195                    }
196                }
197            }
198        }
199
200        let iter = mem::replace(&mut self.iter, [].iter());
201        let drop_len = iter.len();
202
203        let mut vec = self.vec;
204
205        if size_of::<T>() == 0 {
206            // ZSTs have no identity, so we don't need to move them around, we only need to drop the correct amount.
207            // this can be achieved by manipulating the Vec length instead of moving values out from `iter`.
208            unsafe {
209                let vec = vec.as_mut();
210                let old_len = vec.len();
211                vec.set_len(old_len + drop_len + self.tail_len);
212                vec.truncate(old_len + self.tail_len);
213            }
214
215            return;
216        }
217
218        // ensure elements are moved back into their appropriate places, even when drop_in_place panics
219        let _guard = DropGuard(self);
220
221        if drop_len == 0 {
222            return;
223        }
224
225        // as_slice() must only be called when iter.len() is > 0 because
226        // vec::Splice modifies vec::Drain fields and may grow the vec which would invalidate
227        // the iterator's internal pointers. Creating a reference to deallocated memory
228        // is invalid even when it is zero-length
229        let drop_ptr = iter.as_slice().as_ptr();
230
231        unsafe {
232            // drop_ptr comes from a slice::Iter which only gives us a &[T] but for drop_in_place
233            // a pointer with mutable provenance is necessary. Therefore we must reconstruct
234            // it from the original vec but also avoid creating a &mut to the front since that could
235            // invalidate raw pointers to it which some unsafe code might rely on.
236            let vec_ptr = vec.as_mut().as_mut_ptr();
237            let drop_offset = drop_ptr.offset_from(vec_ptr) as usize;
238            let to_drop = ptr::slice_from_raw_parts_mut(vec_ptr.add(drop_offset), drop_len);
239            ptr::drop_in_place(to_drop);
240        }
241    }
242}
243
244impl<T, A: Allocator> ExactSizeIterator for Drain<'_, T, A> {}
245
246impl<T, A: Allocator> FusedIterator for Drain<'_, T, A> {}