1 //! Defines the `IntoIter` owned iterator for arrays.
5 iter::{ExactSizeIterator, FusedIterator, TrustedLen},
6 mem::{self, MaybeUninit},
10 use super::LengthAtMost32;
13 /// A by-value [array] iterator.
15 /// [array]: ../../std/primitive.array.html
16 #[unstable(feature = "array_value_iter", issue = "65798")]
17 pub struct IntoIter<T, const N: usize>
19 [T; N]: LengthAtMost32,
21 /// This is the array we are iterating over.
23 /// Elements with index `i` where `alive.start <= i < alive.end` have not
24 /// been yielded yet and are valid array entries. Elements with indices `i
25 /// < alive.start` or `i >= alive.end` have been yielded already and must
26 /// not be accessed anymore! Those dead elements might even be in a
27 /// completely uninitialized state!
29 /// So the invariants are:
30 /// - `data[alive]` is alive (i.e. contains valid elements)
31 /// - `data[..alive.start]` and `data[alive.end..]` are dead (i.e. the
32 /// elements were already read and must not be touched anymore!)
33 data: [MaybeUninit<T>; N],
35 /// The elements in `data` that have not been yielded yet.
38 /// - `alive.start <= alive.end`
39 /// - `alive.end <= N`
43 impl<T, const N: usize> IntoIter<T, {N}>
45 [T; N]: LengthAtMost32,
47 /// Creates a new iterator over the given `array`.
49 /// *Note*: this method might never get stabilized and/or removed in the
50 /// future as there will likely be another, preferred way of obtaining this
51 /// iterator (either via `IntoIterator` for arrays or via another way).
52 #[unstable(feature = "array_value_iter", issue = "65798")]
53 pub fn new(array: [T; N]) -> Self {
54 // SAFETY: The transmute here is actually safe. The docs of `MaybeUninit`
57 // > `MaybeUninit<T>` is guaranteed to have the same size and alignment
60 // The docs even show a transmute from an array of `MaybeUninit<T>` to
63 // With that, this initialization satisfies the invariants.
65 // FIXME(LukasKalbertodt): actually use `mem::transmute` here, once it
66 // works with const generics:
67 // `mem::transmute::<[T; {N}], [MaybeUninit<T>; {N}]>(array)`
69 // Until then, we do it manually here. We first create a bitwise copy
70 // but cast the pointer so that it is treated as a different type. Then
71 // we forget `array` so that it is not dropped.
73 let data = ptr::read(&array as *const [T; N] as *const [MaybeUninit<T>; N]);
84 /// Returns an immutable slice of all elements that have not been yielded
86 fn as_slice(&self) -> &[T] {
87 let slice = &self.data[self.alive.clone()];
88 // SAFETY: This transmute is safe. As mentioned in `new`, `MaybeUninit` retains
89 // the size and alignment of `T`. Furthermore, we know that all
90 // elements within `alive` are properly initialized.
92 mem::transmute::<&[MaybeUninit<T>], &[T]>(slice)
96 /// Returns a mutable slice of all elements that have not been yielded yet.
97 fn as_mut_slice(&mut self) -> &mut [T] {
98 // This transmute is safe, same as in `as_slice` above.
99 let slice = &mut self.data[self.alive.clone()];
100 // SAFETY: This transmute is safe. As mentioned in `new`, `MaybeUninit` retains
101 // the size and alignment of `T`. Furthermore, we know that all
102 // elements within `alive` are properly initialized.
104 mem::transmute::<&mut [MaybeUninit<T>], &mut [T]>(slice)
110 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
111 impl<T, const N: usize> Iterator for IntoIter<T, {N}>
113 [T; N]: LengthAtMost32,
116 fn next(&mut self) -> Option<Self::Item> {
117 if self.alive.start == self.alive.end {
123 // From the check above we know that `alive.start != alive.end`.
124 // Combine this with the invariant `alive.start <= alive.end`, we know
125 // that `alive.start < alive.end`. Increasing `alive.start` by 1
126 // maintains the invariant regarding `alive`. However, due to this
127 // change, for a short time, the alive zone is not `data[alive]`
128 // anymore, but `data[idx..alive.end]`.
129 let idx = self.alive.start;
130 self.alive.start += 1;
132 // Read the element from the array.
133 // SAFETY: This is safe: `idx` is an index
134 // into the "alive" region of the array. Reading this element means
135 // that `data[idx]` is regarded as dead now (i.e. do not touch). As
136 // `idx` was the start of the alive-zone, the alive zone is now
137 // `data[alive]` again, restoring all invariants.
138 let out = unsafe { self.data.get_unchecked(idx).read() };
143 fn size_hint(&self) -> (usize, Option<usize>) {
144 let len = self.len();
148 fn count(self) -> usize {
152 fn last(mut self) -> Option<Self::Item> {
157 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
158 impl<T, const N: usize> DoubleEndedIterator for IntoIter<T, {N}>
160 [T; N]: LengthAtMost32,
162 fn next_back(&mut self) -> Option<Self::Item> {
163 if self.alive.start == self.alive.end {
167 // Decrease end index.
169 // From the check above we know that `alive.start != alive.end`.
170 // Combine this with the invariant `alive.start <= alive.end`, we know
171 // that `alive.start < alive.end`. As `alive.start` cannot be negative,
172 // `alive.end` is at least 1, meaning that we can safely decrement it
173 // by one. This also maintains the invariant `alive.start <=
174 // alive.end`. However, due to this change, for a short time, the alive
175 // zone is not `data[alive]` anymore, but `data[alive.start..alive.end
179 // Read the element from the array.
180 // SAFETY: This is safe: `alive.end` is an
181 // index into the "alive" region of the array. Compare the previous
182 // comment that states that the alive region is
183 // `data[alive.start..alive.end + 1]`. Reading this element means that
184 // `data[alive.end]` is regarded as dead now (i.e. do not touch). As
185 // `alive.end` was the end of the alive-zone, the alive zone is now
186 // `data[alive]` again, restoring all invariants.
187 let out = unsafe { self.data.get_unchecked(self.alive.end).read() };
193 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
194 impl<T, const N: usize> Drop for IntoIter<T, {N}>
196 [T; N]: LengthAtMost32,
199 // SAFETY: This is safe: `as_mut_slice` returns exactly the sub-slice
200 // of elements that have not been moved out yet and that remain
203 ptr::drop_in_place(self.as_mut_slice())
208 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
209 impl<T, const N: usize> ExactSizeIterator for IntoIter<T, {N}>
211 [T; N]: LengthAtMost32,
213 fn len(&self) -> usize {
214 // Will never underflow due to the invariant `alive.start <=
216 self.alive.end - self.alive.start
218 fn is_empty(&self) -> bool {
219 self.alive.is_empty()
223 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
224 impl<T, const N: usize> FusedIterator for IntoIter<T, {N}>
226 [T; N]: LengthAtMost32,
229 // The iterator indeed reports the correct length. The number of "alive"
230 // elements (that will still be yielded) is the length of the range `alive`.
231 // This range is decremented in length in either `next` or `next_back`. It is
232 // always decremented by 1 in those methods, but only if `Some(_)` is returned.
233 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
234 unsafe impl<T, const N: usize> TrustedLen for IntoIter<T, {N}>
236 [T; N]: LengthAtMost32,
239 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
240 impl<T: Clone, const N: usize> Clone for IntoIter<T, {N}>
242 [T; N]: LengthAtMost32,
244 fn clone(&self) -> Self {
245 // SAFETY: each point of unsafety is documented inside the unsafe block
247 // This creates a new uninitialized array. Note that the `assume_init`
248 // refers to the array, not the individual elements. And it is Ok if
249 // the array is in an uninitialized state as all elements may be
250 // uninitialized (all bit patterns are valid). Compare the
251 // `MaybeUninit` docs for more information.
252 let mut new_data: [MaybeUninit<T>; N] = MaybeUninit::uninit().assume_init();
254 // Clone all alive elements.
255 for idx in self.alive.clone() {
256 // The element at `idx` in the old array is alive, so we can
257 // safely call `get_ref()`. We then clone it, and write the
258 // clone into the new array.
259 let clone = self.data.get_unchecked(idx).get_ref().clone();
260 new_data.get_unchecked_mut(idx).write(clone);
265 alive: self.alive.clone(),
271 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
272 impl<T: fmt::Debug, const N: usize> fmt::Debug for IntoIter<T, {N}>
274 [T; N]: LengthAtMost32,
276 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277 // Only print the elements that were not yielded yet: we cannot
278 // access the yielded elements anymore.
279 f.debug_tuple("IntoIter")
280 .field(&self.as_slice())