use core::{cell::Cell, fmt, ops::Deref};
use crate::{once::Once, RelaxStrategy, Spin};
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 {
f.debug_struct("Lazy").field("cell", &self.cell).field("init", &"..").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)) }
}
}
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)
}
}