Skip to main content

nativeview_store/value/
opt.rs

1//! Niche/packed `Option<T>` support (`OptWord`) for sub-word and niche-bearing `WordValue` types.
2//!
3//! Every `OptWord` encoding guarantees that bit pattern `0` represents `None`, so all-zero
4//! default table words decode cleanly to `None` with zero per-field initialization cost.
5
6use core::num::{NonZeroU16, NonZeroU32, NonZeroU8};
7
8use nativeview_abi::table::{FieldKind, OptEncoding, ValueSetDesc};
9use nativeview_abi::SurfaceId;
10
11use super::WordValue;
12use crate::NodeId;
13
14/// A value whose `Option<Self>` packs into `OPT_BITS` (`<= 32`) bits of one row word,
15/// with bit pattern `0` always representing `None`.
16///
17/// `opt_from_bits` must be total: any invalid or out-of-range bit pattern decodes to `None`.
18///
19/// # Compile-time guard examples (with positive controls)
20///
21/// Valid `#[derive(WordEnum)]` (positive control):
22/// ```
23/// use nativeview_store::{OptWord, WordEnum, WordValue};
24/// #[repr(u8)]
25/// #[derive(Clone, Copy, Debug, PartialEq, Eq, Default, WordEnum)]
26/// enum Good { #[default] Off = 0, On = 1 }
27/// assert_eq!(Good::try_from_word(1), Some(Good::On));
28/// assert_eq!(Good::opt_to_word(Some(Good::Off)), 1);
29/// assert_eq!(<Option<Good> as WordValue>::from_bits(0), None);
30/// ```
31///
32/// Rejecting a hand-rolled `Unset` variant:
33/// ```compile_fail
34/// use nativeview_store::WordEnum;
35/// #[repr(u8)]
36/// #[derive(Clone, Copy, WordEnum)]
37/// enum Bad { Unset = 0, On = 1 }
38/// ```
39///
40/// Rejecting non-contiguous discriminants:
41/// ```compile_fail
42/// use nativeview_store::WordEnum;
43/// #[repr(u8)]
44/// #[derive(Clone, Copy, WordEnum)]
45/// enum BadGap { A = 0, B = 2 }
46/// ```
47///
48/// Rejecting data-carrying variants:
49/// ```compile_fail
50/// use nativeview_store::WordEnum;
51/// #[repr(u8)]
52/// #[derive(Clone, Copy, WordEnum)]
53/// enum BadData { A = 0, B(u8) }
54/// ```
55///
56/// Valid resource field via `Res<R>` (positive control):
57/// ```
58/// use nativeview_store::{FlatResource, NvTable, Res, ValidatedWords};
59/// use nativeview_abi::Key64;
60/// struct Blob(Vec<u32>);
61/// impl FlatResource for Blob {
62///     const KIND: Key64 = Key64::of("doctest.blob");
63///     type View<'a> = &'a [u32];
64///     fn write_words(&self, out: &mut Vec<u32>) -> bool { out.extend_from_slice(&self.0); true }
65///     fn validate(_words: &[u32]) -> bool { true }
66///     fn view(words: ValidatedWords<'_, Self>) -> &[u32] { words.as_slice() }
67/// }
68/// #[derive(NvTable)]
69/// #[nv_table(name = "doctest.res_ok", storage = "sparse")]
70/// struct ResOk { #[effect(paint)] blob: Res<Blob> }
71/// let _ = ResOk::KEY;
72/// ```
73///
74/// Valid integer narrowing `#[bits(N)]` (positive control):
75/// ```
76/// use nativeview_store::NvTable;
77/// #[derive(NvTable)]
78/// #[nv_table(name = "doctest.bits_ok", storage = "sparse")]
79/// struct BitsOk {
80///     #[effect(paint)] #[bits(4)] #[default(-3i8)] small_i: i8,
81///     #[effect(paint)] #[bits(6)] #[default(63u8)] small_u: u8,
82/// }
83/// assert_eq!(<BitsOk as NvTable>::DESC.words(), 1);
84/// ```
85///
86/// Exact compile-failure diagnostics (error codes and messages) for raw `ResourceId`, narrowed
87/// default overflow, ill-typed defaults, magic sentinels, split-bool pairs, `WordEnum`, and >32
88/// word tables are snapshot-tested via `trybuild` in `tests/compile_fail_ui.rs`.
89pub trait OptWord: Copy {
90    const OPT_BITS: u8;
91    const OPT_KIND: FieldKind;
92    const OPT_ENCODING: OptEncoding;
93    /// Named values of the inner type (see [`WordValue::VALUES`]).
94    const VALUES: Option<&'static ValueSetDesc> = None;
95    fn opt_to_bits(v: Option<Self>) -> u32;
96    fn opt_from_bits(bits: u32) -> Option<Self>;
97}
98
99impl<T: OptWord> WordValue for Option<T> {
100    const BITS: u8 = T::OPT_BITS;
101    const KIND: FieldKind = T::OPT_KIND;
102    const OPT_ENCODING: OptEncoding = T::OPT_ENCODING;
103    const VALUES: Option<&'static ValueSetDesc> = <T as OptWord>::VALUES;
104
105    #[inline(always)]
106    fn to_bits(self) -> u32 {
107        T::opt_to_bits(self)
108    }
109
110    #[inline(always)]
111    fn from_bits(bits: u32) -> Self {
112        T::opt_from_bits(bits)
113    }
114}
115
116#[doc(hidden)]
117#[inline(always)]
118pub const fn opt_bool_to_word(v: Option<bool>) -> u32 {
119    match v {
120        None => 0,
121        Some(false) => 1,
122        Some(true) => 2,
123    }
124}
125
126#[doc(hidden)]
127#[inline(always)]
128pub const fn opt_u8_to_word(v: Option<u8>) -> u32 {
129    match v {
130        None => 0,
131        Some(x) => ((x as u32) << 1) | 1,
132    }
133}
134
135#[doc(hidden)]
136#[inline(always)]
137pub const fn opt_i8_to_word(v: Option<i8>) -> u32 {
138    match v {
139        None => 0,
140        Some(x) => (((x as u8) as u32) << 1) | 1,
141    }
142}
143
144#[doc(hidden)]
145#[inline(always)]
146pub const fn opt_u16_to_word(v: Option<u16>) -> u32 {
147    match v {
148        None => 0,
149        Some(x) => ((x as u32) << 1) | 1,
150    }
151}
152
153#[doc(hidden)]
154#[inline(always)]
155pub const fn opt_i16_to_word(v: Option<i16>) -> u32 {
156    match v {
157        None => 0,
158        Some(x) => (((x as u16) as u32) << 1) | 1,
159    }
160}
161
162#[doc(hidden)]
163#[inline(always)]
164pub const fn opt_node_to_word(v: Option<NodeId>) -> u32 {
165    match v {
166        Some(id) if !id.is_null() => id.raw(),
167        _ => 0,
168    }
169}
170
171#[doc(hidden)]
172#[inline(always)]
173pub const fn opt_nz_u8_to_word(v: Option<NonZeroU8>) -> u32 {
174    match v {
175        Some(n) => n.get() as u32,
176        None => 0,
177    }
178}
179
180#[doc(hidden)]
181#[inline(always)]
182pub const fn opt_nz_u16_to_word(v: Option<NonZeroU16>) -> u32 {
183    match v {
184        Some(n) => n.get() as u32,
185        None => 0,
186    }
187}
188
189#[doc(hidden)]
190#[inline(always)]
191pub const fn opt_nz_u32_to_word(v: Option<NonZeroU32>) -> u32 {
192    match v {
193        Some(n) => n.get(),
194        None => 0,
195    }
196}
197
198#[doc(hidden)]
199#[inline(always)]
200pub const fn opt_surf_to_word(v: Option<SurfaceId>) -> u32 {
201    match v {
202        Some(id) if !id.is_null() => id.raw(),
203        _ => 0,
204    }
205}
206
207impl OptWord for bool {
208    const OPT_BITS: u8 = 2;
209    const OPT_KIND: FieldKind = FieldKind::Enum;
210    const OPT_ENCODING: OptEncoding = OptEncoding::PlusOne;
211
212    #[inline(always)]
213    fn opt_to_bits(v: Option<Self>) -> u32 {
214        opt_bool_to_word(v)
215    }
216
217    #[inline(always)]
218    fn opt_from_bits(bits: u32) -> Option<Self> {
219        match bits & 0b11 {
220            1 => Some(false),
221            2 => Some(true),
222            _ => None,
223        }
224    }
225}
226
227impl OptWord for u8 {
228    const OPT_BITS: u8 = 9;
229    const OPT_KIND: FieldKind = FieldKind::U32;
230    const OPT_ENCODING: OptEncoding = OptEncoding::Bit0Present;
231
232    #[inline(always)]
233    fn opt_to_bits(v: Option<Self>) -> u32 {
234        opt_u8_to_word(v)
235    }
236
237    #[inline(always)]
238    fn opt_from_bits(bits: u32) -> Option<Self> {
239        if bits & 1 == 0 {
240            None
241        } else {
242            Some((bits >> 1) as u8)
243        }
244    }
245}
246
247impl OptWord for i8 {
248    const OPT_BITS: u8 = 9;
249    const OPT_KIND: FieldKind = FieldKind::I32;
250    const OPT_ENCODING: OptEncoding = OptEncoding::Bit0Present;
251
252    #[inline(always)]
253    fn opt_to_bits(v: Option<Self>) -> u32 {
254        opt_i8_to_word(v)
255    }
256
257    #[inline(always)]
258    fn opt_from_bits(bits: u32) -> Option<Self> {
259        if bits & 1 == 0 {
260            None
261        } else {
262            Some(((bits >> 1) as u8) as i8)
263        }
264    }
265}
266
267impl OptWord for u16 {
268    const OPT_BITS: u8 = 17;
269    const OPT_KIND: FieldKind = FieldKind::U32;
270    const OPT_ENCODING: OptEncoding = OptEncoding::Bit0Present;
271
272    #[inline(always)]
273    fn opt_to_bits(v: Option<Self>) -> u32 {
274        opt_u16_to_word(v)
275    }
276
277    #[inline(always)]
278    fn opt_from_bits(bits: u32) -> Option<Self> {
279        if bits & 1 == 0 {
280            None
281        } else {
282            Some((bits >> 1) as u16)
283        }
284    }
285}
286
287impl OptWord for i16 {
288    const OPT_BITS: u8 = 17;
289    const OPT_KIND: FieldKind = FieldKind::I32;
290    const OPT_ENCODING: OptEncoding = OptEncoding::Bit0Present;
291
292    #[inline(always)]
293    fn opt_to_bits(v: Option<Self>) -> u32 {
294        opt_i16_to_word(v)
295    }
296
297    #[inline(always)]
298    fn opt_from_bits(bits: u32) -> Option<Self> {
299        if bits & 1 == 0 {
300            None
301        } else {
302            Some(((bits >> 1) as u16) as i16)
303        }
304    }
305}
306
307impl OptWord for NodeId {
308    const OPT_BITS: u8 = 32;
309    const OPT_KIND: FieldKind = FieldKind::Node;
310    const OPT_ENCODING: OptEncoding = OptEncoding::ZeroNiche;
311
312    #[inline(always)]
313    fn opt_to_bits(v: Option<Self>) -> u32 {
314        opt_node_to_word(v)
315    }
316
317    #[inline(always)]
318    fn opt_from_bits(bits: u32) -> Option<Self> {
319        NodeId::from_raw(bits)
320    }
321}
322
323impl OptWord for NonZeroU8 {
324    const OPT_BITS: u8 = 8;
325    const OPT_KIND: FieldKind = FieldKind::U32;
326    const OPT_ENCODING: OptEncoding = OptEncoding::ZeroNiche;
327
328    #[inline(always)]
329    fn opt_to_bits(v: Option<Self>) -> u32 {
330        opt_nz_u8_to_word(v)
331    }
332
333    #[inline(always)]
334    fn opt_from_bits(bits: u32) -> Option<Self> {
335        NonZeroU8::new(bits as u8)
336    }
337}
338
339impl OptWord for NonZeroU16 {
340    const OPT_BITS: u8 = 16;
341    const OPT_KIND: FieldKind = FieldKind::U32;
342    const OPT_ENCODING: OptEncoding = OptEncoding::ZeroNiche;
343
344    #[inline(always)]
345    fn opt_to_bits(v: Option<Self>) -> u32 {
346        opt_nz_u16_to_word(v)
347    }
348
349    #[inline(always)]
350    fn opt_from_bits(bits: u32) -> Option<Self> {
351        NonZeroU16::new(bits as u16)
352    }
353}
354
355impl OptWord for NonZeroU32 {
356    const OPT_BITS: u8 = 32;
357    const OPT_KIND: FieldKind = FieldKind::U32;
358    const OPT_ENCODING: OptEncoding = OptEncoding::ZeroNiche;
359
360    #[inline(always)]
361    fn opt_to_bits(v: Option<Self>) -> u32 {
362        opt_nz_u32_to_word(v)
363    }
364
365    #[inline(always)]
366    fn opt_from_bits(bits: u32) -> Option<Self> {
367        NonZeroU32::new(bits)
368    }
369}
370
371impl OptWord for SurfaceId {
372    const OPT_BITS: u8 = 32;
373    const OPT_KIND: FieldKind = FieldKind::U32;
374    const OPT_ENCODING: OptEncoding = OptEncoding::ZeroNiche;
375
376    #[inline(always)]
377    fn opt_to_bits(v: Option<Self>) -> u32 {
378        opt_surf_to_word(v)
379    }
380
381    #[inline(always)]
382    fn opt_from_bits(bits: u32) -> Option<Self> {
383        SurfaceId::from_raw(bits)
384    }
385}
386
387#[cfg(test)]
388mod tests {
389    use super::*;
390
391    #[test]
392    fn opt_word_primitives_roundtrip_and_zero_is_none() {
393        assert_eq!(<Option<bool> as WordValue>::to_bits(None), 0);
394        assert_eq!(<Option<bool> as WordValue>::from_bits(0), None);
395        assert_eq!(<Option<bool> as WordValue>::from_bits(3), None);
396        for b in [false, true] {
397            let bits = Some(b).to_bits();
398            assert_ne!(bits, 0);
399            assert_eq!(<Option<bool> as WordValue>::from_bits(bits), Some(b));
400        }
401
402        for x in [0u8, 1, 127, 255] {
403            let bits = Some(x).to_bits();
404            assert!(bits != 0 && bits < (1 << 9));
405            assert_eq!(<Option<u8> as WordValue>::from_bits(bits), Some(x));
406        }
407        assert_eq!(<Option<u8> as WordValue>::from_bits(0b10), None);
408
409        for x in [i8::MIN, -1, 0, 1, i8::MAX] {
410            let bits = Some(x).to_bits();
411            assert!(bits != 0 && bits < (1 << 9));
412            assert_eq!(<Option<i8> as WordValue>::from_bits(bits), Some(x));
413        }
414
415        for x in [0u16, 1, 128, u16::MAX] {
416            let bits = Some(x).to_bits();
417            assert!(bits != 0 && bits < (1 << 17));
418            assert_eq!(<Option<u16> as WordValue>::from_bits(bits), Some(x));
419        }
420
421        for x in [i16::MIN, -1, 0, 1, i16::MAX] {
422            let bits = Some(x).to_bits();
423            assert!(bits != 0 && bits < (1 << 17));
424            assert_eq!(<Option<i16> as WordValue>::from_bits(bits), Some(x));
425        }
426        assert_eq!(<Option<i16> as WordValue>::from_bits(0), None);
427        assert_eq!(<Option<i16> as WordValue>::from_bits(0xFFFE), None);
428
429        assert_eq!(<Option<NodeId> as WordValue>::from_bits(0), None);
430        assert_eq!(<Option<NodeId> as WordValue>::to_bits(Some(NodeId::NULL)), 0);
431        assert_eq!(
432            <Option<NodeId> as WordValue>::from_bits(Some(NodeId::ROOT).to_bits()),
433            Some(NodeId::ROOT)
434        );
435        assert_eq!(<Option<SurfaceId> as WordValue>::from_bits(0), None);
436        assert_eq!(
437            <Option<SurfaceId> as WordValue>::from_bits(Some(SurfaceId::ROOT).to_bits()),
438            Some(SurfaceId::ROOT)
439        );
440
441        assert_eq!(<Option<NonZeroU8> as WordValue>::from_bits(0), None);
442        assert_eq!(
443            <Option<NonZeroU8> as WordValue>::from_bits(NonZeroU8::new(7).to_bits()),
444            NonZeroU8::new(7)
445        );
446        assert_eq!(<Option<NonZeroU16> as WordValue>::from_bits(0), None);
447        assert_eq!(
448            <Option<NonZeroU16> as WordValue>::from_bits(NonZeroU16::new(3).to_bits()),
449            NonZeroU16::new(3)
450        );
451        assert_eq!(
452            <Option<NonZeroU16> as WordValue>::from_bits(NonZeroU16::new(u16::MAX).to_bits()),
453            NonZeroU16::new(u16::MAX)
454        );
455        assert_eq!(<Option<NonZeroU32> as WordValue>::from_bits(0), None);
456        assert_eq!(
457            <Option<NonZeroU32> as WordValue>::from_bits(NonZeroU32::new(u32::MAX).to_bits()),
458            NonZeroU32::new(u32::MAX)
459        );
460    }
461}