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