1 //! Defines the `IntoIter` owned iterator for arrays.
3 use super::LengthAtMost32;
6 iter::{ExactSizeIterator, FusedIterator, TrustedLen},
7 mem::{self, MaybeUninit},
12 /// A by-value [array] iterator.
14 /// [array]: ../../std/primitive.array.html
15 #[unstable(feature = "array_value_iter", issue = "65798")]
16 pub struct IntoIter<T, const N: usize>
18 [T; N]: LengthAtMost32,
20 /// This is the array we are iterating over.
22 /// Elements with index `i` where `alive.start <= i < alive.end` have not
23 /// been yielded yet and are valid array entries. Elements with indices `i
24 /// < alive.start` or `i >= alive.end` have been yielded already and must
25 /// not be accessed anymore! Those dead elements might even be in a
26 /// completely uninitialized state!
28 /// So the invariants are:
29 /// - `data[alive]` is alive (i.e. contains valid elements)
30 /// - `data[..alive.start]` and `data[alive.end..]` are dead (i.e. the
31 /// elements were already read and must not be touched anymore!)
32 data: [MaybeUninit<T>; N],
34 /// The elements in `data` that have not been yielded yet.
37 /// - `alive.start <= alive.end`
38 /// - `alive.end <= N`
42 impl<T, const N: usize> IntoIter<T, { N }>
44 [T; N]: LengthAtMost32,
46 /// Creates a new iterator over the given `array`.
48 /// *Note*: this method might never get stabilized and/or removed in the
49 /// future as there will likely be another, preferred way of obtaining this
50 /// iterator (either via `IntoIterator` for arrays or via another way).
51 #[unstable(feature = "array_value_iter", issue = "65798")]
52 pub fn new(array: [T; N]) -> Self {
53 // SAFETY: The transmute here is actually safe. The docs of `MaybeUninit`
56 // > `MaybeUninit<T>` is guaranteed to have the same size and alignment
59 // The docs even show a transmute from an array of `MaybeUninit<T>` to
62 // With that, this initialization satisfies the invariants.
64 // FIXME(LukasKalbertodt): actually use `mem::transmute` here, once it
65 // works with const generics:
66 // `mem::transmute::<[T; {N}], [MaybeUninit<T>; {N}]>(array)`
68 // Until then, we do it manually here. We first create a bitwise copy
69 // but cast the pointer so that it is treated as a different type. Then
70 // we forget `array` so that it is not dropped.
72 let data = ptr::read(&array as *const [T; N] as *const [MaybeUninit<T>; N]);
77 Self { data, alive: 0..N }
80 /// Returns an immutable slice of all elements that have not been yielded
82 fn as_slice(&self) -> &[T] {
83 let slice = &self.data[self.alive.clone()];
84 // SAFETY: This transmute is safe. As mentioned in `new`, `MaybeUninit` retains
85 // the size and alignment of `T`. Furthermore, we know that all
86 // elements within `alive` are properly initialized.
87 unsafe { mem::transmute::<&[MaybeUninit<T>], &[T]>(slice) }
90 /// Returns a mutable slice of all elements that have not been yielded yet.
91 fn as_mut_slice(&mut self) -> &mut [T] {
92 // This transmute is safe, same as in `as_slice` above.
93 let slice = &mut self.data[self.alive.clone()];
94 // SAFETY: This transmute is safe. As mentioned in `new`, `MaybeUninit` retains
95 // the size and alignment of `T`. Furthermore, we know that all
96 // elements within `alive` are properly initialized.
97 unsafe { mem::transmute::<&mut [MaybeUninit<T>], &mut [T]>(slice) }
101 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
102 impl<T, const N: usize> Iterator for IntoIter<T, { N }>
104 [T; N]: LengthAtMost32,
107 fn next(&mut self) -> Option<Self::Item> {
108 if self.alive.start == self.alive.end {
114 // From the check above we know that `alive.start != alive.end`.
115 // Combine this with the invariant `alive.start <= alive.end`, we know
116 // that `alive.start < alive.end`. Increasing `alive.start` by 1
117 // maintains the invariant regarding `alive`. However, due to this
118 // change, for a short time, the alive zone is not `data[alive]`
119 // anymore, but `data[idx..alive.end]`.
120 let idx = self.alive.start;
121 self.alive.start += 1;
123 // Read the element from the array.
124 // SAFETY: This is safe: `idx` is an index
125 // into the "alive" region of the array. Reading this element means
126 // that `data[idx]` is regarded as dead now (i.e. do not touch). As
127 // `idx` was the start of the alive-zone, the alive zone is now
128 // `data[alive]` again, restoring all invariants.
129 let out = unsafe { self.data.get_unchecked(idx).read() };
134 fn size_hint(&self) -> (usize, Option<usize>) {
135 let len = self.len();
139 fn count(self) -> usize {
143 fn last(mut self) -> Option<Self::Item> {
148 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
149 impl<T, const N: usize> DoubleEndedIterator for IntoIter<T, { N }>
151 [T; N]: LengthAtMost32,
153 fn next_back(&mut self) -> Option<Self::Item> {
154 if self.alive.start == self.alive.end {
158 // Decrease end index.
160 // From the check above we know that `alive.start != alive.end`.
161 // Combine this with the invariant `alive.start <= alive.end`, we know
162 // that `alive.start < alive.end`. As `alive.start` cannot be negative,
163 // `alive.end` is at least 1, meaning that we can safely decrement it
164 // by one. This also maintains the invariant `alive.start <=
165 // alive.end`. However, due to this change, for a short time, the alive
166 // zone is not `data[alive]` anymore, but `data[alive.start..alive.end
170 // Read the element from the array.
171 // SAFETY: This is safe: `alive.end` is an
172 // index into the "alive" region of the array. Compare the previous
173 // comment that states that the alive region is
174 // `data[alive.start..alive.end + 1]`. Reading this element means that
175 // `data[alive.end]` is regarded as dead now (i.e. do not touch). As
176 // `alive.end` was the end of the alive-zone, the alive zone is now
177 // `data[alive]` again, restoring all invariants.
178 let out = unsafe { self.data.get_unchecked(self.alive.end).read() };
184 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
185 impl<T, const N: usize> Drop for IntoIter<T, { N }>
187 [T; N]: LengthAtMost32,
190 // SAFETY: This is safe: `as_mut_slice` returns exactly the sub-slice
191 // of elements that have not been moved out yet and that remain
193 unsafe { ptr::drop_in_place(self.as_mut_slice()) }
197 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
198 impl<T, const N: usize> ExactSizeIterator for IntoIter<T, { N }>
200 [T; N]: LengthAtMost32,
202 fn len(&self) -> usize {
203 // Will never underflow due to the invariant `alive.start <=
205 self.alive.end - self.alive.start
207 fn is_empty(&self) -> bool {
208 self.alive.is_empty()
212 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
213 impl<T, const N: usize> FusedIterator for IntoIter<T, { N }> where [T; N]: LengthAtMost32 {}
215 // The iterator indeed reports the correct length. The number of "alive"
216 // elements (that will still be yielded) is the length of the range `alive`.
217 // This range is decremented in length in either `next` or `next_back`. It is
218 // always decremented by 1 in those methods, but only if `Some(_)` is returned.
219 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
220 unsafe impl<T, const N: usize> TrustedLen for IntoIter<T, { N }> where [T; N]: LengthAtMost32 {}
222 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
223 impl<T: Clone, const N: usize> Clone for IntoIter<T, { N }>
225 [T; N]: LengthAtMost32,
227 fn clone(&self) -> Self {
228 // SAFETY: each point of unsafety is documented inside the unsafe block
230 // This creates a new uninitialized array. Note that the `assume_init`
231 // refers to the array, not the individual elements. And it is Ok if
232 // the array is in an uninitialized state as all elements may be
233 // uninitialized (all bit patterns are valid). Compare the
234 // `MaybeUninit` docs for more information.
235 let mut new_data: [MaybeUninit<T>; N] = MaybeUninit::uninit().assume_init();
237 // Clone all alive elements.
238 for idx in self.alive.clone() {
239 // The element at `idx` in the old array is alive, so we can
240 // safely call `get_ref()`. We then clone it, and write the
241 // clone into the new array.
242 let clone = self.data.get_unchecked(idx).get_ref().clone();
243 new_data.get_unchecked_mut(idx).write(clone);
246 Self { data: new_data, alive: self.alive.clone() }
251 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
252 impl<T: fmt::Debug, const N: usize> fmt::Debug for IntoIter<T, { N }>
254 [T; N]: LengthAtMost32,
256 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
257 // Only print the elements that were not yielded yet: we cannot
258 // access the yielded elements anymore.
259 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()