dvb-si 6.1.0

ETSI EN 300 468 DVB Service Information parser + builder. MPEG-2 PSI included.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
//! Unified descriptor dispatch: [`AnyDescriptor`] + [`parse_loop`].
//!
//! [`AnyDescriptor`] is generated from a single declarative list
//! (`declare_descriptors!`) — one line per crate-implemented descriptor tag.
//! The list is the single source of truth: it produces the enum, the
//! `From<T>` conversions, and the tag → type dispatcher, and a drift test
//! pins each tag literal to the type's [`crate::traits::DescriptorDef::TAG`].
//!
//! [`parse_loop`] lazily walks a raw descriptor loop (the variable-length
//! `descriptor()` sequence inside tables), yielding one [`AnyDescriptor`] per
//! entry. It never panics: a malformed entry whose length is known yields an
//! `Err` and iteration continues; a truncated final header/body yields one
//! final `Err` and then fuses.
//!
//! ```
//! use dvb_si::descriptors::{parse_loop, AnyDescriptor};
//!
//! // A two-descriptor loop: short_event (tag 0x4D, "eng" / "News") then an
//! // unrecognised private tag 0xA7 — the walker yields a typed value for the
//! // first and `Unknown` for the second, never panicking.
//! let loop_bytes = [
//!     0x4D, 0x07, b'e', b'n', b'g', 0x02, b'H', b'i', 0x00, // short_event
//!     0xA7, 0x02, 0xCA, 0xFE,                               // unknown 0xA7
//! ];
//! let items: Vec<_> = parse_loop(&loop_bytes).collect();
//! assert_eq!(items.len(), 2);
//! match items[0].as_ref().unwrap() {
//!     AnyDescriptor::ShortEvent(se) => {
//!         assert_eq!(se.language_code.as_str(), "eng");
//!         assert_eq!(se.event_name.decode(), "Hi");
//!     }
//!     other => panic!("expected ShortEvent, got {other:?}"),
//! }
//! assert!(matches!(items[1].as_ref().unwrap(), AnyDescriptor::Unknown { tag: 0xA7, .. }));
//! ```
//!
//! # Adding a descriptor
//!
//! 1. Create the module with the wire layout, a `pub const TAG: u8`, and the
//!    symmetric [`dvb_common::Parse`]/[`dvb_common::Serialize`] impls +
//!    round-trip tests (copy an existing module).
//! 2. `impl DescriptorDef` for the type (`TAG` from the module const, `NAME`
//!    in SCREAMING_SNAKE without the `_descriptor` suffix).
//! 3. Add one line to the `declare_descriptors!` invocation below — the enum
//!    variant, dispatcher arm, and drift test are generated from it.
//! 4. The integration completeness test walks the generated
//!    [`AnyDescriptor::DISPATCHED_TAGS`] automatically — no test edits needed.

/// Declares [`AnyDescriptor`] + its dispatcher from one tag list.
///
/// Each line is `Variant = 0xTAG => module::Type[<'a>]`. The optional trailing
/// `@no_dispatch …` section adds variants that are NOT reachable from the
/// generated dispatcher (private / context-dependent tags such as 0x83
/// logical_channel) — the variant exists for callers that opt in via the
/// registry, but `dispatch` never produces it.
macro_rules! declare_descriptors {
    (
        $lt:lifetime;
        $( $variant:ident = $tag:literal => $($path:ident)::+ $(<$plt:lifetime>)? ),+ $(,)?
        $( ; @no_dispatch $( $nd_variant:ident => $($nd_path:ident)::+ $(<$nd_plt:lifetime>)? ),+ $(,)? )?
    ) => {
        /// Every crate-implemented descriptor, plus an `Unknown` fallthrough.
        ///
        /// serde uses external tagging with camelCase variant keys —
        /// a parsed short_event_descriptor serializes as `{"shortEvent": {…}}`.
        /// Variant names map 1:1 to the descriptor modules; see each module
        /// for the wire layout.
        #[derive(Debug)]
        #[cfg_attr(feature = "serde", derive(serde::Serialize))]
        #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
        // Every variant is covariant in `$lt`: typed variants hold only
        // lifetime-parametrised views, `Unknown` holds `&$lt [u8]`, and the
        // `Other` value is a `'static` `Box<dyn DescriptorObject>`. The derive
        // accepts the `'static` field unchanged, so the impl is sound.
        #[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
        #[non_exhaustive]
        pub enum AnyDescriptor<$lt> {
            $(
                #[allow(missing_docs)]
                $variant($($path)::+ $(<$plt>)?),
            )+
            $($(
                #[allow(missing_docs)]
                $nd_variant($($nd_path)::+ $(<$nd_plt>)?),
            )+)?
            /// Runtime-registered custom descriptor (see [`DescriptorRegistry`]).
            ///
            /// [`DescriptorRegistry`]: crate::descriptors::registry::DescriptorRegistry
            Other {
                /// The raw descriptor_tag byte.
                tag: u8,
                /// The parsed, type-erased descriptor value. Call `downcast_ref`
                /// on it (see [`DescriptorObject`](crate::descriptors::registry::DescriptorObject))
                /// to recover the concrete type.
                #[cfg_attr(
                    feature = "serde",
                    serde(serialize_with = "crate::descriptors::registry::serialize_erased")
                )]
                value: Box<dyn crate::descriptors::registry::DescriptorObject>,
            },
            /// Tag with no typed implementation; `body` is the payload sans
            /// the 2-byte (tag, length) header.
            Unknown {
                /// The raw descriptor_tag byte.
                tag: u8,
                /// The raw payload bytes (descriptor_length bytes).
                body: &$lt [u8],
            },
        }

        $(
            impl<$lt> From<$($path)::+ $(<$plt>)?> for AnyDescriptor<$lt> {
                fn from(d: $($path)::+ $(<$plt>)?) -> Self {
                    Self::$variant(d)
                }
            }
        )+
        $($(
            impl<$lt> From<$($nd_path)::+ $(<$nd_plt>)?> for AnyDescriptor<$lt> {
                fn from(d: $($nd_path)::+ $(<$nd_plt>)?) -> Self {
                    Self::$nd_variant(d)
                }
            }
        )+)?

        impl<$lt> AnyDescriptor<$lt> {
            /// Every tag the generated dispatcher routes (excludes `@no_dispatch`
            /// variants and [`AnyDescriptor::Unknown`]).
            pub const DISPATCHED_TAGS: &'static [u8] = &[$($tag),+];

            /// Diagnostic name of the contained descriptor — the type's
            /// [`DescriptorDef::NAME`](crate::traits::DescriptorDef::NAME)
            /// (`"SHORT_EVENT"`, `"NETWORK_NAME"`, …); `"CUSTOM"` for
            /// [`AnyDescriptor::Other`] (runtime-registered) and `"UNKNOWN"`
            /// for [`AnyDescriptor::Unknown`].
            #[must_use]
            pub fn name(&self) -> &'static str {
                match self {
                    $(
                        Self::$variant(_) =>
                            <$($path)::+ as crate::traits::DescriptorDef>::NAME,
                    )+
                    $($(
                        Self::$nd_variant(_) =>
                            <$($nd_path)::+ as crate::traits::DescriptorDef>::NAME,
                    )+)?
                    Self::Other { .. } => "CUSTOM",
                    Self::Unknown { .. } => "UNKNOWN",
                }
            }

            /// Parse one full descriptor (2-byte header included) by its tag.
            ///
            /// `None` means no typed implementation exists for `tag` (the
            /// caller turns that into [`AnyDescriptor::Unknown`]). `Some(Err)`
            /// is a typed parse failure for a recognised tag.
            pub(crate) fn dispatch(tag: u8, full: &$lt [u8]) -> Option<crate::Result<Self>> {
                use dvb_common::Parse;
                match tag {
                    $(
                        $tag => Some(<$($path)::+>::parse(full).map(Self::$variant)),
                    )+
                    _ => None,
                }
            }
        }

        #[cfg(test)]
        mod macro_drift {
            #[test]
            fn tag_literals_match_descriptor_def() {
                use crate::traits::DescriptorDef;
                $(
                    assert_eq!(
                        $tag,
                        <$($path)::+ as DescriptorDef>::TAG,
                        concat!("tag literal drift for ", stringify!($variant)),
                    );
                    assert!(
                        !<$($path)::+ as DescriptorDef>::NAME.is_empty(),
                        concat!("empty NAME for ", stringify!($variant)),
                    );
                )+
                $($(
                    assert!(
                        !<$($nd_path)::+ as DescriptorDef>::NAME.is_empty(),
                        concat!("empty NAME for ", stringify!($nd_variant)),
                    );
                )+)?
            }
        }
    };
}

declare_descriptors! {'a;
    // MPEG-2 systems descriptors (ISO/IEC 13818-1) used outside table context.
    Registration = 0x05 => crate::descriptors::registration::RegistrationDescriptor<'a>,
    DataStreamAlignment = 0x06 => crate::descriptors::data_stream_alignment::DataStreamAlignmentDescriptor,
    Ca = 0x09 => crate::descriptors::ca::CaDescriptor<'a>,
    Iso639Language = 0x0A => crate::descriptors::iso_639_language::Iso639LanguageDescriptor,
    PrivateDataIndicator = 0x0F => crate::descriptors::private_data_indicator::PrivateDataIndicatorDescriptor,
    // DVB descriptors (ETSI EN 300 468) — contiguous 0x40..=0x7F.
    NetworkName = 0x40 => crate::descriptors::network_name::NetworkNameDescriptor<'a>,
    ServiceList = 0x41 => crate::descriptors::service_list::ServiceListDescriptor,
    Stuffing = 0x42 => crate::descriptors::stuffing::StuffingDescriptor<'a>,
    SatelliteDeliverySystem = 0x43 => crate::descriptors::satellite_delivery_system::SatelliteDeliverySystemDescriptor,
    CableDeliverySystem = 0x44 => crate::descriptors::cable_delivery_system::CableDeliverySystemDescriptor,
    VbiData = 0x45 => crate::descriptors::vbi_data::VbiDataDescriptor<'a>,
    VbiTeletext = 0x46 => crate::descriptors::vbi_teletext::VbiTeletextDescriptor,
    BouquetName = 0x47 => crate::descriptors::bouquet_name::BouquetNameDescriptor<'a>,
    Service = 0x48 => crate::descriptors::service::ServiceDescriptor<'a>,
    CountryAvailability = 0x49 => crate::descriptors::country_availability::CountryAvailabilityDescriptor,
    Linkage = 0x4A => crate::descriptors::linkage::LinkageDescriptor<'a>,
    NvodReference = 0x4B => crate::descriptors::nvod_reference::NvodReferenceDescriptor,
    TimeShiftedService = 0x4C => crate::descriptors::time_shifted_service::TimeShiftedServiceDescriptor,
    ShortEvent = 0x4D => crate::descriptors::short_event::ShortEventDescriptor<'a>,
    ExtendedEvent = 0x4E => crate::descriptors::extended_event::ExtendedEventDescriptor<'a>,
    TimeShiftedEvent = 0x4F => crate::descriptors::time_shifted_event::TimeShiftedEventDescriptor,
    Component = 0x50 => crate::descriptors::component::ComponentDescriptor<'a>,
    Mosaic = 0x51 => crate::descriptors::mosaic::MosaicDescriptor,
    StreamIdentifier = 0x52 => crate::descriptors::stream_identifier::StreamIdentifierDescriptor,
    CaIdentifier = 0x53 => crate::descriptors::ca_identifier::CaIdentifierDescriptor,
    Content = 0x54 => crate::descriptors::content::ContentDescriptor,
    ParentalRating = 0x55 => crate::descriptors::parental_rating::ParentalRatingDescriptor,
    Teletext = 0x56 => crate::descriptors::teletext::TeletextDescriptor,
    Telephone = 0x57 => crate::descriptors::telephone::TelephoneDescriptor<'a>,
    LocalTimeOffset = 0x58 => crate::descriptors::local_time_offset::LocalTimeOffsetDescriptor,
    Subtitling = 0x59 => crate::descriptors::subtitling::SubtitlingDescriptor,
    TerrestrialDeliverySystem = 0x5A => crate::descriptors::terrestrial_delivery_system::TerrestrialDeliverySystemDescriptor,
    MultilingualNetworkName = 0x5B => crate::descriptors::multilingual_network_name::MultilingualNetworkNameDescriptor<'a>,
    MultilingualBouquetName = 0x5C => crate::descriptors::multilingual_bouquet_name::MultilingualBouquetNameDescriptor<'a>,
    MultilingualServiceName = 0x5D => crate::descriptors::multilingual_service_name::MultilingualServiceNameDescriptor<'a>,
    MultilingualComponent = 0x5E => crate::descriptors::multilingual_component::MultilingualComponentDescriptor<'a>,
    PrivateDataSpecifier = 0x5F => crate::descriptors::private_data_specifier::PrivateDataSpecifierDescriptor,
    ServiceMove = 0x60 => crate::descriptors::service_move::ServiceMoveDescriptor,
    ShortSmoothingBuffer = 0x61 => crate::descriptors::short_smoothing_buffer::ShortSmoothingBufferDescriptor<'a>,
    FrequencyList = 0x62 => crate::descriptors::frequency_list::FrequencyListDescriptor,
    PartialTransportStream = 0x63 => crate::descriptors::partial_transport_stream::PartialTransportStreamDescriptor,
    DataBroadcast = 0x64 => crate::descriptors::data_broadcast::DataBroadcastDescriptor<'a>,
    Scrambling = 0x65 => crate::descriptors::scrambling::ScramblingDescriptor,
    DataBroadcastId = 0x66 => crate::descriptors::data_broadcast_id::DataBroadcastIdDescriptor<'a>,
    TransportStream = 0x67 => crate::descriptors::transport_stream::TransportStreamDescriptor<'a>,
    Dsng = 0x68 => crate::descriptors::dsng::DsngDescriptor<'a>,
    Pdc = 0x69 => crate::descriptors::pdc::PdcDescriptor,
    Ac3 = 0x6A => crate::descriptors::ac3::Ac3Descriptor<'a>,
    AncillaryData = 0x6B => crate::descriptors::ancillary_data::AncillaryDataDescriptor,
    CellList = 0x6C => crate::descriptors::cell_list::CellListDescriptor,
    CellFrequencyLink = 0x6D => crate::descriptors::cell_frequency_link::CellFrequencyLinkDescriptor,
    AnnouncementSupport = 0x6E => crate::descriptors::announcement_support::AnnouncementSupportDescriptor,
    ApplicationSignalling = 0x6F => crate::descriptors::application_signalling::ApplicationSignallingDescriptor,
    AdaptationFieldData = 0x70 => crate::descriptors::adaptation_field_data::AdaptationFieldDataDescriptor,
    ServiceIdentifier = 0x71 => crate::descriptors::service_identifier::ServiceIdentifierDescriptor<'a>,
    ServiceAvailability = 0x72 => crate::descriptors::service_availability::ServiceAvailabilityDescriptor,
    DefaultAuthority = 0x73 => crate::descriptors::default_authority::DefaultAuthorityDescriptor<'a>,
    RelatedContent = 0x74 => crate::descriptors::related_content::RelatedContentDescriptor,
    TvaId = 0x75 => crate::descriptors::tva_id::TvaIdDescriptor,
    ContentIdentifier = 0x76 => crate::descriptors::content_identifier::ContentIdentifierDescriptor<'a>,
    TimeSliceFecIdentifier = 0x77 => crate::descriptors::time_slice_fec_identifier::TimeSliceFecIdentifierDescriptor<'a>,
    EcmRepetitionRate = 0x78 => crate::descriptors::ecm_repetition_rate::EcmRepetitionRateDescriptor<'a>,
    S2SatelliteDeliverySystem = 0x79 => crate::descriptors::s2_satellite_delivery_system::S2SatelliteDeliverySystemDescriptor,
    EnhancedAc3 = 0x7A => crate::descriptors::enhanced_ac3::EnhancedAc3Descriptor<'a>,
    Dts = 0x7B => crate::descriptors::dts::DtsDescriptor<'a>,
    Aac = 0x7C => crate::descriptors::aac::AacDescriptor<'a>,
    XaitLocation = 0x7D => crate::descriptors::xait_location::XaitLocationDescriptor,
    FtaContentManagement = 0x7E => crate::descriptors::fta_content_management::FtaContentManagementDescriptor,
    Extension = 0x7F => crate::descriptors::extension::ExtensionDescriptor<'a>;
    // Private / context-dependent: variant exists but is NOT auto-dispatched.
    // 0x83 logical_channel requires private_data_specifier context; enabled
    // via the descriptor registry (Task 4).
    @no_dispatch
    LogicalChannel => crate::descriptors::logical_channel::LogicalChannelDescriptor,
}

/// Lazily walk a raw descriptor loop. Never panics.
///
/// Per-descriptor parse errors yield `Err` and iteration continues (the
/// descriptor_length field bounds each entry, so the walker can always
/// advance past a malformed body). A truncated final header or body yields
/// one `Err` and then the iterator fuses (returns `None` forever after).
#[must_use]
pub fn parse_loop(bytes: &[u8]) -> DescriptorIter<'_> {
    DescriptorIter {
        bytes,
        pos: 0,
        fused: false,
    }
}

/// Extract the next descriptor-loop entry (tag + full-entry slice) from the
/// raw byte stream. Shared by [`DescriptorIter::next`] and
/// [`RegistryIter::next`](crate::descriptors::registry::RegistryIter::next).
///
/// On success, advances `pos` past the entry and returns `(tag, full)`.
/// On truncation, sets `fused = true` and returns `Some(Err(..))`.
/// When the loop is exhausted, returns `None`.
pub(crate) fn next_loop_entry<'a>(
    bytes: &'a [u8],
    pos: &mut usize,
    fused: &mut bool,
) -> Option<crate::Result<(u8, &'a [u8])>> {
    if *fused || *pos >= bytes.len() {
        return None;
    }
    let rem = &bytes[*pos..];
    if rem.len() < 2 {
        *fused = true;
        return Some(Err(crate::Error::BufferTooShort {
            need: 2,
            have: rem.len(),
            what: "descriptor header in loop",
        }));
    }
    let tag = rem[0];
    let len = rem[1] as usize;
    let total = 2 + len;
    if rem.len() < total {
        *fused = true;
        return Some(Err(crate::Error::BufferTooShort {
            need: total,
            have: rem.len(),
            what: "descriptor body in loop",
        }));
    }
    let full = &rem[..total];
    *pos += total;
    Some(Ok((tag, full)))
}

/// Iterator over a raw descriptor loop; see [`parse_loop`].
#[derive(Debug, Clone)]
pub struct DescriptorIter<'a> {
    bytes: &'a [u8],
    pos: usize,
    fused: bool,
}

impl<'a> Iterator for DescriptorIter<'a> {
    type Item = crate::Result<AnyDescriptor<'a>>;

    fn next(&mut self) -> Option<Self::Item> {
        let (tag, full) = match next_loop_entry(self.bytes, &mut self.pos, &mut self.fused)? {
            Ok(v) => v,
            Err(e) => return Some(Err(e)),
        };
        Some(match AnyDescriptor::dispatch(tag, full) {
            Some(res) => res,
            None => Ok(AnyDescriptor::Unknown {
                tag,
                body: &full[2..],
            }),
        })
    }
}

impl std::iter::FusedIterator for DescriptorIter<'_> {}

/// A raw descriptor loop, borrowed from the section. Zero-copy: walk it
/// typed via [`DescriptorLoop::iter`]; serde serializes the typed walk.
///
/// This is the table-loop analogue of [`crate::text::DvbText`]: it wraps the
/// raw `descriptor()` sequence (the variable-length region inside a table) and
/// decodes — i.e. dispatches each entry to a typed [`AnyDescriptor`] — only on
/// demand. Parsing stays zero-copy; the typed walk happens when you call
/// [`DescriptorLoop::iter`] or serialize.
///
/// ```
/// use dvb_si::descriptors::{AnyDescriptor, DescriptorLoop};
///
/// // short_event (tag 0x4D, "eng" / "Hi") then an unknown private tag 0xA7.
/// let raw = [
///     0x4D, 0x07, b'e', b'n', b'g', 0x02, b'H', b'i', 0x00,
///     0xA7, 0x02, 0xCA, 0xFE,
/// ];
/// let loop_ = DescriptorLoop::new(&raw);
/// let items: Vec<_> = loop_.iter().collect();
/// assert_eq!(items.len(), 2);
/// assert!(matches!(items[0].as_ref().unwrap(), AnyDescriptor::ShortEvent(_)));
/// assert_eq!(loop_.raw(), &raw[..]); // bytes preserved verbatim
/// ```
#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "yoke", derive(yoke::Yokeable))]
pub struct DescriptorLoop<'a>(&'a [u8]);

/// Bytes of a descriptor header: `descriptor_tag` (1) + `descriptor_length` (1).
const DESC_HEADER_LEN: usize = 2;

impl<'a> DescriptorLoop<'a> {
    /// Wrap a raw descriptor-loop slice (the `descriptor()` bytes only — no
    /// enclosing length field).
    #[must_use]
    pub const fn new(raw: &'a [u8]) -> Self {
        Self(raw)
    }

    /// The raw wire bytes of the loop, verbatim. These are what a serializer
    /// writes back; use them for the byte length of the loop.
    #[must_use]
    pub const fn raw(&self) -> &'a [u8] {
        self.0
    }

    /// Lazily walk the loop, yielding one typed [`AnyDescriptor`] per entry
    /// (or [`AnyDescriptor::Unknown`] for tags with no implementation).
    /// Delegates to [`parse_loop`]; never panics.
    #[must_use]
    pub fn iter(&self) -> DescriptorIter<'a> {
        parse_loop(self.0)
    }

    /// Walk the loop's `(tag, body)` pairs by the TLV structure only — never
    /// typed-parses a body. Each entry is `descriptor_tag` (1 byte) +
    /// `descriptor_length` (1 byte) + that many body bytes; a truncated final
    /// entry (declared length running past the buffer) simply ends iteration.
    ///
    /// Use this for body-agnostic structural scans (e.g. "is tag X present?")
    /// where a malformed or empty body should not hide the tag — unlike
    /// [`iter`](Self::iter), which yields `Err`/`Unknown` for bodies that fail
    /// to typed-parse.
    pub fn raw_tags(&self) -> impl Iterator<Item = (u8, &'a [u8])> {
        let b = self.0;
        let mut pos = 0usize;
        core::iter::from_fn(move || {
            if pos + DESC_HEADER_LEN > b.len() {
                return None;
            }
            let tag = b[pos];
            let len = b[pos + 1] as usize;
            let end = pos + DESC_HEADER_LEN + len;
            if end > b.len() {
                return None; // truncated final entry
            }
            let body = &b[pos + DESC_HEADER_LEN..end];
            pos = end;
            Some((tag, body))
        })
    }

    /// True if the loop contains a descriptor with `tag`, regardless of whether
    /// its body parses (or even fits). Pure structural walk: checks the
    /// `descriptor_tag` byte at each entry header, so an empty (`[tag, 0x00]`)
    /// or truncated (`[tag, 0x01]`) descriptor still counts as present.
    #[must_use]
    pub fn contains_tag(&self, tag: u8) -> bool {
        let b = self.0;
        let mut pos = 0usize;
        while pos < b.len() {
            if b[pos] == tag {
                return true;
            }
            // Need the length byte to advance to the next header; without it
            // the tag byte just checked was the last thing in the loop.
            if pos + 1 >= b.len() {
                break;
            }
            pos += DESC_HEADER_LEN + b[pos + 1] as usize;
        }
        false
    }

    /// Walk this loop through a [`DescriptorRegistry`](crate::descriptors::registry::DescriptorRegistry)
    /// so registered private/custom descriptors (and PDS-scoped tags) are
    /// produced as [`AnyDescriptor::Other`]; mirrors [`iter`](Self::iter)
    /// otherwise.
    ///
    /// See [`DescriptorRegistry::parse_loop`](crate::descriptors::registry::DescriptorRegistry::parse_loop)
    /// for precedence rules and PDS-scoped dispatch.
    #[must_use]
    pub fn iter_with<'r>(
        &self,
        registry: &'r crate::descriptors::registry::DescriptorRegistry,
    ) -> crate::descriptors::registry::RegistryIter<'r, 'a> {
        registry.parse_loop(self.0)
    }

    /// Walk this loop through both a [`DescriptorRegistry`](crate::descriptors::registry::DescriptorRegistry) and an
    /// [`ExtensionRegistry`](crate::descriptors::extension::registry::ExtensionRegistry),
    /// so that custom-registered extension bodies (tag `0x7F` with a known
    /// `descriptor_tag_extension`) are surfaced as
    /// [`ExtIterItem::CustomExtension`](crate::descriptors::registry::ExtIterItem::CustomExtension) with the type-erased value available
    /// for downcast. All other descriptors follow the normal
    /// [`iter_with`](Self::iter_with) precedence.
    ///
    /// This is the only way to reach private extension bodies during a
    /// descriptor-loop walk; [`iter_with`](Self::iter_with) alone produces
    /// the built-in [`ExtensionBody::Raw`](crate::descriptors::extension::ExtensionBody::Raw)
    /// for unrecognised `descriptor_tag_extension` values.
    #[must_use]
    pub fn iter_with_extensions<'r>(
        &self,
        desc_reg: &'r crate::descriptors::registry::DescriptorRegistry,
        ext_reg: &'r crate::descriptors::extension::registry::ExtensionRegistry,
    ) -> crate::descriptors::registry::ExtRegistryIter<'r, 'a> {
        crate::descriptors::registry::ExtRegistryIter::new(desc_reg, ext_reg, self.0)
    }
}

impl<'a> std::ops::Deref for DescriptorLoop<'a> {
    /// Derefs to the raw wire bytes — `len()`/indexing are **byte counts for
    /// serialization, not entry counts**. To count entries, use
    /// [`DescriptorLoop::iter`].
    type Target = [u8];
    fn deref(&self) -> &[u8] {
        self.0
    }
}

impl<'a> From<&'a [u8]> for DescriptorLoop<'a> {
    fn from(raw: &'a [u8]) -> Self {
        Self(raw)
    }
}

impl std::fmt::Debug for DescriptorLoop<'_> {
    /// Cheap: prints the byte length, not the decoded entries.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "DescriptorLoop(<{} bytes>)", self.0.len())
    }
}

impl<'a> IntoIterator for &DescriptorLoop<'a> {
    type Item = crate::Result<AnyDescriptor<'a>>;
    type IntoIter = DescriptorIter<'a>;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for DescriptorLoop<'_> {
    /// Serializes as a sequence of the typed walk: each `Ok(d)` becomes the
    /// [`AnyDescriptor`] (camelCase external tagging), and each `Err(e)`
    /// becomes a `{"parseError": "<Display>"}` map — parse errors are surfaced,
    /// never silently dropped.
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        struct Entry<'a>(crate::Result<AnyDescriptor<'a>>);
        impl serde::Serialize for Entry<'_> {
            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
                match &self.0 {
                    Ok(d) => d.serialize(s),
                    Err(e) => {
                        use serde::ser::SerializeMap;
                        let mut m = s.serialize_map(Some(1))?;
                        m.serialize_entry("parseError", &e.to_string())?;
                        m.end()
                    }
                }
            }
        }
        s.collect_seq(self.iter().map(Entry))
    }
}
// Serialize-only: the typed walk decodes DVB text and dispatches per-tag —
// there is no lossless way to reconstruct the raw loop bytes from the
// serialized form. Structs holding a DescriptorLoop derive Serialize only.
// To reconstruct, keep the wire bytes and re-`parse` the table.

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn contains_tag_detects_present_tag_regardless_of_body() {
        // Well-formed AC-3 (0x6A) with a flags byte.
        assert!(DescriptorLoop::new(&[0x6A, 0x01, 0x80]).contains_tag(0x6A));
        // Empty body — malformed for AC-3, but the tag is present.
        assert!(DescriptorLoop::new(&[0x6A, 0x00]).contains_tag(0x6A));
        // Truncated — declares 1 body byte that isn't there; tag still present.
        assert!(DescriptorLoop::new(&[0x6A, 0x01]).contains_tag(0x6A));
        // Present after an earlier well-formed entry.
        assert!(DescriptorLoop::new(&[0x09, 0x02, 0x00, 0x00, 0x7A, 0x00]).contains_tag(0x7A));
        // Absent.
        assert!(!DescriptorLoop::new(&[0x09, 0x02, 0x00, 0x00]).contains_tag(0x6A));
        assert!(!DescriptorLoop::new(&[]).contains_tag(0x6A));
    }

    #[test]
    fn raw_tags_walks_tlv_without_typed_parsing() {
        // Two complete entries: tag 0x6A (empty body) + tag 0x40 (2-byte body).
        let loop_ = DescriptorLoop::new(&[0x6A, 0x00, 0x40, 0x02, 0xAA, 0xBB]);
        let pairs: Vec<_> = loop_.raw_tags().collect();
        assert_eq!(pairs, vec![(0x6A, &[][..]), (0x40, &[0xAA, 0xBB][..])]);
        // First entry [0x40,len=1,0xAA] complete, then a truncated [0x6A, len=5]
        // entry whose declared body runs past the buffer.
        let trunc = DescriptorLoop::new(&[0x40, 0x01, 0xAA, 0x6A, 0x05]);
        let tags: Vec<u8> = trunc.raw_tags().map(|(t, _)| t).collect();
        assert_eq!(tags, vec![0x40]); // the truncated 0x6A entry is dropped by raw_tags
                                      // ...but contains_tag still sees the truncated tag.
        assert!(trunc.contains_tag(0x6A));
    }

    #[test]
    fn unknown_tag_yields_unknown_with_body_sans_header() {
        // tag 0xA7 (no typed impl), length 2, body [0xDE, 0xAD].
        let bytes = [0xA7, 0x02, 0xDE, 0xAD];
        let items: Vec<_> = parse_loop(&bytes).collect();
        assert_eq!(items.len(), 1);
        match items[0].as_ref().unwrap() {
            AnyDescriptor::Unknown { tag, body } => {
                assert_eq!(*tag, 0xA7);
                assert_eq!(*body, &[0xDE, 0xAD]);
            }
            other => panic!("expected Unknown, got {other:?}"),
        }
    }

    #[test]
    fn empty_loop_yields_nothing() {
        assert_eq!(parse_loop(&[]).count(), 0);
    }

    #[test]
    fn logical_channel_0x83_is_not_dispatched() {
        // 0x83 has a variant but no dispatcher entry → Unknown, never panics.
        let bytes = [0x83, 0x04, 0x00, 0x01, 0xFC, 0x01];
        let items: Vec<_> = parse_loop(&bytes).collect();
        assert_eq!(items.len(), 1);
        assert!(matches!(
            items[0].as_ref().unwrap(),
            AnyDescriptor::Unknown { tag: 0x83, .. }
        ));
    }

    #[test]
    fn descriptor_loop_iter_matches_parse_loop() {
        let raw = [
            0x4D, 0x07, b'e', b'n', b'g', 0x02, b'H', b'i', 0x00, // short_event
            0xA7, 0x02, 0xCA, 0xFE, // unknown 0xA7
        ];
        let via_loop: Vec<_> = DescriptorLoop::new(&raw)
            .iter()
            .map(|r| format!("{r:?}"))
            .collect();
        let via_fn: Vec<_> = parse_loop(&raw).map(|r| format!("{r:?}")).collect();
        assert_eq!(via_loop, via_fn);
        // raw()/Deref expose the wire bytes (byte length, not entry count).
        assert_eq!(DescriptorLoop::new(&raw).raw(), &raw[..]);
        assert_eq!(DescriptorLoop::new(&raw).len(), raw.len());
        // IntoIterator for &DescriptorLoop.
        let count = (&DescriptorLoop::new(&raw)).into_iter().count();
        assert_eq!(count, 2);
    }

    #[test]
    fn descriptor_loop_debug_is_cheap() {
        let raw = [0x4D, 0x02, 0x01, 0x02];
        assert_eq!(
            format!("{:?}", DescriptorLoop::new(&raw)),
            "DescriptorLoop(<4 bytes>)"
        );
    }

    #[test]
    fn iter_with_custom_tag_yields_other() {
        use crate::descriptors::registry::DescriptorRegistry;
        use crate::traits::DescriptorDef;

        #[derive(Debug, PartialEq, Eq)]
        #[cfg_attr(feature = "serde", derive(serde::Serialize))]
        struct MyTag0xA7 {
            x: u8,
        }

        impl<'a> dvb_common::Parse<'a> for MyTag0xA7 {
            type Error = crate::error::Error;
            fn parse(bytes: &'a [u8]) -> crate::Result<Self> {
                if bytes.len() < 3 {
                    return Err(crate::error::Error::BufferTooShort {
                        need: 3,
                        have: bytes.len(),
                        what: "MyTag0xA7",
                    });
                }
                Ok(Self { x: bytes[2] })
            }
        }

        impl<'a> DescriptorDef<'a> for MyTag0xA7 {
            const TAG: u8 = 0xA7;
            const NAME: &'static str = "MY_TAG_0xA7";
        }

        let mut reg = DescriptorRegistry::new();
        reg.register::<MyTag0xA7>();

        let raw = [
            0x4D, 0x07, b'e', b'n', b'g', 0x02, b'H', b'i', 0x00, 0xA7, 0x02, 0xCA, 0xFE,
        ];
        let loop_ = DescriptorLoop::new(&raw);
        let items: Vec<_> = loop_.iter_with(&reg).collect::<Result<_, _>>().unwrap();
        assert_eq!(items.len(), 2);
        assert!(matches!(items[0], AnyDescriptor::ShortEvent(_)));
        match &items[1] {
            AnyDescriptor::Other { tag, value } => {
                assert_eq!(*tag, 0xA7);
                assert_eq!(value.downcast_ref::<MyTag0xA7>().unwrap().x, 0xCA);
            }
            other => panic!("expected Other, got {other:?}"),
        }
    }

    #[test]
    fn iter_with_empty_registry_matches_iter_for_builtin() {
        let raw = [
            0x4D, 0x07, b'e', b'n', b'g', 0x02, b'H', b'i', 0x00, 0xA7, 0x02, 0xCA, 0xFE,
        ];
        let loop_ = DescriptorLoop::new(&raw);
        let reg = crate::descriptors::registry::DescriptorRegistry::new();
        let via_iter: Vec<_> = loop_.iter().collect();
        let via_iter_with: Vec<_> = loop_.iter_with(&reg).collect();

        assert_eq!(via_iter.len(), via_iter_with.len());
        for (a, b) in via_iter.iter().zip(via_iter_with.iter()) {
            match (a, b) {
                (Ok(AnyDescriptor::ShortEvent(_)), Ok(AnyDescriptor::ShortEvent(_))) => {}
                (
                    Ok(AnyDescriptor::Unknown { tag: t1, body: b1 }),
                    Ok(AnyDescriptor::Unknown { tag: t2, body: b2 }),
                ) => {
                    assert_eq!(t1, t2);
                    assert_eq!(b1, b2);
                }
                (Err(_), Err(_)) => {}
                (l, r) => panic!("mismatch: {l:?} vs {r:?}"),
            }
        }
    }

    #[cfg(feature = "serde")]
    #[test]
    fn descriptor_loop_serializes_typed_unknown_and_parse_error() {
        // [valid short_event, unknown tag 0xA7, truncated final entry].
        // A truncated final entry (declared len 5, only 1 body byte present)
        // makes the walker yield a final Err → {"parseError": …}.
        let raw = [
            0x4D, 0x07, b'e', b'n', b'g', 0x02, b'H', b'i', 0x00, // short_event
            0xA7, 0x02, 0xCA, 0xFE, // unknown 0xA7
            0x55, 0x05, 0x00, // parental_rating header claims 5 bytes; only 1 present
        ];
        let v = serde_json::to_value(DescriptorLoop::new(&raw)).unwrap();
        let arr = v.as_array().expect("sequence");
        assert_eq!(arr.len(), 3);
        // 1. typed short_event under the camelCase variant key.
        assert!(arr[0].get("shortEvent").is_some(), "got {}", arr[0]);
        assert_eq!(arr[0]["shortEvent"]["event_name"], "Hi");
        // 2. unknown tag carries its raw body bytes.
        let unknown = arr[1].get("unknown").expect("unknown variant");
        assert_eq!(unknown["tag"], 0xA7);
        assert_eq!(unknown["body"], serde_json::json!([0xCA, 0xFE]));
        // 3. truncated entry → parseError, never silently dropped.
        assert!(
            arr[2].get("parseError").is_some(),
            "expected parseError, got {}",
            arr[2]
        );
    }
}