use crate::{once::Once, RelaxStrategy, Spin};
use core::{cell::Cell, fmt, ops::Deref};
pub struct Lazy<T, F = fn() -> T, R = Spin> {
cell: Once<T, R>,
init: Cell<Option<F>>,
}
impl<T: fmt::Debug, F, R> fmt::Debug for Lazy<T, F, R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_tuple("Lazy");
let d = if let Some(x) = self.cell.get() {
d.field(&x)
} else {
d.field(&format_args!("<uninit>"))
};
d.finish()
}
}
unsafe impl<T, F: Send> Sync for Lazy<T, F> where Once<T>: Sync {}
impl<T, F, R> Lazy<T, F, R> {
pub const fn new(f: F) -> Self {
Self {
cell: Once::new(),
init: Cell::new(Some(f)),
}
}
pub fn as_mut_ptr(&self) -> *mut T {
self.cell.as_mut_ptr()
}
}
impl<T, F: FnOnce() -> T, R: RelaxStrategy> Lazy<T, F, R> {
pub fn force(this: &Self) -> &T {
this.cell.call_once(|| match this.init.take() {
Some(f) => f(),
None => panic!("Lazy instance has previously been poisoned"),
})
}
}
impl<T, F: FnOnce() -> T, R: RelaxStrategy> Deref for Lazy<T, F, R> {
type Target = T;
fn deref(&self) -> &T {
Self::force(self)
}
}
impl<T: Default, R> Default for Lazy<T, fn() -> T, R> {
fn default() -> Self {
Self::new(T::default)
}
}