Skip to main content

nativeview_codec/
flat_op.rs

1//! Generic schema descriptors for flat 4-byte-aligned (`u32`-word) operation-stream resources.
2//!
3//! A flat word-op stream uses the little-endian wire layout:
4//! ```text
5//! [op_count: u32] [header_field_0] [header_field_1] ...
6//!   for _ in 0..op_count:
7//!     [opcode: u32] [field_0 ...] [field_1 ...] ...
8//! ```
9//! Each scalar field occupies one little-endian 32-bit word (`u32`, `ColorRgba` packed as
10//! `r | (g << 8) | (b << 16) | (a << 24)`, or IEEE-754 `f32`). Variable-length
11//! [`FlatOpFieldType::StrSlice`] fields encode `[byte_len: u32, zero_padded_utf8_le_words...]`
12//! (`1 + byte_len.div_ceil(4)` words, strict UTF-8, trailing padding bytes zeroed, matching
13//! `nativeview-store`'s `write_str_words`/`validate_str_words`). Variable-length
14//! [`FlatOpFieldType::Point2Slice`] fields encode `[count: u32, (x: f32, y: f32) * count]` and
15//! must appear as the final field of their operation. Optional fixed [`FlatOpStreamDesc::header`]
16//! scalar fields (e.g. a picture `viewBox`) follow `op_count` and reach every generated sink once,
17//! through `onHeader`, before the first operation.
18
19/// Validation predicate enforced on decoded IEEE-754 `f32` words.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum FloatConstraint {
22    /// Rejects `NaN`, `+Inf`, and `-Inf`.
23    Finite,
24    /// Rejects `NaN`, `+Inf`, `-Inf`, and strictly negative values (`< 0.0`).
25    /// IEEE-754 `-0.0 >= 0.0` is `true` across Rust, C++, Java, Swift, Dart, and JS/TS.
26    NonNegative,
27    /// Rejects `NaN`, `+Inf`, `-Inf`, zero (either sign), and negative values (`<= 0.0`), e.g. a
28    /// `viewBox` extent that a reader divides by.
29    Positive,
30}
31
32impl FloatConstraint {
33    /// Returns `true` when `value` satisfies this constraint.
34    #[inline]
35    pub const fn check(self, value: f32) -> bool {
36        match self {
37            Self::Finite => value.is_finite(),
38            Self::NonNegative => value.is_finite() && value >= 0.0,
39            Self::Positive => value.is_finite() && value > 0.0,
40        }
41    }
42}
43
44/// Wire type and validation constraint for one field inside a [`FlatOpDesc`].
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
46pub enum FlatOpFieldType {
47    /// Single little-endian `u32` word.
48    U32,
49    /// Single little-endian `u32` RGBA8888 word (`r | (g << 8) | (b << 16) | (a << 24)`).
50    ColorRgba,
51    /// Single IEEE-754 little-endian `f32` word subject to [`FloatConstraint`].
52    F32(FloatConstraint),
53    /// Variable-length `(x, y)` `f32` vertex slice: `[count: u32, (x: f32, y: f32) * count]`.
54    Point2Slice {
55        /// Strict upper bound on vertex count per operation.
56        max_len: u32,
57        /// Constant identifier emitted in generated host decoders (e.g. `"MAX_POLYLINE_POINTS"`).
58        max_const_name: &'static str,
59        /// Float constraint applied to every decoded `(x, y)` coordinate.
60        coord_constraint: FloatConstraint,
61    },
62    /// Variable-length word-padded UTF-8 string slice:
63    /// `[byte_len: u32, zero_padded_utf8_le_words...]` (`1 + byte_len.div_ceil(4)` words).
64    ///
65    /// Matches `nativeview-store`'s `write_str_words` / `validate_str_words` wire layout: strict UTF-8,
66    /// `byte_len <= max_bytes`, and trailing padding bytes in the final word MUST be zero.
67    StrSlice {
68        /// Strict upper bound on encoded UTF-8 byte length.
69        max_bytes: u32,
70    },
71}
72
73/// Named payload field inside a [`FlatOpDesc`], ordered in exact wire sequence.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
75pub struct FlatOpFieldDesc {
76    /// `snake_case` field name (e.g. `"x0"`, `"radius"`, `"color"`, `"points"`).
77    pub name: &'static str,
78    /// Wire type and validation constraint.
79    pub ty: FlatOpFieldType,
80}
81
82/// Single operation variant inside a [`FlatOpStreamDesc`].
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
84pub struct FlatOpDesc {
85    /// `PascalCase` operation name (e.g. `"FillRoundedRect"`, `"StrokePolyline"`).
86    pub name: &'static str,
87    /// Stable little-endian `u32` opcode word (`>= 1`).
88    pub opcode: u32,
89    /// Ordered payload fields immediately following the opcode word.
90    pub fields: &'static [FlatOpFieldDesc],
91}
92
93impl FlatOpDesc {
94    /// Number of fixed `u32` payload words preceding any trailing [`FlatOpFieldType::Point2Slice`]
95    /// vertices (including the slice's `u32` vertex count word itself), or `None` when this
96    /// operation contains variable-width [`FlatOpFieldType::StrSlice`] fields.
97    #[inline]
98    pub const fn fixed_words(&self) -> Option<usize> {
99        if self.has_str_slice() {
100            None
101        } else {
102            Some(self.fields.len())
103        }
104    }
105
106    /// Minimum number of `u32` payload words for this operation (one word per scalar, slice count,
107    /// or string byte-length prefix, excluding variable-length payload words).
108    #[inline]
109    pub const fn min_words(&self) -> usize {
110        self.fields.len()
111    }
112
113    /// Returns `true` if this operation ends with a variable-length [`FlatOpFieldType::Point2Slice`].
114    #[inline]
115    pub const fn has_point_slice(&self) -> bool {
116        if self.fields.is_empty() {
117            return false;
118        }
119        matches!(
120            self.fields[self.fields.len() - 1].ty,
121            FlatOpFieldType::Point2Slice { .. }
122        )
123    }
124
125    /// Returns `true` if this operation contains any [`FlatOpFieldType::StrSlice`] field.
126    #[inline]
127    pub const fn has_str_slice(&self) -> bool {
128        let mut i = 0;
129        while i < self.fields.len() {
130            if matches!(self.fields[i].ty, FlatOpFieldType::StrSlice { .. }) {
131                return true;
132            }
133            i += 1;
134        }
135        false
136    }
137}
138
139/// Optional balanced push/pop scope discipline enforced by generated stream decoders
140/// (e.g. `ClipRect` / `RestoreClip` capped at `MAX_CLIP_DEPTH = 64`).
141///
142/// Every generated decoder enforces identical semantics:
143/// - Pushing while `depth < max_depth` increments `depth` BEFORE invoking the push callback
144///   (so throwing callbacks still unwind cleanly).
145/// - Pushing while `depth >= max_depth` skips the push callback and increments `overflow`.
146/// - Popping while `overflow > 0` decrements `overflow` without invoking the pop callback.
147/// - Popping while `overflow == 0 && depth > 0` decrements `depth` and invokes the pop callback.
148/// - Popping while `overflow == 0 && depth == 0` is a no-op.
149/// - On normal stream end or callback error/exception unwind, all remaining `depth` scopes are
150///   closed by invoking the pop callback `depth` times.
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
152pub struct FlatOpScopeDesc {
153    /// Constant identifier for the depth cap (e.g. `"MAX_CLIP_DEPTH"`).
154    pub limit_name: &'static str,
155    /// Opcode that pushes a scope (e.g. `7` for `ClipRect`).
156    pub push_opcode: u32,
157    /// Opcode that pops a scope (e.g. `8` for `RestoreClip`; must have zero fields).
158    pub pop_opcode: u32,
159    /// Maximum live scope depth passed to the sink (e.g. `64`).
160    pub max_depth: u32,
161}
162
163/// Complete schema descriptor for one flat 4-byte-aligned word-op stream resource.
164#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
165pub struct FlatOpStreamDesc {
166    /// `PascalCase` stream name (e.g. `"DrawList"` -> `NvDrawList` / `nv_draw_list`).
167    pub name: &'static str,
168    /// Canonical resource kind string hashed via XXH64 (`Key64::of(kind_name)`).
169    pub kind_name: &'static str,
170    /// Constant identifier for the op-count upper bound (e.g. `"MAX_DRAW_OPS"`).
171    pub max_ops_const_name: &'static str,
172    /// Strict upper bound on operations per stream.
173    pub max_ops: u32,
174    /// Fixed scalar fields (no [`FlatOpFieldType::Point2Slice`]) following `op_count`, delivered to
175    /// sinks once before the first operation (empty for plain op streams).
176    pub header: &'static [FlatOpFieldDesc],
177    /// Optional balanced push/pop scope pair.
178    pub scope: Option<FlatOpScopeDesc>,
179    /// All valid operation variants in canonical wire order.
180    pub ops: &'static [FlatOpDesc],
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    const SAMPLE_OP: FlatOpDesc = FlatOpDesc {
188        name: "StrokePolyline",
189        opcode: 6,
190        fields: &[
191            FlatOpFieldDesc {
192                name: "width",
193                ty: FlatOpFieldType::F32(FloatConstraint::NonNegative),
194            },
195            FlatOpFieldDesc {
196                name: "color",
197                ty: FlatOpFieldType::ColorRgba,
198            },
199            FlatOpFieldDesc {
200                name: "points",
201                ty: FlatOpFieldType::Point2Slice {
202                    max_len: 16_384,
203                    max_const_name: "MAX_POLYLINE_POINTS",
204                    coord_constraint: FloatConstraint::Finite,
205                },
206            },
207        ],
208    };
209
210    #[test]
211    fn float_constraints_handle_edge_values() {
212        assert!(FloatConstraint::Finite.check(0.0));
213        assert!(FloatConstraint::Finite.check(-0.0));
214        assert!(FloatConstraint::Finite.check(-42.5));
215        assert!(!FloatConstraint::Finite.check(f32::NAN));
216        assert!(!FloatConstraint::Finite.check(f32::INFINITY));
217        assert!(!FloatConstraint::Finite.check(f32::NEG_INFINITY));
218
219        assert!(FloatConstraint::NonNegative.check(0.0));
220        assert!(FloatConstraint::NonNegative.check(-0.0));
221        assert!(FloatConstraint::NonNegative.check(1.25));
222        assert!(!FloatConstraint::NonNegative.check(-0.0001));
223        assert!(!FloatConstraint::NonNegative.check(f32::NAN));
224        assert!(!FloatConstraint::NonNegative.check(f32::INFINITY));
225        assert!(!FloatConstraint::NonNegative.check(f32::NEG_INFINITY));
226
227        assert!(FloatConstraint::Positive.check(f32::MIN_POSITIVE));
228        assert!(FloatConstraint::Positive.check(f32::from_bits(1)));
229        assert!(FloatConstraint::Positive.check(f32::MAX));
230        assert!(!FloatConstraint::Positive.check(0.0));
231        assert!(!FloatConstraint::Positive.check(-0.0));
232        assert!(!FloatConstraint::Positive.check(-1.0));
233        assert!(!FloatConstraint::Positive.check(f32::NAN));
234        assert!(!FloatConstraint::Positive.check(f32::INFINITY));
235    }
236
237    #[test]
238    fn flat_op_desc_reports_word_shape() {
239        assert_eq!(SAMPLE_OP.fixed_words(), Some(3));
240        assert_eq!(SAMPLE_OP.min_words(), 3);
241        assert!(SAMPLE_OP.has_point_slice());
242        assert!(!SAMPLE_OP.has_str_slice());
243
244        const TEXT_OP: FlatOpDesc = FlatOpDesc {
245            name: "DrawText",
246            opcode: 9,
247            fields: &[
248                FlatOpFieldDesc {
249                    name: "x",
250                    ty: FlatOpFieldType::F32(FloatConstraint::Finite),
251                },
252                FlatOpFieldDesc {
253                    name: "text",
254                    ty: FlatOpFieldType::StrSlice { max_bytes: 4096 },
255                },
256            ],
257        };
258        assert_eq!(TEXT_OP.fixed_words(), None);
259        assert_eq!(TEXT_OP.min_words(), 2);
260        assert!(!TEXT_OP.has_point_slice());
261        assert!(TEXT_OP.has_str_slice());
262
263        const EMPTY_OP: FlatOpDesc = FlatOpDesc {
264            name: "RestoreClip",
265            opcode: 8,
266            fields: &[],
267        };
268        assert_eq!(EMPTY_OP.fixed_words(), Some(0));
269        assert_eq!(EMPTY_OP.min_words(), 0);
270        assert!(!EMPTY_OP.has_point_slice());
271        assert!(!EMPTY_OP.has_str_slice());
272    }
273}