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