use core::cell::UnsafeCell;
use core::mem::MaybeUninit;
use core::sync::atomic::{AtomicBool, Ordering};
struct Claimed<T: 'static>(*mut T);
impl<T> Claimed<T> {
#[inline(always)]
fn into_ref(self) -> &'static mut T {
unsafe { &mut *self.0 }
}
}
pub struct StaticCell<T> {
used: AtomicBool,
val: UnsafeCell<MaybeUninit<T>>,
}
unsafe impl<T> Send for StaticCell<T> {}
unsafe impl<T> Sync for StaticCell<T> {}
impl<T> StaticCell<T> {
#[inline]
pub const fn new() -> Self {
Self {
used: AtomicBool::new(false),
val: UnsafeCell::new(MaybeUninit::uninit()),
}
}
#[inline]
fn try_claim(&'static self) -> Option<Claimed<MaybeUninit<T>>> {
self.used
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
.ok()
.map(|_| Claimed(self.val.get()))
}
#[inline]
#[track_caller]
pub fn init(&'static self, val: T) -> &'static mut T {
self.uninit().write(val)
}
#[inline]
#[track_caller]
pub fn init_with(&'static self, f: impl FnOnce() -> T) -> &'static mut T {
self.uninit().write(f())
}
#[inline]
#[track_caller]
pub fn uninit(&'static self) -> &'static mut MaybeUninit<T> {
match self.try_uninit() {
Some(v) => v,
None => panic!("StaticCell already initialized"),
}
}
#[inline]
pub fn try_init(&'static self, val: T) -> Option<&'static mut T> {
Some(self.try_uninit()?.write(val))
}
#[inline]
pub fn try_init_with(&'static self, f: impl FnOnce() -> T) -> Option<&'static mut T> {
Some(self.try_uninit()?.write(f()))
}
#[inline]
pub fn try_uninit(&'static self) -> Option<&'static mut MaybeUninit<T>> {
self.try_claim().map(Claimed::into_ref)
}
}
impl<T> Default for StaticCell<T> {
#[inline]
fn default() -> Self {
Self::new()
}
}
pub struct ConstStaticCell<T> {
taken: AtomicBool,
val: UnsafeCell<T>,
}
unsafe impl<T: Send> Send for ConstStaticCell<T> {}
unsafe impl<T: Send> Sync for ConstStaticCell<T> {}
impl<T> ConstStaticCell<T> {
#[inline]
pub const fn new(value: T) -> Self {
Self {
taken: AtomicBool::new(false),
val: UnsafeCell::new(value),
}
}
#[inline]
fn try_claim(&'static self) -> Option<Claimed<T>> {
self.taken
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
.ok()
.map(|_| Claimed(self.val.get()))
}
#[inline]
#[track_caller]
pub fn take(&'static self) -> &'static mut T {
match self.try_take() {
Some(v) => v,
None => panic!("ConstStaticCell already taken"),
}
}
#[inline]
pub fn try_take(&'static self) -> Option<&'static mut T> {
self.try_claim().map(Claimed::into_ref)
}
}
#[macro_export]
macro_rules! make_static {
($t:ty, || $body:expr) => {{
static CELL: $crate::kit::cell::StaticCell<$t> = $crate::kit::cell::StaticCell::new();
CELL.init_with(|| $body)
}};
($t:ty, $val:expr) => {{
static CELL: $crate::kit::cell::StaticCell<$t> = $crate::kit::cell::StaticCell::new();
CELL.init($val)
}};
}