inplace_init/storage.rs
1//! 可消费的未初始化存储容器,以及将初始化器接入堆分配的扩展 trait。
2//! Consumable uninitialized-storage containers and extension traits for heap allocation.
3
4use core::{
5 mem::MaybeUninit,
6 ops::{Deref, DerefMut},
7};
8
9use crate::{
10 init::{Init, InitDefault, InitDefaultInit, InitMode},
11 init_in,
12};
13
14#[cfg(feature = "alloc")]
15use crate::{init::PinInitMode, pin_init_in};
16#[cfg(feature = "alloc")]
17use alloc::boxed::Box;
18#[cfg(feature = "alloc")]
19use core::{mem::forget, pin::Pin};
20
21/// 可消费的普通初始化存储。
22/// Consumable storage for movable initialization.
23///
24/// 初始化成功后会交付拥有型 [`InitValue`];失败时错误返回给调用方,尚未初始化的存储随容器释放。
25/// Success yields an owning [`InitValue`]; on failure, the error is returned and the uninitialized storage is released with the container.
26pub struct InitStorage<T> {
27 storage: MaybeUninit<T>,
28}
29
30impl<T> InitStorage<T> {
31 /// 创建尚未初始化的拥有型存储。
32 /// Create owned storage that does not yet contain a `T`.
33 pub const fn uninit() -> Self {
34 Self {
35 storage: MaybeUninit::uninit(),
36 }
37 }
38
39 /// 消耗未初始化存储,并尝试返回拥有初始化值的对象。
40 /// Consume the uninitialized storage and try to return an object that owns the initialized value.
41 ///
42 /// 错误不会产生 `InitValue`;若初始化器失败,调用方只会收到其错误值。
43 /// No `InitValue` is produced on error; if the initializer fails, the caller receives its error value.
44 /// 该错误路径依赖 `Init` 的 unsafe 契约:返回错误或 panic 时,存储必须保持未初始化。
45 /// The error path relies on `Init`'s unsafe contract that storage remains uninitialized on error or panic.
46 pub fn initialize<I, E>(mut self, initializer: I) -> Result<InitValue<T>, E>
47 where
48 I: Init<T, E>,
49 {
50 let receipt = init_in(&mut self.storage, initializer)?;
51 Ok(InitValue {
52 value: receipt.into_inner(),
53 })
54 }
55
56 /// 在存储槽位中构造默认值并返回拥有该值的对象。
57 /// Construct the default value in the storage slot and return an object that owns it.
58 pub fn initialize_default(self) -> InitValue<T>
59 where
60 T: InitDefault<T, InitMode>,
61 {
62 self.initialize_default_with::<T>()
63 }
64
65 /// 使用指定的默认值提供者在存储槽位中构造目标。
66 /// Construct the target in the storage slot using the specified default-value provider.
67 ///
68 /// `I` 可以与 `T` 不同,只要它实现了针对 `T` 和普通地址模式的 [`InitDefault`]。
69 /// `I` may differ from `T` as long as it implements [`InitDefault`] for `T` in movable mode.
70 pub fn initialize_default_with<I>(self) -> InitValue<T>
71 where
72 I: InitDefault<T, InitMode>,
73 {
74 match self.initialize(InitDefaultInit::<T, I>::new()) {
75 Ok(value) => value,
76 Err(never) => match never {},
77 }
78 }
79}
80
81/// 由普通初始化存储返回、拥有完整值的容器。
82/// An owning container returned by ordinary initialization storage.
83///
84/// 它负责析构内部值,并提供借用、可变借用或移出值的入口。
85/// It drops the contained value and provides shared borrowing, mutable borrowing, and ownership extraction.
86pub struct InitValue<T> {
87 value: T,
88}
89
90impl<T> InitValue<T> {
91 /// 借用内部值。
92 /// Borrow the contained value.
93 pub fn get(&self) -> &T {
94 &self.value
95 }
96
97 /// 独占借用内部值。
98 /// Mutably borrow the contained value.
99 pub fn get_mut(&mut self) -> &mut T {
100 &mut self.value
101 }
102
103 /// 移出内部值并转移所有权。
104 /// Move the contained value out and transfer ownership to the caller.
105 pub fn into_inner(self) -> T {
106 self.value
107 }
108}
109
110impl<T> Deref for InitValue<T> {
111 type Target = T;
112
113 fn deref(&self) -> &Self::Target {
114 &self.value
115 }
116}
117
118impl<T> DerefMut for InitValue<T> {
119 fn deref_mut(&mut self) -> &mut Self::Target {
120 &mut self.value
121 }
122}
123
124#[cfg(feature = "alloc")]
125/// 为普通初始化器提供堆分配入口。
126/// Adds a heap-allocation entry point for movable initializers.
127pub trait InitBoxExt<T, E>: Init<T, E> {
128 /// 在堆存储中构造一个允许移动的值。
129 /// Construct a movable value in heap storage and return its owning `Box`.
130 fn init_box(self) -> Result<Box<T>, E>
131 where
132 Self: Sized,
133 {
134 let mut storage = Box::new(MaybeUninit::<T>::uninit());
135 let receipt = init_in(&mut storage, self)?;
136 forget(receipt);
137 // 安全性:凭证已将析构责任转交给同一分配中的 Box<T>。 Safety: the receipt's drop responsibility is transferred to `Box<T>` for the same allocation.
138 Ok(unsafe { storage.assume_init() })
139 }
140}
141
142#[cfg(feature = "alloc")]
143impl<T, E, I> InitBoxExt<T, E> for I where I: Init<T, E> {}
144
145#[cfg(feature = "alloc")]
146/// 为固定地址初始化器提供堆分配入口。
147/// Adds a heap-allocation entry point for pinned initializers.
148pub trait PinInitBoxExt<T, E>: Init<T, E, PinInitMode> {
149 /// 在堆分配的最终地址中构造并固定一个值。
150 /// Construct and pin a value at its final address in a heap allocation.
151 fn pin_box(self) -> Result<Pin<Box<T>>, E>
152 where
153 Self: Sized,
154 {
155 let mut storage = Box::new(MaybeUninit::<T>::uninit());
156 // 安全性:Box 提供对齐且足够大的稳定存储,分配在转换前不会移动。 Safety: `Box` provides aligned storage of sufficient size, and the allocation does not move during conversion.
157 let pinned_storage = unsafe { Pin::new_unchecked(&mut *storage) };
158 // 安全性:本方法独占分配,并在返回后把该分配转换为 Pin<Box<T>>。 Safety: this method exclusively owns the allocation and converts it to `Pin<Box<T>>` before returning.
159 let receipt = unsafe { pin_init_in(pinned_storage, self)? };
160 forget(receipt);
161 // 安全性:凭证已将固定值的析构责任转交给同一稳定分配。 Safety: the receipt's drop responsibility for the pinned value is transferred to the same stable allocation.
162 let value = unsafe { storage.assume_init() };
163 Ok(Box::into_pin(value))
164 }
165}
166
167#[cfg(feature = "alloc")]
168impl<T, E, I> PinInitBoxExt<T, E> for I where I: Init<T, E, PinInitMode> {}