]> git.proxmox.com Git - rustc.git/blob - library/core/src/array/iter.rs
New upstream version 1.51.0+dfsg1
[rustc.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 #[stable(feature = "array_value_iter", since = "1.51.0")]
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 be deprecated in the future,
42 /// after [`IntoIterator` is implemented for arrays][array-into-iter].
43 ///
44 /// # Examples
45 ///
46 /// ```
47 /// use std::array;
48 ///
49 /// for value in array::IntoIter::new([1, 2, 3, 4, 5]) {
50 /// // The type of `value` is a `i32` here, instead of `&i32`
51 /// let _: i32 = value;
52 /// }
53 /// ```
54 /// [array-into-iter]: https://github.com/rust-lang/rust/pull/65819
55 #[stable(feature = "array_value_iter", since = "1.51.0")]
56 pub fn new(array: [T; N]) -> Self {
57 // SAFETY: The transmute here is actually safe. The docs of `MaybeUninit`
58 // promise:
59 //
60 // > `MaybeUninit<T>` is guaranteed to have the same size and alignment
61 // > as `T`.
62 //
63 // The docs even show a transmute from an array of `MaybeUninit<T>` to
64 // an array of `T`.
65 //
66 // With that, this initialization satisfies the invariants.
67
68 // FIXME(LukasKalbertodt): actually use `mem::transmute` here, once it
69 // works with const generics:
70 // `mem::transmute::<[T; N], [MaybeUninit<T>; N]>(array)`
71 //
72 // Until then, we can use `mem::transmute_copy` to create a bitwise copy
73 // as a different type, then forget `array` so that it is not dropped.
74 unsafe {
75 let iter = Self { data: mem::transmute_copy(&array), alive: 0..N };
76 mem::forget(array);
77 iter
78 }
79 }
80
81 /// Returns an immutable slice of all elements that have not been yielded
82 /// yet.
83 #[stable(feature = "array_value_iter", since = "1.51.0")]
84 pub fn as_slice(&self) -> &[T] {
85 // SAFETY: We know that all elements within `alive` are properly initialized.
86 unsafe {
87 let slice = self.data.get_unchecked(self.alive.clone());
88 MaybeUninit::slice_assume_init_ref(slice)
89 }
90 }
91
92 /// Returns a mutable slice of all elements that have not been yielded yet.
93 #[stable(feature = "array_value_iter", since = "1.51.0")]
94 pub fn as_mut_slice(&mut self) -> &mut [T] {
95 // SAFETY: We know that all elements within `alive` are properly initialized.
96 unsafe {
97 let slice = self.data.get_unchecked_mut(self.alive.clone());
98 MaybeUninit::slice_assume_init_mut(slice)
99 }
100 }
101 }
102
103 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
104 impl<T, const N: usize> Iterator for IntoIter<T, N> {
105 type Item = T;
106 fn next(&mut self) -> Option<Self::Item> {
107 // Get the next index from the front.
108 //
109 // Increasing `alive.start` by 1 maintains the invariant regarding
110 // `alive`. However, due to this change, for a short time, the alive
111 // zone is not `data[alive]` anymore, but `data[idx..alive.end]`.
112 self.alive.next().map(|idx| {
113 // Read the element from the array.
114 // SAFETY: `idx` is an index into the former "alive" region of the
115 // array. Reading this element means that `data[idx]` is regarded as
116 // dead now (i.e. do not touch). As `idx` was the start of the
117 // alive-zone, the alive zone is now `data[alive]` again, restoring
118 // all invariants.
119 unsafe { self.data.get_unchecked(idx).assume_init_read() }
120 })
121 }
122
123 fn size_hint(&self) -> (usize, Option<usize>) {
124 let len = self.len();
125 (len, Some(len))
126 }
127
128 fn count(self) -> usize {
129 self.len()
130 }
131
132 fn last(mut self) -> Option<Self::Item> {
133 self.next_back()
134 }
135 }
136
137 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
138 impl<T, const N: usize> DoubleEndedIterator for IntoIter<T, N> {
139 fn next_back(&mut self) -> Option<Self::Item> {
140 // Get the next index from the back.
141 //
142 // Decreasing `alive.end` by 1 maintains the invariant regarding
143 // `alive`. However, due to this change, for a short time, the alive
144 // zone is not `data[alive]` anymore, but `data[alive.start..=idx]`.
145 self.alive.next_back().map(|idx| {
146 // Read the element from the array.
147 // SAFETY: `idx` is an index into the former "alive" region of the
148 // array. Reading this element means that `data[idx]` is regarded as
149 // dead now (i.e. do not touch). As `idx` was the end of the
150 // alive-zone, the alive zone is now `data[alive]` again, restoring
151 // all invariants.
152 unsafe { self.data.get_unchecked(idx).assume_init_read() }
153 })
154 }
155 }
156
157 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
158 impl<T, const N: usize> Drop for IntoIter<T, N> {
159 fn drop(&mut self) {
160 // SAFETY: This is safe: `as_mut_slice` returns exactly the sub-slice
161 // of elements that have not been moved out yet and that remain
162 // to be dropped.
163 unsafe { ptr::drop_in_place(self.as_mut_slice()) }
164 }
165 }
166
167 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
168 impl<T, const N: usize> ExactSizeIterator for IntoIter<T, N> {
169 fn len(&self) -> usize {
170 // Will never underflow due to the invariant `alive.start <=
171 // alive.end`.
172 self.alive.end - self.alive.start
173 }
174 fn is_empty(&self) -> bool {
175 self.alive.is_empty()
176 }
177 }
178
179 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
180 impl<T, const N: usize> FusedIterator for IntoIter<T, N> {}
181
182 // The iterator indeed reports the correct length. The number of "alive"
183 // elements (that will still be yielded) is the length of the range `alive`.
184 // This range is decremented in length in either `next` or `next_back`. It is
185 // always decremented by 1 in those methods, but only if `Some(_)` is returned.
186 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
187 unsafe impl<T, const N: usize> TrustedLen for IntoIter<T, N> {}
188
189 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
190 impl<T: Clone, const N: usize> Clone for IntoIter<T, N> {
191 fn clone(&self) -> Self {
192 // Note, we don't really need to match the exact same alive range, so
193 // we can just clone into offset 0 regardless of where `self` is.
194 let mut new = Self { data: MaybeUninit::uninit_array(), alive: 0..0 };
195
196 // Clone all alive elements.
197 for (src, dst) in self.as_slice().iter().zip(&mut new.data) {
198 // Write a clone into the new array, then update its alive range.
199 // If cloning panics, we'll correctly drop the previous items.
200 dst.write(src.clone());
201 new.alive.end += 1;
202 }
203
204 new
205 }
206 }
207
208 #[stable(feature = "array_value_iter_impls", since = "1.40.0")]
209 impl<T: fmt::Debug, const N: usize> fmt::Debug for IntoIter<T, N> {
210 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211 // Only print the elements that were not yielded yet: we cannot
212 // access the yielded elements anymore.
213 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
214 }
215 }