]> git.lizzy.rs Git - rust.git/blob - library/core/src/array/mod.rs
030b42a53d05d757f0b35953ce9f268fed89e8a7
[rust.git] / library / core / src / array / mod.rs
1 //! Helper functions and types for fixed-length arrays.
2 //!
3 //! *[See also the array primitive type](array).*
4
5 #![stable(feature = "core_array", since = "1.36.0")]
6
7 use crate::borrow::{Borrow, BorrowMut};
8 use crate::cmp::Ordering;
9 use crate::convert::{Infallible, TryFrom};
10 use crate::fmt;
11 use crate::hash::{self, Hash};
12 use crate::iter::TrustedLen;
13 use crate::mem::{self, MaybeUninit};
14 use crate::ops::{Index, IndexMut};
15 use crate::slice::{Iter, IterMut};
16
17 mod iter;
18
19 #[stable(feature = "array_value_iter", since = "1.51.0")]
20 pub use iter::IntoIter;
21
22 /// Converts a reference to `T` into a reference to an array of length 1 (without copying).
23 #[stable(feature = "array_from_ref", since = "1.53.0")]
24 pub fn from_ref<T>(s: &T) -> &[T; 1] {
25     // SAFETY: Converting `&T` to `&[T; 1]` is sound.
26     unsafe { &*(s as *const T).cast::<[T; 1]>() }
27 }
28
29 /// Converts a mutable reference to `T` into a mutable reference to an array of length 1 (without copying).
30 #[stable(feature = "array_from_ref", since = "1.53.0")]
31 pub fn from_mut<T>(s: &mut T) -> &mut [T; 1] {
32     // SAFETY: Converting `&mut T` to `&mut [T; 1]` is sound.
33     unsafe { &mut *(s as *mut T).cast::<[T; 1]>() }
34 }
35
36 /// The error type returned when a conversion from a slice to an array fails.
37 #[stable(feature = "try_from", since = "1.34.0")]
38 #[derive(Debug, Copy, Clone)]
39 pub struct TryFromSliceError(());
40
41 #[stable(feature = "core_array", since = "1.36.0")]
42 impl fmt::Display for TryFromSliceError {
43     #[inline]
44     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45         fmt::Display::fmt(self.__description(), f)
46     }
47 }
48
49 impl TryFromSliceError {
50     #[unstable(
51         feature = "array_error_internals",
52         reason = "available through Error trait and this method should not \
53                      be exposed publicly",
54         issue = "none"
55     )]
56     #[inline]
57     #[doc(hidden)]
58     pub fn __description(&self) -> &str {
59         "could not convert slice to array"
60     }
61 }
62
63 #[stable(feature = "try_from_slice_error", since = "1.36.0")]
64 impl From<Infallible> for TryFromSliceError {
65     fn from(x: Infallible) -> TryFromSliceError {
66         match x {}
67     }
68 }
69
70 #[stable(feature = "rust1", since = "1.0.0")]
71 impl<T, const N: usize> AsRef<[T]> for [T; N] {
72     #[inline]
73     fn as_ref(&self) -> &[T] {
74         &self[..]
75     }
76 }
77
78 #[stable(feature = "rust1", since = "1.0.0")]
79 impl<T, const N: usize> AsMut<[T]> for [T; N] {
80     #[inline]
81     fn as_mut(&mut self) -> &mut [T] {
82         &mut self[..]
83     }
84 }
85
86 #[stable(feature = "array_borrow", since = "1.4.0")]
87 impl<T, const N: usize> Borrow<[T]> for [T; N] {
88     fn borrow(&self) -> &[T] {
89         self
90     }
91 }
92
93 #[stable(feature = "array_borrow", since = "1.4.0")]
94 impl<T, const N: usize> BorrowMut<[T]> for [T; N] {
95     fn borrow_mut(&mut self) -> &mut [T] {
96         self
97     }
98 }
99
100 #[stable(feature = "try_from", since = "1.34.0")]
101 impl<T, const N: usize> TryFrom<&[T]> for [T; N]
102 where
103     T: Copy,
104 {
105     type Error = TryFromSliceError;
106
107     fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError> {
108         <&Self>::try_from(slice).map(|r| *r)
109     }
110 }
111
112 #[stable(feature = "try_from", since = "1.34.0")]
113 impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N] {
114     type Error = TryFromSliceError;
115
116     fn try_from(slice: &[T]) -> Result<&[T; N], TryFromSliceError> {
117         if slice.len() == N {
118             let ptr = slice.as_ptr() as *const [T; N];
119             // SAFETY: ok because we just checked that the length fits
120             unsafe { Ok(&*ptr) }
121         } else {
122             Err(TryFromSliceError(()))
123         }
124     }
125 }
126
127 #[stable(feature = "try_from", since = "1.34.0")]
128 impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N] {
129     type Error = TryFromSliceError;
130
131     fn try_from(slice: &mut [T]) -> Result<&mut [T; N], TryFromSliceError> {
132         if slice.len() == N {
133             let ptr = slice.as_mut_ptr() as *mut [T; N];
134             // SAFETY: ok because we just checked that the length fits
135             unsafe { Ok(&mut *ptr) }
136         } else {
137             Err(TryFromSliceError(()))
138         }
139     }
140 }
141
142 /// The hash of an array is the same as that of the corresponding slice,
143 /// as required by the `Borrow` implementation.
144 ///
145 /// ```
146 /// #![feature(build_hasher_simple_hash_one)]
147 /// use std::hash::BuildHasher;
148 ///
149 /// let b = std::collections::hash_map::RandomState::new();
150 /// let a: [u8; 3] = [0xa8, 0x3c, 0x09];
151 /// let s: &[u8] = &[0xa8, 0x3c, 0x09];
152 /// assert_eq!(b.hash_one(a), b.hash_one(s));
153 /// ```
154 #[stable(feature = "rust1", since = "1.0.0")]
155 impl<T: Hash, const N: usize> Hash for [T; N] {
156     fn hash<H: hash::Hasher>(&self, state: &mut H) {
157         Hash::hash(&self[..], state)
158     }
159 }
160
161 #[stable(feature = "rust1", since = "1.0.0")]
162 impl<T: fmt::Debug, const N: usize> fmt::Debug for [T; N] {
163     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164         fmt::Debug::fmt(&&self[..], f)
165     }
166 }
167
168 // Note: the `#[rustc_skip_array_during_method_dispatch]` on `trait IntoIterator`
169 // hides this implementation from explicit `.into_iter()` calls on editions < 2021,
170 // so those calls will still resolve to the slice implementation, by reference.
171 #[stable(feature = "array_into_iter_impl", since = "1.53.0")]
172 impl<T, const N: usize> IntoIterator for [T; N] {
173     type Item = T;
174     type IntoIter = IntoIter<T, N>;
175
176     /// Creates a consuming iterator, that is, one that moves each value out of
177     /// the array (from start to end). The array cannot be used after calling
178     /// this unless `T` implements `Copy`, so the whole array is copied.
179     ///
180     /// Arrays have special behavior when calling `.into_iter()` prior to the
181     /// 2021 edition -- see the [array] Editions section for more information.
182     ///
183     /// [array]: prim@array
184     fn into_iter(self) -> Self::IntoIter {
185         IntoIter::new(self)
186     }
187 }
188
189 #[stable(feature = "rust1", since = "1.0.0")]
190 impl<'a, T, const N: usize> IntoIterator for &'a [T; N] {
191     type Item = &'a T;
192     type IntoIter = Iter<'a, T>;
193
194     fn into_iter(self) -> Iter<'a, T> {
195         self.iter()
196     }
197 }
198
199 #[stable(feature = "rust1", since = "1.0.0")]
200 impl<'a, T, const N: usize> IntoIterator for &'a mut [T; N] {
201     type Item = &'a mut T;
202     type IntoIter = IterMut<'a, T>;
203
204     fn into_iter(self) -> IterMut<'a, T> {
205         self.iter_mut()
206     }
207 }
208
209 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
210 impl<T, I, const N: usize> Index<I> for [T; N]
211 where
212     [T]: Index<I>,
213 {
214     type Output = <[T] as Index<I>>::Output;
215
216     #[inline]
217     fn index(&self, index: I) -> &Self::Output {
218         Index::index(self as &[T], index)
219     }
220 }
221
222 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
223 impl<T, I, const N: usize> IndexMut<I> for [T; N]
224 where
225     [T]: IndexMut<I>,
226 {
227     #[inline]
228     fn index_mut(&mut self, index: I) -> &mut Self::Output {
229         IndexMut::index_mut(self as &mut [T], index)
230     }
231 }
232
233 #[stable(feature = "rust1", since = "1.0.0")]
234 impl<A, B, const N: usize> PartialEq<[B; N]> for [A; N]
235 where
236     A: PartialEq<B>,
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 {
253     #[inline]
254     fn eq(&self, other: &[B]) -> bool {
255         self[..] == other[..]
256     }
257     #[inline]
258     fn ne(&self, other: &[B]) -> bool {
259         self[..] != other[..]
260     }
261 }
262
263 #[stable(feature = "rust1", since = "1.0.0")]
264 impl<A, B, const N: usize> PartialEq<[A; N]> for [B]
265 where
266     B: PartialEq<A>,
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<A, B, const N: usize> PartialEq<&[B]> for [A; N]
280 where
281     A: PartialEq<B>,
282 {
283     #[inline]
284     fn eq(&self, other: &&[B]) -> bool {
285         self[..] == other[..]
286     }
287     #[inline]
288     fn ne(&self, other: &&[B]) -> bool {
289         self[..] != other[..]
290     }
291 }
292
293 #[stable(feature = "rust1", since = "1.0.0")]
294 impl<A, B, const N: usize> PartialEq<[A; N]> for &[B]
295 where
296     B: PartialEq<A>,
297 {
298     #[inline]
299     fn eq(&self, other: &[A; N]) -> bool {
300         self[..] == other[..]
301     }
302     #[inline]
303     fn ne(&self, other: &[A; N]) -> bool {
304         self[..] != other[..]
305     }
306 }
307
308 #[stable(feature = "rust1", since = "1.0.0")]
309 impl<A, B, const N: usize> PartialEq<&mut [B]> for [A; N]
310 where
311     A: PartialEq<B>,
312 {
313     #[inline]
314     fn eq(&self, other: &&mut [B]) -> bool {
315         self[..] == other[..]
316     }
317     #[inline]
318     fn ne(&self, other: &&mut [B]) -> bool {
319         self[..] != other[..]
320     }
321 }
322
323 #[stable(feature = "rust1", since = "1.0.0")]
324 impl<A, B, const N: usize> PartialEq<[A; N]> for &mut [B]
325 where
326     B: PartialEq<A>,
327 {
328     #[inline]
329     fn eq(&self, other: &[A; N]) -> bool {
330         self[..] == other[..]
331     }
332     #[inline]
333     fn ne(&self, other: &[A; N]) -> bool {
334         self[..] != other[..]
335     }
336 }
337
338 // NOTE: some less important impls are omitted to reduce code bloat
339 // __impl_slice_eq2! { [A; $N], &'b [B; $N] }
340 // __impl_slice_eq2! { [A; $N], &'b mut [B; $N] }
341
342 #[stable(feature = "rust1", since = "1.0.0")]
343 impl<T: Eq, const N: usize> Eq for [T; N] {}
344
345 #[stable(feature = "rust1", since = "1.0.0")]
346 impl<T: PartialOrd, const N: usize> PartialOrd for [T; N] {
347     #[inline]
348     fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
349         PartialOrd::partial_cmp(&&self[..], &&other[..])
350     }
351     #[inline]
352     fn lt(&self, other: &[T; N]) -> bool {
353         PartialOrd::lt(&&self[..], &&other[..])
354     }
355     #[inline]
356     fn le(&self, other: &[T; N]) -> bool {
357         PartialOrd::le(&&self[..], &&other[..])
358     }
359     #[inline]
360     fn ge(&self, other: &[T; N]) -> bool {
361         PartialOrd::ge(&&self[..], &&other[..])
362     }
363     #[inline]
364     fn gt(&self, other: &[T; N]) -> bool {
365         PartialOrd::gt(&&self[..], &&other[..])
366     }
367 }
368
369 /// Implements comparison of arrays [lexicographically](Ord#lexicographical-comparison).
370 #[stable(feature = "rust1", since = "1.0.0")]
371 impl<T: Ord, const N: usize> Ord for [T; N] {
372     #[inline]
373     fn cmp(&self, other: &[T; N]) -> Ordering {
374         Ord::cmp(&&self[..], &&other[..])
375     }
376 }
377
378 // The Default impls cannot be done with const generics because `[T; 0]` doesn't
379 // require Default to be implemented, and having different impl blocks for
380 // different numbers isn't supported yet.
381
382 macro_rules! array_impl_default {
383     {$n:expr, $t:ident $($ts:ident)*} => {
384         #[stable(since = "1.4.0", feature = "array_default")]
385         impl<T> Default for [T; $n] where T: Default {
386             fn default() -> [T; $n] {
387                 [$t::default(), $($ts::default()),*]
388             }
389         }
390         array_impl_default!{($n - 1), $($ts)*}
391     };
392     {$n:expr,} => {
393         #[stable(since = "1.4.0", feature = "array_default")]
394         impl<T> Default for [T; $n] {
395             fn default() -> [T; $n] { [] }
396         }
397     };
398 }
399
400 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}
401
402 #[lang = "array"]
403 impl<T, const N: usize> [T; N] {
404     /// Returns an array of the same size as `self`, with function `f` applied to each element
405     /// in order.
406     ///
407     /// # Examples
408     ///
409     /// ```
410     /// #![feature(array_map)]
411     /// let x = [1, 2, 3];
412     /// let y = x.map(|v| v + 1);
413     /// assert_eq!(y, [2, 3, 4]);
414     ///
415     /// let x = [1, 2, 3];
416     /// let mut temp = 0;
417     /// let y = x.map(|v| { temp += 1; v * temp });
418     /// assert_eq!(y, [1, 4, 9]);
419     ///
420     /// let x = ["Ferris", "Bueller's", "Day", "Off"];
421     /// let y = x.map(|v| v.len());
422     /// assert_eq!(y, [6, 9, 3, 3]);
423     /// ```
424     #[unstable(feature = "array_map", issue = "75243")]
425     pub fn map<F, U>(self, f: F) -> [U; N]
426     where
427         F: FnMut(T) -> U,
428     {
429         // SAFETY: we know for certain that this iterator will yield exactly `N`
430         // items.
431         unsafe { collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
432     }
433
434     /// 'Zips up' two arrays into a single array of pairs.
435     ///
436     /// `zip()` returns a new array where every element is a tuple where the
437     /// first element comes from the first array, and the second element comes
438     /// from the second array. In other words, it zips two arrays together,
439     /// into a single one.
440     ///
441     /// # Examples
442     ///
443     /// ```
444     /// #![feature(array_zip)]
445     /// let x = [1, 2, 3];
446     /// let y = [4, 5, 6];
447     /// let z = x.zip(y);
448     /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
449     /// ```
450     #[unstable(feature = "array_zip", issue = "80094")]
451     pub fn zip<U>(self, rhs: [U; N]) -> [(T, U); N] {
452         let mut iter = IntoIterator::into_iter(self).zip(rhs);
453
454         // SAFETY: we know for certain that this iterator will yield exactly `N`
455         // items.
456         unsafe { collect_into_array_unchecked(&mut iter) }
457     }
458
459     /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
460     #[unstable(feature = "array_methods", issue = "76118")]
461     pub fn as_slice(&self) -> &[T] {
462         self
463     }
464
465     /// Returns a mutable slice containing the entire array. Equivalent to
466     /// `&mut s[..]`.
467     #[unstable(feature = "array_methods", issue = "76118")]
468     pub fn as_mut_slice(&mut self) -> &mut [T] {
469         self
470     }
471
472     /// Borrows each element and returns an array of references with the same
473     /// size as `self`.
474     ///
475     ///
476     /// # Example
477     ///
478     /// ```
479     /// #![feature(array_methods)]
480     ///
481     /// let floats = [3.1, 2.7, -1.0];
482     /// let float_refs: [&f64; 3] = floats.each_ref();
483     /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
484     /// ```
485     ///
486     /// This method is particularly useful if combined with other methods, like
487     /// [`map`](#method.map). This way, you can avoid moving the original
488     /// array if its elements are not `Copy`.
489     ///
490     /// ```
491     /// #![feature(array_methods, array_map)]
492     ///
493     /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
494     /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
495     /// assert_eq!(is_ascii, [true, false, true]);
496     ///
497     /// // We can still access the original array: it has not been moved.
498     /// assert_eq!(strings.len(), 3);
499     /// ```
500     #[unstable(feature = "array_methods", issue = "76118")]
501     pub fn each_ref(&self) -> [&T; N] {
502         // SAFETY: we know for certain that this iterator will yield exactly `N`
503         // items.
504         unsafe { collect_into_array_unchecked(&mut self.iter()) }
505     }
506
507     /// Borrows each element mutably and returns an array of mutable references
508     /// with the same size as `self`.
509     ///
510     ///
511     /// # Example
512     ///
513     /// ```
514     /// #![feature(array_methods)]
515     ///
516     /// let mut floats = [3.1, 2.7, -1.0];
517     /// let float_refs: [&mut f64; 3] = floats.each_mut();
518     /// *float_refs[0] = 0.0;
519     /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
520     /// assert_eq!(floats, [0.0, 2.7, -1.0]);
521     /// ```
522     #[unstable(feature = "array_methods", issue = "76118")]
523     pub fn each_mut(&mut self) -> [&mut T; N] {
524         // SAFETY: we know for certain that this iterator will yield exactly `N`
525         // items.
526         unsafe { collect_into_array_unchecked(&mut self.iter_mut()) }
527     }
528 }
529
530 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
531 /// yields fewer than `N` items, this function exhibits undefined behavior.
532 ///
533 /// See [`collect_into_array`] for more information.
534 ///
535 ///
536 /// # Safety
537 ///
538 /// It is up to the caller to guarantee that `iter` yields at least `N` items.
539 /// Violating this condition causes undefined behavior.
540 unsafe fn collect_into_array_unchecked<I, const N: usize>(iter: &mut I) -> [I::Item; N]
541 where
542     // Note: `TrustedLen` here is somewhat of an experiment. This is just an
543     // internal function, so feel free to remove if this bound turns out to be a
544     // bad idea. In that case, remember to also remove the lower bound
545     // `debug_assert!` below!
546     I: Iterator + TrustedLen,
547 {
548     debug_assert!(N <= iter.size_hint().1.unwrap_or(usize::MAX));
549     debug_assert!(N <= iter.size_hint().0);
550
551     match collect_into_array(iter) {
552         Some(array) => array,
553         // SAFETY: covered by the function contract.
554         None => unsafe { crate::hint::unreachable_unchecked() },
555     }
556 }
557
558 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
559 /// yields fewer than `N` items, `None` is returned and all already yielded
560 /// items are dropped.
561 ///
562 /// Since the iterator is passed as a mutable reference and this function calls
563 /// `next` at most `N` times, the iterator can still be used afterwards to
564 /// retrieve the remaining items.
565 ///
566 /// If `iter.next()` panicks, all items already yielded by the iterator are
567 /// dropped.
568 fn collect_into_array<I, const N: usize>(iter: &mut I) -> Option<[I::Item; N]>
569 where
570     I: Iterator,
571 {
572     if N == 0 {
573         // SAFETY: An empty array is always inhabited and has no validity invariants.
574         return unsafe { Some(mem::zeroed()) };
575     }
576
577     struct Guard<T, const N: usize> {
578         ptr: *mut T,
579         initialized: usize,
580     }
581
582     impl<T, const N: usize> Drop for Guard<T, N> {
583         fn drop(&mut self) {
584             debug_assert!(self.initialized <= N);
585
586             let initialized_part = crate::ptr::slice_from_raw_parts_mut(self.ptr, self.initialized);
587
588             // SAFETY: this raw slice will contain only initialized objects.
589             unsafe {
590                 crate::ptr::drop_in_place(initialized_part);
591             }
592         }
593     }
594
595     let mut array = MaybeUninit::uninit_array::<N>();
596     let mut guard: Guard<_, N> =
597         Guard { ptr: MaybeUninit::slice_as_mut_ptr(&mut array), initialized: 0 };
598
599     while let Some(item) = iter.next() {
600         // SAFETY: `guard.initialized` starts at 0, is increased by one in the
601         // loop and the loop is aborted once it reaches N (which is
602         // `array.len()`).
603         unsafe {
604             array.get_unchecked_mut(guard.initialized).write(item);
605         }
606         guard.initialized += 1;
607
608         // Check if the whole array was initialized.
609         if guard.initialized == N {
610             mem::forget(guard);
611
612             // SAFETY: the condition above asserts that all elements are
613             // initialized.
614             let out = unsafe { MaybeUninit::array_assume_init(array) };
615             return Some(out);
616         }
617     }
618
619     // This is only reached if the iterator is exhausted before
620     // `guard.initialized` reaches `N`. Also note that `guard` is dropped here,
621     // dropping all already initialized elements.
622     None
623 }