// SPDX-License-Identifier: Apache-2.0 OR MIT12//! This module contains library internal items.3//!4//! These items must not be used outside of this crate and the pin-init-internal crate located at5//! `../internal`.67use super::*;89/// See the [nomicon] for what subtyping is. See also [this table].10///11/// The reason for not using `PhantomData<*mut T>` is that that type never implements [`Send`] and12/// [`Sync`]. Hence `fn(*mut T) -> *mut T` is used, as that type always implements them.13///14/// [nomicon]: https://doc.rust-lang.org/nomicon/subtyping.html15/// [this table]: https://doc.rust-lang.org/nomicon/phantom-data.html#table-of-phantomdata-patterns16pub(crate) type Invariant<T> = PhantomData<fn(*mut T) -> *mut T>;1718/// Module-internal type implementing `PinInit` and `Init`.19///20/// It is unsafe to create this type, since the closure needs to fulfill the same safety21/// requirement as the `__pinned_init`/`__init` functions.22pub(crate) struct InitClosure<F, T: ?Sized, E>(pub(crate) F, pub(crate) Invariant<(E, T)>);2324// SAFETY: While constructing the `InitClosure`, the user promised that it upholds the25// `__init` invariants.26unsafe impl<T: ?Sized, F, E> Init<T, E> for InitClosure<F, T, E>27where28F: FnOnce(*mut T) -> Result<(), E>,29{30#[inline]31unsafe fn __init(self, slot: *mut T) -> Result<(), E> {32(self.0)(slot)33}34}3536// SAFETY: While constructing the `InitClosure`, the user promised that it upholds the37// `__pinned_init` invariants.38unsafe impl<T: ?Sized, F, E> PinInit<T, E> for InitClosure<F, T, E>39where40F: FnOnce(*mut T) -> Result<(), E>,41{42#[inline]43unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {44(self.0)(slot)45}46}4748/// This trait is only implemented via the `#[pin_data]` proc-macro. It is used to facilitate49/// the pin projections within the initializers.50///51/// # Safety52///53/// Only the `init` module is allowed to use this trait.54pub unsafe trait HasPinData {55type PinData: PinData;5657#[expect(clippy::missing_safety_doc)]58unsafe fn __pin_data() -> Self::PinData;59}6061/// Marker trait for pinning data of structs.62///63/// # Safety64///65/// Only the `init` module is allowed to use this trait.66pub unsafe trait PinData: Copy {67type Datee: ?Sized + HasPinData;6869/// Type inference helper function.70fn make_closure<F, O, E>(self, f: F) -> F71where72F: FnOnce(*mut Self::Datee) -> Result<O, E>,73{74f75}76}7778/// This trait is automatically implemented for every type. It aims to provide the same type79/// inference help as `HasPinData`.80///81/// # Safety82///83/// Only the `init` module is allowed to use this trait.84pub unsafe trait HasInitData {85type InitData: InitData;8687#[expect(clippy::missing_safety_doc)]88unsafe fn __init_data() -> Self::InitData;89}9091/// Same function as `PinData`, but for arbitrary data.92///93/// # Safety94///95/// Only the `init` module is allowed to use this trait.96pub unsafe trait InitData: Copy {97type Datee: ?Sized + HasInitData;9899/// Type inference helper function.100fn make_closure<F, O, E>(self, f: F) -> F101where102F: FnOnce(*mut Self::Datee) -> Result<O, E>,103{104f105}106}107108pub struct AllData<T: ?Sized>(Invariant<T>);109110impl<T: ?Sized> Clone for AllData<T> {111fn clone(&self) -> Self {112*self113}114}115116impl<T: ?Sized> Copy for AllData<T> {}117118// SAFETY: TODO.119unsafe impl<T: ?Sized> InitData for AllData<T> {120type Datee = T;121}122123// SAFETY: TODO.124unsafe impl<T: ?Sized> HasInitData for T {125type InitData = AllData<T>;126127unsafe fn __init_data() -> Self::InitData {128AllData(PhantomData)129}130}131132/// Stack initializer helper type. Use [`stack_pin_init`] instead of this primitive.133///134/// # Invariants135///136/// If `self.is_init` is true, then `self.value` is initialized.137///138/// [`stack_pin_init`]: crate::stack_pin_init139pub struct StackInit<T> {140value: MaybeUninit<T>,141is_init: bool,142}143144impl<T> Drop for StackInit<T> {145#[inline]146fn drop(&mut self) {147if self.is_init {148// SAFETY: As we are being dropped, we only call this once. And since `self.is_init` is149// true, `self.value` is initialized.150unsafe { self.value.assume_init_drop() };151}152}153}154155impl<T> StackInit<T> {156/// Creates a new [`StackInit<T>`] that is uninitialized. Use [`stack_pin_init`] instead of this157/// primitive.158///159/// [`stack_pin_init`]: crate::stack_pin_init160#[inline]161pub fn uninit() -> Self {162Self {163value: MaybeUninit::uninit(),164is_init: false,165}166}167168/// Initializes the contents and returns the result.169#[inline]170pub fn init<E>(self: Pin<&mut Self>, init: impl PinInit<T, E>) -> Result<Pin<&mut T>, E> {171// SAFETY: We never move out of `this`.172let this = unsafe { Pin::into_inner_unchecked(self) };173// The value is currently initialized, so it needs to be dropped before we can reuse174// the memory (this is a safety guarantee of `Pin`).175if this.is_init {176this.is_init = false;177// SAFETY: `this.is_init` was true and therefore `this.value` is initialized.178unsafe { this.value.assume_init_drop() };179}180// SAFETY: The memory slot is valid and this type ensures that it will stay pinned.181unsafe { init.__pinned_init(this.value.as_mut_ptr())? };182// INVARIANT: `this.value` is initialized above.183this.is_init = true;184// SAFETY: The slot is now pinned, since we will never give access to `&mut T`.185Ok(unsafe { Pin::new_unchecked(this.value.assume_init_mut()) })186}187}188189#[test]190#[cfg(feature = "std")]191fn stack_init_reuse() {192use ::std::{borrow::ToOwned, println, string::String};193use core::pin::pin;194195#[derive(Debug)]196struct Foo {197a: usize,198b: String,199}200let mut slot: Pin<&mut StackInit<Foo>> = pin!(StackInit::uninit());201let value: Result<Pin<&mut Foo>, core::convert::Infallible> =202slot.as_mut().init(crate::init!(Foo {203a: 42,204b: "Hello".to_owned(),205}));206let value = value.unwrap();207println!("{value:?}");208let value: Result<Pin<&mut Foo>, core::convert::Infallible> =209slot.as_mut().init(crate::init!(Foo {210a: 24,211b: "world!".to_owned(),212}));213let value = value.unwrap();214println!("{value:?}");215}216217/// When a value of this type is dropped, it drops a `T`.218///219/// Can be forgotten to prevent the drop.220pub struct DropGuard<T: ?Sized> {221ptr: *mut T,222}223224impl<T: ?Sized> DropGuard<T> {225/// Creates a new [`DropGuard<T>`]. It will [`ptr::drop_in_place`] `ptr` when it gets dropped.226///227/// # Safety228///229/// `ptr` must be a valid pointer.230///231/// It is the callers responsibility that `self` will only get dropped if the pointee of `ptr`:232/// - has not been dropped,233/// - is not accessible by any other means,234/// - will not be dropped by any other means.235#[inline]236pub unsafe fn new(ptr: *mut T) -> Self {237Self { ptr }238}239}240241impl<T: ?Sized> Drop for DropGuard<T> {242#[inline]243fn drop(&mut self) {244// SAFETY: A `DropGuard` can only be constructed using the unsafe `new` function245// ensuring that this operation is safe.246unsafe { ptr::drop_in_place(self.ptr) }247}248}249250/// Token used by `PinnedDrop` to prevent calling the function without creating this unsafely251/// created struct. This is needed, because the `drop` function is safe, but should not be called252/// manually.253pub struct OnlyCallFromDrop(());254255impl OnlyCallFromDrop {256/// # Safety257///258/// This function should only be called from the [`Drop::drop`] function and only be used to259/// delegate the destruction to the pinned destructor [`PinnedDrop::drop`] of the same type.260pub unsafe fn new() -> Self {261Self(())262}263}264265/// Initializer that always fails.266///267/// Used by [`assert_pinned!`].268///269/// [`assert_pinned!`]: crate::assert_pinned270pub struct AlwaysFail<T: ?Sized> {271_t: PhantomData<T>,272}273274impl<T: ?Sized> AlwaysFail<T> {275/// Creates a new initializer that always fails.276pub fn new() -> Self {277Self { _t: PhantomData }278}279}280281impl<T: ?Sized> Default for AlwaysFail<T> {282fn default() -> Self {283Self::new()284}285}286287// SAFETY: `__pinned_init` always fails, which is always okay.288unsafe impl<T: ?Sized> PinInit<T, ()> for AlwaysFail<T> {289unsafe fn __pinned_init(self, _slot: *mut T) -> Result<(), ()> {290Err(())291}292}293294295