inplace-init 0.1.0

In-place initialization for Rust values, including pinned and field-by-field construction.
Documentation
//! 派生宏使用的字段元数据、模式适配器和类型状态标记。
//! Field metadata, mode adapters, and typestate markers used by the derive macro.

use core::{convert::Infallible, marker::PhantomData};

use crate::init::{Init, InitMode, InitReceipt, InitSlot, PinInitMode};

/// 存放初始化器类型侧提供的字段清单。
/// Stores the field inventory supplied by the initializer type.
///
/// # Safety
/// 目标类型不得使用 `repr(packed)`;`FIELD_COUNT` 与 `FIELDS` 必须准确描述目标
/// 结构体的全部字段,字段名不得重复,第二项必须准确反映 `#[pin]` 标记。通常
/// 应使用 `#[derive(Init)]` 生成实现。
/// The target must not use `repr(packed)`. `FIELD_COUNT` and `FIELDS` must describe every field accurately, names must be unique, and the second tuple item must match each `#[pin]` marker. Implementations should normally be generated by `#[derive(Init)]`.
#[doc(hidden)]
pub unsafe trait InitFields {
    /// 目标结构体的字段数量。
    /// Number of fields in the target struct.
    const FIELD_COUNT: usize;

    /// 字段名以及字段是否要求固定地址初始化。
    /// Field names and whether each field requires pinned initialization.
    const FIELDS: &'static [(&'static str, bool)];
}

/// 为宏展开提供按字段名键定位的字段类型和地址。
/// Provides field types and addresses selected by field-name keys for macro expansion.
///
/// # Safety
/// 实现必须让每个键对应目标结构体中的唯一字段,并返回该字段在目标内的实际地址。
/// Each key must identify one unique field in the target struct, and the implementation must return that field's actual address within the target.
#[doc(hidden)]
pub unsafe trait InitField<const KEY: u64>: Sized {
    /// 键对应的字段类型。
    /// The field type associated with this key.
    type Field;

    /// 该字段是否要求固定地址初始化。
    /// Whether this field requires pinned initialization.
    type State;

    /// 返回目标中该字段的原始地址。
    /// Return the raw address of this field within the target.
    ///
    /// # Safety
    /// `target` 必须指向有效、对齐且可写的 `Self` 存储。
    /// `target` must point to valid, aligned, writable storage for `Self`.
    unsafe fn __field_ptr(target: *mut Self) -> *mut Self::Field;
}

/// 表示无需固定地址的字段。
/// Marker for a field that does not require a stable address.
#[doc(hidden)]
pub struct MovableField;

/// 表示必须固定地址的字段。
/// Marker for a field that must remain at a stable address.
#[doc(hidden)]
pub struct PinnedField;

/// 按字段元数据选择普通或固定地址初始化器。
/// Selects a movable or pinned initializer according to field metadata.
///
/// # Safety
/// 实现必须在成功时返回唯一拥有已初始化字段析构责任的凭证;若返回错误或 panic,
/// 必须清理字段并使其保持未初始化。实现还必须遵守 `Mode` 与 `FieldState` 的地址约束。
///
/// # Safety
/// Implementations must return the sole receipt responsible for dropping an initialized field on
/// success. On error or panic, they must clean up the field and leave it uninitialized. They must
/// also uphold the address requirements of `Mode` and `FieldState`.
#[doc(hidden)]
pub unsafe trait InitFieldInit<T, E, Mode, FieldState> {
    /// 消耗字段槽位并返回该字段的析构凭证。
    /// Consume the field slot and return its destruction receipt.
    fn initialize<'slot>(
        self,
        slot: InitSlot<'slot, T, Mode>,
    ) -> Result<InitReceipt<'slot, T, Mode>, E>;
}

// 安全性依据:Init 的 unsafe 契约保证该字段的凭证所有权及失败清理。
// Safety: Init's unsafe contract guarantees this field's receipt ownership and failure cleanup.
unsafe impl<T, E, I> InitFieldInit<T, E, InitMode, MovableField> for I
where
    I: Init<T, E, InitMode>,
{
    fn initialize<'slot>(
        self,
        slot: InitSlot<'slot, T, InitMode>,
    ) -> Result<InitReceipt<'slot, T, InitMode>, E> {
        Init::initialize(self, slot)
    }
}

// 安全性依据:Init 的 unsafe 契约保证固定字段的凭证所有权、失败清理和地址约束。
// Safety: Init's unsafe contract guarantees receipt ownership, failure cleanup, and address requirements for pinned fields.
unsafe impl<T, E, I> InitFieldInit<T, E, PinInitMode, PinnedField> for I
where
    I: Init<T, E, PinInitMode>,
{
    fn initialize<'slot>(
        self,
        slot: InitSlot<'slot, T, PinInitMode>,
    ) -> Result<InitReceipt<'slot, T, PinInitMode>, E> {
        Init::initialize(self, slot)
    }
}

// 安全性依据:Init 保证可移动字段的清理;字段元数据保证重标记不会放宽固定字段约束。
// Safety: Init guarantees cleanup for the movable field, and field metadata ensures retagging does not weaken a pinned-field invariant.
unsafe impl<T, E, I> InitFieldInit<T, E, PinInitMode, MovableField> for I
where
    I: Init<T, E, InitMode>,
{
    fn initialize<'slot>(
        self,
        slot: InitSlot<'slot, T, PinInitMode>,
    ) -> Result<InitReceipt<'slot, T, PinInitMode>, E> {
        // 安全性:字段元数据保证该字段不属于固定地址不变式。 Safety: field metadata guarantees this field is not part of the target's pinning invariant.
        let movable_slot = unsafe { slot.__retag() };
        Init::initialize(self, movable_slot).map(|receipt| unsafe { receipt.__retag() })
    }
}

/// 将固定目标地址转为可写入裸指针字段的值。
/// Converts the stable target address into a value for a raw-pointer field.
#[doc(hidden)]
pub trait InitTargetPointer<Target> {
    /// 从目标地址构造指针字段值。
    /// Construct the pointer-field value from the target address.
    fn from_target(pointer: *mut Target) -> Self;
}

impl<Target> InitTargetPointer<Target> for *const Target {
    fn from_target(pointer: *mut Target) -> Self {
        pointer
    }
}

impl<Target> InitTargetPointer<Target> for *mut Target {
    fn from_target(pointer: *mut Target) -> Self {
        pointer
    }
}

/// 表示类型状态 builder 中尚未设置的字段。
/// Marks a field that has not yet been set in the typestate builder.
#[doc(hidden)]
pub struct Unset;

/// 表示类型状态 builder 中已经设置的字段。
/// Marks a field that has already been set in the typestate builder.
#[doc(hidden)]
pub struct Set<I, E = Infallible> {
    initializer: I,
    _error: PhantomData<fn() -> E>,
}

impl<I, E> Set<I, E> {
    /// 创建已设置字段状态。
    /// Create a state marker containing the field initializer.
    pub const fn new(initializer: I) -> Self {
        Self {
            initializer,
            _error: PhantomData,
        }
    }
}

/// 类型状态 builder 字段的初始化能力。
/// Initialization capability for a field represented in a typestate builder.
///
/// # Safety
/// 实现必须仅在字段完整初始化且返回的凭证独占析构责任时返回 `Ok`;返回错误或 panic
/// 时必须清理字段并使其保持未初始化。实现必须满足 `Mode` 和 `PINNED` 表示的地址约束。
///
/// # Safety
/// Implementations may return `Ok` only when the field is fully initialized and the returned
/// receipt exclusively owns its destruction responsibility. On error or panic, they must clean
/// up the field and leave it uninitialized. They must uphold the address requirements represented
/// by `Mode` and `PINNED`.
#[doc(hidden)]
pub unsafe trait InitState<T, Mode, const PINNED: bool = false> {
    /// 当前字段初始化器的错误类型。
    /// Error type returned by this field's initializer.
    type Error;

    /// 消耗字段槽位并返回该字段的析构凭证。
    /// Consume the field slot and return its destruction receipt.
    fn initialize<'slot>(
        self,
        slot: InitSlot<'slot, T, Mode>,
    ) -> Result<InitReceipt<'slot, T, Mode>, Self::Error>;
}

// 安全性依据:Init 的 unsafe 契约为普通模式字段提供完整值、唯一凭证及失败清理保证。
// Safety: Init's unsafe contract guarantees a complete movable field, its sole receipt, and cleanup on failure.
unsafe impl<T, I, E> InitState<T, InitMode, false> for Set<I, E>
where
    I: Init<T, E, InitMode>,
{
    type Error = E;

    fn initialize<'slot>(
        self,
        slot: InitSlot<'slot, T, InitMode>,
    ) -> Result<InitReceipt<'slot, T, InitMode>, E> {
        self.initializer.initialize(slot)
    }
}

// 安全性依据:Init 的 unsafe 契约为固定字段提供完整值、唯一凭证、失败清理和地址保证。
// Safety: Init's unsafe contract guarantees a complete pinned field, its sole receipt, failure cleanup, and address stability.
unsafe impl<T, I, E> InitState<T, PinInitMode, true> for Set<I, E>
where
    I: Init<T, E, PinInitMode>,
{
    type Error = E;

    fn initialize<'slot>(
        self,
        slot: InitSlot<'slot, T, PinInitMode>,
    ) -> Result<InitReceipt<'slot, T, PinInitMode>, E> {
        self.initializer.initialize(slot)
    }
}

// 安全性依据:Init 保证普通字段的清理;此适配仅对未固定字段重新标记凭证。
// Safety: Init guarantees cleanup for the movable field, and this adapter retags receipts only for fields that are not pinned.
unsafe impl<T, I, E> InitState<T, PinInitMode, false> for Set<I, E>
where
    I: Init<T, E, InitMode>,
{
    type Error = E;

    fn initialize<'slot>(
        self,
        slot: InitSlot<'slot, T, PinInitMode>,
    ) -> Result<InitReceipt<'slot, T, PinInitMode>, E> {
        // 安全性:该适配只用于未标记 #[pin] 的字段;字段凭证不会逃出提交过程。 Safety: this adapter is used only for fields without #[pin], and the field receipt cannot escape the parent initialization.
        let movable_slot = unsafe { slot.__retag() };
        self.initializer
            .initialize(movable_slot)
            .map(|receipt| unsafe { receipt.__retag() })
    }
}