use super::*;
impl<T> Clone for Memo<T>
where
T: 'static,
{
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for Memo<T> where T: 'static {}
impl<T> PartialEq for Memo<T>
where
T: 'static,
{
fn eq(&self, other: &Self) -> bool {
self.id() == other.id()
}
}
impl<T> Eq for Memo<T> where T: 'static {}
impl<T> Memo<T>
where
T: 'static,
{
#[must_use]
pub fn id(&self) -> MemoId {
let Self { id, .. } = *self;
id
}
}
impl<T> Memo<T>
where
T: Clone + PartialEq + 'static,
{
#[must_use]
pub fn new<F>(mut compute: F) -> Self
where
F: FnMut() -> T + 'static,
{
let id: MemoId = with_runtime(
|rt: &mut ReactiveRuntime| {
rt.create_memo(move |slot: &mut Option<Box<dyn Any>>| {
let next_val: T = compute();
if let Some(prev_val) = slot
.as_mut()
.and_then(|boxed: &mut Box<dyn Any>| boxed.downcast_mut::<T>())
{
if *prev_val == next_val {
return false;
}
*prev_val = next_val;
return true;
}
*slot = Some(Box::new(next_val));
true
})
},
MemoId::default(),
);
evaluate_memo(id);
Self {
id,
marker: PhantomData,
}
}
#[must_use]
pub fn try_get(&self) -> Option<T> {
read_memo_fused::<T>(self.id())
}
#[must_use]
pub fn get(&self) -> T
where
T: Default,
{
self.try_get().unwrap_or_default()
}
pub fn dispose(&self) {
let id: MemoId = self.id();
with_runtime(
|rt: &mut ReactiveRuntime| {
rt.dispose_memo(id);
},
(),
);
}
}