1 //! Implementations of things like `Eq` for fixed-length arrays
2 //! up to a certain length. Eventually, we should be able to generalize
5 //! *[See also the array primitive type](../../std/primitive.array.html).*
7 #![stable(feature = "core_array", since = "1.36.0")]
9 use crate::borrow::{Borrow, BorrowMut};
10 use crate::cmp::Ordering;
11 use crate::convert::{Infallible, TryFrom};
13 use crate::hash::{self, Hash};
14 use crate::marker::Unsize;
15 use crate::ops::{Index, IndexMut};
16 use crate::slice::{Iter, IterMut};
20 #[unstable(feature = "array_value_iter", issue = "65798")]
21 pub use iter::IntoIter;
23 /// Converts a reference to `T` into a reference to an array of length 1 (without copying).
24 #[unstable(feature = "array_from_ref", issue = "77101")]
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 #[unstable(feature = "array_from_ref", issue = "77101")]
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 /// Utility trait implemented only on arrays of fixed size
39 /// This trait can be used to implement other traits on fixed-size arrays
40 /// without causing much metadata bloat.
42 /// The trait is marked unsafe in order to restrict implementors to fixed-size
43 /// arrays. User of this trait can assume that implementors have the exact
44 /// layout in memory of a fixed size array (for example, for unsafe
47 /// Note that the traits [`AsRef`] and [`AsMut`] provide similar methods for types that
48 /// may not be fixed-size arrays. Implementors should prefer those traits
50 #[unstable(feature = "fixed_size_array", issue = "27778")]
51 pub unsafe trait FixedSizeArray<T> {
52 /// Converts the array to immutable slice
53 #[unstable(feature = "fixed_size_array", issue = "27778")]
54 fn as_slice(&self) -> &[T];
55 /// Converts the array to mutable slice
56 #[unstable(feature = "fixed_size_array", issue = "27778")]
57 fn as_mut_slice(&mut self) -> &mut [T];
60 #[unstable(feature = "fixed_size_array", issue = "27778")]
61 unsafe impl<T, A: Unsize<[T]>> FixedSizeArray<T> for A {
63 fn as_slice(&self) -> &[T] {
67 fn as_mut_slice(&mut self) -> &mut [T] {
72 /// The error type returned when a conversion from a slice to an array fails.
73 #[stable(feature = "try_from", since = "1.34.0")]
74 #[derive(Debug, Copy, Clone)]
75 pub struct TryFromSliceError(());
77 #[stable(feature = "core_array", since = "1.36.0")]
78 impl fmt::Display for TryFromSliceError {
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 fmt::Display::fmt(self.__description(), f)
85 impl TryFromSliceError {
87 feature = "array_error_internals",
88 reason = "available through Error trait and this method should not \
94 pub fn __description(&self) -> &str {
95 "could not convert slice to array"
99 #[stable(feature = "try_from_slice_error", since = "1.36.0")]
100 impl From<Infallible> for TryFromSliceError {
101 fn from(x: Infallible) -> TryFromSliceError {
106 #[stable(feature = "rust1", since = "1.0.0")]
107 impl<T, const N: usize> AsRef<[T]> for [T; N] {
109 fn as_ref(&self) -> &[T] {
114 #[stable(feature = "rust1", since = "1.0.0")]
115 impl<T, const N: usize> AsMut<[T]> for [T; N] {
117 fn as_mut(&mut self) -> &mut [T] {
122 #[stable(feature = "array_borrow", since = "1.4.0")]
123 impl<T, const N: usize> Borrow<[T]> for [T; N] {
124 fn borrow(&self) -> &[T] {
129 #[stable(feature = "array_borrow", since = "1.4.0")]
130 impl<T, const N: usize> BorrowMut<[T]> for [T; N] {
131 fn borrow_mut(&mut self) -> &mut [T] {
136 #[stable(feature = "try_from", since = "1.34.0")]
137 impl<T, const N: usize> TryFrom<&[T]> for [T; N]
141 type Error = TryFromSliceError;
143 fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError> {
144 <&Self>::try_from(slice).map(|r| *r)
148 #[stable(feature = "try_from", since = "1.34.0")]
149 impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N] {
150 type Error = TryFromSliceError;
152 fn try_from(slice: &[T]) -> Result<&[T; N], TryFromSliceError> {
153 if slice.len() == N {
154 let ptr = slice.as_ptr() as *const [T; N];
155 // SAFETY: ok because we just checked that the length fits
158 Err(TryFromSliceError(()))
163 #[stable(feature = "try_from", since = "1.34.0")]
164 impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N] {
165 type Error = TryFromSliceError;
167 fn try_from(slice: &mut [T]) -> Result<&mut [T; N], TryFromSliceError> {
168 if slice.len() == N {
169 let ptr = slice.as_mut_ptr() as *mut [T; N];
170 // SAFETY: ok because we just checked that the length fits
171 unsafe { Ok(&mut *ptr) }
173 Err(TryFromSliceError(()))
178 #[stable(feature = "rust1", since = "1.0.0")]
179 impl<T: Hash, const N: usize> Hash for [T; N] {
180 fn hash<H: hash::Hasher>(&self, state: &mut H) {
181 Hash::hash(&self[..], state)
185 #[stable(feature = "rust1", since = "1.0.0")]
186 impl<T: fmt::Debug, const N: usize> fmt::Debug for [T; N] {
187 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188 fmt::Debug::fmt(&&self[..], f)
192 #[stable(feature = "rust1", since = "1.0.0")]
193 impl<'a, T, const N: usize> IntoIterator for &'a [T; N] {
195 type IntoIter = Iter<'a, T>;
197 fn into_iter(self) -> Iter<'a, T> {
202 #[stable(feature = "rust1", since = "1.0.0")]
203 impl<'a, T, const N: usize> IntoIterator for &'a mut [T; N] {
204 type Item = &'a mut T;
205 type IntoIter = IterMut<'a, T>;
207 fn into_iter(self) -> IterMut<'a, T> {
212 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
213 impl<T, I, const N: usize> Index<I> for [T; N]
217 type Output = <[T] as Index<I>>::Output;
220 fn index(&self, index: I) -> &Self::Output {
221 Index::index(self as &[T], index)
225 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
226 impl<T, I, const N: usize> IndexMut<I> for [T; N]
231 fn index_mut(&mut self, index: I) -> &mut Self::Output {
232 IndexMut::index_mut(self as &mut [T], index)
236 #[stable(feature = "rust1", since = "1.0.0")]
237 impl<A, B, const N: usize> PartialEq<[B; N]> for [A; N]
242 fn eq(&self, other: &[B; N]) -> bool {
243 self[..] == other[..]
246 fn ne(&self, other: &[B; N]) -> bool {
247 self[..] != other[..]
251 #[stable(feature = "rust1", since = "1.0.0")]
252 impl<A, B, const N: usize> PartialEq<[B]> for [A; N]
257 fn eq(&self, other: &[B]) -> bool {
258 self[..] == other[..]
261 fn ne(&self, other: &[B]) -> bool {
262 self[..] != other[..]
266 #[stable(feature = "rust1", since = "1.0.0")]
267 impl<A, B, const N: usize> PartialEq<[A; N]> for [B]
272 fn eq(&self, other: &[A; N]) -> bool {
273 self[..] == other[..]
276 fn ne(&self, other: &[A; N]) -> bool {
277 self[..] != other[..]
281 #[stable(feature = "rust1", since = "1.0.0")]
282 impl<A, B, const N: usize> PartialEq<&[B]> for [A; N]
287 fn eq(&self, other: &&[B]) -> bool {
288 self[..] == other[..]
291 fn ne(&self, other: &&[B]) -> bool {
292 self[..] != other[..]
296 #[stable(feature = "rust1", since = "1.0.0")]
297 impl<A, B, const N: usize> PartialEq<[A; N]> for &[B]
302 fn eq(&self, other: &[A; N]) -> bool {
303 self[..] == other[..]
306 fn ne(&self, other: &[A; N]) -> bool {
307 self[..] != other[..]
311 #[stable(feature = "rust1", since = "1.0.0")]
312 impl<A, B, const N: usize> PartialEq<&mut [B]> for [A; N]
317 fn eq(&self, other: &&mut [B]) -> bool {
318 self[..] == other[..]
321 fn ne(&self, other: &&mut [B]) -> bool {
322 self[..] != other[..]
326 #[stable(feature = "rust1", since = "1.0.0")]
327 impl<A, B, const N: usize> PartialEq<[A; N]> for &mut [B]
332 fn eq(&self, other: &[A; N]) -> bool {
333 self[..] == other[..]
336 fn ne(&self, other: &[A; N]) -> bool {
337 self[..] != other[..]
341 // NOTE: some less important impls are omitted to reduce code bloat
342 // __impl_slice_eq2! { [A; $N], &'b [B; $N] }
343 // __impl_slice_eq2! { [A; $N], &'b mut [B; $N] }
345 #[stable(feature = "rust1", since = "1.0.0")]
346 impl<T: Eq, const N: usize> Eq for [T; N] {}
348 #[stable(feature = "rust1", since = "1.0.0")]
349 impl<T: PartialOrd, const N: usize> PartialOrd for [T; N] {
351 fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
352 PartialOrd::partial_cmp(&&self[..], &&other[..])
355 fn lt(&self, other: &[T; N]) -> bool {
356 PartialOrd::lt(&&self[..], &&other[..])
359 fn le(&self, other: &[T; N]) -> bool {
360 PartialOrd::le(&&self[..], &&other[..])
363 fn ge(&self, other: &[T; N]) -> bool {
364 PartialOrd::ge(&&self[..], &&other[..])
367 fn gt(&self, other: &[T; N]) -> bool {
368 PartialOrd::gt(&&self[..], &&other[..])
372 /// Implements comparison of arrays [lexicographically](Ord#lexicographical-comparison).
373 #[stable(feature = "rust1", since = "1.0.0")]
374 impl<T: Ord, const N: usize> Ord for [T; N] {
376 fn cmp(&self, other: &[T; N]) -> Ordering {
377 Ord::cmp(&&self[..], &&other[..])
381 // The Default impls cannot be done with const generics because `[T; 0]` doesn't
382 // require Default to be implemented, and having different impl blocks for
383 // different numbers isn't supported yet.
385 macro_rules! array_impl_default {
386 {$n:expr, $t:ident $($ts:ident)*} => {
387 #[stable(since = "1.4.0", feature = "array_default")]
388 impl<T> Default for [T; $n] where T: Default {
389 fn default() -> [T; $n] {
390 [$t::default(), $($ts::default()),*]
393 array_impl_default!{($n - 1), $($ts)*}
396 #[stable(since = "1.4.0", feature = "array_default")]
397 impl<T> Default for [T; $n] {
398 fn default() -> [T; $n] { [] }
403 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}
406 impl<T, const N: usize> [T; N] {
407 /// Returns an array of the same size as `self`, with function `f` applied to each element
413 /// #![feature(array_map)]
414 /// let x = [1, 2, 3];
415 /// let y = x.map(|v| v + 1);
416 /// assert_eq!(y, [2, 3, 4]);
418 /// let x = [1, 2, 3];
419 /// let mut temp = 0;
420 /// let y = x.map(|v| { temp += 1; v * temp });
421 /// assert_eq!(y, [1, 4, 9]);
423 /// let x = ["Ferris", "Bueller's", "Day", "Off"];
424 /// let y = x.map(|v| v.len());
425 /// assert_eq!(y, [6, 9, 3, 3]);
427 #[unstable(feature = "array_map", issue = "75243")]
428 pub fn map<F, U>(self, mut f: F) -> [U; N]
432 use crate::mem::MaybeUninit;
433 struct Guard<T, const N: usize> {
438 impl<T, const N: usize> Drop for Guard<T, N> {
440 debug_assert!(self.initialized <= N);
442 let initialized_part =
443 crate::ptr::slice_from_raw_parts_mut(self.dst, self.initialized);
444 // SAFETY: this raw slice will contain only initialized objects
445 // that's why, it is allowed to drop it.
447 crate::ptr::drop_in_place(initialized_part);
451 let mut dst = MaybeUninit::uninit_array::<N>();
452 let mut guard: Guard<U, N> =
453 Guard { dst: MaybeUninit::slice_as_mut_ptr(&mut dst), initialized: 0 };
454 for (src, dst) in IntoIter::new(self).zip(&mut dst) {
456 guard.initialized += 1;
458 // FIXME: Convert to crate::mem::transmute once it works with generics.
459 // unsafe { crate::mem::transmute::<[MaybeUninit<U>; N], [U; N]>(dst) }
460 crate::mem::forget(guard);
461 // SAFETY: At this point we've properly initialized the whole array
462 // and we just need to cast it to the correct type.
463 unsafe { crate::mem::transmute_copy::<_, [U; N]>(&dst) }
466 /// 'Zips up' two arrays into a single array of pairs.
467 /// `zip()` returns a new array where every element is a tuple where the first element comes from the first array, and the second element comes from the second array.
468 /// In other words, it zips two arrays together, into a single one.
473 /// #![feature(array_zip)]
474 /// let x = [1, 2, 3];
475 /// let y = [4, 5, 6];
476 /// let z = x.zip(y);
477 /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
479 #[unstable(feature = "array_zip", issue = "none")]
480 pub fn zip<U>(self, rhs: [U; N]) -> [(T, U); N] {
481 use crate::mem::MaybeUninit;
483 let mut dst = MaybeUninit::uninit_array::<N>();
484 for (i, (lhs, rhs)) in IntoIter::new(self).zip(IntoIter::new(rhs)).enumerate() {
485 dst[i].write((lhs, rhs));
487 // FIXME: Convert to crate::mem::transmute once it works with generics.
488 // unsafe { crate::mem::transmute::<[MaybeUninit<U>; N], [U; N]>(dst) }
489 // SAFETY: At this point we've properly initialized the whole array
490 // and we just need to cast it to the correct type.
491 unsafe { crate::mem::transmute_copy::<_, [(T, U); N]>(&dst) }
494 /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
495 #[unstable(feature = "array_methods", issue = "76118")]
496 pub fn as_slice(&self) -> &[T] {
500 /// Returns a mutable slice containing the entire array. Equivalent to
502 #[unstable(feature = "array_methods", issue = "76118")]
503 pub fn as_mut_slice(&mut self) -> &mut [T] {