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