Skip to content

Commit

Permalink
Expand safety comment on uninit and add test
Browse files Browse the repository at this point in the history
  • Loading branch information
tarcieri committed Jan 11, 2024
1 parent 8bd2cf9 commit 94b05e5
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,13 @@ where
{
/// Create an uninitialized array of [`MaybeUninit`]s for the given type.
pub const fn uninit() -> Self {
// SAFETY: an array of `MaybeUninit`s is always valid.
// SAFETY: `Self` is a `repr(transparent)` newtype for `[MaybeUninit<T>; N]`. It is safe
// to assume `[MaybeUninit<T>; N]` is "initialized" because there is no initialization state
// for a `MaybeUninit`: it's a type for representing potentially uninitialized memory (and
// in this case it's uninitialized).
//
// See how `core` defines `MaybeUninit::uninit_array` for a similar example:
// <https://github.com/rust-lang/rust/blob/917f654/library/core/src/mem/maybe_uninit.rs#L350-L352>
#[allow(clippy::uninit_assumed_init)]
unsafe {
MaybeUninit::uninit().assume_init()
Expand Down
13 changes: 13 additions & 0 deletions tests/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use hybrid_array::{Array, ArrayN};
use std::mem::MaybeUninit;
use typenum::{U0, U2, U3, U4, U5, U6, U7};

const EXAMPLE_SLICE: &[u8] = &[1, 2, 3, 4, 5, 6];
Expand Down Expand Up @@ -126,3 +127,15 @@ fn try_from_iterator_too_long() {
let result = Array::<u8, U5>::try_from_iter(EXAMPLE_SLICE.iter().copied());
assert!(result.is_err());
}

#[test]
fn maybe_uninit() {
let mut uninit_array = Array::<MaybeUninit<u8>, U6>::uninit();

for i in 0..6 {
uninit_array[i].write(EXAMPLE_SLICE[i]);
}

let array = unsafe { uninit_array.assume_init() };
assert_eq!(array.as_slice(), EXAMPLE_SLICE);
}

0 comments on commit 94b05e5

Please sign in to comment.