• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! Utilities for the array primitive type.
2 //!
3 //! *[See also the array primitive type](array).*
4 
5 #![stable(feature = "core_array", since = "1.36.0")]
6 
7 use crate::borrow::{Borrow, BorrowMut};
8 use crate::cmp::Ordering;
9 use crate::convert::{Infallible, TryFrom};
10 use crate::error::Error;
11 use crate::fmt;
12 use crate::hash::{self, Hash};
13 use crate::iter::UncheckedIterator;
14 use crate::mem::{self, MaybeUninit};
15 use crate::ops::{
16     ChangeOutputType, ControlFlow, FromResidual, Index, IndexMut, NeverShortCircuit, Residual, Try,
17 };
18 use crate::slice::{Iter, IterMut};
19 
20 mod ascii;
21 mod drain;
22 mod equality;
23 mod iter;
24 
25 pub(crate) use drain::drain_array_with;
26 
27 #[stable(feature = "array_value_iter", since = "1.51.0")]
28 pub use iter::IntoIter;
29 
30 /// Creates an array of type [T; N], where each element `T` is the returned value from `cb`
31 /// using that element's index.
32 ///
33 /// # Arguments
34 ///
35 /// * `cb`: Callback where the passed argument is the current array index.
36 ///
37 /// # Example
38 ///
39 /// ```rust
40 /// // type inference is helping us here, the way `from_fn` knows how many
41 /// // elements to produce is the length of array down there: only arrays of
42 /// // equal lengths can be compared, so the const generic parameter `N` is
43 /// // inferred to be 5, thus creating array of 5 elements.
44 ///
45 /// let array = core::array::from_fn(|i| i);
46 /// // indexes are:    0  1  2  3  4
47 /// assert_eq!(array, [0, 1, 2, 3, 4]);
48 ///
49 /// let array2: [usize; 8] = core::array::from_fn(|i| i * 2);
50 /// // indexes are:     0  1  2  3  4  5   6   7
51 /// assert_eq!(array2, [0, 2, 4, 6, 8, 10, 12, 14]);
52 ///
53 /// let bool_arr = core::array::from_fn::<_, 5, _>(|i| i % 2 == 0);
54 /// // indexes are:       0     1      2     3      4
55 /// assert_eq!(bool_arr, [true, false, true, false, true]);
56 /// ```
57 #[inline]
58 #[stable(feature = "array_from_fn", since = "1.63.0")]
from_fn<T, const N: usize, F>(cb: F) -> [T; N] where F: FnMut(usize) -> T,59 pub fn from_fn<T, const N: usize, F>(cb: F) -> [T; N]
60 where
61     F: FnMut(usize) -> T,
62 {
63     try_from_fn(NeverShortCircuit::wrap_mut_1(cb)).0
64 }
65 
66 /// Creates an array `[T; N]` where each fallible array element `T` is returned by the `cb` call.
67 /// Unlike [`from_fn`], where the element creation can't fail, this version will return an error
68 /// if any element creation was unsuccessful.
69 ///
70 /// The return type of this function depends on the return type of the closure.
71 /// If you return `Result<T, E>` from the closure, you'll get a `Result<[T; N], E>`.
72 /// If you return `Option<T>` from the closure, you'll get an `Option<[T; N]>`.
73 ///
74 /// # Arguments
75 ///
76 /// * `cb`: Callback where the passed argument is the current array index.
77 ///
78 /// # Example
79 ///
80 /// ```rust
81 /// #![feature(array_try_from_fn)]
82 ///
83 /// let array: Result<[u8; 5], _> = std::array::try_from_fn(|i| i.try_into());
84 /// assert_eq!(array, Ok([0, 1, 2, 3, 4]));
85 ///
86 /// let array: Result<[i8; 200], _> = std::array::try_from_fn(|i| i.try_into());
87 /// assert!(array.is_err());
88 ///
89 /// let array: Option<[_; 4]> = std::array::try_from_fn(|i| i.checked_add(100));
90 /// assert_eq!(array, Some([100, 101, 102, 103]));
91 ///
92 /// let array: Option<[_; 4]> = std::array::try_from_fn(|i| i.checked_sub(100));
93 /// assert_eq!(array, None);
94 /// ```
95 #[inline]
96 #[unstable(feature = "array_try_from_fn", issue = "89379")]
try_from_fn<R, const N: usize, F>(cb: F) -> ChangeOutputType<R, [R::Output; N]> where F: FnMut(usize) -> R, R: Try, R::Residual: Residual<[R::Output; N]>,97 pub fn try_from_fn<R, const N: usize, F>(cb: F) -> ChangeOutputType<R, [R::Output; N]>
98 where
99     F: FnMut(usize) -> R,
100     R: Try,
101     R::Residual: Residual<[R::Output; N]>,
102 {
103     let mut array = MaybeUninit::uninit_array::<N>();
104     match try_from_fn_erased(&mut array, cb) {
105         ControlFlow::Break(r) => FromResidual::from_residual(r),
106         ControlFlow::Continue(()) => {
107             // SAFETY: All elements of the array were populated.
108             try { unsafe { MaybeUninit::array_assume_init(array) } }
109         }
110     }
111 }
112 
113 /// Converts a reference to `T` into a reference to an array of length 1 (without copying).
114 #[stable(feature = "array_from_ref", since = "1.53.0")]
115 #[rustc_const_stable(feature = "const_array_from_ref_shared", since = "1.63.0")]
from_ref<T>(s: &T) -> &[T; 1]116 pub const fn from_ref<T>(s: &T) -> &[T; 1] {
117     // SAFETY: Converting `&T` to `&[T; 1]` is sound.
118     unsafe { &*(s as *const T).cast::<[T; 1]>() }
119 }
120 
121 /// Converts a mutable reference to `T` into a mutable reference to an array of length 1 (without copying).
122 #[stable(feature = "array_from_ref", since = "1.53.0")]
123 #[rustc_const_unstable(feature = "const_array_from_ref", issue = "90206")]
from_mut<T>(s: &mut T) -> &mut [T; 1]124 pub const fn from_mut<T>(s: &mut T) -> &mut [T; 1] {
125     // SAFETY: Converting `&mut T` to `&mut [T; 1]` is sound.
126     unsafe { &mut *(s as *mut T).cast::<[T; 1]>() }
127 }
128 
129 /// The error type returned when a conversion from a slice to an array fails.
130 #[stable(feature = "try_from", since = "1.34.0")]
131 #[derive(Debug, Copy, Clone)]
132 pub struct TryFromSliceError(());
133 
134 #[stable(feature = "core_array", since = "1.36.0")]
135 impl fmt::Display for TryFromSliceError {
136     #[inline]
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result137     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138         #[allow(deprecated)]
139         self.description().fmt(f)
140     }
141 }
142 
143 #[stable(feature = "try_from", since = "1.34.0")]
144 impl Error for TryFromSliceError {
145     #[allow(deprecated)]
description(&self) -> &str146     fn description(&self) -> &str {
147         "could not convert slice to array"
148     }
149 }
150 
151 #[stable(feature = "try_from_slice_error", since = "1.36.0")]
152 impl From<Infallible> for TryFromSliceError {
from(x: Infallible) -> TryFromSliceError153     fn from(x: Infallible) -> TryFromSliceError {
154         match x {}
155     }
156 }
157 
158 #[stable(feature = "rust1", since = "1.0.0")]
159 impl<T, const N: usize> AsRef<[T]> for [T; N] {
160     #[inline]
as_ref(&self) -> &[T]161     fn as_ref(&self) -> &[T] {
162         &self[..]
163     }
164 }
165 
166 #[stable(feature = "rust1", since = "1.0.0")]
167 impl<T, const N: usize> AsMut<[T]> for [T; N] {
168     #[inline]
as_mut(&mut self) -> &mut [T]169     fn as_mut(&mut self) -> &mut [T] {
170         &mut self[..]
171     }
172 }
173 
174 #[stable(feature = "array_borrow", since = "1.4.0")]
175 impl<T, const N: usize> Borrow<[T]> for [T; N] {
borrow(&self) -> &[T]176     fn borrow(&self) -> &[T] {
177         self
178     }
179 }
180 
181 #[stable(feature = "array_borrow", since = "1.4.0")]
182 impl<T, const N: usize> BorrowMut<[T]> for [T; N] {
borrow_mut(&mut self) -> &mut [T]183     fn borrow_mut(&mut self) -> &mut [T] {
184         self
185     }
186 }
187 
188 /// Tries to create an array `[T; N]` by copying from a slice `&[T]`. Succeeds if
189 /// `slice.len() == N`.
190 ///
191 /// ```
192 /// let bytes: [u8; 3] = [1, 0, 2];
193 ///
194 /// let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&bytes[0..2]).unwrap();
195 /// assert_eq!(1, u16::from_le_bytes(bytes_head));
196 ///
197 /// let bytes_tail: [u8; 2] = bytes[1..3].try_into().unwrap();
198 /// assert_eq!(512, u16::from_le_bytes(bytes_tail));
199 /// ```
200 #[stable(feature = "try_from", since = "1.34.0")]
201 impl<T, const N: usize> TryFrom<&[T]> for [T; N]
202 where
203     T: Copy,
204 {
205     type Error = TryFromSliceError;
206 
207     #[inline]
try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError>208     fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError> {
209         <&Self>::try_from(slice).map(|r| *r)
210     }
211 }
212 
213 /// Tries to create an array `[T; N]` by copying from a mutable slice `&mut [T]`.
214 /// Succeeds if `slice.len() == N`.
215 ///
216 /// ```
217 /// let mut bytes: [u8; 3] = [1, 0, 2];
218 ///
219 /// let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
220 /// assert_eq!(1, u16::from_le_bytes(bytes_head));
221 ///
222 /// let bytes_tail: [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
223 /// assert_eq!(512, u16::from_le_bytes(bytes_tail));
224 /// ```
225 #[stable(feature = "try_from_mut_slice_to_array", since = "1.59.0")]
226 impl<T, const N: usize> TryFrom<&mut [T]> for [T; N]
227 where
228     T: Copy,
229 {
230     type Error = TryFromSliceError;
231 
232     #[inline]
try_from(slice: &mut [T]) -> Result<[T; N], TryFromSliceError>233     fn try_from(slice: &mut [T]) -> Result<[T; N], TryFromSliceError> {
234         <Self>::try_from(&*slice)
235     }
236 }
237 
238 /// Tries to create an array ref `&[T; N]` from a slice ref `&[T]`. Succeeds if
239 /// `slice.len() == N`.
240 ///
241 /// ```
242 /// let bytes: [u8; 3] = [1, 0, 2];
243 ///
244 /// let bytes_head: &[u8; 2] = <&[u8; 2]>::try_from(&bytes[0..2]).unwrap();
245 /// assert_eq!(1, u16::from_le_bytes(*bytes_head));
246 ///
247 /// let bytes_tail: &[u8; 2] = bytes[1..3].try_into().unwrap();
248 /// assert_eq!(512, u16::from_le_bytes(*bytes_tail));
249 /// ```
250 #[stable(feature = "try_from", since = "1.34.0")]
251 impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N] {
252     type Error = TryFromSliceError;
253 
254     #[inline]
try_from(slice: &'a [T]) -> Result<&'a [T; N], TryFromSliceError>255     fn try_from(slice: &'a [T]) -> Result<&'a [T; N], TryFromSliceError> {
256         if slice.len() == N {
257             let ptr = slice.as_ptr() as *const [T; N];
258             // SAFETY: ok because we just checked that the length fits
259             unsafe { Ok(&*ptr) }
260         } else {
261             Err(TryFromSliceError(()))
262         }
263     }
264 }
265 
266 /// Tries to create a mutable array ref `&mut [T; N]` from a mutable slice ref
267 /// `&mut [T]`. Succeeds if `slice.len() == N`.
268 ///
269 /// ```
270 /// let mut bytes: [u8; 3] = [1, 0, 2];
271 ///
272 /// let bytes_head: &mut [u8; 2] = <&mut [u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
273 /// assert_eq!(1, u16::from_le_bytes(*bytes_head));
274 ///
275 /// let bytes_tail: &mut [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
276 /// assert_eq!(512, u16::from_le_bytes(*bytes_tail));
277 /// ```
278 #[stable(feature = "try_from", since = "1.34.0")]
279 impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N] {
280     type Error = TryFromSliceError;
281 
282     #[inline]
try_from(slice: &'a mut [T]) -> Result<&'a mut [T; N], TryFromSliceError>283     fn try_from(slice: &'a mut [T]) -> Result<&'a mut [T; N], TryFromSliceError> {
284         if slice.len() == N {
285             let ptr = slice.as_mut_ptr() as *mut [T; N];
286             // SAFETY: ok because we just checked that the length fits
287             unsafe { Ok(&mut *ptr) }
288         } else {
289             Err(TryFromSliceError(()))
290         }
291     }
292 }
293 
294 /// The hash of an array is the same as that of the corresponding slice,
295 /// as required by the `Borrow` implementation.
296 ///
297 /// ```
298 /// use std::hash::BuildHasher;
299 ///
300 /// let b = std::collections::hash_map::RandomState::new();
301 /// let a: [u8; 3] = [0xa8, 0x3c, 0x09];
302 /// let s: &[u8] = &[0xa8, 0x3c, 0x09];
303 /// assert_eq!(b.hash_one(a), b.hash_one(s));
304 /// ```
305 #[stable(feature = "rust1", since = "1.0.0")]
306 impl<T: Hash, const N: usize> Hash for [T; N] {
hash<H: hash::Hasher>(&self, state: &mut H)307     fn hash<H: hash::Hasher>(&self, state: &mut H) {
308         Hash::hash(&self[..], state)
309     }
310 }
311 
312 #[stable(feature = "rust1", since = "1.0.0")]
313 impl<T: fmt::Debug, const N: usize> fmt::Debug for [T; N] {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result314     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315         fmt::Debug::fmt(&&self[..], f)
316     }
317 }
318 
319 #[stable(feature = "rust1", since = "1.0.0")]
320 impl<'a, T, const N: usize> IntoIterator for &'a [T; N] {
321     type Item = &'a T;
322     type IntoIter = Iter<'a, T>;
323 
into_iter(self) -> Iter<'a, T>324     fn into_iter(self) -> Iter<'a, T> {
325         self.iter()
326     }
327 }
328 
329 #[stable(feature = "rust1", since = "1.0.0")]
330 impl<'a, T, const N: usize> IntoIterator for &'a mut [T; N] {
331     type Item = &'a mut T;
332     type IntoIter = IterMut<'a, T>;
333 
into_iter(self) -> IterMut<'a, T>334     fn into_iter(self) -> IterMut<'a, T> {
335         self.iter_mut()
336     }
337 }
338 
339 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
340 impl<T, I, const N: usize> Index<I> for [T; N]
341 where
342     [T]: Index<I>,
343 {
344     type Output = <[T] as Index<I>>::Output;
345 
346     #[inline]
index(&self, index: I) -> &Self::Output347     fn index(&self, index: I) -> &Self::Output {
348         Index::index(self as &[T], index)
349     }
350 }
351 
352 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
353 impl<T, I, const N: usize> IndexMut<I> for [T; N]
354 where
355     [T]: IndexMut<I>,
356 {
357     #[inline]
index_mut(&mut self, index: I) -> &mut Self::Output358     fn index_mut(&mut self, index: I) -> &mut Self::Output {
359         IndexMut::index_mut(self as &mut [T], index)
360     }
361 }
362 
363 #[stable(feature = "rust1", since = "1.0.0")]
364 impl<T: PartialOrd, const N: usize> PartialOrd for [T; N] {
365     #[inline]
partial_cmp(&self, other: &[T; N]) -> Option<Ordering>366     fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
367         PartialOrd::partial_cmp(&&self[..], &&other[..])
368     }
369     #[inline]
lt(&self, other: &[T; N]) -> bool370     fn lt(&self, other: &[T; N]) -> bool {
371         PartialOrd::lt(&&self[..], &&other[..])
372     }
373     #[inline]
le(&self, other: &[T; N]) -> bool374     fn le(&self, other: &[T; N]) -> bool {
375         PartialOrd::le(&&self[..], &&other[..])
376     }
377     #[inline]
ge(&self, other: &[T; N]) -> bool378     fn ge(&self, other: &[T; N]) -> bool {
379         PartialOrd::ge(&&self[..], &&other[..])
380     }
381     #[inline]
gt(&self, other: &[T; N]) -> bool382     fn gt(&self, other: &[T; N]) -> bool {
383         PartialOrd::gt(&&self[..], &&other[..])
384     }
385 }
386 
387 /// Implements comparison of arrays [lexicographically](Ord#lexicographical-comparison).
388 #[stable(feature = "rust1", since = "1.0.0")]
389 impl<T: Ord, const N: usize> Ord for [T; N] {
390     #[inline]
cmp(&self, other: &[T; N]) -> Ordering391     fn cmp(&self, other: &[T; N]) -> Ordering {
392         Ord::cmp(&&self[..], &&other[..])
393     }
394 }
395 
396 #[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
397 impl<T: Copy, const N: usize> Copy for [T; N] {}
398 
399 #[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
400 impl<T: Clone, const N: usize> Clone for [T; N] {
401     #[inline]
clone(&self) -> Self402     fn clone(&self) -> Self {
403         SpecArrayClone::clone(self)
404     }
405 
406     #[inline]
clone_from(&mut self, other: &Self)407     fn clone_from(&mut self, other: &Self) {
408         self.clone_from_slice(other);
409     }
410 }
411 
412 trait SpecArrayClone: Clone {
clone<const N: usize>(array: &[Self; N]) -> [Self; N]413     fn clone<const N: usize>(array: &[Self; N]) -> [Self; N];
414 }
415 
416 impl<T: Clone> SpecArrayClone for T {
417     #[inline]
clone<const N: usize>(array: &[T; N]) -> [T; N]418     default fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
419         from_trusted_iterator(array.iter().cloned())
420     }
421 }
422 
423 impl<T: Copy> SpecArrayClone for T {
424     #[inline]
clone<const N: usize>(array: &[T; N]) -> [T; N]425     fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
426         *array
427     }
428 }
429 
430 // The Default impls cannot be done with const generics because `[T; 0]` doesn't
431 // require Default to be implemented, and having different impl blocks for
432 // different numbers isn't supported yet.
433 
434 macro_rules! array_impl_default {
435     {$n:expr, $t:ident $($ts:ident)*} => {
436         #[stable(since = "1.4.0", feature = "array_default")]
437         impl<T> Default for [T; $n] where T: Default {
438             fn default() -> [T; $n] {
439                 [$t::default(), $($ts::default()),*]
440             }
441         }
442         array_impl_default!{($n - 1), $($ts)*}
443     };
444     {$n:expr,} => {
445         #[stable(since = "1.4.0", feature = "array_default")]
446         impl<T> Default for [T; $n] {
447             fn default() -> [T; $n] { [] }
448         }
449     };
450 }
451 
452 array_impl_default! {32, T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T}
453 
454 impl<T, const N: usize> [T; N] {
455     /// Returns an array of the same size as `self`, with function `f` applied to each element
456     /// in order.
457     ///
458     /// If you don't necessarily need a new fixed-size array, consider using
459     /// [`Iterator::map`] instead.
460     ///
461     ///
462     /// # Note on performance and stack usage
463     ///
464     /// Unfortunately, usages of this method are currently not always optimized
465     /// as well as they could be. This mainly concerns large arrays, as mapping
466     /// over small arrays seem to be optimized just fine. Also note that in
467     /// debug mode (i.e. without any optimizations), this method can use a lot
468     /// of stack space (a few times the size of the array or more).
469     ///
470     /// Therefore, in performance-critical code, try to avoid using this method
471     /// on large arrays or check the emitted code. Also try to avoid chained
472     /// maps (e.g. `arr.map(...).map(...)`).
473     ///
474     /// In many cases, you can instead use [`Iterator::map`] by calling `.iter()`
475     /// or `.into_iter()` on your array. `[T; N]::map` is only necessary if you
476     /// really need a new array of the same size as the result. Rust's lazy
477     /// iterators tend to get optimized very well.
478     ///
479     ///
480     /// # Examples
481     ///
482     /// ```
483     /// let x = [1, 2, 3];
484     /// let y = x.map(|v| v + 1);
485     /// assert_eq!(y, [2, 3, 4]);
486     ///
487     /// let x = [1, 2, 3];
488     /// let mut temp = 0;
489     /// let y = x.map(|v| { temp += 1; v * temp });
490     /// assert_eq!(y, [1, 4, 9]);
491     ///
492     /// let x = ["Ferris", "Bueller's", "Day", "Off"];
493     /// let y = x.map(|v| v.len());
494     /// assert_eq!(y, [6, 9, 3, 3]);
495     /// ```
496     #[stable(feature = "array_map", since = "1.55.0")]
map<F, U>(self, f: F) -> [U; N] where F: FnMut(T) -> U,497     pub fn map<F, U>(self, f: F) -> [U; N]
498     where
499         F: FnMut(T) -> U,
500     {
501         self.try_map(NeverShortCircuit::wrap_mut_1(f)).0
502     }
503 
504     /// A fallible function `f` applied to each element on array `self` in order to
505     /// return an array the same size as `self` or the first error encountered.
506     ///
507     /// The return type of this function depends on the return type of the closure.
508     /// If you return `Result<T, E>` from the closure, you'll get a `Result<[T; N], E>`.
509     /// If you return `Option<T>` from the closure, you'll get an `Option<[T; N]>`.
510     ///
511     /// # Examples
512     ///
513     /// ```
514     /// #![feature(array_try_map)]
515     /// let a = ["1", "2", "3"];
516     /// let b = a.try_map(|v| v.parse::<u32>()).unwrap().map(|v| v + 1);
517     /// assert_eq!(b, [2, 3, 4]);
518     ///
519     /// let a = ["1", "2a", "3"];
520     /// let b = a.try_map(|v| v.parse::<u32>());
521     /// assert!(b.is_err());
522     ///
523     /// use std::num::NonZeroU32;
524     /// let z = [1, 2, 0, 3, 4];
525     /// assert_eq!(z.try_map(NonZeroU32::new), None);
526     /// let a = [1, 2, 3];
527     /// let b = a.try_map(NonZeroU32::new);
528     /// let c = b.map(|x| x.map(NonZeroU32::get));
529     /// assert_eq!(c, Some(a));
530     /// ```
531     #[unstable(feature = "array_try_map", issue = "79711")]
try_map<F, R>(self, f: F) -> ChangeOutputType<R, [R::Output; N]> where F: FnMut(T) -> R, R: Try, R::Residual: Residual<[R::Output; N]>,532     pub fn try_map<F, R>(self, f: F) -> ChangeOutputType<R, [R::Output; N]>
533     where
534         F: FnMut(T) -> R,
535         R: Try,
536         R::Residual: Residual<[R::Output; N]>,
537     {
538         drain_array_with(self, |iter| try_from_trusted_iterator(iter.map(f)))
539     }
540 
541     /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
542     #[stable(feature = "array_as_slice", since = "1.57.0")]
543     #[rustc_const_stable(feature = "array_as_slice", since = "1.57.0")]
as_slice(&self) -> &[T]544     pub const fn as_slice(&self) -> &[T] {
545         self
546     }
547 
548     /// Returns a mutable slice containing the entire array. Equivalent to
549     /// `&mut s[..]`.
550     #[stable(feature = "array_as_slice", since = "1.57.0")]
as_mut_slice(&mut self) -> &mut [T]551     pub fn as_mut_slice(&mut self) -> &mut [T] {
552         self
553     }
554 
555     /// Borrows each element and returns an array of references with the same
556     /// size as `self`.
557     ///
558     ///
559     /// # Example
560     ///
561     /// ```
562     /// #![feature(array_methods)]
563     ///
564     /// let floats = [3.1, 2.7, -1.0];
565     /// let float_refs: [&f64; 3] = floats.each_ref();
566     /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
567     /// ```
568     ///
569     /// This method is particularly useful if combined with other methods, like
570     /// [`map`](#method.map). This way, you can avoid moving the original
571     /// array if its elements are not [`Copy`].
572     ///
573     /// ```
574     /// #![feature(array_methods)]
575     ///
576     /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
577     /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
578     /// assert_eq!(is_ascii, [true, false, true]);
579     ///
580     /// // We can still access the original array: it has not been moved.
581     /// assert_eq!(strings.len(), 3);
582     /// ```
583     #[unstable(feature = "array_methods", issue = "76118")]
each_ref(&self) -> [&T; N]584     pub fn each_ref(&self) -> [&T; N] {
585         from_trusted_iterator(self.iter())
586     }
587 
588     /// Borrows each element mutably and returns an array of mutable references
589     /// with the same size as `self`.
590     ///
591     ///
592     /// # Example
593     ///
594     /// ```
595     /// #![feature(array_methods)]
596     ///
597     /// let mut floats = [3.1, 2.7, -1.0];
598     /// let float_refs: [&mut f64; 3] = floats.each_mut();
599     /// *float_refs[0] = 0.0;
600     /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
601     /// assert_eq!(floats, [0.0, 2.7, -1.0]);
602     /// ```
603     #[unstable(feature = "array_methods", issue = "76118")]
each_mut(&mut self) -> [&mut T; N]604     pub fn each_mut(&mut self) -> [&mut T; N] {
605         from_trusted_iterator(self.iter_mut())
606     }
607 
608     /// Divides one array reference into two at an index.
609     ///
610     /// The first will contain all indices from `[0, M)` (excluding
611     /// the index `M` itself) and the second will contain all
612     /// indices from `[M, N)` (excluding the index `N` itself).
613     ///
614     /// # Panics
615     ///
616     /// Panics if `M > N`.
617     ///
618     /// # Examples
619     ///
620     /// ```
621     /// #![feature(split_array)]
622     ///
623     /// let v = [1, 2, 3, 4, 5, 6];
624     ///
625     /// {
626     ///    let (left, right) = v.split_array_ref::<0>();
627     ///    assert_eq!(left, &[]);
628     ///    assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
629     /// }
630     ///
631     /// {
632     ///     let (left, right) = v.split_array_ref::<2>();
633     ///     assert_eq!(left, &[1, 2]);
634     ///     assert_eq!(right, &[3, 4, 5, 6]);
635     /// }
636     ///
637     /// {
638     ///     let (left, right) = v.split_array_ref::<6>();
639     ///     assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
640     ///     assert_eq!(right, &[]);
641     /// }
642     /// ```
643     #[unstable(
644         feature = "split_array",
645         reason = "return type should have array as 2nd element",
646         issue = "90091"
647     )]
648     #[inline]
split_array_ref<const M: usize>(&self) -> (&[T; M], &[T])649     pub fn split_array_ref<const M: usize>(&self) -> (&[T; M], &[T]) {
650         (&self[..]).split_array_ref::<M>()
651     }
652 
653     /// Divides one mutable array reference into two at an index.
654     ///
655     /// The first will contain all indices from `[0, M)` (excluding
656     /// the index `M` itself) and the second will contain all
657     /// indices from `[M, N)` (excluding the index `N` itself).
658     ///
659     /// # Panics
660     ///
661     /// Panics if `M > N`.
662     ///
663     /// # Examples
664     ///
665     /// ```
666     /// #![feature(split_array)]
667     ///
668     /// let mut v = [1, 0, 3, 0, 5, 6];
669     /// let (left, right) = v.split_array_mut::<2>();
670     /// assert_eq!(left, &mut [1, 0][..]);
671     /// assert_eq!(right, &mut [3, 0, 5, 6]);
672     /// left[1] = 2;
673     /// right[1] = 4;
674     /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
675     /// ```
676     #[unstable(
677         feature = "split_array",
678         reason = "return type should have array as 2nd element",
679         issue = "90091"
680     )]
681     #[inline]
split_array_mut<const M: usize>(&mut self) -> (&mut [T; M], &mut [T])682     pub fn split_array_mut<const M: usize>(&mut self) -> (&mut [T; M], &mut [T]) {
683         (&mut self[..]).split_array_mut::<M>()
684     }
685 
686     /// Divides one array reference into two at an index from the end.
687     ///
688     /// The first will contain all indices from `[0, N - M)` (excluding
689     /// the index `N - M` itself) and the second will contain all
690     /// indices from `[N - M, N)` (excluding the index `N` itself).
691     ///
692     /// # Panics
693     ///
694     /// Panics if `M > N`.
695     ///
696     /// # Examples
697     ///
698     /// ```
699     /// #![feature(split_array)]
700     ///
701     /// let v = [1, 2, 3, 4, 5, 6];
702     ///
703     /// {
704     ///    let (left, right) = v.rsplit_array_ref::<0>();
705     ///    assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
706     ///    assert_eq!(right, &[]);
707     /// }
708     ///
709     /// {
710     ///     let (left, right) = v.rsplit_array_ref::<2>();
711     ///     assert_eq!(left, &[1, 2, 3, 4]);
712     ///     assert_eq!(right, &[5, 6]);
713     /// }
714     ///
715     /// {
716     ///     let (left, right) = v.rsplit_array_ref::<6>();
717     ///     assert_eq!(left, &[]);
718     ///     assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
719     /// }
720     /// ```
721     #[unstable(
722         feature = "split_array",
723         reason = "return type should have array as 2nd element",
724         issue = "90091"
725     )]
726     #[inline]
rsplit_array_ref<const M: usize>(&self) -> (&[T], &[T; M])727     pub fn rsplit_array_ref<const M: usize>(&self) -> (&[T], &[T; M]) {
728         (&self[..]).rsplit_array_ref::<M>()
729     }
730 
731     /// Divides one mutable array reference into two at an index from the end.
732     ///
733     /// The first will contain all indices from `[0, N - M)` (excluding
734     /// the index `N - M` itself) and the second will contain all
735     /// indices from `[N - M, N)` (excluding the index `N` itself).
736     ///
737     /// # Panics
738     ///
739     /// Panics if `M > N`.
740     ///
741     /// # Examples
742     ///
743     /// ```
744     /// #![feature(split_array)]
745     ///
746     /// let mut v = [1, 0, 3, 0, 5, 6];
747     /// let (left, right) = v.rsplit_array_mut::<4>();
748     /// assert_eq!(left, &mut [1, 0]);
749     /// assert_eq!(right, &mut [3, 0, 5, 6][..]);
750     /// left[1] = 2;
751     /// right[1] = 4;
752     /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
753     /// ```
754     #[unstable(
755         feature = "split_array",
756         reason = "return type should have array as 2nd element",
757         issue = "90091"
758     )]
759     #[inline]
rsplit_array_mut<const M: usize>(&mut self) -> (&mut [T], &mut [T; M])760     pub fn rsplit_array_mut<const M: usize>(&mut self) -> (&mut [T], &mut [T; M]) {
761         (&mut self[..]).rsplit_array_mut::<M>()
762     }
763 }
764 
765 /// Populate an array from the first `N` elements of `iter`
766 ///
767 /// # Panics
768 ///
769 /// If the iterator doesn't actually have enough items.
770 ///
771 /// By depending on `TrustedLen`, however, we can do that check up-front (where
772 /// it easily optimizes away) so it doesn't impact the loop that fills the array.
773 #[inline]
from_trusted_iterator<T, const N: usize>(iter: impl UncheckedIterator<Item = T>) -> [T; N]774 fn from_trusted_iterator<T, const N: usize>(iter: impl UncheckedIterator<Item = T>) -> [T; N] {
775     try_from_trusted_iterator(iter.map(NeverShortCircuit)).0
776 }
777 
778 #[inline]
try_from_trusted_iterator<T, R, const N: usize>( iter: impl UncheckedIterator<Item = R>, ) -> ChangeOutputType<R, [T; N]> where R: Try<Output = T>, R::Residual: Residual<[T; N]>,779 fn try_from_trusted_iterator<T, R, const N: usize>(
780     iter: impl UncheckedIterator<Item = R>,
781 ) -> ChangeOutputType<R, [T; N]>
782 where
783     R: Try<Output = T>,
784     R::Residual: Residual<[T; N]>,
785 {
786     assert!(iter.size_hint().0 >= N);
next<T>(mut iter: impl UncheckedIterator<Item = T>) -> impl FnMut(usize) -> T787     fn next<T>(mut iter: impl UncheckedIterator<Item = T>) -> impl FnMut(usize) -> T {
788         move |_| {
789             // SAFETY: We know that `from_fn` will call this at most N times,
790             // and we checked to ensure that we have at least that many items.
791             unsafe { iter.next_unchecked() }
792         }
793     }
794 
795     try_from_fn(next(iter))
796 }
797 
798 /// Version of [`try_from_fn`] using a passed-in slice in order to avoid
799 /// needing to monomorphize for every array length.
800 ///
801 /// This takes a generator rather than an iterator so that *at the type level*
802 /// it never needs to worry about running out of items.  When combined with
803 /// an infallible `Try` type, that means the loop canonicalizes easily, allowing
804 /// it to optimize well.
805 ///
806 /// It would be *possible* to unify this and [`iter_next_chunk_erased`] into one
807 /// function that does the union of both things, but last time it was that way
808 /// it resulted in poor codegen from the "are there enough source items?" checks
809 /// not optimizing away.  So if you give it a shot, make sure to watch what
810 /// happens in the codegen tests.
811 #[inline]
try_from_fn_erased<T, R>( buffer: &mut [MaybeUninit<T>], mut generator: impl FnMut(usize) -> R, ) -> ControlFlow<R::Residual> where R: Try<Output = T>,812 fn try_from_fn_erased<T, R>(
813     buffer: &mut [MaybeUninit<T>],
814     mut generator: impl FnMut(usize) -> R,
815 ) -> ControlFlow<R::Residual>
816 where
817     R: Try<Output = T>,
818 {
819     let mut guard = Guard { array_mut: buffer, initialized: 0 };
820 
821     while guard.initialized < guard.array_mut.len() {
822         let item = generator(guard.initialized).branch()?;
823 
824         // SAFETY: The loop condition ensures we have space to push the item
825         unsafe { guard.push_unchecked(item) };
826     }
827 
828     mem::forget(guard);
829     ControlFlow::Continue(())
830 }
831 
832 /// Panic guard for incremental initialization of arrays.
833 ///
834 /// Disarm the guard with `mem::forget` once the array has been initialized.
835 ///
836 /// # Safety
837 ///
838 /// All write accesses to this structure are unsafe and must maintain a correct
839 /// count of `initialized` elements.
840 ///
841 /// To minimize indirection fields are still pub but callers should at least use
842 /// `push_unchecked` to signal that something unsafe is going on.
843 struct Guard<'a, T> {
844     /// The array to be initialized.
845     pub array_mut: &'a mut [MaybeUninit<T>],
846     /// The number of items that have been initialized so far.
847     pub initialized: usize,
848 }
849 
850 impl<T> Guard<'_, T> {
851     /// Adds an item to the array and updates the initialized item counter.
852     ///
853     /// # Safety
854     ///
855     /// No more than N elements must be initialized.
856     #[inline]
push_unchecked(&mut self, item: T)857     pub unsafe fn push_unchecked(&mut self, item: T) {
858         // SAFETY: If `initialized` was correct before and the caller does not
859         // invoke this method more than N times then writes will be in-bounds
860         // and slots will not be initialized more than once.
861         unsafe {
862             self.array_mut.get_unchecked_mut(self.initialized).write(item);
863             self.initialized = self.initialized.unchecked_add(1);
864         }
865     }
866 }
867 
868 impl<T> Drop for Guard<'_, T> {
drop(&mut self)869     fn drop(&mut self) {
870         debug_assert!(self.initialized <= self.array_mut.len());
871 
872         // SAFETY: this slice will contain only initialized objects.
873         unsafe {
874             crate::ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(
875                 self.array_mut.get_unchecked_mut(..self.initialized),
876             ));
877         }
878     }
879 }
880 
881 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
882 /// yields fewer than `N` items, `Err` is returned containing an iterator over
883 /// the already yielded items.
884 ///
885 /// Since the iterator is passed as a mutable reference and this function calls
886 /// `next` at most `N` times, the iterator can still be used afterwards to
887 /// retrieve the remaining items.
888 ///
889 /// If `iter.next()` panicks, all items already yielded by the iterator are
890 /// dropped.
891 ///
892 /// Used for [`Iterator::next_chunk`].
893 #[inline]
iter_next_chunk<T, const N: usize>( iter: &mut impl Iterator<Item = T>, ) -> Result<[T; N], IntoIter<T, N>>894 pub(crate) fn iter_next_chunk<T, const N: usize>(
895     iter: &mut impl Iterator<Item = T>,
896 ) -> Result<[T; N], IntoIter<T, N>> {
897     let mut array = MaybeUninit::uninit_array::<N>();
898     let r = iter_next_chunk_erased(&mut array, iter);
899     match r {
900         Ok(()) => {
901             // SAFETY: All elements of `array` were populated.
902             Ok(unsafe { MaybeUninit::array_assume_init(array) })
903         }
904         Err(initialized) => {
905             // SAFETY: Only the first `initialized` elements were populated
906             Err(unsafe { IntoIter::new_unchecked(array, 0..initialized) })
907         }
908     }
909 }
910 
911 /// Version of [`iter_next_chunk`] using a passed-in slice in order to avoid
912 /// needing to monomorphize for every array length.
913 ///
914 /// Unfortunately this loop has two exit conditions, the buffer filling up
915 /// or the iterator running out of items, making it tend to optimize poorly.
916 #[inline]
iter_next_chunk_erased<T>( buffer: &mut [MaybeUninit<T>], iter: &mut impl Iterator<Item = T>, ) -> Result<(), usize>917 fn iter_next_chunk_erased<T>(
918     buffer: &mut [MaybeUninit<T>],
919     iter: &mut impl Iterator<Item = T>,
920 ) -> Result<(), usize> {
921     let mut guard = Guard { array_mut: buffer, initialized: 0 };
922     while guard.initialized < guard.array_mut.len() {
923         let Some(item) = iter.next() else {
924             // Unlike `try_from_fn_erased`, we want to keep the partial results,
925             // so we need to defuse the guard instead of using `?`.
926             let initialized = guard.initialized;
927             mem::forget(guard);
928             return Err(initialized)
929         };
930 
931         // SAFETY: The loop condition ensures we have space to push the item
932         unsafe { guard.push_unchecked(item) };
933     }
934 
935     mem::forget(guard);
936     Ok(())
937 }
938