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