Skip to content

Commit 085e4e4

Browse files
committed
Add the Wrapper trait.
This trait allows crating `PinInitializers` for wrapper or new-type structs with the inner value structurally pinned, when given the initializer for the inner value. This commit implements this trait for `UnsafeCell` and `MaybeUninit`. Signed-off-by: Christian Schrefl <chrisi.schrefl@gmail.com>
1 parent a4ec26b commit 085e4e4

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

src/lib.rs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1513,3 +1513,46 @@ macro_rules! impl_tuple_zeroable {
15131513
}
15141514

15151515
impl_tuple_zeroable!(A, B, C, D, E, F, G, H, I, J);
1516+
1517+
/// This trait allows creating an instance of `Self` which contains exactly one [structurally pinned value].
1518+
///
1519+
/// This is useful when using wrapper `struct`s like [`UnsafeCell`] or with new-type `struct`s.
1520+
///
1521+
/// # Examples
1522+
///
1523+
/// ```
1524+
/// # use core::cell::UnsafeCell;
1525+
/// # use pin_init::{pin_data, pin_init, Wrapper};
1526+
///
1527+
/// #[pin_data]
1528+
/// struct Foo {}
1529+
///
1530+
/// #[pin_data]
1531+
/// struct Bar {
1532+
/// #[pin]
1533+
/// content: UnsafeCell<Foo>
1534+
/// };
1535+
///
1536+
/// let foo_initializer = pin_init!(Foo{});
1537+
/// let initializer = pin_init!(Bar {
1538+
/// content <- UnsafeCell::pin_init(foo_initializer)
1539+
/// });
1540+
/// ```
1541+
pub trait Wrapper<T> {
1542+
/// Create an pin-initializer for a [`Self`] containing `T` form the `value_init` initializer.
1543+
fn pin_init<E>(value_init: impl PinInit<T, E>) -> impl PinInit<Self, E>;
1544+
}
1545+
1546+
impl<T> Wrapper<T> for UnsafeCell<T> {
1547+
fn pin_init<E>(value_init: impl PinInit<T, E>) -> impl PinInit<Self, E> {
1548+
// SAFETY: `UnsafeCell<T>` has a compatible layout to `T`.
1549+
unsafe { cast_pin_init(value_init) }
1550+
}
1551+
}
1552+
1553+
impl<T> Wrapper<T> for MaybeUninit<T> {
1554+
fn pin_init<E>(value_init: impl PinInit<T, E>) -> impl PinInit<Self, E> {
1555+
// SAFETY: `MaybeUninit<T>` has a compatible layout to `T`.
1556+
unsafe { cast_pin_init(value_init) }
1557+
}
1558+
}

0 commit comments

Comments
 (0)