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.
18    #[debug(skip)]
19    #[get(pub(crate))]
20    #[get_mut(pub(crate))]
21    #[set(pub(crate))]
22    pub(crate) listeners: Vec<Box<dyn FnMut()>>,
23    /// Whether this signal is still active. Set to `false` by `deactivate()`
24    /// (and `clear_signal_listeners`) to make subsequent `set()` calls
25    /// complete no-ops (no value update, no listener invocation, no
26    /// dispatch scheduling), ensuring stale closures like orphaned
27    /// `setInterval` handlers or pending `spawn_local` futures become harmless.
28    #[get(pub, type(copy))]
29    #[get_mut(pub(crate))]
30    #[set(pub(crate))]
31    pub(crate) alive: bool,
32    /// IDs of dynamic nodes that depend on this signal for precise dirty marking.
33    /// When this signal changes, only these dynamic nodes are marked dirty
34    /// instead of broadcasting to all registered dynamic nodes.
35    #[debug(skip)]
36    #[get(pub(crate))]
37    #[get_mut(pub(crate))]
38    #[set(pub(crate))]
39    #[new(skip)]
40    pub(crate) dependents: Vec<usize>,
41    /// Flag indicating that `replace_subscribe` was called during
42    /// `update_and_notify`'s swap-out phase. When a listener callback
43    /// re-registers listeners via `replace_subscribe`, it intends to
44    /// replace all existing listeners — but the old listeners have
45    /// already been swapped out into the local variable. Without this
46    /// flag, `update_and_notify` would incorrectly merge the old
47    /// listeners back with the new ones, defeating `replace_subscribe`'s
48    /// replacement semantics and causing listener accumulation.
49    #[get(pub, type(copy))]
50    #[get_mut(pub(crate))]
51    #[set(pub(crate))]
52    #[new(skip)]
53    pub(crate) listeners_replaced: bool,
54}
55
56/// A reactive signal handle.
57///
58/// Allows reading, writing, and subscribing to changes.
59/// Implements `Clone` and `Copy` for ergonomic use; all copies share the same
60/// underlying state. The inner state is heap-allocated via `Box` and accessed
61/// through a raw pointer stored as a `usize`. The allocation is tracked in a
62/// global registry for lifecycle management. The `Copy` semantics are safe
63/// because only the pointer address is copied — the actual heap allocation
64/// is owned by the registry.
65#[derive(CustomDebug, Data, Eq, Hash, New, Ord, PartialEq, PartialOrd)]
66pub struct Signal<T>
67where
68    T: Clone + PartialEq + 'static,
69{
70    /// Address of the heap-allocated inner state (`*mut SignalInner<T>`).
71    #[debug(skip)]
72    #[get(pub, type(copy))]
73    #[get_mut(pub(crate))]
74    #[set(pub(crate))]
75    pub(crate) inner: usize,
76    /// Marker for the generic type parameter (uses fn pointer to be `Copy`
77    /// regardless of `T`).
78    #[debug(skip)]
79    #[get(pub, type(copy))]
80    #[get_mut(pub(crate))]
81    #[set(pub(crate))]
82    pub(crate) _marker: PhantomData<fn() -> T>,
83}
84
85/// A `Sync` wrapper for single-threaded global `Signal` access.
86///
87/// SAFETY: This type is only safe to use in single-threaded contexts
88/// (e.g., WASM). It implements `Sync` to allow usage as a `static`
89/// variable, but concurrent access from multiple threads would be
90/// undefined behavior.
91#[derive(CustomDebug, Data, New)]
92pub struct SignalCell<T>
93where
94    T: Clone + PartialEq + 'static,
95{
96    /// Interior-mutable storage for an optional signal handle.
97    #[debug(skip)]
98    #[get(pub(crate))]
99    #[get_mut(pub(crate))]
100    #[set(pub(crate))]
101    pub(crate) inner: UnsafeCell<Option<Signal<T>>>,
102}
103
104/// A `Sync` wrapper for single-threaded global `HashMap` access.
105///
106/// SAFETY: This type is only safe to use in single-threaded contexts
107/// (e.g., WASM). It implements `Sync` to allow usage as a `static`
108/// variable, but concurrent access from multiple threads would be
109/// undefined behavior.
110#[derive(Data, Debug, New)]
111pub(crate) struct BridgeRefsCell(
112    /// Interior-mutable storage for the bridge dependency reverse-index.
113    #[get(pub(crate))]
114    #[get_mut(pub(crate))]
115    #[set(pub(crate))]
116    pub UnsafeCell<HashMap<usize, HashSet<usize>>>,
117);
118
119/// A handle to a leaked `FnMut()` closure, stored as the closure's heap address.
120///
121/// The closure is double-boxed (`Box<Box<dyn FnMut()>>`) and leaked, so its
122/// memory outlives any `FireHandle` copy and can be safely invoked from any
123/// context via the raw pointer. The handle is `Copy` because it only holds
124/// the address — repeated invocations on captured copies all resolve to the
125/// same underlying closure.
126///
127/// This type replaces the inline `Box::leak(... as *mut Box<dyn FnMut()> as usize)`
128/// pattern that was used by `watch!`/`computed!` macros and the virtual list
129/// component, encapsulating the unsized coercion, double-boxing, and raw
130/// pointer arithmetic behind `From`/`Into` conversions and a dedicated
131/// `fire` method.
132#[derive(Clone, Copy, CustomDebug, Data, Eq, Hash, Ord, PartialEq, PartialOrd)]
133pub struct FireHandle {
134    /// Address of the leaked `Box<dyn FnMut()>` allocation.
135    #[get(pub, type(copy))]
136    #[get_mut(pub(crate))]
137    #[set(pub(crate))]
138    pub(crate) inner: usize,
139}
140
141/// Typed slab allocator for `SignalInner<T>`.
142///
143/// The slab owns all `SignalInner<T>` allocations for the program's
144/// lifetime. `Signal<T>` carries only a `usize` slot index, so signals are
145/// trivially `Copy` and stay cheap to clone. Reclamation is explicit via
146/// `Signal::deactivate`, which calls [`SignalSlab::free`]; `Copy`
147/// semantics intentionally prevent an implicit `Drop` from double-freeing.
148///
149/// Layout:
150/// - `entries: Vec<SignalSlot>` — slot storage, indexed 0..len.
151/// - `free_head: usize` — head of the free-slot stack, `usize::MAX` when empty.
152///
153/// Allocation is O(1) (free-list pop or Vec push). Free is O(1) (push to
154/// free-list head, drop the boxed inner). Lookup is O(1) bounds-checked
155/// `Vec` indexing.
156pub(crate) struct SignalSlab {
157    /// Slot storage. Index 0..len.
158    pub(crate) entries: Vec<SignalSlot>,
159    /// Head of the free-slot stack; `usize::MAX` when no free slots exist.
160    pub(crate) free_head: usize,
161}
162
163/// Implementation of the typed signal slab allocator.
164impl SignalSlab {
165    /// Creates an empty slab.
166    pub(crate) fn new() -> Self {
167        Self {
168            entries: Vec::new(),
169            free_head: usize::MAX,
170        }
171    }
172
173    /// Inserts a new typed `SignalInner<T>` and returns its slot index.
174    ///
175    /// Reuses a previously freed slot when the free list is non-empty;
176    /// otherwise appends a fresh entry to `entries`. Both paths are O(1).
177    pub(crate) fn insert<T>(&mut self, inner: SignalInner<T>) -> usize
178    where
179        T: Clone + PartialEq + 'static,
180    {
181        let boxed: Box<dyn AnySignalInner> = Box::new(inner);
182        if self.free_head != usize::MAX {
183            let idx: usize = self.free_head;
184            let next: usize = match &self.entries[idx] {
185                SignalSlot::Free { next } => *next,
186                SignalSlot::Occupied(_) => {
187                    // Invariant violation: free_head pointed to an
188                    // occupied slot. Defensively reset the free list and
189                    // allocate a fresh entry. This branch is unreachable
190                    // in correct usage because `free()` is the only code
191                    // that mutates the free list and it always pushes a
192                    // Free entry. We avoid `unreachable!()` per project
193                    // audit rule R11.4 (no panic in production code).
194                    self.free_head = usize::MAX;
195                    let new_idx: usize = self.entries.len();
196                    self.entries.push(SignalSlot::Occupied(boxed));
197                    return new_idx;
198                }
199            };
200            self.free_head = next;
201            self.entries[idx] = SignalSlot::Occupied(boxed);
202            idx
203        } else {
204            let idx: usize = self.entries.len();
205            self.entries.push(SignalSlot::Occupied(boxed));
206            idx
207        }
208    }
209
210    /// Returns a typed `&mut SignalInner<T>` view of the slot at `idx`.
211    ///
212    /// Returns `None` when the slot is free or has a different concrete
213    /// `T` (defensive TypeId check). Both outcomes mean the caller is
214    /// holding a stale `Signal<T>` handle — that is a bug, but we surface
215    /// it as `None` rather than panicking so that stale handles from
216    /// long-deactivated signals degrade into safe no-ops (matching the
217    /// existing `alive == false` semantics).
218    pub(crate) fn get_mut<T>(&mut self, idx: usize) -> Option<&mut SignalInner<T>>
219    where
220        T: Clone + PartialEq + 'static,
221    {
222        match self.entries.get_mut(idx)? {
223            SignalSlot::Occupied(slot) => {
224                let any: &mut dyn Any = (**slot).as_any_mut();
225                any.downcast_mut::<SignalInner<T>>()
226            }
227            SignalSlot::Free { .. } => None,
228        }
229    }
230
231    /// Returns `true` when the slot at `idx` is occupied AND its inner
232    /// signal is still marked `alive`. Used by `Signal::is_alive` and the
233    /// bridge-reclaim paths.
234    ///
235    /// Matches the old `SIGNAL_INNER_REGISTRY.contains(&addr)` semantic:
236    /// after `clear_listeners` calls `deactivate(idx)`, the inner's
237    /// `alive` flag becomes `false` and `is_alive` returns `false`, even
238    /// though the slot remains parked for stale-handle safety.
239    pub(crate) fn is_alive(&self, idx: usize) -> bool {
240        match self.entries.get(idx) {
241            Some(SignalSlot::Occupied(inner)) => inner.alive(),
242            Some(SignalSlot::Free { .. }) => false,
243            None => false,
244        }
245    }
246
247    /// Frees the slot at `idx` and pushes it onto the free list.
248    ///
249    /// The boxed `SignalInner<T>` is dropped (releasing its inner Vec
250    /// capacity back to the allocator) before the slot is recycled.
251    /// Subsequent `insert` calls reuse this slot index.
252    pub(crate) fn free(&mut self, idx: usize) {
253        if let Some(slot @ SignalSlot::Occupied(_)) = self.entries.get_mut(idx) {
254            // Drop the boxed inner explicitly, then replace with Free.
255            *slot = SignalSlot::Free {
256                next: self.free_head,
257            };
258            self.free_head = idx;
259        }
260    }
261
262    /// Marks the slot at `idx` as inactive without freeing it.
263    ///
264    /// Mirrors the existing `deactivate` semantics: the slot remains
265    /// occupied (so stale `Signal<T>` copies continue to find a slot and
266    /// become safe no-ops via the `alive == false` check) but stops
267    /// accepting new value updates.
268    pub(crate) fn deactivate(&mut self, idx: usize) {
269        if let Some(SignalSlot::Occupied(inner)) = self.entries.get_mut(idx) {
270            inner.set_inactive();
271        }
272    }
273}