Skip to main content

nativeview_store/tx/
mod.rs

1//! [`TxCore`] (every mutation), [`Transaction`] (adds `commit_into`, which closes the frame) and
2//! validated [`NodeMut`]: the only way to mutate a [`NodeStore`].
3
4use std::ops::{Deref, DerefMut};
5
6mod children;
7
8use nativeview_abi::table::effect;
9
10use crate::id::{NodeId, NodeIndex, ResourceId};
11use crate::node::node_mut::{NodeMut, TempResources};
12use crate::resource::FlatResource;
13use crate::row::{DirtyList, RowWriter};
14use crate::row::patch::{RowPatchView, WordMask, WordOp};
15use crate::span_pool::StrSpan;
16use crate::store::{
17    NodeRow, NodeStore, CREATED, DEAD_IN_FREE, DEAD_MASK, DEAD_PENDING_FREE, LIVE,
18};
19use crate::table::{NvTable, Prop, ResProp, ScalarField, StrProp, TableSlot};
20
21/// Non-committing mutation handle: every node, table, and resource edit of a frame. Reached through
22/// a [`Transaction`] (via `Deref`) or [`TempResources::tx`], which must not close the frame while
23/// temporary resource handles are still retained.
24pub struct TxCore<'s> {
25    pub(crate) store: &'s mut NodeStore,
26}
27
28/// Mutable frame scope over a [`NodeStore`]: [`TxCore`] plus `commit_into`.
29pub struct Transaction<'s> {
30    pub(crate) core: TxCore<'s>,
31}
32
33impl<'s> Deref for Transaction<'s> {
34    type Target = TxCore<'s>;
35
36    #[inline(always)]
37    fn deref(&self) -> &TxCore<'s> {
38        &self.core
39    }
40}
41
42impl DerefMut for Transaction<'_> {
43    #[inline(always)]
44    fn deref_mut(&mut self) -> &mut Self::Target {
45        &mut self.core
46    }
47}
48
49impl NodeStore {
50    /// Opens a mutation scope. Changes accumulate across transactions until `commit_into`.
51    #[inline]
52    pub fn tx(&mut self) -> Transaction<'_> {
53        Transaction {
54            core: TxCore { store: self },
55        }
56    }
57}
58
59#[inline(always)]
60pub(crate) fn touch(node: &mut NodeRow, touched: &mut DirtyList, index: NodeIndex, fx: u8) {
61    let had = node.effects;
62    node.effects = had | fx;
63    touched.push_if(index, (had == 0) & (fx != 0));
64}
65
66/// Typed writer resolving `T::slot()` and ensuring its column once before mutating words.
67#[inline]
68pub(crate) fn writer_at_typed<T: NvTable>(
69    store: &mut NodeStore,
70    index: NodeIndex,
71) -> RowWriter<'_> {
72    let slot = T::slot();
73    store.column_mut_typed::<T>(slot);
74    writer_at_existing(store, index, slot)
75}
76
77/// Internal writer taking an already-validated `NodeIndex` (zero redundant liveness checks).
78#[inline]
79fn writer_at(store: &mut NodeStore, index: NodeIndex, slot: TableSlot) -> RowWriter<'_> {
80    store.column_mut(slot);
81    writer_at_existing(store, index, slot)
82}
83
84#[inline]
85fn writer_at_existing(store: &mut NodeStore, index: NodeIndex, slot: TableSlot) -> RowWriter<'_> {
86    let NodeStore {
87        nodes,
88        columns,
89        text,
90        resources,
91        touched,
92        realization_mask,
93        ..
94    } = store;
95    let node = &mut nodes[index];
96    let col = columns[slot.0 as usize]
97        .as_mut()
98        .expect("column created above");
99    if !node.tables.contains(slot) {
100        let id = NodeId::from_index(index, node.generation);
101        col.attach(id, index);
102        node.tables.insert(slot);
103        let realize = if realization_mask.contains(slot) {
104            effect::REALIZE
105        } else {
106            0
107        };
108        touch(node, touched, index, realize | col.desc.effects());
109    }
110    let row = col.row_of(index);
111    let w = col.w;
112    RowWriter {
113        row: &mut col.rows[row * w..(row + 1) * w],
114        mask: &mut col.masks[row],
115        dirty: &mut col.dirty,
116        node_index: index,
117        node,
118        touched,
119        desc: &col.desc,
120        text,
121        resources,
122    }
123}
124
125/// Fallible internal row writer for wire decoding: uses `try_reserve` + `Column::try_attach`
126/// against `SessionBudget`, returning `WireError::Budget` on slot-budget overrun or
127/// `WireError::Alloc` on transient OOM instead of aborting.
128#[inline]
129fn try_writer_at_existing<'a>(
130    store: &'a mut NodeStore,
131    index: NodeIndex,
132    slot: TableSlot,
133    budget: &mut crate::wire::budget::SessionBudget,
134) -> Result<RowWriter<'a>, crate::wire::WireError> {
135    let NodeStore {
136        nodes,
137        columns,
138        text,
139        resources,
140        touched,
141        realization_mask,
142        ..
143    } = store;
144    let node = &mut nodes[index];
145    let col = columns[slot.0 as usize]
146        .as_mut()
147        .ok_or(crate::wire::WireError::UndeclaredTable(slot.0))?;
148    touched.try_reserve(usize::from(node.effects == 0))?;
149    let row = if !node.tables.contains(slot) {
150        let id = NodeId::from_index(index, node.generation);
151        let r = col.try_attach(id, index, budget)?;
152        node.tables.insert(slot);
153        let realize = if realization_mask.contains(slot) {
154            effect::REALIZE
155        } else {
156            0
157        };
158        touch(node, touched, index, realize | col.desc.effects());
159        r
160    } else {
161        let r = col.row_of(index);
162        col.dirty.try_reserve(usize::from(col.masks[r] == 0))?;
163        r
164    };
165    let w = col.w;
166    Ok(RowWriter {
167        row: &mut col.rows[row * w..(row + 1) * w],
168        mask: &mut col.masks[row],
169        dirty: &mut col.dirty,
170        node_index: index,
171        node,
172        touched,
173        desc: &col.desc,
174        text,
175        resources,
176    })
177}
178
179impl TxCore<'_> {
180    /// Read access to the store mid-transaction.
181    #[inline]
182    pub fn store(&self) -> &NodeStore {
183        self.store
184    }
185
186    /// Allocates a node (detached, no tables).
187    pub fn create(&mut self) -> NodeId {
188        let index = self.alloc_slot();
189        NodeId::from_index(index, self.store.nodes[index].generation)
190    }
191
192    /// Allocates a node and returns a validated [`NodeMut`] handle for chained zero-check edits.
193    #[inline]
194    pub fn spawn(&mut self) -> NodeMut<'_> {
195        let index = self.alloc_slot();
196        NodeMut::new(self.store, index)
197    }
198
199    /// Validates `id` once and returns a [`NodeMut`] handle (`None` if dead/stale).
200    #[inline(always)]
201    pub fn node_mut(&mut self, id: NodeId) -> Option<NodeMut<'_>> {
202        let index = id.node_index();
203        let r = self.store.nodes.get(index)?;
204        if r.flags & LIVE != 0 && r.generation == id.generation() {
205            Some(NodeMut::new(self.store, index))
206        } else {
207            None
208        }
209    }
210
211    fn alloc_slot(&mut self) -> NodeIndex {
212        let s = &mut *self.store;
213        let mut reused = None;
214        while let Some(i) = s.free.pop_front() {
215            if (s.nodes[i].flags & (LIVE | DEAD_MASK)) == DEAD_IN_FREE {
216                reused = Some(i);
217                break;
218            }
219        }
220        let index = match reused {
221            Some(i) => i,
222            None => {
223                let raw = s.nodes.len() as u32;
224                assert!(
225                    raw <= NodeId::MAX_INDEX,
226                    "NodeStore: node index space exhausted"
227                );
228                s.nodes.push(NodeRow::default())
229            }
230        };
231        let row = &mut s.nodes[index];
232        row.flags = LIVE | CREATED;
233        row.primary_slot = TableSlot::NONE;
234        let id = NodeId::from_index(index, row.generation);
235        s.created.push(id);
236        index
237    }
238
239    /// Creates `id` exactly (replica stores applying a wire frame). Returns `false` if the slot
240    /// is occupied by a live node. O(1) — clears `IN_FREE`/`PENDING_FREE` flags without scanning.
241    pub fn create_at(&mut self, id: NodeId) -> bool {
242        self.store.try_create_at(id, None).unwrap_or(false)
243    }
244
245    /// Removes `id` and its whole subtree, detaching it from its parent (zero heap allocations
246    /// once `scratch_stack` is warm). Records `removed` in postorder (descendants before ancestors).
247    pub fn remove(&mut self, id: NodeId) {
248        if !self.store.is_live(id) {
249            return;
250        }
251        self.detach_child_inner(id, false);
252        let removed_start = self.store.removed.len();
253        self.store.scratch_stack.clear();
254        self.store.scratch_stack.push(id);
255        while let Some(n) = self.store.scratch_stack.pop() {
256            let row = self.store.nodes[n.node_index()];
257            if row.flags & LIVE == 0 || row.generation != n.generation() {
258                continue;
259            }
260            let children_span = row.children;
261            let NodeStore {
262                children,
263                scratch_stack,
264                ..
265            } = &mut *self.store;
266            scratch_stack.extend_from_slice(children.get(children_span));
267            self.free_node(n);
268        }
269        // Reverse this subtree's recorded removals so descendants precede ancestors.
270        self.store.removed[removed_start..].reverse();
271    }
272
273    fn free_node(&mut self, id: NodeId) {
274        let index = id.node_index();
275        let row = self.store.nodes[index];
276        debug_assert!(
277            row.flags & LIVE != 0 && row.generation == id.generation(),
278            "free_node called on non-live or stale node {id:?}"
279        );
280        if row.flags & LIVE == 0 || row.generation != id.generation() {
281            return;
282        }
283        let tables = row.tables;
284        for slot in tables.iter_slots() {
285            self.release_row(index, slot);
286        }
287        let s = &mut *self.store;
288        let row = s.nodes[index];
289        s.children.free(row.children);
290        if row.flags & CREATED == 0 {
291            s.removed.push(id);
292        }
293        s.nodes[index] = NodeRow {
294            generation: row.generation,
295            flags: DEAD_PENDING_FREE,
296            ..NodeRow::default()
297        };
298        s.pending_free.push(index);
299    }
300
301    /// Releases strings/resources referenced by `slot`'s row and drops the row.
302    fn release_row(&mut self, index: NodeIndex, slot: TableSlot) {
303        let s = &mut *self.store;
304        let Some(col) = s.columns[slot.0 as usize].as_mut() else {
305            return;
306        };
307        let Some(row) = col.find_row(index) else {
308            return;
309        };
310        let (str_words, res_words) = (col.desc.str_words(), col.desc.resource_words());
311        let words = &mut col.rows[row * col.w..(row + 1) * col.w];
312        let mut m = str_words;
313        while m != 0 {
314            let w = m.trailing_zeros() as usize;
315            m &= m - 1;
316            s.text.free(StrSpan::new(words[w], words[w + 1]));
317            words[w] = 0;
318            words[w + 1] = 0;
319        }
320        let mut m = res_words;
321        while m != 0 {
322            let w = m.trailing_zeros() as usize;
323            m &= m - 1;
324            s.resources.release(ResourceId(words[w]));
325            words[w] = 0;
326        }
327        if col.is_dense() {
328            col.masks[row] = 0;
329        }
330        col.remove_row(index);
331    }
332
333    // -----------------------------------------------------------------------------------------
334    // Tables
335    // -----------------------------------------------------------------------------------------
336
337    /// Fallible crate-private row writer for `slot` on `id`, attaching the table (defaults) when
338    /// absent via `try_attach` charged to `budget`. Sealed against raw scalar overwrites.
339    pub(crate) fn try_writer<'a>(
340        &'a mut self,
341        id: NodeId,
342        slot: TableSlot,
343        budget: &mut crate::wire::budget::SessionBudget,
344    ) -> Result<RowWriter<'a>, crate::wire::WireError> {
345        if !self.store.is_live(id) {
346            return Err(crate::wire::WireError::DeadNode(id.raw()));
347        }
348        self.store.column_mut(slot);
349        try_writer_at_existing(self.store, id.node_index(), slot, budget)
350    }
351
352    /// Fluent typed writer for `T` on `id` (attaches `T` with defaults when absent).
353    #[inline]
354    pub fn edit<T: NvTable>(&mut self, id: NodeId) -> T::Mut<'_> {
355        assert!(
356            self.store.is_live(id),
357            "NodeStore: write to dead node {id:?}"
358        );
359        T::from_row_writer(writer_at_typed::<T>(self.store, id.node_index()))
360    }
361
362    /// Attaches `T` with its defaults (no-op if attached).
363    #[inline]
364    pub fn attach<T: NvTable>(&mut self, id: NodeId) {
365        assert!(
366            self.store.is_live(id),
367            "NodeStore: write to dead node {id:?}"
368        );
369        writer_at_typed::<T>(self.store, id.node_index());
370    }
371
372    /// Sets one scalar or wide-optional property.
373    #[inline(always)]
374    pub fn set<T: NvTable, V: ScalarField>(&mut self, id: NodeId, prop: Prop<T, V>, value: V) {
375        assert!(self.store.is_live(id), "NodeStore: write to dead node {id:?}");
376        let mut w = writer_at_typed::<T>(self.store, id.node_index());
377        value.write_row(
378            &mut w,
379            prop.word as usize,
380            prop.shift as u32,
381            prop.mask,
382            prop.val_word as usize,
383        );
384        if prop.explicit_bit != u8::MAX {
385            w.set_explicit_bit(prop.explicit_bit as u32, prop.field_effects);
386        }
387    }
388
389    /// Sets one string property.
390    #[inline]
391    pub fn set_str<T: NvTable>(&mut self, id: NodeId, prop: StrProp<T>, text: &str) {
392        assert!(self.store.is_live(id), "NodeStore: write to dead node {id:?}");
393        let mut w = writer_at_typed::<T>(self.store, id.node_index());
394        w.put_str(prop.word as usize, text);
395        if prop.explicit_bit != u8::MAX {
396            w.set_explicit_bit(prop.explicit_bit as u32, prop.field_effects);
397        }
398    }
399
400    /// Opens a leak-free temporary resource scope for building nested resources (e.g.
401    /// `ResponsiveRules` / `StateRules` embedding child `BackgroundFillRes` / `GridTracks`).
402    #[inline]
403    pub fn with_temp_resources<R>(&mut self, f: impl FnOnce(&mut TempResources<'_>) -> R) -> R {
404        let mut scope = TempResources::new(self.store);
405        f(&mut scope)
406    }
407
408    /// Sets (interned) or clears one resource property.
409    #[inline]
410    pub fn set_resource<T: NvTable, R: FlatResource>(
411        &mut self,
412        id: NodeId,
413        prop: ResProp<T, R>,
414        value: Option<&R>,
415    ) {
416        assert!(self.store.is_live(id), "NodeStore: write to dead node {id:?}");
417        let mut w = writer_at_typed::<T>(self.store, id.node_index());
418        w.put_resource(prop.word as usize, value);
419        if prop.explicit_bit != u8::MAX {
420            w.set_explicit_bit(prop.explicit_bit as u32, prop.field_effects);
421        }
422    }
423
424    /// Sets (interned) one resource property via a zero-alloc scratch-word closure.
425    #[inline]
426    pub fn set_resource_with<T: NvTable, R: FlatResource>(
427        &mut self,
428        id: NodeId,
429        prop: ResProp<T, R>,
430        write: impl FnOnce(&mut Vec<u32>) -> bool,
431    ) {
432        assert!(self.store.is_live(id), "NodeStore: write to dead node {id:?}");
433        let mut w = writer_at_typed::<T>(self.store, id.node_index());
434        w.put_resource_with::<R>(prop.word as usize, write);
435        if prop.explicit_bit != u8::MAX {
436            w.set_explicit_bit(prop.explicit_bit as u32, prop.field_effects);
437        }
438    }
439
440    /// Points one resource property at a live [`ResourceId`] of type `R` (or `ResourceId::NONE`).
441    /// Returns `false` without mutating if `rid` is stale, dead, or of a mismatched kind/type.
442    #[inline]
443    pub fn set_resource_id<T: NvTable, R: FlatResource>(
444        &mut self,
445        id: NodeId,
446        prop: ResProp<T, R>,
447        rid: ResourceId,
448    ) -> bool {
449        assert!(self.store.is_live(id), "NodeStore: write to dead node {id:?}");
450        // Reject before attaching `T` so an invalid id never realizes the row.
451        if !rid.is_none() && !self.store.resources.is_live_of::<R>(rid) {
452            return false;
453        }
454        let mut w = writer_at_typed::<T>(self.store, id.node_index());
455        if !w.put_resource_id::<R>(prop.word as usize, rid) {
456            return false;
457        }
458        if prop.explicit_bit != u8::MAX {
459            w.set_explicit_bit(prop.explicit_bit as u32, prop.field_effects);
460        }
461        true
462    }
463
464    /// Applies every valid table operation in `patch` onto live node `id`, attaching a touched
465    /// table only when at least one non-metadata op passes word, liveness, and resource-kind
466    /// checks. On `#[nv_table(inherited)]` tables, explicit bits belonging to skipped ops or
467    /// forged/orphan word-0 set bits lacking all accompanying data-word ops are masked out before
468    /// updating word 0 so rejected or unpatched fields never override inherited values.
469    pub fn apply_row_patch(&mut self, id: NodeId, patch: RowPatchView<'_>) {
470        assert!(self.store.is_live(id), "NodeStore: write to dead node {id:?}");
471        for table in patch.tables() {
472            let Some(slot) = crate::table::slot_of(table.key()) else {
473                continue;
474            };
475            let desc = crate::table::desc(slot);
476            let words_len = desc.words().min(nativeview_abi::table::MAX_TABLE_WORDS);
477            let str_mask = desc.str_words | (desc.str_words << 1);
478            let res_mask = desc.resource_words;
479            let inherited = desc.inherited;
480            let has_valid = table.ops().any(|op| {
481                let wi = op.word() as usize;
482                let bit = 1u32 << (wi & 31);
483                if wi >= words_len || (str_mask & bit) != 0 || op.is_resource() != ((res_mask & bit) != 0) {
484                    return false;
485                }
486                if inherited && wi == 0 {
487                    return false;
488                }
489                if !op.is_resource() {
490                    return true;
491                }
492                let rid = ResourceId(op.set_bits());
493                rid.is_none()
494                    || desc
495                        .resource_kind(wi)
496                        .is_some_and(|k| self.store.resources.is_live_with_kind(rid, k))
497            });
498            if !has_valid {
499                continue;
500            }
501            let mut w = writer_at(self.store, id.node_index(), slot);
502            let mut explicit_op: Option<WordOp> = None;
503            let mut skipped_words_mask = 0u32;
504            let mut applied_masks = [0u32; nativeview_abi::table::MAX_TABLE_WORDS];
505            for op in table.ops() {
506                let wi = op.word() as usize;
507                let bit = 1u32 << (wi & 31);
508                if wi >= words_len || (str_mask & bit) != 0 || op.is_resource() != ((res_mask & bit) != 0) {
509                    if wi < words_len {
510                        skipped_words_mask |= bit;
511                    }
512                    continue;
513                }
514                if inherited && wi == 0 {
515                    explicit_op = Some(op);
516                } else if op.is_resource() {
517                    let rid = ResourceId(op.set_bits());
518                    if rid.is_none()
519                        || desc
520                            .resource_kind(wi)
521                            .is_some_and(|k| w.resources.is_live_with_kind(rid, k))
522                    {
523                        w.put_resource_id_wire(wi, rid);
524                        applied_masks[wi] |= op.clear_mask().raw();
525                    } else {
526                        skipped_words_mask |= bit;
527                    }
528                } else {
529                    w.put(wi, 0, op.clear_mask().raw(), op.set_bits());
530                    applied_masks[wi] |= op.clear_mask().raw();
531                }
532            }
533            if let Some(op) = explicit_op {
534                let effective_clear = crate::row::patch::effective_inherited_explicit_clear(
535                    desc,
536                    op,
537                    skipped_words_mask,
538                    &applied_masks,
539                );
540                if effective_clear != 0 {
541                    let effective_set = op.set_bits() & effective_clear;
542                    let merged = WordMask(effective_clear).apply(w.words()[0], effective_set);
543                    w.put_explicit_word(merged);
544                }
545            }
546        }
547    }
548
549    /// Marks an existing row of table `T` on live node `id` as paint-dirty without mutating its
550    /// authored words, so both `ChangeSet::touched` (`effect::PAINT`) and
551    /// `NvTableView::dirty_owners` report it for the current frame (zero steady-state allocations).
552    #[inline]
553    pub fn mark_table_paint_dirty<T: NvTable>(&mut self, id: NodeId) {
554        if !self.store.is_live(id) {
555            return;
556        }
557        let slot = T::slot();
558        let index = id.node_index();
559        let node = &mut self.store.nodes[index];
560        if !node.tables.contains(slot) {
561            return;
562        }
563        let Some(col) = self.store.columns[slot.0 as usize].as_mut() else {
564            return;
565        };
566        let Some(row) = col.find_row(index) else {
567            return;
568        };
569        let was = col.masks[row];
570        col.masks[row] = was | 1;
571        col.dirty.push_if(index, was == 0);
572        touch(node, &mut self.store.touched, index, effect::PAINT);
573    }
574
575    /// Detaches table `T` from `id`, releasing its strings and resources.
576    #[inline]
577    pub fn detach<T: NvTable>(&mut self, id: NodeId) {
578        self.detach_slot(id, T::slot());
579    }
580
581    pub fn detach_slot(&mut self, id: NodeId, slot: TableSlot) {
582        if !self.store.has_slot(id, slot) {
583            return;
584        }
585        self.detach_live_slot(id, slot);
586    }
587
588    /// Fallible crate-private detach for [`crate::wire::WireDecoder`], reserving `touched` and
589    /// `col.detached` before mutating state so hostile `Op::Detach` frames never OOM-abort.
590    pub(crate) fn try_detach_slot(
591        &mut self,
592        id: NodeId,
593        slot: TableSlot,
594    ) -> Result<(), crate::wire::WireError> {
595        if !self.store.has_slot(id, slot) {
596            return Ok(());
597        }
598        let index = id.node_index();
599        let node = &self.store.nodes[index];
600        let created = node.flags & CREATED != 0;
601        let need_touch = usize::from(node.effects == 0);
602        self.store.touched.try_reserve(need_touch)?;
603        if !created && let Some(col) = self.store.columns[slot.0 as usize].as_mut() {
604            col.detached
605                .try_reserve(1)
606                .map_err(|_| crate::wire::WireError::Alloc)?;
607        }
608        self.detach_live_slot(id, slot);
609        Ok(())
610    }
611
612    fn detach_live_slot(&mut self, id: NodeId, slot: TableSlot) {
613        let index = id.node_index();
614        self.release_row(index, slot);
615        let s = &mut *self.store;
616        let fx = s.columns[slot.0 as usize]
617            .as_ref()
618            .map_or(0, |c| c.desc.effects());
619        let node = &mut s.nodes[index];
620        node.tables.remove(slot);
621        let created = node.flags & CREATED != 0;
622        let realize = if s.realization_mask.contains(slot) {
623            effect::REALIZE
624        } else {
625            0
626        };
627        touch(node, &mut s.touched, index, realize | fx);
628        if !created && let Some(col) = s.columns[slot.0 as usize].as_mut() {
629            col.record_detached(id);
630        }
631    }
632
633    pub(crate) fn store_mut(&mut self) -> &mut NodeStore {
634        self.store
635    }
636}