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 pub fn from_ref<T>(s: &T) -> &[T; 1] {
89 // SAFETY: Converting `&T` to `&[T; 1]` is sound.
90 unsafe { &*(s as *const T).cast::<[T; 1]>() }
93 /// Converts a mutable reference to `T` into a mutable reference to an array of length 1 (without copying).
94 #[stable(feature = "array_from_ref", since = "1.53.0")]
95 pub fn from_mut<T>(s: &mut T) -> &mut [T; 1] {
96 // SAFETY: Converting `&mut T` to `&mut [T; 1]` is sound.
97 unsafe { &mut *(s as *mut T).cast::<[T; 1]>() }
100 /// The error type returned when a conversion from a slice to an array fails.
101 #[stable(feature = "try_from", since = "1.34.0")]
102 #[derive(Debug, Copy, Clone)]
103 pub struct TryFromSliceError(());
105 #[stable(feature = "core_array", since = "1.36.0")]
106 impl fmt::Display for TryFromSliceError {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109 fmt::Display::fmt(self.__description(), f)
113 impl TryFromSliceError {
115 feature = "array_error_internals",
116 reason = "available through Error trait and this method should not \
117 be exposed publicly",
122 pub fn __description(&self) -> &str {
123 "could not convert slice to array"
127 #[stable(feature = "try_from_slice_error", since = "1.36.0")]
128 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
129 impl const From<Infallible> for TryFromSliceError {
130 fn from(x: Infallible) -> TryFromSliceError {
135 #[stable(feature = "rust1", since = "1.0.0")]
136 impl<T, const N: usize> AsRef<[T]> for [T; N] {
138 fn as_ref(&self) -> &[T] {
143 #[stable(feature = "rust1", since = "1.0.0")]
144 impl<T, const N: usize> AsMut<[T]> for [T; N] {
146 fn as_mut(&mut self) -> &mut [T] {
151 #[stable(feature = "array_borrow", since = "1.4.0")]
152 impl<T, const N: usize> Borrow<[T]> for [T; N] {
153 fn borrow(&self) -> &[T] {
158 #[stable(feature = "array_borrow", since = "1.4.0")]
159 impl<T, const N: usize> BorrowMut<[T]> for [T; N] {
160 fn borrow_mut(&mut self) -> &mut [T] {
165 #[stable(feature = "try_from", since = "1.34.0")]
166 impl<T, const N: usize> TryFrom<&[T]> for [T; N]
170 type Error = TryFromSliceError;
172 fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError> {
173 <&Self>::try_from(slice).map(|r| *r)
177 #[stable(feature = "try_from", since = "1.34.0")]
178 impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N] {
179 type Error = TryFromSliceError;
181 fn try_from(slice: &[T]) -> Result<&[T; N], TryFromSliceError> {
182 if slice.len() == N {
183 let ptr = slice.as_ptr() as *const [T; N];
184 // SAFETY: ok because we just checked that the length fits
187 Err(TryFromSliceError(()))
192 #[stable(feature = "try_from", since = "1.34.0")]
193 impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N] {
194 type Error = TryFromSliceError;
196 fn try_from(slice: &mut [T]) -> Result<&mut [T; N], TryFromSliceError> {
197 if slice.len() == N {
198 let ptr = slice.as_mut_ptr() as *mut [T; N];
199 // SAFETY: ok because we just checked that the length fits
200 unsafe { Ok(&mut *ptr) }
202 Err(TryFromSliceError(()))
207 /// The hash of an array is the same as that of the corresponding slice,
208 /// as required by the `Borrow` implementation.
211 /// #![feature(build_hasher_simple_hash_one)]
212 /// use std::hash::BuildHasher;
214 /// let b = std::collections::hash_map::RandomState::new();
215 /// let a: [u8; 3] = [0xa8, 0x3c, 0x09];
216 /// let s: &[u8] = &[0xa8, 0x3c, 0x09];
217 /// assert_eq!(b.hash_one(a), b.hash_one(s));
219 #[stable(feature = "rust1", since = "1.0.0")]
220 impl<T: Hash, const N: usize> Hash for [T; N] {
221 fn hash<H: hash::Hasher>(&self, state: &mut H) {
222 Hash::hash(&self[..], state)
226 #[stable(feature = "rust1", since = "1.0.0")]
227 impl<T: fmt::Debug, const N: usize> fmt::Debug for [T; N] {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 fmt::Debug::fmt(&&self[..], f)
233 // Note: the `#[rustc_skip_array_during_method_dispatch]` on `trait IntoIterator`
234 // hides this implementation from explicit `.into_iter()` calls on editions < 2021,
235 // so those calls will still resolve to the slice implementation, by reference.
236 #[stable(feature = "array_into_iter_impl", since = "1.53.0")]
237 impl<T, const N: usize> IntoIterator for [T; N] {
239 type IntoIter = IntoIter<T, N>;
241 /// Creates a consuming iterator, that is, one that moves each value out of
242 /// the array (from start to end). The array cannot be used after calling
243 /// this unless `T` implements `Copy`, so the whole array is copied.
245 /// Arrays have special behavior when calling `.into_iter()` prior to the
246 /// 2021 edition -- see the [array] Editions section for more information.
248 /// [array]: prim@array
249 fn into_iter(self) -> Self::IntoIter {
254 #[stable(feature = "rust1", since = "1.0.0")]
255 impl<'a, T, const N: usize> IntoIterator for &'a [T; N] {
257 type IntoIter = Iter<'a, T>;
259 fn into_iter(self) -> Iter<'a, T> {
264 #[stable(feature = "rust1", since = "1.0.0")]
265 impl<'a, T, const N: usize> IntoIterator for &'a mut [T; N] {
266 type Item = &'a mut T;
267 type IntoIter = IterMut<'a, T>;
269 fn into_iter(self) -> IterMut<'a, T> {
274 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
275 impl<T, I, const N: usize> Index<I> for [T; N]
279 type Output = <[T] as Index<I>>::Output;
282 fn index(&self, index: I) -> &Self::Output {
283 Index::index(self as &[T], index)
287 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
288 impl<T, I, const N: usize> IndexMut<I> for [T; N]
293 fn index_mut(&mut self, index: I) -> &mut Self::Output {
294 IndexMut::index_mut(self as &mut [T], index)
298 #[stable(feature = "rust1", since = "1.0.0")]
299 impl<T: PartialOrd, const N: usize> PartialOrd for [T; N] {
301 fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
302 PartialOrd::partial_cmp(&&self[..], &&other[..])
305 fn lt(&self, other: &[T; N]) -> bool {
306 PartialOrd::lt(&&self[..], &&other[..])
309 fn le(&self, other: &[T; N]) -> bool {
310 PartialOrd::le(&&self[..], &&other[..])
313 fn ge(&self, other: &[T; N]) -> bool {
314 PartialOrd::ge(&&self[..], &&other[..])
317 fn gt(&self, other: &[T; N]) -> bool {
318 PartialOrd::gt(&&self[..], &&other[..])
322 /// Implements comparison of arrays [lexicographically](Ord#lexicographical-comparison).
323 #[stable(feature = "rust1", since = "1.0.0")]
324 impl<T: Ord, const N: usize> Ord for [T; N] {
326 fn cmp(&self, other: &[T; N]) -> Ordering {
327 Ord::cmp(&&self[..], &&other[..])
331 // The Default impls cannot be done with const generics because `[T; 0]` doesn't
332 // require Default to be implemented, and having different impl blocks for
333 // different numbers isn't supported yet.
335 macro_rules! array_impl_default {
336 {$n:expr, $t:ident $($ts:ident)*} => {
337 #[stable(since = "1.4.0", feature = "array_default")]
338 impl<T> Default for [T; $n] where T: Default {
339 fn default() -> [T; $n] {
340 [$t::default(), $($ts::default()),*]
343 array_impl_default!{($n - 1), $($ts)*}
346 #[stable(since = "1.4.0", feature = "array_default")]
347 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
348 impl<T> const Default for [T; $n] {
349 fn default() -> [T; $n] { [] }
354 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}
357 impl<T, const N: usize> [T; N] {
358 /// Returns an array of the same size as `self`, with function `f` applied to each element
361 /// If you don't necessarily need a new fixed-size array, consider using
362 /// [`Iterator::map`] instead.
365 /// # Note on performance and stack usage
367 /// Unfortunately, usages of this method are currently not always optimized
368 /// as well as they could be. This mainly concerns large arrays, as mapping
369 /// over small arrays seem to be optimized just fine. Also note that in
370 /// debug mode (i.e. without any optimizations), this method can use a lot
371 /// of stack space (a few times the size of the array or more).
373 /// Therefore, in performance-critical code, try to avoid using this method
374 /// on large arrays or check the emitted code. Also try to avoid chained
375 /// maps (e.g. `arr.map(...).map(...)`).
377 /// In many cases, you can instead use [`Iterator::map`] by calling `.iter()`
378 /// or `.into_iter()` on your array. `[T; N]::map` is only necessary if you
379 /// really need a new array of the same size as the result. Rust's lazy
380 /// iterators tend to get optimized very well.
386 /// let x = [1, 2, 3];
387 /// let y = x.map(|v| v + 1);
388 /// assert_eq!(y, [2, 3, 4]);
390 /// let x = [1, 2, 3];
391 /// let mut temp = 0;
392 /// let y = x.map(|v| { temp += 1; v * temp });
393 /// assert_eq!(y, [1, 4, 9]);
395 /// let x = ["Ferris", "Bueller's", "Day", "Off"];
396 /// let y = x.map(|v| v.len());
397 /// assert_eq!(y, [6, 9, 3, 3]);
399 #[stable(feature = "array_map", since = "1.55.0")]
400 pub fn map<F, U>(self, f: F) -> [U; N]
404 // SAFETY: we know for certain that this iterator will yield exactly `N`
406 unsafe { collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
409 /// 'Zips up' two arrays into a single array of pairs.
411 /// `zip()` returns a new array where every element is a tuple where the
412 /// first element comes from the first array, and the second element comes
413 /// from the second array. In other words, it zips two arrays together,
414 /// into a single one.
419 /// #![feature(array_zip)]
420 /// let x = [1, 2, 3];
421 /// let y = [4, 5, 6];
422 /// let z = x.zip(y);
423 /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
425 #[unstable(feature = "array_zip", issue = "80094")]
426 pub fn zip<U>(self, rhs: [U; N]) -> [(T, U); N] {
427 let mut iter = IntoIterator::into_iter(self).zip(rhs);
429 // SAFETY: we know for certain that this iterator will yield exactly `N`
431 unsafe { collect_into_array_unchecked(&mut iter) }
434 /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
435 #[stable(feature = "array_as_slice", since = "1.57.0")]
436 pub const fn as_slice(&self) -> &[T] {
440 /// Returns a mutable slice containing the entire array. Equivalent to
442 #[stable(feature = "array_as_slice", since = "1.57.0")]
443 pub fn as_mut_slice(&mut self) -> &mut [T] {
447 /// Borrows each element and returns an array of references with the same
454 /// #![feature(array_methods)]
456 /// let floats = [3.1, 2.7, -1.0];
457 /// let float_refs: [&f64; 3] = floats.each_ref();
458 /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
461 /// This method is particularly useful if combined with other methods, like
462 /// [`map`](#method.map). This way, you can avoid moving the original
463 /// array if its elements are not [`Copy`].
466 /// #![feature(array_methods)]
468 /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
469 /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
470 /// assert_eq!(is_ascii, [true, false, true]);
472 /// // We can still access the original array: it has not been moved.
473 /// assert_eq!(strings.len(), 3);
475 #[unstable(feature = "array_methods", issue = "76118")]
476 pub fn each_ref(&self) -> [&T; N] {
477 // SAFETY: we know for certain that this iterator will yield exactly `N`
479 unsafe { collect_into_array_unchecked(&mut self.iter()) }
482 /// Borrows each element mutably and returns an array of mutable references
483 /// with the same size as `self`.
489 /// #![feature(array_methods)]
491 /// let mut floats = [3.1, 2.7, -1.0];
492 /// let float_refs: [&mut f64; 3] = floats.each_mut();
493 /// *float_refs[0] = 0.0;
494 /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
495 /// assert_eq!(floats, [0.0, 2.7, -1.0]);
497 #[unstable(feature = "array_methods", issue = "76118")]
498 pub fn each_mut(&mut self) -> [&mut T; N] {
499 // SAFETY: we know for certain that this iterator will yield exactly `N`
501 unsafe { collect_into_array_unchecked(&mut self.iter_mut()) }
505 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
506 /// yields fewer than `N` items, this function exhibits undefined behavior.
508 /// See [`collect_into_array`] for more information.
513 /// It is up to the caller to guarantee that `iter` yields at least `N` items.
514 /// Violating this condition causes undefined behavior.
515 unsafe fn collect_into_array_rslt_unchecked<E, I, T, const N: usize>(
517 ) -> Result<[T; N], E>
519 // Note: `TrustedLen` here is somewhat of an experiment. This is just an
520 // internal function, so feel free to remove if this bound turns out to be a
521 // bad idea. In that case, remember to also remove the lower bound
522 // `debug_assert!` below!
523 I: Iterator<Item = Result<T, E>> + TrustedLen,
525 debug_assert!(N <= iter.size_hint().1.unwrap_or(usize::MAX));
526 debug_assert!(N <= iter.size_hint().0);
528 // SAFETY: covered by the function contract.
529 unsafe { collect_into_array(iter).unwrap_unchecked() }
532 // Infallible version of `collect_into_array_rslt_unchecked`.
533 unsafe fn collect_into_array_unchecked<I, const N: usize>(iter: &mut I) -> [I::Item; N]
535 I: Iterator + TrustedLen,
537 let mut map = iter.map(Ok::<_, Infallible>);
539 // SAFETY: The same safety considerations w.r.t. the iterator length
540 // apply for `collect_into_array_rslt_unchecked` as for
541 // `collect_into_array_unchecked`
542 match unsafe { collect_into_array_rslt_unchecked(&mut map) } {
547 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
548 /// yields fewer than `N` items, `None` is returned and all already yielded
549 /// items are dropped.
551 /// Since the iterator is passed as a mutable reference and this function calls
552 /// `next` at most `N` times, the iterator can still be used afterwards to
553 /// retrieve the remaining items.
555 /// If `iter.next()` panicks, all items already yielded by the iterator are
557 fn collect_into_array<E, I, T, const N: usize>(iter: &mut I) -> Option<Result<[T; N], E>>
559 I: Iterator<Item = Result<T, E>>,
562 // SAFETY: An empty array is always inhabited and has no validity invariants.
563 return unsafe { Some(Ok(mem::zeroed())) };
566 struct Guard<'a, T, const N: usize> {
567 array_mut: &'a mut [MaybeUninit<T>; N],
571 impl<T, const N: usize> Drop for Guard<'_, T, N> {
573 debug_assert!(self.initialized <= N);
575 // SAFETY: this slice will contain only initialized objects.
577 crate::ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(
578 &mut self.array_mut.get_unchecked_mut(..self.initialized),
584 let mut array = MaybeUninit::uninit_array::<N>();
585 let mut guard = Guard { array_mut: &mut array, initialized: 0 };
587 while let Some(item_rslt) = iter.next() {
588 let item = match item_rslt {
590 return Some(Err(err));
595 // SAFETY: `guard.initialized` starts at 0, is increased by one in the
596 // loop and the loop is aborted once it reaches N (which is
599 guard.array_mut.get_unchecked_mut(guard.initialized).write(item);
601 guard.initialized += 1;
603 // Check if the whole array was initialized.
604 if guard.initialized == N {
607 // SAFETY: the condition above asserts that all elements are
609 let out = unsafe { MaybeUninit::array_assume_init(array) };
610 return Some(Ok(out));
614 // This is only reached if the iterator is exhausted before
615 // `guard.initialized` reaches `N`. Also note that `guard` is dropped here,
616 // dropping all already initialized elements.