Skip to content

Commit aeb5eca

Browse files
DdystopiaBennoLossin
authored andcommitted
rust: pin-init: 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 enables users to use external allocation mechanisms such as `static_cell` [1]. Signed-off-by: Oleksandr Babak <alexanderbabak@proton.me> Link: https://crates.io/crates/static_cell [1] [ Added link to `static_cell` - Benno ] Signed-off-by: Benno Lossin <lossin@kernel.org>
1 parent da9cfc4 commit aeb5eca

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

rust/pin-init/src/lib.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1403,6 +1403,33 @@ pub trait InPlaceWrite<T> {
14031403
fn write_pin_init<E>(self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E>;
14041404
}
14051405

1406+
impl<T> InPlaceWrite<T> for &'static mut MaybeUninit<T> {
1407+
type Initialized = &'static mut T;
1408+
1409+
fn write_init<E>(self, init: impl Init<T, E>) -> Result<Self::Initialized, E> {
1410+
let slot = self.as_mut_ptr();
1411+
1412+
// SAFETY: `slot` is a valid pointer to uninitialized memory.
1413+
unsafe { init.__init(slot)? };
1414+
1415+
// SAFETY: The above call initialized the memory.
1416+
unsafe { Ok(self.assume_init_mut()) }
1417+
}
1418+
1419+
fn write_pin_init<E>(self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E> {
1420+
let slot = self.as_mut_ptr();
1421+
1422+
// SAFETY: `slot` is a valid pointer to uninitialized memory.
1423+
//
1424+
// The `'static` borrow guarantees the data will not be
1425+
// moved/invalidated until it gets dropped (which is never).
1426+
unsafe { init.__pinned_init(slot)? };
1427+
1428+
// SAFETY: The above call initialized the memory.
1429+
Ok(Pin::static_mut(unsafe { self.assume_init_mut() }))
1430+
}
1431+
}
1432+
14061433
/// Trait facilitating pinned destruction.
14071434
///
14081435
/// Use [`pinned_drop`] to implement this trait safely:

0 commit comments

Comments
 (0)