38 lines
1.1 KiB
Rust
38 lines
1.1 KiB
Rust
use crate::ExternRef;
|
|
use alloc::collections::BTreeMap;
|
|
|
|
pub trait Cacheable {
|
|
fn get_cache<'a>() -> &'a mut BTreeMap<ExternRef<Self>, Self>
|
|
where
|
|
Self: Sized;
|
|
|
|
fn from_ref(ptr: ExternRef<Self>, ctor: &dyn Fn(ExternRef<Self>) -> Self) -> Self
|
|
where
|
|
Self: Sized,
|
|
Self: Clone,
|
|
{
|
|
let opt = Self::get_cache().get(&ptr);
|
|
if let Some(v) = opt {
|
|
return v.clone();
|
|
}
|
|
Self::get_cache().insert(ptr, ctor(ptr));
|
|
return Self::get_cache().get(&ptr).unwrap().clone();
|
|
}
|
|
}
|
|
|
|
macro_rules! cacheable {
|
|
($type: ident) => {
|
|
paste::paste!{
|
|
static mut [<$type:upper _CACHE>]: alloc::collections::BTreeMap<ExternRef<$type>, $type> =
|
|
alloc::collections::BTreeMap::new();
|
|
impl crate::handling::Cacheable for $type {
|
|
fn get_cache<'a>() -> &'a mut alloc::collections::BTreeMap<ExternRef<$type>, $type> {
|
|
unsafe { &mut [<$type:upper _CACHE>] }
|
|
}
|
|
}
|
|
}
|
|
};
|
|
}
|
|
|
|
pub(crate) use cacheable;
|