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 /// let x = [1, 2, 3];
300 /// let y = x.map(|v| v + 1);
301 /// assert_eq!(y, [2, 3, 4]);
303 /// let x = [1, 2, 3];
304 /// let mut temp = 0;
305 /// let y = x.map(|v| { temp += 1; v * temp });
306 /// assert_eq!(y, [1, 4, 9]);
308 /// let x = ["Ferris", "Bueller's", "Day", "Off"];
309 /// let y = x.map(|v| v.len());
310 /// assert_eq!(y, [6, 9, 3, 3]);
312 #[stable(feature = "array_map", since = "1.55.0")]
313 pub fn map
<F
, U
>(self, f
: F
) -> [U
; N
]
317 // SAFETY: we know for certain that this iterator will yield exactly `N`
319 unsafe { collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
322 /// 'Zips up' two arrays into a single array of pairs.
324 /// `zip()` returns a new array where every element is a tuple where the
325 /// first element comes from the first array, and the second element comes
326 /// from the second array. In other words, it zips two arrays together,
327 /// into a single one.
332 /// #![feature(array_zip)]
333 /// let x = [1, 2, 3];
334 /// let y = [4, 5, 6];
335 /// let z = x.zip(y);
336 /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
338 #[unstable(feature = "array_zip", issue = "80094")]
339 pub fn zip
<U
>(self, rhs
: [U
; N
]) -> [(T
, U
); N
] {
340 let mut iter
= IntoIterator
::into_iter(self).zip(rhs
);
342 // SAFETY: we know for certain that this iterator will yield exactly `N`
344 unsafe { collect_into_array_unchecked(&mut iter) }
347 /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
348 #[unstable(feature = "array_methods", issue = "76118")]
349 pub fn as_slice(&self) -> &[T
] {
353 /// Returns a mutable slice containing the entire array. Equivalent to
355 #[unstable(feature = "array_methods", issue = "76118")]
356 pub fn as_mut_slice(&mut self) -> &mut [T
] {
360 /// Borrows each element and returns an array of references with the same
367 /// #![feature(array_methods)]
369 /// let floats = [3.1, 2.7, -1.0];
370 /// let float_refs: [&f64; 3] = floats.each_ref();
371 /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
374 /// This method is particularly useful if combined with other methods, like
375 /// [`map`](#method.map). This way, you can avoid moving the original
376 /// array if its elements are not `Copy`.
379 /// #![feature(array_methods)]
381 /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
382 /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
383 /// assert_eq!(is_ascii, [true, false, true]);
385 /// // We can still access the original array: it has not been moved.
386 /// assert_eq!(strings.len(), 3);
388 #[unstable(feature = "array_methods", issue = "76118")]
389 pub fn each_ref(&self) -> [&T
; N
] {
390 // SAFETY: we know for certain that this iterator will yield exactly `N`
392 unsafe { collect_into_array_unchecked(&mut self.iter()) }
395 /// Borrows each element mutably and returns an array of mutable references
396 /// with the same size as `self`.
402 /// #![feature(array_methods)]
404 /// let mut floats = [3.1, 2.7, -1.0];
405 /// let float_refs: [&mut f64; 3] = floats.each_mut();
406 /// *float_refs[0] = 0.0;
407 /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
408 /// assert_eq!(floats, [0.0, 2.7, -1.0]);
410 #[unstable(feature = "array_methods", issue = "76118")]
411 pub fn each_mut(&mut self) -> [&mut T
; N
] {
412 // SAFETY: we know for certain that this iterator will yield exactly `N`
414 unsafe { collect_into_array_unchecked(&mut self.iter_mut()) }
418 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
419 /// yields fewer than `N` items, this function exhibits undefined behavior.
421 /// See [`collect_into_array`] for more information.
426 /// It is up to the caller to guarantee that `iter` yields at least `N` items.
427 /// Violating this condition causes undefined behavior.
428 unsafe fn collect_into_array_unchecked
<I
, const N
: usize>(iter
: &mut I
) -> [I
::Item
; N
]
430 // Note: `TrustedLen` here is somewhat of an experiment. This is just an
431 // internal function, so feel free to remove if this bound turns out to be a
432 // bad idea. In that case, remember to also remove the lower bound
433 // `debug_assert!` below!
434 I
: Iterator
+ TrustedLen
,
436 debug_assert
!(N
<= iter
.size_hint().1.unwrap_or
(usize::MAX
));
437 debug_assert
!(N
<= iter
.size_hint().0);
439 match collect_into_array(iter
) {
440 Some(array
) => array
,
441 // SAFETY: covered by the function contract.
442 None
=> unsafe { crate::hint::unreachable_unchecked() }
,
446 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
447 /// yields fewer than `N` items, `None` is returned and all already yielded
448 /// items are dropped.
450 /// Since the iterator is passed as a mutable reference and this function calls
451 /// `next` at most `N` times, the iterator can still be used afterwards to
452 /// retrieve the remaining items.
454 /// If `iter.next()` panicks, all items already yielded by the iterator are
456 fn collect_into_array
<I
, const N
: usize>(iter
: &mut I
) -> Option
<[I
::Item
; N
]>
461 // SAFETY: An empty array is always inhabited and has no validity invariants.
462 return unsafe { Some(mem::zeroed()) }
;
465 struct Guard
<T
, const N
: usize> {
470 impl<T
, const N
: usize> Drop
for Guard
<T
, N
> {
472 debug_assert
!(self.initialized
<= N
);
474 let initialized_part
= crate::ptr
::slice_from_raw_parts_mut(self.ptr
, self.initialized
);
476 // SAFETY: this raw slice will contain only initialized objects.
478 crate::ptr
::drop_in_place(initialized_part
);
483 let mut array
= MaybeUninit
::uninit_array
::<N
>();
484 let mut guard
: Guard
<_
, N
> =
485 Guard { ptr: MaybeUninit::slice_as_mut_ptr(&mut array), initialized: 0 }
;
487 while let Some(item
) = iter
.next() {
488 // SAFETY: `guard.initialized` starts at 0, is increased by one in the
489 // loop and the loop is aborted once it reaches N (which is
492 array
.get_unchecked_mut(guard
.initialized
).write(item
);
494 guard
.initialized
+= 1;
496 // Check if the whole array was initialized.
497 if guard
.initialized
== N
{
500 // SAFETY: the condition above asserts that all elements are
502 let out
= unsafe { MaybeUninit::array_assume_init(array) }
;
507 // This is only reached if the iterator is exhausted before
508 // `guard.initialized` reaches `N`. Also note that `guard` is dropped here,
509 // dropping all already initialized elements.