Skip to content

Add helper functions for Array<MaybeUninit<T>, U> #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,35 @@ where
}
}

impl<T, U, const N: usize> Array<MaybeUninit<T>, U>
where
U: ArraySize<ArrayType<MaybeUninit<T>> = [MaybeUninit<T>; N]>,
{
/// Create an uninitialized array of [`MaybeUninit`]s for the given type.
pub const fn uninit() -> Self {
// 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>
// TODO(tarcieri): use `MaybeUninit::uninit_array` when stable
Self(unsafe { MaybeUninit::<U::ArrayType<MaybeUninit<T>>>::uninit().assume_init() })
}

/// Extract the values from an array of `MaybeUninit` containers.
///
/// # Safety
///
/// It is up to the caller to guarantee that all elements of the array are in an initialized
/// state.
pub unsafe fn assume_init(self) -> Array<T, U> {
// TODO(tarcieri): use `MaybeUninit::array_assume_init` when stable
Array(ptr::read(self.0.as_ptr().cast()))
}
}

impl<T, U> AsRef<[T]> for Array<T, U>
where
U: ArraySize,
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);
}