]> git.lizzy.rs Git - rust.git/blob - src/libcore/array.rs
Rollup merge of #63208 - tmandry:issue-62658, r=cramertj
[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 #![stable(feature = "core_array", since = "1.36.0")]
8
9 use crate::borrow::{Borrow, BorrowMut};
10 use crate::cmp::Ordering;
11 use crate::convert::{Infallible, TryFrom};
12 use crate::fmt;
13 use crate::hash::{Hash, self};
14 use crate::marker::Unsize;
15 use crate::slice::{Iter, IterMut};
16
17 /// Utility trait implemented only on arrays of fixed size
18 ///
19 /// This trait can be used to implement other traits on fixed-size arrays
20 /// without causing much metadata bloat.
21 ///
22 /// The trait is marked unsafe in order to restrict implementors to fixed-size
23 /// arrays. User of this trait can assume that implementors have the exact
24 /// layout in memory of a fixed size array (for example, for unsafe
25 /// initialization).
26 ///
27 /// Note that the traits [`AsRef`] and [`AsMut`] provide similar methods for types that
28 /// may not be fixed-size arrays. Implementors should prefer those traits
29 /// instead.
30 ///
31 /// [`AsRef`]: ../convert/trait.AsRef.html
32 /// [`AsMut`]: ../convert/trait.AsMut.html
33 #[unstable(feature = "fixed_size_array", issue = "27778")]
34 pub unsafe trait FixedSizeArray<T> {
35     /// Converts the array to immutable slice
36     #[unstable(feature = "fixed_size_array", issue = "27778")]
37     fn as_slice(&self) -> &[T];
38     /// Converts the array to mutable slice
39     #[unstable(feature = "fixed_size_array", issue = "27778")]
40     fn as_mut_slice(&mut self) -> &mut [T];
41 }
42
43 #[unstable(feature = "fixed_size_array", issue = "27778")]
44 unsafe impl<T, A: Unsize<[T]>> FixedSizeArray<T> for A {
45     #[inline]
46     fn as_slice(&self) -> &[T] {
47         self
48     }
49     #[inline]
50     fn as_mut_slice(&mut self) -> &mut [T] {
51         self
52     }
53 }
54
55 /// The error type returned when a conversion from a slice to an array fails.
56 #[stable(feature = "try_from", since = "1.34.0")]
57 #[derive(Debug, Copy, Clone)]
58 pub struct TryFromSliceError(());
59
60 #[stable(feature = "core_array", since = "1.36.0")]
61 impl fmt::Display for TryFromSliceError {
62     #[inline]
63     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64         fmt::Display::fmt(self.__description(), f)
65     }
66 }
67
68 impl TryFromSliceError {
69     #[unstable(feature = "array_error_internals",
70            reason = "available through Error trait and this method should not \
71                      be exposed publicly",
72            issue = "0")]
73     #[inline]
74     #[doc(hidden)]
75     pub fn __description(&self) -> &str {
76         "could not convert slice to array"
77     }
78 }
79
80 #[stable(feature = "try_from_slice_error", since = "1.36.0")]
81 impl From<Infallible> for TryFromSliceError {
82     fn from(x: Infallible) -> TryFromSliceError {
83         match x {}
84     }
85 }
86
87 #[stable(feature = "rust1", since = "1.0.0")]
88 impl<T, const N: usize> AsRef<[T]> for [T; N]
89 where
90     [T; N]: LengthAtMost32,
91 {
92     #[inline]
93     fn as_ref(&self) -> &[T] {
94         &self[..]
95     }
96 }
97
98 #[stable(feature = "rust1", since = "1.0.0")]
99 impl<T, const N: usize> AsMut<[T]> for [T; N]
100 where
101     [T; N]: LengthAtMost32,
102 {
103     #[inline]
104     fn as_mut(&mut self) -> &mut [T] {
105         &mut self[..]
106     }
107 }
108
109 #[stable(feature = "array_borrow", since = "1.4.0")]
110 impl<T, const N: usize> Borrow<[T]> for [T; N]
111 where
112     [T; N]: LengthAtMost32,
113 {
114     fn borrow(&self) -> &[T] {
115         self
116     }
117 }
118
119 #[stable(feature = "array_borrow", since = "1.4.0")]
120 impl<T, const N: usize> BorrowMut<[T]> for [T; N]
121 where
122     [T; N]: LengthAtMost32,
123 {
124     fn borrow_mut(&mut self) -> &mut [T] {
125         self
126     }
127 }
128
129 #[stable(feature = "try_from", since = "1.34.0")]
130 impl<T, const N: usize> TryFrom<&[T]> for [T; N]
131 where
132     T: Copy,
133     [T; N]: LengthAtMost32,
134 {
135     type Error = TryFromSliceError;
136
137     fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError> {
138         <&Self>::try_from(slice).map(|r| *r)
139     }
140 }
141
142 #[stable(feature = "try_from", since = "1.34.0")]
143 impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N]
144 where
145     [T; N]: LengthAtMost32,
146 {
147     type Error = TryFromSliceError;
148
149     fn try_from(slice: &[T]) -> Result<&[T; N], TryFromSliceError> {
150         if slice.len() == N {
151             let ptr = slice.as_ptr() as *const [T; N];
152             unsafe { Ok(&*ptr) }
153         } else {
154             Err(TryFromSliceError(()))
155         }
156     }
157 }
158
159 #[stable(feature = "try_from", since = "1.34.0")]
160 impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N]
161 where
162     [T; N]: LengthAtMost32,
163 {
164     type Error = TryFromSliceError;
165
166     fn try_from(slice: &mut [T]) -> Result<&mut [T; N], TryFromSliceError> {
167         if slice.len() == N {
168             let ptr = slice.as_mut_ptr() as *mut [T; N];
169             unsafe { Ok(&mut *ptr) }
170         } else {
171             Err(TryFromSliceError(()))
172         }
173     }
174 }
175
176 #[stable(feature = "rust1", since = "1.0.0")]
177 impl<T: Hash, const N: usize> Hash for [T; N]
178 where
179     [T; N]: LengthAtMost32,
180 {
181     fn hash<H: hash::Hasher>(&self, state: &mut H) {
182         Hash::hash(&self[..], state)
183     }
184 }
185
186 #[stable(feature = "rust1", since = "1.0.0")]
187 impl<T: fmt::Debug, const N: usize> fmt::Debug for [T; N]
188 where
189     [T; N]: LengthAtMost32,
190 {
191     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192         fmt::Debug::fmt(&&self[..], f)
193     }
194 }
195
196 #[stable(feature = "rust1", since = "1.0.0")]
197 impl<'a, T, const N: usize> IntoIterator for &'a [T; N]
198 where
199     [T; N]: LengthAtMost32,
200 {
201     type Item = &'a T;
202     type IntoIter = Iter<'a, T>;
203
204     fn into_iter(self) -> Iter<'a, T> {
205         self.iter()
206     }
207 }
208
209 #[stable(feature = "rust1", since = "1.0.0")]
210 impl<'a, T, const N: usize> IntoIterator for &'a mut [T; N]
211 where
212     [T; N]: LengthAtMost32,
213 {
214     type Item = &'a mut T;
215     type IntoIter = IterMut<'a, T>;
216
217     fn into_iter(self) -> IterMut<'a, T> {
218         self.iter_mut()
219     }
220 }
221
222 #[stable(feature = "rust1", since = "1.0.0")]
223 impl<A, B, const N: usize> PartialEq<[B; N]> for [A; N]
224 where
225     A: PartialEq<B>,
226     [A; N]: LengthAtMost32,
227     [B; N]: LengthAtMost32,
228 {
229     #[inline]
230     fn eq(&self, other: &[B; N]) -> bool {
231         self[..] == other[..]
232     }
233     #[inline]
234     fn ne(&self, other: &[B; N]) -> bool {
235         self[..] != other[..]
236     }
237 }
238
239 #[stable(feature = "rust1", since = "1.0.0")]
240 impl<A, B, const N: usize> PartialEq<[B]> for [A; N]
241 where
242     A: PartialEq<B>,
243     [A; N]: LengthAtMost32,
244 {
245     #[inline]
246     fn eq(&self, other: &[B]) -> bool {
247         self[..] == other[..]
248     }
249     #[inline]
250     fn ne(&self, other: &[B]) -> bool {
251         self[..] != other[..]
252     }
253 }
254
255 #[stable(feature = "rust1", since = "1.0.0")]
256 impl<A, B, const N: usize> PartialEq<[A; N]> for [B]
257 where
258     B: PartialEq<A>,
259     [A; N]: LengthAtMost32,
260 {
261     #[inline]
262     fn eq(&self, other: &[A; N]) -> bool {
263         self[..] == other[..]
264     }
265     #[inline]
266     fn ne(&self, other: &[A; N]) -> bool {
267         self[..] != other[..]
268     }
269 }
270
271 #[stable(feature = "rust1", since = "1.0.0")]
272 impl<'b, A, B, const N: usize> PartialEq<&'b [B]> for [A; N]
273 where
274     A: PartialEq<B>,
275     [A; N]: LengthAtMost32,
276 {
277     #[inline]
278     fn eq(&self, other: &&'b [B]) -> bool {
279         self[..] == other[..]
280     }
281     #[inline]
282     fn ne(&self, other: &&'b [B]) -> bool {
283         self[..] != other[..]
284     }
285 }
286
287 #[stable(feature = "rust1", since = "1.0.0")]
288 impl<'b, A, B, const N: usize> PartialEq<[A; N]> for &'b [B]
289 where
290     B: PartialEq<A>,
291     [A; N]: LengthAtMost32,
292 {
293     #[inline]
294     fn eq(&self, other: &[A; N]) -> bool {
295         self[..] == other[..]
296     }
297     #[inline]
298     fn ne(&self, other: &[A; N]) -> bool {
299         self[..] != other[..]
300     }
301 }
302
303 #[stable(feature = "rust1", since = "1.0.0")]
304 impl<'b, A, B, const N: usize> PartialEq<&'b mut [B]> for [A; N]
305 where
306     A: PartialEq<B>,
307     [A; N]: LengthAtMost32,
308 {
309     #[inline]
310     fn eq(&self, other: &&'b mut [B]) -> bool {
311         self[..] == other[..]
312     }
313     #[inline]
314     fn ne(&self, other: &&'b mut [B]) -> bool {
315         self[..] != other[..]
316     }
317 }
318
319 #[stable(feature = "rust1", since = "1.0.0")]
320 impl<'b, A, B, const N: usize> PartialEq<[A; N]> for &'b mut [B]
321 where
322     B: PartialEq<A>,
323     [A; N]: LengthAtMost32,
324 {
325     #[inline]
326     fn eq(&self, other: &[A; N]) -> bool {
327         self[..] == other[..]
328     }
329     #[inline]
330     fn ne(&self, other: &[A; N]) -> bool {
331         self[..] != other[..]
332     }
333 }
334
335 // NOTE: some less important impls are omitted to reduce code bloat
336 // __impl_slice_eq2! { [A; $N], &'b [B; $N] }
337 // __impl_slice_eq2! { [A; $N], &'b mut [B; $N] }
338
339 #[stable(feature = "rust1", since = "1.0.0")]
340 impl<T: Eq, const N: usize> Eq for [T; N] where [T; N]: LengthAtMost32 {}
341
342 #[stable(feature = "rust1", since = "1.0.0")]
343 impl<T: PartialOrd, const N: usize> PartialOrd for [T; N]
344 where
345     [T; N]: LengthAtMost32,
346 {
347     #[inline]
348     fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
349         PartialOrd::partial_cmp(&&self[..], &&other[..])
350     }
351     #[inline]
352     fn lt(&self, other: &[T; N]) -> bool {
353         PartialOrd::lt(&&self[..], &&other[..])
354     }
355     #[inline]
356     fn le(&self, other: &[T; N]) -> bool {
357         PartialOrd::le(&&self[..], &&other[..])
358     }
359     #[inline]
360     fn ge(&self, other: &[T; N]) -> bool {
361         PartialOrd::ge(&&self[..], &&other[..])
362     }
363     #[inline]
364     fn gt(&self, other: &[T; N]) -> bool {
365         PartialOrd::gt(&&self[..], &&other[..])
366     }
367 }
368
369 #[stable(feature = "rust1", since = "1.0.0")]
370 impl<T: Ord, const N: usize> Ord for [T; N]
371 where
372     [T; N]: LengthAtMost32,
373 {
374     #[inline]
375     fn cmp(&self, other: &[T; N]) -> Ordering {
376         Ord::cmp(&&self[..], &&other[..])
377     }
378 }
379
380 /// Implemented for lengths where trait impls are allowed on arrays in core/std
381 #[rustc_on_unimplemented(
382     message="arrays only have std trait implementations for lengths 0..=32",
383 )]
384 #[unstable(feature = "const_generic_impls_guard", issue = "0",
385     reason = "will never be stable, just a temporary step until const generics are stable")]
386 pub trait LengthAtMost32 {}
387
388 macro_rules! array_impls {
389     ($($N:literal)+) => {
390         $(
391             #[unstable(feature = "const_generic_impls_guard", issue = "0")]
392             impl<T> LengthAtMost32 for [T; $N] {}
393         )+
394     }
395 }
396
397 array_impls! {
398      0  1  2  3  4  5  6  7  8  9
399     10 11 12 13 14 15 16 17 18 19
400     20 21 22 23 24 25 26 27 28 29
401     30 31 32
402 }
403
404 // The Default impls cannot be generated using the array_impls! macro because
405 // they require array literals.
406
407 macro_rules! array_impl_default {
408     {$n:expr, $t:ident $($ts:ident)*} => {
409         #[stable(since = "1.4.0", feature = "array_default")]
410         impl<T> Default for [T; $n] where T: Default {
411             fn default() -> [T; $n] {
412                 [$t::default(), $($ts::default()),*]
413             }
414         }
415         array_impl_default!{($n - 1), $($ts)*}
416     };
417     {$n:expr,} => {
418         #[stable(since = "1.4.0", feature = "array_default")]
419         impl<T> Default for [T; $n] {
420             fn default() -> [T; $n] { [] }
421         }
422     };
423 }
424
425 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}