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