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