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