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")]
198const impl 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")]
206const impl<T, const N: usize> 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")]
215const impl<T, const N: usize> 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")]
224const impl<T, const N: usize> 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")]
232const impl<T, const N: usize> 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")]
252const impl<T, const N: usize> 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")]
278const impl<T, const N: usize> 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")]
304const impl<'a, T, const N: usize> 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")]
327const impl<'a, T, const N: usize> 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")]
383const impl<T, I, const N: usize> 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")]
397const impl<T, I, const N: usize> 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")]
410const impl<T: [const] PartialOrd, const N: usize> PartialOrd for [T; N] {
411    #[inline]
412    fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
413        <[T] as PartialOrd>::partial_cmp(self, other)
414    }
415
416    #[inline]
417    fn lt(&self, other: &[T; N]) -> bool {
418        <[T] as PartialOrd>::lt(self, other)
419    }
420    #[inline]
421    fn le(&self, other: &[T; N]) -> bool {
422        <[T] as PartialOrd>::le(self, other)
423    }
424    #[inline]
425    fn ge(&self, other: &[T; N]) -> bool {
426        <[T] as PartialOrd>::ge(self, other)
427    }
428    #[inline]
429    fn gt(&self, other: &[T; N]) -> bool {
430        <[T] as PartialOrd>::gt(self, other)
431    }
432
433    #[inline]
434    fn __chaining_lt(&self, other: &[T; N]) -> ControlFlow<bool> {
435        <[T] as PartialOrd>::__chaining_lt(self, other)
436    }
437    #[inline]
438    fn __chaining_le(&self, other: &[T; N]) -> ControlFlow<bool> {
439        <[T] as PartialOrd>::__chaining_le(self, other)
440    }
441    #[inline]
442    fn __chaining_ge(&self, other: &[T; N]) -> ControlFlow<bool> {
443        <[T] as PartialOrd>::__chaining_ge(self, other)
444    }
445    #[inline]
446    fn __chaining_gt(&self, other: &[T; N]) -> ControlFlow<bool> {
447        <[T] as PartialOrd>::__chaining_gt(self, other)
448    }
449}
450
451/// Implements comparison of arrays [lexicographically](Ord#lexicographical-comparison).
452#[stable(feature = "rust1", since = "1.0.0")]
453#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
454const impl<T: [const] Ord, const N: usize> Ord for [T; N] {
455    #[inline]
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    fn clone(&self) -> Self {
468        SpecArrayClone::clone(self)
469    }
470
471    #[inline]
472    fn clone_from(&mut self, other: &Self) {
473        self.clone_from_slice(other);
474    }
475}
476
477#[doc(hidden)]
478#[unstable(feature = "trivial_clone", issue = "none")]
479unsafe impl<T: TrivialClone, const N: usize> TrivialClone for [T; N] {}
480
481trait SpecArrayClone: Clone {
482    fn clone<const N: usize>(array: &[Self; N]) -> [Self; N];
483}
484
485impl<T: Clone> SpecArrayClone for T {
486    #[inline]
487    default fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
488        let mut ptr: *const T = array.as_ptr();
489        // SAFETY: Unless a panic occurs, from_fn will call the closure N times,
490        // so our pointer arithmetic will be in bounds for the N-element array.
491        // This works even for ZSTs, since in that case, add() is a no-op.
492        from_fn(move |_| unsafe {
493            let old = ptr;
494            ptr = ptr.add(1);
495            (&*old).clone()
496        })
497    }
498}
499
500impl<T: TrivialClone> SpecArrayClone for T {
501    #[inline]
502    fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
503        // SAFETY: `TrivialClone` implies that this is equivalent to calling
504        // `Clone` on every element.
505        unsafe { ptr::read(array) }
506    }
507}
508
509// The Default impls cannot be done with const generics because `[T; 0]` doesn't
510// require Default to be implemented, and having different impl blocks for
511// different numbers isn't supported yet.
512//
513// Trying to improve the `[T; 0]` situation has proven to be difficult.
514// Please see these issues for more context on past attempts and crater runs:
515// - https://github.com/rust-lang/rust/issues/61415
516// - https://github.com/rust-lang/rust/pull/145457
517
518macro_rules! array_impl_default {
519    {$n:expr, $t:ident $($ts:ident)*} => {
520        #[stable(since = "1.4.0", feature = "array_default")]
521        impl<T> Default for [T; $n] where T: Default {
522            fn default() -> [T; $n] {
523                [$t::default(), $($ts::default()),*]
524            }
525        }
526        array_impl_default!{($n - 1), $($ts)*}
527    };
528    {$n:expr,} => {
529        #[stable(since = "1.4.0", feature = "array_default")]
530        impl<T> Default for [T; $n] {
531            fn default() -> [T; $n] { [] }
532        }
533    };
534}
535
536array_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}
537
538impl<T, const N: usize> [T; N] {
539    /// Returns an array of the same size as `self`, with function `f` applied to each element
540    /// in order.
541    ///
542    /// If you don't necessarily need a new fixed-size array, consider using
543    /// [`Iterator::map`] instead.
544    ///
545    ///
546    /// # Note on performance and stack usage
547    ///
548    /// Note that this method is *eager*.  It evaluates `f` all `N` times before
549    /// returning the new array.
550    ///
551    /// That means that `arr.map(f).map(g)` is, in general, *not* equivalent to
552    /// `array.map(|x| g(f(x)))`, as the former calls `f` 4 times then `g` 4 times,
553    /// whereas the latter interleaves the calls (`fgfgfgfg`).
554    ///
555    /// A consequence of this is that it can have fairly-high stack usage, especially
556    /// in debug mode or for long arrays.  The backend may be able to optimize it
557    /// away, but especially for complicated mappings it might not be able to.
558    ///
559    /// If you're doing a one-step `map` and really want an array as the result,
560    /// then absolutely use this method.  Its implementation uses a bunch of tricks
561    /// to help the optimizer handle it well.  Particularly for simple arrays,
562    /// like `[u8; 3]` or `[f32; 4]`, there's nothing to be concerned about.
563    ///
564    /// However, if you don't actually need an *array* of the results specifically,
565    /// just to process them, then you likely want [`Iterator::map`] instead.
566    ///
567    /// For example, rather than doing an array-to-array map of all the elements
568    /// in the array up-front and only iterating after that completes,
569    ///
570    /// ```
571    /// # let my_array = [1, 2, 3];
572    /// # let f = |x: i32| x + 1;
573    /// for x in my_array.map(f) {
574    ///     // ...
575    /// }
576    /// ```
577    ///
578    /// It's often better to use an iterator along the lines of
579    ///
580    /// ```
581    /// # let my_array = [1, 2, 3];
582    /// # let f = |x: i32| x + 1;
583    /// for x in my_array.into_iter().map(f) {
584    ///     // ...
585    /// }
586    /// ```
587    ///
588    /// as that's more likely to avoid large temporaries.
589    ///
590    ///
591    /// # Examples
592    ///
593    /// ```
594    /// let x = [1, 2, 3];
595    /// let y = x.map(|v| v + 1);
596    /// assert_eq!(y, [2, 3, 4]);
597    ///
598    /// let x = [1, 2, 3];
599    /// let mut temp = 0;
600    /// let y = x.map(|v| { temp += 1; v * temp });
601    /// assert_eq!(y, [1, 4, 9]);
602    ///
603    /// let x = ["Ferris", "Bueller's", "Day", "Off"];
604    /// let y = x.map(|v| v.len());
605    /// assert_eq!(y, [6, 9, 3, 3]);
606    /// ```
607    #[must_use]
608    #[stable(feature = "array_map", since = "1.55.0")]
609    #[rustc_const_unstable(feature = "const_array", issue = "147606")]
610    pub const fn map<F, U>(self, f: F) -> [U; N]
611    where
612        F: [const] FnMut(T) -> U + [const] Destruct,
613        U: [const] Destruct,
614        T: [const] Destruct,
615    {
616        self.try_map(NeverShortCircuit::wrap_mut_1(f)).0
617    }
618
619    /// A fallible function `f` applied to each element on array `self` in order to
620    /// return an array the same size as `self` or the first error encountered.
621    ///
622    /// The return type of this function depends on the return type of the closure.
623    /// If you return `Result<T, E>` from the closure, you'll get a `Result<[T; N], E>`.
624    /// If you return `Option<T>` from the closure, you'll get an `Option<[T; N]>`.
625    ///
626    /// # Examples
627    ///
628    /// ```
629    /// #![feature(array_try_map)]
630    ///
631    /// let a = ["1", "2", "3"];
632    /// let b = a.try_map(|v| v.parse::<u32>()).unwrap().map(|v| v + 1);
633    /// assert_eq!(b, [2, 3, 4]);
634    ///
635    /// let a = ["1", "2a", "3"];
636    /// let b = a.try_map(|v| v.parse::<u32>());
637    /// assert!(b.is_err());
638    ///
639    /// use std::num::NonZero;
640    ///
641    /// let z = [1, 2, 0, 3, 4];
642    /// assert_eq!(z.try_map(NonZero::new), None);
643    ///
644    /// let a = [1, 2, 3];
645    /// let b = a.try_map(NonZero::new);
646    /// let c = b.map(|x| x.map(NonZero::get));
647    /// assert_eq!(c, Some(a));
648    /// ```
649    #[unstable(feature = "array_try_map", issue = "79711")]
650    #[rustc_const_unstable(feature = "array_try_map", issue = "79711")]
651    pub const fn try_map<R>(
652        self,
653        mut f: impl [const] FnMut(T) -> R + [const] Destruct,
654    ) -> ChangeOutputType<R, [R::Output; N]>
655    where
656        R: [const] Try<Residual: [const] Residual<[R::Output; N]>, Output: [const] Destruct>,
657        T: [const] Destruct,
658    {
659        let mut me = ManuallyDrop::new(self);
660        // SAFETY: try_from_fn calls `f` N times.
661        let mut f = unsafe { drain::Drain::new(&mut me, &mut f) };
662        try_from_fn(&mut f)
663    }
664
665    /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
666    #[stable(feature = "array_as_slice", since = "1.57.0")]
667    #[rustc_const_stable(feature = "array_as_slice", since = "1.57.0")]
668    pub const fn as_slice(&self) -> &[T] {
669        self
670    }
671
672    /// Returns a mutable slice containing the entire array. Equivalent to
673    /// `&mut s[..]`.
674    #[stable(feature = "array_as_slice", since = "1.57.0")]
675    #[rustc_const_stable(feature = "const_array_as_mut_slice", since = "1.89.0")]
676    pub const fn as_mut_slice(&mut self) -> &mut [T] {
677        self
678    }
679
680    /// Borrows each element and returns an array of references with the same
681    /// size as `self`.
682    ///
683    ///
684    /// # Example
685    ///
686    /// ```
687    /// let floats = [3.1, 2.7, -1.0];
688    /// let float_refs: [&f64; 3] = floats.each_ref();
689    /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
690    /// ```
691    ///
692    /// This method is particularly useful if combined with other methods, like
693    /// [`map`](#method.map). This way, you can avoid moving the original
694    /// array if its elements are not [`Copy`].
695    ///
696    /// ```
697    /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
698    /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
699    /// assert_eq!(is_ascii, [true, false, true]);
700    ///
701    /// // We can still access the original array: it has not been moved.
702    /// assert_eq!(strings.len(), 3);
703    /// ```
704    #[stable(feature = "array_methods", since = "1.77.0")]
705    #[rustc_const_stable(feature = "const_array_each_ref", since = "1.91.0")]
706    pub const fn each_ref(&self) -> [&T; N] {
707        let mut buf = [null::<T>(); N];
708
709        // 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.
710        let mut i = 0;
711        while i < N {
712            buf[i] = &raw const self[i];
713
714            i += 1;
715        }
716
717        // SAFETY: `*const T` has the same layout as `&T`, and we've also initialised each pointer as a valid reference.
718        unsafe { transmute_unchecked(buf) }
719    }
720
721    /// Borrows each element mutably and returns an array of mutable references
722    /// with the same size as `self`.
723    ///
724    ///
725    /// # Example
726    ///
727    /// ```
728    ///
729    /// let mut floats = [3.1, 2.7, -1.0];
730    /// let float_refs: [&mut f64; 3] = floats.each_mut();
731    /// *float_refs[0] = 0.0;
732    /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
733    /// assert_eq!(floats, [0.0, 2.7, -1.0]);
734    /// ```
735    #[stable(feature = "array_methods", since = "1.77.0")]
736    #[rustc_const_stable(feature = "const_array_each_ref", since = "1.91.0")]
737    pub const fn each_mut(&mut self) -> [&mut T; N] {
738        let mut buf = [null_mut::<T>(); N];
739
740        // 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.
741        let mut i = 0;
742        while i < N {
743            buf[i] = &raw mut self[i];
744
745            i += 1;
746        }
747
748        // SAFETY: `*mut T` has the same layout as `&mut T`, and we've also initialised each pointer as a valid reference.
749        unsafe { transmute_unchecked(buf) }
750    }
751
752    /// Divides one array reference into two at an index.
753    ///
754    /// The first will contain all indices from `[0, M)` (excluding
755    /// the index `M` itself) and the second will contain all
756    /// indices from `[M, N)` (excluding the index `N` itself).
757    ///
758    /// # Panics
759    ///
760    /// Panics if `M > N`.
761    ///
762    /// # Examples
763    ///
764    /// ```
765    /// #![feature(split_array)]
766    ///
767    /// let v = [1, 2, 3, 4, 5, 6];
768    ///
769    /// {
770    ///    let (left, right) = v.split_array_ref::<0>();
771    ///    assert_eq!(left, &[]);
772    ///    assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
773    /// }
774    ///
775    /// {
776    ///     let (left, right) = v.split_array_ref::<2>();
777    ///     assert_eq!(left, &[1, 2]);
778    ///     assert_eq!(right, &[3, 4, 5, 6]);
779    /// }
780    ///
781    /// {
782    ///     let (left, right) = v.split_array_ref::<6>();
783    ///     assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
784    ///     assert_eq!(right, &[]);
785    /// }
786    /// ```
787    #[unstable(
788        feature = "split_array",
789        reason = "return type should have array as 2nd element",
790        issue = "90091"
791    )]
792    #[inline]
793    pub fn split_array_ref<const M: usize>(&self) -> (&[T; M], &[T]) {
794        self.split_first_chunk::<M>().unwrap()
795    }
796
797    /// Divides one mutable array reference into two at an index.
798    ///
799    /// The first will contain all indices from `[0, M)` (excluding
800    /// the index `M` itself) and the second will contain all
801    /// indices from `[M, N)` (excluding the index `N` itself).
802    ///
803    /// # Panics
804    ///
805    /// Panics if `M > N`.
806    ///
807    /// # Examples
808    ///
809    /// ```
810    /// #![feature(split_array)]
811    ///
812    /// let mut v = [1, 0, 3, 0, 5, 6];
813    /// let (left, right) = v.split_array_mut::<2>();
814    /// assert_eq!(left, &mut [1, 0][..]);
815    /// assert_eq!(right, &mut [3, 0, 5, 6]);
816    /// left[1] = 2;
817    /// right[1] = 4;
818    /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
819    /// ```
820    #[unstable(
821        feature = "split_array",
822        reason = "return type should have array as 2nd element",
823        issue = "90091"
824    )]
825    #[inline]
826    pub fn split_array_mut<const M: usize>(&mut self) -> (&mut [T; M], &mut [T]) {
827        self.split_first_chunk_mut::<M>().unwrap()
828    }
829
830    /// Divides one array reference into two at an index from the end.
831    ///
832    /// The first will contain all indices from `[0, N - M)` (excluding
833    /// the index `N - M` itself) and the second will contain all
834    /// indices from `[N - M, N)` (excluding the index `N` itself).
835    ///
836    /// # Panics
837    ///
838    /// Panics if `M > N`.
839    ///
840    /// # Examples
841    ///
842    /// ```
843    /// #![feature(split_array)]
844    ///
845    /// let v = [1, 2, 3, 4, 5, 6];
846    ///
847    /// {
848    ///    let (left, right) = v.rsplit_array_ref::<0>();
849    ///    assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
850    ///    assert_eq!(right, &[]);
851    /// }
852    ///
853    /// {
854    ///     let (left, right) = v.rsplit_array_ref::<2>();
855    ///     assert_eq!(left, &[1, 2, 3, 4]);
856    ///     assert_eq!(right, &[5, 6]);
857    /// }
858    ///
859    /// {
860    ///     let (left, right) = v.rsplit_array_ref::<6>();
861    ///     assert_eq!(left, &[]);
862    ///     assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
863    /// }
864    /// ```
865    #[unstable(
866        feature = "split_array",
867        reason = "return type should have array as 2nd element",
868        issue = "90091"
869    )]
870    #[inline]
871    pub fn rsplit_array_ref<const M: usize>(&self) -> (&[T], &[T; M]) {
872        self.split_last_chunk::<M>().unwrap()
873    }
874
875    /// Divides one mutable array reference into two at an index from the end.
876    ///
877    /// The first will contain all indices from `[0, N - M)` (excluding
878    /// the index `N - M` itself) and the second will contain all
879    /// indices from `[N - M, N)` (excluding the index `N` itself).
880    ///
881    /// # Panics
882    ///
883    /// Panics if `M > N`.
884    ///
885    /// # Examples
886    ///
887    /// ```
888    /// #![feature(split_array)]
889    ///
890    /// let mut v = [1, 0, 3, 0, 5, 6];
891    /// let (left, right) = v.rsplit_array_mut::<4>();
892    /// assert_eq!(left, &mut [1, 0]);
893    /// assert_eq!(right, &mut [3, 0, 5, 6][..]);
894    /// left[1] = 2;
895    /// right[1] = 4;
896    /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
897    /// ```
898    #[unstable(
899        feature = "split_array",
900        reason = "return type should have array as 2nd element",
901        issue = "90091"
902    )]
903    #[inline]
904    pub fn rsplit_array_mut<const M: usize>(&mut self) -> (&mut [T], &mut [T; M]) {
905        self.split_last_chunk_mut::<M>().unwrap()
906    }
907}
908
909/// Version of [`try_from_fn`] using a passed-in slice in order to avoid
910/// needing to monomorphize for every array length.
911///
912/// This takes a generator rather than an iterator so that *at the type level*
913/// it never needs to worry about running out of items.  When combined with
914/// an infallible `Try` type, that means the loop canonicalizes easily, allowing
915/// it to optimize well.
916///
917/// It would be *possible* to unify this and [`iter_next_chunk_erased`] into one
918/// function that does the union of both things, but last time it was that way
919/// it resulted in poor codegen from the "are there enough source items?" checks
920/// not optimizing away.  So if you give it a shot, make sure to watch what
921/// happens in the codegen tests.
922#[inline]
923#[rustc_const_unstable(feature = "array_try_from_fn", issue = "89379")]
924const fn try_from_fn_erased<R: [const] Try<Output: [const] Destruct>>(
925    buffer: &mut [MaybeUninit<R::Output>],
926    mut generator: impl [const] FnMut(usize) -> R + [const] Destruct,
927) -> ControlFlow<R::Residual> {
928    let mut guard = Guard { array_mut: buffer, initialized: 0 };
929
930    while guard.initialized < guard.array_mut.len() {
931        let item = generator(guard.initialized).branch()?;
932
933        // SAFETY: The loop condition ensures we have space to push the item
934        unsafe { guard.push_unchecked(item) };
935    }
936
937    mem::forget(guard);
938    ControlFlow::Continue(())
939}
940
941/// Panic guard for incremental initialization of arrays.
942///
943/// Disarm the guard with `mem::forget` once the array has been initialized.
944///
945/// # Safety
946///
947/// All write accesses to this structure are unsafe and must maintain a correct
948/// count of `initialized` elements.
949///
950/// To minimize indirection, fields are still pub but callers should at least use
951/// `push_unchecked` to signal that something unsafe is going on.
952struct Guard<'a, T> {
953    /// The array to be initialized.
954    pub array_mut: &'a mut [MaybeUninit<T>],
955    /// The number of items that have been initialized so far.
956    pub initialized: usize,
957}
958
959impl<T> Guard<'_, T> {
960    /// Adds an item to the array and updates the initialized item counter.
961    ///
962    /// # Safety
963    ///
964    /// No more than N elements must be initialized.
965    #[inline]
966    #[rustc_const_unstable(feature = "array_try_from_fn", issue = "89379")]
967    pub(crate) const unsafe fn push_unchecked(&mut self, item: T) {
968        // SAFETY: If `initialized` was correct before and the caller does not
969        // invoke this method more than N times, then writes will be in-bounds
970        // and slots will not be initialized more than once.
971        unsafe {
972            self.array_mut.get_unchecked_mut(self.initialized).write(item);
973            self.initialized = self.initialized.unchecked_add(1);
974        }
975    }
976}
977
978#[rustc_const_unstable(feature = "array_try_from_fn", issue = "89379")]
979const impl<T: [const] Destruct> Drop for Guard<'_, T> {
980    #[inline]
981    fn drop(&mut self) {
982        debug_assert!(self.initialized <= self.array_mut.len());
983        // SAFETY: this slice will contain only initialized objects.
984        unsafe {
985            self.array_mut.get_unchecked_mut(..self.initialized).assume_init_drop();
986        }
987    }
988}
989
990/// Panic guard for incremental initialization of arrays from the back.
991///
992/// Elements of the array are populated starting from the end towards the beginning.
993/// Disarm the guard with `mem::forget` once the array has been fully initialized.
994///
995/// # Safety
996///
997/// All write accesses to this structure are unsafe and must maintain a correct
998/// count of `initialized` elements.
999struct GuardBack<'a, T> {
1000    /// The array to be initialized (will be filled from the end).
1001    pub array_mut: &'a mut [MaybeUninit<T>],
1002    /// The number of items that have been initialized so far.
1003    pub initialized: usize,
1004}
1005
1006impl<T> GuardBack<'_, T> {
1007    /// Adds an item to the array and updates the initialized item counter.
1008    ///
1009    /// # Safety
1010    ///
1011    /// No more than N elements must be initialized.
1012    #[inline]
1013    pub(crate) unsafe fn push_unchecked(&mut self, item: T) {
1014        // SAFETY: If `initialized` was correct before and the caller does not
1015        // invoke this method more than N times, then writes will be in-bounds
1016        // and slots will not be initialized more than once.
1017        unsafe {
1018            let offset = self.initialized.unchecked_add(1);
1019            let index = self.array_mut.len().unchecked_sub(offset);
1020            self.array_mut.get_unchecked_mut(index).write(item);
1021            self.initialized = offset;
1022        }
1023    }
1024}
1025
1026impl<T: Destruct> Drop for GuardBack<'_, T> {
1027    #[inline]
1028    fn drop(&mut self) {
1029        debug_assert!(self.initialized <= self.array_mut.len());
1030        let len = self.array_mut.len();
1031        // SAFETY: this slice will contain only initialized objects.
1032        unsafe {
1033            self.array_mut.get_unchecked_mut(len - self.initialized..len).assume_init_drop();
1034        }
1035    }
1036}
1037
1038/// Pulls `N` items from `iter` and returns them as an array. If the iterator
1039/// yields fewer than `N` items, `Err` is returned containing an iterator over
1040/// the already yielded items.
1041///
1042/// Since the iterator is passed as a mutable reference and this function calls
1043/// `next` at most `N` times, the iterator can still be used afterwards to
1044/// retrieve the remaining items.
1045///
1046/// If `iter.next()` panics, all items already yielded by the iterator are
1047/// dropped.
1048///
1049/// Used for [`Iterator::next_chunk`].
1050#[rustc_const_unstable(feature = "const_iter", issue = "92476")]
1051#[inline]
1052pub(crate) const fn iter_next_chunk<T, const N: usize>(
1053    iter: &mut impl [const] Iterator<Item = T>,
1054) -> Result<[T; N], IntoIter<T, N>> {
1055    iter.spec_next_chunk()
1056}
1057
1058pub(crate) const trait SpecNextChunk<T, const N: usize>: Iterator<Item = T> {
1059    fn spec_next_chunk(&mut self) -> Result<[T; N], IntoIter<T, N>>;
1060}
1061#[rustc_const_unstable(feature = "const_iter", issue = "92476")]
1062const impl<I: [const] Iterator<Item = T>, T, const N: usize> SpecNextChunk<T, N> for I {
1063    #[inline]
1064    default fn spec_next_chunk(&mut self) -> Result<[T; N], IntoIter<T, N>> {
1065        let mut array = [const { MaybeUninit::uninit() }; N];
1066        let r = iter_next_chunk_erased(&mut array, self);
1067        match r {
1068            Ok(()) => {
1069                // SAFETY: All elements of `array` were populated.
1070                Ok(unsafe { MaybeUninit::array_assume_init(array) })
1071            }
1072            Err(initialized) => {
1073                // SAFETY: Only the first `initialized` elements were populated
1074                Err(unsafe { IntoIter::new_unchecked(array, 0..initialized) })
1075            }
1076        }
1077    }
1078}
1079#[rustc_const_unstable(feature = "const_iter", issue = "92476")]
1080const impl<I: [const] Iterator<Item = T> + TrustedLen, T, const N: usize> SpecNextChunk<T, N>
1081    for I
1082{
1083    fn spec_next_chunk(&mut self) -> Result<[T; N], IntoIter<T, N>> {
1084        let len = (*self).size_hint().0;
1085        let mut array = [const { MaybeUninit::uninit() }; N];
1086        if len < N {
1087            // SAFETY: `TrustedLen`, an unsafe trait, requires that i can get len items out of it.
1088            unsafe { write(&mut array, self, len) };
1089            // SAFETY: Only the first `len` elements were populated
1090            Err(unsafe { IntoIter::new_unchecked(array, 0..len) })
1091        } else {
1092            // SAFETY: `TrustedLen`, an unsafe trait, requires that i can get N items out of it.
1093            unsafe { write(&mut array, self, N) };
1094            // SAFETY: All N items were populated
1095            Ok(unsafe { MaybeUninit::array_assume_init(array) })
1096        }
1097    }
1098}
1099// SAFETY: `from` must have len items, and len items must be < N.
1100#[rustc_const_unstable(feature = "const_iter", issue = "92476")]
1101const unsafe fn write<T, const N: usize>(
1102    to: &mut [MaybeUninit<T>; N],
1103    from: &mut impl [const] Iterator<Item = T>,
1104    len: usize,
1105) {
1106    let mut guard = Guard { array_mut: to, initialized: 0 };
1107    while guard.initialized < len {
1108        // SAFETY: caller has guaranteed, from has len items.
1109        let item = unsafe { from.next().unwrap_unchecked() };
1110        // SAFETY: guard.initialized < len < N
1111        unsafe { guard.push_unchecked(item) };
1112    }
1113    crate::mem::forget(guard);
1114}
1115
1116/// Version of [`iter_next_chunk`] using a passed-in slice in order to avoid
1117/// needing to monomorphize for every array length.
1118///
1119/// Unfortunately this loop has two exit conditions, the buffer filling up
1120/// or the iterator running out of items, making it tend to optimize poorly.
1121#[rustc_const_unstable(feature = "const_iter", issue = "92476")]
1122#[inline]
1123const fn iter_next_chunk_erased<T>(
1124    buffer: &mut [MaybeUninit<T>],
1125    iter: &mut impl [const] Iterator<Item = T>,
1126) -> Result<(), usize> {
1127    // if `Iterator::next` panics, this guard will drop already initialized items
1128    let mut guard = Guard { array_mut: buffer, initialized: 0 };
1129    while guard.initialized < guard.array_mut.len() {
1130        let Some(item) = iter.next() else {
1131            // Unlike `try_from_fn_erased`, we want to keep the partial results,
1132            // so we need to defuse the guard instead of using `?`.
1133            let initialized = guard.initialized;
1134            mem::forget(guard);
1135            return Err(initialized);
1136        };
1137
1138        // SAFETY: The loop condition ensures we have space to push the item
1139        unsafe { guard.push_unchecked(item) };
1140    }
1141
1142    mem::forget(guard);
1143    Ok(())
1144}
1145
1146/// Pulls `N` items from the back of `iter` and returns them as an array.
1147/// If the iterator yields fewer than `N` items, `Err` is returned containing
1148/// an iterator over the already yielded items.
1149///
1150/// Since the iterator is passed as a mutable reference and this function calls
1151/// `next_back` at most `N` times, the iterator can still be used afterwards to
1152/// retrieve the remaining items.
1153///
1154/// If `iter.next_back()` panics, all items already yielded by the iterator are
1155/// dropped.
1156///
1157/// Used for [`DoubleEndedIterator::next_chunk_back`].
1158#[inline]
1159pub(crate) fn iter_next_chunk_back<T, const N: usize>(
1160    iter: &mut impl DoubleEndedIterator<Item = T>,
1161) -> Result<[T; N], IntoIter<T, N>> {
1162    iter.spec_next_chunk_back()
1163}
1164
1165pub(crate) trait SpecNextChunkBack<T, const N: usize>:
1166    DoubleEndedIterator<Item = T>
1167{
1168    fn spec_next_chunk_back(&mut self) -> Result<[T; N], IntoIter<T, N>>;
1169}
1170
1171impl<I: DoubleEndedIterator<Item = T>, T, const N: usize> SpecNextChunkBack<T, N> for I {
1172    #[inline]
1173    default fn spec_next_chunk_back(&mut self) -> Result<[T; N], IntoIter<T, N>> {
1174        let mut array = [const { MaybeUninit::uninit() }; N];
1175        let r = iter_next_chunk_back_erased(&mut array, self);
1176        match r {
1177            Ok(()) => {
1178                // SAFETY: All elements of `array` were populated.
1179                Ok(unsafe { MaybeUninit::array_assume_init(array) })
1180            }
1181            Err(initialized) => {
1182                // SAFETY: Only the last `initialized` elements were populated
1183                Err(unsafe { IntoIter::new_unchecked(array, N - initialized..N) })
1184            }
1185        }
1186    }
1187}
1188
1189impl<I: DoubleEndedIterator<Item = T> + TrustedLen, T, const N: usize> SpecNextChunkBack<T, N>
1190    for I
1191{
1192    fn spec_next_chunk_back(&mut self) -> Result<[T; N], IntoIter<T, N>> {
1193        let len = (*self).size_hint().0;
1194        let mut array = [const { MaybeUninit::uninit() }; N];
1195        if len < N {
1196            // SAFETY: `TrustedLen`, an unsafe trait, requires that i can get len items out of it.
1197            unsafe { write_back(&mut array, self, len) };
1198            // SAFETY: Only the last `len` elements were populated
1199            Err(unsafe { IntoIter::new_unchecked(array, N - len..N) })
1200        } else {
1201            // SAFETY: `TrustedLen`, an unsafe trait, requires that i can get N items out of it.
1202            unsafe { write_back(&mut array, self, N) };
1203            // SAFETY: All N items were populated
1204            Ok(unsafe { MaybeUninit::array_assume_init(array) })
1205        }
1206    }
1207}
1208
1209// SAFETY: `from` must have len items, and len items must be < N.
1210unsafe fn write_back<T, const N: usize>(
1211    to: &mut [MaybeUninit<T>; N],
1212    from: &mut impl DoubleEndedIterator<Item = T>,
1213    len: usize,
1214) {
1215    let mut guard = GuardBack { array_mut: to, initialized: 0 };
1216    while guard.initialized < len {
1217        // SAFETY: caller has guaranteed, from has len items.
1218        let item = unsafe { from.next_back().unwrap_unchecked() };
1219        // SAFETY: guard.initialized < len < N
1220        unsafe { guard.push_unchecked(item) };
1221    }
1222    crate::mem::forget(guard);
1223}
1224
1225/// Version of [`iter_next_chunk_back`] using a passed-in slice
1226/// in order to avoid needing to monomorphize for every array length.
1227///
1228/// Unfortunately this loop has two exit conditions, the buffer filling up
1229/// or the iterator running out of items, making it tend to optimize poorly.
1230#[inline]
1231fn iter_next_chunk_back_erased<T>(
1232    buffer: &mut [MaybeUninit<T>],
1233    iter: &mut impl DoubleEndedIterator<Item = T>,
1234) -> Result<(), usize> {
1235    // if `Iterator::next_back` panics, this guard will drop already initialized items
1236    let mut guard = GuardBack { array_mut: buffer, initialized: 0 };
1237    while guard.initialized < guard.array_mut.len() {
1238        let Some(item) = iter.next_back() else {
1239            let initialized = guard.initialized;
1240            mem::forget(guard);
1241            return Err(initialized);
1242        };
1243
1244        // SAFETY: The loop condition ensures we have space to push the item
1245        unsafe { guard.push_unchecked(item) };
1246    }
1247
1248    mem::forget(guard);
1249    Ok(())
1250}