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