Skip to main content

crabshell_reactive/
memo.rs

1//! Memos: derived values, recomputed only when read while stale.
2
3use 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
12/// A value derived from signals and other memos.
13///
14/// Create one with [`Owner::memo`](crate::Owner::memo). It computes nothing
15/// until something reads it. When a value it read changes, it only becomes
16/// stale, and recomputes the next time something reads it. If the new value
17/// equals the old one, the memos and effects that read it don't rerun.
18///
19/// If its closure panics, the memo is logged and disabled. It keeps its last
20/// value, and `try_get()` returns `None` if it never had one. A memo must not
21/// write signals or call [`Runtime::flush`](crate::Runtime::flush): either
22/// panics, which disables it the same way.
23pub 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      // The value that isn't kept goes back to the runtime, which drops
47      // it once the readers have been told.
48      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  /// How many memos and effects read this on their last run.
69  #[cfg(test)]
70  pub(crate) fn subscriber_count(&self) -> usize {
71    runtime::subscriber_count(self.id)
72  }
73
74  /// Returns a clone of the value, recomputing it first if it is stale.
75  /// Inside a memo or effect, this makes it depend on this memo.
76  ///
77  /// # Panics
78  ///
79  /// If the memo's owner was disposed, if it has no value because its
80  /// closure panicked on the first run, or if the memo reads itself.
81  /// [`try_get`](Self::try_get) returns `None` in the first two cases.
82  #[track_caller]
83  pub fn get(&self) -> T
84  where
85    T: Clone,
86  {
87    self.with(T::clone)
88  }
89
90  /// Calls `f` with a reference to the value. Otherwise like
91  /// [`get`](Self::get).
92  #[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  /// Like [`get`](Self::get), but records no dependency.
98  #[track_caller]
99  pub fn get_untracked(&self) -> T
100  where
101    T: Clone,
102  {
103    self.with_untracked(T::clone)
104  }
105
106  /// Like [`with`](Self::with), but records no dependency.
107  #[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  /// Like [`get`](Self::get), but returns `None` if the owner was disposed
113  /// or the memo has no value.
114  #[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  /// Like [`with`](Self::with), but returns `None` if the owner was
123  /// disposed or the memo has no value.
124  #[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  /// Gives the memo a debug name, such as a widget path, for log lines.
130  pub fn named(self, name: impl Into<String>) -> Self {
131    runtime::set_name(self.id, name.into());
132    self
133  }
134}