Skip to main content

euv_core/reactive/memo/
impl.rs

1use super::*;
2
3/// Manual `Clone` implementation so `Memo<T>` is always `Copy`.
4impl<ValueType> Clone for Memo<ValueType>
5where
6    ValueType: '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<ValueType> Copy for Memo<ValueType> where ValueType: 'static {}
24
25/// Equality comparison by underlying `MemoId`.
26impl<ValueType> PartialEq for Memo<ValueType>
27where
28    ValueType: '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<ValueType> Eq for Memo<ValueType> where ValueType: 'static {}
47
48/// Identity accessors for `Memo<T>`.
49impl<ValueType> Memo<ValueType>
50where
51    ValueType: '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<ValueType> Memo<ValueType>
71where
72    ValueType: 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    /// - `CallbackFn` - 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<CallbackFn>(mut compute: CallbackFn) -> Self
85    where
86        CallbackFn: FnMut() -> ValueType + 'static,
87    {
88        let id: MemoId = with_runtime(
89            |runtime_ref: &mut ReactiveRuntime| {
90                runtime_ref.create_memo(move |slot: &mut SignalSlot| {
91                    let next_val: ValueType = compute();
92                    if let Some(prev_val) = slot.downcast_mut::<ValueType>() {
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<ValueType>` - Current computed value if alive.
120    #[must_use]
121    pub fn try_get(&self) -> Option<ValueType> {
122        read_memo_fused::<ValueType>(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    /// - `ValueType` - Computed value or default fallback.
134    #[must_use]
135    pub fn get(&self) -> ValueType
136    where
137        ValueType: Default,
138    {
139        self.try_get().unwrap_or_default()
140    }
141
142    /// Evaluates the memo if stale and applies `reader` directly to a shared borrowed `&T` without cloning.
143    ///
144    /// # Arguments
145    ///
146    /// - `&Self` - Memo handle to borrow.
147    /// - `ReaderFn` - Read-only closure receiving `&T`.
148    ///
149    /// # Returns
150    ///
151    /// - `Option<ReturnValue>` - Closure return value if alive and readable.
152    #[inline]
153    pub fn try_with_ref<ReaderFn, ReturnValue>(&self, reader: ReaderFn) -> Option<ReturnValue>
154    where
155        ReaderFn: FnOnce(&ValueType) -> ReturnValue,
156    {
157        read_memo_with_ref::<ValueType, ReaderFn, ReturnValue>(self.id(), reader)
158    }
159
160    /// Evaluates the memo if stale and applies `reader` directly to a shared borrowed `&T` without cloning.
161    ///
162    /// # Arguments
163    ///
164    /// - `&Self` - Memo handle to borrow.
165    /// - `ReaderFn` - Read-only closure receiving `&T`.
166    ///
167    /// # Returns
168    ///
169    /// - `ReturnValue` - Value returned by `reader`.
170    #[inline]
171    pub fn with_ref<ReaderFn, ReturnValue>(&self, reader: ReaderFn) -> ReturnValue
172    where
173        ReaderFn: FnOnce(&ValueType) -> ReturnValue,
174    {
175        self.try_with_ref(reader).unwrap()
176    }
177
178    /// Disposes this memo, unlinks all its edges in O(deg), and drops its cached value outside the runtime borrow.
179    ///
180    /// # Arguments
181    ///
182    /// - `&Self` - Memo handle to dispose.
183    pub fn dispose(&self) {
184        let id: MemoId = self.id();
185        let dropped: SignalSlot = with_runtime(
186            |runtime_ref: &mut ReactiveRuntime| runtime_ref.dispose_memo(id),
187            SignalSlot::empty(),
188        );
189        drop(dropped);
190    }
191}