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