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

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