1 //! Utilities for the array primitive type.
3 //! *[See also the array primitive type](array).*
5 #![stable(feature = "core_array", since = "1.36.0")]
7 use crate::borrow::{Borrow, BorrowMut};
8 use crate::cmp::Ordering;
9 use crate::convert::{Infallible, TryFrom};
10 #[cfg(not(bootstrap))]
11 use crate::error::Error;
13 use crate::hash::{self, Hash};
14 use crate::iter::TrustedLen;
15 use crate::mem::{self, MaybeUninit};
17 ChangeOutputType, ControlFlow, FromResidual, Index, IndexMut, NeverShortCircuit, Residual, Try,
19 use crate::slice::{Iter, IterMut};
24 #[stable(feature = "array_value_iter", since = "1.51.0")]
25 pub use iter::IntoIter;
27 /// Creates an array `[T; N]` where each array element `T` is returned by the `cb` call.
31 /// * `cb`: Callback where the passed argument is the current array index.
36 /// let array = core::array::from_fn(|i| i);
37 /// assert_eq!(array, [0, 1, 2, 3, 4]);
40 #[stable(feature = "array_from_fn", since = "1.63.0")]
41 pub fn from_fn<T, const N: usize, F>(mut cb: F) -> [T; N]
53 /// Creates an array `[T; N]` where each fallible array element `T` is returned by the `cb` call.
54 /// Unlike [`from_fn`], where the element creation can't fail, this version will return an error
55 /// if any element creation was unsuccessful.
57 /// The return type of this function depends on the return type of the closure.
58 /// If you return `Result<T, E>` from the closure, you'll get a `Result<[T; N]; E>`.
59 /// If you return `Option<T>` from the closure, you'll get an `Option<[T; N]>`.
63 /// * `cb`: Callback where the passed argument is the current array index.
68 /// #![feature(array_try_from_fn)]
70 /// let array: Result<[u8; 5], _> = std::array::try_from_fn(|i| i.try_into());
71 /// assert_eq!(array, Ok([0, 1, 2, 3, 4]));
73 /// let array: Result<[i8; 200], _> = std::array::try_from_fn(|i| i.try_into());
74 /// assert!(array.is_err());
76 /// let array: Option<[_; 4]> = std::array::try_from_fn(|i| i.checked_add(100));
77 /// assert_eq!(array, Some([100, 101, 102, 103]));
79 /// let array: Option<[_; 4]> = std::array::try_from_fn(|i| i.checked_sub(100));
80 /// assert_eq!(array, None);
83 #[unstable(feature = "array_try_from_fn", issue = "89379")]
84 pub fn try_from_fn<R, const N: usize, F>(cb: F) -> ChangeOutputType<R, [R::Output; N]>
88 R::Residual: Residual<[R::Output; N]>,
90 // SAFETY: we know for certain that this iterator will yield exactly `N`
92 unsafe { try_collect_into_array_unchecked(&mut (0..N).map(cb)) }
95 /// Converts a reference to `T` into a reference to an array of length 1 (without copying).
96 #[stable(feature = "array_from_ref", since = "1.53.0")]
97 #[rustc_const_stable(feature = "const_array_from_ref_shared", since = "1.63.0")]
98 pub const fn from_ref<T>(s: &T) -> &[T; 1] {
99 // SAFETY: Converting `&T` to `&[T; 1]` is sound.
100 unsafe { &*(s as *const T).cast::<[T; 1]>() }
103 /// Converts a mutable reference to `T` into a mutable reference to an array of length 1 (without copying).
104 #[stable(feature = "array_from_ref", since = "1.53.0")]
105 #[rustc_const_unstable(feature = "const_array_from_ref", issue = "90206")]
106 pub const fn from_mut<T>(s: &mut T) -> &mut [T; 1] {
107 // SAFETY: Converting `&mut T` to `&mut [T; 1]` is sound.
108 unsafe { &mut *(s as *mut T).cast::<[T; 1]>() }
111 /// The error type returned when a conversion from a slice to an array fails.
112 #[stable(feature = "try_from", since = "1.34.0")]
113 #[derive(Debug, Copy, Clone)]
114 pub struct TryFromSliceError(());
116 #[stable(feature = "core_array", since = "1.36.0")]
117 impl fmt::Display for TryFromSliceError {
119 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120 fmt::Display::fmt(self.__description(), f)
124 #[cfg(not(bootstrap))]
125 #[stable(feature = "try_from", since = "1.34.0")]
126 impl Error for TryFromSliceError {
128 fn description(&self) -> &str {
133 impl TryFromSliceError {
135 feature = "array_error_internals",
136 reason = "available through Error trait and this method should not \
137 be exposed publicly",
142 pub fn __description(&self) -> &str {
143 "could not convert slice to array"
147 #[stable(feature = "try_from_slice_error", since = "1.36.0")]
148 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
149 impl const From<Infallible> for TryFromSliceError {
150 fn from(x: Infallible) -> TryFromSliceError {
155 #[stable(feature = "rust1", since = "1.0.0")]
156 impl<T, const N: usize> AsRef<[T]> for [T; N] {
158 fn as_ref(&self) -> &[T] {
163 #[stable(feature = "rust1", since = "1.0.0")]
164 impl<T, const N: usize> AsMut<[T]> for [T; N] {
166 fn as_mut(&mut self) -> &mut [T] {
171 #[stable(feature = "array_borrow", since = "1.4.0")]
172 #[rustc_const_unstable(feature = "const_borrow", issue = "91522")]
173 impl<T, const N: usize> const Borrow<[T]> for [T; N] {
174 fn borrow(&self) -> &[T] {
179 #[stable(feature = "array_borrow", since = "1.4.0")]
180 #[rustc_const_unstable(feature = "const_borrow", issue = "91522")]
181 impl<T, const N: usize> const BorrowMut<[T]> for [T; N] {
182 fn borrow_mut(&mut self) -> &mut [T] {
187 #[stable(feature = "try_from", since = "1.34.0")]
188 impl<T, const N: usize> TryFrom<&[T]> for [T; N]
192 type Error = TryFromSliceError;
194 fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError> {
195 <&Self>::try_from(slice).map(|r| *r)
199 #[stable(feature = "try_from_mut_slice_to_array", since = "1.59.0")]
200 impl<T, const N: usize> TryFrom<&mut [T]> for [T; N]
204 type Error = TryFromSliceError;
206 fn try_from(slice: &mut [T]) -> Result<[T; N], TryFromSliceError> {
207 <Self>::try_from(&*slice)
211 #[stable(feature = "try_from", since = "1.34.0")]
212 impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N] {
213 type Error = TryFromSliceError;
215 fn try_from(slice: &[T]) -> Result<&[T; N], TryFromSliceError> {
216 if slice.len() == N {
217 let ptr = slice.as_ptr() as *const [T; N];
218 // SAFETY: ok because we just checked that the length fits
221 Err(TryFromSliceError(()))
226 #[stable(feature = "try_from", since = "1.34.0")]
227 impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N] {
228 type Error = TryFromSliceError;
230 fn try_from(slice: &mut [T]) -> Result<&mut [T; N], TryFromSliceError> {
231 if slice.len() == N {
232 let ptr = slice.as_mut_ptr() as *mut [T; N];
233 // SAFETY: ok because we just checked that the length fits
234 unsafe { Ok(&mut *ptr) }
236 Err(TryFromSliceError(()))
241 /// The hash of an array is the same as that of the corresponding slice,
242 /// as required by the `Borrow` implementation.
245 /// #![feature(build_hasher_simple_hash_one)]
246 /// use std::hash::BuildHasher;
248 /// let b = std::collections::hash_map::RandomState::new();
249 /// let a: [u8; 3] = [0xa8, 0x3c, 0x09];
250 /// let s: &[u8] = &[0xa8, 0x3c, 0x09];
251 /// assert_eq!(b.hash_one(a), b.hash_one(s));
253 #[stable(feature = "rust1", since = "1.0.0")]
254 impl<T: Hash, const N: usize> Hash for [T; N] {
255 fn hash<H: hash::Hasher>(&self, state: &mut H) {
256 Hash::hash(&self[..], state)
260 #[stable(feature = "rust1", since = "1.0.0")]
261 impl<T: fmt::Debug, const N: usize> fmt::Debug for [T; N] {
262 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263 fmt::Debug::fmt(&&self[..], f)
267 #[stable(feature = "rust1", since = "1.0.0")]
268 impl<'a, T, const N: usize> IntoIterator for &'a [T; N] {
270 type IntoIter = Iter<'a, T>;
272 fn into_iter(self) -> Iter<'a, T> {
277 #[stable(feature = "rust1", since = "1.0.0")]
278 impl<'a, T, const N: usize> IntoIterator for &'a mut [T; N] {
279 type Item = &'a mut T;
280 type IntoIter = IterMut<'a, T>;
282 fn into_iter(self) -> IterMut<'a, T> {
287 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
288 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
289 impl<T, I, const N: usize> const Index<I> for [T; N]
291 [T]: ~const Index<I>,
293 type Output = <[T] as Index<I>>::Output;
296 fn index(&self, index: I) -> &Self::Output {
297 Index::index(self as &[T], index)
301 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
302 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
303 impl<T, I, const N: usize> const IndexMut<I> for [T; N]
305 [T]: ~const IndexMut<I>,
308 fn index_mut(&mut self, index: I) -> &mut Self::Output {
309 IndexMut::index_mut(self as &mut [T], index)
313 #[stable(feature = "rust1", since = "1.0.0")]
314 impl<T: PartialOrd, const N: usize> PartialOrd for [T; N] {
316 fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
317 PartialOrd::partial_cmp(&&self[..], &&other[..])
320 fn lt(&self, other: &[T; N]) -> bool {
321 PartialOrd::lt(&&self[..], &&other[..])
324 fn le(&self, other: &[T; N]) -> bool {
325 PartialOrd::le(&&self[..], &&other[..])
328 fn ge(&self, other: &[T; N]) -> bool {
329 PartialOrd::ge(&&self[..], &&other[..])
332 fn gt(&self, other: &[T; N]) -> bool {
333 PartialOrd::gt(&&self[..], &&other[..])
337 /// Implements comparison of arrays [lexicographically](Ord#lexicographical-comparison).
338 #[stable(feature = "rust1", since = "1.0.0")]
339 impl<T: Ord, const N: usize> Ord for [T; N] {
341 fn cmp(&self, other: &[T; N]) -> Ordering {
342 Ord::cmp(&&self[..], &&other[..])
346 #[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
347 impl<T: Copy, const N: usize> Copy for [T; N] {}
349 #[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
350 impl<T: Clone, const N: usize> Clone for [T; N] {
352 fn clone(&self) -> Self {
353 SpecArrayClone::clone(self)
357 fn clone_from(&mut self, other: &Self) {
358 self.clone_from_slice(other);
362 trait SpecArrayClone: Clone {
363 fn clone<const N: usize>(array: &[Self; N]) -> [Self; N];
366 impl<T: Clone> SpecArrayClone for T {
368 default fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
369 // SAFETY: we know for certain that this iterator will yield exactly `N`
371 unsafe { collect_into_array_unchecked(&mut array.iter().cloned()) }
375 impl<T: Copy> SpecArrayClone for T {
377 fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
382 // The Default impls cannot be done with const generics because `[T; 0]` doesn't
383 // require Default to be implemented, and having different impl blocks for
384 // different numbers isn't supported yet.
386 macro_rules! array_impl_default {
387 {$n:expr, $t:ident $($ts:ident)*} => {
388 #[stable(since = "1.4.0", feature = "array_default")]
389 impl<T> Default for [T; $n] where T: Default {
390 fn default() -> [T; $n] {
391 [$t::default(), $($ts::default()),*]
394 array_impl_default!{($n - 1), $($ts)*}
397 #[stable(since = "1.4.0", feature = "array_default")]
398 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
399 impl<T> const Default for [T; $n] {
400 fn default() -> [T; $n] { [] }
405 array_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}
407 impl<T, const N: usize> [T; N] {
408 /// Returns an array of the same size as `self`, with function `f` applied to each element
411 /// If you don't necessarily need a new fixed-size array, consider using
412 /// [`Iterator::map`] instead.
415 /// # Note on performance and stack usage
417 /// Unfortunately, usages of this method are currently not always optimized
418 /// as well as they could be. This mainly concerns large arrays, as mapping
419 /// over small arrays seem to be optimized just fine. Also note that in
420 /// debug mode (i.e. without any optimizations), this method can use a lot
421 /// of stack space (a few times the size of the array or more).
423 /// Therefore, in performance-critical code, try to avoid using this method
424 /// on large arrays or check the emitted code. Also try to avoid chained
425 /// maps (e.g. `arr.map(...).map(...)`).
427 /// In many cases, you can instead use [`Iterator::map`] by calling `.iter()`
428 /// or `.into_iter()` on your array. `[T; N]::map` is only necessary if you
429 /// really need a new array of the same size as the result. Rust's lazy
430 /// iterators tend to get optimized very well.
436 /// let x = [1, 2, 3];
437 /// let y = x.map(|v| v + 1);
438 /// assert_eq!(y, [2, 3, 4]);
440 /// let x = [1, 2, 3];
441 /// let mut temp = 0;
442 /// let y = x.map(|v| { temp += 1; v * temp });
443 /// assert_eq!(y, [1, 4, 9]);
445 /// let x = ["Ferris", "Bueller's", "Day", "Off"];
446 /// let y = x.map(|v| v.len());
447 /// assert_eq!(y, [6, 9, 3, 3]);
449 #[stable(feature = "array_map", since = "1.55.0")]
450 pub fn map<F, U>(self, f: F) -> [U; N]
454 // SAFETY: we know for certain that this iterator will yield exactly `N`
456 unsafe { collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
459 /// A fallible function `f` applied to each element on array `self` in order to
460 /// return an array the same size as `self` or the first error encountered.
462 /// The return type of this function depends on the return type of the closure.
463 /// If you return `Result<T, E>` from the closure, you'll get a `Result<[T; N]; E>`.
464 /// If you return `Option<T>` from the closure, you'll get an `Option<[T; N]>`.
469 /// #![feature(array_try_map)]
470 /// let a = ["1", "2", "3"];
471 /// let b = a.try_map(|v| v.parse::<u32>()).unwrap().map(|v| v + 1);
472 /// assert_eq!(b, [2, 3, 4]);
474 /// let a = ["1", "2a", "3"];
475 /// let b = a.try_map(|v| v.parse::<u32>());
476 /// assert!(b.is_err());
478 /// use std::num::NonZeroU32;
479 /// let z = [1, 2, 0, 3, 4];
480 /// assert_eq!(z.try_map(NonZeroU32::new), None);
481 /// let a = [1, 2, 3];
482 /// let b = a.try_map(NonZeroU32::new);
483 /// let c = b.map(|x| x.map(NonZeroU32::get));
484 /// assert_eq!(c, Some(a));
486 #[unstable(feature = "array_try_map", issue = "79711")]
487 pub fn try_map<F, R>(self, f: F) -> ChangeOutputType<R, [R::Output; N]>
491 R::Residual: Residual<[R::Output; N]>,
493 // SAFETY: we know for certain that this iterator will yield exactly `N`
495 unsafe { try_collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
498 /// 'Zips up' two arrays into a single array of pairs.
500 /// `zip()` returns a new array where every element is a tuple where the
501 /// first element comes from the first array, and the second element comes
502 /// from the second array. In other words, it zips two arrays together,
503 /// into a single one.
508 /// #![feature(array_zip)]
509 /// let x = [1, 2, 3];
510 /// let y = [4, 5, 6];
511 /// let z = x.zip(y);
512 /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
514 #[unstable(feature = "array_zip", issue = "80094")]
515 pub fn zip<U>(self, rhs: [U; N]) -> [(T, U); N] {
516 let mut iter = IntoIterator::into_iter(self).zip(rhs);
518 // SAFETY: we know for certain that this iterator will yield exactly `N`
520 unsafe { collect_into_array_unchecked(&mut iter) }
523 /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
524 #[stable(feature = "array_as_slice", since = "1.57.0")]
525 #[rustc_const_stable(feature = "array_as_slice", since = "1.57.0")]
526 pub const fn as_slice(&self) -> &[T] {
530 /// Returns a mutable slice containing the entire array. Equivalent to
532 #[stable(feature = "array_as_slice", since = "1.57.0")]
533 pub fn as_mut_slice(&mut self) -> &mut [T] {
537 /// Borrows each element and returns an array of references with the same
544 /// #![feature(array_methods)]
546 /// let floats = [3.1, 2.7, -1.0];
547 /// let float_refs: [&f64; 3] = floats.each_ref();
548 /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
551 /// This method is particularly useful if combined with other methods, like
552 /// [`map`](#method.map). This way, you can avoid moving the original
553 /// array if its elements are not [`Copy`].
556 /// #![feature(array_methods)]
558 /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
559 /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
560 /// assert_eq!(is_ascii, [true, false, true]);
562 /// // We can still access the original array: it has not been moved.
563 /// assert_eq!(strings.len(), 3);
565 #[unstable(feature = "array_methods", issue = "76118")]
566 pub fn each_ref(&self) -> [&T; N] {
567 // SAFETY: we know for certain that this iterator will yield exactly `N`
569 unsafe { collect_into_array_unchecked(&mut self.iter()) }
572 /// Borrows each element mutably and returns an array of mutable references
573 /// with the same size as `self`.
579 /// #![feature(array_methods)]
581 /// let mut floats = [3.1, 2.7, -1.0];
582 /// let float_refs: [&mut f64; 3] = floats.each_mut();
583 /// *float_refs[0] = 0.0;
584 /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
585 /// assert_eq!(floats, [0.0, 2.7, -1.0]);
587 #[unstable(feature = "array_methods", issue = "76118")]
588 pub fn each_mut(&mut self) -> [&mut T; N] {
589 // SAFETY: we know for certain that this iterator will yield exactly `N`
591 unsafe { collect_into_array_unchecked(&mut self.iter_mut()) }
594 /// Divides one array reference into two at an index.
596 /// The first will contain all indices from `[0, M)` (excluding
597 /// the index `M` itself) and the second will contain all
598 /// indices from `[M, N)` (excluding the index `N` itself).
602 /// Panics if `M > N`.
607 /// #![feature(split_array)]
609 /// let v = [1, 2, 3, 4, 5, 6];
612 /// let (left, right) = v.split_array_ref::<0>();
613 /// assert_eq!(left, &[]);
614 /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
618 /// let (left, right) = v.split_array_ref::<2>();
619 /// assert_eq!(left, &[1, 2]);
620 /// assert_eq!(right, &[3, 4, 5, 6]);
624 /// let (left, right) = v.split_array_ref::<6>();
625 /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
626 /// assert_eq!(right, &[]);
630 feature = "split_array",
631 reason = "return type should have array as 2nd element",
635 pub fn split_array_ref<const M: usize>(&self) -> (&[T; M], &[T]) {
636 (&self[..]).split_array_ref::<M>()
639 /// Divides one mutable array reference into two at an index.
641 /// The first will contain all indices from `[0, M)` (excluding
642 /// the index `M` itself) and the second will contain all
643 /// indices from `[M, N)` (excluding the index `N` itself).
647 /// Panics if `M > N`.
652 /// #![feature(split_array)]
654 /// let mut v = [1, 0, 3, 0, 5, 6];
655 /// let (left, right) = v.split_array_mut::<2>();
656 /// assert_eq!(left, &mut [1, 0][..]);
657 /// assert_eq!(right, &mut [3, 0, 5, 6]);
660 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
663 feature = "split_array",
664 reason = "return type should have array as 2nd element",
668 pub fn split_array_mut<const M: usize>(&mut self) -> (&mut [T; M], &mut [T]) {
669 (&mut self[..]).split_array_mut::<M>()
672 /// Divides one array reference into two at an index from the end.
674 /// The first will contain all indices from `[0, N - M)` (excluding
675 /// the index `N - M` itself) and the second will contain all
676 /// indices from `[N - M, N)` (excluding the index `N` itself).
680 /// Panics if `M > N`.
685 /// #![feature(split_array)]
687 /// let v = [1, 2, 3, 4, 5, 6];
690 /// let (left, right) = v.rsplit_array_ref::<0>();
691 /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
692 /// assert_eq!(right, &[]);
696 /// let (left, right) = v.rsplit_array_ref::<2>();
697 /// assert_eq!(left, &[1, 2, 3, 4]);
698 /// assert_eq!(right, &[5, 6]);
702 /// let (left, right) = v.rsplit_array_ref::<6>();
703 /// assert_eq!(left, &[]);
704 /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
708 feature = "split_array",
709 reason = "return type should have array as 2nd element",
713 pub fn rsplit_array_ref<const M: usize>(&self) -> (&[T], &[T; M]) {
714 (&self[..]).rsplit_array_ref::<M>()
717 /// Divides one mutable array reference into two at an index from the end.
719 /// The first will contain all indices from `[0, N - M)` (excluding
720 /// the index `N - M` itself) and the second will contain all
721 /// indices from `[N - M, N)` (excluding the index `N` itself).
725 /// Panics if `M > N`.
730 /// #![feature(split_array)]
732 /// let mut v = [1, 0, 3, 0, 5, 6];
733 /// let (left, right) = v.rsplit_array_mut::<4>();
734 /// assert_eq!(left, &mut [1, 0]);
735 /// assert_eq!(right, &mut [3, 0, 5, 6][..]);
738 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
741 feature = "split_array",
742 reason = "return type should have array as 2nd element",
746 pub fn rsplit_array_mut<const M: usize>(&mut self) -> (&mut [T], &mut [T; M]) {
747 (&mut self[..]).rsplit_array_mut::<M>()
751 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
752 /// yields fewer than `N` items, this function exhibits undefined behavior.
754 /// See [`try_collect_into_array`] for more information.
759 /// It is up to the caller to guarantee that `iter` yields at least `N` items.
760 /// Violating this condition causes undefined behavior.
761 unsafe fn try_collect_into_array_unchecked<I, T, R, const N: usize>(iter: &mut I) -> R::TryType
763 // Note: `TrustedLen` here is somewhat of an experiment. This is just an
764 // internal function, so feel free to remove if this bound turns out to be a
765 // bad idea. In that case, remember to also remove the lower bound
766 // `debug_assert!` below!
767 I: Iterator + TrustedLen,
768 I::Item: Try<Output = T, Residual = R>,
771 debug_assert!(N <= iter.size_hint().1.unwrap_or(usize::MAX));
772 debug_assert!(N <= iter.size_hint().0);
774 // SAFETY: covered by the function contract.
775 unsafe { try_collect_into_array(iter).unwrap_unchecked() }
778 // Infallible version of `try_collect_into_array_unchecked`.
779 unsafe fn collect_into_array_unchecked<I, const N: usize>(iter: &mut I) -> [I::Item; N]
781 I: Iterator + TrustedLen,
783 let mut map = iter.map(NeverShortCircuit);
785 // SAFETY: The same safety considerations w.r.t. the iterator length
786 // apply for `try_collect_into_array_unchecked` as for
787 // `collect_into_array_unchecked`
788 match unsafe { try_collect_into_array_unchecked(&mut map) } {
789 NeverShortCircuit(array) => array,
793 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
794 /// yields fewer than `N` items, `Err` is returned containing an iterator over
795 /// the already yielded items.
797 /// Since the iterator is passed as a mutable reference and this function calls
798 /// `next` at most `N` times, the iterator can still be used afterwards to
799 /// retrieve the remaining items.
801 /// If `iter.next()` panicks, all items already yielded by the iterator are
804 fn try_collect_into_array<I, T, R, const N: usize>(
806 ) -> Result<R::TryType, IntoIter<T, N>>
809 I::Item: Try<Output = T, Residual = R>,
813 // SAFETY: An empty array is always inhabited and has no validity invariants.
814 return Ok(Try::from_output(unsafe { mem::zeroed() }));
817 struct Guard<'a, T, const N: usize> {
818 array_mut: &'a mut [MaybeUninit<T>; N],
822 impl<T, const N: usize> Drop for Guard<'_, T, N> {
824 debug_assert!(self.initialized <= N);
826 // SAFETY: this slice will contain only initialized objects.
828 crate::ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(
829 &mut self.array_mut.get_unchecked_mut(..self.initialized),
835 let mut array = MaybeUninit::uninit_array::<N>();
836 let mut guard = Guard { array_mut: &mut array, initialized: 0 };
841 let item = match item_rslt.branch() {
842 ControlFlow::Break(r) => {
843 return Ok(FromResidual::from_residual(r));
845 ControlFlow::Continue(elem) => elem,
848 // SAFETY: `guard.initialized` starts at 0, is increased by one in the
849 // loop and the loop is aborted once it reaches N (which is
852 guard.array_mut.get_unchecked_mut(guard.initialized).write(item);
854 guard.initialized += 1;
857 let alive = 0..guard.initialized;
859 // SAFETY: `array` was initialized with exactly `initialized`
860 // number of elements.
861 return Err(unsafe { IntoIter::new_unchecked(array, alive) });
867 // SAFETY: All elements of the array were populated in the loop above.
868 let output = unsafe { MaybeUninit::array_assume_init(array) };
869 Ok(Try::from_output(output))
872 /// Returns the next chunk of `N` items from the iterator or errors with an
873 /// iterator over the remainder. Used for `Iterator::next_chunk`.
875 pub(crate) fn iter_next_chunk<I, const N: usize>(
877 ) -> Result<[I::Item; N], IntoIter<I::Item, N>>
881 let mut map = iter.map(NeverShortCircuit);
882 try_collect_into_array(&mut map).map(|NeverShortCircuit(arr)| arr)