core/array/
iter.rs

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