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