Skip to main content

core/array/iter/
iter_inner.rs

1//! Defines the `IntoIter` owned iterator for arrays.
2
3use crate::clone::TrivialClone;
4use crate::mem::MaybeUninit;
5use crate::num::NonZero;
6use crate::ops::{IndexRange, NeverShortCircuit, Try};
7use crate::{fmt, iter, ptr};
8
9#[allow(private_bounds)]
10trait PartialDrop {
11    /// # Safety
12    /// `self[alive]` are all initialized before the call,
13    /// then are never used (without reinitializing them) after it.
14    unsafe fn partial_drop(&mut self, alive: IndexRange);
15}
16impl<T> PartialDrop for [MaybeUninit<T>] {
17    #[ferrocene::prevalidated]
18    unsafe fn partial_drop(&mut self, alive: IndexRange) {
19        // SAFETY: We know that all elements within `alive` are properly initialized.
20        unsafe { self.get_unchecked_mut(alive).assume_init_drop() }
21    }
22}
23impl<T, const N: usize> PartialDrop for [MaybeUninit<T>; N] {
24    #[ferrocene::prevalidated]
25    unsafe fn partial_drop(&mut self, alive: IndexRange) {
26        let slice: &mut [MaybeUninit<T>] = self;
27        // SAFETY: Initialized elements in the array are also initialized in the slice.
28        unsafe { slice.partial_drop(alive) }
29    }
30}
31
32/// The internals of a by-value array iterator.
33///
34/// The real `array::IntoIter<T, N>` stores a `PolymorphicIter<[MaybeUninit<T>, N]>`
35/// which it unsizes to `PolymorphicIter<[MaybeUninit<T>]>` to iterate.
36#[allow(private_bounds)]
37#[ferrocene::prevalidated]
38pub(super) struct PolymorphicIter<DATA: ?Sized>
39where
40    DATA: PartialDrop,
41{
42    /// The elements in `data` that have not been yielded yet.
43    ///
44    /// Invariants:
45    /// - `alive.end <= N`
46    ///
47    /// (And the `IndexRange` type requires `alive.start <= alive.end`.)
48    alive: IndexRange,
49
50    /// This is the array we are iterating over.
51    ///
52    /// Elements with index `i` where `alive.start <= i < alive.end` have not
53    /// been yielded yet and are valid array entries. Elements with indices `i
54    /// < alive.start` or `i >= alive.end` have been yielded already and must
55    /// not be accessed anymore! Those dead elements might even be in a
56    /// completely uninitialized state!
57    ///
58    /// So the invariants are:
59    /// - `data[alive]` is alive (i.e. contains valid elements)
60    /// - `data[..alive.start]` and `data[alive.end..]` are dead (i.e. the
61    ///   elements were already read and must not be touched anymore!)
62    data: DATA,
63}
64
65#[allow(private_bounds)]
66impl<DATA: ?Sized> PolymorphicIter<DATA>
67where
68    DATA: PartialDrop,
69{
70    #[inline]
71    #[ferrocene::prevalidated]
72    pub(super) const fn len(&self) -> usize {
73        self.alive.len()
74    }
75}
76
77#[allow(private_bounds)]
78impl<DATA: ?Sized> Drop for PolymorphicIter<DATA>
79where
80    DATA: PartialDrop,
81{
82    #[inline]
83    #[ferrocene::prevalidated]
84    fn drop(&mut self) {
85        // SAFETY: by our type invariant `self.alive` is exactly the initialized
86        // items, and this is drop so nothing can use the items afterwards.
87        unsafe { self.data.partial_drop(self.alive.clone()) }
88    }
89}
90
91impl<T, const N: usize> PolymorphicIter<[MaybeUninit<T>; N]> {
92    #[inline]
93    #[ferrocene::prevalidated]
94    pub(super) const fn empty() -> Self {
95        Self { alive: IndexRange::zero_to(0), data: [const { MaybeUninit::uninit() }; N] }
96    }
97
98    /// # Safety
99    /// `data[alive]` are all initialized.
100    #[inline]
101    #[ferrocene::prevalidated]
102    pub(super) const unsafe fn new_unchecked(alive: IndexRange, data: [MaybeUninit<T>; N]) -> Self {
103        Self { alive, data }
104    }
105}
106
107impl<T: Clone, const N: usize> Clone for PolymorphicIter<[MaybeUninit<T>; N]> {
108    #[inline]
109    #[ferrocene::prevalidated]
110    fn clone(&self) -> Self {
111        SpecPolymorphicIterClone::<N>::spec_clone(self)
112    }
113}
114
115trait SpecPolymorphicIterClone<const N: usize> {
116    fn spec_clone(
117        this: &PolymorphicIter<[MaybeUninit<Self>; N]>,
118    ) -> PolymorphicIter<[MaybeUninit<Self>; N]>
119    where
120        Self: Sized;
121}
122
123impl<T: Clone, const N: usize> SpecPolymorphicIterClone<N> for T {
124    #[inline]
125    default fn spec_clone(
126        this: &PolymorphicIter<[MaybeUninit<Self>; N]>,
127    ) -> PolymorphicIter<[MaybeUninit<Self>; N]> {
128        // Note, we don't really need to match the exact same alive range, so
129        // we can just clone into offset 0 regardless of where `self` is.
130        let mut new = PolymorphicIter::<[MaybeUninit<T>; N]>::empty();
131
132        #[ferrocene::prevalidated]
133        fn clone_into_new<U: Clone>(
134            source: &PolymorphicIter<[MaybeUninit<U>]>,
135            target: &mut PolymorphicIter<[MaybeUninit<U>]>,
136        ) {
137            // Clone all alive elements.
138            for (src, dst) in iter::zip(source.as_slice(), &mut target.data) {
139                // Write a clone into the new array, then update its alive range.
140                // If cloning panics, we'll correctly drop the previous items.
141                dst.write(src.clone());
142                // This addition cannot overflow as we're iterating a slice,
143                // the length of which always fits in usize.
144                target.alive = IndexRange::zero_to(target.alive.end() + 1);
145            }
146        }
147
148        clone_into_new(this, &mut new);
149        new
150    }
151}
152
153impl<T: TrivialClone, const N: usize> SpecPolymorphicIterClone<N> for T {
154    #[inline]
155    fn spec_clone(
156        this: &PolymorphicIter<[MaybeUninit<Self>; N]>,
157    ) -> PolymorphicIter<[MaybeUninit<Self>; N]> {
158        // Note, we don't really need to match the exact same alive range, so
159        // we can just clone into offset 0 regardless of where `self` is.
160        let mut new = PolymorphicIter::<[MaybeUninit<T>; N]>::empty();
161
162        let len = this.alive.len();
163
164        // SAFETY: These two allocations can not overlap since `new` is allocated
165        // on the stack of this function.
166        unsafe {
167            ptr::copy_nonoverlapping(
168                this.data.as_ptr().add(this.alive.start()),
169                new.data.as_mut_ptr(),
170                len,
171            );
172            new.alive = IndexRange::zero_to(len);
173        }
174
175        new
176    }
177}
178
179impl<T> PolymorphicIter<[MaybeUninit<T>]> {
180    #[inline]
181    #[ferrocene::prevalidated]
182    pub(super) fn as_slice(&self) -> &[T] {
183        // SAFETY: We know that all elements within `alive` are properly initialized.
184        unsafe {
185            let slice = self.data.get_unchecked(self.alive.clone());
186            slice.assume_init_ref()
187        }
188    }
189
190    #[inline]
191    #[ferrocene::prevalidated]
192    #[rustc_const_unstable(feature = "const_iter", issue = "92476")]
193    pub(super) const fn as_mut_slice(&mut self) -> &mut [T] {
194        // SAFETY: We know that all elements within `alive` are properly initialized.
195        unsafe {
196            let slice = self.data.get_unchecked_mut(self.alive.clone());
197            slice.assume_init_mut()
198        }
199    }
200}
201
202impl<T: fmt::Debug> fmt::Debug for PolymorphicIter<[MaybeUninit<T>]> {
203    #[inline]
204    #[ferrocene::prevalidated]
205    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206        // Only print the elements that were not yielded yet: we cannot
207        // access the yielded elements anymore.
208        f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
209    }
210}
211
212/// Iterator-equivalent methods.
213///
214/// We don't implement the actual iterator traits because we want to implement
215/// things like `try_fold` that require `Self: Sized` (which we're not).
216impl<T> PolymorphicIter<[MaybeUninit<T>]> {
217    #[inline]
218    #[ferrocene::prevalidated]
219    pub(super) fn next(&mut self) -> Option<T> {
220        // Get the next index from the front.
221        //
222        // Increasing `alive.start` by 1 maintains the invariant regarding
223        // `alive`. However, due to this change, for a short time, the alive
224        // zone is not `data[alive]` anymore, but `data[idx..alive.end]`.
225        self.alive.next().map(|idx| {
226            // Read the element from the array.
227            // SAFETY: `idx` is an index into the former "alive" region of the
228            // array. Reading this element means that `data[idx]` is regarded as
229            // dead now (i.e. do not touch). As `idx` was the start of the
230            // alive-zone, the alive zone is now `data[alive]` again, restoring
231            // all invariants.
232            unsafe { self.data.get_unchecked(idx).assume_init_read() }
233        })
234    }
235
236    #[inline]
237    #[ferrocene::prevalidated]
238    pub(super) fn size_hint(&self) -> (usize, Option<usize>) {
239        let len = self.len();
240        (len, Some(len))
241    }
242
243    #[inline]
244    #[ferrocene::prevalidated]
245    pub(super) fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
246        // This also moves the start, which marks them as conceptually "dropped",
247        // so if anything goes bad then our drop impl won't double-free them.
248        let range_to_drop = self.alive.take_prefix(n);
249        let remaining = n - range_to_drop.len();
250
251        // SAFETY: These elements are currently initialized, so it's fine to drop them.
252        unsafe {
253            let slice = self.data.get_unchecked_mut(range_to_drop);
254            slice.assume_init_drop();
255        }
256
257        NonZero::new(remaining).map_or(Ok(()), Err)
258    }
259
260    #[inline]
261    #[ferrocene::prevalidated]
262    pub(super) fn fold<B>(&mut self, init: B, f: impl FnMut(B, T) -> B) -> B {
263        self.try_fold(init, NeverShortCircuit::wrap_mut_2(f)).0
264    }
265
266    #[inline]
267    #[ferrocene::prevalidated]
268    pub(super) fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R
269    where
270        F: FnMut(B, T) -> R,
271        R: Try<Output = B>,
272    {
273        // `alive` is an `IndexRange`, not an arbitrary iterator, so we can
274        // trust that its `try_fold` isn't going to do something weird like
275        // call the fold-er multiple times for the same index.
276        let data = &mut self.data;
277        self.alive.try_fold(init, move |accum, idx| {
278            // SAFETY: `idx` has been removed from the alive range, so we're not
279            // going to drop it (even if `f` panics) and thus its ok to give
280            // out ownership of that item to `f` to handle.
281            let elem = unsafe { data.get_unchecked(idx).assume_init_read() };
282            f(accum, elem)
283        })
284    }
285
286    #[inline]
287    #[ferrocene::prevalidated]
288    pub(super) fn next_back(&mut self) -> Option<T> {
289        // Get the next index from the back.
290        //
291        // Decreasing `alive.end` by 1 maintains the invariant regarding
292        // `alive`. However, due to this change, for a short time, the alive
293        // zone is not `data[alive]` anymore, but `data[alive.start..=idx]`.
294        self.alive.next_back().map(|idx| {
295            // Read the element from the array.
296            // SAFETY: `idx` is an index into the former "alive" region of the
297            // array. Reading this element means that `data[idx]` is regarded as
298            // dead now (i.e. do not touch). As `idx` was the end of the
299            // alive-zone, the alive zone is now `data[alive]` again, restoring
300            // all invariants.
301            unsafe { self.data.get_unchecked(idx).assume_init_read() }
302        })
303    }
304
305    #[inline]
306    #[ferrocene::prevalidated]
307    pub(super) fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
308        // This also moves the end, which marks them as conceptually "dropped",
309        // so if anything goes bad then our drop impl won't double-free them.
310        let range_to_drop = self.alive.take_suffix(n);
311        let remaining = n - range_to_drop.len();
312
313        // SAFETY: These elements are currently initialized, so it's fine to drop them.
314        unsafe {
315            let slice = self.data.get_unchecked_mut(range_to_drop);
316            slice.assume_init_drop();
317        }
318
319        NonZero::new(remaining).map_or(Ok(()), Err)
320    }
321
322    #[inline]
323    #[ferrocene::prevalidated]
324    pub(super) fn rfold<B>(&mut self, init: B, f: impl FnMut(B, T) -> B) -> B {
325        self.try_rfold(init, NeverShortCircuit::wrap_mut_2(f)).0
326    }
327
328    #[inline]
329    #[ferrocene::prevalidated]
330    pub(super) fn try_rfold<B, F, R>(&mut self, init: B, mut f: F) -> R
331    where
332        F: FnMut(B, T) -> R,
333        R: Try<Output = B>,
334    {
335        // `alive` is an `IndexRange`, not an arbitrary iterator, so we can
336        // trust that its `try_rfold` isn't going to do something weird like
337        // call the fold-er multiple times for the same index.
338        let data = &mut self.data;
339        self.alive.try_rfold(init, move |accum, idx| {
340            // SAFETY: `idx` has been removed from the alive range, so we're not
341            // going to drop it (even if `f` panics) and thus its ok to give
342            // out ownership of that item to `f` to handle.
343            let elem = unsafe { data.get_unchecked(idx).assume_init_read() };
344            f(accum, elem)
345        })
346    }
347}