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