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::error::Error;
11use crate::hash::{self, Hash};
12use crate::intrinsics::transmute_unchecked;
13use crate::iter::{TrustedLen, repeat_n};
14use crate::marker::Destruct;
15use crate::mem::{self, ManuallyDrop, MaybeUninit};
16use crate::ops::{
17    ChangeOutputType, ControlFlow, FromResidual, Index, IndexMut, NeverShortCircuit, Residual, Try,
18};
19use crate::ptr::{null, null_mut};
20use crate::slice::{Iter, IterMut};
21use crate::{fmt, ptr};
22
23mod ascii;
24mod drain;
25mod equality;
26mod iter;
27
28#[stable(feature = "array_value_iter", since = "1.51.0")]
29pub use iter::IntoIter;
30
31/// Creates an array of type `[T; N]` by repeatedly cloning a value.
32///
33/// This is the same as `[val; N]`, but it also works for types that do not
34/// implement [`Copy`].
35///
36/// The provided value will be used as an element of the resulting array and
37/// will be cloned N - 1 times to fill up the rest. If N is zero, the value
38/// will be dropped.
39///
40/// # Example
41///
42/// Creating multiple copies of a `String`:
43/// ```rust
44/// use std::array;
45///
46/// let string = "Hello there!".to_string();
47/// let strings = array::repeat(string);
48/// assert_eq!(strings, ["Hello there!", "Hello there!"]);
49/// ```
50#[inline]
51#[must_use = "cloning is often expensive and is not expected to have side effects"]
52#[stable(feature = "array_repeat", since = "1.91.0")]
53pub fn repeat<T: Clone, const N: usize>(val: T) -> [T; N] {
54    let mut iter = repeat_n(val, N);
55    // SAFETY: Unless a panic occurs, from_fn will call the closure N times,
56    // and repeat_n's next() will return Some for N times.
57    from_fn(move |_| unsafe { iter.next().unwrap_unchecked() })
58}
59
60/// Creates an array where each element is produced by calling `f` with
61/// that element's index while walking forward through the array.
62///
63/// This is essentially the same as writing
64/// ```text
65/// [f(0), f(1), f(2), …, f(N - 2), f(N - 1)]
66/// ```
67/// and is similar to `(0..i).map(f)`, just for arrays not iterators.
68///
69/// If `N == 0`, this produces an empty array without ever calling `f`.
70///
71/// # Example
72///
73/// ```rust
74/// // type inference is helping us here, the way `from_fn` knows how many
75/// // elements to produce is the length of array down there: only arrays of
76/// // equal lengths can be compared, so the const generic parameter `N` is
77/// // inferred to be 5, thus creating array of 5 elements.
78///
79/// let array = core::array::from_fn(|i| i);
80/// // indexes are:    0  1  2  3  4
81/// assert_eq!(array, [0, 1, 2, 3, 4]);
82///
83/// let array2: [usize; 8] = core::array::from_fn(|i| i * 2);
84/// // indexes are:     0  1  2  3  4  5   6   7
85/// assert_eq!(array2, [0, 2, 4, 6, 8, 10, 12, 14]);
86///
87/// let bool_arr = core::array::from_fn::<_, 5, _>(|i| i % 2 == 0);
88/// // indexes are:       0     1      2     3      4
89/// assert_eq!(bool_arr, [true, false, true, false, true]);
90/// ```
91///
92/// You can also capture things, for example to create an array full of clones
93/// where you can't just use `[item; N]` because it's not `Copy`:
94/// ```
95/// let my_string: [String; 2] = std::array::from_fn(|i| format!("Hello {i}"));
96/// assert_eq!(my_string, ["Hello 0", "Hello 1"]);
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")]
109#[ferrocene::prevalidated]
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")]
149#[ferrocene::prevalidated]
150pub const fn try_from_fn<R, const N: usize, F>(cb: F) -> ChangeOutputType<R, [R::Output; N]>
151where
152    R: [const] Try<Residual: [const] Residual<[R::Output; N]>, Output: [const] Destruct>,
153    F: [const] FnMut(usize) -> R + [const] Destruct,
154{
155    let mut array = [const { MaybeUninit::uninit() }; N];
156    match try_from_fn_erased(&mut array, cb) {
157        ControlFlow::Break(r) => FromResidual::from_residual(r),
158        ControlFlow::Continue(()) => {
159            // SAFETY: All elements of the array were populated.
160            try { unsafe { MaybeUninit::array_assume_init(array) } }
161        }
162    }
163}
164
165/// Converts a reference to `T` into a reference to an array of length 1 (without copying).
166#[stable(feature = "array_from_ref", since = "1.53.0")]
167#[rustc_const_stable(feature = "const_array_from_ref_shared", since = "1.63.0")]
168#[ferrocene::prevalidated]
169pub const fn from_ref<T>(s: &T) -> &[T; 1] {
170    // SAFETY: Converting `&T` to `&[T; 1]` is sound.
171    unsafe { &*(s as *const T).cast::<[T; 1]>() }
172}
173
174/// Converts a mutable reference to `T` into a mutable reference to an array of length 1 (without copying).
175#[stable(feature = "array_from_ref", since = "1.53.0")]
176#[rustc_const_stable(feature = "const_array_from_ref", since = "1.83.0")]
177#[ferrocene::prevalidated]
178pub const fn from_mut<T>(s: &mut T) -> &mut [T; 1] {
179    // SAFETY: Converting `&mut T` to `&mut [T; 1]` is sound.
180    unsafe { &mut *(s as *mut T).cast::<[T; 1]>() }
181}
182
183/// The error type returned when a conversion from a slice to an array fails.
184#[stable(feature = "try_from", since = "1.34.0")]
185#[derive(Debug, Copy, Clone)]
186#[ferrocene::prevalidated]
187pub struct TryFromSliceError(());
188
189#[stable(feature = "core_array", since = "1.35.0")]
190impl fmt::Display for TryFromSliceError {
191    #[inline]
192    #[ferrocene::prevalidated]
193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194        "could not convert slice to array".fmt(f)
195    }
196}
197
198#[stable(feature = "try_from", since = "1.34.0")]
199impl Error for TryFromSliceError {}
200
201#[stable(feature = "try_from_slice_error", since = "1.36.0")]
202#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
203const impl From<!> for TryFromSliceError {
204    fn from(x: !) -> TryFromSliceError {
205        match x {}
206    }
207}
208
209#[stable(feature = "rust1", since = "1.0.0")]
210#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
211const impl<T, const N: usize> AsRef<[T]> for [T; N] {
212    #[inline]
213    #[ferrocene::prevalidated]
214    fn as_ref(&self) -> &[T] {
215        &self[..]
216    }
217}
218
219#[stable(feature = "rust1", since = "1.0.0")]
220#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
221const impl<T, const N: usize> AsMut<[T]> for [T; N] {
222    #[inline]
223    fn as_mut(&mut self) -> &mut [T] {
224        &mut self[..]
225    }
226}
227
228#[stable(feature = "array_borrow", since = "1.4.0")]
229#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
230const impl<T, const N: usize> Borrow<[T]> for [T; N] {
231    fn borrow(&self) -> &[T] {
232        self
233    }
234}
235
236#[stable(feature = "array_borrow", since = "1.4.0")]
237#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
238const impl<T, const N: usize> BorrowMut<[T]> for [T; N] {
239    fn borrow_mut(&mut self) -> &mut [T] {
240        self
241    }
242}
243
244/// Tries to create an array `[T; N]` by copying from a slice `&[T]`.
245/// Succeeds if `slice.len() == N`.
246///
247/// ```
248/// let bytes: [u8; 3] = [1, 0, 2];
249///
250/// let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&bytes[0..2]).unwrap();
251/// assert_eq!(1, u16::from_le_bytes(bytes_head));
252///
253/// let bytes_tail: [u8; 2] = bytes[1..3].try_into().unwrap();
254/// assert_eq!(512, u16::from_le_bytes(bytes_tail));
255/// ```
256#[stable(feature = "try_from", since = "1.34.0")]
257#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
258const impl<T, const N: usize> TryFrom<&[T]> for [T; N]
259where
260    T: Copy,
261{
262    type Error = TryFromSliceError;
263
264    #[inline]
265    #[ferrocene::prevalidated]
266    fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError> {
267        <&Self>::try_from(slice).copied()
268    }
269}
270
271/// Tries to create an array `[T; N]` by copying from a mutable slice `&mut [T]`.
272/// Succeeds if `slice.len() == N`.
273///
274/// ```
275/// let mut bytes: [u8; 3] = [1, 0, 2];
276///
277/// let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
278/// assert_eq!(1, u16::from_le_bytes(bytes_head));
279///
280/// let bytes_tail: [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
281/// assert_eq!(512, u16::from_le_bytes(bytes_tail));
282/// ```
283#[stable(feature = "try_from_mut_slice_to_array", since = "1.59.0")]
284#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
285const impl<T, const N: usize> TryFrom<&mut [T]> for [T; N]
286where
287    T: Copy,
288{
289    type Error = TryFromSliceError;
290
291    #[inline]
292    #[ferrocene::prevalidated]
293    fn try_from(slice: &mut [T]) -> Result<[T; N], TryFromSliceError> {
294        <Self>::try_from(&*slice)
295    }
296}
297
298/// Tries to create an array ref `&[T; N]` from a slice ref `&[T]`. Succeeds if
299/// `slice.len() == N`.
300///
301/// ```
302/// let bytes: [u8; 3] = [1, 0, 2];
303///
304/// let bytes_head: &[u8; 2] = <&[u8; 2]>::try_from(&bytes[0..2]).unwrap();
305/// assert_eq!(1, u16::from_le_bytes(*bytes_head));
306///
307/// let bytes_tail: &[u8; 2] = bytes[1..3].try_into().unwrap();
308/// assert_eq!(512, u16::from_le_bytes(*bytes_tail));
309/// ```
310#[stable(feature = "try_from", since = "1.34.0")]
311#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
312const impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N] {
313    type Error = TryFromSliceError;
314
315    #[inline]
316    #[ferrocene::prevalidated]
317    fn try_from(slice: &'a [T]) -> Result<&'a [T; N], TryFromSliceError> {
318        slice.as_array().ok_or(TryFromSliceError(()))
319    }
320}
321
322/// Tries to create a mutable array ref `&mut [T; N]` from a mutable slice ref
323/// `&mut [T]`. Succeeds if `slice.len() == N`.
324///
325/// ```
326/// let mut bytes: [u8; 3] = [1, 0, 2];
327///
328/// let bytes_head: &mut [u8; 2] = <&mut [u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
329/// assert_eq!(1, u16::from_le_bytes(*bytes_head));
330///
331/// let bytes_tail: &mut [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
332/// assert_eq!(512, u16::from_le_bytes(*bytes_tail));
333/// ```
334#[stable(feature = "try_from", since = "1.34.0")]
335#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
336const impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N] {
337    type Error = TryFromSliceError;
338
339    #[inline]
340    #[ferrocene::prevalidated]
341    fn try_from(slice: &'a mut [T]) -> Result<&'a mut [T; N], TryFromSliceError> {
342        slice.as_mut_array().ok_or(TryFromSliceError(()))
343    }
344}
345
346/// The hash of an array is the same as that of the corresponding slice,
347/// as required by the `Borrow` implementation.
348///
349/// ```
350/// use std::hash::BuildHasher;
351///
352/// let b = std::hash::RandomState::new();
353/// let a: [u8; 3] = [0xa8, 0x3c, 0x09];
354/// let s: &[u8] = &[0xa8, 0x3c, 0x09];
355/// assert_eq!(b.hash_one(a), b.hash_one(s));
356/// ```
357#[stable(feature = "rust1", since = "1.0.0")]
358impl<T: Hash, const N: usize> Hash for [T; N] {
359    #[ferrocene::prevalidated]
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")]
397const impl<T, I, const N: usize> 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")]
412const impl<T, I, const N: usize> 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")]
426const impl<T: [const] PartialOrd, const N: usize> PartialOrd for [T; N] {
427    #[inline]
428    #[ferrocene::prevalidated]
429    fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
430        <[T] as PartialOrd>::partial_cmp(self, other)
431    }
432
433    #[inline]
434    fn lt(&self, other: &[T; N]) -> bool {
435        <[T] as PartialOrd>::lt(self, other)
436    }
437    #[inline]
438    fn le(&self, other: &[T; N]) -> bool {
439        <[T] as PartialOrd>::le(self, other)
440    }
441    #[inline]
442    fn ge(&self, other: &[T; N]) -> bool {
443        <[T] as PartialOrd>::ge(self, other)
444    }
445    #[inline]
446    fn gt(&self, other: &[T; N]) -> bool {
447        <[T] as PartialOrd>::gt(self, other)
448    }
449
450    #[inline]
451    fn __chaining_less(&self, other: &[T; N]) -> ControlFlow<bool> {
452        <[T] as PartialOrd>::__chaining_less(self, other)
453    }
454    #[inline]
455    fn __chaining_greater(&self, other: &[T; N]) -> ControlFlow<bool> {
456        <[T] as PartialOrd>::__chaining_greater(self, other)
457    }
458}
459
460/// Implements comparison of arrays [lexicographically](Ord#lexicographical-comparison).
461#[stable(feature = "rust1", since = "1.0.0")]
462#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
463const impl<T: [const] Ord, const N: usize> Ord for [T; N] {
464    #[inline]
465    #[ferrocene::prevalidated]
466    fn cmp(&self, other: &[T; N]) -> Ordering {
467        Ord::cmp(&&self[..], &&other[..])
468    }
469}
470
471#[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
472impl<T: Copy, const N: usize> Copy for [T; N] {}
473
474#[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
475impl<T: Clone, const N: usize> Clone for [T; N] {
476    #[inline]
477    #[ferrocene::prevalidated]
478    fn clone(&self) -> Self {
479        SpecArrayClone::clone(self)
480    }
481
482    #[inline]
483    fn clone_from(&mut self, other: &Self) {
484        self.clone_from_slice(other);
485    }
486}
487
488#[doc(hidden)]
489#[unstable(feature = "trivial_clone", issue = "none")]
490unsafe impl<T: TrivialClone, const N: usize> TrivialClone for [T; N] {}
491
492trait SpecArrayClone: Clone {
493    fn clone<const N: usize>(array: &[Self; N]) -> [Self; N];
494}
495
496impl<T: Clone> SpecArrayClone for T {
497    #[inline]
498    #[ferrocene::prevalidated]
499    default fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
500        let mut ptr: *const T = array.as_ptr();
501        // SAFETY: Unless a panic occurs, from_fn will call the closure N times,
502        // so our pointer arithmetic will be in bounds for the N-element array.
503        // This works even for ZSTs, since in that case, add() is a no-op.
504        from_fn(move |_| unsafe {
505            let old = ptr;
506            ptr = ptr.add(1);
507            (&*old).clone()
508        })
509    }
510}
511
512impl<T: TrivialClone> SpecArrayClone for T {
513    #[inline]
514    #[ferrocene::prevalidated]
515    fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
516        // SAFETY: `TrivialClone` implies that this is equivalent to calling
517        // `Clone` on every element.
518        unsafe { ptr::read(array) }
519    }
520}
521
522// The Default impls cannot be done with const generics because `[T; 0]` doesn't
523// require Default to be implemented, and having different impl blocks for
524// different numbers isn't supported yet.
525//
526// Trying to improve the `[T; 0]` situation has proven to be difficult.
527// Please see these issues for more context on past attempts and crater runs:
528// - https://github.com/rust-lang/rust/issues/61415
529// - https://github.com/rust-lang/rust/pull/145457
530
531macro_rules! array_impl_default {
532    {$n:expr, $t:ident $($ts:ident)*} => {
533        #[stable(since = "1.4.0", feature = "array_default")]
534        impl<T> Default for [T; $n] where T: Default {
535            fn default() -> [T; $n] {
536                [$t::default(), $($ts::default()),*]
537            }
538        }
539        array_impl_default!{($n - 1), $($ts)*}
540    };
541    {$n:expr,} => {
542        #[stable(since = "1.4.0", feature = "array_default")]
543        impl<T> Default for [T; $n] {
544            fn default() -> [T; $n] { [] }
545        }
546    };
547}
548
549array_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}
550
551impl<T, const N: usize> [T; N] {
552    /// Returns an array of the same size as `self`, with function `f` applied to each element
553    /// in order.
554    ///
555    /// If you don't necessarily need a new fixed-size array, consider using
556    /// [`Iterator::map`] instead.
557    ///
558    ///
559    /// # Note on performance and stack usage
560    ///
561    /// Note that this method is *eager*.  It evaluates `f` all `N` times before
562    /// returning the new array.
563    ///
564    /// That means that `arr.map(f).map(g)` is, in general, *not* equivalent to
565    /// `array.map(|x| g(f(x)))`, as the former calls `f` 4 times then `g` 4 times,
566    /// whereas the latter interleaves the calls (`fgfgfgfg`).
567    ///
568    /// A consequence of this is that it can have fairly-high stack usage, especially
569    /// in debug mode or for long arrays.  The backend may be able to optimize it
570    /// away, but especially for complicated mappings it might not be able to.
571    ///
572    /// If you're doing a one-step `map` and really want an array as the result,
573    /// then absolutely use this method.  Its implementation uses a bunch of tricks
574    /// to help the optimizer handle it well.  Particularly for simple arrays,
575    /// like `[u8; 3]` or `[f32; 4]`, there's nothing to be concerned about.
576    ///
577    /// However, if you don't actually need an *array* of the results specifically,
578    /// just to process them, then you likely want [`Iterator::map`] instead.
579    ///
580    /// For example, rather than doing an array-to-array map of all the elements
581    /// in the array up-front and only iterating after that completes,
582    ///
583    /// ```
584    /// # let my_array = [1, 2, 3];
585    /// # let f = |x: i32| x + 1;
586    /// for x in my_array.map(f) {
587    ///     // ...
588    /// }
589    /// ```
590    ///
591    /// It's often better to use an iterator along the lines of
592    ///
593    /// ```
594    /// # let my_array = [1, 2, 3];
595    /// # let f = |x: i32| x + 1;
596    /// for x in my_array.into_iter().map(f) {
597    ///     // ...
598    /// }
599    /// ```
600    ///
601    /// as that's more likely to avoid large temporaries.
602    ///
603    ///
604    /// # Examples
605    ///
606    /// ```
607    /// let x = [1, 2, 3];
608    /// let y = x.map(|v| v + 1);
609    /// assert_eq!(y, [2, 3, 4]);
610    ///
611    /// let x = [1, 2, 3];
612    /// let mut temp = 0;
613    /// let y = x.map(|v| { temp += 1; v * temp });
614    /// assert_eq!(y, [1, 4, 9]);
615    ///
616    /// let x = ["Ferris", "Bueller's", "Day", "Off"];
617    /// let y = x.map(|v| v.len());
618    /// assert_eq!(y, [6, 9, 3, 3]);
619    /// ```
620    #[must_use]
621    #[stable(feature = "array_map", since = "1.55.0")]
622    #[rustc_const_unstable(feature = "const_array", issue = "147606")]
623    #[ferrocene::prevalidated]
624    pub const fn map<F, U>(self, f: F) -> [U; N]
625    where
626        F: [const] FnMut(T) -> U + [const] Destruct,
627        U: [const] Destruct,
628        T: [const] Destruct,
629    {
630        self.try_map(NeverShortCircuit::wrap_mut_1(f)).0
631    }
632
633    /// A fallible function `f` applied to each element on array `self` in order to
634    /// return an array the same size as `self` or the first error encountered.
635    ///
636    /// The return type of this function depends on the return type of the closure.
637    /// If you return `Result<T, E>` from the closure, you'll get a `Result<[T; N], E>`.
638    /// If you return `Option<T>` from the closure, you'll get an `Option<[T; N]>`.
639    ///
640    /// # Examples
641    ///
642    /// ```
643    /// #![feature(array_try_map)]
644    ///
645    /// let a = ["1", "2", "3"];
646    /// let b = a.try_map(|v| v.parse::<u32>()).unwrap().map(|v| v + 1);
647    /// assert_eq!(b, [2, 3, 4]);
648    ///
649    /// let a = ["1", "2a", "3"];
650    /// let b = a.try_map(|v| v.parse::<u32>());
651    /// assert!(b.is_err());
652    ///
653    /// use std::num::NonZero;
654    ///
655    /// let z = [1, 2, 0, 3, 4];
656    /// assert_eq!(z.try_map(NonZero::new), None);
657    ///
658    /// let a = [1, 2, 3];
659    /// let b = a.try_map(NonZero::new);
660    /// let c = b.map(|x| x.map(NonZero::get));
661    /// assert_eq!(c, Some(a));
662    /// ```
663    #[unstable(feature = "array_try_map", issue = "79711")]
664    #[rustc_const_unstable(feature = "array_try_map", issue = "79711")]
665    #[ferrocene::prevalidated]
666    pub const fn try_map<R>(
667        self,
668        mut f: impl [const] FnMut(T) -> R + [const] Destruct,
669    ) -> ChangeOutputType<R, [R::Output; N]>
670    where
671        R: [const] Try<Residual: [const] Residual<[R::Output; N]>, Output: [const] Destruct>,
672        T: [const] Destruct,
673    {
674        let mut me = ManuallyDrop::new(self);
675        // SAFETY: try_from_fn calls `f` N times.
676        let mut f = unsafe { drain::Drain::new(&mut me, &mut f) };
677        try_from_fn(&mut f)
678    }
679
680    /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
681    #[stable(feature = "array_as_slice", since = "1.57.0")]
682    #[rustc_const_stable(feature = "array_as_slice", since = "1.57.0")]
683    #[ferrocene::prevalidated]
684    pub const fn as_slice(&self) -> &[T] {
685        self
686    }
687
688    /// Returns a mutable slice containing the entire array. Equivalent to
689    /// `&mut s[..]`.
690    #[stable(feature = "array_as_slice", since = "1.57.0")]
691    #[rustc_const_stable(feature = "const_array_as_mut_slice", since = "1.89.0")]
692    #[ferrocene::prevalidated]
693    pub const fn as_mut_slice(&mut self) -> &mut [T] {
694        self
695    }
696
697    /// Borrows each element and returns an array of references with the same
698    /// size as `self`.
699    ///
700    ///
701    /// # Example
702    ///
703    /// ```
704    /// let floats = [3.1, 2.7, -1.0];
705    /// let float_refs: [&f64; 3] = floats.each_ref();
706    /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
707    /// ```
708    ///
709    /// This method is particularly useful if combined with other methods, like
710    /// [`map`](#method.map). This way, you can avoid moving the original
711    /// array if its elements are not [`Copy`].
712    ///
713    /// ```
714    /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
715    /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
716    /// assert_eq!(is_ascii, [true, false, true]);
717    ///
718    /// // We can still access the original array: it has not been moved.
719    /// assert_eq!(strings.len(), 3);
720    /// ```
721    #[stable(feature = "array_methods", since = "1.77.0")]
722    #[rustc_const_stable(feature = "const_array_each_ref", since = "1.91.0")]
723    pub const fn each_ref(&self) -> [&T; N] {
724        let mut buf = [null::<T>(); N];
725
726        // 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.
727        let mut i = 0;
728        while i < N {
729            buf[i] = &raw const self[i];
730
731            i += 1;
732        }
733
734        // SAFETY: `*const T` has the same layout as `&T`, and we've also initialised each pointer as a valid reference.
735        unsafe { transmute_unchecked(buf) }
736    }
737
738    /// Borrows each element mutably and returns an array of mutable references
739    /// with the same size as `self`.
740    ///
741    ///
742    /// # Example
743    ///
744    /// ```
745    ///
746    /// let mut floats = [3.1, 2.7, -1.0];
747    /// let float_refs: [&mut f64; 3] = floats.each_mut();
748    /// *float_refs[0] = 0.0;
749    /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
750    /// assert_eq!(floats, [0.0, 2.7, -1.0]);
751    /// ```
752    #[stable(feature = "array_methods", since = "1.77.0")]
753    #[rustc_const_stable(feature = "const_array_each_ref", since = "1.91.0")]
754    pub const fn each_mut(&mut self) -> [&mut T; N] {
755        let mut buf = [null_mut::<T>(); N];
756
757        // 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.
758        let mut i = 0;
759        while i < N {
760            buf[i] = &raw mut self[i];
761
762            i += 1;
763        }
764
765        // SAFETY: `*mut T` has the same layout as `&mut T`, and we've also initialised each pointer as a valid reference.
766        unsafe { transmute_unchecked(buf) }
767    }
768
769    /// Divides one array reference into two at an index.
770    ///
771    /// The first will contain all indices from `[0, M)` (excluding
772    /// the index `M` itself) and the second will contain all
773    /// indices from `[M, N)` (excluding the index `N` itself).
774    ///
775    /// # Panics
776    ///
777    /// Panics if `M > N`.
778    ///
779    /// # Examples
780    ///
781    /// ```
782    /// #![feature(split_array)]
783    ///
784    /// let v = [1, 2, 3, 4, 5, 6];
785    ///
786    /// {
787    ///    let (left, right) = v.split_array_ref::<0>();
788    ///    assert_eq!(left, &[]);
789    ///    assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
790    /// }
791    ///
792    /// {
793    ///     let (left, right) = v.split_array_ref::<2>();
794    ///     assert_eq!(left, &[1, 2]);
795    ///     assert_eq!(right, &[3, 4, 5, 6]);
796    /// }
797    ///
798    /// {
799    ///     let (left, right) = v.split_array_ref::<6>();
800    ///     assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
801    ///     assert_eq!(right, &[]);
802    /// }
803    /// ```
804    #[unstable(
805        feature = "split_array",
806        reason = "return type should have array as 2nd element",
807        issue = "90091"
808    )]
809    #[inline]
810    pub fn split_array_ref<const M: usize>(&self) -> (&[T; M], &[T]) {
811        self.split_first_chunk::<M>().unwrap()
812    }
813
814    /// Divides one mutable array reference into two at an index.
815    ///
816    /// The first will contain all indices from `[0, M)` (excluding
817    /// the index `M` itself) and the second will contain all
818    /// indices from `[M, N)` (excluding the index `N` itself).
819    ///
820    /// # Panics
821    ///
822    /// Panics if `M > N`.
823    ///
824    /// # Examples
825    ///
826    /// ```
827    /// #![feature(split_array)]
828    ///
829    /// let mut v = [1, 0, 3, 0, 5, 6];
830    /// let (left, right) = v.split_array_mut::<2>();
831    /// assert_eq!(left, &mut [1, 0][..]);
832    /// assert_eq!(right, &mut [3, 0, 5, 6]);
833    /// left[1] = 2;
834    /// right[1] = 4;
835    /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
836    /// ```
837    #[unstable(
838        feature = "split_array",
839        reason = "return type should have array as 2nd element",
840        issue = "90091"
841    )]
842    #[inline]
843    pub fn split_array_mut<const M: usize>(&mut self) -> (&mut [T; M], &mut [T]) {
844        self.split_first_chunk_mut::<M>().unwrap()
845    }
846
847    /// Divides one array reference into two at an index from the end.
848    ///
849    /// The first will contain all indices from `[0, N - M)` (excluding
850    /// the index `N - M` itself) and the second will contain all
851    /// indices from `[N - M, N)` (excluding the index `N` itself).
852    ///
853    /// # Panics
854    ///
855    /// Panics if `M > N`.
856    ///
857    /// # Examples
858    ///
859    /// ```
860    /// #![feature(split_array)]
861    ///
862    /// let v = [1, 2, 3, 4, 5, 6];
863    ///
864    /// {
865    ///    let (left, right) = v.rsplit_array_ref::<0>();
866    ///    assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
867    ///    assert_eq!(right, &[]);
868    /// }
869    ///
870    /// {
871    ///     let (left, right) = v.rsplit_array_ref::<2>();
872    ///     assert_eq!(left, &[1, 2, 3, 4]);
873    ///     assert_eq!(right, &[5, 6]);
874    /// }
875    ///
876    /// {
877    ///     let (left, right) = v.rsplit_array_ref::<6>();
878    ///     assert_eq!(left, &[]);
879    ///     assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
880    /// }
881    /// ```
882    #[unstable(
883        feature = "split_array",
884        reason = "return type should have array as 2nd element",
885        issue = "90091"
886    )]
887    #[inline]
888    pub fn rsplit_array_ref<const M: usize>(&self) -> (&[T], &[T; M]) {
889        self.split_last_chunk::<M>().unwrap()
890    }
891
892    /// Divides one mutable array reference into two at an index from the end.
893    ///
894    /// The first will contain all indices from `[0, N - M)` (excluding
895    /// the index `N - M` itself) and the second will contain all
896    /// indices from `[N - M, N)` (excluding the index `N` itself).
897    ///
898    /// # Panics
899    ///
900    /// Panics if `M > N`.
901    ///
902    /// # Examples
903    ///
904    /// ```
905    /// #![feature(split_array)]
906    ///
907    /// let mut v = [1, 0, 3, 0, 5, 6];
908    /// let (left, right) = v.rsplit_array_mut::<4>();
909    /// assert_eq!(left, &mut [1, 0]);
910    /// assert_eq!(right, &mut [3, 0, 5, 6][..]);
911    /// left[1] = 2;
912    /// right[1] = 4;
913    /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
914    /// ```
915    #[unstable(
916        feature = "split_array",
917        reason = "return type should have array as 2nd element",
918        issue = "90091"
919    )]
920    #[inline]
921    pub fn rsplit_array_mut<const M: usize>(&mut self) -> (&mut [T], &mut [T; M]) {
922        self.split_last_chunk_mut::<M>().unwrap()
923    }
924}
925
926/// Version of [`try_from_fn`] using a passed-in slice in order to avoid
927/// needing to monomorphize for every array length.
928///
929/// This takes a generator rather than an iterator so that *at the type level*
930/// it never needs to worry about running out of items.  When combined with
931/// an infallible `Try` type, that means the loop canonicalizes easily, allowing
932/// it to optimize well.
933///
934/// It would be *possible* to unify this and [`iter_next_chunk_erased`] into one
935/// function that does the union of both things, but last time it was that way
936/// it resulted in poor codegen from the "are there enough source items?" checks
937/// not optimizing away.  So if you give it a shot, make sure to watch what
938/// happens in the codegen tests.
939#[inline]
940#[rustc_const_unstable(feature = "array_try_from_fn", issue = "89379")]
941#[ferrocene::prevalidated]
942const fn try_from_fn_erased<R: [const] Try<Output: [const] Destruct>>(
943    buffer: &mut [MaybeUninit<R::Output>],
944    mut generator: impl [const] FnMut(usize) -> R + [const] Destruct,
945) -> ControlFlow<R::Residual> {
946    let mut guard = Guard { array_mut: buffer, initialized: 0 };
947
948    while guard.initialized < guard.array_mut.len() {
949        let item = generator(guard.initialized).branch()?;
950
951        // SAFETY: The loop condition ensures we have space to push the item
952        unsafe { guard.push_unchecked(item) };
953    }
954
955    mem::forget(guard);
956    ControlFlow::Continue(())
957}
958
959/// Panic guard for incremental initialization of arrays.
960///
961/// Disarm the guard with `mem::forget` once the array has been initialized.
962///
963/// # Safety
964///
965/// All write accesses to this structure are unsafe and must maintain a correct
966/// count of `initialized` elements.
967///
968/// To minimize indirection, fields are still pub but callers should at least use
969/// `push_unchecked` to signal that something unsafe is going on.
970#[ferrocene::prevalidated]
971struct Guard<'a, T> {
972    /// The array to be initialized.
973    pub array_mut: &'a mut [MaybeUninit<T>],
974    /// The number of items that have been initialized so far.
975    pub initialized: usize,
976}
977
978impl<T> Guard<'_, T> {
979    /// Adds an item to the array and updates the initialized item counter.
980    ///
981    /// # Safety
982    ///
983    /// No more than N elements must be initialized.
984    #[inline]
985    #[rustc_const_unstable(feature = "array_try_from_fn", issue = "89379")]
986    #[ferrocene::prevalidated]
987    pub(crate) const unsafe fn push_unchecked(&mut self, item: T) {
988        // SAFETY: If `initialized` was correct before and the caller does not
989        // invoke this method more than N times, then writes will be in-bounds
990        // and slots will not be initialized more than once.
991        unsafe {
992            self.array_mut.get_unchecked_mut(self.initialized).write(item);
993            self.initialized = self.initialized.unchecked_add(1);
994        }
995    }
996}
997
998#[rustc_const_unstable(feature = "array_try_from_fn", issue = "89379")]
999const impl<T: [const] Destruct> Drop for Guard<'_, T> {
1000    #[inline]
1001    #[ferrocene::prevalidated]
1002    fn drop(&mut self) {
1003        debug_assert!(self.initialized <= self.array_mut.len());
1004        // SAFETY: this slice will contain only initialized objects.
1005        unsafe {
1006            self.array_mut.get_unchecked_mut(..self.initialized).assume_init_drop();
1007        }
1008    }
1009}
1010
1011/// Panic guard for incremental initialization of arrays from the back.
1012///
1013/// Elements of the array are populated starting from the end towards the beginning.
1014/// Disarm the guard with `mem::forget` once the array has been fully initialized.
1015///
1016/// # Safety
1017///
1018/// All write accesses to this structure are unsafe and must maintain a correct
1019/// count of `initialized` elements.
1020struct GuardBack<'a, T> {
1021    /// The array to be initialized (will be filled from the end).
1022    pub array_mut: &'a mut [MaybeUninit<T>],
1023    /// The number of items that have been initialized so far.
1024    pub initialized: usize,
1025}
1026
1027impl<T> GuardBack<'_, T> {
1028    /// Adds an item to the array and updates the initialized item counter.
1029    ///
1030    /// # Safety
1031    ///
1032    /// No more than N elements must be initialized.
1033    #[inline]
1034    pub(crate) unsafe fn push_unchecked(&mut self, item: T) {
1035        // SAFETY: If `initialized` was correct before and the caller does not
1036        // invoke this method more than N times, then writes will be in-bounds
1037        // and slots will not be initialized more than once.
1038        unsafe {
1039            let offset = self.initialized.unchecked_add(1);
1040            let index = self.array_mut.len().unchecked_sub(offset);
1041            self.array_mut.get_unchecked_mut(index).write(item);
1042            self.initialized = offset;
1043        }
1044    }
1045}
1046
1047impl<T: Destruct> Drop for GuardBack<'_, T> {
1048    #[inline]
1049    fn drop(&mut self) {
1050        debug_assert!(self.initialized <= self.array_mut.len());
1051        let len = self.array_mut.len();
1052        // SAFETY: this slice will contain only initialized objects.
1053        unsafe {
1054            self.array_mut.get_unchecked_mut(len - self.initialized..len).assume_init_drop();
1055        }
1056    }
1057}
1058
1059/// Pulls `N` items from `iter` and returns them as an array. If the iterator
1060/// yields fewer than `N` items, `Err` is returned containing an iterator over
1061/// the already yielded items.
1062///
1063/// Since the iterator is passed as a mutable reference and this function calls
1064/// `next` at most `N` times, the iterator can still be used afterwards to
1065/// retrieve the remaining items.
1066///
1067/// If `iter.next()` panics, all items already yielded by the iterator are
1068/// dropped.
1069///
1070/// Used for [`Iterator::next_chunk`].
1071#[rustc_const_unstable(feature = "const_iter", issue = "92476")]
1072#[inline]
1073pub(crate) const fn iter_next_chunk<T, const N: usize>(
1074    iter: &mut impl [const] Iterator<Item = T>,
1075) -> Result<[T; N], IntoIter<T, N>> {
1076    iter.spec_next_chunk()
1077}
1078
1079pub(crate) const trait SpecNextChunk<T, const N: usize>: Iterator<Item = T> {
1080    fn spec_next_chunk(&mut self) -> Result<[T; N], IntoIter<T, N>>;
1081}
1082#[rustc_const_unstable(feature = "const_iter", issue = "92476")]
1083const impl<I: [const] Iterator<Item = T>, T, const N: usize> SpecNextChunk<T, N> for I {
1084    #[inline]
1085    default fn spec_next_chunk(&mut self) -> Result<[T; N], IntoIter<T, N>> {
1086        let mut array = [const { MaybeUninit::uninit() }; N];
1087        let r = iter_next_chunk_erased(&mut array, self);
1088        match r {
1089            Ok(()) => {
1090                // SAFETY: All elements of `array` were populated.
1091                Ok(unsafe { MaybeUninit::array_assume_init(array) })
1092            }
1093            Err(initialized) => {
1094                // SAFETY: Only the first `initialized` elements were populated
1095                Err(unsafe { IntoIter::new_unchecked(array, 0..initialized) })
1096            }
1097        }
1098    }
1099}
1100#[rustc_const_unstable(feature = "const_iter", issue = "92476")]
1101const impl<I: [const] Iterator<Item = T> + TrustedLen, T, const N: usize> SpecNextChunk<T, N>
1102    for I
1103{
1104    fn spec_next_chunk(&mut self) -> Result<[T; N], IntoIter<T, N>> {
1105        let len = (*self).size_hint().0;
1106        let mut array = [const { MaybeUninit::uninit() }; N];
1107        if len < N {
1108            // SAFETY: `TrustedLen`, an unsafe trait, requires that i can get len items out of it.
1109            unsafe { write(&mut array, self, len) };
1110            // SAFETY: Only the first `len` elements were populated
1111            Err(unsafe { IntoIter::new_unchecked(array, 0..len) })
1112        } else {
1113            // SAFETY: `TrustedLen`, an unsafe trait, requires that i can get N items out of it.
1114            unsafe { write(&mut array, self, N) };
1115            // SAFETY: All N items were populated
1116            Ok(unsafe { MaybeUninit::array_assume_init(array) })
1117        }
1118    }
1119}
1120// SAFETY: `from` must have len items, and len items must be < N.
1121#[rustc_const_unstable(feature = "const_iter", issue = "92476")]
1122const unsafe fn write<T, const N: usize>(
1123    to: &mut [MaybeUninit<T>; N],
1124    from: &mut impl [const] Iterator<Item = T>,
1125    len: usize,
1126) {
1127    let mut guard = Guard { array_mut: to, initialized: 0 };
1128    while guard.initialized < len {
1129        // SAFETY: caller has guaranteed, from has len items.
1130        let item = unsafe { from.next().unwrap_unchecked() };
1131        // SAFETY: guard.initialized < len < N
1132        unsafe { guard.push_unchecked(item) };
1133    }
1134    crate::mem::forget(guard);
1135}
1136
1137/// Version of [`iter_next_chunk`] using a passed-in slice in order to avoid
1138/// needing to monomorphize for every array length.
1139///
1140/// Unfortunately this loop has two exit conditions, the buffer filling up
1141/// or the iterator running out of items, making it tend to optimize poorly.
1142#[rustc_const_unstable(feature = "const_iter", issue = "92476")]
1143#[inline]
1144const fn iter_next_chunk_erased<T>(
1145    buffer: &mut [MaybeUninit<T>],
1146    iter: &mut impl [const] Iterator<Item = T>,
1147) -> Result<(), usize> {
1148    // if `Iterator::next` panics, this guard will drop already initialized items
1149    let mut guard = Guard { array_mut: buffer, initialized: 0 };
1150    while guard.initialized < guard.array_mut.len() {
1151        let Some(item) = iter.next() else {
1152            // Unlike `try_from_fn_erased`, we want to keep the partial results,
1153            // so we need to defuse the guard instead of using `?`.
1154            let initialized = guard.initialized;
1155            mem::forget(guard);
1156            return Err(initialized);
1157        };
1158
1159        // SAFETY: The loop condition ensures we have space to push the item
1160        unsafe { guard.push_unchecked(item) };
1161    }
1162
1163    mem::forget(guard);
1164    Ok(())
1165}
1166
1167/// Pulls `N` items from the back of `iter` and returns them as an array.
1168/// If the iterator yields fewer than `N` items, `Err` is returned containing
1169/// an iterator over the already yielded items.
1170///
1171/// Since the iterator is passed as a mutable reference and this function calls
1172/// `next_back` at most `N` times, the iterator can still be used afterwards to
1173/// retrieve the remaining items.
1174///
1175/// If `iter.next_back()` panics, all items already yielded by the iterator are
1176/// dropped.
1177///
1178/// Used for [`DoubleEndedIterator::next_chunk_back`].
1179#[inline]
1180pub(crate) fn iter_next_chunk_back<T, const N: usize>(
1181    iter: &mut impl DoubleEndedIterator<Item = T>,
1182) -> Result<[T; N], IntoIter<T, N>> {
1183    iter.spec_next_chunk_back()
1184}
1185
1186pub(crate) trait SpecNextChunkBack<T, const N: usize>:
1187    DoubleEndedIterator<Item = T>
1188{
1189    fn spec_next_chunk_back(&mut self) -> Result<[T; N], IntoIter<T, N>>;
1190}
1191
1192impl<I: DoubleEndedIterator<Item = T>, T, const N: usize> SpecNextChunkBack<T, N> for I {
1193    #[inline]
1194    default fn spec_next_chunk_back(&mut self) -> Result<[T; N], IntoIter<T, N>> {
1195        let mut array = [const { MaybeUninit::uninit() }; N];
1196        let r = iter_next_chunk_back_erased(&mut array, self);
1197        match r {
1198            Ok(()) => {
1199                // SAFETY: All elements of `array` were populated.
1200                Ok(unsafe { MaybeUninit::array_assume_init(array) })
1201            }
1202            Err(initialized) => {
1203                // SAFETY: Only the last `initialized` elements were populated
1204                Err(unsafe { IntoIter::new_unchecked(array, N - initialized..N) })
1205            }
1206        }
1207    }
1208}
1209
1210impl<I: DoubleEndedIterator<Item = T> + TrustedLen, T, const N: usize> SpecNextChunkBack<T, N>
1211    for I
1212{
1213    fn spec_next_chunk_back(&mut self) -> Result<[T; N], IntoIter<T, N>> {
1214        let len = (*self).size_hint().0;
1215        let mut array = [const { MaybeUninit::uninit() }; N];
1216        if len < N {
1217            // SAFETY: `TrustedLen`, an unsafe trait, requires that i can get len items out of it.
1218            unsafe { write_back(&mut array, self, len) };
1219            // SAFETY: Only the last `len` elements were populated
1220            Err(unsafe { IntoIter::new_unchecked(array, N - len..N) })
1221        } else {
1222            // SAFETY: `TrustedLen`, an unsafe trait, requires that i can get N items out of it.
1223            unsafe { write_back(&mut array, self, N) };
1224            // SAFETY: All N items were populated
1225            Ok(unsafe { MaybeUninit::array_assume_init(array) })
1226        }
1227    }
1228}
1229
1230// SAFETY: `from` must have len items, and len items must be < N.
1231unsafe fn write_back<T, const N: usize>(
1232    to: &mut [MaybeUninit<T>; N],
1233    from: &mut impl DoubleEndedIterator<Item = T>,
1234    len: usize,
1235) {
1236    let mut guard = GuardBack { array_mut: to, initialized: 0 };
1237    while guard.initialized < len {
1238        // SAFETY: caller has guaranteed, from has len items.
1239        let item = unsafe { from.next_back().unwrap_unchecked() };
1240        // SAFETY: guard.initialized < len < N
1241        unsafe { guard.push_unchecked(item) };
1242    }
1243    crate::mem::forget(guard);
1244}
1245
1246/// Version of [`iter_next_chunk_back`] using a passed-in slice
1247/// in order to avoid needing to monomorphize for every array length.
1248///
1249/// Unfortunately this loop has two exit conditions, the buffer filling up
1250/// or the iterator running out of items, making it tend to optimize poorly.
1251#[inline]
1252fn iter_next_chunk_back_erased<T>(
1253    buffer: &mut [MaybeUninit<T>],
1254    iter: &mut impl DoubleEndedIterator<Item = T>,
1255) -> Result<(), usize> {
1256    // if `Iterator::next_back` panics, this guard will drop already initialized items
1257    let mut guard = GuardBack { array_mut: buffer, initialized: 0 };
1258    while guard.initialized < guard.array_mut.len() {
1259        let Some(item) = iter.next_back() else {
1260            let initialized = guard.initialized;
1261            mem::forget(guard);
1262            return Err(initialized);
1263        };
1264
1265        // SAFETY: The loop condition ensures we have space to push the item
1266        unsafe { guard.push_unchecked(item) };
1267    }
1268
1269    mem::forget(guard);
1270    Ok(())
1271}
1272
1273/// Ferrocene addition: Hidden module to test crate-internal functionality
1274#[doc(hidden)]
1275#[unstable(feature = "ferrocene_test", issue = "none")]
1276pub mod ferrocene_test;