Skip to main content

inplace_init/
lib.rs

1#![no_std]
2#![doc = concat!(
3    include_str!("../README.md"),
4    "\n\n",
5    include_str!("../README_CN.md"),
6)]
7
8use core::{mem::MaybeUninit, pin::Pin};
9
10#[doc(hidden)]
11pub extern crate self as inplace_init;
12
13#[cfg(feature = "alloc")]
14extern crate alloc;
15
16#[cfg(feature = "std")]
17extern crate std;
18
19pub use inplace_init_macros::{Init, init, pin_init, pin_init_local};
20
21mod init;
22mod storage;
23
24pub use init::{
25    Init, InitDefault, InitDefaultInit, InitDefaultValue, InitField, InitFieldInit, InitFields,
26    InitFn, InitFnRaw, InitMode, InitRaw, InitReceipt, InitSlot, InitState, InitTargetPointer,
27    InitTyBool, InitTyChar, InitTyI8, InitTyI16, InitTyI32, InitTyI64, InitTyI128, InitTyIsize,
28    InitTyU8, InitTyU16, InitTyU32, InitTyU64, InitTyU128, InitTyUsize, MapInitError, MovableField,
29    PinInitMode, PinnedField, RawInit, Set, Unset,
30};
31pub use storage::{InitStorage, InitValue};
32
33#[cfg(feature = "alloc")]
34pub use storage::{InitBoxExt, PinInitBoxExt};
35
36/// 在 `MaybeUninit` 存储中初始化可移动值,并返回负责析构该值的凭证。
37/// Initialize a movable value in `MaybeUninit` storage and return the receipt that drops it.
38///
39/// 调用方独占借用槽位直到凭证被销毁或值被移出;初始化器返回的错误会原样传给调用方。
40/// The slot remains exclusively borrowed until the receipt is dropped or the value is moved out; initializer errors are returned unchanged.
41/// 安全性由 `Init` 的 unsafe 实现契约保证:错误或 panic 时槽位保持未初始化。
42/// The `Init` implementation's unsafe contract guarantees that the slot remains uninitialized on error or panic.
43pub fn init_in<'slot, T, I, E>(
44    slot: &'slot mut MaybeUninit<T>,
45    initializer: I,
46) -> Result<InitReceipt<'slot, T, InitMode>, E>
47where
48    I: Init<T, E>,
49{
50    // 安全性:独占借用保证目标地址有效、对齐且当前未初始化。 Safety: the exclusive borrow guarantees that the target address is valid, aligned, and currently uninitialized.
51    let slot = unsafe { InitSlot::__from_raw(slot.as_mut_ptr()) };
52    initializer.initialize(slot)
53}
54
55/// 在固定地址的 `MaybeUninit` 存储中初始化值,并返回固定析构凭证。
56/// Initialize a value in pinned `MaybeUninit` storage and return a pinned destruction receipt.
57///
58/// 该入口不会移动存储,但调用方必须保证传入存储及其地址满足下方的固定约束。
59/// This function does not move the storage, but the caller must uphold the pinning requirements below.
60///
61/// # Safety
62/// 调用方必须保证存储在凭证销毁前始终固定。如果凭证被遗忘,存储也不得被移动、
63/// 重用或以其他方式暴露为可再次初始化的槽位。
64/// The storage must remain pinned until the receipt is dropped. If the receipt is forgotten, the storage must not be moved, reused, or exposed as an initialization slot again.
65pub unsafe fn pin_init_in<'slot, T, I, E>(
66    slot: Pin<&'slot mut MaybeUninit<T>>,
67    initializer: I,
68) -> Result<InitReceipt<'slot, T, PinInitMode>, E>
69where
70    I: Init<T, E, PinInitMode>,
71{
72    // 安全性:调用方承诺凭证遗忘后仍不移动或复用存储。 Safety: the caller promises not to move or reuse the storage even if the receipt is forgotten.
73    let storage = unsafe { Pin::get_unchecked_mut(slot) };
74    // 安全性:storage 来自固定独占借用,地址在初始化过程中保持稳定。 Safety: storage comes from a pinned exclusive borrow, so its address stays stable during initialization.
75    let slot = unsafe { InitSlot::__from_raw(storage.as_mut_ptr()) };
76    initializer.initialize(slot)
77}
78
79/// 在编译期核对初始化宏调用与目标结构体的字段清单。
80/// Validate at compile time that an initialization macro call matches its target struct's field inventory.
81///
82/// `provided` 中的布尔值表示字段是否在目标地址原位初始化;固定字段必须同时使用固定入口和原位语法。
83/// Each boolean in `provided` records whether that field is initialized in place; pinned fields require both a pinned entry point and in-place syntax.
84#[doc(hidden)]
85pub const fn __validate_init_fields<T: InitFields>(provided: &[(&str, bool)], pinned: bool) {
86    let expected = T::FIELDS;
87    assert!(
88        expected.len() == T::FIELD_COUNT,
89        "`InitFields` field metadata has an incorrect length"
90    );
91    assert!(
92        expected.len() == provided.len(),
93        "The number of initialized fields does not match the target struct"
94    );
95
96    let mut expected_index = 0;
97    while expected_index < expected.len() {
98        let (expected_name, is_pinned) = expected[expected_index];
99        let mut prior_index = 0;
100        while prior_index < expected_index {
101            let (prior_name, _) = expected[prior_index];
102            assert!(
103                !__str_eq(expected_name, prior_name),
104                "`InitFields` field names must be unique"
105            );
106            prior_index += 1;
107        }
108
109        let mut matching_index = 0;
110        let mut match_count = 0;
111        let mut initialized_in_place = false;
112        while matching_index < provided.len() {
113            let (provided_name, provided_in_place) = provided[matching_index];
114            if __str_eq(expected_name, provided_name) {
115                match_count += 1;
116                initialized_in_place = provided_in_place;
117            }
118            matching_index += 1;
119        }
120
121        assert!(
122            match_count == 1,
123            "Initialized fields do not match the target struct's fields"
124        );
125        assert!(
126            !is_pinned || (pinned && initialized_in_place),
127            "`#[pin]` fields must be initialized with the `<-` syntax in `pin_init!`"
128        );
129        expected_index += 1;
130    }
131}
132
133/// 在常量求值期间逐字节比较字段名。
134/// Compare field names byte by byte during constant evaluation.
135const fn __str_eq(left: &str, right: &str) -> bool {
136    let left = left.as_bytes();
137    let right = right.as_bytes();
138    if left.len() != right.len() {
139        return false;
140    }
141
142    let mut index = 0;
143    while index < left.len() {
144        if left[index] != right[index] {
145            return false;
146        }
147        index += 1;
148    }
149    true
150}