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;
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/// Implements comparison of arrays [lexicographically](Ord#lexicographical-comparison).
364#[stable(feature = "rust1", since = "1.0.0")]
365impl<T: PartialOrd, const N: usize> PartialOrd for [T; N] {
366 #[inline]
367 fn partial_cmp(&self, other: &[T; N]) -> Option<Ordering> {
368 PartialOrd::partial_cmp(&&self[..], &&other[..])
369 }
370 #[inline]
371 fn lt(&self, other: &[T; N]) -> bool {
372 PartialOrd::lt(&&self[..], &&other[..])
373 }
374 #[inline]
375 fn le(&self, other: &[T; N]) -> bool {
376 PartialOrd::le(&&self[..], &&other[..])
377 }
378 #[inline]
379 fn ge(&self, other: &[T; N]) -> bool {
380 PartialOrd::ge(&&self[..], &&other[..])
381 }
382 #[inline]
383 fn gt(&self, other: &[T; N]) -> bool {
384 PartialOrd::gt(&&self[..], &&other[..])
385 }
386}
387
388/// Implements comparison of arrays [lexicographically](Ord#lexicographical-comparison).
389#[stable(feature = "rust1", since = "1.0.0")]
390impl<T: Ord, const N: usize> Ord for [T; N] {
391 #[inline]
392 fn cmp(&self, other: &[T; N]) -> Ordering {
393 Ord::cmp(&&self[..], &&other[..])
394 }
395}
396
397#[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
398impl<T: Copy, const N: usize> Copy for [T; N] {}
399
400#[stable(feature = "copy_clone_array_lib", since = "1.58.0")]
401impl<T: Clone, const N: usize> Clone for [T; N] {
402 #[inline]
403 fn clone(&self) -> Self {
404 SpecArrayClone::clone(self)
405 }
406
407 #[inline]
408 fn clone_from(&mut self, other: &Self) {
409 self.clone_from_slice(src:other);
410 }
411}
412
413trait SpecArrayClone: Clone {
414 fn clone<const N: usize>(array: &[Self; N]) -> [Self; N];
415}
416
417impl<T: Clone> SpecArrayClone for T {
418 #[inline]
419 default fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
420 from_trusted_iterator(iter:array.iter().cloned())
421 }
422}
423
424impl<T: Copy> SpecArrayClone for T {
425 #[inline]
426 fn clone<const N: usize>(array: &[T; N]) -> [T; N] {
427 *array
428 }
429}
430
431// The Default impls cannot be done with const generics because `[T; 0]` doesn't
432// require Default to be implemented, and having different impl blocks for
433// different numbers isn't supported yet.
434
435macro_rules! array_impl_default {
436 {$n:expr, $t:ident $($ts:ident)*} => {
437 #[stable(since = "1.4.0", feature = "array_default")]
438 impl<T> Default for [T; $n] where T: Default {
439 fn default() -> [T; $n] {
440 [$t::default(), $($ts::default()),*]
441 }
442 }
443 array_impl_default!{($n - 1), $($ts)*}
444 };
445 {$n:expr,} => {
446 #[stable(since = "1.4.0", feature = "array_default")]
447 impl<T> Default for [T; $n] {
448 fn default() -> [T; $n] { [] }
449 }
450 };
451}
452
453array_impl_default! {32, T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T}
454
455impl<T, const N: usize> [T; N] {
456 /// Returns an array of the same size as `self`, with function `f` applied to each element
457 /// in order.
458 ///
459 /// If you don't necessarily need a new fixed-size array, consider using
460 /// [`Iterator::map`] instead.
461 ///
462 ///
463 /// # Note on performance and stack usage
464 ///
465 /// Unfortunately, usages of this method are currently not always optimized
466 /// as well as they could be. This mainly concerns large arrays, as mapping
467 /// over small arrays seem to be optimized just fine. Also note that in
468 /// debug mode (i.e. without any optimizations), this method can use a lot
469 /// of stack space (a few times the size of the array or more).
470 ///
471 /// Therefore, in performance-critical code, try to avoid using this method
472 /// on large arrays or check the emitted code. Also try to avoid chained
473 /// maps (e.g. `arr.map(...).map(...)`).
474 ///
475 /// In many cases, you can instead use [`Iterator::map`] by calling `.iter()`
476 /// or `.into_iter()` on your array. `[T; N]::map` is only necessary if you
477 /// really need a new array of the same size as the result. Rust's lazy
478 /// iterators tend to get optimized very well.
479 ///
480 ///
481 /// # Examples
482 ///
483 /// ```
484 /// let x = [1, 2, 3];
485 /// let y = x.map(|v| v + 1);
486 /// assert_eq!(y, [2, 3, 4]);
487 ///
488 /// let x = [1, 2, 3];
489 /// let mut temp = 0;
490 /// let y = x.map(|v| { temp += 1; v * temp });
491 /// assert_eq!(y, [1, 4, 9]);
492 ///
493 /// let x = ["Ferris", "Bueller's", "Day", "Off"];
494 /// let y = x.map(|v| v.len());
495 /// assert_eq!(y, [6, 9, 3, 3]);
496 /// ```
497 #[stable(feature = "array_map", since = "1.55.0")]
498 pub fn map<F, U>(self, f: F) -> [U; N]
499 where
500 F: FnMut(T) -> U,
501 {
502 self.try_map(NeverShortCircuit::wrap_mut_1(f)).0
503 }
504
505 /// A fallible function `f` applied to each element on array `self` in order to
506 /// return an array the same size as `self` or the first error encountered.
507 ///
508 /// The return type of this function depends on the return type of the closure.
509 /// If you return `Result<T, E>` from the closure, you'll get a `Result<[T; N], E>`.
510 /// If you return `Option<T>` from the closure, you'll get an `Option<[T; N]>`.
511 ///
512 /// # Examples
513 ///
514 /// ```
515 /// #![feature(array_try_map)]
516 ///
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::NonZero;
526 ///
527 /// let z = [1, 2, 0, 3, 4];
528 /// assert_eq!(z.try_map(NonZero::new), None);
529 ///
530 /// let a = [1, 2, 3];
531 /// let b = a.try_map(NonZero::new);
532 /// let c = b.map(|x| x.map(NonZero::get));
533 /// assert_eq!(c, Some(a));
534 /// ```
535 #[unstable(feature = "array_try_map", issue = "79711")]
536 pub fn try_map<F, R>(self, f: F) -> ChangeOutputType<R, [R::Output; N]>
537 where
538 F: FnMut(T) -> R,
539 R: Try,
540 R::Residual: Residual<[R::Output; N]>,
541 {
542 drain_array_with(self, |iter| try_from_trusted_iterator(iter.map(f)))
543 }
544
545 /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
546 #[stable(feature = "array_as_slice", since = "1.57.0")]
547 #[rustc_const_stable(feature = "array_as_slice", since = "1.57.0")]
548 pub const fn as_slice(&self) -> &[T] {
549 self
550 }
551
552 /// Returns a mutable slice containing the entire array. Equivalent to
553 /// `&mut s[..]`.
554 #[stable(feature = "array_as_slice", since = "1.57.0")]
555 pub fn as_mut_slice(&mut self) -> &mut [T] {
556 self
557 }
558
559 /// Borrows each element and returns an array of references with the same
560 /// size as `self`.
561 ///
562 ///
563 /// # Example
564 ///
565 /// ```
566 /// let floats = [3.1, 2.7, -1.0];
567 /// let float_refs: [&f64; 3] = floats.each_ref();
568 /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
569 /// ```
570 ///
571 /// This method is particularly useful if combined with other methods, like
572 /// [`map`](#method.map). This way, you can avoid moving the original
573 /// array if its elements are not [`Copy`].
574 ///
575 /// ```
576 /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
577 /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
578 /// assert_eq!(is_ascii, [true, false, true]);
579 ///
580 /// // We can still access the original array: it has not been moved.
581 /// assert_eq!(strings.len(), 3);
582 /// ```
583 #[stable(feature = "array_methods", since = "1.77.0")]
584 pub fn each_ref(&self) -> [&T; N] {
585 from_trusted_iterator(self.iter())
586 }
587
588 /// Borrows each element mutably and returns an array of mutable references
589 /// with the same size as `self`.
590 ///
591 ///
592 /// # Example
593 ///
594 /// ```
595 ///
596 /// let mut floats = [3.1, 2.7, -1.0];
597 /// let float_refs: [&mut f64; 3] = floats.each_mut();
598 /// *float_refs[0] = 0.0;
599 /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
600 /// assert_eq!(floats, [0.0, 2.7, -1.0]);
601 /// ```
602 #[stable(feature = "array_methods", since = "1.77.0")]
603 pub fn each_mut(&mut self) -> [&mut T; N] {
604 from_trusted_iterator(self.iter_mut())
605 }
606
607 /// Divides one array reference into two at an index.
608 ///
609 /// The first will contain all indices from `[0, M)` (excluding
610 /// the index `M` itself) and the second will contain all
611 /// indices from `[M, N)` (excluding the index `N` itself).
612 ///
613 /// # Panics
614 ///
615 /// Panics if `M > N`.
616 ///
617 /// # Examples
618 ///
619 /// ```
620 /// #![feature(split_array)]
621 ///
622 /// let v = [1, 2, 3, 4, 5, 6];
623 ///
624 /// {
625 /// let (left, right) = v.split_array_ref::<0>();
626 /// assert_eq!(left, &[]);
627 /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
628 /// }
629 ///
630 /// {
631 /// let (left, right) = v.split_array_ref::<2>();
632 /// assert_eq!(left, &[1, 2]);
633 /// assert_eq!(right, &[3, 4, 5, 6]);
634 /// }
635 ///
636 /// {
637 /// let (left, right) = v.split_array_ref::<6>();
638 /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
639 /// assert_eq!(right, &[]);
640 /// }
641 /// ```
642 #[unstable(
643 feature = "split_array",
644 reason = "return type should have array as 2nd element",
645 issue = "90091"
646 )]
647 #[inline]
648 pub fn split_array_ref<const M: usize>(&self) -> (&[T; M], &[T]) {
649 (&self[..]).split_first_chunk::<M>().unwrap()
650 }
651
652 /// Divides one mutable array reference into two at an index.
653 ///
654 /// The first will contain all indices from `[0, M)` (excluding
655 /// the index `M` itself) and the second will contain all
656 /// indices from `[M, N)` (excluding the index `N` itself).
657 ///
658 /// # Panics
659 ///
660 /// Panics if `M > N`.
661 ///
662 /// # Examples
663 ///
664 /// ```
665 /// #![feature(split_array)]
666 ///
667 /// let mut v = [1, 0, 3, 0, 5, 6];
668 /// let (left, right) = v.split_array_mut::<2>();
669 /// assert_eq!(left, &mut [1, 0][..]);
670 /// assert_eq!(right, &mut [3, 0, 5, 6]);
671 /// left[1] = 2;
672 /// right[1] = 4;
673 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
674 /// ```
675 #[unstable(
676 feature = "split_array",
677 reason = "return type should have array as 2nd element",
678 issue = "90091"
679 )]
680 #[inline]
681 pub fn split_array_mut<const M: usize>(&mut self) -> (&mut [T; M], &mut [T]) {
682 (&mut self[..]).split_first_chunk_mut::<M>().unwrap()
683 }
684
685 /// Divides one array reference into two at an index from the end.
686 ///
687 /// The first will contain all indices from `[0, N - M)` (excluding
688 /// the index `N - M` itself) and the second will contain all
689 /// indices from `[N - M, N)` (excluding the index `N` itself).
690 ///
691 /// # Panics
692 ///
693 /// Panics if `M > N`.
694 ///
695 /// # Examples
696 ///
697 /// ```
698 /// #![feature(split_array)]
699 ///
700 /// let v = [1, 2, 3, 4, 5, 6];
701 ///
702 /// {
703 /// let (left, right) = v.rsplit_array_ref::<0>();
704 /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
705 /// assert_eq!(right, &[]);
706 /// }
707 ///
708 /// {
709 /// let (left, right) = v.rsplit_array_ref::<2>();
710 /// assert_eq!(left, &[1, 2, 3, 4]);
711 /// assert_eq!(right, &[5, 6]);
712 /// }
713 ///
714 /// {
715 /// let (left, right) = v.rsplit_array_ref::<6>();
716 /// assert_eq!(left, &[]);
717 /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
718 /// }
719 /// ```
720 #[unstable(
721 feature = "split_array",
722 reason = "return type should have array as 2nd element",
723 issue = "90091"
724 )]
725 #[inline]
726 pub fn rsplit_array_ref<const M: usize>(&self) -> (&[T], &[T; M]) {
727 (&self[..]).split_last_chunk::<M>().unwrap()
728 }
729
730 /// Divides one mutable array reference into two at an index from the end.
731 ///
732 /// The first will contain all indices from `[0, N - M)` (excluding
733 /// the index `N - M` itself) and the second will contain all
734 /// indices from `[N - M, N)` (excluding the index `N` itself).
735 ///
736 /// # Panics
737 ///
738 /// Panics if `M > N`.
739 ///
740 /// # Examples
741 ///
742 /// ```
743 /// #![feature(split_array)]
744 ///
745 /// let mut v = [1, 0, 3, 0, 5, 6];
746 /// let (left, right) = v.rsplit_array_mut::<4>();
747 /// assert_eq!(left, &mut [1, 0]);
748 /// assert_eq!(right, &mut [3, 0, 5, 6][..]);
749 /// left[1] = 2;
750 /// right[1] = 4;
751 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
752 /// ```
753 #[unstable(
754 feature = "split_array",
755 reason = "return type should have array as 2nd element",
756 issue = "90091"
757 )]
758 #[inline]
759 pub fn rsplit_array_mut<const M: usize>(&mut self) -> (&mut [T], &mut [T; M]) {
760 (&mut self[..]).split_last_chunk_mut::<M>().unwrap()
761 }
762}
763
764/// Populate an array from the first `N` elements of `iter`
765///
766/// # Panics
767///
768/// If the iterator doesn't actually have enough items.
769///
770/// By depending on `TrustedLen`, however, we can do that check up-front (where
771/// it easily optimizes away) so it doesn't impact the loop that fills the array.
772#[inline]
773fn from_trusted_iterator<T, const N: usize>(iter: impl UncheckedIterator<Item = T>) -> [T; N] {
774 try_from_trusted_iterator(iter:iter.map(NeverShortCircuit)).0
775}
776
777#[inline]
778fn try_from_trusted_iterator<T, R, const N: usize>(
779 iter: impl UncheckedIterator<Item = R>,
780) -> ChangeOutputType<R, [T; N]>
781where
782 R: Try<Output = T>,
783 R::Residual: Residual<[T; N]>,
784{
785 assert!(iter.size_hint().0 >= N);
786 fn next<T>(mut iter: impl UncheckedIterator<Item = T>) -> impl FnMut(usize) -> T {
787 move |_| {
788 // SAFETY: We know that `from_fn` will call this at most N times,
789 // and we checked to ensure that we have at least that many items.
790 unsafe { iter.next_unchecked() }
791 }
792 }
793
794 try_from_fn(cb:next(iter))
795}
796
797/// Version of [`try_from_fn`] using a passed-in slice in order to avoid
798/// needing to monomorphize for every array length.
799///
800/// This takes a generator rather than an iterator so that *at the type level*
801/// it never needs to worry about running out of items. When combined with
802/// an infallible `Try` type, that means the loop canonicalizes easily, allowing
803/// it to optimize well.
804///
805/// It would be *possible* to unify this and [`iter_next_chunk_erased`] into one
806/// function that does the union of both things, but last time it was that way
807/// it resulted in poor codegen from the "are there enough source items?" checks
808/// not optimizing away. So if you give it a shot, make sure to watch what
809/// happens in the codegen tests.
810#[inline]
811fn try_from_fn_erased<T, R>(
812 buffer: &mut [MaybeUninit<T>],
813 mut generator: impl FnMut(usize) -> R,
814) -> ControlFlow<R::Residual>
815where
816 R: Try<Output = T>,
817{
818 let mut guard: Guard<'_, T> = Guard { array_mut: buffer, initialized: 0 };
819
820 while guard.initialized < guard.array_mut.len() {
821 let item: T = generator(guard.initialized).branch()?;
822
823 // SAFETY: The loop condition ensures we have space to push the item
824 unsafe { guard.push_unchecked(item) };
825 }
826
827 mem::forget(guard);
828 ControlFlow::Continue(())
829}
830
831/// Panic guard for incremental initialization of arrays.
832///
833/// Disarm the guard with `mem::forget` once the array has been initialized.
834///
835/// # Safety
836///
837/// All write accesses to this structure are unsafe and must maintain a correct
838/// count of `initialized` elements.
839///
840/// To minimize indirection fields are still pub but callers should at least use
841/// `push_unchecked` to signal that something unsafe is going on.
842struct Guard<'a, T> {
843 /// The array to be initialized.
844 pub array_mut: &'a mut [MaybeUninit<T>],
845 /// The number of items that have been initialized so far.
846 pub initialized: usize,
847}
848
849impl<T> Guard<'_, T> {
850 /// Adds an item to the array and updates the initialized item counter.
851 ///
852 /// # Safety
853 ///
854 /// No more than N elements must be initialized.
855 #[inline]
856 pub unsafe fn push_unchecked(&mut self, item: T) {
857 // SAFETY: If `initialized` was correct before and the caller does not
858 // invoke this method more than N times then writes will be in-bounds
859 // and slots will not be initialized more than once.
860 unsafe {
861 self.array_mut.get_unchecked_mut(self.initialized).write(val:item);
862 self.initialized = self.initialized.unchecked_add(1);
863 }
864 }
865}
866
867impl<T> Drop for Guard<'_, T> {
868 fn drop(&mut self) {
869 debug_assert!(self.initialized <= self.array_mut.len());
870
871 // SAFETY: this slice will contain only initialized objects.
872 unsafe {
873 crate::ptr::drop_in_place(to_drop:MaybeUninit::slice_assume_init_mut(
874 self.array_mut.get_unchecked_mut(..self.initialized),
875 ));
876 }
877 }
878}
879
880/// Pulls `N` items from `iter` and returns them as an array. If the iterator
881/// yields fewer than `N` items, `Err` is returned containing an iterator over
882/// the already yielded items.
883///
884/// Since the iterator is passed as a mutable reference and this function calls
885/// `next` at most `N` times, the iterator can still be used afterwards to
886/// retrieve the remaining items.
887///
888/// If `iter.next()` panicks, all items already yielded by the iterator are
889/// dropped.
890///
891/// Used for [`Iterator::next_chunk`].
892#[inline]
893pub(crate) fn iter_next_chunk<T, const N: usize>(
894 iter: &mut impl Iterator<Item = T>,
895) -> Result<[T; N], IntoIter<T, N>> {
896 let mut array: [MaybeUninit; N] = MaybeUninit::uninit_array::<N>();
897 let r: Result<(), usize> = iter_next_chunk_erased(&mut array, iter);
898 match r {
899 Ok(()) => {
900 // SAFETY: All elements of `array` were populated.
901 Ok(unsafe { MaybeUninit::array_assume_init(array) })
902 }
903 Err(initialized: usize) => {
904 // SAFETY: Only the first `initialized` elements were populated
905 Err(unsafe { IntoIter::new_unchecked(buffer:array, initialized:0..initialized) })
906 }
907 }
908}
909
910/// Version of [`iter_next_chunk`] using a passed-in slice in order to avoid
911/// needing to monomorphize for every array length.
912///
913/// Unfortunately this loop has two exit conditions, the buffer filling up
914/// or the iterator running out of items, making it tend to optimize poorly.
915#[inline]
916fn iter_next_chunk_erased<T>(
917 buffer: &mut [MaybeUninit<T>],
918 iter: &mut impl Iterator<Item = T>,
919) -> Result<(), usize> {
920 let mut guard: Guard<'_, T> = Guard { array_mut: buffer, initialized: 0 };
921 while guard.initialized < guard.array_mut.len() {
922 let Some(item: T) = iter.next() else {
923 // Unlike `try_from_fn_erased`, we want to keep the partial results,
924 // so we need to defuse the guard instead of using `?`.
925 let initialized: usize = guard.initialized;
926 mem::forget(guard);
927 return Err(initialized);
928 };
929
930 // SAFETY: The loop condition ensures we have space to push the item
931 unsafe { guard.push_unchecked(item) };
932 }
933
934 mem::forget(guard);
935 Ok(())
936}
937