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 impl<T> Default for [T; $n] {
284 fn default() -> [T; $n] { [] }
289 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}
292 impl<T, const N: usize> [T; N] {
293 /// Returns an array of the same size as `self`, with function `f` applied to each element
299 /// #![feature(array_map)]
300 /// let x = [1, 2, 3];
301 /// let y = x.map(|v| v + 1);
302 /// assert_eq!(y, [2, 3, 4]);
304 /// let x = [1, 2, 3];
305 /// let mut temp = 0;
306 /// let y = x.map(|v| { temp += 1; v * temp });
307 /// assert_eq!(y, [1, 4, 9]);
309 /// let x = ["Ferris", "Bueller's", "Day", "Off"];
310 /// let y = x.map(|v| v.len());
311 /// assert_eq!(y, [6, 9, 3, 3]);
313 #[unstable(feature = "array_map", issue = "75243")]
314 pub fn map<F, U>(self, f: F) -> [U; N]
318 // SAFETY: we know for certain that this iterator will yield exactly `N`
320 unsafe { collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
323 /// 'Zips up' two arrays into a single array of pairs.
325 /// `zip()` returns a new array where every element is a tuple where the
326 /// first element comes from the first array, and the second element comes
327 /// from the second array. In other words, it zips two arrays together,
328 /// into a single one.
333 /// #![feature(array_zip)]
334 /// let x = [1, 2, 3];
335 /// let y = [4, 5, 6];
336 /// let z = x.zip(y);
337 /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
339 #[unstable(feature = "array_zip", issue = "80094")]
340 pub fn zip<U>(self, rhs: [U; N]) -> [(T, U); N] {
341 let mut iter = IntoIterator::into_iter(self).zip(rhs);
343 // SAFETY: we know for certain that this iterator will yield exactly `N`
345 unsafe { collect_into_array_unchecked(&mut iter) }
348 /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
349 #[unstable(feature = "array_methods", issue = "76118")]
350 pub fn as_slice(&self) -> &[T] {
354 /// Returns a mutable slice containing the entire array. Equivalent to
356 #[unstable(feature = "array_methods", issue = "76118")]
357 pub fn as_mut_slice(&mut self) -> &mut [T] {
361 /// Borrows each element and returns an array of references with the same
368 /// #![feature(array_methods)]
370 /// let floats = [3.1, 2.7, -1.0];
371 /// let float_refs: [&f64; 3] = floats.each_ref();
372 /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
375 /// This method is particularly useful if combined with other methods, like
376 /// [`map`](#method.map). This way, you can avoid moving the original
377 /// array if its elements are not `Copy`.
380 /// #![feature(array_methods, array_map)]
382 /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
383 /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
384 /// assert_eq!(is_ascii, [true, false, true]);
386 /// // We can still access the original array: it has not been moved.
387 /// assert_eq!(strings.len(), 3);
389 #[unstable(feature = "array_methods", issue = "76118")]
390 pub fn each_ref(&self) -> [&T; N] {
391 // SAFETY: we know for certain that this iterator will yield exactly `N`
393 unsafe { collect_into_array_unchecked(&mut self.iter()) }
396 /// Borrows each element mutably and returns an array of mutable references
397 /// with the same size as `self`.
403 /// #![feature(array_methods)]
405 /// let mut floats = [3.1, 2.7, -1.0];
406 /// let float_refs: [&mut f64; 3] = floats.each_mut();
407 /// *float_refs[0] = 0.0;
408 /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
409 /// assert_eq!(floats, [0.0, 2.7, -1.0]);
411 #[unstable(feature = "array_methods", issue = "76118")]
412 pub fn each_mut(&mut self) -> [&mut T; N] {
413 // SAFETY: we know for certain that this iterator will yield exactly `N`
415 unsafe { collect_into_array_unchecked(&mut self.iter_mut()) }
419 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
420 /// yields fewer than `N` items, this function exhibits undefined behavior.
422 /// See [`collect_into_array`] for more information.
427 /// It is up to the caller to guarantee that `iter` yields at least `N` items.
428 /// Violating this condition causes undefined behavior.
429 unsafe fn collect_into_array_unchecked<I, const N: usize>(iter: &mut I) -> [I::Item; N]
431 // Note: `TrustedLen` here is somewhat of an experiment. This is just an
432 // internal function, so feel free to remove if this bound turns out to be a
433 // bad idea. In that case, remember to also remove the lower bound
434 // `debug_assert!` below!
435 I: Iterator + TrustedLen,
437 debug_assert!(N <= iter.size_hint().1.unwrap_or(usize::MAX));
438 debug_assert!(N <= iter.size_hint().0);
440 match collect_into_array(iter) {
441 Some(array) => array,
442 // SAFETY: covered by the function contract.
443 None => unsafe { crate::hint::unreachable_unchecked() },
447 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
448 /// yields fewer than `N` items, `None` is returned and all already yielded
449 /// items are dropped.
451 /// Since the iterator is passed as a mutable reference and this function calls
452 /// `next` at most `N` times, the iterator can still be used afterwards to
453 /// retrieve the remaining items.
455 /// If `iter.next()` panicks, all items already yielded by the iterator are
457 fn collect_into_array<I, const N: usize>(iter: &mut I) -> Option<[I::Item; N]>
462 // SAFETY: An empty array is always inhabited and has no validity invariants.
463 return unsafe { Some(mem::zeroed()) };
466 struct Guard<T, const N: usize> {
471 impl<T, const N: usize> Drop for Guard<T, N> {
473 debug_assert!(self.initialized <= N);
475 let initialized_part = crate::ptr::slice_from_raw_parts_mut(self.ptr, self.initialized);
477 // SAFETY: this raw slice will contain only initialized objects.
479 crate::ptr::drop_in_place(initialized_part);
484 let mut array = MaybeUninit::uninit_array::<N>();
485 let mut guard: Guard<_, N> =
486 Guard { ptr: MaybeUninit::slice_as_mut_ptr(&mut array), initialized: 0 };
488 while let Some(item) = iter.next() {
489 // SAFETY: `guard.initialized` starts at 0, is increased by one in the
490 // loop and the loop is aborted once it reaches N (which is
493 array.get_unchecked_mut(guard.initialized).write(item);
495 guard.initialized += 1;
497 // Check if the whole array was initialized.
498 if guard.initialized == N {
501 // SAFETY: the condition above asserts that all elements are
503 let out = unsafe { MaybeUninit::array_assume_init(array) };
508 // This is only reached if the iterator is exhausted before
509 // `guard.initialized` reaches `N`. Also note that `guard` is dropped here,
510 // dropping all already initialized elements.