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