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