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