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