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