]> git.lizzy.rs Git - rust.git/blob - library/core/src/array/mod.rs
Stabilize File::options()
[rust.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 // The Default impls cannot be done with const generics because `[T; 0]` doesn't
334 // require Default to be implemented, and having different impl blocks for
335 // different numbers isn't supported yet.
336
337 macro_rules! array_impl_default {
338     {$n:expr, $t:ident $($ts:ident)*} => {
339         #[stable(since = "1.4.0", feature = "array_default")]
340         impl<T> Default for [T; $n] where T: Default {
341             fn default() -> [T; $n] {
342                 [$t::default(), $($ts::default()),*]
343             }
344         }
345         array_impl_default!{($n - 1), $($ts)*}
346     };
347     {$n:expr,} => {
348         #[stable(since = "1.4.0", feature = "array_default")]
349         #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
350         impl<T> const Default for [T; $n] {
351             fn default() -> [T; $n] { [] }
352         }
353     };
354 }
355
356 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}
357
358 #[lang = "array"]
359 impl<T, const N: usize> [T; N] {
360     /// Returns an array of the same size as `self`, with function `f` applied to each element
361     /// in order.
362     ///
363     /// If you don't necessarily need a new fixed-size array, consider using
364     /// [`Iterator::map`] instead.
365     ///
366     ///
367     /// # Note on performance and stack usage
368     ///
369     /// Unfortunately, usages of this method are currently not always optimized
370     /// as well as they could be. This mainly concerns large arrays, as mapping
371     /// over small arrays seem to be optimized just fine. Also note that in
372     /// debug mode (i.e. without any optimizations), this method can use a lot
373     /// of stack space (a few times the size of the array or more).
374     ///
375     /// Therefore, in performance-critical code, try to avoid using this method
376     /// on large arrays or check the emitted code. Also try to avoid chained
377     /// maps (e.g. `arr.map(...).map(...)`).
378     ///
379     /// In many cases, you can instead use [`Iterator::map`] by calling `.iter()`
380     /// or `.into_iter()` on your array. `[T; N]::map` is only necessary if you
381     /// really need a new array of the same size as the result. Rust's lazy
382     /// iterators tend to get optimized very well.
383     ///
384     ///
385     /// # Examples
386     ///
387     /// ```
388     /// let x = [1, 2, 3];
389     /// let y = x.map(|v| v + 1);
390     /// assert_eq!(y, [2, 3, 4]);
391     ///
392     /// let x = [1, 2, 3];
393     /// let mut temp = 0;
394     /// let y = x.map(|v| { temp += 1; v * temp });
395     /// assert_eq!(y, [1, 4, 9]);
396     ///
397     /// let x = ["Ferris", "Bueller's", "Day", "Off"];
398     /// let y = x.map(|v| v.len());
399     /// assert_eq!(y, [6, 9, 3, 3]);
400     /// ```
401     #[stable(feature = "array_map", since = "1.55.0")]
402     pub fn map<F, U>(self, f: F) -> [U; N]
403     where
404         F: FnMut(T) -> U,
405     {
406         // SAFETY: we know for certain that this iterator will yield exactly `N`
407         // items.
408         unsafe { collect_into_array_unchecked(&mut IntoIterator::into_iter(self).map(f)) }
409     }
410
411     /// 'Zips up' two arrays into a single array of pairs.
412     ///
413     /// `zip()` returns a new array where every element is a tuple where the
414     /// first element comes from the first array, and the second element comes
415     /// from the second array. In other words, it zips two arrays together,
416     /// into a single one.
417     ///
418     /// # Examples
419     ///
420     /// ```
421     /// #![feature(array_zip)]
422     /// let x = [1, 2, 3];
423     /// let y = [4, 5, 6];
424     /// let z = x.zip(y);
425     /// assert_eq!(z, [(1, 4), (2, 5), (3, 6)]);
426     /// ```
427     #[unstable(feature = "array_zip", issue = "80094")]
428     pub fn zip<U>(self, rhs: [U; N]) -> [(T, U); N] {
429         let mut iter = IntoIterator::into_iter(self).zip(rhs);
430
431         // SAFETY: we know for certain that this iterator will yield exactly `N`
432         // items.
433         unsafe { collect_into_array_unchecked(&mut iter) }
434     }
435
436     /// Returns a slice containing the entire array. Equivalent to `&s[..]`.
437     #[stable(feature = "array_as_slice", since = "1.57.0")]
438     pub const fn as_slice(&self) -> &[T] {
439         self
440     }
441
442     /// Returns a mutable slice containing the entire array. Equivalent to
443     /// `&mut s[..]`.
444     #[stable(feature = "array_as_slice", since = "1.57.0")]
445     pub fn as_mut_slice(&mut self) -> &mut [T] {
446         self
447     }
448
449     /// Borrows each element and returns an array of references with the same
450     /// size as `self`.
451     ///
452     ///
453     /// # Example
454     ///
455     /// ```
456     /// #![feature(array_methods)]
457     ///
458     /// let floats = [3.1, 2.7, -1.0];
459     /// let float_refs: [&f64; 3] = floats.each_ref();
460     /// assert_eq!(float_refs, [&3.1, &2.7, &-1.0]);
461     /// ```
462     ///
463     /// This method is particularly useful if combined with other methods, like
464     /// [`map`](#method.map). This way, you can avoid moving the original
465     /// array if its elements are not [`Copy`].
466     ///
467     /// ```
468     /// #![feature(array_methods)]
469     ///
470     /// let strings = ["Ferris".to_string(), "♥".to_string(), "Rust".to_string()];
471     /// let is_ascii = strings.each_ref().map(|s| s.is_ascii());
472     /// assert_eq!(is_ascii, [true, false, true]);
473     ///
474     /// // We can still access the original array: it has not been moved.
475     /// assert_eq!(strings.len(), 3);
476     /// ```
477     #[unstable(feature = "array_methods", issue = "76118")]
478     pub fn each_ref(&self) -> [&T; N] {
479         // SAFETY: we know for certain that this iterator will yield exactly `N`
480         // items.
481         unsafe { collect_into_array_unchecked(&mut self.iter()) }
482     }
483
484     /// Borrows each element mutably and returns an array of mutable references
485     /// with the same size as `self`.
486     ///
487     ///
488     /// # Example
489     ///
490     /// ```
491     /// #![feature(array_methods)]
492     ///
493     /// let mut floats = [3.1, 2.7, -1.0];
494     /// let float_refs: [&mut f64; 3] = floats.each_mut();
495     /// *float_refs[0] = 0.0;
496     /// assert_eq!(float_refs, [&mut 0.0, &mut 2.7, &mut -1.0]);
497     /// assert_eq!(floats, [0.0, 2.7, -1.0]);
498     /// ```
499     #[unstable(feature = "array_methods", issue = "76118")]
500     pub fn each_mut(&mut self) -> [&mut T; N] {
501         // SAFETY: we know for certain that this iterator will yield exactly `N`
502         // items.
503         unsafe { collect_into_array_unchecked(&mut self.iter_mut()) }
504     }
505
506     /// Divides one array reference into two at an index.
507     ///
508     /// The first will contain all indices from `[0, M)` (excluding
509     /// the index `M` itself) and the second will contain all
510     /// indices from `[M, N)` (excluding the index `N` itself).
511     ///
512     /// # Panics
513     ///
514     /// Panics if `M > N`.
515     ///
516     /// # Examples
517     ///
518     /// ```
519     /// #![feature(split_array)]
520     ///
521     /// let v = [1, 2, 3, 4, 5, 6];
522     ///
523     /// {
524     ///    let (left, right) = v.split_array_ref::<0>();
525     ///    assert_eq!(left, &[]);
526     ///    assert_eq!(right, &[1, 2, 3, 4, 5, 6]);
527     /// }
528     ///
529     /// {
530     ///     let (left, right) = v.split_array_ref::<2>();
531     ///     assert_eq!(left, &[1, 2]);
532     ///     assert_eq!(right, &[3, 4, 5, 6]);
533     /// }
534     ///
535     /// {
536     ///     let (left, right) = v.split_array_ref::<6>();
537     ///     assert_eq!(left, &[1, 2, 3, 4, 5, 6]);
538     ///     assert_eq!(right, &[]);
539     /// }
540     /// ```
541     #[unstable(
542         feature = "split_array",
543         reason = "return type should have array as 2nd element",
544         issue = "90091"
545     )]
546     #[inline]
547     pub fn split_array_ref<const M: usize>(&self) -> (&[T; M], &[T]) {
548         (&self[..]).split_array_ref::<M>()
549     }
550
551     /// Divides one mutable array reference into two at an index.
552     ///
553     /// The first will contain all indices from `[0, M)` (excluding
554     /// the index `M` itself) and the second will contain all
555     /// indices from `[M, N)` (excluding the index `N` itself).
556     ///
557     /// # Panics
558     ///
559     /// Panics if `M > N`.
560     ///
561     /// # Examples
562     ///
563     /// ```
564     /// #![feature(split_array)]
565     ///
566     /// let mut v = [1, 0, 3, 0, 5, 6];
567     /// let (left, right) = v.split_array_mut::<2>();
568     /// assert_eq!(left, &mut [1, 0][..]);
569     /// assert_eq!(right, &mut [3, 0, 5, 6]);
570     /// left[1] = 2;
571     /// right[1] = 4;
572     /// assert_eq!(v, [1, 2, 3, 4, 5, 6]);
573     /// ```
574     #[unstable(
575         feature = "split_array",
576         reason = "return type should have array as 2nd element",
577         issue = "90091"
578     )]
579     #[inline]
580     pub fn split_array_mut<const M: usize>(&mut self) -> (&mut [T; M], &mut [T]) {
581         (&mut self[..]).split_array_mut::<M>()
582     }
583 }
584
585 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
586 /// yields fewer than `N` items, this function exhibits undefined behavior.
587 ///
588 /// See [`collect_into_array`] for more information.
589 ///
590 ///
591 /// # Safety
592 ///
593 /// It is up to the caller to guarantee that `iter` yields at least `N` items.
594 /// Violating this condition causes undefined behavior.
595 unsafe fn collect_into_array_rslt_unchecked<E, I, T, const N: usize>(
596     iter: &mut I,
597 ) -> Result<[T; N], E>
598 where
599     // Note: `TrustedLen` here is somewhat of an experiment. This is just an
600     // internal function, so feel free to remove if this bound turns out to be a
601     // bad idea. In that case, remember to also remove the lower bound
602     // `debug_assert!` below!
603     I: Iterator<Item = Result<T, E>> + TrustedLen,
604 {
605     debug_assert!(N <= iter.size_hint().1.unwrap_or(usize::MAX));
606     debug_assert!(N <= iter.size_hint().0);
607
608     // SAFETY: covered by the function contract.
609     unsafe { collect_into_array(iter).unwrap_unchecked() }
610 }
611
612 // Infallible version of `collect_into_array_rslt_unchecked`.
613 unsafe fn collect_into_array_unchecked<I, const N: usize>(iter: &mut I) -> [I::Item; N]
614 where
615     I: Iterator + TrustedLen,
616 {
617     let mut map = iter.map(Ok::<_, Infallible>);
618
619     // SAFETY: The same safety considerations w.r.t. the iterator length
620     // apply for `collect_into_array_rslt_unchecked` as for
621     // `collect_into_array_unchecked`
622     match unsafe { collect_into_array_rslt_unchecked(&mut map) } {
623         Ok(array) => array,
624     }
625 }
626
627 /// Pulls `N` items from `iter` and returns them as an array. If the iterator
628 /// yields fewer than `N` items, `None` is returned and all already yielded
629 /// items are dropped.
630 ///
631 /// Since the iterator is passed as a mutable reference and this function calls
632 /// `next` at most `N` times, the iterator can still be used afterwards to
633 /// retrieve the remaining items.
634 ///
635 /// If `iter.next()` panicks, all items already yielded by the iterator are
636 /// dropped.
637 fn collect_into_array<E, I, T, const N: usize>(iter: &mut I) -> Option<Result<[T; N], E>>
638 where
639     I: Iterator<Item = Result<T, E>>,
640 {
641     if N == 0 {
642         // SAFETY: An empty array is always inhabited and has no validity invariants.
643         return unsafe { Some(Ok(mem::zeroed())) };
644     }
645
646     struct Guard<'a, T, const N: usize> {
647         array_mut: &'a mut [MaybeUninit<T>; N],
648         initialized: usize,
649     }
650
651     impl<T, const N: usize> Drop for Guard<'_, T, N> {
652         fn drop(&mut self) {
653             debug_assert!(self.initialized <= N);
654
655             // SAFETY: this slice will contain only initialized objects.
656             unsafe {
657                 crate::ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(
658                     &mut self.array_mut.get_unchecked_mut(..self.initialized),
659                 ));
660             }
661         }
662     }
663
664     let mut array = MaybeUninit::uninit_array::<N>();
665     let mut guard = Guard { array_mut: &mut array, initialized: 0 };
666
667     while let Some(item_rslt) = iter.next() {
668         let item = match item_rslt {
669             Err(err) => {
670                 return Some(Err(err));
671             }
672             Ok(elem) => elem,
673         };
674
675         // SAFETY: `guard.initialized` starts at 0, is increased by one in the
676         // loop and the loop is aborted once it reaches N (which is
677         // `array.len()`).
678         unsafe {
679             guard.array_mut.get_unchecked_mut(guard.initialized).write(item);
680         }
681         guard.initialized += 1;
682
683         // Check if the whole array was initialized.
684         if guard.initialized == N {
685             mem::forget(guard);
686
687             // SAFETY: the condition above asserts that all elements are
688             // initialized.
689             let out = unsafe { MaybeUninit::array_assume_init(array) };
690             return Some(Ok(out));
691         }
692     }
693
694     // This is only reached if the iterator is exhausted before
695     // `guard.initialized` reaches `N`. Also note that `guard` is dropped here,
696     // dropping all already initialized elements.
697     None
698 }