dvb_si/tables/any.rs
1//! Unified table-section dispatch: [`AnyTableSection`].
2//!
3//! [`AnyTableSection`] is generated from a single declarative list
4//! (`declare_tables!`) — one line per crate-implemented section type.
5//! The list is the single source of truth: it produces the enum, the
6//! `From<T>` conversions, the table_id range dispatcher, and a drift test
7//! that pins each range literal to the type's
8//! [`crate::traits::TableDef::TABLE_ID_RANGES`].
9//!
10//! [`AnyTableSection::parse`] dispatches on the first byte (table_id) using range
11//! patterns. An unrecognised table_id yields
12//! `AnyTableSection::Unknown { table_id, raw }` — the full section bytes are
13//! retained.
14//!
15//! [`AnyTableSection::parse_as`] is a type-keyed thin alias to `T::parse` — it
16//! bypasses dispatch entirely and lets callers obtain, for example, a
17//! [`crate::tables::mpe::MpeDatagramSection`] for a `0x3E` section that the
18//! default dispatcher would route to `DsmccSection`.
19//!
20//! ```
21//! use dvb_common::Serialize;
22//! use dvb_si::tables::AnyTableSection;
23//! use dvb_si::tables::pat::{PatSection, PatEntry};
24//!
25//! // Serialize a small PAT, then dispatch the bytes back through AnyTableSection::parse.
26//! let pat = PatSection {
27//! transport_stream_id: 1, version_number: 0, current_next_indicator: true,
28//! section_number: 0, last_section_number: 0,
29//! entries: vec![PatEntry { program_number: 1, pid: 0x0100 }],
30//! };
31//! let mut section = vec![0u8; pat.serialized_len()];
32//! pat.serialize_into(&mut section).unwrap();
33//!
34//! match AnyTableSection::parse(§ion).unwrap() {
35//! AnyTableSection::PatSection(parsed) => assert_eq!(parsed.entries[0].pid, 0x0100),
36//! other => panic!("expected PatSection, got {other:?}"),
37//! }
38//! ```
39//!
40//! # Adding a section parser
41//!
42//! 1. Create the module with the wire layout, a `pub const TABLE_ID: u8` (or
43//! `TABLE_ID_FIRST`/`TABLE_ID_LAST` for a range), and the symmetric
44//! [`dvb_common::Parse`]/[`dvb_common::Serialize`] impls + round-trip tests
45//! (copy an existing module).
46//! 2. `impl TableDef` for the type (`TABLE_ID_RANGES` covering the full
47//! table_id range, `NAME` in SCREAMING_SNAKE without the `_section` or
48//! `_table` suffix).
49//! 3. Add one line to the `declare_tables!` invocation below — the enum
50//! variant, dispatcher arm, and drift test entry are generated from it.
51//! If the type should NOT be auto-dispatched (e.g. `MpeDatagramSection`,
52//! whose `0x3E` id is claimed by the `DsmccSection` range), add it to the
53//! `@no_dispatch` section instead.
54//! 4. The disjointness test in `declare_tables_tests` catches any overlapping
55//! range entries automatically — no manual test edits needed.
56
57/// Declares [`AnyTableSection`] + its dispatcher from one range list.
58///
59/// Each dispatch line is `Variant = [lo..=hi, …] => module::Type[<'a>]`.
60/// The optional trailing `@no_dispatch …` section adds variants that are NOT
61/// reachable from the generated dispatcher — the variant exists for callers
62/// that obtain the type via `AnyTableSection::parse_as` or direct `T::parse`.
63macro_rules! declare_tables {
64 (
65 $lt:lifetime;
66 $( $variant:ident = [ $( $lo:literal ..= $hi:literal ),+ ] => $($path:ident)::+ $(<$plt:lifetime>)? ),+ $(,)?
67 $( ; @no_dispatch $( $nd_variant:ident => $($nd_path:ident)::+ $(<$nd_plt:lifetime>)? ),+ $(,)? )?
68 ) => {
69 /// Every crate-implemented table-section parser, plus an `Unknown`
70 /// fallthrough.
71 ///
72 /// serde uses external tagging with camelCase variant keys — a parsed
73 /// PAT section serializes as `{"patSection": {…}}`.
74 /// Variant names map 1:1 to section parser types; see each module for
75 /// the wire layout.
76 ///
77 /// `0x3E` (`datagram_section`) is routed to `DsmccSection` by the
78 /// default dispatcher. The typed MPE view is reachable via
79 /// `AnyTableSection::parse_as::<MpeDatagramSection>` or
80 /// `MpeDatagramSection::parse` directly; the `MpeDatagram` variant
81 /// exists in this enum for API completeness but is never produced by
82 /// `AnyTableSection::parse`.
83 #[derive(Debug)]
84 #[cfg_attr(feature = "serde", derive(serde::Serialize))]
85 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
86 // Covariant in `$lt`: every variant holds only lifetime-parametrised
87 // table views or `&$lt [u8]` (`Unknown`), so the derived impl is sound.
88 #[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
89 #[non_exhaustive]
90 pub enum AnyTableSection<$lt> {
91 $(
92 #[allow(missing_docs)]
93 $variant($($path)::+ $(<$plt>)?),
94 )+
95 $($(
96 #[allow(missing_docs)]
97 $nd_variant($($nd_path)::+ $(<$nd_plt>)?),
98 )+)?
99 /// table_id with no typed implementation; `raw` is the full
100 /// section bytes including the table_id header.
101 Unknown {
102 /// The raw table_id byte.
103 table_id: u8,
104 /// The raw section bytes (full, header included).
105 raw: &$lt [u8],
106 },
107 }
108
109 $(
110 impl<$lt> From<$($path)::+ $(<$plt>)?> for AnyTableSection<$lt> {
111 fn from(t: $($path)::+ $(<$plt>)?) -> Self {
112 Self::$variant(t)
113 }
114 }
115 )+
116 $($(
117 impl<$lt> From<$($nd_path)::+ $(<$nd_plt>)?> for AnyTableSection<$lt> {
118 fn from(t: $($nd_path)::+ $(<$nd_plt>)?) -> Self {
119 Self::$nd_variant(t)
120 }
121 }
122 )+)?
123
124 impl<$lt> AnyTableSection<$lt> {
125 /// All table_id ranges covered by the auto-dispatcher (excludes
126 /// `@no_dispatch` variants). Each entry is `(lo, hi)` inclusive.
127 pub const DISPATCHED_RANGES: &'static [(u8, u8)] =
128 &[$( $( ($lo, $hi) ),+ ),+];
129
130 /// Diagnostic name of the contained table — the type's
131 /// [`TableDef::NAME`](crate::traits::TableDef::NAME)
132 /// (`"EVENT_INFORMATION"`, `"PROGRAM_ASSOCIATION"`, …);
133 /// `"UNKNOWN"` for [`AnyTableSection::Unknown`].
134 #[must_use]
135 pub fn name(&self) -> &'static str {
136 match self {
137 $(
138 Self::$variant(_) =>
139 <$($path)::+ as crate::traits::TableDef>::NAME,
140 )+
141 $($(
142 Self::$nd_variant(_) =>
143 <$($nd_path)::+ as crate::traits::TableDef>::NAME,
144 )+)?
145 Self::Unknown { .. } => "UNKNOWN",
146 }
147 }
148
149 /// Dispatch one complete section by its table_id (byte 0).
150 ///
151 /// Returns `Err(BufferTooShort)` when `bytes` is empty.
152 /// Unknown table_ids produce `Ok(AnyTableSection::Unknown { … })`.
153 ///
154 /// # Errors
155 /// - [`crate::Error::BufferTooShort`] — `bytes` is empty.
156 /// - Any parse error from the dispatched type.
157 pub fn parse(bytes: &$lt [u8]) -> crate::Result<Self> {
158 let table_id = *bytes.first().ok_or(crate::Error::BufferTooShort {
159 need: 1,
160 have: 0,
161 what: "section table_id",
162 })?;
163 match table_id {
164 $(
165 $( $lo..=$hi )|+ => {
166 <$($path)::+ as dvb_common::Parse>::parse(bytes).map(Self::$variant)
167 }
168 )+
169 _ => Ok(Self::Unknown { table_id, raw: bytes }),
170 }
171 }
172
173 /// Type-keyed parse: bypass the dispatcher and parse `bytes`
174 /// directly as `T`. Useful for types excluded from the default
175 /// dispatch, e.g.:
176 ///
177 /// ```rust
178 /// use dvb_si::tables::AnyTableSection;
179 /// use dvb_si::tables::mpe::MpeDatagramSection;
180 ///
181 /// // A deliberately-too-short slice: parse_as propagates the
182 /// // BufferTooShort error from MpeDatagramSection::parse.
183 /// let err = AnyTableSection::parse_as::<MpeDatagramSection>(&[0x3E, 0x00]);
184 /// assert!(err.is_err());
185 /// ```
186 ///
187 /// # Errors
188 /// Propagates `T::parse` errors.
189 pub fn parse_as<T>(bytes: &$lt [u8]) -> crate::Result<T>
190 where
191 T: crate::traits::TableDef<$lt>,
192 {
193 <T as dvb_common::Parse>::parse(bytes)
194 }
195 }
196
197 #[cfg(test)]
198 mod macro_drift {
199 #[test]
200 fn ranges_match_tabledef() {
201 use crate::traits::TableDef;
202 $(
203 assert_eq!(
204 &[ $( ($lo, $hi) ),+ ][..],
205 <$($path)::+ as TableDef>::TABLE_ID_RANGES,
206 concat!("TABLE_ID_RANGES drift for ", stringify!($variant)),
207 );
208 assert!(
209 !<$($path)::+ as TableDef>::NAME.is_empty(),
210 concat!("empty NAME for ", stringify!($variant)),
211 );
212 )+
213 $($(
214 assert!(
215 !<$($nd_path)::+ as TableDef>::NAME.is_empty(),
216 concat!("empty NAME for no-dispatch ", stringify!($nd_variant)),
217 );
218 )+)?
219 }
220
221 #[test]
222 fn dispatched_ranges_are_disjoint() {
223 // Collect all (lo, hi) pairs, sort by lo, then check no
224 // two adjacent entries overlap.
225 let mut ranges: Vec<(u8, u8)> = vec![
226 $( $( ($lo, $hi), )+ )+
227 ];
228 ranges.sort_by_key(|r| r.0);
229 for w in ranges.windows(2) {
230 let (_, prev_hi) = w[0];
231 let (next_lo, _) = w[1];
232 assert!(
233 next_lo > prev_hi,
234 "overlapping dispatch ranges: {w:?}",
235 );
236 }
237 }
238 }
239 };
240}
241
242declare_tables! {'a;
243 // MPEG-2 systems tables (ISO/IEC 13818-1).
244 PatSection = [0x00..=0x00] => crate::tables::pat::PatSection,
245 CatSection = [0x01..=0x01] => crate::tables::cat::CatSection<'a>,
246 PmtSection = [0x02..=0x02] => crate::tables::pmt::PmtSection<'a>,
247 TsdtSection = [0x03..=0x03] => crate::tables::tsdt::TsdtSection<'a>,
248 // DSM-CC sections (ISO/IEC 13818-6) — 0x3E is included; the MPE typed
249 // view (`MpeDatagramSection`) is reachable via `AnyTableSection::parse_as` or
250 // `MpeDatagramSection::parse`.
251 DsmccSection = [0x3A..=0x3F] => crate::tables::dsmcc::DsmccSection<'a>,
252 // DVB tables (ETSI EN 300 468).
253 NitSection = [0x40..=0x41] => crate::tables::nit::NitSection<'a>,
254 SdtSection = [0x42..=0x42, 0x46..=0x46] => crate::tables::sdt::SdtSection<'a>,
255 BatSection = [0x4A..=0x4A] => crate::tables::bat::BatSection<'a>,
256 UntSection = [0x4B..=0x4B] => crate::tables::unt::UntSection<'a>,
257 IntSection = [0x4C..=0x4C] => crate::tables::int::IntSection<'a>,
258 SatSection = [0x4D..=0x4D] => crate::tables::sat::SatSection<'a>,
259 EitSection = [0x4E..=0x6F] => crate::tables::eit::EitSection<'a>,
260 TdtSection = [0x70..=0x70] => crate::tables::tdt::TdtSection,
261 RstSection = [0x71..=0x71] => crate::tables::rst::RstSection,
262 StSection = [0x72..=0x72] => crate::tables::st::StSection,
263 TotSection = [0x73..=0x73] => crate::tables::tot::TotSection<'a>,
264 AitSection = [0x74..=0x74] => crate::tables::ait::AitSection<'a>,
265 ContainerSection = [0x75..=0x75] => crate::tables::container::ContainerSection<'a>,
266 RctSection = [0x76..=0x76] => crate::tables::rct::RctSection<'a>,
267 CitSection = [0x77..=0x77] => crate::tables::cit::CitSection<'a>,
268 MpeFecSection = [0x78..=0x78] => crate::tables::mpe_fec::MpeFecSection<'a>,
269 RntSection = [0x79..=0x79] => crate::tables::rnt::RntSection<'a>,
270 MpeIfecSection = [0x7A..=0x7A] => crate::tables::mpe_ifec::MpeIfecSection<'a>,
271 ProtectionMessage = [0x7B..=0x7B] => crate::tables::protection_message::ProtectionMessageSection<'a>,
272 DownloadableFontInfo = [0x7C..=0x7C] => crate::tables::downloadable_font_info::DownloadableFontInfoSection<'a>,
273 DitSection = [0x7E..=0x7E] => crate::tables::dit::DitSection,
274 SitSection = [0x7F..=0x7F] => crate::tables::sit::SitSection<'a>;
275 // MPE datagram_section (ETSI EN 301 192 §7.1): table_id 0x3E overlaps
276 // the DsmccSection range above, so it is NOT auto-dispatched. Use
277 // `AnyTableSection::parse_as::<MpeDatagramSection>(bytes)` for the typed view.
278 @no_dispatch
279 MpeDatagram => crate::tables::mpe::MpeDatagramSection<'a>,
280}