Skip to content

Commit 470c122

Browse files
authored
Merge pull request #91 from Ddystopia/impl_for_mut_ref
- implement `InPlaceWrite<T>` for `&'static mut MaybeUninit<T>`
2 parents c5c055c + 760be09 commit 470c122

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1010
### Added
1111

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

1416
### Changed
1517

src/lib.rs

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

1539+
impl<T> InPlaceWrite<T> for &'static mut MaybeUninit<T> {
1540+
type Initialized = &'static mut T;
1541+
1542+
fn write_init<E>(self, init: impl Init<T, E>) -> Result<Self::Initialized, E> {
1543+
let slot = self.as_mut_ptr();
1544+
1545+
// SAFETY: `slot` is a valid pointer to uninitialized memory.
1546+
unsafe { init.__init(slot)? };
1547+
1548+
// SAFETY: The above call initialized the memory.
1549+
unsafe { Ok(self.assume_init_mut()) }
1550+
}
1551+
1552+
fn write_pin_init<E>(self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E> {
1553+
let slot = self.as_mut_ptr();
1554+
1555+
// SAFETY: `slot` is a valid pointer to uninitialized memory.
1556+
//
1557+
// The `'static` borrow guarantees the data will not be
1558+
// moved/invalidated until it gets dropped (which is never).
1559+
unsafe { init.__pinned_init(slot)? };
1560+
1561+
// SAFETY: The above call initialized the memory.
1562+
Ok(Pin::static_mut(unsafe { self.assume_init_mut() }))
1563+
}
1564+
}
1565+
15391566
/// Trait facilitating pinned destruction.
15401567
///
15411568
/// Use [`pinned_drop`] to implement this trait safely:

0 commit comments

Comments
 (0)