use super::*;
impl<ValueType> Clone for Memo<ValueType>
where
ValueType: 'static,
{
fn clone(&self) -> Self {
*self
}
}
impl<ValueType> Copy for Memo<ValueType> where ValueType: 'static {}
impl<ValueType> PartialEq for Memo<ValueType>
where
ValueType: 'static,
{
fn eq(&self, other: &Self) -> bool {
self.id() == other.id()
}
}
impl<ValueType> Eq for Memo<ValueType> where ValueType: 'static {}
impl<ValueType> Memo<ValueType>
where
ValueType: 'static,
{
#[must_use]
pub fn id(&self) -> MemoId {
let Self { id, .. } = *self;
id
}
}
impl<ValueType> Memo<ValueType>
where
ValueType: Clone + PartialEq + 'static,
{
#[must_use]
pub fn new<CallbackFn>(mut compute: CallbackFn) -> Self
where
CallbackFn: FnMut() -> ValueType + 'static,
{
let id: MemoId = with_runtime(
|runtime_ref: &mut ReactiveRuntime| {
runtime_ref.create_memo(move |slot: &mut SignalSlot| {
let next_val: ValueType = compute();
if let Some(prev_val) = slot.downcast_mut::<ValueType>() {
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<ValueType> {
read_memo_fused::<ValueType>(self.id())
}
#[must_use]
pub fn get(&self) -> ValueType
where
ValueType: Default,
{
self.try_get().unwrap_or_default()
}
#[inline]
pub fn try_with_ref<ReaderFn, ReturnValue>(&self, reader: ReaderFn) -> Option<ReturnValue>
where
ReaderFn: FnOnce(&ValueType) -> ReturnValue,
{
read_memo_with_ref::<ValueType, ReaderFn, ReturnValue>(self.id(), reader)
}
#[inline]
pub fn with_ref<ReaderFn, ReturnValue>(&self, reader: ReaderFn) -> ReturnValue
where
ReaderFn: FnOnce(&ValueType) -> ReturnValue,
{
self.try_with_ref(reader).unwrap()
}
pub fn dispose(&self) {
let id: MemoId = self.id();
let dropped: SignalSlot = with_runtime(
|runtime_ref: &mut ReactiveRuntime| runtime_ref.dispose_memo(id),
SignalSlot::empty(),
);
drop(dropped);
}
}