Thanks to visit codestin.com
Credit goes to doc.rust-lang.org

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