From 4ca8c15f23c64ce38d7e26effcd348ac5e51d575 Mon Sep 17 00:00:00 2001 From: Joshua Simmons Date: Sun, 26 Feb 2023 19:16:59 +0100 Subject: [PATCH] Improve Box's MaybeUninit helpers --- libs/narcissus-core/src/lib.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/libs/narcissus-core/src/lib.rs b/libs/narcissus-core/src/lib.rs index af72681..1453b4e 100644 --- a/libs/narcissus-core/src/lib.rs +++ b/libs/narcissus-core/src/lib.rs @@ -253,6 +253,8 @@ pub fn string_from_c_str(c_str: &[i8]) -> String { String::from_utf8_lossy(s).into_owned() } +/// Constructs a new box with uninitialized contents. +#[inline] pub fn uninit_box() -> Box> { let layout = std::alloc::Layout::new::>(); unsafe { @@ -261,6 +263,8 @@ pub fn uninit_box() -> Box> { } } +/// Constructs a new box with zeroed contents. +#[inline] pub fn zeroed_box() -> Box> { let layout = std::alloc::Layout::new::>(); unsafe { @@ -269,6 +273,21 @@ pub fn zeroed_box() -> Box> { } } +/// Converts `Box>` to `Box` +/// +/// # Safety +/// +/// As with [`MaybeUninit::assume_init`], it is up to the caller to guarantee that the value really +/// is in an initialized state. Calling this when the content is not yet fully initialized causes +/// immediate undefined behavior. +/// +/// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init +#[inline] +pub unsafe fn box_assume_init(value: Box>) -> Box { + let raw = Box::into_raw(value); + unsafe { Box::from_raw(raw as *mut T) } +} + /// Negative traits aren't stable yet, so use a dummy PhantomData marker to implement !Send pub type PhantomUnsend = std::marker::PhantomData<*mut ()>; -- 2.49.0