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