use std::{
cell::UnsafeCell,
mem::{self, MaybeUninit},
panic::{RefUnwindSafe, UnwindSafe},
ptr,
sync::atomic::{AtomicBool, Ordering},
};
use parking_lot::{lock_api::RawMutex as _RawMutex, RawMutex};
pub(crate) struct OnceCell<T> {
mutex: Mutex,
is_initialized: AtomicBool,
value: UnsafeCell<MaybeUninit<T>>,
}
unsafe impl<T: Sync + Send> Sync for OnceCell<T> {}
unsafe impl<T: Send> Send for OnceCell<T> {}
impl<T: RefUnwindSafe + UnwindSafe> RefUnwindSafe for OnceCell<T> {}
impl<T: UnwindSafe> UnwindSafe for OnceCell<T> {}
impl<T> OnceCell<T> {
pub(crate) const fn new() -> OnceCell<T> {
OnceCell {
mutex: Mutex::new(),
is_initialized: AtomicBool::new(false),
value: UnsafeCell::new(MaybeUninit::uninit()),
}
}
#[inline]
pub(crate) fn is_initialized(&self) -> bool {
self.is_initialized.load(Ordering::Acquire)
}
#[cold]
pub(crate) fn initialize<F, E>(&self, f: F) -> Result<(), E>
where
F: FnOnce() -> Result<T, E>,
{
let _guard = self.mutex.lock();
if !self.is_initialized() {
let value = f()?;
unsafe { self.as_mut_ptr().write(value) };
self.is_initialized.store(true, Ordering::Release);
}
Ok(())
}
pub(crate) unsafe fn get_unchecked(&self) -> &T {
debug_assert!(self.is_initialized());
&*self.as_ptr()
}
pub(crate) fn get_mut(&mut self) -> Option<&mut T> {
if self.is_initialized() {
Some(unsafe { &mut *self.as_mut_ptr() })
} else {
None
}
}
pub(crate) fn into_inner(self) -> Option<T> {
if !self.is_initialized() {
return None;
}
let value: T = unsafe { ptr::read(self.as_ptr()) };
mem::forget(self);
Some(value)
}
fn as_ptr(&self) -> *const T {
unsafe {
let slot: &MaybeUninit<T> = &*self.value.get();
slot.as_ptr()
}
}
fn as_mut_ptr(&self) -> *mut T {
unsafe {
let slot: &mut MaybeUninit<T> = &mut *self.value.get();
slot.as_mut_ptr()
}
}
}
impl<T> Drop for OnceCell<T> {
fn drop(&mut self) {
if self.is_initialized() {
unsafe { ptr::drop_in_place(self.as_mut_ptr()) };
}
}
}
struct Mutex {
inner: RawMutex,
}
impl Mutex {
const fn new() -> Mutex {
Mutex { inner: RawMutex::INIT }
}
fn lock(&self) -> MutexGuard<'_> {
self.inner.lock();
MutexGuard { inner: &self.inner }
}
}
struct MutexGuard<'a> {
inner: &'a RawMutex,
}
impl Drop for MutexGuard<'_> {
fn drop(&mut self) {
self.inner.unlock();
}
}
#[test]
fn test_size() {
use std::mem::size_of;
assert_eq!(size_of::<OnceCell<bool>>(), 2 * size_of::<bool>() + size_of::<u8>());
}