Skip to main content

core/array/
iter.rs

1//! Defines the `IntoIter` owned iterator for arrays.
2
3use crate::intrinsics::transmute_unchecked;
4#[cfg(not(feature = "ferrocene_subset"))]
5use crate::iter::{FusedIterator, TrustedLen, TrustedRandomAccessNoCoerce};
6use crate::mem::{ManuallyDrop, MaybeUninit};
7use crate::num::NonZero;
8#[cfg(not(feature = "ferrocene_subset"))]
9use crate::ops::{Deref as _, DerefMut as _, IndexRange, Range, Try};
10#[cfg(not(feature = "ferrocene_subset"))]
11use crate::{fmt, ptr};
12
13// Ferrocene addition: imports for certified subset
14#[cfg(feature = "ferrocene_subset")]
15#[rustfmt::skip]
16use crate::{
17    fmt,
18    ops::{Deref as _, DerefMut as _, IndexRange, Try},
19};
20
21mod iter_inner;
22
23type InnerSized<T, const N: usize> = iter_inner::PolymorphicIter<[MaybeUninit<T>; N]>;
24type InnerUnsized<T> = iter_inner::PolymorphicIter<[MaybeUninit<T>]>;
25
26/// A by-value [array] iterator.
27#[stable(feature = "array_value_iter", since = "1.51.0")]
28#[rustc_insignificant_dtor]
29#[rustc_diagnostic_item = "ArrayIntoIter"]
30#[derive(Clone)]
31pub struct IntoIter<T, const N: usize> {
32    inner: ManuallyDrop<InnerSized<T, N>>,
33}
34
35impl<T, const N: usize> IntoIter<T, N> {
36    #[inline]
37    fn unsize(&self) -> &InnerUnsized<T> {
38        self.inner.deref()
39    }
40    #[inline]
41    fn unsize_mut(&mut self) -> &mut InnerUnsized<T> {
42        self.inner.deref_mut()
43    }
44}
45
46// Note: the `#[rustc_skip_during_method_dispatch(array)]` on `trait IntoIterator`
47// hides this implementation from explicit `.into_iter()` calls on editions < 2021,
48// so those calls will still resolve to the slice implementation, by reference.
49#[stable(feature = "array_into_iter_impl", since = "1.53.0")]
50impl<T, const N: usize> IntoIterator for [T; N] {
51    type Item = T;
52    type IntoIter = IntoIter<T, N>;
53
54    /// Creates a consuming iterator, that is, one that moves each value out of
55    /// the array (from start to end).
56    ///
57    /// The array cannot be used after calling this unless `T` implements
58    /// `Copy`, so the whole array is copied.
59    ///
60    /// Arrays have special behavior when calling `.into_iter()` prior to the
61    /// 2021 edition -- see the [array] Editions section for more information.
62    ///
63    /// [array]: prim@array
64    #[inline]
65    fn into_iter(self) -> Self::IntoIter {
66        // SAFETY: The transmute here is actually safe. The docs of `MaybeUninit`
67        // promise:
68        //
69        // > `MaybeUninit<T>` is guaranteed to have the same size and alignment
70        // > as `T`.
71        //
72        // The docs even show a transmute from an array of `MaybeUninit<T>` to
73        // an array of `T`.
74        //
75        // With that, this initialization satisfies the invariants.
76        //
77        // FIXME: If normal `transmute` ever gets smart enough to allow this
78        // directly, use it instead of `transmute_unchecked`.
79        let data: [MaybeUninit<T>; N] = unsafe { transmute_unchecked(self) };
80        // SAFETY: The original array was entirely initialized and the alive
81        // range we're passing here represents that fact.
82        let inner = unsafe { InnerSized::new_unchecked(IndexRange::zero_to(N), data) };
83        IntoIter { inner: ManuallyDrop::new(inner) }
84    }
85}
86
87#[cfg(not(feature = "ferrocene_subset"))]
88impl<T, const N: usize> IntoIter<T, N> {
89    /// Creates a new iterator over the given `array`.
90    #[stable(feature = "array_value_iter", since = "1.51.0")]
91    #[deprecated(since = "1.59.0", note = "use `IntoIterator::into_iter` instead")]
92    pub fn new(array: [T; N]) -> Self {
93        IntoIterator::into_iter(array)
94    }
95
96    /// Creates an iterator over the elements in a partially-initialized buffer.
97    ///
98    /// If you have a fully-initialized array, then use [`IntoIterator`].
99    /// But this is useful for returning partial results from unsafe code.
100    ///
101    /// # Safety
102    ///
103    /// - The `buffer[initialized]` elements must all be initialized.
104    /// - The range must be canonical, with `initialized.start <= initialized.end`.
105    /// - The range must be in-bounds for the buffer, with `initialized.end <= N`.
106    ///   (Like how indexing `[0][100..100]` fails despite the range being empty.)
107    ///
108    /// It's sound to have more elements initialized than mentioned, though that
109    /// will most likely result in them being leaked.
110    ///
111    /// # Examples
112    ///
113    /// ```
114    /// #![feature(array_into_iter_constructors)]
115    /// #![feature(maybe_uninit_uninit_array_transpose)]
116    /// use std::array::IntoIter;
117    /// use std::mem::MaybeUninit;
118    ///
119    /// # // Hi!  Thanks for reading the code. This is restricted to `Copy` because
120    /// # // otherwise it could leak. A fully-general version this would need a drop
121    /// # // guard to handle panics from the iterator, but this works for an example.
122    /// fn next_chunk<T: Copy, const N: usize>(
123    ///     it: &mut impl Iterator<Item = T>,
124    /// ) -> Result<[T; N], IntoIter<T, N>> {
125    ///     let mut buffer = [const { MaybeUninit::uninit() }; N];
126    ///     let mut i = 0;
127    ///     while i < N {
128    ///         match it.next() {
129    ///             Some(x) => {
130    ///                 buffer[i].write(x);
131    ///                 i += 1;
132    ///             }
133    ///             None => {
134    ///                 // SAFETY: We've initialized the first `i` items
135    ///                 unsafe {
136    ///                     return Err(IntoIter::new_unchecked(buffer, 0..i));
137    ///                 }
138    ///             }
139    ///         }
140    ///     }
141    ///
142    ///     // SAFETY: We've initialized all N items
143    ///     unsafe { Ok(buffer.transpose().assume_init()) }
144    /// }
145    ///
146    /// let r: [_; 4] = next_chunk(&mut (10..16)).unwrap();
147    /// assert_eq!(r, [10, 11, 12, 13]);
148    /// let r: IntoIter<_, 40> = next_chunk(&mut (10..16)).unwrap_err();
149    /// assert_eq!(r.collect::<Vec<_>>(), vec![10, 11, 12, 13, 14, 15]);
150    /// ```
151    #[unstable(feature = "array_into_iter_constructors", issue = "91583")]
152    #[inline]
153    pub const unsafe fn new_unchecked(
154        buffer: [MaybeUninit<T>; N],
155        initialized: Range<usize>,
156    ) -> Self {
157        // SAFETY: one of our safety conditions is that the range is canonical.
158        let alive = unsafe { IndexRange::new_unchecked(initialized.start, initialized.end) };
159        // SAFETY: one of our safety condition is that these items are initialized.
160        let inner = unsafe { InnerSized::new_unchecked(alive, buffer) };
161        IntoIter { inner: ManuallyDrop::new(inner) }
162    }
163
164    /// Creates an iterator over `T` which returns no elements.
165    ///
166    /// If you just need an empty iterator, then use
167    /// [`iter::empty()`](crate::iter::empty) instead.
168    /// And if you need an empty array, use `[]`.
169    ///
170    /// But this is useful when you need an `array::IntoIter<T, N>` *specifically*.
171    ///
172    /// # Examples
173    ///
174    /// ```
175    /// #![feature(array_into_iter_constructors)]
176    /// use std::array::IntoIter;
177    ///
178    /// let empty = IntoIter::<i32, 3>::empty();
179    /// assert_eq!(empty.len(), 0);
180    /// assert_eq!(empty.as_slice(), &[]);
181    ///
182    /// let empty = IntoIter::<std::convert::Infallible, 200>::empty();
183    /// assert_eq!(empty.len(), 0);
184    /// ```
185    ///
186    /// `[1, 2].into_iter()` and `[].into_iter()` have different types
187    /// ```should_fail,edition2021
188    /// #![feature(array_into_iter_constructors)]
189    /// use std::array::IntoIter;
190    ///
191    /// pub fn get_bytes(b: bool) -> IntoIter<i8, 4> {
192    ///     if b {
193    ///         [1, 2, 3, 4].into_iter()
194    ///     } else {
195    ///         [].into_iter() // error[E0308]: mismatched types
196    ///     }
197    /// }
198    /// ```
199    ///
200    /// But using this method you can get an empty iterator of appropriate size:
201    /// ```edition2021
202    /// #![feature(array_into_iter_constructors)]
203    /// use std::array::IntoIter;
204    ///
205    /// pub fn get_bytes(b: bool) -> IntoIter<i8, 4> {
206    ///     if b {
207    ///         [1, 2, 3, 4].into_iter()
208    ///     } else {
209    ///         IntoIter::empty()
210    ///     }
211    /// }
212    ///
213    /// assert_eq!(get_bytes(true).collect::<Vec<_>>(), vec![1, 2, 3, 4]);
214    /// assert_eq!(get_bytes(false).collect::<Vec<_>>(), vec![]);
215    /// ```
216    #[unstable(feature = "array_into_iter_constructors", issue = "91583")]
217    #[inline]
218    pub const fn empty() -> Self {
219        let inner = InnerSized::empty();
220        IntoIter { inner: ManuallyDrop::new(inner) }
221    }
222
223    /// Returns an immutable slice of all elements that have not been yielded
224    /// yet.
225    #[stable(feature = "array_value_iter", since = "1.51.0")]
226    #[inline]
227    pub fn as_slice(&self) -> &[T] {
228        self.unsize().as_slice()
229    }
230
231    /// Returns a mutable slice of all elements that have not been yielded yet.
232    #[stable(feature = "array_value_iter", since = "1.51.0")]
233    #[inline]
234    pub fn as_mut_slice(&mut self) -> &mut [T] {
235        self.unsize_mut().as_mut_slice()
236    }
237}
238
239#[stable(feature = "array_value_iter_default", since = "1.89.0")]
240#[cfg(not(feature = "ferrocene_subset"))]
241impl<T, const N: usize> Default for IntoIter<T, N> {
242    fn default() -> Self {
243        IntoIter::empty()
244    }
245}
246
247#[stable(feature = "array_value_iter_impls", since = "1.40.0")]
248impl<T, const N: usize> Iterator for IntoIter<T, N> {
249    type Item = T;
250
251    #[inline]
252    fn next(&mut self) -> Option<Self::Item> {
253        self.unsize_mut().next()
254    }
255
256    #[inline]
257    fn size_hint(&self) -> (usize, Option<usize>) {
258        self.unsize().size_hint()
259    }
260
261    #[inline]
262    fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
263    where
264        Fold: FnMut(Acc, Self::Item) -> Acc,
265    {
266        self.unsize_mut().fold(init, fold)
267    }
268
269    #[inline]
270    fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
271    where
272        Self: Sized,
273        F: FnMut(B, Self::Item) -> R,
274        R: Try<Output = B>,
275    {
276        self.unsize_mut().try_fold(init, f)
277    }
278
279    #[inline]
280    fn count(self) -> usize {
281        self.len()
282    }
283
284    #[inline]
285    fn last(mut self) -> Option<Self::Item> {
286        self.next_back()
287    }
288
289    #[inline]
290    fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
291        self.unsize_mut().advance_by(n)
292    }
293
294    #[inline]
295    #[cfg(not(feature = "ferrocene_subset"))]
296    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
297        // SAFETY: The caller must provide an idx that is in bound of the remainder.
298        let elem_ref = unsafe { self.as_mut_slice().get_unchecked_mut(idx) };
299        // SAFETY: We only implement `TrustedRandomAccessNoCoerce` for types
300        // which are actually `Copy`, so cannot have multiple-drop issues.
301        unsafe { ptr::read(elem_ref) }
302    }
303}
304
305#[stable(feature = "array_value_iter_impls", since = "1.40.0")]
306impl<T, const N: usize> DoubleEndedIterator for IntoIter<T, N> {
307    #[inline]
308    fn next_back(&mut self) -> Option<Self::Item> {
309        self.unsize_mut().next_back()
310    }
311
312    #[inline]
313    fn rfold<Acc, Fold>(mut self, init: Acc, rfold: Fold) -> Acc
314    where
315        Fold: FnMut(Acc, Self::Item) -> Acc,
316    {
317        self.unsize_mut().rfold(init, rfold)
318    }
319
320    #[inline]
321    fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
322    where
323        Self: Sized,
324        F: FnMut(B, Self::Item) -> R,
325        R: Try<Output = B>,
326    {
327        self.unsize_mut().try_rfold(init, f)
328    }
329
330    #[inline]
331    fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
332        self.unsize_mut().advance_back_by(n)
333    }
334}
335
336#[stable(feature = "array_value_iter_impls", since = "1.40.0")]
337// Even though all the Drop logic could be completely handled by
338// PolymorphicIter, this impl still serves two purposes:
339// - Drop has been part of the public API, so we can't remove it
340// - the partial_drop function doesn't always get fully optimized away
341//   for !Drop types and ends up as dead code in the final binary.
342//   Branching on needs_drop higher in the call-tree allows it to be
343//   removed by earlier optimization passes.
344impl<T, const N: usize> Drop for IntoIter<T, N> {
345    #[inline]
346    fn drop(&mut self) {
347        if crate::mem::needs_drop::<T>() {
348            // SAFETY: This is the only place where we drop this field.
349            unsafe { ManuallyDrop::drop(&mut self.inner) }
350        }
351    }
352}
353
354#[stable(feature = "array_value_iter_impls", since = "1.40.0")]
355impl<T, const N: usize> ExactSizeIterator for IntoIter<T, N> {
356    #[inline]
357    fn len(&self) -> usize {
358        self.inner.len()
359    }
360    #[inline]
361    fn is_empty(&self) -> bool {
362        self.inner.len() == 0
363    }
364}
365
366#[stable(feature = "array_value_iter_impls", since = "1.40.0")]
367#[cfg(not(feature = "ferrocene_subset"))]
368impl<T, const N: usize> FusedIterator for IntoIter<T, N> {}
369
370// The iterator indeed reports the correct length. The number of "alive"
371// elements (that will still be yielded) is the length of the range `alive`.
372// This range is decremented in length in either `next` or `next_back`. It is
373// always decremented by 1 in those methods, but only if `Some(_)` is returned.
374#[stable(feature = "array_value_iter_impls", since = "1.40.0")]
375#[cfg(not(feature = "ferrocene_subset"))]
376unsafe impl<T, const N: usize> TrustedLen for IntoIter<T, N> {}
377
378#[doc(hidden)]
379#[unstable(issue = "none", feature = "std_internals")]
380#[rustc_unsafe_specialization_marker]
381#[cfg(not(feature = "ferrocene_subset"))]
382pub trait NonDrop {}
383
384// T: Copy as approximation for !Drop since get_unchecked does not advance self.alive
385// and thus we can't implement drop-handling
386#[unstable(issue = "none", feature = "std_internals")]
387#[cfg(not(feature = "ferrocene_subset"))]
388impl<T: Copy> NonDrop for T {}
389
390#[doc(hidden)]
391#[unstable(issue = "none", feature = "std_internals")]
392#[cfg(not(feature = "ferrocene_subset"))]
393unsafe impl<T, const N: usize> TrustedRandomAccessNoCoerce for IntoIter<T, N>
394where
395    T: NonDrop,
396{
397    const MAY_HAVE_SIDE_EFFECT: bool = false;
398}
399
400#[stable(feature = "array_value_iter_impls", since = "1.40.0")]
401impl<T: fmt::Debug, const N: usize> fmt::Debug for IntoIter<T, N> {
402    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
403        self.unsize().fmt(f)
404    }
405}