use std::any::{Any, type_name};
use std::cell::RefCell;
use std::marker::PhantomData;
use std::panic::Location;
use std::rc::Rc;
use crate::handle::{Marker, handle_impls};
use crate::runtime::{self, Computed, NodeId, drop_isolated};
pub struct Memo<T> {
id: NodeId,
_marker: Marker<T>,
}
handle_impls!(Memo<T>);
impl<T: PartialEq + 'static> Memo<T> {
#[track_caller]
pub(crate) fn new(owner: NodeId, mut f: impl FnMut() -> T + 'static) -> Self {
let created = Location::caller();
let value: Rc<RefCell<Option<T>>> = Rc::new(RefCell::new(None));
let slot = Rc::clone(&value);
let compute = move || {
let new = f();
let Ok(mut current) = slot.try_borrow_mut() else {
drop_isolated(new);
runtime::borrow_conflict(format!(
"Memo<{}> (created at {created}) was recomputed while a with() call on it \
was still running",
type_name::<T>()
));
};
if current.as_ref() == Some(&new) {
return Computed {
changed: false,
leftover: Some(Box::new(new)),
};
}
let old = current.replace(new);
Computed {
changed: true,
leftover: old.map(|old| Box::new(old) as Box<dyn Any>),
}
};
Memo {
id: runtime::create_memo(owner, value, Box::new(compute)),
_marker: PhantomData,
}
}
}
impl<T: 'static> Memo<T> {
#[cfg(test)]
pub(crate) fn subscriber_count(&self) -> usize {
runtime::subscriber_count(self.id)
}
#[track_caller]
pub fn get(&self) -> T
where
T: Clone,
{
self.with(T::clone)
}
#[track_caller]
pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
runtime::read_or_panic(self.id, true, "Memo", f)
}
#[track_caller]
pub fn get_untracked(&self) -> T
where
T: Clone,
{
self.with_untracked(T::clone)
}
#[track_caller]
pub fn with_untracked<R>(&self, f: impl FnOnce(&T) -> R) -> R {
runtime::read_or_panic(self.id, false, "Memo", f)
}
#[track_caller]
pub fn try_get(&self) -> Option<T>
where
T: Clone,
{
self.try_with(T::clone)
}
#[track_caller]
pub fn try_with<R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
runtime::read(self.id, true, "Memo", f).ok()
}
pub fn named(self, name: impl Into<String>) -> Self {
runtime::set_name(self.id, name.into());
self
}
}