Skip to main content

nativeview_store/row/patch/
mod.rs

1//! Table-generic, 4-byte-aligned sparse word-patch format ([`RowPatch`] / [`RowPatchView`]).
2//!
3//! Replaces bespoke hand-maintained patch structs (`StylePatch`) with a single uniform word-level
4//! override representation that works for **every** `#[derive(NvTable)]` table (built-in or 3P
5//! module), preserves packed bitfield siblings via `(clear_mask, set_bits)`, sets inherited
6//! word-0 explicit bits automatically, and tracks embedded `ResourceId` overrides as refcounted
7//! child dependencies in [`crate::ResourceStore`].
8//!
9//! ## Flat Word Layout (`[u32]`, little-endian)
10//!
11//! ```text
12//! words[0] = table_count (0..=MAX_PATCH_TABLES)
13//! For each table (strictly ascending TableKey order):
14//!     table_key_lo: u32
15//!     table_key_hi: u32
16//!     op_count: u32 (1..=MAX_TABLE_WORDS)
17//!     For each op (strictly ascending word_idx < 32):
18//!         word_and_flags: u32  // bits 0..16 = word_idx, bits 16..32 = flags (0=scalar, 1=resource)
19//!         clear_mask: u32      // non-zero; u32::MAX when flags == WORD_OP_RESOURCE
20//!         set_bits: u32        // invariant: (set_bits & !clear_mask) == 0
21//! ```
22
23use nativeview_abi::table::{TableKey, Word, MAX_TABLE_WORDS};
24
25use crate::id::ResourceId;
26use crate::resource::FlatResource;
27use crate::table::{NvTable, Prop, ResProp, ScalarField};
28
29mod view;
30
31#[cfg(test)]
32mod tests;
33pub(crate) use view::effective_inherited_explicit_clear;
34pub use view::{prop_written, RowPatchView, TableOpsIter, TableOpsView, WordOpsIter};
35use view::apply_ops_checked;
36
37/// Maximum distinct tables allowed in a single [`RowPatch`].
38pub const MAX_PATCH_TABLES: usize = 32;
39
40/// Non-zero bitmask of modified bits inside a single `NvTable` word.
41#[repr(transparent)]
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
43pub struct WordMask(pub u32);
44
45impl WordMask {
46    /// Mask selecting all 32 bits of a word.
47    pub const ALL: Self = Self(u32::MAX);
48
49    #[inline(always)]
50    pub const fn raw(self) -> u32 {
51        self.0
52    }
53
54    #[inline(always)]
55    pub const fn apply(self, current: Word, set_bits: Word) -> Word {
56        (current & !self.0) | (set_bits & self.0)
57    }
58}
59
60/// Discriminator distinguishing scalar/bitfield word updates from [`ResourceId`] word updates.
61#[repr(u16)]
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum WordOpKind {
64    Scalar = 0,
65    Resource = 1,
66}
67
68/// Scalar / packed-bitfield word op wire tag.
69pub const WORD_OP_SCALAR: u16 = WordOpKind::Scalar as u16;
70/// `ResourceId` word op wire tag (`clear_mask == WordMask::ALL`; `set_bits` is a `ResourceId`).
71pub const WORD_OP_RESOURCE: u16 = WordOpKind::Resource as u16;
72
73/// One validated masked word update targeting a single word inside an `NvTable` row.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub struct WordOp {
76    word: u8,
77    kind: WordOpKind,
78    clear_mask: WordMask,
79    set_bits: Word,
80}
81
82impl WordOp {
83    /// Constructs a validated scalar/bitfield word op, returning `None` if `word >= MAX_TABLE_WORDS`,
84    /// `clear_mask == 0`, or `(set_bits & !clear_mask) != 0`.
85    #[inline(always)]
86    pub const fn scalar(word: u8, clear_mask: WordMask, set_bits: Word) -> Option<Self> {
87        if (word as usize) >= MAX_TABLE_WORDS
88            || clear_mask.0 == 0
89            || (set_bits & !clear_mask.0) != 0
90        {
91            return None;
92        }
93        Some(Self {
94            word,
95            kind: WordOpKind::Scalar,
96            clear_mask,
97            set_bits,
98        })
99    }
100
101    /// Constructs a validated [`ResourceId`] word op (`clear_mask == WordMask::ALL`).
102    #[inline(always)]
103    pub const fn resource(word: u8, id: ResourceId) -> Option<Self> {
104        if (word as usize) >= MAX_TABLE_WORDS {
105            return None;
106        }
107        Some(Self {
108            word,
109            kind: WordOpKind::Resource,
110            clear_mask: WordMask::ALL,
111            set_bits: id.0,
112        })
113    }
114
115    #[inline(always)]
116    pub(crate) const fn from_validated_raw(
117        word: u8,
118        kind: WordOpKind,
119        clear_mask: WordMask,
120        set_bits: Word,
121    ) -> Self {
122        Self {
123            word,
124            kind,
125            clear_mask,
126            set_bits,
127        }
128    }
129
130    #[inline(always)]
131    pub const fn word(self) -> u8 {
132        self.word
133    }
134
135    #[inline(always)]
136    pub const fn kind(self) -> WordOpKind {
137        self.kind
138    }
139
140    #[inline(always)]
141    pub const fn clear_mask(self) -> WordMask {
142        self.clear_mask
143    }
144
145    #[inline(always)]
146    pub const fn set_bits(self) -> Word {
147        self.set_bits
148    }
149
150    #[inline(always)]
151    pub const fn is_resource(self) -> bool {
152        matches!(self.kind, WordOpKind::Resource)
153    }
154}
155
156#[derive(Debug, Clone, PartialEq, Eq)]
157struct TablePatch {
158    key: TableKey,
159    ops: Vec<WordOp>,
160}
161
162/// Owned, ergonomic table-generic word patch builder that encodes directly into flat `u32` words
163/// and implements [`FlatResource`].
164#[derive(Debug, Clone, Default, PartialEq, Eq)]
165pub struct RowPatch {
166    tables: Vec<TablePatch>,
167}
168
169impl RowPatch {
170    #[inline]
171    pub const fn new() -> Self {
172        Self { tables: Vec::new() }
173    }
174
175    #[inline]
176    pub fn is_empty(&self) -> bool {
177        self.tables.is_empty()
178    }
179
180    #[inline]
181    pub fn table_count(&self) -> usize {
182        self.tables.len()
183    }
184
185    #[inline]
186    pub fn has_table<T: NvTable>(&self) -> bool {
187        self.tables.binary_search_by_key(&T::DESC.key.0, |t| t.key.0).is_ok()
188    }
189
190    #[inline]
191    pub fn clear(&mut self) {
192        self.tables.clear();
193    }
194
195    fn push_raw_op(
196        &mut self,
197        key: TableKey,
198        word: u8,
199        kind: WordOpKind,
200        clear_mask: WordMask,
201        set_bits: Word,
202    ) {
203        debug_assert!((word as usize) < MAX_TABLE_WORDS);
204        debug_assert!(clear_mask.0 != 0);
205        debug_assert_eq!(set_bits & !clear_mask.0, 0);
206
207        let t_idx = match self.tables.binary_search_by_key(&key.0, |t| t.key.0) {
208            Ok(i) => i,
209            Err(i) => {
210                // Allow unbounded in-memory table merges (e.g. combining multiple valid wire
211                // `StateRules`); `write_words` enforces `<= MAX_PATCH_TABLES` fallibly on encode.
212                self.tables.insert(
213                    i,
214                    TablePatch {
215                        key,
216                        ops: Vec::with_capacity(4),
217                    },
218                );
219                i
220            }
221        };
222        let ops = &mut self.tables[t_idx].ops;
223        match ops.binary_search_by_key(&word, |o| o.word) {
224            Ok(oi) => {
225                let existing = &mut ops[oi];
226                existing.kind = kind;
227                existing.clear_mask = WordMask(existing.clear_mask.0 | clear_mask.0);
228                existing.set_bits = clear_mask.apply(existing.set_bits, set_bits);
229            }
230            Err(oi) => {
231                ops.insert(
232                    oi,
233                    WordOp::from_validated_raw(word, kind, clear_mask, set_bits),
234                );
235            }
236        }
237    }
238
239    /// Records a typed scalar, narrow-optional, wide-optional, or 64-bit property override for
240    /// table `T`, coalescing packed sibling fields cleanly and setting word-0's explicit bit on
241    /// `#[nv_table(inherited)]` tables.
242    #[inline]
243    pub fn set<T: NvTable, V: ScalarField>(&mut self, prop: Prop<T, V>, value: V) -> &mut Self {
244        let key = T::DESC.key;
245        value.encode_patch_ops(
246            prop.word as usize,
247            prop.shift as u32,
248            prop.mask,
249            prop.val_word as usize,
250            &mut |w, clear_mask, set_bits| {
251                self.push_raw_op(
252                    key,
253                    w as u8,
254                    WordOpKind::Scalar,
255                    WordMask(clear_mask),
256                    set_bits,
257                );
258            },
259        );
260        if prop.explicit_bit < 32 {
261            let bit = 1u32 << prop.explicit_bit;
262            self.push_raw_op(key, 0, WordOpKind::Scalar, WordMask(bit), bit);
263        }
264        self
265    }
266
267    /// Fluent by-value counterpart to [`Self::set`].
268    #[inline]
269    pub fn with<T: NvTable, V: ScalarField>(mut self, prop: Prop<T, V>, value: V) -> Self {
270        self.set(prop, value);
271        self
272    }
273
274    /// Records a [`ResourceId`] override for a `Res<R>` field of table `T` (marking it as a
275    /// refcounted child resource edge when `id != ResourceId::NONE`).
276    #[inline]
277    pub fn set_res_id<T: NvTable, R: FlatResource>(
278        &mut self,
279        prop: ResProp<T, R>,
280        id: ResourceId,
281    ) -> &mut Self {
282        let key = T::DESC.key;
283        self.push_raw_op(key, prop.word, WordOpKind::Resource, WordMask::ALL, id.0);
284        if prop.explicit_bit < 32 {
285            let bit = 1u32 << prop.explicit_bit;
286            self.push_raw_op(key, 0, WordOpKind::Scalar, WordMask(bit), bit);
287        }
288        self
289    }
290
291    /// Fluent by-value counterpart to [`Self::set_res_id`].
292    #[inline]
293    pub fn with_res_id<T: NvTable, R: FlatResource>(
294        mut self,
295        prop: ResProp<T, R>,
296        id: ResourceId,
297    ) -> Self {
298        self.set_res_id(prop, id);
299        self
300    }
301
302    /// Merges all operations from `other` on top of `self` (last-writer-wins cascade).
303    pub fn merge(&mut self, other: &Self) {
304        for tp in &other.tables {
305            for op in &tp.ops {
306                self.push_raw_op(tp.key, op.word, op.kind, op.clear_mask, op.set_bits);
307            }
308        }
309    }
310
311    /// Merges all operations from a zero-copy [`RowPatchView`] on top of `self`.
312    pub fn merge_view(&mut self, other: RowPatchView<'_>) {
313        for table in other.tables() {
314            let key = table.key();
315            for op in table.ops() {
316                self.push_raw_op(key, op.word(), op.kind(), op.clear_mask(), op.set_bits());
317            }
318        }
319    }
320
321    /// Applies every op targeting table `T` onto `out` (skipping string words and mismatched
322    /// resource/scalar flags). Returns `true` if `T` was present in this patch.
323    pub fn apply_table<T: NvTable>(&self, out: &mut [Word]) -> bool {
324        let Ok(idx) = self.tables.binary_search_by_key(&T::DESC.key.0, |t| t.key.0) else {
325            return false;
326        };
327        apply_ops_checked::<T>(&self.tables[idx].ops, out, None);
328        true
329    }
330
331    /// Applies ops targeting table `T` onto `out` and ORs each op's `clear_mask` into
332    /// `written_masks[w]` so backends (e.g. Web CSS) know exactly which packed bits were patched.
333    pub fn apply_table_with_mask<T: NvTable>(
334        &self,
335        out: &mut [Word],
336        written_masks: &mut [u32],
337    ) -> bool {
338        let Ok(idx) = self.tables.binary_search_by_key(&T::DESC.key.0, |t| t.key.0) else {
339            return false;
340        };
341        apply_ops_checked::<T>(&self.tables[idx].ops, out, Some(written_masks));
342        true
343    }
344
345    /// Reads `prop` if all bits/words belonging to `prop` were set in this patch.
346    pub fn get_prop<T: NvTable, V: ScalarField>(&self, prop: Prop<T, V>) -> Option<V> {
347        let idx = self.tables.binary_search_by_key(&T::DESC.key.0, |t| t.key.0).ok()?;
348        let mut row = [0u32; MAX_TABLE_WORDS];
349        let mut masks = [0u32; MAX_TABLE_WORDS];
350        let n = T::DESC.words();
351        row[..n].copy_from_slice(T::DESC.defaults);
352        apply_ops_checked::<T>(&self.tables[idx].ops, &mut row[..n], Some(&mut masks[..n]));
353        if !prop_written(&masks[..n], prop) {
354            return None;
355        }
356        Some(prop.get(&row[..n]))
357    }
358
359    /// Reads the patched [`ResourceId`] for `prop`, if set in this patch.
360    pub fn get_res_id<T: NvTable, R: FlatResource>(
361        &self,
362        prop: ResProp<T, R>,
363    ) -> Option<ResourceId> {
364        let idx = self.tables.binary_search_by_key(&T::DESC.key.0, |t| t.key.0).ok()?;
365        let oi = self.tables[idx]
366            .ops
367            .binary_search_by_key(&prop.word, |o| o.word)
368            .ok()?;
369        let op = self.tables[idx].ops[oi];
370        op.is_resource().then_some(ResourceId(op.set_bits))
371    }
372
373    /// Visits every non-none [`ResourceId`] referenced by this owned patch.
374    pub fn visit_resources(&self, mut visit: impl FnMut(ResourceId)) {
375        for tp in &self.tables {
376            for op in &tp.ops {
377                if op.is_resource() {
378                    let id = ResourceId(op.set_bits);
379                    if !id.is_none() {
380                        visit(id);
381                    }
382                }
383            }
384        }
385    }
386
387    /// Decodes a [`RowPatchView`] back into an owned [`RowPatch`].
388    pub fn from_view(view: RowPatchView<'_>) -> Self {
389        let mut out = Self::new();
390        out.merge_view(view);
391        out
392    }
393}