Skip to main content

dvb_si/tables/
registry.rs

1//! Runtime table registry — open registration of client private table_ids.
2//!
3//! [`TableRegistry`] allows clients to register their own private table types.
4//! Registered custom parsers win over built-in dispatch; an unregistered
5//! table_id falls through to [`crate::tables::AnyTableSection::Unknown`].
6//!
7//! # Owned types only
8//!
9//! Registered types must be `'static` (i.e. owned — no borrowed slices).
10//! This is required because the parsed value is heap-allocated as a
11//! `Box<dyn TableObject>` whose concrete type is erased; `dyn Any`
12//! downcast demands `'static`.  If your wire layout contains borrowed bytes,
13//! copy them into a `Vec<u8>` in the struct.
14//!
15//! # Example
16//!
17//! ```rust,no_run
18//! use dvb_si::tables::{TableRegistry, AnyTableSection};
19//! use dvb_si::traits::TableDef;
20//! use broadcast_core::{Parse, ParseWith};
21//!
22//! // A registered type must be `serde::Serialize` only when the `serde`
23//! // feature is on (that is what `TableObject` requires there).
24//! #[derive(Debug)]
25//! #[cfg_attr(feature = "serde", derive(serde::Serialize))]
26//! struct MyPrivate { x: u8 }
27//!
28//! impl<'a> Parse<'a> for MyPrivate {
29//!     type Error = dvb_si::Error;
30//!     fn parse(bytes: &'a [u8]) -> dvb_si::Result<Self> {
31//!         if bytes.len() < 2 {
32//!             return Err(dvb_si::Error::BufferTooShort(broadcast_core::error::BufferTooShort::new(
33//!                 2, bytes.len(), "MyPrivate",
34//!             )));
35//!         }
36//!         Ok(Self { x: bytes[1] })
37//!     }
38//! }
39//!
40//! impl<'a> TableDef<'a> for MyPrivate {
41//!     const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(0x90, 0x90)];
42//!     const NAME: &'static str = "MY_PRIVATE";
43//! }
44//!
45//! let mut reg = TableRegistry::new();
46//! reg.register::<MyPrivate>();
47//!
48//! let bytes = [0x90, 0x00, 0x42u8];
49//! match AnyTableSection::parse_with(&bytes, &reg).unwrap() {
50//!     AnyTableSection::Other { table_id, ref value } => {
51//!         assert_eq!(table_id, 0x90);
52//!         assert_eq!(value.downcast_ref::<MyPrivate>().unwrap().x, 0x42);
53//!     }
54//!     other => panic!("expected Other, got {other:?}"),
55//! }
56//! ```
57
58use alloc::boxed::Box;
59use alloc::collections::BTreeMap;
60
61broadcast_common::declare_object_trait! {
62    /// Object-safe face of a runtime-registered table section value.
63    ///
64    /// Registered types must be owned (`'static`) because the `dyn Any` downcast
65    /// path requires it.  See the [module docs][self] for details.
66    ///
67    /// Implemented automatically via the blanket impl for any `T` satisfying the
68    /// supertraits; you do not need to write this by hand.
69    pub trait TableObject, "table section"
70}
71
72// ---------------------------------------------------------------------------
73// Internal parse closure type
74// ---------------------------------------------------------------------------
75
76/// A heap-allocated parse closure that takes a full section (header + body)
77/// and returns an owned, type-erased table-section value.
78pub(crate) type CustomParse =
79    Box<dyn for<'a> Fn(&'a [u8]) -> crate::Result<Box<dyn TableObject>> + Send + Sync>;
80
81// ---------------------------------------------------------------------------
82// TableRegistry
83// ---------------------------------------------------------------------------
84
85/// Runtime-configurable table registry.
86///
87/// By default the registry has no custom parsers.  Use
88/// [`register`][Self::register] to add one.
89///
90/// # Precedence (per table_id)
91///
92/// 1. Custom-registered parser (table_id in the [`custom`][Self::register] map) →
93///    [`crate::tables::AnyTableSection::Other`]
94/// 2. Built-in dispatch ([`crate::tables::AnyTableSection::parse`]) → typed variant
95/// 3. Unknown → [`crate::tables::AnyTableSection::Unknown`]
96#[derive(Default)]
97pub struct TableRegistry {
98    custom: BTreeMap<u8, CustomParse>,
99}
100
101impl TableRegistry {
102    /// Create an empty registry (built-in dispatch only).
103    #[must_use]
104    pub fn new() -> Self {
105        Self::default()
106    }
107
108    /// Look up a custom parser for the given `table_id`.
109    #[must_use]
110    pub(crate) fn lookup(&self, table_id: u8) -> Option<&CustomParse> {
111        self.custom.get(&table_id)
112    }
113
114    /// Register an owned custom table-section type for every table_id in its
115    /// [`TableDef::TABLE_ID_RANGES`][crate::traits::TableDef::TABLE_ID_RANGES].
116    ///
117    /// # Owned types only
118    ///
119    /// `T` must be `'static` — no borrowed slices.  The registered value is
120    /// type-erased as `Box<dyn TableObject>`; `dyn Any` downcast requires
121    /// the concrete type to be `'static`.
122    ///
123    /// # Multi-range registration
124    ///
125    /// A type may cover multiple table_id ranges (e.g.
126    /// `&[(0x90, 0x90), (0x92, 0x93)]`).  Every table_id in every range is
127    /// registered under the same parse closure.
128    ///
129    /// Registering a type whose table_id is already used by a built-in **overrides**
130    /// the built-in for that table_id.
131    ///
132    /// Re-registering the same table_id replaces the prior custom parser (last wins).
133    /// A failing custom parse surfaces the client's `Parse::Error` unwrapped —
134    /// embed identifying context (type/table_id) in your error's `what`/`reason` fields.
135    pub fn register<T>(&mut self) -> &mut Self
136    where
137        T: for<'a> crate::traits::TableDef<'a> + TableObject + 'static,
138    {
139        let ranges = <T as crate::traits::TableDef<'static>>::TABLE_ID_RANGES;
140        for &(lo, hi) in ranges {
141            for id in lo..=hi {
142                self.custom.insert(
143                    id,
144                    Box::new(|b| {
145                        Ok(Box::new(<T as broadcast_core::Parse>::parse(b)?)
146                            as Box<dyn TableObject>)
147                    }),
148                );
149            }
150        }
151        self
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158    use crate::tables::AnyTableSection;
159    use crate::traits::TableDef;
160    use alloc::{vec, vec::Vec};
161    use broadcast_core::Parse;
162    use broadcast_core::ParseWith;
163
164    // -- A trivial custom table for a private table_id -------------------------
165    const CUSTOM_TABLE_ID: u8 = 0x90;
166
167    #[derive(Debug, PartialEq)]
168    #[cfg_attr(feature = "serde", derive(serde::Serialize))]
169    struct CustomTable {
170        table_id: u8,
171        payload: Vec<u8>,
172    }
173
174    impl<'a> Parse<'a> for CustomTable {
175        type Error = crate::Error;
176        fn parse(bytes: &'a [u8]) -> crate::Result<Self> {
177            if bytes.is_empty() {
178                return Err(crate::Error::BufferTooShort(
179                    broadcast_core::error::BufferTooShort::new(1, 0, "CustomTable"),
180                ));
181            }
182            Ok(Self {
183                table_id: bytes[0],
184                payload: bytes[1..].to_vec(),
185            })
186        }
187    }
188
189    impl TableDef<'_> for CustomTable {
190        const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(CUSTOM_TABLE_ID, CUSTOM_TABLE_ID)];
191        const NAME: &'static str = "CUSTOM_TABLE";
192    }
193
194    // -- A multi-range custom table --------------------------------------------
195    const MULTI_LO: u8 = 0x90;
196    const MULTI_MID: u8 = 0x92;
197    const MULTI_HI: u8 = 0x93;
198
199    #[derive(Debug, PartialEq)]
200    #[cfg_attr(feature = "serde", derive(serde::Serialize))]
201    struct MultiRangeTable {
202        table_id: u8,
203    }
204
205    impl<'a> Parse<'a> for MultiRangeTable {
206        type Error = crate::Error;
207        fn parse(bytes: &'a [u8]) -> crate::Result<Self> {
208            if bytes.is_empty() {
209                return Err(crate::Error::BufferTooShort(
210                    broadcast_core::error::BufferTooShort::new(1, 0, "MultiRangeTable"),
211                ));
212            }
213            Ok(Self { table_id: bytes[0] })
214        }
215    }
216
217    impl TableDef<'_> for MultiRangeTable {
218        const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(MULTI_LO, MULTI_LO), (MULTI_MID, MULTI_HI)];
219        const NAME: &'static str = "MULTI_RANGE_TABLE";
220    }
221
222    // -- A custom table that overrides a built-in (PAT = 0x00) -----------------
223    #[derive(Debug, PartialEq)]
224    #[cfg_attr(feature = "serde", derive(serde::Serialize))]
225    struct OverridePat {
226        table_id: u8,
227    }
228
229    impl<'a> Parse<'a> for OverridePat {
230        type Error = crate::Error;
231        fn parse(bytes: &'a [u8]) -> crate::Result<Self> {
232            if bytes.is_empty() {
233                return Err(crate::Error::BufferTooShort(
234                    broadcast_core::error::BufferTooShort::new(1, 0, "OverridePat"),
235                ));
236            }
237            Ok(Self { table_id: bytes[0] })
238        }
239    }
240
241    impl TableDef<'_> for OverridePat {
242        const TABLE_ID_RANGES: &'static [(u8, u8)] = &[(0x00, 0x00)];
243        const NAME: &'static str = "OVERRIDE_PAT";
244    }
245
246    #[test]
247    fn custom_table_dispatches_to_other() {
248        let mut reg = TableRegistry::new();
249        reg.register::<CustomTable>();
250
251        let bytes = [CUSTOM_TABLE_ID, 0xAA, 0xBB];
252        let result = AnyTableSection::parse_with(&bytes, &reg).unwrap();
253        match result {
254            AnyTableSection::Other {
255                table_id,
256                ref value,
257            } => {
258                assert_eq!(table_id, CUSTOM_TABLE_ID);
259                let ct = value.downcast_ref::<CustomTable>().unwrap();
260                assert_eq!(ct.table_id, CUSTOM_TABLE_ID);
261                assert_eq!(ct.payload, &[0xAA, 0xBB]);
262            }
263            other => panic!("expected Other, got {other:?}"),
264        }
265    }
266
267    #[test]
268    fn multi_range_registers_all_ids() {
269        let mut reg = TableRegistry::new();
270        reg.register::<MultiRangeTable>();
271
272        assert!(reg.lookup(MULTI_LO).is_some());
273        assert!(reg.lookup(MULTI_MID).is_some());
274        assert!(reg.lookup(MULTI_MID + 1).is_some());
275        assert!(reg.lookup(MULTI_HI).is_some());
276        // 0x91 is NOT in any range
277        assert!(reg.lookup(MULTI_LO + 1).is_none());
278
279        // Each registered id dispatches to Other
280        for id in [MULTI_LO, MULTI_MID, MULTI_MID + 1, MULTI_HI] {
281            let bytes = [id, 0x00];
282            let result = AnyTableSection::parse_with(&bytes, &reg).unwrap();
283            match result {
284                AnyTableSection::Other { table_id, .. } => assert_eq!(table_id, id),
285                other => panic!("id {id:#04x}: expected Other, got {other:?}"),
286            }
287        }
288
289        // 0x91 falls to Unknown
290        let bytes = [MULTI_LO + 1, 0x00];
291        let result = AnyTableSection::parse_with(&bytes, &reg).unwrap();
292        assert!(
293            matches!(result, AnyTableSection::Unknown { .. }),
294            "expected Unknown for unregistered id 0x91, got {result:?}",
295        );
296    }
297
298    #[test]
299    fn fallback_to_builtin_for_unregistered() {
300        let reg = TableRegistry::new();
301        // Build a minimal PAT (table_id 0x00)
302        use crate::tables::pat::{PatEntry, PatSection};
303        use broadcast_core::Serialize;
304        use mpeg_ts::pid::Pid;
305        let pat = PatSection::new(
306            1,
307            0,
308            true,
309            0,
310            0,
311            vec![PatEntry::new(1, Pid::from_const(0x0100))],
312        );
313        let mut buf = vec![0u8; pat.serialized_len()];
314        pat.serialize_into(&mut buf).unwrap();
315
316        let result = AnyTableSection::parse_with(&buf, &reg).unwrap();
317        match result {
318            AnyTableSection::PatSection(p) => assert_eq!(p.entries.len(), 1),
319            other => panic!("expected PatSection, got {other:?}"),
320        }
321    }
322
323    #[test]
324    fn override_builtin_yields_other() {
325        let mut reg = TableRegistry::new();
326        reg.register::<OverridePat>();
327
328        // Minimal PAT bytes (just table_id + enough to not error in OverridePat)
329        let bytes = [0x00u8, 0x01, 0x02];
330        let result = AnyTableSection::parse_with(&bytes, &reg).unwrap();
331        match result {
332            AnyTableSection::Other {
333                table_id,
334                ref value,
335            } => {
336                assert_eq!(table_id, 0x00);
337                let op = value.downcast_ref::<OverridePat>().unwrap();
338                assert_eq!(op.table_id, 0x00);
339            }
340            other => panic!("expected Other (override), got {other:?}"),
341        }
342    }
343
344    #[test]
345    fn empty_bytes_returns_buffer_too_short() {
346        let reg = TableRegistry::new();
347        let result = AnyTableSection::parse_with(&[], &reg);
348        assert!(matches!(
349            result,
350            Err(crate::Error::BufferTooShort(
351                broadcast_core::error::BufferTooShort {
352                    need: 1,
353                    have: 0,
354                    ..
355                }
356            ))
357        ));
358    }
359
360    #[cfg(feature = "serde")]
361    #[test]
362    fn serde_other_variant() {
363        let mut reg = TableRegistry::new();
364        reg.register::<CustomTable>();
365
366        let bytes = [CUSTOM_TABLE_ID, 0xAA, 0xBB];
367        let result = AnyTableSection::parse_with(&bytes, &reg).unwrap();
368
369        let json = serde_json::to_string(&result).unwrap();
370        assert!(json.contains("\"other\""), "unexpected JSON: {json}");
371    }
372}