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