Skip to main content

dvb_common/
lib.rs

1//! Shared primitives for the dvb_si / dvb_t2mi / dvb_bbframe family.
2//!
3//! See individual modules for documentation: the [`Parse`] / [`Serialize`]
4//! traits every wire type implements, the MPEG-2 [`crc32_mpeg2`] CRC, and the
5//! [`bcd`] / [`time`] codecs.
6//!
7//! # Quick start
8//! ```
9//! use dvb_common::{bcd, crc32_mpeg2};
10//!
11//! // Binary-coded decimal (as used in MJD/BCD time fields):
12//! assert_eq!(bcd::from_bcd_byte(0x42), Some(42));
13//! assert_eq!(bcd::to_bcd_byte(42), Some(0x42));
14//!
15//! // MPEG-2 CRC-32 over a section body (deterministic):
16//! let crc = crc32_mpeg2::compute(&[0xDE, 0xAD, 0xBE, 0xEF]);
17//! assert_eq!(crc, crc32_mpeg2::compute(&[0xDE, 0xAD, 0xBE, 0xEF]));
18//! ```
19
20#![forbid(unsafe_code)]
21#![warn(missing_docs)]
22#![cfg_attr(docsrs, feature(doc_cfg))]
23#![cfg_attr(not(feature = "std"), no_std)]
24// The crate's runnable examples, embedded so they render on docs.rs and stay in
25// sync with the actual `examples/*.rs` files (shown, not compiled).
26#![doc = "\n# Examples\n"]
27#![doc = "Two runnable examples ship with this crate (`cargo run -p dvb-common --example <name>`).\n"]
28#![doc = "\n## `crc_and_bcd`\n\n```rust,ignore"]
29#![doc = include_str!("../examples/crc_and_bcd.rs")]
30#![doc = "```\n\n## `implement_parse_serialize`\n\n```rust,ignore"]
31#![doc = include_str!("../examples/implement_parse_serialize.rs")]
32#![doc = "```"]
33
34extern crate alloc;
35
36pub mod bcd;
37pub mod bits;
38pub mod crc32_mpeg2;
39pub mod time;
40pub mod traits;
41
42pub use traits::{Parse, Serialize};
43
44/// Generate a [`core::fmt::Display`] impl for a spec/field enum that delegates
45/// to an inherent `fn name(&self) -> &'static str`.
46///
47/// This is the project-wide convention for every public spec/field enum across
48/// the `dvb-*` crates (see issue #204): `name()` is the hand-written,
49/// zero-alloc static spec token (lossy on the reserved/unknown arm, which
50/// returns `"reserved"`), and `Display` is the lossless, composable view that
51/// delegates to it. The labels themselves live in `name()` in source — never in
52/// this macro — so they sit next to the variant docs and stay greppable. This
53/// macro carries no labels; it only removes the otherwise-identical `Display`
54/// boilerplate and keeps the two in lockstep.
55///
56/// # Forms
57/// - `impl_spec_display!(Ty)` — every variant's `Display` is exactly `name()`.
58///   Use when there is no byte-bearing catch-all (or its byte need not be
59///   shown), e.g. a unit `Reserved` variant.
60/// - `impl_spec_display!(Ty, Var1, Var2, …)` — each named variant is a
61///   single-field tuple binding a byte; `Display` renders it as
62///   `"{name}(0x{:02X})"` so the value is preserved (e.g. `Reserved(0x1A)` →
63///   `reserved(0x1A)`, `UserDefined(0x1A)` → `user defined(0x1A)`). All other
64///   variants delegate to `name()`.
65///
66/// ```
67/// pub enum Mode { Normal, HighEfficiency, Reserved(u8) }
68/// impl Mode {
69///     pub fn name(&self) -> &'static str {
70///         match self {
71///             Self::Normal => "normal",
72///             Self::HighEfficiency => "high efficiency",
73///             Self::Reserved(_) => "reserved",
74///         }
75///     }
76/// }
77/// dvb_common::impl_spec_display!(Mode, Reserved);
78/// assert_eq!(Mode::Normal.to_string(), "normal");
79/// assert_eq!(Mode::Reserved(0x1A).to_string(), "reserved(0x1A)");
80/// ```
81#[macro_export]
82macro_rules! impl_spec_display {
83    ($ty:ty) => {
84        impl ::core::fmt::Display for $ty {
85            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
86                f.write_str(self.name())
87            }
88        }
89    };
90    ($ty:ty, $($resv:ident),+ $(,)?) => {
91        impl ::core::fmt::Display for $ty {
92            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
93                match self {
94                    $( Self::$resv(v) => ::core::write!(f, "{}(0x{:02X})", self.name(), v), )+
95                    other => f.write_str(other.name()),
96                }
97            }
98        }
99    };
100}