Skip to main content

nativeview_store/node/
node_mut.rs

1//! Validated mutable handle ([`NodeMut`]) for zero-check chained edits on a single live node.
2
3use crate::id::{NodeId, NodeIndex, ResourceId};
4use crate::resource::FlatResource;
5use crate::store::{NodeRef, NodeStore};
6use crate::table::{NvTable, Prop, ResProp, ScalarField, StrProp};
7use crate::tx::{writer_at_typed, TxCore};
8
9/// Temporary handles kept inline before spilling to the heap (typical nested resources hold a few).
10const INLINE_TEMPS: usize = 8;
11
12/// Scoped RAII arena for temporary child resources interned while assembling parent resources
13/// (e.g. `BackgroundFillRes` / `GridTracks` referenced inside `StateRules` / `ResponsiveRules`).
14///
15/// Releases every temporary handle automatically on drop so children owned by a newly interned
16/// parent drop cleanly to `refs == 1` and abandoned temporaries are reclaimed at `end_frame`.
17pub struct TempResources<'a> {
18    store: &'a mut NodeStore,
19    /// Inline temporaries in insertion order; free slots hold [`ResourceId::NONE`].
20    inline: [ResourceId; INLINE_TEMPS],
21    spill: Vec<ResourceId>,
22}
23
24impl<'a> TempResources<'a> {
25    #[inline]
26    pub(crate) fn new(store: &'a mut NodeStore) -> Self {
27        Self {
28            store,
29            inline: [ResourceId::NONE; INLINE_TEMPS],
30            spill: Vec::new(),
31        }
32    }
33
34    #[inline]
35    fn track(&mut self, id: ResourceId) {
36        if id.is_none() {
37            return;
38        }
39        match self.inline.iter_mut().find(|slot| slot.is_none()) {
40            Some(slot) => *slot = id,
41            None => self.spill.push(id),
42        }
43    }
44
45    /// Interns `value`, scheduling its temporary handle for automatic release when this scope ends.
46    #[inline]
47    pub fn intern<R: FlatResource>(&mut self, value: &R) -> ResourceId {
48        let id = self.store.resources.intern(value);
49        self.track(id);
50        id
51    }
52
53    /// Interns via a zero-alloc scratch closure, scheduling its temporary handle for release.
54    #[inline]
55    pub fn intern_with<R: FlatResource>(
56        &mut self,
57        write: impl FnOnce(&mut Vec<u32>) -> bool,
58    ) -> ResourceId {
59        let id = self
60            .store
61            .resources
62            .try_intern_with::<R>(write)
63            .unwrap_or(ResourceId::NONE);
64        self.track(id);
65        id
66    }
67
68    /// Reborrows a non-committing [`TxCore`] so callers can attach parent resources referencing
69    /// temporary ids; the frame cannot be closed while temporaries are still retained:
70    ///
71    /// ```compile_fail
72    /// let mut store = nativeview_store::NodeStore::new();
73    /// let mut tx = store.tx();
74    /// tx.with_temp_resources(|scope| {
75    ///     scope.tx().commit_into(&mut nativeview_store::ChangeSet::default());
76    /// });
77    /// ```
78    #[inline]
79    pub fn tx(&mut self) -> TxCore<'_> {
80        TxCore { store: self.store }
81    }
82}
83
84impl Drop for TempResources<'_> {
85    fn drop(&mut self) {
86        while let Some(id) = self.spill.pop() {
87            self.store.resources.release(id);
88        }
89        for &id in self.inline.iter().rev().filter(|id| !id.is_none()) {
90            self.store.resources.release(id);
91        }
92    }
93}
94
95/// Zero-cost validated mutable handle to a single live node (2 registers: `&mut NodeStore` +
96/// `NodeIndex`).
97///
98/// Created via [`Transaction::spawn`] or [`Transaction::node_mut`], validating liveness once so
99/// multiple table edits / property writes on the same node skip repeated checks.
100pub struct NodeMut<'a> {
101    pub(crate) store: &'a mut NodeStore,
102    pub(crate) index: NodeIndex,
103}
104
105impl<'a> NodeMut<'a> {
106    #[inline(always)]
107    pub(crate) fn new(store: &'a mut NodeStore, index: NodeIndex) -> Self {
108        Self { store, index }
109    }
110
111    #[inline(always)]
112    pub fn index(&self) -> NodeIndex {
113        self.index
114    }
115
116    #[inline(always)]
117    pub fn id(&self) -> NodeId {
118        NodeId::from_index(self.index, self.store.nodes[self.index].generation)
119    }
120
121    #[inline(always)]
122    pub fn as_ref(&self) -> NodeRef<'_> {
123        NodeRef::new_unchecked(self.store, self.index)
124    }
125
126    /// Fluent typed writer for `T` on this node (skips repeated liveness/generation checks).
127    #[inline(always)]
128    pub fn edit<T: NvTable>(&mut self) -> T::Mut<'_> {
129        T::from_row_writer(writer_at_typed::<T>(self.store, self.index))
130    }
131
132    /// Attaches `T` with its defaults (no-op if attached).
133    #[inline]
134    pub fn attach<T: NvTable>(&mut self) -> &mut Self {
135        writer_at_typed::<T>(self.store, self.index);
136        self
137    }
138
139    /// Sets one scalar or wide-optional property on this node.
140    #[inline(always)]
141    pub fn set<T: NvTable, V: ScalarField>(&mut self, prop: Prop<T, V>, value: V) -> &mut Self {
142        let mut w = writer_at_typed::<T>(self.store, self.index);
143        value.write_row(
144            &mut w,
145            prop.word as usize,
146            prop.shift as u32,
147            prop.mask,
148            prop.val_word as usize,
149        );
150        if prop.explicit_bit != u8::MAX {
151            w.set_explicit_bit(prop.explicit_bit as u32, prop.field_effects);
152        }
153        self
154    }
155
156    /// Sets one string property on this node.
157    #[inline]
158    pub fn set_str<T: NvTable>(&mut self, prop: StrProp<T>, text: &str) -> &mut Self {
159        let mut w = writer_at_typed::<T>(self.store, self.index);
160        w.put_str(prop.word as usize, text);
161        if prop.explicit_bit != u8::MAX {
162            w.set_explicit_bit(prop.explicit_bit as u32, prop.field_effects);
163        }
164        self
165    }
166
167    /// Sets (interning) or clears one resource property on this node.
168    #[inline]
169    pub fn set_resource<T: NvTable, R: FlatResource>(
170        &mut self,
171        prop: ResProp<T, R>,
172        value: Option<&R>,
173    ) -> &mut Self {
174        let mut w = writer_at_typed::<T>(self.store, self.index);
175        w.put_resource(prop.word as usize, value);
176        if prop.explicit_bit != u8::MAX {
177            w.set_explicit_bit(prop.explicit_bit as u32, prop.field_effects);
178        }
179        self
180    }
181
182    /// Points one resource property on this node at a live [`ResourceId`] of type `R` (or
183    /// `ResourceId::NONE`). Ignores stale, dead, or mismatched-kind ids.
184    #[inline]
185    pub fn set_resource_id<T: NvTable, R: FlatResource>(
186        &mut self,
187        prop: ResProp<T, R>,
188        rid: ResourceId,
189    ) -> &mut Self {
190        // Reject before attaching `T` so an invalid id never realizes the row.
191        if !rid.is_none() && !self.store.resources.is_live_of::<R>(rid) {
192            return self;
193        }
194        let mut w = writer_at_typed::<T>(self.store, self.index);
195        if w.put_resource_id::<R>(prop.word as usize, rid) && prop.explicit_bit != u8::MAX {
196            w.set_explicit_bit(prop.explicit_bit as u32, prop.field_effects);
197        }
198        self
199    }
200
201    /// Replaces this node's ordered child list (zero heap allocations).
202    #[inline]
203    pub fn set_children(&mut self, children: &[NodeId]) -> &mut Self {
204        let id = self.id();
205        TxCore { store: self.store }.set_children(id, children);
206        self
207    }
208
209    /// Detaches table `T` from this node.
210    #[inline]
211    pub fn detach<T: NvTable>(&mut self) -> &mut Self {
212        let id = self.id();
213        TxCore { store: self.store }.detach_slot(id, T::slot());
214        self
215    }
216
217    /// Removes this node and its subtree.
218    #[inline]
219    pub fn remove(self) {
220        let id = self.id();
221        TxCore { store: self.store }.remove(id);
222    }
223}