Skip to main content

core/array/
iter.rs

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