Skip to content

Commit e809736

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 enables users to use external allocation mechanisms such as `static_cell`. Signed-off-by: Oleksandr Babak <[email protected]>
1 parent 871cf88 commit e809736

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased]
99

10+
### Added
11+
12+
- `&'static mut MaybeUninit<T>` now implements `InPlaceWrite`. This enables users to use external
13+
allocation mechanisms such as `static_cell`.
14+
1015
### Changed
1116

1217
- `#[pin_data]` now generates a `*Projection` struct similar to the `pin-project` crate.

src/lib.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1449,6 +1449,30 @@ 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+
1455+
fn write_init<E>(self, init: impl Init<T, E>) -> Result<Self::Initialized, E> {
1456+
let slot = self.as_mut_ptr();
1457+
1458+
// SAFETY: `slot` is a valid pointer to uninitialized memory.
1459+
unsafe { init.__init(slot)? };
1460+
1461+
// SAFETY: The above call initialized the memory.
1462+
unsafe { Ok(self.assume_init_mut()) }
1463+
}
1464+
1465+
fn write_pin_init<E>(self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E> {
1466+
let slot = self.as_mut_ptr();
1467+
1468+
// SAFETY: `slot` is a valid pointer to uninitialized memory.
1469+
unsafe { init.__init(slot)? };
1470+
1471+
// SAFETY: The above call initialized the memory.
1472+
unsafe { Ok(Pin::static_mut(self.assume_init_mut())) }
1473+
}
1474+
}
1475+
14521476
/// Trait facilitating pinned destruction.
14531477
///
14541478
/// Use [`pinned_drop`] to implement this trait safely:

0 commit comments

Comments
 (0)