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}
;
14 use crate::ops
::{Index, IndexMut}
;
15 use crate::slice
::{Iter, IterMut}
;
20 #[stable(feature = "array_value_iter", since = "1.51.0")]
21 pub use iter
::IntoIter
;
23 /// Creates an array `[T; N]` where each array element `T` is returned by the `cb` call.
27 /// * `cb`: Callback where the passed argument is the current array index.
32 /// #![feature(array_from_fn)]
34 /// let array = core::array::from_fn(|i| i);
35 /// assert_eq!(array, [0, 1, 2, 3, 4]);
38 #[unstable(feature = "array_from_fn", issue = "89379")]
39 pub fn from_fn
<F
, T
, const N
: usize>(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 `core::array::from_fn`, where the element creation can't fail, this version will return an error
53 /// if any element creation was unsuccessful.
57 /// * `cb`: Callback where the passed argument is the current array index.
62 /// #![feature(array_from_fn)]
64 /// #[derive(Debug, PartialEq)]
69 /// let array = core::array::try_from_fn(|i| Ok::<_, SomeError>(i));
70 /// assert_eq!(array, Ok([0, 1, 2, 3, 4]));
72 /// let another_array = core::array::try_from_fn::<SomeError, _, (), 2>(|_| Err(SomeError::Foo));
73 /// assert_eq!(another_array, Err(SomeError::Foo));
76 #[unstable(feature = "array_from_fn", issue = "89379")]
77 pub fn try_from_fn
<E
, F
, T
, const N
: usize>(cb
: F
) -> Result
<[T
; N
], E
>
79 F
: FnMut(usize) -> Result
<T
, E
>,
81 // SAFETY: we know for certain that this iterator will yield exactly `N`
83 unsafe { collect_into_array_rslt_unchecked(&mut (0..N).map(cb)) }
86 /// Converts a reference to `T` into a reference to an array of length 1 (without copying).
87 #[stable(feature = "array_from_ref", since = "1.53.0")]
88 #[rustc_const_unstable(feature = "const_array_from_ref", issue = "90206")]
89 pub const fn from_ref
<T
>(s
: &T
) -> &[T
; 1] {
90 // SAFETY: Converting `&T` to `&[T; 1]` is sound.
91 unsafe { &*(s as *const T).cast::<[T; 1]>() }
94 /// Converts a mutable reference to `T` into a mutable reference to an array of length 1 (without copying).
95 #[stable(feature = "array_from_ref", since = "1.53.0")]
96 #[rustc_const_unstable(feature = "const_array_from_ref", issue = "90206")]
97 pub const fn from_mut
<T
>(s
: &mut T
) -> &mut [T
; 1] {
98 // SAFETY: Converting `&mut T` to `&mut [T; 1]` is sound.
99 unsafe { &mut *(s as *mut T).cast::<[T; 1]>() }
102 /// The error type returned when a conversion from a slice to an array fails.
103 #[stable(feature = "try_from", since = "1.34.0")]
104 #[derive(Debug, Copy, Clone)]
105 pub struct TryFromSliceError(());
107 #[stable(feature = "core_array", since = "1.36.0")]
108 impl fmt
::Display
for TryFromSliceError
{
110 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
111 fmt
::Display
::fmt(self.__description(), f
)
115 impl TryFromSliceError
{
117 feature
= "array_error_internals",
118 reason
= "available through Error trait and this method should not \
119 be exposed publicly",
124 pub fn __description(&self) -> &str {
125 "could not convert slice to array"
129 #[stable(feature = "try_from_slice_error", since = "1.36.0")]
130 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
131 impl const From
<Infallible
> for TryFromSliceError
{
132 fn from(x
: Infallible
) -> TryFromSliceError
{
137 #[stable(feature = "rust1", since = "1.0.0")]
138 impl<T
, const N
: usize> AsRef
<[T
]> for [T
; N
] {
140 fn as_ref(&self) -> &[T
] {
145 #[stable(feature = "rust1", since = "1.0.0")]
146 impl<T
, const N
: usize> AsMut
<[T
]> for [T
; N
] {
148 fn as_mut(&mut self) -> &mut [T
] {
153 #[stable(feature = "array_borrow", since = "1.4.0")]
154 impl<T
, const N
: usize> Borrow
<[T
]> for [T
; N
] {
155 fn borrow(&self) -> &[T
] {
160 #[stable(feature = "array_borrow", since = "1.4.0")]
161 impl<T
, const N
: usize> BorrowMut
<[T
]> for [T
; N
] {
162 fn borrow_mut(&mut self) -> &mut [T
] {
167 #[stable(feature = "try_from", since = "1.34.0")]
168 impl<T
, const N
: usize> TryFrom
<&[T
]> for [T
; N
]
172 type Error
= TryFromSliceError
;
174 fn try_from(slice
: &[T
]) -> Result
<[T
; N
], TryFromSliceError
> {
175 <&Self>::try_from(slice
).map(|r
| *r
)
179 #[stable(feature = "try_from", since = "1.34.0")]
180 impl<'a
, T
, const N
: usize> TryFrom
<&'a
[T
]> for &'a
[T
; N
] {
181 type Error
= TryFromSliceError
;
183 fn try_from(slice
: &[T
]) -> Result
<&[T
; N
], TryFromSliceError
> {
184 if slice
.len() == N
{
185 let ptr
= slice
.as_ptr() as *const [T
; N
];
186 // SAFETY: ok because we just checked that the length fits
189 Err(TryFromSliceError(()))
194 #[stable(feature = "try_from", since = "1.34.0")]
195 impl<'a
, T
, const N
: usize> TryFrom
<&'a
mut [T
]> for &'a
mut [T
; N
] {
196 type Error
= TryFromSliceError
;
198 fn try_from(slice
: &mut [T
]) -> Result
<&mut [T
; N
], TryFromSliceError
> {
199 if slice
.len() == N
{
200 let ptr
= slice
.as_mut_ptr() as *mut [T
; N
];
201 // SAFETY: ok because we just checked that the length fits
202 unsafe { Ok(&mut *ptr) }
204 Err(TryFromSliceError(()))
209 /// The hash of an array is the same as that of the corresponding slice,
210 /// as required by the `Borrow` implementation.
213 /// #![feature(build_hasher_simple_hash_one)]
214 /// use std::hash::BuildHasher;
216 /// let b = std::collections::hash_map::RandomState::new();
217 /// let a: [u8; 3] = [0xa8, 0x3c, 0x09];
218 /// let s: &[u8] = &[0xa8, 0x3c, 0x09];
219 /// assert_eq!(b.hash_one(a), b.hash_one(s));
221 #[stable(feature = "rust1", since = "1.0.0")]
222 impl<T
: Hash
, const N
: usize> Hash
for [T
; N
] {
223 fn hash
<H
: hash
::Hasher
>(&self, state
: &mut H
) {
224 Hash
::hash(&self[..], state
)
228 #[stable(feature = "rust1", since = "1.0.0")]
229 impl<T
: fmt
::Debug
, const N
: usize> fmt
::Debug
for [T
; N
] {
230 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
231 fmt
::Debug
::fmt(&&self[..], f
)
235 // Note: the `#[rustc_skip_array_during_method_dispatch]` on `trait IntoIterator`
236 // hides this implementation from explicit `.into_iter()` calls on editions < 2021,
237 // so those calls will still resolve to the slice implementation, by reference.
238 #[stable(feature = "array_into_iter_impl", since = "1.53.0")]
239 impl<T
, const N
: usize> IntoIterator
for [T
; N
] {
241 type IntoIter
= IntoIter
<T
, N
>;
243 /// Creates a consuming iterator, that is, one that moves each value out of
244 /// the array (from start to end). The array cannot be used after calling
245 /// this unless `T` implements `Copy`, so the whole array is copied.
247 /// Arrays have special behavior when calling `.into_iter()` prior to the
248 /// 2021 edition -- see the [array] Editions section for more information.
250 /// [array]: prim@array
251 fn into_iter(self) -> Self::IntoIter
{
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 impl<T
, I
, const N
: usize> Index
<I
> for [T
; N
]
281 type Output
= <[T
] as Index
<I
>>::Output
;
284 fn index(&self, index
: I
) -> &Self::Output
{
285 Index
::index(self as &[T
], index
)
289 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
290 impl<T
, I
, const N
: usize> IndexMut
<I
> for [T
; N
]
295 fn index_mut(&mut self, index
: I
) -> &mut Self::Output
{
296 IndexMut
::index_mut(self as &mut [T
], index
)
300 #[stable(feature = "rust1", since = "1.0.0")]
301 impl<T
: PartialOrd
, const N
: usize> PartialOrd
for [T
; N
] {
303 fn partial_cmp(&self, other
: &[T
; N
]) -> Option
<Ordering
> {
304 PartialOrd
::partial_cmp(&&self[..], &&other
[..])
307 fn lt(&self, other
: &[T
; N
]) -> bool
{
308 PartialOrd
::lt(&&self[..], &&other
[..])
311 fn le(&self, other
: &[T
; N
]) -> bool
{
312 PartialOrd
::le(&&self[..], &&other
[..])
315 fn ge(&self, other
: &[T
; N
]) -> bool
{
316 PartialOrd
::ge(&&self[..], &&other
[..])
319 fn gt(&self, other
: &[T
; N
]) -> bool
{
320 PartialOrd
::gt(&&self[..], &&other
[..])
324 /// Implements comparison of arrays [lexicographically](Ord#lexicographical-comparison).
325 #[stable(feature = "rust1", since = "1.0.0")]
326 impl<T
: Ord
, const N
: usize> Ord
for [T
; N
] {
328 fn cmp(&self, other
: &[T
; N
]) -> Ordering
{
329 Ord
::cmp(&&self[..], &&other
[..])
333 #[cfg(not(bootstrap))]
334 #[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
335 impl<T
: Copy
, const N
: usize> Copy
for [T
; N
] {}
337 #[cfg(not(bootstrap))]
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 #[cfg(not(bootstrap))]
352 trait SpecArrayClone
: Clone
{
353 fn clone
<const N
: usize>(array
: &[Self; N
]) -> [Self; N
];
356 #[cfg(not(bootstrap))]
357 impl<T
: Clone
> SpecArrayClone
for T
{
359 default fn clone
<const N
: usize>(array
: &[T
; N
]) -> [T
; N
] {
360 // SAFETY: we know for certain that this iterator will yield exactly `N`
362 unsafe { collect_into_array_unchecked(&mut array.iter().cloned()) }
366 #[cfg(not(bootstrap))]
367 impl<T
: Copy
> SpecArrayClone
for T
{
369 fn clone
<const N
: usize>(array
: &[T
; N
]) -> [T
; N
] {
374 // The Default impls cannot be done with const generics because `[T; 0]` doesn't
375 // require Default to be implemented, and having different impl blocks for
376 // different numbers isn't supported yet.
378 macro_rules
! array_impl_default
{
379 {$n:expr, $t:ident $($ts:ident)*}
=> {
380 #[stable(since = "1.4.0", feature = "array_default")]
381 impl<T
> Default
for [T
; $n
] where T
: Default
{
382 fn default() -> [T
; $n
] {
383 [$t
::default(), $
($ts
::default()),*]
386 array_impl_default
!{($n - 1), $($ts)*}
389 #[stable(since = "1.4.0", feature = "array_default")]
390 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
391 impl<T
> const Default
for [T
; $n
] {
392 fn default() -> [T
; $n
] { [] }
397 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}
400 impl<T
, const N
: usize> [T
; N
] {
401 /// Returns an array of the same size as `self`, with function `f` applied to each element
404 /// If you don't necessarily need a new fixed-size array, consider using
405 /// [`Iterator::map`] instead.
408 /// # Note on performance and stack usage
410 /// Unfortunately, usages of this method are currently not always optimized
411 /// as well as they could be. This mainly concerns large arrays, as mapping
412 /// over small arrays seem to be optimized just fine. Also note that in
413 /// debug mode (i.e. without any optimizations), this method can use a lot
414 /// of stack space (a few times the size of the array or more).
416 /// Therefore, in performance-critical code, try to avoid using this method
417 /// on large arrays or check the emitted code. Also try to avoid chained
418 /// maps (e.g. `arr.map(...).map(...)`).
420 /// In many cases, you can instead use [`Iterator::map`] by calling `.iter()`
421 /// or `.into_iter()` on your array. `[T; N]::map` is only necessary if you
422 /// really need a new array of the same size as the result. Rust's lazy
423 /// iterators tend to get optimized very well.
429 /// let x = [1, 2, 3];
430 /// let y = x.map(|v| v + 1);
431 /// assert_eq!(y, [2, 3, 4]);
433 /// let x = [1, 2, 3];
434 /// let mut temp = 0;
435 /// let y = x.map(|v| { temp += 1; v * temp });
436 /// assert_eq!(y, [1, 4, 9]);
438 /// let x = ["Ferris", "Bueller's", "Day", "Off"];
439 /// let y = x.map(|v| v.len());
440 /// assert_eq!(y, [6, 9, 3, 3]);
442 #[stable(feature = "array_map", since = "1.55.0")]
443 pub fn map
<F
, U
>(self, f
: F
) -> [U
; N
]
447 // SAFETY: we know for certain that this iterator will yield exactly `N`
449 unsafe { collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
452 /// 'Zips up' two arrays into a single array of pairs.
454 /// `zip()` returns a new array where every element is a tuple where the
455 /// first element comes from the first array, and the second element comes
456 /// from the second array. In other words, it zips two arrays together,
457 /// into a single one.
462 /// #![feature(array_zip)]
463 /// let x = [1, 2, 3];
464 /// let y = [4, 5, 6];
465 /// let z = x.zip(y);
466 /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
468 #[unstable(feature = "array_zip", issue = "80094")]
469 pub fn zip
<U
>(self, rhs
: [U
; N
]) -> [(T
, U
); N
] {
470 let mut iter
= IntoIterator
::into_iter(self).zip(rhs
);
472 // SAFETY: we know for certain that this iterator will yield exactly `N`
474 unsafe { collect_into_array_unchecked(&mut iter) }
477 /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
478 #[stable(feature = "array_as_slice", since = "1.57.0")]
479 pub const fn as_slice(&self) -> &[T
] {
483 /// Returns a mutable slice containing the entire array. Equivalent to
485 #[stable(feature = "array_as_slice", since = "1.57.0")]
486 pub fn as_mut_slice(&mut self) -> &mut [T
] {
490 /// Borrows each element and returns an array of references with the same
497 /// #![feature(array_methods)]
499 /// let floats = [3.1, 2.7, -1.0];
500 /// let float_refs: [&f64; 3] = floats.each_ref();
501 /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
504 /// This method is particularly useful if combined with other methods, like
505 /// [`map`](#method.map). This way, you can avoid moving the original
506 /// array if its elements are not [`Copy`].
509 /// #![feature(array_methods)]
511 /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
512 /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
513 /// assert_eq!(is_ascii, [true, false, true]);
515 /// // We can still access the original array: it has not been moved.
516 /// assert_eq!(strings.len(), 3);
518 #[unstable(feature = "array_methods", issue = "76118")]
519 pub fn each_ref(&self) -> [&T
; N
] {
520 // SAFETY: we know for certain that this iterator will yield exactly `N`
522 unsafe { collect_into_array_unchecked(&mut self.iter()) }
525 /// Borrows each element mutably and returns an array of mutable references
526 /// with the same size as `self`.
532 /// #![feature(array_methods)]
534 /// let mut floats = [3.1, 2.7, -1.0];
535 /// let float_refs: [&mut f64; 3] = floats.each_mut();
536 /// *float_refs[0] = 0.0;
537 /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
538 /// assert_eq!(floats, [0.0, 2.7, -1.0]);
540 #[unstable(feature = "array_methods", issue = "76118")]
541 pub fn each_mut(&mut self) -> [&mut T
; N
] {
542 // SAFETY: we know for certain that this iterator will yield exactly `N`
544 unsafe { collect_into_array_unchecked(&mut self.iter_mut()) }
547 /// Divides one array reference into two at an index.
549 /// The first will contain all indices from `[0, M)` (excluding
550 /// the index `M` itself) and the second will contain all
551 /// indices from `[M, N)` (excluding the index `N` itself).
555 /// Panics if `M > N`.
560 /// #![feature(split_array)]
562 /// let v = [1, 2, 3, 4, 5, 6];
565 /// let (left, right) = v.split_array_ref::<0>();
566 /// assert_eq!(left, &[]);
567 /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
571 /// let (left, right) = v.split_array_ref::<2>();
572 /// assert_eq!(left, &[1, 2]);
573 /// assert_eq!(right, &[3, 4, 5, 6]);
577 /// let (left, right) = v.split_array_ref::<6>();
578 /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
579 /// assert_eq!(right, &[]);
583 feature
= "split_array",
584 reason
= "return type should have array as 2nd element",
588 pub fn split_array_ref
<const M
: usize>(&self) -> (&[T
; M
], &[T
]) {
589 (&self[..]).split_array_ref
::<M
>()
592 /// Divides one mutable array reference into two at an index.
594 /// The first will contain all indices from `[0, M)` (excluding
595 /// the index `M` itself) and the second will contain all
596 /// indices from `[M, N)` (excluding the index `N` itself).
600 /// Panics if `M > N`.
605 /// #![feature(split_array)]
607 /// let mut v = [1, 0, 3, 0, 5, 6];
608 /// let (left, right) = v.split_array_mut::<2>();
609 /// assert_eq!(left, &mut [1, 0][..]);
610 /// assert_eq!(right, &mut [3, 0, 5, 6]);
613 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
616 feature
= "split_array",
617 reason
= "return type should have array as 2nd element",
621 pub fn split_array_mut
<const M
: usize>(&mut self) -> (&mut [T
; M
], &mut [T
]) {
622 (&mut self[..]).split_array_mut
::<M
>()
626 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
627 /// yields fewer than `N` items, this function exhibits undefined behavior.
629 /// See [`collect_into_array`] for more information.
634 /// It is up to the caller to guarantee that `iter` yields at least `N` items.
635 /// Violating this condition causes undefined behavior.
636 unsafe fn collect_into_array_rslt_unchecked
<E
, I
, T
, const N
: usize>(
638 ) -> Result
<[T
; N
], E
>
640 // Note: `TrustedLen` here is somewhat of an experiment. This is just an
641 // internal function, so feel free to remove if this bound turns out to be a
642 // bad idea. In that case, remember to also remove the lower bound
643 // `debug_assert!` below!
644 I
: Iterator
<Item
= Result
<T
, E
>> + TrustedLen
,
646 debug_assert
!(N
<= iter
.size_hint().1.unwrap_or
(usize::MAX
));
647 debug_assert
!(N
<= iter
.size_hint().0);
649 // SAFETY: covered by the function contract.
650 unsafe { collect_into_array(iter).unwrap_unchecked() }
653 // Infallible version of `collect_into_array_rslt_unchecked`.
654 unsafe fn collect_into_array_unchecked
<I
, const N
: usize>(iter
: &mut I
) -> [I
::Item
; N
]
656 I
: Iterator
+ TrustedLen
,
658 let mut map
= iter
.map(Ok
::<_
, Infallible
>);
660 // SAFETY: The same safety considerations w.r.t. the iterator length
661 // apply for `collect_into_array_rslt_unchecked` as for
662 // `collect_into_array_unchecked`
663 match unsafe { collect_into_array_rslt_unchecked(&mut map) }
{
668 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
669 /// yields fewer than `N` items, `None` is returned and all already yielded
670 /// items are dropped.
672 /// Since the iterator is passed as a mutable reference and this function calls
673 /// `next` at most `N` times, the iterator can still be used afterwards to
674 /// retrieve the remaining items.
676 /// If `iter.next()` panicks, all items already yielded by the iterator are
678 fn collect_into_array
<E
, I
, T
, const N
: usize>(iter
: &mut I
) -> Option
<Result
<[T
; N
], E
>>
680 I
: Iterator
<Item
= Result
<T
, E
>>,
683 // SAFETY: An empty array is always inhabited and has no validity invariants.
684 return unsafe { Some(Ok(mem::zeroed())) }
;
687 struct Guard
<'a
, T
, const N
: usize> {
688 array_mut
: &'a
mut [MaybeUninit
<T
>; N
],
692 impl<T
, const N
: usize> Drop
for Guard
<'_
, T
, N
> {
694 debug_assert
!(self.initialized
<= N
);
696 // SAFETY: this slice will contain only initialized objects.
698 crate::ptr
::drop_in_place(MaybeUninit
::slice_assume_init_mut(
699 &mut self.array_mut
.get_unchecked_mut(..self.initialized
),
705 let mut array
= MaybeUninit
::uninit_array
::<N
>();
706 let mut guard
= Guard { array_mut: &mut array, initialized: 0 }
;
708 while let Some(item_rslt
) = iter
.next() {
709 let item
= match item_rslt
{
711 return Some(Err(err
));
716 // SAFETY: `guard.initialized` starts at 0, is increased by one in the
717 // loop and the loop is aborted once it reaches N (which is
720 guard
.array_mut
.get_unchecked_mut(guard
.initialized
).write(item
);
722 guard
.initialized
+= 1;
724 // Check if the whole array was initialized.
725 if guard
.initialized
== N
{
728 // SAFETY: the condition above asserts that all elements are
730 let out
= unsafe { MaybeUninit::array_assume_init(array) }
;
731 return Some(Ok(out
));
735 // This is only reached if the iterator is exhausted before
736 // `guard.initialized` reaches `N`. Also note that `guard` is dropped here,
737 // dropping all already initialized elements.