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 /// Runtime-registered custom table section (see [`TableRegistry`]).
100 ///
101 /// [`TableRegistry`]: crate::tables::registry::TableRegistry
102 Other {
103 /// The raw table_id byte.
104 table_id: u8,
105 /// The parsed, type-erased table-section value. Call `downcast_ref`
106 /// on it (see [`TableObject`](crate::tables::registry::TableObject))
107 /// to recover the concrete type.
108 #[cfg_attr(
109 feature = "serde",
110 serde(serialize_with = "crate::tables::registry::serialize_erased")
111 )]
112 value: Box<dyn crate::tables::registry::TableObject>,
113 },
114 /// table_id with no typed implementation; `raw` is the full
115 /// section bytes including the table_id header.
116 Unknown {
117 /// The raw table_id byte.
118 table_id: u8,
119 /// The raw section bytes (full, header included).
120 raw: &$lt [u8],
121 },
122 }
123
124 $(
125 impl<$lt> From<$($path)::+ $(<$plt>)?> for AnyTableSection<$lt> {
126 fn from(t: $($path)::+ $(<$plt>)?) -> Self {
127 Self::$variant(t)
128 }
129 }
130 )+
131 $($(
132 impl<$lt> From<$($nd_path)::+ $(<$nd_plt>)?> for AnyTableSection<$lt> {
133 fn from(t: $($nd_path)::+ $(<$nd_plt>)?) -> Self {
134 Self::$nd_variant(t)
135 }
136 }
137 )+)?
138
139 impl<$lt> AnyTableSection<$lt> {
140 /// All table_id ranges covered by the auto-dispatcher (excludes
141 /// `@no_dispatch` variants). Each entry is `(lo, hi)` inclusive.
142 pub const DISPATCHED_RANGES: &'static [(u8, u8)] =
143 &[$( $( ($lo, $hi) ),+ ),+];
144
145 /// Diagnostic name of the contained table — the type's
146 /// [`TableDef::NAME`](crate::traits::TableDef::NAME)
147 /// (`"EVENT_INFORMATION"`, `"PROGRAM_ASSOCIATION"`, …);
148 /// `"UNKNOWN"` for [`AnyTableSection::Unknown`].
149 #[must_use]
150 pub fn name(&self) -> &'static str {
151 match self {
152 $(
153 Self::$variant(_) =>
154 <$($path)::+ as crate::traits::TableDef>::NAME,
155 )+
156 $($(
157 Self::$nd_variant(_) =>
158 <$($nd_path)::+ as crate::traits::TableDef>::NAME,
159 )+)?
160 Self::Other { .. } => "CUSTOM",
161 Self::Unknown { .. } => "UNKNOWN",
162 }
163 }
164
165 /// Dispatch one complete section by its table_id (byte 0).
166 ///
167 /// Returns `Err(BufferTooShort)` when `bytes` is empty.
168 /// Unknown table_ids produce `Ok(AnyTableSection::Unknown { … })`.
169 ///
170 /// # Errors
171 /// - [`crate::Error::BufferTooShort`] — `bytes` is empty.
172 /// - Any parse error from the dispatched type.
173 pub fn parse(bytes: &$lt [u8]) -> crate::Result<Self> {
174 let table_id = *bytes.first().ok_or(crate::Error::BufferTooShort {
175 need: 1,
176 have: 0,
177 what: "section table_id",
178 })?;
179 match table_id {
180 $(
181 $( $lo..=$hi )|+ => {
182 <$($path)::+ as dvb_common::Parse>::parse(bytes).map(Self::$variant)
183 }
184 )+
185 _ => Ok(Self::Unknown { table_id, raw: bytes }),
186 }
187 }
188
189 /// Type-keyed parse: bypass the dispatcher and parse `bytes`
190 /// directly as `T`. Useful for types excluded from the default
191 /// dispatch, e.g.:
192 ///
193 /// ```rust
194 /// use dvb_si::tables::AnyTableSection;
195 /// use dvb_si::tables::mpe::MpeDatagramSection;
196 ///
197 /// // A deliberately-too-short slice: parse_as propagates the
198 /// // BufferTooShort error from MpeDatagramSection::parse.
199 /// let err = AnyTableSection::parse_as::<MpeDatagramSection>(&[0x3E, 0x00]);
200 /// assert!(err.is_err());
201 /// ```
202 ///
203 /// # Errors
204 /// Propagates `T::parse` errors.
205 pub fn parse_as<T>(bytes: &$lt [u8]) -> crate::Result<T>
206 where
207 T: crate::traits::TableDef<$lt>,
208 {
209 <T as dvb_common::Parse>::parse(bytes)
210 }
211 }
212
213 #[cfg(test)]
214 mod macro_drift {
215 #[test]
216 fn ranges_match_tabledef() {
217 use crate::traits::TableDef;
218 $(
219 assert_eq!(
220 &[ $( ($lo, $hi) ),+ ][..],
221 <$($path)::+ as TableDef>::TABLE_ID_RANGES,
222 concat!("TABLE_ID_RANGES drift for ", stringify!($variant)),
223 );
224 assert!(
225 !<$($path)::+ as TableDef>::NAME.is_empty(),
226 concat!("empty NAME for ", stringify!($variant)),
227 );
228 )+
229 $($(
230 assert!(
231 !<$($nd_path)::+ as TableDef>::NAME.is_empty(),
232 concat!("empty NAME for no-dispatch ", stringify!($nd_variant)),
233 );
234 )+)?
235 }
236
237 #[test]
238 fn dispatched_ranges_are_disjoint() {
239 // Collect all (lo, hi) pairs, sort by lo, then check no
240 // two adjacent entries overlap.
241 let mut ranges: Vec<(u8, u8)> = vec![
242 $( $( ($lo, $hi), )+ )+
243 ];
244 ranges.sort_by_key(|r| r.0);
245 for w in ranges.windows(2) {
246 let (_, prev_hi) = w[0];
247 let (next_lo, _) = w[1];
248 assert!(
249 next_lo > prev_hi,
250 "overlapping dispatch ranges: {w:?}",
251 );
252 }
253 }
254 }
255 };
256}
257
258declare_tables! {'a;
259 // MPEG-2 systems tables (ISO/IEC 13818-1).
260 PatSection = [0x00..=0x00] => crate::tables::pat::PatSection,
261 CatSection = [0x01..=0x01] => crate::tables::cat::CatSection<'a>,
262 PmtSection = [0x02..=0x02] => crate::tables::pmt::PmtSection<'a>,
263 TsdtSection = [0x03..=0x03] => crate::tables::tsdt::TsdtSection<'a>,
264 // DSM-CC sections (ISO/IEC 13818-6) — 0x3E is included; the MPE typed
265 // view (`MpeDatagramSection`) is reachable via `AnyTableSection::parse_as` or
266 // `MpeDatagramSection::parse`.
267 DsmccSection = [0x3A..=0x3F] => crate::tables::dsmcc::DsmccSection<'a>,
268 // DVB tables (ETSI EN 300 468).
269 NitSection = [0x40..=0x41] => crate::tables::nit::NitSection<'a>,
270 SdtSection = [0x42..=0x42, 0x46..=0x46] => crate::tables::sdt::SdtSection<'a>,
271 BatSection = [0x4A..=0x4A] => crate::tables::bat::BatSection<'a>,
272 UntSection = [0x4B..=0x4B] => crate::tables::unt::UntSection<'a>,
273 IntSection = [0x4C..=0x4C] => crate::tables::int::IntSection<'a>,
274 SatSection = [0x4D..=0x4D] => crate::tables::sat::SatSection,
275 EitSection = [0x4E..=0x6F] => crate::tables::eit::EitSection<'a>,
276 TdtSection = [0x70..=0x70] => crate::tables::tdt::TdtSection,
277 RstSection = [0x71..=0x71] => crate::tables::rst::RstSection,
278 StSection = [0x72..=0x72] => crate::tables::st::StSection,
279 TotSection = [0x73..=0x73] => crate::tables::tot::TotSection<'a>,
280 AitSection = [0x74..=0x74] => crate::tables::ait::AitSection<'a>,
281 ContainerSection = [0x75..=0x75] => crate::tables::container::ContainerSection<'a>,
282 RctSection = [0x76..=0x76] => crate::tables::rct::RctSection<'a>,
283 CitSection = [0x77..=0x77] => crate::tables::cit::CitSection<'a>,
284 MpeFecSection = [0x78..=0x78] => crate::tables::mpe_fec::MpeFecSection<'a>,
285 RntSection = [0x79..=0x79] => crate::tables::rnt::RntSection<'a>,
286 MpeIfecSection = [0x7A..=0x7A] => crate::tables::mpe_ifec::MpeIfecSection<'a>,
287 ProtectionMessage = [0x7B..=0x7B] => crate::tables::protection_message::ProtectionMessageSection<'a>,
288 DownloadableFontInfo = [0x7C..=0x7C] => crate::tables::downloadable_font_info::DownloadableFontInfoSection<'a>,
289 DitSection = [0x7E..=0x7E] => crate::tables::dit::DitSection,
290 SitSection = [0x7F..=0x7F] => crate::tables::sit::SitSection<'a>;
291 // MPE datagram_section (ETSI EN 301 192 §7.1): table_id 0x3E overlaps
292 // the DsmccSection range above, so it is NOT auto-dispatched. Use
293 // `AnyTableSection::parse_as::<MpeDatagramSection>(bytes)` for the typed view.
294 @no_dispatch
295 MpeDatagram => crate::tables::mpe::MpeDatagramSection<'a>,
296}
297
298impl<'a> AnyTableSection<'a> {
299 /// Dispatch one complete section with custom-registry support.
300 ///
301 /// Precedence: (1) if the registry has a custom parser for the section's
302 /// table_id, use it → [`AnyTableSection::Other`]; (2) else delegate to
303 /// [`AnyTableSection::parse`] (built-in dispatch, which itself falls to
304 /// [`AnyTableSection::Unknown`]).
305 ///
306 /// # Errors
307 /// - [`crate::Error::BufferTooShort`] — `bytes` is empty.
308 /// - Any parse error from the dispatched type.
309 pub fn parse_with(
310 registry: &crate::tables::registry::TableRegistry,
311 bytes: &'a [u8],
312 ) -> crate::Result<Self> {
313 let table_id = *bytes.first().ok_or(crate::Error::BufferTooShort {
314 need: 1,
315 have: 0,
316 what: "section table_id",
317 })?;
318 if let Some(parse_fn) = registry.lookup(table_id) {
319 let value = parse_fn(bytes)?;
320 return Ok(Self::Other { table_id, value });
321 }
322 Self::parse(bytes)
323 }
324}