rune_alloc/vec/
drain.rs

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