inplace-init 0.1.0

In-place initialization for Rust values, including pinned and field-by-field construction.
Documentation
use core::{
    convert::Infallible,
    marker::PhantomData,
    mem::ManuallyDrop,
    ops::{Deref, DerefMut},
    pin::Pin,
    ptr,
};

mod defaults;
mod fields;
mod initializer;

pub use defaults::{InitDefault, InitDefaultInit, InitDefaultValue};
pub use fields::{
    InitField, InitFieldInit, InitFields, InitState, InitTargetPointer, MovableField, PinnedField,
    Set, Unset,
};
pub use initializer::{
    InitFn, InitFnRaw, InitTyBool, InitTyChar, InitTyI8, InitTyI16, InitTyI32, InitTyI64,
    InitTyI128, InitTyIsize, InitTyU8, InitTyU16, InitTyU32, InitTyU64, InitTyU128, InitTyUsize,
    MapInitError,
};

/// 普通初始化的地址模式;初始化完成后,值可从其存储位置移出。
/// Marker for movable initialization; after initialization, the value may be moved out of its storage.
pub struct InitMode;

/// 固定地址初始化的模式标记;初始化器必须在目标的最终地址构造值。
/// Marker for pinned initialization; the initializer must construct the value at its final address.
pub struct PinInitMode;

/// 独占一个未初始化目标地址的一次性凭证。
/// A one-use token that exclusively owns an uninitialized target address.
///
/// 槽位携带目标的独占借用;成功初始化后必须消费它并取得 [`InitReceipt`]。
/// The slot carries an exclusive borrow of the target; successful initialization consumes it and yields an [`InitReceipt`].
pub struct InitSlot<'slot, T, Mode = InitMode> {
    pointer: *mut T,
    _borrow: PhantomData<&'slot mut T>,
    _mode: PhantomData<fn() -> Mode>,
}

impl<'slot, T, Mode> InitSlot<'slot, T, Mode> {
    /// 将完整值写入目标存储,并返回负责析构该值的凭证。
    /// Write a complete value into the target storage and return the receipt that owns its destruction.
    pub fn write(self, value: T) -> InitReceipt<'slot, T, Mode> {
        // 安全性:槽位仅由有效未初始化存储的独占入口创建。 Safety: a slot is created only from exclusive access to valid, uninitialized storage.
        unsafe { self.pointer.write(value) };
        // 安全性:上一步已在槽位地址完整构造一个 T。 Safety: the previous write fully constructed a T at the slot address.
        unsafe { InitReceipt::new(self.pointer) }
    }

    /// 使用目标类型为当前地址模式提供的默认实现构造值。
    /// Construct a value using the target type's default initializer for the current address mode.
    pub fn initialize_default(self) -> InitReceipt<'slot, T, Mode>
    where
        T: InitDefault<T, Mode>,
    {
        T::initialize_default(self)
    }

    /// 返回目标的原始地址,供派生宏生成的字段投影代码使用。
    /// Return the target's raw address for field-projection code generated by the derive macro.
    #[doc(hidden)]
    pub fn __target_ptr(&self) -> *mut T {
        self.pointer
    }

    /// 返回目标的原始可变地址,供高级原始地址初始化适配器使用。
    /// Return the target's raw mutable address for advanced raw-pointer initializer adapters.
    #[doc(hidden)]
    pub fn __raw_mut_ptr(&self) -> *mut T {
        self.pointer
    }

    /// 为父目标中的一个独占字段创建一次性槽位。
    /// Create a one-use slot for an exclusive field within the parent target.
    ///
    /// # 安全性要求
    /// `pointer` 必须指向父目标中有效、对齐且尚未初始化的字段,且不得与仍在使用的其他字段槽位重叠。
    ///
    /// # Safety
    /// `pointer` must point to a valid, aligned, uninitialized field in the parent target and must not overlap another field slot that is still in use.
    #[doc(hidden)]
    pub unsafe fn __project<U>(&mut self, pointer: *mut U) -> InitSlot<'slot, U, Mode> {
        InitSlot {
            pointer,
            _borrow: PhantomData,
            _mode: PhantomData,
        }
    }

    /// 将字段槽位重新标记为另一地址模式。
    /// Retag a field slot with another address mode.
    ///
    /// # 安全性要求
    /// 调用方必须确保新模式不会让初始化器违反目标字段的固定约束;派生代码仅对未标记 `#[pin]` 的字段使用此入口。
    ///
    /// # Safety
    /// The caller must ensure that the new mode cannot violate the field's pinning invariants; derive code uses this only for fields without `#[pin]`.
    #[doc(hidden)]
    pub unsafe fn __retag<Other>(self) -> InitSlot<'slot, T, Other> {
        InitSlot {
            pointer: self.pointer,
            _borrow: PhantomData,
            _mode: PhantomData,
        }
    }

    /// 将已完整构造的目标转换为析构凭证。
    /// Convert a fully constructed target into its destruction receipt.
    ///
    /// # 安全性要求
    /// 调用方必须先在目标地址完整构造有效的 `T`,并确保它满足 `Mode` 的地址保证。
    ///
    /// # Safety
    /// The caller must first fully construct a valid `T` at the target address and uphold the address guarantees of `Mode`.
    #[doc(hidden)]
    pub unsafe fn __assume_init(self) -> InitReceipt<'slot, T, Mode> {
        // 安全性:由调用方保证目标已经完整初始化。 Safety: the caller guarantees that the target is fully initialized.
        unsafe { InitReceipt::new(self.pointer) }
    }

    /// 从受控的原始存储创建槽位。
    /// Create a slot from storage whose validity is established by the caller.
    ///
    /// # 安全性要求
    /// `pointer` 必须指向有效、对齐且未初始化的 `T` 存储,并在槽位及后续凭证存活期间保持有效。
    ///
    /// # Safety
    /// `pointer` must point to valid, aligned, uninitialized storage for `T` and remain valid while the slot and any resulting receipt exist.
    #[doc(hidden)]
    pub unsafe fn __from_raw(pointer: *mut T) -> Self {
        Self {
            pointer,
            _borrow: PhantomData,
            _mode: PhantomData,
        }
    }
}

/// 独占已初始化值及其析构责任的凭证。
/// A receipt that exclusively owns an initialized value and responsibility for dropping it.
///
/// 凭证被销毁时会析构目标;普通模式可移出值,固定模式只能通过 `Pin` 借用。
/// Dropping the receipt drops the target; movable mode can extract the value, while pinned mode exposes only `Pin` borrows.
pub struct InitReceipt<'slot, T, Mode = InitMode> {
    pointer: *mut T,
    _borrow: PhantomData<&'slot mut T>,
    _mode: PhantomData<fn() -> Mode>,
}

impl<'slot, T, Mode> InitReceipt<'slot, T, Mode> {
    /// 为已初始化目标创建唯一析构凭证。
    /// Create the unique destruction receipt for an initialized target.
    /// # Safety
    /// `pointer` 必须指向有效且已初始化的 `T`,并且本凭证必须独占其析构责任。
    /// The pointer must refer to a valid initialized `T`, and this receipt must be the sole owner of its destruction responsibility.
    pub(crate) unsafe fn new(pointer: *mut T) -> Self {
        Self {
            pointer,
            _borrow: PhantomData,
            _mode: PhantomData,
        }
    }

    /// 将凭证转换为另一地址模式。
    /// Retag the receipt with another address mode.
    ///
    /// # Safety
    /// 调用方必须证明转换后的模式仍满足目标值的地址约束,且转换期间没有其他
    /// 凭证持有该值的析构责任。
    /// The caller must prove that the new mode still satisfies the value's address invariants and that no other receipt owns its destruction responsibility.
    #[doc(hidden)]
    pub unsafe fn __retag<Other>(self) -> InitReceipt<'slot, T, Other> {
        let receipt = ManuallyDrop::new(self);
        // 安全性:调用方保证新模式合法;ManuallyDrop 转移唯一析构责任。 Safety: the caller validates the new mode, and ManuallyDrop transfers the sole drop responsibility.
        unsafe { InitReceipt::new(receipt.pointer) }
    }
}

impl<T, Mode> Deref for InitReceipt<'_, T, Mode> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        // 安全性:凭证仅在初始化成功后创建,并独占目标值。 Safety: a receipt is created only after successful initialization and exclusively owns the target value.
        unsafe { &*self.pointer }
    }
}

impl<T> DerefMut for InitReceipt<'_, T, InitMode> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        // 安全性:普通模式凭证的独占借用允许访问可移动目标。 Safety: the exclusive borrow held by a movable-mode receipt permits mutable access to its target.
        unsafe { &mut *self.pointer }
    }
}

impl<T> InitReceipt<'_, T, InitMode> {
    /// 将普通值从其存储地址移出,并转移其所有权给调用方。
    /// Move a value out of its storage and transfer ownership to the caller.
    pub fn into_inner(self) -> T {
        let receipt = ManuallyDrop::new(self);
        // 安全性:普通模式允许移动值;ManuallyDrop 防止源地址再次析构。 Safety: movable mode permits extraction, and ManuallyDrop prevents the source address from being dropped again.
        unsafe { receipt.pointer.read() }
    }
}

impl<T> InitReceipt<'_, T, PinInitMode> {
    /// 获取已固定值的共享固定借用。
    /// Obtain a shared pinned borrow of the initialized value.
    pub fn as_pin_ref(&self) -> Pin<&T> {
        // 安全性:PinInitMode 仅由固定初始化入口创建。 Safety: PinInitMode is created only by pinned initialization entry points.
        unsafe { Pin::new_unchecked(&*self.pointer) }
    }

    /// 获取已固定值的可变固定借用。
    /// Obtain an exclusive pinned borrow of the initialized value.
    pub fn as_pin_mut(&mut self) -> Pin<&mut T> {
        // 安全性:凭证独占目标,且 PinInitMode 保证目标地址稳定。 Safety: the receipt exclusively borrows the target, and PinInitMode guarantees its address remains stable.
        unsafe { Pin::new_unchecked(&mut *self.pointer) }
    }
}

impl<T, Mode> Drop for InitReceipt<'_, T, Mode> {
    fn drop(&mut self) {
        // 安全性:凭证唯一拥有目标值的析构责任。 Safety: the receipt is the sole owner of the target's destruction responsibility.
        unsafe { ptr::drop_in_place(self.pointer) };
    }
}

/// 在一次性槽位中构造一个值。
/// An initializer that constructs a value in a one-use target slot.
///
/// 错误类型与地址模式由 trait 参数表达;只有成功时才会返回析构凭证。
/// The error type and address mode are expressed by trait parameters; a destruction receipt is returned only on success.
///
/// # 安全性
/// 实现必须满足以下所有条件:
///
/// - 成功时恰好构造一个有效的 `T`,返回的凭证是该值唯一的析构责任拥有者。
/// - 返回 `Err` 或展开 panic 时,必须销毁所有已构造的完整值和部分字段,使槽位保持未初始化;不得留下未被有效凭证跟踪的已初始化状态。
/// - 初始化多个字段时,必须保留已完成字段的凭证,直到后续字段也完成;只有全部字段成功后,才能消费字段凭证并创建整体凭证。
/// - 必须满足 `Mode` 对目标地址的约束。
///
/// # Safety
/// Implementations must satisfy all of the following:
///
/// - On success, construct exactly one valid `T`, and return the sole receipt responsible for dropping it.
/// - On `Err` or panic unwinding, drop every constructed value and partial field, leaving the slot uninitialized; no initialized state may remain without a valid receipt tracking it.
/// - When initializing multiple fields, retain receipts for completed fields until all later fields succeed. Consume those receipts and create the whole-value receipt only after every field succeeds.
/// - Uphold the target-address requirements of `Mode`.
pub unsafe trait Init<T, E = Infallible, Mode = InitMode>: Sized {
    /// 消耗目标槽位并返回已初始化值的析构凭证。
    /// Consume the target slot and return a destruction receipt for the initialized value.
    fn initialize<'slot>(
        self,
        slot: InitSlot<'slot, T, Mode>,
    ) -> Result<InitReceipt<'slot, T, Mode>, E>;

    /// 将初始化器的错误映射为另一种错误类型,同时保留地址模式。
    /// Map the initializer's error to another type while preserving its address mode.
    ///
    /// 成功时不会调用映射闭包;闭包会随初始化器结果一同释放。
    /// The mapping closure is not called on success and is dropped with the completed initializer.
    fn map_err<F, E2>(self, map: F) -> MapInitError<Self, F, E, Mode>
    where
        Self: Sized,
        F: FnOnce(E) -> E2,
    {
        MapInitError::<Self, F, E, Mode>::new(self, map)
    }
}

/// 直接操作原始地址的高级初始化器。
/// An advanced initializer that writes directly through a raw target pointer.
///
/// # Safety
/// 成功时必须恰好构造一个有效的 `T`,且其唯一析构责任应交给 [`RawInit`] 创建的凭证;
/// 同时满足 `Mode` 的地址保证。返回错误或发生 panic 时,目标存储必须保持未初始化,
/// 并清理此前已构造的所有完整值和部分状态。
/// On success, the implementation must construct exactly one valid `T`, transfer its sole
/// destruction responsibility to the receipt created by [`RawInit`], and uphold `Mode`'s address
/// guarantees. On error or panic, storage must remain uninitialized and all constructed values
/// and partial state must be cleaned up.
pub unsafe trait InitRaw<T, E = Infallible, Mode = InitMode> {
    /// 在目标存储中构造值。
    /// Construct a value in the target storage.
    ///
    /// # Safety
    /// `slot` 必须非空、正确对齐,并指向可写入 `T` 大小的未初始化存储。
    /// `slot` must be non-null, properly aligned, writable, and point to uninitialized storage large enough for `T`.
    unsafe fn init_raw(self, slot: *mut T) -> Result<(), E>;
}

/// 将高级原始地址初始化器接入安全初始化入口。
/// Adapts an advanced raw-pointer initializer to the safe [`Init`] interface.
pub struct RawInit<I> {
    initializer: I,
}

impl<I> RawInit<I> {
    /// 包装一个实现了 [`InitRaw`] 的初始化器。
    /// Wrap an initializer that implements [`InitRaw`].
    pub const fn new(initializer: I) -> Self {
        Self { initializer }
    }
}

// 安全性依据:InitRaw 的 unsafe 契约保证失败时清理且成功时恰好构造一个完整目标;本适配器只在成功后创建整体凭证。
// Safety: InitRaw's unsafe contract guarantees cleanup on failure and exactly one complete target on success; this adapter creates the whole-value receipt only after success.
unsafe impl<T, E, Mode, I> Init<T, E, Mode> for RawInit<I>
where
    I: InitRaw<T, E, Mode>,
{
    fn initialize<'slot>(
        self,
        slot: InitSlot<'slot, T, Mode>,
    ) -> Result<InitReceipt<'slot, T, Mode>, E> {
        // 安全性:InitRaw 契约要求错误或 panic 时清理部分状态。 Safety: InitRaw's contract requires partial state to be cleaned up on error or panic.
        unsafe { self.initializer.init_raw(slot.__raw_mut_ptr())? };
        // 安全性:InitRaw 成功返回时已完整构造满足模式约束的 T。 Safety: a successful InitRaw return means a complete T satisfying the mode invariants exists.
        Ok(unsafe { slot.__assume_init() })
    }
}