1use std::collections::VecDeque;
4use std::sync::atomic::{AtomicU64, Ordering};
5
6use nativeview_abi::table::{MAX_TABLE_SLOTS, TableDesc, Word};
7
8use crate::column::Column;
9use crate::id::{IndexVec, NodeId, NodeIndex, ResourceId, TableSet};
10mod tables;
11pub(crate) mod types;
12
13pub(crate) use crate::node::node_ref::NodeRef;
14use crate::resource::{FlatResource, ResourceStore};
15use crate::row::{DirtyList, RowRef};
16pub(crate) use crate::node::row::{
17 ANCESTOR_MARK, CHILDREN_DIRTY, CHILD_SEEN, CREATED, DEAD_IN_FREE, DEAD_MASK,
18 DEAD_PENDING_FREE, DEAD_RETIRED,
19};
20pub use crate::node::row::{NodeRow, CONNECTED, INLINE, LIVE};
21use crate::span_pool::{SpanPool, StrArena, StrSpan};
22use types::RealizationOrder;
23use crate::table::{self, NvTable, TableMeta, TableSlot};
24use crate::wire::WireError;
25use crate::wire::budget::SessionBudget;
26
27
28pub struct NodeStore {
30 pub(crate) nodes: IndexVec<NodeIndex, NodeRow>,
31 pub(crate) columns: Vec<Option<Column>>,
32 pub(crate) children: SpanPool<NodeId>,
33 pub(crate) text: StrArena,
34 pub(crate) resources: ResourceStore,
35 pub(crate) free: VecDeque<NodeIndex>,
36 pub(crate) pending_free: Vec<NodeIndex>,
37 pub(crate) touched: DirtyList,
38 pub(crate) created: Vec<NodeId>,
39 pub(crate) removed: Vec<NodeId>,
40 pub(crate) reparented: DirtyList,
41 pub(crate) scratch_stack: Vec<NodeId>,
42 pub(crate) inline_stack: Vec<(NodeIndex, bool)>,
43 pub(crate) connected_stack: Vec<NodeIndex>,
44 pub(crate) realization: RealizationOrder,
45 pub(crate) realization_mask: TableSet,
46 pub(crate) stacking_context_tables: TableSet,
47 pub(crate) inline_context_slots: TableSet,
48 pub(crate) non_inline_context_slots: TableSet,
49 pub(crate) inherits_typography_slots: TableSet,
50 pub(crate) frame: u64,
51 pub(crate) commit_epoch: u64,
52 instance: u64,
54}
55
56static NEXT_STORE_INSTANCE: AtomicU64 = AtomicU64::new(1);
58
59impl Default for NodeStore {
60 fn default() -> Self {
61 Self::new()
62 }
63}
64
65impl NodeStore {
66 pub fn new() -> Self {
68 let mut columns = Vec::with_capacity(MAX_TABLE_SLOTS);
69 columns.resize_with(MAX_TABLE_SLOTS, || None);
70 let root = NodeRow {
71 generation: 0,
72 primary_slot: TableSlot::NONE,
73 flags: LIVE | CONNECTED | CREATED,
74 ..NodeRow::default()
75 };
76 Self {
77 nodes: IndexVec::from_vec(vec![NodeRow::default(), root]),
78 columns,
79 children: SpanPool::default(),
80 text: StrArena::default(),
81 resources: ResourceStore::default(),
82 free: VecDeque::new(),
83 pending_free: Vec::new(),
84 touched: DirtyList::default(),
85 created: vec![NodeId::ROOT],
86 removed: Vec::new(),
87 reparented: DirtyList::default(),
88 scratch_stack: Vec::new(),
89 inline_stack: Vec::new(),
90 connected_stack: Vec::new(),
91 realization: RealizationOrder::default(),
92 realization_mask: TableSet::EMPTY,
93 stacking_context_tables: TableSet::EMPTY,
94 inline_context_slots: TableSet::EMPTY,
95 non_inline_context_slots: TableSet::EMPTY,
96 inherits_typography_slots: TableSet::EMPTY,
97 frame: 0,
98 commit_epoch: 0,
99 instance: NEXT_STORE_INSTANCE.fetch_add(1, Ordering::Relaxed),
100 }
101 }
102
103 #[inline]
107 pub fn instance_id(&self) -> u64 {
108 self.instance
109 }
110
111 pub fn replica() -> Self {
114 let mut s = Self::new();
115 s.nodes.truncate(1);
116 s.created.clear();
117 s
118 }
119
120 pub fn reserve_for_frame0(
123 &mut self,
124 node_count: usize,
125 payload_bytes: usize,
126 ) -> Result<(), WireError> {
127 let capped_nodes = node_count
128 .min(payload_bytes / 4)
129 .min(NodeId::MAX_INDEX as usize);
130 if capped_nodes == 0 {
131 return Ok(());
132 }
133 let target_slots = self
134 .nodes
135 .len()
136 .saturating_add(capped_nodes)
137 .saturating_add(1)
138 .min(NodeId::MAX_INDEX as usize + 1);
139 if self.nodes.capacity() < target_slots {
140 self.nodes
141 .try_reserve_exact(target_slots - self.nodes.len())
142 .map_err(|_| WireError::Alloc)?;
143 }
144 self.reserve_aux_for_frame0(capped_nodes, payload_bytes)
145 }
146
147 pub(crate) fn reserve_aux_for_frame0(
150 &mut self,
151 capped_nodes: usize,
152 payload_bytes: usize,
153 ) -> Result<(), WireError> {
154 if capped_nodes == 0 {
155 return Ok(());
156 }
157 let target_created = self.created.len().saturating_add(capped_nodes);
158 if self.created.capacity() < target_created {
159 self.created
160 .try_reserve(target_created.saturating_sub(self.created.len()))
161 .map_err(|_| WireError::Alloc)?;
162 }
163 self.touched.try_reserve(capped_nodes)?;
164 self.reparented.try_reserve(capped_nodes)?;
165 let child_target = self
166 .children
167 .data()
168 .len()
169 .saturating_add(capped_nodes.saturating_mul(2));
170 self.children
171 .try_reserve_data(child_target)
172 .map_err(|_| WireError::Alloc)?;
173 let text_add = payload_bytes.min(capped_nodes.saturating_mul(128).max(4096));
174 self.text
175 .try_reserve_bytes(self.text.data().len().saturating_add(text_add))
176 .map_err(|_| WireError::Alloc)?;
177 Ok(())
178 }
179
180 #[inline]
182 pub(crate) fn nodes_cap(&self) -> usize {
183 self.nodes.capacity()
184 }
185
186 pub(crate) fn reserve_nodes_budgeted(
189 &mut self,
190 needed: usize,
191 budget: &mut SessionBudget,
192 ) -> Result<(), WireError> {
193 let old_cap = self.nodes.capacity();
194 let (target, delta_bytes) = SessionBudget::bounded_target_cap(
195 old_cap,
196 self.nodes.len(),
197 needed,
198 size_of::<NodeRow>(),
199 budget.remaining(),
200 )?;
201 if target > old_cap {
202 self.nodes
203 .try_reserve_exact(target - self.nodes.len())
204 .map_err(|_| WireError::Alloc)?;
205 budget.charge(delta_bytes)?;
206 }
207 Ok(())
208 }
209
210 pub(crate) fn try_create_at(
213 &mut self,
214 id: NodeId,
215 budget: Option<&mut SessionBudget>,
216 ) -> Result<bool, WireError> {
217 let index = id.node_index();
218 if index == NodeIndex::NULL || self.nodes.get(index).is_some_and(|r| r.flags & LIVE != 0) {
219 return Ok(false);
220 }
221 let needed = index.as_usize().checked_add(1).ok_or(WireError::Budget)?;
222 if self.nodes.len() < needed {
223 if let Some(budget) = budget {
224 self.reserve_nodes_budgeted(needed, budget)?;
225 } else if self.nodes.capacity() < needed {
226 let add = needed - self.nodes.len();
227 self.nodes.try_reserve(add).map_err(|_| WireError::Alloc)?;
228 }
229 }
230 self.created.try_reserve(1).map_err(|_| WireError::Alloc)?;
231 if self.nodes.len() < needed {
232 self.nodes.resize(needed, NodeRow::default());
233 }
234 let connected_flag = if id == NodeId::ROOT { CONNECTED } else { 0 };
235 self.nodes[index] = NodeRow {
236 generation: id.generation(),
237 primary_slot: TableSlot::NONE,
238 flags: LIVE | connected_flag | CREATED,
239 ..NodeRow::default()
240 };
241 self.created.push(id);
242 Ok(true)
243 }
244
245 pub(crate) fn reserve_column_bulk(
247 &mut self,
248 slot: TableSlot,
249 expected_rows: usize,
250 max_node_index: usize,
251 budget: &mut SessionBudget,
252 ) -> Result<(), WireError> {
253 self.column_mut(slot)
254 .reserve_bulk(expected_rows, max_node_index, budget)
255 }
256
257 pub(crate) fn insert_realizing_slot(
265 &mut self,
266 slot: TableSlot,
267 priority: u8,
268 key: nativeview_abi::table::TableKey,
269 ) {
270 if priority == 0 || self.realization_mask.contains(slot) {
271 return;
272 }
273 let rank = |s: TableSlot| -> (u8, core::cmp::Reverse<u64>) {
274 if let Some(m) = self.table_meta(s) {
275 (m.realization_priority(), core::cmp::Reverse(m.key().0))
276 } else if let Some(d) = table::try_desc(s) {
277 (d.realization_priority, core::cmp::Reverse(d.key.0))
278 } else {
279 (0, core::cmp::Reverse(u64::MAX))
280 }
281 };
282 let new_rank = (priority, core::cmp::Reverse(key.0));
283 let pos = self
284 .realization
285 .slots
286 .iter()
287 .rposition(|&existing| rank(existing) >= new_rank)
288 .map_or(0, |i| i + 1);
289 self.realization.slots.insert(pos, slot);
290 self.realization_mask.insert(slot);
291 }
292
293 pub fn set_realization_order(&mut self, order: RealizationOrder) {
297 self.realization_mask = TableSet(order.slots.iter().fold(0u128, |m, &s| m | s.bit()));
298 for &slot in &order.slots {
299 if let Some(d) = table::try_desc(slot) {
300 if (d.flags & nativeview_abi::table::table_flags::INLINE_CONTEXT) != 0 {
301 self.inline_context_slots.insert(slot);
302 }
303 if (d.flags & nativeview_abi::table::table_flags::NO_INLINE_CONTEXT) != 0 {
304 self.non_inline_context_slots.insert(slot);
305 }
306 if (d.flags & nativeview_abi::table::table_flags::INHERITS_TYPOGRAPHY) != 0 {
307 self.inherits_typography_slots.insert(slot);
308 }
309 }
310 }
311 self.realization = order;
312 let mut installed = [(TableSlot(0), 0u8, nativeview_abi::Key64(0)); MAX_TABLE_SLOTS];
313 let mut installed_len = 0usize;
314 for (i, col) in self.columns.iter().enumerate() {
315 if let Some(col) = col {
316 let p = col.desc.realization_priority();
317 if p > 0 {
318 installed[installed_len] = (TableSlot(i as u8), p, col.desc.key());
319 installed_len += 1;
320 }
321 }
322 }
323 for &(slot, priority, key) in &installed[..installed_len] {
324 self.insert_realizing_slot(slot, priority, key);
325 }
326 let n = self.nodes.len();
327 for i in 1..n {
328 let row = &mut self.nodes[NodeIndex(i as u32)];
329 if row.flags & LIVE != 0 {
330 row.primary_slot = self.realization.primary_slot(row.tables);
331 }
332 }
333 self.recompute_all_inline_flags();
334 }
335
336 #[inline]
338 pub fn frame(&self) -> u64 {
339 self.frame
340 }
341
342 #[inline]
344 pub fn commit_epoch(&self) -> u64 {
345 self.commit_epoch
346 }
347
348 #[inline(always)]
350 pub fn stacking_context_tables(&self) -> TableSet {
351 self.stacking_context_tables
352 }
353
354 #[inline(always)]
356 pub fn inherits_typography_slots(&self) -> TableSet {
357 self.inherits_typography_slots
358 }
359
360 #[inline(always)]
362 pub fn node_tables(&self, id: NodeId) -> TableSet {
363 self.node(id).map_or(TableSet::EMPTY, |r| r.tables)
364 }
365
366 #[inline(always)]
367 pub fn is_live(&self, id: NodeId) -> bool {
368 self.nodes
369 .get(id.node_index())
370 .is_some_and(|r| r.flags & LIVE != 0 && r.generation == id.generation())
371 }
372
373 #[inline(always)]
375 pub fn is_connected(&self, id: NodeId) -> bool {
376 self.nodes.get(id.node_index()).is_some_and(|r| {
377 (r.flags & (LIVE | CONNECTED)) == (LIVE | CONNECTED)
378 && r.generation == id.generation()
379 })
380 }
381
382
383 #[inline(always)]
385 pub fn get(&self, id: NodeId) -> Option<NodeRef<'_>> {
386 let idx = id.node_index();
387 let r = self.nodes.get(idx)?;
388 if r.flags & LIVE != 0 && r.generation == id.generation() {
389 Some(NodeRef::new_unchecked(self, idx))
390 } else {
391 None
392 }
393 }
394
395 #[inline(always)]
397 pub fn node(&self, id: NodeId) -> Option<&NodeRow> {
398 self.nodes
399 .get(id.node_index())
400 .filter(|r| r.flags & LIVE != 0 && r.generation == id.generation())
401 }
402
403 #[inline]
405 pub fn id_at(&self, index: usize) -> Option<NodeId> {
406 let idx = NodeIndex(index as u32);
407 let r = self.nodes.get(idx)?;
408 (r.flags & LIVE != 0).then(|| NodeId::from_index(idx, r.generation))
409 }
410
411 #[inline]
413 pub fn capacity(&self) -> usize {
414 self.nodes.len()
415 }
416
417 #[inline]
420 pub fn node_rows(&self) -> &[NodeRow] {
421 self.nodes.as_slice()
422 }
423
424 pub fn live_nodes(&self) -> impl Iterator<Item = NodeId> + '_ {
426 (1..self.nodes.len()).filter_map(|i| self.id_at(i))
427 }
428
429 #[inline]
430 pub fn parent(&self, id: NodeId) -> Option<NodeId> {
431 self.get(id).and_then(NodeRef::parent)
432 }
433
434 #[inline]
435 pub fn children(&self, id: NodeId) -> &[NodeId] {
436 self.get(id).map_or(&[], NodeRef::children)
437 }
438
439 #[inline]
440 pub fn primary_slot(&self, id: NodeId) -> TableSlot {
441 self.get(id).map_or(TableSlot::NONE, NodeRef::primary_slot)
442 }
443
444 #[inline(always)]
446 pub fn is_inline(&self, id: NodeId) -> bool {
447 self.get(id).is_some_and(NodeRef::is_inline)
448 }
449
450 #[inline(always)]
452 pub fn inline_context_slots(&self) -> TableSet {
453 self.inline_context_slots
454 }
455
456 #[inline(always)]
458 pub fn is_inline_context_root(&self, id: NodeId) -> bool {
459 self.get(id).is_some_and(|n| {
460 let r = n.raw_row();
461 (r.flags & INLINE) == 0
462 && crate::commit::row_establishes_inline_context(
463 r,
464 self.inline_context_slots,
465 self.non_inline_context_slots,
466 )
467 })
468 }
469
470 #[inline(always)]
471 pub fn has<T: NvTable>(&self, id: NodeId) -> bool {
472 self.get(id).is_some_and(NodeRef::has::<T>)
473 }
474
475 #[inline(always)]
476 pub fn has_slot(&self, id: NodeId, slot: TableSlot) -> bool {
477 self.get(id).is_some_and(|n| n.has_slot(slot))
478 }
479
480 #[inline]
482 pub fn words(&self, id: NodeId, slot: TableSlot) -> Option<&[Word]> {
483 self.get(id)?.words(slot)
484 }
485
486 #[inline]
488 pub fn try_row<T: NvTable>(&self, id: NodeId) -> Option<T::Ref<'_>> {
489 self.get(id)?.try_row::<T>()
490 }
491
492 #[inline]
494 pub fn row<T: NvTable>(&self, id: NodeId) -> T::Ref<'_> {
495 self.get(id).map_or_else(
496 || T::from_row_ref(RowRef::new(T::DESC.defaults, &self.text, T::DESC.str_words)),
497 NodeRef::row::<T>,
498 )
499 }
500
501 #[inline]
505 pub fn row_from_words<'a, T: NvTable>(&'a self, words: &'a [Word]) -> T::Ref<'a> {
506 assert!(
507 T::DESC.str_words == 0 && words.len() >= T::DESC.words(),
508 "row_from_words requires a string-free table and >= {} words",
509 T::DESC.words()
510 );
511 T::from_row_ref(RowRef::new(words, &self.text, 0))
512 }
513
514 #[inline]
516 pub fn copy_row_words<T: NvTable>(&self, id: NodeId, out: &mut [Word]) {
517 let n = T::DESC.words();
518 debug_assert!(out.len() >= n);
519 let src = self
520 .get(id)
521 .and_then(|nr| nr.words(T::slot()))
522 .unwrap_or(T::DESC.defaults);
523 out[..n].copy_from_slice(&src[..n]);
524 }
525
526 #[inline]
528 pub fn try_text(&self, span: StrSpan) -> Option<&str> {
529 self.text.try_str(span)
530 }
531
532 #[inline]
535 pub fn text(&self, span: StrSpan) -> &str {
536 self.text.str(span)
537 }
538
539 #[inline(always)]
540 pub(crate) fn text_arena(&self) -> &StrArena {
541 &self.text
542 }
543
544 #[inline]
546 pub fn text_slab(&self) -> &[u8] {
547 self.text.data()
548 }
549
550 #[inline]
552 pub fn children_slab(&self) -> &[NodeId] {
553 self.children.data()
554 }
555
556 #[inline]
557 pub fn resources(&self) -> &ResourceStore {
558 &self.resources
559 }
560
561 #[inline]
562 pub fn resource<R: FlatResource>(&self, id: ResourceId) -> Option<R::View<'_>> {
563 self.resources.get::<R>(id)
564 }
565
566 #[inline]
568 pub fn table_desc(&self, slot: TableSlot) -> Option<&'static TableDesc> {
569 self.columns[slot.0 as usize]
570 .as_ref()
571 .and_then(|c| c.desc.as_static())
572 }
573
574 #[inline]
576 pub fn table_key(&self, slot: TableSlot) -> Option<nativeview_abi::table::TableKey> {
577 self.table_meta(slot).map(TableMeta::key)
578 }
579
580 #[inline]
582 pub(crate) fn table_meta(&self, slot: TableSlot) -> Option<&TableMeta> {
583 self.columns[slot.0 as usize].as_ref().map(|c| &c.desc)
584 }
585
586 pub(crate) fn column_mut(&mut self, slot: TableSlot) -> &mut Column {
587 let slot_idx = slot.0 as usize;
588 if self.columns[slot_idx].is_none() {
589 assert!(
590 slot_idx < table::MAX_STATIC_TABLE_SLOTS,
591 "cannot lazily allocate static column in dynamic slot {}",
592 slot.0
593 );
594 let d = table::desc(slot);
595 if (d.flags & nativeview_abi::table::table_flags::STACKING_CONTEXT) != 0 {
596 self.stacking_context_tables.insert(slot);
597 }
598 if (d.flags & nativeview_abi::table::table_flags::INLINE_CONTEXT) != 0 {
599 self.inline_context_slots.insert(slot);
600 }
601 if (d.flags & nativeview_abi::table::table_flags::NO_INLINE_CONTEXT) != 0 {
602 self.non_inline_context_slots.insert(slot);
603 }
604 if (d.flags & nativeview_abi::table::table_flags::INHERITS_TYPOGRAPHY) != 0 {
605 self.inherits_typography_slots.insert(slot);
606 }
607 self.columns[slot_idx] = Some(Column::new(TableMeta::Static(d)));
608 self.insert_realizing_slot(slot, d.realization_priority, d.key);
610 }
611 self.columns[slot_idx]
612 .as_mut()
613 .expect("column initialized above")
614 }
615
616 #[inline]
617 pub(crate) fn column_mut_typed<T: NvTable>(&mut self, slot: TableSlot) -> &mut Column {
618 let col = self.column_mut(slot);
619 debug_assert_eq!(
620 col.desc.key(),
621 T::DESC.key,
622 "table slot {} key mismatch for `{}`",
623 slot.0,
624 T::DESC.name
625 );
626 col
627 }
628}