crabshell_reactive/
memo.rs1use std::any::{Any, type_name};
4use std::cell::RefCell;
5use std::marker::PhantomData;
6use std::panic::Location;
7use std::rc::Rc;
8
9use crate::handle::{Marker, handle_impls};
10use crate::runtime::{self, Computed, NodeId, drop_isolated};
11
12pub struct Memo<T> {
24 id: NodeId,
25 _marker: Marker<T>,
26}
27
28handle_impls!(Memo<T>);
29
30impl<T: PartialEq + 'static> Memo<T> {
31 #[track_caller]
32 pub(crate) fn new(owner: NodeId, mut f: impl FnMut() -> T + 'static) -> Self {
33 let created = Location::caller();
34 let value: Rc<RefCell<Option<T>>> = Rc::new(RefCell::new(None));
35 let slot = Rc::clone(&value);
36 let compute = move || {
37 let new = f();
38 let Ok(mut current) = slot.try_borrow_mut() else {
39 drop_isolated(new);
40 runtime::borrow_conflict(format!(
41 "Memo<{}> (created at {created}) was recomputed while a with() call on it \
42 was still running",
43 type_name::<T>()
44 ));
45 };
46 if current.as_ref() == Some(&new) {
49 return Computed {
50 changed: false,
51 leftover: Some(Box::new(new)),
52 };
53 }
54 let old = current.replace(new);
55 Computed {
56 changed: true,
57 leftover: old.map(|old| Box::new(old) as Box<dyn Any>),
58 }
59 };
60 Memo {
61 id: runtime::create_memo(owner, value, Box::new(compute)),
62 _marker: PhantomData,
63 }
64 }
65}
66
67impl<T: 'static> Memo<T> {
68 #[cfg(test)]
70 pub(crate) fn subscriber_count(&self) -> usize {
71 runtime::subscriber_count(self.id)
72 }
73
74 #[track_caller]
83 pub fn get(&self) -> T
84 where
85 T: Clone,
86 {
87 self.with(T::clone)
88 }
89
90 #[track_caller]
93 pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
94 runtime::read_or_panic(self.id, true, "Memo", f)
95 }
96
97 #[track_caller]
99 pub fn get_untracked(&self) -> T
100 where
101 T: Clone,
102 {
103 self.with_untracked(T::clone)
104 }
105
106 #[track_caller]
108 pub fn with_untracked<R>(&self, f: impl FnOnce(&T) -> R) -> R {
109 runtime::read_or_panic(self.id, false, "Memo", f)
110 }
111
112 #[track_caller]
115 pub fn try_get(&self) -> Option<T>
116 where
117 T: Clone,
118 {
119 self.try_with(T::clone)
120 }
121
122 #[track_caller]
125 pub fn try_with<R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
126 runtime::read(self.id, true, "Memo", f).ok()
127 }
128
129 pub fn named(self, name: impl Into<String>) -> Self {
131 runtime::set_name(self.id, name.into());
132 self
133 }
134}