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