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 use crate::error
::Error
;
12 use crate::hash
::{self, Hash}
;
13 use crate::iter
::TrustedLen
;
14 use crate::mem
::{self, MaybeUninit}
;
16 ChangeOutputType
, ControlFlow
, FromResidual
, Index
, IndexMut
, NeverShortCircuit
, Residual
, Try
,
18 use crate::slice
::{Iter, IterMut}
;
23 #[stable(feature = "array_value_iter", since = "1.51.0")]
24 pub use iter
::IntoIter
;
26 /// Creates an array of type [T; N], where each element `T` is the returned value from `cb`
27 /// using that element's index.
31 /// * `cb`: Callback where the passed argument is the current array index.
36 /// // type inference is helping us here, the way `from_fn` knows how many
37 /// // elements to produce is the length of array down there: only arrays of
38 /// // equal lengths can be compared, so the const generic parameter `N` is
39 /// // inferred to be 5, thus creating array of 5 elements.
41 /// let array = core::array::from_fn(|i| i);
42 /// // indexes are: 0 1 2 3 4
43 /// assert_eq!(array, [0, 1, 2, 3, 4]);
45 /// let array2: [usize; 8] = core::array::from_fn(|i| i * 2);
46 /// // indexes are: 0 1 2 3 4 5 6 7
47 /// assert_eq!(array2, [0, 2, 4, 6, 8, 10, 12, 14]);
49 /// let bool_arr = core::array::from_fn::<_, 5, _>(|i| i % 2 == 0);
50 /// // indexes are: 0 1 2 3 4
51 /// assert_eq!(bool_arr, [true, false, true, false, true]);
54 #[stable(feature = "array_from_fn", since = "1.63.0")]
55 pub fn from_fn
<T
, const N
: usize, F
>(mut cb
: F
) -> [T
; N
]
67 /// Creates an array `[T; N]` where each fallible array element `T` is returned by the `cb` call.
68 /// Unlike [`from_fn`], where the element creation can't fail, this version will return an error
69 /// if any element creation was unsuccessful.
71 /// The return type of this function depends on the return type of the closure.
72 /// If you return `Result<T, E>` from the closure, you'll get a `Result<[T; N]; E>`.
73 /// If you return `Option<T>` from the closure, you'll get an `Option<[T; N]>`.
77 /// * `cb`: Callback where the passed argument is the current array index.
82 /// #![feature(array_try_from_fn)]
84 /// let array: Result<[u8; 5], _> = std::array::try_from_fn(|i| i.try_into());
85 /// assert_eq!(array, Ok([0, 1, 2, 3, 4]));
87 /// let array: Result<[i8; 200], _> = std::array::try_from_fn(|i| i.try_into());
88 /// assert!(array.is_err());
90 /// let array: Option<[_; 4]> = std::array::try_from_fn(|i| i.checked_add(100));
91 /// assert_eq!(array, Some([100, 101, 102, 103]));
93 /// let array: Option<[_; 4]> = std::array::try_from_fn(|i| i.checked_sub(100));
94 /// assert_eq!(array, None);
97 #[unstable(feature = "array_try_from_fn", issue = "89379")]
98 pub fn try_from_fn
<R
, const N
: usize, F
>(cb
: F
) -> ChangeOutputType
<R
, [R
::Output
; N
]>
100 F
: FnMut(usize) -> R
,
102 R
::Residual
: Residual
<[R
::Output
; N
]>,
104 // SAFETY: we know for certain that this iterator will yield exactly `N`
106 unsafe { try_collect_into_array_unchecked(&mut (0..N).map(cb)) }
109 /// Converts a reference to `T` into a reference to an array of length 1 (without copying).
110 #[stable(feature = "array_from_ref", since = "1.53.0")]
111 #[rustc_const_stable(feature = "const_array_from_ref_shared", since = "1.63.0")]
112 pub const fn from_ref
<T
>(s
: &T
) -> &[T
; 1] {
113 // SAFETY: Converting `&T` to `&[T; 1]` is sound.
114 unsafe { &*(s as *const T).cast::<[T; 1]>() }
117 /// Converts a mutable reference to `T` into a mutable reference to an array of length 1 (without copying).
118 #[stable(feature = "array_from_ref", since = "1.53.0")]
119 #[rustc_const_unstable(feature = "const_array_from_ref", issue = "90206")]
120 pub const fn from_mut
<T
>(s
: &mut T
) -> &mut [T
; 1] {
121 // SAFETY: Converting `&mut T` to `&mut [T; 1]` is sound.
122 unsafe { &mut *(s as *mut T).cast::<[T; 1]>() }
125 /// The error type returned when a conversion from a slice to an array fails.
126 #[stable(feature = "try_from", since = "1.34.0")]
127 #[derive(Debug, Copy, Clone)]
128 pub struct TryFromSliceError(());
130 #[stable(feature = "core_array", since = "1.36.0")]
131 impl fmt
::Display
for TryFromSliceError
{
133 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
134 fmt
::Display
::fmt(self.__description(), f
)
138 #[stable(feature = "try_from", since = "1.34.0")]
139 impl Error
for TryFromSliceError
{
141 fn description(&self) -> &str {
146 impl TryFromSliceError
{
148 feature
= "array_error_internals",
149 reason
= "available through Error trait and this method should not \
150 be exposed publicly",
155 pub fn __description(&self) -> &str {
156 "could not convert slice to array"
160 #[stable(feature = "try_from_slice_error", since = "1.36.0")]
161 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
162 impl const From
<Infallible
> for TryFromSliceError
{
163 fn from(x
: Infallible
) -> TryFromSliceError
{
168 #[stable(feature = "rust1", since = "1.0.0")]
169 impl<T
, const N
: usize> AsRef
<[T
]> for [T
; N
] {
171 fn as_ref(&self) -> &[T
] {
176 #[stable(feature = "rust1", since = "1.0.0")]
177 impl<T
, const N
: usize> AsMut
<[T
]> for [T
; N
] {
179 fn as_mut(&mut self) -> &mut [T
] {
184 #[stable(feature = "array_borrow", since = "1.4.0")]
185 #[rustc_const_unstable(feature = "const_borrow", issue = "91522")]
186 impl<T
, const N
: usize> const Borrow
<[T
]> for [T
; N
] {
187 fn borrow(&self) -> &[T
] {
192 #[stable(feature = "array_borrow", since = "1.4.0")]
193 #[rustc_const_unstable(feature = "const_borrow", issue = "91522")]
194 impl<T
, const N
: usize> const BorrowMut
<[T
]> for [T
; N
] {
195 fn borrow_mut(&mut self) -> &mut [T
] {
200 /// Tries to create an array `[T; N]` by copying from a slice `&[T]`. Succeeds if
201 /// `slice.len() == N`.
204 /// let bytes: [u8; 3] = [1, 0, 2];
206 /// let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&bytes[0..2]).unwrap();
207 /// assert_eq!(1, u16::from_le_bytes(bytes_head));
209 /// let bytes_tail: [u8; 2] = bytes[1..3].try_into().unwrap();
210 /// assert_eq!(512, u16::from_le_bytes(bytes_tail));
212 #[stable(feature = "try_from", since = "1.34.0")]
213 impl<T
, const N
: usize> TryFrom
<&[T
]> for [T
; N
]
217 type Error
= TryFromSliceError
;
219 fn try_from(slice
: &[T
]) -> Result
<[T
; N
], TryFromSliceError
> {
220 <&Self>::try_from(slice
).map(|r
| *r
)
224 /// Tries to create an array `[T; N]` by copying from a mutable slice `&mut [T]`.
225 /// Succeeds if `slice.len() == N`.
228 /// let mut bytes: [u8; 3] = [1, 0, 2];
230 /// let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
231 /// assert_eq!(1, u16::from_le_bytes(bytes_head));
233 /// let bytes_tail: [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
234 /// assert_eq!(512, u16::from_le_bytes(bytes_tail));
236 #[stable(feature = "try_from_mut_slice_to_array", since = "1.59.0")]
237 impl<T
, const N
: usize> TryFrom
<&mut [T
]> for [T
; N
]
241 type Error
= TryFromSliceError
;
243 fn try_from(slice
: &mut [T
]) -> Result
<[T
; N
], TryFromSliceError
> {
244 <Self>::try_from(&*slice
)
248 /// Tries to create an array ref `&[T; N]` from a slice ref `&[T]`. Succeeds if
249 /// `slice.len() == N`.
252 /// let bytes: [u8; 3] = [1, 0, 2];
254 /// let bytes_head: &[u8; 2] = <&[u8; 2]>::try_from(&bytes[0..2]).unwrap();
255 /// assert_eq!(1, u16::from_le_bytes(*bytes_head));
257 /// let bytes_tail: &[u8; 2] = bytes[1..3].try_into().unwrap();
258 /// assert_eq!(512, u16::from_le_bytes(*bytes_tail));
260 #[stable(feature = "try_from", since = "1.34.0")]
261 impl<'a
, T
, const N
: usize> TryFrom
<&'a
[T
]> for &'a
[T
; N
] {
262 type Error
= TryFromSliceError
;
264 fn try_from(slice
: &[T
]) -> Result
<&[T
; N
], TryFromSliceError
> {
265 if slice
.len() == N
{
266 let ptr
= slice
.as_ptr() as *const [T
; N
];
267 // SAFETY: ok because we just checked that the length fits
270 Err(TryFromSliceError(()))
275 /// Tries to create a mutable array ref `&mut [T; N]` from a mutable slice ref
276 /// `&mut [T]`. Succeeds if `slice.len() == N`.
279 /// let mut bytes: [u8; 3] = [1, 0, 2];
281 /// let bytes_head: &mut [u8; 2] = <&mut [u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
282 /// assert_eq!(1, u16::from_le_bytes(*bytes_head));
284 /// let bytes_tail: &mut [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
285 /// assert_eq!(512, u16::from_le_bytes(*bytes_tail));
287 #[stable(feature = "try_from", since = "1.34.0")]
288 impl<'a
, T
, const N
: usize> TryFrom
<&'a
mut [T
]> for &'a
mut [T
; N
] {
289 type Error
= TryFromSliceError
;
291 fn try_from(slice
: &mut [T
]) -> Result
<&mut [T
; N
], TryFromSliceError
> {
292 if slice
.len() == N
{
293 let ptr
= slice
.as_mut_ptr() as *mut [T
; N
];
294 // SAFETY: ok because we just checked that the length fits
295 unsafe { Ok(&mut *ptr) }
297 Err(TryFromSliceError(()))
302 /// The hash of an array is the same as that of the corresponding slice,
303 /// as required by the `Borrow` implementation.
306 /// #![feature(build_hasher_simple_hash_one)]
307 /// use std::hash::BuildHasher;
309 /// let b = std::collections::hash_map::RandomState::new();
310 /// let a: [u8; 3] = [0xa8, 0x3c, 0x09];
311 /// let s: &[u8] = &[0xa8, 0x3c, 0x09];
312 /// assert_eq!(b.hash_one(a), b.hash_one(s));
314 #[stable(feature = "rust1", since = "1.0.0")]
315 impl<T
: Hash
, const N
: usize> Hash
for [T
; N
] {
316 fn hash
<H
: hash
::Hasher
>(&self, state
: &mut H
) {
317 Hash
::hash(&self[..], state
)
321 #[stable(feature = "rust1", since = "1.0.0")]
322 impl<T
: fmt
::Debug
, const N
: usize> fmt
::Debug
for [T
; N
] {
323 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
324 fmt
::Debug
::fmt(&&self[..], f
)
328 #[stable(feature = "rust1", since = "1.0.0")]
329 impl<'a
, T
, const N
: usize> IntoIterator
for &'a
[T
; N
] {
331 type IntoIter
= Iter
<'a
, T
>;
333 fn into_iter(self) -> Iter
<'a
, T
> {
338 #[stable(feature = "rust1", since = "1.0.0")]
339 impl<'a
, T
, const N
: usize> IntoIterator
for &'a
mut [T
; N
] {
340 type Item
= &'a
mut T
;
341 type IntoIter
= IterMut
<'a
, T
>;
343 fn into_iter(self) -> IterMut
<'a
, T
> {
348 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
349 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
350 impl<T
, I
, const N
: usize> const Index
<I
> for [T
; N
]
352 [T
]: ~const Index
<I
>,
354 type Output
= <[T
] as Index
<I
>>::Output
;
357 fn index(&self, index
: I
) -> &Self::Output
{
358 Index
::index(self as &[T
], index
)
362 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
363 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
364 impl<T
, I
, const N
: usize> const IndexMut
<I
> for [T
; N
]
366 [T
]: ~const IndexMut
<I
>,
369 fn index_mut(&mut self, index
: I
) -> &mut Self::Output
{
370 IndexMut
::index_mut(self as &mut [T
], index
)
374 #[stable(feature = "rust1", since = "1.0.0")]
375 impl<T
: PartialOrd
, const N
: usize> PartialOrd
for [T
; N
] {
377 fn partial_cmp(&self, other
: &[T
; N
]) -> Option
<Ordering
> {
378 PartialOrd
::partial_cmp(&&self[..], &&other
[..])
381 fn lt(&self, other
: &[T
; N
]) -> bool
{
382 PartialOrd
::lt(&&self[..], &&other
[..])
385 fn le(&self, other
: &[T
; N
]) -> bool
{
386 PartialOrd
::le(&&self[..], &&other
[..])
389 fn ge(&self, other
: &[T
; N
]) -> bool
{
390 PartialOrd
::ge(&&self[..], &&other
[..])
393 fn gt(&self, other
: &[T
; N
]) -> bool
{
394 PartialOrd
::gt(&&self[..], &&other
[..])
398 /// Implements comparison of arrays [lexicographically](Ord#lexicographical-comparison).
399 #[stable(feature = "rust1", since = "1.0.0")]
400 impl<T
: Ord
, const N
: usize> Ord
for [T
; N
] {
402 fn cmp(&self, other
: &[T
; N
]) -> Ordering
{
403 Ord
::cmp(&&self[..], &&other
[..])
407 #[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
408 impl<T
: Copy
, const N
: usize> Copy
for [T
; N
] {}
410 #[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
411 impl<T
: Clone
, const N
: usize> Clone
for [T
; N
] {
413 fn clone(&self) -> Self {
414 SpecArrayClone
::clone(self)
418 fn clone_from(&mut self, other
: &Self) {
419 self.clone_from_slice(other
);
423 trait SpecArrayClone
: Clone
{
424 fn clone
<const N
: usize>(array
: &[Self; N
]) -> [Self; N
];
427 impl<T
: Clone
> SpecArrayClone
for T
{
429 default fn clone
<const N
: usize>(array
: &[T
; N
]) -> [T
; N
] {
430 // SAFETY: we know for certain that this iterator will yield exactly `N`
432 unsafe { collect_into_array_unchecked(&mut array.iter().cloned()) }
436 impl<T
: Copy
> SpecArrayClone
for T
{
438 fn clone
<const N
: usize>(array
: &[T
; N
]) -> [T
; N
] {
443 // The Default impls cannot be done with const generics because `[T; 0]` doesn't
444 // require Default to be implemented, and having different impl blocks for
445 // different numbers isn't supported yet.
447 macro_rules
! array_impl_default
{
448 {$n:expr, $t:ident $($ts:ident)*}
=> {
449 #[stable(since = "1.4.0", feature = "array_default")]
450 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
451 impl<T
> const Default
for [T
; $n
] where T
: ~const Default
{
452 fn default() -> [T
; $n
] {
453 [$t
::default(), $
($ts
::default()),*]
456 array_impl_default
!{($n - 1), $($ts)*}
459 #[stable(since = "1.4.0", feature = "array_default")]
460 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
461 impl<T
> const Default
for [T
; $n
] {
462 fn default() -> [T
; $n
] { [] }
467 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}
469 impl<T
, const N
: usize> [T
; N
] {
470 /// Returns an array of the same size as `self`, with function `f` applied to each element
473 /// If you don't necessarily need a new fixed-size array, consider using
474 /// [`Iterator::map`] instead.
477 /// # Note on performance and stack usage
479 /// Unfortunately, usages of this method are currently not always optimized
480 /// as well as they could be. This mainly concerns large arrays, as mapping
481 /// over small arrays seem to be optimized just fine. Also note that in
482 /// debug mode (i.e. without any optimizations), this method can use a lot
483 /// of stack space (a few times the size of the array or more).
485 /// Therefore, in performance-critical code, try to avoid using this method
486 /// on large arrays or check the emitted code. Also try to avoid chained
487 /// maps (e.g. `arr.map(...).map(...)`).
489 /// In many cases, you can instead use [`Iterator::map`] by calling `.iter()`
490 /// or `.into_iter()` on your array. `[T; N]::map` is only necessary if you
491 /// really need a new array of the same size as the result. Rust's lazy
492 /// iterators tend to get optimized very well.
498 /// let x = [1, 2, 3];
499 /// let y = x.map(|v| v + 1);
500 /// assert_eq!(y, [2, 3, 4]);
502 /// let x = [1, 2, 3];
503 /// let mut temp = 0;
504 /// let y = x.map(|v| { temp += 1; v * temp });
505 /// assert_eq!(y, [1, 4, 9]);
507 /// let x = ["Ferris", "Bueller's", "Day", "Off"];
508 /// let y = x.map(|v| v.len());
509 /// assert_eq!(y, [6, 9, 3, 3]);
511 #[stable(feature = "array_map", since = "1.55.0")]
512 pub fn map
<F
, U
>(self, f
: F
) -> [U
; N
]
516 // SAFETY: we know for certain that this iterator will yield exactly `N`
518 unsafe { collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
521 /// A fallible function `f` applied to each element on array `self` in order to
522 /// return an array the same size as `self` or the first error encountered.
524 /// The return type of this function depends on the return type of the closure.
525 /// If you return `Result<T, E>` from the closure, you'll get a `Result<[T; N]; E>`.
526 /// If you return `Option<T>` from the closure, you'll get an `Option<[T; N]>`.
531 /// #![feature(array_try_map)]
532 /// let a = ["1", "2", "3"];
533 /// let b = a.try_map(|v| v.parse::<u32>()).unwrap().map(|v| v + 1);
534 /// assert_eq!(b, [2, 3, 4]);
536 /// let a = ["1", "2a", "3"];
537 /// let b = a.try_map(|v| v.parse::<u32>());
538 /// assert!(b.is_err());
540 /// use std::num::NonZeroU32;
541 /// let z = [1, 2, 0, 3, 4];
542 /// assert_eq!(z.try_map(NonZeroU32::new), None);
543 /// let a = [1, 2, 3];
544 /// let b = a.try_map(NonZeroU32::new);
545 /// let c = b.map(|x| x.map(NonZeroU32::get));
546 /// assert_eq!(c, Some(a));
548 #[unstable(feature = "array_try_map", issue = "79711")]
549 pub fn try_map
<F
, R
>(self, f
: F
) -> ChangeOutputType
<R
, [R
::Output
; N
]>
553 R
::Residual
: Residual
<[R
::Output
; N
]>,
555 // SAFETY: we know for certain that this iterator will yield exactly `N`
557 unsafe { try_collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
560 /// 'Zips up' two arrays into a single array of pairs.
562 /// `zip()` returns a new array where every element is a tuple where the
563 /// first element comes from the first array, and the second element comes
564 /// from the second array. In other words, it zips two arrays together,
565 /// into a single one.
570 /// #![feature(array_zip)]
571 /// let x = [1, 2, 3];
572 /// let y = [4, 5, 6];
573 /// let z = x.zip(y);
574 /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
576 #[unstable(feature = "array_zip", issue = "80094")]
577 pub fn zip
<U
>(self, rhs
: [U
; N
]) -> [(T
, U
); N
] {
578 let mut iter
= IntoIterator
::into_iter(self).zip(rhs
);
580 // SAFETY: we know for certain that this iterator will yield exactly `N`
582 unsafe { collect_into_array_unchecked(&mut iter) }
585 /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
586 #[stable(feature = "array_as_slice", since = "1.57.0")]
587 #[rustc_const_stable(feature = "array_as_slice", since = "1.57.0")]
588 pub const fn as_slice(&self) -> &[T
] {
592 /// Returns a mutable slice containing the entire array. Equivalent to
594 #[stable(feature = "array_as_slice", since = "1.57.0")]
595 pub fn as_mut_slice(&mut self) -> &mut [T
] {
599 /// Borrows each element and returns an array of references with the same
606 /// #![feature(array_methods)]
608 /// let floats = [3.1, 2.7, -1.0];
609 /// let float_refs: [&f64; 3] = floats.each_ref();
610 /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
613 /// This method is particularly useful if combined with other methods, like
614 /// [`map`](#method.map). This way, you can avoid moving the original
615 /// array if its elements are not [`Copy`].
618 /// #![feature(array_methods)]
620 /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
621 /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
622 /// assert_eq!(is_ascii, [true, false, true]);
624 /// // We can still access the original array: it has not been moved.
625 /// assert_eq!(strings.len(), 3);
627 #[unstable(feature = "array_methods", issue = "76118")]
628 pub fn each_ref(&self) -> [&T
; N
] {
629 // SAFETY: we know for certain that this iterator will yield exactly `N`
631 unsafe { collect_into_array_unchecked(&mut self.iter()) }
634 /// Borrows each element mutably and returns an array of mutable references
635 /// with the same size as `self`.
641 /// #![feature(array_methods)]
643 /// let mut floats = [3.1, 2.7, -1.0];
644 /// let float_refs: [&mut f64; 3] = floats.each_mut();
645 /// *float_refs[0] = 0.0;
646 /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
647 /// assert_eq!(floats, [0.0, 2.7, -1.0]);
649 #[unstable(feature = "array_methods", issue = "76118")]
650 pub fn each_mut(&mut self) -> [&mut T
; N
] {
651 // SAFETY: we know for certain that this iterator will yield exactly `N`
653 unsafe { collect_into_array_unchecked(&mut self.iter_mut()) }
656 /// Divides one array reference into two at an index.
658 /// The first will contain all indices from `[0, M)` (excluding
659 /// the index `M` itself) and the second will contain all
660 /// indices from `[M, N)` (excluding the index `N` itself).
664 /// Panics if `M > N`.
669 /// #![feature(split_array)]
671 /// let v = [1, 2, 3, 4, 5, 6];
674 /// let (left, right) = v.split_array_ref::<0>();
675 /// assert_eq!(left, &[]);
676 /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
680 /// let (left, right) = v.split_array_ref::<2>();
681 /// assert_eq!(left, &[1, 2]);
682 /// assert_eq!(right, &[3, 4, 5, 6]);
686 /// let (left, right) = v.split_array_ref::<6>();
687 /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
688 /// assert_eq!(right, &[]);
692 feature
= "split_array",
693 reason
= "return type should have array as 2nd element",
697 pub fn split_array_ref
<const M
: usize>(&self) -> (&[T
; M
], &[T
]) {
698 (&self[..]).split_array_ref
::<M
>()
701 /// Divides one mutable array reference into two at an index.
703 /// The first will contain all indices from `[0, M)` (excluding
704 /// the index `M` itself) and the second will contain all
705 /// indices from `[M, N)` (excluding the index `N` itself).
709 /// Panics if `M > N`.
714 /// #![feature(split_array)]
716 /// let mut v = [1, 0, 3, 0, 5, 6];
717 /// let (left, right) = v.split_array_mut::<2>();
718 /// assert_eq!(left, &mut [1, 0][..]);
719 /// assert_eq!(right, &mut [3, 0, 5, 6]);
722 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
725 feature
= "split_array",
726 reason
= "return type should have array as 2nd element",
730 pub fn split_array_mut
<const M
: usize>(&mut self) -> (&mut [T
; M
], &mut [T
]) {
731 (&mut self[..]).split_array_mut
::<M
>()
734 /// Divides one array reference into two at an index from the end.
736 /// The first will contain all indices from `[0, N - M)` (excluding
737 /// the index `N - M` itself) and the second will contain all
738 /// indices from `[N - M, N)` (excluding the index `N` itself).
742 /// Panics if `M > N`.
747 /// #![feature(split_array)]
749 /// let v = [1, 2, 3, 4, 5, 6];
752 /// let (left, right) = v.rsplit_array_ref::<0>();
753 /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
754 /// assert_eq!(right, &[]);
758 /// let (left, right) = v.rsplit_array_ref::<2>();
759 /// assert_eq!(left, &[1, 2, 3, 4]);
760 /// assert_eq!(right, &[5, 6]);
764 /// let (left, right) = v.rsplit_array_ref::<6>();
765 /// assert_eq!(left, &[]);
766 /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
770 feature
= "split_array",
771 reason
= "return type should have array as 2nd element",
775 pub fn rsplit_array_ref
<const M
: usize>(&self) -> (&[T
], &[T
; M
]) {
776 (&self[..]).rsplit_array_ref
::<M
>()
779 /// Divides one mutable array reference into two at an index from the end.
781 /// The first will contain all indices from `[0, N - M)` (excluding
782 /// the index `N - M` itself) and the second will contain all
783 /// indices from `[N - M, N)` (excluding the index `N` itself).
787 /// Panics if `M > N`.
792 /// #![feature(split_array)]
794 /// let mut v = [1, 0, 3, 0, 5, 6];
795 /// let (left, right) = v.rsplit_array_mut::<4>();
796 /// assert_eq!(left, &mut [1, 0]);
797 /// assert_eq!(right, &mut [3, 0, 5, 6][..]);
800 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
803 feature
= "split_array",
804 reason
= "return type should have array as 2nd element",
808 pub fn rsplit_array_mut
<const M
: usize>(&mut self) -> (&mut [T
], &mut [T
; M
]) {
809 (&mut self[..]).rsplit_array_mut
::<M
>()
813 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
814 /// yields fewer than `N` items, this function exhibits undefined behavior.
816 /// See [`try_collect_into_array`] for more information.
821 /// It is up to the caller to guarantee that `iter` yields at least `N` items.
822 /// Violating this condition causes undefined behavior.
823 unsafe fn try_collect_into_array_unchecked
<I
, T
, R
, const N
: usize>(iter
: &mut I
) -> R
::TryType
825 // Note: `TrustedLen` here is somewhat of an experiment. This is just an
826 // internal function, so feel free to remove if this bound turns out to be a
827 // bad idea. In that case, remember to also remove the lower bound
828 // `debug_assert!` below!
829 I
: Iterator
+ TrustedLen
,
830 I
::Item
: Try
<Output
= T
, Residual
= R
>,
833 debug_assert
!(N
<= iter
.size_hint().1.unwrap_or
(usize::MAX
));
834 debug_assert
!(N
<= iter
.size_hint().0);
836 // SAFETY: covered by the function contract.
837 unsafe { try_collect_into_array(iter).unwrap_unchecked() }
840 // Infallible version of `try_collect_into_array_unchecked`.
841 unsafe fn collect_into_array_unchecked
<I
, const N
: usize>(iter
: &mut I
) -> [I
::Item
; N
]
843 I
: Iterator
+ TrustedLen
,
845 let mut map
= iter
.map(NeverShortCircuit
);
847 // SAFETY: The same safety considerations w.r.t. the iterator length
848 // apply for `try_collect_into_array_unchecked` as for
849 // `collect_into_array_unchecked`
850 match unsafe { try_collect_into_array_unchecked(&mut map) }
{
851 NeverShortCircuit(array
) => array
,
855 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
856 /// yields fewer than `N` items, `Err` is returned containing an iterator over
857 /// the already yielded items.
859 /// Since the iterator is passed as a mutable reference and this function calls
860 /// `next` at most `N` times, the iterator can still be used afterwards to
861 /// retrieve the remaining items.
863 /// If `iter.next()` panicks, all items already yielded by the iterator are
866 fn try_collect_into_array
<I
, T
, R
, const N
: usize>(
868 ) -> Result
<R
::TryType
, IntoIter
<T
, N
>>
871 I
::Item
: Try
<Output
= T
, Residual
= R
>,
875 // SAFETY: An empty array is always inhabited and has no validity invariants.
876 return Ok(Try
::from_output(unsafe { mem::zeroed() }
));
879 let mut array
= MaybeUninit
::uninit_array
::<N
>();
880 let mut guard
= Guard { array_mut: &mut array, initialized: 0 }
;
885 let item
= match item_rslt
.branch() {
886 ControlFlow
::Break(r
) => {
887 return Ok(FromResidual
::from_residual(r
));
889 ControlFlow
::Continue(elem
) => elem
,
892 // SAFETY: `guard.initialized` starts at 0, which means push can be called
893 // at most N times, which this loop does.
895 guard
.push_unchecked(item
);
899 let alive
= 0..guard
.initialized
;
901 // SAFETY: `array` was initialized with exactly `initialized`
902 // number of elements.
903 return Err(unsafe { IntoIter::new_unchecked(array, alive) }
);
909 // SAFETY: All elements of the array were populated in the loop above.
910 let output
= unsafe { array.transpose().assume_init() }
;
911 Ok(Try
::from_output(output
))
914 /// Panic guard for incremental initialization of arrays.
916 /// Disarm the guard with `mem::forget` once the array has been initialized.
920 /// All write accesses to this structure are unsafe and must maintain a correct
921 /// count of `initialized` elements.
923 /// To minimize indirection fields are still pub but callers should at least use
924 /// `push_unchecked` to signal that something unsafe is going on.
925 pub(crate) struct Guard
<'a
, T
, const N
: usize> {
926 /// The array to be initialized.
927 pub array_mut
: &'a
mut [MaybeUninit
<T
>; N
],
928 /// The number of items that have been initialized so far.
929 pub initialized
: usize,
932 impl<T
, const N
: usize> Guard
<'_
, T
, N
> {
933 /// Adds an item to the array and updates the initialized item counter.
937 /// No more than N elements must be initialized.
939 pub unsafe fn push_unchecked(&mut self, item
: T
) {
940 // SAFETY: If `initialized` was correct before and the caller does not
941 // invoke this method more than N times then writes will be in-bounds
942 // and slots will not be initialized more than once.
944 self.array_mut
.get_unchecked_mut(self.initialized
).write(item
);
945 self.initialized
= self.initialized
.unchecked_add(1);
950 impl<T
, const N
: usize> Drop
for Guard
<'_
, T
, N
> {
952 debug_assert
!(self.initialized
<= N
);
954 // SAFETY: this slice will contain only initialized objects.
956 crate::ptr
::drop_in_place(MaybeUninit
::slice_assume_init_mut(
957 &mut self.array_mut
.get_unchecked_mut(..self.initialized
),
963 /// Returns the next chunk of `N` items from the iterator or errors with an
964 /// iterator over the remainder. Used for `Iterator::next_chunk`.
966 pub(crate) fn iter_next_chunk
<I
, const N
: usize>(
968 ) -> Result
<[I
::Item
; N
], IntoIter
<I
::Item
, N
>>
972 let mut map
= iter
.map(NeverShortCircuit
);
973 try_collect_into_array(&mut map
).map(|NeverShortCircuit(arr
)| arr
)