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 /// Tries to create an array `[T; N]` by copying from a slice `&[T]`. Succeeds if
188 /// `slice.len() == N`.
191 /// let bytes: [u8; 3] = [1, 0, 2];
193 /// let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&bytes[0..2]).unwrap();
194 /// assert_eq!(1, u16::from_le_bytes(bytes_head));
196 /// let bytes_tail: [u8; 2] = bytes[1..3].try_into().unwrap();
197 /// assert_eq!(512, u16::from_le_bytes(bytes_tail));
199 #[stable(feature = "try_from", since = "1.34.0")]
200 impl<T, const N: usize> TryFrom<&[T]> for [T; N]
204 type Error = TryFromSliceError;
206 fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError> {
207 <&Self>::try_from(slice).map(|r| *r)
211 /// Tries to create an array `[T; N]` by copying from a mutable slice `&mut [T]`.
212 /// Succeeds if `slice.len() == N`.
215 /// let mut bytes: [u8; 3] = [1, 0, 2];
217 /// let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
218 /// assert_eq!(1, u16::from_le_bytes(bytes_head));
220 /// let bytes_tail: [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
221 /// assert_eq!(512, u16::from_le_bytes(bytes_tail));
223 #[stable(feature = "try_from_mut_slice_to_array", since = "1.59.0")]
224 impl<T, const N: usize> TryFrom<&mut [T]> for [T; N]
228 type Error = TryFromSliceError;
230 fn try_from(slice: &mut [T]) -> Result<[T; N], TryFromSliceError> {
231 <Self>::try_from(&*slice)
235 /// Tries to create an array ref `&[T; N]` from a slice ref `&[T]`. Succeeds if
236 /// `slice.len() == N`.
239 /// let bytes: [u8; 3] = [1, 0, 2];
241 /// let bytes_head: &[u8; 2] = <&[u8; 2]>::try_from(&bytes[0..2]).unwrap();
242 /// assert_eq!(1, u16::from_le_bytes(*bytes_head));
244 /// let bytes_tail: &[u8; 2] = bytes[1..3].try_into().unwrap();
245 /// assert_eq!(512, u16::from_le_bytes(*bytes_tail));
247 #[stable(feature = "try_from", since = "1.34.0")]
248 impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N] {
249 type Error = TryFromSliceError;
251 fn try_from(slice: &[T]) -> Result<&[T; N], TryFromSliceError> {
252 if slice.len() == N {
253 let ptr = slice.as_ptr() as *const [T; N];
254 // SAFETY: ok because we just checked that the length fits
257 Err(TryFromSliceError(()))
262 /// Tries to create a mutable array ref `&mut [T; N]` from a mutable slice ref
263 /// `&mut [T]`. Succeeds if `slice.len() == N`.
266 /// let mut bytes: [u8; 3] = [1, 0, 2];
268 /// let bytes_head: &mut [u8; 2] = <&mut [u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
269 /// assert_eq!(1, u16::from_le_bytes(*bytes_head));
271 /// let bytes_tail: &mut [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
272 /// assert_eq!(512, u16::from_le_bytes(*bytes_tail));
274 #[stable(feature = "try_from", since = "1.34.0")]
275 impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N] {
276 type Error = TryFromSliceError;
278 fn try_from(slice: &mut [T]) -> Result<&mut [T; N], TryFromSliceError> {
279 if slice.len() == N {
280 let ptr = slice.as_mut_ptr() as *mut [T; N];
281 // SAFETY: ok because we just checked that the length fits
282 unsafe { Ok(&mut *ptr) }
284 Err(TryFromSliceError(()))
289 /// The hash of an array is the same as that of the corresponding slice,
290 /// as required by the `Borrow` implementation.
293 /// #![feature(build_hasher_simple_hash_one)]
294 /// use std::hash::BuildHasher;
296 /// let b = std::collections::hash_map::RandomState::new();
297 /// let a: [u8; 3] = [0xa8, 0x3c, 0x09];
298 /// let s: &[u8] = &[0xa8, 0x3c, 0x09];
299 /// assert_eq!(b.hash_one(a), b.hash_one(s));
301 #[stable(feature = "rust1", since = "1.0.0")]
302 impl<T: Hash, const N: usize> Hash for [T; N] {
303 fn hash<H: hash::Hasher>(&self, state: &mut H) {
304 Hash::hash(&self[..], state)
308 #[stable(feature = "rust1", since = "1.0.0")]
309 impl<T: fmt::Debug, const N: usize> fmt::Debug for [T; N] {
310 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311 fmt::Debug::fmt(&&self[..], f)
315 #[stable(feature = "rust1", since = "1.0.0")]
316 impl<'a, T, const N: usize> IntoIterator for &'a [T; N] {
318 type IntoIter = Iter<'a, T>;
320 fn into_iter(self) -> Iter<'a, T> {
325 #[stable(feature = "rust1", since = "1.0.0")]
326 impl<'a, T, const N: usize> IntoIterator for &'a mut [T; N] {
327 type Item = &'a mut T;
328 type IntoIter = IterMut<'a, T>;
330 fn into_iter(self) -> IterMut<'a, T> {
335 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
336 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
337 impl<T, I, const N: usize> const Index<I> for [T; N]
339 [T]: ~const Index<I>,
341 type Output = <[T] as Index<I>>::Output;
344 fn index(&self, index: I) -> &Self::Output {
345 Index::index(self as &[T], index)
349 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
350 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
351 impl<T, I, const N: usize> const IndexMut<I> for [T; N]
353 [T]: ~const IndexMut<I>,
356 fn index_mut(&mut self, index: I) -> &mut Self::Output {
357 IndexMut::index_mut(self as &mut [T], index)
361 #[stable(feature = "rust1", since = "1.0.0")]
362 impl<T: PartialOrd, const N: usize> PartialOrd for [T; N] {
364 fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
365 PartialOrd::partial_cmp(&&self[..], &&other[..])
368 fn lt(&self, other: &[T; N]) -> bool {
369 PartialOrd::lt(&&self[..], &&other[..])
372 fn le(&self, other: &[T; N]) -> bool {
373 PartialOrd::le(&&self[..], &&other[..])
376 fn ge(&self, other: &[T; N]) -> bool {
377 PartialOrd::ge(&&self[..], &&other[..])
380 fn gt(&self, other: &[T; N]) -> bool {
381 PartialOrd::gt(&&self[..], &&other[..])
385 /// Implements comparison of arrays [lexicographically](Ord#lexicographical-comparison).
386 #[stable(feature = "rust1", since = "1.0.0")]
387 impl<T: Ord, const N: usize> Ord for [T; N] {
389 fn cmp(&self, other: &[T; N]) -> Ordering {
390 Ord::cmp(&&self[..], &&other[..])
394 #[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
395 impl<T: Copy, const N: usize> Copy for [T; N] {}
397 #[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
398 impl<T: Clone, const N: usize> Clone for [T; N] {
400 fn clone(&self) -> Self {
401 SpecArrayClone::clone(self)
405 fn clone_from(&mut self, other: &Self) {
406 self.clone_from_slice(other);
410 trait SpecArrayClone: Clone {
411 fn clone<const N: usize>(array: &[Self; N]) -> [Self; N];
414 impl<T: Clone> SpecArrayClone for T {
416 default fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
417 // SAFETY: we know for certain that this iterator will yield exactly `N`
419 unsafe { collect_into_array_unchecked(&mut array.iter().cloned()) }
423 impl<T: Copy> SpecArrayClone for T {
425 fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
430 // The Default impls cannot be done with const generics because `[T; 0]` doesn't
431 // require Default to be implemented, and having different impl blocks for
432 // different numbers isn't supported yet.
434 macro_rules! array_impl_default {
435 {$n:expr, $t:ident $($ts:ident)*} => {
436 #[stable(since = "1.4.0", feature = "array_default")]
437 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
438 impl<T> const Default for [T; $n] where T: ~const Default {
439 fn default() -> [T; $n] {
440 [$t::default(), $($ts::default()),*]
443 array_impl_default!{($n - 1), $($ts)*}
446 #[stable(since = "1.4.0", feature = "array_default")]
447 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
448 impl<T> const Default for [T; $n] {
449 fn default() -> [T; $n] { [] }
454 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}
456 impl<T, const N: usize> [T; N] {
457 /// Returns an array of the same size as `self`, with function `f` applied to each element
460 /// If you don't necessarily need a new fixed-size array, consider using
461 /// [`Iterator::map`] instead.
464 /// # Note on performance and stack usage
466 /// Unfortunately, usages of this method are currently not always optimized
467 /// as well as they could be. This mainly concerns large arrays, as mapping
468 /// over small arrays seem to be optimized just fine. Also note that in
469 /// debug mode (i.e. without any optimizations), this method can use a lot
470 /// of stack space (a few times the size of the array or more).
472 /// Therefore, in performance-critical code, try to avoid using this method
473 /// on large arrays or check the emitted code. Also try to avoid chained
474 /// maps (e.g. `arr.map(...).map(...)`).
476 /// In many cases, you can instead use [`Iterator::map`] by calling `.iter()`
477 /// or `.into_iter()` on your array. `[T; N]::map` is only necessary if you
478 /// really need a new array of the same size as the result. Rust's lazy
479 /// iterators tend to get optimized very well.
485 /// let x = [1, 2, 3];
486 /// let y = x.map(|v| v + 1);
487 /// assert_eq!(y, [2, 3, 4]);
489 /// let x = [1, 2, 3];
490 /// let mut temp = 0;
491 /// let y = x.map(|v| { temp += 1; v * temp });
492 /// assert_eq!(y, [1, 4, 9]);
494 /// let x = ["Ferris", "Bueller's", "Day", "Off"];
495 /// let y = x.map(|v| v.len());
496 /// assert_eq!(y, [6, 9, 3, 3]);
498 #[stable(feature = "array_map", since = "1.55.0")]
499 pub fn map<F, U>(self, f: F) -> [U; N]
503 // SAFETY: we know for certain that this iterator will yield exactly `N`
505 unsafe { collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
508 /// A fallible function `f` applied to each element on array `self` in order to
509 /// return an array the same size as `self` or the first error encountered.
511 /// The return type of this function depends on the return type of the closure.
512 /// If you return `Result<T, E>` from the closure, you'll get a `Result<[T; N]; E>`.
513 /// If you return `Option<T>` from the closure, you'll get an `Option<[T; N]>`.
518 /// #![feature(array_try_map)]
519 /// let a = ["1", "2", "3"];
520 /// let b = a.try_map(|v| v.parse::<u32>()).unwrap().map(|v| v + 1);
521 /// assert_eq!(b, [2, 3, 4]);
523 /// let a = ["1", "2a", "3"];
524 /// let b = a.try_map(|v| v.parse::<u32>());
525 /// assert!(b.is_err());
527 /// use std::num::NonZeroU32;
528 /// let z = [1, 2, 0, 3, 4];
529 /// assert_eq!(z.try_map(NonZeroU32::new), None);
530 /// let a = [1, 2, 3];
531 /// let b = a.try_map(NonZeroU32::new);
532 /// let c = b.map(|x| x.map(NonZeroU32::get));
533 /// assert_eq!(c, Some(a));
535 #[unstable(feature = "array_try_map", issue = "79711")]
536 pub fn try_map<F, R>(self, f: F) -> ChangeOutputType<R, [R::Output; N]>
540 R::Residual: Residual<[R::Output; N]>,
542 // SAFETY: we know for certain that this iterator will yield exactly `N`
544 unsafe { try_collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
547 /// 'Zips up' two arrays into a single array of pairs.
549 /// `zip()` returns a new array where every element is a tuple where the
550 /// first element comes from the first array, and the second element comes
551 /// from the second array. In other words, it zips two arrays together,
552 /// into a single one.
557 /// #![feature(array_zip)]
558 /// let x = [1, 2, 3];
559 /// let y = [4, 5, 6];
560 /// let z = x.zip(y);
561 /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
563 #[unstable(feature = "array_zip", issue = "80094")]
564 pub fn zip<U>(self, rhs: [U; N]) -> [(T, U); N] {
565 let mut iter = IntoIterator::into_iter(self).zip(rhs);
567 // SAFETY: we know for certain that this iterator will yield exactly `N`
569 unsafe { collect_into_array_unchecked(&mut iter) }
572 /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
573 #[stable(feature = "array_as_slice", since = "1.57.0")]
574 #[rustc_const_stable(feature = "array_as_slice", since = "1.57.0")]
575 pub const fn as_slice(&self) -> &[T] {
579 /// Returns a mutable slice containing the entire array. Equivalent to
581 #[stable(feature = "array_as_slice", since = "1.57.0")]
582 pub fn as_mut_slice(&mut self) -> &mut [T] {
586 /// Borrows each element and returns an array of references with the same
593 /// #![feature(array_methods)]
595 /// let floats = [3.1, 2.7, -1.0];
596 /// let float_refs: [&f64; 3] = floats.each_ref();
597 /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
600 /// This method is particularly useful if combined with other methods, like
601 /// [`map`](#method.map). This way, you can avoid moving the original
602 /// array if its elements are not [`Copy`].
605 /// #![feature(array_methods)]
607 /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
608 /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
609 /// assert_eq!(is_ascii, [true, false, true]);
611 /// // We can still access the original array: it has not been moved.
612 /// assert_eq!(strings.len(), 3);
614 #[unstable(feature = "array_methods", issue = "76118")]
615 pub fn each_ref(&self) -> [&T; N] {
616 // SAFETY: we know for certain that this iterator will yield exactly `N`
618 unsafe { collect_into_array_unchecked(&mut self.iter()) }
621 /// Borrows each element mutably and returns an array of mutable references
622 /// with the same size as `self`.
628 /// #![feature(array_methods)]
630 /// let mut floats = [3.1, 2.7, -1.0];
631 /// let float_refs: [&mut f64; 3] = floats.each_mut();
632 /// *float_refs[0] = 0.0;
633 /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
634 /// assert_eq!(floats, [0.0, 2.7, -1.0]);
636 #[unstable(feature = "array_methods", issue = "76118")]
637 pub fn each_mut(&mut self) -> [&mut T; N] {
638 // SAFETY: we know for certain that this iterator will yield exactly `N`
640 unsafe { collect_into_array_unchecked(&mut self.iter_mut()) }
643 /// Divides one array reference into two at an index.
645 /// The first will contain all indices from `[0, M)` (excluding
646 /// the index `M` itself) and the second will contain all
647 /// indices from `[M, N)` (excluding the index `N` itself).
651 /// Panics if `M > N`.
656 /// #![feature(split_array)]
658 /// let v = [1, 2, 3, 4, 5, 6];
661 /// let (left, right) = v.split_array_ref::<0>();
662 /// assert_eq!(left, &[]);
663 /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
667 /// let (left, right) = v.split_array_ref::<2>();
668 /// assert_eq!(left, &[1, 2]);
669 /// assert_eq!(right, &[3, 4, 5, 6]);
673 /// let (left, right) = v.split_array_ref::<6>();
674 /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
675 /// assert_eq!(right, &[]);
679 feature = "split_array",
680 reason = "return type should have array as 2nd element",
684 pub fn split_array_ref<const M: usize>(&self) -> (&[T; M], &[T]) {
685 (&self[..]).split_array_ref::<M>()
688 /// Divides one mutable array reference into two at an index.
690 /// The first will contain all indices from `[0, M)` (excluding
691 /// the index `M` itself) and the second will contain all
692 /// indices from `[M, N)` (excluding the index `N` itself).
696 /// Panics if `M > N`.
701 /// #![feature(split_array)]
703 /// let mut v = [1, 0, 3, 0, 5, 6];
704 /// let (left, right) = v.split_array_mut::<2>();
705 /// assert_eq!(left, &mut [1, 0][..]);
706 /// assert_eq!(right, &mut [3, 0, 5, 6]);
709 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
712 feature = "split_array",
713 reason = "return type should have array as 2nd element",
717 pub fn split_array_mut<const M: usize>(&mut self) -> (&mut [T; M], &mut [T]) {
718 (&mut self[..]).split_array_mut::<M>()
721 /// Divides one array reference into two at an index from the end.
723 /// The first will contain all indices from `[0, N - M)` (excluding
724 /// the index `N - M` itself) and the second will contain all
725 /// indices from `[N - M, N)` (excluding the index `N` itself).
729 /// Panics if `M > N`.
734 /// #![feature(split_array)]
736 /// let v = [1, 2, 3, 4, 5, 6];
739 /// let (left, right) = v.rsplit_array_ref::<0>();
740 /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
741 /// assert_eq!(right, &[]);
745 /// let (left, right) = v.rsplit_array_ref::<2>();
746 /// assert_eq!(left, &[1, 2, 3, 4]);
747 /// assert_eq!(right, &[5, 6]);
751 /// let (left, right) = v.rsplit_array_ref::<6>();
752 /// assert_eq!(left, &[]);
753 /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
757 feature = "split_array",
758 reason = "return type should have array as 2nd element",
762 pub fn rsplit_array_ref<const M: usize>(&self) -> (&[T], &[T; M]) {
763 (&self[..]).rsplit_array_ref::<M>()
766 /// Divides one mutable array reference into two at an index from the end.
768 /// The first will contain all indices from `[0, N - M)` (excluding
769 /// the index `N - M` itself) and the second will contain all
770 /// indices from `[N - M, N)` (excluding the index `N` itself).
774 /// Panics if `M > N`.
779 /// #![feature(split_array)]
781 /// let mut v = [1, 0, 3, 0, 5, 6];
782 /// let (left, right) = v.rsplit_array_mut::<4>();
783 /// assert_eq!(left, &mut [1, 0]);
784 /// assert_eq!(right, &mut [3, 0, 5, 6][..]);
787 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
790 feature = "split_array",
791 reason = "return type should have array as 2nd element",
795 pub fn rsplit_array_mut<const M: usize>(&mut self) -> (&mut [T], &mut [T; M]) {
796 (&mut self[..]).rsplit_array_mut::<M>()
800 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
801 /// yields fewer than `N` items, this function exhibits undefined behavior.
803 /// See [`try_collect_into_array`] for more information.
808 /// It is up to the caller to guarantee that `iter` yields at least `N` items.
809 /// Violating this condition causes undefined behavior.
810 unsafe fn try_collect_into_array_unchecked<I, T, R, const N: usize>(iter: &mut I) -> R::TryType
812 // Note: `TrustedLen` here is somewhat of an experiment. This is just an
813 // internal function, so feel free to remove if this bound turns out to be a
814 // bad idea. In that case, remember to also remove the lower bound
815 // `debug_assert!` below!
816 I: Iterator + TrustedLen,
817 I::Item: Try<Output = T, Residual = R>,
820 debug_assert!(N <= iter.size_hint().1.unwrap_or(usize::MAX));
821 debug_assert!(N <= iter.size_hint().0);
823 // SAFETY: covered by the function contract.
824 unsafe { try_collect_into_array(iter).unwrap_unchecked() }
827 // Infallible version of `try_collect_into_array_unchecked`.
828 unsafe fn collect_into_array_unchecked<I, const N: usize>(iter: &mut I) -> [I::Item; N]
830 I: Iterator + TrustedLen,
832 let mut map = iter.map(NeverShortCircuit);
834 // SAFETY: The same safety considerations w.r.t. the iterator length
835 // apply for `try_collect_into_array_unchecked` as for
836 // `collect_into_array_unchecked`
837 match unsafe { try_collect_into_array_unchecked(&mut map) } {
838 NeverShortCircuit(array) => array,
842 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
843 /// yields fewer than `N` items, `Err` is returned containing an iterator over
844 /// the already yielded items.
846 /// Since the iterator is passed as a mutable reference and this function calls
847 /// `next` at most `N` times, the iterator can still be used afterwards to
848 /// retrieve the remaining items.
850 /// If `iter.next()` panicks, all items already yielded by the iterator are
853 fn try_collect_into_array<I, T, R, const N: usize>(
855 ) -> Result<R::TryType, IntoIter<T, N>>
858 I::Item: Try<Output = T, Residual = R>,
862 // SAFETY: An empty array is always inhabited and has no validity invariants.
863 return Ok(Try::from_output(unsafe { mem::zeroed() }));
866 struct Guard<'a, T, const N: usize> {
867 array_mut: &'a mut [MaybeUninit<T>; N],
871 impl<T, const N: usize> Drop for Guard<'_, T, N> {
873 debug_assert!(self.initialized <= N);
875 // SAFETY: this slice will contain only initialized objects.
877 crate::ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(
878 &mut self.array_mut.get_unchecked_mut(..self.initialized),
884 let mut array = MaybeUninit::uninit_array::<N>();
885 let mut guard = Guard { array_mut: &mut array, initialized: 0 };
890 let item = match item_rslt.branch() {
891 ControlFlow::Break(r) => {
892 return Ok(FromResidual::from_residual(r));
894 ControlFlow::Continue(elem) => elem,
897 // SAFETY: `guard.initialized` starts at 0, is increased by one in the
898 // loop and the loop is aborted once it reaches N (which is
901 guard.array_mut.get_unchecked_mut(guard.initialized).write(item);
903 guard.initialized += 1;
906 let alive = 0..guard.initialized;
908 // SAFETY: `array` was initialized with exactly `initialized`
909 // number of elements.
910 return Err(unsafe { IntoIter::new_unchecked(array, alive) });
916 // SAFETY: All elements of the array were populated in the loop above.
917 let output = unsafe { MaybeUninit::array_assume_init(array) };
918 Ok(Try::from_output(output))
921 /// Returns the next chunk of `N` items from the iterator or errors with an
922 /// iterator over the remainder. Used for `Iterator::next_chunk`.
924 pub(crate) fn iter_next_chunk<I, const N: usize>(
926 ) -> Result<[I::Item; N], IntoIter<I::Item, N>>
930 let mut map = iter.map(NeverShortCircuit);
931 try_collect_into_array(&mut map).map(|NeverShortCircuit(arr)| arr)