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<ValueType> Clone for Signal<ValueType>
5where
6    ValueType: '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<ValueType> Copy for Signal<ValueType> where ValueType: 'static {}
24
25/// Zero-allocation dangling `Default` handle for `Signal<T>`, used when initializing component prop descriptors.
26impl<ValueType> Default for Signal<ValueType>
27where
28    ValueType: '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<ValueType> PartialEq for Signal<ValueType>
45where
46    ValueType: '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<ValueType> Eq for Signal<ValueType> where ValueType: 'static {}
65
66/// Hash implementation based on underlying `SignalId`.
67impl<ValueType> Hash for Signal<ValueType>
68where
69    ValueType: 'static,
70{
71    /// Hashes the underlying arena signal identifier.
72    ///
73    /// # Arguments
74    ///
75    /// - `&Self` - Signal handle to hash.
76    /// - `&mut HasherType` - Hasher state.
77    fn hash<HasherType>(&self, state: &mut HasherType)
78    where
79        HasherType: Hasher,
80    {
81        self.id().hash(state);
82    }
83}
84
85/// Core reactive operations for `Signal<T>`.
86impl<ValueType> Signal<ValueType>
87where
88    ValueType: 'static,
89{
90    /// Allocates a new reactive signal initialized with `initial_value`.
91    ///
92    /// # Arguments
93    ///
94    /// - `ValueType` - Initial signal value.
95    ///
96    /// # Returns
97    ///
98    /// - `Self` - Copyable handle to the created signal.
99    #[must_use]
100    pub fn new(initial_value: ValueType) -> Self {
101        let id: SignalId = with_runtime(
102            |runtime_ref: &mut ReactiveRuntime| runtime_ref.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    /// - `ValueType` - 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: ValueType) -> Self {
122        let id: SignalId = with_runtime(
123            |runtime_ref: &mut ReactiveRuntime| runtime_ref.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_ref(
179            |runtime_ref: &ReactiveRuntime| runtime_ref.signal_has_subscribers(id),
180            false,
181        )
182    }
183
184    /// Returns the number of active downstream subscribers observing this signal in O(1).
185    ///
186    /// # Arguments
187    ///
188    /// - `&Self` - Signal handle to inspect.
189    ///
190    /// # Returns
191    ///
192    /// - `usize` - Number of live memo or effect subscribers, or `0` if disposed.
193    #[must_use]
194    #[inline(always)]
195    pub fn subscriber_count(&self) -> usize {
196        let id: SignalId = self.id();
197        with_runtime_ref(
198            |runtime_ref: &ReactiveRuntime| runtime_ref.signal_subscriber_count(id),
199            0,
200        )
201    }
202
203    /// Returns whether this live signal stores its value inline inside the 24-byte SBO buffer without heap allocation.
204    ///
205    /// # Arguments
206    ///
207    /// - `&Self` - Signal handle to inspect.
208    ///
209    /// # Returns
210    ///
211    /// - `bool` - `true` when alive and stored inline in SBO storage.
212    #[must_use]
213    #[inline(always)]
214    pub fn is_inline(&self) -> bool {
215        let id: SignalId = self.id();
216        with_runtime_ref(
217            |runtime_ref: &ReactiveRuntime| runtime_ref.signal_is_inline(id),
218            false,
219        )
220    }
221
222    /// Records a dependency on this signal in the active observer without cloning its value.
223    ///
224    /// # Arguments
225    ///
226    /// - `&Self` - Signal handle to track.
227    #[inline(always)]
228    pub fn track(&self) {
229        track_or_defer_dependency(DependencyId::Signal(self.id()));
230    }
231
232    /// Reads the current value by cloning and tracks the active observer dependency.
233    ///
234    /// # Arguments
235    ///
236    /// - `&Self` - Signal handle to read.
237    ///
238    /// # Returns
239    ///
240    /// - `Option<ValueType>` - Current value if the signal is still alive.
241    #[must_use]
242    #[inline(always)]
243    pub fn try_get(&self) -> Option<ValueType>
244    where
245        ValueType: Clone,
246    {
247        let id: SignalId = self.id();
248        if ref_borrow_depth() > 0 || !is_tracking_active() {
249            return read_signal_with_ref::<ValueType, _, ValueType>(id, true, |val: &ValueType| {
250                val.clone()
251            });
252        }
253        with_runtime(
254            |runtime_ref: &mut ReactiveRuntime| runtime_ref.read_signal_cloned::<ValueType>(id),
255            None,
256        )
257    }
258
259    /// Reads the current value, returning `T::default()` if the signal was disposed.
260    ///
261    /// # Arguments
262    ///
263    /// - `&Self` - Signal handle to read.
264    ///
265    /// # Returns
266    ///
267    /// - `ValueType` - Current value or default fallback.
268    #[must_use]
269    #[inline(always)]
270    pub fn get(&self) -> ValueType
271    where
272        ValueType: Clone + Default,
273    {
274        self.try_get().unwrap_or_default()
275    }
276
277    /// Reads the current value without tracking any reactive dependency.
278    ///
279    /// # Arguments
280    ///
281    /// - `&Self` - Signal handle to inspect.
282    ///
283    /// # Returns
284    ///
285    /// - `Option<ValueType>` - Current value if alive.
286    #[must_use]
287    #[inline(always)]
288    pub fn try_get_untracked(&self) -> Option<ValueType>
289    where
290        ValueType: Clone,
291    {
292        let id: SignalId = self.id();
293        with_runtime_ref(
294            |runtime_ref: &ReactiveRuntime| runtime_ref.read_signal_untracked::<ValueType>(id),
295            None,
296        )
297    }
298
299    /// Reads the current value untracked, returning `T::default()` if disposed.
300    ///
301    /// # Arguments
302    ///
303    /// - `&Self` - Signal handle to inspect.
304    ///
305    /// # Returns
306    ///
307    /// - `ValueType` - Current value or default fallback.
308    #[must_use]
309    #[inline(always)]
310    pub fn get_untracked(&self) -> ValueType
311    where
312        ValueType: Clone + Default,
313    {
314        self.try_get_untracked().unwrap_or_default()
315    }
316
317    /// Applies `reader` directly to a shared borrowed `&T` inside the arena without cloning, returning `None` if disposed or mutably borrowed.
318    ///
319    /// # Arguments
320    ///
321    /// - `&Self` - Signal handle to borrow.
322    /// - `ReaderFn` - Read-only closure receiving `&T` (nested `with_ref` calls are supported).
323    ///
324    /// # Returns
325    ///
326    /// - `Option<ReturnValue>` - Closure return value when the signal is alive and readable.
327    #[inline]
328    pub fn try_with_ref<ReaderFn, ReturnValue>(&self, reader: ReaderFn) -> Option<ReturnValue>
329    where
330        ReaderFn: FnOnce(&ValueType) -> ReturnValue,
331    {
332        read_signal_with_ref::<ValueType, ReaderFn, ReturnValue>(self.id(), true, reader)
333    }
334
335    /// Applies `reader` directly to a shared borrowed `&T` without tracking dependencies or cloning, returning `None` if disposed or mutably borrowed.
336    ///
337    /// # Arguments
338    ///
339    /// - `&Self` - Signal handle to borrow untracked.
340    /// - `ReaderFn` - Read-only closure receiving `&T`.
341    ///
342    /// # Returns
343    ///
344    /// - `Option<ReturnValue>` - Closure return value when the signal is alive and readable.
345    #[inline]
346    pub fn try_with_ref_untracked<ReaderFn, ReturnValue>(
347        &self,
348        reader: ReaderFn,
349    ) -> Option<ReturnValue>
350    where
351        ReaderFn: FnOnce(&ValueType) -> ReturnValue,
352    {
353        read_signal_with_ref::<ValueType, ReaderFn, ReturnValue>(self.id(), false, reader)
354    }
355
356    /// Applies `reader` directly to a shared borrowed `&T` inside the arena without cloning and tracks the active observer dependency.
357    ///
358    /// # Arguments
359    ///
360    /// - `&Self` - Signal handle to borrow.
361    /// - `ReaderFn` - Read-only closure receiving `&T` (nested read-only `with_ref` calls are supported; do not mutate signals inside `reader`).
362    ///
363    /// # Returns
364    ///
365    /// - `ReturnValue` - Value returned by `reader`.
366    #[inline]
367    pub fn with_ref<ReaderFn, ReturnValue>(&self, reader: ReaderFn) -> ReturnValue
368    where
369        ReaderFn: FnOnce(&ValueType) -> ReturnValue,
370    {
371        self.try_with_ref(reader).unwrap()
372    }
373
374    /// Applies `reader` to a cloned snapshot outside any `RefCell` borrow so re-entrant mutating callbacks remain safe.
375    ///
376    /// # Arguments
377    ///
378    /// - `&Self` - Signal handle to read.
379    /// - `CallbackFn` - Reader closure receiving `&T`.
380    ///
381    /// # Returns
382    ///
383    /// - `Option<ReturnValue>` - Closure return value if the signal is alive.
384    #[inline]
385    pub fn with<CallbackFn, ReturnValue>(&self, reader: CallbackFn) -> Option<ReturnValue>
386    where
387        ValueType: Clone,
388        CallbackFn: FnOnce(&ValueType) -> ReturnValue,
389    {
390        let snapshot: ValueType = self.try_get()?;
391        Some(reader(&snapshot))
392    }
393
394    /// Replaces the stored value and flushes downstream reactive effects.
395    ///
396    /// # Arguments
397    ///
398    /// - `&Self` - Signal handle to write.
399    /// - `ValueType` - Replacement value.
400    ///
401    /// # Returns
402    ///
403    /// - `bool` - True when the signal was alive and updated.
404    #[inline(always)]
405    pub fn set(&self, value: ValueType) -> bool {
406        let id: SignalId = self.id();
407        let (updated, should_flush): (bool, bool) = with_runtime(
408            |runtime_ref: &mut ReactiveRuntime| runtime_ref.write_signal(id, value),
409            (false, false),
410        );
411        if should_flush {
412            flush_effects();
413        }
414        updated
415    }
416
417    /// Replaces the stored value only when `value` differs from the current stored value.
418    ///
419    /// # Arguments
420    ///
421    /// - `&Self` - Signal handle to write.
422    /// - `ValueType` - Candidate value.
423    ///
424    /// # Returns
425    ///
426    /// - `bool` - True when the value changed and downstream effects were scheduled.
427    #[inline(always)]
428    pub fn set_if_changed(&self, value: ValueType) -> bool
429    where
430        ValueType: PartialEq,
431    {
432        let id: SignalId = self.id();
433        let (updated, should_flush): (bool, bool) = with_runtime(
434            |runtime_ref: &mut ReactiveRuntime| runtime_ref.write_signal_if_changed(id, value),
435            (false, false),
436        );
437        if should_flush {
438            flush_effects();
439        }
440        updated
441    }
442
443    /// Disposes this signal, unlinks its edges in O(deg), and drops its payload outside the runtime borrow.
444    ///
445    /// # Arguments
446    ///
447    /// - `&Self` - Signal handle to dispose.
448    pub fn dispose(&self) {
449        let id: SignalId = self.id();
450        let dropped: SignalSlot = with_runtime(
451            |runtime_ref: &mut ReactiveRuntime| runtime_ref.dispose_signal(id),
452            SignalSlot::empty(),
453        );
454        drop(dropped);
455    }
456}