Skip to main content

cranpose_core/
subcompose.rs

1//! State tracking for measure-time subcomposition.
2//!
3//! The [`SubcomposeState`] keeps book of which slots are active, which nodes can
4//! be reused, and which precompositions need to be disposed. Reuse follows a
5//! two-phase lookup: first [`SlotId`]s that match exactly are preferred. If no
6//! exact match exists, the [`SlotReusePolicy`] is consulted to determine whether
7//! a node produced for another slot is compatible with the requested slot.
8
9use std::{any::Any, collections::VecDeque, fmt, rc::Rc};
10
11use smallvec::SmallVec;
12
13use crate::{
14    CallbackHolder, NodeId, RecomposeScope, SlotTable, SlotsHost,
15    collections::map::{HashMap, HashSet},
16};
17
18pub type DebugSlotGroup = (usize, crate::Key, Option<usize>, usize);
19
20/// Identifier for a subcomposed slot.
21///
22/// This mirrors the `slotId` concept in Jetpack Compose where callers provide
23/// stable identifiers for reusable children during measure-time composition.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
25pub struct SlotId(pub u64);
26
27impl SlotId {
28    #[inline]
29    pub fn new(raw: u64) -> Self {
30        Self(raw)
31    }
32
33    #[inline]
34    pub fn raw(self) -> u64 {
35        self.0
36    }
37}
38
39/// Policy that decides which previously composed slots should be retained for
40/// potential reuse during the next subcompose pass.
41///
42/// Note: This trait does NOT require Send + Sync because the compose runtime
43/// is single-threaded (uses Rc/RefCell throughout).
44pub trait SlotReusePolicy: 'static {
45    /// Returns the subset of slots that should be retained for reuse after the
46    /// current measurement pass. Slots that are not part of the returned set
47    /// will be disposed.
48    fn get_slots_to_retain(&self, active: &[SlotId]) -> HashSet<SlotId>;
49
50    /// Determines whether a node that previously rendered the slot `existing`
51    /// can be reused when the caller requests `requested`.
52    ///
53    /// Implementations should document what constitutes compatibility (for
54    /// example, identical slot identifiers, matching layout classes, or node
55    /// types). Returning `true` allows [`SubcomposeState`] to move the node
56    /// across slots instead of disposing it.
57    fn are_compatible(&self, existing: SlotId, requested: SlotId) -> bool;
58
59    /// Registers the content type for a slot.
60    ///
61    /// Policies that support content-type-based reuse (like [`ContentTypeReusePolicy`])
62    /// should override this to record the type. The default implementation is a no-op.
63    ///
64    /// Call this before subcomposing an item to enable content-type-aware slot reuse.
65    fn register_content_type(&self, _slot_id: SlotId, _content_type: u64) {}
66
67    /// Removes the content type for a slot (e.g., when transitioning to None).
68    ///
69    /// Policies that track content types should override this to clean up.
70    /// The default implementation is a no-op.
71    fn remove_content_type(&self, _slot_id: SlotId) {}
72}
73
74/// Default reuse policy that mirrors Jetpack Compose behaviour: dispose
75/// everything from the tail so that the next measurement can decide which
76/// content to keep alive. Compatibility defaults to exact slot matches.
77#[derive(Debug, Default)]
78pub struct DefaultSlotReusePolicy;
79
80impl SlotReusePolicy for DefaultSlotReusePolicy {
81    fn get_slots_to_retain(&self, active: &[SlotId]) -> HashSet<SlotId> {
82        let _ = active;
83        HashSet::default()
84    }
85
86    fn are_compatible(&self, existing: SlotId, requested: SlotId) -> bool {
87        existing == requested
88    }
89}
90
91/// Reuse policy that allows cross-slot reuse when content types match.
92///
93/// This policy enables efficient recycling of layout nodes across different
94/// slot IDs when they share the same content type (e.g., list items with
95/// similar structure but different data).
96///
97/// # Example
98///
99/// ```rust,ignore
100/// use cranpose_core::{ContentTypeReusePolicy, SubcomposeState, SlotId};
101///
102/// let mut policy = ContentTypeReusePolicy::new();
103///
104/// // Register content types for slots
105/// policy.set_content_type(SlotId::new(0), 1); // Header type
106/// policy.set_content_type(SlotId::new(1), 2); // Item type
107/// policy.set_content_type(SlotId::new(2), 2); // Item type (same as slot 1)
108///
109/// // Slot 1 can reuse slot 2's node since they share content type 2
110/// assert!(policy.are_compatible(SlotId::new(2), SlotId::new(1)));
111/// ```
112pub struct ContentTypeReusePolicy {
113    slot_types: std::cell::RefCell<HashMap<SlotId, u64>>,
114}
115
116impl std::fmt::Debug for ContentTypeReusePolicy {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        let types = self.slot_types.borrow();
119        f.debug_struct("ContentTypeReusePolicy")
120            .field("slot_types", &*types)
121            .finish()
122    }
123}
124
125impl Default for ContentTypeReusePolicy {
126    fn default() -> Self {
127        Self::new()
128    }
129}
130
131impl ContentTypeReusePolicy {
132    /// Creates a new content-type-aware reuse policy.
133    pub fn new() -> Self {
134        Self {
135            slot_types: std::cell::RefCell::new(HashMap::default()),
136        }
137    }
138
139    /// Registers the content type for a slot.
140    ///
141    /// Call this when subcomposing an item with a known content type.
142    pub fn set_content_type(&self, slot: SlotId, content_type: u64) {
143        self.slot_types.borrow_mut().insert(slot, content_type);
144    }
145
146    /// Removes the content type for a slot (e.g., when disposed).
147    pub fn remove_content_type(&self, slot: SlotId) {
148        self.slot_types.borrow_mut().remove(&slot);
149    }
150
151    /// Clears all registered content types.
152    pub fn clear(&self) {
153        self.slot_types.borrow_mut().clear();
154    }
155
156    /// Returns the content type for a slot, if registered.
157    pub fn get_content_type(&self, slot: SlotId) -> Option<u64> {
158        self.slot_types.borrow().get(&slot).copied()
159    }
160}
161
162impl SlotReusePolicy for ContentTypeReusePolicy {
163    fn get_slots_to_retain(&self, active: &[SlotId]) -> HashSet<SlotId> {
164        let _ = active;
165        HashSet::default()
166    }
167
168    fn are_compatible(&self, existing: SlotId, requested: SlotId) -> bool {
169        if existing == requested {
170            return true;
171        }
172
173        let types = self.slot_types.borrow();
174        match (types.get(&existing), types.get(&requested)) {
175            (Some(existing_type), Some(requested_type)) => existing_type == requested_type,
176            (None, None) => true,
177            _ => false,
178        }
179    }
180
181    fn register_content_type(&self, slot_id: SlotId, content_type: u64) {
182        self.set_content_type(slot_id, content_type);
183    }
184
185    fn remove_content_type(&self, slot_id: SlotId) {
186        ContentTypeReusePolicy::remove_content_type(self, slot_id);
187    }
188}
189
190#[doc(hidden)]
191pub struct ExactSlotActivation {
192    pub nodes: Vec<NodeId>,
193    pub scopes: Vec<RecomposeScope>,
194    pub reactivate_scopes: bool,
195}
196
197#[derive(Default, Clone)]
198
199struct NodeSlotMapping {
200    slot_to_nodes: HashMap<SlotId, Vec<NodeId>>,
201    node_to_slot: HashMap<NodeId, SlotId>,
202    slot_to_scopes: HashMap<SlotId, Vec<RecomposeScope>>,
203}
204
205impl fmt::Debug for NodeSlotMapping {
206    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
207        f.debug_struct("NodeSlotMapping")
208            .field("slot_to_nodes", &self.slot_to_nodes)
209            .field("node_to_slot", &self.node_to_slot)
210            .finish()
211    }
212}
213
214impl NodeSlotMapping {
215    fn set_nodes(&mut self, slot: SlotId, nodes: &[NodeId]) {
216        self.slot_to_nodes.insert(slot, nodes.to_vec());
217        for node in nodes {
218            self.node_to_slot.insert(*node, slot);
219        }
220    }
221
222    fn set_scopes(&mut self, slot: SlotId, scopes: &[RecomposeScope]) {
223        self.slot_to_scopes.insert(slot, scopes.to_vec());
224    }
225
226    fn add_node(&mut self, slot: SlotId, node: NodeId) {
227        self.slot_to_nodes.entry(slot).or_default().push(node);
228        self.node_to_slot.insert(node, slot);
229    }
230
231    fn remove_by_node(&mut self, node: &NodeId) -> Option<SlotId> {
232        if let Some(slot) = self.node_to_slot.remove(node) {
233            if let Some(nodes) = self.slot_to_nodes.get_mut(&slot) {
234                if let Some(index) = nodes.iter().position(|candidate| candidate == node) {
235                    nodes.remove(index);
236                }
237                if nodes.is_empty() {
238                    self.slot_to_nodes.remove(&slot);
239                    self.slot_to_scopes.remove(&slot);
240                }
241            }
242            Some(slot)
243        } else {
244            None
245        }
246    }
247
248    fn get_nodes(&self, slot: &SlotId) -> Option<&[NodeId]> {
249        self.slot_to_nodes.get(slot).map(|nodes| nodes.as_slice())
250    }
251
252    fn get_scopes(&self, slot: &SlotId) -> Option<&[RecomposeScope]> {
253        self.slot_to_scopes
254            .get(slot)
255            .map(|scopes| scopes.as_slice())
256    }
257
258    fn slot_has_invalid_scopes(&self, slot: SlotId) -> bool {
259        self.slot_to_scopes
260            .get(&slot)
261            .is_some_and(|scopes| scopes.iter().any(RecomposeScope::is_invalid))
262    }
263
264    fn slot_has_inactive_scopes(&self, slot: SlotId) -> bool {
265        self.slot_to_scopes
266            .get(&slot)
267            .is_some_and(|scopes| scopes.iter().any(|scope| !scope.is_active()))
268    }
269
270    fn deactivate_slot(&self, slot: SlotId) {
271        if let Some(scopes) = self.slot_to_scopes.get(&slot) {
272            for scope in scopes {
273                scope.deactivate();
274            }
275        }
276    }
277
278    fn invalidate_scopes(&self) {
279        for scopes in self.slot_to_scopes.values() {
280            for scope in scopes {
281                scope.invalidate();
282            }
283        }
284    }
285}
286
287/// Tracks the state of nodes produced by subcomposition, enabling reuse between
288/// measurement passes.
289pub struct SubcomposeState {
290    mapping: NodeSlotMapping,
291    active_order: Vec<SlotId>,
292    live_slots: HashSet<SlotId>,
293    current_pass_active_slots: HashSet<SlotId>,
294    reusable_by_type: HashMap<u64, VecDeque<(SlotId, NodeId)>>,
295    reusable_nodes_untyped: VecDeque<(SlotId, NodeId)>,
296    reusable_node_counts: HashMap<SlotId, usize>,
297    exact_reactivation_slots: HashSet<SlotId>,
298    slot_content_types: HashMap<SlotId, u64>,
299    precomposed_nodes: HashMap<SlotId, Vec<NodeId>>,
300    policy: Box<dyn SlotReusePolicy>,
301    pub(crate) current_index: usize,
302    pub(crate) reusable_count: usize,
303    pub(crate) precomposed_count: usize,
304    slot_compositions: HashMap<SlotId, Rc<SlotsHost>>,
305    slot_callbacks: HashMap<SlotId, CallbackHolder>,
306    max_reusable_per_type: usize,
307    max_reusable_untyped: usize,
308    last_slot_reused: Option<bool>,
309    retained_capture_keys: HashMap<SlotId, RetainedCaptureKey>,
310    content_generation: std::cell::Cell<u64>,
311    slot_composed_generation: HashMap<SlotId, (u64, u64)>,
312}
313
314struct RetainedCaptureKey {
315    value: Box<dyn Any>,
316    eq: fn(&dyn Any, &dyn Any) -> bool,
317}
318
319fn retained_capture_key_eq<K: PartialEq + 'static>(stored: &dyn Any, candidate: &dyn Any) -> bool {
320    match (stored.downcast_ref::<K>(), candidate.downcast_ref::<K>()) {
321        (Some(stored), Some(candidate)) => stored == candidate,
322        _ => false,
323    }
324}
325
326impl fmt::Debug for SubcomposeState {
327    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328        f.debug_struct("SubcomposeState")
329            .field("mapping", &self.mapping)
330            .field("active_order", &self.active_order)
331            .field("reusable_by_type_count", &self.reusable_by_type.len())
332            .field("reusable_untyped_count", &self.reusable_nodes_untyped.len())
333            .field("precomposed_nodes", &self.precomposed_nodes)
334            .field("current_index", &self.current_index)
335            .field("reusable_count", &self.reusable_count)
336            .field("precomposed_count", &self.precomposed_count)
337            .field("slot_compositions_count", &self.slot_compositions.len())
338            .finish()
339    }
340}
341
342impl Default for SubcomposeState {
343    fn default() -> Self {
344        Self::new(Box::new(DefaultSlotReusePolicy))
345    }
346}
347
348const DEFAULT_MAX_REUSABLE_PER_TYPE: usize = 5;
349
350const DEFAULT_MAX_REUSABLE_UNTYPED: usize = 10;
351
352impl SubcomposeState {
353    /// Creates a new [`SubcomposeState`] using the supplied reuse policy.
354    pub fn new(policy: Box<dyn SlotReusePolicy>) -> Self {
355        Self {
356            mapping: NodeSlotMapping::default(),
357            active_order: Vec::new(),
358            live_slots: HashSet::default(),
359            current_pass_active_slots: HashSet::default(),
360            reusable_by_type: HashMap::default(),
361            reusable_nodes_untyped: VecDeque::new(),
362            reusable_node_counts: HashMap::default(),
363            exact_reactivation_slots: HashSet::default(),
364            slot_content_types: HashMap::default(),
365            precomposed_nodes: HashMap::default(),
366            policy,
367            current_index: 0,
368            reusable_count: 0,
369            precomposed_count: 0,
370            slot_compositions: HashMap::default(),
371            slot_callbacks: HashMap::default(),
372            max_reusable_per_type: DEFAULT_MAX_REUSABLE_PER_TYPE,
373            max_reusable_untyped: DEFAULT_MAX_REUSABLE_UNTYPED,
374            last_slot_reused: None,
375            retained_capture_keys: HashMap::default(),
376            content_generation: std::cell::Cell::new(0),
377            slot_composed_generation: HashMap::default(),
378        }
379    }
380
381    /// Sets the policy used for future reuse decisions.
382    pub fn set_policy(&mut self, policy: Box<dyn SlotReusePolicy>) {
383        self.policy = policy;
384    }
385
386    pub fn set_reusable_pool_limits(&mut self, per_type: usize, untyped: usize) {
387        self.max_reusable_per_type = per_type;
388        self.max_reusable_untyped = untyped;
389    }
390
391    /// Registers a content type for a slot.
392    ///
393    /// Stores the content type locally for efficient pool-based reuse lookup,
394    /// and also delegates to the policy for compatibility checking.
395    ///
396    /// Call this before subcomposing an item to enable content-type-aware slot reuse.
397    pub fn register_content_type(&mut self, slot_id: SlotId, content_type: u64) {
398        self.slot_content_types.insert(slot_id, content_type);
399        self.policy.register_content_type(slot_id, content_type);
400    }
401
402    /// Updates the content type for a slot, handling optional content types.
403    ///
404    /// If `content_type` is `Some(type)`, registers the type for the slot.
405    /// If `content_type` is `None`, removes any previously registered type.
406    /// This ensures stale types don't drive incorrect reuse.
407    pub fn update_content_type(&mut self, slot_id: SlotId, content_type: Option<u64>) {
408        match content_type {
409            Some(ct) => self.register_content_type(slot_id, ct),
410            None => {
411                self.slot_content_types.remove(&slot_id);
412                self.policy.remove_content_type(slot_id);
413            }
414        }
415    }
416
417    /// Returns the content type for a slot, if registered.
418    pub fn get_content_type(&self, slot_id: SlotId) -> Option<u64> {
419        self.slot_content_types.get(&slot_id).copied()
420    }
421
422    /// Starts a new subcompose pass.
423    ///
424    /// Call this before subcomposing the current frame so the state can
425    /// track which slots are active and dispose the inactive ones later.
426    pub fn begin_pass(&mut self) {
427        self.current_index = 0;
428        self.current_pass_active_slots.clear();
429    }
430
431    /// Returns the current active slot cursor for the in-progress pass.
432    pub fn active_slot_cursor(&self) -> usize {
433        self.current_index
434    }
435
436    /// Restores the active slot cursor for work that should not become part of
437    /// the rendered active set, such as lazy-list prefetch measurement.
438    pub fn restore_active_slot_cursor(&mut self, cursor: usize) {
439        self.current_index = cursor.min(self.active_order.len());
440    }
441
442    /// Moves an active slot out of the rendered set and into the reusable pool.
443    pub fn recycle_active_slot(&mut self, slot_id: SlotId) -> Vec<NodeId> {
444        self.recycle_active_slot_internal(slot_id, false)
445    }
446
447    pub fn recycle_prefetched_active_slot(&mut self, slot_id: SlotId) -> Vec<NodeId> {
448        self.recycle_active_slot_internal(slot_id, true)
449    }
450
451    pub fn recycle_active_slots_where(
452        &mut self,
453        mut predicate: impl FnMut(SlotId) -> bool,
454    ) -> Vec<NodeId> {
455        let slots: Vec<_> = self
456            .active_order
457            .iter()
458            .copied()
459            .filter(|slot| !self.current_pass_active_slots.contains(slot))
460            .filter(|slot| predicate(*slot))
461            .collect();
462        let mut disposed = Vec::new();
463        for slot in slots {
464            disposed.extend(self.recycle_active_slot(slot));
465        }
466        disposed
467    }
468
469    fn recycle_active_slot_internal(
470        &mut self,
471        slot_id: SlotId,
472        allow_exact_reactivation: bool,
473    ) -> Vec<NodeId> {
474        let Some(position) = self
475            .active_order
476            .iter()
477            .position(|candidate| *candidate == slot_id)
478        else {
479            return Vec::new();
480        };
481        self.active_order.remove(position);
482        if position < self.current_index {
483            self.current_index = self.current_index.saturating_sub(1);
484        }
485        self.move_slot_to_reusable(slot_id, allow_exact_reactivation);
486        self.enforce_reusable_pool_limits()
487    }
488
489    /// Finishes a subcompose pass, disposing slots that were not used.
490    pub fn finish_pass(&mut self) -> Vec<NodeId> {
491        self.dispose_or_reuse_starting_from_index(self.current_index)
492    }
493
494    /// Returns the SlotsHost for the given slot ID, creating a new one if it doesn't exist.
495    /// Each slot gets its own isolated slot table, avoiding cursor-based conflicts when
496    /// items are subcomposed in different orders.
497    pub fn get_or_create_slots(&mut self, slot_id: SlotId) -> Rc<SlotsHost> {
498        Rc::clone(
499            self.slot_compositions
500                .entry(slot_id)
501                .or_insert_with(|| Rc::new(SlotsHost::new(SlotTable::new()))),
502        )
503    }
504
505    /// Returns the latest callback holder for the given slot, creating one if needed.
506    pub fn callback_holder(&mut self, slot_id: SlotId) -> CallbackHolder {
507        self.slot_callbacks.entry(slot_id).or_default().clone()
508    }
509
510    #[doc(hidden)]
511    pub fn activate_current_active_slot(&mut self, slot_id: SlotId) -> Option<Vec<NodeId>> {
512        if self.current_pass_active_slots.contains(&slot_id)
513            || self.exact_reactivation_slots.contains(&slot_id)
514            || self.reusable_node_counts.contains_key(&slot_id)
515            || self
516                .active_order
517                .get(self.current_index)
518                .copied()
519                .is_none_or(|active_slot| active_slot != slot_id)
520            || self.mapping.slot_has_invalid_scopes(slot_id)
521            || self.mapping.slot_has_inactive_scopes(slot_id)
522        {
523            return None;
524        }
525
526        let nodes = self.mapping.get_nodes(&slot_id)?.to_vec();
527        self.last_slot_reused = Some(true);
528        self.live_slots.insert(slot_id);
529        self.current_pass_active_slots.insert(slot_id);
530        self.current_index += 1;
531        Some(nodes)
532    }
533
534    /// Whether precomposed nodes are waiting to be consumed for this slot.
535    /// A pending precomposition means the retained mapping is about to be
536    /// superseded, so clean-slot reuse must reject and compose.
537    pub fn has_pending_precompositions(&self, slot_id: SlotId) -> bool {
538        self.precomposed_nodes.contains_key(&slot_id)
539    }
540
541    /// Whether the slot's stored capture key equals `key`. A missing key never
542    /// matches: a slot must compose at least once under the key discipline
543    /// before it may skip.
544    pub fn retained_capture_key_matches<K: PartialEq + 'static>(
545        &self,
546        slot_id: SlotId,
547        key: &K,
548    ) -> bool {
549        self.retained_capture_keys
550            .get(&slot_id)
551            .is_some_and(|retained| (retained.eq)(retained.value.as_ref(), key))
552    }
553
554    /// Records the capture key the slot is being composed under.
555    pub fn store_retained_capture_key<K: PartialEq + 'static>(&mut self, slot_id: SlotId, key: K) {
556        self.retained_capture_keys.insert(
557            slot_id,
558            RetainedCaptureKey {
559                value: Box::new(key),
560                eq: retained_capture_key_eq::<K>,
561            },
562        );
563    }
564
565    #[doc(hidden)]
566    pub fn take_exact_slot_activation(&mut self, slot_id: SlotId) -> Option<ExactSlotActivation> {
567        let active_position = self
568            .active_order
569            .iter()
570            .position(|candidate| *candidate == slot_id);
571        let is_exact_reactivation = self.exact_reactivation_slots.contains(&slot_id);
572        if active_position.is_none() && !is_exact_reactivation
573            || self.mapping.slot_has_invalid_scopes(slot_id)
574        {
575            return None;
576        }
577
578        let nodes = self.mapping.get_nodes(&slot_id)?.to_vec();
579        let scopes = self
580            .mapping
581            .get_scopes(&slot_id)
582            .unwrap_or_default()
583            .to_vec();
584        if active_position.is_none() {
585            for node in &nodes {
586                let _ = self.remove_from_reusable_pools(*node);
587            }
588        }
589        self.exact_reactivation_slots.remove(&slot_id);
590        Some(ExactSlotActivation {
591            nodes,
592            scopes,
593            reactivate_scopes: active_position.is_none(),
594        })
595    }
596
597    #[doc(hidden)]
598    pub fn take_exact_slot_for_activation(
599        &mut self,
600        slot_id: SlotId,
601    ) -> Option<(Vec<NodeId>, Vec<RecomposeScope>)> {
602        self.take_exact_slot_activation(slot_id)
603            .map(|activation| (activation.nodes, activation.scopes))
604    }
605
606    /// Records that the nodes in `node_ids` are currently rendering the provided
607    /// `slot_id`.
608    pub fn register_active(
609        &mut self,
610        slot_id: SlotId,
611        node_ids: &[NodeId],
612        scopes: &[RecomposeScope],
613    ) {
614        self.register_active_with_scope_reactivation(slot_id, node_ids, scopes, true);
615    }
616
617    #[doc(hidden)]
618    pub fn register_active_with_scope_reactivation(
619        &mut self,
620        slot_id: SlotId,
621        node_ids: &[NodeId],
622        scopes: &[RecomposeScope],
623        reactivate_scopes: bool,
624    ) {
625        let was_reused = self.mapping.get_nodes(&slot_id).is_some();
626        self.last_slot_reused = Some(was_reused);
627        self.live_slots.insert(slot_id);
628        self.current_pass_active_slots.insert(slot_id);
629        self.exact_reactivation_slots.remove(&slot_id);
630
631        if let Some(position) = self.active_order.iter().position(|slot| *slot == slot_id) {
632            if position < self.current_index {
633                if reactivate_scopes {
634                    for scope in scopes {
635                        scope.reactivate();
636                    }
637                }
638                self.update_active_slot_mapping(slot_id, node_ids, scopes);
639                return;
640            }
641            self.active_order.remove(position);
642        }
643        if reactivate_scopes {
644            for scope in scopes {
645                scope.reactivate();
646            }
647        }
648        self.update_active_slot_mapping(slot_id, node_ids, scopes);
649        let insert_at = self.current_index.min(self.active_order.len());
650        self.active_order.insert(insert_at, slot_id);
651        self.current_index += 1;
652    }
653
654    fn update_active_slot_mapping(
655        &mut self,
656        slot_id: SlotId,
657        node_ids: &[NodeId],
658        scopes: &[RecomposeScope],
659    ) {
660        self.mapping.set_nodes(slot_id, node_ids);
661        self.mapping.set_scopes(slot_id, scopes);
662        if let Some(nodes) = self.precomposed_nodes.get_mut(&slot_id) {
663            let before_len = nodes.len();
664            nodes.retain(|node| !node_ids.contains(node));
665            let removed = before_len - nodes.len();
666            self.precomposed_count = self.precomposed_count.saturating_sub(removed);
667            if nodes.is_empty() {
668                self.precomposed_nodes.remove(&slot_id);
669            }
670        }
671    }
672
673    /// Stores a precomposed node for the provided slot. Precomposed nodes stay
674    /// detached from the tree until they are activated by `register_active`.
675    pub fn register_precomposed(&mut self, slot_id: SlotId, node_id: NodeId) {
676        self.precomposed_nodes
677            .entry(slot_id)
678            .or_default()
679            .push(node_id);
680        self.precomposed_count += 1;
681    }
682
683    fn increment_reusable_slot(&mut self, slot_id: SlotId) {
684        *self.reusable_node_counts.entry(slot_id).or_insert(0) += 1;
685        self.reusable_count += 1;
686    }
687
688    fn decrement_reusable_slot(&mut self, slot_id: SlotId) {
689        let Some(entry) = self.reusable_node_counts.get_mut(&slot_id) else {
690            self.reusable_count = self.reusable_count.saturating_sub(1);
691            return;
692        };
693        *entry = entry.saturating_sub(1);
694        if *entry == 0 {
695            self.reusable_node_counts.remove(&slot_id);
696        }
697        self.reusable_count = self.reusable_count.saturating_sub(1);
698    }
699
700    fn prune_slot_if_unused(&mut self, slot_id: SlotId) {
701        if self.live_slots.contains(&slot_id) || self.reusable_node_counts.contains_key(&slot_id) {
702            return;
703        }
704
705        debug_assert!(
706            self.mapping.get_nodes(&slot_id).is_none(),
707            "inactive slot {slot_id:?} still has mapped nodes",
708        );
709
710        self.slot_compositions.remove(&slot_id);
711        self.slot_callbacks.remove(&slot_id);
712        self.slot_content_types.remove(&slot_id);
713        self.retained_capture_keys.remove(&slot_id);
714        self.slot_composed_generation.remove(&slot_id);
715        self.policy.remove_content_type(slot_id);
716        if let Some(nodes) = self.precomposed_nodes.remove(&slot_id) {
717            self.precomposed_count = self.precomposed_count.saturating_sub(nodes.len());
718        }
719    }
720
721    /// Returns the node that previously rendered this slot, if it is still
722    /// considered reusable, and whether it was REBOUND — taken from another
723    /// slot, so its retained subtree is about to show different content. An
724    /// exact-slot reactivation hands the same item its own subtree back and
725    /// is not a rebinding.
726    ///
727    /// Lookup order:
728    /// 1. Exact slot match in the appropriate pool (not a rebinding)
729    /// 2. Any policy-compatible node from the same content-type pool
730    /// 3. Fallback to untyped pool with policy compatibility check
731    pub fn take_node_from_reusables(&mut self, slot_id: SlotId) -> Option<(NodeId, bool)> {
732        if let Some(nodes) = self.mapping.get_nodes(&slot_id) {
733            let first_node = nodes.first().copied();
734            if let Some(node_id) = first_node {
735                let _ = self.remove_from_reusable_pools(node_id);
736                self.exact_reactivation_slots.remove(&slot_id);
737                return Some((node_id, false));
738            }
739        }
740
741        let content_type = self.slot_content_types.get(&slot_id).copied();
742
743        if let Some(ct) = content_type
744            && let Some((old_slot, node_id)) = self.take_compatible_typed_reusable(ct, slot_id)
745        {
746            self.decrement_reusable_slot(old_slot);
747            self.move_node_to_slot(node_id, old_slot, slot_id);
748            return Some((node_id, true));
749        }
750
751        let exact_reactivation_slots = &self.exact_reactivation_slots;
752        let policy = &self.policy;
753        let position = self
754            .reusable_nodes_untyped
755            .iter()
756            .position(|(existing_slot, _)| {
757                !exact_reactivation_slots.contains(existing_slot)
758                    && policy.are_compatible(*existing_slot, slot_id)
759            });
760
761        if let Some(index) = position
762            && let Some((old_slot, node_id)) = self.reusable_nodes_untyped.remove(index)
763        {
764            self.decrement_reusable_slot(old_slot);
765            self.move_node_to_slot(node_id, old_slot, slot_id);
766            return Some((node_id, true));
767        }
768
769        None
770    }
771
772    fn take_compatible_typed_reusable(
773        &mut self,
774        content_type: u64,
775        requested_slot: SlotId,
776    ) -> Option<(SlotId, NodeId)> {
777        let reused = {
778            let policy = &self.policy;
779            let exact_reactivation_slots = &self.exact_reactivation_slots;
780            let pool = self.reusable_by_type.get_mut(&content_type)?;
781            let index = pool.iter().position(|(existing_slot, _)| {
782                !exact_reactivation_slots.contains(existing_slot)
783                    && policy.are_compatible(*existing_slot, requested_slot)
784            })?;
785            pool.remove(index)
786        };
787
788        if self
789            .reusable_by_type
790            .get(&content_type)
791            .map(|pool| pool.is_empty())
792            .unwrap_or(false)
793        {
794            self.reusable_by_type.remove(&content_type);
795        }
796
797        reused
798    }
799
800    fn remove_from_reusable_pools(&mut self, node_id: NodeId) -> Option<SlotId> {
801        let mut typed_match = None;
802        for (&content_type, pool) in &self.reusable_by_type {
803            if let Some(position) = pool
804                .iter()
805                .position(|(_, pooled_node)| *pooled_node == node_id)
806            {
807                typed_match = Some((content_type, position));
808                break;
809            }
810        }
811        if let Some((content_type, position)) = typed_match {
812            let pool = self.reusable_by_type.get_mut(&content_type)?;
813            let (slot, _) = pool.remove(position)?;
814            if pool.is_empty() {
815                self.reusable_by_type.remove(&content_type);
816            }
817            self.decrement_reusable_slot(slot);
818            return Some(slot);
819        }
820        if let Some(position) = self
821            .reusable_nodes_untyped
822            .iter()
823            .position(|(_, n)| *n == node_id)
824            && let Some((slot, _)) = self.reusable_nodes_untyped.remove(position)
825        {
826            self.decrement_reusable_slot(slot);
827            return Some(slot);
828        }
829        None
830    }
831
832    fn move_node_to_slot(&mut self, node_id: NodeId, old_slot: SlotId, new_slot: SlotId) {
833        if old_slot == new_slot {
834            return;
835        }
836
837        self.mapping.remove_by_node(&node_id);
838        self.exact_reactivation_slots.remove(&old_slot);
839        self.mapping.add_node(new_slot, node_id);
840        self.slot_content_types.remove(&old_slot);
841        self.retained_capture_keys.remove(&old_slot);
842        self.retained_capture_keys.remove(&new_slot);
843        self.slot_composed_generation.remove(&old_slot);
844        self.slot_composed_generation.remove(&new_slot);
845        self.policy.remove_content_type(old_slot);
846        if let Some(slots) = self.slot_compositions.remove(&old_slot) {
847            self.slot_compositions.insert(new_slot, slots);
848        }
849        if let Some(callback) = self.slot_callbacks.remove(&old_slot) {
850            self.slot_callbacks.insert(new_slot, callback);
851        }
852        if let Some(nodes) = self.precomposed_nodes.get_mut(&old_slot) {
853            let before_len = nodes.len();
854            nodes.retain(|candidate| *candidate != node_id);
855            let removed = before_len - nodes.len();
856            self.precomposed_count = self.precomposed_count.saturating_sub(removed);
857            if nodes.is_empty() {
858                self.precomposed_nodes.remove(&old_slot);
859            }
860        }
861    }
862
863    /// Moves active slots starting from `start_index` to the reusable bucket.
864    /// Returns the list of node ids that were DISPOSED (not just moved to reusable).
865    /// Nodes that exceed max_reusable_per_type are disposed instead of cached.
866    pub fn dispose_or_reuse_starting_from_index(&mut self, start_index: usize) -> Vec<NodeId> {
867        if start_index >= self.active_order.len() {
868            return Vec::new();
869        }
870
871        let retain = self
872            .policy
873            .get_slots_to_retain(&self.active_order[start_index..]);
874        let mut retained = Vec::new();
875        while self.active_order.len() > start_index {
876            let Some(slot) = self.active_order.pop() else {
877                break;
878            };
879            if retain.contains(&slot) {
880                retained.push(slot);
881                continue;
882            }
883            self.move_slot_to_reusable(slot, false);
884        }
885        retained.reverse();
886        self.active_order.extend(retained);
887
888        self.enforce_reusable_pool_limits()
889    }
890
891    fn move_slot_to_reusable(&mut self, slot: SlotId, allow_exact_reactivation: bool) {
892        self.live_slots.remove(&slot);
893        self.current_pass_active_slots.remove(&slot);
894        self.mapping.deactivate_slot(slot);
895        let forgot_effects = self
896            .slot_compositions
897            .get(&slot)
898            .is_some_and(|host| host.forget_effects());
899        if allow_exact_reactivation && !forgot_effects {
900            self.exact_reactivation_slots.insert(slot);
901        } else {
902            self.exact_reactivation_slots.remove(&slot);
903        }
904
905        let content_type = self.slot_content_types.get(&slot).copied();
906        let nodes: SmallVec<[NodeId; 4]> = self
907            .mapping
908            .get_nodes(&slot)
909            .into_iter()
910            .flatten()
911            .copied()
912            .collect();
913        for node in nodes {
914            if let Some(ct) = content_type {
915                self.reusable_by_type
916                    .entry(ct)
917                    .or_default()
918                    .push_back((slot, node));
919            } else {
920                self.reusable_nodes_untyped.push_back((slot, node));
921            }
922            self.increment_reusable_slot(slot);
923        }
924    }
925
926    fn enforce_reusable_pool_limits(&mut self) -> Vec<NodeId> {
927        let mut disposed = Vec::new();
928        let mut typed_disposals = Vec::new();
929        for pool in self.reusable_by_type.values_mut() {
930            while pool.len() > self.max_reusable_per_type {
931                if let Some((slot, node_id)) = pool.pop_front() {
932                    typed_disposals.push((slot, node_id));
933                }
934            }
935        }
936        for (slot, node_id) in typed_disposals {
937            self.decrement_reusable_slot(slot);
938            self.mapping.remove_by_node(&node_id);
939            self.exact_reactivation_slots.remove(&slot);
940            disposed.push(node_id);
941        }
942
943        while self.reusable_nodes_untyped.len() > self.max_reusable_untyped {
944            if let Some((slot, node_id)) = self.reusable_nodes_untyped.pop_front() {
945                self.decrement_reusable_slot(slot);
946                self.mapping.remove_by_node(&node_id);
947                self.exact_reactivation_slots.remove(&slot);
948                disposed.push(node_id);
949            }
950        }
951
952        self.reusable_by_type.retain(|_, pool| !pool.is_empty());
953        disposed
954    }
955
956    /// Returns a snapshot of currently reusable nodes.
957    pub fn reusable(&self) -> Vec<NodeId> {
958        let mut nodes: Vec<NodeId> = self
959            .reusable_by_type
960            .values()
961            .flat_map(|pool| pool.iter().map(|(_, n)| *n))
962            .collect();
963        nodes.extend(self.reusable_nodes_untyped.iter().map(|(_, n)| *n));
964        nodes
965    }
966
967    /// Returns the number of slots currently active (in use during this pass).
968    ///
969    /// This reflects the slots that were activated via `register_active()` during
970    /// the current measurement pass.
971    pub fn active_slots_count(&self) -> usize {
972        self.active_order.len()
973    }
974
975    /// Returns the number of reusable slots in the pool.
976    ///
977    /// These are slots that were previously active but are now available for reuse
978    /// by compatible content types.
979    pub fn reusable_slots_count(&self) -> usize {
980        self.reusable_count
981    }
982
983    /// Invalidates all tracked subcomposition scopes.
984    ///
985    /// Hosts should call this when parent-captured inputs change without directly invalidating
986    /// the child scopes themselves. The next subcompose pass will then re-run active slot
987    /// content instead of skipping with stale captures.
988    /// Invalidating scopes alone is not a reliable "recompose on next
989    /// measure" signal: the recomposer drains invalid scopes before measure
990    /// runs, re-executing the RETAINED slot callbacks — parent-captured
991    /// values baked into a replaced closure never flow in, yet the scopes
992    /// come back valid. The generation bump is the unlaunderable half: only
993    /// a measure-time compose of the slot brings it current, so clean-slot
994    /// reuse stays blocked until the new content actually landed.
995    pub fn invalidate_scopes(&self) {
996        self.mapping.invalidate_scopes();
997        self.content_generation
998            .set(self.content_generation.get() + 1);
999    }
1000
1001    /// Advances the content generation without invalidating scopes: every
1002    /// slot must re-compose once before clean-slot reuse may skip it again.
1003    /// Called when the owning node leaves its parent — a retained subtree
1004    /// that comes back from the reuse pool restarts its effects only if its
1005    /// slots actually recompose, and scope flags carry no durable trace of
1006    /// the detach (deactivation walks stop at nested slot-host boundaries).
1007    pub fn bump_content_generation(&self) {
1008        self.content_generation
1009            .set(self.content_generation.get() + 1);
1010    }
1011
1012    /// Whether the slot last composed under the current content generation
1013    /// and owner-chain deactivation epoch. False after any
1014    /// [`Self::invalidate_scopes`], and false after any composition up the
1015    /// owner chain was deactivated, until a measure-time compose of this
1016    /// slot runs.
1017    pub fn slot_content_generation_current(&self, slot_id: SlotId, owner_epoch: u64) -> bool {
1018        self.slot_composed_generation.get(&slot_id).copied()
1019            == Some((self.content_generation.get(), owner_epoch))
1020    }
1021
1022    /// Records that the slot just composed under the current generation and
1023    /// the given owner-chain deactivation epoch.
1024    pub fn mark_slot_composed_current(&mut self, slot_id: SlotId, owner_epoch: u64) {
1025        self.slot_composed_generation
1026            .insert(slot_id, (self.content_generation.get(), owner_epoch));
1027    }
1028
1029    /// Returns whether the last slot registered via [`Self::register_active`] was reused.
1030    ///
1031    /// Returns `Some(true)` if the slot already existed (was reused from pool or
1032    /// was recomposed), `Some(false)` if it was newly created, or `None` if no
1033    /// slot has been registered yet this pass.
1034    ///
1035    /// This is useful for tracking composition statistics in lazy layouts.
1036    pub fn was_last_slot_reused(&self) -> Option<bool> {
1037        self.last_slot_reused
1038    }
1039
1040    #[doc(hidden)]
1041    pub fn debug_scope_ids_by_slot(&self) -> Vec<(u64, Vec<usize>)> {
1042        self.mapping
1043            .slot_to_scopes
1044            .iter()
1045            .map(|(slot, scopes)| (slot.raw(), scopes.iter().map(RecomposeScope::id).collect()))
1046            .collect()
1047    }
1048
1049    #[doc(hidden)]
1050    pub fn debug_slot_table_for_slot(&self, slot_id: SlotId) -> Option<Vec<crate::SlotDebugEntry>> {
1051        let slots = self.slot_compositions.get(&slot_id)?;
1052        Some(slots.borrow().debug_dump_slot_entries())
1053    }
1054
1055    #[doc(hidden)]
1056    pub fn debug_slot_table_groups_for_slot(&self, slot_id: SlotId) -> Option<Vec<DebugSlotGroup>> {
1057        let slots = self.slot_compositions.get(&slot_id)?;
1058        Some(slots.borrow().debug_dump_groups())
1059    }
1060
1061    /// Returns a snapshot of precomposed nodes.
1062    pub fn precomposed(&self) -> &HashMap<SlotId, Vec<NodeId>> {
1063        &self.precomposed_nodes
1064    }
1065
1066    /// Removes any precomposed nodes whose slots were not activated during the
1067    /// current pass and returns their identifiers for disposal.
1068    pub fn drain_inactive_precomposed(&mut self) -> Vec<NodeId> {
1069        let mut disposed = Vec::new();
1070        let mut empty_slots = Vec::new();
1071        for (slot, nodes) in self.precomposed_nodes.iter_mut() {
1072            if !self.current_pass_active_slots.contains(slot) {
1073                disposed.extend(nodes.iter().copied());
1074                empty_slots.push(*slot);
1075            }
1076        }
1077        for slot in empty_slots {
1078            self.precomposed_nodes.remove(&slot);
1079            self.prune_slot_if_unused(slot);
1080        }
1081        self.precomposed_count = self.precomposed_count.saturating_sub(disposed.len());
1082        disposed
1083    }
1084}
1085
1086#[cfg(test)]
1087#[path = "tests/subcompose_tests.rs"]
1088mod tests;