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