Skip to main content

alloc/vec/
drain.rs

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