Skip to main content

nativeview_store/store/
tables.rs

1//! Table introspection, dynamic table installation, schema hashing, published storage views,
2//! and store statistics for [`NodeStore`].
3
4use std::sync::Arc;
5
6use nativeview_abi::table::{MAX_TABLE_SLOTS, Storage, TableDesc};
7
8use crate::column::Column;
9use crate::id::{NodeId, NodeIndex, ResourceId, TableSet};
10use crate::store::{LIVE, NodeStore};
11use super::types::{StoreStats, TableStorage};
12use crate::table::{self, NvTable, OwnedTableDesc, TableMeta, TableSlot};
13
14impl NodeStore {
15    /// Word holding the `EventSet` listener bitmask for `slot`, or [`nativeview_abi::table::NO_VAL_WORD`]
16    /// when `slot` has no events or is not installed in this store.
17    #[inline]
18    pub fn events_word(&self, slot: TableSlot) -> u8 {
19        self.table_meta(slot)
20            .map_or(nativeview_abi::table::NO_VAL_WORD, TableMeta::events_word)
21    }
22
23    /// Raw 32-bit `EventSet` listener bitmask on live node `id` for `slot` (`0` if absent or no
24    /// events).
25    #[inline]
26    pub fn node_events_mask(&self, slot: TableSlot, id: NodeId) -> u32 {
27        let ew = self.events_word(slot);
28        if ew == nativeview_abi::table::NO_VAL_WORD {
29            return 0;
30        }
31        self.words(id, slot)
32            .and_then(|w| w.get(ew as usize).copied())
33            .unwrap_or(0)
34    }
35
36    /// Installs a session-scoped dynamic table column strictly in the dynamic slot partition
37    /// (`MAX_STATIC_TABLE_SLOTS..MAX_TABLE_SLOTS`), returning `false` on slot-range violation or
38    /// schema mismatch against an already-installed column at `slot`.
39    pub(crate) fn install_dynamic_table(
40        &mut self,
41        slot: TableSlot,
42        desc: Arc<OwnedTableDesc>,
43    ) -> bool {
44        let slot_idx = slot.0 as usize;
45        if !(table::MAX_STATIC_TABLE_SLOTS..MAX_TABLE_SLOTS).contains(&slot_idx) {
46            return false;
47        }
48        match &self.columns[slot_idx] {
49            None => {
50                if (desc.flags & nativeview_abi::table::table_flags::STACKING_CONTEXT) != 0 {
51                    self.stacking_context_tables.insert(slot);
52                }
53                if (desc.flags & nativeview_abi::table::table_flags::INLINE_CONTEXT) != 0 {
54                    self.inline_context_slots.insert(slot);
55                }
56                if (desc.flags & nativeview_abi::table::table_flags::NO_INLINE_CONTEXT) != 0 {
57                    self.non_inline_context_slots.insert(slot);
58                }
59                if (desc.flags & nativeview_abi::table::table_flags::INHERITS_TYPOGRAPHY) != 0 {
60                    self.inherits_typography_slots.insert(slot);
61                }
62                let priority = desc.realization_priority;
63                let key = desc.key;
64                self.columns[slot_idx] = Some(Column::new(TableMeta::Dynamic(desc)));
65                // Column was just created empty, so zero live nodes can carry `slot`.
66                self.insert_realizing_slot(slot, priority, key);
67                true
68            }
69            Some(col) => {
70                matches!(&col.desc, TableMeta::Dynamic(existing) if existing.as_ref() == desc.as_ref())
71            }
72        }
73    }
74
75    /// Deterministic 64-bit XXH64 schema digest over `base_descs` unioned with every table
76    /// actually attached to at least one live node in this store (both compiled static and
77    /// wire-declared dynamic tables). Matches [`crate::tables_schema_hash(base_descs)`] when
78    /// only tables in `base_descs` are live.
79    pub fn schema_hash_with_base(&self, base_descs: &[&'static TableDesc]) -> u64 {
80        let mut live_bits = 0u128;
81        for i in 1..self.nodes.len() {
82            let row = self.nodes[NodeIndex(i as u32)];
83            if row.flags & LIVE != 0 {
84                live_bits |= row.tables.0;
85            }
86        }
87        table::hash_table_schema_pairs(
88            base_descs
89                .iter()
90                .map(|d| (d.key.0, d.schema_hash))
91                .chain(
92                    TableSet(live_bits)
93                        .iter_slots()
94                        .filter_map(|slot| self.table_meta(slot))
95                        .map(|meta| (meta.key().0, meta.schema_hash())),
96                ),
97        )
98    }
99
100    /// Slots of every table that has a column in this store.
101    pub fn table_slots(&self) -> impl Iterator<Item = TableSlot> + '_ {
102        self.columns
103            .iter()
104            .enumerate()
105            .filter(|(_, c)| c.is_some())
106            .map(|(i, _)| TableSlot(i as u8))
107    }
108
109    /// Invokes `f` once for every live row owner in `slot` (sparse or dense) storing a `ResourceId`
110    /// matching `is_changed`. Uses `TableDesc::resource_words` when registered, falling back to
111    /// scanning every word of the row when no descriptor exists (including rows wider than 32 words).
112    pub fn for_each_owner_referencing_resources(
113        &self,
114        slot: TableSlot,
115        mut is_changed: impl FnMut(ResourceId) -> bool,
116        mut f: impl FnMut(NodeId),
117    ) {
118        let Some(TableStorage {
119            rows,
120            owners,
121            row_count,
122            ..
123        }) = self.table_storage(slot)
124        else {
125            return;
126        };
127        if row_count == 0 {
128            return;
129        }
130        let desc = self.table_desc(slot);
131        let words_per_row = desc.map_or_else(|| rows.len() / row_count, |d| d.words());
132        let res_mask = desc.map(|d| d.resource_words);
133        if words_per_row == 0 || res_mask == Some(0) {
134            return;
135        }
136        let max_bits = if words_per_row >= 32 {
137            u32::MAX
138        } else {
139            (1u32 << words_per_row) - 1
140        };
141        let is_dense = owners.is_empty();
142        for r in 0..row_count {
143            let owner = if is_dense {
144                let Some(id) = self.id_at(r) else {
145                    continue;
146                };
147                if !self.has_slot(id, slot) {
148                    continue;
149                }
150                id
151            } else {
152                let id = owners.get(r).copied().unwrap_or(NodeId::NULL);
153                if id.is_null() || !self.is_live(id) {
154                    continue;
155                }
156                id
157            };
158            let row_base = r * words_per_row;
159            let hit = if let Some(mask) = res_mask {
160                let mut m = mask & max_bits;
161                let mut found = false;
162                while m != 0 {
163                    let w = m.trailing_zeros() as usize;
164                    m &= m - 1;
165                    if let Some(&word) = rows.get(row_base + w) {
166                        let rid = ResourceId(word);
167                        if !rid.is_none() && is_changed(rid) {
168                            found = true;
169                            break;
170                        }
171                    }
172                }
173                found
174            } else {
175                rows.get(row_base..row_base + words_per_row)
176                    .is_some_and(|row| {
177                        row.iter().any(|&word| {
178                            let rid = ResourceId(word);
179                            !rid.is_none() && is_changed(rid)
180                        })
181                    })
182            };
183            if hit {
184                f(owner);
185            }
186        }
187    }
188
189    /// Visits every `(slot, owner)` across `slots` whose row references a resource in
190    /// `changes.resources_defined` or `changes.resources_released`, automatically switching from
191    /// linear scan (`<= 4` changed resources) to a `FastBuildHasher` set (`> 4`).
192    pub fn for_each_slot_owner_referencing_changed_resources(
193        &self,
194        slots: &[TableSlot],
195        changes: &crate::ChangeSet,
196        mut f: impl FnMut(TableSlot, NodeId),
197    ) {
198        let total = changes.resources_defined.len() + changes.resources_released.len();
199        if total == 0 || slots.is_empty() {
200            return;
201        }
202        let changed_set = (total > 4).then(|| {
203            let mut set = std::collections::HashSet::with_capacity_and_hasher(
204                total,
205                crate::lru::FastBuildHasher,
206            );
207            set.extend(changes.resources_defined.iter().copied());
208            set.extend(changes.resources_released.iter().copied());
209            set
210        });
211        for &slot in slots {
212            self.for_each_owner_referencing_resources(
213                slot,
214                |rid| {
215                    if let Some(ref set) = changed_set {
216                        set.contains(&rid)
217                    } else {
218                        changes.resources_defined.contains(&rid)
219                            || changes.resources_released.contains(&rid)
220                    }
221                },
222                |owner| f(slot, owner),
223            );
224        }
225    }
226
227    /// A table's storage exactly as published in `NvTableView`.
228    pub fn table_storage(&self, slot: TableSlot) -> Option<TableStorage<'_>> {
229        let c = self.columns[slot.0 as usize].as_ref()?;
230        let rc = c.published_row_count(self.capacity());
231        if c.is_dense() {
232            return Some(TableStorage {
233                rows: &c.rows[..rc * c.w],
234                owners: &[],
235                row_count: rc,
236                row_index_dir: &[],
237                row_index_pages: &[],
238            });
239        }
240        let (row_index_dir, row_index_pages) = c.row_index();
241        Some(TableStorage {
242            rows: &c.rows,
243            owners: &c.owners,
244            row_count: rc,
245            row_index_dir,
246            row_index_pages,
247        })
248    }
249
250    /// The owner of every row of the sparse table `T`, in row order: rows swap-remove on detach,
251    /// so each entry is a live node owning a `T` row. O(rows) iteration instead of a scan over
252    /// every slot. A dense `T` is a compile error (it has no owner list).
253    #[inline]
254    pub fn row_owners<T: NvTable>(&self) -> &[NodeId] {
255        const { assert!(matches!(T::DESC.storage, Storage::Sparse), "row_owners needs a sparse table") };
256        self.columns[T::slot().0 as usize]
257            .as_ref()
258            .map_or(&[], |c| c.owners.as_slice())
259    }
260
261    pub fn stats(&self) -> StoreStats {
262        let live_nodes = (1..self.nodes.len())
263            .filter(|&i| self.nodes[NodeIndex(i as u32)].flags & LIVE != 0)
264            .count();
265        StoreStats {
266            live_nodes,
267            node_capacity: self.nodes.len(),
268            children_live: self.children.live(),
269            children_capacity: self.children.data().len(),
270            text_live: self.text.live(),
271            text_capacity: self.text.data().len(),
272            resources_live: self.resources.live(),
273            table_count: self.columns.iter().filter(|c| c.is_some()).count(),
274        }
275    }
276}