Skip to main content

broadcast_common/
lib.rs

1#![doc = include_str!("../README.md")]
2#![doc = "\n"]
3//! # Reserved-bit and trailing-byte policy
4//!
5//! One workspace-wide rule for every wire crate (issue #1139):
6//!
7//! - **Parse is tolerant.** A non-conformant reserved bit, or trailing data
8//!   that real senders emit, is accepted rather than rejected (a crate may
9//!   choose stricter validation, as `dvb-t2mi` does for RFU bits, but must
10//!   document it).
11//! - **Serialize preserves what was parsed.** Reserved bits are captured on
12//!   parse in typed, spec-named fields and re-emitted verbatim, so a stream
13//!   from a sender that deviates from the governing edition re-serializes
14//!   **byte-identically** (`dvb-si` descriptors, `mpeg-ps`, `rmt-flute`,
15//!   `cc-data` fixed bits, `rtcp-packet` `profile_extensions`, `mp4-emsg`
16//!   flags). There is no raw passthrough blob.
17//! - **Constructed values default to the edition value**: a struct built by
18//!   hand (`new(..)` / `Default`) carries `1` for `reserved_future_use` and
19//!   H.222.0 "reserved", `0` for `reserved_zero_future_use`, with any explicit
20//!   per-field exception documented on the field. (A crate that has not
21//!   adopted preserve-on-parse documents which fields it normalizes to the
22//!   spec value on serialize; `mpeg-ts`, `mpeg-pes` and `mpeg-ps` preserve.)
23//! - A caller that needs byte-for-byte preservation of reserved bits in a
24//!   not-yet-migrated crate **keeps the original bytes** rather than
25//!   re-serializing.
26//! - Trailing bytes inside a descriptor or section body are never silently
27//!   dropped without a documented decision: hold them in a typed field, or
28//!   document the field as "ignored".
29//! - Reserved bytes are always **written explicitly** by `serialize_into`;
30//!   never rely on a pre-zeroed output buffer.
31//!
32//! The round-trip gate is byte-exact against the original fixture slice
33//! (see `docs/CRATE-ACCEPTANCE.md`).
34
35#![forbid(unsafe_code)]
36#![warn(missing_docs)]
37#![cfg_attr(docsrs, feature(doc_cfg))]
38#![cfg_attr(not(feature = "std"), no_std)]
39// The crate's runnable examples, embedded so they render on docs.rs and stay in
40// sync with the actual `examples/*.rs` files (shown, not compiled).
41#![doc = "\n# Examples\n"]
42#![doc = "Two runnable examples ship with this crate (`cargo run -p broadcast-common --example <name>`).\n"]
43#![doc = "\n## `crc_and_bcd`\n\n```rust,ignore"]
44#![doc = include_str!("../examples/crc_and_bcd.rs")]
45#![doc = "```\n\n## `implement_parse_serialize`\n\n```rust,ignore"]
46#![doc = include_str!("../examples/implement_parse_serialize.rs")]
47#![doc = "```"]
48
49extern crate alloc;
50
51pub mod bcd;
52pub mod bits;
53pub mod cenc;
54pub mod clock33;
55pub mod crc32_mpeg2;
56pub mod hex;
57pub mod len;
58pub mod mux;
59pub mod parity;
60pub mod pusi;
61pub mod seq;
62pub mod stage;
63pub mod time;
64pub mod traits;
65pub mod ts_dup;
66
67pub use cenc::CencScheme;
68pub use mux::{Decrypt, Encrypt, Package, Unpackage};
69pub use stage::{Demand, Stage, Timestamp};
70pub use traits::{Parse, Serialize};
71
72/// Generate a [`core::fmt::Display`] impl for a spec/field enum that delegates
73/// to an inherent `fn name(&self) -> &'static str`.
74///
75/// This is the project-wide convention for every public spec/field enum across
76/// the `dvb-*` crates (see issue #204): `name()` is the hand-written,
77/// zero-alloc static spec token (lossy on the reserved/unknown arm, which
78/// returns `"reserved"`), and `Display` is the lossless, composable view that
79/// delegates to it. The labels themselves live in `name()` in source — never in
80/// this macro — so they sit next to the variant docs and stay greppable. This
81/// macro carries no labels; it only removes the otherwise-identical `Display`
82/// boilerplate and keeps the two in lockstep.
83///
84/// # Forms
85/// - `impl_spec_display!(Ty)` — every variant's `Display` is exactly `name()`.
86///   Use when there is no byte-bearing catch-all (or its byte need not be
87///   shown), e.g. a unit `Reserved` variant.
88/// - `impl_spec_display!(Ty, Var1, Var2, …)` — each named variant is a
89///   single-field tuple binding a byte; `Display` renders it as
90///   `"{name}(0x{:02X})"` so the value is preserved (e.g. `Reserved(0x1A)` →
91///   `reserved(0x1A)`, `UserDefined(0x1A)` → `user defined(0x1A)`). All other
92///   variants delegate to `name()`.
93///
94/// ```
95/// pub enum Mode { Normal, HighEfficiency, Reserved(u8) }
96/// impl Mode {
97///     pub fn name(&self) -> &'static str {
98///         match self {
99///             Self::Normal => "normal",
100///             Self::HighEfficiency => "high efficiency",
101///             Self::Reserved(_) => "reserved",
102///         }
103///     }
104/// }
105/// broadcast_common::impl_spec_display!(Mode, Reserved);
106/// assert_eq!(Mode::Normal.to_string(), "normal");
107/// assert_eq!(Mode::Reserved(0x1A).to_string(), "reserved(0x1A)");
108/// ```
109#[macro_export]
110macro_rules! impl_spec_display {
111    ($ty:ty) => {
112        impl ::core::fmt::Display for $ty {
113            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
114                f.write_str(self.name())
115            }
116        }
117    };
118    ($ty:ty, $($resv:ident),+ $(,)?) => {
119        impl ::core::fmt::Display for $ty {
120            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
121                match self {
122                    $( Self::$resv(v) => ::core::write!(f, "{}(0x{:02X})", self.name(), v), )+
123                    other => f.write_str(other.name()),
124                }
125            }
126        }
127    };
128}