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