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 SignalSlot| {
let next_val: T = compute();
if let Some(prev_val) = slot.downcast_mut::<T>() {
if *prev_val == next_val {
return false;
}
*prev_val = next_val;
return true;
}
slot.replace(next_val);
true
})
},
MemoId::default(),
);
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()
}
#[inline]
pub fn try_with_ref<R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
read_memo_with_ref::<T, R>(self.id(), f)
}
#[inline]
pub fn with_ref<R>(&self, f: impl FnOnce(&T) -> R) -> R {
self.try_with_ref(f).unwrap()
}
pub fn dispose(&self) {
let id: MemoId = self.id();
let dropped: SignalSlot = with_runtime(
|rt: &mut ReactiveRuntime| rt.dispose_memo(id),
SignalSlot::empty(),
);
drop(dropped);
}
}