onceinit/
lib.rs

1// MIT License
2//
3// Copyright (c) 2025 worksoup <https://github.com/worksoup/>
4//
5// Permission is hereby granted, free of charge, to any person obtaining a copy
6// of this software and associated documentation files (the "Software"), to deal
7// in the Software without restriction, including without limitation the rights
8// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9// copies of the Software, and to permit persons to whom the Software is
10// furnished to do so, subject to the following conditions:
11//
12// The above copyright notice and this permission notice shall be included in all
13// copies or substantial portions of the Software.
14//
15// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21// SOFTWARE.
22
23# ![doc = include_str!("../README.md")]
24#![cfg_attr(feature = "no_std", no_std)]
25#[cfg(all(not(feature = "no_std"), test))]
26mod tests;
27
28#[cfg(feature = "alloc")]
29extern crate alloc;
30
31use ::core::{
32    cell::UnsafeCell,
33    error::Error,
34    fmt::Display,
35    ops::Deref,
36    sync::atomic::{AtomicUsize, Ordering},
37};
38#[cfg(feature = "alloc")]
39use alloc::boxed::Box;
40use core::fmt::Debug;
41
42#[derive(Debug)]
43/// # `OnceInitError`
44/// 读取或初始化 [`OnceInit`] 内部数据时可能返回该错误。
45pub enum OnceInitError {
46    /// 数据未被初始化。
47    DataUninitialized,
48    /// 数据已被初始化。
49    DataInitialized,
50}
51
52impl Display for OnceInitError {
53    #[inline]
54    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
55        match self {
56            OnceInitError::DataUninitialized => f.write_str("data is uninitialized."),
57            OnceInitError::DataInitialized => f.write_str("data has already been initialized."),
58        }
59    }
60}
61impl Error for OnceInitError {}
62#[derive(Debug)]
63#[repr(usize)]
64/// # `OnceInitState`
65/// 表示 [`OnceInit`] 内部数据的初始化状态。
66pub enum OnceInitState {
67    /// 数据未被初始化。
68    UNINITIALIZED = 0,
69    /// 数据已被初始化。
70    INITIALIZED = 2,
71}
72
73const UNINITIALIZED: usize = 0;
74const INITIALIZING: usize = 1;
75const INITIALIZED: usize = 2;
76
77/// # `OnceInit`
78/// 仅可设置一次数据的类型。
79///
80/// 当 `T` 实现了 [`Sync`] 时,该类型也会实现 [`Sync`].
81/// [`Sync`] 是由内部原子类型的 `state` 和外部 api 共同保证的。
82/// 外部 api 保证,当 `state` 指示数据正在或已经初始化时,该类型不可变。
83pub struct OnceInit<T: ?Sized + 'static>
84where
85    &'static T: Sized,
86{
87    state: AtomicUsize,
88    data: UnsafeCell<Option<&'static T>>,
89}
90
91impl<T: ?Sized> OnceInit<T> {
92    /// 返回未初始化的 [`OnceInit`] 类型。
93    #[inline]
94    pub const fn uninit() -> Self {
95        Self {
96            state: AtomicUsize::new(UNINITIALIZED),
97            data: UnsafeCell::new(None),
98        }
99    }
100    /// 返回初始化过的 [`OnceInit`] 类型。
101    #[inline]
102    pub const fn new(data: &'static T) -> Self
103    where
104        &'static T: Sized,
105        Self: Sized,
106    {
107        Self {
108            state: AtomicUsize::new(INITIALIZED),
109            data: UnsafeCell::new(Some(data)),
110        }
111    }
112    /// 返回内部数据,若未初始化,则返回 [`OnceInitError`].
113    ///
114    /// 若需要可变数据,请在内部使用具有内部可见性的数据结构,如 [`Mutex`](std::sync::Mutex) 等。
115    #[inline]
116    pub fn get(&self) -> Result<&'static T, OnceInitError> {
117        match self.state.load(Ordering::Acquire) {
118            INITIALIZED => Ok(unsafe { (*self.data.get()).unwrap_unchecked() }),
119            INITIALIZING => {
120                while self.state.load(Ordering::SeqCst) == INITIALIZING {
121                    core::hint::spin_loop()
122                }
123                Ok(unsafe { (*self.data.get()).unwrap_unchecked() })
124            }
125            _ => Err(OnceInitError::DataUninitialized),
126        }
127    }
128    /// 返回内部数据,若未初始化,则返回 `<T as StaticDefault>::static_default()`.
129    ///
130    /// 需要 `T` 实现 [`StaticDefault`].
131    #[inline]
132    pub fn get_or_default(&self) -> &'static T
133    where
134        T: StaticDefault,
135    {
136        self.get().unwrap_or_else(|_| T::static_default())
137    }
138    /// 不检查是否初始化,直接返回内部数据。
139    ///
140    /// 若需要可变数据,请在内部使用具有内部可见性的数据结构,如 [`Mutex`](std::sync::Mutex) 等。
141    ///
142    /// # Safety
143    ///
144    /// 未初始化时,调用此函数会在内部的 [`None`] 值上调用 [`Option::unwrap_unchecked`], 造成[*未定义行为*]。
145    ///
146    /// [*未定义行为*]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
147    #[inline]
148    pub unsafe fn get_unchecked(&self) -> &'static T {
149        unsafe { (*self.data.get()).unwrap_unchecked() }
150    }
151    /// 返回数据状态,见 [`OnceInitState`].
152    pub fn state(&self) -> OnceInitState {
153        match self.state.load(Ordering::Acquire) {
154            UNINITIALIZED => OnceInitState::UNINITIALIZED,
155            INITIALIZING => {
156                while self.state.load(Ordering::SeqCst) == INITIALIZING {
157                    core::hint::spin_loop()
158                }
159                OnceInitState::UNINITIALIZED
160            }
161            INITIALIZED => OnceInitState::INITIALIZED,
162            _ => unreachable!(),
163        }
164    }
165    fn init_internal<F>(&self, make_data: F) -> Result<(), OnceInitError>
166    where
167        F: FnOnce() -> &'static T,
168    {
169        let old_state = match self.state.compare_exchange(
170            UNINITIALIZED,
171            INITIALIZING,
172            Ordering::SeqCst,
173            Ordering::SeqCst,
174        ) {
175            Ok(s) | Err(s) => s,
176        };
177        match old_state {
178            INITIALIZING => {
179                while self.state.load(Ordering::SeqCst) == INITIALIZING {
180                    core::hint::spin_loop()
181                }
182                Err(OnceInitError::DataInitialized)
183            }
184            INITIALIZED => Err(OnceInitError::DataInitialized),
185            _ => {
186                unsafe { *self.data.get() = Some(make_data()) }
187                self.state.store(INITIALIZED, Ordering::SeqCst);
188                Ok(())
189            }
190        }
191    }
192    /// 初始化内部数据,只可调用一次,成功则初始化完成,之后调用均会返回错误。
193    ///
194    /// 如果 `data` 不是 `'static` 的,请使用 [`init_boxed`](Self::init_boxed).
195    #[inline]
196    pub fn init(&self, data: &'static T) -> Result<(), OnceInitError> {
197        self.init_internal(|| data)
198    }
199    /// 初始化内部数据,只可调用一次,成功则初始化完成,之后调用均会返回错误。
200    #[inline]
201    #[cfg(any(feature = "alloc", not(feature = "no_std")))]
202    pub fn init_boxed(&self, data: Box<T>) -> Result<(), OnceInitError> {
203        self.init_internal(|| Box::leak(data))
204    }
205}
206unsafe impl<T> Sync for OnceInit<T> where T: ?Sized + Sync {}
207impl<T> Default for OnceInit<T>
208where
209    T: ?Sized + StaticDefault,
210    Self: Sized,
211{
212    #[inline]
213    fn default() -> Self {
214        Self::new(T::static_default())
215    }
216}
217impl<T: ?Sized + Debug> Debug for OnceInit<T> {
218    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
219        let mut d = f.debug_tuple("OnceInit");
220        match self.get().ok() {
221            Some(data) => d.field(&data),
222            None => d.field(&format_args!("<uninit>")),
223        };
224        d.finish()
225    }
226}
227
228/// # [`StaticDefault`]
229///
230/// 返回类型的 `'static` 生命周期引用。
231///
232/// ## Safety
233///
234/// 在实现该类型时,应当避免使用 [`Box::leak`], 这是因为该特型专为 [`OnceInit`] 设计,
235/// 且 `OnceInit` **不保证** [`static_default`](StaticDefault::static_default) 只被调用一次。
236///
237/// 若内部使用了 `Box::leak`, 则可能会造成大量内存泄漏。
238///
239/// 最好只为真正拥有静态变量的类型实现该特型。
240/// 如需使用 `Box::leak`, 请记得[初始化 `OnceInit`](OnceInit::init),
241/// 初始化后的 `OnceInit` 将不再调用 `static_default`.
242pub unsafe trait StaticDefault {
243    /// 返回类型的 `'static` 生命周期引用。
244    fn static_default() -> &'static Self;
245}
246impl<T: ?Sized + StaticDefault> Deref for OnceInit<T> {
247    type Target = T;
248
249    #[inline]
250    fn deref(&self) -> &'static Self::Target {
251        self.get_or_default()
252    }
253}
254/// 指示拥有一个全局实例,但可能未初始化。
255pub trait UninitGlobalHolder<T: ?Sized> {
256    /// 初始化内部数据。
257    fn init(&self, data: &'static T) -> Result<(), OnceInitError>;
258    /// 初始化内部数据。
259    #[cfg(any(feature = "alloc", not(feature = "no_std")))]
260    fn init_boxed(&self, data: Box<T>) -> Result<(), OnceInitError>;
261}
262impl<T: ?Sized> UninitGlobalHolder<T> for OnceInit<T> {
263    /// 初始化内部数据,只可调用一次,成功则初始化完成,之后调用均会返回错误。
264    ///
265    /// 如果 `data` 不是 `'static` 的,请使用 [`init_boxed`](Self::init_boxed).
266    #[inline]
267    fn init(&self, data: &'static T) -> Result<(), OnceInitError> {
268        OnceInit::init(self, data)
269    }
270    /// 初始化内部数据,只可调用一次,成功则初始化完成,之后调用均会返回错误。
271    #[inline]
272    fn init_boxed(&self, data: Box<T>) -> Result<(), OnceInitError> {
273        OnceInit::init_boxed(self, data)
274    }
275}
276/// 一个可能有用的模式。
277///
278/// 该模式表示:类型 `T` 拥有一个全局实例,并被 `M` 包装,可以对其进行初始化。
279pub trait UninitGlobal<T: ?Sized, M> {
280    fn holder() -> &'static M;
281    #[inline]
282    fn init(data: &'static T) -> Result<(), OnceInitError>
283    where
284        M: UninitGlobalHolder<T> + 'static,
285    {
286        Self::holder().init(data)
287    }
288    #[inline]
289    #[cfg(any(feature = "alloc", not(feature = "no_std")))]
290    fn init_boxed(data: Box<T>) -> Result<(), OnceInitError>
291    where
292        M: UninitGlobalHolder<T> + 'static,
293    {
294        Self::holder().init_boxed(data)
295    }
296}