nativeview-codec 0.1.0-rc.1

Zero-unsafe, zero-runtime-dependency Tier-2 little-endian binary codec primitives and #[derive(NvCodec)]
Documentation
//! Zero-unsafe, zero-runtime-dependency Tier-2 little-endian binary codec primitives
//! (`ByteReader`, `ByteWriter`, `SliceWriter`, `ByteSink`, `ByteBuf`, `CodecError`, `NvEncode`,
//! `NvDecode`) and `#[derive(NvCodec)]`.
//!
//! Sits strictly below `nativeview-abi` in the workspace dependency DAG (depends only on zero-dep
//! `nativeview-abi-macros`) so every core, framework, backend, and module crate shares one canonical,
//! bounds-checked, DoS-hardened Tier-2 codec.

#![forbid(unsafe_code)]
#![deny(clippy::let_underscore_must_use)]
#![cfg_attr(doctest, doc = include_str!("../README.md"))]

mod flat_op;
mod flat_op_str;
mod reader;
mod traits;
pub mod transport;
mod writer;

pub use traits::{NvDecode, NvEncode};

#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_words;

use core::fmt;
use core::ops::{Deref, DerefMut};

/// Derives [`NvEncode`] and [`NvDecode`] for Tier-2 little-endian structs and enums.
///
/// # Compile-Time Guards
///
/// Generics are rejected:
/// ```compile_fail
/// use nativeview_codec::NvCodec;
/// #[derive(NvCodec)]
/// struct BadGeneric<T: nativeview_codec::NvEncode + nativeview_codec::NvDecode>(T);
/// ```
///
/// `where` clauses are rejected:
/// ```compile_fail
/// use nativeview_codec::NvCodec;
/// #[derive(NvCodec)]
/// struct BadWhere(u8) where u8: Copy;
/// ```
///
/// Field-level `#[nativeview_codec(...)]` attributes are rejected:
/// ```compile_fail
/// use nativeview_codec::NvCodec;
/// #[derive(NvCodec)]
/// struct BadFieldAttr {
///     #[nativeview_codec(skip)]
///     a: u8,
/// }
/// ```
///
/// Conflicting `#[nativeview_codec(tag = ...)]` and `= discriminant` are rejected:
/// ```compile_fail
/// use nativeview_codec::NvCodec;
/// #[repr(u8)]
/// #[derive(NvCodec)]
/// enum ConflictingTag {
///     #[nativeview_codec(tag = 1)]
///     A(u8) = 2,
/// }
/// ```
///
/// Duplicate enum tags are rejected:
/// ```compile_fail
/// use nativeview_codec::NvCodec;
/// #[derive(NvCodec)]
/// enum DupTag {
///     #[nativeview_codec(tag = 1)]
///     A(u8),
///     #[nativeview_codec(tag = 1)]
///     B(u16),
/// }
/// ```
///
/// Out-of-range tags are rejected:
/// ```compile_fail
/// use nativeview_codec::NvCodec;
/// #[derive(NvCodec)]
/// enum OutOfRange {
///     #[nativeview_codec(tag = 256)]
///     TooBig(u8),
/// }
/// ```
///
/// Non-`u8` data-carrying enums are rejected:
/// ```compile_fail
/// use nativeview_codec::NvCodec;
/// #[repr(u16)]
/// #[derive(NvCodec)]
/// enum BadDataRepr {
///     A(u32),
/// }
/// ```
///
/// Unknown `#[nativeview_codec(...)]` keys are rejected:
/// ```compile_fail
/// use nativeview_codec::NvCodec;
/// #[derive(NvCodec)]
/// #[nativeview_codec(unknown_key = "x")]
/// struct BadKey(u8);
/// ```
///
/// Unit-only enums must use Rust discriminants instead of `#[nativeview_codec(tag = ...)]`:
/// ```compile_fail
/// use nativeview_codec::NvCodec;
/// #[repr(u8)]
/// #[derive(NvCodec)]
/// enum BadUnitTag {
///     #[nativeview_codec(tag = 7)]
///     A,
/// }
/// ```
///
/// Unsupported integer `#[repr(...)]` attributes are rejected:
/// ```compile_fail
/// use nativeview_codec::NvCodec;
/// #[repr(i8)]
/// #[derive(NvCodec)]
/// enum BadRepr {
///     A = 1,
/// }
/// ```
pub use flat_op::{
    FlatOpDesc, FlatOpFieldDesc, FlatOpFieldType, FlatOpScopeDesc, FlatOpStreamDesc,
    FloatConstraint,
};
pub use flat_op_str::{
    check_flat_op_bytes_words, flat_op_str_pad_mask, for_each_padded_le_word, flat_op_str_padded_bytes,
    flat_op_str_word_len, read_flat_op_padded_bytes, read_flat_op_str_bytes, read_flat_op_str_words,
    read_flat_op_str_words_into, validate_flat_op_str_bytes, validate_flat_op_str_words,
    write_flat_op_bytes_words, write_flat_op_str_bytes, write_flat_op_str_words, FlatOpStrError,
};
pub use nativeview_abi_macros::{NvCodec, ReprEnum};
pub use reader::{ByteReader, DEFAULT_MAX_DEPTH};
pub use transport::{
    call_sync_decode, decode_opt_raw_str, encode_f32_stack, encode_f64_stack, encode_opt_raw_str,
    try_with_stack_writer, with_stack_writer, ByteTransport, StackWriter, TransportDoneFn,
    TransportError,
};
pub use writer::{try_write_fixed, write_fixed, write_fixed_into, ByteSink, ByteWriter, SliceWriter};

/// Default upper bound on element counts encoded/decoded by `NvEncode`/`NvDecode` for `Vec<T>`.
pub const DEFAULT_MAX_ITEMS: usize = 65_536;

/// Default upper bound on byte/string lengths encoded/decoded by `NvEncode`/`NvDecode` (`16 MiB`).
pub const DEFAULT_MAX_BYTES: usize = 16 * 1024 * 1024;

/// Canonical quiet NaN bit pattern for `f32` (IEEE-754 little-endian deterministic encoding).
pub const CANONICAL_F32_NAN_BITS: u32 = 0x7FC0_0000;

/// Canonical quiet NaN bit pattern for `f64` (IEEE-754 little-endian deterministic encoding).
pub const CANONICAL_F64_NAN_BITS: u64 = 0x7FF8_0000_0000_0000;

/// Canonicalizes an `f32` (`-0.0` -> `+0.0`, any `NaN` -> canonical quiet `NaN`).
#[inline]
pub const fn canonical_f32_bits(v: f32) -> u32 {
    if v.is_nan() {
        CANONICAL_F32_NAN_BITS
    } else if v == 0.0 {
        0
    } else {
        v.to_bits()
    }
}

/// Canonicalizes an `f64` (`-0.0` -> `+0.0`, any `NaN` -> canonical quiet `NaN`).
#[inline]
pub const fn canonical_f64_bits(v: f64) -> u64 {
    if v.is_nan() {
        CANONICAL_F64_NAN_BITS
    } else if v == 0.0 {
        0
    } else {
        v.to_bits()
    }
}

/// Decodes one ASCII hexadecimal digit (`0-9`, `a-f`, `A-F`) into its 4-bit value `0..=15`.
#[inline]
pub const fn hex_nibble(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

/// Typed, allocation-free error produced by [`ByteReader`], [`ByteWriter`], [`SliceWriter`],
/// and `#[derive(NvCodec)]`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CodecError {
    /// Input ended before the required number of bytes could be read (or destination slice was full).
    Truncated { needed: usize, remaining: usize },
    /// Expected fixed magic prefix did not match.
    BadMagic,
    /// Unsupported wire or archive format version.
    BadVersion(u32),
    /// Unknown enum discriminant or tag (stored as `i64` so both `u32::MAX` and `i32::MIN` are exact).
    BadEnum { ty: &'static str, raw: i64 },
    /// Boolean byte was neither `0` nor `1`.
    BadBool(u8),
    /// Reserved / padding field was non-zero.
    NonZeroReserved(u64),
    /// Length or element count exceeded its configured upper bound or wire integer capacity.
    LenOverflow { len: usize, max: usize },
    /// Unexpected unread bytes remained at [`ByteReader::finish`] / [`SliceWriter::finish`].
    TrailingBytes(usize),
    /// Length-prefixed string slice was not valid UTF-8.
    InvalidUtf8,
    /// Recursive container nesting (`read_vec`/`read_opt`) exceeded `ByteReader`'s max depth.
    DepthExceeded { max: usize },
}

impl fmt::Display for CodecError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Truncated { needed, remaining } => {
                write!(f, "truncated binary input: needed {needed}B, remaining {remaining}B")
            }
            Self::BadMagic => f.write_str("invalid binary magic header"),
            Self::BadVersion(v) => write!(f, "unsupported binary format version {v}"),
            Self::BadEnum { ty, raw } => write!(f, "invalid enum discriminant {raw} for `{ty}`"),
            Self::BadBool(b) => write!(f, "invalid boolean byte {b} (expected 0 or 1)"),
            Self::NonZeroReserved(v) => write!(f, "non-zero reserved field {v:#x}"),
            Self::LenOverflow { len, max } => {
                write!(f, "binary length {len} exceeds maximum {max}")
            }
            Self::TrailingBytes(n) => write!(f, "unexpected {n} trailing byte(s)"),
            Self::InvalidUtf8 => f.write_str("invalid UTF-8 string in binary payload"),
            Self::DepthExceeded { max } => {
                write!(f, "binary container nesting exceeded maximum depth {max}")
            }
        }
    }
}

impl std::error::Error for CodecError {}

/// Owned binary byte buffer (`u32` length prefix + raw bytes, capped at [`DEFAULT_MAX_BYTES`] =
/// 16 MiB and encoded/decoded in one bulk slice copy).
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct ByteBuf(pub Vec<u8>);

impl ByteBuf {
    #[inline]
    pub const fn new() -> Self {
        Self(Vec::new())
    }

    #[inline]
    pub fn into_vec(self) -> Vec<u8> {
        self.0
    }
}

impl Deref for ByteBuf {
    type Target = [u8];

    #[inline]
    fn deref(&self) -> &[u8] {
        &self.0
    }
}

impl DerefMut for ByteBuf {
    #[inline]
    fn deref_mut(&mut self) -> &mut [u8] {
        &mut self.0
    }
}

impl AsRef<[u8]> for ByteBuf {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl From<Vec<u8>> for ByteBuf {
    #[inline]
    fn from(v: Vec<u8>) -> Self {
        Self(v)
    }
}

impl From<ByteBuf> for Vec<u8> {
    #[inline]
    fn from(b: ByteBuf) -> Self {
        b.0
    }
}