iter.rs - source
Skip to main content core/array/ iter.rs 1 //! Defines the `IntoIter` owned iterator for arrays. 2 3 use crate ::intrinsics::transmute_unchecked ; 4 use crate ::iter::{ FusedIterator , TrustedLen , TrustedRandomAccessNoCoerce }; 5 use crate ::mem::{ ManuallyDrop , MaybeUninit }; 6 use crate ::num::NonZero ; 7 use crate ::ops::{ Deref as _ , DerefMut as _ , IndexRange , Range , Try }; 8 use crate ::{ fmt , ptr }; 9 10 mod iter_inner ; 11 12 type InnerSized<T, const N: usize > = iter_inner:: PolymorphicIter <[ MaybeUninit <T>; N ]>; 13 type InnerUnsized<T> = iter_inner:: PolymorphicIter <[ MaybeUninit <T>]>; 14 15 /// A by-value [array] iterator.
16 #[stable(feature = "array_value_iter" , since = "1.51.0" )] 17 #[rustc_insignificant_dtor] 18 #[rustc_diagnostic_item = "ArrayIntoIter" ] 19 #[derive( Clone )] 20 pub struct IntoIter <T, const N: usize > { 21 inner: ManuallyDrop < InnerSized <T, N >>, 22 } 23 24 impl <T, const N: usize > IntoIter <T, N > { 25 #[inline] 26 #[rustc_const_unstable(feature = "const_iter" , issue = "92476" )] 27 const fn unsize( & self ) -> & InnerUnsized <T> { 28 self .inner. deref () 29 } 30 #[inline] 31 #[rustc_const_unstable(feature = "const_iter" , issue = "92476" )] 32 const fn unsize_mut( &mut self ) -> &mut InnerUnsized <T> { 33 self .inner. deref_mut () 34 } 35 } 36 37 #[stable(feature = "boxed_array_value_iter" , since = "1.99.0" )] 38 impl <T, const N: usize > !
Iterator for [T; N ] {} 39 40 // Note: the `#[rustc_skip_during_method_dispatch(array)]` on `trait IntoIterator` 41 // hides this implementation from explicit `.into_iter()` calls on editions < 2021, 42 // so those calls will still resolve to the slice implementation, by reference. 43 #[stable(feature = "array_into_iter_impl" , since = "1.53.0" )] 44 impl <T, const N: usize > IntoIterator for [T; N ] { 45 type Item = T; 46 type IntoIter = IntoIter <T, N >; 47 48 /// Creates a consuming iterator, that is, one that moves each value out of 49 /// the array (from start to end).
50 /// 51 /// The array cannot be used after calling this unless `T` implements 52 /// `Copy`, so the whole array is copied. 53 /// 54 /// Arrays have special behavior when calling `.into_iter()` prior to the 55 /// 2021 edition -- see the [array] Editions section for more information. 56 /// 57 /// [array]: prim@array 58 #[inline] 59 fn into_iter( self ) -> Self ::IntoIter { 60 // SAFETY: The transmute here is actually safe.
The docs of `MaybeUninit` 61 // promise: 62 // 63 // > `MaybeUninit<T>` is guaranteed to have the same size and alignment 64 // > as `T`. 65 // 66 // The docs even show a transmute from an array of `MaybeUninit<T>` to 67 // an array of `T`. 68 // 69 // With that, this initialization satisfies the invariants. 70 // 71 // FIXME: If normal `transmute` ever gets smart enough to allow this 72 // directly, use it instead of `transmute_unchecked`.
73 let data: [ MaybeUninit <T>; N ] = unsafe { transmute_unchecked ( self ) }; 74 // SAFETY: The original array was entirely initialized and the alive 75 // range we're passing here represents that fact. 76 let inner = unsafe { InnerSized :: new_unchecked ( IndexRange :: zero_to ( N ), data ) }; 77 IntoIter { inner: ManuallyDrop :: new ( inner ) } 78 } 79 } 80 81 impl <T, const N: usize > IntoIter <T, N > { 82 /// Creates a new iterator over the given `array`.
83 #[stable(feature = "array_value_iter" , since = "1.51.0" )] 84 #[deprecated(since = "1.59.0" , note = "use `IntoIterator::into_iter` instead" )] 85 pub fn new(array: [T; N ]) -> Self { 86 IntoIterator:: into_iter ( array ) 87 } 88 89 /// Creates an iterator over the elements in a partially-initialized buffer. 90 /// 91 /// If you have a fully-initialized array, then use [`IntoIterator`]. 92 /// But this is useful for returning partial results from unsafe code.
93 /// 94 /// # Safety 95 /// 96 /// - The `buffer[initialized]` elements must all be initialized. 97 /// - The range must be canonical, with `initialized.start <= initialized.end`. 98 /// - The range must be in-bounds for the buffer, with `initialized.end <= N`. 99 /// (Like how indexing `[0][100..100]` fails despite the range being empty.) 100 /// 101 /// It's sound to have more elements initialized than mentioned, though that 102 /// will most likely result in them being leaked.
103 /// 104 /// # Examples 105 /// 106 /// ``` 107 /// #![feature(array_into_iter_constructors)] 108 /// #![feature(maybe_uninit_uninit_array_transpose)] 109 /// use std::array::IntoIter; 110 /// use std::mem::MaybeUninit; 111 /// 112 /// # // Hi! Thanks for reading the code. This is restricted to `Copy` because 113 /// # // otherwise it could leak. A fully-general version this would need a drop 114 /// # // guard to handle panics from the iterator, but this works for an example.
115 /// fn next_chunk<T: Copy, const N: usize>( 116 /// it: &mut impl Iterator<Item = T>, 117 /// ) -> Result<[T; N], IntoIter<T, N>> { 118 /// let mut buffer = [const { MaybeUninit::uninit() }; N]; 119 /// let mut i = 0; 120 /// while i < N { 121 /// match it.next() { 122 /// Some(x) => { 123 /// buffer[i].write(x); 124 /// i += 1; 125 /// } 126 /// None => { 127 /// // SAFETY: We've initialized the first `i` items 128 /// unsafe { 129 /// return Err(IntoIter::new_unchecked(buffer, 0..i)); 130 /// } 131 /// } 132 /// } 133 /// } 134 /// 135 /// // SAFETY: We've initialized all N items 136 /// unsafe { Ok(buffer.transpose().assume_init()) } 137 /// } 138 /// 139 /// let r: [_; 4] = next_chunk(&mut (10..16)).unwrap(); 140 /// assert_eq!(r, [10, 11, 12, 13]); 141 /// let r: IntoIter<_, 40> = next_chunk(&mut (10..16)).unwrap_err(); 142 /// assert_eq!(r.collect::<Vec<_>>(), vec![10, 11, 12, 13, 14, 15]); 143 /// ``` 144 #[unstable(feature = "array_into_iter_constructors" , issue = "91583" )] 145 #[inline] 146 pub const unsafe fn new_unchecked( 147 buffer: [ MaybeUninit <T>; N ], 148 initialized: Range < usize >, 149 ) -> Self { 150 // SAFETY: one of our safety conditions is that the range is canonical.
151 let alive = unsafe { IndexRange :: new_unchecked ( initialized .start, initialized .end) }; 152 // SAFETY: one of our safety condition is that these items are initialized. 153 let inner = unsafe { InnerSized :: new_unchecked ( alive , buffer ) }; 154 IntoIter { inner: ManuallyDrop :: new ( inner ) } 155 } 156 157 /// Creates an iterator over `T` which returns no elements. 158 /// 159 /// If you just need an empty iterator, then use 160 /// [`iter::empty()`](crate::iter::empty) instead.
161 /// And if you need an empty array, use `[]`. 162 /// 163 /// But this is useful when you need an `array::IntoIter<T, N>` *specifically*. 164 /// 165 /// # Examples 166 /// 167 /// ``` 168 /// #![feature(array_into_iter_constructors)] 169 /// use std::array::IntoIter; 170 /// 171 /// let empty = IntoIter::<i32, 3>::empty(); 172 /// assert_eq!(empty.len(), 0); 173 /// assert_eq!(empty.as_slice(), &[]); 174 /// 175 /// let empty = IntoIter::<!, 200>::empty(); 176 /// assert_eq!(empty.len(), 0); 177 /// ``` 178 /// 179 /// `[1, 2].into_iter()` and `[].into_iter()` have different types 180 /// ```should_fail,edition2021 181 /// #![feature(array_into_iter_constructors)] 182 /// use std::array::IntoIter; 183 /// 184 /// pub fn get_bytes(b: bool) -> IntoIter<i8, 4> { 185 /// if b { 186 /// [1, 2, 3, 4].into_iter() 187 /// } else { 188 /// [].into_iter() // error[E0308]: mismatched types 189 /// } 190 /// } 191 /// ``` 192 /// 193 /// But using this method you can get an empty iterator of appropriate size: 194 /// ```edition2021 195 /// #![feature(array_into_iter_constructors)] 196 /// use std::array::IntoIter; 197 /// 198 /// pub fn get_bytes(b: bool) -> IntoIter<i8, 4> { 199 /// if b { 200 /// [1, 2, 3, 4].into_iter() 201 /// } else { 202 /// IntoIter::empty() 203 /// } 204 /// } 205 /// 206 /// assert_eq!(get_bytes(true).collect::<Vec<_>>(), vec![1, 2, 3, 4]); 207 /// assert_eq!(get_bytes(false).collect::<Vec<_>>(), vec![]); 208 /// ``` 209 #[unstable(feature = "array_into_iter_constr
The rest of this page is on the live site.