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
7use crate::borrow::{Borrow, BorrowMut};
8use crate::cmp::Ordering;
9use crate::convert::{Infallible, TryFrom};
10use crate::error::Error;
11use crate::fmt;
12use crate::hash::{self, Hash};
13use crate::iter::UncheckedIterator;
14use crate::mem::{self, MaybeUninit};
15use crate::ops::{
16 ChangeOutputType, ControlFlow, FromResidual, Index, IndexMut, NeverShortCircuit, Residual, Try,
17};
18use crate::slice::{Iter, IterMut};
19
20mod ascii;
21mod drain;
22mod equality;
23mod iter;
24
25pub(crate) use drain::drain_array_with;
26
27#[stable(feature = "array_value_iter", since = "1.51.0")]
28pub use iter::IntoIter;
29
30/// Creates an array of type [T; N], where each element `T` is the returned value from `cb`
31/// using that element's index.
32///
33/// # Arguments
34///
35/// * `cb`: Callback where the passed argument is the current array index.
36///
37/// # Example
38///
39/// ```rust
40/// // type inference is helping us here, the way `from_fn` knows how many
41/// // elements to produce is the length of array down there: only arrays of
42/// // equal lengths can be compared, so the const generic parameter `N` is
43/// // inferred to be 5, thus creating array of 5 elements.
44///
45/// let array = core::array::from_fn(|i| i);
46/// // indexes are: 0 1 2 3 4
47/// assert_eq!(array, [0, 1, 2, 3, 4]);
48///
49/// let array2: [usize; 8] = core::array::from_fn(|i| i * 2);
50/// // indexes are: 0 1 2 3 4 5 6 7
51/// assert_eq!(array2, [0, 2, 4, 6, 8, 10, 12, 14]);
52///
53/// let bool_arr = core::array::from_fn::<_, 5, _>(|i| i % 2 == 0);
54/// // indexes are: 0 1 2 3 4
55/// assert_eq!(bool_arr, [true, false, true, false, true]);
56/// ```
57#[inline]
58#[stable(feature = "array_from_fn", since = "1.63.0")]
59pub fn from_fn<T, const N: usize, F>(cb: F) -> [T; N]
60where
61 F: FnMut(usize) -> T,
62{
63 try_from_fn(cb:NeverShortCircuit::wrap_mut_1(cb)).0
64}
65
66/// Creates an array `[T; N]` where each fallible array element `T` is returned by the `cb` call.
67/// Unlike [`from_fn`], where the element creation can't fail, this version will return an error
68/// if any element creation was unsuccessful.
69///
70/// The return type of this function depends on the return type of the closure.
71/// If you return `Result<T, E>` from the closure, you'll get a `Result<[T; N], E>`.
72/// If you return `Option<T>` from the closure, you'll get an `Option<[T; N]>`.
73///
74/// # Arguments
75///
76/// * `cb`: Callback where the passed argument is the current array index.
77///
78/// # Example
79///
80/// ```rust
81/// #![feature(array_try_from_fn)]
82///
83/// let array: Result<[u8; 5], _> = std::array::try_from_fn(|i| i.try_into());
84/// assert_eq!(array, Ok([0, 1, 2, 3, 4]));
85///
86/// let array: Result<[i8; 200], _> = std::array::try_from_fn(|i| i.try_into());
87/// assert!(array.is_err());
88///
89/// let array: Option<[_; 4]> = std::array::try_from_fn(|i| i.checked_add(100));
90/// assert_eq!(array, Some([100, 101, 102, 103]));
91///
92/// let array: Option<[_; 4]> = std::array::try_from_fn(|i| i.checked_sub(100));
93/// assert_eq!(array, None);
94/// ```
95#[inline]
96#[unstable(feature = "array_try_from_fn", issue = "89379")]
97pub fn try_from_fn<R, const N: usize, F>(cb: F) -> ChangeOutputType<R, [R::Output; N]>
98where
99 F: FnMut(usize) -> R,
100 R: Try,
101 R::Residual: Residual<[R::Output; N]>,
102{
103 let mut array: [MaybeUninit<::Output>; N] = MaybeUninit::uninit_array::<N>();
104 match try_from_fn_erased(&mut array, generator:cb) {
105 ControlFlow::Break(r: ::Residual) => FromResidual::from_residual(r),
106 ControlFlow::Continue(()) => {
107 // SAFETY: All elements of the array were populated.
108 try { unsafe { MaybeUninit::array_assume_init(array) } }
109 }
110 }
111}
112
113/// Converts a reference to `T` into a reference to an array of length 1 (without copying).
114#[stable(feature = "array_from_ref", since = "1.53.0")]
115#[rustc_const_stable(feature = "const_array_from_ref_shared", since = "1.63.0")]
116pub const fn from_ref<T>(s: &T) -> &[T; 1] {
117 // SAFETY: Converting `&T` to `&[T; 1]` is sound.
118 unsafe { &*(s as *const T).cast::<[T; 1]>() }
119}
120
121/// Converts a mutable reference to `T` into a mutable reference to an array of length 1 (without copying).
122#[stable(feature = "array_from_ref", since = "1.53.0")]
123#[rustc_const_unstable(feature = "const_array_from_ref", issue = "90206")]
124pub const fn from_mut<T>(s: &mut T) -> &mut [T; 1] {
125 // SAFETY: Converting `&mut T` to `&mut [T; 1]` is sound.
126 unsafe { &mut *(s as *mut T).cast::<[T; 1]>() }
127}
128
129/// The error type returned when a conversion from a slice to an array fails.
130#[stable(feature = "try_from", since = "1.34.0")]
131#[derive(Debug, Copy, Clone)]
132pub struct TryFromSliceError(());
133
134#[stable(feature = "core_array", since = "1.36.0")]
135impl fmt::Display for TryFromSliceError {
136 #[inline]
137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138 #[allow(deprecated)]
139 self.description().fmt(f)
140 }
141}
142
143#[stable(feature = "try_from", since = "1.34.0")]
144impl Error for TryFromSliceError {
145 #[allow(deprecated)]
146 fn description(&self) -> &str {
147 "could not convert slice to array"
148 }
149}
150
151#[stable(feature = "try_from_slice_error", since = "1.36.0")]
152impl From<Infallible> for TryFromSliceError {
153 fn from(x: Infallible) -> TryFromSliceError {
154 match x {}
155 }
156}
157
158#[stable(feature = "rust1", since = "1.0.0")]
159impl<T, const N: usize> AsRef<[T]> for [T; N] {
160 #[inline]
161 fn as_ref(&self) -> &[T] {
162 &self[..]
163 }
164}
165
166#[stable(feature = "rust1", since = "1.0.0")]
167impl<T, const N: usize> AsMut<[T]> for [T; N] {
168 #[inline]
169 fn as_mut(&mut self) -> &mut [T] {
170 &mut self[..]
171 }
172}
173
174#[stable(feature = "array_borrow", since = "1.4.0")]
175impl<T, const N: usize> Borrow<[T]> for [T; N] {
176 fn borrow(&self) -> &[T] {
177 self
178 }
179}
180
181#[stable(feature = "array_borrow", since = "1.4.0")]
182impl<T, const N: usize> BorrowMut<[T]> for [T; N] {
183 fn borrow_mut(&mut self) -> &mut [T] {
184 self
185 }
186}
187
188/// Tries to create an array `[T; N]` by copying from a slice `&[T]`. Succeeds if
189/// `slice.len() == N`.
190///
191/// ```
192/// let bytes: [u8; 3] = [1, 0, 2];
193///
194/// let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&bytes[0..2]).unwrap();
195/// assert_eq!(1, u16::from_le_bytes(bytes_head));
196///
197/// let bytes_tail: [u8; 2] = bytes[1..3].try_into().unwrap();
198/// assert_eq!(512, u16::from_le_bytes(bytes_tail));
199/// ```
200#[stable(feature = "try_from", since = "1.34.0")]
201impl<T, const N: usize> TryFrom<&[T]> for [T; N]
202where
203 T: Copy,
204{
205 type Error = TryFromSliceError;
206
207 #[inline]
208 fn try_from(slice: &[T]) -> Result<[T; N], TryFromSliceError> {
209 <&Self>::try_from(slice).copied()
210 }
211}
212
213/// Tries to create an array `[T; N]` by copying from a mutable slice `&mut [T]`.
214/// Succeeds if `slice.len() == N`.
215///
216/// ```
217/// let mut bytes: [u8; 3] = [1, 0, 2];
218///
219/// let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
220/// assert_eq!(1, u16::from_le_bytes(bytes_head));
221///
222/// let bytes_tail: [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
223/// assert_eq!(512, u16::from_le_bytes(bytes_tail));
224/// ```
225#[stable(feature = "try_from_mut_slice_to_array", since = "1.59.0")]
226impl<T, const N: usize> TryFrom<&mut [T]> for [T; N]
227where
228 T: Copy,
229{
230 type Error = TryFromSliceError;
231
232 #[inline]
233 fn try_from(slice: &mut [T]) -> Result<[T; N], TryFromSliceError> {
234 <Self>::try_from(&*slice)
235 }
236}
237
238/// Tries to create an array ref `&[T; N]` from a slice ref `&[T]`. Succeeds if
239/// `slice.len() == N`.
240///
241/// ```
242/// let bytes: [u8; 3] = [1, 0, 2];
243///
244/// let bytes_head: &[u8; 2] = <&[u8; 2]>::try_from(&bytes[0..2]).unwrap();
245/// assert_eq!(1, u16::from_le_bytes(*bytes_head));
246///
247/// let bytes_tail: &[u8; 2] = bytes[1..3].try_into().unwrap();
248/// assert_eq!(512, u16::from_le_bytes(*bytes_tail));
249/// ```
250#[stable(feature = "try_from", since = "1.34.0")]
251impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N] {
252 type Error = TryFromSliceError;
253
254 #[inline]
255 fn try_from(slice: &'a [T]) -> Result<&'a [T; N], TryFromSliceError> {
256 if slice.len() == N {
257 let ptr: *const [T; N] = slice.as_ptr() as *const [T; N];
258 // SAFETY: ok because we just checked that the length fits
259 unsafe { Ok(&*ptr) }
260 } else {
261 Err(TryFromSliceError(()))
262 }
263 }
264}
265
266/// Tries to create a mutable array ref `&mut [T; N]` from a mutable slice ref
267/// `&mut [T]`. Succeeds if `slice.len() == N`.
268///
269/// ```
270/// let mut bytes: [u8; 3] = [1, 0, 2];
271///
272/// let bytes_head: &mut [u8; 2] = <&mut [u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
273/// assert_eq!(1, u16::from_le_bytes(*bytes_head));
274///
275/// let bytes_tail: &mut [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
276/// assert_eq!(512, u16::from_le_bytes(*bytes_tail));
277/// ```
278#[stable(feature = "try_from", since = "1.34.0")]
279impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N] {
280 type Error = TryFromSliceError;
281
282 #[inline]
283 fn try_from(slice: &'a mut [T]) -> Result<&'a mut [T; N], TryFromSliceError> {
284 if slice.len() == N {
285 let ptr: *mut [T; N] = slice.as_mut_ptr() as *mut [T; N];
286 // SAFETY: ok because we just checked that the length fits
287 unsafe { Ok(&mut *ptr) }
288 } else {
289 Err(TryFromSliceError(()))
290 }
291 }
292}
293
294/// The hash of an array is the same as that of the corresponding slice,
295/// as required by the `Borrow` implementation.
296///
297/// ```
298/// use std::hash::BuildHasher;
299///
300/// let b = std::hash::RandomState::new();
301/// let a: [u8; 3] = [0xa8, 0x3c, 0x09];
302/// let s: &[u8] = &[0xa8, 0x3c, 0x09];
303/// assert_eq!(b.hash_one(a), b.hash_one(s));
304/// ```
305#[stable(feature = "rust1", since = "1.0.0")]
306impl<T: Hash, const N: usize> Hash for [T; N] {
307 fn hash<H: hash::Hasher>(&self, state: &mut H) {
308 Hash::hash(&self[..], state)
309 }
310}
311
312#[stable(feature = "rust1", since = "1.0.0")]
313impl<T: fmt::Debug, const N: usize> fmt::Debug for [T; N] {
314 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315 fmt::Debug::fmt(&&self[..], f)
316 }
317}
318
319#[stable(feature = "rust1", since = "1.0.0")]
320impl<'a, T, const N: usize> IntoIterator for &'a [T; N] {
321 type Item = &'a T;
322 type IntoIter = Iter<'a, T>;
323
324 fn into_iter(self) -> Iter<'a, T> {
325 self.iter()
326 }
327}
328
329#[stable(feature = "rust1", since = "1.0.0")]
330impl<'a, T, const N: usize> IntoIterator for &'a mut [T; N] {
331 type Item = &'a mut T;
332 type IntoIter = IterMut<'a, T>;
333
334 fn into_iter(self) -> IterMut<'a, T> {
335 self.iter_mut()
336 }
337}
338
339#[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
340impl<T, I, const N: usize> Index<I> for [T; N]
341where
342 [T]: Index<I>,
343{
344 type Output = <[T] as Index<I>>::Output;
345
346 #[inline]
347 fn index(&self, index: I) -> &Self::Output {
348 Index::index(self as &[T], index)
349 }
350}
351
352#[stable(feature = "index_trait_on_arrays", since = "1.50.0")]
353impl<T, I, const N: usize> IndexMut<I> for [T; N]
354where
355 [T]: IndexMut<I>,
356{
357 #[inline]
358 fn index_mut(&mut self, index: I) -> &mut Self::Output {
359 IndexMut::index_mut(self as &mut [T], index)
360 }
361}
362
363#[stable(feature = "rust1", since = "1.0.0")]
364impl<T: PartialOrd, const N: usize> PartialOrd for [T; N] {
365 #[inline]
366 fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
367 PartialOrd::partial_cmp(&&self[..], &&other[..])
368 }
369 #[inline]
370 fn lt(&self, other: &[T; N]) -> bool {
371 PartialOrd::lt(&&self[..], &&other[..])
372 }
373 #[inline]
374 fn le(&self, other: &[T; N]) -> bool {
375 PartialOrd::le(&&self[..], &&other[..])
376 }
377 #[inline]
378 fn ge(&self, other: &[T; N]) -> bool {
379 PartialOrd::ge(&&self[..], &&other[..])
380 }
381 #[inline]
382 fn gt(&self, other: &[T; N]) -> bool {
383 PartialOrd::gt(&&self[..], &&other[..])
384 }
385}
386
387/// Implements comparison of arrays [lexicographically](Ord#lexicographical-comparison).
388#[stable(feature = "rust1", since = "1.0.0")]
389impl<T: Ord, const N: usize> Ord for [T; N] {
390 #[inline]
391 fn cmp(&self, other: &[T; N]) -> Ordering {
392 Ord::cmp(&&self[..], &&other[..])
393 }
394}
395
396#[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
397impl<T: Copy, const N: usize> Copy for [T; N] {}
398
399#[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
400impl<T: Clone, const N: usize> Clone for [T; N] {
401 #[inline]
402 fn clone(&self) -> Self {
403 SpecArrayClone::clone(self)
404 }
405
406 #[inline]
407 fn clone_from(&mut self, other: &Self) {
408 self.clone_from_slice(src:other);
409 }
410}
411
412trait SpecArrayClone: Clone {
413 fn clone<const N: usize>(array: &[Self; N]) -> [Self; N];
414}
415
416impl<T: Clone> SpecArrayClone for T {
417 #[inline]
418 default fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
419 from_trusted_iterator(iter:array.iter().cloned())
420 }
421}
422
423impl<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
434macro_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 impl<T> Default for [T; $n] {
447 fn default() -> [T; $n] { [] }
448 }
449 };
450}
451
452array_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
454impl<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 self.try_map(NeverShortCircuit::wrap_mut_1(f)).0
502 }
503
504 /// A fallible function `f` applied to each element on array `self` in order to
505 /// return an array the same size as `self` or the first error encountered.
506 ///
507 /// The return type of this function depends on the return type of the closure.
508 /// If you return `Result<T, E>` from the closure, you'll get a `Result<[T; N], E>`.
509 /// If you return `Option<T>` from the closure, you'll get an `Option<[T; N]>`.
510 ///
511 /// # Examples
512 ///
513 /// ```
514 /// #![feature(array_try_map)]
515 /// let a = ["1", "2", "3"];
516 /// let b = a.try_map(|v| v.parse::<u32>()).unwrap().map(|v| v + 1);
517 /// assert_eq!(b, [2, 3, 4]);
518 ///
519 /// let a = ["1", "2a", "3"];
520 /// let b = a.try_map(|v| v.parse::<u32>());
521 /// assert!(b.is_err());
522 ///
523 /// use std::num::NonZeroU32;
524 /// let z = [1, 2, 0, 3, 4];
525 /// assert_eq!(z.try_map(NonZeroU32::new), None);
526 /// let a = [1, 2, 3];
527 /// let b = a.try_map(NonZeroU32::new);
528 /// let c = b.map(|x| x.map(NonZeroU32::get));
529 /// assert_eq!(c, Some(a));
530 /// ```
531 #[unstable(feature = "array_try_map", issue = "79711")]
532 pub fn try_map<F, R>(self, f: F) -> ChangeOutputType<R, [R::Output; N]>
533 where
534 F: FnMut(T) -> R,
535 R: Try,
536 R::Residual: Residual<[R::Output; N]>,
537 {
538 drain_array_with(self, |iter| try_from_trusted_iterator(iter.map(f)))
539 }
540
541 /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
542 #[stable(feature = "array_as_slice", since = "1.57.0")]
543 #[rustc_const_stable(feature = "array_as_slice", since = "1.57.0")]
544 pub const fn as_slice(&self) -> &[T] {
545 self
546 }
547
548 /// Returns a mutable slice containing the entire array. Equivalent to
549 /// `&mut s[..]`.
550 #[stable(feature = "array_as_slice", since = "1.57.0")]
551 pub fn as_mut_slice(&mut self) -> &mut [T] {
552 self
553 }
554
555 /// Borrows each element and returns an array of references with the same
556 /// size as `self`.
557 ///
558 ///
559 /// # Example
560 ///
561 /// ```
562 /// let floats = [3.1, 2.7, -1.0];
563 /// let float_refs: [&f64; 3] = floats.each_ref();
564 /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
565 /// ```
566 ///
567 /// This method is particularly useful if combined with other methods, like
568 /// [`map`](#method.map). This way, you can avoid moving the original
569 /// array if its elements are not [`Copy`].
570 ///
571 /// ```
572 /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
573 /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
574 /// assert_eq!(is_ascii, [true, false, true]);
575 ///
576 /// // We can still access the original array: it has not been moved.
577 /// assert_eq!(strings.len(), 3);
578 /// ```
579 #[stable(feature = "array_methods", since = "1.77.0")]
580 pub fn each_ref(&self) -> [&T; N] {
581 from_trusted_iterator(self.iter())
582 }
583
584 /// Borrows each element mutably and returns an array of mutable references
585 /// with the same size as `self`.
586 ///
587 ///
588 /// # Example
589 ///
590 /// ```
591 ///
592 /// let mut floats = [3.1, 2.7, -1.0];
593 /// let float_refs: [&mut f64; 3] = floats.each_mut();
594 /// *float_refs[0] = 0.0;
595 /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
596 /// assert_eq!(floats, [0.0, 2.7, -1.0]);
597 /// ```
598 #[stable(feature = "array_methods", since = "1.77.0")]
599 pub fn each_mut(&mut self) -> [&mut T; N] {
600 from_trusted_iterator(self.iter_mut())
601 }
602
603 /// Divides one array reference into two at an index.
604 ///
605 /// The first will contain all indices from `[0, M)` (excluding
606 /// the index `M` itself) and the second will contain all
607 /// indices from `[M, N)` (excluding the index `N` itself).
608 ///
609 /// # Panics
610 ///
611 /// Panics if `M > N`.
612 ///
613 /// # Examples
614 ///
615 /// ```
616 /// #![feature(split_array)]
617 ///
618 /// let v = [1, 2, 3, 4, 5, 6];
619 ///
620 /// {
621 /// let (left, right) = v.split_array_ref::<0>();
622 /// assert_eq!(left, &[]);
623 /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
624 /// }
625 ///
626 /// {
627 /// let (left, right) = v.split_array_ref::<2>();
628 /// assert_eq!(left, &[1, 2]);
629 /// assert_eq!(right, &[3, 4, 5, 6]);
630 /// }
631 ///
632 /// {
633 /// let (left, right) = v.split_array_ref::<6>();
634 /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
635 /// assert_eq!(right, &[]);
636 /// }
637 /// ```
638 #[unstable(
639 feature = "split_array",
640 reason = "return type should have array as 2nd element",
641 issue = "90091"
642 )]
643 #[inline]
644 pub fn split_array_ref<const M: usize>(&self) -> (&[T; M], &[T]) {
645 (&self[..]).split_first_chunk::<M>().unwrap()
646 }
647
648 /// Divides one mutable array reference into two at an index.
649 ///
650 /// The first will contain all indices from `[0, M)` (excluding
651 /// the index `M` itself) and the second will contain all
652 /// indices from `[M, N)` (excluding the index `N` itself).
653 ///
654 /// # Panics
655 ///
656 /// Panics if `M > N`.
657 ///
658 /// # Examples
659 ///
660 /// ```
661 /// #![feature(split_array)]
662 ///
663 /// let mut v = [1, 0, 3, 0, 5, 6];
664 /// let (left, right) = v.split_array_mut::<2>();
665 /// assert_eq!(left, &mut [1, 0][..]);
666 /// assert_eq!(right, &mut [3, 0, 5, 6]);
667 /// left[1] = 2;
668 /// right[1] = 4;
669 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
670 /// ```
671 #[unstable(
672 feature = "split_array",
673 reason = "return type should have array as 2nd element",
674 issue = "90091"
675 )]
676 #[inline]
677 pub fn split_array_mut<const M: usize>(&mut self) -> (&mut [T; M], &mut [T]) {
678 (&mut self[..]).split_first_chunk_mut::<M>().unwrap()
679 }
680
681 /// Divides one array reference into two at an index from the end.
682 ///
683 /// The first will contain all indices from `[0, N - M)` (excluding
684 /// the index `N - M` itself) and the second will contain all
685 /// indices from `[N - M, N)` (excluding the index `N` itself).
686 ///
687 /// # Panics
688 ///
689 /// Panics if `M > N`.
690 ///
691 /// # Examples
692 ///
693 /// ```
694 /// #![feature(split_array)]
695 ///
696 /// let v = [1, 2, 3, 4, 5, 6];
697 ///
698 /// {
699 /// let (left, right) = v.rsplit_array_ref::<0>();
700 /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
701 /// assert_eq!(right, &[]);
702 /// }
703 ///
704 /// {
705 /// let (left, right) = v.rsplit_array_ref::<2>();
706 /// assert_eq!(left, &[1, 2, 3, 4]);
707 /// assert_eq!(right, &[5, 6]);
708 /// }
709 ///
710 /// {
711 /// let (left, right) = v.rsplit_array_ref::<6>();
712 /// assert_eq!(left, &[]);
713 /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
714 /// }
715 /// ```
716 #[unstable(
717 feature = "split_array",
718 reason = "return type should have array as 2nd element",
719 issue = "90091"
720 )]
721 #[inline]
722 pub fn rsplit_array_ref<const M: usize>(&self) -> (&[T], &[T; M]) {
723 (&self[..]).split_last_chunk::<M>().unwrap()
724 }
725
726 /// Divides one mutable array reference into two at an index from the end.
727 ///
728 /// The first will contain all indices from `[0, N - M)` (excluding
729 /// the index `N - M` itself) and the second will contain all
730 /// indices from `[N - M, N)` (excluding the index `N` itself).
731 ///
732 /// # Panics
733 ///
734 /// Panics if `M > N`.
735 ///
736 /// # Examples
737 ///
738 /// ```
739 /// #![feature(split_array)]
740 ///
741 /// let mut v = [1, 0, 3, 0, 5, 6];
742 /// let (left, right) = v.rsplit_array_mut::<4>();
743 /// assert_eq!(left, &mut [1, 0]);
744 /// assert_eq!(right, &mut [3, 0, 5, 6][..]);
745 /// left[1] = 2;
746 /// right[1] = 4;
747 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
748 /// ```
749 #[unstable(
750 feature = "split_array",
751 reason = "return type should have array as 2nd element",
752 issue = "90091"
753 )]
754 #[inline]
755 pub fn rsplit_array_mut<const M: usize>(&mut self) -> (&mut [T], &mut [T; M]) {
756 (&mut self[..]).split_last_chunk_mut::<M>().unwrap()
757 }
758}
759
760/// Populate an array from the first `N` elements of `iter`
761///
762/// # Panics
763///
764/// If the iterator doesn't actually have enough items.
765///
766/// By depending on `TrustedLen`, however, we can do that check up-front (where
767/// it easily optimizes away) so it doesn't impact the loop that fills the array.
768#[inline]
769fn from_trusted_iterator<T, const N: usize>(iter: impl UncheckedIterator<Item = T>) -> [T; N] {
770 try_from_trusted_iterator(iter:iter.map(NeverShortCircuit)).0
771}
772
773#[inline]
774fn try_from_trusted_iterator<T, R, const N: usize>(
775 iter: impl UncheckedIterator<Item = R>,
776) -> ChangeOutputType<R, [T; N]>
777where
778 R: Try<Output = T>,
779 R::Residual: Residual<[T; N]>,
780{
781 assert!(iter.size_hint().0 >= N);
782 fn next<T>(mut iter: impl UncheckedIterator<Item = T>) -> impl FnMut(usize) -> T {
783 move |_| {
784 // SAFETY: We know that `from_fn` will call this at most N times,
785 // and we checked to ensure that we have at least that many items.
786 unsafe { iter.next_unchecked() }
787 }
788 }
789
790 try_from_fn(cb:next(iter))
791}
792
793/// Version of [`try_from_fn`] using a passed-in slice in order to avoid
794/// needing to monomorphize for every array length.
795///
796/// This takes a generator rather than an iterator so that *at the type level*
797/// it never needs to worry about running out of items. When combined with
798/// an infallible `Try` type, that means the loop canonicalizes easily, allowing
799/// it to optimize well.
800///
801/// It would be *possible* to unify this and [`iter_next_chunk_erased`] into one
802/// function that does the union of both things, but last time it was that way
803/// it resulted in poor codegen from the "are there enough source items?" checks
804/// not optimizing away. So if you give it a shot, make sure to watch what
805/// happens in the codegen tests.
806#[inline]
807fn try_from_fn_erased<T, R>(
808 buffer: &mut [MaybeUninit<T>],
809 mut generator: impl FnMut(usize) -> R,
810) -> ControlFlow<R::Residual>
811where
812 R: Try<Output = T>,
813{
814 let mut guard: Guard<'_, T> = Guard { array_mut: buffer, initialized: 0 };
815
816 while guard.initialized < guard.array_mut.len() {
817 let item: T = generator(guard.initialized).branch()?;
818
819 // SAFETY: The loop condition ensures we have space to push the item
820 unsafe { guard.push_unchecked(item) };
821 }
822
823 mem::forget(guard);
824 ControlFlow::Continue(())
825}
826
827/// Panic guard for incremental initialization of arrays.
828///
829/// Disarm the guard with `mem::forget` once the array has been initialized.
830///
831/// # Safety
832///
833/// All write accesses to this structure are unsafe and must maintain a correct
834/// count of `initialized` elements.
835///
836/// To minimize indirection fields are still pub but callers should at least use
837/// `push_unchecked` to signal that something unsafe is going on.
838struct Guard<'a, T> {
839 /// The array to be initialized.
840 pub array_mut: &'a mut [MaybeUninit<T>],
841 /// The number of items that have been initialized so far.
842 pub initialized: usize,
843}
844
845impl<T> Guard<'_, T> {
846 /// Adds an item to the array and updates the initialized item counter.
847 ///
848 /// # Safety
849 ///
850 /// No more than N elements must be initialized.
851 #[inline]
852 pub unsafe fn push_unchecked(&mut self, item: T) {
853 // SAFETY: If `initialized` was correct before and the caller does not
854 // invoke this method more than N times then writes will be in-bounds
855 // and slots will not be initialized more than once.
856 unsafe {
857 self.array_mut.get_unchecked_mut(self.initialized).write(val:item);
858 self.initialized = self.initialized.unchecked_add(1);
859 }
860 }
861}
862
863impl<T> Drop for Guard<'_, T> {
864 fn drop(&mut self) {
865 debug_assert!(self.initialized <= self.array_mut.len());
866
867 // SAFETY: this slice will contain only initialized objects.
868 unsafe {
869 crate::ptr::drop_in_place(to_drop:MaybeUninit::slice_assume_init_mut(
870 self.array_mut.get_unchecked_mut(..self.initialized),
871 ));
872 }
873 }
874}
875
876/// Pulls `N` items from `iter` and returns them as an array. If the iterator
877/// yields fewer than `N` items, `Err` is returned containing an iterator over
878/// the already yielded items.
879///
880/// Since the iterator is passed as a mutable reference and this function calls
881/// `next` at most `N` times, the iterator can still be used afterwards to
882/// retrieve the remaining items.
883///
884/// If `iter.next()` panicks, all items already yielded by the iterator are
885/// dropped.
886///
887/// Used for [`Iterator::next_chunk`].
888#[inline]
889pub(crate) fn iter_next_chunk<T, const N: usize>(
890 iter: &mut impl Iterator<Item = T>,
891) -> Result<[T; N], IntoIter<T, N>> {
892 let mut array: [MaybeUninit; N] = MaybeUninit::uninit_array::<N>();
893 let r: Result<(), usize> = iter_next_chunk_erased(&mut array, iter);
894 match r {
895 Ok(()) => {
896 // SAFETY: All elements of `array` were populated.
897 Ok(unsafe { MaybeUninit::array_assume_init(array) })
898 }
899 Err(initialized: usize) => {
900 // SAFETY: Only the first `initialized` elements were populated
901 Err(unsafe { IntoIter::new_unchecked(buffer:array, initialized:0..initialized) })
902 }
903 }
904}
905
906/// Version of [`iter_next_chunk`] using a passed-in slice in order to avoid
907/// needing to monomorphize for every array length.
908///
909/// Unfortunately this loop has two exit conditions, the buffer filling up
910/// or the iterator running out of items, making it tend to optimize poorly.
911#[inline]
912fn iter_next_chunk_erased<T>(
913 buffer: &mut [MaybeUninit<T>],
914 iter: &mut impl Iterator<Item = T>,
915) -> Result<(), usize> {
916 let mut guard: Guard<'_, T> = Guard { array_mut: buffer, initialized: 0 };
917 while guard.initialized < guard.array_mut.len() {
918 let Some(item: T) = iter.next() else {
919 // Unlike `try_from_fn_erased`, we want to keep the partial results,
920 // so we need to defuse the guard instead of using `?`.
921 let initialized: usize = guard.initialized;
922 mem::forget(guard);
923 return Err(initialized);
924 };
925
926 // SAFETY: The loop condition ensures we have space to push the item
927 unsafe { guard.push_unchecked(item) };
928 }
929
930 mem::forget(guard);
931 Ok(())
932}
933