Skip to main content

cranpose_core/memory_applier/
applier_impl.rs

1use std::{any::TypeId, cmp::Reverse, collections::BinaryHeap};
2
3use super::MemoryApplier;
4use crate::{Applier, Node, NodeError, NodeId, RecycleOrigin, RecycledNode, RecycledNodeInsertion};
5
6impl Applier for MemoryApplier {
7    fn record_structural_change(&mut self, parent_id: NodeId) {
8        if self.state.structural_change_parents.last() != Some(&parent_id) {
9            self.state.structural_change_parents.push(parent_id);
10        }
11    }
12
13    fn create(&mut self, node: Box<dyn Node>) -> NodeId {
14        let stable_id = self.state.next_stable_id;
15        self.state.next_stable_id = self.state.next_stable_id.next();
16        if stable_id >= Self::HIGH_ID_THRESHOLD {
17            self.insert_high_id_node(stable_id, node, RecycleOrigin::Cold);
18            return stable_id;
19        }
20
21        let is_virtual = node.is_virtual();
22        let physical_id = if let Some(Reverse(id)) = self.state.free_ids.pop() {
23            debug_assert!(
24                self.state.nodes[id].is_none(),
25                "freelist entry {id} is not None"
26            );
27            self.state.nodes[id] = Some(node);
28            self.state.physical_stable_ids[id] = Self::pack_stable_id(stable_id);
29            self.state.physical_warm_recycled_origins[id] = RecycleOrigin::Cold;
30            id
31        } else {
32            self.ensure_dense_node_storage_capacity();
33            let id = self.state.nodes.len();
34            self.state.nodes.push(Some(node));
35            self.state
36                .physical_stable_ids
37                .push(Self::pack_stable_id(stable_id));
38            self.state
39                .physical_warm_recycled_origins
40                .push(RecycleOrigin::Cold);
41            id
42        };
43        self.state.stable_index.insert_fresh(stable_id, physical_id);
44        if is_virtual {
45            self.state.stable_index.mark_virtual(stable_id);
46        }
47        stable_id
48    }
49
50    fn node_generation(&self, id: NodeId) -> u32 {
51        if id >= Self::HIGH_ID_THRESHOLD {
52            return self
53                .state
54                .high_ids
55                .get(&id)
56                .map_or(0, |slot| slot.generation);
57        }
58        self.state.stable_index.generation(id)
59    }
60
61    #[inline]
62    fn get_mut(&mut self, id: NodeId) -> Result<&mut dyn Node, NodeError> {
63        match self.resolve_node_index(id) {
64            Some(physical_id) => self
65                .state
66                .nodes
67                .get_mut(physical_id)
68                .and_then(Option::as_deref_mut)
69                .ok_or(NodeError::Missing { id }),
70            None => self.high_id_node_mut(id),
71        }
72    }
73
74    fn remove(&mut self, id: NodeId) -> Result<(), NodeError> {
75        self.state.bubble_passes.forget();
76        self.remove_subtree_postorder(id).map(|_| ())
77    }
78
79    fn begin_bubble_batch(&mut self) {
80        self.state.bubble_passes.begin_batch();
81    }
82
83    fn note_layout_dirt(&mut self, id: NodeId) {
84        self.state.layout_dirt_roots.note(id);
85    }
86
87    fn end_bubble_batch(&mut self) {
88        self.state.bubble_passes.end_batch();
89    }
90
91    fn forget_bubble_passes(&mut self) {
92        self.state.bubble_passes.forget();
93    }
94
95    fn bubble_passes_of(&mut self, id: NodeId) -> Option<u8> {
96        self.resolve_node_index(id)
97            .map(|index| self.state.bubble_passes.passed(index))
98    }
99
100    fn note_bubble_pass(&mut self, id: NodeId, flags: u8) -> bool {
101        self.resolve_node_index(id)
102            .is_some_and(|index| self.state.bubble_passes.note(index, flags))
103    }
104
105    /// One lookup of the node's slot serves the pass note and the node.
106    fn bubble_node(&mut self, id: NodeId, flags: u8, note: bool) -> Option<&mut dyn Node> {
107        let Some(index) = self.resolve_node_index(id) else {
108            return self
109                .state
110                .high_ids
111                .get_mut(&id)
112                .and_then(|slot| slot.node.as_deref_mut());
113        };
114        if note && self.state.bubble_passes.note(index, flags) {
115            return None;
116        }
117        self.state.nodes.get_mut(index)?.as_deref_mut()
118    }
119
120    fn get_ref(&self, id: NodeId) -> Result<&dyn Node, NodeError> {
121        Self::get_ref(self, id)
122    }
123
124    fn insert_recycled_node_or_create(
125        &mut self,
126        stable_id: NodeId,
127        node: Box<dyn Node>,
128    ) -> RecycledNodeInsertion {
129        if self.contains_node_id(stable_id) {
130            let id = self.create(node);
131            return RecycledNodeInsertion::fresh(
132                id,
133                Some(NodeError::AlreadyExists { id: stable_id }),
134            );
135        }
136
137        self.insert_available_with_id(stable_id, node);
138        RecycledNodeInsertion::reused(stable_id)
139    }
140
141    fn compact(&mut self) {
142        let live_count = self
143            .state
144            .nodes
145            .iter()
146            .filter(|slot| slot.is_some())
147            .count();
148        let tombstone_count = self.state.nodes.len().saturating_sub(live_count);
149        if tombstone_count == 0 {
150            return;
151        }
152        if self.state.nodes.len() > Self::EAGER_COMPACT_NODE_LEN && tombstone_count < live_count {
153            return;
154        }
155        let rehouse_live_nodes = tombstone_count >= live_count;
156        let mut packed_nodes = Vec::with_capacity(live_count);
157        let mut packed_physical_stable_ids = Vec::with_capacity(live_count);
158        let mut packed_warm_recycled_origins = Vec::with_capacity(live_count);
159
160        for physical_id in 0..self.state.nodes.len() {
161            let Some(mut node) = self.state.nodes[physical_id].take() else {
162                continue;
163            };
164            if rehouse_live_nodes && let Some(rehoused) = node.rehouse_for_live_compaction() {
165                node = rehoused;
166            }
167            let stable_id = std::mem::replace(
168                &mut self.state.physical_stable_ids[physical_id],
169                Self::INVALID_STABLE_ID,
170            );
171            debug_assert_ne!(
172                stable_id,
173                Self::INVALID_STABLE_ID,
174                "live physical slot must have a stable id",
175            );
176            let stable_id = Self::unpack_stable_id(stable_id);
177            packed_nodes.push(Some(node));
178            packed_physical_stable_ids.push(Self::pack_stable_id(stable_id));
179            packed_warm_recycled_origins
180                .push(self.state.physical_warm_recycled_origins[physical_id]);
181            self.state
182                .stable_index
183                .set_slot(stable_id, packed_nodes.len() - 1);
184        }
185
186        self.state.nodes = packed_nodes;
187        self.state.physical_stable_ids = packed_physical_stable_ids;
188        self.state.physical_warm_recycled_origins = packed_warm_recycled_origins;
189        self.state.free_ids = BinaryHeap::new();
190        debug_assert_eq!(
191            self.state.stable_index.live(),
192            live_count,
193            "every live node keeps one indexed slot through compaction",
194        );
195        self.prune_stable_generations();
196    }
197
198    fn take_recycled_node(&mut self, key: TypeId) -> Option<RecycledNode> {
199        self.state.recycle_pools.get_mut(&key)?.take()
200    }
201
202    fn set_recycled_node_origin(&mut self, id: NodeId, origin: RecycleOrigin) {
203        if let Some(physical_id) = self.resolve_node_index(id) {
204            self.state.physical_warm_recycled_origins[physical_id] = origin;
205        } else if let Some(slot) = self.state.high_ids.get_mut(&id)
206            && slot.node.is_some()
207        {
208            slot.origin = origin;
209        }
210    }
211
212    fn seed_recycled_node_shell(
213        &mut self,
214        key: TypeId,
215        recycle_pool_limit: Option<usize>,
216        shell: Box<dyn Node>,
217    ) {
218        self.seed_recycled_node_shell_impl(key, recycle_pool_limit, shell);
219    }
220
221    fn record_fresh_recyclable_creation(&mut self, key: TypeId) {
222        self.state
223            .recycle_pools
224            .entry(key)
225            .or_default()
226            .fresh_creations += 1;
227    }
228
229    fn clear_recycled_nodes(&mut self) {
230        let next_stable_id = &mut self.state.next_stable_id;
231        for pool in self.state.recycle_pools.values_mut() {
232            pool.end_pass(next_stable_id);
233        }
234        self.prune_stable_generations();
235        self.compact();
236    }
237}