Skip to main content

dvb_si/tables/
any.rs

1//! Unified table dispatch: [`AnyTable`].
2//!
3//! [`AnyTable`] is generated from a single declarative list
4//! (`declare_tables!`) — one line per crate-implemented table 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//! [`AnyTable::parse`] dispatches on the first byte (table_id) using range
11//! patterns. An unrecognised table_id yields
12//! `AnyTable::Unknown { table_id, raw }` — the full section bytes are
13//! retained.
14//!
15//! [`AnyTable::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::AnyTable;
23//! use dvb_si::tables::pat::{Pat, PatEntry};
24//!
25//! // Serialize a small PAT, then dispatch the bytes back through AnyTable::parse.
26//! let pat = Pat {
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 AnyTable::parse(&section).unwrap() {
35//!     AnyTable::Pat(parsed) => assert_eq!(parsed.entries[0].pid, 0x0100),
36//!     other => panic!("expected Pat, got {other:?}"),
37//! }
38//! ```
39//!
40//! # Adding a table
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 [`AnyTable`] + 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 `AnyTable::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, plus an `Unknown` fallthrough.
70        ///
71        /// serde uses external tagging with camelCase variant keys — a parsed
72        /// PAT serializes as `{"pat": {…}}`.
73        /// Variant names map 1:1 to the table modules; see each module for the
74        /// wire layout.
75        ///
76        /// `0x3E` (`datagram_section`) is routed to `DsmccSection` by the
77        /// default dispatcher. The typed MPE view is reachable via
78        /// `AnyTable::parse_as::<MpeDatagramSection>` or
79        /// `MpeDatagramSection::parse` directly; the `MpeDatagram` variant
80        /// exists in this enum for API completeness but is never produced by
81        /// `AnyTable::parse`.
82        #[derive(Debug)]
83        #[cfg_attr(feature = "serde", derive(serde::Serialize))]
84        #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
85        // Covariant in `$lt`: every variant holds only lifetime-parametrised
86        // table views or `&$lt [u8]` (`Unknown`), so the derived impl is sound.
87        #[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
88        #[non_exhaustive]
89        pub enum AnyTable<$lt> {
90            $(
91                #[allow(missing_docs)]
92                $variant($($path)::+ $(<$plt>)?),
93            )+
94            $($(
95                #[allow(missing_docs)]
96                $nd_variant($($nd_path)::+ $(<$nd_plt>)?),
97            )+)?
98            /// table_id with no typed implementation; `raw` is the full
99            /// section bytes including the table_id header.
100            Unknown {
101                /// The raw table_id byte.
102                table_id: u8,
103                /// The raw section bytes (full, header included).
104                raw: &$lt [u8],
105            },
106        }
107
108        $(
109            impl<$lt> From<$($path)::+ $(<$plt>)?> for AnyTable<$lt> {
110                fn from(t: $($path)::+ $(<$plt>)?) -> Self {
111                    Self::$variant(t)
112                }
113            }
114        )+
115        $($(
116            impl<$lt> From<$($nd_path)::+ $(<$nd_plt>)?> for AnyTable<$lt> {
117                fn from(t: $($nd_path)::+ $(<$nd_plt>)?) -> Self {
118                    Self::$nd_variant(t)
119                }
120            }
121        )+)?
122
123        impl<$lt> AnyTable<$lt> {
124            /// All table_id ranges covered by the auto-dispatcher (excludes
125            /// `@no_dispatch` variants). Each entry is `(lo, hi)` inclusive.
126            pub const DISPATCHED_RANGES: &'static [(u8, u8)] =
127                &[$( $( ($lo, $hi) ),+ ),+];
128
129            /// Diagnostic name of the contained table — the type's
130            /// [`TableDef::NAME`](crate::traits::TableDef::NAME)
131            /// (`"EVENT_INFORMATION"`, `"PROGRAM_ASSOCIATION"`, …);
132            /// `"UNKNOWN"` for [`AnyTable::Unknown`].
133            #[must_use]
134            pub fn name(&self) -> &'static str {
135                match self {
136                    $(
137                        Self::$variant(_) =>
138                            <$($path)::+ as crate::traits::TableDef>::NAME,
139                    )+
140                    $($(
141                        Self::$nd_variant(_) =>
142                            <$($nd_path)::+ as crate::traits::TableDef>::NAME,
143                    )+)?
144                    Self::Unknown { .. } => "UNKNOWN",
145                }
146            }
147
148            /// Dispatch one complete section by its table_id (byte 0).
149            ///
150            /// Returns `Err(BufferTooShort)` when `bytes` is empty.
151            /// Unknown table_ids produce `Ok(AnyTable::Unknown { … })`.
152            ///
153            /// # Errors
154            /// - [`crate::Error::BufferTooShort`] — `bytes` is empty.
155            /// - Any parse error from the dispatched type.
156            pub fn parse(bytes: &$lt [u8]) -> crate::Result<Self> {
157                let table_id = *bytes.first().ok_or(crate::Error::BufferTooShort {
158                    need: 1,
159                    have: 0,
160                    what: "section table_id",
161                })?;
162                match table_id {
163                    $(
164                        $( $lo..=$hi )|+ => {
165                            <$($path)::+ as dvb_common::Parse>::parse(bytes).map(Self::$variant)
166                        }
167                    )+
168                    _ => Ok(Self::Unknown { table_id, raw: bytes }),
169                }
170            }
171
172            /// Type-keyed parse: bypass the dispatcher and parse `bytes`
173            /// directly as `T`. Useful for types excluded from the default
174            /// dispatch, e.g.:
175            ///
176            /// ```rust
177            /// use dvb_si::tables::AnyTable;
178            /// use dvb_si::tables::mpe::MpeDatagramSection;
179            ///
180            /// // A deliberately-too-short slice: parse_as propagates the
181            /// // BufferTooShort error from MpeDatagramSection::parse.
182            /// let err = AnyTable::parse_as::<MpeDatagramSection>(&[0x3E, 0x00]);
183            /// assert!(err.is_err());
184            /// ```
185            ///
186            /// # Errors
187            /// Propagates `T::parse` errors.
188            pub fn parse_as<T>(bytes: &$lt [u8]) -> crate::Result<T>
189            where
190                T: crate::traits::TableDef<$lt>,
191            {
192                <T as dvb_common::Parse>::parse(bytes)
193            }
194        }
195
196        #[cfg(test)]
197        mod macro_drift {
198            #[test]
199            fn ranges_match_tabledef() {
200                use crate::traits::TableDef;
201                $(
202                    assert_eq!(
203                        &[ $( ($lo, $hi) ),+ ][..],
204                        <$($path)::+ as TableDef>::TABLE_ID_RANGES,
205                        concat!("TABLE_ID_RANGES drift for ", stringify!($variant)),
206                    );
207                    assert!(
208                        !<$($path)::+ as TableDef>::NAME.is_empty(),
209                        concat!("empty NAME for ", stringify!($variant)),
210                    );
211                )+
212                $($(
213                    assert!(
214                        !<$($nd_path)::+ as TableDef>::NAME.is_empty(),
215                        concat!("empty NAME for no-dispatch ", stringify!($nd_variant)),
216                    );
217                )+)?
218            }
219
220            #[test]
221            fn dispatched_ranges_are_disjoint() {
222                // Collect all (lo, hi) pairs, sort by lo, then check no
223                // two adjacent entries overlap.
224                let mut ranges: Vec<(u8, u8)> = vec![
225                    $( $( ($lo, $hi), )+ )+
226                ];
227                ranges.sort_by_key(|r| r.0);
228                for w in ranges.windows(2) {
229                    let (_, prev_hi) = w[0];
230                    let (next_lo, _) = w[1];
231                    assert!(
232                        next_lo > prev_hi,
233                        "overlapping dispatch ranges: {w:?}",
234                    );
235                }
236            }
237        }
238    };
239}
240
241declare_tables! {'a;
242    // MPEG-2 systems tables (ISO/IEC 13818-1).
243    Pat       = [0x00..=0x00] => crate::tables::pat::Pat,
244    Cat       = [0x01..=0x01] => crate::tables::cat::Cat<'a>,
245    Pmt       = [0x02..=0x02] => crate::tables::pmt::Pmt<'a>,
246    Tsdt      = [0x03..=0x03] => crate::tables::tsdt::Tsdt<'a>,
247    // DSM-CC sections (ISO/IEC 13818-6) — 0x3E is included; the MPE typed
248    // view (`MpeDatagramSection`) is reachable via `AnyTable::parse_as` or
249    // `MpeDatagramSection::parse`.
250    DsmccSection = [0x3A..=0x3F] => crate::tables::dsmcc::DsmccSection<'a>,
251    // DVB tables (ETSI EN 300 468).
252    Nit       = [0x40..=0x41] => crate::tables::nit::Nit<'a>,
253    Sdt       = [0x42..=0x42, 0x46..=0x46] => crate::tables::sdt::Sdt<'a>,
254    Bat       = [0x4A..=0x4A] => crate::tables::bat::Bat<'a>,
255    Unt       = [0x4B..=0x4B] => crate::tables::unt::Unt<'a>,
256    Int       = [0x4C..=0x4C] => crate::tables::int::Int<'a>,
257    Sat       = [0x4D..=0x4D] => crate::tables::sat::Sat<'a>,
258    Eit       = [0x4E..=0x6F] => crate::tables::eit::Eit<'a>,
259    Tdt       = [0x70..=0x70] => crate::tables::tdt::Tdt,
260    Rst       = [0x71..=0x71] => crate::tables::rst::Rst,
261    St        = [0x72..=0x72] => crate::tables::st::St,
262    Tot       = [0x73..=0x73] => crate::tables::tot::Tot<'a>,
263    Ait       = [0x74..=0x74] => crate::tables::ait::Ait<'a>,
264    Container = [0x75..=0x75] => crate::tables::container::Container<'a>,
265    Rct       = [0x76..=0x76] => crate::tables::rct::Rct<'a>,
266    Cit       = [0x77..=0x77] => crate::tables::cit::Cit<'a>,
267    MpeFec    = [0x78..=0x78] => crate::tables::mpe_fec::MpeFec<'a>,
268    Rnt       = [0x79..=0x79] => crate::tables::rnt::Rnt<'a>,
269    MpeIfec   = [0x7A..=0x7A] => crate::tables::mpe_ifec::MpeIfec<'a>,
270    ProtectionMessage    = [0x7B..=0x7B] => crate::tables::protection_message::ProtectionMessageSection<'a>,
271    DownloadableFontInfo = [0x7C..=0x7C] => crate::tables::downloadable_font_info::DownloadableFontInfoSection<'a>,
272    Dit       = [0x7E..=0x7E] => crate::tables::dit::Dit,
273    Sit       = [0x7F..=0x7F] => crate::tables::sit::Sit<'a>;
274    // MPE datagram_section (ETSI EN 301 192 §7.1): table_id 0x3E overlaps
275    // the DsmccSection range above, so it is NOT auto-dispatched. Use
276    // `AnyTable::parse_as::<MpeDatagramSection>(bytes)` for the typed view.
277    @no_dispatch
278    MpeDatagram => crate::tables::mpe::MpeDatagramSection<'a>,
279}