Skip to main content

dvb_si/descriptors/
any.rs

1//! Unified descriptor dispatch: [`AnyDescriptor`] + [`parse_loop`].
2//!
3//! [`AnyDescriptor`] is generated from a single declarative list
4//! (`declare_descriptors!`) — one line per crate-implemented descriptor tag.
5//! The list is the single source of truth: it produces the enum, the
6//! `From<T>` conversions, and the tag → type dispatcher, and a drift test
7//! pins each tag literal to the type's [`crate::traits::DescriptorDef::TAG`].
8//!
9//! [`parse_loop`] lazily walks a raw descriptor loop (the variable-length
10//! `descriptor()` sequence inside tables), yielding one [`AnyDescriptor`] per
11//! entry. It never panics: a malformed entry whose length is known yields an
12//! `Err` and iteration continues; a truncated final header/body yields one
13//! final `Err` and then fuses.
14//!
15//! ```
16//! use dvb_si::descriptors::{parse_loop, AnyDescriptor};
17//!
18//! // A two-descriptor loop: short_event (tag 0x4D, "eng" / "News") then an
19//! // unrecognised private tag 0xA7 — the walker yields a typed value for the
20//! // first and `Unknown` for the second, never panicking.
21//! let loop_bytes = [
22//!     0x4D, 0x07, b'e', b'n', b'g', 0x02, b'H', b'i', 0x00, // short_event
23//!     0xA7, 0x02, 0xCA, 0xFE,                               // unknown 0xA7
24//! ];
25//! let items: Vec<_> = parse_loop(&loop_bytes).collect();
26//! assert_eq!(items.len(), 2);
27//! match items[0].as_ref().unwrap() {
28//!     AnyDescriptor::ShortEvent(se) => {
29//!         assert_eq!(se.language_code.as_str(), "eng");
30//!         assert_eq!(se.event_name.decode(), "Hi");
31//!     }
32//!     other => panic!("expected ShortEvent, got {other:?}"),
33//! }
34//! assert!(matches!(items[1].as_ref().unwrap(), AnyDescriptor::Unknown { tag: 0xA7, .. }));
35//! ```
36//!
37//! # Adding a descriptor
38//!
39//! 1. Create the module with the wire layout, a `pub const TAG: u8`, and the
40//!    symmetric [`dvb_common::Parse`]/[`dvb_common::Serialize`] impls +
41//!    round-trip tests (copy an existing module).
42//! 2. `impl DescriptorDef` for the type (`TAG` from the module const, `NAME`
43//!    in SCREAMING_SNAKE without the `_descriptor` suffix).
44//! 3. Add one line to the `declare_descriptors!` invocation below — the enum
45//!    variant, dispatcher arm, and drift test are generated from it.
46//! 4. The integration completeness test walks the generated
47//!    [`AnyDescriptor::DISPATCHED_TAGS`] automatically — no test edits needed.
48
49/// Declares [`AnyDescriptor`] + its dispatcher from one tag list.
50///
51/// Each line is `Variant = 0xTAG => module::Type[<'a>]`. The optional trailing
52/// `@no_dispatch …` section adds variants that are NOT reachable from the
53/// generated dispatcher (private / context-dependent tags such as 0x83
54/// logical_channel) — the variant exists for callers that opt in via the
55/// registry, but `dispatch` never produces it.
56macro_rules! declare_descriptors {
57    (
58        $lt:lifetime;
59        $( $variant:ident = $tag:literal => $($path:ident)::+ $(<$plt:lifetime>)? ),+ $(,)?
60        $( ; @no_dispatch $( $nd_variant:ident => $($nd_path:ident)::+ $(<$nd_plt:lifetime>)? ),+ $(,)? )?
61    ) => {
62        /// Every crate-implemented descriptor, plus an `Unknown` fallthrough.
63        ///
64        /// serde uses external tagging with camelCase variant keys —
65        /// a parsed short_event_descriptor serializes as `{"shortEvent": {…}}`.
66        /// Variant names map 1:1 to the descriptor modules; see each module
67        /// for the wire layout.
68        #[derive(Debug)]
69        #[cfg_attr(feature = "serde", derive(serde::Serialize))]
70        #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
71        #[non_exhaustive]
72        pub enum AnyDescriptor<$lt> {
73            $(
74                #[allow(missing_docs)]
75                $variant($($path)::+ $(<$plt>)?),
76            )+
77            $($(
78                #[allow(missing_docs)]
79                $nd_variant($($nd_path)::+ $(<$nd_plt>)?),
80            )+)?
81            /// Runtime-registered custom descriptor (see [`DescriptorRegistry`]).
82            ///
83            /// [`DescriptorRegistry`]: crate::descriptors::registry::DescriptorRegistry
84            Other {
85                /// The raw descriptor_tag byte.
86                tag: u8,
87                /// The parsed, type-erased descriptor value. Use
88                /// [`DescriptorObject::as_any`][crate::descriptors::registry::DescriptorObject::as_any]
89                /// followed by `downcast_ref` to recover the concrete type.
90                #[cfg_attr(
91                    feature = "serde",
92                    serde(serialize_with = "crate::descriptors::registry::serialize_erased")
93                )]
94                value: Box<dyn crate::descriptors::registry::DescriptorObject>,
95            },
96            /// Tag with no typed implementation; `body` is the payload sans
97            /// the 2-byte (tag, length) header.
98            Unknown {
99                /// The raw descriptor_tag byte.
100                tag: u8,
101                /// The raw payload bytes (descriptor_length bytes).
102                body: &$lt [u8],
103            },
104        }
105
106        $(
107            impl<$lt> From<$($path)::+ $(<$plt>)?> for AnyDescriptor<$lt> {
108                fn from(d: $($path)::+ $(<$plt>)?) -> Self {
109                    Self::$variant(d)
110                }
111            }
112        )+
113        $($(
114            impl<$lt> From<$($nd_path)::+ $(<$nd_plt>)?> for AnyDescriptor<$lt> {
115                fn from(d: $($nd_path)::+ $(<$nd_plt>)?) -> Self {
116                    Self::$nd_variant(d)
117                }
118            }
119        )+)?
120
121        impl<$lt> AnyDescriptor<$lt> {
122            /// Every tag the generated dispatcher routes (excludes `@no_dispatch`
123            /// variants and [`AnyDescriptor::Unknown`]).
124            pub const DISPATCHED_TAGS: &'static [u8] = &[$($tag),+];
125
126            /// Diagnostic name of the contained descriptor — the type's
127            /// [`DescriptorDef::NAME`](crate::traits::DescriptorDef::NAME)
128            /// (`"SHORT_EVENT"`, `"NETWORK_NAME"`, …); `"CUSTOM"` for
129            /// [`AnyDescriptor::Other`] (runtime-registered) and `"UNKNOWN"`
130            /// for [`AnyDescriptor::Unknown`].
131            #[must_use]
132            pub fn name(&self) -> &'static str {
133                match self {
134                    $(
135                        Self::$variant(_) =>
136                            <$($path)::+ as crate::traits::DescriptorDef>::NAME,
137                    )+
138                    $($(
139                        Self::$nd_variant(_) =>
140                            <$($nd_path)::+ as crate::traits::DescriptorDef>::NAME,
141                    )+)?
142                    Self::Other { .. } => "CUSTOM",
143                    Self::Unknown { .. } => "UNKNOWN",
144                }
145            }
146
147            /// Parse one full descriptor (2-byte header included) by its tag.
148            ///
149            /// `None` means no typed implementation exists for `tag` (the
150            /// caller turns that into [`AnyDescriptor::Unknown`]). `Some(Err)`
151            /// is a typed parse failure for a recognised tag.
152            pub(crate) fn dispatch(tag: u8, full: &$lt [u8]) -> Option<crate::Result<Self>> {
153                use dvb_common::Parse;
154                match tag {
155                    $(
156                        $tag => Some(<$($path)::+>::parse(full).map(Self::$variant)),
157                    )+
158                    _ => None,
159                }
160            }
161        }
162
163        #[cfg(test)]
164        mod macro_drift {
165            #[test]
166            fn tag_literals_match_descriptor_def() {
167                use crate::traits::DescriptorDef;
168                $(
169                    assert_eq!(
170                        $tag,
171                        <$($path)::+ as DescriptorDef>::TAG,
172                        concat!("tag literal drift for ", stringify!($variant)),
173                    );
174                    assert!(
175                        !<$($path)::+ as DescriptorDef>::NAME.is_empty(),
176                        concat!("empty NAME for ", stringify!($variant)),
177                    );
178                )+
179                $($(
180                    assert!(
181                        !<$($nd_path)::+ as DescriptorDef>::NAME.is_empty(),
182                        concat!("empty NAME for ", stringify!($nd_variant)),
183                    );
184                )+)?
185            }
186        }
187    };
188}
189
190declare_descriptors! {'a;
191    // MPEG-2 systems descriptors (ISO/IEC 13818-1) used outside table context.
192    Registration = 0x05 => crate::descriptors::registration::RegistrationDescriptor<'a>,
193    DataStreamAlignment = 0x06 => crate::descriptors::data_stream_alignment::DataStreamAlignmentDescriptor,
194    Ca = 0x09 => crate::descriptors::ca::CaDescriptor<'a>,
195    Iso639Language = 0x0A => crate::descriptors::iso_639_language::Iso639LanguageDescriptor,
196    PrivateDataIndicator = 0x0F => crate::descriptors::private_data_indicator::PrivateDataIndicatorDescriptor,
197    // DVB descriptors (ETSI EN 300 468) — contiguous 0x40..=0x7F.
198    NetworkName = 0x40 => crate::descriptors::network_name::NetworkNameDescriptor<'a>,
199    ServiceList = 0x41 => crate::descriptors::service_list::ServiceListDescriptor,
200    Stuffing = 0x42 => crate::descriptors::stuffing::StuffingDescriptor<'a>,
201    SatelliteDeliverySystem = 0x43 => crate::descriptors::satellite_delivery_system::SatelliteDeliverySystemDescriptor,
202    CableDeliverySystem = 0x44 => crate::descriptors::cable_delivery_system::CableDeliverySystemDescriptor,
203    VbiData = 0x45 => crate::descriptors::vbi_data::VbiDataDescriptor<'a>,
204    VbiTeletext = 0x46 => crate::descriptors::vbi_teletext::VbiTeletextDescriptor,
205    BouquetName = 0x47 => crate::descriptors::bouquet_name::BouquetNameDescriptor<'a>,
206    Service = 0x48 => crate::descriptors::service::ServiceDescriptor<'a>,
207    CountryAvailability = 0x49 => crate::descriptors::country_availability::CountryAvailabilityDescriptor,
208    Linkage = 0x4A => crate::descriptors::linkage::LinkageDescriptor<'a>,
209    NvodReference = 0x4B => crate::descriptors::nvod_reference::NvodReferenceDescriptor,
210    TimeShiftedService = 0x4C => crate::descriptors::time_shifted_service::TimeShiftedServiceDescriptor,
211    ShortEvent = 0x4D => crate::descriptors::short_event::ShortEventDescriptor<'a>,
212    ExtendedEvent = 0x4E => crate::descriptors::extended_event::ExtendedEventDescriptor<'a>,
213    TimeShiftedEvent = 0x4F => crate::descriptors::time_shifted_event::TimeShiftedEventDescriptor,
214    Component = 0x50 => crate::descriptors::component::ComponentDescriptor<'a>,
215    Mosaic = 0x51 => crate::descriptors::mosaic::MosaicDescriptor,
216    StreamIdentifier = 0x52 => crate::descriptors::stream_identifier::StreamIdentifierDescriptor,
217    CaIdentifier = 0x53 => crate::descriptors::ca_identifier::CaIdentifierDescriptor,
218    Content = 0x54 => crate::descriptors::content::ContentDescriptor,
219    ParentalRating = 0x55 => crate::descriptors::parental_rating::ParentalRatingDescriptor,
220    Teletext = 0x56 => crate::descriptors::teletext::TeletextDescriptor,
221    Telephone = 0x57 => crate::descriptors::telephone::TelephoneDescriptor<'a>,
222    LocalTimeOffset = 0x58 => crate::descriptors::local_time_offset::LocalTimeOffsetDescriptor,
223    Subtitling = 0x59 => crate::descriptors::subtitling::SubtitlingDescriptor,
224    TerrestrialDeliverySystem = 0x5A => crate::descriptors::terrestrial_delivery_system::TerrestrialDeliverySystemDescriptor,
225    MultilingualNetworkName = 0x5B => crate::descriptors::multilingual_network_name::MultilingualNetworkNameDescriptor<'a>,
226    MultilingualBouquetName = 0x5C => crate::descriptors::multilingual_bouquet_name::MultilingualBouquetNameDescriptor<'a>,
227    MultilingualServiceName = 0x5D => crate::descriptors::multilingual_service_name::MultilingualServiceNameDescriptor<'a>,
228    MultilingualComponent = 0x5E => crate::descriptors::multilingual_component::MultilingualComponentDescriptor<'a>,
229    PrivateDataSpecifier = 0x5F => crate::descriptors::private_data_specifier::PrivateDataSpecifierDescriptor,
230    ServiceMove = 0x60 => crate::descriptors::service_move::ServiceMoveDescriptor,
231    ShortSmoothingBuffer = 0x61 => crate::descriptors::short_smoothing_buffer::ShortSmoothingBufferDescriptor<'a>,
232    FrequencyList = 0x62 => crate::descriptors::frequency_list::FrequencyListDescriptor,
233    PartialTransportStream = 0x63 => crate::descriptors::partial_transport_stream::PartialTransportStreamDescriptor,
234    DataBroadcast = 0x64 => crate::descriptors::data_broadcast::DataBroadcastDescriptor<'a>,
235    Scrambling = 0x65 => crate::descriptors::scrambling::ScramblingDescriptor,
236    DataBroadcastId = 0x66 => crate::descriptors::data_broadcast_id::DataBroadcastIdDescriptor<'a>,
237    TransportStream = 0x67 => crate::descriptors::transport_stream::TransportStreamDescriptor<'a>,
238    Dsng = 0x68 => crate::descriptors::dsng::DsngDescriptor<'a>,
239    Pdc = 0x69 => crate::descriptors::pdc::PdcDescriptor,
240    Ac3 = 0x6A => crate::descriptors::ac3::Ac3Descriptor<'a>,
241    AncillaryData = 0x6B => crate::descriptors::ancillary_data::AncillaryDataDescriptor,
242    CellList = 0x6C => crate::descriptors::cell_list::CellListDescriptor,
243    CellFrequencyLink = 0x6D => crate::descriptors::cell_frequency_link::CellFrequencyLinkDescriptor,
244    AnnouncementSupport = 0x6E => crate::descriptors::announcement_support::AnnouncementSupportDescriptor,
245    ApplicationSignalling = 0x6F => crate::descriptors::application_signalling::ApplicationSignallingDescriptor,
246    AdaptationFieldData = 0x70 => crate::descriptors::adaptation_field_data::AdaptationFieldDataDescriptor,
247    ServiceIdentifier = 0x71 => crate::descriptors::service_identifier::ServiceIdentifierDescriptor<'a>,
248    ServiceAvailability = 0x72 => crate::descriptors::service_availability::ServiceAvailabilityDescriptor,
249    DefaultAuthority = 0x73 => crate::descriptors::default_authority::DefaultAuthorityDescriptor<'a>,
250    RelatedContent = 0x74 => crate::descriptors::related_content::RelatedContentDescriptor,
251    TvaId = 0x75 => crate::descriptors::tva_id::TvaIdDescriptor,
252    ContentIdentifier = 0x76 => crate::descriptors::content_identifier::ContentIdentifierDescriptor<'a>,
253    TimeSliceFecIdentifier = 0x77 => crate::descriptors::time_slice_fec_identifier::TimeSliceFecIdentifierDescriptor<'a>,
254    EcmRepetitionRate = 0x78 => crate::descriptors::ecm_repetition_rate::EcmRepetitionRateDescriptor<'a>,
255    S2SatelliteDeliverySystem = 0x79 => crate::descriptors::s2_satellite_delivery_system::S2SatelliteDeliverySystemDescriptor,
256    EnhancedAc3 = 0x7A => crate::descriptors::enhanced_ac3::EnhancedAc3Descriptor<'a>,
257    Dts = 0x7B => crate::descriptors::dts::DtsDescriptor<'a>,
258    Aac = 0x7C => crate::descriptors::aac::AacDescriptor<'a>,
259    XaitLocation = 0x7D => crate::descriptors::xait_location::XaitLocationDescriptor,
260    FtaContentManagement = 0x7E => crate::descriptors::fta_content_management::FtaContentManagementDescriptor,
261    Extension = 0x7F => crate::descriptors::extension::ExtensionDescriptor<'a>;
262    // Private / context-dependent: variant exists but is NOT auto-dispatched.
263    // 0x83 logical_channel requires private_data_specifier context; enabled
264    // via the descriptor registry (Task 4).
265    @no_dispatch
266    LogicalChannel => crate::descriptors::logical_channel::LogicalChannelDescriptor,
267}
268
269/// Lazily walk a raw descriptor loop. Never panics.
270///
271/// Per-descriptor parse errors yield `Err` and iteration continues (the
272/// descriptor_length field bounds each entry, so the walker can always
273/// advance past a malformed body). A truncated final header or body yields
274/// one `Err` and then the iterator fuses (returns `None` forever after).
275#[must_use]
276pub fn parse_loop(bytes: &[u8]) -> DescriptorIter<'_> {
277    DescriptorIter {
278        bytes,
279        pos: 0,
280        fused: false,
281    }
282}
283
284/// Iterator over a raw descriptor loop; see [`parse_loop`].
285#[derive(Debug, Clone)]
286pub struct DescriptorIter<'a> {
287    bytes: &'a [u8],
288    pos: usize,
289    fused: bool,
290}
291
292impl<'a> Iterator for DescriptorIter<'a> {
293    type Item = crate::Result<AnyDescriptor<'a>>;
294
295    fn next(&mut self) -> Option<Self::Item> {
296        if self.fused || self.pos >= self.bytes.len() {
297            return None;
298        }
299        let rem = &self.bytes[self.pos..];
300        if rem.len() < 2 {
301            self.fused = true;
302            return Some(Err(crate::Error::BufferTooShort {
303                need: 2,
304                have: rem.len(),
305                what: "descriptor header in loop",
306            }));
307        }
308        let tag = rem[0];
309        let len = rem[1] as usize;
310        let total = 2 + len;
311        if rem.len() < total {
312            self.fused = true;
313            return Some(Err(crate::Error::BufferTooShort {
314                need: total,
315                have: rem.len(),
316                what: "descriptor body in loop",
317            }));
318        }
319        let full = &rem[..total];
320        self.pos += total;
321        Some(match AnyDescriptor::dispatch(tag, full) {
322            // Ok(typed) or Err(typed parse error) — either way, the length
323            // field already advanced `pos`, so iteration continues.
324            Some(res) => res,
325            None => Ok(AnyDescriptor::Unknown {
326                tag,
327                body: &full[2..],
328            }),
329        })
330    }
331}
332
333impl std::iter::FusedIterator for DescriptorIter<'_> {}
334
335/// A raw descriptor loop, borrowed from the section. Zero-copy: walk it
336/// typed via [`DescriptorLoop::iter`]; serde serializes the typed walk.
337///
338/// This is the table-loop analogue of [`crate::text::DvbText`]: it wraps the
339/// raw `descriptor()` sequence (the variable-length region inside a table) and
340/// decodes — i.e. dispatches each entry to a typed [`AnyDescriptor`] — only on
341/// demand. Parsing stays zero-copy; the typed walk happens when you call
342/// [`DescriptorLoop::iter`] or serialize.
343///
344/// ```
345/// use dvb_si::descriptors::{AnyDescriptor, DescriptorLoop};
346///
347/// // short_event (tag 0x4D, "eng" / "Hi") then an unknown private tag 0xA7.
348/// let raw = [
349///     0x4D, 0x07, b'e', b'n', b'g', 0x02, b'H', b'i', 0x00,
350///     0xA7, 0x02, 0xCA, 0xFE,
351/// ];
352/// let loop_ = DescriptorLoop::new(&raw);
353/// let items: Vec<_> = loop_.iter().collect();
354/// assert_eq!(items.len(), 2);
355/// assert!(matches!(items[0].as_ref().unwrap(), AnyDescriptor::ShortEvent(_)));
356/// assert_eq!(loop_.raw(), &raw[..]); // bytes preserved verbatim
357/// ```
358#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
359pub struct DescriptorLoop<'a>(&'a [u8]);
360
361impl<'a> DescriptorLoop<'a> {
362    /// Wrap a raw descriptor-loop slice (the `descriptor()` bytes only — no
363    /// enclosing length field).
364    #[must_use]
365    pub const fn new(raw: &'a [u8]) -> Self {
366        Self(raw)
367    }
368
369    /// The raw wire bytes of the loop, verbatim. These are what a serializer
370    /// writes back; use them for the byte length of the loop.
371    #[must_use]
372    pub const fn raw(&self) -> &'a [u8] {
373        self.0
374    }
375
376    /// Lazily walk the loop, yielding one typed [`AnyDescriptor`] per entry
377    /// (or [`AnyDescriptor::Unknown`] for tags with no implementation).
378    /// Delegates to [`parse_loop`]; never panics.
379    #[must_use]
380    pub fn iter(&self) -> DescriptorIter<'a> {
381        parse_loop(self.0)
382    }
383}
384
385impl<'a> std::ops::Deref for DescriptorLoop<'a> {
386    /// Derefs to the raw wire bytes — `len()`/indexing are **byte counts for
387    /// serialization, not entry counts**. To count entries, use
388    /// [`DescriptorLoop::iter`].
389    type Target = [u8];
390    fn deref(&self) -> &[u8] {
391        self.0
392    }
393}
394
395impl<'a> From<&'a [u8]> for DescriptorLoop<'a> {
396    fn from(raw: &'a [u8]) -> Self {
397        Self(raw)
398    }
399}
400
401impl std::fmt::Debug for DescriptorLoop<'_> {
402    /// Cheap: prints the byte length, not the decoded entries.
403    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
404        write!(f, "DescriptorLoop(<{} bytes>)", self.0.len())
405    }
406}
407
408impl<'a> IntoIterator for &DescriptorLoop<'a> {
409    type Item = crate::Result<AnyDescriptor<'a>>;
410    type IntoIter = DescriptorIter<'a>;
411    fn into_iter(self) -> Self::IntoIter {
412        self.iter()
413    }
414}
415
416#[cfg(feature = "serde")]
417impl serde::Serialize for DescriptorLoop<'_> {
418    /// Serializes as a sequence of the typed walk: each `Ok(d)` becomes the
419    /// [`AnyDescriptor`] (camelCase external tagging), and each `Err(e)`
420    /// becomes a `{"parseError": "<Display>"}` map — parse errors are surfaced,
421    /// never silently dropped.
422    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
423        struct Entry<'a>(crate::Result<AnyDescriptor<'a>>);
424        impl serde::Serialize for Entry<'_> {
425            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
426                match &self.0 {
427                    Ok(d) => d.serialize(s),
428                    Err(e) => {
429                        use serde::ser::SerializeMap;
430                        let mut m = s.serialize_map(Some(1))?;
431                        m.serialize_entry("parseError", &e.to_string())?;
432                        m.end()
433                    }
434                }
435            }
436        }
437        s.collect_seq(self.iter().map(Entry))
438    }
439}
440// Deliberately NO Deserialize: the typed walk decodes DVB text and dispatches
441// per-tag — there is no lossless way to reconstruct the raw loop bytes from the
442// serialized form. Structs holding a DescriptorLoop derive Serialize only
443// (3.0 break). To reconstruct, keep the wire bytes and re-`parse` the table.
444
445#[cfg(test)]
446mod tests {
447    use super::*;
448
449    #[test]
450    fn unknown_tag_yields_unknown_with_body_sans_header() {
451        // tag 0xA7 (no typed impl), length 2, body [0xDE, 0xAD].
452        let bytes = [0xA7, 0x02, 0xDE, 0xAD];
453        let items: Vec<_> = parse_loop(&bytes).collect();
454        assert_eq!(items.len(), 1);
455        match items[0].as_ref().unwrap() {
456            AnyDescriptor::Unknown { tag, body } => {
457                assert_eq!(*tag, 0xA7);
458                assert_eq!(*body, &[0xDE, 0xAD]);
459            }
460            other => panic!("expected Unknown, got {other:?}"),
461        }
462    }
463
464    #[test]
465    fn empty_loop_yields_nothing() {
466        assert_eq!(parse_loop(&[]).count(), 0);
467    }
468
469    #[test]
470    fn logical_channel_0x83_is_not_dispatched() {
471        // 0x83 has a variant but no dispatcher entry → Unknown, never panics.
472        let bytes = [0x83, 0x04, 0x00, 0x01, 0xFC, 0x01];
473        let items: Vec<_> = parse_loop(&bytes).collect();
474        assert_eq!(items.len(), 1);
475        assert!(matches!(
476            items[0].as_ref().unwrap(),
477            AnyDescriptor::Unknown { tag: 0x83, .. }
478        ));
479    }
480
481    #[test]
482    fn descriptor_loop_iter_matches_parse_loop() {
483        let raw = [
484            0x4D, 0x07, b'e', b'n', b'g', 0x02, b'H', b'i', 0x00, // short_event
485            0xA7, 0x02, 0xCA, 0xFE, // unknown 0xA7
486        ];
487        let via_loop: Vec<_> = DescriptorLoop::new(&raw)
488            .iter()
489            .map(|r| format!("{r:?}"))
490            .collect();
491        let via_fn: Vec<_> = parse_loop(&raw).map(|r| format!("{r:?}")).collect();
492        assert_eq!(via_loop, via_fn);
493        // raw()/Deref expose the wire bytes (byte length, not entry count).
494        assert_eq!(DescriptorLoop::new(&raw).raw(), &raw[..]);
495        assert_eq!(DescriptorLoop::new(&raw).len(), raw.len());
496        // IntoIterator for &DescriptorLoop.
497        let count = (&DescriptorLoop::new(&raw)).into_iter().count();
498        assert_eq!(count, 2);
499    }
500
501    #[test]
502    fn descriptor_loop_debug_is_cheap() {
503        let raw = [0x4D, 0x02, 0x01, 0x02];
504        assert_eq!(
505            format!("{:?}", DescriptorLoop::new(&raw)),
506            "DescriptorLoop(<4 bytes>)"
507        );
508    }
509
510    #[cfg(feature = "serde")]
511    #[test]
512    fn descriptor_loop_serializes_typed_unknown_and_parse_error() {
513        // [valid short_event, unknown tag 0xA7, truncated final entry].
514        // A truncated final entry (declared len 5, only 1 body byte present)
515        // makes the walker yield a final Err → {"parseError": …}.
516        let raw = [
517            0x4D, 0x07, b'e', b'n', b'g', 0x02, b'H', b'i', 0x00, // short_event
518            0xA7, 0x02, 0xCA, 0xFE, // unknown 0xA7
519            0x55, 0x05, 0x00, // parental_rating header claims 5 bytes; only 1 present
520        ];
521        let v = serde_json::to_value(DescriptorLoop::new(&raw)).unwrap();
522        let arr = v.as_array().expect("sequence");
523        assert_eq!(arr.len(), 3);
524        // 1. typed short_event under the camelCase variant key.
525        assert!(arr[0].get("shortEvent").is_some(), "got {}", arr[0]);
526        assert_eq!(arr[0]["shortEvent"]["event_name"], "Hi");
527        // 2. unknown tag carries its raw body bytes.
528        let unknown = arr[1].get("unknown").expect("unknown variant");
529        assert_eq!(unknown["tag"], 0xA7);
530        assert_eq!(unknown["body"], serde_json::json!([0xCA, 0xFE]));
531        // 3. truncated entry → parseError, never silently dropped.
532        assert!(
533            arr[2].get("parseError").is_some(),
534            "expected parseError, got {}",
535            arr[2]
536        );
537    }
538}