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