Skip to main content

nativeview_store/value/
mod.rs

1//! Values that pack into (part of) one row word, plus `OptWord`, `GridLine`, `Length`, and
2//! `word_flags!`.
3
4mod grid_line;
5mod length;
6mod opt;
7
8use nativeview_abi::table::{FieldKind, OptEncoding, ValueSetDesc};
9use nativeview_abi::SurfaceId;
10
11pub use grid_line::GridLine;
12pub use length::Length;
13pub use opt::{
14    opt_bool_to_word, opt_i16_to_word, opt_i8_to_word, opt_node_to_word, opt_nz_u16_to_word,
15    opt_nz_u32_to_word, opt_nz_u8_to_word, opt_surf_to_word, opt_u16_to_word, opt_u8_to_word,
16    OptWord,
17};
18
19/// A value stored in `BITS` bits of one row word.
20///
21/// `from_bits` must be total: any bit pattern (e.g. from a corrupt wire frame) decodes to some
22/// value (enums fall back to their default variant).
23pub trait WordValue: Copy {
24    const BITS: u8;
25    const KIND: FieldKind;
26    /// Optionality & bit-encoding discriminator hashed into `TableDesc::schema_hash`.
27    const OPT_ENCODING: OptEncoding = OptEncoding::Required;
28    /// Named values (`WordEnum` variants, `word_flags!` bits), mirrored to hosts as
29    /// `NV_<TYPE>_<VALUE>` by codegen so foreign code never hand-copies them.
30    const VALUES: Option<&'static ValueSetDesc> = None;
31    fn to_bits(self) -> u32;
32    fn from_bits(bits: u32) -> Self;
33
34    /// Encodes `self` into a field of `bit_width` (`1..=32`) bits.
35    ///
36    /// For narrowed integer fields (`#[bits(N)]`), debug builds assert that `self` fits in the
37    /// narrowed signed/unsigned range; release builds truncate/wrap modulo `2^bit_width` via the
38    /// caller's branchless bitmask write.
39    #[inline(always)]
40    fn to_masked_bits(self, _bit_width: u32) -> u32 {
41        self.to_bits()
42    }
43
44    /// Decodes `bits` from a field of `bit_width` (`1..=32`) bits (sign-extending narrowed signed
45    /// integers).
46    #[inline(always)]
47    fn from_masked_bits(bits: u32, _bit_width: u32) -> Self {
48        Self::from_bits(bits)
49    }
50}
51
52impl WordValue for f32 {
53    const BITS: u8 = 32;
54    const KIND: FieldKind = FieldKind::F32;
55    #[inline(always)]
56    fn to_bits(self) -> u32 {
57        f32::to_bits(self)
58    }
59    #[inline(always)]
60    fn from_bits(bits: u32) -> Self {
61        f32::from_bits(bits)
62    }
63}
64
65impl WordValue for u32 {
66    const BITS: u8 = 32;
67    const KIND: FieldKind = FieldKind::U32;
68    #[inline(always)]
69    fn to_bits(self) -> u32 {
70        self
71    }
72    #[inline(always)]
73    fn from_bits(bits: u32) -> Self {
74        bits
75    }
76    #[inline(always)]
77    fn to_masked_bits(self, bit_width: u32) -> u32 {
78        debug_assert!((1..=32).contains(&bit_width), "bit_width {bit_width} must be in 1..=32");
79        let w = bit_width.clamp(1, 32);
80        debug_assert!(
81            w >= 32 || self < (1u32 << w),
82            "u32 value {self} overflows #[bits({w})]"
83        );
84        self
85    }
86}
87
88impl WordValue for i32 {
89    const BITS: u8 = 32;
90    const KIND: FieldKind = FieldKind::I32;
91    #[inline(always)]
92    fn to_bits(self) -> u32 {
93        self as u32
94    }
95    #[inline(always)]
96    fn from_bits(bits: u32) -> Self {
97        bits as i32
98    }
99    #[inline(always)]
100    fn to_masked_bits(self, bit_width: u32) -> u32 {
101        debug_assert!((1..=32).contains(&bit_width), "bit_width {bit_width} must be in 1..=32");
102        let w = bit_width.clamp(1, 32);
103        debug_assert!(
104            w >= 32
105                || (i64::from(self) >= -(1i64 << (w - 1))
106                    && i64::from(self) < (1i64 << (w - 1))),
107            "i32 value {self} overflows signed #[bits({w})]"
108        );
109        self as u32
110    }
111    #[inline(always)]
112    fn from_masked_bits(bits: u32, bit_width: u32) -> Self {
113        debug_assert!((1..=32).contains(&bit_width), "bit_width {bit_width} must be in 1..=32");
114        let shift = 32 - bit_width.clamp(1, 32);
115        ((bits << shift) as i32) >> shift
116    }
117}
118
119impl WordValue for bool {
120    const BITS: u8 = 1;
121    const KIND: FieldKind = FieldKind::Bool;
122    #[inline(always)]
123    fn to_bits(self) -> u32 {
124        self as u32
125    }
126    #[inline(always)]
127    fn from_bits(bits: u32) -> Self {
128        bits & 1 != 0
129    }
130}
131
132impl WordValue for u8 {
133    const BITS: u8 = 8;
134    const KIND: FieldKind = FieldKind::U32;
135    #[inline(always)]
136    fn to_bits(self) -> u32 {
137        self as u32
138    }
139    #[inline(always)]
140    fn from_bits(bits: u32) -> Self {
141        bits as u8
142    }
143    #[inline(always)]
144    fn to_masked_bits(self, bit_width: u32) -> u32 {
145        debug_assert!((1..=32).contains(&bit_width), "bit_width {bit_width} must be in 1..=32");
146        let w = bit_width.clamp(1, 32);
147        debug_assert!(
148            w >= 8 || u32::from(self) < (1u32 << w),
149            "u8 value {self} overflows #[bits({w})]"
150        );
151        u32::from(self)
152    }
153}
154
155impl WordValue for i8 {
156    const BITS: u8 = 8;
157    const KIND: FieldKind = FieldKind::I32;
158    #[inline(always)]
159    fn to_bits(self) -> u32 {
160        (self as u8) as u32
161    }
162    #[inline(always)]
163    fn from_bits(bits: u32) -> Self {
164        (bits as u8) as i8
165    }
166    #[inline(always)]
167    fn to_masked_bits(self, bit_width: u32) -> u32 {
168        debug_assert!((1..=32).contains(&bit_width), "bit_width {bit_width} must be in 1..=32");
169        let w = bit_width.clamp(1, 32);
170        debug_assert!(
171            w >= 8
172                || (i32::from(self) >= -(1i32 << (w - 1))
173                    && i32::from(self) < (1i32 << (w - 1))),
174            "i8 value {self} overflows signed #[bits({w})]"
175        );
176        (self as u8) as u32
177    }
178    #[inline(always)]
179    fn from_masked_bits(bits: u32, bit_width: u32) -> Self {
180        debug_assert!((1..=8).contains(&bit_width), "i8 bit_width {bit_width} must be in 1..=8");
181        let shift = 32 - bit_width;
182        (((bits << shift) as i32) >> shift) as i8
183    }
184}
185
186impl WordValue for u16 {
187    const BITS: u8 = 16;
188    const KIND: FieldKind = FieldKind::U32;
189    #[inline(always)]
190    fn to_bits(self) -> u32 {
191        self as u32
192    }
193    #[inline(always)]
194    fn from_bits(bits: u32) -> Self {
195        bits as u16
196    }
197    #[inline(always)]
198    fn to_masked_bits(self, bit_width: u32) -> u32 {
199        debug_assert!((1..=32).contains(&bit_width), "bit_width {bit_width} must be in 1..=32");
200        let w = bit_width.clamp(1, 32);
201        debug_assert!(
202            w >= 16 || u32::from(self) < (1u32 << w),
203            "u16 value {self} overflows #[bits({w})]"
204        );
205        u32::from(self)
206    }
207}
208
209impl WordValue for i16 {
210    const BITS: u8 = 16;
211    const KIND: FieldKind = FieldKind::I32;
212    #[inline(always)]
213    fn to_bits(self) -> u32 {
214        (self as u16) as u32
215    }
216    #[inline(always)]
217    fn from_bits(bits: u32) -> Self {
218        (bits as u16) as i16
219    }
220    #[inline(always)]
221    fn to_masked_bits(self, bit_width: u32) -> u32 {
222        debug_assert!((1..=32).contains(&bit_width), "bit_width {bit_width} must be in 1..=32");
223        let w = bit_width.clamp(1, 32);
224        debug_assert!(
225            w >= 16
226                || (i32::from(self) >= -(1i32 << (w - 1))
227                    && i32::from(self) < (1i32 << (w - 1))),
228            "i16 value {self} overflows signed #[bits({w})]"
229        );
230        (self as u16) as u32
231    }
232    #[inline(always)]
233    fn from_masked_bits(bits: u32, bit_width: u32) -> Self {
234        debug_assert!((1..=16).contains(&bit_width), "i16 bit_width {bit_width} must be in 1..=16");
235        let shift = 32 - bit_width;
236        (((bits << shift) as i32) >> shift) as i16
237    }
238}
239
240impl WordValue for crate::NodeId {
241    const BITS: u8 = 32;
242    const KIND: FieldKind = FieldKind::Node;
243    #[inline(always)]
244    fn to_bits(self) -> u32 {
245        self.raw()
246    }
247    #[inline(always)]
248    fn from_bits(bits: u32) -> Self {
249        Self::from_raw_or_null(bits)
250    }
251}
252
253impl WordValue for SurfaceId {
254    const BITS: u8 = 32;
255    const KIND: FieldKind = FieldKind::U32;
256    #[inline(always)]
257    fn to_bits(self) -> u32 {
258        self.raw()
259    }
260    #[inline(always)]
261    fn from_bits(bits: u32) -> Self {
262        Self::from_raw(bits).unwrap_or(Self::NULL)
263    }
264}
265
266macro_rules! impl_abi_word_enum {
267    ($ty:path, opt_bits = $opt_bits:expr) => {
268        impl WordValue for $ty {
269            const BITS: u8 = Self::BITS;
270            const KIND: FieldKind = FieldKind::Enum;
271            const VALUES: Option<&'static ValueSetDesc> = Some(&Self::VALUE_SET);
272
273            #[inline(always)]
274            fn to_bits(self) -> u32 {
275                self.to_word()
276            }
277
278            #[inline(always)]
279            fn from_bits(bits: u32) -> Self {
280                Self::try_from_word(bits).unwrap_or_default()
281            }
282        }
283
284        impl OptWord for $ty {
285            const OPT_BITS: u8 = $opt_bits;
286            const OPT_KIND: FieldKind = FieldKind::Enum;
287            const OPT_ENCODING: OptEncoding = OptEncoding::PlusOne;
288            const VALUES: Option<&'static ValueSetDesc> = Some(&Self::VALUE_SET);
289
290            #[inline(always)]
291            fn opt_to_bits(v: Option<Self>) -> u32 {
292                Self::opt_to_word(v)
293            }
294
295            #[inline(always)]
296            fn opt_from_bits(bits: u32) -> Option<Self> {
297                Self::try_from_word(bits.wrapping_sub(1))
298            }
299        }
300    };
301}
302
303impl_abi_word_enum!(nativeview_abi::FlexDirection, opt_bits = 3);
304
305impl<E: nativeview_abi::EventEnum> WordValue for nativeview_abi::EventSet<E> {
306    const BITS: u8 = 32;
307    const KIND: FieldKind = FieldKind::U32;
308    #[inline(always)]
309    fn to_bits(self) -> u32 {
310        self.raw()
311    }
312    #[inline(always)]
313    fn from_bits(bits: u32) -> Self {
314        Self::from_raw(bits)
315    }
316}
317
318/// Packed `RGBA8888` color (`r | g<<8 | b<<16 | a<<24`).
319#[repr(transparent)]
320#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
321pub struct Rgba(pub u32);
322
323impl Rgba {
324    pub const TRANSPARENT: Self = Self(0);
325    pub const BLACK: Self = Self::rgb(0, 0, 0);
326    pub const WHITE: Self = Self::rgb(255, 255, 255);
327
328    #[inline(always)]
329    pub const fn new(r: u8, g: u8, b: u8, a: u8) -> Self {
330        Self(u32::from_le_bytes([r, g, b, a]))
331    }
332    #[inline(always)]
333    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
334        Self::new(r, g, b, 255)
335    }
336    #[inline(always)]
337    pub const fn r(self) -> u8 {
338        self.0 as u8
339    }
340    #[inline(always)]
341    pub const fn g(self) -> u8 {
342        (self.0 >> 8) as u8
343    }
344    #[inline(always)]
345    pub const fn b(self) -> u8 {
346        (self.0 >> 16) as u8
347    }
348    #[inline(always)]
349    pub const fn a(self) -> u8 {
350        (self.0 >> 24) as u8
351    }
352    #[inline(always)]
353    pub const fn with_alpha(self, a: u8) -> Self {
354        Self(self.0 & 0x00FF_FFFF | (a as u32) << 24)
355    }
356    #[inline(always)]
357    pub const fn to_word(self) -> u32 {
358        self.0
359    }
360}
361
362/// Both pack `r | g << 8 | b << 16 | a << 24`: theme / style colors become table words for free.
363impl From<nativeview_abi::ColorRgba> for Rgba {
364    #[inline(always)]
365    fn from(c: nativeview_abi::ColorRgba) -> Self {
366        Self(c.to_u32())
367    }
368}
369
370impl From<Rgba> for nativeview_abi::ColorRgba {
371    #[inline(always)]
372    fn from(c: Rgba) -> Self {
373        Self::from_u32(c.0)
374    }
375}
376
377impl WordValue for Rgba {
378    const BITS: u8 = 32;
379    const KIND: FieldKind = FieldKind::Color;
380    #[inline(always)]
381    fn to_bits(self) -> u32 {
382        self.0
383    }
384    #[inline(always)]
385    fn from_bits(bits: u32) -> Self {
386        Self(bits)
387    }
388}
389
390/// Computes the minimum bit width needed to pack a bitmask `all_mask` (minimum 1 bit).
391#[doc(hidden)]
392pub const fn bitflags_width(all_mask: u32) -> u8 {
393    if all_mask == 0 {
394        1
395    } else {
396        (u32::BITS - all_mask.leading_zeros()) as u8
397    }
398}
399
400/// Declares a packed `#[repr(transparent)]` bitflags type backed by `u8` / `u16` / `u32` that
401/// wraps `nativeview_abi::define_bitflags!` and automatically implements `Default`, [`WordValue`], and
402/// (for `u8`/`u16`) [`OptWord`] with exact compile-time bit widths.
403#[macro_export]
404macro_rules! word_flags {
405    (
406        $(#[$meta:meta])*
407        $vis:vis struct $name:ident(u8) {
408            $(
409                $(#[$flag_meta:meta])*
410                const $flag:ident = $val:expr;
411            )*
412        }
413    ) => {
414        $crate::__private::define_bitflags! {
415            $(#[$meta])*
416            #[derive(Default)]
417            $vis struct $name(u8) {
418                $(
419                    $(#[$flag_meta])*
420                    const $flag = $val;
421                )*
422            }
423        }
424        $crate::__word_flags_impl!($name, u8, opt);
425        $crate::__word_flags_values!($name; $($flag),*);
426    };
427    (
428        $(#[$meta:meta])*
429        $vis:vis struct $name:ident(u16) {
430            $(
431                $(#[$flag_meta:meta])*
432                const $flag:ident = $val:expr;
433            )*
434        }
435    ) => {
436        $crate::__private::define_bitflags! {
437            $(#[$meta])*
438            #[derive(Default)]
439            $vis struct $name(u16) {
440                $(
441                    $(#[$flag_meta])*
442                    const $flag = $val;
443                )*
444            }
445        }
446        $crate::__word_flags_impl!($name, u16, opt);
447        $crate::__word_flags_values!($name; $($flag),*);
448    };
449    (
450        $(#[$meta:meta])*
451        $vis:vis struct $name:ident(u32) {
452            $(
453                $(#[$flag_meta:meta])*
454                const $flag:ident = $val:expr;
455            )*
456        }
457    ) => {
458        $crate::__private::define_bitflags! {
459            $(#[$meta])*
460            #[derive(Default)]
461            $vis struct $name(u32) {
462                $(
463                    $(#[$flag_meta])*
464                    const $flag = $val;
465                )*
466            }
467        }
468        $crate::__word_flags_impl!($name, u32, wide);
469        $crate::__word_flags_values!($name; $($flag),*);
470    };
471}
472
473#[doc(hidden)]
474#[macro_export]
475macro_rules! __word_flags_values {
476    ($name:ident; $($flag:ident),*) => {
477        impl $name {
478            /// Named flag bits mirrored to hosts as `NV_<TYPE>_<FLAG>` masks.
479            pub const VALUE_SET: $crate::__private::ValueSetDesc = $crate::__private::ValueSetDesc {
480                name: stringify!($name),
481                flags: true,
482                values: &[$((stringify!($flag), Self::$flag.bits() as u32)),*],
483            };
484        }
485    };
486}
487
488#[doc(hidden)]
489#[macro_export]
490macro_rules! __word_flags_impl {
491    ($name:ident, $repr:ty, opt) => {
492        $crate::__word_flags_impl!($name, $repr, wide);
493
494        #[allow(dead_code)]
495        impl $name {
496            #[inline(always)]
497            pub const fn opt_to_word(v: ::core::option::Option<Self>) -> u32 {
498                match v {
499                    ::core::option::Option::None => 0,
500                    ::core::option::Option::Some(f) => {
501                        (((f.bits() & Self::ALL.bits()) as u32) << 1) | 1
502                    }
503                }
504            }
505        }
506
507        impl $crate::OptWord for $name {
508            const OPT_BITS: u8 = <Self as $crate::WordValue>::BITS + 1;
509            const OPT_KIND: $crate::__private::FieldKind = $crate::__private::FieldKind::U32;
510            const OPT_ENCODING: $crate::__private::OptEncoding =
511                $crate::__private::OptEncoding::Bit0Present;
512            const VALUES: ::core::option::Option<&'static $crate::__private::ValueSetDesc> =
513                ::core::option::Option::Some(&Self::VALUE_SET);
514
515            #[inline(always)]
516            fn opt_to_bits(v: ::core::option::Option<Self>) -> u32 {
517                Self::opt_to_word(v)
518            }
519
520            #[inline(always)]
521            fn opt_from_bits(bits: u32) -> ::core::option::Option<Self> {
522                if bits & 1 == 0 {
523                    ::core::option::Option::None
524                } else {
525                    ::core::option::Option::Some(Self::from_bits_truncate((bits >> 1) as $repr))
526                }
527            }
528        }
529    };
530    ($name:ident, $repr:ty, wide) => {
531        #[allow(dead_code)]
532        impl $name {
533            pub const BITS: u8 = $crate::__private::bitflags_width(Self::ALL.bits() as u32);
534
535            #[inline(always)]
536            pub const fn to_word(self) -> u32 {
537                (self.bits() as u32) & (Self::ALL.bits() as u32)
538            }
539
540            #[inline(always)]
541            pub const fn from_word(bits: u32) -> Self {
542                Self::from_bits_truncate(bits as $repr)
543            }
544        }
545
546        impl $crate::WordValue for $name {
547            const BITS: u8 = Self::BITS;
548            const KIND: $crate::__private::FieldKind = $crate::__private::FieldKind::U32;
549            const VALUES: ::core::option::Option<&'static $crate::__private::ValueSetDesc> =
550                ::core::option::Option::Some(&Self::VALUE_SET);
551
552            #[inline(always)]
553            fn to_bits(self) -> u32 {
554                self.to_word()
555            }
556
557            #[inline(always)]
558            fn from_bits(bits: u32) -> Self {
559                Self::from_bits_truncate(bits as $repr)
560            }
561        }
562    };
563}
564
565#[cfg(test)]
566mod tests {
567    use super::*;
568    use crate::WordEnum;
569
570    #[repr(u8)]
571    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, WordEnum)]
572    enum Dir {
573        #[default]
574        Column = 0,
575        Row = 1,
576        ColumnReverse = 2,
577        RowReverse = 3,
578    }
579
580    word_flags! {
581        struct Deco(u8) {
582            const UNDERLINE = 1 << 0;
583            const OVERLINE = 1 << 1;
584            const LINE_THROUGH = 1 << 2;
585        }
586    }
587
588    word_flags! {
589        struct SparseFlags(u8) {
590            const A = 1 << 0;
591            const C = 1 << 2;
592        }
593    }
594
595    #[test]
596    fn word_enum_and_word_flags_are_total_and_const() {
597        const W: u32 = Dir::RowReverse.to_word();
598        assert_eq!(W, 3);
599        assert_eq!(Dir::COUNT, 4);
600        assert_eq!(Dir::BITS, 2);
601        assert_eq!(<Option<Dir> as WordValue>::BITS, 3);
602        assert_eq!(Dir::try_from_word(1), Some(Dir::Row));
603        assert_eq!(Dir::try_from_word(4), None);
604        assert_eq!(Dir::from_bits(1), Dir::Row);
605        assert_eq!(Dir::from_bits(9), Dir::Column);
606        assert_eq!(Dir::default(), Dir::Column);
607
608        assert_eq!(<Option<Dir> as WordValue>::from_bits(0), None);
609        for &d in Dir::ALL {
610            let bits = Some(d).to_bits();
611            assert_eq!(bits, Dir::opt_to_word(Some(d)));
612            assert_ne!(bits, 0);
613            assert_eq!(<Option<Dir> as WordValue>::from_bits(bits), Some(d));
614        }
615        assert_eq!(<Option<Dir> as WordValue>::from_bits(7), None);
616
617        assert_eq!(Deco::BITS, 3);
618        assert_eq!(<Option<Deco> as WordValue>::BITS, 4);
619        let d = Deco::UNDERLINE | Deco::LINE_THROUGH;
620        assert_eq!(Deco::from_bits(d.to_bits()), d);
621        assert_eq!(Deco::from_bits(0xFF), Deco::ALL);
622        assert_eq!(<Option<Deco> as WordValue>::from_bits(0), None);
623        assert_eq!(
624            <Option<Deco> as WordValue>::from_bits(Some(Deco::NONE).to_bits()),
625            Some(Deco::NONE)
626        );
627        assert_eq!(
628            <Option<Deco> as WordValue>::from_bits(Some(d).to_bits()),
629            Some(d)
630        );
631
632        // Sparse flags must mask undeclared/reserved bits in both `to_word` and `opt_to_word`.
633        let dirty = SparseFlags::from_bits_retain(0xFF);
634        assert_eq!(dirty.to_word(), 0b101);
635        assert_eq!(dirty.to_bits(), 0b101);
636        assert_eq!(SparseFlags::opt_to_word(Some(dirty)), (0b101 << 1) | 1);
637        assert_eq!(Some(dirty).to_bits(), (0b101 << 1) | 1);
638        assert_eq!(
639            <Option<SparseFlags> as WordValue>::from_bits(Some(dirty).to_bits()),
640            Some(SparseFlags::A | SparseFlags::C)
641        );
642    }
643
644    #[test]
645    fn rgba_channels() {
646        let c = Rgba::new(1, 2, 3, 4);
647        assert_eq!((c.r(), c.g(), c.b(), c.a()), (1, 2, 3, 4));
648        assert_eq!(c.with_alpha(9).a(), 9);
649    }
650}