]> git.lizzy.rs Git - rust.git/blob - library/core/src/array/mod.rs
Rollup merge of #75837 - GuillaumeGomez:fix-font-color-help-button, r=Cldfire
[rust.git] / library / core / src / 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 #[unstable(feature = "fixed_size_array", issue = "27778")]
36 pub unsafe trait FixedSizeArray<T> {
37     /// Converts the array to immutable slice
38     #[unstable(feature = "fixed_size_array", issue = "27778")]
39     fn as_slice(&self) -> &[T];
40     /// Converts the array to mutable slice
41     #[unstable(feature = "fixed_size_array", issue = "27778")]
42     fn as_mut_slice(&mut self) -> &mut [T];
43 }
44
45 #[unstable(feature = "fixed_size_array", issue = "27778")]
46 unsafe impl<T, A: Unsize<[T]>> FixedSizeArray<T> for A {
47     #[inline]
48     fn as_slice(&self) -> &[T] {
49         self
50     }
51     #[inline]
52     fn as_mut_slice(&mut self) -> &mut [T] {
53         self
54     }
55 }
56
57 /// The error type returned when a conversion from a slice to an array fails.
58 #[stable(feature = "try_from", since = "1.34.0")]
59 #[derive(Debug, Copy, Clone)]
60 pub struct TryFromSliceError(());
61
62 #[stable(feature = "core_array", since = "1.36.0")]
63 impl fmt::Display for TryFromSliceError {
64     #[inline]
65     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66         fmt::Display::fmt(self.__description(), f)
67     }
68 }
69
70 impl TryFromSliceError {
71     #[unstable(
72         feature = "array_error_internals",
73         reason = "available through Error trait and this method should not \
74                      be exposed publicly",
75         issue = "none"
76     )]
77     #[inline]
78     #[doc(hidden)]
79     pub fn __description(&self) -> &str {
80         "could not convert slice to array"
81     }
82 }
83
84 #[stable(feature = "try_from_slice_error", since = "1.36.0")]
85 impl From<Infallible> for TryFromSliceError {
86     fn from(x: Infallible) -> TryFromSliceError {
87         match x {}
88     }
89 }
90
91 #[stable(feature = "rust1", since = "1.0.0")]
92 impl<T, const N: usize> AsRef<[T]> for [T; N] {
93     #[inline]
94     fn as_ref(&self) -> &[T] {
95         &self[..]
96     }
97 }
98
99 #[stable(feature = "rust1", since = "1.0.0")]
100 impl<T, const N: usize> AsMut<[T]> for [T; N] {
101     #[inline]
102     fn as_mut(&mut self) -> &mut [T] {
103         &mut self[..]
104     }
105 }
106
107 #[stable(feature = "array_borrow", since = "1.4.0")]
108 impl<T, const N: usize> Borrow<[T]> for [T; N] {
109     fn borrow(&self) -> &[T] {
110         self
111     }
112 }
113
114 #[stable(feature = "array_borrow", since = "1.4.0")]
115 impl<T, const N: usize> BorrowMut<[T]> for [T; N] {
116     fn borrow_mut(&mut self) -> &mut [T] {
117         self
118     }
119 }
120
121 #[stable(feature = "try_from", since = "1.34.0")]
122 impl<T, const N: usize> TryFrom<&[T]> for [T; N]
123 where
124     T: Copy,
125 {
126     type Error = TryFromSliceError;
127
128     fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError> {
129         <&Self>::try_from(slice).map(|r| *r)
130     }
131 }
132
133 #[stable(feature = "try_from", since = "1.34.0")]
134 impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N] {
135     type Error = TryFromSliceError;
136
137     fn try_from(slice: &[T]) -> Result<&[T; N], TryFromSliceError> {
138         if slice.len() == N {
139             let ptr = slice.as_ptr() as *const [T; N];
140             // SAFETY: ok because we just checked that the length fits
141             unsafe { Ok(&*ptr) }
142         } else {
143             Err(TryFromSliceError(()))
144         }
145     }
146 }
147
148 #[stable(feature = "try_from", since = "1.34.0")]
149 impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N] {
150     type Error = TryFromSliceError;
151
152     fn try_from(slice: &mut [T]) -> Result<&mut [T; N], TryFromSliceError> {
153         if slice.len() == N {
154             let ptr = slice.as_mut_ptr() as *mut [T; N];
155             // SAFETY: ok because we just checked that the length fits
156             unsafe { Ok(&mut *ptr) }
157         } else {
158             Err(TryFromSliceError(()))
159         }
160     }
161 }
162
163 #[stable(feature = "rust1", since = "1.0.0")]
164 impl<T: Hash, const N: usize> Hash for [T; N] {
165     fn hash<H: hash::Hasher>(&self, state: &mut H) {
166         Hash::hash(&self[..], state)
167     }
168 }
169
170 #[stable(feature = "rust1", since = "1.0.0")]
171 impl<T: fmt::Debug, const N: usize> fmt::Debug for [T; N] {
172     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173         fmt::Debug::fmt(&&self[..], f)
174     }
175 }
176
177 #[stable(feature = "rust1", since = "1.0.0")]
178 impl<'a, T, const N: usize> IntoIterator for &'a [T; N] {
179     type Item = &'a T;
180     type IntoIter = Iter<'a, T>;
181
182     fn into_iter(self) -> Iter<'a, T> {
183         self.iter()
184     }
185 }
186
187 #[stable(feature = "rust1", since = "1.0.0")]
188 impl<'a, T, const N: usize> IntoIterator for &'a mut [T; N] {
189     type Item = &'a mut T;
190     type IntoIter = IterMut<'a, T>;
191
192     fn into_iter(self) -> IterMut<'a, T> {
193         self.iter_mut()
194     }
195 }
196
197 #[stable(feature = "rust1", since = "1.0.0")]
198 impl<A, B, const N: usize> PartialEq<[B; N]> for [A; N]
199 where
200     A: PartialEq<B>,
201 {
202     #[inline]
203     fn eq(&self, other: &[B; N]) -> bool {
204         self[..] == other[..]
205     }
206     #[inline]
207     fn ne(&self, other: &[B; N]) -> bool {
208         self[..] != other[..]
209     }
210 }
211
212 #[stable(feature = "rust1", since = "1.0.0")]
213 impl<A, B, const N: usize> PartialEq<[B]> for [A; N]
214 where
215     A: PartialEq<B>,
216 {
217     #[inline]
218     fn eq(&self, other: &[B]) -> bool {
219         self[..] == other[..]
220     }
221     #[inline]
222     fn ne(&self, other: &[B]) -> bool {
223         self[..] != other[..]
224     }
225 }
226
227 #[stable(feature = "rust1", since = "1.0.0")]
228 impl<A, B, const N: usize> PartialEq<[A; N]> for [B]
229 where
230     B: PartialEq<A>,
231 {
232     #[inline]
233     fn eq(&self, other: &[A; N]) -> bool {
234         self[..] == other[..]
235     }
236     #[inline]
237     fn ne(&self, other: &[A; N]) -> bool {
238         self[..] != other[..]
239     }
240 }
241
242 #[stable(feature = "rust1", since = "1.0.0")]
243 impl<'b, A, B, const N: usize> PartialEq<&'b [B]> for [A; N]
244 where
245     A: PartialEq<B>,
246 {
247     #[inline]
248     fn eq(&self, other: &&'b [B]) -> bool {
249         self[..] == other[..]
250     }
251     #[inline]
252     fn ne(&self, other: &&'b [B]) -> bool {
253         self[..] != other[..]
254     }
255 }
256
257 #[stable(feature = "rust1", since = "1.0.0")]
258 impl<'b, A, B, const N: usize> PartialEq<[A; N]> for &'b [B]
259 where
260     B: PartialEq<A>,
261 {
262     #[inline]
263     fn eq(&self, other: &[A; N]) -> bool {
264         self[..] == other[..]
265     }
266     #[inline]
267     fn ne(&self, other: &[A; N]) -> bool {
268         self[..] != other[..]
269     }
270 }
271
272 #[stable(feature = "rust1", since = "1.0.0")]
273 impl<'b, A, B, const N: usize> PartialEq<&'b mut [B]> for [A; N]
274 where
275     A: PartialEq<B>,
276 {
277     #[inline]
278     fn eq(&self, other: &&'b mut [B]) -> bool {
279         self[..] == other[..]
280     }
281     #[inline]
282     fn ne(&self, other: &&'b mut [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 mut [B]
289 where
290     B: PartialEq<A>,
291 {
292     #[inline]
293     fn eq(&self, other: &[A; N]) -> bool {
294         self[..] == other[..]
295     }
296     #[inline]
297     fn ne(&self, other: &[A; N]) -> bool {
298         self[..] != other[..]
299     }
300 }
301
302 // NOTE: some less important impls are omitted to reduce code bloat
303 // __impl_slice_eq2! { [A; $N], &'b [B; $N] }
304 // __impl_slice_eq2! { [A; $N], &'b mut [B; $N] }
305
306 #[stable(feature = "rust1", since = "1.0.0")]
307 impl<T: Eq, const N: usize> Eq for [T; N] {}
308
309 #[stable(feature = "rust1", since = "1.0.0")]
310 impl<T: PartialOrd, const N: usize> PartialOrd for [T; N] {
311     #[inline]
312     fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
313         PartialOrd::partial_cmp(&&self[..], &&other[..])
314     }
315     #[inline]
316     fn lt(&self, other: &[T; N]) -> bool {
317         PartialOrd::lt(&&self[..], &&other[..])
318     }
319     #[inline]
320     fn le(&self, other: &[T; N]) -> bool {
321         PartialOrd::le(&&self[..], &&other[..])
322     }
323     #[inline]
324     fn ge(&self, other: &[T; N]) -> bool {
325         PartialOrd::ge(&&self[..], &&other[..])
326     }
327     #[inline]
328     fn gt(&self, other: &[T; N]) -> bool {
329         PartialOrd::gt(&&self[..], &&other[..])
330     }
331 }
332
333 /// Implements comparison of arrays lexicographically.
334 #[stable(feature = "rust1", since = "1.0.0")]
335 impl<T: Ord, const N: usize> Ord for [T; N] {
336     #[inline]
337     fn cmp(&self, other: &[T; N]) -> Ordering {
338         Ord::cmp(&&self[..], &&other[..])
339     }
340 }
341
342 // The Default impls cannot be generated using the array_impls! macro because
343 // they require array literals.
344
345 macro_rules! array_impl_default {
346     {$n:expr, $t:ident $($ts:ident)*} => {
347         #[stable(since = "1.4.0", feature = "array_default")]
348         impl<T> Default for [T; $n] where T: Default {
349             fn default() -> [T; $n] {
350                 [$t::default(), $($ts::default()),*]
351             }
352         }
353         array_impl_default!{($n - 1), $($ts)*}
354     };
355     {$n:expr,} => {
356         #[stable(since = "1.4.0", feature = "array_default")]
357         impl<T> Default for [T; $n] {
358             fn default() -> [T; $n] { [] }
359         }
360     };
361 }
362
363 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}
364
365 #[cfg(not(bootstrap))]
366 #[lang = "array"]
367 impl<T, const N: usize> [T; N] {
368     /// Returns an array of the same size as `self`, with function `f` applied to each element
369     /// in order.
370     ///
371     /// # Examples
372     ///
373     /// ```
374     /// #![feature(array_map)]
375     /// let x = [1, 2, 3];
376     /// let y = x.map(|v| v + 1);
377     /// assert_eq!(y, [2, 3, 4]);
378     ///
379     /// let x = [1, 2, 3];
380     /// let mut temp = 0;
381     /// let y = x.map(|v| { temp += 1; v * temp });
382     /// assert_eq!(y, [1, 4, 9]);
383     ///
384     /// let x = ["Ferris", "Bueller's", "Day", "Off"];
385     /// let y = x.map(|v| v.len());
386     /// assert_eq!(y, [6, 9, 3, 3]);
387     /// ```
388     #[unstable(feature = "array_map", issue = "75243")]
389     pub fn map<F, U>(self, mut f: F) -> [U; N]
390     where
391         F: FnMut(T) -> U,
392     {
393         use crate::mem::MaybeUninit;
394         struct Guard<T, const N: usize> {
395             dst: *mut T,
396             initialized: usize,
397         }
398
399         impl<T, const N: usize> Drop for Guard<T, N> {
400             fn drop(&mut self) {
401                 debug_assert!(self.initialized <= N);
402
403                 let initialized_part =
404                     crate::ptr::slice_from_raw_parts_mut(self.dst, self.initialized);
405                 // SAFETY: this raw slice will contain only initialized objects
406                 // that's why, it is allowed to drop it.
407                 unsafe {
408                     crate::ptr::drop_in_place(initialized_part);
409                 }
410             }
411         }
412         let mut dst = MaybeUninit::uninit_array::<N>();
413         let mut guard: Guard<U, N> =
414             Guard { dst: MaybeUninit::first_ptr_mut(&mut dst), initialized: 0 };
415         for (src, dst) in IntoIter::new(self).zip(&mut dst) {
416             dst.write(f(src));
417             guard.initialized += 1;
418         }
419         // FIXME: Convert to crate::mem::transmute once it works with generics.
420         // unsafe { crate::mem::transmute::<[MaybeUninit<U>; N], [U; N]>(dst) }
421         crate::mem::forget(guard);
422         // SAFETY: At this point we've properly initialized the whole array
423         // and we just need to cast it to the correct type.
424         unsafe { crate::mem::transmute_copy::<_, [U; N]>(&dst) }
425     }
426 }