Skip to main content

euv_core/reactive/memo/
impl.rs

1use super::*;
2
3/// Manual `Clone` implementation so `Memo<T>` is always `Copy`.
4impl<T> Clone for Memo<T>
5where
6    T: 'static,
7{
8    /// Copies the lightweight 8-byte memo handle.
9    ///
10    /// # Arguments
11    ///
12    /// - `&Self` - Memo handle to copy.
13    ///
14    /// # Returns
15    ///
16    /// - `Self` - Identical memo handle.
17    fn clone(&self) -> Self {
18        *self
19    }
20}
21
22/// Marker `Copy` implementation for `Memo<T>`.
23impl<T> Copy for Memo<T> where T: 'static {}
24
25/// Equality comparison by underlying `MemoId`.
26impl<T> PartialEq for Memo<T>
27where
28    T: 'static,
29{
30    /// Compares two memo handles by arena identifier.
31    ///
32    /// # Arguments
33    ///
34    /// - `&Self` - Left-hand memo handle.
35    /// - `&Self` - Right-hand memo handle.
36    ///
37    /// # Returns
38    ///
39    /// - `bool` - True if both handles reference the same memo slot and generation.
40    fn eq(&self, other: &Self) -> bool {
41        self.id() == other.id()
42    }
43}
44
45/// Reflexive equality for `Memo<T>`.
46impl<T> Eq for Memo<T> where T: 'static {}
47
48/// Identity accessors for `Memo<T>`.
49impl<T> Memo<T>
50where
51    T: 'static,
52{
53    /// Returns the underlying `MemoId`.
54    ///
55    /// # Arguments
56    ///
57    /// - `&Self` - Memo handle.
58    ///
59    /// # Returns
60    ///
61    /// - `MemoId` - Underlying arena identifier.
62    #[must_use]
63    pub fn id(&self) -> MemoId {
64        let Self { id, .. } = *self;
65        id
66    }
67}
68
69/// Core reactive memoization operations for `Memo<T>`.
70impl<T> Memo<T>
71where
72    T: Clone + PartialEq + 'static,
73{
74    /// Creates a new lazy memoized derived computation evaluated on first read with value-equality short-circuiting.
75    ///
76    /// # Arguments
77    ///
78    /// - `F` - Computation closure evaluated lazily on first read and whenever upstream dependencies change.
79    ///
80    /// # Returns
81    ///
82    /// - `Self` - Copyable handle to the lazy memo.
83    #[must_use]
84    pub fn new<F>(mut compute: F) -> Self
85    where
86        F: FnMut() -> T + 'static,
87    {
88        let id: MemoId = with_runtime(
89            |rt: &mut ReactiveRuntime| {
90                rt.create_memo(move |slot: &mut SignalSlot| {
91                    let next_val: T = compute();
92                    if let Some(prev_val) = slot.downcast_mut::<T>() {
93                        if *prev_val == next_val {
94                            return false;
95                        }
96                        *prev_val = next_val;
97                        return true;
98                    }
99                    slot.replace(next_val);
100                    true
101                })
102            },
103            MemoId::default(),
104        );
105        Self {
106            id,
107            marker: PhantomData,
108        }
109    }
110
111    /// Evaluates the memo if stale, tracks it in the current observer, and returns a cloned value.
112    ///
113    /// # Arguments
114    ///
115    /// - `&Self` - Memo handle to read.
116    ///
117    /// # Returns
118    ///
119    /// - `Option<T>` - Current computed value if alive.
120    #[must_use]
121    pub fn try_get(&self) -> Option<T> {
122        read_memo_fused::<T>(self.id())
123    }
124
125    /// Evaluates the memo if stale and returns the value or `T::default()` if disposed.
126    ///
127    /// # Arguments
128    ///
129    /// - `&Self` - Memo handle to read.
130    ///
131    /// # Returns
132    ///
133    /// - `T` - Computed value or default fallback.
134    #[must_use]
135    pub fn get(&self) -> T
136    where
137        T: Default,
138    {
139        self.try_get().unwrap_or_default()
140    }
141
142    /// Evaluates the memo if stale and applies `f` directly to a shared borrowed `&T` without cloning.
143    ///
144    /// # Arguments
145    ///
146    /// - `&Self` - Memo handle to borrow.
147    /// - `impl FnOnce(&T) -> R` - Read-only closure receiving `&T`.
148    ///
149    /// # Returns
150    ///
151    /// - `Option<R>` - Closure return value if alive and readable.
152    #[inline]
153    pub fn try_with_ref<R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
154        read_memo_with_ref::<T, R>(self.id(), f)
155    }
156
157    /// Evaluates the memo if stale and applies `f` directly to a shared borrowed `&T` without cloning.
158    ///
159    /// # Arguments
160    ///
161    /// - `&Self` - Memo handle to borrow.
162    /// - `impl FnOnce(&T) -> R` - Read-only closure receiving `&T`.
163    ///
164    /// # Returns
165    ///
166    /// - `R` - Value returned by `f`.
167    #[inline]
168    pub fn with_ref<R>(&self, f: impl FnOnce(&T) -> R) -> R {
169        self.try_with_ref(f).unwrap()
170    }
171
172    /// Disposes this memo, unlinks all its edges in O(deg), and drops its cached value outside the runtime borrow.
173    ///
174    /// # Arguments
175    ///
176    /// - `&Self` - Memo handle to dispose.
177    pub fn dispose(&self) {
178        let id: MemoId = self.id();
179        let dropped: SignalSlot = with_runtime(
180            |rt: &mut ReactiveRuntime| rt.dispose_memo(id),
181            SignalSlot::empty(),
182        );
183        drop(dropped);
184    }
185}