Skip to main content

inplace_init/init/
initializer.rs

1//! 初始化器适配器、闭包封装和编译期常量初始化器。
2//! Initializer adapters, closure wrappers, and compile-time constant initializers.
3
4use core::{convert::Infallible, marker::PhantomData};
5
6use crate::init::{Init, InitDefault, InitMode, InitReceipt, InitSlot, PinInitMode};
7
8/// 错误映射后的初始化器。
9/// An initializer wrapper that converts the underlying initializer's error.
10///
11/// 只有初始化失败时才调用映射闭包;成功时保留原始析构凭证。
12/// The mapping closure runs only on failure; on success, the original destruction receipt is preserved.
13pub struct MapInitError<I, F, E, Mode = InitMode> {
14    initializer: I,
15    map: F,
16    _error: PhantomData<fn(E)>,
17    _mode: PhantomData<fn() -> Mode>,
18}
19
20impl<I, F, E, Mode> MapInitError<I, F, E, Mode> {
21    /// 创建保留原错误类型和地址模式的映射适配器。
22    /// Create a mapping adapter that retains the original error type and address mode.
23    pub(crate) fn new(initializer: I, map: F) -> Self {
24        Self {
25            initializer,
26            map,
27            _error: PhantomData,
28            _mode: PhantomData,
29        }
30    }
31}
32
33// 安全性依据:底层 Init 的 unsafe 契约保证错误时槽位未初始化;映射闭包只转换错误,成功时保留原凭证。
34// Safety: the underlying Init contract guarantees an uninitialized slot on error; the mapper only converts errors and preserves the original receipt on success.
35unsafe impl<T, E1, E2, I, F, Mode> Init<T, E2, Mode> for MapInitError<I, F, E1, Mode>
36where
37    I: Init<T, E1, Mode>,
38    F: FnOnce(E1) -> E2,
39{
40    fn initialize<'slot>(
41        self,
42        slot: InitSlot<'slot, T, Mode>,
43    ) -> Result<InitReceipt<'slot, T, Mode>, E2> {
44        let MapInitError {
45            initializer, map, ..
46        } = self;
47        match initializer.initialize(slot) {
48            Ok(receipt) => {
49                drop(map);
50                Ok(receipt)
51            }
52            Err(error) => Err(map(error)),
53        }
54    }
55}
56
57struct InitFnMarker<T, E, Mode> {
58    _value: PhantomData<fn() -> T>,
59    _error: PhantomData<fn() -> E>,
60    _mode: PhantomData<fn() -> Mode>,
61}
62
63/// 将按值构造闭包适配为普通可移动模式的初始化器。
64/// Adapts a by-value construction closure into a movable-mode initializer.
65///
66/// 闭包只需返回一个值或错误;值会在目标槽位中写入,错误或 panic 不会留下已初始化状态。固定地址初始化请使用 [`InitFnRaw`] 或其他支持固定模式的初始化器。
67/// The closure only returns a value or error; the value is written into the target slot, and an error or panic cannot leave initialized state behind. Use [`InitFnRaw`] or another pinned-mode initializer for pinned initialization.
68pub struct InitFn<T, E, F> {
69    initialize: F,
70    _marker: InitFnMarker<T, E, InitMode>,
71}
72
73impl<T, E, F> InitFn<T, E, F> {
74    /// 封装一个无参数、返回值或错误的闭包。
75    /// Wrap a no-argument closure that returns a value or an error.
76    pub fn new(initialize: F) -> Self
77    where
78        F: FnOnce() -> Result<T, E>,
79    {
80        Self {
81            initialize,
82            _marker: InitFnMarker {
83                _value: PhantomData,
84                _error: PhantomData,
85                _mode: PhantomData,
86            },
87        }
88    }
89}
90
91// 安全性依据:闭包只按值返回 T;错误或 panic 时尚未写入槽位,成功时 slot.write 创建唯一凭证。
92// Safety: the closure only returns T by value; errors and panics occur before the slot is written, and slot.write creates the sole receipt on success.
93unsafe impl<T, E, F> Init<T, E, InitMode> for InitFn<T, E, F>
94where
95    F: FnOnce() -> Result<T, E>,
96{
97    fn initialize<'slot>(
98        self,
99        slot: InitSlot<'slot, T, InitMode>,
100    ) -> Result<InitReceipt<'slot, T, InitMode>, E> {
101        let value = (self.initialize)()?;
102        Ok(slot.write(value))
103    }
104}
105
106/// 由闭包直接在目标槽位中构造值的原始初始化器包装类型。
107/// Raw initializer wrapper for closures that construct a value directly in the target slot.
108///
109/// 闭包必须返回与槽位生命周期一致的凭证,因此不能把槽位引用或凭证延长到目标借用之外。
110/// The closure must return a receipt tied to the slot lifetime, so neither the slot nor its receipt can outlive the target borrow.
111pub struct InitFnRaw<T, E, F, Mode = InitMode> {
112    initialize: F,
113    _marker: InitFnMarker<T, E, Mode>,
114}
115
116impl<T, E, F, Mode> InitFnRaw<T, E, F, Mode> {
117    /// 封装一个接收目标槽位并返回初始化结果的闭包。
118    /// Wrap a closure that accepts a target slot and returns the initialization result.
119    ///
120    /// # 安全性要求
121    /// 闭包必须满足 [`Init`] 的完整安全契约:成功时只留下一个完整目标并返回唯一凭证;
122    /// 返回错误或 panic 时清理所有已构造状态;同时遵守地址模式约束。
123    ///
124    /// # Safety
125    /// The closure must uphold the full [`Init`] safety contract: leave exactly one complete
126    /// target and return its sole receipt on success; clean up every initialized part on error or
127    /// panic; and uphold the address-mode requirements.
128    pub unsafe fn new(initialize: F) -> Self
129    where
130        F: for<'slot> FnOnce(InitSlot<'slot, T, Mode>) -> Result<InitReceipt<'slot, T, Mode>, E>,
131    {
132        Self {
133            initialize,
134            _marker: InitFnMarker {
135                _value: PhantomData,
136                _error: PhantomData,
137                _mode: PhantomData,
138            },
139        }
140    }
141}
142
143// 安全性依据:InitFnRaw 只能通过 unsafe new 创建,调用者承诺闭包满足 Init 的完整契约。
144// Safety: InitFnRaw can only be constructed through unsafe new, whose caller promises the closure upholds the full Init contract.
145unsafe impl<T, E, F, Mode> Init<T, E, Mode> for InitFnRaw<T, E, F, Mode>
146where
147    F: for<'slot> FnOnce(InitSlot<'slot, T, Mode>) -> Result<InitReceipt<'slot, T, Mode>, E>,
148{
149    fn initialize<'slot>(
150        self,
151        slot: InitSlot<'slot, T, Mode>,
152    ) -> Result<InitReceipt<'slot, T, Mode>, E> {
153        (self.initialize)(slot)
154    }
155}
156
157macro_rules! const_init {
158    ($name:ident, $value_type:ty, $default:expr) => {
159        #[doc = concat!("使用编译期 `", stringify!($value_type), "` 常量构造值的初始化器。 / An initializer that constructs a value from a compile-time `", stringify!($value_type), "` constant.")]
160        pub struct $name<const VALUE: $value_type>;
161
162        unsafe impl<Mode> InitDefault<$value_type, Mode> for $value_type {
163            fn initialize_default<'slot>(
164                slot: InitSlot<'slot, $value_type, Mode>,
165            ) -> InitReceipt<'slot, $value_type, Mode> {
166                slot.write($default)
167            }
168        }
169
170        unsafe impl<const VALUE: $value_type, Mode> InitDefault<$value_type, Mode>
171            for $name<VALUE>
172        {
173            fn initialize_default<'slot>(
174                slot: InitSlot<'slot, $value_type, Mode>,
175            ) -> InitReceipt<'slot, $value_type, Mode> {
176                slot.write(VALUE)
177            }
178        }
179
180        // 安全性依据:slot.write 原子地写入一个完整标量并返回其唯一凭证。
181        // Safety: slot.write constructs one complete scalar and returns its sole receipt.
182        unsafe impl<const VALUE: $value_type> Init<$value_type> for $name<VALUE> {
183            fn initialize<'slot>(
184                self,
185                slot: InitSlot<'slot, $value_type>,
186            ) -> Result<InitReceipt<'slot, $value_type>, Infallible> {
187                Ok(slot.write(VALUE))
188            }
189        }
190
191        // 安全性依据:标量不依赖固定地址,slot.write 完整构造值并返回其唯一凭证。
192        // Safety: scalars do not depend on a stable address, and slot.write constructs the complete value and returns its sole receipt.
193        unsafe impl<const VALUE: $value_type> Init<$value_type, Infallible, PinInitMode> for $name<VALUE> {
194            fn initialize<'slot>(
195                self,
196                slot: InitSlot<'slot, $value_type, PinInitMode>,
197            ) -> Result<InitReceipt<'slot, $value_type, PinInitMode>, Infallible> {
198                Ok(slot.write(VALUE))
199            }
200        }
201    };
202}
203
204const_init!(InitTyBool, bool, false);
205const_init!(InitTyChar, char, '\0');
206const_init!(InitTyI8, i8, 0);
207const_init!(InitTyI16, i16, 0);
208const_init!(InitTyI32, i32, 0);
209const_init!(InitTyI64, i64, 0);
210const_init!(InitTyI128, i128, 0);
211const_init!(InitTyIsize, isize, 0);
212const_init!(InitTyU8, u8, 0);
213const_init!(InitTyU16, u16, 0);
214const_init!(InitTyU32, u32, 0);
215const_init!(InitTyU64, u64, 0);
216const_init!(InitTyU128, u128, 0);
217const_init!(InitTyUsize, usize, 0);