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