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 memoized derived computation with value-equality short-circuiting.
75    ///
76    /// # Arguments
77    ///
78    /// - `F` - Computation closure evaluated lazily when upstream dependencies change.
79    ///
80    /// # Returns
81    ///
82    /// - `Self` - Copyable handle to the 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 Option<Box<dyn Any>>| {
91                    let next_val: T = compute();
92                    if let Some(prev_val) = slot
93                        .as_mut()
94                        .and_then(|boxed: &mut Box<dyn Any>| boxed.downcast_mut::<T>())
95                    {
96                        if *prev_val == next_val {
97                            return false;
98                        }
99                        *prev_val = next_val;
100                        return true;
101                    }
102                    *slot = Some(Box::new(next_val));
103                    true
104                })
105            },
106            MemoId::default(),
107        );
108        evaluate_memo(id);
109        Self {
110            id,
111            marker: PhantomData,
112        }
113    }
114
115    /// Evaluates the memo if stale, tracks it in the current observer, and returns a cloned value.
116    ///
117    /// # Arguments
118    ///
119    /// - `&Self` - Memo handle to read.
120    ///
121    /// # Returns
122    ///
123    /// - `Option<T>` - Current computed value if alive.
124    #[must_use]
125    pub fn try_get(&self) -> Option<T> {
126        let id: MemoId = self.id();
127        let slot: SlotId = id.slot();
128        let fast_hit: Option<Option<T>> = with_runtime(
129            |rt: &mut ReactiveRuntime| {
130                let entry: &MemoEntry = rt.get_memos().get(slot.as_usize())?;
131                if entry.get_generation() != slot.get_generation() {
132                    return Some(None);
133                }
134                if entry.get_state() != NodeState::Clean {
135                    return None;
136                }
137                let val: Option<T> = entry
138                    .value
139                    .as_ref()
140                    .and_then(|boxed: &Box<dyn Any>| boxed.downcast_ref::<T>())
141                    .cloned();
142                rt.track_dependency(DependencyId::Memo(id));
143                Some(val)
144            },
145            None,
146        );
147        if let Some(result) = fast_hit {
148            return result;
149        }
150        evaluate_memo(id);
151        with_runtime(
152            |rt: &mut ReactiveRuntime| {
153                rt.track_dependency(DependencyId::Memo(id));
154                let entry: &MemoEntry = rt.get_memos().get(slot.as_usize())?;
155                if entry.get_generation() != slot.get_generation() {
156                    return None;
157                }
158                entry
159                    .value
160                    .as_ref()
161                    .and_then(|boxed: &Box<dyn Any>| boxed.downcast_ref::<T>())
162                    .cloned()
163            },
164            None,
165        )
166    }
167
168    /// Evaluates the memo if stale and returns the value or `T::default()` if disposed.
169    ///
170    /// # Arguments
171    ///
172    /// - `&Self` - Memo handle to read.
173    ///
174    /// # Returns
175    ///
176    /// - `T` - Computed value or default fallback.
177    #[must_use]
178    pub fn get(&self) -> T
179    where
180        T: Default,
181    {
182        self.try_get().unwrap_or_default()
183    }
184
185    /// Disposes this memo and detaches its dependency links.
186    ///
187    /// # Arguments
188    ///
189    /// - `&Self` - Memo handle to dispose.
190    pub fn dispose(&self) {
191        let id: MemoId = self.id();
192        with_runtime(
193            |rt: &mut ReactiveRuntime| {
194                rt.dispose_memo(id);
195            },
196            (),
197        );
198    }
199}