Skip to main content

euv_core/reactive/signal/
struct.rs

1use super::*;
2
3/// Inner state of a signal, holding the value and subscribed listeners.
4///
5/// This struct is not exposed directly; use `Signal` instead.
6#[derive(CustomDebug, Data, New)]
7pub(crate) struct SignalInner<T>
8where
9    T: Clone,
10{
11    /// The current value of the signal.
12    #[debug(skip)]
13    #[get(pub(crate))]
14    #[get_mut(pub(crate))]
15    #[set(pub(crate))]
16    pub(crate) value: T,
17    /// Callbacks to invoke when the value changes, each paired with its
18    /// subscription id so [`Signal::unsubscribe`] can detach a single
19    /// listener without disturbing the rest.
20    #[debug(skip)]
21    #[get(pub(crate))]
22    #[get_mut(pub(crate))]
23    #[set(pub(crate))]
24    pub(crate) listeners: Vec<(u64, Box<dyn FnMut()>)>,
25    /// Monotonic counter backing subscription ids for `listeners`.
26    #[get(pub, type(copy))]
27    #[get_mut(pub(crate))]
28    #[set(pub(crate))]
29    #[new(skip)]
30    pub(crate) next_listener_id: u64,
31    /// Ids detached via [`Signal::unsubscribe`] while `update` had the
32    /// listener list swapped out. Drained by `update`'s merge-back pass so
33    /// a listener detached mid-notification is not resurrected.
34    #[debug(skip)]
35    #[get(pub(crate))]
36    #[get_mut(pub(crate))]
37    #[set(pub(crate))]
38    #[new(skip)]
39    pub(crate) removed_listener_ids: Vec<u64>,
40    /// `true` while `update` has the listener list swapped out for
41    /// notification. `unsubscribe` consults this flag to decide between
42    /// direct removal and deferred removal via `removed_listener_ids`.
43    #[get(pub, type(copy))]
44    #[get_mut(pub(crate))]
45    #[set(pub(crate))]
46    #[new(skip)]
47    pub(crate) notifying: bool,
48    /// Whether this signal is still active. Set to `false` by `deactivate()`
49    /// (and `clear_signal_listeners`) to make subsequent `set()` calls
50    /// complete no-ops (no value update, no listener invocation, no
51    /// dispatch scheduling), ensuring stale closures like orphaned
52    /// `setInterval` handlers or pending `spawn_local` futures become harmless.
53    #[get(pub, type(copy))]
54    #[get_mut(pub(crate))]
55    #[set(pub(crate))]
56    pub(crate) alive: bool,
57    /// IDs of dynamic nodes that depend on this signal for precise dirty marking.
58    /// When this signal changes, only these dynamic nodes are marked dirty
59    /// instead of broadcasting to all registered dynamic nodes.
60    #[debug(skip)]
61    #[get(pub(crate))]
62    #[get_mut(pub(crate))]
63    #[set(pub(crate))]
64    #[new(skip)]
65    pub(crate) dependents: Vec<usize>,
66}
67
68/// A reactive signal handle.
69///
70/// Allows reading, writing, and subscribing to changes.
71/// Implements `Clone` and `Copy` for ergonomic use; all copies share the same
72/// underlying state. The inner state is heap-allocated via `Box` and accessed
73/// through a raw pointer stored as a `usize`. The allocation is tracked in a
74/// global registry for lifecycle management. The `Copy` semantics are safe
75/// because only the pointer address is copied — the actual heap allocation
76/// is owned by the registry.
77#[derive(CustomDebug, Data, Eq, Hash, New, Ord, PartialEq, PartialOrd)]
78pub struct Signal<T>
79where
80    T: Clone + PartialEq + 'static,
81{
82    /// Address of the heap-allocated inner state (`*mut SignalInner<T>`).
83    #[debug(skip)]
84    #[get(pub, type(copy))]
85    #[get_mut(pub(crate))]
86    #[set(pub(crate))]
87    pub(crate) inner: usize,
88    /// Marker for the generic type parameter (uses fn pointer to be `Copy`
89    /// regardless of `T`).
90    #[debug(skip)]
91    #[get(pub, type(copy))]
92    #[get_mut(pub(crate))]
93    #[set(pub(crate))]
94    pub(crate) _marker: PhantomData<fn() -> T>,
95}
96
97/// A `Sync` wrapper for single-threaded global `Signal` access.
98///
99/// SAFETY: This type is only safe to use in single-threaded contexts
100/// (e.g., WASM). It implements `Sync` to allow usage as a `static`
101/// variable, but concurrent access from multiple threads would be
102/// undefined behavior.
103#[derive(CustomDebug, Data, New)]
104pub struct SignalCell<T>
105where
106    T: Clone + PartialEq + 'static,
107{
108    /// Interior-mutable storage for an optional signal handle.
109    #[debug(skip)]
110    #[get(pub(crate))]
111    #[get_mut(pub(crate))]
112    #[set(pub(crate))]
113    pub(crate) inner: UnsafeCell<Option<Signal<T>>>,
114}
115
116/// Typed slab allocator for `SignalInner<T>`.
117///
118/// The slab owns all `SignalInner<T>` allocations for the program's
119/// lifetime. `Signal<T>` carries only a `usize` slot index, so signals are
120/// trivially `Copy` and stay cheap to clone. Slots are append-only and
121/// never recycled: a stale `Signal<T>` handle therefore always finds its
122/// original slot (marked `alive == false` after `Signal::deactivate`), so
123/// stale reads return the last stored value instead of hitting a reused
124/// slot of a different type or — worse — a `mem::zeroed()` fallback for
125/// a freed slot.
126pub(crate) struct SignalSlab {
127    /// Slot storage. Index 0..len.
128    pub(crate) entries: Vec<Box<dyn AnySignalInner>>,
129}
130
131/// A handle to a leaked `FnMut()` closure, stored as the closure's heap address.
132///
133/// The closure is double-boxed (`Box<Box<dyn FnMut()>>`) and leaked, so its
134/// memory outlives any `FireHandle` copy and can be safely invoked from any
135/// context via the raw pointer. The handle is `Copy` because it only holds
136/// the address — repeated invocations on captured copies all resolve to the
137/// same underlying closure.
138///
139/// This type replaces the inline `Box::leak(... as *mut Box<dyn FnMut()> as usize)`
140/// pattern that was used by `watch!`/`computed!` macros and the virtual list
141/// component, encapsulating the unsized coercion, double-boxing, and raw
142/// pointer arithmetic behind `From`/`Into` conversions and a dedicated
143/// `fire` method.
144#[derive(Clone, Copy, CustomDebug, Data, Eq, Hash, Ord, PartialEq, PartialOrd)]
145pub struct FireHandle {
146    /// Address of the leaked `Box<dyn FnMut()>` allocation.
147    #[get(pub, type(copy))]
148    #[get_mut(pub(crate))]
149    #[set(pub(crate))]
150    pub(crate) inner: usize,
151}