Skip to main content

euv_core/reactive/signal/
impl.rs

1use super::*;
2
3/// Manual `Clone` implementation so `Signal<T>` is always `Copy` regardless of `T`.
4impl<T> Clone for Signal<T>
5where
6    T: 'static,
7{
8    /// Copies the lightweight 8-byte signal handle.
9    ///
10    /// # Arguments
11    ///
12    /// - `&Self` - Signal handle to copy.
13    ///
14    /// # Returns
15    ///
16    /// - `Self` - Identical signal handle.
17    fn clone(&self) -> Self {
18        *self
19    }
20}
21
22/// Marker `Copy` implementation for `Signal<T>`.
23impl<T> Copy for Signal<T> where T: 'static {}
24
25/// Zero-allocation dangling `Default` handle for `Signal<T>`, used when initializing component prop descriptors.
26impl<T> Default for Signal<T>
27where
28    T: 'static,
29{
30    /// Constructs an unallocated placeholder `Signal<T>` handle with `SignalId::default()`.
31    ///
32    /// # Returns
33    ///
34    /// - `Self` - Zero-cost placeholder signal handle.
35    fn default() -> Self {
36        Self {
37            id: SignalId::default(),
38            marker: PhantomData,
39        }
40    }
41}
42
43/// Equality comparison by underlying `SignalId`.
44impl<T> PartialEq for Signal<T>
45where
46    T: 'static,
47{
48    /// Compares two signal handles by arena identifier.
49    ///
50    /// # Arguments
51    ///
52    /// - `&Self` - Left-hand signal handle.
53    /// - `&Self` - Right-hand signal handle.
54    ///
55    /// # Returns
56    ///
57    /// - `bool` - True if both handles reference the same arena slot and generation.
58    fn eq(&self, other: &Self) -> bool {
59        self.id() == other.id()
60    }
61}
62
63/// Reflexive equality for `Signal<T>`.
64impl<T> Eq for Signal<T> where T: 'static {}
65
66/// Hash implementation based on underlying `SignalId`.
67impl<T> Hash for Signal<T>
68where
69    T: 'static,
70{
71    /// Hashes the underlying arena signal identifier.
72    ///
73    /// # Arguments
74    ///
75    /// - `&Self` - Signal handle to hash.
76    /// - `&mut H` - Hasher state.
77    fn hash<H>(&self, state: &mut H)
78    where
79        H: Hasher,
80    {
81        self.id().hash(state);
82    }
83}
84
85/// Core reactive operations for `Signal<T>`.
86impl<T> Signal<T>
87where
88    T: 'static,
89{
90    /// Allocates a new reactive signal initialized with `initial_value`.
91    ///
92    /// # Arguments
93    ///
94    /// - `T` - Initial signal value.
95    ///
96    /// # Returns
97    ///
98    /// - `Self` - Copyable handle to the created signal.
99    #[must_use]
100    pub fn new(initial_value: T) -> Self {
101        let id: SignalId = with_runtime(
102            |rt: &mut ReactiveRuntime| rt.create_signal(initial_value),
103            SignalId::default(),
104        );
105        Self {
106            id,
107            marker: PhantomData,
108        }
109    }
110
111    /// Allocates a new reactive signal detached from any enclosing transient `Scope` so hub/store state survives UI rebuilds.
112    ///
113    /// # Arguments
114    ///
115    /// - `T` - Initial signal value.
116    ///
117    /// # Returns
118    ///
119    /// - `Self` - Copyable handle to the created detached signal.
120    #[must_use]
121    pub fn new_detached(initial_value: T) -> Self {
122        let id: SignalId = with_runtime(
123            |rt: &mut ReactiveRuntime| rt.create_detached_signal(initial_value),
124            SignalId::default(),
125        );
126        Self {
127            id,
128            marker: PhantomData,
129        }
130    }
131
132    /// Reconstructs a typed `Signal<T>` handle from an arena `SignalId`.
133    ///
134    /// # Arguments
135    ///
136    /// - `SignalId` - Arena signal identifier.
137    ///
138    /// # Returns
139    ///
140    /// - `Self` - Lightweight copyable signal handle.
141    #[must_use]
142    pub(crate) fn from_raw_id(id: SignalId) -> Self {
143        Self {
144            id,
145            marker: PhantomData,
146        }
147    }
148
149    /// Returns the underlying `SignalId`.
150    ///
151    /// # Arguments
152    ///
153    /// - `&Self` - Signal handle.
154    ///
155    /// # Returns
156    ///
157    /// - `SignalId` - Underlying arena identifier.
158    #[must_use]
159    #[inline(always)]
160    pub fn id(&self) -> SignalId {
161        let Self { id, .. } = *self;
162        id
163    }
164
165    /// Returns whether this signal currently has at least one active downstream subscriber.
166    ///
167    /// # Arguments
168    ///
169    /// - `&Self` - Signal handle to inspect.
170    ///
171    /// # Returns
172    ///
173    /// - `bool` - True when the signal is alive and observed by at least one memo or effect.
174    #[must_use]
175    #[inline(always)]
176    pub fn has_subscribers(&self) -> bool {
177        let id: SignalId = self.id();
178        with_runtime(
179            |rt: &mut ReactiveRuntime| rt.signal_has_subscribers(id),
180            false,
181        )
182    }
183
184    /// Records a dependency on this signal in the active observer without cloning its value.
185    ///
186    /// # Arguments
187    ///
188    /// - `&Self` - Signal handle to track.
189    #[inline(always)]
190    pub fn track(&self) {
191        let id: SignalId = self.id();
192        with_runtime(
193            |rt: &mut ReactiveRuntime| {
194                rt.track_dependency(DependencyId::Signal(id));
195            },
196            (),
197        );
198    }
199
200    /// Reads the current value by cloning and tracks the active observer dependency.
201    ///
202    /// # Arguments
203    ///
204    /// - `&Self` - Signal handle to read.
205    ///
206    /// # Returns
207    ///
208    /// - `Option<T>` - Current value if the signal is still alive.
209    #[must_use]
210    #[inline(always)]
211    pub fn try_get(&self) -> Option<T>
212    where
213        T: Clone,
214    {
215        let id: SignalId = self.id();
216        with_runtime(
217            |rt: &mut ReactiveRuntime| rt.read_signal_cloned::<T>(id),
218            None,
219        )
220    }
221
222    /// Reads the current value, returning `T::default()` if the signal was disposed.
223    ///
224    /// # Arguments
225    ///
226    /// - `&Self` - Signal handle to read.
227    ///
228    /// # Returns
229    ///
230    /// - `T` - Current value or default fallback.
231    #[must_use]
232    #[inline(always)]
233    pub fn get(&self) -> T
234    where
235        T: Clone + Default,
236    {
237        self.try_get().unwrap_or_default()
238    }
239
240    /// Reads the current value without tracking any reactive dependency.
241    ///
242    /// # Arguments
243    ///
244    /// - `&Self` - Signal handle to inspect.
245    ///
246    /// # Returns
247    ///
248    /// - `Option<T>` - Current value if alive.
249    #[must_use]
250    #[inline(always)]
251    pub fn try_get_untracked(&self) -> Option<T>
252    where
253        T: Clone,
254    {
255        let id: SignalId = self.id();
256        with_runtime(
257            |rt: &mut ReactiveRuntime| rt.read_signal_untracked::<T>(id),
258            None,
259        )
260    }
261
262    /// Reads the current value untracked, returning `T::default()` if disposed.
263    ///
264    /// # Arguments
265    ///
266    /// - `&Self` - Signal handle to inspect.
267    ///
268    /// # Returns
269    ///
270    /// - `T` - Current value or default fallback.
271    #[must_use]
272    #[inline(always)]
273    pub fn get_untracked(&self) -> T
274    where
275        T: Clone + Default,
276    {
277        self.try_get_untracked().unwrap_or_default()
278    }
279
280    /// Applies `reader` to a cloned snapshot outside any `RefCell` borrow so nested reads remain safe.
281    ///
282    /// # Arguments
283    ///
284    /// - `&Self` - Signal handle to read.
285    /// - `F` - Reader closure receiving `&T`.
286    ///
287    /// # Returns
288    ///
289    /// - `Option<R>` - Closure return value if the signal is alive.
290    #[inline]
291    pub fn with<F, R>(&self, reader: F) -> Option<R>
292    where
293        T: Clone,
294        F: FnOnce(&T) -> R,
295    {
296        let snapshot: T = self.try_get()?;
297        Some(reader(&snapshot))
298    }
299
300    /// Replaces the stored value and flushes downstream reactive effects.
301    ///
302    /// # Arguments
303    ///
304    /// - `&Self` - Signal handle to write.
305    /// - `T` - Replacement value.
306    ///
307    /// # Returns
308    ///
309    /// - `bool` - True when the signal was alive and updated.
310    #[inline(always)]
311    pub fn set(&self, value: T) -> bool {
312        let id: SignalId = self.id();
313        let (updated, should_flush): (bool, bool) = with_runtime(
314            |rt: &mut ReactiveRuntime| rt.write_signal(id, value),
315            (false, false),
316        );
317        if should_flush {
318            flush_effects();
319        }
320        updated
321    }
322
323    /// Replaces the stored value only when `value` differs from the current stored value.
324    ///
325    /// # Arguments
326    ///
327    /// - `&Self` - Signal handle to write.
328    /// - `T` - Candidate value.
329    ///
330    /// # Returns
331    ///
332    /// - `bool` - True when the value changed and downstream effects were scheduled.
333    #[inline(always)]
334    pub fn set_if_changed(&self, value: T) -> bool
335    where
336        T: PartialEq,
337    {
338        let id: SignalId = self.id();
339        let (updated, should_flush): (bool, bool) = with_runtime(
340            |rt: &mut ReactiveRuntime| rt.write_signal_if_changed(id, value),
341            (false, false),
342        );
343        if should_flush {
344            flush_effects();
345        }
346        updated
347    }
348
349    /// Mutates the signal value in place outside the runtime borrow without cloning and flushes effects.
350    ///
351    /// # Arguments
352    ///
353    /// - `&Self` - Signal handle to update.
354    /// - `F` - Mutation closure receiving `&mut T`.
355    ///
356    /// # Returns
357    ///
358    /// - `bool` - True when the signal was alive and updated.
359    #[inline]
360    pub fn update<F>(&self, updater: F) -> bool
361    where
362        T: Clone,
363        F: FnOnce(&mut T),
364    {
365        let id: SignalId = self.id();
366        let Some(mut boxed) =
367            with_runtime(|rt: &mut ReactiveRuntime| rt.take_signal_box::<T>(id), None)
368        else {
369            return false;
370        };
371        if let Some(current) = boxed.downcast_mut::<T>() {
372            updater(current);
373        }
374        let (updated, should_flush): (bool, bool) = with_runtime(
375            |rt: &mut ReactiveRuntime| rt.commit_signal_box(id, boxed),
376            (false, false),
377        );
378        if should_flush {
379            flush_effects();
380        }
381        updated
382    }
383
384    /// Disposes this signal and reclaims its arena slot.
385    ///
386    /// # Arguments
387    ///
388    /// - `&Self` - Signal handle to dispose.
389    pub fn dispose(&self) {
390        let id: SignalId = self.id();
391        with_runtime(
392            |rt: &mut ReactiveRuntime| {
393                rt.dispose_signal(id);
394            },
395            (),
396        );
397    }
398}