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