Skip to main content

core/array/
mod.rs

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