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};
9use crate::clone::TrivialClone;
10#[cfg(not(feature = "ferrocene_certified"))]
11use crate::cmp::Ordering;
12#[cfg(not(feature = "ferrocene_certified"))]
13use crate::convert::Infallible;
14#[cfg(not(feature = "ferrocene_certified"))]
15use crate::error::Error;
16#[cfg(not(feature = "ferrocene_certified"))]
17use crate::fmt;
18#[cfg(not(feature = "ferrocene_certified"))]
19use crate::hash::{self, Hash};
20#[cfg(not(feature = "ferrocene_certified"))]
21use crate::intrinsics::transmute_unchecked;
22#[cfg(not(feature = "ferrocene_certified"))]
23use crate::iter::{UncheckedIterator, repeat_n};
24use crate::mem::{self, MaybeUninit};
25use crate::ops::{
26    ChangeOutputType, ControlFlow, FromResidual, Index, IndexMut, NeverShortCircuit, Residual, Try,
27};
28use crate::ptr;
29#[cfg(not(feature = "ferrocene_certified"))]
30use crate::ptr::{null, null_mut};
31use crate::slice::{Iter, IterMut};
32
33// Ferrocene addition: imports for certified subset
34#[cfg(feature = "ferrocene_certified")]
35#[rustfmt::skip]
36use crate::iter::UncheckedIterator;
37
38#[cfg(not(feature = "ferrocene_certified"))]
39mod ascii;
40mod drain;
41mod equality;
42mod iter;
43
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
484#[doc(hidden)]
485#[unstable(feature = "trivial_clone", issue = "none")]
486unsafe impl<T: TrivialClone, const N: usize> TrivialClone for [T; N] {}
487
488trait SpecArrayClone: Clone {
489    fn clone<const N: usize>(array: &[Self; N]) -> [Self; N];
490}
491
492impl<T: Clone> SpecArrayClone for T {
493    #[inline]
494    default fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
495        from_trusted_iterator(array.iter().cloned())
496    }
497}
498
499impl<T: TrivialClone> SpecArrayClone for T {
500    #[inline]
501    fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
502        // SAFETY: `TrivialClone` implies that this is equivalent to calling
503        // `Clone` on every element.
504        unsafe { ptr::read(array) }
505    }
506}
507
508// The Default impls cannot be done with const generics because `[T; 0]` doesn't
509// require Default to be implemented, and having different impl blocks for
510// different numbers isn't supported yet.
511//
512// Trying to improve the `[T; 0]` situation has proven to be difficult.
513// Please see these issues for more context on past attempts and crater runs:
514// - https://github.com/rust-lang/rust/issues/61415
515// - https://github.com/rust-lang/rust/pull/145457
516
517#[cfg(not(feature = "ferrocene_certified"))]
518macro_rules! array_impl_default {
519    {$n:expr, $t:ident $($ts:ident)*} => {
520        #[stable(since = "1.4.0", feature = "array_default")]
521        impl<T> Default for [T; $n] where T: Default {
522            fn default() -> [T; $n] {
523                [$t::default(), $($ts::default()),*]
524            }
525        }
526        array_impl_default!{($n - 1), $($ts)*}
527    };
528    {$n:expr,} => {
529        #[stable(since = "1.4.0", feature = "array_default")]
530        impl<T> Default for [T; $n] {
531            fn default() -> [T; $n] { [] }
532        }
533    };
534}
535
536#[cfg(not(feature = "ferrocene_certified"))]
537array_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}
538
539impl<T, const N: usize> [T; N] {
540    /// Returns an array of the same size as `self`, with function `f` applied to each element
541    /// in order.
542    ///
543    /// If you don't necessarily need a new fixed-size array, consider using
544    /// [`Iterator::map`] instead.
545    ///
546    ///
547    /// # Note on performance and stack usage
548    ///
549    /// Unfortunately, usages of this method are currently not always optimized
550    /// as well as they could be. This mainly concerns large arrays, as mapping
551    /// over small arrays seem to be optimized just fine. Also note that in
552    /// debug mode (i.e. without any optimizations), this method can use a lot
553    /// of stack space (a few times the size of the array or more).
554    ///
555    /// Therefore, in performance-critical code, try to avoid using this method
556    /// on large arrays or check the emitted code. Also try to avoid chained
557    /// maps (e.g. `arr.map(...).map(...)`).
558    ///
559    /// In many cases, you can instead use [`Iterator::map`] by calling `.iter()`
560    /// or `.into_iter()` on your array. `[T; N]::map` is only necessary if you
561    /// really need a new array of the same size as the result. Rust's lazy
562    /// iterators tend to get optimized very well.
563    ///
564    ///
565    /// # Examples
566    ///
567    /// ```
568    /// let x = [1, 2, 3];
569    /// let y = x.map(|v| v + 1);
570    /// assert_eq!(y, [2, 3, 4]);
571    ///
572    /// let x = [1, 2, 3];
573    /// let mut temp = 0;
574    /// let y = x.map(|v| { temp += 1; v * temp });
575    /// assert_eq!(y, [1, 4, 9]);
576    ///
577    /// let x = ["Ferris", "Bueller's", "Day", "Off"];
578    /// let y = x.map(|v| v.len());
579    /// assert_eq!(y, [6, 9, 3, 3]);
580    /// ```
581    #[must_use]
582    #[stable(feature = "array_map", since = "1.55.0")]
583    pub fn map<F, U>(self, f: F) -> [U; N]
584    where
585        F: FnMut(T) -> U,
586    {
587        self.try_map(NeverShortCircuit::wrap_mut_1(f)).0
588    }
589
590    /// A fallible function `f` applied to each element on array `self` in order to
591    /// return an array the same size as `self` or the first error encountered.
592    ///
593    /// The return type of this function depends on the return type of the closure.
594    /// If you return `Result<T, E>` from the closure, you'll get a `Result<[T; N], E>`.
595    /// If you return `Option<T>` from the closure, you'll get an `Option<[T; N]>`.
596    ///
597    /// # Examples
598    ///
599    /// ```
600    /// #![feature(array_try_map)]
601    ///
602    /// let a = ["1", "2", "3"];
603    /// let b = a.try_map(|v| v.parse::<u32>()).unwrap().map(|v| v + 1);
604    /// assert_eq!(b, [2, 3, 4]);
605    ///
606    /// let a = ["1", "2a", "3"];
607    /// let b = a.try_map(|v| v.parse::<u32>());
608    /// assert!(b.is_err());
609    ///
610    /// use std::num::NonZero;
611    ///
612    /// let z = [1, 2, 0, 3, 4];
613    /// assert_eq!(z.try_map(NonZero::new), None);
614    ///
615    /// let a = [1, 2, 3];
616    /// let b = a.try_map(NonZero::new);
617    /// let c = b.map(|x| x.map(NonZero::get));
618    /// assert_eq!(c, Some(a));
619    /// ```
620    #[unstable(feature = "array_try_map", issue = "79711")]
621    pub fn try_map<R>(self, f: impl FnMut(T) -> R) -> ChangeOutputType<R, [R::Output; N]>
622    where
623        R: Try<Residual: Residual<[R::Output; N]>>,
624    {
625        drain_array_with(self, |iter| try_from_trusted_iterator(iter.map(f)))
626    }
627
628    /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
629    #[stable(feature = "array_as_slice", since = "1.57.0")]
630    #[rustc_const_stable(feature = "array_as_slice", since = "1.57.0")]
631    pub const fn as_slice(&self) -> &[T] {
632        self
633    }
634
635    /// Returns a mutable slice containing the entire array. Equivalent to
636    /// `&mut s[..]`.
637    #[stable(feature = "array_as_slice", since = "1.57.0")]
638    #[rustc_const_stable(feature = "const_array_as_mut_slice", since = "1.89.0")]
639    pub const fn as_mut_slice(&mut self) -> &mut [T] {
640        self
641    }
642
643    /// Borrows each element and returns an array of references with the same
644    /// size as `self`.
645    ///
646    ///
647    /// # Example
648    ///
649    /// ```
650    /// let floats = [3.1, 2.7, -1.0];
651    /// let float_refs: [&f64; 3] = floats.each_ref();
652    /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
653    /// ```
654    ///
655    /// This method is particularly useful if combined with other methods, like
656    /// [`map`](#method.map). This way, you can avoid moving the original
657    /// array if its elements are not [`Copy`].
658    ///
659    /// ```
660    /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
661    /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
662    /// assert_eq!(is_ascii, [true, false, true]);
663    ///
664    /// // We can still access the original array: it has not been moved.
665    /// assert_eq!(strings.len(), 3);
666    /// ```
667    #[stable(feature = "array_methods", since = "1.77.0")]
668    #[rustc_const_stable(feature = "const_array_each_ref", since = "1.91.0")]
669    #[cfg(not(feature = "ferrocene_certified"))]
670    pub const fn each_ref(&self) -> [&T; N] {
671        let mut buf = [null::<T>(); N];
672
673        // 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.
674        let mut i = 0;
675        while i < N {
676            buf[i] = &raw const self[i];
677
678            i += 1;
679        }
680
681        // SAFETY: `*const T` has the same layout as `&T`, and we've also initialised each pointer as a valid reference.
682        unsafe { transmute_unchecked(buf) }
683    }
684
685    /// Borrows each element mutably and returns an array of mutable references
686    /// with the same size as `self`.
687    ///
688    ///
689    /// # Example
690    ///
691    /// ```
692    ///
693    /// let mut floats = [3.1, 2.7, -1.0];
694    /// let float_refs: [&mut f64; 3] = floats.each_mut();
695    /// *float_refs[0] = 0.0;
696    /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
697    /// assert_eq!(floats, [0.0, 2.7, -1.0]);
698    /// ```
699    #[stable(feature = "array_methods", since = "1.77.0")]
700    #[rustc_const_stable(feature = "const_array_each_ref", since = "1.91.0")]
701    #[cfg(not(feature = "ferrocene_certified"))]
702    pub const fn each_mut(&mut self) -> [&mut T; N] {
703        let mut buf = [null_mut::<T>(); N];
704
705        // 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.
706        let mut i = 0;
707        while i < N {
708            buf[i] = &raw mut self[i];
709
710            i += 1;
711        }
712
713        // SAFETY: `*mut T` has the same layout as `&mut T`, and we've also initialised each pointer as a valid reference.
714        unsafe { transmute_unchecked(buf) }
715    }
716
717    /// Divides one array reference into two at an index.
718    ///
719    /// The first will contain all indices from `[0, M)` (excluding
720    /// the index `M` itself) and the second will contain all
721    /// indices from `[M, N)` (excluding the index `N` itself).
722    ///
723    /// # Panics
724    ///
725    /// Panics if `M > N`.
726    ///
727    /// # Examples
728    ///
729    /// ```
730    /// #![feature(split_array)]
731    ///
732    /// let v = [1, 2, 3, 4, 5, 6];
733    ///
734    /// {
735    ///    let (left, right) = v.split_array_ref::<0>();
736    ///    assert_eq!(left, &[]);
737    ///    assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
738    /// }
739    ///
740    /// {
741    ///     let (left, right) = v.split_array_ref::<2>();
742    ///     assert_eq!(left, &[1, 2]);
743    ///     assert_eq!(right, &[3, 4, 5, 6]);
744    /// }
745    ///
746    /// {
747    ///     let (left, right) = v.split_array_ref::<6>();
748    ///     assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
749    ///     assert_eq!(right, &[]);
750    /// }
751    /// ```
752    #[unstable(
753        feature = "split_array",
754        reason = "return type should have array as 2nd element",
755        issue = "90091"
756    )]
757    #[inline]
758    #[cfg(not(feature = "ferrocene_certified"))]
759    pub fn split_array_ref<const M: usize>(&self) -> (&[T; M], &[T]) {
760        self.split_first_chunk::<M>().unwrap()
761    }
762
763    /// Divides one mutable array reference into two at an index.
764    ///
765    /// The first will contain all indices from `[0, M)` (excluding
766    /// the index `M` itself) and the second will contain all
767    /// indices from `[M, N)` (excluding the index `N` itself).
768    ///
769    /// # Panics
770    ///
771    /// Panics if `M > N`.
772    ///
773    /// # Examples
774    ///
775    /// ```
776    /// #![feature(split_array)]
777    ///
778    /// let mut v = [1, 0, 3, 0, 5, 6];
779    /// let (left, right) = v.split_array_mut::<2>();
780    /// assert_eq!(left, &mut [1, 0][..]);
781    /// assert_eq!(right, &mut [3, 0, 5, 6]);
782    /// left[1] = 2;
783    /// right[1] = 4;
784    /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
785    /// ```
786    #[unstable(
787        feature = "split_array",
788        reason = "return type should have array as 2nd element",
789        issue = "90091"
790    )]
791    #[inline]
792    #[cfg(not(feature = "ferrocene_certified"))]
793    pub fn split_array_mut<const M: usize>(&mut self) -> (&mut [T; M], &mut [T]) {
794        self.split_first_chunk_mut::<M>().unwrap()
795    }
796
797    /// Divides one array reference into two at an index from the end.
798    ///
799    /// The first will contain all indices from `[0, N - M)` (excluding
800    /// the index `N - M` itself) and the second will contain all
801    /// indices from `[N - M, N)` (excluding the index `N` itself).
802    ///
803    /// # Panics
804    ///
805    /// Panics if `M > N`.
806    ///
807    /// # Examples
808    ///
809    /// ```
810    /// #![feature(split_array)]
811    ///
812    /// let v = [1, 2, 3, 4, 5, 6];
813    ///
814    /// {
815    ///    let (left, right) = v.rsplit_array_ref::<0>();
816    ///    assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
817    ///    assert_eq!(right, &[]);
818    /// }
819    ///
820    /// {
821    ///     let (left, right) = v.rsplit_array_ref::<2>();
822    ///     assert_eq!(left, &[1, 2, 3, 4]);
823    ///     assert_eq!(right, &[5, 6]);
824    /// }
825    ///
826    /// {
827    ///     let (left, right) = v.rsplit_array_ref::<6>();
828    ///     assert_eq!(left, &[]);
829    ///     assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
830    /// }
831    /// ```
832    #[unstable(
833        feature = "split_array",
834        reason = "return type should have array as 2nd element",
835        issue = "90091"
836    )]
837    #[inline]
838    #[cfg(not(feature = "ferrocene_certified"))]
839    pub fn rsplit_array_ref<const M: usize>(&self) -> (&[T], &[T; M]) {
840        self.split_last_chunk::<M>().unwrap()
841    }
842
843    /// Divides one mutable array reference into two at an index from the end.
844    ///
845    /// The first will contain all indices from `[0, N - M)` (excluding
846    /// the index `N - M` itself) and the second will contain all
847    /// indices from `[N - M, N)` (excluding the index `N` itself).
848    ///
849    /// # Panics
850    ///
851    /// Panics if `M > N`.
852    ///
853    /// # Examples
854    ///
855    /// ```
856    /// #![feature(split_array)]
857    ///
858    /// let mut v = [1, 0, 3, 0, 5, 6];
859    /// let (left, right) = v.rsplit_array_mut::<4>();
860    /// assert_eq!(left, &mut [1, 0]);
861    /// assert_eq!(right, &mut [3, 0, 5, 6][..]);
862    /// left[1] = 2;
863    /// right[1] = 4;
864    /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
865    /// ```
866    #[unstable(
867        feature = "split_array",
868        reason = "return type should have array as 2nd element",
869        issue = "90091"
870    )]
871    #[inline]
872    #[cfg(not(feature = "ferrocene_certified"))]
873    pub fn rsplit_array_mut<const M: usize>(&mut self) -> (&mut [T], &mut [T; M]) {
874        self.split_last_chunk_mut::<M>().unwrap()
875    }
876}
877
878/// Populate an array from the first `N` elements of `iter`
879///
880/// # Panics
881///
882/// If the iterator doesn't actually have enough items.
883///
884/// By depending on `TrustedLen`, however, we can do that check up-front (where
885/// it easily optimizes away) so it doesn't impact the loop that fills the array.
886#[inline]
887fn from_trusted_iterator<T, const N: usize>(iter: impl UncheckedIterator<Item = T>) -> [T; N] {
888    try_from_trusted_iterator(iter.map(NeverShortCircuit)).0
889}
890
891#[inline]
892fn try_from_trusted_iterator<T, R, const N: usize>(
893    iter: impl UncheckedIterator<Item = R>,
894) -> ChangeOutputType<R, [T; N]>
895where
896    R: Try<Output = T>,
897    R::Residual: Residual<[T; N]>,
898{
899    assert!(iter.size_hint().0 >= N);
900    fn next<T>(mut iter: impl UncheckedIterator<Item = T>) -> impl FnMut(usize) -> T {
901        move |_| {
902            // SAFETY: We know that `from_fn` will call this at most N times,
903            // and we checked to ensure that we have at least that many items.
904            unsafe { iter.next_unchecked() }
905        }
906    }
907
908    try_from_fn(next(iter))
909}
910
911/// Version of [`try_from_fn`] using a passed-in slice in order to avoid
912/// needing to monomorphize for every array length.
913///
914/// This takes a generator rather than an iterator so that *at the type level*
915/// it never needs to worry about running out of items.  When combined with
916/// an infallible `Try` type, that means the loop canonicalizes easily, allowing
917/// it to optimize well.
918///
919/// It would be *possible* to unify this and [`iter_next_chunk_erased`] into one
920/// function that does the union of both things, but last time it was that way
921/// it resulted in poor codegen from the "are there enough source items?" checks
922/// not optimizing away.  So if you give it a shot, make sure to watch what
923/// happens in the codegen tests.
924#[inline]
925fn try_from_fn_erased<T, R>(
926    buffer: &mut [MaybeUninit<T>],
927    mut generator: impl FnMut(usize) -> R,
928) -> ControlFlow<R::Residual>
929where
930    R: Try<Output = T>,
931{
932    let mut guard = Guard { array_mut: buffer, initialized: 0 };
933
934    while guard.initialized < guard.array_mut.len() {
935        let item = generator(guard.initialized).branch()?;
936
937        // SAFETY: The loop condition ensures we have space to push the item
938        unsafe { guard.push_unchecked(item) };
939    }
940
941    mem::forget(guard);
942    ControlFlow::Continue(())
943}
944
945/// Panic guard for incremental initialization of arrays.
946///
947/// Disarm the guard with `mem::forget` once the array has been initialized.
948///
949/// # Safety
950///
951/// All write accesses to this structure are unsafe and must maintain a correct
952/// count of `initialized` elements.
953///
954/// To minimize indirection fields are still pub but callers should at least use
955/// `push_unchecked` to signal that something unsafe is going on.
956struct Guard<'a, T> {
957    /// The array to be initialized.
958    pub array_mut: &'a mut [MaybeUninit<T>],
959    /// The number of items that have been initialized so far.
960    pub initialized: usize,
961}
962
963impl<T> Guard<'_, T> {
964    /// Adds an item to the array and updates the initialized item counter.
965    ///
966    /// # Safety
967    ///
968    /// No more than N elements must be initialized.
969    #[inline]
970    pub(crate) unsafe fn push_unchecked(&mut self, item: T) {
971        // SAFETY: If `initialized` was correct before and the caller does not
972        // invoke this method more than N times then writes will be in-bounds
973        // and slots will not be initialized more than once.
974        unsafe {
975            self.array_mut.get_unchecked_mut(self.initialized).write(item);
976            self.initialized = self.initialized.unchecked_add(1);
977        }
978    }
979}
980
981impl<T> Drop for Guard<'_, T> {
982    #[inline]
983    fn drop(&mut self) {
984        debug_assert!(self.initialized <= self.array_mut.len());
985
986        // SAFETY: this slice will contain only initialized objects.
987        unsafe {
988            self.array_mut.get_unchecked_mut(..self.initialized).assume_init_drop();
989        }
990    }
991}
992
993/// Pulls `N` items from `iter` and returns them as an array. If the iterator
994/// yields fewer than `N` items, `Err` is returned containing an iterator over
995/// the already yielded items.
996///
997/// Since the iterator is passed as a mutable reference and this function calls
998/// `next` at most `N` times, the iterator can still be used afterwards to
999/// retrieve the remaining items.
1000///
1001/// If `iter.next()` panicks, all items already yielded by the iterator are
1002/// dropped.
1003///
1004/// Used for [`Iterator::next_chunk`].
1005#[inline]
1006#[cfg(not(feature = "ferrocene_certified"))]
1007pub(crate) fn iter_next_chunk<T, const N: usize>(
1008    iter: &mut impl Iterator<Item = T>,
1009) -> Result<[T; N], IntoIter<T, N>> {
1010    let mut array = [const { MaybeUninit::uninit() }; N];
1011    let r = iter_next_chunk_erased(&mut array, iter);
1012    match r {
1013        Ok(()) => {
1014            // SAFETY: All elements of `array` were populated.
1015            Ok(unsafe { MaybeUninit::array_assume_init(array) })
1016        }
1017        Err(initialized) => {
1018            // SAFETY: Only the first `initialized` elements were populated
1019            Err(unsafe { IntoIter::new_unchecked(array, 0..initialized) })
1020        }
1021    }
1022}
1023
1024/// Version of [`iter_next_chunk`] using a passed-in slice in order to avoid
1025/// needing to monomorphize for every array length.
1026///
1027/// Unfortunately this loop has two exit conditions, the buffer filling up
1028/// or the iterator running out of items, making it tend to optimize poorly.
1029#[inline]
1030#[cfg(not(feature = "ferrocene_certified"))]
1031fn iter_next_chunk_erased<T>(
1032    buffer: &mut [MaybeUninit<T>],
1033    iter: &mut impl Iterator<Item = T>,
1034) -> Result<(), usize> {
1035    let mut guard = Guard { array_mut: buffer, initialized: 0 };
1036    while guard.initialized < guard.array_mut.len() {
1037        let Some(item) = iter.next() else {
1038            // Unlike `try_from_fn_erased`, we want to keep the partial results,
1039            // so we need to defuse the guard instead of using `?`.
1040            let initialized = guard.initialized;
1041            mem::forget(guard);
1042            return Err(initialized);
1043        };
1044
1045        // SAFETY: The loop condition ensures we have space to push the item
1046        unsafe { guard.push_unchecked(item) };
1047    }
1048
1049    mem::forget(guard);
1050    Ok(())
1051}