Skip to main content

nativeview_abi/
id.rs

1//! Strongly typed `#[repr(transparent)]` ABI handles and scalar unit newtypes shared across
2//! `nativeview-abi`, `nativeview-store`, `nativeview-engine`, `nativeview-interop`, backends, modules, and C/foreign hosts.
3//!
4//! Every handle has the exact size, alignment, and register calling convention of its underlying
5//! primitive (`u8`/`u16`/`u32`/`i32`/`u64`) while preventing accidental mixing of domain spaces
6//! (`NodeId` vs `SurfaceId` vs `NodeIndex` vs `FrameId` vs `DurationUs`) at compile time.
7
8use core::fmt;
9use core::mem::{align_of, size_of};
10use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign};
11
12use nativeview_abi_macros::NvAbi;
13use nativeview_codec::{ByteReader, ByteSink, CodecError, NvCodec, NvDecode, NvEncode};
14
15/// Dense slot index into `NodeStore`'s node table (`0` is reserved for null).
16///
17/// Distinct from [`NodeId`] (`index:24 | generation:8`) so internal slot-index lists cannot be
18/// accidentally mixed with generational `NodeId`s at compile time.
19#[repr(transparent)]
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, NvCodec)]
21#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
22#[cfg_attr(feature = "serde", serde(transparent))]
23pub struct NodeIndex(pub u32);
24
25impl NodeIndex {
26    pub const NULL: Self = Self(0);
27    pub const ROOT: Self = Self(1);
28
29    #[inline(always)]
30    pub const fn as_usize(self) -> usize {
31        self.0 as usize
32    }
33
34    #[inline(always)]
35    pub const fn raw(self) -> u32 {
36        self.0
37    }
38}
39
40impl fmt::Display for NodeIndex {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        write!(f, "{}", self.0)
43    }
44}
45
46/// Shared generational handle (`index: 24 | generation: 8`) implementation sealing the canonical
47/// null invariant (`x.is_null() <=> x == Self::NULL`) across constructors, `NvCodec`, and `serde`.
48macro_rules! impl_generational_handle {
49    ($name:ident, $label:literal, $root_doc:literal) => {
50        impl $name {
51            pub const NULL: Self = Self(0);
52            #[doc = $root_doc]
53            pub const ROOT: Self = Self(1);
54            pub const INDEX_BITS: u32 = 24;
55            pub const MAX_INDEX: u32 = (1 << Self::INDEX_BITS) - 1;
56
57            /// Constructs a handle from a 24-bit slot index and 8-bit generation.
58            ///
59            /// Debug-asserts `index <= MAX_INDEX`. Both index `0` and out-of-range indices
60            /// (`> MAX_INDEX`) canonicalize to [`Self::NULL`] in release builds (never wrapping
61            /// to a live slot such as [`Self::ROOT`]); for explicit validation use
62            /// [`Self::try_new`] or [`Self::from_raw`].
63            #[inline(always)]
64            pub const fn new(index: u32, generation: u8) -> Self {
65                debug_assert!(
66                    index <= Self::MAX_INDEX,
67                    concat!(stringify!($name), " index exceeds 24-bit MAX_INDEX")
68                );
69                if index == 0 || index > Self::MAX_INDEX {
70                    Self::NULL
71                } else {
72                    Self(((generation as u32) << Self::INDEX_BITS) | index)
73                }
74            }
75
76            /// Fallible constructor rejecting null index `0` and any index `> MAX_INDEX`.
77            #[inline(always)]
78            pub const fn try_new(index: u32, generation: u8) -> Option<Self> {
79                if index == 0 || index > Self::MAX_INDEX {
80                    None
81                } else {
82                    Some(Self(((generation as u32) << Self::INDEX_BITS) | index))
83                }
84            }
85
86            /// Decodes a raw `u32` at FFI/wire ingress, rejecting any handle whose 24-bit index is `0`
87            /// (both `0` and non-zero generations paired with index `0`).
88            #[inline(always)]
89            pub const fn from_raw(raw: u32) -> Option<Self> {
90                if (raw & Self::MAX_INDEX) == 0 {
91                    None
92                } else {
93                    Some(Self(raw))
94                }
95            }
96
97            /// Decodes a nullable raw `u32` at FFI/wire ingress, canonicalizing any index-`0` value
98            /// to [`Self::NULL`].
99            #[inline(always)]
100            pub const fn from_raw_or_null(raw: u32) -> Self {
101                if (raw & Self::MAX_INDEX) == 0 {
102                    Self::NULL
103                } else {
104                    Self(raw)
105                }
106            }
107
108            #[inline(always)]
109            pub const fn index(self) -> usize {
110                (self.0 & Self::MAX_INDEX) as usize
111            }
112
113            #[inline(always)]
114            pub const fn index_u32(self) -> u32 {
115                self.0 & Self::MAX_INDEX
116            }
117
118            #[inline(always)]
119            pub const fn generation(self) -> u8 {
120                (self.0 >> Self::INDEX_BITS) as u8
121            }
122
123            /// Returns `true` when the 24-bit slot index is `0`.
124            #[inline(always)]
125            pub const fn is_null(self) -> bool {
126                self.index_u32() == 0
127            }
128
129            #[inline(always)]
130            pub const fn raw(self) -> u32 {
131                self.0
132            }
133        }
134
135        impl fmt::Display for $name {
136            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137                if self.is_null() {
138                    f.write_str(concat!($label, "(null)"))
139                } else {
140                    write!(f, concat!($label, "({},{})"), self.index_u32(), self.generation())
141                }
142            }
143        }
144
145        impl NvEncode for $name {
146            #[inline]
147            fn encode<W: ByteSink + ?Sized>(&self, w: &mut W) -> Result<(), CodecError> {
148                w.put_u32(self.0)
149            }
150        }
151
152        impl NvDecode for $name {
153            const MIN_ENCODED_BYTES: usize = 4;
154
155            #[inline]
156            fn decode(r: &mut ByteReader<'_>) -> Result<Self, CodecError> {
157                Ok(Self::from_raw_or_null(r.read_u32()?))
158            }
159        }
160
161        #[cfg(feature = "serde")]
162        impl serde::Serialize for $name {
163            #[inline]
164            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
165                self.0.serialize(serializer)
166            }
167        }
168
169        #[cfg(feature = "serde")]
170        impl<'de> serde::Deserialize<'de> for $name {
171            #[inline]
172            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
173                u32::deserialize(deserializer).map(Self::from_raw_or_null)
174            }
175        }
176    };
177}
178
179/// Generational node identity: `index: 24 | generation: 8`. Raw `0` is [`NodeId::NULL`].
180///
181/// Indices are recycled only at frame boundaries; the 8-bit generation catches stale IDs across
182/// frames without hash maps or heap allocations.
183#[repr(transparent)]
184#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, NvAbi)]
185#[nativeview_abi(name = "NvNodeId")]
186pub struct NodeId(u32);
187
188impl_generational_handle!(
189    NodeId,
190    "node",
191    "Reserved root node of every surface (index `1`, generation `0`)."
192);
193
194impl NodeId {
195    #[inline(always)]
196    pub const fn from_index(index: NodeIndex, generation: u8) -> Self {
197        Self::new(index.0, generation)
198    }
199
200    #[inline(always)]
201    pub const fn node_index(self) -> NodeIndex {
202        NodeIndex(self.0 & Self::MAX_INDEX)
203    }
204}
205
206nativeview_abi_macros::abi_consts! {
207    pub(crate) const ID_ABI_CONSTS;
208
209    /// Reserved root node ID for every surface (`NodeId::ROOT`).
210    #[nativeview_abi(name = "NV_ROOT_NODE_ID")]
211    pub const ROOT_NODE_ID: NodeId = NodeId::ROOT;
212}
213
214/// Generational surface identity: `index: 24 | generation: 8`. Raw `0` is [`SurfaceId::NULL`].
215///
216/// `SurfaceId` is `#[repr(transparent)]` over a plain `u32` (never `NonZeroU32`), so zero-initialized
217/// `extern "C"` POD structs never trigger UB; FFI/wire ingress reads canonicalize any index-`0`
218/// bit pattern to [`SurfaceId::NULL`] via [`Self::from_raw_or_null`].
219#[repr(transparent)]
220#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, NvAbi)]
221#[nativeview_abi(name = "NvSurfaceId")]
222pub struct SurfaceId(u32);
223
224impl_generational_handle!(
225    SurfaceId,
226    "surface",
227    "Conventional first surface (index `1`, generation `0`)."
228);
229
230/// Monotonic 64-bit frame identifier.
231#[repr(transparent)]
232#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, NvCodec, NvAbi)]
233#[nativeview_abi(name = "NvFrameId")]
234#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
235#[cfg_attr(feature = "serde", serde(transparent))]
236pub struct FrameId(pub u64);
237
238impl FrameId {
239    pub const ZERO: Self = Self(0);
240
241    #[inline(always)]
242    pub const fn raw(self) -> u64 {
243        self.0
244    }
245
246    /// Advances to the next non-zero frame identifier, skipping `0` on `u64::MAX` wrap-around.
247    #[inline(always)]
248    pub const fn next(self) -> Self {
249        let next = self.0.wrapping_add(1);
250        Self(if next == 0 { 1 } else { next })
251    }
252}
253
254impl fmt::Display for FrameId {
255    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
256        write!(f, "{}", self.0)
257    }
258}
259
260/// Monotonic timestamp in microseconds.
261#[repr(transparent)]
262#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, NvCodec, NvAbi)]
263#[nativeview_abi(name = "NvTimestampUs")]
264#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
265#[cfg_attr(feature = "serde", serde(transparent))]
266pub struct TimestampUs(pub u64);
267
268impl TimestampUs {
269    pub const ZERO: Self = Self(0);
270
271    #[inline(always)]
272    pub const fn raw(self) -> u64 {
273        self.0
274    }
275}
276
277impl fmt::Display for TimestampUs {
278    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
279        write!(f, "{}", self.0)
280    }
281}
282
283/// Elapsed duration in microseconds.
284#[repr(transparent)]
285#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, NvCodec, NvAbi)]
286#[nativeview_abi(name = "NvDurationUs")]
287#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
288#[cfg_attr(feature = "serde", serde(transparent))]
289pub struct DurationUs(pub u64);
290
291impl DurationUs {
292    pub const ZERO: Self = Self(0);
293
294    #[inline(always)]
295    pub const fn raw(self) -> u64 {
296        self.0
297    }
298}
299
300impl fmt::Display for DurationUs {
301    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
302        write!(f, "{}", self.0)
303    }
304}
305
306/// Elapsed duration in milliseconds.
307#[repr(transparent)]
308#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, NvCodec, NvAbi)]
309#[nativeview_abi(name = "NvDurationMs")]
310#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
311#[cfg_attr(feature = "serde", serde(transparent))]
312pub struct DurationMs(pub u32);
313
314impl DurationMs {
315    pub const ZERO: Self = Self(0);
316
317    #[inline(always)]
318    pub const fn raw(self) -> u32 {
319        self.0
320    }
321}
322
323impl fmt::Display for DurationMs {
324    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
325        write!(f, "{}", self.0)
326    }
327}
328
329/// Unix timestamp in milliseconds.
330#[repr(transparent)]
331#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, NvCodec)]
332#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
333#[cfg_attr(feature = "serde", serde(transparent))]
334pub struct TimestampMs(pub u64);
335
336impl TimestampMs {
337    pub const ZERO: Self = Self(0);
338
339    #[inline(always)]
340    pub const fn raw(self) -> u64 {
341        self.0
342    }
343}
344
345impl fmt::Display for TimestampMs {
346    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
347        write!(f, "{}", self.0)
348    }
349}
350
351/// Table-scoped event discriminant (`0..32`).
352#[repr(transparent)]
353#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, NvCodec, NvAbi)]
354#[nativeview_abi(name = "NvEventId")]
355#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
356#[cfg_attr(feature = "serde", serde(transparent))]
357pub struct EventId(pub u32);
358
359impl EventId {
360    #[inline(always)]
361    pub const fn raw(self) -> u32 {
362        self.0
363    }
364
365    #[inline(always)]
366    pub const fn as_usize(self) -> usize {
367        self.0 as usize
368    }
369}
370
371impl fmt::Display for EventId {
372    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
373        write!(f, "{}", self.0)
374    }
375}
376
377/// Typed bitflags on a uniform 64-byte `NvEvent` (modifiers, pointer buttons, capture, IME).
378#[repr(transparent)]
379#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, NvCodec, NvAbi)]
380#[nativeview_abi(name = "NvEventFlags")]
381#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
382#[cfg_attr(feature = "serde", serde(transparent))]
383pub struct EventFlags(pub u32);
384
385impl EventFlags {
386    pub const EMPTY: Self = Self(0);
387
388    #[inline(always)]
389    pub const fn raw(self) -> u32 {
390        self.0
391    }
392
393    #[inline(always)]
394    pub const fn contains(self, other: Self) -> bool {
395        (self.0 & other.0) == other.0
396    }
397
398    #[inline(always)]
399    pub const fn intersects(self, other: Self) -> bool {
400        (self.0 & other.0) != 0
401    }
402
403    #[inline(always)]
404    pub const fn union(self, other: Self) -> Self {
405        Self(self.0 | other.0)
406    }
407
408    #[inline(always)]
409    pub const fn intersection(self, other: Self) -> Self {
410        Self(self.0 & other.0)
411    }
412}
413
414impl BitOr for EventFlags {
415    type Output = Self;
416    #[inline(always)]
417    fn bitor(self, rhs: Self) -> Self {
418        Self(self.0 | rhs.0)
419    }
420}
421
422impl BitOrAssign for EventFlags {
423    #[inline(always)]
424    fn bitor_assign(&mut self, rhs: Self) {
425        self.0 |= rhs.0;
426    }
427}
428
429impl BitAnd for EventFlags {
430    type Output = Self;
431    #[inline(always)]
432    fn bitand(self, rhs: Self) -> Self {
433        Self(self.0 & rhs.0)
434    }
435}
436
437impl BitAndAssign for EventFlags {
438    #[inline(always)]
439    fn bitand_assign(&mut self, rhs: Self) {
440        self.0 &= rhs.0;
441    }
442}
443
444/// Byte offset inside a flat arena or event batch byte buffer.
445#[repr(transparent)]
446#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, NvCodec, NvAbi)]
447#[nativeview_abi(name = "NvArenaOffset")]
448#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
449#[cfg_attr(feature = "serde", serde(transparent))]
450pub struct ArenaOffset(pub u32);
451
452impl ArenaOffset {
453    pub const ZERO: Self = Self(0);
454
455    #[inline(always)]
456    pub const fn raw(self) -> u32 {
457        self.0
458    }
459
460    #[inline(always)]
461    pub const fn as_usize(self) -> usize {
462        self.0 as usize
463    }
464}
465
466/// 32-bit byte length across ABI headers and arenas (never element counts).
467#[repr(transparent)]
468#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, NvCodec, NvAbi)]
469#[nativeview_abi(name = "NvByteLen")]
470#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
471#[cfg_attr(feature = "serde", serde(transparent))]
472pub struct ByteLen(pub u32);
473
474impl ByteLen {
475    pub const ZERO: Self = Self(0);
476
477    #[inline(always)]
478    pub const fn raw(self) -> u32 {
479        self.0
480    }
481
482    #[inline(always)]
483    pub const fn as_usize(self) -> usize {
484        self.0 as usize
485    }
486}
487
488/// Compact 16-bit byte length inside fixed-stride 64-byte scene records.
489#[repr(transparent)]
490#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, NvCodec)]
491#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
492#[cfg_attr(feature = "serde", serde(transparent))]
493pub struct ShortLen(pub u16);
494
495impl ShortLen {
496    pub const ZERO: Self = Self(0);
497
498    #[inline(always)]
499    pub const fn raw(self) -> u16 {
500        self.0
501    }
502
503    #[inline(always)]
504    pub const fn as_usize(self) -> usize {
505        self.0 as usize
506    }
507}
508
509/// Realizing table slot index on a published node row (`0..128`), or [`PrimarySlot::NONE`]
510/// (`0xFF`) for a plain container node.
511#[repr(transparent)]
512#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, NvCodec)]
513#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
514#[cfg_attr(feature = "serde", serde(transparent))]
515pub struct PrimarySlot(pub u8);
516
517impl PrimarySlot {
518    pub const NONE: Self = Self(0xFF);
519
520    #[inline(always)]
521    pub const fn raw(self) -> u8 {
522        self.0
523    }
524
525    #[inline(always)]
526    pub const fn is_none(self) -> bool {
527        self.0 == 0xFF
528    }
529
530    #[inline(always)]
531    pub const fn slot(self) -> Option<u8> {
532        if self.0 == 0xFF {
533            None
534        } else {
535            Some(self.0)
536        }
537    }
538}
539
540impl Default for PrimarySlot {
541    #[inline(always)]
542    fn default() -> Self {
543        Self::NONE
544    }
545}
546
547/// Stacking z-index layer order.
548#[repr(transparent)]
549#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, NvCodec)]
550#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
551#[cfg_attr(feature = "serde", serde(transparent))]
552pub struct ZIndex(pub i32);
553
554impl ZIndex {
555    pub const ZERO: Self = Self(0);
556
557    #[inline(always)]
558    pub const fn raw(self) -> i32 {
559        self.0
560    }
561}
562
563/// Modular C ABI interface identifier passed to `nv_get_interface`.
564#[repr(transparent)]
565#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, NvCodec, NvAbi)]
566#[nativeview_abi(name = "NvInterfaceId")]
567#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
568#[cfg_attr(feature = "serde", serde(transparent))]
569pub struct InterfaceId(pub u32);
570
571impl InterfaceId {
572    #[inline(always)]
573    pub const fn raw(self) -> u32 {
574        self.0
575    }
576}
577
578impl fmt::Display for InterfaceId {
579    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
580        write!(f, "{}", self.0)
581    }
582}
583
584impl fmt::UpperHex for InterfaceId {
585    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
586        fmt::UpperHex::fmt(&self.0, f)
587    }
588}
589
590const _: () = {
591    assert!(size_of::<NodeIndex>() == 4 && align_of::<NodeIndex>() == align_of::<u32>());
592    assert!(size_of::<DurationMs>() == 4 && align_of::<DurationMs>() == align_of::<u32>());
593    assert!(size_of::<TimestampMs>() == 8 && align_of::<TimestampMs>() == align_of::<u64>());
594    assert!(size_of::<ShortLen>() == 2 && align_of::<ShortLen>() == align_of::<u16>());
595    assert!(size_of::<PrimarySlot>() == 1 && align_of::<PrimarySlot>() == align_of::<u8>());
596    assert!(size_of::<ZIndex>() == 4 && align_of::<ZIndex>() == align_of::<i32>());
597};
598
599#[cfg(test)]
600#[path = "id_tests.rs"]
601mod tests;