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 // The Default impls cannot be done with const generics because `[T; 0]` doesn't
334 // require Default to be implemented, and having different impl blocks for
335 // different numbers isn't supported yet.
337 macro_rules! array_impl_default {
338 {$n:expr, $t:ident $($ts:ident)*} => {
339 #[stable(since = "1.4.0", feature = "array_default")]
340 impl<T> Default for [T; $n] where T: Default {
341 fn default() -> [T; $n] {
342 [$t::default(), $($ts::default()),*]
345 array_impl_default!{($n - 1), $($ts)*}
348 #[stable(since = "1.4.0", feature = "array_default")]
349 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
350 impl<T> const Default for [T; $n] {
351 fn default() -> [T; $n] { [] }
356 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}
359 impl<T, const N: usize> [T; N] {
360 /// Returns an array of the same size as `self`, with function `f` applied to each element
363 /// If you don't necessarily need a new fixed-size array, consider using
364 /// [`Iterator::map`] instead.
367 /// # Note on performance and stack usage
369 /// Unfortunately, usages of this method are currently not always optimized
370 /// as well as they could be. This mainly concerns large arrays, as mapping
371 /// over small arrays seem to be optimized just fine. Also note that in
372 /// debug mode (i.e. without any optimizations), this method can use a lot
373 /// of stack space (a few times the size of the array or more).
375 /// Therefore, in performance-critical code, try to avoid using this method
376 /// on large arrays or check the emitted code. Also try to avoid chained
377 /// maps (e.g. `arr.map(...).map(...)`).
379 /// In many cases, you can instead use [`Iterator::map`] by calling `.iter()`
380 /// or `.into_iter()` on your array. `[T; N]::map` is only necessary if you
381 /// really need a new array of the same size as the result. Rust's lazy
382 /// iterators tend to get optimized very well.
388 /// let x = [1, 2, 3];
389 /// let y = x.map(|v| v + 1);
390 /// assert_eq!(y, [2, 3, 4]);
392 /// let x = [1, 2, 3];
393 /// let mut temp = 0;
394 /// let y = x.map(|v| { temp += 1; v * temp });
395 /// assert_eq!(y, [1, 4, 9]);
397 /// let x = ["Ferris", "Bueller's", "Day", "Off"];
398 /// let y = x.map(|v| v.len());
399 /// assert_eq!(y, [6, 9, 3, 3]);
401 #[stable(feature = "array_map", since = "1.55.0")]
402 pub fn map<F, U>(self, f: F) -> [U; N]
406 // SAFETY: we know for certain that this iterator will yield exactly `N`
408 unsafe { collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
411 /// 'Zips up' two arrays into a single array of pairs.
413 /// `zip()` returns a new array where every element is a tuple where the
414 /// first element comes from the first array, and the second element comes
415 /// from the second array. In other words, it zips two arrays together,
416 /// into a single one.
421 /// #![feature(array_zip)]
422 /// let x = [1, 2, 3];
423 /// let y = [4, 5, 6];
424 /// let z = x.zip(y);
425 /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
427 #[unstable(feature = "array_zip", issue = "80094")]
428 pub fn zip<U>(self, rhs: [U; N]) -> [(T, U); N] {
429 let mut iter = IntoIterator::into_iter(self).zip(rhs);
431 // SAFETY: we know for certain that this iterator will yield exactly `N`
433 unsafe { collect_into_array_unchecked(&mut iter) }
436 /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
437 #[stable(feature = "array_as_slice", since = "1.57.0")]
438 pub const fn as_slice(&self) -> &[T] {
442 /// Returns a mutable slice containing the entire array. Equivalent to
444 #[stable(feature = "array_as_slice", since = "1.57.0")]
445 pub fn as_mut_slice(&mut self) -> &mut [T] {
449 /// Borrows each element and returns an array of references with the same
456 /// #![feature(array_methods)]
458 /// let floats = [3.1, 2.7, -1.0];
459 /// let float_refs: [&f64; 3] = floats.each_ref();
460 /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
463 /// This method is particularly useful if combined with other methods, like
464 /// [`map`](#method.map). This way, you can avoid moving the original
465 /// array if its elements are not [`Copy`].
468 /// #![feature(array_methods)]
470 /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
471 /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
472 /// assert_eq!(is_ascii, [true, false, true]);
474 /// // We can still access the original array: it has not been moved.
475 /// assert_eq!(strings.len(), 3);
477 #[unstable(feature = "array_methods", issue = "76118")]
478 pub fn each_ref(&self) -> [&T; N] {
479 // SAFETY: we know for certain that this iterator will yield exactly `N`
481 unsafe { collect_into_array_unchecked(&mut self.iter()) }
484 /// Borrows each element mutably and returns an array of mutable references
485 /// with the same size as `self`.
491 /// #![feature(array_methods)]
493 /// let mut floats = [3.1, 2.7, -1.0];
494 /// let float_refs: [&mut f64; 3] = floats.each_mut();
495 /// *float_refs[0] = 0.0;
496 /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
497 /// assert_eq!(floats, [0.0, 2.7, -1.0]);
499 #[unstable(feature = "array_methods", issue = "76118")]
500 pub fn each_mut(&mut self) -> [&mut T; N] {
501 // SAFETY: we know for certain that this iterator will yield exactly `N`
503 unsafe { collect_into_array_unchecked(&mut self.iter_mut()) }
506 /// Divides one array reference into two at an index.
508 /// The first will contain all indices from `[0, M)` (excluding
509 /// the index `M` itself) and the second will contain all
510 /// indices from `[M, N)` (excluding the index `N` itself).
514 /// Panics if `M > N`.
519 /// #![feature(split_array)]
521 /// let v = [1, 2, 3, 4, 5, 6];
524 /// let (left, right) = v.split_array_ref::<0>();
525 /// assert_eq!(left, &[]);
526 /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
530 /// let (left, right) = v.split_array_ref::<2>();
531 /// assert_eq!(left, &[1, 2]);
532 /// assert_eq!(right, &[3, 4, 5, 6]);
536 /// let (left, right) = v.split_array_ref::<6>();
537 /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
538 /// assert_eq!(right, &[]);
542 feature = "split_array",
543 reason = "return type should have array as 2nd element",
547 pub fn split_array_ref<const M: usize>(&self) -> (&[T; M], &[T]) {
548 (&self[..]).split_array_ref::<M>()
551 /// Divides one mutable array reference into two at an index.
553 /// The first will contain all indices from `[0, M)` (excluding
554 /// the index `M` itself) and the second will contain all
555 /// indices from `[M, N)` (excluding the index `N` itself).
559 /// Panics if `M > N`.
564 /// #![feature(split_array)]
566 /// let mut v = [1, 0, 3, 0, 5, 6];
567 /// let (left, right) = v.split_array_mut::<2>();
568 /// assert_eq!(left, &mut [1, 0][..]);
569 /// assert_eq!(right, &mut [3, 0, 5, 6]);
572 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
575 feature = "split_array",
576 reason = "return type should have array as 2nd element",
580 pub fn split_array_mut<const M: usize>(&mut self) -> (&mut [T; M], &mut [T]) {
581 (&mut self[..]).split_array_mut::<M>()
585 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
586 /// yields fewer than `N` items, this function exhibits undefined behavior.
588 /// See [`collect_into_array`] for more information.
593 /// It is up to the caller to guarantee that `iter` yields at least `N` items.
594 /// Violating this condition causes undefined behavior.
595 unsafe fn collect_into_array_rslt_unchecked<E, I, T, const N: usize>(
597 ) -> Result<[T; N], E>
599 // Note: `TrustedLen` here is somewhat of an experiment. This is just an
600 // internal function, so feel free to remove if this bound turns out to be a
601 // bad idea. In that case, remember to also remove the lower bound
602 // `debug_assert!` below!
603 I: Iterator<Item = Result<T, E>> + TrustedLen,
605 debug_assert!(N <= iter.size_hint().1.unwrap_or(usize::MAX));
606 debug_assert!(N <= iter.size_hint().0);
608 // SAFETY: covered by the function contract.
609 unsafe { collect_into_array(iter).unwrap_unchecked() }
612 // Infallible version of `collect_into_array_rslt_unchecked`.
613 unsafe fn collect_into_array_unchecked<I, const N: usize>(iter: &mut I) -> [I::Item; N]
615 I: Iterator + TrustedLen,
617 let mut map = iter.map(Ok::<_, Infallible>);
619 // SAFETY: The same safety considerations w.r.t. the iterator length
620 // apply for `collect_into_array_rslt_unchecked` as for
621 // `collect_into_array_unchecked`
622 match unsafe { collect_into_array_rslt_unchecked(&mut map) } {
627 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
628 /// yields fewer than `N` items, `None` is returned and all already yielded
629 /// items are dropped.
631 /// Since the iterator is passed as a mutable reference and this function calls
632 /// `next` at most `N` times, the iterator can still be used afterwards to
633 /// retrieve the remaining items.
635 /// If `iter.next()` panicks, all items already yielded by the iterator are
637 fn collect_into_array<E, I, T, const N: usize>(iter: &mut I) -> Option<Result<[T; N], E>>
639 I: Iterator<Item = Result<T, E>>,
642 // SAFETY: An empty array is always inhabited and has no validity invariants.
643 return unsafe { Some(Ok(mem::zeroed())) };
646 struct Guard<'a, T, const N: usize> {
647 array_mut: &'a mut [MaybeUninit<T>; N],
651 impl<T, const N: usize> Drop for Guard<'_, T, N> {
653 debug_assert!(self.initialized <= N);
655 // SAFETY: this slice will contain only initialized objects.
657 crate::ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(
658 &mut self.array_mut.get_unchecked_mut(..self.initialized),
664 let mut array = MaybeUninit::uninit_array::<N>();
665 let mut guard = Guard { array_mut: &mut array, initialized: 0 };
667 while let Some(item_rslt) = iter.next() {
668 let item = match item_rslt {
670 return Some(Err(err));
675 // SAFETY: `guard.initialized` starts at 0, is increased by one in the
676 // loop and the loop is aborted once it reaches N (which is
679 guard.array_mut.get_unchecked_mut(guard.initialized).write(item);
681 guard.initialized += 1;
683 // Check if the whole array was initialized.
684 if guard.initialized == N {
687 // SAFETY: the condition above asserts that all elements are
689 let out = unsafe { MaybeUninit::array_assume_init(array) };
690 return Some(Ok(out));
694 // This is only reached if the iterator is exhausted before
695 // `guard.initialized` reaches `N`. Also note that `guard` is dropped here,
696 // dropping all already initialized elements.