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 /// Converts a reference to `T` into a reference to an array of length 1 (without copying).
24 #[stable(feature = "array_from_ref", since = "1.53.0")]
25 pub fn from_ref<T>(s: &T) -> &[T; 1] {
26 // SAFETY: Converting `&T` to `&[T; 1]` is sound.
27 unsafe { &*(s as *const T).cast::<[T; 1]>() }
30 /// Converts a mutable reference to `T` into a mutable reference to an array of length 1 (without copying).
31 #[stable(feature = "array_from_ref", since = "1.53.0")]
32 pub fn from_mut<T>(s: &mut T) -> &mut [T; 1] {
33 // SAFETY: Converting `&mut T` to `&mut [T; 1]` is sound.
34 unsafe { &mut *(s as *mut T).cast::<[T; 1]>() }
37 /// The error type returned when a conversion from a slice to an array fails.
38 #[stable(feature = "try_from", since = "1.34.0")]
39 #[derive(Debug, Copy, Clone)]
40 pub struct TryFromSliceError(());
42 #[stable(feature = "core_array", since = "1.36.0")]
43 impl fmt::Display for TryFromSliceError {
45 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46 fmt::Display::fmt(self.__description(), f)
50 impl TryFromSliceError {
52 feature = "array_error_internals",
53 reason = "available through Error trait and this method should not \
59 pub fn __description(&self) -> &str {
60 "could not convert slice to array"
64 #[stable(feature = "try_from_slice_error", since = "1.36.0")]
65 impl From<Infallible> for TryFromSliceError {
66 fn from(x: Infallible) -> TryFromSliceError {
71 #[stable(feature = "rust1", since = "1.0.0")]
72 impl<T, const N: usize> AsRef<[T]> for [T; N] {
74 fn as_ref(&self) -> &[T] {
79 #[stable(feature = "rust1", since = "1.0.0")]
80 impl<T, const N: usize> AsMut<[T]> for [T; N] {
82 fn as_mut(&mut self) -> &mut [T] {
87 #[stable(feature = "array_borrow", since = "1.4.0")]
88 impl<T, const N: usize> Borrow<[T]> for [T; N] {
89 fn borrow(&self) -> &[T] {
94 #[stable(feature = "array_borrow", since = "1.4.0")]
95 impl<T, const N: usize> BorrowMut<[T]> for [T; N] {
96 fn borrow_mut(&mut self) -> &mut [T] {
101 #[stable(feature = "try_from", since = "1.34.0")]
102 impl<T, const N: usize> TryFrom<&[T]> for [T; N]
106 type Error = TryFromSliceError;
108 fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError> {
109 <&Self>::try_from(slice).map(|r| *r)
113 #[stable(feature = "try_from", since = "1.34.0")]
114 impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N] {
115 type Error = TryFromSliceError;
117 fn try_from(slice: &[T]) -> Result<&[T; N], TryFromSliceError> {
118 if slice.len() == N {
119 let ptr = slice.as_ptr() as *const [T; N];
120 // SAFETY: ok because we just checked that the length fits
123 Err(TryFromSliceError(()))
128 #[stable(feature = "try_from", since = "1.34.0")]
129 impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N] {
130 type Error = TryFromSliceError;
132 fn try_from(slice: &mut [T]) -> Result<&mut [T; N], TryFromSliceError> {
133 if slice.len() == N {
134 let ptr = slice.as_mut_ptr() as *mut [T; N];
135 // SAFETY: ok because we just checked that the length fits
136 unsafe { Ok(&mut *ptr) }
138 Err(TryFromSliceError(()))
143 /// The hash of an array is the same as that of the corresponding slice,
144 /// as required by the `Borrow` implementation.
147 /// #![feature(build_hasher_simple_hash_one)]
148 /// use std::hash::BuildHasher;
150 /// let b = std::collections::hash_map::RandomState::new();
151 /// let a: [u8; 3] = [0xa8, 0x3c, 0x09];
152 /// let s: &[u8] = &[0xa8, 0x3c, 0x09];
153 /// assert_eq!(b.hash_one(a), b.hash_one(s));
155 #[stable(feature = "rust1", since = "1.0.0")]
156 impl<T: Hash, const N: usize> Hash for [T; N] {
157 fn hash<H: hash::Hasher>(&self, state: &mut H) {
158 Hash::hash(&self[..], state)
162 #[stable(feature = "rust1", since = "1.0.0")]
163 impl<T: fmt::Debug, const N: usize> fmt::Debug for [T; N] {
164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165 fmt::Debug::fmt(&&self[..], f)
169 // Note: the `#[rustc_skip_array_during_method_dispatch]` on `trait IntoIterator`
170 // hides this implementation from explicit `.into_iter()` calls on editions < 2021,
171 // so those calls will still resolve to the slice implementation, by reference.
172 #[stable(feature = "array_into_iter_impl", since = "1.53.0")]
173 impl<T, const N: usize> IntoIterator for [T; N] {
175 type IntoIter = IntoIter<T, N>;
177 /// Creates a consuming iterator, that is, one that moves each value out of
178 /// the array (from start to end). The array cannot be used after calling
179 /// this unless `T` implements `Copy`, so the whole array is copied.
181 /// Arrays have special behavior when calling `.into_iter()` prior to the
182 /// 2021 edition -- see the [array] Editions section for more information.
184 /// [array]: prim@array
185 fn into_iter(self) -> Self::IntoIter {
190 #[stable(feature = "rust1", since = "1.0.0")]
191 impl<'a, T, const N: usize> IntoIterator for &'a [T; N] {
193 type IntoIter = Iter<'a, T>;
195 fn into_iter(self) -> Iter<'a, T> {
200 #[stable(feature = "rust1", since = "1.0.0")]
201 impl<'a, T, const N: usize> IntoIterator for &'a mut [T; N] {
202 type Item = &'a mut T;
203 type IntoIter = IterMut<'a, T>;
205 fn into_iter(self) -> IterMut<'a, T> {
210 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
211 impl<T, I, const N: usize> Index<I> for [T; N]
215 type Output = <[T] as Index<I>>::Output;
218 fn index(&self, index: I) -> &Self::Output {
219 Index::index(self as &[T], index)
223 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
224 impl<T, I, const N: usize> IndexMut<I> for [T; N]
229 fn index_mut(&mut self, index: I) -> &mut Self::Output {
230 IndexMut::index_mut(self as &mut [T], index)
234 #[stable(feature = "rust1", since = "1.0.0")]
235 impl<T: PartialOrd, const N: usize> PartialOrd for [T; N] {
237 fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
238 PartialOrd::partial_cmp(&&self[..], &&other[..])
241 fn lt(&self, other: &[T; N]) -> bool {
242 PartialOrd::lt(&&self[..], &&other[..])
245 fn le(&self, other: &[T; N]) -> bool {
246 PartialOrd::le(&&self[..], &&other[..])
249 fn ge(&self, other: &[T; N]) -> bool {
250 PartialOrd::ge(&&self[..], &&other[..])
253 fn gt(&self, other: &[T; N]) -> bool {
254 PartialOrd::gt(&&self[..], &&other[..])
258 /// Implements comparison of arrays [lexicographically](Ord#lexicographical-comparison).
259 #[stable(feature = "rust1", since = "1.0.0")]
260 impl<T: Ord, const N: usize> Ord for [T; N] {
262 fn cmp(&self, other: &[T; N]) -> Ordering {
263 Ord::cmp(&&self[..], &&other[..])
267 // The Default impls cannot be done with const generics because `[T; 0]` doesn't
268 // require Default to be implemented, and having different impl blocks for
269 // different numbers isn't supported yet.
271 macro_rules! array_impl_default {
272 {$n:expr, $t:ident $($ts:ident)*} => {
273 #[stable(since = "1.4.0", feature = "array_default")]
274 impl<T> Default for [T; $n] where T: Default {
275 fn default() -> [T; $n] {
276 [$t::default(), $($ts::default()),*]
279 array_impl_default!{($n - 1), $($ts)*}
282 #[stable(since = "1.4.0", feature = "array_default")]
283 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
284 impl<T> const Default for [T; $n] {
285 fn default() -> [T; $n] { [] }
290 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}
293 impl<T, const N: usize> [T; N] {
294 /// Returns an array of the same size as `self`, with function `f` applied to each element
297 /// If you don't necessarily need a new fixed-size array, consider using
298 /// [`Iterator::map`] instead.
301 /// # Note on performance and stack usage
303 /// Unfortunately, usages of this method are currently not always optimized
304 /// as well as they could be. This mainly concerns large arrays, as mapping
305 /// over small arrays seem to be optimized just fine. Also note that in
306 /// debug mode (i.e. without any optimizations), this method can use a lot
307 /// of stack space (a few times the size of the array or more).
309 /// Therefore, in performance-critical code, try to avoid using this method
310 /// on large arrays or check the emitted code. Also try to avoid chained
311 /// maps (e.g. `arr.map(...).map(...)`).
313 /// In many cases, you can instead use [`Iterator::map`] by calling `.iter()`
314 /// or `.into_iter()` on your array. `[T; N]::map` is only necessary if you
315 /// really need a new array of the same size as the result. Rust's lazy
316 /// iterators tend to get optimized very well.
322 /// let x = [1, 2, 3];
323 /// let y = x.map(|v| v + 1);
324 /// assert_eq!(y, [2, 3, 4]);
326 /// let x = [1, 2, 3];
327 /// let mut temp = 0;
328 /// let y = x.map(|v| { temp += 1; v * temp });
329 /// assert_eq!(y, [1, 4, 9]);
331 /// let x = ["Ferris", "Bueller's", "Day", "Off"];
332 /// let y = x.map(|v| v.len());
333 /// assert_eq!(y, [6, 9, 3, 3]);
335 #[stable(feature = "array_map", since = "1.55.0")]
336 pub fn map<F, U>(self, f: F) -> [U; N]
340 // SAFETY: we know for certain that this iterator will yield exactly `N`
342 unsafe { collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
345 /// 'Zips up' two arrays into a single array of pairs.
347 /// `zip()` returns a new array where every element is a tuple where the
348 /// first element comes from the first array, and the second element comes
349 /// from the second array. In other words, it zips two arrays together,
350 /// into a single one.
355 /// #![feature(array_zip)]
356 /// let x = [1, 2, 3];
357 /// let y = [4, 5, 6];
358 /// let z = x.zip(y);
359 /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
361 #[unstable(feature = "array_zip", issue = "80094")]
362 pub fn zip<U>(self, rhs: [U; N]) -> [(T, U); N] {
363 let mut iter = IntoIterator::into_iter(self).zip(rhs);
365 // SAFETY: we know for certain that this iterator will yield exactly `N`
367 unsafe { collect_into_array_unchecked(&mut iter) }
370 /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
371 #[stable(feature = "array_as_slice", since = "1.57.0")]
372 pub const fn as_slice(&self) -> &[T] {
376 /// Returns a mutable slice containing the entire array. Equivalent to
378 #[stable(feature = "array_as_slice", since = "1.57.0")]
379 pub fn as_mut_slice(&mut self) -> &mut [T] {
383 /// Borrows each element and returns an array of references with the same
390 /// #![feature(array_methods)]
392 /// let floats = [3.1, 2.7, -1.0];
393 /// let float_refs: [&f64; 3] = floats.each_ref();
394 /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
397 /// This method is particularly useful if combined with other methods, like
398 /// [`map`](#method.map). This way, you can avoid moving the original
399 /// array if its elements are not [`Copy`].
402 /// #![feature(array_methods)]
404 /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
405 /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
406 /// assert_eq!(is_ascii, [true, false, true]);
408 /// // We can still access the original array: it has not been moved.
409 /// assert_eq!(strings.len(), 3);
411 #[unstable(feature = "array_methods", issue = "76118")]
412 pub fn each_ref(&self) -> [&T; N] {
413 // SAFETY: we know for certain that this iterator will yield exactly `N`
415 unsafe { collect_into_array_unchecked(&mut self.iter()) }
418 /// Borrows each element mutably and returns an array of mutable references
419 /// with the same size as `self`.
425 /// #![feature(array_methods)]
427 /// let mut floats = [3.1, 2.7, -1.0];
428 /// let float_refs: [&mut f64; 3] = floats.each_mut();
429 /// *float_refs[0] = 0.0;
430 /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
431 /// assert_eq!(floats, [0.0, 2.7, -1.0]);
433 #[unstable(feature = "array_methods", issue = "76118")]
434 pub fn each_mut(&mut self) -> [&mut T; N] {
435 // SAFETY: we know for certain that this iterator will yield exactly `N`
437 unsafe { collect_into_array_unchecked(&mut self.iter_mut()) }
441 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
442 /// yields fewer than `N` items, this function exhibits undefined behavior.
444 /// See [`collect_into_array`] for more information.
449 /// It is up to the caller to guarantee that `iter` yields at least `N` items.
450 /// Violating this condition causes undefined behavior.
451 unsafe fn collect_into_array_unchecked<I, const N: usize>(iter: &mut I) -> [I::Item; N]
453 // Note: `TrustedLen` here is somewhat of an experiment. This is just an
454 // internal function, so feel free to remove if this bound turns out to be a
455 // bad idea. In that case, remember to also remove the lower bound
456 // `debug_assert!` below!
457 I: Iterator + TrustedLen,
459 debug_assert!(N <= iter.size_hint().1.unwrap_or(usize::MAX));
460 debug_assert!(N <= iter.size_hint().0);
462 // SAFETY: covered by the function contract.
463 unsafe { collect_into_array(iter).unwrap_unchecked() }
466 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
467 /// yields fewer than `N` items, `None` is returned and all already yielded
468 /// items are dropped.
470 /// Since the iterator is passed as a mutable reference and this function calls
471 /// `next` at most `N` times, the iterator can still be used afterwards to
472 /// retrieve the remaining items.
474 /// If `iter.next()` panicks, all items already yielded by the iterator are
476 fn collect_into_array<I, const N: usize>(iter: &mut I) -> Option<[I::Item; N]>
481 // SAFETY: An empty array is always inhabited and has no validity invariants.
482 return unsafe { Some(mem::zeroed()) };
485 struct Guard<T, const N: usize> {
490 impl<T, const N: usize> Drop for Guard<T, N> {
492 debug_assert!(self.initialized <= N);
494 let initialized_part = crate::ptr::slice_from_raw_parts_mut(self.ptr, self.initialized);
496 // SAFETY: this raw slice will contain only initialized objects.
498 crate::ptr::drop_in_place(initialized_part);
503 let mut array = MaybeUninit::uninit_array::<N>();
504 let mut guard: Guard<_, N> =
505 Guard { ptr: MaybeUninit::slice_as_mut_ptr(&mut array), initialized: 0 };
507 while let Some(item) = iter.next() {
508 // SAFETY: `guard.initialized` starts at 0, is increased by one in the
509 // loop and the loop is aborted once it reaches N (which is
512 array.get_unchecked_mut(guard.initialized).write(item);
514 guard.initialized += 1;
516 // Check if the whole array was initialized.
517 if guard.initialized == N {
520 // SAFETY: the condition above asserts that all elements are
522 let out = unsafe { MaybeUninit::array_assume_init(array) };
527 // This is only reached if the iterator is exhausted before
528 // `guard.initialized` reaches `N`. Also note that `guard` is dropped here,
529 // dropping all already initialized elements.