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::slice::{Iter, IterMut};
19 #[unstable(feature = "array_value_iter", issue = "65798")]
20 pub use iter::IntoIter;
22 /// Utility trait implemented only on arrays of fixed size
24 /// This trait can be used to implement other traits on fixed-size arrays
25 /// without causing much metadata bloat.
27 /// The trait is marked unsafe in order to restrict implementors to fixed-size
28 /// arrays. User of this trait can assume that implementors have the exact
29 /// layout in memory of a fixed size array (for example, for unsafe
32 /// Note that the traits [`AsRef`] and [`AsMut`] provide similar methods for types that
33 /// may not be fixed-size arrays. Implementors should prefer those traits
36 /// [`AsRef`]: ../convert/trait.AsRef.html
37 /// [`AsMut`]: ../convert/trait.AsMut.html
38 #[unstable(feature = "fixed_size_array", issue = "27778")]
39 pub unsafe trait FixedSizeArray<T> {
40 /// Converts the array to immutable slice
41 #[unstable(feature = "fixed_size_array", issue = "27778")]
42 fn as_slice(&self) -> &[T];
43 /// Converts the array to mutable slice
44 #[unstable(feature = "fixed_size_array", issue = "27778")]
45 fn as_mut_slice(&mut self) -> &mut [T];
48 #[unstable(feature = "fixed_size_array", issue = "27778")]
49 unsafe impl<T, A: Unsize<[T]>> FixedSizeArray<T> for A {
51 fn as_slice(&self) -> &[T] {
55 fn as_mut_slice(&mut self) -> &mut [T] {
60 /// The error type returned when a conversion from a slice to an array fails.
61 #[stable(feature = "try_from", since = "1.34.0")]
62 #[derive(Debug, Copy, Clone)]
63 pub struct TryFromSliceError(());
65 #[stable(feature = "core_array", since = "1.36.0")]
66 impl fmt::Display for TryFromSliceError {
68 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69 fmt::Display::fmt(self.__description(), f)
73 impl TryFromSliceError {
75 feature = "array_error_internals",
76 reason = "available through Error trait and this method should not \
82 pub fn __description(&self) -> &str {
83 "could not convert slice to array"
87 #[stable(feature = "try_from_slice_error", since = "1.36.0")]
88 impl From<Infallible> for TryFromSliceError {
89 fn from(x: Infallible) -> TryFromSliceError {
94 #[stable(feature = "rust1", since = "1.0.0")]
95 impl<T, const N: usize> AsRef<[T]> for [T; N] {
97 fn as_ref(&self) -> &[T] {
102 #[stable(feature = "rust1", since = "1.0.0")]
103 impl<T, const N: usize> AsMut<[T]> for [T; N] {
105 fn as_mut(&mut self) -> &mut [T] {
110 #[stable(feature = "array_borrow", since = "1.4.0")]
111 impl<T, const N: usize> Borrow<[T]> for [T; N] {
112 fn borrow(&self) -> &[T] {
117 #[stable(feature = "array_borrow", since = "1.4.0")]
118 impl<T, const N: usize> BorrowMut<[T]> for [T; N] {
119 fn borrow_mut(&mut self) -> &mut [T] {
124 #[stable(feature = "try_from", since = "1.34.0")]
125 impl<T, const N: usize> TryFrom<&[T]> for [T; N]
129 type Error = TryFromSliceError;
131 fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError> {
132 <&Self>::try_from(slice).map(|r| *r)
136 #[stable(feature = "try_from", since = "1.34.0")]
137 impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N] {
138 type Error = TryFromSliceError;
140 fn try_from(slice: &[T]) -> Result<&[T; N], TryFromSliceError> {
141 if slice.len() == N {
142 let ptr = slice.as_ptr() as *const [T; N];
143 // SAFETY: ok because we just checked that the length fits
146 Err(TryFromSliceError(()))
151 #[stable(feature = "try_from", since = "1.34.0")]
152 impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N] {
153 type Error = TryFromSliceError;
155 fn try_from(slice: &mut [T]) -> Result<&mut [T; N], TryFromSliceError> {
156 if slice.len() == N {
157 let ptr = slice.as_mut_ptr() as *mut [T; N];
158 // SAFETY: ok because we just checked that the length fits
159 unsafe { Ok(&mut *ptr) }
161 Err(TryFromSliceError(()))
166 #[stable(feature = "rust1", since = "1.0.0")]
167 impl<T: Hash, const N: usize> Hash for [T; N] {
168 fn hash<H: hash::Hasher>(&self, state: &mut H) {
169 Hash::hash(&self[..], state)
173 #[stable(feature = "rust1", since = "1.0.0")]
174 impl<T: fmt::Debug, const N: usize> fmt::Debug for [T; N] {
175 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176 fmt::Debug::fmt(&&self[..], f)
180 #[stable(feature = "rust1", since = "1.0.0")]
181 impl<'a, T, const N: usize> IntoIterator for &'a [T; N] {
183 type IntoIter = Iter<'a, T>;
185 fn into_iter(self) -> Iter<'a, T> {
190 #[stable(feature = "rust1", since = "1.0.0")]
191 impl<'a, T, const N: usize> IntoIterator for &'a mut [T; N] {
192 type Item = &'a mut T;
193 type IntoIter = IterMut<'a, T>;
195 fn into_iter(self) -> IterMut<'a, T> {
200 #[stable(feature = "rust1", since = "1.0.0")]
201 impl<A, B, const N: usize> PartialEq<[B; N]> for [A; N]
206 fn eq(&self, other: &[B; N]) -> bool {
207 self[..] == other[..]
210 fn ne(&self, other: &[B; N]) -> bool {
211 self[..] != other[..]
215 #[stable(feature = "rust1", since = "1.0.0")]
216 impl<A, B, const N: usize> PartialEq<[B]> for [A; N]
221 fn eq(&self, other: &[B]) -> bool {
222 self[..] == other[..]
225 fn ne(&self, other: &[B]) -> bool {
226 self[..] != other[..]
230 #[stable(feature = "rust1", since = "1.0.0")]
231 impl<A, B, const N: usize> PartialEq<[A; N]> for [B]
236 fn eq(&self, other: &[A; N]) -> bool {
237 self[..] == other[..]
240 fn ne(&self, other: &[A; N]) -> bool {
241 self[..] != other[..]
245 #[stable(feature = "rust1", since = "1.0.0")]
246 impl<'b, A, B, const N: usize> PartialEq<&'b [B]> for [A; N]
251 fn eq(&self, other: &&'b [B]) -> bool {
252 self[..] == other[..]
255 fn ne(&self, other: &&'b [B]) -> bool {
256 self[..] != other[..]
260 #[stable(feature = "rust1", since = "1.0.0")]
261 impl<'b, A, B, const N: usize> PartialEq<[A; N]> for &'b [B]
266 fn eq(&self, other: &[A; N]) -> bool {
267 self[..] == other[..]
270 fn ne(&self, other: &[A; N]) -> bool {
271 self[..] != other[..]
275 #[stable(feature = "rust1", since = "1.0.0")]
276 impl<'b, A, B, const N: usize> PartialEq<&'b mut [B]> for [A; N]
281 fn eq(&self, other: &&'b mut [B]) -> bool {
282 self[..] == other[..]
285 fn ne(&self, other: &&'b mut [B]) -> bool {
286 self[..] != other[..]
290 #[stable(feature = "rust1", since = "1.0.0")]
291 impl<'b, A, B, const N: usize> PartialEq<[A; N]> for &'b mut [B]
296 fn eq(&self, other: &[A; N]) -> bool {
297 self[..] == other[..]
300 fn ne(&self, other: &[A; N]) -> bool {
301 self[..] != other[..]
305 // NOTE: some less important impls are omitted to reduce code bloat
306 // __impl_slice_eq2! { [A; $N], &'b [B; $N] }
307 // __impl_slice_eq2! { [A; $N], &'b mut [B; $N] }
309 #[stable(feature = "rust1", since = "1.0.0")]
310 impl<T: Eq, const N: usize> Eq for [T; N] {}
312 #[stable(feature = "rust1", since = "1.0.0")]
313 impl<T: PartialOrd, const N: usize> PartialOrd for [T; N] {
315 fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
316 PartialOrd::partial_cmp(&&self[..], &&other[..])
319 fn lt(&self, other: &[T; N]) -> bool {
320 PartialOrd::lt(&&self[..], &&other[..])
323 fn le(&self, other: &[T; N]) -> bool {
324 PartialOrd::le(&&self[..], &&other[..])
327 fn ge(&self, other: &[T; N]) -> bool {
328 PartialOrd::ge(&&self[..], &&other[..])
331 fn gt(&self, other: &[T; N]) -> bool {
332 PartialOrd::gt(&&self[..], &&other[..])
336 /// Implements comparison of arrays lexicographically.
337 #[stable(feature = "rust1", since = "1.0.0")]
338 impl<T: Ord, const N: usize> Ord for [T; N] {
340 fn cmp(&self, other: &[T; N]) -> Ordering {
341 Ord::cmp(&&self[..], &&other[..])
345 // The Default impls cannot be generated using the array_impls! macro because
346 // they require array literals.
348 macro_rules! array_impl_default {
349 {$n:expr, $t:ident $($ts:ident)*} => {
350 #[stable(since = "1.4.0", feature = "array_default")]
351 impl<T> Default for [T; $n] where T: Default {
352 fn default() -> [T; $n] {
353 [$t::default(), $($ts::default()),*]
356 array_impl_default!{($n - 1), $($ts)*}
359 #[stable(since = "1.4.0", feature = "array_default")]
360 impl<T> Default for [T; $n] {
361 fn default() -> [T; $n] { [] }
366 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}
368 #[cfg(not(bootstrap))]
370 impl<T, const N: usize> [T; N] {
371 /// Returns an array of the same size as `self`, with function `f` applied to each element
377 /// #![feature(array_map)]
378 /// let x = [1, 2, 3];
379 /// let y = x.map(|v| v + 1);
380 /// assert_eq!(y, [2, 3, 4]);
382 /// let x = [1, 2, 3];
383 /// let mut temp = 0;
384 /// let y = x.map(|v| { temp += 1; v * temp });
385 /// assert_eq!(y, [1, 4, 9]);
387 /// let x = ["Ferris", "Bueller's", "Day", "Off"];
388 /// let y = x.map(|v| v.len());
389 /// assert_eq!(y, [6, 9, 3, 3]);
391 #[unstable(feature = "array_map", issue = "75243")]
392 pub fn map<F, U>(self, mut f: F) -> [U; N]
396 use crate::mem::MaybeUninit;
397 struct Guard<T, const N: usize> {
402 impl<T, const N: usize> Drop for Guard<T, N> {
404 debug_assert!(self.initialized <= N);
406 let initialized_part =
407 crate::ptr::slice_from_raw_parts_mut(self.dst, self.initialized);
408 // SAFETY: this raw slice will contain only initialized objects
409 // that's why, it is allowed to drop it.
411 crate::ptr::drop_in_place(initialized_part);
415 let mut dst = MaybeUninit::uninit_array::<N>();
416 let mut guard: Guard<U, N> =
417 Guard { dst: MaybeUninit::first_ptr_mut(&mut dst), initialized: 0 };
418 for (src, dst) in IntoIter::new(self).zip(&mut dst) {
420 guard.initialized += 1;
422 // FIXME: Convert to crate::mem::transmute once it works with generics.
423 // unsafe { crate::mem::transmute::<[MaybeUninit<U>; N], [U; N]>(dst) }
424 crate::mem::forget(guard);
425 // SAFETY: At this point we've properly initialized the whole array
426 // and we just need to cast it to the correct type.
427 unsafe { crate::mem::transmute_copy::<_, [U; N]>(&dst) }