Skip to main content

dvb_si/collect/
mod.rs

1//! Multi-section table collection.
2//!
3//! Section parsers in [`crate::tables`] describe one wire section. This module
4//! adds the next layer up: collect all sections in `0..=last_section_number`
5//! for one logical version, then expose a complete table view.
6//!
7//! Collectors validate long-form section CRCs before retaining bytes. If the
8//! input already came from [`crate::demux::SiDemux`], that validation has
9//! already happened; direct section-byte callers get the same guard here.
10//!
11//! A collector error describes the section that was just pushed, not the whole
12//! stream. Long-running consumers should normally log/drop that section and
13//! continue feeding later sections; previous valid collector state is retained.
14
15use alloc::collections::BTreeMap;
16use alloc::sync::Arc;
17use alloc::vec;
18use alloc::vec::Vec;
19use core::num::NonZeroUsize;
20use mpeg_ts::pid::Pid;
21
22use crate::descriptors::{AnyDescriptor, DescriptorLoop, DescriptorRegistry};
23use crate::sub_table::SubTableQualifier;
24use broadcast_core::Parse;
25use mpeg_ts::section::Section;
26
27mod bat;
28mod eit;
29mod nit;
30mod sdt;
31
32pub use bat::*;
33pub use eit::*;
34pub use nit::*;
35pub use sdt::*;
36
37/// Transport-stream entry in a complete NIT or BAT.
38#[derive(Debug)]
39#[non_exhaustive]
40pub struct CompleteTransportStream<'a> {
41    /// transport_stream_id of the described TS.
42    pub transport_stream_id: u16,
43    /// original_network_id of the described TS.
44    pub original_network_id: u16,
45    /// Typed descriptor loop for this transport stream.
46    pub descriptors: ParsedDescriptorLoop<'a>,
47}
48
49impl<'a> CompleteTransportStream<'a> {
50    pub(crate) fn collect<I>(entries: I, registry: Option<&'a DescriptorRegistry>) -> Vec<Self>
51    where
52        I: IntoIterator<Item = (u16, u16, DescriptorLoop<'a>)>,
53    {
54        entries
55            .into_iter()
56            .map(
57                |(transport_stream_id, original_network_id, descriptors)| Self {
58                    transport_stream_id,
59                    original_network_id,
60                    descriptors: ParsedDescriptorLoop::parse(descriptors, registry),
61                },
62            )
63            .collect()
64    }
65}
66
67/// Result alias for collection operations.
68pub type CollectResult<T> = core::result::Result<T, CollectError>;
69
70/// Errors returned by multi-section collectors.
71///
72/// These errors are scoped to the current input section. They usually mean
73/// "skip this section and keep going", especially on live streams where a
74/// broadcaster may mutate section bytes without bumping `version_number`.
75#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
76#[non_exhaustive]
77pub enum CollectError {
78    /// The section bytes did not parse as a generic PSI/SI section.
79    #[error("section parse failed: {0}")]
80    Section(#[from] crate::Error),
81
82    /// A short-form section was fed to a multi-section collector.
83    #[error(
84        "table_id {table_id:#04x} is a short-form section and cannot be multi-section collected"
85    )]
86    #[non_exhaustive]
87    ShortFormSection {
88        /// Raw table_id byte.
89        table_id: u8,
90    },
91
92    /// `section_number` was outside the advertised section range.
93    #[error(
94        "section_number {section_number} exceeds last_section_number {last_section_number} for table_id {table_id:#04x}"
95    )]
96    #[non_exhaustive]
97    SectionNumberOutOfRange {
98        /// Raw table_id byte.
99        table_id: u8,
100        /// Section number carried by the section.
101        section_number: u8,
102        /// Last section number carried by the section.
103        last_section_number: u8,
104    },
105
106    /// A slot already contained different bytes for the same version.
107    #[error("conflicting bytes for table_id {table_id:#04x} section {section_number}")]
108    #[non_exhaustive]
109    ConflictingSection {
110        /// Raw table_id byte.
111        table_id: u8,
112        /// Section slot that conflicted.
113        section_number: u8,
114    },
115
116    /// An EIT schedule section advertised an impossible table-id range.
117    #[error(
118        "EIT schedule table_id {table_id:#04x} is outside advertised range {first_table_id:#04x}..={last_table_id:#04x}"
119    )]
120    #[non_exhaustive]
121    EitTableIdOutOfRange {
122        /// Incoming EIT schedule table_id.
123        table_id: u8,
124        /// First table_id for this schedule kind.
125        first_table_id: u8,
126        /// Advertised last_table_id.
127        last_table_id: u8,
128    },
129}
130
131impl CollectError {
132    /// Builds [`Self::ConflictingSection`].
133    #[must_use]
134    pub fn conflicting_section(table_id: u8, section_number: u8) -> Self {
135        Self::ConflictingSection {
136            table_id,
137            section_number,
138        }
139    }
140
141    /// Builds [`Self::EitTableIdOutOfRange`].
142    #[must_use]
143    pub fn eit_table_id_out_of_range(table_id: u8, first_table_id: u8, last_table_id: u8) -> Self {
144        Self::EitTableIdOutOfRange {
145            table_id,
146            first_table_id,
147            last_table_id,
148        }
149    }
150
151    /// Builds [`Self::SectionNumberOutOfRange`].
152    #[must_use]
153    pub fn section_number_out_of_range(
154        table_id: u8,
155        section_number: u8,
156        last_section_number: u8,
157    ) -> Self {
158        Self::SectionNumberOutOfRange {
159            table_id,
160            section_number,
161            last_section_number,
162        }
163    }
164
165    /// Builds [`Self::ShortFormSection`].
166    #[must_use]
167    pub fn short_form_section(table_id: u8) -> Self {
168        Self::ShortFormSection { table_id }
169    }
170}
171
172impl From<mpeg_ts::Error> for CollectError {
173    fn from(e: mpeg_ts::Error) -> Self {
174        CollectError::Section(crate::Error::from(e))
175    }
176}
177
178/// Logical key for one section sequence.
179///
180/// The key deliberately excludes `version_number` and `section_number`. Version
181/// changes reset a collection; section numbers index into that collection.
182#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
183#[non_exhaustive]
184pub struct SectionSetKey {
185    /// Optional PID context supplied by the caller.
186    pub pid: Option<Pid>,
187    /// Raw `table_id`.
188    pub table_id: u8,
189    /// Long-form `table_id_extension`.
190    pub extension_id: u16,
191    /// `current_next_indicator`.
192    pub current_next_indicator: bool,
193    /// The identifying fields outside the generic header (the SDT's
194    /// `original_network_id`, the EIT's `transport_stream_id` and
195    /// `original_network_id`), see [`crate::sub_table`].
196    pub qualifier: Option<SubTableQualifier>,
197}
198
199/// Metadata shared by every section in a complete section set.
200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
201#[non_exhaustive]
202pub struct SectionSetMeta {
203    /// Logical section-set key.
204    pub key: SectionSetKey,
205    /// 5-bit `version_number`.
206    pub version_number: u8,
207    /// Last section number for this set.
208    pub last_section_number: u8,
209}
210
211#[derive(Debug)]
212struct PartialSectionSet {
213    meta: SectionSetMeta,
214    slots: Vec<Option<Arc<[u8]>>>,
215    filled: usize,
216    emitted: bool,
217    /// The collector's `tick` at the last touch (push) of this key; `0` is a
218    /// sentinel meaning "never touched yet" (the collector's first real tick
219    /// is `1`), used to find and evict the least-recently-touched entry.
220    last_touch: u64,
221}
222
223impl PartialSectionSet {
224    fn new(meta: SectionSetMeta) -> Self {
225        let len = meta.last_section_number as usize + 1;
226        Self {
227            meta,
228            slots: vec![None; len],
229            filled: 0,
230            emitted: false,
231            last_touch: 0,
232        }
233    }
234
235    fn reset(&mut self, meta: SectionSetMeta) {
236        let last_touch = self.last_touch;
237        *self = Self::new(meta);
238        self.last_touch = last_touch;
239    }
240
241    fn insert(&mut self, section_number: u8, bytes: &[u8]) -> CollectResult<bool> {
242        let index = section_number as usize;
243        if let Some(existing) = &self.slots[index] {
244            if existing.as_ref() == bytes {
245                return Ok(false);
246            }
247            return Err(CollectError::ConflictingSection {
248                table_id: self.meta.key.table_id,
249                section_number,
250            });
251        }
252
253        // Allocate only for a section that is actually retained: a repeating
254        // carousel re-sends identical sections every cycle, and copying each
255        // one just to compare and drop it was pure waste (audit r02-O1).
256        self.slots[index] = Some(Arc::from(bytes));
257        self.filled += 1;
258        self.emitted = false;
259        Ok(true)
260    }
261
262    fn complete(&self) -> bool {
263        self.filled == self.slots.len()
264    }
265
266    fn to_complete(&self) -> Option<CompleteSectionSet> {
267        if !self.complete() || self.emitted {
268            return None;
269        }
270
271        let sections = self
272            .slots
273            .iter()
274            .map(|slot| slot.as_ref().expect("complete set has no holes").clone())
275            .collect();
276        Some(CompleteSectionSet {
277            meta: self.meta,
278            sections,
279        })
280    }
281}
282
283/// Generic collector for long-form `section_number`/`last_section_number`
284/// sequences.
285///
286/// The partial-key cap is the caller's: [`SectionSetCollector::new`] takes it.
287///
288/// # Capacity: LRU eviction, not a permanent wall (issue #1002)
289///
290/// The cap bounds `partial`'s total entry count, including **completed**
291/// sets — a completed set is retained (so a repeat/duplicate section for it
292/// is recognized and does not re-emit) but a real network can complete far
293/// more distinct `(table_id, extension_id, current_next_indicator)` keys
294/// over time than the cap allows to stay in-progress simultaneously (EIT
295/// *other* alone can span 150+ services). Capping only entry *creation* and
296/// never evicting anything would eventually wall off every new key behind a
297/// permanently-full map of old, no-longer-interesting completed entries,
298/// with the caller seeing only silent `Ok(None)` and no way to tell "still
299/// collecting" apart from "capacity exhausted, this key will never
300/// complete". Instead, when a *new* key arrives at capacity, the
301/// **least-recently-touched** entry (by push, not by construction) is
302/// evicted to admit it — old, no-longer-fed keys naturally age out in
303/// favor of active ones. [`evicted_for_capacity`](Self::evicted_for_capacity)
304/// counts evictions, so a caller can detect this churn instead of it being
305/// invisible.
306#[derive(Debug)]
307pub struct SectionSetCollector {
308    partial: BTreeMap<SectionSetKey, PartialSectionSet>,
309    /// `tick` at last touch → key, for O(log n) least-recently-touched lookup.
310    touch_order: BTreeMap<u64, SectionSetKey>,
311    tick: u64,
312    max_partial_keys: usize,
313    evicted_for_capacity: u64,
314}
315
316impl SectionSetCollector {
317    /// Create an empty collector holding at most `max_partial_keys` keys.
318    /// When a *new* key arrives at capacity, the least-recently-touched
319    /// existing key is evicted to admit it (see the type-level docs).
320    #[must_use]
321    pub fn new(max_partial_keys: NonZeroUsize) -> Self {
322        Self {
323            partial: BTreeMap::new(),
324            touch_order: BTreeMap::new(),
325            tick: 0,
326            max_partial_keys: max_partial_keys.get(),
327            evicted_for_capacity: 0,
328        }
329    }
330
331    /// Number of keys evicted so far to admit a new key at capacity. A
332    /// nonzero, growing count means the cap is genuinely too small for the
333    /// stream's distinct-key churn — raise the cap passed to
334    /// [`new`](Self::new).
335    #[must_use]
336    pub fn evicted_for_capacity(&self) -> u64 {
337        self.evicted_for_capacity
338    }
339
340    /// Record a touch of `key` at the current tick, evicting the
341    /// least-recently-touched entry first if `key` is new and the map is
342    /// already at capacity. Returns `false` only in the (should-be
343    /// unreachable) case that eviction could not free a slot.
344    fn touch_or_evict(&mut self, key: SectionSetKey) -> bool {
345        self.tick = self.tick.wrapping_add(1).max(1);
346        if !self.partial.contains_key(&key) && self.partial.len() >= self.max_partial_keys {
347            let oldest = self.touch_order.keys().next().copied();
348            match oldest {
349                Some(oldest_tick) => {
350                    if let Some(oldest_key) = self.touch_order.remove(&oldest_tick) {
351                        self.partial.remove(&oldest_key);
352                        self.evicted_for_capacity += 1;
353                    }
354                }
355                None => return false,
356            }
357        }
358        true
359    }
360
361    /// Push one complete section. Returns `Some` only when the logical section
362    /// set has become complete for the first time at this version.
363    ///
364    /// # Errors
365    ///
366    /// Returns a [`CollectError`] if the bytes are not a valid long-form
367    /// section or if the section set becomes internally inconsistent. Treat the
368    /// error as applying to this section only unless your application wants
369    /// strict stream-fail behavior.
370    pub fn push_section(
371        &mut self,
372        bytes: impl AsRef<[u8]>,
373    ) -> CollectResult<Option<CompleteSectionSet>> {
374        self.push_section_with_pid(None, bytes)
375    }
376
377    /// Push one complete section with PID context.
378    ///
379    /// The PID is folded into the section-set key so tables with identical
380    /// table id/extension on different PIDs do not collide.
381    pub fn push_section_with_pid(
382        &mut self,
383        pid: Option<Pid>,
384        bytes: impl AsRef<[u8]>,
385    ) -> CollectResult<Option<CompleteSectionSet>> {
386        let raw = bytes.as_ref();
387        let section = Section::parse(raw)?;
388        if !section.section_syntax_indicator {
389            return Err(CollectError::ShortFormSection {
390                table_id: section.table_id,
391            });
392        }
393        if section.section_number > section.last_section_number {
394            return Err(CollectError::SectionNumberOutOfRange {
395                table_id: section.table_id,
396                section_number: section.section_number,
397                last_section_number: section.last_section_number,
398            });
399        }
400        mpeg_ts::section::validate_crc(raw)?;
401
402        let key = SectionSetKey {
403            pid,
404            table_id: section.table_id,
405            extension_id: section.extension_id,
406            current_next_indicator: section.current_next_indicator,
407            qualifier: SubTableQualifier::of(section.table_id, section.payload),
408        };
409        let meta = SectionSetMeta {
410            key,
411            version_number: section.version_number,
412            last_section_number: section.last_section_number,
413        };
414        if !self.touch_or_evict(key) {
415            return Ok(None);
416        }
417        let now = self.tick;
418
419        let partial = self
420            .partial
421            .entry(key)
422            .or_insert_with(|| PartialSectionSet::new(meta));
423
424        if partial.meta.version_number != meta.version_number
425            || partial.meta.last_section_number != meta.last_section_number
426        {
427            partial.reset(meta);
428        }
429
430        // Re-touch: drop this key's old tick from touch_order (if any) before
431        // recording the new one, so touch_order never accumulates stale ticks
432        // for a key that keeps getting fed.
433        self.touch_order.remove(&partial.last_touch);
434        partial.last_touch = now;
435        self.touch_order.insert(now, key);
436
437        partial.insert(section.section_number, raw)?;
438        let complete = partial.to_complete();
439        if complete.is_some() {
440            partial.emitted = true;
441        }
442        Ok(complete)
443    }
444
445    /// Drop all retained partial section sets.
446    pub fn clear(&mut self) {
447        self.partial.clear();
448        self.touch_order.clear();
449    }
450
451    /// Number of retained partial section-set states.
452    #[must_use]
453    pub fn len(&self) -> usize {
454        self.partial.len()
455    }
456
457    /// Whether the collector currently has no retained state.
458    #[must_use]
459    pub fn is_empty(&self) -> bool {
460        self.partial.is_empty()
461    }
462}
463
464/// A complete owned set of original section bytes for one logical section
465/// sequence.
466#[derive(Debug, Clone)]
467pub struct CompleteSectionSet {
468    meta: SectionSetMeta,
469    sections: Vec<Arc<[u8]>>,
470}
471
472/// Generic complete table view for one collected section set.
473///
474/// This is the all-table escape hatch: every long-form PSI/SI table with
475/// `section_number`/`last_section_number` can be collected into a
476/// [`CompleteSectionSet`] and parsed as `CompleteTable<T>`. Table-specific
477/// complete views such as [`CompleteNit`] add flattened convenience fields where
478/// the logical table shape is useful.
479#[derive(Debug)]
480pub struct CompleteTable<T> {
481    meta: SectionSetMeta,
482    sections: Vec<T>,
483}
484
485impl<T> CompleteTable<T> {
486    /// Metadata shared by the section set.
487    #[must_use]
488    pub const fn meta(&self) -> SectionSetMeta {
489        self.meta
490    }
491
492    /// Parsed sections in section-number order.
493    #[must_use]
494    pub fn sections(&self) -> &[T] {
495        &self.sections
496    }
497
498    /// Consume the complete table and return its parsed sections.
499    #[must_use]
500    pub fn into_sections(self) -> Vec<T> {
501        self.sections
502    }
503}
504
505impl CompleteSectionSet {
506    /// Metadata shared by the section set.
507    #[must_use]
508    pub const fn meta(&self) -> SectionSetMeta {
509        self.meta
510    }
511
512    /// Complete section bytes in section-number order.
513    #[must_use]
514    pub fn section_bytes(&self) -> impl ExactSizeIterator<Item = &[u8]> {
515        self.sections.iter().map(AsRef::as_ref)
516    }
517
518    /// Parse every section in this set as `T`.
519    ///
520    /// The parsed values borrow from this [`CompleteSectionSet`], so callers can
521    /// retain the set and use borrowed typed views without copying table loops.
522    pub fn parse_sections<'a, T>(&'a self) -> crate::Result<Vec<T>>
523    where
524        T: Parse<'a, Error = crate::Error>,
525    {
526        self.section_bytes().map(T::parse).collect()
527    }
528
529    /// Parse this set as a generic complete table.
530    ///
531    /// Use this for any long-form table that does not need a specialised
532    /// flattened logical view.
533    pub fn table<'a, T>(&'a self) -> crate::Result<CompleteTable<T>>
534    where
535        T: Parse<'a, Error = crate::Error>,
536    {
537        Ok(CompleteTable {
538            meta: self.meta,
539            sections: self.parse_sections()?,
540        })
541    }
542
543    /// Build a complete NIT view from this section set.
544    pub fn nit(&self) -> crate::Result<CompleteNit<'_>> {
545        CompleteNit::parse(self, None)
546    }
547
548    /// Build a complete NIT view using a descriptor registry.
549    pub fn nit_with_registry<'a>(
550        &'a self,
551        registry: &'a DescriptorRegistry,
552    ) -> crate::Result<CompleteNit<'a>> {
553        CompleteNit::parse(self, Some(registry))
554    }
555
556    /// Build a complete BAT view from this section set.
557    pub fn bat(&self) -> crate::Result<CompleteBat<'_>> {
558        CompleteBat::parse(self, None)
559    }
560
561    /// Build a complete BAT view using a descriptor registry.
562    pub fn bat_with_registry<'a>(
563        &'a self,
564        registry: &'a DescriptorRegistry,
565    ) -> crate::Result<CompleteBat<'a>> {
566        CompleteBat::parse(self, Some(registry))
567    }
568
569    /// Build a complete SDT view from this section set.
570    pub fn sdt(&self) -> crate::Result<CompleteSdt<'_>> {
571        CompleteSdt::parse(self, None)
572    }
573
574    /// Build a complete SDT view using a descriptor registry.
575    pub fn sdt_with_registry<'a>(
576        &'a self,
577        registry: &'a DescriptorRegistry,
578    ) -> crate::Result<CompleteSdt<'a>> {
579        CompleteSdt::parse(self, Some(registry))
580    }
581
582    /// Build a complete EIT view from this section set.
583    pub fn eit(&self) -> crate::Result<CompleteEit<'_>> {
584        CompleteEit::parse(self, None)
585    }
586
587    /// Build a complete EIT view using a descriptor registry.
588    pub fn eit_with_registry<'a>(
589        &'a self,
590        registry: &'a DescriptorRegistry,
591    ) -> crate::Result<CompleteEit<'a>> {
592        CompleteEit::parse(self, Some(registry))
593    }
594}
595
596/// Parsed descriptor loop retaining the raw bytes and the typed descriptor
597/// results.
598///
599/// Usually backed by a single section's descriptor loop, but a table-wide
600/// loop that a spec allows to split across sections (e.g. NIT §5.2.1 / BAT
601/// §5.2.2's `network_descriptors_loop` / `bouquet_descriptors_loop`, one per
602/// section) is built by concatenating each section's loop internally:
603/// `raw()` then yields one entry per contributing section, in section
604/// order, and `descriptors()` is their concatenation in the same order.
605#[derive(Debug)]
606pub struct ParsedDescriptorLoop<'a> {
607    raw: Vec<DescriptorLoop<'a>>,
608    descriptors: Vec<crate::Result<AnyDescriptor<'a>>>,
609}
610
611impl<'a> ParsedDescriptorLoop<'a> {
612    pub(crate) fn parse(raw: DescriptorLoop<'a>, registry: Option<&'a DescriptorRegistry>) -> Self {
613        Self::parse_all(core::iter::once(raw), registry)
614    }
615
616    /// Parse and concatenate descriptors from several raw descriptor loops,
617    /// in order, into one logical loop.
618    pub(crate) fn parse_all(
619        raws: impl IntoIterator<Item = DescriptorLoop<'a>>,
620        registry: Option<&'a DescriptorRegistry>,
621    ) -> Self {
622        let raw: Vec<DescriptorLoop<'a>> = raws.into_iter().collect();
623        let mut descriptors = Vec::new();
624        for loop_ in &raw {
625            match registry {
626                Some(registry) => descriptors.extend(registry.parse_loop(loop_.raw())),
627                None => descriptors.extend(loop_.iter()),
628            }
629        }
630        Self { raw, descriptors }
631    }
632
633    /// Raw descriptor-loop bytes, one entry per contributing section (in
634    /// section order). Almost always a single entry.
635    ///
636    /// Use `raw()[i].iter_with_extensions(&desc_reg, &ext_reg)` to recover
637    /// custom extension bodies from a `Complete*` view.
638    #[must_use]
639    pub fn raw(&self) -> &[DescriptorLoop<'a>] {
640        &self.raw
641    }
642
643    /// Typed descriptor parse results in wire order (concatenated across
644    /// every contributing section for a multi-section loop).
645    pub fn descriptors(&self) -> &[crate::Result<AnyDescriptor<'a>>] {
646        &self.descriptors
647    }
648}
649
650#[cfg(test)]
651mod tests {
652    const TEST_MAX_PARTIAL_KEYS: core::num::NonZeroUsize =
653        core::num::NonZeroUsize::MIN.saturating_add(255);
654
655    use super::*;
656
657    const TEST_TABLE_ID: u8 = 0x42;
658
659    fn min_section(extension_id: u16) -> Vec<u8> {
660        let section_length: u16 = 9; // 5 (ext_header) + 0 (payload) + 4 (crc)
661        let mut buf = vec![0u8; 12];
662        buf[0] = TEST_TABLE_ID;
663        buf[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
664        buf[2] = (section_length & 0xFF) as u8;
665        buf[3..5].copy_from_slice(&extension_id.to_be_bytes());
666        buf[5] = 0xC1;
667        buf[6] = 0;
668        buf[7] = 0;
669        let crc = broadcast_common::crc32_mpeg2::compute(&buf[..8]);
670        buf[8..12].copy_from_slice(&crc.to_be_bytes());
671        buf
672    }
673
674    #[test]
675    fn collect_single_section_is_complete() {
676        let mut c = SectionSetCollector::new(TEST_MAX_PARTIAL_KEYS);
677        let sec = min_section(0);
678        let result = c.push_section(&sec).unwrap();
679        assert!(result.is_some());
680        assert_eq!(c.len(), 1);
681    }
682
683    /// Regression for issue #1002: a completed (`emitted = true`) entry used
684    /// to count against the cap forever, so once the map filled with
685    /// completed keys, every later distinct key silently got `Ok(None)` with
686    /// no way to tell "still collecting" from "capacity exhausted, this will
687    /// never complete". A new key at capacity must now evict the
688    /// least-recently-touched entry (even a completed one) and succeed.
689    #[test]
690    fn new_key_beyond_cap_evicts_least_recently_touched_completed_entry() {
691        let mut c = SectionSetCollector::new(NonZeroUsize::MIN.saturating_add(2));
692
693        // Push sections for 3 distinct extension IDs — fills the cap, all completed.
694        for eid in 0..3u16 {
695            let sec = min_section(eid);
696            let result = c.push_section(&sec).unwrap();
697            assert!(
698                result.is_some(),
699                "single-section set for eid {eid} completes"
700            );
701        }
702        assert_eq!(c.len(), 3);
703        assert_eq!(c.evicted_for_capacity(), 0);
704
705        // A 4th distinct key now EVICTS the least-recently-touched (eid 0),
706        // not silently vanishes into Ok(None).
707        let sec4 = min_section(3);
708        let result = c.push_section(&sec4).unwrap();
709        assert!(
710            result.is_some(),
711            "new key beyond cap must evict, not be skipped"
712        );
713        assert_eq!(c.len(), 3, "cap stays honored, not just grown");
714        assert_eq!(c.evicted_for_capacity(), 1);
715
716        // eid 0 is gone; feeding it again is treated as a brand-new key
717        // (re-completes from scratch) rather than "already known".
718        let sec0_again = min_section(0);
719        let result = c.push_section(&sec0_again).unwrap();
720        assert!(result.is_some(), "evicted key re-admits like a fresh one");
721
722        // Clear frees space too.
723        c.clear();
724        assert!(c.is_empty());
725        let result = c.push_section(&sec4).unwrap();
726        assert!(result.is_some());
727        assert_eq!(c.len(), 1);
728    }
729
730    #[test]
731    fn partial_keys_cap_does_not_skip_existing_key() {
732        let mut c = SectionSetCollector::new(NonZeroUsize::MIN);
733
734        // Fill the cap with one multi-section NIT-like extension (section 0 of 1).
735        let sec0 = {
736            let mut buf = min_section(0xAB);
737            // Make section 0 of 1 be incomplete: change last_section_number to 1
738            buf[7] = 1;
739            // Recompute CRC
740            let crc = broadcast_common::crc32_mpeg2::compute(&buf[..8]);
741            buf[8..12].copy_from_slice(&crc.to_be_bytes());
742            buf
743        };
744        let result = c.push_section(&sec0).unwrap();
745        assert!(result.is_none(), "incomplete section set yields None");
746
747        // Push section 1 of 1 for the same key — cap is full but key already
748        // exists, so it must NOT be skipped.
749        let mut sec1 = min_section(0xAB);
750        sec1[6] = 1; // section_number = 1
751        sec1[7] = 1; // last_section_number = 1
752        let crc = broadcast_common::crc32_mpeg2::compute(&sec1[..8]);
753        sec1[8..12].copy_from_slice(&crc.to_be_bytes());
754
755        let result = c.push_section(&sec1).unwrap();
756        assert!(
757            result.is_some(),
758            "existing key must NOT be skipped when cap full"
759        );
760        assert_eq!(c.len(), 1);
761    }
762
763    fn long_section(table_id: u8, ext: u16, payload: &[u8]) -> Vec<u8> {
764        let section_length = (5 + payload.len() + 4) as u16;
765        let mut buf = vec![0u8; 3 + section_length as usize];
766        buf[0] = table_id;
767        buf[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
768        buf[2] = (section_length & 0xFF) as u8;
769        buf[3..5].copy_from_slice(&ext.to_be_bytes());
770        buf[5] = 0xC1;
771        buf[8..8 + payload.len()].copy_from_slice(payload);
772        let crc_off = buf.len() - 4;
773        let crc = broadcast_common::crc32_mpeg2::compute(&buf[..crc_off]);
774        buf[crc_off..].copy_from_slice(&crc.to_be_bytes());
775        buf
776    }
777
778    fn complete_set(section: &[u8]) -> CompleteSectionSet {
779        SectionSetCollector::new(TEST_MAX_PARTIAL_KEYS)
780            .push_section(section)
781            .unwrap()
782            .unwrap()
783    }
784
785    const LCN_DESCRIPTOR: [u8; 6] = [0x83, 4, 0x00, 0x01, 0xFC, 0x05];
786
787    fn only_descriptor<'a, 'b>(loop_: &'b ParsedDescriptorLoop<'a>) -> &'b AnyDescriptor<'a> {
788        assert_eq!(loop_.descriptors().len(), 1);
789        loop_.descriptors()[0].as_ref().unwrap()
790    }
791
792    fn lcn_registry() -> DescriptorRegistry {
793        let mut registry = DescriptorRegistry::new();
794        registry.with_logical_channel();
795        registry
796    }
797
798    #[test]
799    fn bat_with_registry_types_the_opted_in_private_descriptor() {
800        let mut payload = vec![0xF0, LCN_DESCRIPTOR.len() as u8];
801        payload.extend_from_slice(&LCN_DESCRIPTOR);
802        payload.extend_from_slice(&[0xF0, 0x00]);
803        let set = complete_set(&long_section(0x4A, 0x1234, &payload));
804        let registry = lcn_registry();
805        let with = set.bat_with_registry(&registry).unwrap();
806        assert_eq!(with.bouquet_id, 0x1234);
807        assert!(matches!(
808            only_descriptor(&with.bouquet_descriptors),
809            AnyDescriptor::LogicalChannel(_)
810        ));
811        let plain = set.bat().unwrap();
812        assert!(matches!(
813            only_descriptor(&plain.bouquet_descriptors),
814            AnyDescriptor::Unknown { tag: 0x83, .. }
815        ));
816    }
817
818    #[test]
819    fn sdt_with_registry_types_the_opted_in_private_descriptor() {
820        let mut payload = vec![
821            0,
822            1,
823            0xFF,
824            0x00,
825            0x07,
826            0xFC,
827            0x80,
828            LCN_DESCRIPTOR.len() as u8,
829        ];
830        payload.extend_from_slice(&LCN_DESCRIPTOR);
831        let set = complete_set(&long_section(0x42, 7, &payload));
832        let registry = lcn_registry();
833        let with = set.sdt_with_registry(&registry).unwrap();
834        assert_eq!(with.original_network_id, 1);
835        assert_eq!(with.services.len(), 1);
836        assert_eq!(with.services[0].service_id, 7);
837        assert!(matches!(
838            only_descriptor(&with.services[0].descriptors),
839            AnyDescriptor::LogicalChannel(_)
840        ));
841        let plain = set.sdt().unwrap();
842        assert!(matches!(
843            only_descriptor(&plain.services[0].descriptors),
844            AnyDescriptor::Unknown { tag: 0x83, .. }
845        ));
846    }
847
848    #[test]
849    fn eit_with_registry_types_the_opted_in_private_descriptor() {
850        let mut payload = vec![
851            0,
852            1,
853            0,
854            2,
855            0,
856            0x4E,
857            0x00,
858            0x09,
859            0xE4,
860            0x09,
861            0x12,
862            0x34,
863            0x56,
864            0x00,
865            0x01,
866            0x00,
867            0x80,
868            LCN_DESCRIPTOR.len() as u8,
869        ];
870        payload.extend_from_slice(&LCN_DESCRIPTOR);
871        let set = complete_set(&long_section(0x4E, 100, &payload));
872        let registry = lcn_registry();
873        let with = set.eit_with_registry(&registry).unwrap();
874        assert_eq!(with.service_id, 100);
875        assert_eq!(with.events.len(), 1);
876        assert_eq!(with.events[0].event_id, 9);
877        assert!(matches!(
878            only_descriptor(&with.events[0].descriptors),
879            AnyDescriptor::LogicalChannel(_)
880        ));
881        let plain = set.eit().unwrap();
882        assert!(matches!(
883            only_descriptor(&plain.events[0].descriptors),
884            AnyDescriptor::Unknown { tag: 0x83, .. }
885        ));
886    }
887
888    #[test]
889    fn into_sections_returns_every_parsed_section() {
890        let set = complete_set(&long_section(0x4A, 9, &[0xF0, 0, 0xF0, 0]));
891        let table = set.table::<crate::tables::bat::BatSection>().unwrap();
892        assert_eq!(table.sections().len(), 1);
893        let sections = table.into_sections();
894        assert_eq!(sections.len(), 1);
895        assert_eq!(sections[0].bouquet_id, 9);
896    }
897}