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 /// let array = core::array::from_fn(|i| i);
35 /// assert_eq!(array, [0, 1, 2, 3, 4]);
38 #[stable(feature = "array_from_fn", since = "1.63.0")]
39 pub fn from_fn
<T
, const N
: usize, F
>(mut cb
: F
) -> [T
; N
]
51 /// Creates an array `[T; N]` where each fallible array element `T` is returned by the `cb` call.
52 /// Unlike [`from_fn`], where the element creation can't fail, this version will return an error
53 /// if any element creation was unsuccessful.
55 /// The return type of this function depends on the return type of the closure.
56 /// If you return `Result<T, E>` from the closure, you'll get a `Result<[T; N]; E>`.
57 /// If you return `Option<T>` from the closure, you'll get an `Option<[T; N]>`.
61 /// * `cb`: Callback where the passed argument is the current array index.
66 /// #![feature(array_try_from_fn)]
68 /// let array: Result<[u8; 5], _> = std::array::try_from_fn(|i| i.try_into());
69 /// assert_eq!(array, Ok([0, 1, 2, 3, 4]));
71 /// let array: Result<[i8; 200], _> = std::array::try_from_fn(|i| i.try_into());
72 /// assert!(array.is_err());
74 /// let array: Option<[_; 4]> = std::array::try_from_fn(|i| i.checked_add(100));
75 /// assert_eq!(array, Some([100, 101, 102, 103]));
77 /// let array: Option<[_; 4]> = std::array::try_from_fn(|i| i.checked_sub(100));
78 /// assert_eq!(array, None);
81 #[unstable(feature = "array_try_from_fn", issue = "89379")]
82 pub fn try_from_fn
<R
, const N
: usize, F
>(cb
: F
) -> ChangeOutputType
<R
, [R
::Output
; N
]>
86 R
::Residual
: Residual
<[R
::Output
; N
]>,
88 // SAFETY: we know for certain that this iterator will yield exactly `N`
90 unsafe { try_collect_into_array_unchecked(&mut (0..N).map(cb)) }
93 /// Converts a reference to `T` into a reference to an array of length 1 (without copying).
94 #[stable(feature = "array_from_ref", since = "1.53.0")]
95 #[rustc_const_stable(feature = "const_array_from_ref_shared", since = "1.63.0")]
96 pub const fn from_ref
<T
>(s
: &T
) -> &[T
; 1] {
97 // SAFETY: Converting `&T` to `&[T; 1]` is sound.
98 unsafe { &*(s as *const T).cast::<[T; 1]>() }
101 /// Converts a mutable reference to `T` into a mutable reference to an array of length 1 (without copying).
102 #[stable(feature = "array_from_ref", since = "1.53.0")]
103 #[rustc_const_unstable(feature = "const_array_from_ref", issue = "90206")]
104 pub const fn from_mut
<T
>(s
: &mut T
) -> &mut [T
; 1] {
105 // SAFETY: Converting `&mut T` to `&mut [T; 1]` is sound.
106 unsafe { &mut *(s as *mut T).cast::<[T; 1]>() }
109 /// The error type returned when a conversion from a slice to an array fails.
110 #[stable(feature = "try_from", since = "1.34.0")]
111 #[derive(Debug, Copy, Clone)]
112 pub struct TryFromSliceError(());
114 #[stable(feature = "core_array", since = "1.36.0")]
115 impl fmt
::Display
for TryFromSliceError
{
117 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
118 fmt
::Display
::fmt(self.__description(), f
)
122 impl TryFromSliceError
{
124 feature
= "array_error_internals",
125 reason
= "available through Error trait and this method should not \
126 be exposed publicly",
131 pub fn __description(&self) -> &str {
132 "could not convert slice to array"
136 #[stable(feature = "try_from_slice_error", since = "1.36.0")]
137 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
138 impl const From
<Infallible
> for TryFromSliceError
{
139 fn from(x
: Infallible
) -> TryFromSliceError
{
144 #[stable(feature = "rust1", since = "1.0.0")]
145 impl<T
, const N
: usize> AsRef
<[T
]> for [T
; N
] {
147 fn as_ref(&self) -> &[T
] {
152 #[stable(feature = "rust1", since = "1.0.0")]
153 impl<T
, const N
: usize> AsMut
<[T
]> for [T
; N
] {
155 fn as_mut(&mut self) -> &mut [T
] {
160 #[stable(feature = "array_borrow", since = "1.4.0")]
161 #[rustc_const_unstable(feature = "const_borrow", issue = "91522")]
162 impl<T
, const N
: usize> const Borrow
<[T
]> for [T
; N
] {
163 fn borrow(&self) -> &[T
] {
168 #[stable(feature = "array_borrow", since = "1.4.0")]
169 #[rustc_const_unstable(feature = "const_borrow", issue = "91522")]
170 impl<T
, const N
: usize> const BorrowMut
<[T
]> for [T
; N
] {
171 fn borrow_mut(&mut self) -> &mut [T
] {
176 #[stable(feature = "try_from", since = "1.34.0")]
177 impl<T
, const N
: usize> TryFrom
<&[T
]> for [T
; N
]
181 type Error
= TryFromSliceError
;
183 fn try_from(slice
: &[T
]) -> Result
<[T
; N
], TryFromSliceError
> {
184 <&Self>::try_from(slice
).map(|r
| *r
)
188 #[stable(feature = "try_from_mut_slice_to_array", since = "1.59.0")]
189 impl<T
, const N
: usize> TryFrom
<&mut [T
]> for [T
; N
]
193 type Error
= TryFromSliceError
;
195 fn try_from(slice
: &mut [T
]) -> Result
<[T
; N
], TryFromSliceError
> {
196 <Self>::try_from(&*slice
)
200 #[stable(feature = "try_from", since = "1.34.0")]
201 impl<'a
, T
, const N
: usize> TryFrom
<&'a
[T
]> for &'a
[T
; N
] {
202 type Error
= TryFromSliceError
;
204 fn try_from(slice
: &[T
]) -> Result
<&[T
; N
], TryFromSliceError
> {
205 if slice
.len() == N
{
206 let ptr
= slice
.as_ptr() as *const [T
; N
];
207 // SAFETY: ok because we just checked that the length fits
210 Err(TryFromSliceError(()))
215 #[stable(feature = "try_from", since = "1.34.0")]
216 impl<'a
, T
, const N
: usize> TryFrom
<&'a
mut [T
]> for &'a
mut [T
; N
] {
217 type Error
= TryFromSliceError
;
219 fn try_from(slice
: &mut [T
]) -> Result
<&mut [T
; N
], TryFromSliceError
> {
220 if slice
.len() == N
{
221 let ptr
= slice
.as_mut_ptr() as *mut [T
; N
];
222 // SAFETY: ok because we just checked that the length fits
223 unsafe { Ok(&mut *ptr) }
225 Err(TryFromSliceError(()))
230 /// The hash of an array is the same as that of the corresponding slice,
231 /// as required by the `Borrow` implementation.
234 /// #![feature(build_hasher_simple_hash_one)]
235 /// use std::hash::BuildHasher;
237 /// let b = std::collections::hash_map::RandomState::new();
238 /// let a: [u8; 3] = [0xa8, 0x3c, 0x09];
239 /// let s: &[u8] = &[0xa8, 0x3c, 0x09];
240 /// assert_eq!(b.hash_one(a), b.hash_one(s));
242 #[stable(feature = "rust1", since = "1.0.0")]
243 impl<T
: Hash
, const N
: usize> Hash
for [T
; N
] {
244 fn hash
<H
: hash
::Hasher
>(&self, state
: &mut H
) {
245 Hash
::hash(&self[..], state
)
249 #[stable(feature = "rust1", since = "1.0.0")]
250 impl<T
: fmt
::Debug
, const N
: usize> fmt
::Debug
for [T
; N
] {
251 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
252 fmt
::Debug
::fmt(&&self[..], f
)
256 #[stable(feature = "rust1", since = "1.0.0")]
257 impl<'a
, T
, const N
: usize> IntoIterator
for &'a
[T
; N
] {
259 type IntoIter
= Iter
<'a
, T
>;
261 fn into_iter(self) -> Iter
<'a
, T
> {
266 #[stable(feature = "rust1", since = "1.0.0")]
267 impl<'a
, T
, const N
: usize> IntoIterator
for &'a
mut [T
; N
] {
268 type Item
= &'a
mut T
;
269 type IntoIter
= IterMut
<'a
, T
>;
271 fn into_iter(self) -> IterMut
<'a
, T
> {
276 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
277 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
278 impl<T
, I
, const N
: usize> const Index
<I
> for [T
; N
]
280 [T
]: ~const Index
<I
>,
282 type Output
= <[T
] as Index
<I
>>::Output
;
285 fn index(&self, index
: I
) -> &Self::Output
{
286 Index
::index(self as &[T
], index
)
290 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
291 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
292 impl<T
, I
, const N
: usize> const IndexMut
<I
> for [T
; N
]
294 [T
]: ~const IndexMut
<I
>,
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}
396 impl<T
, const N
: usize> [T
; N
] {
397 /// Returns an array of the same size as `self`, with function `f` applied to each element
400 /// If you don't necessarily need a new fixed-size array, consider using
401 /// [`Iterator::map`] instead.
404 /// # Note on performance and stack usage
406 /// Unfortunately, usages of this method are currently not always optimized
407 /// as well as they could be. This mainly concerns large arrays, as mapping
408 /// over small arrays seem to be optimized just fine. Also note that in
409 /// debug mode (i.e. without any optimizations), this method can use a lot
410 /// of stack space (a few times the size of the array or more).
412 /// Therefore, in performance-critical code, try to avoid using this method
413 /// on large arrays or check the emitted code. Also try to avoid chained
414 /// maps (e.g. `arr.map(...).map(...)`).
416 /// In many cases, you can instead use [`Iterator::map`] by calling `.iter()`
417 /// or `.into_iter()` on your array. `[T; N]::map` is only necessary if you
418 /// really need a new array of the same size as the result. Rust's lazy
419 /// iterators tend to get optimized very well.
425 /// let x = [1, 2, 3];
426 /// let y = x.map(|v| v + 1);
427 /// assert_eq!(y, [2, 3, 4]);
429 /// let x = [1, 2, 3];
430 /// let mut temp = 0;
431 /// let y = x.map(|v| { temp += 1; v * temp });
432 /// assert_eq!(y, [1, 4, 9]);
434 /// let x = ["Ferris", "Bueller's", "Day", "Off"];
435 /// let y = x.map(|v| v.len());
436 /// assert_eq!(y, [6, 9, 3, 3]);
438 #[stable(feature = "array_map", since = "1.55.0")]
439 pub fn map
<F
, U
>(self, f
: F
) -> [U
; N
]
443 // SAFETY: we know for certain that this iterator will yield exactly `N`
445 unsafe { collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
448 /// A fallible function `f` applied to each element on array `self` in order to
449 /// return an array the same size as `self` or the first error encountered.
451 /// The return type of this function depends on the return type of the closure.
452 /// If you return `Result<T, E>` from the closure, you'll get a `Result<[T; N]; E>`.
453 /// If you return `Option<T>` from the closure, you'll get an `Option<[T; N]>`.
458 /// #![feature(array_try_map)]
459 /// let a = ["1", "2", "3"];
460 /// let b = a.try_map(|v| v.parse::<u32>()).unwrap().map(|v| v + 1);
461 /// assert_eq!(b, [2, 3, 4]);
463 /// let a = ["1", "2a", "3"];
464 /// let b = a.try_map(|v| v.parse::<u32>());
465 /// assert!(b.is_err());
467 /// use std::num::NonZeroU32;
468 /// let z = [1, 2, 0, 3, 4];
469 /// assert_eq!(z.try_map(NonZeroU32::new), None);
470 /// let a = [1, 2, 3];
471 /// let b = a.try_map(NonZeroU32::new);
472 /// let c = b.map(|x| x.map(NonZeroU32::get));
473 /// assert_eq!(c, Some(a));
475 #[unstable(feature = "array_try_map", issue = "79711")]
476 pub fn try_map
<F
, R
>(self, f
: F
) -> ChangeOutputType
<R
, [R
::Output
; N
]>
480 R
::Residual
: Residual
<[R
::Output
; N
]>,
482 // SAFETY: we know for certain that this iterator will yield exactly `N`
484 unsafe { try_collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
487 /// 'Zips up' two arrays into a single array of pairs.
489 /// `zip()` returns a new array where every element is a tuple where the
490 /// first element comes from the first array, and the second element comes
491 /// from the second array. In other words, it zips two arrays together,
492 /// into a single one.
497 /// #![feature(array_zip)]
498 /// let x = [1, 2, 3];
499 /// let y = [4, 5, 6];
500 /// let z = x.zip(y);
501 /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
503 #[unstable(feature = "array_zip", issue = "80094")]
504 pub fn zip
<U
>(self, rhs
: [U
; N
]) -> [(T
, U
); N
] {
505 let mut iter
= IntoIterator
::into_iter(self).zip(rhs
);
507 // SAFETY: we know for certain that this iterator will yield exactly `N`
509 unsafe { collect_into_array_unchecked(&mut iter) }
512 /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
513 #[stable(feature = "array_as_slice", since = "1.57.0")]
514 #[rustc_const_stable(feature = "array_as_slice", since = "1.57.0")]
515 pub const fn as_slice(&self) -> &[T
] {
519 /// Returns a mutable slice containing the entire array. Equivalent to
521 #[stable(feature = "array_as_slice", since = "1.57.0")]
522 pub fn as_mut_slice(&mut self) -> &mut [T
] {
526 /// Borrows each element and returns an array of references with the same
533 /// #![feature(array_methods)]
535 /// let floats = [3.1, 2.7, -1.0];
536 /// let float_refs: [&f64; 3] = floats.each_ref();
537 /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
540 /// This method is particularly useful if combined with other methods, like
541 /// [`map`](#method.map). This way, you can avoid moving the original
542 /// array if its elements are not [`Copy`].
545 /// #![feature(array_methods)]
547 /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
548 /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
549 /// assert_eq!(is_ascii, [true, false, true]);
551 /// // We can still access the original array: it has not been moved.
552 /// assert_eq!(strings.len(), 3);
554 #[unstable(feature = "array_methods", issue = "76118")]
555 pub fn each_ref(&self) -> [&T
; N
] {
556 // SAFETY: we know for certain that this iterator will yield exactly `N`
558 unsafe { collect_into_array_unchecked(&mut self.iter()) }
561 /// Borrows each element mutably and returns an array of mutable references
562 /// with the same size as `self`.
568 /// #![feature(array_methods)]
570 /// let mut floats = [3.1, 2.7, -1.0];
571 /// let float_refs: [&mut f64; 3] = floats.each_mut();
572 /// *float_refs[0] = 0.0;
573 /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
574 /// assert_eq!(floats, [0.0, 2.7, -1.0]);
576 #[unstable(feature = "array_methods", issue = "76118")]
577 pub fn each_mut(&mut self) -> [&mut T
; N
] {
578 // SAFETY: we know for certain that this iterator will yield exactly `N`
580 unsafe { collect_into_array_unchecked(&mut self.iter_mut()) }
583 /// Divides one array reference into two at an index.
585 /// The first will contain all indices from `[0, M)` (excluding
586 /// the index `M` itself) and the second will contain all
587 /// indices from `[M, N)` (excluding the index `N` itself).
591 /// Panics if `M > N`.
596 /// #![feature(split_array)]
598 /// let v = [1, 2, 3, 4, 5, 6];
601 /// let (left, right) = v.split_array_ref::<0>();
602 /// assert_eq!(left, &[]);
603 /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
607 /// let (left, right) = v.split_array_ref::<2>();
608 /// assert_eq!(left, &[1, 2]);
609 /// assert_eq!(right, &[3, 4, 5, 6]);
613 /// let (left, right) = v.split_array_ref::<6>();
614 /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
615 /// assert_eq!(right, &[]);
619 feature
= "split_array",
620 reason
= "return type should have array as 2nd element",
624 pub fn split_array_ref
<const M
: usize>(&self) -> (&[T
; M
], &[T
]) {
625 (&self[..]).split_array_ref
::<M
>()
628 /// Divides one mutable array reference into two at an index.
630 /// The first will contain all indices from `[0, M)` (excluding
631 /// the index `M` itself) and the second will contain all
632 /// indices from `[M, N)` (excluding the index `N` itself).
636 /// Panics if `M > N`.
641 /// #![feature(split_array)]
643 /// let mut v = [1, 0, 3, 0, 5, 6];
644 /// let (left, right) = v.split_array_mut::<2>();
645 /// assert_eq!(left, &mut [1, 0][..]);
646 /// assert_eq!(right, &mut [3, 0, 5, 6]);
649 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
652 feature
= "split_array",
653 reason
= "return type should have array as 2nd element",
657 pub fn split_array_mut
<const M
: usize>(&mut self) -> (&mut [T
; M
], &mut [T
]) {
658 (&mut self[..]).split_array_mut
::<M
>()
661 /// Divides one array reference into two at an index from the end.
663 /// The first will contain all indices from `[0, N - M)` (excluding
664 /// the index `N - M` itself) and the second will contain all
665 /// indices from `[N - M, N)` (excluding the index `N` itself).
669 /// Panics if `M > N`.
674 /// #![feature(split_array)]
676 /// let v = [1, 2, 3, 4, 5, 6];
679 /// let (left, right) = v.rsplit_array_ref::<0>();
680 /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
681 /// assert_eq!(right, &[]);
685 /// let (left, right) = v.rsplit_array_ref::<2>();
686 /// assert_eq!(left, &[1, 2, 3, 4]);
687 /// assert_eq!(right, &[5, 6]);
691 /// let (left, right) = v.rsplit_array_ref::<6>();
692 /// assert_eq!(left, &[]);
693 /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
697 feature
= "split_array",
698 reason
= "return type should have array as 2nd element",
702 pub fn rsplit_array_ref
<const M
: usize>(&self) -> (&[T
], &[T
; M
]) {
703 (&self[..]).rsplit_array_ref
::<M
>()
706 /// Divides one mutable array reference into two at an index from the end.
708 /// The first will contain all indices from `[0, N - M)` (excluding
709 /// the index `N - M` itself) and the second will contain all
710 /// indices from `[N - M, N)` (excluding the index `N` itself).
714 /// Panics if `M > N`.
719 /// #![feature(split_array)]
721 /// let mut v = [1, 0, 3, 0, 5, 6];
722 /// let (left, right) = v.rsplit_array_mut::<4>();
723 /// assert_eq!(left, &mut [1, 0]);
724 /// assert_eq!(right, &mut [3, 0, 5, 6][..]);
727 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
730 feature
= "split_array",
731 reason
= "return type should have array as 2nd element",
735 pub fn rsplit_array_mut
<const M
: usize>(&mut self) -> (&mut [T
], &mut [T
; M
]) {
736 (&mut self[..]).rsplit_array_mut
::<M
>()
740 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
741 /// yields fewer than `N` items, this function exhibits undefined behavior.
743 /// See [`try_collect_into_array`] for more information.
748 /// It is up to the caller to guarantee that `iter` yields at least `N` items.
749 /// Violating this condition causes undefined behavior.
750 unsafe fn try_collect_into_array_unchecked
<I
, T
, R
, const N
: usize>(iter
: &mut I
) -> R
::TryType
752 // Note: `TrustedLen` here is somewhat of an experiment. This is just an
753 // internal function, so feel free to remove if this bound turns out to be a
754 // bad idea. In that case, remember to also remove the lower bound
755 // `debug_assert!` below!
756 I
: Iterator
+ TrustedLen
,
757 I
::Item
: Try
<Output
= T
, Residual
= R
>,
760 debug_assert
!(N
<= iter
.size_hint().1.unwrap_or
(usize::MAX
));
761 debug_assert
!(N
<= iter
.size_hint().0);
763 // SAFETY: covered by the function contract.
764 unsafe { try_collect_into_array(iter).unwrap_unchecked() }
767 // Infallible version of `try_collect_into_array_unchecked`.
768 unsafe fn collect_into_array_unchecked
<I
, const N
: usize>(iter
: &mut I
) -> [I
::Item
; N
]
770 I
: Iterator
+ TrustedLen
,
772 let mut map
= iter
.map(NeverShortCircuit
);
774 // SAFETY: The same safety considerations w.r.t. the iterator length
775 // apply for `try_collect_into_array_unchecked` as for
776 // `collect_into_array_unchecked`
777 match unsafe { try_collect_into_array_unchecked(&mut map) }
{
778 NeverShortCircuit(array
) => array
,
782 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
783 /// yields fewer than `N` items, `Err` is returned containing an iterator over
784 /// the already yielded items.
786 /// Since the iterator is passed as a mutable reference and this function calls
787 /// `next` at most `N` times, the iterator can still be used afterwards to
788 /// retrieve the remaining items.
790 /// If `iter.next()` panicks, all items already yielded by the iterator are
793 fn try_collect_into_array
<I
, T
, R
, const N
: usize>(
795 ) -> Result
<R
::TryType
, IntoIter
<T
, N
>>
798 I
::Item
: Try
<Output
= T
, Residual
= R
>,
802 // SAFETY: An empty array is always inhabited and has no validity invariants.
803 return Ok(Try
::from_output(unsafe { mem::zeroed() }
));
806 struct Guard
<'a
, T
, const N
: usize> {
807 array_mut
: &'a
mut [MaybeUninit
<T
>; N
],
811 impl<T
, const N
: usize> Drop
for Guard
<'_
, T
, N
> {
813 debug_assert
!(self.initialized
<= N
);
815 // SAFETY: this slice will contain only initialized objects.
817 crate::ptr
::drop_in_place(MaybeUninit
::slice_assume_init_mut(
818 &mut self.array_mut
.get_unchecked_mut(..self.initialized
),
824 let mut array
= MaybeUninit
::uninit_array
::<N
>();
825 let mut guard
= Guard { array_mut: &mut array, initialized: 0 }
;
830 let item
= match item_rslt
.branch() {
831 ControlFlow
::Break(r
) => {
832 return Ok(FromResidual
::from_residual(r
));
834 ControlFlow
::Continue(elem
) => elem
,
837 // SAFETY: `guard.initialized` starts at 0, is increased by one in the
838 // loop and the loop is aborted once it reaches N (which is
841 guard
.array_mut
.get_unchecked_mut(guard
.initialized
).write(item
);
843 guard
.initialized
+= 1;
846 let alive
= 0..guard
.initialized
;
848 // SAFETY: `array` was initialized with exactly `initialized`
849 // number of elements.
850 return Err(unsafe { IntoIter::new_unchecked(array, alive) }
);
856 // SAFETY: All elements of the array were populated in the loop above.
857 let output
= unsafe { MaybeUninit::array_assume_init(array) }
;
858 Ok(Try
::from_output(output
))
861 /// Returns the next chunk of `N` items from the iterator or errors with an
862 /// iterator over the remainder. Used for `Iterator::next_chunk`.
864 pub(crate) fn iter_next_chunk
<I
, const N
: usize>(
866 ) -> Result
<[I
::Item
; N
], IntoIter
<I
::Item
, N
>>
870 let mut map
= iter
.map(NeverShortCircuit
);
871 try_collect_into_array(&mut map
).map(|NeverShortCircuit(arr
)| arr
)