]> git.lizzy.rs Git - rust.git/blob - library/core/src/array/mod.rs
Rollup merge of #86037 - soerenmeier:cursor_remaining, r=yaahc
[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 /// use std::hash::{BuildHasher, Hash, Hasher};
147 ///
148 /// fn hash_of(x: impl Hash, b: &impl BuildHasher) -> u64 {
149 ///     let mut h = b.build_hasher();
150 ///     x.hash(&mut h);
151 ///     h.finish()
152 /// }
153 ///
154 /// let b = std::collections::hash_map::RandomState::new();
155 /// let a: [u8; 3] = [0xa8, 0x3c, 0x09];
156 /// let s: &[u8] = &[0xa8, 0x3c, 0x09];
157 /// assert_eq!(hash_of(a, &b), hash_of(s, &b));
158 /// ```
159 #[stable(feature = "rust1", since = "1.0.0")]
160 impl<T: Hash, const N: usize> Hash for [T; N] {
161     fn hash<H: hash::Hasher>(&self, state: &mut H) {
162         Hash::hash(&self[..], state)
163     }
164 }
165
166 #[stable(feature = "rust1", since = "1.0.0")]
167 impl<T: fmt::Debug, const N: usize> fmt::Debug for [T; N] {
168     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169         fmt::Debug::fmt(&&self[..], f)
170     }
171 }
172
173 // Note: the `#[rustc_skip_array_during_method_dispatch]` on `trait IntoIterator`
174 // hides this implementation from explicit `.into_iter()` calls on editions < 2021,
175 // so those calls will still resolve to the slice implementation, by reference.
176 #[stable(feature = "array_into_iter_impl", since = "1.53.0")]
177 impl<T, const N: usize> IntoIterator for [T; N] {
178     type Item = T;
179     type IntoIter = IntoIter<T, N>;
180
181     /// Creates a consuming iterator, that is, one that moves each value out of
182     /// the array (from start to end). The array cannot be used after calling
183     /// this unless `T` implements `Copy`, so the whole array is copied.
184     ///
185     /// Arrays have special behavior when calling `.into_iter()` prior to the
186     /// 2021 edition -- see the [array] Editions section for more information.
187     ///
188     /// [array]: prim@array
189     fn into_iter(self) -> Self::IntoIter {
190         IntoIter::new(self)
191     }
192 }
193
194 #[stable(feature = "rust1", since = "1.0.0")]
195 impl<'a, T, const N: usize> IntoIterator for &'a [T; N] {
196     type Item = &'a T;
197     type IntoIter = Iter<'a, T>;
198
199     fn into_iter(self) -> Iter<'a, T> {
200         self.iter()
201     }
202 }
203
204 #[stable(feature = "rust1", since = "1.0.0")]
205 impl<'a, T, const N: usize> IntoIterator for &'a mut [T; N] {
206     type Item = &'a mut T;
207     type IntoIter = IterMut<'a, T>;
208
209     fn into_iter(self) -> IterMut<'a, T> {
210         self.iter_mut()
211     }
212 }
213
214 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
215 impl<T, I, const N: usize> Index<I> for [T; N]
216 where
217     [T]: Index<I>,
218 {
219     type Output = <[T] as Index<I>>::Output;
220
221     #[inline]
222     fn index(&self, index: I) -> &Self::Output {
223         Index::index(self as &[T], index)
224     }
225 }
226
227 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
228 impl<T, I, const N: usize> IndexMut<I> for [T; N]
229 where
230     [T]: IndexMut<I>,
231 {
232     #[inline]
233     fn index_mut(&mut self, index: I) -> &mut Self::Output {
234         IndexMut::index_mut(self as &mut [T], index)
235     }
236 }
237
238 #[stable(feature = "rust1", since = "1.0.0")]
239 impl<A, B, const N: usize> PartialEq<[B; N]> for [A; N]
240 where
241     A: PartialEq<B>,
242 {
243     #[inline]
244     fn eq(&self, other: &[B; N]) -> bool {
245         self[..] == other[..]
246     }
247     #[inline]
248     fn ne(&self, other: &[B; N]) -> bool {
249         self[..] != other[..]
250     }
251 }
252
253 #[stable(feature = "rust1", since = "1.0.0")]
254 impl<A, B, const N: usize> PartialEq<[B]> for [A; N]
255 where
256     A: PartialEq<B>,
257 {
258     #[inline]
259     fn eq(&self, other: &[B]) -> bool {
260         self[..] == other[..]
261     }
262     #[inline]
263     fn ne(&self, other: &[B]) -> bool {
264         self[..] != other[..]
265     }
266 }
267
268 #[stable(feature = "rust1", since = "1.0.0")]
269 impl<A, B, const N: usize> PartialEq<[A; N]> for [B]
270 where
271     B: PartialEq<A>,
272 {
273     #[inline]
274     fn eq(&self, other: &[A; N]) -> bool {
275         self[..] == other[..]
276     }
277     #[inline]
278     fn ne(&self, other: &[A; N]) -> bool {
279         self[..] != other[..]
280     }
281 }
282
283 #[stable(feature = "rust1", since = "1.0.0")]
284 impl<A, B, const N: usize> PartialEq<&[B]> for [A; N]
285 where
286     A: PartialEq<B>,
287 {
288     #[inline]
289     fn eq(&self, other: &&[B]) -> bool {
290         self[..] == other[..]
291     }
292     #[inline]
293     fn ne(&self, other: &&[B]) -> bool {
294         self[..] != other[..]
295     }
296 }
297
298 #[stable(feature = "rust1", since = "1.0.0")]
299 impl<A, B, const N: usize> PartialEq<[A; N]> for &[B]
300 where
301     B: PartialEq<A>,
302 {
303     #[inline]
304     fn eq(&self, other: &[A; N]) -> bool {
305         self[..] == other[..]
306     }
307     #[inline]
308     fn ne(&self, other: &[A; N]) -> bool {
309         self[..] != other[..]
310     }
311 }
312
313 #[stable(feature = "rust1", since = "1.0.0")]
314 impl<A, B, const N: usize> PartialEq<&mut [B]> for [A; N]
315 where
316     A: PartialEq<B>,
317 {
318     #[inline]
319     fn eq(&self, other: &&mut [B]) -> bool {
320         self[..] == other[..]
321     }
322     #[inline]
323     fn ne(&self, other: &&mut [B]) -> bool {
324         self[..] != other[..]
325     }
326 }
327
328 #[stable(feature = "rust1", since = "1.0.0")]
329 impl<A, B, const N: usize> PartialEq<[A; N]> for &mut [B]
330 where
331     B: PartialEq<A>,
332 {
333     #[inline]
334     fn eq(&self, other: &[A; N]) -> bool {
335         self[..] == other[..]
336     }
337     #[inline]
338     fn ne(&self, other: &[A; N]) -> bool {
339         self[..] != other[..]
340     }
341 }
342
343 // NOTE: some less important impls are omitted to reduce code bloat
344 // __impl_slice_eq2! { [A; $N], &'b [B; $N] }
345 // __impl_slice_eq2! { [A; $N], &'b mut [B; $N] }
346
347 #[stable(feature = "rust1", since = "1.0.0")]
348 impl<T: Eq, const N: usize> Eq for [T; N] {}
349
350 #[stable(feature = "rust1", since = "1.0.0")]
351 impl<T: PartialOrd, const N: usize> PartialOrd for [T; N] {
352     #[inline]
353     fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
354         PartialOrd::partial_cmp(&&self[..], &&other[..])
355     }
356     #[inline]
357     fn lt(&self, other: &[T; N]) -> bool {
358         PartialOrd::lt(&&self[..], &&other[..])
359     }
360     #[inline]
361     fn le(&self, other: &[T; N]) -> bool {
362         PartialOrd::le(&&self[..], &&other[..])
363     }
364     #[inline]
365     fn ge(&self, other: &[T; N]) -> bool {
366         PartialOrd::ge(&&self[..], &&other[..])
367     }
368     #[inline]
369     fn gt(&self, other: &[T; N]) -> bool {
370         PartialOrd::gt(&&self[..], &&other[..])
371     }
372 }
373
374 /// Implements comparison of arrays [lexicographically](Ord#lexicographical-comparison).
375 #[stable(feature = "rust1", since = "1.0.0")]
376 impl<T: Ord, const N: usize> Ord for [T; N] {
377     #[inline]
378     fn cmp(&self, other: &[T; N]) -> Ordering {
379         Ord::cmp(&&self[..], &&other[..])
380     }
381 }
382
383 // The Default impls cannot be done with const generics because `[T; 0]` doesn't
384 // require Default to be implemented, and having different impl blocks for
385 // different numbers isn't supported yet.
386
387 macro_rules! array_impl_default {
388     {$n:expr, $t:ident $($ts:ident)*} => {
389         #[stable(since = "1.4.0", feature = "array_default")]
390         impl<T> Default for [T; $n] where T: Default {
391             fn default() -> [T; $n] {
392                 [$t::default(), $($ts::default()),*]
393             }
394         }
395         array_impl_default!{($n - 1), $($ts)*}
396     };
397     {$n:expr,} => {
398         #[stable(since = "1.4.0", feature = "array_default")]
399         impl<T> Default for [T; $n] {
400             fn default() -> [T; $n] { [] }
401         }
402     };
403 }
404
405 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}
406
407 #[lang = "array"]
408 impl<T, const N: usize> [T; N] {
409     /// Returns an array of the same size as `self`, with function `f` applied to each element
410     /// in order.
411     ///
412     /// # Examples
413     ///
414     /// ```
415     /// #![feature(array_map)]
416     /// let x = [1, 2, 3];
417     /// let y = x.map(|v| v + 1);
418     /// assert_eq!(y, [2, 3, 4]);
419     ///
420     /// let x = [1, 2, 3];
421     /// let mut temp = 0;
422     /// let y = x.map(|v| { temp += 1; v * temp });
423     /// assert_eq!(y, [1, 4, 9]);
424     ///
425     /// let x = ["Ferris", "Bueller's", "Day", "Off"];
426     /// let y = x.map(|v| v.len());
427     /// assert_eq!(y, [6, 9, 3, 3]);
428     /// ```
429     #[unstable(feature = "array_map", issue = "75243")]
430     pub fn map<F, U>(self, f: F) -> [U; N]
431     where
432         F: FnMut(T) -> U,
433     {
434         // SAFETY: we know for certain that this iterator will yield exactly `N`
435         // items.
436         unsafe { collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
437     }
438
439     /// 'Zips up' two arrays into a single array of pairs.
440     ///
441     /// `zip()` returns a new array where every element is a tuple where the
442     /// first element comes from the first array, and the second element comes
443     /// from the second array. In other words, it zips two arrays together,
444     /// into a single one.
445     ///
446     /// # Examples
447     ///
448     /// ```
449     /// #![feature(array_zip)]
450     /// let x = [1, 2, 3];
451     /// let y = [4, 5, 6];
452     /// let z = x.zip(y);
453     /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
454     /// ```
455     #[unstable(feature = "array_zip", issue = "80094")]
456     pub fn zip<U>(self, rhs: [U; N]) -> [(T, U); N] {
457         let mut iter = IntoIterator::into_iter(self).zip(rhs);
458
459         // SAFETY: we know for certain that this iterator will yield exactly `N`
460         // items.
461         unsafe { collect_into_array_unchecked(&mut iter) }
462     }
463
464     /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
465     #[unstable(feature = "array_methods", issue = "76118")]
466     pub fn as_slice(&self) -> &[T] {
467         self
468     }
469
470     /// Returns a mutable slice containing the entire array. Equivalent to
471     /// `&mut s[..]`.
472     #[unstable(feature = "array_methods", issue = "76118")]
473     pub fn as_mut_slice(&mut self) -> &mut [T] {
474         self
475     }
476
477     /// Borrows each element and returns an array of references with the same
478     /// size as `self`.
479     ///
480     ///
481     /// # Example
482     ///
483     /// ```
484     /// #![feature(array_methods)]
485     ///
486     /// let floats = [3.1, 2.7, -1.0];
487     /// let float_refs: [&f64; 3] = floats.each_ref();
488     /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
489     /// ```
490     ///
491     /// This method is particularly useful if combined with other methods, like
492     /// [`map`](#method.map). This way, you can avoid moving the original
493     /// array if its elements are not `Copy`.
494     ///
495     /// ```
496     /// #![feature(array_methods, array_map)]
497     ///
498     /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
499     /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
500     /// assert_eq!(is_ascii, [true, false, true]);
501     ///
502     /// // We can still access the original array: it has not been moved.
503     /// assert_eq!(strings.len(), 3);
504     /// ```
505     #[unstable(feature = "array_methods", issue = "76118")]
506     pub fn each_ref(&self) -> [&T; N] {
507         // SAFETY: we know for certain that this iterator will yield exactly `N`
508         // items.
509         unsafe { collect_into_array_unchecked(&mut self.iter()) }
510     }
511
512     /// Borrows each element mutably and returns an array of mutable references
513     /// with the same size as `self`.
514     ///
515     ///
516     /// # Example
517     ///
518     /// ```
519     /// #![feature(array_methods)]
520     ///
521     /// let mut floats = [3.1, 2.7, -1.0];
522     /// let float_refs: [&mut f64; 3] = floats.each_mut();
523     /// *float_refs[0] = 0.0;
524     /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
525     /// assert_eq!(floats, [0.0, 2.7, -1.0]);
526     /// ```
527     #[unstable(feature = "array_methods", issue = "76118")]
528     pub fn each_mut(&mut self) -> [&mut T; N] {
529         // SAFETY: we know for certain that this iterator will yield exactly `N`
530         // items.
531         unsafe { collect_into_array_unchecked(&mut self.iter_mut()) }
532     }
533 }
534
535 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
536 /// yields fewer than `N` items, this function exhibits undefined behavior.
537 ///
538 /// See [`collect_into_array`] for more information.
539 ///
540 ///
541 /// # Safety
542 ///
543 /// It is up to the caller to guarantee that `iter` yields at least `N` items.
544 /// Violating this condition causes undefined behavior.
545 unsafe fn collect_into_array_unchecked<I, const N: usize>(iter: &mut I) -> [I::Item; N]
546 where
547     // Note: `TrustedLen` here is somewhat of an experiment. This is just an
548     // internal function, so feel free to remove if this bound turns out to be a
549     // bad idea. In that case, remember to also remove the lower bound
550     // `debug_assert!` below!
551     I: Iterator + TrustedLen,
552 {
553     debug_assert!(N <= iter.size_hint().1.unwrap_or(usize::MAX));
554     debug_assert!(N <= iter.size_hint().0);
555
556     match collect_into_array(iter) {
557         Some(array) => array,
558         // SAFETY: covered by the function contract.
559         None => unsafe { crate::hint::unreachable_unchecked() },
560     }
561 }
562
563 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
564 /// yields fewer than `N` items, `None` is returned and all already yielded
565 /// items are dropped.
566 ///
567 /// Since the iterator is passed as a mutable reference and this function calls
568 /// `next` at most `N` times, the iterator can still be used afterwards to
569 /// retrieve the remaining items.
570 ///
571 /// If `iter.next()` panicks, all items already yielded by the iterator are
572 /// dropped.
573 fn collect_into_array<I, const N: usize>(iter: &mut I) -> Option<[I::Item; N]>
574 where
575     I: Iterator,
576 {
577     if N == 0 {
578         // SAFETY: An empty array is always inhabited and has no validity invariants.
579         return unsafe { Some(mem::zeroed()) };
580     }
581
582     struct Guard<T, const N: usize> {
583         ptr: *mut T,
584         initialized: usize,
585     }
586
587     impl<T, const N: usize> Drop for Guard<T, N> {
588         fn drop(&mut self) {
589             debug_assert!(self.initialized <= N);
590
591             let initialized_part = crate::ptr::slice_from_raw_parts_mut(self.ptr, self.initialized);
592
593             // SAFETY: this raw slice will contain only initialized objects.
594             unsafe {
595                 crate::ptr::drop_in_place(initialized_part);
596             }
597         }
598     }
599
600     let mut array = MaybeUninit::uninit_array::<N>();
601     let mut guard: Guard<_, N> =
602         Guard { ptr: MaybeUninit::slice_as_mut_ptr(&mut array), initialized: 0 };
603
604     while let Some(item) = iter.next() {
605         // SAFETY: `guard.initialized` starts at 0, is increased by one in the
606         // loop and the loop is aborted once it reaches N (which is
607         // `array.len()`).
608         unsafe {
609             array.get_unchecked_mut(guard.initialized).write(item);
610         }
611         guard.initialized += 1;
612
613         // Check if the whole array was initialized.
614         if guard.initialized == N {
615             mem::forget(guard);
616
617             // SAFETY: the condition above asserts that all elements are
618             // initialized.
619             let out = unsafe { MaybeUninit::array_assume_init(array) };
620             return Some(out);
621         }
622     }
623
624     // This is only reached if the iterator is exhausted before
625     // `guard.initialized` reaches `N`. Also note that `guard` is dropped here,
626     // dropping all already initialized elements.
627     None
628 }