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