|
| 1 | +use core::mem::MaybeUninit; |
| 2 | +use core::ptr; |
| 3 | + |
| 4 | +/// Helper struct to build up an array element by element. |
| 5 | +struct ArrayBuilder<T, const N: usize> { |
| 6 | + arr: [MaybeUninit<T>; N], // Invariant: arr[..len] is initialized. |
| 7 | + len: usize, // Invariant: len <= N. |
| 8 | +} |
| 9 | + |
| 10 | +impl<T, const N: usize> ArrayBuilder<T, N> { |
| 11 | + pub fn new() -> Self { |
| 12 | + Self { |
| 13 | + arr: [(); N].map(|_| MaybeUninit::uninit()), |
| 14 | + len: 0, |
| 15 | + } |
| 16 | + } |
| 17 | + |
| 18 | + pub fn push(&mut self, value: T) { |
| 19 | + // We maintain the invariant here that arr[..len] is initialized. |
| 20 | + // Indexing with self.len also ensures self.len < N, and thus <= N after |
| 21 | + // the increment. |
| 22 | + self.arr[self.len] = MaybeUninit::new(value); |
| 23 | + self.len += 1; |
| 24 | + } |
| 25 | + |
| 26 | + pub fn take(&mut self) -> Option<[T; N]> { |
| 27 | + if self.len == N { |
| 28 | + // Take the array, resetting the length back to zero. |
| 29 | + let arr = core::mem::replace(&mut self.arr, [(); N].map(|_| MaybeUninit::uninit())); |
| 30 | + self.len = 0; |
| 31 | + |
| 32 | + // SAFETY: we had len == N, so all elements in arr are initialized. |
| 33 | + Some(unsafe { arr.map(|v| v.assume_init()) }) |
| 34 | + } else { |
| 35 | + None |
| 36 | + } |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +impl<T, const N: usize> Drop for ArrayBuilder<T, N> { |
| 41 | + fn drop(&mut self) { |
| 42 | + unsafe { |
| 43 | + // SAFETY: arr[..len] is initialized, so must be dropped. |
| 44 | + // First we create a pointer to this initialized slice, then drop |
| 45 | + // that slice in-place. The cast from *mut MaybeUninit<T> to *mut T |
| 46 | + // is always sound by the layout guarantees of MaybeUninit. |
| 47 | + let ptr_to_first: *mut MaybeUninit<T> = self.arr.as_mut_ptr(); |
| 48 | + let ptr_to_slice = ptr::slice_from_raw_parts_mut(ptr_to_first.cast::<T>(), self.len); |
| 49 | + ptr::drop_in_place(ptr_to_slice); |
| 50 | + } |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +/// Equivalent to `it.next_array()`. |
| 55 | +pub fn next_array<I, T, const N: usize>(it: &mut I) -> Option<[T; N]> |
| 56 | +where |
| 57 | + I: Iterator<Item = T>, |
| 58 | +{ |
| 59 | + let mut builder = ArrayBuilder::new(); |
| 60 | + for _ in 0..N { |
| 61 | + builder.push(it.next()?); |
| 62 | + } |
| 63 | + builder.take() |
| 64 | +} |
0 commit comments