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