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