Skip to content

Commit

Permalink
Use MaybeUninit to init array without heap allocation
Browse files Browse the repository at this point in the history
  • Loading branch information
dhruv9vats committed May 21, 2024
1 parent cd8d65e commit a1a059f
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions src/array/fixed_size_list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,12 +263,28 @@ impl<const N: usize, I: IntoIterator> Iterator for FixedSizeArrayChunks<N, I> {
type Item = [I::Item; N];

fn next(&mut self) -> Option<Self::Item> {
let mut data: [MaybeUninit<I::Item>; N] =
// Safety:
// - https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html#initializing-an-array-element-by-element
unsafe { MaybeUninit::uninit().assume_init() };

let mut total_elements_written: usize = 0;
self.iter
.by_ref()
.take(N)
.collect::<Vec<_>>()
.try_into()
.ok()
.enumerate()
.for_each(|(array_index, val)| {
data[array_index].write(val);
total_elements_written += 1;
});

(total_elements_written == N).then(|| {
data.map(|item| {
// Safety:
// - We only initialize if the number of elements that were written are actually N.
unsafe { item.assume_init() }
})
})
}
}

Check warning on line 289 in src/array/fixed_size_list.rs

View check run for this annotation

Codecov / codecov/patch

src/array/fixed_size_list.rs#L289

Added line #L289 was not covered by tests

Expand Down

0 comments on commit a1a059f

Please sign in to comment.