Skip to content

Commit 8ffcd06

Browse files
committed
Implement InPlaceWrite<T> for &'static mut MaybeUninit<T>
This feature allows users to use `&'static mut MaybeUninit<T>` as a place to initialize the value. It mirrors an existing implemetation for `Box<MaybeUninit>`, but allows users to avoid allocation. Signed-off-by: Oleksandr Babak <alexanderbabak@proton.me>
1 parent 871cf88 commit 8ffcd06

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/lib.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1449,6 +1449,28 @@ pub trait InPlaceWrite<T> {
14491449
fn write_pin_init<E>(self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E>;
14501450
}
14511451

1452+
impl<T> InPlaceWrite<T> for &'static mut MaybeUninit<T> {
1453+
type Initialized = &'static mut T;
1454+
fn write_init<E>(self, init: impl Init<T, E>) -> Result<Self::Initialized, E> {
1455+
let slot = self.as_mut_ptr();
1456+
// SAFETY: `self` is a valid pointer to uninitialized memory.
1457+
unsafe { init.__init(slot)? };
1458+
// SAFETY: The above call initialized the memory.
1459+
Ok(unsafe { &mut *slot })
1460+
}
1461+
1462+
fn write_pin_init<E>(self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E> {
1463+
let slot = self.as_mut_ptr();
1464+
// SAFETY: `self` is a valid pointer to uninitialized memory.
1465+
unsafe { init.__pinned_init(slot)? };
1466+
// SAFETY:
1467+
// - The above call initialized the memory.
1468+
// - The 'static borrow guarantees the data will not be moved/invalidated
1469+
// until it gets dropped (which is never).
1470+
Ok(unsafe { Pin::new_unchecked(&mut *slot) })
1471+
}
1472+
}
1473+
14521474
/// Trait facilitating pinned destruction.
14531475
///
14541476
/// Use [`pinned_drop`] to implement this trait safely:

0 commit comments

Comments
 (0)