]> git.lizzy.rs Git - rust.git/blob - library/core/src/array/mod.rs
Auto merge of #98457 - japaric:gh98378, r=m-ou-se
[rust.git] / library / core / src / array / mod.rs
1 //! Utilities for the array primitive type.
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 #[cfg(not(bootstrap))]
11 use crate::error::Error;
12 use crate::fmt;
13 use crate::hash::{self, Hash};
14 use crate::iter::TrustedLen;
15 use crate::mem::{self, MaybeUninit};
16 use crate::ops::{
17     ChangeOutputType, ControlFlow, FromResidual, Index, IndexMut, NeverShortCircuit, Residual, Try,
18 };
19 use crate::slice::{Iter, IterMut};
20
21 mod equality;
22 mod iter;
23
24 #[stable(feature = "array_value_iter", since = "1.51.0")]
25 pub use iter::IntoIter;
26
27 /// Creates an array `[T; N]` where each array element `T` is returned by the `cb` call.
28 ///
29 /// # Arguments
30 ///
31 /// * `cb`: Callback where the passed argument is the current array index.
32 ///
33 /// # Example
34 ///
35 /// ```rust
36 /// let array = core::array::from_fn(|i| i);
37 /// assert_eq!(array, [0, 1, 2, 3, 4]);
38 /// ```
39 #[inline]
40 #[stable(feature = "array_from_fn", since = "1.63.0")]
41 pub fn from_fn<T, const N: usize, F>(mut cb: F) -> [T; N]
42 where
43     F: FnMut(usize) -> T,
44 {
45     let mut idx = 0;
46     [(); N].map(|_| {
47         let res = cb(idx);
48         idx += 1;
49         res
50     })
51 }
52
53 /// Creates an array `[T; N]` where each fallible array element `T` is returned by the `cb` call.
54 /// Unlike [`from_fn`], where the element creation can't fail, this version will return an error
55 /// if any element creation was unsuccessful.
56 ///
57 /// The return type of this function depends on the return type of the closure.
58 /// If you return `Result<T, E>` from the closure, you'll get a `Result<[T; N]; E>`.
59 /// If you return `Option<T>` from the closure, you'll get an `Option<[T; N]>`.
60 ///
61 /// # Arguments
62 ///
63 /// * `cb`: Callback where the passed argument is the current array index.
64 ///
65 /// # Example
66 ///
67 /// ```rust
68 /// #![feature(array_try_from_fn)]
69 ///
70 /// let array: Result<[u8; 5], _> = std::array::try_from_fn(|i| i.try_into());
71 /// assert_eq!(array, Ok([0, 1, 2, 3, 4]));
72 ///
73 /// let array: Result<[i8; 200], _> = std::array::try_from_fn(|i| i.try_into());
74 /// assert!(array.is_err());
75 ///
76 /// let array: Option<[_; 4]> = std::array::try_from_fn(|i| i.checked_add(100));
77 /// assert_eq!(array, Some([100, 101, 102, 103]));
78 ///
79 /// let array: Option<[_; 4]> = std::array::try_from_fn(|i| i.checked_sub(100));
80 /// assert_eq!(array, None);
81 /// ```
82 #[inline]
83 #[unstable(feature = "array_try_from_fn", issue = "89379")]
84 pub fn try_from_fn<R, const N: usize, F>(cb: F) -> ChangeOutputType<R, [R::Output; N]>
85 where
86     F: FnMut(usize) -> R,
87     R: Try,
88     R::Residual: Residual<[R::Output; N]>,
89 {
90     // SAFETY: we know for certain that this iterator will yield exactly `N`
91     // items.
92     unsafe { try_collect_into_array_unchecked(&mut (0..N).map(cb)) }
93 }
94
95 /// Converts a reference to `T` into a reference to an array of length 1 (without copying).
96 #[stable(feature = "array_from_ref", since = "1.53.0")]
97 #[rustc_const_stable(feature = "const_array_from_ref_shared", since = "1.63.0")]
98 pub const fn from_ref<T>(s: &T) -> &[T; 1] {
99     // SAFETY: Converting `&T` to `&[T; 1]` is sound.
100     unsafe { &*(s as *const T).cast::<[T; 1]>() }
101 }
102
103 /// Converts a mutable reference to `T` into a mutable reference to an array of length 1 (without copying).
104 #[stable(feature = "array_from_ref", since = "1.53.0")]
105 #[rustc_const_unstable(feature = "const_array_from_ref", issue = "90206")]
106 pub const fn from_mut<T>(s: &mut T) -> &mut [T; 1] {
107     // SAFETY: Converting `&mut T` to `&mut [T; 1]` is sound.
108     unsafe { &mut *(s as *mut T).cast::<[T; 1]>() }
109 }
110
111 /// The error type returned when a conversion from a slice to an array fails.
112 #[stable(feature = "try_from", since = "1.34.0")]
113 #[derive(Debug, Copy, Clone)]
114 pub struct TryFromSliceError(());
115
116 #[stable(feature = "core_array", since = "1.36.0")]
117 impl fmt::Display for TryFromSliceError {
118     #[inline]
119     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120         fmt::Display::fmt(self.__description(), f)
121     }
122 }
123
124 #[cfg(not(bootstrap))]
125 #[stable(feature = "try_from", since = "1.34.0")]
126 impl Error for TryFromSliceError {
127     #[allow(deprecated)]
128     fn description(&self) -> &str {
129         self.__description()
130     }
131 }
132
133 impl TryFromSliceError {
134     #[unstable(
135         feature = "array_error_internals",
136         reason = "available through Error trait and this method should not \
137                      be exposed publicly",
138         issue = "none"
139     )]
140     #[inline]
141     #[doc(hidden)]
142     pub fn __description(&self) -> &str {
143         "could not convert slice to array"
144     }
145 }
146
147 #[stable(feature = "try_from_slice_error", since = "1.36.0")]
148 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
149 impl const From<Infallible> for TryFromSliceError {
150     fn from(x: Infallible) -> TryFromSliceError {
151         match x {}
152     }
153 }
154
155 #[stable(feature = "rust1", since = "1.0.0")]
156 impl<T, const N: usize> AsRef<[T]> for [T; N] {
157     #[inline]
158     fn as_ref(&self) -> &[T] {
159         &self[..]
160     }
161 }
162
163 #[stable(feature = "rust1", since = "1.0.0")]
164 impl<T, const N: usize> AsMut<[T]> for [T; N] {
165     #[inline]
166     fn as_mut(&mut self) -> &mut [T] {
167         &mut self[..]
168     }
169 }
170
171 #[stable(feature = "array_borrow", since = "1.4.0")]
172 #[rustc_const_unstable(feature = "const_borrow", issue = "91522")]
173 impl<T, const N: usize> const Borrow<[T]> for [T; N] {
174     fn borrow(&self) -> &[T] {
175         self
176     }
177 }
178
179 #[stable(feature = "array_borrow", since = "1.4.0")]
180 #[rustc_const_unstable(feature = "const_borrow", issue = "91522")]
181 impl<T, const N: usize> const BorrowMut<[T]> for [T; N] {
182     fn borrow_mut(&mut self) -> &mut [T] {
183         self
184     }
185 }
186
187 /// Tries to create an array `[T; N]` by copying from a slice `&[T]`. Succeeds if
188 /// `slice.len() == N`.
189 ///
190 /// ```
191 /// let bytes: [u8; 3] = [1, 0, 2];
192 ///
193 /// let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&bytes[0..2]).unwrap();
194 /// assert_eq!(1, u16::from_le_bytes(bytes_head));
195 ///
196 /// let bytes_tail: [u8; 2] = bytes[1..3].try_into().unwrap();
197 /// assert_eq!(512, u16::from_le_bytes(bytes_tail));
198 /// ```
199 #[stable(feature = "try_from", since = "1.34.0")]
200 impl<T, const N: usize> TryFrom<&[T]> for [T; N]
201 where
202     T: Copy,
203 {
204     type Error = TryFromSliceError;
205
206     fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError> {
207         <&Self>::try_from(slice).map(|r| *r)
208     }
209 }
210
211 /// Tries to create an array `[T; N]` by copying from a mutable slice `&mut [T]`.
212 /// Succeeds if `slice.len() == N`.
213 ///
214 /// ```
215 /// let mut bytes: [u8; 3] = [1, 0, 2];
216 ///
217 /// let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
218 /// assert_eq!(1, u16::from_le_bytes(bytes_head));
219 ///
220 /// let bytes_tail: [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
221 /// assert_eq!(512, u16::from_le_bytes(bytes_tail));
222 /// ```
223 #[stable(feature = "try_from_mut_slice_to_array", since = "1.59.0")]
224 impl<T, const N: usize> TryFrom<&mut [T]> for [T; N]
225 where
226     T: Copy,
227 {
228     type Error = TryFromSliceError;
229
230     fn try_from(slice: &mut [T]) -> Result<[T; N], TryFromSliceError> {
231         <Self>::try_from(&*slice)
232     }
233 }
234
235 /// Tries to create an array ref `&[T; N]` from a slice ref `&[T]`. Succeeds if
236 /// `slice.len() == N`.
237 ///
238 /// ```
239 /// let bytes: [u8; 3] = [1, 0, 2];
240 ///
241 /// let bytes_head: &[u8; 2] = <&[u8; 2]>::try_from(&bytes[0..2]).unwrap();
242 /// assert_eq!(1, u16::from_le_bytes(*bytes_head));
243 ///
244 /// let bytes_tail: &[u8; 2] = bytes[1..3].try_into().unwrap();
245 /// assert_eq!(512, u16::from_le_bytes(*bytes_tail));
246 /// ```
247 #[stable(feature = "try_from", since = "1.34.0")]
248 impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N] {
249     type Error = TryFromSliceError;
250
251     fn try_from(slice: &[T]) -> Result<&[T; N], TryFromSliceError> {
252         if slice.len() == N {
253             let ptr = slice.as_ptr() as *const [T; N];
254             // SAFETY: ok because we just checked that the length fits
255             unsafe { Ok(&*ptr) }
256         } else {
257             Err(TryFromSliceError(()))
258         }
259     }
260 }
261
262 /// Tries to create a mutable array ref `&mut [T; N]` from a mutable slice ref
263 /// `&mut [T]`. Succeeds if `slice.len() == N`.
264 ///
265 /// ```
266 /// let mut bytes: [u8; 3] = [1, 0, 2];
267 ///
268 /// let bytes_head: &mut [u8; 2] = <&mut [u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
269 /// assert_eq!(1, u16::from_le_bytes(*bytes_head));
270 ///
271 /// let bytes_tail: &mut [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
272 /// assert_eq!(512, u16::from_le_bytes(*bytes_tail));
273 /// ```
274 #[stable(feature = "try_from", since = "1.34.0")]
275 impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N] {
276     type Error = TryFromSliceError;
277
278     fn try_from(slice: &mut [T]) -> Result<&mut [T; N], TryFromSliceError> {
279         if slice.len() == N {
280             let ptr = slice.as_mut_ptr() as *mut [T; N];
281             // SAFETY: ok because we just checked that the length fits
282             unsafe { Ok(&mut *ptr) }
283         } else {
284             Err(TryFromSliceError(()))
285         }
286     }
287 }
288
289 /// The hash of an array is the same as that of the corresponding slice,
290 /// as required by the `Borrow` implementation.
291 ///
292 /// ```
293 /// #![feature(build_hasher_simple_hash_one)]
294 /// use std::hash::BuildHasher;
295 ///
296 /// let b = std::collections::hash_map::RandomState::new();
297 /// let a: [u8; 3] = [0xa8, 0x3c, 0x09];
298 /// let s: &[u8] = &[0xa8, 0x3c, 0x09];
299 /// assert_eq!(b.hash_one(a), b.hash_one(s));
300 /// ```
301 #[stable(feature = "rust1", since = "1.0.0")]
302 impl<T: Hash, const N: usize> Hash for [T; N] {
303     fn hash<H: hash::Hasher>(&self, state: &mut H) {
304         Hash::hash(&self[..], state)
305     }
306 }
307
308 #[stable(feature = "rust1", since = "1.0.0")]
309 impl<T: fmt::Debug, const N: usize> fmt::Debug for [T; N] {
310     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311         fmt::Debug::fmt(&&self[..], f)
312     }
313 }
314
315 #[stable(feature = "rust1", since = "1.0.0")]
316 impl<'a, T, const N: usize> IntoIterator for &'a [T; N] {
317     type Item = &'a T;
318     type IntoIter = Iter<'a, T>;
319
320     fn into_iter(self) -> Iter<'a, T> {
321         self.iter()
322     }
323 }
324
325 #[stable(feature = "rust1", since = "1.0.0")]
326 impl<'a, T, const N: usize> IntoIterator for &'a mut [T; N] {
327     type Item = &'a mut T;
328     type IntoIter = IterMut<'a, T>;
329
330     fn into_iter(self) -> IterMut<'a, T> {
331         self.iter_mut()
332     }
333 }
334
335 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
336 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
337 impl<T, I, const N: usize> const Index<I> for [T; N]
338 where
339     [T]: ~const Index<I>,
340 {
341     type Output = <[T] as Index<I>>::Output;
342
343     #[inline]
344     fn index(&self, index: I) -> &Self::Output {
345         Index::index(self as &[T], index)
346     }
347 }
348
349 #[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
350 #[rustc_const_unstable(feature = "const_slice_index", issue = "none")]
351 impl<T, I, const N: usize> const IndexMut<I> for [T; N]
352 where
353     [T]: ~const IndexMut<I>,
354 {
355     #[inline]
356     fn index_mut(&mut self, index: I) -> &mut Self::Output {
357         IndexMut::index_mut(self as &mut [T], index)
358     }
359 }
360
361 #[stable(feature = "rust1", since = "1.0.0")]
362 impl<T: PartialOrd, const N: usize> PartialOrd for [T; N] {
363     #[inline]
364     fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
365         PartialOrd::partial_cmp(&&self[..], &&other[..])
366     }
367     #[inline]
368     fn lt(&self, other: &[T; N]) -> bool {
369         PartialOrd::lt(&&self[..], &&other[..])
370     }
371     #[inline]
372     fn le(&self, other: &[T; N]) -> bool {
373         PartialOrd::le(&&self[..], &&other[..])
374     }
375     #[inline]
376     fn ge(&self, other: &[T; N]) -> bool {
377         PartialOrd::ge(&&self[..], &&other[..])
378     }
379     #[inline]
380     fn gt(&self, other: &[T; N]) -> bool {
381         PartialOrd::gt(&&self[..], &&other[..])
382     }
383 }
384
385 /// Implements comparison of arrays [lexicographically](Ord#lexicographical-comparison).
386 #[stable(feature = "rust1", since = "1.0.0")]
387 impl<T: Ord, const N: usize> Ord for [T; N] {
388     #[inline]
389     fn cmp(&self, other: &[T; N]) -> Ordering {
390         Ord::cmp(&&self[..], &&other[..])
391     }
392 }
393
394 #[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
395 impl<T: Copy, const N: usize> Copy for [T; N] {}
396
397 #[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
398 impl<T: Clone, const N: usize> Clone for [T; N] {
399     #[inline]
400     fn clone(&self) -> Self {
401         SpecArrayClone::clone(self)
402     }
403
404     #[inline]
405     fn clone_from(&mut self, other: &Self) {
406         self.clone_from_slice(other);
407     }
408 }
409
410 trait SpecArrayClone: Clone {
411     fn clone<const N: usize>(array: &[Self; N]) -> [Self; N];
412 }
413
414 impl<T: Clone> SpecArrayClone for T {
415     #[inline]
416     default fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
417         // SAFETY: we know for certain that this iterator will yield exactly `N`
418         // items.
419         unsafe { collect_into_array_unchecked(&mut array.iter().cloned()) }
420     }
421 }
422
423 impl<T: Copy> SpecArrayClone for T {
424     #[inline]
425     fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
426         *array
427     }
428 }
429
430 // The Default impls cannot be done with const generics because `[T; 0]` doesn't
431 // require Default to be implemented, and having different impl blocks for
432 // different numbers isn't supported yet.
433
434 macro_rules! array_impl_default {
435     {$n:expr, $t:ident $($ts:ident)*} => {
436         #[stable(since = "1.4.0", feature = "array_default")]
437         impl<T> Default for [T; $n] where T: Default {
438             fn default() -> [T; $n] {
439                 [$t::default(), $($ts::default()),*]
440             }
441         }
442         array_impl_default!{($n - 1), $($ts)*}
443     };
444     {$n:expr,} => {
445         #[stable(since = "1.4.0", feature = "array_default")]
446         #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
447         impl<T> const Default for [T; $n] {
448             fn default() -> [T; $n] { [] }
449         }
450     };
451 }
452
453 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}
454
455 impl<T, const N: usize> [T; N] {
456     /// Returns an array of the same size as `self`, with function `f` applied to each element
457     /// in order.
458     ///
459     /// If you don't necessarily need a new fixed-size array, consider using
460     /// [`Iterator::map`] instead.
461     ///
462     ///
463     /// # Note on performance and stack usage
464     ///
465     /// Unfortunately, usages of this method are currently not always optimized
466     /// as well as they could be. This mainly concerns large arrays, as mapping
467     /// over small arrays seem to be optimized just fine. Also note that in
468     /// debug mode (i.e. without any optimizations), this method can use a lot
469     /// of stack space (a few times the size of the array or more).
470     ///
471     /// Therefore, in performance-critical code, try to avoid using this method
472     /// on large arrays or check the emitted code. Also try to avoid chained
473     /// maps (e.g. `arr.map(...).map(...)`).
474     ///
475     /// In many cases, you can instead use [`Iterator::map`] by calling `.iter()`
476     /// or `.into_iter()` on your array. `[T; N]::map` is only necessary if you
477     /// really need a new array of the same size as the result. Rust's lazy
478     /// iterators tend to get optimized very well.
479     ///
480     ///
481     /// # Examples
482     ///
483     /// ```
484     /// let x = [1, 2, 3];
485     /// let y = x.map(|v| v + 1);
486     /// assert_eq!(y, [2, 3, 4]);
487     ///
488     /// let x = [1, 2, 3];
489     /// let mut temp = 0;
490     /// let y = x.map(|v| { temp += 1; v * temp });
491     /// assert_eq!(y, [1, 4, 9]);
492     ///
493     /// let x = ["Ferris", "Bueller's", "Day", "Off"];
494     /// let y = x.map(|v| v.len());
495     /// assert_eq!(y, [6, 9, 3, 3]);
496     /// ```
497     #[stable(feature = "array_map", since = "1.55.0")]
498     pub fn map<F, U>(self, f: F) -> [U; N]
499     where
500         F: FnMut(T) -> U,
501     {
502         // SAFETY: we know for certain that this iterator will yield exactly `N`
503         // items.
504         unsafe { collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
505     }
506
507     /// A fallible function `f` applied to each element on array `self` in order to
508     /// return an array the same size as `self` or the first error encountered.
509     ///
510     /// The return type of this function depends on the return type of the closure.
511     /// If you return `Result<T, E>` from the closure, you'll get a `Result<[T; N]; E>`.
512     /// If you return `Option<T>` from the closure, you'll get an `Option<[T; N]>`.
513     ///
514     /// # Examples
515     ///
516     /// ```
517     /// #![feature(array_try_map)]
518     /// let a = ["1", "2", "3"];
519     /// let b = a.try_map(|v| v.parse::<u32>()).unwrap().map(|v| v + 1);
520     /// assert_eq!(b, [2, 3, 4]);
521     ///
522     /// let a = ["1", "2a", "3"];
523     /// let b = a.try_map(|v| v.parse::<u32>());
524     /// assert!(b.is_err());
525     ///
526     /// use std::num::NonZeroU32;
527     /// let z = [1, 2, 0, 3, 4];
528     /// assert_eq!(z.try_map(NonZeroU32::new), None);
529     /// let a = [1, 2, 3];
530     /// let b = a.try_map(NonZeroU32::new);
531     /// let c = b.map(|x| x.map(NonZeroU32::get));
532     /// assert_eq!(c, Some(a));
533     /// ```
534     #[unstable(feature = "array_try_map", issue = "79711")]
535     pub fn try_map<F, R>(self, f: F) -> ChangeOutputType<R, [R::Output; N]>
536     where
537         F: FnMut(T) -> R,
538         R: Try,
539         R::Residual: Residual<[R::Output; N]>,
540     {
541         // SAFETY: we know for certain that this iterator will yield exactly `N`
542         // items.
543         unsafe { try_collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
544     }
545
546     /// 'Zips up' two arrays into a single array of pairs.
547     ///
548     /// `zip()` returns a new array where every element is a tuple where the
549     /// first element comes from the first array, and the second element comes
550     /// from the second array. In other words, it zips two arrays together,
551     /// into a single one.
552     ///
553     /// # Examples
554     ///
555     /// ```
556     /// #![feature(array_zip)]
557     /// let x = [1, 2, 3];
558     /// let y = [4, 5, 6];
559     /// let z = x.zip(y);
560     /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
561     /// ```
562     #[unstable(feature = "array_zip", issue = "80094")]
563     pub fn zip<U>(self, rhs: [U; N]) -> [(T, U); N] {
564         let mut iter = IntoIterator::into_iter(self).zip(rhs);
565
566         // SAFETY: we know for certain that this iterator will yield exactly `N`
567         // items.
568         unsafe { collect_into_array_unchecked(&mut iter) }
569     }
570
571     /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
572     #[stable(feature = "array_as_slice", since = "1.57.0")]
573     #[rustc_const_stable(feature = "array_as_slice", since = "1.57.0")]
574     pub const fn as_slice(&self) -> &[T] {
575         self
576     }
577
578     /// Returns a mutable slice containing the entire array. Equivalent to
579     /// `&mut s[..]`.
580     #[stable(feature = "array_as_slice", since = "1.57.0")]
581     pub fn as_mut_slice(&mut self) -> &mut [T] {
582         self
583     }
584
585     /// Borrows each element and returns an array of references with the same
586     /// size as `self`.
587     ///
588     ///
589     /// # Example
590     ///
591     /// ```
592     /// #![feature(array_methods)]
593     ///
594     /// let floats = [3.1, 2.7, -1.0];
595     /// let float_refs: [&f64; 3] = floats.each_ref();
596     /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
597     /// ```
598     ///
599     /// This method is particularly useful if combined with other methods, like
600     /// [`map`](#method.map). This way, you can avoid moving the original
601     /// array if its elements are not [`Copy`].
602     ///
603     /// ```
604     /// #![feature(array_methods)]
605     ///
606     /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
607     /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
608     /// assert_eq!(is_ascii, [true, false, true]);
609     ///
610     /// // We can still access the original array: it has not been moved.
611     /// assert_eq!(strings.len(), 3);
612     /// ```
613     #[unstable(feature = "array_methods", issue = "76118")]
614     pub fn each_ref(&self) -> [&T; N] {
615         // SAFETY: we know for certain that this iterator will yield exactly `N`
616         // items.
617         unsafe { collect_into_array_unchecked(&mut self.iter()) }
618     }
619
620     /// Borrows each element mutably and returns an array of mutable references
621     /// with the same size as `self`.
622     ///
623     ///
624     /// # Example
625     ///
626     /// ```
627     /// #![feature(array_methods)]
628     ///
629     /// let mut floats = [3.1, 2.7, -1.0];
630     /// let float_refs: [&mut f64; 3] = floats.each_mut();
631     /// *float_refs[0] = 0.0;
632     /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
633     /// assert_eq!(floats, [0.0, 2.7, -1.0]);
634     /// ```
635     #[unstable(feature = "array_methods", issue = "76118")]
636     pub fn each_mut(&mut self) -> [&mut T; N] {
637         // SAFETY: we know for certain that this iterator will yield exactly `N`
638         // items.
639         unsafe { collect_into_array_unchecked(&mut self.iter_mut()) }
640     }
641
642     /// Divides one array reference into two at an index.
643     ///
644     /// The first will contain all indices from `[0, M)` (excluding
645     /// the index `M` itself) and the second will contain all
646     /// indices from `[M, N)` (excluding the index `N` itself).
647     ///
648     /// # Panics
649     ///
650     /// Panics if `M > N`.
651     ///
652     /// # Examples
653     ///
654     /// ```
655     /// #![feature(split_array)]
656     ///
657     /// let v = [1, 2, 3, 4, 5, 6];
658     ///
659     /// {
660     ///    let (left, right) = v.split_array_ref::<0>();
661     ///    assert_eq!(left, &[]);
662     ///    assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
663     /// }
664     ///
665     /// {
666     ///     let (left, right) = v.split_array_ref::<2>();
667     ///     assert_eq!(left, &[1, 2]);
668     ///     assert_eq!(right, &[3, 4, 5, 6]);
669     /// }
670     ///
671     /// {
672     ///     let (left, right) = v.split_array_ref::<6>();
673     ///     assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
674     ///     assert_eq!(right, &[]);
675     /// }
676     /// ```
677     #[unstable(
678         feature = "split_array",
679         reason = "return type should have array as 2nd element",
680         issue = "90091"
681     )]
682     #[inline]
683     pub fn split_array_ref<const M: usize>(&self) -> (&[T; M], &[T]) {
684         (&self[..]).split_array_ref::<M>()
685     }
686
687     /// Divides one mutable array reference into two at an index.
688     ///
689     /// The first will contain all indices from `[0, M)` (excluding
690     /// the index `M` itself) and the second will contain all
691     /// indices from `[M, N)` (excluding the index `N` itself).
692     ///
693     /// # Panics
694     ///
695     /// Panics if `M > N`.
696     ///
697     /// # Examples
698     ///
699     /// ```
700     /// #![feature(split_array)]
701     ///
702     /// let mut v = [1, 0, 3, 0, 5, 6];
703     /// let (left, right) = v.split_array_mut::<2>();
704     /// assert_eq!(left, &mut [1, 0][..]);
705     /// assert_eq!(right, &mut [3, 0, 5, 6]);
706     /// left[1] = 2;
707     /// right[1] = 4;
708     /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
709     /// ```
710     #[unstable(
711         feature = "split_array",
712         reason = "return type should have array as 2nd element",
713         issue = "90091"
714     )]
715     #[inline]
716     pub fn split_array_mut<const M: usize>(&mut self) -> (&mut [T; M], &mut [T]) {
717         (&mut self[..]).split_array_mut::<M>()
718     }
719
720     /// Divides one array reference into two at an index from the end.
721     ///
722     /// The first will contain all indices from `[0, N - M)` (excluding
723     /// the index `N - M` itself) and the second will contain all
724     /// indices from `[N - M, N)` (excluding the index `N` itself).
725     ///
726     /// # Panics
727     ///
728     /// Panics if `M > N`.
729     ///
730     /// # Examples
731     ///
732     /// ```
733     /// #![feature(split_array)]
734     ///
735     /// let v = [1, 2, 3, 4, 5, 6];
736     ///
737     /// {
738     ///    let (left, right) = v.rsplit_array_ref::<0>();
739     ///    assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
740     ///    assert_eq!(right, &[]);
741     /// }
742     ///
743     /// {
744     ///     let (left, right) = v.rsplit_array_ref::<2>();
745     ///     assert_eq!(left, &[1, 2, 3, 4]);
746     ///     assert_eq!(right, &[5, 6]);
747     /// }
748     ///
749     /// {
750     ///     let (left, right) = v.rsplit_array_ref::<6>();
751     ///     assert_eq!(left, &[]);
752     ///     assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
753     /// }
754     /// ```
755     #[unstable(
756         feature = "split_array",
757         reason = "return type should have array as 2nd element",
758         issue = "90091"
759     )]
760     #[inline]
761     pub fn rsplit_array_ref<const M: usize>(&self) -> (&[T], &[T; M]) {
762         (&self[..]).rsplit_array_ref::<M>()
763     }
764
765     /// Divides one mutable array reference into two at an index from the end.
766     ///
767     /// The first will contain all indices from `[0, N - M)` (excluding
768     /// the index `N - M` itself) and the second will contain all
769     /// indices from `[N - M, N)` (excluding the index `N` itself).
770     ///
771     /// # Panics
772     ///
773     /// Panics if `M > N`.
774     ///
775     /// # Examples
776     ///
777     /// ```
778     /// #![feature(split_array)]
779     ///
780     /// let mut v = [1, 0, 3, 0, 5, 6];
781     /// let (left, right) = v.rsplit_array_mut::<4>();
782     /// assert_eq!(left, &mut [1, 0]);
783     /// assert_eq!(right, &mut [3, 0, 5, 6][..]);
784     /// left[1] = 2;
785     /// right[1] = 4;
786     /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
787     /// ```
788     #[unstable(
789         feature = "split_array",
790         reason = "return type should have array as 2nd element",
791         issue = "90091"
792     )]
793     #[inline]
794     pub fn rsplit_array_mut<const M: usize>(&mut self) -> (&mut [T], &mut [T; M]) {
795         (&mut self[..]).rsplit_array_mut::<M>()
796     }
797 }
798
799 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
800 /// yields fewer than `N` items, this function exhibits undefined behavior.
801 ///
802 /// See [`try_collect_into_array`] for more information.
803 ///
804 ///
805 /// # Safety
806 ///
807 /// It is up to the caller to guarantee that `iter` yields at least `N` items.
808 /// Violating this condition causes undefined behavior.
809 unsafe fn try_collect_into_array_unchecked<I, T, R, const N: usize>(iter: &mut I) -> R::TryType
810 where
811     // Note: `TrustedLen` here is somewhat of an experiment. This is just an
812     // internal function, so feel free to remove if this bound turns out to be a
813     // bad idea. In that case, remember to also remove the lower bound
814     // `debug_assert!` below!
815     I: Iterator + TrustedLen,
816     I::Item: Try<Output = T, Residual = R>,
817     R: Residual<[T; N]>,
818 {
819     debug_assert!(N <= iter.size_hint().1.unwrap_or(usize::MAX));
820     debug_assert!(N <= iter.size_hint().0);
821
822     // SAFETY: covered by the function contract.
823     unsafe { try_collect_into_array(iter).unwrap_unchecked() }
824 }
825
826 // Infallible version of `try_collect_into_array_unchecked`.
827 unsafe fn collect_into_array_unchecked<I, const N: usize>(iter: &mut I) -> [I::Item; N]
828 where
829     I: Iterator + TrustedLen,
830 {
831     let mut map = iter.map(NeverShortCircuit);
832
833     // SAFETY: The same safety considerations w.r.t. the iterator length
834     // apply for `try_collect_into_array_unchecked` as for
835     // `collect_into_array_unchecked`
836     match unsafe { try_collect_into_array_unchecked(&mut map) } {
837         NeverShortCircuit(array) => array,
838     }
839 }
840
841 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
842 /// yields fewer than `N` items, `Err` is returned containing an iterator over
843 /// the already yielded items.
844 ///
845 /// Since the iterator is passed as a mutable reference and this function calls
846 /// `next` at most `N` times, the iterator can still be used afterwards to
847 /// retrieve the remaining items.
848 ///
849 /// If `iter.next()` panicks, all items already yielded by the iterator are
850 /// dropped.
851 #[inline]
852 fn try_collect_into_array<I, T, R, const N: usize>(
853     iter: &mut I,
854 ) -> Result<R::TryType, IntoIter<T, N>>
855 where
856     I: Iterator,
857     I::Item: Try<Output = T, Residual = R>,
858     R: Residual<[T; N]>,
859 {
860     if N == 0 {
861         // SAFETY: An empty array is always inhabited and has no validity invariants.
862         return Ok(Try::from_output(unsafe { mem::zeroed() }));
863     }
864
865     struct Guard<'a, T, const N: usize> {
866         array_mut: &'a mut [MaybeUninit<T>; N],
867         initialized: usize,
868     }
869
870     impl<T, const N: usize> Drop for Guard<'_, T, N> {
871         fn drop(&mut self) {
872             debug_assert!(self.initialized <= N);
873
874             // SAFETY: this slice will contain only initialized objects.
875             unsafe {
876                 crate::ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(
877                     &mut self.array_mut.get_unchecked_mut(..self.initialized),
878                 ));
879             }
880         }
881     }
882
883     let mut array = MaybeUninit::uninit_array::<N>();
884     let mut guard = Guard { array_mut: &mut array, initialized: 0 };
885
886     for _ in 0..N {
887         match iter.next() {
888             Some(item_rslt) => {
889                 let item = match item_rslt.branch() {
890                     ControlFlow::Break(r) => {
891                         return Ok(FromResidual::from_residual(r));
892                     }
893                     ControlFlow::Continue(elem) => elem,
894                 };
895
896                 // SAFETY: `guard.initialized` starts at 0, is increased by one in the
897                 // loop and the loop is aborted once it reaches N (which is
898                 // `array.len()`).
899                 unsafe {
900                     guard.array_mut.get_unchecked_mut(guard.initialized).write(item);
901                 }
902                 guard.initialized += 1;
903             }
904             None => {
905                 let alive = 0..guard.initialized;
906                 mem::forget(guard);
907                 // SAFETY: `array` was initialized with exactly `initialized`
908                 // number of elements.
909                 return Err(unsafe { IntoIter::new_unchecked(array, alive) });
910             }
911         }
912     }
913
914     mem::forget(guard);
915     // SAFETY: All elements of the array were populated in the loop above.
916     let output = unsafe { MaybeUninit::array_assume_init(array) };
917     Ok(Try::from_output(output))
918 }
919
920 /// Returns the next chunk of `N` items from the iterator or errors with an
921 /// iterator over the remainder. Used for `Iterator::next_chunk`.
922 #[inline]
923 pub(crate) fn iter_next_chunk<I, const N: usize>(
924     iter: &mut I,
925 ) -> Result<[I::Item; N], IntoIter<I::Item, N>>
926 where
927     I: Iterator,
928 {
929     let mut map = iter.map(NeverShortCircuit);
930     try_collect_into_array(&mut map).map(|NeverShortCircuit(arr)| arr)
931 }