1 //! Helper functions and types for fixed-length arrays.
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};
11 use crate::hash::{self, Hash};
12 use crate::iter::TrustedLen;
13 use crate::mem::{self, MaybeUninit};
15 ChangeOutputType, ControlFlow, FromResidual, Index, IndexMut, NeverShortCircuit, Residual, Try,
17 use crate::slice::{Iter, IterMut};
22 #[stable(feature = "array_value_iter", since = "1.51.0")]
23 pub use iter::IntoIter;
25 /// Creates an array `[T; N]` where each array element `T` is returned by the `cb` call.
29 /// * `cb`: Callback where the passed argument is the current array index.
34 /// #![feature(array_from_fn)]
36 /// let array = core::array::from_fn(|i| i);
37 /// assert_eq!(array, [0, 1, 2, 3, 4]);
40 #[unstable(feature = "array_from_fn", issue = "89379")]
41 pub fn from_fn<F, T, const N: usize>(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_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_from_fn", issue = "89379")]
84 pub fn try_from_fn<F, R, const N: usize>(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_unstable(feature = "const_array_from_ref", issue = "90206")]
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 impl TryFromSliceError {
126 feature = "array_error_internals",
127 reason = "available through Error trait and this method should not \
128 be exposed publicly",
133 pub fn __description(&self) -> &str {
134 "could not convert slice to array"
138 #[stable(feature = "try_from_slice_error", since = "1.36.0")]
139 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
140 impl const From<Infallible> for TryFromSliceError {
141 fn from(x: Infallible) -> TryFromSliceError {
146 #[stable(feature = "rust1", since = "1.0.0")]
147 impl<T, const N: usize> AsRef<[T]> for [T; N] {
149 fn as_ref(&self) -> &[T] {
154 #[stable(feature = "rust1", since = "1.0.0")]
155 impl<T, const N: usize> AsMut<[T]> for [T; N] {
157 fn as_mut(&mut self) -> &mut [T] {
162 #[stable(feature = "array_borrow", since = "1.4.0")]
163 #[rustc_const_unstable(feature = "const_borrow", issue = "91522")]
164 impl<T, const N: usize> const Borrow<[T]> for [T; N] {
165 fn borrow(&self) -> &[T] {
170 #[stable(feature = "array_borrow", since = "1.4.0")]
171 #[rustc_const_unstable(feature = "const_borrow", issue = "91522")]
172 impl<T, const N: usize> const BorrowMut<[T]> for [T; N] {
173 fn borrow_mut(&mut self) -> &mut [T] {
178 #[stable(feature = "try_from", since = "1.34.0")]
179 impl<T, const N: usize> TryFrom<&[T]> for [T; N]
183 type Error = TryFromSliceError;
185 fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError> {
186 <&Self>::try_from(slice).map(|r| *r)
190 #[stable(feature = "try_from_mut_slice_to_array", since = "1.59.0")]
191 impl<T, const N: usize> TryFrom<&mut [T]> for [T; N]
195 type Error = TryFromSliceError;
197 fn try_from(slice: &mut [T]) -> Result<[T; N], TryFromSliceError> {
198 <Self>::try_from(&*slice)
202 #[stable(feature = "try_from", since = "1.34.0")]
203 impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N] {
204 type Error = TryFromSliceError;
206 fn try_from(slice: &[T]) -> Result<&[T; N], TryFromSliceError> {
207 if slice.len() == N {
208 let ptr = slice.as_ptr() as *const [T; N];
209 // SAFETY: ok because we just checked that the length fits
212 Err(TryFromSliceError(()))
217 #[stable(feature = "try_from", since = "1.34.0")]
218 impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N] {
219 type Error = TryFromSliceError;
221 fn try_from(slice: &mut [T]) -> Result<&mut [T; N], TryFromSliceError> {
222 if slice.len() == N {
223 let ptr = slice.as_mut_ptr() as *mut [T; N];
224 // SAFETY: ok because we just checked that the length fits
225 unsafe { Ok(&mut *ptr) }
227 Err(TryFromSliceError(()))
232 /// The hash of an array is the same as that of the corresponding slice,
233 /// as required by the `Borrow` implementation.
236 /// #![feature(build_hasher_simple_hash_one)]
237 /// use std::hash::BuildHasher;
239 /// let b = std::collections::hash_map::RandomState::new();
240 /// let a: [u8; 3] = [0xa8, 0x3c, 0x09];
241 /// let s: &[u8] = &[0xa8, 0x3c, 0x09];
242 /// assert_eq!(b.hash_one(a), b.hash_one(s));
244 #[stable(feature = "rust1", since = "1.0.0")]
245 impl<T: Hash, const N: usize> Hash for [T; N] {
246 fn hash<H: hash::Hasher>(&self, state: &mut H) {
247 Hash::hash(&self[..], state)
251 #[stable(feature = "rust1", since = "1.0.0")]
252 impl<T: fmt::Debug, const N: usize> fmt::Debug for [T; N] {
253 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254 fmt::Debug::fmt(&&self[..], f)
258 #[stable(feature = "rust1", since = "1.0.0")]
259 impl<'a, T, const N: usize> IntoIterator for &'a [T; N] {
261 type IntoIter = Iter<'a, T>;
263 fn into_iter(self) -> Iter<'a, T> {
268 #[stable(feature = "rust1", since = "1.0.0")]
269 impl<'a, T, const N: usize> IntoIterator for &'a mut [T; N] {
270 type Item = &'a mut T;
271 type IntoIter = IterMut<'a, T>;
273 fn into_iter(self) -> IterMut<'a, T> {
278 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
279 impl<T, I, const N: usize> Index<I> for [T; N]
283 type Output = <[T] as Index<I>>::Output;
286 fn index(&self, index: I) -> &Self::Output {
287 Index::index(self as &[T], index)
291 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
292 impl<T, I, const N: usize> IndexMut<I> for [T; N]
297 fn index_mut(&mut self, index: I) -> &mut Self::Output {
298 IndexMut::index_mut(self as &mut [T], index)
302 #[stable(feature = "rust1", since = "1.0.0")]
303 impl<T: PartialOrd, const N: usize> PartialOrd for [T; N] {
305 fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
306 PartialOrd::partial_cmp(&&self[..], &&other[..])
309 fn lt(&self, other: &[T; N]) -> bool {
310 PartialOrd::lt(&&self[..], &&other[..])
313 fn le(&self, other: &[T; N]) -> bool {
314 PartialOrd::le(&&self[..], &&other[..])
317 fn ge(&self, other: &[T; N]) -> bool {
318 PartialOrd::ge(&&self[..], &&other[..])
321 fn gt(&self, other: &[T; N]) -> bool {
322 PartialOrd::gt(&&self[..], &&other[..])
326 /// Implements comparison of arrays [lexicographically](Ord#lexicographical-comparison).
327 #[stable(feature = "rust1", since = "1.0.0")]
328 impl<T: Ord, const N: usize> Ord for [T; N] {
330 fn cmp(&self, other: &[T; N]) -> Ordering {
331 Ord::cmp(&&self[..], &&other[..])
335 #[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
336 impl<T: Copy, const N: usize> Copy for [T; N] {}
338 #[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
339 impl<T: Clone, const N: usize> Clone for [T; N] {
341 fn clone(&self) -> Self {
342 SpecArrayClone::clone(self)
346 fn clone_from(&mut self, other: &Self) {
347 self.clone_from_slice(other);
351 trait SpecArrayClone: Clone {
352 fn clone<const N: usize>(array: &[Self; N]) -> [Self; N];
355 impl<T: Clone> SpecArrayClone for T {
357 default fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
358 // SAFETY: we know for certain that this iterator will yield exactly `N`
360 unsafe { collect_into_array_unchecked(&mut array.iter().cloned()) }
364 impl<T: Copy> SpecArrayClone for T {
366 fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
371 // The Default impls cannot be done with const generics because `[T; 0]` doesn't
372 // require Default to be implemented, and having different impl blocks for
373 // different numbers isn't supported yet.
375 macro_rules! array_impl_default {
376 {$n:expr, $t:ident $($ts:ident)*} => {
377 #[stable(since = "1.4.0", feature = "array_default")]
378 impl<T> Default for [T; $n] where T: Default {
379 fn default() -> [T; $n] {
380 [$t::default(), $($ts::default()),*]
383 array_impl_default!{($n - 1), $($ts)*}
386 #[stable(since = "1.4.0", feature = "array_default")]
387 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
388 impl<T> const Default for [T; $n] {
389 fn default() -> [T; $n] { [] }
394 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}
397 impl<T, const N: usize> [T; N] {
398 /// Returns an array of the same size as `self`, with function `f` applied to each element
401 /// If you don't necessarily need a new fixed-size array, consider using
402 /// [`Iterator::map`] instead.
405 /// # Note on performance and stack usage
407 /// Unfortunately, usages of this method are currently not always optimized
408 /// as well as they could be. This mainly concerns large arrays, as mapping
409 /// over small arrays seem to be optimized just fine. Also note that in
410 /// debug mode (i.e. without any optimizations), this method can use a lot
411 /// of stack space (a few times the size of the array or more).
413 /// Therefore, in performance-critical code, try to avoid using this method
414 /// on large arrays or check the emitted code. Also try to avoid chained
415 /// maps (e.g. `arr.map(...).map(...)`).
417 /// In many cases, you can instead use [`Iterator::map`] by calling `.iter()`
418 /// or `.into_iter()` on your array. `[T; N]::map` is only necessary if you
419 /// really need a new array of the same size as the result. Rust's lazy
420 /// iterators tend to get optimized very well.
426 /// let x = [1, 2, 3];
427 /// let y = x.map(|v| v + 1);
428 /// assert_eq!(y, [2, 3, 4]);
430 /// let x = [1, 2, 3];
431 /// let mut temp = 0;
432 /// let y = x.map(|v| { temp += 1; v * temp });
433 /// assert_eq!(y, [1, 4, 9]);
435 /// let x = ["Ferris", "Bueller's", "Day", "Off"];
436 /// let y = x.map(|v| v.len());
437 /// assert_eq!(y, [6, 9, 3, 3]);
439 #[stable(feature = "array_map", since = "1.55.0")]
440 pub fn map<F, U>(self, f: F) -> [U; N]
444 // SAFETY: we know for certain that this iterator will yield exactly `N`
446 unsafe { collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
449 /// A fallible function `f` applied to each element on array `self` in order to
450 /// return an array the same size as `self` or the first error encountered.
452 /// The return type of this function depends on the return type of the closure.
453 /// If you return `Result<T, E>` from the closure, you'll get a `Result<[T; N]; E>`.
454 /// If you return `Option<T>` from the closure, you'll get an `Option<[T; N]>`.
459 /// #![feature(array_try_map)]
460 /// let a = ["1", "2", "3"];
461 /// let b = a.try_map(|v| v.parse::<u32>()).unwrap().map(|v| v + 1);
462 /// assert_eq!(b, [2, 3, 4]);
464 /// let a = ["1", "2a", "3"];
465 /// let b = a.try_map(|v| v.parse::<u32>());
466 /// assert!(b.is_err());
468 /// use std::num::NonZeroU32;
469 /// let z = [1, 2, 0, 3, 4];
470 /// assert_eq!(z.try_map(NonZeroU32::new), None);
471 /// let a = [1, 2, 3];
472 /// let b = a.try_map(NonZeroU32::new);
473 /// let c = b.map(|x| x.map(NonZeroU32::get));
474 /// assert_eq!(c, Some(a));
476 #[unstable(feature = "array_try_map", issue = "79711")]
477 pub fn try_map<F, R>(self, f: F) -> ChangeOutputType<R, [R::Output; N]>
481 R::Residual: Residual<[R::Output; N]>,
483 // SAFETY: we know for certain that this iterator will yield exactly `N`
485 unsafe { try_collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
488 /// 'Zips up' two arrays into a single array of pairs.
490 /// `zip()` returns a new array where every element is a tuple where the
491 /// first element comes from the first array, and the second element comes
492 /// from the second array. In other words, it zips two arrays together,
493 /// into a single one.
498 /// #![feature(array_zip)]
499 /// let x = [1, 2, 3];
500 /// let y = [4, 5, 6];
501 /// let z = x.zip(y);
502 /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
504 #[unstable(feature = "array_zip", issue = "80094")]
505 pub fn zip<U>(self, rhs: [U; N]) -> [(T, U); N] {
506 let mut iter = IntoIterator::into_iter(self).zip(rhs);
508 // SAFETY: we know for certain that this iterator will yield exactly `N`
510 unsafe { collect_into_array_unchecked(&mut iter) }
513 /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
514 #[stable(feature = "array_as_slice", since = "1.57.0")]
515 #[rustc_const_stable(feature = "array_as_slice", since = "1.57.0")]
516 pub const fn as_slice(&self) -> &[T] {
520 /// Returns a mutable slice containing the entire array. Equivalent to
522 #[stable(feature = "array_as_slice", since = "1.57.0")]
523 pub fn as_mut_slice(&mut self) -> &mut [T] {
527 /// Borrows each element and returns an array of references with the same
534 /// #![feature(array_methods)]
536 /// let floats = [3.1, 2.7, -1.0];
537 /// let float_refs: [&f64; 3] = floats.each_ref();
538 /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
541 /// This method is particularly useful if combined with other methods, like
542 /// [`map`](#method.map). This way, you can avoid moving the original
543 /// array if its elements are not [`Copy`].
546 /// #![feature(array_methods)]
548 /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
549 /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
550 /// assert_eq!(is_ascii, [true, false, true]);
552 /// // We can still access the original array: it has not been moved.
553 /// assert_eq!(strings.len(), 3);
555 #[unstable(feature = "array_methods", issue = "76118")]
556 pub fn each_ref(&self) -> [&T; N] {
557 // SAFETY: we know for certain that this iterator will yield exactly `N`
559 unsafe { collect_into_array_unchecked(&mut self.iter()) }
562 /// Borrows each element mutably and returns an array of mutable references
563 /// with the same size as `self`.
569 /// #![feature(array_methods)]
571 /// let mut floats = [3.1, 2.7, -1.0];
572 /// let float_refs: [&mut f64; 3] = floats.each_mut();
573 /// *float_refs[0] = 0.0;
574 /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
575 /// assert_eq!(floats, [0.0, 2.7, -1.0]);
577 #[unstable(feature = "array_methods", issue = "76118")]
578 pub fn each_mut(&mut self) -> [&mut T; N] {
579 // SAFETY: we know for certain that this iterator will yield exactly `N`
581 unsafe { collect_into_array_unchecked(&mut self.iter_mut()) }
584 /// Divides one array reference into two at an index.
586 /// The first will contain all indices from `[0, M)` (excluding
587 /// the index `M` itself) and the second will contain all
588 /// indices from `[M, N)` (excluding the index `N` itself).
592 /// Panics if `M > N`.
597 /// #![feature(split_array)]
599 /// let v = [1, 2, 3, 4, 5, 6];
602 /// let (left, right) = v.split_array_ref::<0>();
603 /// assert_eq!(left, &[]);
604 /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
608 /// let (left, right) = v.split_array_ref::<2>();
609 /// assert_eq!(left, &[1, 2]);
610 /// assert_eq!(right, &[3, 4, 5, 6]);
614 /// let (left, right) = v.split_array_ref::<6>();
615 /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
616 /// assert_eq!(right, &[]);
620 feature = "split_array",
621 reason = "return type should have array as 2nd element",
625 pub fn split_array_ref<const M: usize>(&self) -> (&[T; M], &[T]) {
626 (&self[..]).split_array_ref::<M>()
629 /// Divides one mutable array reference into two at an index.
631 /// The first will contain all indices from `[0, M)` (excluding
632 /// the index `M` itself) and the second will contain all
633 /// indices from `[M, N)` (excluding the index `N` itself).
637 /// Panics if `M > N`.
642 /// #![feature(split_array)]
644 /// let mut v = [1, 0, 3, 0, 5, 6];
645 /// let (left, right) = v.split_array_mut::<2>();
646 /// assert_eq!(left, &mut [1, 0][..]);
647 /// assert_eq!(right, &mut [3, 0, 5, 6]);
650 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
653 feature = "split_array",
654 reason = "return type should have array as 2nd element",
658 pub fn split_array_mut<const M: usize>(&mut self) -> (&mut [T; M], &mut [T]) {
659 (&mut self[..]).split_array_mut::<M>()
662 /// Divides one array reference into two at an index from the end.
664 /// The first will contain all indices from `[0, N - M)` (excluding
665 /// the index `N - M` itself) and the second will contain all
666 /// indices from `[N - M, N)` (excluding the index `N` itself).
670 /// Panics if `M > N`.
675 /// #![feature(split_array)]
677 /// let v = [1, 2, 3, 4, 5, 6];
680 /// let (left, right) = v.rsplit_array_ref::<0>();
681 /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
682 /// assert_eq!(right, &[]);
686 /// let (left, right) = v.rsplit_array_ref::<2>();
687 /// assert_eq!(left, &[1, 2, 3, 4]);
688 /// assert_eq!(right, &[5, 6]);
692 /// let (left, right) = v.rsplit_array_ref::<6>();
693 /// assert_eq!(left, &[]);
694 /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
698 feature = "split_array",
699 reason = "return type should have array as 2nd element",
703 pub fn rsplit_array_ref<const M: usize>(&self) -> (&[T], &[T; M]) {
704 (&self[..]).rsplit_array_ref::<M>()
707 /// Divides one mutable array reference into two at an index from the end.
709 /// The first will contain all indices from `[0, N - M)` (excluding
710 /// the index `N - M` itself) and the second will contain all
711 /// indices from `[N - M, N)` (excluding the index `N` itself).
715 /// Panics if `M > N`.
720 /// #![feature(split_array)]
722 /// let mut v = [1, 0, 3, 0, 5, 6];
723 /// let (left, right) = v.rsplit_array_mut::<4>();
724 /// assert_eq!(left, &mut [1, 0]);
725 /// assert_eq!(right, &mut [3, 0, 5, 6][..]);
728 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
731 feature = "split_array",
732 reason = "return type should have array as 2nd element",
736 pub fn rsplit_array_mut<const M: usize>(&mut self) -> (&mut [T], &mut [T; M]) {
737 (&mut self[..]).rsplit_array_mut::<M>()
741 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
742 /// yields fewer than `N` items, this function exhibits undefined behavior.
744 /// See [`try_collect_into_array`] for more information.
749 /// It is up to the caller to guarantee that `iter` yields at least `N` items.
750 /// Violating this condition causes undefined behavior.
751 unsafe fn try_collect_into_array_unchecked<I, T, R, const N: usize>(iter: &mut I) -> R::TryType
753 // Note: `TrustedLen` here is somewhat of an experiment. This is just an
754 // internal function, so feel free to remove if this bound turns out to be a
755 // bad idea. In that case, remember to also remove the lower bound
756 // `debug_assert!` below!
757 I: Iterator + TrustedLen,
758 I::Item: Try<Output = T, Residual = R>,
761 debug_assert!(N <= iter.size_hint().1.unwrap_or(usize::MAX));
762 debug_assert!(N <= iter.size_hint().0);
764 // SAFETY: covered by the function contract.
765 unsafe { try_collect_into_array(iter).unwrap_unchecked() }
768 // Infallible version of `try_collect_into_array_unchecked`.
769 unsafe fn collect_into_array_unchecked<I, const N: usize>(iter: &mut I) -> [I::Item; N]
771 I: Iterator + TrustedLen,
773 let mut map = iter.map(NeverShortCircuit);
775 // SAFETY: The same safety considerations w.r.t. the iterator length
776 // apply for `try_collect_into_array_unchecked` as for
777 // `collect_into_array_unchecked`
778 match unsafe { try_collect_into_array_unchecked(&mut map) } {
779 NeverShortCircuit(array) => array,
783 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
784 /// yields fewer than `N` items, `None` is returned and all already yielded
785 /// items are dropped.
787 /// Since the iterator is passed as a mutable reference and this function calls
788 /// `next` at most `N` times, the iterator can still be used afterwards to
789 /// retrieve the remaining items.
791 /// If `iter.next()` panicks, all items already yielded by the iterator are
793 fn try_collect_into_array<I, T, R, const N: usize>(iter: &mut I) -> Option<R::TryType>
796 I::Item: Try<Output = T, Residual = R>,
800 // SAFETY: An empty array is always inhabited and has no validity invariants.
801 return unsafe { Some(Try::from_output(mem::zeroed())) };
804 struct Guard<'a, T, const N: usize> {
805 array_mut: &'a mut [MaybeUninit<T>; N],
809 impl<T, const N: usize> Drop for Guard<'_, T, N> {
811 debug_assert!(self.initialized <= N);
813 // SAFETY: this slice will contain only initialized objects.
815 crate::ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(
816 &mut self.array_mut.get_unchecked_mut(..self.initialized),
822 let mut array = MaybeUninit::uninit_array::<N>();
823 let mut guard = Guard { array_mut: &mut array, initialized: 0 };
825 while let Some(item_rslt) = iter.next() {
826 let item = match item_rslt.branch() {
827 ControlFlow::Break(r) => {
828 return Some(FromResidual::from_residual(r));
830 ControlFlow::Continue(elem) => elem,
833 // SAFETY: `guard.initialized` starts at 0, is increased by one in the
834 // loop and the loop is aborted once it reaches N (which is
837 guard.array_mut.get_unchecked_mut(guard.initialized).write(item);
839 guard.initialized += 1;
841 // Check if the whole array was initialized.
842 if guard.initialized == N {
845 // SAFETY: the condition above asserts that all elements are
847 let out = unsafe { MaybeUninit::array_assume_init(array) };
848 return Some(Try::from_output(out));
852 // This is only reached if the iterator is exhausted before
853 // `guard.initialized` reaches `N`. Also note that `guard` is dropped here,
854 // dropping all already initialized elements.