# ![doc = include_str!("../README.md")]
#![cfg_attr(feature = "no_std", no_std)]
#[cfg(all(not(feature = "no_std"), test))]
mod tests;
#[cfg(feature = "alloc")]
extern crate alloc;
use ::core::{
cell::UnsafeCell,
error::Error,
fmt::Display,
ops::Deref,
sync::atomic::{AtomicUsize, Ordering},
};
#[cfg(feature = "alloc")]
use alloc::boxed::Box;
use core::fmt::Debug;
#[derive(Debug)]
pub enum OnceInitError {
DataUninitialized,
DataInitialized,
}
impl Display for OnceInitError {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
match self {
OnceInitError::DataUninitialized => f.write_str("data is uninitialized."),
OnceInitError::DataInitialized => f.write_str("data has already been initialized."),
}
}
}
impl Error for OnceInitError {}
#[derive(Debug)]
#[repr(usize)]
pub enum OnceInitState {
UNINITIALIZED = 0,
INITIALIZED = 2,
}
const UNINITIALIZED: usize = 0;
const INITIALIZING: usize = 1;
const INITIALIZED: usize = 2;
pub struct OnceInit<T: ?Sized + 'static>
where
&'static T: Sized,
{
state: AtomicUsize,
data: UnsafeCell<Option<&'static T>>,
}
impl<T: ?Sized> OnceInit<T> {
#[inline]
pub const fn uninit() -> Self {
Self {
state: AtomicUsize::new(UNINITIALIZED),
data: UnsafeCell::new(None),
}
}
#[inline]
pub const fn new(data: &'static T) -> Self
where
&'static T: Sized,
Self: Sized,
{
Self {
state: AtomicUsize::new(INITIALIZED),
data: UnsafeCell::new(Some(data)),
}
}
#[inline]
pub fn get(&self) -> Result<&'static T, OnceInitError> {
match self.state.load(Ordering::Acquire) {
INITIALIZED => Ok(unsafe { (*self.data.get()).unwrap_unchecked() }),
INITIALIZING => {
while self.state.load(Ordering::SeqCst) == INITIALIZING {
core::hint::spin_loop()
}
Ok(unsafe { (*self.data.get()).unwrap_unchecked() })
}
_ => Err(OnceInitError::DataUninitialized),
}
}
#[inline]
pub fn get_or_default(&self) -> &'static T
where
T: StaticDefault,
{
self.get().unwrap_or_else(|_| T::static_default())
}
#[inline]
pub unsafe fn get_unchecked(&self) -> &'static T {
unsafe { (*self.data.get()).unwrap_unchecked() }
}
pub fn state(&self) -> OnceInitState {
match self.state.load(Ordering::Acquire) {
UNINITIALIZED => OnceInitState::UNINITIALIZED,
INITIALIZING => {
while self.state.load(Ordering::SeqCst) == INITIALIZING {
core::hint::spin_loop()
}
OnceInitState::UNINITIALIZED
}
INITIALIZED => OnceInitState::INITIALIZED,
_ => unreachable!(),
}
}
fn init_internal<F>(&self, make_data: F) -> Result<(), OnceInitError>
where
F: FnOnce() -> &'static T,
{
let old_state = match self.state.compare_exchange(
UNINITIALIZED,
INITIALIZING,
Ordering::SeqCst,
Ordering::SeqCst,
) {
Ok(s) | Err(s) => s,
};
match old_state {
INITIALIZING => {
while self.state.load(Ordering::SeqCst) == INITIALIZING {
core::hint::spin_loop()
}
Err(OnceInitError::DataInitialized)
}
INITIALIZED => Err(OnceInitError::DataInitialized),
_ => {
unsafe { *self.data.get() = Some(make_data()) }
self.state.store(INITIALIZED, Ordering::SeqCst);
Ok(())
}
}
}
#[inline]
pub fn init(&self, data: &'static T) -> Result<(), OnceInitError> {
self.init_internal(|| data)
}
#[inline]
#[cfg(any(feature = "alloc", not(feature = "no_std")))]
pub fn init_boxed(&self, data: Box<T>) -> Result<(), OnceInitError> {
self.init_internal(|| Box::leak(data))
}
}
unsafe impl<T> Sync for OnceInit<T> where T: ?Sized + Sync {}
impl<T> Default for OnceInit<T>
where
T: ?Sized + StaticDefault,
Self: Sized,
{
#[inline]
fn default() -> Self {
Self::new(T::static_default())
}
}
impl<T: ?Sized + Debug> Debug for OnceInit<T> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let mut d = f.debug_tuple("OnceInit");
match self.get().ok() {
Some(data) => d.field(&data),
None => d.field(&format_args!("<uninit>")),
};
d.finish()
}
}
pub unsafe trait StaticDefault {
fn static_default() -> &'static Self;
}
impl<T: ?Sized + StaticDefault> Deref for OnceInit<T> {
type Target = T;
#[inline]
fn deref(&self) -> &'static Self::Target {
self.get_or_default()
}
}
pub trait UninitGlobalHolder<T: ?Sized> {
fn init(&self, data: &'static T) -> Result<(), OnceInitError>;
#[cfg(any(feature = "alloc", not(feature = "no_std")))]
fn init_boxed(&self, data: Box<T>) -> Result<(), OnceInitError>;
}
impl<T: ?Sized> UninitGlobalHolder<T> for OnceInit<T> {
#[inline]
fn init(&self, data: &'static T) -> Result<(), OnceInitError> {
OnceInit::init(self, data)
}
#[inline]
fn init_boxed(&self, data: Box<T>) -> Result<(), OnceInitError> {
OnceInit::init_boxed(self, data)
}
}
pub trait UninitGlobal<T: ?Sized, M> {
fn holder() -> &'static M;
#[inline]
fn init(data: &'static T) -> Result<(), OnceInitError>
where
M: UninitGlobalHolder<T> + 'static,
{
Self::holder().init(data)
}
#[inline]
#[cfg(any(feature = "alloc", not(feature = "no_std")))]
fn init_boxed(data: Box<T>) -> Result<(), OnceInitError>
where
M: UninitGlobalHolder<T> + 'static,
{
Self::holder().init_boxed(data)
}
}