core/array/
mod.rs

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