Skip to main content

nativeview_store/row/patch/
view.rs

1//! Zero-copy borrowed views ([`RowPatchView`], [`TableOpsView`]), iterators, [`prop_written`],
2//! and the [`FlatResource`] implementation for [`RowPatch`].
3
4use nativeview_abi::table::{TableKey, Word, MAX_TABLE_WORDS};
5use nativeview_abi::Key64;
6
7use crate::id::ResourceId;
8use crate::resource::FlatResource;
9use crate::resource::ingress::ValidatedWords;
10use crate::table::{NvTable, Prop, ResProp, ScalarField};
11
12use super::{RowPatch, WordMask, WordOp, WordOpKind, MAX_PATCH_TABLES, WORD_OP_RESOURCE};
13
14/// Zero-copy borrowed view over flat `RowPatch` `u32` words.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub struct RowPatchView<'a>(&'a [u32]);
17
18impl<'a> RowPatchView<'a> {
19    pub const EMPTY: Self = Self(&[0]);
20
21    /// Validates `words` via [`RowPatch::validate`] and returns a zero-copy view on success.
22    #[inline]
23    pub fn from_words(words: &'a [u32]) -> Option<Self> {
24        RowPatch::validate(words).then_some(Self(words))
25    }
26
27    #[doc(hidden)]
28    #[inline(always)]
29    pub const fn from_validated_words(words: &'a [u32]) -> Self {
30        Self(words)
31    }
32
33    #[inline(always)]
34    pub const fn raw_words(self) -> &'a [u32] {
35        self.0
36    }
37
38    #[inline(always)]
39    pub const fn table_count(self) -> usize {
40        if self.0.is_empty() {
41            0
42        } else {
43            self.0[0] as usize
44        }
45    }
46
47    #[inline(always)]
48    pub const fn is_empty(self) -> bool {
49        self.table_count() == 0
50    }
51
52    #[inline]
53    pub fn tables(self) -> TableOpsIter<'a> {
54        let count = self.table_count();
55        TableOpsIter {
56            words: if self.0.len() > 1 { &self.0[1..] } else { &[] },
57            pos: 0,
58            remaining: count,
59        }
60    }
61
62    /// Finds the operations for table `key`, if present.
63    #[inline]
64    pub fn table_ops(self, key: TableKey) -> Option<TableOpsView<'a>> {
65        self.tables().find(|t| t.key() == key)
66    }
67
68    #[inline]
69    pub fn has_table<T: NvTable>(self) -> bool {
70        self.table_ops(T::DESC.key).is_some()
71    }
72
73    /// Branchless masked apply onto `out` for table `T`. Returns `true` if `T` was present.
74    #[inline]
75    pub fn apply_table<T: NvTable>(self, out: &mut [Word]) -> bool {
76        let Some(t) = self.table_ops(T::DESC.key) else {
77            return false;
78        };
79        t.apply_checked::<T>(out, None);
80        true
81    }
82
83    /// Masked apply onto `out` for table `T`, also recording every written bit in `written_masks`.
84    #[inline]
85    pub fn apply_table_with_mask<T: NvTable>(
86        self,
87        out: &mut [Word],
88        written_masks: &mut [u32],
89    ) -> bool {
90        let Some(t) = self.table_ops(T::DESC.key) else {
91            return false;
92        };
93        t.apply_checked::<T>(out, Some(written_masks));
94        true
95    }
96
97    /// Reads `prop` directly from this flat view if all its words/bits are patched.
98    pub fn get_prop<T: NvTable, V: ScalarField>(self, prop: Prop<T, V>) -> Option<V> {
99        let t = self.table_ops(T::DESC.key)?;
100        let mut row = [0u32; MAX_TABLE_WORDS];
101        let mut masks = [0u32; MAX_TABLE_WORDS];
102        let n = T::DESC.words();
103        row[..n].copy_from_slice(T::DESC.defaults);
104        t.apply_checked::<T>(&mut row[..n], Some(&mut masks[..n]));
105        if !prop_written(&masks[..n], prop) {
106            return None;
107        }
108        Some(prop.get(&row[..n]))
109    }
110
111    /// Reads the patched [`ResourceId`] for `prop`, if set.
112    pub fn get_res_id<T: NvTable, R: FlatResource>(
113        self,
114        prop: ResProp<T, R>,
115    ) -> Option<ResourceId> {
116        let t = self.table_ops(T::DESC.key)?;
117        t.ops()
118            .find(|op| op.word == prop.word && op.is_resource())
119            .map(|op| ResourceId(op.set_bits))
120    }
121
122    /// Visits every non-none embedded [`ResourceId`] across all tables in this patch.
123    pub fn visit_resources(self, visit: &mut dyn FnMut(ResourceId)) {
124        for t in self.tables() {
125            for op in t.ops() {
126                if op.is_resource() {
127                    let id = ResourceId(op.set_bits);
128                    if !id.is_none() {
129                        visit(id);
130                    }
131                }
132            }
133        }
134    }
135}
136
137/// Zero-copy view of one table's masked word operations inside a [`RowPatchView`].
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub struct TableOpsView<'a> {
140    key: TableKey,
141    op_words: &'a [u32],
142}
143
144impl<'a> TableOpsView<'a> {
145    #[inline(always)]
146    pub const fn key(self) -> TableKey {
147        self.key
148    }
149
150    #[inline(always)]
151    pub const fn len(self) -> usize {
152        self.op_words.len() / 3
153    }
154
155    #[inline(always)]
156    pub const fn is_empty(self) -> bool {
157        self.op_words.is_empty()
158    }
159
160    #[inline]
161    pub fn ops(self) -> WordOpsIter<'a> {
162        WordOpsIter {
163            words: self.op_words,
164            pos: 0,
165        }
166    }
167
168    #[inline]
169    fn apply_checked<T: NvTable>(
170        self,
171        out: &mut [Word],
172        written_masks: Option<&mut [u32]>,
173    ) {
174        apply_ops_iter::<T>(self.ops(), out, written_masks);
175    }
176}
177
178/// Zero-alloc iterator over [`TableOpsView`] sections in a [`RowPatchView`].
179#[derive(Debug, Clone)]
180pub struct TableOpsIter<'a> {
181    words: &'a [u32],
182    pos: usize,
183    remaining: usize,
184}
185
186impl<'a> Iterator for TableOpsIter<'a> {
187    type Item = TableOpsView<'a>;
188
189    #[inline]
190    fn next(&mut self) -> Option<Self::Item> {
191        if self.remaining == 0 {
192            return None;
193        }
194        let key_lo = *self.words.get(self.pos)?;
195        let key_hi = *self.words.get(self.pos + 1)?;
196        let op_count = *self.words.get(self.pos + 2)? as usize;
197        let ops_start = self.pos + 3;
198        let ops_end = ops_start.checked_add(op_count.checked_mul(3)?)?;
199        let op_words = self.words.get(ops_start..ops_end)?;
200        self.pos = ops_end;
201        self.remaining -= 1;
202        Some(TableOpsView {
203            key: Key64::from_halves(key_lo, key_hi),
204            op_words,
205        })
206    }
207}
208
209/// Zero-alloc iterator over [`WordOp`]s inside one [`TableOpsView`].
210#[derive(Debug, Clone)]
211pub struct WordOpsIter<'a> {
212    words: &'a [u32],
213    pos: usize,
214}
215
216impl Iterator for WordOpsIter<'_> {
217    type Item = WordOp;
218
219    #[inline]
220    fn next(&mut self) -> Option<Self::Item> {
221        let wf = *self.words.get(self.pos)?;
222        let clear_mask = WordMask(*self.words.get(self.pos + 1)?);
223        let set_bits = *self.words.get(self.pos + 2)?;
224        self.pos += 3;
225        let word = wf & 0xFFFF;
226        let flags = (wf >> 16) as u16;
227        if word as usize >= MAX_TABLE_WORDS || flags > WORD_OP_RESOURCE {
228            return None;
229        }
230        let kind = if flags == WORD_OP_RESOURCE {
231            WordOpKind::Resource
232        } else {
233            WordOpKind::Scalar
234        };
235        Some(WordOp::from_validated_raw(
236            word as u8,
237            kind,
238            clear_mask,
239            set_bits,
240        ))
241    }
242}
243
244#[inline]
245fn apply_ops_iter<T: NvTable>(
246    ops: impl Iterator<Item = WordOp>,
247    out: &mut [Word],
248    mut written_masks: Option<&mut [u32]>,
249) {
250    let str_mask = T::DESC.str_words | (T::DESC.str_words << 1);
251    let res_mask = T::DESC.resource_words;
252    for op in ops {
253        let w = op.word() as usize;
254        if w >= out.len() || w >= MAX_TABLE_WORDS {
255            continue;
256        }
257        let bit = 1u32 << w;
258        if (str_mask & bit) != 0 {
259            continue;
260        }
261        if op.is_resource() != ((res_mask & bit) != 0) {
262            continue;
263        }
264        out[w] = op.clear_mask().apply(out[w], op.set_bits());
265        if let Some(wm) = written_masks.as_deref_mut()
266            && w < wm.len()
267        {
268            wm[w] |= op.clear_mask().raw();
269        }
270    }
271}
272
273#[inline]
274pub(super) fn apply_ops_checked<T: NvTable>(
275    ops: &[WordOp],
276    out: &mut [Word],
277    written_masks: Option<&mut [u32]>,
278) {
279    apply_ops_iter::<T>(ops.iter().copied(), out, written_masks);
280}
281
282/// Returns `true` iff every word/bit required by `prop` is covered by `written_masks`.
283#[inline]
284pub fn prop_written<T: NvTable, V: ScalarField>(written_masks: &[u32], prop: Prop<T, V>) -> bool {
285    let w = prop.word as usize;
286    if w >= written_masks.len() || (written_masks[w] & prop.mask) != prop.mask {
287        return false;
288    }
289    if prop.val_word != nativeview_abi::table::NO_VAL_WORD {
290        let vw = prop.val_word as usize;
291        return vw < written_masks.len() && written_masks[vw] == u32::MAX;
292    }
293    if V::BITS == 64 {
294        let w1 = w + 1;
295        return w1 < written_masks.len() && written_masks[w1] == u32::MAX;
296    }
297    true
298}
299
300/// Computes the safe word-0 explicit-mask `clear_mask` for an `#[nv_table(inherited)]` patch op,
301/// masking out undeclared bits, any field with a skipped word, and any set bit whose field's
302/// complete bit/word mask was not written in `applied_masks` (mirroring [`prop_written`]).
303pub(crate) fn effective_inherited_explicit_clear(
304    desc: &nativeview_abi::table::TableDesc,
305    op: WordOp,
306    skipped_words_mask: u32,
307    applied_masks: &[u32; MAX_TABLE_WORDS],
308) -> u32 {
309    let words_len = desc.words().min(MAX_TABLE_WORDS);
310    let set_bits = op.set_bits();
311    let field_count = desc.fields.len().min(32);
312    let valid_field_bits = if field_count == 32 {
313        u32::MAX
314    } else {
315        (1u32 << field_count) - 1
316    };
317    let mut masked_explicit_bits = 0u32;
318    for (b, f) in desc.fields.iter().take(32).enumerate() {
319        let fw = usize::from(f.word);
320        let mut field_words = if fw < words_len { 1u32 << fw } else { 0 };
321        if f.val_word != nativeview_abi::table::NO_VAL_WORD {
322            let vw = usize::from(f.val_word);
323            if vw < words_len {
324                field_words |= 1u32 << vw;
325            }
326        }
327        if f.bits == 64 && fw + 1 < words_len {
328            field_words |= 1u32 << (fw + 1);
329        }
330        let explicit_bit = 1u32 << b;
331        let any_skipped = (skipped_words_mask & field_words) != 0;
332        let fully_applied = if f.bits == 64 {
333            fw + 1 < words_len && applied_masks[fw] == u32::MAX && applied_masks[fw + 1] == u32::MAX
334        } else if f.val_word != nativeview_abi::table::NO_VAL_WORD {
335            let vw = usize::from(f.val_word);
336            fw < words_len
337                && vw < words_len
338                && f.shift < 32
339                && (applied_masks[fw] & (1u32 << f.shift)) != 0
340                && applied_masks[vw] == u32::MAX
341        } else if f.bits > 0 && f.bits <= 32 && usize::from(f.shift) + usize::from(f.bits) <= 32 {
342            let field_mask = if f.bits == 32 {
343                u32::MAX
344            } else {
345                ((1u32 << f.bits) - 1) << f.shift
346            };
347            fw < words_len && (applied_masks[fw] & field_mask) == field_mask
348        } else {
349            false
350        };
351        if any_skipped || ((set_bits & explicit_bit) != 0 && !fully_applied) {
352            masked_explicit_bits |= explicit_bit;
353        }
354    }
355    op.clear_mask().raw() & valid_field_bits & !masked_explicit_bits
356}
357
358impl FlatResource for RowPatch {
359    const KIND: Key64 = Key64::of("nv.res.row_patch");
360    type View<'a> = RowPatchView<'a>;
361
362    fn write_words(&self, out: &mut Vec<u32>) -> bool {
363        if self.tables.len() > MAX_PATCH_TABLES {
364            return false;
365        }
366        let mut needed = 1usize;
367        for tp in &self.tables {
368            if tp.ops.is_empty() || tp.ops.len() > MAX_TABLE_WORDS {
369                return false;
370            }
371            needed += 3 + tp.ops.len() * 3;
372        }
373        out.reserve(needed);
374        out.push(self.tables.len() as u32);
375        for tp in &self.tables {
376            out.push(tp.key.lo());
377            out.push(tp.key.hi());
378            out.push(tp.ops.len() as u32);
379            for op in &tp.ops {
380                out.push(u32::from(op.word()) | (u32::from(op.kind() as u16) << 16));
381                out.push(op.clear_mask().raw());
382                out.push(op.set_bits());
383            }
384        }
385        true
386    }
387
388    fn validate(words: &[u32]) -> bool {
389        let Some(&table_count_u32) = words.first() else {
390            return false;
391        };
392        let table_count = table_count_u32 as usize;
393        if table_count > MAX_PATCH_TABLES {
394            return false;
395        }
396        let mut pos = 1usize;
397        let mut prev_key: Option<u64> = None;
398        for _ in 0..table_count {
399            let Some(&key_lo) = words.get(pos) else {
400                return false;
401            };
402            let Some(&key_hi) = words.get(pos + 1) else {
403                return false;
404            };
405            let Some(&op_count_u32) = words.get(pos + 2) else {
406                return false;
407            };
408            let key = Key64::from_halves(key_lo, key_hi).0;
409            if prev_key.is_some_and(|pk| key <= pk) {
410                return false;
411            }
412            prev_key = Some(key);
413            let op_count = op_count_u32 as usize;
414            if op_count == 0 || op_count > MAX_TABLE_WORDS {
415                return false;
416            }
417            pos += 3;
418            let Some(ops_end) = op_count.checked_mul(3).and_then(|n| pos.checked_add(n)) else {
419                return false;
420            };
421            if ops_end > words.len() {
422                return false;
423            }
424            let mut prev_word: Option<u32> = None;
425            for _ in 0..op_count {
426                let wf = words[pos];
427                let clear_mask = words[pos + 1];
428                let set_bits = words[pos + 2];
429                pos += 3;
430                let word_idx = wf & 0xFFFF;
431                let flags = (wf >> 16) as u16;
432                if word_idx as usize >= MAX_TABLE_WORDS
433                    || prev_word.is_some_and(|pw| word_idx <= pw)
434                {
435                    return false;
436                }
437                prev_word = Some(word_idx);
438                if flags > WORD_OP_RESOURCE || clear_mask == 0 || (set_bits & !clear_mask) != 0 {
439                    return false;
440                }
441                if flags == WORD_OP_RESOURCE && clear_mask != u32::MAX {
442                    return false;
443                }
444            }
445        }
446        pos == words.len()
447    }
448
449    #[inline(always)]
450    fn view<'a>(words: ValidatedWords<'a, Self>) -> Self::View<'a> {
451        RowPatchView(words.as_slice())
452    }
453
454    fn child_resources(words: &[u32], visit: &mut dyn FnMut(ResourceId)) {
455        RowPatchView(words).visit_resources(visit);
456    }
457}