]> git.lizzy.rs Git - rust.git/blob - src/libcore/array/iter.rs
Rollup merge of #66535 - estebank:issue-62480, r=matthewjasper
[rust.git] / src / libcore / array / iter.rs
1 //! Defines the `IntoIter` owned iterator for arrays.
2
3 use crate::{
4     fmt,
5     iter::{ExactSizeIterator, FusedIterator, TrustedLen},
6     mem::{self, MaybeUninit},
7     ops::Range,
8     ptr,
9 };
10 use super::LengthAtMost32;
11
12
13 /// A by-value [array] iterator.
14 ///
15 /// [array]: ../../std/primitive.array.html
16 #[unstable(feature = "array_value_iter", issue = "65798")]
17 pub struct IntoIter<T, const N: usize>
18 where
19     [T; N]: LengthAtMost32,
20 {
21     /// This is the array we are iterating over.
22     ///
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!
28     ///
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],
34
35     /// The elements in `data` that have not been yielded yet.
36     ///
37     /// Invariants:
38     /// - `alive.start <= alive.end`
39     /// - `alive.end <= N`
40     alive: Range<usize>,
41 }
42
43 impl<T, const N: usize> IntoIter<T, {N}>
44 where
45     [T; N]: LengthAtMost32,
46 {
47     /// Creates a new iterator over the given `array`.
48     ///
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`
55         // promise:
56         //
57         // > `MaybeUninit<T>` is guaranteed to have the same size and alignment
58         // > as `T`.
59         //
60         // The docs even show a transmute from an array of `MaybeUninit<T>` to
61         // an array of `T`.
62         //
63         // With that, this initialization satisfies the invariants.
64
65         // FIXME(LukasKalbertodt): actually use `mem::transmute` here, once it
66         // works with const generics:
67         //     `mem::transmute::<[T; {N}], [MaybeUninit<T>; {N}]>(array)`
68         //
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.
72         let data = unsafe {
73             let data = ptr::read(&array as *const [T; N] as *const [MaybeUninit<T>; N]);
74             mem::forget(array);
75             data
76         };
77
78         Self {
79             data,
80             alive: 0..N,
81         }
82     }
83
84     /// Returns an immutable slice of all elements that have not been yielded
85     /// yet.
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.
91         unsafe {
92             mem::transmute::<&[MaybeUninit<T>], &[T]>(slice)
93         }
94     }
95
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.
103         unsafe {
104             mem::transmute::<&mut [MaybeUninit<T>], &mut [T]>(slice)
105         }
106     }
107 }
108
109
110 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
111 impl<T, const N: usize> Iterator for IntoIter<T, {N}>
112 where
113     [T; N]: LengthAtMost32,
114 {
115     type Item = T;
116     fn next(&mut self) -> Option<Self::Item> {
117         if self.alive.start == self.alive.end {
118             return None;
119         }
120
121         // Bump start index.
122         //
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;
131
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() };
139
140         Some(out)
141     }
142
143     fn size_hint(&self) -> (usize, Option<usize>) {
144         let len = self.len();
145         (len, Some(len))
146     }
147
148     fn count(self) -> usize {
149         self.len()
150     }
151
152     fn last(mut self) -> Option<Self::Item> {
153         self.next_back()
154     }
155 }
156
157 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
158 impl<T, const N: usize> DoubleEndedIterator for IntoIter<T, {N}>
159 where
160     [T; N]: LengthAtMost32,
161 {
162     fn next_back(&mut self) -> Option<Self::Item> {
163         if self.alive.start == self.alive.end {
164             return None;
165         }
166
167         // Decrease end index.
168         //
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
176         // + 1]`.
177         self.alive.end -= 1;
178
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() };
188
189         Some(out)
190     }
191 }
192
193 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
194 impl<T, const N: usize> Drop for IntoIter<T, {N}>
195 where
196     [T; N]: LengthAtMost32,
197 {
198     fn drop(&mut self) {
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
201         // to be dropped.
202         unsafe {
203             ptr::drop_in_place(self.as_mut_slice())
204         }
205     }
206 }
207
208 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
209 impl<T, const N: usize> ExactSizeIterator for IntoIter<T, {N}>
210 where
211     [T; N]: LengthAtMost32,
212 {
213     fn len(&self) -> usize {
214         // Will never underflow due to the invariant `alive.start <=
215         // alive.end`.
216         self.alive.end - self.alive.start
217     }
218     fn is_empty(&self) -> bool {
219         self.alive.is_empty()
220     }
221 }
222
223 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
224 impl<T, const N: usize> FusedIterator for IntoIter<T, {N}>
225 where
226     [T; N]: LengthAtMost32,
227 {}
228
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}>
235 where
236     [T; N]: LengthAtMost32,
237 {}
238
239 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
240 impl<T: Clone, const N: usize> Clone for IntoIter<T, {N}>
241 where
242     [T; N]: LengthAtMost32,
243 {
244     fn clone(&self) -> Self {
245         // SAFETY: each point of unsafety is documented inside the unsafe block
246         unsafe {
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();
253
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);
261             }
262
263             Self {
264                 data: new_data,
265                 alive: self.alive.clone(),
266             }
267         }
268     }
269 }
270
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}>
273 where
274     [T; N]: LengthAtMost32,
275 {
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())
281             .finish()
282     }
283 }