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#[stable(feature = "boxed_array_value_iter", since = "CURRENT_RUSTC_VERSION")]
41impl<T, const N: usize> !Iterator for [T; N] {}
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    #[ferrocene::prevalidated]
63    fn into_iter(self) -> Self::IntoIter {
64        // SAFETY: The transmute here is actually safe. The docs of `MaybeUninit`
65        // promise:
66        //
67        // > `MaybeUninit<T>` is guaranteed to have the same size and alignment
68        // > as `T`.
69        //
70        // The docs even show a transmute from an array of `MaybeUninit<T>` to
71        // an array of `T`.
72        //
73        // With that, this initialization satisfies the invariants.
74        //
75        // FIXME: If normal `transmute` ever gets smart enough to allow this
76        // directly, use it instead of `transmute_unchecked`.
77        let data: [MaybeUninit<T>; N] = unsafe { transmute_unchecked(self) };
78        // SAFETY: The original array was entirely initialized and the alive
79        // range we're passing here represents that fact.
80        let inner = unsafe { InnerSized::new_unchecked(IndexRange::zero_to(N), data) };
81        IntoIter { inner: ManuallyDrop::new(inner) }
82    }
83}
84
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    #[ferrocene::prevalidated]
232    #[rustc_const_unstable(feature = "const_iter", issue = "92476")]
233    pub const fn as_mut_slice(&mut self) -> &mut [T] {
234        self.unsize_mut().as_mut_slice()
235    }
236}
237
238#[stable(feature = "array_value_iter_default", since = "1.89.0")]
239impl<T, const N: usize> Default for IntoIter<T, N> {
240    fn default() -> Self {
241        IntoIter::empty()
242    }
243}
244
245#[stable(feature = "array_value_iter_impls", since = "1.40.0")]
246impl<T, const N: usize> Iterator for IntoIter<T, N> {
247    type Item = T;
248
249    #[inline]
250    #[ferrocene::prevalidated]
251    fn next(&mut self) -> Option<Self::Item> {
252        self.unsize_mut().next()
253    }
254
255    #[inline]
256    #[ferrocene::prevalidated]
257    fn size_hint(&self) -> (usize, Option<usize>) {
258        self.unsize().size_hint()
259    }
260
261    #[inline]
262    #[ferrocene::prevalidated]
263    fn fold<Acc, Fold>(mut self, init: Acc, fold: Fold) -> Acc
264    where
265        Fold: FnMut(Acc, Self::Item) -> Acc,
266    {
267        self.unsize_mut().fold(init, fold)
268    }
269
270    #[inline]
271    #[ferrocene::prevalidated]
272    fn try_fold<B, F, R>(&mut self, init: B, f: F) -> R
273    where
274        Self: Sized,
275        F: FnMut(B, Self::Item) -> R,
276        R: Try<Output = B>,
277    {
278        self.unsize_mut().try_fold(init, f)
279    }
280
281    #[inline]
282    #[ferrocene::prevalidated]
283    fn count(self) -> usize {
284        self.len()
285    }
286
287    #[inline]
288    #[ferrocene::prevalidated]
289    fn last(mut self) -> Option<Self::Item> {
290        self.next_back()
291    }
292
293    #[inline]
294    #[ferrocene::prevalidated]
295    fn advance_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
296        self.unsize_mut().advance_by(n)
297    }
298
299    #[inline]
300    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item {
301        // SAFETY: The caller must provide an idx that is in bound of the remainder.
302        let elem_ref = unsafe { self.as_mut_slice().get_unchecked_mut(idx) };
303        // SAFETY: We only implement `TrustedRandomAccessNoCoerce` for types
304        // which are actually `Copy`, so cannot have multiple-drop issues.
305        unsafe { ptr::read(elem_ref) }
306    }
307}
308
309#[stable(feature = "array_value_iter_impls", since = "1.40.0")]
310impl<T, const N: usize> DoubleEndedIterator for IntoIter<T, N> {
311    #[inline]
312    #[ferrocene::prevalidated]
313    fn next_back(&mut self) -> Option<Self::Item> {
314        self.unsize_mut().next_back()
315    }
316
317    #[inline]
318    #[ferrocene::prevalidated]
319    fn rfold<Acc, Fold>(mut self, init: Acc, rfold: Fold) -> Acc
320    where
321        Fold: FnMut(Acc, Self::Item) -> Acc,
322    {
323        self.unsize_mut().rfold(init, rfold)
324    }
325
326    #[inline]
327    #[ferrocene::prevalidated]
328    fn try_rfold<B, F, R>(&mut self, init: B, f: F) -> R
329    where
330        Self: Sized,
331        F: FnMut(B, Self::Item) -> R,
332        R: Try<Output = B>,
333    {
334        self.unsize_mut().try_rfold(init, f)
335    }
336
337    #[inline]
338    #[ferrocene::prevalidated]
339    fn advance_back_by(&mut self, n: usize) -> Result<(), NonZero<usize>> {
340        self.unsize_mut().advance_back_by(n)
341    }
342}
343
344#[stable(feature = "array_value_iter_impls", since = "1.40.0")]
345// Even though all the Drop logic could be completely handled by
346// PolymorphicIter, this impl still serves two purposes:
347// - Drop has been part of the public API, so we can't remove it
348// - the partial_drop function doesn't always get fully optimized away
349//   for !Drop types and ends up as dead code in the final binary.
350//   Branching on needs_drop higher in the call-tree allows it to be
351//   removed by earlier optimization passes.
352impl<T, const N: usize> Drop for IntoIter<T, N> {
353    #[inline]
354    #[ferrocene::prevalidated]
355    fn drop(&mut self) {
356        if crate::mem::needs_drop::<T>() {
357            // SAFETY: This is the only place where we drop this field.
358            unsafe { ManuallyDrop::drop(&mut self.inner) }
359        }
360    }
361}
362
363#[stable(feature = "array_value_iter_impls", since = "1.40.0")]
364impl<T, const N: usize> ExactSizeIterator for IntoIter<T, N> {
365    #[inline]
366    #[ferrocene::prevalidated]
367    fn len(&self) -> usize {
368        self.inner.len()
369    }
370    #[inline]
371    #[ferrocene::prevalidated]
372    fn is_empty(&self) -> bool {
373        self.inner.len() == 0
374    }
375}
376
377#[stable(feature = "array_value_iter_impls", since = "1.40.0")]
378impl<T, const N: usize> FusedIterator for IntoIter<T, N> {}
379
380// The iterator indeed reports the correct length. The number of "alive"
381// elements (that will still be yielded) is the length of the range `alive`.
382// This range is decremented in length in either `next` or `next_back`. It is
383// always decremented by 1 in those methods, but only if `Some(_)` is returned.
384#[stable(feature = "array_value_iter_impls", since = "1.40.0")]
385unsafe impl<T, const N: usize> TrustedLen for IntoIter<T, N> {}
386
387#[doc(hidden)]
388#[unstable(issue = "none", feature = "std_internals")]
389#[rustc_unsafe_specialization_marker]
390trait NonDrop {}
391
392// T: Copy as approximation for !Drop since get_unchecked does not advance self.alive
393// and thus we can't implement drop-handling
394#[unstable(issue = "none", feature = "std_internals")]
395impl<T: Copy> NonDrop for T {}
396
397#[doc(hidden)]
398#[unstable(issue = "none", feature = "std_internals")]
399unsafe impl<T, const N: usize> TrustedRandomAccessNoCoerce for IntoIter<T, N>
400where
401    T: NonDrop,
402{
403    const MAY_HAVE_SIDE_EFFECT: bool = false;
404}
405
406#[stable(feature = "array_value_iter_impls", since = "1.40.0")]
407impl<T: fmt::Debug, const N: usize> fmt::Debug for IntoIter<T, N> {
408    #[ferrocene::prevalidated]
409    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
410        self.unsize().fmt(f)
411    }
412}