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