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