]> git.lizzy.rs Git - rust.git/blob - src/libcore/array.rs
Rollup merge of #58595 - stjepang:make-duration-consts-associated, r=oli-obk
[rust.git] / src / libcore / array.rs
1 //! Implementations of things like `Eq` for fixed-length arrays
2 //! up to a certain length. Eventually we should able to generalize
3 //! to all lengths.
4 //!
5 //! *[See also the array primitive type](../../std/primitive.array.html).*
6
7 #![unstable(feature = "fixed_size_array",
8             reason = "traits and impls are better expressed through generic \
9                       integer constants",
10             issue = "27778")]
11
12 use borrow::{Borrow, BorrowMut};
13 use cmp::Ordering;
14 use convert::TryFrom;
15 use fmt;
16 use hash::{Hash, self};
17 use marker::Unsize;
18 use slice::{Iter, IterMut};
19
20 /// Utility trait implemented only on arrays of fixed size
21 ///
22 /// This trait can be used to implement other traits on fixed-size arrays
23 /// without causing much metadata bloat.
24 ///
25 /// The trait is marked unsafe in order to restrict implementors to fixed-size
26 /// arrays. User of this trait can assume that implementors have the exact
27 /// layout in memory of a fixed size array (for example, for unsafe
28 /// initialization).
29 ///
30 /// Note that the traits AsRef and AsMut provide similar methods for types that
31 /// may not be fixed-size arrays. Implementors should prefer those traits
32 /// instead.
33 pub unsafe trait FixedSizeArray<T> {
34     /// Converts the array to immutable slice
35     fn as_slice(&self) -> &[T];
36     /// Converts the array to mutable slice
37     fn as_mut_slice(&mut self) -> &mut [T];
38 }
39
40 unsafe impl<T, A: Unsize<[T]>> FixedSizeArray<T> for A {
41     #[inline]
42     fn as_slice(&self) -> &[T] {
43         self
44     }
45     #[inline]
46     fn as_mut_slice(&mut self) -> &mut [T] {
47         self
48     }
49 }
50
51 /// The error type returned when a conversion from a slice to an array fails.
52 #[unstable(feature = "try_from", issue = "33417")]
53 #[derive(Debug, Copy, Clone)]
54 pub struct TryFromSliceError(());
55
56 impl fmt::Display for TryFromSliceError {
57     #[inline]
58     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
59         fmt::Display::fmt(self.__description(), f)
60     }
61 }
62
63 impl TryFromSliceError {
64     #[unstable(feature = "array_error_internals",
65            reason = "available through Error trait and this method should not \
66                      be exposed publicly",
67            issue = "0")]
68     #[inline]
69     #[doc(hidden)]
70     pub fn __description(&self) -> &str {
71         "could not convert slice to array"
72     }
73 }
74
75 macro_rules! __impl_slice_eq1 {
76     ($Lhs: ty, $Rhs: ty) => {
77         __impl_slice_eq1! { $Lhs, $Rhs, Sized }
78     };
79     ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
80         #[stable(feature = "rust1", since = "1.0.0")]
81         impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
82             #[inline]
83             fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] }
84             #[inline]
85             fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] }
86         }
87     }
88 }
89
90 macro_rules! __impl_slice_eq2 {
91     ($Lhs: ty, $Rhs: ty) => {
92         __impl_slice_eq2! { $Lhs, $Rhs, Sized }
93     };
94     ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
95         __impl_slice_eq1!($Lhs, $Rhs, $Bound);
96
97         #[stable(feature = "rust1", since = "1.0.0")]
98         impl<'a, 'b, A: $Bound, B> PartialEq<$Lhs> for $Rhs where B: PartialEq<A> {
99             #[inline]
100             fn eq(&self, other: &$Lhs) -> bool { self[..] == other[..] }
101             #[inline]
102             fn ne(&self, other: &$Lhs) -> bool { self[..] != other[..] }
103         }
104     }
105 }
106
107 // macro for implementing n-element array functions and operations
108 macro_rules! array_impls {
109     ($($N:expr)+) => {
110         $(
111             #[stable(feature = "rust1", since = "1.0.0")]
112             impl<T> AsRef<[T]> for [T; $N] {
113                 #[inline]
114                 fn as_ref(&self) -> &[T] {
115                     &self[..]
116                 }
117             }
118
119             #[stable(feature = "rust1", since = "1.0.0")]
120             impl<T> AsMut<[T]> for [T; $N] {
121                 #[inline]
122                 fn as_mut(&mut self) -> &mut [T] {
123                     &mut self[..]
124                 }
125             }
126
127             #[stable(feature = "array_borrow", since = "1.4.0")]
128             impl<T> Borrow<[T]> for [T; $N] {
129                 fn borrow(&self) -> &[T] {
130                     self
131                 }
132             }
133
134             #[stable(feature = "array_borrow", since = "1.4.0")]
135             impl<T> BorrowMut<[T]> for [T; $N] {
136                 fn borrow_mut(&mut self) -> &mut [T] {
137                     self
138                 }
139             }
140
141             #[unstable(feature = "try_from", issue = "33417")]
142             impl<'a, T> TryFrom<&'a [T]> for [T; $N] where T: Copy {
143                 type Error = TryFromSliceError;
144
145                 fn try_from(slice: &[T]) -> Result<[T; $N], TryFromSliceError> {
146                     <&Self>::try_from(slice).map(|r| *r)
147                 }
148             }
149
150             #[unstable(feature = "try_from", issue = "33417")]
151             impl<'a, T> TryFrom<&'a [T]> for &'a [T; $N] {
152                 type Error = TryFromSliceError;
153
154                 fn try_from(slice: &[T]) -> Result<&[T; $N], TryFromSliceError> {
155                     if slice.len() == $N {
156                         let ptr = slice.as_ptr() as *const [T; $N];
157                         unsafe { Ok(&*ptr) }
158                     } else {
159                         Err(TryFromSliceError(()))
160                     }
161                 }
162             }
163
164             #[unstable(feature = "try_from", issue = "33417")]
165             impl<'a, T> TryFrom<&'a mut [T]> for &'a mut [T; $N] {
166                 type Error = TryFromSliceError;
167
168                 fn try_from(slice: &mut [T]) -> Result<&mut [T; $N], TryFromSliceError> {
169                     if slice.len() == $N {
170                         let ptr = slice.as_mut_ptr() as *mut [T; $N];
171                         unsafe { Ok(&mut *ptr) }
172                     } else {
173                         Err(TryFromSliceError(()))
174                     }
175                 }
176             }
177
178             #[stable(feature = "rust1", since = "1.0.0")]
179             impl<T: Hash> Hash for [T; $N] {
180                 fn hash<H: hash::Hasher>(&self, state: &mut H) {
181                     Hash::hash(&self[..], state)
182                 }
183             }
184
185             #[stable(feature = "rust1", since = "1.0.0")]
186             impl<T: fmt::Debug> fmt::Debug for [T; $N] {
187                 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
188                     fmt::Debug::fmt(&&self[..], f)
189                 }
190             }
191
192             #[stable(feature = "rust1", since = "1.0.0")]
193             impl<'a, T> IntoIterator for &'a [T; $N] {
194                 type Item = &'a T;
195                 type IntoIter = Iter<'a, T>;
196
197                 fn into_iter(self) -> Iter<'a, T> {
198                     self.iter()
199                 }
200             }
201
202             #[stable(feature = "rust1", since = "1.0.0")]
203             impl<'a, T> IntoIterator for &'a mut [T; $N] {
204                 type Item = &'a mut T;
205                 type IntoIter = IterMut<'a, T>;
206
207                 fn into_iter(self) -> IterMut<'a, T> {
208                     self.iter_mut()
209                 }
210             }
211
212             // NOTE: some less important impls are omitted to reduce code bloat
213             __impl_slice_eq1! { [A; $N], [B; $N] }
214             __impl_slice_eq2! { [A; $N], [B] }
215             __impl_slice_eq2! { [A; $N], &'b [B] }
216             __impl_slice_eq2! { [A; $N], &'b mut [B] }
217             // __impl_slice_eq2! { [A; $N], &'b [B; $N] }
218             // __impl_slice_eq2! { [A; $N], &'b mut [B; $N] }
219
220             #[stable(feature = "rust1", since = "1.0.0")]
221             impl<T:Eq> Eq for [T; $N] { }
222
223             #[stable(feature = "rust1", since = "1.0.0")]
224             impl<T:PartialOrd> PartialOrd for [T; $N] {
225                 #[inline]
226                 fn partial_cmp(&self, other: &[T; $N]) -> Option<Ordering> {
227                     PartialOrd::partial_cmp(&&self[..], &&other[..])
228                 }
229                 #[inline]
230                 fn lt(&self, other: &[T; $N]) -> bool {
231                     PartialOrd::lt(&&self[..], &&other[..])
232                 }
233                 #[inline]
234                 fn le(&self, other: &[T; $N]) -> bool {
235                     PartialOrd::le(&&self[..], &&other[..])
236                 }
237                 #[inline]
238                 fn ge(&self, other: &[T; $N]) -> bool {
239                     PartialOrd::ge(&&self[..], &&other[..])
240                 }
241                 #[inline]
242                 fn gt(&self, other: &[T; $N]) -> bool {
243                     PartialOrd::gt(&&self[..], &&other[..])
244                 }
245             }
246
247             #[stable(feature = "rust1", since = "1.0.0")]
248             impl<T:Ord> Ord for [T; $N] {
249                 #[inline]
250                 fn cmp(&self, other: &[T; $N]) -> Ordering {
251                     Ord::cmp(&&self[..], &&other[..])
252                 }
253             }
254         )+
255     }
256 }
257
258 array_impls! {
259      0  1  2  3  4  5  6  7  8  9
260     10 11 12 13 14 15 16 17 18 19
261     20 21 22 23 24 25 26 27 28 29
262     30 31 32
263 }
264
265 // The Default impls cannot be generated using the array_impls! macro because
266 // they require array literals.
267
268 macro_rules! array_impl_default {
269     {$n:expr, $t:ident $($ts:ident)*} => {
270         #[stable(since = "1.4.0", feature = "array_default")]
271         impl<T> Default for [T; $n] where T: Default {
272             fn default() -> [T; $n] {
273                 [$t::default(), $($ts::default()),*]
274             }
275         }
276         array_impl_default!{($n - 1), $($ts)*}
277     };
278     {$n:expr,} => {
279         #[stable(since = "1.4.0", feature = "array_default")]
280         impl<T> Default for [T; $n] {
281             fn default() -> [T; $n] { [] }
282         }
283     };
284 }
285
286 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}