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