]> git.lizzy.rs Git - rust.git/blob - library/core/src/array/mod.rs
Update zip for better codegen, see discussion
[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::ops::{Index, IndexMut};
16 use crate::slice::{Iter, IterMut};
17
18 mod iter;
19
20 #[unstable(feature = "array_value_iter", issue = "65798")]
21 pub use iter::IntoIter;
22
23 /// Converts a reference to `T` into a reference to an array of length 1 (without copying).
24 #[unstable(feature = "array_from_ref", issue = "77101")]
25 pub fn from_ref<T>(s: &T) -> &[T; 1] {
26     // SAFETY: Converting `&T` to `&[T; 1]` is sound.
27     unsafe { &*(s as *const T).cast::<[T; 1]>() }
28 }
29
30 /// Converts a mutable reference to `T` into a mutable reference to an array of length 1 (without copying).
31 #[unstable(feature = "array_from_ref", issue = "77101")]
32 pub fn from_mut<T>(s: &mut T) -> &mut [T; 1] {
33     // SAFETY: Converting `&mut T` to `&mut [T; 1]` is sound.
34     unsafe { &mut *(s as *mut T).cast::<[T; 1]>() }
35 }
36
37 /// Utility trait implemented only on arrays of fixed size
38 ///
39 /// This trait can be used to implement other traits on fixed-size arrays
40 /// without causing much metadata bloat.
41 ///
42 /// The trait is marked unsafe in order to restrict implementors to fixed-size
43 /// arrays. User of this trait can assume that implementors have the exact
44 /// layout in memory of a fixed size array (for example, for unsafe
45 /// initialization).
46 ///
47 /// Note that the traits [`AsRef`] and [`AsMut`] provide similar methods for types that
48 /// may not be fixed-size arrays. Implementors should prefer those traits
49 /// instead.
50 #[unstable(feature = "fixed_size_array", issue = "27778")]
51 pub unsafe trait FixedSizeArray<T> {
52     /// Converts the array to immutable slice
53     #[unstable(feature = "fixed_size_array", issue = "27778")]
54     fn as_slice(&self) -> &[T];
55     /// Converts the array to mutable slice
56     #[unstable(feature = "fixed_size_array", issue = "27778")]
57     fn as_mut_slice(&mut self) -> &mut [T];
58 }
59
60 #[unstable(feature = "fixed_size_array", issue = "27778")]
61 unsafe impl<T, A: Unsize<[T]>> FixedSizeArray<T> for A {
62     #[inline]
63     fn as_slice(&self) -> &[T] {
64         self
65     }
66     #[inline]
67     fn as_mut_slice(&mut self) -> &mut [T] {
68         self
69     }
70 }
71
72 /// The error type returned when a conversion from a slice to an array fails.
73 #[stable(feature = "try_from", since = "1.34.0")]
74 #[derive(Debug, Copy, Clone)]
75 pub struct TryFromSliceError(());
76
77 #[stable(feature = "core_array", since = "1.36.0")]
78 impl fmt::Display for TryFromSliceError {
79     #[inline]
80     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81         fmt::Display::fmt(self.__description(), f)
82     }
83 }
84
85 impl TryFromSliceError {
86     #[unstable(
87         feature = "array_error_internals",
88         reason = "available through Error trait and this method should not \
89                      be exposed publicly",
90         issue = "none"
91     )]
92     #[inline]
93     #[doc(hidden)]
94     pub fn __description(&self) -> &str {
95         "could not convert slice to array"
96     }
97 }
98
99 #[stable(feature = "try_from_slice_error", since = "1.36.0")]
100 impl From<Infallible> for TryFromSliceError {
101     fn from(x: Infallible) -> TryFromSliceError {
102         match x {}
103     }
104 }
105
106 #[stable(feature = "rust1", since = "1.0.0")]
107 impl<T, const N: usize> AsRef<[T]> for [T; N] {
108     #[inline]
109     fn as_ref(&self) -> &[T] {
110         &self[..]
111     }
112 }
113
114 #[stable(feature = "rust1", since = "1.0.0")]
115 impl<T, const N: usize> AsMut<[T]> for [T; N] {
116     #[inline]
117     fn as_mut(&mut self) -> &mut [T] {
118         &mut self[..]
119     }
120 }
121
122 #[stable(feature = "array_borrow", since = "1.4.0")]
123 impl<T, const N: usize> Borrow<[T]> for [T; N] {
124     fn borrow(&self) -> &[T] {
125         self
126     }
127 }
128
129 #[stable(feature = "array_borrow", since = "1.4.0")]
130 impl<T, const N: usize> BorrowMut<[T]> for [T; N] {
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 {
141     type Error = TryFromSliceError;
142
143     fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError> {
144         <&Self>::try_from(slice).map(|r| *r)
145     }
146 }
147
148 #[stable(feature = "try_from", since = "1.34.0")]
149 impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N] {
150     type Error = TryFromSliceError;
151
152     fn try_from(slice: &[T]) -> Result<&[T; N], TryFromSliceError> {
153         if slice.len() == N {
154             let ptr = slice.as_ptr() as *const [T; N];
155             // SAFETY: ok because we just checked that the length fits
156             unsafe { Ok(&*ptr) }
157         } else {
158             Err(TryFromSliceError(()))
159         }
160     }
161 }
162
163 #[stable(feature = "try_from", since = "1.34.0")]
164 impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N] {
165     type Error = TryFromSliceError;
166
167     fn try_from(slice: &mut [T]) -> Result<&mut [T; N], TryFromSliceError> {
168         if slice.len() == N {
169             let ptr = slice.as_mut_ptr() as *mut [T; N];
170             // SAFETY: ok because we just checked that the length fits
171             unsafe { Ok(&mut *ptr) }
172         } else {
173             Err(TryFromSliceError(()))
174         }
175     }
176 }
177
178 #[stable(feature = "rust1", since = "1.0.0")]
179 impl<T: Hash, const N: usize> Hash for [T; N] {
180     fn hash<H: hash::Hasher>(&self, state: &mut H) {
181         Hash::hash(&self[..], state)
182     }
183 }
184
185 #[stable(feature = "rust1", since = "1.0.0")]
186 impl<T: fmt::Debug, const N: usize> fmt::Debug for [T; N] {
187     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188         fmt::Debug::fmt(&&self[..], f)
189     }
190 }
191
192 #[stable(feature = "rust1", since = "1.0.0")]
193 impl<'a, T, const N: usize> IntoIterator for &'a [T; N] {
194     type Item = &'a T;
195     type IntoIter = Iter<'a, T>;
196
197     fn into_iter(self) -> Iter<'a, T> {
198         self.iter()
199     }
200 }
201
202 #[stable(feature = "rust1", since = "1.0.0")]
203 impl<'a, T, const N: usize> IntoIterator for &'a mut [T; N] {
204     type Item = &'a mut T;
205     type IntoIter = IterMut<'a, T>;
206
207     fn into_iter(self) -> IterMut<'a, T> {
208         self.iter_mut()
209     }
210 }
211
212 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
213 impl<T, I, const N: usize> Index<I> for [T; N]
214 where
215     [T]: Index<I>,
216 {
217     type Output = <[T] as Index<I>>::Output;
218
219     #[inline]
220     fn index(&self, index: I) -> &Self::Output {
221         Index::index(self as &[T], index)
222     }
223 }
224
225 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
226 impl<T, I, const N: usize> IndexMut<I> for [T; N]
227 where
228     [T]: IndexMut<I>,
229 {
230     #[inline]
231     fn index_mut(&mut self, index: I) -> &mut Self::Output {
232         IndexMut::index_mut(self as &mut [T], index)
233     }
234 }
235
236 #[stable(feature = "rust1", since = "1.0.0")]
237 impl<A, B, const N: usize> PartialEq<[B; N]> for [A; N]
238 where
239     A: PartialEq<B>,
240 {
241     #[inline]
242     fn eq(&self, other: &[B; N]) -> bool {
243         self[..] == other[..]
244     }
245     #[inline]
246     fn ne(&self, other: &[B; N]) -> bool {
247         self[..] != other[..]
248     }
249 }
250
251 #[stable(feature = "rust1", since = "1.0.0")]
252 impl<A, B, const N: usize> PartialEq<[B]> for [A; N]
253 where
254     A: PartialEq<B>,
255 {
256     #[inline]
257     fn eq(&self, other: &[B]) -> bool {
258         self[..] == other[..]
259     }
260     #[inline]
261     fn ne(&self, other: &[B]) -> bool {
262         self[..] != other[..]
263     }
264 }
265
266 #[stable(feature = "rust1", since = "1.0.0")]
267 impl<A, B, const N: usize> PartialEq<[A; N]> for [B]
268 where
269     B: PartialEq<A>,
270 {
271     #[inline]
272     fn eq(&self, other: &[A; N]) -> bool {
273         self[..] == other[..]
274     }
275     #[inline]
276     fn ne(&self, other: &[A; N]) -> bool {
277         self[..] != other[..]
278     }
279 }
280
281 #[stable(feature = "rust1", since = "1.0.0")]
282 impl<A, B, const N: usize> PartialEq<&[B]> for [A; N]
283 where
284     A: PartialEq<B>,
285 {
286     #[inline]
287     fn eq(&self, other: &&[B]) -> bool {
288         self[..] == other[..]
289     }
290     #[inline]
291     fn ne(&self, other: &&[B]) -> bool {
292         self[..] != other[..]
293     }
294 }
295
296 #[stable(feature = "rust1", since = "1.0.0")]
297 impl<A, B, const N: usize> PartialEq<[A; N]> for &[B]
298 where
299     B: PartialEq<A>,
300 {
301     #[inline]
302     fn eq(&self, other: &[A; N]) -> bool {
303         self[..] == other[..]
304     }
305     #[inline]
306     fn ne(&self, other: &[A; N]) -> bool {
307         self[..] != other[..]
308     }
309 }
310
311 #[stable(feature = "rust1", since = "1.0.0")]
312 impl<A, B, const N: usize> PartialEq<&mut [B]> for [A; N]
313 where
314     A: PartialEq<B>,
315 {
316     #[inline]
317     fn eq(&self, other: &&mut [B]) -> bool {
318         self[..] == other[..]
319     }
320     #[inline]
321     fn ne(&self, other: &&mut [B]) -> bool {
322         self[..] != other[..]
323     }
324 }
325
326 #[stable(feature = "rust1", since = "1.0.0")]
327 impl<A, B, const N: usize> PartialEq<[A; N]> for &mut [B]
328 where
329     B: PartialEq<A>,
330 {
331     #[inline]
332     fn eq(&self, other: &[A; N]) -> bool {
333         self[..] == other[..]
334     }
335     #[inline]
336     fn ne(&self, other: &[A; N]) -> bool {
337         self[..] != other[..]
338     }
339 }
340
341 // NOTE: some less important impls are omitted to reduce code bloat
342 // __impl_slice_eq2! { [A; $N], &'b [B; $N] }
343 // __impl_slice_eq2! { [A; $N], &'b mut [B; $N] }
344
345 #[stable(feature = "rust1", since = "1.0.0")]
346 impl<T: Eq, const N: usize> Eq for [T; N] {}
347
348 #[stable(feature = "rust1", since = "1.0.0")]
349 impl<T: PartialOrd, const N: usize> PartialOrd for [T; N] {
350     #[inline]
351     fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
352         PartialOrd::partial_cmp(&&self[..], &&other[..])
353     }
354     #[inline]
355     fn lt(&self, other: &[T; N]) -> bool {
356         PartialOrd::lt(&&self[..], &&other[..])
357     }
358     #[inline]
359     fn le(&self, other: &[T; N]) -> bool {
360         PartialOrd::le(&&self[..], &&other[..])
361     }
362     #[inline]
363     fn ge(&self, other: &[T; N]) -> bool {
364         PartialOrd::ge(&&self[..], &&other[..])
365     }
366     #[inline]
367     fn gt(&self, other: &[T; N]) -> bool {
368         PartialOrd::gt(&&self[..], &&other[..])
369     }
370 }
371
372 /// Implements comparison of arrays [lexicographically](Ord#lexicographical-comparison).
373 #[stable(feature = "rust1", since = "1.0.0")]
374 impl<T: Ord, const N: usize> Ord for [T; N] {
375     #[inline]
376     fn cmp(&self, other: &[T; N]) -> Ordering {
377         Ord::cmp(&&self[..], &&other[..])
378     }
379 }
380
381 // The Default impls cannot be done with const generics because `[T; 0]` doesn't
382 // require Default to be implemented, and having different impl blocks for
383 // different numbers isn't supported yet.
384
385 macro_rules! array_impl_default {
386     {$n:expr, $t:ident $($ts:ident)*} => {
387         #[stable(since = "1.4.0", feature = "array_default")]
388         impl<T> Default for [T; $n] where T: Default {
389             fn default() -> [T; $n] {
390                 [$t::default(), $($ts::default()),*]
391             }
392         }
393         array_impl_default!{($n - 1), $($ts)*}
394     };
395     {$n:expr,} => {
396         #[stable(since = "1.4.0", feature = "array_default")]
397         impl<T> Default for [T; $n] {
398             fn default() -> [T; $n] { [] }
399         }
400     };
401 }
402
403 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}
404
405 #[lang = "array"]
406 impl<T, const N: usize> [T; N] {
407     /// Returns an array of the same size as `self`, with function `f` applied to each element
408     /// in order.
409     ///
410     /// # Examples
411     ///
412     /// ```
413     /// #![feature(array_map)]
414     /// let x = [1, 2, 3];
415     /// let y = x.map(|v| v + 1);
416     /// assert_eq!(y, [2, 3, 4]);
417     ///
418     /// let x = [1, 2, 3];
419     /// let mut temp = 0;
420     /// let y = x.map(|v| { temp += 1; v * temp });
421     /// assert_eq!(y, [1, 4, 9]);
422     ///
423     /// let x = ["Ferris", "Bueller's", "Day", "Off"];
424     /// let y = x.map(|v| v.len());
425     /// assert_eq!(y, [6, 9, 3, 3]);
426     /// ```
427     #[unstable(feature = "array_map", issue = "75243")]
428     pub fn map<F, U>(self, mut f: F) -> [U; N]
429     where
430         F: FnMut(T) -> U,
431     {
432         use crate::mem::MaybeUninit;
433         struct Guard<T, const N: usize> {
434             dst: *mut T,
435             initialized: usize,
436         }
437
438         impl<T, const N: usize> Drop for Guard<T, N> {
439             fn drop(&mut self) {
440                 debug_assert!(self.initialized <= N);
441
442                 let initialized_part =
443                     crate::ptr::slice_from_raw_parts_mut(self.dst, self.initialized);
444                 // SAFETY: this raw slice will contain only initialized objects
445                 // that's why, it is allowed to drop it.
446                 unsafe {
447                     crate::ptr::drop_in_place(initialized_part);
448                 }
449             }
450         }
451         let mut dst = MaybeUninit::uninit_array::<N>();
452         let mut guard: Guard<U, N> =
453             Guard { dst: MaybeUninit::slice_as_mut_ptr(&mut dst), initialized: 0 };
454         for (src, dst) in IntoIter::new(self).zip(&mut dst) {
455             dst.write(f(src));
456             guard.initialized += 1;
457         }
458         // FIXME: Convert to crate::mem::transmute once it works with generics.
459         // unsafe { crate::mem::transmute::<[MaybeUninit<U>; N], [U; N]>(dst) }
460         crate::mem::forget(guard);
461         // SAFETY: At this point we've properly initialized the whole array
462         // and we just need to cast it to the correct type.
463         unsafe { crate::mem::transmute_copy::<_, [U; N]>(&dst) }
464     }
465
466     /// 'Zips up' two arrays into a single array of pairs.
467     /// `zip()` returns a new array where every element is a tuple where the first element comes from the first array, and the second element comes from the second array.
468     /// In other words, it zips two arrays together, into a single one.
469     ///
470     /// # Examples
471     ///
472     /// ```
473     /// #![feature(array_zip)]
474     /// let x = [1, 2, 3];
475     /// let y = [4, 5, 6];
476     /// let z = x.zip(y);
477     /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
478     /// ```
479     #[unstable(feature = "array_zip", issue = "none")]
480     pub fn zip<U>(self, rhs: [U; N]) -> [(T, U); N] {
481         use crate::mem::MaybeUninit;
482
483         let mut dst = MaybeUninit::uninit_array::<N>();
484         for (i, (lhs, rhs)) in IntoIter::new(self).zip(IntoIter::new(rhs)).enumerate() {
485             dst[i].write((lhs, rhs));
486         }
487         // FIXME: Convert to crate::mem::transmute once it works with generics.
488         // unsafe { crate::mem::transmute::<[MaybeUninit<U>; N], [U; N]>(dst) }
489         // SAFETY: At this point we've properly initialized the whole array
490         // and we just need to cast it to the correct type.
491         unsafe { crate::mem::transmute_copy::<_, [(T, U); N]>(&dst) }
492     }
493
494     /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
495     #[unstable(feature = "array_methods", issue = "76118")]
496     pub fn as_slice(&self) -> &[T] {
497         self
498     }
499
500     /// Returns a mutable slice containing the entire array. Equivalent to
501     /// `&mut s[..]`.
502     #[unstable(feature = "array_methods", issue = "76118")]
503     pub fn as_mut_slice(&mut self) -> &mut [T] {
504         self
505     }
506 }