broadcast-core 0.1.0

Frozen wire-format contract for the rust-broadcast crates: symmetric Parse/Serialize traits, checked field-width helpers, MSB-first bit I/O, reserved-bit fields, media timescales, the shared error kinds and the CENC scheme identity. no_std + alloc.
Documentation
//! The wire-format contract the rust-broadcast crates build on: the
//! symmetric [`Parse`] / [`ParsePrefix`] / [`ParseWith`] / [`Serialize`]
//! traits every wire type implements, and the small, settled pieces those
//! implementations share: checked field-width helpers, MSB-first bit I/O,
//! big-endian wire cursors, the shared error kinds, typed reserved bits, media
//! timescales, the CENC scheme identity, the track and byte-range identities,
//! the damage report a best-effort reader emits, and the streaming
//! [`Stage`](stage::Stage) contract every muxer, segmenter and demuxer stage
//! implements. Every format crate in the workspace (`broadcast-common`,
//! `broadcast-bitstream`, `mpeg-ts`, `dvb-si`, `isobmff`, `transmux`, ...)
//! depends on it; it depends on nothing but an optional `serde` derive.
//!
//! The crate is `#![no_std]` + `alloc` on every target (`std` adds only
//! [`Instant::from_instant`](stage::Instant::from_instant)), forbids `unsafe`,
//! and implements no format of its own. Its API is **the contract the wire
//! crates build on and is not yet frozen**: this is `0.1`, and it is meant to
//! freeze at `1.0`. Until then the `core_api_pin` workspace guard records
//! every item's signature, derives, `impl` headers and exported macro
//! expansions, so any change is a reviewed edit of the pin rather than an
//! accident. `Display` text is diagnostic and outside that promise.
//!
//! # Quickstart
//!
//! Implement the contract for a small wire type with the checked
//! [`wire`] cursors and [`WireError`](error::WireError), then round-trip it:
//!
//! ```
//! use broadcast_core::error::WireError;
//! use broadcast_core::wire::{Reader, Writer};
//! use broadcast_core::{Parse, Serialize};
//!
//! #[derive(Debug, PartialEq)]
//! struct Header {
//!     tag: u8,
//!     length: u16,
//! }
//!
//! const HEADER_LEN: usize = 3;
//!
//! impl<'a> Parse<'a> for Header {
//!     type Error = WireError;
//!     fn parse(bytes: &'a [u8]) -> Result<Self, WireError> {
//!         let mut r = Reader::new(bytes);
//!         Ok(Header { tag: r.u8("tag")?, length: r.u16("length")? })
//!     }
//! }
//!
//! impl Serialize for Header {
//!     type Error = WireError;
//!     fn serialized_len(&self) -> usize {
//!         HEADER_LEN
//!     }
//!     fn serialize_into(&self, buf: &mut [u8]) -> Result<usize, WireError> {
//!         let mut w = Writer::new(buf);
//!         w.u8(self.tag, "tag")?;
//!         w.u16(self.length, "length")?;
//!         Ok(w.position())
//!     }
//! }
//!
//! let wire = [0x48, 0x01, 0x2C];
//! let header = Header::parse(&wire)?;
//! assert_eq!(header, Header { tag: 0x48, length: 300 });
//! assert_eq!(header.try_to_bytes()?, wire);
//! assert!(matches!(Header::parse(&wire[..2]), Err(WireError::BufferTooShort(_))));
//! # Ok::<(), WireError>(())
//! ```
//!
//! # How do I...
//!
//! - Implement parse and serialize for my own wire type: [`Parse`],
//!   [`Serialize`] and [`Serialize::try_to_bytes`],
//!   `examples/implement_parse_serialize.rs` (and the Quickstart above).
//! - Walk a run of length-delimited items (descriptors, boxes, TLVs):
//!   [`ParsePrefix`]; no example yet.
//! - Parse something whose work the caller must bound: [`ParseWith`] with
//!   the type's own `Limits` struct; no example yet.
//! - Read and write packed sub-byte fields: [`bits::BitReader`],
//!   [`bits::BitWriter`], `examples/bits_round_trip.rs`.
//! - Write bits without knowing the final size: [`bits::BitBuf`]; no
//!   example yet.
//! - Read and write big-endian fields with bounds checks: [`wire::Reader`],
//!   [`wire::Writer`], the Quickstart above.
//! - Narrow a length or count into its wire field without wrapping:
//!   [`len::fit_u8`], [`len::fit_u16`], [`len::fit_bits`], [`len::fit_mask`];
//!   no example yet.
//! - Keep reserved bits byte-exact through a round trip:
//!   [`reserved::Reserved`]; no example yet.
//! - Convert ticks between timescales without overflow:
//!   [`timescale::Timescale`], [`timescale!`], [`timescale::rescale`],
//!   [`timescale::to_duration`]; no example yet.
//! - Report content a reader skipped and let the caller decide:
//!   [`damage::Damage`], [`damage::DamagePolicy::admit`]; no example yet.
//! - Write a streaming stage: [`stage::Stage`], [`stage::Demand`],
//!   [`stage::Instant`]; the [`Stage`](stage::Stage) documentation carries a
//!   runnable stage.
//! - Give a spec enum its `Display`: [`impl_spec_display!`]; see its
//!   documentation.
//!
//! # Modules
//!
//! The contract: [`traits`] (`Parse`, `ParsePrefix`, `ParseWith`,
//! `Serialize`, re-exported at the root), [`error`] (the shared failure kinds
//! and [`WireError`](error::WireError) joining them).
//!
//! Field I/O: [`wire`] (checked big- and little-endian byte cursors), [`bits`]
//! (MSB-first bit reader, writer and growable buffer), [`len`] (checked
//! narrowing of lengths and counts, and caller-limit checks), [`reserved`]
//! (typed reserved-bit runs).
//!
//! Media vocabulary: [`timescale`](mod@timescale) (non-zero timescale and
//! rescaling), [`units`] (decimal time-unit ratios), [`cenc`] (the CENC
//! scheme identity), [`ids`] (track identity), [`range`] (absolute byte
//! range).
//!
//! Streaming: [`stage`] (the `Stage` contract, `Demand` and `Instant`),
//! [`damage`] (skipped-content reports and the caller's policy).
//!
//! # Feature flags
//!
//! - `std` (default): forwards to `serde/std` and adds
//!   [`Instant::from_instant`](stage::Instant::from_instant); the crate is
//!   `no_std` + `alloc` either way.
//! - `serde`: `serde::Serialize` on the shared spec types
//!   ([`cenc::CencScheme`], [`reserved::Reserved`],
//!   [`timescale::Timescale`], the damage report).
//!
//! # Spec citations
//!
//! This crate implements no format. [`cenc`] names the `schm.scheme_type`
//! four-CC of ISO/IEC 14496-12:2026 §13.4.6 (`cenc`, `cens`, `cbc1`, `cbcs`;
//! the cipher rules are de facto, verified against conformance files and
//! independent tools as the module records); every other module is
//! format-independent.

#![no_std]
#![forbid(unsafe_code)]
#![deny(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]

extern crate alloc;
#[cfg(feature = "std")]
extern crate std;

pub mod bits;
pub mod cenc;
pub mod damage;
pub mod error;
pub mod ids;
pub mod len;
pub mod range;
pub mod reserved;
pub mod stage;
pub mod timescale;
pub mod traits;
pub mod units;
pub mod wire;

pub use traits::{Parse, ParsePrefix, ParseWith, Serialize};

/// Generate a [`core::fmt::Display`] impl for a spec/field enum that delegates
/// to an inherent `fn name(&self) -> &'static str`.
///
/// This is the project-wide convention for every public spec/field enum across
/// the `dvb-*` crates (see issue #204): `name()` is the hand-written,
/// zero-alloc static spec token (lossy on the reserved/unknown arm, which
/// returns `"reserved"`), and `Display` is the lossless, composable view that
/// delegates to it. The labels themselves live in `name()` in source — never in
/// this macro — so they sit next to the variant docs and stay greppable. This
/// macro carries no labels; it only removes the otherwise-identical `Display`
/// boilerplate and keeps the two in lockstep.
///
/// # Forms
/// - `impl_spec_display!(Ty)` — every variant's `Display` is exactly `name()`.
///   Use when there is no byte-bearing catch-all (or its byte need not be
///   shown), e.g. a unit `Reserved` variant.
/// - `impl_spec_display!(Ty, Var1, Var2, …)` — each named variant is a
///   single-field tuple binding a byte; `Display` renders it as
///   `"{name}(0x{:02X})"` so the value is preserved (e.g. `Reserved(0x1A)` →
///   `reserved(0x1A)`, `UserDefined(0x1A)` → `user defined(0x1A)`). All other
///   variants delegate to `name()`.
///
/// ```
/// pub enum Mode { Normal, HighEfficiency, Reserved(u8) }
/// impl Mode {
///     pub fn name(&self) -> &'static str {
///         match self {
///             Self::Normal => "normal",
///             Self::HighEfficiency => "high efficiency",
///             Self::Reserved(_) => "reserved",
///         }
///     }
/// }
/// broadcast_core::impl_spec_display!(Mode, Reserved);
/// assert_eq!(Mode::Normal.to_string(), "normal");
/// assert_eq!(Mode::Reserved(0x1A).to_string(), "reserved(0x1A)");
/// ```
#[macro_export]
macro_rules! impl_spec_display {
    ($ty:ty) => {
        impl ::core::fmt::Display for $ty {
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                f.write_str(self.name())
            }
        }
    };
    ($ty:ty, $($resv:ident),+ $(,)?) => {
        impl ::core::fmt::Display for $ty {
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                match self {
                    $( Self::$resv(v) => ::core::write!(f, "{}(0x{:02X})", self.name(), v), )+
                    other => f.write_str(other.name()),
                }
            }
        }
    };
}