Skip to main content

nativeview_codec/
lib.rs

1//! Zero-unsafe, zero-runtime-dependency Tier-2 little-endian binary codec primitives
2//! (`ByteReader`, `ByteWriter`, `SliceWriter`, `ByteSink`, `ByteBuf`, `CodecError`, `NvEncode`,
3//! `NvDecode`) and `#[derive(NvCodec)]`.
4//!
5//! Sits strictly below `nativeview-abi` in the workspace dependency DAG (depends only on zero-dep
6//! `nativeview-abi-macros`) so every core, framework, backend, and module crate shares one canonical,
7//! bounds-checked, DoS-hardened Tier-2 codec.
8
9#![forbid(unsafe_code)]
10#![deny(clippy::let_underscore_must_use)]
11#![cfg_attr(doctest, doc = include_str!("../README.md"))]
12
13mod flat_op;
14mod flat_op_str;
15mod reader;
16mod traits;
17pub mod transport;
18mod writer;
19
20pub use traits::{NvDecode, NvEncode};
21
22#[cfg(test)]
23mod tests;
24#[cfg(test)]
25mod tests_words;
26
27use core::fmt;
28use core::ops::{Deref, DerefMut};
29
30/// Derives [`NvEncode`] and [`NvDecode`] for Tier-2 little-endian structs and enums.
31///
32/// # Compile-Time Guards
33///
34/// Generics are rejected:
35/// ```compile_fail
36/// use nativeview_codec::NvCodec;
37/// #[derive(NvCodec)]
38/// struct BadGeneric<T: nativeview_codec::NvEncode + nativeview_codec::NvDecode>(T);
39/// ```
40///
41/// `where` clauses are rejected:
42/// ```compile_fail
43/// use nativeview_codec::NvCodec;
44/// #[derive(NvCodec)]
45/// struct BadWhere(u8) where u8: Copy;
46/// ```
47///
48/// Field-level `#[nativeview_codec(...)]` attributes are rejected:
49/// ```compile_fail
50/// use nativeview_codec::NvCodec;
51/// #[derive(NvCodec)]
52/// struct BadFieldAttr {
53///     #[nativeview_codec(skip)]
54///     a: u8,
55/// }
56/// ```
57///
58/// Conflicting `#[nativeview_codec(tag = ...)]` and `= discriminant` are rejected:
59/// ```compile_fail
60/// use nativeview_codec::NvCodec;
61/// #[repr(u8)]
62/// #[derive(NvCodec)]
63/// enum ConflictingTag {
64///     #[nativeview_codec(tag = 1)]
65///     A(u8) = 2,
66/// }
67/// ```
68///
69/// Duplicate enum tags are rejected:
70/// ```compile_fail
71/// use nativeview_codec::NvCodec;
72/// #[derive(NvCodec)]
73/// enum DupTag {
74///     #[nativeview_codec(tag = 1)]
75///     A(u8),
76///     #[nativeview_codec(tag = 1)]
77///     B(u16),
78/// }
79/// ```
80///
81/// Out-of-range tags are rejected:
82/// ```compile_fail
83/// use nativeview_codec::NvCodec;
84/// #[derive(NvCodec)]
85/// enum OutOfRange {
86///     #[nativeview_codec(tag = 256)]
87///     TooBig(u8),
88/// }
89/// ```
90///
91/// Non-`u8` data-carrying enums are rejected:
92/// ```compile_fail
93/// use nativeview_codec::NvCodec;
94/// #[repr(u16)]
95/// #[derive(NvCodec)]
96/// enum BadDataRepr {
97///     A(u32),
98/// }
99/// ```
100///
101/// Unknown `#[nativeview_codec(...)]` keys are rejected:
102/// ```compile_fail
103/// use nativeview_codec::NvCodec;
104/// #[derive(NvCodec)]
105/// #[nativeview_codec(unknown_key = "x")]
106/// struct BadKey(u8);
107/// ```
108///
109/// Unit-only enums must use Rust discriminants instead of `#[nativeview_codec(tag = ...)]`:
110/// ```compile_fail
111/// use nativeview_codec::NvCodec;
112/// #[repr(u8)]
113/// #[derive(NvCodec)]
114/// enum BadUnitTag {
115///     #[nativeview_codec(tag = 7)]
116///     A,
117/// }
118/// ```
119///
120/// Unsupported integer `#[repr(...)]` attributes are rejected:
121/// ```compile_fail
122/// use nativeview_codec::NvCodec;
123/// #[repr(i8)]
124/// #[derive(NvCodec)]
125/// enum BadRepr {
126///     A = 1,
127/// }
128/// ```
129pub use flat_op::{
130    FlatOpDesc, FlatOpFieldDesc, FlatOpFieldType, FlatOpScopeDesc, FlatOpStreamDesc,
131    FloatConstraint,
132};
133pub use flat_op_str::{
134    check_flat_op_bytes_words, flat_op_str_pad_mask, for_each_padded_le_word, flat_op_str_padded_bytes,
135    flat_op_str_word_len, read_flat_op_padded_bytes, read_flat_op_str_bytes, read_flat_op_str_words,
136    read_flat_op_str_words_into, validate_flat_op_str_bytes, validate_flat_op_str_words,
137    write_flat_op_bytes_words, write_flat_op_str_bytes, write_flat_op_str_words, FlatOpStrError,
138};
139pub use nativeview_abi_macros::{NvCodec, ReprEnum};
140pub use reader::{ByteReader, DEFAULT_MAX_DEPTH};
141pub use transport::{
142    call_sync_decode, decode_opt_raw_str, encode_f32_stack, encode_f64_stack, encode_opt_raw_str,
143    try_with_stack_writer, with_stack_writer, ByteTransport, StackWriter, TransportDoneFn,
144    TransportError,
145};
146pub use writer::{try_write_fixed, write_fixed, write_fixed_into, ByteSink, ByteWriter, SliceWriter};
147
148/// Default upper bound on element counts encoded/decoded by `NvEncode`/`NvDecode` for `Vec<T>`.
149pub const DEFAULT_MAX_ITEMS: usize = 65_536;
150
151/// Default upper bound on byte/string lengths encoded/decoded by `NvEncode`/`NvDecode` (`16 MiB`).
152pub const DEFAULT_MAX_BYTES: usize = 16 * 1024 * 1024;
153
154/// Canonical quiet NaN bit pattern for `f32` (IEEE-754 little-endian deterministic encoding).
155pub const CANONICAL_F32_NAN_BITS: u32 = 0x7FC0_0000;
156
157/// Canonical quiet NaN bit pattern for `f64` (IEEE-754 little-endian deterministic encoding).
158pub const CANONICAL_F64_NAN_BITS: u64 = 0x7FF8_0000_0000_0000;
159
160/// Canonicalizes an `f32` (`-0.0` -> `+0.0`, any `NaN` -> canonical quiet `NaN`).
161#[inline]
162pub const fn canonical_f32_bits(v: f32) -> u32 {
163    if v.is_nan() {
164        CANONICAL_F32_NAN_BITS
165    } else if v == 0.0 {
166        0
167    } else {
168        v.to_bits()
169    }
170}
171
172/// Canonicalizes an `f64` (`-0.0` -> `+0.0`, any `NaN` -> canonical quiet `NaN`).
173#[inline]
174pub const fn canonical_f64_bits(v: f64) -> u64 {
175    if v.is_nan() {
176        CANONICAL_F64_NAN_BITS
177    } else if v == 0.0 {
178        0
179    } else {
180        v.to_bits()
181    }
182}
183
184/// Decodes one ASCII hexadecimal digit (`0-9`, `a-f`, `A-F`) into its 4-bit value `0..=15`.
185#[inline]
186pub const fn hex_nibble(b: u8) -> Option<u8> {
187    match b {
188        b'0'..=b'9' => Some(b - b'0'),
189        b'a'..=b'f' => Some(b - b'a' + 10),
190        b'A'..=b'F' => Some(b - b'A' + 10),
191        _ => None,
192    }
193}
194
195/// Typed, allocation-free error produced by [`ByteReader`], [`ByteWriter`], [`SliceWriter`],
196/// and `#[derive(NvCodec)]`.
197#[derive(Debug, Clone, PartialEq, Eq)]
198pub enum CodecError {
199    /// Input ended before the required number of bytes could be read (or destination slice was full).
200    Truncated { needed: usize, remaining: usize },
201    /// Expected fixed magic prefix did not match.
202    BadMagic,
203    /// Unsupported wire or archive format version.
204    BadVersion(u32),
205    /// Unknown enum discriminant or tag (stored as `i64` so both `u32::MAX` and `i32::MIN` are exact).
206    BadEnum { ty: &'static str, raw: i64 },
207    /// Boolean byte was neither `0` nor `1`.
208    BadBool(u8),
209    /// Reserved / padding field was non-zero.
210    NonZeroReserved(u64),
211    /// Length or element count exceeded its configured upper bound or wire integer capacity.
212    LenOverflow { len: usize, max: usize },
213    /// Unexpected unread bytes remained at [`ByteReader::finish`] / [`SliceWriter::finish`].
214    TrailingBytes(usize),
215    /// Length-prefixed string slice was not valid UTF-8.
216    InvalidUtf8,
217    /// Recursive container nesting (`read_vec`/`read_opt`) exceeded `ByteReader`'s max depth.
218    DepthExceeded { max: usize },
219}
220
221impl fmt::Display for CodecError {
222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223        match self {
224            Self::Truncated { needed, remaining } => {
225                write!(f, "truncated binary input: needed {needed}B, remaining {remaining}B")
226            }
227            Self::BadMagic => f.write_str("invalid binary magic header"),
228            Self::BadVersion(v) => write!(f, "unsupported binary format version {v}"),
229            Self::BadEnum { ty, raw } => write!(f, "invalid enum discriminant {raw} for `{ty}`"),
230            Self::BadBool(b) => write!(f, "invalid boolean byte {b} (expected 0 or 1)"),
231            Self::NonZeroReserved(v) => write!(f, "non-zero reserved field {v:#x}"),
232            Self::LenOverflow { len, max } => {
233                write!(f, "binary length {len} exceeds maximum {max}")
234            }
235            Self::TrailingBytes(n) => write!(f, "unexpected {n} trailing byte(s)"),
236            Self::InvalidUtf8 => f.write_str("invalid UTF-8 string in binary payload"),
237            Self::DepthExceeded { max } => {
238                write!(f, "binary container nesting exceeded maximum depth {max}")
239            }
240        }
241    }
242}
243
244impl std::error::Error for CodecError {}
245
246/// Owned binary byte buffer (`u32` length prefix + raw bytes, capped at [`DEFAULT_MAX_BYTES`] =
247/// 16 MiB and encoded/decoded in one bulk slice copy).
248#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
249pub struct ByteBuf(pub Vec<u8>);
250
251impl ByteBuf {
252    #[inline]
253    pub const fn new() -> Self {
254        Self(Vec::new())
255    }
256
257    #[inline]
258    pub fn into_vec(self) -> Vec<u8> {
259        self.0
260    }
261}
262
263impl Deref for ByteBuf {
264    type Target = [u8];
265
266    #[inline]
267    fn deref(&self) -> &[u8] {
268        &self.0
269    }
270}
271
272impl DerefMut for ByteBuf {
273    #[inline]
274    fn deref_mut(&mut self) -> &mut [u8] {
275        &mut self.0
276    }
277}
278
279impl AsRef<[u8]> for ByteBuf {
280    #[inline]
281    fn as_ref(&self) -> &[u8] {
282        &self.0
283    }
284}
285
286impl From<Vec<u8>> for ByteBuf {
287    #[inline]
288    fn from(v: Vec<u8>) -> Self {
289        Self(v)
290    }
291}
292
293impl From<ByteBuf> for Vec<u8> {
294    #[inline]
295    fn from(b: ByteBuf) -> Self {
296        b.0
297    }
298}
299