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 /// Unfortunately, usages of this method are currently not always optimized
546 /// as well as they could be. This mainly concerns large arrays, as mapping
547 /// over small arrays seem to be optimized just fine. Also note that in
548 /// debug mode (i.e. without any optimizations), this method can use a lot
549 /// of stack space (a few times the size of the array or more).
550 ///
551 /// Therefore, in performance-critical code, try to avoid using this method
552 /// on large arrays or check the emitted code. Also try to avoid chained
553 /// maps (e.g. `arr.map(...).map(...)`).
554 ///
555 /// In many cases, you can instead use [`Iterator::map`] by calling `.iter()`
556 /// or `.into_iter()` on your array. `[T; N]::map` is only necessary if you
557 /// really need a new array of the same size as the result. Rust's lazy
558 /// iterators tend to get optimized very well.
559 ///
560 ///
561 /// # Examples
562 ///
563 /// ```
564 /// let x = [1, 2, 3];
565 /// let y = x.map(|v| v + 1);
566 /// assert_eq!(y, [2, 3, 4]);
567 ///
568 /// let x = [1, 2, 3];
569 /// let mut temp = 0;
570 /// let y = x.map(|v| { temp += 1; v * temp });
571 /// assert_eq!(y, [1, 4, 9]);
572 ///
573 /// let x = ["Ferris", "Bueller's", "Day", "Off"];
574 /// let y = x.map(|v| v.len());
575 /// assert_eq!(y, [6, 9, 3, 3]);
576 /// ```
577 #[must_use]
578 #[stable(feature = "array_map", since = "1.55.0")]
579 #[rustc_const_unstable(feature = "const_array", issue = "147606")]
580 pub const fn map<F, U>(self, f: F) -> [U; N]
581 where
582 F: [const] FnMut(T) -> U + [const] Destruct,
583 U: [const] Destruct,
584 T: [const] Destruct,
585 {
586 self.try_map(NeverShortCircuit::wrap_mut_1(f)).0
587 }
588
589 /// A fallible function `f` applied to each element on array `self` in order to
590 /// return an array the same size as `self` or the first error encountered.
591 ///
592 /// The return type of this function depends on the return type of the closure.
593 /// If you return `Result<T, E>` from the closure, you'll get a `Result<[T; N], E>`.
594 /// If you return `Option<T>` from the closure, you'll get an `Option<[T; N]>`.
595 ///
596 /// # Examples
597 ///
598 /// ```
599 /// #![feature(array_try_map)]
600 ///
601 /// let a = ["1", "2", "3"];
602 /// let b = a.try_map(|v| v.parse::<u32>()).unwrap().map(|v| v + 1);
603 /// assert_eq!(b, [2, 3, 4]);
604 ///
605 /// let a = ["1", "2a", "3"];
606 /// let b = a.try_map(|v| v.parse::<u32>());
607 /// assert!(b.is_err());
608 ///
609 /// use std::num::NonZero;
610 ///
611 /// let z = [1, 2, 0, 3, 4];
612 /// assert_eq!(z.try_map(NonZero::new), None);
613 ///
614 /// let a = [1, 2, 3];
615 /// let b = a.try_map(NonZero::new);
616 /// let c = b.map(|x| x.map(NonZero::get));
617 /// assert_eq!(c, Some(a));
618 /// ```
619 #[unstable(feature = "array_try_map", issue = "79711")]
620 #[rustc_const_unstable(feature = "array_try_map", issue = "79711")]
621 pub const fn try_map<R>(
622 self,
623 mut f: impl [const] FnMut(T) -> R + [const] Destruct,
624 ) -> ChangeOutputType<R, [R::Output; N]>
625 where
626 R: [const] Try<Residual: [const] Residual<[R::Output; N]>, Output: [const] Destruct>,
627 T: [const] Destruct,
628 {
629 let mut me = ManuallyDrop::new(self);
630 // SAFETY: try_from_fn calls `f` N times.
631 let mut f = unsafe { drain::Drain::new(&mut me, &mut f) };
632 try_from_fn(&mut f)
633 }
634
635 /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
636 #[stable(feature = "array_as_slice", since = "1.57.0")]
637 #[rustc_const_stable(feature = "array_as_slice", since = "1.57.0")]
638 pub const fn as_slice(&self) -> &[T] {
639 self
640 }
641
642 /// Returns a mutable slice containing the entire array. Equivalent to
643 /// `&mut s[..]`.
644 #[stable(feature = "array_as_slice", since = "1.57.0")]
645 #[rustc_const_stable(feature = "const_array_as_mut_slice", since = "1.89.0")]
646 pub const fn as_mut_slice(&mut self) -> &mut [T] {
647 self
648 }
649
650 /// Borrows each element and returns an array of references with the same
651 /// size as `self`.
652 ///
653 ///
654 /// # Example
655 ///
656 /// ```
657 /// let floats = [3.1, 2.7, -1.0];
658 /// let float_refs: [&f64; 3] = floats.each_ref();
659 /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
660 /// ```
661 ///
662 /// This method is particularly useful if combined with other methods, like
663 /// [`map`](#method.map). This way, you can avoid moving the original
664 /// array if its elements are not [`Copy`].
665 ///
666 /// ```
667 /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
668 /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
669 /// assert_eq!(is_ascii, [true, false, true]);
670 ///
671 /// // We can still access the original array: it has not been moved.
672 /// assert_eq!(strings.len(), 3);
673 /// ```
674 #[stable(feature = "array_methods", since = "1.77.0")]
675 #[rustc_const_stable(feature = "const_array_each_ref", since = "1.91.0")]
676 #[cfg(not(feature = "ferrocene_subset"))]
677 pub const fn each_ref(&self) -> [&T; N] {
678 let mut buf = [null::<T>(); N];
679
680 // 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.
681 let mut i = 0;
682 while i < N {
683 buf[i] = &raw const self[i];
684
685 i += 1;
686 }
687
688 // SAFETY: `*const T` has the same layout as `&T`, and we've also initialised each pointer as a valid reference.
689 unsafe { transmute_unchecked(buf) }
690 }
691
692 /// Borrows each element mutably and returns an array of mutable references
693 /// with the same size as `self`.
694 ///
695 ///
696 /// # Example
697 ///
698 /// ```
699 ///
700 /// let mut floats = [3.1, 2.7, -1.0];
701 /// let float_refs: [&mut f64; 3] = floats.each_mut();
702 /// *float_refs[0] = 0.0;
703 /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
704 /// assert_eq!(floats, [0.0, 2.7, -1.0]);
705 /// ```
706 #[stable(feature = "array_methods", since = "1.77.0")]
707 #[rustc_const_stable(feature = "const_array_each_ref", since = "1.91.0")]
708 #[cfg(not(feature = "ferrocene_subset"))]
709 pub const fn each_mut(&mut self) -> [&mut T; N] {
710 let mut buf = [null_mut::<T>(); N];
711
712 // 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.
713 let mut i = 0;
714 while i < N {
715 buf[i] = &raw mut self[i];
716
717 i += 1;
718 }
719
720 // SAFETY: `*mut T` has the same layout as `&mut T`, and we've also initialised each pointer as a valid reference.
721 unsafe { transmute_unchecked(buf) }
722 }
723
724 /// Divides one array reference into two at an index.
725 ///
726 /// The first will contain all indices from `[0, M)` (excluding
727 /// the index `M` itself) and the second will contain all
728 /// indices from `[M, N)` (excluding the index `N` itself).
729 ///
730 /// # Panics
731 ///
732 /// Panics if `M > N`.
733 ///
734 /// # Examples
735 ///
736 /// ```
737 /// #![feature(split_array)]
738 ///
739 /// let v = [1, 2, 3, 4, 5, 6];
740 ///
741 /// {
742 /// let (left, right) = v.split_array_ref::<0>();
743 /// assert_eq!(left, &[]);
744 /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
745 /// }
746 ///
747 /// {
748 /// let (left, right) = v.split_array_ref::<2>();
749 /// assert_eq!(left, &[1, 2]);
750 /// assert_eq!(right, &[3, 4, 5, 6]);
751 /// }
752 ///
753 /// {
754 /// let (left, right) = v.split_array_ref::<6>();
755 /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
756 /// assert_eq!(right, &[]);
757 /// }
758 /// ```
759 #[unstable(
760 feature = "split_array",
761 reason = "return type should have array as 2nd element",
762 issue = "90091"
763 )]
764 #[inline]
765 #[cfg(not(feature = "ferrocene_subset"))]
766 pub fn split_array_ref<const M: usize>(&self) -> (&[T; M], &[T]) {
767 self.split_first_chunk::<M>().unwrap()
768 }
769
770 /// Divides one mutable array reference into two at an index.
771 ///
772 /// The first will contain all indices from `[0, M)` (excluding
773 /// the index `M` itself) and the second will contain all
774 /// indices from `[M, N)` (excluding the index `N` itself).
775 ///
776 /// # Panics
777 ///
778 /// Panics if `M > N`.
779 ///
780 /// # Examples
781 ///
782 /// ```
783 /// #![feature(split_array)]
784 ///
785 /// let mut v = [1, 0, 3, 0, 5, 6];
786 /// let (left, right) = v.split_array_mut::<2>();
787 /// assert_eq!(left, &mut [1, 0][..]);
788 /// assert_eq!(right, &mut [3, 0, 5, 6]);
789 /// left[1] = 2;
790 /// right[1] = 4;
791 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
792 /// ```
793 #[unstable(
794 feature = "split_array",
795 reason = "return type should have array as 2nd element",
796 issue = "90091"
797 )]
798 #[inline]
799 #[cfg(not(feature = "ferrocene_subset"))]
800 pub fn split_array_mut<const M: usize>(&mut self) -> (&mut [T; M], &mut [T]) {
801 self.split_first_chunk_mut::<M>().unwrap()
802 }
803
804 /// Divides one array reference into two at an index from the end.
805 ///
806 /// The first will contain all indices from `[0, N - M)` (excluding
807 /// the index `N - M` itself) and the second will contain all
808 /// indices from `[N - M, N)` (excluding the index `N` itself).
809 ///
810 /// # Panics
811 ///
812 /// Panics if `M > N`.
813 ///
814 /// # Examples
815 ///
816 /// ```
817 /// #![feature(split_array)]
818 ///
819 /// let v = [1, 2, 3, 4, 5, 6];
820 ///
821 /// {
822 /// let (left, right) = v.rsplit_array_ref::<0>();
823 /// assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
824 /// assert_eq!(right, &[]);
825 /// }
826 ///
827 /// {
828 /// let (left, right) = v.rsplit_array_ref::<2>();
829 /// assert_eq!(left, &[1, 2, 3, 4]);
830 /// assert_eq!(right, &[5, 6]);
831 /// }
832 ///
833 /// {
834 /// let (left, right) = v.rsplit_array_ref::<6>();
835 /// assert_eq!(left, &[]);
836 /// assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
837 /// }
838 /// ```
839 #[unstable(
840 feature = "split_array",
841 reason = "return type should have array as 2nd element",
842 issue = "90091"
843 )]
844 #[inline]
845 #[cfg(not(feature = "ferrocene_subset"))]
846 pub fn rsplit_array_ref<const M: usize>(&self) -> (&[T], &[T; M]) {
847 self.split_last_chunk::<M>().unwrap()
848 }
849
850 /// Divides one mutable array reference into two at an index from the end.
851 ///
852 /// The first will contain all indices from `[0, N - M)` (excluding
853 /// the index `N - M` itself) and the second will contain all
854 /// indices from `[N - M, N)` (excluding the index `N` itself).
855 ///
856 /// # Panics
857 ///
858 /// Panics if `M > N`.
859 ///
860 /// # Examples
861 ///
862 /// ```
863 /// #![feature(split_array)]
864 ///
865 /// let mut v = [1, 0, 3, 0, 5, 6];
866 /// let (left, right) = v.rsplit_array_mut::<4>();
867 /// assert_eq!(left, &mut [1, 0]);
868 /// assert_eq!(right, &mut [3, 0, 5, 6][..]);
869 /// left[1] = 2;
870 /// right[1] = 4;
871 /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
872 /// ```
873 #[unstable(
874 feature = "split_array",
875 reason = "return type should have array as 2nd element",
876 issue = "90091"
877 )]
878 #[inline]
879 #[cfg(not(feature = "ferrocene_subset"))]
880 pub fn rsplit_array_mut<const M: usize>(&mut self) -> (&mut [T], &mut [T; M]) {
881 self.split_last_chunk_mut::<M>().unwrap()
882 }
883}
884
885/// Populate an array from the first `N` elements of `iter`
886///
887/// # Panics
888///
889/// If the iterator doesn't actually have enough items.
890///
891/// By depending on `TrustedLen`, however, we can do that check up-front (where
892/// it easily optimizes away) so it doesn't impact the loop that fills the array.
893#[inline]
894fn from_trusted_iterator<T, const N: usize>(iter: impl UncheckedIterator<Item = T>) -> [T; N] {
895 try_from_trusted_iterator(iter.map(NeverShortCircuit)).0
896}
897
898#[inline]
899fn try_from_trusted_iterator<T, R, const N: usize>(
900 iter: impl UncheckedIterator<Item = R>,
901) -> ChangeOutputType<R, [T; N]>
902where
903 R: Try<Output = T>,
904 R::Residual: Residual<[T; N]>,
905{
906 assert!(iter.size_hint().0 >= N);
907 fn next<T>(mut iter: impl UncheckedIterator<Item = T>) -> impl FnMut(usize) -> T {
908 move |_| {
909 // SAFETY: We know that `from_fn` will call this at most N times,
910 // and we checked to ensure that we have at least that many items.
911 unsafe { iter.next_unchecked() }
912 }
913 }
914
915 try_from_fn(next(iter))
916}
917
918/// Version of [`try_from_fn`] using a passed-in slice in order to avoid
919/// needing to monomorphize for every array length.
920///
921/// This takes a generator rather than an iterator so that *at the type level*
922/// it never needs to worry about running out of items. When combined with
923/// an infallible `Try` type, that means the loop canonicalizes easily, allowing
924/// it to optimize well.
925///
926/// It would be *possible* to unify this and [`iter_next_chunk_erased`] into one
927/// function that does the union of both things, but last time it was that way
928/// it resulted in poor codegen from the "are there enough source items?" checks
929/// not optimizing away. So if you give it a shot, make sure to watch what
930/// happens in the codegen tests.
931#[inline]
932#[rustc_const_unstable(feature = "array_try_from_fn", issue = "89379")]
933const fn try_from_fn_erased<R: [const] Try<Output: [const] Destruct>>(
934 buffer: &mut [MaybeUninit<R::Output>],
935 mut generator: impl [const] FnMut(usize) -> R + [const] Destruct,
936) -> ControlFlow<R::Residual> {
937 let mut guard = Guard { array_mut: buffer, initialized: 0 };
938
939 while guard.initialized < guard.array_mut.len() {
940 let item = generator(guard.initialized).branch()?;
941
942 // SAFETY: The loop condition ensures we have space to push the item
943 unsafe { guard.push_unchecked(item) };
944 }
945
946 mem::forget(guard);
947 ControlFlow::Continue(())
948}
949
950/// Panic guard for incremental initialization of arrays.
951///
952/// Disarm the guard with `mem::forget` once the array has been initialized.
953///
954/// # Safety
955///
956/// All write accesses to this structure are unsafe and must maintain a correct
957/// count of `initialized` elements.
958///
959/// To minimize indirection, fields are still pub but callers should at least use
960/// `push_unchecked` to signal that something unsafe is going on.
961struct Guard<'a, T> {
962 /// The array to be initialized.
963 pub array_mut: &'a mut [MaybeUninit<T>],
964 /// The number of items that have been initialized so far.
965 pub initialized: usize,
966}
967
968impl<T> Guard<'_, T> {
969 /// Adds an item to the array and updates the initialized item counter.
970 ///
971 /// # Safety
972 ///
973 /// No more than N elements must be initialized.
974 #[inline]
975 #[rustc_const_unstable(feature = "array_try_from_fn", issue = "89379")]
976 pub(crate) const unsafe fn push_unchecked(&mut self, item: T) {
977 // SAFETY: If `initialized` was correct before and the caller does not
978 // invoke this method more than N times, then writes will be in-bounds
979 // and slots will not be initialized more than once.
980 unsafe {
981 self.array_mut.get_unchecked_mut(self.initialized).write(item);
982 self.initialized = self.initialized.unchecked_add(1);
983 }
984 }
985}
986
987#[rustc_const_unstable(feature = "array_try_from_fn", issue = "89379")]
988impl<T: [const] Destruct> const Drop for Guard<'_, T> {
989 #[inline]
990 fn drop(&mut self) {
991 debug_assert!(self.initialized <= self.array_mut.len());
992 // SAFETY: this slice will contain only initialized objects.
993 unsafe {
994 self.array_mut.get_unchecked_mut(..self.initialized).assume_init_drop();
995 }
996 }
997}
998
999/// Pulls `N` items from `iter` and returns them as an array. If the iterator
1000/// yields fewer than `N` items, `Err` is returned containing an iterator over
1001/// the already yielded items.
1002///
1003/// Since the iterator is passed as a mutable reference and this function calls
1004/// `next` at most `N` times, the iterator can still be used afterwards to
1005/// retrieve the remaining items.
1006///
1007/// If `iter.next()` panics, all items already yielded by the iterator are
1008/// dropped.
1009///
1010/// Used for [`Iterator::next_chunk`].
1011#[inline]
1012#[cfg(not(feature = "ferrocene_subset"))]
1013pub(crate) fn iter_next_chunk<T, const N: usize>(
1014 iter: &mut impl Iterator<Item = T>,
1015) -> Result<[T; N], IntoIter<T, N>> {
1016 let mut array = [const { MaybeUninit::uninit() }; N];
1017 let r = iter_next_chunk_erased(&mut array, iter);
1018 match r {
1019 Ok(()) => {
1020 // SAFETY: All elements of `array` were populated.
1021 Ok(unsafe { MaybeUninit::array_assume_init(array) })
1022 }
1023 Err(initialized) => {
1024 // SAFETY: Only the first `initialized` elements were populated
1025 Err(unsafe { IntoIter::new_unchecked(array, 0..initialized) })
1026 }
1027 }
1028}
1029
1030/// Version of [`iter_next_chunk`] using a passed-in slice in order to avoid
1031/// needing to monomorphize for every array length.
1032///
1033/// Unfortunately this loop has two exit conditions, the buffer filling up
1034/// or the iterator running out of items, making it tend to optimize poorly.
1035#[inline]
1036#[cfg(not(feature = "ferrocene_subset"))]
1037fn iter_next_chunk_erased<T>(
1038 buffer: &mut [MaybeUninit<T>],
1039 iter: &mut impl Iterator<Item = T>,
1040) -> Result<(), usize> {
1041 // if `Iterator::next` panics, this guard will drop already initialized items
1042 let mut guard = Guard { array_mut: buffer, initialized: 0 };
1043 while guard.initialized < guard.array_mut.len() {
1044 let Some(item) = iter.next() else {
1045 // Unlike `try_from_fn_erased`, we want to keep the partial results,
1046 // so we need to defuse the guard instead of using `?`.
1047 let initialized = guard.initialized;
1048 mem::forget(guard);
1049 return Err(initialized);
1050 };
1051
1052 // SAFETY: The loop condition ensures we have space to push the item
1053 unsafe { guard.push_unchecked(item) };
1054 }
1055
1056 mem::forget(guard);
1057 Ok(())
1058}
1059
1060/// Ferrocene addition: Hidden module to test crate-internal functionality
1061#[doc(hidden)]
1062#[unstable(feature = "ferrocene_test", issue = "none")]
1063#[cfg(not(feature = "ferrocene_subset"))]
1064pub mod ferrocene_test {
1065 use super::*;
1066
1067 pub fn test_drain_call_once() {
1068 let mut md = ManuallyDrop::new([1, 2, 3, 4, 5]);
1069 let mut f = |c| c + 10;
1070 // SAFETY: is only called once
1071 let mut drain = unsafe { drain::Drain::new(&mut md, &mut f) };
1072 assert_eq!(11, drain.call_once((15,)));
1073 }
1074}