#[cfg(feature = "std")]
use std::sync::OnceLock as Inner;
#[cfg(not(feature = "std"))]
use spin::Once as Inner;
pub(crate) struct SyncOnceCell<T>(Inner<T>);
impl<T: core::fmt::Debug> core::fmt::Debug for SyncOnceCell<T> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_tuple("SyncOnceCell").field(&self.get()).finish()
}
}
impl<T> SyncOnceCell<T> {
pub fn new() -> Self {
Self(Inner::new())
}
pub fn initialized(value: T) -> Self {
#[cfg(feature = "std")]
{
let cell = Inner::new();
cell.set(value).ok().expect("cell was just created");
Self(cell)
}
#[cfg(not(feature = "std"))]
{
Self(Inner::initialized(value))
}
}
pub fn get(&self) -> Option<&T> {
self.0.get()
}
pub fn get_or_init<F: FnOnce() -> T>(&self, f: F) -> &T {
#[cfg(feature = "std")]
{
self.0.get_or_init(f)
}
#[cfg(not(feature = "std"))]
{
self.0.call_once(f)
}
}
}