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