Skip to main content

euv_core/reactive/runtime/
impl.rs

1use super::*;
2
3/// Inline small-list operations for reactive subscriber and dependency collections.
4impl<T> SmallSubList<T>
5where
6    T: Copy + PartialEq,
7{
8    /// Returns `true` when zero entries are stored.
9    ///
10    /// # Arguments
11    ///
12    /// - `&Self` - Small list reference.
13    ///
14    /// # Returns
15    ///
16    /// - `bool` - `true` if the list contains no items.
17    #[must_use]
18    #[inline(always)]
19    pub(crate) fn is_empty(&self) -> bool {
20        match self {
21            Self::Empty => true,
22            Self::One(_) | Self::Two(_, _) => false,
23            Self::Many(vec) => vec.is_empty(),
24        }
25    }
26
27    /// Returns the number of stored entries.
28    ///
29    /// # Arguments
30    ///
31    /// - `&Self` - Small list reference.
32    ///
33    /// # Returns
34    ///
35    /// - `usize` - Number of items currently stored.
36    #[must_use]
37    #[inline(always)]
38    pub(crate) fn len(&self) -> usize {
39        match self {
40            Self::Empty => 0,
41            Self::One(_) => 1,
42            Self::Two(_, _) => 2,
43            Self::Many(vec) => vec.len(),
44        }
45    }
46
47    /// Returns the entry at `index` if in bounds.
48    ///
49    /// # Arguments
50    ///
51    /// - `&Self` - Small list reference.
52    /// - `usize` - Zero-based item index.
53    ///
54    /// # Returns
55    ///
56    /// - `Option<T>` - Copied item at `index`, or `None` when out of bounds.
57    #[must_use]
58    #[inline(always)]
59    pub(crate) fn get(&self, index: usize) -> Option<T> {
60        match self {
61            Self::Empty => None,
62            Self::One(first) => {
63                if index == 0 {
64                    Some(*first)
65                } else {
66                    None
67                }
68            }
69            Self::Two(first, second) => match index {
70                0 => Some(*first),
71                1 => Some(*second),
72                _ => None,
73            },
74            Self::Many(vec) => vec.get(index).copied(),
75        }
76    }
77
78    /// Checks whether `target` already exists within the prefix `0..end`.
79    ///
80    /// # Arguments
81    ///
82    /// - `&Self` - Small list reference.
83    /// - `usize` - Exclusive upper index bound of the prefix.
84    /// - `T` - Entry to search for.
85    ///
86    /// # Returns
87    ///
88    /// - `bool` - `true` when `target` appears before index `end`.
89    #[must_use]
90    #[inline(always)]
91    pub(crate) fn contains_prefix(&self, end: usize, target: T) -> bool {
92        if end == 0 {
93            return false;
94        }
95        match self {
96            Self::Empty => false,
97            Self::One(first) => *first == target,
98            Self::Two(first, second) => {
99                if *first == target {
100                    true
101                } else {
102                    end > 1 && *second == target
103                }
104            }
105            Self::Many(vec) => {
106                let bound: usize = end.min(vec.len());
107                vec[..bound].contains(&target)
108            }
109        }
110    }
111
112    /// Finds the first index `>= start` whose entry equals `target`.
113    ///
114    /// # Arguments
115    ///
116    /// - `&Self` - Small list reference.
117    /// - `usize` - Inclusive start index.
118    /// - `T` - Entry to locate.
119    ///
120    /// # Returns
121    ///
122    /// - `Option<usize>` - Matching index if found at or after `start`.
123    #[must_use]
124    #[inline(always)]
125    pub(crate) fn find_from(&self, start: usize, target: T) -> Option<usize> {
126        match self {
127            Self::Empty => None,
128            Self::One(first) => {
129                if start == 0 && *first == target {
130                    Some(0)
131                } else {
132                    None
133                }
134            }
135            Self::Two(first, second) => {
136                if start == 0 && *first == target {
137                    Some(0)
138                } else if start <= 1 && *second == target {
139                    Some(1)
140                } else {
141                    None
142                }
143            }
144            Self::Many(vec) => {
145                let mut idx: usize = start;
146                while idx < vec.len() {
147                    if vec[idx] == target {
148                        return Some(idx);
149                    }
150                    idx += 1;
151                }
152                None
153            }
154        }
155    }
156
157    /// Swaps two in-bounds entries at `a` and `b`.
158    ///
159    /// # Arguments
160    ///
161    /// - `&Self` - Mutable small list reference.
162    /// - `usize` - First element index.
163    /// - `usize` - Second element index.
164    #[inline(always)]
165    pub(crate) fn swap(&mut self, a: usize, b: usize) {
166        if a == b {
167            return;
168        }
169        match self {
170            Self::Empty | Self::One(_) => {}
171            Self::Two(first, second) => {
172                if (a == 0 && b == 1) || (a == 1 && b == 0) {
173                    swap(first, second);
174                }
175            }
176            Self::Many(vec) => {
177                if a < vec.len() && b < vec.len() {
178                    vec.swap(a, b);
179                }
180            }
181        }
182    }
183
184    /// Appends `value` assuming uniqueness has already been established by the caller.
185    ///
186    /// # Arguments
187    ///
188    /// - `&Self` - Mutable small list reference.
189    /// - `T` - Unique entry to append.
190    #[inline(always)]
191    pub(crate) fn push_unchecked(&mut self, value: T) {
192        match self {
193            Self::Empty => {
194                *self = Self::One(value);
195            }
196            Self::One(first) => {
197                *self = Self::Two(*first, value);
198            }
199            Self::Two(first, second) => {
200                let mut list: Vec<T> = Vec::with_capacity(INITIAL_SUBSCRIBER_CAPACITY);
201                list.push(*first);
202                list.push(*second);
203                list.push(value);
204                *self = Self::Many(list);
205            }
206            Self::Many(vec) => {
207                vec.push(value);
208            }
209        }
210    }
211
212    /// Splits off and returns all entries at indices `>= keep_len`, keeping `0..keep_len` in place.
213    ///
214    /// # Arguments
215    ///
216    /// - `&Self` - Mutable small list reference.
217    /// - `usize` - Number of leading entries to retain.
218    ///
219    /// # Returns
220    ///
221    /// - `Self` - Removed tail entries.
222    #[inline(always)]
223    pub(crate) fn take_tail(&mut self, keep_len: usize) -> Self {
224        match self {
225            Self::Empty => Self::Empty,
226            Self::One(first) => {
227                if keep_len == 0 {
228                    let item: T = *first;
229                    *self = Self::Empty;
230                    Self::One(item)
231                } else {
232                    Self::Empty
233                }
234            }
235            Self::Two(first, second) => match keep_len {
236                0 => {
237                    let a: T = *first;
238                    let b: T = *second;
239                    *self = Self::Empty;
240                    Self::Two(a, b)
241                }
242                1 => {
243                    let a: T = *first;
244                    let b: T = *second;
245                    *self = Self::One(a);
246                    Self::One(b)
247                }
248                _ => Self::Empty,
249            },
250            Self::Many(vec) => {
251                if keep_len >= vec.len() {
252                    return Self::Empty;
253                }
254                let removed: usize = vec.len() - keep_len;
255                if removed == 1
256                    && let Some(item) = vec.pop()
257                {
258                    return Self::One(item);
259                }
260                if removed == 2
261                    && let Some(second) = vec.pop()
262                    && let Some(first) = vec.pop()
263                {
264                    return Self::Two(first, second);
265                }
266                Self::Many(vec.split_off(keep_len))
267            }
268        }
269    }
270
271    /// Appends `value` if it is not already present, promoting inline storage to `Many` only on the third unique item.
272    ///
273    /// # Arguments
274    ///
275    /// - `&Self` - Mutable small list reference.
276    /// - `T` - Entry to insert uniquely.
277    #[inline(always)]
278    pub(crate) fn push_unique(&mut self, value: T) {
279        match self {
280            Self::Empty => {
281                *self = Self::One(value);
282            }
283            Self::One(first) => {
284                if *first != value {
285                    *self = Self::Two(*first, value);
286                }
287            }
288            Self::Two(first, second) => {
289                if *first != value && *second != value {
290                    let mut list: Vec<T> = Vec::with_capacity(INITIAL_SUBSCRIBER_CAPACITY);
291                    list.push(*first);
292                    list.push(*second);
293                    list.push(value);
294                    *self = Self::Many(list);
295                }
296            }
297            Self::Many(vec) => {
298                if !vec.contains(&value) {
299                    vec.push(value);
300                }
301            }
302        }
303    }
304
305    /// Removes every occurrence of `target` while preserving insertion order of remaining entries.
306    ///
307    /// # Arguments
308    ///
309    /// - `&Self` - Mutable small list reference.
310    /// - `T` - Entry value to remove.
311    #[inline(always)]
312    pub(crate) fn remove_item(&mut self, target: T) {
313        match self {
314            Self::Empty => {}
315            Self::One(first) => {
316                if *first == target {
317                    *self = Self::Empty;
318                }
319            }
320            Self::Two(first, second) => {
321                if *first == target {
322                    *self = Self::One(*second);
323                } else if *second == target {
324                    *self = Self::One(*first);
325                }
326            }
327            Self::Many(vec) => {
328                vec.retain(|item: &T| *item != target);
329            }
330        }
331    }
332
333    /// Empties all stored items while retaining heap capacity if already promoted to `Many`.
334    ///
335    /// # Arguments
336    ///
337    /// - `&Self` - Mutable small list reference.
338    #[inline(always)]
339    pub(crate) fn clear(&mut self) {
340        match self {
341            Self::Empty => {}
342            Self::One(_) | Self::Two(_, _) => {
343                *self = Self::Empty;
344            }
345            Self::Many(vec) => {
346                vec.clear();
347            }
348        }
349    }
350
351    /// Visits every stored item in insertion order without allocating.
352    ///
353    /// # Arguments
354    ///
355    /// - `&Self` - Small list reference.
356    /// - `F` - Visitor closure receiving each copied item.
357    #[inline(always)]
358    pub(crate) fn for_each<F>(&self, mut visit: F)
359    where
360        F: FnMut(T),
361    {
362        match self {
363            Self::Empty => {}
364            Self::One(first) => {
365                visit(*first);
366            }
367            Self::Two(first, second) => {
368                visit(*first);
369                visit(*second);
370            }
371            Self::Many(vec) => {
372                for item in vec.iter().copied() {
373                    visit(item);
374                }
375            }
376        }
377    }
378
379    /// Drains and visits every stored item in insertion order while retaining `Many` heap capacity.
380    ///
381    /// # Arguments
382    ///
383    /// - `&Self` - Mutable small list reference.
384    /// - `F` - Visitor closure receiving each drained item.
385    #[inline(always)]
386    pub(crate) fn drain_each<F>(&mut self, mut visit: F)
387    where
388        F: FnMut(T),
389    {
390        match self {
391            Self::Empty => {}
392            Self::One(first) => {
393                let item: T = *first;
394                *self = Self::Empty;
395                visit(item);
396            }
397            Self::Two(first, second) => {
398                let a: T = *first;
399                let b: T = *second;
400                *self = Self::Empty;
401                visit(a);
402                visit(b);
403            }
404            Self::Many(vec) => {
405                for item in vec.drain(..) {
406                    visit(item);
407                }
408            }
409        }
410    }
411}
412
413/// Panic-safe tracking guard helpers.
414impl TrackingGuard {
415    /// Creates an armed `TrackingGuard` protecting the newly pushed observer frame.
416    ///
417    /// # Returns
418    ///
419    /// - `Self` - Armed unwind guard.
420    #[must_use]
421    #[inline(always)]
422    pub(crate) fn new() -> Self {
423        Self { active: true }
424    }
425
426    /// Disarms the guard before normal completion pops the tracking frame explicitly.
427    ///
428    /// # Arguments
429    ///
430    /// - `&Self` - Mutable guard reference.
431    #[inline(always)]
432    pub(crate) fn disarm(&mut self) {
433        let Self { active } = self;
434        *active = false;
435    }
436}
437
438/// Dirty-propagation target extraction for subscriber small-lists.
439impl SmallSubList<SubscriberId> {
440    /// Extracts a zero-allocation copyable dispatch target for dirty propagation.
441    ///
442    /// # Arguments
443    ///
444    /// - `&Self` - Subscriber list reference.
445    ///
446    /// # Returns
447    ///
448    /// - `DirtyTarget` - Inline target for 0..=2 subscribers or `Many` heap fallback.
449    #[must_use]
450    #[inline(always)]
451    pub(crate) fn dirty_target(&self) -> DirtyTarget {
452        match self {
453            Self::Empty => DirtyTarget::Empty,
454            Self::One(sub) => DirtyTarget::One(*sub),
455            Self::Two(first, second) => DirtyTarget::Two(*first, *second),
456            Self::Many(vec) => {
457                if vec.is_empty() {
458                    DirtyTarget::Empty
459                } else {
460                    DirtyTarget::Many
461                }
462            }
463        }
464    }
465}
466
467/// Unwind cleanup popping any leaked observer frame if a reactive computation panics.
468impl Drop for TrackingGuard {
469    /// Pops the leaked frame from `observer_stack` when unwinding while still armed.
470    ///
471    /// # Arguments
472    ///
473    /// - `&Self` - Mutable guard being dropped.
474    fn drop(&mut self) {
475        let Self { active } = self;
476        if *active {
477            with_runtime(
478                |rt: &mut ReactiveRuntime| {
479                    let _: Option<Option<(SubscriberId, usize)>> =
480                        rt.get_mut_observer_stack().pop();
481                },
482                (),
483            );
484        }
485    }
486}
487
488/// Default initialization for `ReactiveRuntime`.
489impl Default for ReactiveRuntime {
490    /// Creates an empty reactive runtime with preallocated arena buffers.
491    ///
492    /// # Returns
493    ///
494    /// - `Self` - The initialized runtime instance.
495    fn default() -> Self {
496        Self {
497            signals: Vec::with_capacity(INITIAL_ARENA_CAPACITY),
498            free_signals: Vec::new(),
499            memos: Vec::with_capacity(INITIAL_ARENA_CAPACITY),
500            free_memos: Vec::new(),
501            effects: Vec::with_capacity(INITIAL_ARENA_CAPACITY),
502            free_effects: Vec::new(),
503            scopes: Vec::with_capacity(INITIAL_ARENA_CAPACITY),
504            free_scopes: Vec::new(),
505            observer_stack: Vec::new(),
506            scope_stack: Vec::new(),
507            pending_effects: Vec::new(),
508            dirty_queue: Vec::with_capacity(INITIAL_SUBSCRIBER_CAPACITY),
509            check_scratch: Vec::new(),
510            flush_batch_scratch: Vec::new(),
511            scope_stack_scratch: Vec::new(),
512            dispose_effects_scratch: Vec::new(),
513            dispose_memos_scratch: Vec::new(),
514            dispose_signals_scratch: Vec::new(),
515            batch_depth: 0,
516            flushing: false,
517            clock: 0,
518            global_states: HashMap::new(),
519            named_global_states: HashMap::new(),
520            event_channels: HashMap::new(),
521        }
522    }
523}
524
525/// Core arena operations for `ReactiveRuntime`.
526impl ReactiveRuntime {
527    /// Allocates a new signal slot storing `initial_value`.
528    ///
529    /// # Arguments
530    ///
531    /// - `&Self` - Mutable reference to the reactive runtime.
532    /// - `T` - Initial signal value.
533    ///
534    /// # Returns
535    ///
536    /// - `SignalId` - Handle for the newly created signal.
537    pub(crate) fn create_signal<T>(&mut self, initial_value: T) -> SignalId
538    where
539        T: 'static,
540    {
541        let boxed: Box<dyn Any> = Box::new(initial_value);
542        let id: SignalId = if let Some(index) = self.get_mut_free_signals().pop() {
543            let entry: &mut SignalEntry = &mut self.get_mut_signals()[index as usize];
544            let next_gen: u32 = entry.get_generation().wrapping_add(1);
545            entry.set_generation(next_gen);
546            entry.set_version(0);
547            entry.set_value(Some(boxed));
548            entry.get_mut_subscribers().clear();
549            SignalId::from_slot(SlotId::new(index, next_gen))
550        } else {
551            let index: u32 = self.get_signals().len() as u32;
552            self.get_mut_signals().push(SignalEntry {
553                generation: 1,
554                version: 0,
555                value: Some(boxed),
556                subscribers: SmallSubList::Empty,
557            });
558            SignalId::from_slot(SlotId::new(index, 1))
559        };
560        if let Some(scope_id) = self.get_scope_stack().last().copied() {
561            self.attach_signal_to_scope(scope_id, id);
562        }
563        id
564    }
565
566    /// Allocates a new root-lifetime signal in the arena without binding it to the active transient `Scope`.
567    ///
568    /// # Arguments
569    ///
570    /// - `&Self` - Mutable reactive runtime.
571    /// - `T` - Initial signal value.
572    ///
573    /// # Returns
574    ///
575    /// - `SignalId` - Newly allocated detached signal identifier.
576    pub(crate) fn create_detached_signal<T>(&mut self, initial_value: T) -> SignalId
577    where
578        T: 'static,
579    {
580        let boxed: Box<dyn Any> = Box::new(initial_value);
581        if let Some(index) = self.get_mut_free_signals().pop() {
582            let entry: &mut SignalEntry = &mut self.get_mut_signals()[index as usize];
583            let next_gen: u32 = entry.get_generation().wrapping_add(1);
584            entry.set_generation(next_gen);
585            entry.set_version(0);
586            entry.set_value(Some(boxed));
587            entry.get_mut_subscribers().clear();
588            SignalId::from_slot(SlotId::new(index, next_gen))
589        } else {
590            let index: u32 = self.get_signals().len() as u32;
591            self.get_mut_signals().push(SignalEntry {
592                generation: 1,
593                version: 0,
594                value: Some(boxed),
595                subscribers: SmallSubList::Empty,
596            });
597            SignalId::from_slot(SlotId::new(index, 1))
598        }
599    }
600
601    /// Registers or replaces a root-lifetime global state signal keyed by `TypeId::of::<T>()`.
602    ///
603    /// # Arguments
604    ///
605    /// - `&Self` - Mutable reactive runtime.
606    /// - `T` - Initial or replacement global state value.
607    ///
608    /// # Returns
609    ///
610    /// - `(SignalId, bool)` - Tuple of `(signal_id, should_flush)` when updating an existing slot.
611    pub(crate) fn provide_global_state<T>(&mut self, initial: T) -> (SignalId, bool)
612    where
613        T: 'static,
614    {
615        let key: TypeId = TypeId::of::<T>();
616        if let Some(existing_id) = self.get_global_states().get(&key).copied() {
617            let slot: SlotId = existing_id.slot();
618            let alive: bool = self
619                .get_signals()
620                .get(slot.as_usize())
621                .map(|e: &SignalEntry| {
622                    e.get_generation() == slot.get_generation() && e.value.is_some()
623                })
624                .unwrap_or(false);
625            if alive {
626                let (_, flush): (bool, bool) = self.write_signal(existing_id, initial);
627                return (existing_id, flush);
628            }
629        }
630        let id: SignalId = self.create_detached_signal(initial);
631        let _: Option<SignalId> = self.get_mut_global_states().insert(key, id);
632        (id, false)
633    }
634
635    /// Looks up a registered root-lifetime global state signal keyed by `TypeId::of::<T>()`.
636    ///
637    /// # Arguments
638    ///
639    /// - `&Self` - Reactive runtime reference.
640    ///
641    /// # Returns
642    ///
643    /// - `Option<SignalId>` - Registered signal handle if present.
644    pub(crate) fn lookup_global_state<T>(&self) -> Option<SignalId>
645    where
646        T: 'static,
647    {
648        self.get_global_states().get(&TypeId::of::<T>()).copied()
649    }
650
651    /// Looks up a registered global state signal or initializes it lazily with `init`.
652    ///
653    /// # Arguments
654    ///
655    /// - `&Self` - Mutable reactive runtime.
656    /// - `F` - Lazy initializer invoked only when absent.
657    ///
658    /// # Returns
659    ///
660    /// - `SignalId` - Existing or newly created global state signal handle.
661    pub(crate) fn get_or_init_global_state<T, F>(&mut self, init: F) -> SignalId
662    where
663        T: 'static,
664        F: FnOnce() -> T,
665    {
666        let key: TypeId = TypeId::of::<T>();
667        if let Some(existing_id) = self.get_global_states().get(&key).copied() {
668            return existing_id;
669        }
670        let id: SignalId = self.create_detached_signal(init());
671        let _: Option<SignalId> = self.get_mut_global_states().insert(key, id);
672        id
673    }
674
675    /// Registers or replaces a string-keyed root-lifetime named global state signal.
676    ///
677    /// # Arguments
678    ///
679    /// - `&Self` - Mutable reactive runtime.
680    /// - `&str` - Global state channel name.
681    /// - `T` - Initial or replacement value.
682    ///
683    /// # Returns
684    ///
685    /// - `(SignalId, bool)` - Tuple of `(signal_id, should_flush)`.
686    pub(crate) fn provide_named_global_state<T>(
687        &mut self,
688        name: &str,
689        initial: T,
690    ) -> (SignalId, bool)
691    where
692        T: 'static,
693    {
694        if let Some(existing_id) = self.get_named_global_states().get(name).copied() {
695            let slot: SlotId = existing_id.slot();
696            let alive: bool = self
697                .get_signals()
698                .get(slot.as_usize())
699                .map(|e: &SignalEntry| {
700                    e.get_generation() == slot.get_generation() && e.value.is_some()
701                })
702                .unwrap_or(false);
703            if alive {
704                let (_, flush): (bool, bool) = self.write_signal(existing_id, initial);
705                return (existing_id, flush);
706            }
707        }
708        let id: SignalId = self.create_detached_signal(initial);
709        let _: Option<SignalId> = self
710            .get_mut_named_global_states()
711            .insert(name.to_string(), id);
712        (id, false)
713    }
714
715    /// Looks up a string-keyed named global state signal.
716    ///
717    /// # Arguments
718    ///
719    /// - `&Self` - Reactive runtime reference.
720    /// - `&str` - Global state channel name.
721    ///
722    /// # Returns
723    ///
724    /// - `Option<SignalId>` - Registered signal handle if present.
725    pub(crate) fn lookup_named_global_state(&self, name: &str) -> Option<SignalId> {
726        self.get_named_global_states().get(name).copied()
727    }
728
729    /// Looks up or allocates the detached event channel signal for custom event type `E`.
730    ///
731    /// # Arguments
732    ///
733    /// - `&Self` - Mutable reactive runtime.
734    ///
735    /// # Returns
736    ///
737    /// - `SignalId` - Detached `Signal<(u64, Option<E>)>` channel identifier.
738    pub(crate) fn ensure_event_channel<E>(&mut self) -> SignalId
739    where
740        E: CustomEvent,
741    {
742        let key: TypeId = TypeId::of::<E>();
743        if let Some(existing_id) = self.get_event_channels().get(&key).copied() {
744            return existing_id;
745        }
746        let initial: (u64, Option<E>) = (0, None);
747        let id: SignalId = self.create_detached_signal(initial);
748        let _: Option<SignalId> = self.get_mut_event_channels().insert(key, id);
749        id
750    }
751
752    /// Reads a signal value via cloning inside the arena and records dependency tracking.
753    ///
754    /// # Arguments
755    ///
756    /// - `&Self` - Mutable reference to the reactive runtime.
757    /// - `SignalId` - Signal identifier to read.
758    ///
759    /// # Returns
760    ///
761    /// - `Option<T>` - Cloned signal value if the slot is alive and matches type `T`.
762    #[inline]
763    pub(crate) fn read_signal_cloned<T>(&mut self, id: SignalId) -> Option<T>
764    where
765        T: Clone + 'static,
766    {
767        if !self.get_observer_stack().is_empty() {
768            self.track_dependency(DependencyId::Signal(id));
769        }
770        let slot: SlotId = id.slot();
771        let entry: &SignalEntry = self.get_signals().get(slot.as_usize())?;
772        if entry.get_generation() != slot.get_generation() {
773            return None;
774        }
775        let boxed: &Box<dyn Any> = entry.value.as_ref()?;
776        boxed.downcast_ref::<T>().cloned()
777    }
778
779    /// Reads a signal value without recording any reactive dependency.
780    ///
781    /// # Arguments
782    ///
783    /// - `&Self` - Reference to the reactive runtime.
784    /// - `SignalId` - Signal identifier to inspect.
785    ///
786    /// # Returns
787    ///
788    /// - `Option<T>` - Cloned signal value if alive and matching type `T`.
789    #[inline]
790    pub(crate) fn read_signal_untracked<T>(&self, id: SignalId) -> Option<T>
791    where
792        T: Clone + 'static,
793    {
794        let slot: SlotId = id.slot();
795        let entry: &SignalEntry = self.get_signals().get(slot.as_usize())?;
796        if entry.get_generation() != slot.get_generation() {
797            return None;
798        }
799        let boxed: &Box<dyn Any> = entry.value.as_ref()?;
800        boxed.downcast_ref::<T>().cloned()
801    }
802
803    /// Returns whether a live signal slot currently has one or more active subscribers.
804    ///
805    /// # Arguments
806    ///
807    /// - `&Self` - Reference to the reactive runtime.
808    /// - `SignalId` - Signal identifier to inspect.
809    ///
810    /// # Returns
811    ///
812    /// - `bool` - True when the signal is alive and observed by at least one subscriber.
813    #[inline]
814    pub(crate) fn signal_has_subscribers(&self, id: SignalId) -> bool {
815        let slot: SlotId = id.slot();
816        self.get_signals()
817            .get(slot.as_usize())
818            .map(|entry: &SignalEntry| {
819                entry.get_generation() == slot.get_generation()
820                    && entry.value.is_some()
821                    && !entry.get_subscribers().is_empty()
822            })
823            .unwrap_or(false)
824    }
825
826    /// Writes a new signal value in place and propagates dirty notifications without heap allocations.
827    ///
828    /// # Arguments
829    ///
830    /// - `&Self` - Mutable reference to the reactive runtime.
831    /// - `SignalId` - Signal identifier to update.
832    /// - `T` - Replacement value.
833    ///
834    /// # Returns
835    ///
836    /// - `(bool, bool)` - Tuple `(updated, should_flush)` indicating whether the signal was alive and whether effects are pending.
837    #[inline]
838    pub(crate) fn write_signal<T>(&mut self, id: SignalId, value: T) -> (bool, bool)
839    where
840        T: 'static,
841    {
842        let slot: SlotId = id.slot();
843        let idx: usize = slot.as_usize();
844        let Some(entry) = self.get_mut_signals().get_mut(idx) else {
845            return (false, false);
846        };
847        let stale: bool = entry.get_generation() != slot.get_generation();
848        if stale || entry.value.is_none() {
849            return (false, false);
850        }
851        if let Some(existing) = entry
852            .value
853            .as_mut()
854            .and_then(|boxed: &mut Box<dyn Any>| boxed.downcast_mut::<T>())
855        {
856            *existing = value;
857        } else {
858            entry.set_value(Some(Box::new(value)));
859        }
860        let next_ver: u64 = entry.get_version().wrapping_add(1);
861        entry.set_version(next_ver);
862        let target: DirtyTarget = entry.get_subscribers().dirty_target();
863        let next_clock: u64 = self.get_clock().wrapping_add(1);
864        self.set_clock(next_clock);
865        if matches!(target, DirtyTarget::Empty) {
866            return (true, false);
867        }
868        self.propagate_signal_dirty(idx, target);
869        let should_flush: bool = self.get_batch_depth() == 0
870            && !self.get_flushing()
871            && !self.get_pending_effects().is_empty();
872        (true, should_flush)
873    }
874
875    /// Takes a live signal's boxed payload for zero-clone in-place mutation outside the runtime borrow.
876    ///
877    /// # Arguments
878    ///
879    /// - `&Self` - Mutable reference to the reactive runtime.
880    /// - `SignalId` - Signal identifier whose payload should be temporarily taken.
881    ///
882    /// # Returns
883    ///
884    /// - `Option<Box<dyn Any>>` - Existing boxed value when the slot is alive and matches type `T`.
885    #[inline]
886    pub(crate) fn take_signal_box<T>(&mut self, id: SignalId) -> Option<Box<dyn Any>>
887    where
888        T: 'static,
889    {
890        let slot: SlotId = id.slot();
891        let entry: &mut SignalEntry = self.get_mut_signals().get_mut(slot.as_usize())?;
892        if entry.get_generation() != slot.get_generation() {
893            return None;
894        }
895        if !entry
896            .value
897            .as_ref()
898            .is_some_and(|boxed: &Box<dyn Any>| boxed.is::<T>())
899        {
900            return None;
901        }
902        entry.value.take()
903    }
904
905    /// Restores a mutated signal payload box, bumps version and clock, and returns immediately when unobserved.
906    ///
907    /// # Arguments
908    ///
909    /// - `&Self` - Mutable reference to the reactive runtime.
910    /// - `SignalId` - Signal identifier receiving its mutated payload.
911    /// - `Box<dyn Any>` - Mutated payload box previously taken via `take_signal_box`.
912    ///
913    /// # Returns
914    ///
915    /// - `(bool, bool)` - Tuple `(updated, should_flush)` indicating whether the signal was alive and whether effects must flush.
916    #[inline]
917    pub(crate) fn commit_signal_box(&mut self, id: SignalId, boxed: Box<dyn Any>) -> (bool, bool) {
918        let slot: SlotId = id.slot();
919        let idx: usize = slot.as_usize();
920        let Some(entry) = self.get_mut_signals().get_mut(idx) else {
921            return (false, false);
922        };
923        if entry.get_generation() != slot.get_generation() {
924            return (false, false);
925        }
926        entry.set_value(Some(boxed));
927        let next_ver: u64 = entry.get_version().wrapping_add(1);
928        entry.set_version(next_ver);
929        let target: DirtyTarget = entry.get_subscribers().dirty_target();
930        let next_clock: u64 = self.get_clock().wrapping_add(1);
931        self.set_clock(next_clock);
932        if matches!(target, DirtyTarget::Empty) {
933            return (true, false);
934        }
935        self.propagate_signal_dirty(idx, target);
936        let should_flush: bool = self.get_batch_depth() == 0
937            && !self.get_flushing()
938            && !self.get_pending_effects().is_empty();
939        (true, should_flush)
940    }
941
942    /// Writes a signal value and propagates dirtiness without checking flush state, returning whether subscribers existed.
943    ///
944    /// # Arguments
945    ///
946    /// - `&Self` - Mutable reference to the reactive runtime.
947    /// - `SignalId` - Signal identifier to update.
948    /// - `T` - Replacement value.
949    ///
950    /// # Returns
951    ///
952    /// - `bool` - `true` when the signal was alive and had at least one downstream subscriber.
953    #[inline]
954    fn write_signal_no_flush<T>(&mut self, id: SignalId, value: T) -> bool
955    where
956        T: 'static,
957    {
958        let slot: SlotId = id.slot();
959        let idx: usize = slot.as_usize();
960        let Some(entry) = self.get_mut_signals().get_mut(idx) else {
961            return false;
962        };
963        let stale: bool = entry.get_generation() != slot.get_generation();
964        if stale || entry.value.is_none() {
965            return false;
966        }
967        if let Some(existing) = entry
968            .value
969            .as_mut()
970            .and_then(|boxed: &mut Box<dyn Any>| boxed.downcast_mut::<T>())
971        {
972            *existing = value;
973        } else {
974            entry.set_value(Some(Box::new(value)));
975        }
976        let next_ver: u64 = entry.get_version().wrapping_add(1);
977        entry.set_version(next_ver);
978        let target: DirtyTarget = entry.get_subscribers().dirty_target();
979        let next_clock: u64 = self.get_clock().wrapping_add(1);
980        self.set_clock(next_clock);
981        if matches!(target, DirtyTarget::Empty) {
982            return false;
983        }
984        self.propagate_signal_dirty(idx, target);
985        true
986    }
987
988    /// Atomically updates an optional deselected and newly selected `Selector` signal pair in one runtime borrow.
989    ///
990    /// # Arguments
991    ///
992    /// - `&Self` - Mutable reference to the reactive runtime.
993    /// - `Option<SignalId>` - Previously selected key signal to set to `false`, if any.
994    /// - `Option<SignalId>` - Newly selected key signal to set to `true`, if any.
995    ///
996    /// # Returns
997    ///
998    /// - `bool` - `true` when at least one signal had subscribers and effects must be flushed now.
999    pub(crate) fn write_selector_pair(
1000        &mut self,
1001        old_id: Option<SignalId>,
1002        new_id: Option<SignalId>,
1003    ) -> bool {
1004        let mut any_subs: bool = false;
1005        if let Some(id) = old_id
1006            && self.write_signal_no_flush(id, false)
1007        {
1008            any_subs = true;
1009        }
1010        if let Some(id) = new_id
1011            && self.write_signal_no_flush(id, true)
1012        {
1013            any_subs = true;
1014        }
1015        any_subs
1016            && self.get_batch_depth() == 0
1017            && !self.get_flushing()
1018            && !self.get_pending_effects().is_empty()
1019    }
1020
1021    /// Writes a new signal value in place only when it differs from the stored value.
1022    ///
1023    /// # Arguments
1024    ///
1025    /// - `&Self` - Mutable reference to the reactive runtime.
1026    /// - `SignalId` - Signal identifier to update.
1027    /// - `T` - Candidate value compared using `PartialEq`.
1028    ///
1029    /// # Returns
1030    ///
1031    /// - `(bool, bool)` - Tuple `(changed, should_flush)` indicating whether the value changed and whether effects are pending.
1032    #[inline]
1033    pub(crate) fn write_signal_if_changed<T>(&mut self, id: SignalId, value: T) -> (bool, bool)
1034    where
1035        T: PartialEq + 'static,
1036    {
1037        let slot: SlotId = id.slot();
1038        let idx: usize = slot.as_usize();
1039        let Some(entry) = self.get_mut_signals().get_mut(idx) else {
1040            return (false, false);
1041        };
1042        if entry.get_generation() != slot.get_generation() {
1043            return (false, false);
1044        }
1045        let Some(current) = entry
1046            .value
1047            .as_mut()
1048            .and_then(|boxed: &mut Box<dyn Any>| boxed.downcast_mut::<T>())
1049        else {
1050            return (false, false);
1051        };
1052        if *current == value {
1053            return (false, false);
1054        }
1055        *current = value;
1056        let next_ver: u64 = entry.get_version().wrapping_add(1);
1057        entry.set_version(next_ver);
1058        let target: DirtyTarget = entry.get_subscribers().dirty_target();
1059        let next_clock: u64 = self.get_clock().wrapping_add(1);
1060        self.set_clock(next_clock);
1061        if matches!(target, DirtyTarget::Empty) {
1062            return (true, false);
1063        }
1064        self.propagate_signal_dirty(idx, target);
1065        let should_flush: bool = self.get_batch_depth() == 0
1066            && !self.get_flushing()
1067            && !self.get_pending_effects().is_empty();
1068        (true, should_flush)
1069    }
1070
1071    /// Allocates a new memo slot with an in-place type-erased computation closure.
1072    ///
1073    /// # Arguments
1074    ///
1075    /// - `&Self` - Mutable reference to the reactive runtime.
1076    /// - `F` - Memo computation closure mutating the cached value in place and returning `changed`.
1077    ///
1078    /// # Returns
1079    ///
1080    /// - `MemoId` - Handle for the newly created memo.
1081    pub(crate) fn create_memo<F>(&mut self, compute: F) -> MemoId
1082    where
1083        F: FnMut(&mut Option<Box<dyn Any>>) -> bool + 'static,
1084    {
1085        let depth: u32 = (self.get_observer_stack().len() as u32).saturating_add(1);
1086        let compute_rc: MemoComputeFn = Rc::new(RefCell::new(compute));
1087        let id: MemoId = if let Some(index) = self.get_mut_free_memos().pop() {
1088            let entry: &mut MemoEntry = &mut self.get_mut_memos()[index as usize];
1089            let next_gen: u32 = entry.get_generation().wrapping_add(1);
1090            entry.set_generation(next_gen);
1091            entry.set_version(0);
1092            entry.set_state(NodeState::Dirty);
1093            entry.set_value(None);
1094            entry.set_compute(Some(compute_rc));
1095            entry.get_mut_dependencies().clear();
1096            entry.get_mut_subscribers().clear();
1097            entry.set_depth(depth);
1098            MemoId::from_slot(SlotId::new(index, next_gen))
1099        } else {
1100            let index: u32 = self.get_memos().len() as u32;
1101            self.get_mut_memos().push(MemoEntry {
1102                generation: 1,
1103                version: 0,
1104                state: NodeState::Dirty,
1105                value: None,
1106                compute: Some(compute_rc),
1107                dependencies: SmallSubList::Empty,
1108                subscribers: SmallSubList::Empty,
1109                depth,
1110            });
1111            MemoId::from_slot(SlotId::new(index, 1))
1112        };
1113        if let Some(scope_id) = self.get_scope_stack().last().copied() {
1114            self.attach_memo_to_scope(scope_id, id);
1115        }
1116        id
1117    }
1118
1119    /// Allocates a new effect slot and schedules it for immediate execution.
1120    ///
1121    /// # Arguments
1122    ///
1123    /// - `&Self` - Mutable reference to the reactive runtime.
1124    /// - `F` - Effect callback closure.
1125    ///
1126    /// # Returns
1127    ///
1128    /// - `EffectId` - Handle for the newly created effect.
1129    pub(crate) fn create_effect<F>(&mut self, callback: F) -> EffectId
1130    where
1131        F: FnMut() + 'static,
1132    {
1133        let depth: u32 = (self.get_observer_stack().len() as u32).saturating_add(1);
1134        let callback_rc: Rc<RefCell<dyn FnMut()>> = Rc::new(RefCell::new(callback));
1135        let id: EffectId = if let Some(index) = self.get_mut_free_effects().pop() {
1136            let entry: &mut EffectEntry = &mut self.get_mut_effects()[index as usize];
1137            let next_gen: u32 = entry.get_generation().wrapping_add(1);
1138            entry.set_generation(next_gen);
1139            entry.set_alive(true);
1140            entry.set_scheduled(false);
1141            entry.set_callback(Some(callback_rc));
1142            entry.get_mut_dependencies().clear();
1143            entry.set_depth(depth);
1144            entry.set_frozen_depth(0);
1145            entry.set_pending_while_frozen(false);
1146            EffectId::from_slot(SlotId::new(index, next_gen))
1147        } else {
1148            let index: u32 = self.get_effects().len() as u32;
1149            self.get_mut_effects().push(EffectEntry {
1150                generation: 1,
1151                alive: true,
1152                scheduled: false,
1153                callback: Some(callback_rc),
1154                dependencies: SmallSubList::Empty,
1155                depth,
1156                frozen_depth: 0,
1157                pending_while_frozen: false,
1158            });
1159            EffectId::from_slot(SlotId::new(index, 1))
1160        };
1161        if let Some(scope_id) = self.get_scope_stack().last().copied() {
1162            self.attach_effect_to_scope(scope_id, id);
1163        }
1164        id
1165    }
1166
1167    /// Creates a new ownership scope and optionally links it to the active parent scope.
1168    ///
1169    /// # Arguments
1170    ///
1171    /// - `&Self` - Mutable reference to the reactive runtime.
1172    ///
1173    /// # Returns
1174    ///
1175    /// - `ScopeId` - Identifier for the newly created scope.
1176    pub(crate) fn create_scope(&mut self) -> ScopeId {
1177        let parent_opt: Option<ScopeId> = self.get_scope_stack().last().copied();
1178        let live_parent: Option<ScopeId> = parent_opt.filter(|parent_id: &ScopeId| {
1179            let parent_slot: SlotId = parent_id.slot();
1180            self.get_scopes()
1181                .get(parent_slot.as_usize())
1182                .is_some_and(|parent: &ScopeEntry| {
1183                    parent.get_generation() == parent_slot.get_generation() && parent.get_alive()
1184                })
1185        });
1186        let id: ScopeId = if let Some(index) = self.get_mut_free_scopes().pop() {
1187            let entry: &mut ScopeEntry = &mut self.get_mut_scopes()[index as usize];
1188            let next_gen: u32 = entry.get_generation().wrapping_add(1);
1189            entry.set_generation(next_gen);
1190            entry.set_alive(true);
1191            entry.set_frozen(false);
1192            entry.set_parent(live_parent);
1193            entry.get_mut_signals().clear();
1194            entry.get_mut_memos().clear();
1195            entry.get_mut_effects().clear();
1196            entry.get_mut_children().clear();
1197            entry.get_mut_cleanups().clear();
1198            ScopeId::from_slot(SlotId::new(index, next_gen))
1199        } else {
1200            let index: u32 = self.get_scopes().len() as u32;
1201            self.get_mut_scopes().push(ScopeEntry {
1202                generation: 1,
1203                alive: true,
1204                frozen: false,
1205                parent: live_parent,
1206                signals: Vec::new(),
1207                memos: Vec::new(),
1208                effects: Vec::new(),
1209                children: Vec::new(),
1210                cleanups: Vec::new(),
1211            });
1212            ScopeId::from_slot(SlotId::new(index, 1))
1213        };
1214        if let Some(parent_id) = live_parent {
1215            let parent_slot: SlotId = parent_id.slot();
1216            if let Some(parent) = self.get_mut_scopes().get_mut(parent_slot.as_usize()) {
1217                parent.get_mut_children().push(id);
1218            }
1219        }
1220        id
1221    }
1222
1223    /// Registers a cleanup callback on the currently active scope.
1224    ///
1225    /// # Arguments
1226    ///
1227    /// - `&Self` - Mutable reference to the reactive runtime.
1228    /// - `F` - Cleanup closure invoked when the active scope disposes.
1229    pub(crate) fn register_cleanup<F>(&mut self, cleanup: F)
1230    where
1231        F: FnOnce() + 'static,
1232    {
1233        if let Some(scope_id) = self.get_scope_stack().last().copied() {
1234            let slot: SlotId = scope_id.slot();
1235            if let Some(entry) = self.get_mut_scopes().get_mut(slot.as_usize())
1236                && entry.get_generation() == slot.get_generation()
1237                && entry.get_alive()
1238            {
1239                entry.get_mut_cleanups().push(Box::new(cleanup));
1240            }
1241        }
1242    }
1243
1244    /// Records `dependency` on the currently executing observer using O(1) cursor reuse on stable graphs.
1245    ///
1246    /// # Arguments
1247    ///
1248    /// - `&Self` - Mutable reference to the reactive runtime.
1249    /// - `DependencyId` - The dependency accessed during evaluation.
1250    pub(crate) fn track_dependency(&mut self, dependency: DependencyId) {
1251        let Some(Some((subscriber, cursor))) = self.get_observer_stack().last().copied() else {
1252            return;
1253        };
1254        let reuse_outcome: Option<usize> = match subscriber {
1255            SubscriberId::Memo(memo_id) => {
1256                let slot: SlotId = memo_id.slot();
1257                let Some(entry) = self.get_mut_memos().get_mut(slot.as_usize()) else {
1258                    return;
1259                };
1260                if entry.get_generation() != slot.get_generation() {
1261                    return;
1262                }
1263                let deps: &mut SmallSubList<DependencyId> = entry.get_mut_dependencies();
1264                if deps.get(cursor) == Some(dependency) {
1265                    Some(cursor + 1)
1266                } else if deps.contains_prefix(cursor, dependency) {
1267                    return;
1268                } else if let Some(found_idx) = deps.find_from(cursor + 1, dependency) {
1269                    deps.swap(cursor, found_idx);
1270                    Some(cursor + 1)
1271                } else {
1272                    None
1273                }
1274            }
1275            SubscriberId::Effect(effect_id) => {
1276                let slot: SlotId = effect_id.slot();
1277                let Some(entry) = self.get_mut_effects().get_mut(slot.as_usize()) else {
1278                    return;
1279                };
1280                if entry.get_generation() != slot.get_generation() {
1281                    return;
1282                }
1283                let deps: &mut SmallSubList<DependencyId> = entry.get_mut_dependencies();
1284                if deps.get(cursor) == Some(dependency) {
1285                    Some(cursor + 1)
1286                } else if deps.contains_prefix(cursor, dependency) {
1287                    return;
1288                } else if let Some(found_idx) = deps.find_from(cursor + 1, dependency) {
1289                    deps.swap(cursor, found_idx);
1290                    Some(cursor + 1)
1291                } else {
1292                    None
1293                }
1294            }
1295        };
1296        if let Some(next_cursor) = reuse_outcome {
1297            if let Some(Some((_, top_cursor))) = self.get_mut_observer_stack().last_mut() {
1298                *top_cursor = next_cursor;
1299            }
1300            return;
1301        }
1302        self.detach_tail_dependencies(subscriber, cursor);
1303        match dependency {
1304            DependencyId::Signal(sig_id) => {
1305                let slot: SlotId = sig_id.slot();
1306                if let Some(entry) = self.get_mut_signals().get_mut(slot.as_usize())
1307                    && entry.get_generation() == slot.get_generation()
1308                {
1309                    entry.get_mut_subscribers().push_unique(subscriber);
1310                }
1311            }
1312            DependencyId::Memo(memo_id) => {
1313                let slot: SlotId = memo_id.slot();
1314                if let Some(entry) = self.get_mut_memos().get_mut(slot.as_usize())
1315                    && entry.get_generation() == slot.get_generation()
1316                {
1317                    entry.get_mut_subscribers().push_unique(subscriber);
1318                }
1319            }
1320        }
1321        match subscriber {
1322            SubscriberId::Memo(memo_id) => {
1323                let slot: SlotId = memo_id.slot();
1324                if let Some(entry) = self.get_mut_memos().get_mut(slot.as_usize())
1325                    && entry.get_generation() == slot.get_generation()
1326                {
1327                    entry.get_mut_dependencies().push_unchecked(dependency);
1328                }
1329            }
1330            SubscriberId::Effect(effect_id) => {
1331                let slot: SlotId = effect_id.slot();
1332                if let Some(entry) = self.get_mut_effects().get_mut(slot.as_usize())
1333                    && entry.get_generation() == slot.get_generation()
1334                {
1335                    entry.get_mut_dependencies().push_unchecked(dependency);
1336                }
1337            }
1338        }
1339        if let Some(Some((_, top_cursor))) = self.get_mut_observer_stack().last_mut() {
1340            *top_cursor = cursor + 1;
1341        }
1342    }
1343
1344    /// Pops the top tracking frame and unsubscribes any stale tail dependencies beyond its final cursor.
1345    ///
1346    /// # Arguments
1347    ///
1348    /// - `&Self` - Mutable reference to the reactive runtime.
1349    pub(crate) fn finish_tracking(&mut self) {
1350        if let Some(Some((subscriber, cursor))) = self.get_mut_observer_stack().pop() {
1351            self.detach_tail_dependencies(subscriber, cursor);
1352        }
1353    }
1354
1355    /// Truncates `subscriber`'s dependency list to `keep_len` and unsubscribes from any removed tail dependencies.
1356    ///
1357    /// # Arguments
1358    ///
1359    /// - `&Self` - Mutable reference to the reactive runtime.
1360    /// - `SubscriberId` - Observer whose tail dependencies should be trimmed.
1361    /// - `usize` - Number of active leading dependencies to retain.
1362    fn detach_tail_dependencies(&mut self, subscriber: SubscriberId, keep_len: usize) {
1363        let stale: SmallSubList<DependencyId> = match subscriber {
1364            SubscriberId::Memo(memo_id) => {
1365                let slot: SlotId = memo_id.slot();
1366                match self.get_mut_memos().get_mut(slot.as_usize()) {
1367                    Some(entry) if entry.get_generation() == slot.get_generation() => {
1368                        let deps: &mut SmallSubList<DependencyId> = entry.get_mut_dependencies();
1369                        if deps.len() <= keep_len {
1370                            return;
1371                        }
1372                        deps.take_tail(keep_len)
1373                    }
1374                    _ => return,
1375                }
1376            }
1377            SubscriberId::Effect(effect_id) => {
1378                let slot: SlotId = effect_id.slot();
1379                match self.get_mut_effects().get_mut(slot.as_usize()) {
1380                    Some(entry) if entry.get_generation() == slot.get_generation() => {
1381                        let deps: &mut SmallSubList<DependencyId> = entry.get_mut_dependencies();
1382                        if deps.len() <= keep_len {
1383                            return;
1384                        }
1385                        deps.take_tail(keep_len)
1386                    }
1387                    _ => return,
1388                }
1389            }
1390        };
1391        stale.for_each(|dep: DependencyId| match dep {
1392            DependencyId::Signal(sig_id) => {
1393                let slot: SlotId = sig_id.slot();
1394                if let Some(entry) = self.get_mut_signals().get_mut(slot.as_usize())
1395                    && entry.get_generation() == slot.get_generation()
1396                {
1397                    entry.get_mut_subscribers().remove_item(subscriber);
1398                }
1399            }
1400            DependencyId::Memo(memo_id) => {
1401                let slot: SlotId = memo_id.slot();
1402                if let Some(entry) = self.get_mut_memos().get_mut(slot.as_usize())
1403                    && entry.get_generation() == slot.get_generation()
1404                {
1405                    entry.get_mut_subscribers().remove_item(subscriber);
1406                }
1407            }
1408        });
1409    }
1410
1411    /// Drains pending effects into the reusable batch buffer while preserving `pending_effects` capacity and tracking depth order.
1412    ///
1413    /// # Arguments
1414    ///
1415    /// - `&Self` - Mutable reference to the reactive runtime.
1416    /// - `Vec<(u32, EffectId)>` - Reusable caller-owned batch buffer returned from the prior flush step.
1417    ///
1418    /// # Returns
1419    ///
1420    /// - `FlushStep` - Next single effect, batch with sortedness flag, or `FlushStep::Done`.
1421    pub(crate) fn drain_pending_flush_step(
1422        &mut self,
1423        mut batch: Vec<(u32, EffectId)>,
1424    ) -> FlushStep {
1425        let pending_len: usize = self.get_pending_effects().len();
1426        if pending_len == 0 {
1427            if batch.capacity() > self.get_flush_batch_scratch().capacity() {
1428                self.set_flush_batch_scratch(batch);
1429            }
1430            self.set_flushing(false);
1431            return FlushStep::Done;
1432        }
1433        if pending_len == 1 {
1434            if batch.capacity() > self.get_flush_batch_scratch().capacity() {
1435                self.set_flush_batch_scratch(batch);
1436            }
1437            if let Some(eff_id) = self.get_mut_pending_effects().pop() {
1438                return FlushStep::Single(eff_id);
1439            }
1440            self.set_flushing(false);
1441            return FlushStep::Done;
1442        }
1443        if batch.capacity() < self.get_flush_batch_scratch().capacity() {
1444            batch = take(self.get_mut_flush_batch_scratch());
1445        }
1446        let Self {
1447            effects,
1448            pending_effects,
1449            ..
1450        } = self;
1451        batch.clear();
1452        if batch.capacity() < pending_effects.len() {
1453            batch.reserve(pending_effects.len() - batch.capacity());
1454        }
1455        let mut prev_depth: u32 = 0;
1456        let mut is_sorted: bool = true;
1457        for eff_id in pending_effects.drain(..) {
1458            let slot: SlotId = eff_id.slot();
1459            if let Some(entry) = effects.get(slot.as_usize())
1460                && entry.get_generation() == slot.get_generation()
1461                && entry.get_alive()
1462            {
1463                let depth: u32 = entry.get_depth();
1464                if depth < prev_depth {
1465                    is_sorted = false;
1466                }
1467                prev_depth = depth;
1468                batch.push((depth, eff_id));
1469            }
1470        }
1471        if batch.is_empty() {
1472            if batch.capacity() > self.get_flush_batch_scratch().capacity() {
1473                self.set_flush_batch_scratch(batch);
1474            }
1475            self.set_flushing(false);
1476            FlushStep::Done
1477        } else {
1478            FlushStep::Batch(batch, is_sorted)
1479        }
1480    }
1481
1482    /// Extracts upstream `MemoId` dependencies for `NodeState::Check` memo slot `memo_idx` without heap allocation.
1483    ///
1484    /// # Arguments
1485    ///
1486    /// - `&Self` - Mutable reference to the reactive runtime.
1487    /// - `usize` - Memo arena slot index.
1488    ///
1489    /// # Returns
1490    ///
1491    /// - `Option<MemoCheckDeps>` - Snapshot of upstream memo dependencies, or `None` when zero upstream memos exist.
1492    pub(crate) fn collect_check_memos(&mut self, memo_idx: usize) -> Option<MemoCheckDeps> {
1493        let Self {
1494            memos,
1495            check_scratch,
1496            ..
1497        } = self;
1498        let entry: &MemoEntry = memos.get(memo_idx)?;
1499        let mut inline_buf: [MemoId; 4] = [MemoId::default(); 4];
1500        let mut inline_len: usize = 0;
1501        let mut spill_start: Option<usize> = None;
1502        entry.get_dependencies().for_each(|dep: DependencyId| {
1503            if let DependencyId::Memo(parent_memo) = dep {
1504                if spill_start.is_some() {
1505                    check_scratch.push(parent_memo);
1506                } else if inline_len < inline_buf.len() {
1507                    inline_buf[inline_len] = parent_memo;
1508                    inline_len += 1;
1509                } else {
1510                    let start: usize = check_scratch.len();
1511                    check_scratch.extend_from_slice(&inline_buf);
1512                    check_scratch.push(parent_memo);
1513                    spill_start = Some(start);
1514                }
1515            }
1516        });
1517        if let Some(start) = spill_start {
1518            Some(MemoCheckDeps::Spill(start, check_scratch.len()))
1519        } else if inline_len == 0 {
1520            None
1521        } else {
1522            Some(MemoCheckDeps::Inline(inline_buf, inline_len as u8))
1523        }
1524    }
1525
1526    /// Propagates dirty flags downstream from a signal using inline fast paths for 1..=2 subscribers.
1527    ///
1528    /// # Arguments
1529    ///
1530    /// - `&Self` - Mutable reference to the reactive runtime.
1531    /// - `usize` - Signal arena slot index (used only for `DirtyTarget::Many`).
1532    /// - `DirtyTarget` - Pre-extracted subscriber dispatch target.
1533    #[inline]
1534    pub(crate) fn propagate_signal_dirty(&mut self, signal_idx: usize, target: DirtyTarget) {
1535        match target {
1536            DirtyTarget::Empty => {}
1537            DirtyTarget::One(sub) => {
1538                self.mark_single_subscriber_dirty(sub, false);
1539            }
1540            DirtyTarget::Two(first, second) => {
1541                self.mark_single_subscriber_dirty(first, false);
1542                self.mark_single_subscriber_dirty(second, false);
1543            }
1544            DirtyTarget::Many => {
1545                self.mark_signal_subscribers_dirty(signal_idx);
1546            }
1547        }
1548    }
1549
1550    /// Propagates dirty flags downstream from a recomputed memo using inline fast paths for 1..=2 subscribers.
1551    ///
1552    /// # Arguments
1553    ///
1554    /// - `&Self` - Mutable reference to the reactive runtime.
1555    /// - `usize` - Memo arena slot index (used only for `DirtyTarget::Many`).
1556    /// - `DirtyTarget` - Pre-extracted subscriber dispatch target.
1557    #[inline]
1558    pub(crate) fn propagate_memo_dirty(&mut self, memo_idx: usize, target: DirtyTarget) {
1559        match target {
1560            DirtyTarget::Empty => {}
1561            DirtyTarget::One(sub) => {
1562                self.mark_single_subscriber_dirty(sub, true);
1563            }
1564            DirtyTarget::Two(first, second) => {
1565                self.mark_single_subscriber_dirty(first, true);
1566                self.mark_single_subscriber_dirty(second, true);
1567            }
1568            DirtyTarget::Many => {
1569                self.mark_memo_subscribers_dirty(memo_idx);
1570            }
1571        }
1572    }
1573
1574    /// Schedules a single dirty effect without touching `dirty_queue`.
1575    ///
1576    /// # Arguments
1577    ///
1578    /// - `&Self` - Mutable reference to the reactive runtime.
1579    /// - `EffectId` - Effect identifier to schedule or flag while frozen.
1580    /// - `bool` - `true` when propagating from a pulled memo recomputation.
1581    #[inline(always)]
1582    fn schedule_dirty_effect(&mut self, effect_id: EffectId, from_memo: bool) {
1583        let Self {
1584            effects,
1585            observer_stack,
1586            pending_effects,
1587            ..
1588        } = self;
1589        if from_memo
1590            && !observer_stack.is_empty()
1591            && observer_stack
1592                .iter()
1593                .any(|frame: &Option<(SubscriberId, usize)>| {
1594                    matches!(frame, Some((SubscriberId::Effect(active), _)) if *active == effect_id)
1595                })
1596        {
1597            return;
1598        }
1599        let slot: SlotId = effect_id.slot();
1600        if let Some(entry) = effects.get_mut(slot.as_usize())
1601            && entry.get_generation() == slot.get_generation()
1602            && entry.get_alive()
1603        {
1604            if entry.get_frozen_depth() > 0 {
1605                entry.set_pending_while_frozen(true);
1606            } else if !entry.get_scheduled() {
1607                entry.set_scheduled(true);
1608                pending_effects.push(effect_id);
1609            }
1610        }
1611    }
1612
1613    /// Marks a single direct subscriber dirty and walks linear 1-subscriber memo chains in registers before spilling to `dirty_queue`.
1614    ///
1615    /// # Arguments
1616    ///
1617    /// - `&Self` - Mutable reference to the reactive runtime.
1618    /// - `SubscriberId` - Direct downstream subscriber.
1619    /// - `bool` - `true` when propagating from a pulled memo recomputation.
1620    #[inline]
1621    fn mark_single_subscriber_dirty(&mut self, first_sub: SubscriberId, from_memo: bool) {
1622        let mut cur_sub: SubscriberId = first_sub;
1623        let mut target_state: NodeState = NodeState::Dirty;
1624        loop {
1625            match cur_sub {
1626                SubscriberId::Effect(effect_id) => {
1627                    self.schedule_dirty_effect(effect_id, from_memo);
1628                    return;
1629                }
1630                SubscriberId::Memo(memo_id) => {
1631                    let slot: SlotId = memo_id.slot();
1632                    let idx: usize = slot.as_usize();
1633                    let next_target: DirtyTarget = {
1634                        let Some(entry) = self.get_mut_memos().get_mut(idx) else {
1635                            return;
1636                        };
1637                        let stale: bool = entry.get_generation() != slot.get_generation();
1638                        if stale || entry.compute.is_none() {
1639                            return;
1640                        }
1641                        let cur_state: NodeState = entry.get_state();
1642                        let check_covered: bool =
1643                            cur_state == NodeState::Check && target_state == NodeState::Check;
1644                        if cur_state == NodeState::Dirty || check_covered {
1645                            return;
1646                        }
1647                        entry.set_state(target_state);
1648                        entry.get_subscribers().dirty_target()
1649                    };
1650                    match next_target {
1651                        DirtyTarget::Empty => return,
1652                        DirtyTarget::One(next_sub) => {
1653                            cur_sub = next_sub;
1654                            target_state = NodeState::Check;
1655                        }
1656                        DirtyTarget::Two(first, second) => {
1657                            let dq: &mut Vec<(SubscriberId, NodeState)> =
1658                                self.get_mut_dirty_queue();
1659                            dq.clear();
1660                            dq.push((first, NodeState::Check));
1661                            dq.push((second, NodeState::Check));
1662                            self.drain_dirty_queue(from_memo);
1663                            return;
1664                        }
1665                        DirtyTarget::Many => {
1666                            let Self {
1667                                memos, dirty_queue, ..
1668                            } = self;
1669                            dirty_queue.clear();
1670                            if let Some(entry) = memos.get(idx)
1671                                && let SmallSubList::Many(vec) = entry.get_subscribers()
1672                            {
1673                                for child_sub in vec.iter().copied() {
1674                                    dirty_queue.push((child_sub, NodeState::Check));
1675                                }
1676                            }
1677                            self.drain_dirty_queue(from_memo);
1678                            return;
1679                        }
1680                    }
1681                }
1682            }
1683        }
1684    }
1685
1686    /// Propagates dirty flags downstream from signal slot `signal_idx` using the reusable scratch queue.
1687    ///
1688    /// # Arguments
1689    ///
1690    /// - `&Self` - Mutable reference to the reactive runtime.
1691    /// - `usize` - Signal arena slot index.
1692    pub(crate) fn mark_signal_subscribers_dirty(&mut self, signal_idx: usize) {
1693        let Self {
1694            signals,
1695            dirty_queue,
1696            ..
1697        } = self;
1698        dirty_queue.clear();
1699        if let Some(entry) = signals.get(signal_idx) {
1700            entry
1701                .get_subscribers()
1702                .for_each(|subscriber: SubscriberId| {
1703                    dirty_queue.push((subscriber, NodeState::Dirty));
1704                });
1705        }
1706        self.drain_dirty_queue(false);
1707    }
1708
1709    /// Propagates dirty flags downstream from memo slot `memo_idx` using the reusable scratch queue.
1710    ///
1711    /// # Arguments
1712    ///
1713    /// - `&Self` - Mutable reference to the reactive runtime.
1714    /// - `usize` - Memo arena slot index.
1715    pub(crate) fn mark_memo_subscribers_dirty(&mut self, memo_idx: usize) {
1716        let Self {
1717            memos, dirty_queue, ..
1718        } = self;
1719        dirty_queue.clear();
1720        if let Some(entry) = memos.get(memo_idx) {
1721            entry
1722                .get_subscribers()
1723                .for_each(|subscriber: SubscriberId| {
1724                    dirty_queue.push((subscriber, NodeState::Dirty));
1725                });
1726        }
1727        self.drain_dirty_queue(true);
1728    }
1729
1730    /// Drains the reusable `dirty_queue`, marking downstream memos and scheduling effects with zero allocations.
1731    ///
1732    /// # Arguments
1733    ///
1734    /// - `&Self` - Mutable reference to the reactive runtime.
1735    /// - `bool` - `true` when propagating from a pulled memo recomputation (skipping currently executing effects on `observer_stack`).
1736    fn drain_dirty_queue(&mut self, from_memo: bool) {
1737        let Self {
1738            memos,
1739            effects,
1740            observer_stack,
1741            pending_effects,
1742            dirty_queue,
1743            ..
1744        } = self;
1745        let check_running: bool = from_memo && !observer_stack.is_empty();
1746        while let Some((sub, target_state)) = dirty_queue.pop() {
1747            match sub {
1748                SubscriberId::Memo(memo_id) => {
1749                    let slot: SlotId = memo_id.slot();
1750                    if let Some(entry) = memos.get_mut(slot.as_usize()) {
1751                        let stale: bool = entry.get_generation() != slot.get_generation();
1752                        if stale || entry.compute.is_none() {
1753                            continue;
1754                        }
1755                        let cur_state: NodeState = entry.get_state();
1756                        let check_covered: bool =
1757                            cur_state == NodeState::Check && target_state == NodeState::Check;
1758                        if cur_state == NodeState::Dirty || check_covered {
1759                            continue;
1760                        }
1761                        entry.set_state(target_state);
1762                        match entry.get_subscribers() {
1763                            SmallSubList::Empty => {}
1764                            SmallSubList::One(child_sub) => {
1765                                dirty_queue.push((*child_sub, NodeState::Check));
1766                            }
1767                            SmallSubList::Two(first, second) => {
1768                                dirty_queue.push((*first, NodeState::Check));
1769                                dirty_queue.push((*second, NodeState::Check));
1770                            }
1771                            SmallSubList::Many(vec) => {
1772                                for child_sub in vec.iter().copied() {
1773                                    dirty_queue.push((child_sub, NodeState::Check));
1774                                }
1775                            }
1776                        }
1777                    }
1778                }
1779                SubscriberId::Effect(effect_id) => {
1780                    if check_running
1781                        && observer_stack.iter().any(
1782                            |frame: &Option<(SubscriberId, usize)>| {
1783                                matches!(frame, Some((SubscriberId::Effect(active), _)) if *active == effect_id)
1784                            },
1785                        )
1786                    {
1787                        continue;
1788                    }
1789                    let slot: SlotId = effect_id.slot();
1790                    if let Some(entry) = effects.get_mut(slot.as_usize())
1791                        && entry.get_generation() == slot.get_generation()
1792                        && entry.get_alive()
1793                    {
1794                        if entry.get_frozen_depth() > 0 {
1795                            entry.set_pending_while_frozen(true);
1796                        } else if !entry.get_scheduled() {
1797                            entry.set_scheduled(true);
1798                            pending_effects.push(effect_id);
1799                        }
1800                    }
1801                }
1802            }
1803        }
1804    }
1805
1806    /// Detaches a subscriber from all of its previously tracked upstream dependencies while preserving heap capacity.
1807    ///
1808    /// # Arguments
1809    ///
1810    /// - `&Self` - Mutable reference to the reactive runtime.
1811    /// - `SubscriberId` - Subscriber whose dependency links should be cleared.
1812    pub(crate) fn clear_dependencies(&mut self, subscriber: SubscriberId) {
1813        let mut deps: SmallSubList<DependencyId> = match subscriber {
1814            SubscriberId::Memo(memo_id) => {
1815                let slot: SlotId = memo_id.slot();
1816                match self.get_mut_memos().get_mut(slot.as_usize()) {
1817                    Some(entry) if entry.get_generation() == slot.get_generation() => {
1818                        take(entry.get_mut_dependencies())
1819                    }
1820                    _ => SmallSubList::Empty,
1821                }
1822            }
1823            SubscriberId::Effect(effect_id) => {
1824                let slot: SlotId = effect_id.slot();
1825                match self.get_mut_effects().get_mut(slot.as_usize()) {
1826                    Some(entry) if entry.get_generation() == slot.get_generation() => {
1827                        take(entry.get_mut_dependencies())
1828                    }
1829                    _ => SmallSubList::Empty,
1830                }
1831            }
1832        };
1833        if deps.is_empty() {
1834            return;
1835        }
1836        deps.drain_each(|dep: DependencyId| match dep {
1837            DependencyId::Signal(sig_id) => {
1838                let slot: SlotId = sig_id.slot();
1839                if let Some(entry) = self.get_mut_signals().get_mut(slot.as_usize())
1840                    && entry.get_generation() == slot.get_generation()
1841                {
1842                    entry.get_mut_subscribers().remove_item(subscriber);
1843                }
1844            }
1845            DependencyId::Memo(memo_id) => {
1846                let slot: SlotId = memo_id.slot();
1847                if let Some(entry) = self.get_mut_memos().get_mut(slot.as_usize())
1848                    && entry.get_generation() == slot.get_generation()
1849                {
1850                    entry.get_mut_subscribers().remove_item(subscriber);
1851                }
1852            }
1853        });
1854        if matches!(deps, SmallSubList::Many(_)) {
1855            match subscriber {
1856                SubscriberId::Memo(memo_id) => {
1857                    let slot: SlotId = memo_id.slot();
1858                    if let Some(entry) = self.get_mut_memos().get_mut(slot.as_usize())
1859                        && entry.get_generation() == slot.get_generation()
1860                    {
1861                        entry.set_dependencies(deps);
1862                    }
1863                }
1864                SubscriberId::Effect(effect_id) => {
1865                    let slot: SlotId = effect_id.slot();
1866                    if let Some(entry) = self.get_mut_effects().get_mut(slot.as_usize())
1867                        && entry.get_generation() == slot.get_generation()
1868                    {
1869                        entry.set_dependencies(deps);
1870                    }
1871                }
1872            }
1873        }
1874    }
1875
1876    /// Disposes a signal slot and returns it to the free list.
1877    ///
1878    /// # Arguments
1879    ///
1880    /// - `&Self` - Mutable reference to the reactive runtime.
1881    /// - `SignalId` - Signal identifier to dispose.
1882    pub(crate) fn dispose_signal(&mut self, id: SignalId) {
1883        let slot: SlotId = id.slot();
1884        if let Some(entry) = self.get_mut_signals().get_mut(slot.as_usize())
1885            && entry.get_generation() == slot.get_generation()
1886            && entry.value.is_some()
1887        {
1888            entry.set_value(None);
1889            entry.get_mut_subscribers().clear();
1890            let next_gen: u32 = entry.get_generation().wrapping_add(1);
1891            entry.set_generation(next_gen);
1892            self.get_mut_free_signals().push(slot.get_index());
1893        }
1894    }
1895
1896    /// Disposes a memo slot and detaches its dependencies.
1897    ///
1898    /// # Arguments
1899    ///
1900    /// - `&Self` - Mutable reference to the reactive runtime.
1901    /// - `MemoId` - Memo identifier to dispose.
1902    pub(crate) fn dispose_memo(&mut self, id: MemoId) {
1903        self.clear_dependencies(SubscriberId::Memo(id));
1904        let slot: SlotId = id.slot();
1905        if let Some(entry) = self.get_mut_memos().get_mut(slot.as_usize())
1906            && entry.get_generation() == slot.get_generation()
1907            && entry.compute.is_some()
1908        {
1909            entry.set_value(None);
1910            entry.set_compute(None);
1911            entry.get_mut_subscribers().clear();
1912            let next_gen: u32 = entry.get_generation().wrapping_add(1);
1913            entry.set_generation(next_gen);
1914            self.get_mut_free_memos().push(slot.get_index());
1915        }
1916    }
1917
1918    /// Disposes an effect slot and detaches its dependencies.
1919    ///
1920    /// # Arguments
1921    ///
1922    /// - `&Self` - Mutable reference to the reactive runtime.
1923    /// - `EffectId` - Effect identifier to dispose.
1924    pub(crate) fn dispose_effect(&mut self, id: EffectId) {
1925        self.clear_dependencies(SubscriberId::Effect(id));
1926        let slot: SlotId = id.slot();
1927        if let Some(entry) = self.get_mut_effects().get_mut(slot.as_usize())
1928            && entry.get_generation() == slot.get_generation()
1929            && entry.get_alive()
1930        {
1931            entry.set_alive(false);
1932            entry.set_scheduled(false);
1933            entry.set_frozen_depth(0);
1934            entry.set_pending_while_frozen(false);
1935            entry.set_callback(None);
1936            let next_gen: u32 = entry.get_generation().wrapping_add(1);
1937            entry.set_generation(next_gen);
1938            self.get_mut_free_effects().push(slot.get_index());
1939        }
1940    }
1941
1942    /// Collects all resources belonging to a scope and marks them disposed, returning cleanup closures.
1943    ///
1944    /// # Arguments
1945    ///
1946    /// - `&Self` - Mutable reference to the reactive runtime.
1947    /// - `ScopeId` - Scope identifier to dispose recursively.
1948    ///
1949    /// # Returns
1950    ///
1951    /// - `Vec<Box<dyn FnOnce()>>` - Cleanup callbacks to execute outside the runtime borrow.
1952    pub(crate) fn dispose_scope_collect(&mut self, id: ScopeId) -> Vec<Box<dyn FnOnce()>> {
1953        let mut all_cleanups: Vec<Box<dyn FnOnce()>> = Vec::new();
1954        let root_slot: SlotId = id.slot();
1955        let has_children: bool = {
1956            let Self {
1957                scopes,
1958                free_scopes,
1959                scope_stack_scratch,
1960                dispose_effects_scratch,
1961                dispose_memos_scratch,
1962                dispose_signals_scratch,
1963                ..
1964            } = self;
1965            let Some(entry) = scopes.get_mut(root_slot.as_usize()) else {
1966                return all_cleanups;
1967            };
1968            let inactive: bool =
1969                entry.get_generation() != root_slot.get_generation() || !entry.get_alive();
1970            if inactive {
1971                return all_cleanups;
1972            }
1973            entry.set_alive(false);
1974            entry.set_frozen(false);
1975            entry.set_parent(None);
1976            let next_gen: u32 = entry.get_generation().wrapping_add(1);
1977            entry.set_generation(next_gen);
1978            free_scopes.push(root_slot.get_index());
1979            dispose_effects_scratch.clear();
1980            dispose_memos_scratch.clear();
1981            dispose_signals_scratch.clear();
1982            let children_non_empty: bool = !entry.get_children().is_empty();
1983            if children_non_empty {
1984                scope_stack_scratch.clear();
1985                scope_stack_scratch.append(entry.get_mut_children());
1986            }
1987            if !entry.get_effects().is_empty() {
1988                dispose_effects_scratch.append(entry.get_mut_effects());
1989            }
1990            if !entry.get_memos().is_empty() {
1991                dispose_memos_scratch.append(entry.get_mut_memos());
1992            }
1993            if !entry.get_signals().is_empty() {
1994                dispose_signals_scratch.append(entry.get_mut_signals());
1995            }
1996            if !entry.get_mut_cleanups().is_empty() {
1997                all_cleanups = take(entry.get_mut_cleanups());
1998            }
1999            children_non_empty
2000        };
2001        if has_children {
2002            let Self {
2003                scopes,
2004                free_scopes,
2005                scope_stack_scratch,
2006                dispose_effects_scratch,
2007                dispose_memos_scratch,
2008                dispose_signals_scratch,
2009                ..
2010            } = self;
2011            while let Some(current_id) = scope_stack_scratch.pop() {
2012                let slot: SlotId = current_id.slot();
2013                if let Some(entry) = scopes.get_mut(slot.as_usize())
2014                    && entry.get_generation() == slot.get_generation()
2015                    && entry.get_alive()
2016                {
2017                    entry.set_alive(false);
2018                    entry.set_frozen(false);
2019                    entry.set_parent(None);
2020                    let next_gen: u32 = entry.get_generation().wrapping_add(1);
2021                    entry.set_generation(next_gen);
2022                    free_scopes.push(slot.get_index());
2023                    if !entry.get_children().is_empty() {
2024                        scope_stack_scratch.append(entry.get_mut_children());
2025                    }
2026                    if !entry.get_effects().is_empty() {
2027                        dispose_effects_scratch.append(entry.get_mut_effects());
2028                    }
2029                    if !entry.get_memos().is_empty() {
2030                        dispose_memos_scratch.append(entry.get_mut_memos());
2031                    }
2032                    if !entry.get_signals().is_empty() {
2033                        dispose_signals_scratch.append(entry.get_mut_signals());
2034                    }
2035                    if !entry.get_mut_cleanups().is_empty() {
2036                        if all_cleanups.is_empty() {
2037                            all_cleanups = take(entry.get_mut_cleanups());
2038                        } else {
2039                            all_cleanups.append(entry.get_mut_cleanups());
2040                        }
2041                    }
2042                }
2043            }
2044        }
2045        while let Some(eff) = self.get_mut_dispose_effects_scratch().pop() {
2046            self.dispose_effect(eff);
2047        }
2048        while let Some(memo) = self.get_mut_dispose_memos_scratch().pop() {
2049            self.dispose_memo(memo);
2050        }
2051        while let Some(sig) = self.get_mut_dispose_signals_scratch().pop() {
2052            self.dispose_signal(sig);
2053        }
2054        all_cleanups
2055    }
2056
2057    /// Computes live diagnostic statistics for the runtime arena.
2058    ///
2059    /// # Arguments
2060    ///
2061    /// - `&Self` - Reference to the reactive runtime.
2062    ///
2063    /// # Returns
2064    ///
2065    /// - `ReactiveStats` - Snapshot of live node counts and write clock.
2066    #[must_use]
2067    pub fn stats(&self) -> ReactiveStats {
2068        let live_signals: usize = self
2069            .get_signals()
2070            .iter()
2071            .filter(|entry: &&SignalEntry| entry.value.is_some())
2072            .count();
2073        let live_memos: usize = self
2074            .get_memos()
2075            .iter()
2076            .filter(|entry: &&MemoEntry| entry.compute.is_some())
2077            .count();
2078        let live_effects: usize = self
2079            .get_effects()
2080            .iter()
2081            .filter(|entry: &&EffectEntry| entry.get_alive())
2082            .count();
2083        let live_scopes: usize = self
2084            .get_scopes()
2085            .iter()
2086            .filter(|entry: &&ScopeEntry| entry.get_alive())
2087            .count();
2088        ReactiveStats::new(
2089            live_signals,
2090            live_memos,
2091            live_effects,
2092            live_scopes,
2093            self.get_clock(),
2094        )
2095    }
2096
2097    /// Attaches a signal identifier to an active scope entry.
2098    ///
2099    /// # Arguments
2100    ///
2101    /// - `&Self` - Mutable reference to the reactive runtime.
2102    /// - `ScopeId` - Target scope identifier.
2103    /// - `SignalId` - Signal identifier to attach.
2104    fn attach_signal_to_scope(&mut self, scope_id: ScopeId, signal_id: SignalId) {
2105        let slot: SlotId = scope_id.slot();
2106        if let Some(entry) = self.get_mut_scopes().get_mut(slot.as_usize())
2107            && entry.get_generation() == slot.get_generation()
2108            && entry.get_alive()
2109        {
2110            entry.get_mut_signals().push(signal_id);
2111        }
2112    }
2113
2114    /// Attaches a memo identifier to an active scope entry.
2115    ///
2116    /// # Arguments
2117    ///
2118    /// - `&Self` - Mutable reference to the reactive runtime.
2119    /// - `ScopeId` - Target scope identifier.
2120    /// - `MemoId` - Memo identifier to attach.
2121    fn attach_memo_to_scope(&mut self, scope_id: ScopeId, memo_id: MemoId) {
2122        let slot: SlotId = scope_id.slot();
2123        if let Some(entry) = self.get_mut_scopes().get_mut(slot.as_usize())
2124            && entry.get_generation() == slot.get_generation()
2125            && entry.get_alive()
2126        {
2127            entry.get_mut_memos().push(memo_id);
2128        }
2129    }
2130
2131    /// Attaches an effect identifier to an active scope entry.
2132    ///
2133    /// # Arguments
2134    ///
2135    /// - `&Self` - Mutable reference to the reactive runtime.
2136    /// - `ScopeId` - Target scope identifier.
2137    /// - `EffectId` - Effect identifier to attach.
2138    fn attach_effect_to_scope(&mut self, scope_id: ScopeId, effect_id: EffectId) {
2139        let slot: SlotId = scope_id.slot();
2140        let scope_is_frozen: bool = if let Some(entry) =
2141            self.get_mut_scopes().get_mut(slot.as_usize())
2142            && entry.get_generation() == slot.get_generation()
2143            && entry.get_alive()
2144        {
2145            entry.get_mut_effects().push(effect_id);
2146            entry.get_frozen()
2147        } else {
2148            false
2149        };
2150        if scope_is_frozen {
2151            let eff_slot: SlotId = effect_id.slot();
2152            if let Some(eff) = self.get_mut_effects().get_mut(eff_slot.as_usize())
2153                && eff.get_generation() == eff_slot.get_generation()
2154            {
2155                let next_d: u32 = eff.get_frozen_depth().saturating_add(1);
2156                eff.set_frozen_depth(next_d);
2157            }
2158        }
2159    }
2160
2161    /// Applies a freeze or resume transition to a slice of scope-owned effects without cloning.
2162    ///
2163    /// # Arguments
2164    ///
2165    /// - `&[EffectId]` - Slice of effects owned by a scope.
2166    /// - `bool` - `true` to increment freeze depth; `false` to decrement and schedule pending effects.
2167    /// - `&mut [EffectEntry]` - Mutable effect arena slice.
2168    /// - `&mut Vec<EffectId>` - Pending effect queue receiving any resumed dirty effects.
2169    ///
2170    /// # Returns
2171    ///
2172    /// - `bool` - `true` when at least one resumed effect was newly scheduled.
2173    #[inline]
2174    fn apply_scope_effects_frozen(
2175        effect_ids: &[EffectId],
2176        freeze: bool,
2177        effects: &mut [EffectEntry],
2178        pending_effects: &mut Vec<EffectId>,
2179    ) -> bool {
2180        let mut any_resumed_dirty: bool = false;
2181        for &eff_id in effect_ids {
2182            let eslot: SlotId = eff_id.slot();
2183            if let Some(eff) = effects.get_mut(eslot.as_usize())
2184                && eff.get_generation() == eslot.get_generation()
2185                && eff.get_alive()
2186            {
2187                if freeze {
2188                    let next_d: u32 = eff.get_frozen_depth().saturating_add(1);
2189                    eff.set_frozen_depth(next_d);
2190                } else {
2191                    let next_d: u32 = eff.get_frozen_depth().saturating_sub(1);
2192                    eff.set_frozen_depth(next_d);
2193                    if next_d == 0 && eff.get_pending_while_frozen() {
2194                        eff.set_pending_while_frozen(false);
2195                        if !eff.get_scheduled() {
2196                            eff.set_scheduled(true);
2197                            pending_effects.push(eff_id);
2198                            any_resumed_dirty = true;
2199                        }
2200                    }
2201                }
2202            }
2203        }
2204        any_resumed_dirty
2205    }
2206
2207    /// Recursively freezes or resumes `id` and all nested child scopes, coalescing any pending dirty effects on resume.
2208    ///
2209    /// # Arguments
2210    ///
2211    /// - `&Self` - Mutable reference to the reactive runtime.
2212    /// - `ScopeId` - Root scope identifier to freeze or resume.
2213    /// - `bool` - `true` to freeze; `false` to resume.
2214    ///
2215    /// # Returns
2216    ///
2217    /// - `bool` - `true` when resuming scheduled one or more deferred effects that require flushing.
2218    pub(crate) fn set_scope_frozen(&mut self, id: ScopeId, freeze: bool) -> bool {
2219        let Self {
2220            scopes,
2221            effects,
2222            pending_effects,
2223            scope_stack_scratch,
2224            batch_depth,
2225            flushing,
2226            ..
2227        } = self;
2228        let root_slot: SlotId = id.slot();
2229        let Some(root_entry) = scopes.get_mut(root_slot.as_usize()) else {
2230            return false;
2231        };
2232        let inactive: bool =
2233            root_entry.get_generation() != root_slot.get_generation() || !root_entry.get_alive();
2234        if inactive || root_entry.get_frozen() == freeze {
2235            return false;
2236        }
2237        root_entry.set_frozen(freeze);
2238        let root_children_empty: bool = root_entry.get_children().is_empty();
2239        let root_effects_empty: bool = root_entry.get_effects().is_empty();
2240        if root_children_empty && root_effects_empty {
2241            return false;
2242        }
2243        let mut any_resumed_dirty: bool = if root_effects_empty {
2244            false
2245        } else {
2246            Self::apply_scope_effects_frozen(
2247                root_entry.get_effects(),
2248                freeze,
2249                effects,
2250                pending_effects,
2251            )
2252        };
2253        if root_children_empty {
2254            return any_resumed_dirty && *batch_depth == 0 && !*flushing;
2255        }
2256        scope_stack_scratch.clear();
2257        scope_stack_scratch.extend_from_slice(root_entry.get_children());
2258        while let Some(cur_id) = scope_stack_scratch.pop() {
2259            let slot: SlotId = cur_id.slot();
2260            if let Some(entry) = scopes.get(slot.as_usize())
2261                && entry.get_generation() == slot.get_generation()
2262                && entry.get_alive()
2263            {
2264                if !entry.get_children().is_empty() {
2265                    scope_stack_scratch.extend_from_slice(entry.get_children());
2266                }
2267                if !entry.get_effects().is_empty()
2268                    && Self::apply_scope_effects_frozen(
2269                        entry.get_effects(),
2270                        freeze,
2271                        effects,
2272                        pending_effects,
2273                    )
2274                {
2275                    any_resumed_dirty = true;
2276                }
2277            }
2278        }
2279        any_resumed_dirty && *batch_depth == 0 && !*flushing
2280    }
2281
2282    /// Returns whether scope `id` is currently alive and frozen.
2283    ///
2284    /// # Arguments
2285    ///
2286    /// - `&Self` - Reactive runtime reference.
2287    /// - `ScopeId` - Scope identifier to query.
2288    ///
2289    /// # Returns
2290    ///
2291    /// - `bool` - `true` when the scope is frozen.
2292    #[inline]
2293    pub(crate) fn is_scope_frozen(&self, id: ScopeId) -> bool {
2294        let slot: SlotId = id.slot();
2295        self.get_scopes()
2296            .get(slot.as_usize())
2297            .map(|entry: &ScopeEntry| {
2298                entry.get_generation() == slot.get_generation()
2299                    && entry.get_alive()
2300                    && entry.get_frozen()
2301            })
2302            .unwrap_or(false)
2303    }
2304
2305    /// Returns the currently active reactive `ScopeId` on the top of the scope stack, if any.
2306    ///
2307    /// # Arguments
2308    ///
2309    /// - `&Self` - Reactive runtime reference.
2310    ///
2311    /// # Returns
2312    ///
2313    /// - `Option<ScopeId>` - Active scope identifier or `None` outside `Scope::run`/`Scope::enter`.
2314    #[must_use]
2315    #[inline(always)]
2316    pub(crate) fn current_scope_id(&self) -> Option<ScopeId> {
2317        self.get_scope_stack().last().copied()
2318    }
2319
2320    /// Returns `true` when `candidate` equals `root` or is a live descendant scope of `root`.
2321    ///
2322    /// # Arguments
2323    ///
2324    /// - `&Self` - Reactive runtime reference.
2325    /// - `ScopeId` - Scope identifier to test.
2326    /// - `ScopeId` - Subtree root scope identifier.
2327    ///
2328    /// # Returns
2329    ///
2330    /// - `bool` - Whether `candidate` belongs to `root`'s scope hierarchy.
2331    #[must_use]
2332    pub(crate) fn is_scope_in_subtree(&self, candidate: ScopeId, root: ScopeId) -> bool {
2333        if candidate == root {
2334            return true;
2335        }
2336        let scopes: &[ScopeEntry] = self.get_scopes();
2337        let max_steps: usize = scopes.len();
2338        let mut cur: ScopeId = candidate;
2339        let mut steps: usize = 0;
2340        while steps < max_steps {
2341            let slot: SlotId = cur.slot();
2342            let Some(entry) = scopes.get(slot.as_usize()) else {
2343                return false;
2344            };
2345            let inactive: bool =
2346                entry.get_generation() != slot.get_generation() || !entry.get_alive();
2347            if inactive {
2348                return false;
2349            }
2350            let Some(parent_id) = entry.get_parent() else {
2351                return false;
2352            };
2353            if parent_id == root {
2354                let root_slot: SlotId = root.slot();
2355                return scopes
2356                    .get(root_slot.as_usize())
2357                    .is_some_and(|root_entry: &ScopeEntry| {
2358                        root_entry.get_generation() == root_slot.get_generation()
2359                            && root_entry.get_alive()
2360                    });
2361            }
2362            cur = parent_id;
2363            steps += 1;
2364        }
2365        false
2366    }
2367
2368    /// Returns `true` when `id` itself or any live ancestor scope is currently frozen.
2369    ///
2370    /// # Arguments
2371    ///
2372    /// - `&Self` - Reactive runtime reference.
2373    /// - `ScopeId` - Scope identifier to test.
2374    ///
2375    /// # Returns
2376    ///
2377    /// - `bool` - Whether `id` is suspended by freezing.
2378    #[must_use]
2379    pub(crate) fn is_scope_effectively_frozen(&self, id: ScopeId) -> bool {
2380        let scopes: &[ScopeEntry] = self.get_scopes();
2381        let max_steps: usize = scopes.len();
2382        let mut cur: ScopeId = id;
2383        let mut steps: usize = 0;
2384        while steps < max_steps {
2385            let slot: SlotId = cur.slot();
2386            let Some(entry) = scopes.get(slot.as_usize()) else {
2387                return false;
2388            };
2389            let inactive: bool =
2390                entry.get_generation() != slot.get_generation() || !entry.get_alive();
2391            if inactive {
2392                return false;
2393            }
2394            if entry.get_frozen() {
2395                return true;
2396            }
2397            let Some(parent_id) = entry.get_parent() else {
2398                return false;
2399            };
2400            cur = parent_id;
2401            steps += 1;
2402        }
2403        false
2404    }
2405}