use std::{
cell::UnsafeCell,
hint::{likely, unlikely},
mem::MaybeUninit,
panic::AssertUnwindSafe,
sync::{atomic::{AtomicBool, AtomicU8, Ordering}},
future::Future
};
use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard, Mutex};
use futures_util::future::FutureExt;
use crate::{traits::CellTrait, utils::yield_now};
#[repr(transparent)]
struct ResetOnDrop<'a> {
state: &'a AtomicU8,
}
impl<'a> Drop for ResetOnDrop<'a> {
fn drop(&mut self) {
self.state.store(0, Ordering::Release);
}
}
#[repr(C, align(128))]
pub struct RawCell<T> {
state: AtomicU8,
value: UnsafeCell<MaybeUninit<RwLock<T>>>,
}
unsafe impl<T: Send> Send for RawCell<T> {}
unsafe impl<T: Sync> Sync for RawCell<T> {}
impl<T> RawCell<T> {
const UNINIT: u8 = 0;
const INITING: u8 = 1;
const INITED: u8 = 2;
const MAX_SPIN: u8 = 8;
}
impl<T: Send + Sync> const CellTrait<T> for RawCell<T> {
#[inline(always)]
fn new() -> Self {
Self::new()
}
}
impl<T: Send + Sync> RawCell<T> {
#[inline(always)]
pub const fn new() -> Self {
Self {
state: AtomicU8::new(Self::UNINIT),
value: UnsafeCell::new(MaybeUninit::uninit()),
}
}
#[inline(always)]
pub fn default() -> Self
where
T: Default,
{
Self {
state: AtomicU8::new(Self::INITED),
value: UnsafeCell::new(MaybeUninit::new(RwLock::new(T::default()))),
}
}
#[inline(always)]
pub const fn from(value: T) -> Self {
Self {
state: AtomicU8::new(Self::INITED),
value: UnsafeCell::new(MaybeUninit::new(RwLock::new(value))),
}
}
#[inline(always)]
pub fn is_initialized(&self) -> bool {
self.state.load(Ordering::Acquire) == Self::INITED
}
#[inline(always)]
pub fn init<F>(&self, init_fn: F)
where
F: FnOnce() -> T,
{
if likely(self.is_initialized()) {
return;
}
let mut step = 0;
loop {
let state = self.state.load(Ordering::Acquire);
match state {
Self::INITED => return,
Self::UNINIT => {
if self.state.compare_exchange(
Self::UNINIT,
Self::INITING,
Ordering::AcqRel,
Ordering::Acquire,
).is_ok() {
let guard = ResetOnDrop { state: &self.state };
let value = init_fn();
unsafe {
(*self.value.get()).as_mut_ptr().write(RwLock::new(value));
}
std::mem::forget(guard);
self.state.store(Self::INITED, Ordering::Release);
return;
}
}
Self::INITING => {
if step > Self::MAX_SPIN {
std::thread::yield_now();
} else {
for _ in 0..(1 << step) {
std::hint::spin_loop();
}
}
}
_ => unsafe { std::hint::unreachable_unchecked() },
}
step += 1;
}
}
#[inline(always)]
pub async fn init_async<F, Fut>(&self, init_fn: F)
where
F: FnOnce() -> Fut,
Fut: Future<Output = T>,
{
if likely(self.is_initialized()) {
return;
}
let mut step = 0;
loop {
let state = self.state.load(Ordering::Acquire);
match state {
Self::INITED => return,
Self::UNINIT => {
if self.state.compare_exchange(
Self::UNINIT,
Self::INITING,
Ordering::AcqRel,
Ordering::Acquire,
).is_ok() {
let guard = ResetOnDrop { state: &self.state };
let value = AssertUnwindSafe(init_fn())
.catch_unwind()
.await;
if let Ok(value) = value {
unsafe {
(*self.value.get()).as_mut_ptr().write(RwLock::new(value));
}
std::mem::forget(guard);
self.state.store(Self::INITED, Ordering::Release);
} else {
std::panic::resume_unwind(value.err().unwrap());
}
return;
}
}
Self::INITING => {
if step > Self::MAX_SPIN {
yield_now().await;
} else {
for _ in 0..(1 << step) {
std::hint::spin_loop();
}
}
}
_ => unsafe { std::hint::unreachable_unchecked() },
}
step += 1;
}
}
#[inline(always)]
pub unsafe fn inner(&self) -> &RwLock<T> {
debug_assert!(self.is_initialized(), "RawCell is not initialized");
unsafe { (*self.value.get()).assume_init_ref() }
}
#[inline(always)]
pub unsafe fn inner_mut(&self) -> &mut RwLock<T> {
debug_assert!(self.is_initialized(), "RawCell is not initialized");
unsafe { (*self.value.get()).assume_init_mut() }
}
#[inline(always)]
pub unsafe fn read(&self) -> RwLockReadGuard<'_, T> {
debug_assert!(self.is_initialized(), "RawCell is not initialized");
unsafe { (*self.value.get()).assume_init_ref().read() }
}
#[inline(always)]
pub unsafe fn write(&self) -> RwLockWriteGuard<'_, T> {
debug_assert!(self.is_initialized(), "RawCell is not initialized");
unsafe { (*self.value.get()).assume_init_ref().write() }
}
}
impl<T> Drop for RawCell<T> {
fn drop(&mut self) {
if self.state.load(Ordering::Acquire) == Self::INITED {
unsafe {
std::ptr::drop_in_place(
(*self.value.get()).assume_init_mut()
)
}
}
}
}
#[repr(C, align(128))]
pub struct RawMutexCell<T> {
state: AtomicU8,
value: UnsafeCell<MaybeUninit<Mutex<T>>>,
}
unsafe impl<T: Send> Send for RawMutexCell<T> {}
unsafe impl<T: Sync> Sync for RawMutexCell<T> {}
impl<T> const CellTrait<T> for RawMutexCell<T> {
#[inline(always)]
fn new() -> Self {
Self::new()
}
}
impl<T> RawMutexCell<T> {
const UNINIT: u8 = 0;
const INITING: u8 = 1;
const INITED: u8 = 2;
const MAX_SPIN: u8 = 8;
#[inline(always)]
pub const fn new() -> Self {
Self {
state: AtomicU8::new(Self::UNINIT),
value: UnsafeCell::new(MaybeUninit::uninit()),
}
}
#[inline(always)]
pub fn default() -> Self
where
T: Default,
{
Self {
state: AtomicU8::new(Self::INITED),
value: UnsafeCell::new(MaybeUninit::new(Mutex::new(T::default()))),
}
}
#[inline(always)]
pub const fn from(value: T) -> Self {
Self {
state: AtomicU8::new(Self::INITED),
value: UnsafeCell::new(MaybeUninit::new(Mutex::new(value))),
}
}
#[inline(always)]
pub fn is_initialized(&self) -> bool {
self.state.load(Ordering::Acquire) == Self::INITED
}
#[inline(always)]
pub fn init<F>(&self, init_fn: F)
where
F: FnOnce() -> T,
{
let mut step = 0;
loop {
match self.state.compare_exchange(
Self::UNINIT,
Self::INITING,
Ordering::Acquire,
Ordering::Relaxed,
) {
Ok(_) => {
let guard = ResetOnDrop { state: &self.state };
let value = init_fn();
unsafe {
(*self.value.get()).write(Mutex::new(value));
}
std::mem::forget(guard);
self.state.store(Self::INITED, Ordering::Release);
return;
}
Err(state) => match state {
Self::INITING => {
if step > Self::MAX_SPIN {
std::thread::yield_now();
} else {
for _ in 0..(1 << step) {
std::hint::spin_loop();
}
}
}
Self::INITED => return,
_ => unsafe { std::hint::unreachable_unchecked() },
},
}
step += 1;
}
}
#[inline(always)]
pub async fn init_async<F, Fut>(&self, init_fn: F)
where
F: FnOnce() -> Fut,
Fut: Future<Output = T>,
{
let mut step = 0;
loop {
match self.state.compare_exchange(
Self::UNINIT,
Self::INITING,
Ordering::Acquire,
Ordering::Relaxed,
) {
Ok(_) => {
let guard = ResetOnDrop { state: &self.state };
let value = AssertUnwindSafe(init_fn())
.catch_unwind()
.await;
if let Ok(value) = value {
unsafe {
(*self.value.get()).write(Mutex::new(value));
}
std::mem::forget(guard);
self.state.store(Self::INITED, Ordering::Release);
} else {
std::panic::resume_unwind(value.err().unwrap());
}
return;
}
Err(state) => match state {
Self::INITING => {
if step > Self::MAX_SPIN {
yield_now().await;
} else {
for _ in 0..(1 << step) {
std::hint::spin_loop();
}
}
}
Self::INITED => return,
_ => unsafe { std::hint::unreachable_unchecked() },
},
}
step += 1;
}
}
#[inline(always)]
pub unsafe fn inner(&self) -> &Mutex<T> {
debug_assert!(self.is_initialized(), "RawMutexCell is not initialized");
unsafe { &*(*self.value.get()).as_ptr() }
}
#[inline(always)]
pub unsafe fn inner_mut(&self) -> &mut Mutex<T> {
debug_assert!(self.is_initialized(), "RawMutexCell is not initialized");
unsafe { &mut *(*self.value.get()).as_mut_ptr() }
}
}
impl<T> Drop for RawMutexCell<T> {
fn drop(&mut self) {
if self.is_initialized() {
unsafe {
std::ptr::drop_in_place(self.inner_mut());
}
}
}
}
#[repr(C, align(128))]
pub struct RawOnceCell<T> {
state: AtomicU8,
value: UnsafeCell<MaybeUninit<T>>,
}
unsafe impl<T: Send> Send for RawOnceCell<T> {}
unsafe impl<T: Sync> Sync for RawOnceCell<T> {}
impl<T> const CellTrait<T> for RawOnceCell<T> {
#[inline(always)]
fn new() -> Self {
Self::new()
}
}
impl<'a, T> RawOnceCell<T> {
const UNINIT: u8 = 0;
const INITING: u8 = 1;
const INITED: u8 = 2;
#[inline(always)]
pub const fn new() -> Self {
Self {
state: AtomicU8::new(Self::UNINIT),
value: UnsafeCell::new(MaybeUninit::uninit()),
}
}
#[inline(always)]
pub fn is_initialized(&self) -> bool {
self.state.load(Ordering::Acquire) == Self::INITED
}
#[inline(always)]
pub const fn from(value: T) -> Self {
Self {
state: AtomicU8::new(Self::INITED),
value: UnsafeCell::new(MaybeUninit::new(value)),
}
}
#[inline(always)]
pub fn init<F>(&self, init_fn: F)
where
F: FnOnce() -> T,
{
if likely(self.is_initialized()) {
return;
}
let mut step = 0;
loop {
let state = self.state.load(Ordering::Acquire);
match state {
Self::INITED => return,
Self::UNINIT => {
if self.state.compare_exchange(
Self::UNINIT,
Self::INITING,
Ordering::AcqRel,
Ordering::Acquire,
).is_ok() {
let guard = ResetOnDrop { state: &self.state };
unsafe {
(*self.value.get()).as_mut_ptr().write(init_fn());
}
std::mem::forget(guard);
self.state.store(Self::INITED, Ordering::Release);
return;
}
}
Self::INITING => {
if step > 8 {
std::thread::yield_now();
} else {
for _ in 0..(1 << step) {
std::hint::spin_loop();
}
}
}
_ => unsafe { std::hint::unreachable_unchecked() },
}
step += 1;
}
}
#[inline(always)]
pub async fn init_async<F, Fut>(&self, init_fn: F)
where
F: FnOnce() -> Fut,
Fut: Future<Output = T>,
{
if likely(self.is_initialized()) {
return;
}
let mut step = 0;
loop {
let state = self.state.load(Ordering::Acquire);
match state {
Self::INITED => return,
Self::UNINIT => {
if self.state.compare_exchange(
Self::UNINIT,
Self::INITING,
Ordering::AcqRel,
Ordering::Acquire,
).is_ok() {
let guard = ResetOnDrop { state: &self.state };
let value = AssertUnwindSafe(init_fn())
.catch_unwind()
.await;
if let Ok(value) = value {
unsafe {
(*self.value.get()).as_mut_ptr().write(value);
}
std::mem::forget(guard);
self.state.store(Self::INITED, Ordering::Release);
} else {
std::panic::resume_unwind(value.err().unwrap());
}
return;
}
}
Self::INITING => {
if step > 8 {
yield_now().await;
} else {
for _ in 0..(1 << step) {
std::hint::spin_loop();
}
}
}
_ => unsafe { std::hint::unreachable_unchecked() },
}
step += 1;
}
}
#[inline(always)]
pub fn get_or_init<F>(&self, init_fn: F) -> &'a T
where
F: FnOnce() -> T,
{
if !self.is_initialized() {
self.init(init_fn);
}
unsafe { self.inner() }
}
#[inline(always)]
pub unsafe fn inner(&self) -> &'a T {
debug_assert!(self.is_initialized(), "RawOnceCell is not initialized");
unsafe { &*(*self.value.get()).as_ptr() }
}
}
#[repr(C, align(128))]
pub struct RawDirectCell<T> {
value: UnsafeCell<MaybeUninit<T>>,
state: AtomicBool
}
impl<T> const CellTrait<T> for RawDirectCell<T> {
#[inline(always)]
fn new() -> Self {
Self::new()
}
}
impl<T> RawDirectCell<T> {
#[inline(always)]
pub const fn new() -> Self {
Self {
value: UnsafeCell::new(MaybeUninit::uninit()),
state: AtomicBool::new(false),
}
}
#[inline(always)]
pub fn init<F>(&self, init_fn: F)
where
F: FnOnce() -> T,
{
if self.is_initialized() {
return;
}
unsafe {
(*self.value.get()).as_mut_ptr().write(init_fn());
}
self.state.store(true, Ordering::Release);
}
#[inline(always)]
pub fn is_initialized(&self) -> bool {
self.state.load(Ordering::Acquire)
}
#[inline(always)]
pub fn get_or_init<F>(&self, init_fn: F) -> &T
where
F: FnOnce() -> T,
{
if unlikely(!self.is_initialized()) {
self.init(init_fn);
}
unsafe { self.inner() }
}
#[inline(always)]
pub unsafe fn inner(&self) -> &T {
debug_assert!(self.is_initialized(), "RawDirectCell is not initialized");
unsafe { &*(*self.value.get()).as_ptr() }
}
#[inline(always)]
pub unsafe fn inner_mut(&self) -> &mut T {
debug_assert!(self.is_initialized(), "RawDirectCell is not initialized");
unsafe { &mut *(*self.value.get()).as_mut_ptr() }
}
}
impl<T> Drop for RawDirectCell<T> {
fn drop(&mut self) {
if self.is_initialized() {
unsafe {
std::ptr::drop_in_place(self.inner_mut());
}
}
}
}
#[repr(C, align(128))]
pub struct RawOptionCell<T> {
inner: RawCell<Option<T>>,
}
unsafe impl<T: Send> Send for RawOptionCell<T> {}
unsafe impl<T: Sync> Sync for RawOptionCell<T> {}
impl<T: Send + Sync> const CellTrait<Option<T>> for RawOptionCell<T> {
#[inline(always)]
fn new() -> Self {
Self::new()
}
}
impl<T: Send + Sync> RawOptionCell<T> {
#[inline(always)]
pub const fn new() -> Self {
Self {
inner: RawCell::new(),
}
}
#[inline(always)]
pub fn init<F>(&self, init_fn: F)
where
F: FnOnce() -> Option<T>,
{
self.inner.init(init_fn);
}
#[inline(always)]
pub async fn init_async<F, Fut>(&self, init_fn: F)
where
F: FnOnce() -> Fut,
Fut: Future<Output = Option<T>>,
{
self.inner.init_async(init_fn).await;
}
#[inline(always)]
pub unsafe fn read(&self) -> RwLockReadGuard<'_, Option<T>> {
debug_assert!(self.inner.is_initialized(), "RawOptionCell is not initialized");
unsafe { self.inner.read() }
}
#[inline(always)]
pub unsafe fn write(&self) -> RwLockWriteGuard<'_, Option<T>> {
debug_assert!(self.inner.is_initialized(), "RawOptionCell is not initialized");
unsafe { self.inner.write() }
}
}