Skip to main content

nativeview_store/table/
field.rs

1//! `TableField`, `ScalarField`, and typed property handles (`Prop`, `StrProp`, `ResProp`).
2
3use core::marker::PhantomData;
4
5use nativeview_abi::table::{FieldKind, OptEncoding, PackKind, ValueSetDesc, Word, NO_VAL_WORD};
6
7use crate::resource::FlatResource;
8use crate::row::{RowRef, RowWriter};
9use crate::table::NvTable;
10use crate::value::{Rgba, WordValue};
11
12/// Marker field type: a UTF-8 string stored as two words `{ offset, len }` in the text arena.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
14pub struct Str;
15
16/// Marker field type: a `ResourceId` word referencing a deduplicated flat-word blob of type `R`.
17pub struct Res<R: FlatResource>(PhantomData<fn() -> R>);
18
19/// Field type metadata consumed by `#[derive(NvTable)]` and compile-time `pack_table`.
20pub trait TableField {
21    const KIND: FieldKind;
22    /// Optionality & bit-encoding discriminator hashed into `TableDesc::schema_hash`.
23    const OPT_ENCODING: OptEncoding;
24    /// Bits occupied in its primary word (`1..=32` for scalar, `1` for wide `Option<T>`, `64` for 64-bit/`Str`).
25    const BITS: u8;
26    /// Word packing layout shape (`Scalar`, `WideOpt`, `Wide64`, `Str`, `Resource`).
27    const PACK_KIND: PackKind;
28    /// Named values the field holds (see [`WordValue::VALUES`]).
29    const VALUES: Option<&'static ValueSetDesc> = None;
30}
31
32/// Uniform read/write/patch codec for scalar, narrow `Option<T: OptWord>`, wide
33/// `Option<f32|u32|i32|Rgba>`, and 64-bit (`u64`/`i64`/`f64`) table fields.
34pub trait ScalarField: TableField + Copy {
35    fn read_row(row: &[Word], word: usize, shift: u32, mask: u32, val_word: usize) -> Self;
36    fn write_row(
37        self,
38        writer: &mut RowWriter<'_>,
39        word: usize,
40        shift: u32,
41        mask: u32,
42        val_word: usize,
43    );
44    /// Emits `(word_idx, clear_mask, set_bits)` masked patch operations for [`crate::RowPatch`].
45    fn encode_patch_ops(
46        self,
47        word: usize,
48        shift: u32,
49        mask: u32,
50        val_word: usize,
51        emit: &mut dyn FnMut(usize, u32, u32),
52    );
53
54    #[inline(always)]
55    fn read_ref(row: RowRef<'_>, word: usize, shift: u32, mask: u32, val_word: usize) -> Self {
56        Self::read_row(row.words(), word, shift, mask, val_word)
57    }
58}
59
60impl<T: WordValue> TableField for T {
61    const KIND: FieldKind = T::KIND;
62    const OPT_ENCODING: OptEncoding = T::OPT_ENCODING;
63    const BITS: u8 = T::BITS;
64    const PACK_KIND: PackKind = PackKind::Scalar;
65    const VALUES: Option<&'static ValueSetDesc> = T::VALUES;
66}
67
68impl<T: WordValue> ScalarField for T {
69    #[inline(always)]
70    fn read_row(row: &[Word], word: usize, shift: u32, mask: u32, _val_word: usize) -> Self {
71        T::from_masked_bits((row[word] & mask) >> shift, mask.count_ones())
72    }
73
74    #[inline(always)]
75    fn write_row(
76        self,
77        writer: &mut RowWriter<'_>,
78        word: usize,
79        shift: u32,
80        mask: u32,
81        _val_word: usize,
82    ) {
83        writer.put(word, shift, mask, self.to_masked_bits(mask.count_ones()));
84    }
85
86    #[inline(always)]
87    fn encode_patch_ops(
88        self,
89        word: usize,
90        shift: u32,
91        mask: u32,
92        _val_word: usize,
93        emit: &mut dyn FnMut(usize, u32, u32),
94    ) {
95        let bits = self.to_masked_bits(mask.count_ones());
96        emit(word, mask, (bits << shift) & mask);
97    }
98}
99
100macro_rules! impl_wide_opt_field {
101    ($($ty:ty),+ $(,)?) => {
102        $(
103            impl TableField for Option<$ty> {
104                const KIND: FieldKind = <$ty as WordValue>::KIND;
105                const OPT_ENCODING: OptEncoding = OptEncoding::WideBit;
106                const BITS: u8 = 1;
107                const PACK_KIND: PackKind = PackKind::WideOpt;
108                const VALUES: Option<&'static ValueSetDesc> = <$ty as WordValue>::VALUES;
109            }
110
111            impl ScalarField for Option<$ty> {
112                #[inline(always)]
113                fn read_row(
114                    row: &[Word],
115                    word: usize,
116                    shift: u32,
117                    _mask: u32,
118                    val_word: usize,
119                ) -> Self {
120                    if (row[word] >> shift) & 1 != 0 {
121                        Some(<$ty as WordValue>::from_bits(row[val_word]))
122                    } else {
123                        None
124                    }
125                }
126
127                #[inline(always)]
128                fn write_row(
129                    self,
130                    writer: &mut RowWriter<'_>,
131                    word: usize,
132                    shift: u32,
133                    mask: u32,
134                    val_word: usize,
135                ) {
136                    let (present, bits) = match self {
137                        Some(v) => (1u32, <$ty as WordValue>::to_bits(v)),
138                        None => (0u32, 0u32),
139                    };
140                    writer.put(word, shift, mask, present);
141                    writer.put(val_word, 0, u32::MAX, bits);
142                }
143
144                #[inline(always)]
145                fn encode_patch_ops(
146                    self,
147                    word: usize,
148                    shift: u32,
149                    mask: u32,
150                    val_word: usize,
151                    emit: &mut dyn FnMut(usize, u32, u32),
152                ) {
153                    let (present, bits) = match self {
154                        Some(v) => (1u32, <$ty as WordValue>::to_bits(v)),
155                        None => (0u32, 0u32),
156                    };
157                    emit(word, mask, (present << shift) & mask);
158                    emit(val_word, u32::MAX, bits);
159                }
160            }
161        )+
162    };
163}
164
165impl_wide_opt_field!(f32, u32, i32, Rgba);
166
167impl TableField for u64 {
168    const KIND: FieldKind = FieldKind::U64;
169    const OPT_ENCODING: OptEncoding = OptEncoding::Required;
170    const BITS: u8 = 64;
171    const PACK_KIND: PackKind = PackKind::Wide64;
172}
173
174impl ScalarField for u64 {
175    #[inline(always)]
176    fn read_row(row: &[Word], word: usize, _shift: u32, _mask: u32, _val_word: usize) -> Self {
177        (row[word] as u64) | ((row[word + 1] as u64) << 32)
178    }
179    #[inline(always)]
180    fn write_row(
181        self,
182        writer: &mut RowWriter<'_>,
183        word: usize,
184        _shift: u32,
185        _mask: u32,
186        _val_word: usize,
187    ) {
188        writer.put(word, 0, u32::MAX, self as u32);
189        writer.put(word + 1, 0, u32::MAX, (self >> 32) as u32);
190    }
191    #[inline(always)]
192    fn encode_patch_ops(
193        self,
194        word: usize,
195        _shift: u32,
196        _mask: u32,
197        _val_word: usize,
198        emit: &mut dyn FnMut(usize, u32, u32),
199    ) {
200        emit(word, u32::MAX, self as u32);
201        emit(word + 1, u32::MAX, (self >> 32) as u32);
202    }
203}
204
205impl TableField for i64 {
206    const KIND: FieldKind = FieldKind::I64;
207    const OPT_ENCODING: OptEncoding = OptEncoding::Required;
208    const BITS: u8 = 64;
209    const PACK_KIND: PackKind = PackKind::Wide64;
210}
211
212impl ScalarField for i64 {
213    #[inline(always)]
214    fn read_row(row: &[Word], word: usize, shift: u32, mask: u32, val_word: usize) -> Self {
215        u64::read_row(row, word, shift, mask, val_word) as i64
216    }
217    #[inline(always)]
218    fn write_row(
219        self,
220        writer: &mut RowWriter<'_>,
221        word: usize,
222        shift: u32,
223        mask: u32,
224        val_word: usize,
225    ) {
226        (self as u64).write_row(writer, word, shift, mask, val_word);
227    }
228    #[inline(always)]
229    fn encode_patch_ops(
230        self,
231        word: usize,
232        shift: u32,
233        mask: u32,
234        val_word: usize,
235        emit: &mut dyn FnMut(usize, u32, u32),
236    ) {
237        (self as u64).encode_patch_ops(word, shift, mask, val_word, emit);
238    }
239}
240
241impl TableField for f64 {
242    const KIND: FieldKind = FieldKind::F64;
243    const OPT_ENCODING: OptEncoding = OptEncoding::Required;
244    const BITS: u8 = 64;
245    const PACK_KIND: PackKind = PackKind::Wide64;
246}
247
248impl ScalarField for f64 {
249    #[inline(always)]
250    fn read_row(row: &[Word], word: usize, shift: u32, mask: u32, val_word: usize) -> Self {
251        f64::from_bits(u64::read_row(row, word, shift, mask, val_word))
252    }
253    #[inline(always)]
254    fn write_row(
255        self,
256        writer: &mut RowWriter<'_>,
257        word: usize,
258        shift: u32,
259        mask: u32,
260        val_word: usize,
261    ) {
262        self.to_bits().write_row(writer, word, shift, mask, val_word);
263    }
264    #[inline(always)]
265    fn encode_patch_ops(
266        self,
267        word: usize,
268        shift: u32,
269        mask: u32,
270        val_word: usize,
271        emit: &mut dyn FnMut(usize, u32, u32),
272    ) {
273        self.to_bits().encode_patch_ops(word, shift, mask, val_word, emit);
274    }
275}
276
277impl TableField for Str {
278    const KIND: FieldKind = FieldKind::Str;
279    const OPT_ENCODING: OptEncoding = OptEncoding::Required;
280    const BITS: u8 = 64;
281    const PACK_KIND: PackKind = PackKind::Str;
282}
283
284impl<R: FlatResource> TableField for Res<R> {
285    const KIND: FieldKind = FieldKind::Resource;
286    const OPT_ENCODING: OptEncoding = OptEncoding::Required;
287    const BITS: u8 = 32;
288    const PACK_KIND: PackKind = PackKind::Resource;
289}
290
291/// Typed handle to a packed scalar or wide-optional field: `tx.set(node, Visual::OPACITY, 0.5)`.
292pub struct Prop<T, V> {
293    pub(crate) word: u8,
294    pub(crate) shift: u8,
295    pub(crate) val_word: u8,
296    pub(crate) explicit_bit: u8,
297    pub(crate) field_effects: u8,
298    pub(crate) mask: u32,
299    _p: PhantomData<fn() -> (T, V)>,
300}
301
302impl<T, V> Clone for Prop<T, V> {
303    fn clone(&self) -> Self {
304        *self
305    }
306}
307impl<T, V> Copy for Prop<T, V> {}
308
309impl<T, V> Prop<T, V> {
310    /// Bitmask in word `0` (`__explicit`) for an `#[nv_table(inherited)]` field, or `0` on
311    /// non-inherited tables.
312    #[inline(always)]
313    pub const fn explicit_mask(self) -> u32 {
314        if self.explicit_bit < 32 {
315            1u32 << self.explicit_bit
316        } else {
317            0
318        }
319    }
320}
321
322impl<T: NvTable, V: ScalarField> Prop<T, V> {
323    /// Constructs a scalar property handle for `T`.
324    ///
325    /// # Safety
326    ///
327    /// `(word, shift, bits)` must address a declared scalar field of `T::DESC` that does not
328    /// overlap any string or resource word.
329    #[doc(hidden)]
330    #[inline(always)]
331    pub const unsafe fn new(word: u8, shift: u8, bits: u8) -> Self {
332        // SAFETY: caller upholds field-offset invariants; NO_VAL_WORD signals non-wide scalar.
333        unsafe { Self::new_wide(word, shift, bits, NO_VAL_WORD) }
334    }
335
336    /// Constructs a scalar or wide-optional property handle for `T`.
337    ///
338    /// # Safety
339    ///
340    /// `(word, shift, bits, val_word)` must address a declared field of `T::DESC` that does not
341    /// overlap any string or resource word.
342    #[doc(hidden)]
343    #[inline(always)]
344    pub const unsafe fn new_wide(word: u8, shift: u8, bits: u8, val_word: u8) -> Self {
345        let mask = if bits >= 32 {
346            u32::MAX
347        } else {
348            ((1u32 << bits) - 1) << shift
349        };
350        Self {
351            word,
352            shift,
353            val_word,
354            explicit_bit: u8::MAX,
355            field_effects: 0,
356            mask,
357            _p: PhantomData,
358        }
359    }
360
361    /// Attaches inherited explicit-bit metadata for `#[nv_table(inherited)]` tables.
362    ///
363    /// # Safety
364    ///
365    /// `T::DESC.inherited` must be `true`, `bit < 32`, word `0` must be the hidden `__explicit`
366    /// bitmask (never a string or resource word), and `field_effects` must equal
367    /// `T::DESC.fields[bit as usize].effects`.
368    #[doc(hidden)]
369    #[inline(always)]
370    pub const unsafe fn with_explicit(mut self, bit: u8, field_effects: u8) -> Self {
371        self.explicit_bit = bit;
372        self.field_effects = field_effects;
373        self
374    }
375
376    #[inline(always)]
377    pub const fn word(self) -> u8 {
378        self.word
379    }
380
381    #[inline(always)]
382    pub const fn shift(self) -> u8 {
383        self.shift
384    }
385
386    #[inline(always)]
387    pub const fn val_word(self) -> u8 {
388        self.val_word
389    }
390
391    #[inline(always)]
392    pub const fn mask(self) -> u32 {
393        self.mask
394    }
395
396    #[inline(always)]
397    pub fn get(self, row: &[Word]) -> V {
398        V::read_row(
399            row,
400            self.word as usize,
401            self.shift as u32,
402            self.mask,
403            self.val_word as usize,
404        )
405    }
406}
407
408/// Typed handle to a string field.
409pub struct StrProp<T> {
410    pub(crate) word: u8,
411    pub(crate) explicit_bit: u8,
412    pub(crate) field_effects: u8,
413    _p: PhantomData<fn() -> T>,
414}
415
416impl<T> Clone for StrProp<T> {
417    fn clone(&self) -> Self {
418        *self
419    }
420}
421impl<T> Copy for StrProp<T> {}
422
423impl<T: NvTable> StrProp<T> {
424    /// Constructs a string property handle for `T`.
425    ///
426    /// # Safety
427    ///
428    /// `word` must have its bit set in `T::DESC.str_words`.
429    #[doc(hidden)]
430    #[inline(always)]
431    pub const unsafe fn new(word: u8) -> Self {
432        Self {
433            word,
434            explicit_bit: u8::MAX,
435            field_effects: 0,
436            _p: PhantomData,
437        }
438    }
439
440    /// Attaches inherited explicit-bit metadata for `#[nv_table(inherited)]` tables.
441    ///
442    /// # Safety
443    ///
444    /// `T::DESC.inherited` must be `true`, `bit < 32`, word `0` must be the hidden `__explicit`
445    /// bitmask (never a string or resource word), and `field_effects` must equal
446    /// `T::DESC.fields[bit as usize].effects`.
447    #[doc(hidden)]
448    #[inline(always)]
449    pub const unsafe fn with_explicit(mut self, bit: u8, field_effects: u8) -> Self {
450        self.explicit_bit = bit;
451        self.field_effects = field_effects;
452        self
453    }
454
455    #[inline(always)]
456    pub const fn word(self) -> u8 {
457        self.word
458    }
459}
460
461/// Typed handle to a resource field.
462pub struct ResProp<T, R> {
463    pub(crate) word: u8,
464    pub(crate) explicit_bit: u8,
465    pub(crate) field_effects: u8,
466    _p: PhantomData<fn() -> (T, R)>,
467}
468
469impl<T, R> Clone for ResProp<T, R> {
470    fn clone(&self) -> Self {
471        *self
472    }
473}
474impl<T, R> Copy for ResProp<T, R> {}
475
476impl<T: NvTable, R: FlatResource> ResProp<T, R> {
477    /// Constructs a resource property handle for `T`.
478    ///
479    /// # Safety
480    ///
481    /// `word` must have its bit set in `T::DESC.resource_words`.
482    #[doc(hidden)]
483    #[inline(always)]
484    pub const unsafe fn new(word: u8) -> Self {
485        Self {
486            word,
487            explicit_bit: u8::MAX,
488            field_effects: 0,
489            _p: PhantomData,
490        }
491    }
492
493    /// Attaches inherited explicit-bit metadata for `#[nv_table(inherited)]` tables.
494    ///
495    /// # Safety
496    ///
497    /// `T::DESC.inherited` must be `true`, `bit < 32`, word `0` must be the hidden `__explicit`
498    /// bitmask (never a string or resource word), and `field_effects` must equal
499    /// `T::DESC.fields[bit as usize].effects`.
500    #[doc(hidden)]
501    #[inline(always)]
502    pub const unsafe fn with_explicit(mut self, bit: u8, field_effects: u8) -> Self {
503        self.explicit_bit = bit;
504        self.field_effects = field_effects;
505        self
506    }
507
508    #[inline(always)]
509    pub const fn word(self) -> u8 {
510        self.word
511    }
512}