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