Skip to content
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added

- `[pin_]init_scope` functions to run arbitrary code inside of an initializer.
- `&'static mut MaybeUninit<T>` now implements `InPlaceWrite`. This enables users to use external
allocation mechanisms such as `static_cell`.

### Changed

Expand Down
27 changes: 27 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1536,6 +1536,33 @@ pub trait InPlaceWrite<T> {
fn write_pin_init<E>(self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E>;
}

impl<T> InPlaceWrite<T> for &'static mut MaybeUninit<T> {
type Initialized = &'static mut T;

fn write_init<E>(self, init: impl Init<T, E>) -> Result<Self::Initialized, E> {
let slot = self.as_mut_ptr();

// SAFETY: `slot` is a valid pointer to uninitialized memory.
unsafe { init.__init(slot)? };

// SAFETY: The above call initialized the memory.
unsafe { Ok(self.assume_init_mut()) }
}

fn write_pin_init<E>(self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E> {
let slot = self.as_mut_ptr();

// SAFETY: `slot` is a valid pointer to uninitialized memory.
//
// The `'static` borrow guarantees the data will not be
// moved/invalidated until it gets dropped (which is never).
unsafe { init.__pinned_init(slot)? };

// SAFETY: The above call initialized the memory.
Ok(Pin::static_mut(unsafe { self.assume_init_mut() }))
}
}

/// Trait facilitating pinned destruction.
///
/// Use [`pinned_drop`] to implement this trait safely:
Expand Down