]> git.lizzy.rs Git - rust.git/blob - library/core/src/array/iter.rs
Add comment about the lack of `ExpnData` serialization for proc-macro crates
[rust.git] / library / core / src / 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
11 /// A by-value [array] iterator.
12 ///
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.
17     ///
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!
23     ///
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],
29
30     /// The elements in `data` that have not been yielded yet.
31     ///
32     /// Invariants:
33     /// - `alive.start <= alive.end`
34     /// - `alive.end <= N`
35     alive: Range<usize>,
36 }
37
38 impl<T, const N: usize> IntoIter<T, N> {
39     /// Creates a new iterator over the given `array`.
40     ///
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`
47         // promise:
48         //
49         // > `MaybeUninit<T>` is guaranteed to have the same size and alignment
50         // > as `T`.
51         //
52         // The docs even show a transmute from an array of `MaybeUninit<T>` to
53         // an array of `T`.
54         //
55         // With that, this initialization satisfies the invariants.
56
57         // FIXME(LukasKalbertodt): actually use `mem::transmute` here, once it
58         // works with const generics:
59         //     `mem::transmute::<[T; {N}], [MaybeUninit<T>; {N}]>(array)`
60         //
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.
64         let data = unsafe {
65             let data = ptr::read(&array as *const [T; N] as *const [MaybeUninit<T>; N]);
66             mem::forget(array);
67             data
68         };
69
70         Self { data, alive: 0..N }
71     }
72
73     /// Returns an immutable slice of all elements that have not been yielded
74     /// yet.
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) }
81     }
82
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) }
91     }
92 }
93
94 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
95 impl<T, const N: usize> Iterator for IntoIter<T, N> {
96     type Item = T;
97     fn next(&mut self) -> Option<Self::Item> {
98         if self.alive.start == self.alive.end {
99             return None;
100         }
101
102         // Bump start index.
103         //
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;
112
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() };
120
121         Some(out)
122     }
123
124     fn size_hint(&self) -> (usize, Option<usize>) {
125         let len = self.len();
126         (len, Some(len))
127     }
128
129     fn count(self) -> usize {
130         self.len()
131     }
132
133     fn last(mut self) -> Option<Self::Item> {
134         self.next_back()
135     }
136 }
137
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 {
142             return None;
143         }
144
145         // Decrease end index.
146         //
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
154         // + 1]`.
155         self.alive.end -= 1;
156
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() };
166
167         Some(out)
168     }
169 }
170
171 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
172 impl<T, const N: usize> Drop for IntoIter<T, N> {
173     fn drop(&mut self) {
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
176         // to be dropped.
177         unsafe { ptr::drop_in_place(self.as_mut_slice()) }
178     }
179 }
180
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 <=
185         // alive.end`.
186         self.alive.end - self.alive.start
187     }
188     fn is_empty(&self) -> bool {
189         self.alive.is_empty()
190     }
191 }
192
193 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
194 impl<T, const N: usize> FusedIterator for IntoIter<T, N> {}
195
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> {}
202
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
207         unsafe {
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();
214
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);
222             }
223
224             Self { data: new_data, alive: self.alive.clone() }
225         }
226     }
227 }
228
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()
235     }
236 }