use std::ops::{Deref, DerefMut};
pub(crate) struct LazyBox<T>(Option<Box<T>>);
pub(crate) trait EmptyDefault: Default + 'static {
fn empty() -> &'static Self;
}
impl<T> LazyBox<T> {
pub(crate) const fn new() -> Self {
Self(None)
}
}
impl<T> Default for LazyBox<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Clone> Clone for LazyBox<T> {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}
impl<T: EmptyDefault> Deref for LazyBox<T> {
type Target = T;
fn deref(&self) -> &T {
match &self.0 {
Some(value) => value,
None => T::empty(),
}
}
}
impl<T: EmptyDefault> DerefMut for LazyBox<T> {
fn deref_mut(&mut self) -> &mut T {
self.0.get_or_insert_with(Default::default)
}
}
macro_rules! empty_default {
($ty:ty) => {
impl $crate::node::lazy_box::EmptyDefault for $ty {
fn empty() -> &'static Self {
static EMPTY: std::sync::LazyLock<$ty> = std::sync::LazyLock::new(<$ty>::default);
&EMPTY
}
}
};
}
pub(crate) use empty_default;