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