1 //! Defines the `IntoIter` owned iterator for arrays.
5 iter::{ExactSizeIterator, FusedIterator, TrustedLen},
6 mem::{self, MaybeUninit},
11 /// A by-value [array] iterator.
13 /// [array]: ../../std/primitive.array.html
14 #[unstable(feature = "array_value_iter", issue = "65798")]
15 pub struct IntoIter<T, const N: usize> {
16 /// This is the array we are iterating over.
18 /// Elements with index `i` where `alive.start <= i < alive.end` have not
19 /// been yielded yet and are valid array entries. Elements with indices `i
20 /// < alive.start` or `i >= alive.end` have been yielded already and must
21 /// not be accessed anymore! Those dead elements might even be in a
22 /// completely uninitialized state!
24 /// So the invariants are:
25 /// - `data[alive]` is alive (i.e. contains valid elements)
26 /// - `data[..alive.start]` and `data[alive.end..]` are dead (i.e. the
27 /// elements were already read and must not be touched anymore!)
28 data: [MaybeUninit<T>; N],
30 /// The elements in `data` that have not been yielded yet.
33 /// - `alive.start <= alive.end`
34 /// - `alive.end <= N`
38 impl<T, const N: usize> IntoIter<T, N> {
39 /// Creates a new iterator over the given `array`.
41 /// *Note*: this method might never get stabilized and/or removed in the
42 /// future as there will likely be another, preferred way of obtaining this
43 /// iterator (either via `IntoIterator` for arrays or via another way).
44 #[unstable(feature = "array_value_iter", issue = "65798")]
45 pub fn new(array: [T; N]) -> Self {
46 // SAFETY: The transmute here is actually safe. The docs of `MaybeUninit`
49 // > `MaybeUninit<T>` is guaranteed to have the same size and alignment
52 // The docs even show a transmute from an array of `MaybeUninit<T>` to
55 // With that, this initialization satisfies the invariants.
57 // FIXME(LukasKalbertodt): actually use `mem::transmute` here, once it
58 // works with const generics:
59 // `mem::transmute::<[T; {N}], [MaybeUninit<T>; {N}]>(array)`
61 // Until then, we do it manually here. We first create a bitwise copy
62 // but cast the pointer so that it is treated as a different type. Then
63 // we forget `array` so that it is not dropped.
65 let data = ptr::read(&array as *const [T; N] as *const [MaybeUninit<T>; N]);
70 Self { data, alive: 0..N }
73 /// Returns an immutable slice of all elements that have not been yielded
75 fn as_slice(&self) -> &[T] {
76 let slice = &self.data[self.alive.clone()];
77 // SAFETY: This transmute is safe. As mentioned in `new`, `MaybeUninit` retains
78 // the size and alignment of `T`. Furthermore, we know that all
79 // elements within `alive` are properly initialized.
80 unsafe { mem::transmute::<&[MaybeUninit<T>], &[T]>(slice) }
83 /// Returns a mutable slice of all elements that have not been yielded yet.
84 fn as_mut_slice(&mut self) -> &mut [T] {
85 // This transmute is safe, same as in `as_slice` above.
86 let slice = &mut self.data[self.alive.clone()];
87 // SAFETY: This transmute is safe. As mentioned in `new`, `MaybeUninit` retains
88 // the size and alignment of `T`. Furthermore, we know that all
89 // elements within `alive` are properly initialized.
90 unsafe { mem::transmute::<&mut [MaybeUninit<T>], &mut [T]>(slice) }
94 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
95 impl<T, const N: usize> Iterator for IntoIter<T, N> {
97 fn next(&mut self) -> Option<Self::Item> {
98 if self.alive.start == self.alive.end {
104 // From the check above we know that `alive.start != alive.end`.
105 // Combine this with the invariant `alive.start <= alive.end`, we know
106 // that `alive.start < alive.end`. Increasing `alive.start` by 1
107 // maintains the invariant regarding `alive`. However, due to this
108 // change, for a short time, the alive zone is not `data[alive]`
109 // anymore, but `data[idx..alive.end]`.
110 let idx = self.alive.start;
111 self.alive.start += 1;
113 // Read the element from the array.
114 // SAFETY: This is safe: `idx` is an index
115 // into the "alive" region of the array. Reading this element means
116 // that `data[idx]` is regarded as dead now (i.e. do not touch). As
117 // `idx` was the start of the alive-zone, the alive zone is now
118 // `data[alive]` again, restoring all invariants.
119 let out = unsafe { self.data.get_unchecked(idx).read() };
124 fn size_hint(&self) -> (usize, Option<usize>) {
125 let len = self.len();
129 fn count(self) -> usize {
133 fn last(mut self) -> Option<Self::Item> {
138 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
139 impl<T, const N: usize> DoubleEndedIterator for IntoIter<T, N> {
140 fn next_back(&mut self) -> Option<Self::Item> {
141 if self.alive.start == self.alive.end {
145 // Decrease end index.
147 // From the check above we know that `alive.start != alive.end`.
148 // Combine this with the invariant `alive.start <= alive.end`, we know
149 // that `alive.start < alive.end`. As `alive.start` cannot be negative,
150 // `alive.end` is at least 1, meaning that we can safely decrement it
151 // by one. This also maintains the invariant `alive.start <=
152 // alive.end`. However, due to this change, for a short time, the alive
153 // zone is not `data[alive]` anymore, but `data[alive.start..alive.end
157 // Read the element from the array.
158 // SAFETY: This is safe: `alive.end` is an
159 // index into the "alive" region of the array. Compare the previous
160 // comment that states that the alive region is
161 // `data[alive.start..alive.end + 1]`. Reading this element means that
162 // `data[alive.end]` is regarded as dead now (i.e. do not touch). As
163 // `alive.end` was the end of the alive-zone, the alive zone is now
164 // `data[alive]` again, restoring all invariants.
165 let out = unsafe { self.data.get_unchecked(self.alive.end).read() };
171 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
172 impl<T, const N: usize> Drop for IntoIter<T, N> {
174 // SAFETY: This is safe: `as_mut_slice` returns exactly the sub-slice
175 // of elements that have not been moved out yet and that remain
177 unsafe { ptr::drop_in_place(self.as_mut_slice()) }
181 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
182 impl<T, const N: usize> ExactSizeIterator for IntoIter<T, N> {
183 fn len(&self) -> usize {
184 // Will never underflow due to the invariant `alive.start <=
186 self.alive.end - self.alive.start
188 fn is_empty(&self) -> bool {
189 self.alive.is_empty()
193 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
194 impl<T, const N: usize> FusedIterator for IntoIter<T, N> {}
196 // The iterator indeed reports the correct length. The number of "alive"
197 // elements (that will still be yielded) is the length of the range `alive`.
198 // This range is decremented in length in either `next` or `next_back`. It is
199 // always decremented by 1 in those methods, but only if `Some(_)` is returned.
200 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
201 unsafe impl<T, const N: usize> TrustedLen for IntoIter<T, N> {}
203 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
204 impl<T: Clone, const N: usize> Clone for IntoIter<T, N> {
205 fn clone(&self) -> Self {
206 // SAFETY: each point of unsafety is documented inside the unsafe block
208 // This creates a new uninitialized array. Note that the `assume_init`
209 // refers to the array, not the individual elements. And it is Ok if
210 // the array is in an uninitialized state as all elements may be
211 // uninitialized (all bit patterns are valid). Compare the
212 // `MaybeUninit` docs for more information.
213 let mut new_data: [MaybeUninit<T>; N] = MaybeUninit::uninit().assume_init();
215 // Clone all alive elements.
216 for idx in self.alive.clone() {
217 // The element at `idx` in the old array is alive, so we can
218 // safely call `get_ref()`. We then clone it, and write the
219 // clone into the new array.
220 let clone = self.data.get_unchecked(idx).get_ref().clone();
221 new_data.get_unchecked_mut(idx).write(clone);
224 Self { data: new_data, alive: self.alive.clone() }
229 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
230 impl<T: fmt::Debug, const N: usize> fmt::Debug for IntoIter<T, N> {
231 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
232 // Only print the elements that were not yielded yet: we cannot
233 // access the yielded elements anymore.
234 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()