Skip to main content

mpeg_ts/
section.rs

1//! Generic PSI/SI section framing — ITU-T H.222.0 §2.4 (= ISO/IEC 13818-1) and ETSI EN 300 468 §5.1.1.
2//!
3//! Every PSI and SI table is carried in one or more sections. This module
4//! parses the **section header** and exposes the payload for table-specific
5//! parsers to consume.
6//!
7//! # Section layout
8//!
9//! ```text
10//! byte 0:       table_id (8 bits)
11//! byte 1 bit 7: section_syntax_indicator (1 bit)
12//! byte 1 bit 6: private_indicator (1 bit)
13//! byte 1 bits 5-4: reserved (2 bits)
14//! byte 1 bits 3-0 + byte 2: section_length (12 bits)
15//!
16//! Long-form (section_syntax_indicator == 1):
17//!   byte 3-4:   table_id_extension (16 bits)
18//!   byte 5:     reserved(2) | version_number(5) | current_next_indicator(1)
19//!   byte 6:     section_number (8 bits)
20//!   byte 7:     last_section_number (8 bits)
21//!   byte 8..(total-4): payload
22//!   last 4 bytes: CRC_32
23//!
24//! Short-form (section_syntax_indicator == 0, e.g. TDT):
25//!   byte 3..(3+section_length): payload (no extension header, no CRC)
26//! ```
27//!
28//! NOTE the TOT exception: the TOT (0x73) also sets SSI=0 but DOES end with a
29//! CRC_32 (EN 300 468 §5.2.6). Parsing it through this generic short-form
30//! path folds the CRC into `payload` — use the table-specific `TotSection` parser instead.
31//!
32//! `section_length` counts bytes *after* the 3-byte section header, so the
33//! total section size is `section_length + 3`. It is derived from the payload
34//! on serialize, never stored, so a section whose payload is edited cannot
35//! carry a stale count or CRC.
36
37use crate::error::{Error, Result};
38use broadcast_common::crc32_mpeg2 as crc;
39use broadcast_core::len::{fit_bits, fit_u8, need_in, need_out};
40use broadcast_core::{Parse, Serialize};
41
42const MIN_HEADER_LEN: usize = 3;
43
44// Long-form header adds: extension_id(2) + version/cni(1) + sec_num(1) +
45// last_sec_num(1) = 5 bytes.
46const LONG_FORM_EXTRA: usize = 5;
47
48// CRC occupies the last 4 bytes of every long-form section.
49const CRC_LEN: usize = 4;
50
51// W15 (#1074): named bit-field masks for the section header, used by both
52// `parse` and `serialize_into` — ISO/IEC 13818-1 §2.4.4.1.
53
54/// `section_syntax_indicator` — byte 1 bit 7.
55const SSI_MASK: u8 = 0x80;
56/// `private_indicator` (byte 1 bit 6). Meaning is table-specific; DVB SI uses
57/// this position for the DVB `private_indicator` (ETSI EN 300 468 §5.1.1).
58const PRIVATE_INDICATOR_MASK: u8 = 0x40;
59/// Byte 1 bits 5-4: reserved (ISO/IEC 13818-1 §2.4.4.1).
60const HEADER_RESERVED_MASK: u8 = 0x30;
61/// Number of bits in the `section_length` field (12, ISO/IEC 13818-1 §2.4.4.1).
62const SECTION_LENGTH_BITS: u32 = 12;
63/// `version_number` — 5 bits (byte 5 bits 5-1 of the long-form extension header).
64const VERSION_NUMBER_MASK: u8 = 0x1F;
65/// Number of bits in `version_number` (5, ISO/IEC 13818-1 §2.4.4.1).
66const VERSION_NUMBER_BITS: u32 = 5;
67/// Byte 5 bits 7-6: reserved (ISO/IEC 13818-1 §2.4.4.1).
68const VERSION_BYTE_RESERVED_MASK: u8 = 0xC0;
69/// The 2 reserved bits sit at bits 7..6 of byte 5.
70const VERSION_BYTE_RESERVED_SHIFT: u32 = 6;
71/// `current_next_indicator` — byte 5 bit 0 of the long-form extension header.
72const CURRENT_NEXT_MASK: u8 = 0x01;
73
74/// Byte offsets of the 3-byte common section header (ISO/IEC 13818-1 §2.4.4.1).
75const TABLE_ID_OFFSET: usize = 0;
76const FLAGS_BYTE_OFFSET: usize = TABLE_ID_OFFSET + 1;
77/// Byte offset of the 16-bit `table_id_extension` field, the first byte of the
78/// long-form extension header (ISO/IEC 13818-1 §2.4.4.1).
79const EXTENSION_ID_OFFSET: usize = MIN_HEADER_LEN;
80/// Byte offset of the `version_number`/`current_next_indicator` byte.
81const VERSION_BYTE_OFFSET: usize = EXTENSION_ID_OFFSET + core::mem::size_of::<u16>();
82/// Byte offset of `section_number`.
83const SECTION_NUMBER_OFFSET: usize = VERSION_BYTE_OFFSET + 1;
84/// Byte offset of `last_section_number`.
85const LAST_SECTION_NUMBER_OFFSET: usize = SECTION_NUMBER_OFFSET + 1;
86/// Bit shift of `section_syntax_indicator` within byte 1.
87const SSI_SHIFT: u32 = 7;
88/// Bit shift of `private_indicator` within byte 1.
89const PRIVATE_INDICATOR_SHIFT: u32 = 6;
90/// Bit shift of `version_number` within its byte.
91const VERSION_NUMBER_SHIFT: u32 = 1;
92/// What the section CRC_32 protects, named in a mismatch.
93const SECTION_CRC_WHAT: &str = "section";
94/// Bit shift that places a 16-bit field's high byte in position.
95const HIGH_BYTE_SHIFT: u32 = 8;
96
97/// Read the big-endian CRC_32 at `off` (ISO/IEC 13818-1 §2.4.4.1).
98fn read_crc32(bytes: &[u8], off: usize) -> u32 {
99    let mut raw = [0_u8; CRC_LEN];
100    raw.copy_from_slice(&bytes[off..off + CRC_LEN]);
101    u32::from_be_bytes(raw)
102}
103
104/// A parsed PSI/SI section header, borrowing the raw input buffer for payload.
105///
106/// Created via `Section::parse(bytes)`. Does **not** validate the CRC on
107/// construction — call [`Section::validate_crc`] (or the raw-byte
108/// [`validate_crc`]) explicitly.
109#[derive(Debug, Clone, PartialEq, Eq)]
110#[cfg_attr(feature = "serde", derive(serde::Serialize))]
111pub struct Section<'a> {
112    /// Table identifier.
113    pub table_id: u8,
114    /// When `true` the section uses the long-form syntax (has extension header
115    /// and CRC). When `false` only the 3-byte header is present (short form,
116    /// e.g. TDT — but see the module docs for the TOT exception: SSI=0 yet
117    /// CRC present; parse TOT via `tables::tot`, not this path).
118    pub section_syntax_indicator: bool,
119    /// Private indicator bit (meaning is table-specific).
120    pub private_indicator: bool,
121    /// Table ID extension (aka `table_id_extension`). Present only for
122    /// long-form sections; zero for short-form.
123    pub extension_id: u16,
124    /// Version number (5 bits). Present only for long-form sections.
125    pub version_number: u8,
126    /// `current_next_indicator` flag. Present only for long-form sections.
127    pub current_next_indicator: bool,
128    /// Section number within the table sub-table.
129    pub section_number: u8,
130    /// Number of the last section in the table sub-table.
131    pub last_section_number: u8,
132    /// Section payload: excludes the header bytes and the trailing CRC for
133    /// long-form sections. For short-form sections this is bytes
134    /// `3..(section_length + 3)`.
135    pub payload: &'a [u8],
136    /// The 2 `reserved` bits of byte 1 (spec convention `0b11`) — kept so a
137    /// section that does not use the convention still round-trips.
138    pub byte1_reserved: u8,
139    /// The 2 `reserved` bits of byte 5 (spec convention `0b11`); only
140    /// meaningful for long-form sections.
141    pub byte5_reserved: u8,
142    /// The CRC_32 the section carried when it was parsed; `None` for
143    /// short-form sections. Never written back: [`Serialize`] recomputes the
144    /// CRC from the current fields.
145    parsed_crc32: Option<u32>,
146}
147
148/// Validate the CRC-32 of a complete long-form section held in `raw`: the
149/// header, the payload and the 4 trailing CRC bytes.
150///
151/// Every byte is on the wire, so this needs no parsed [`Section`], and a
152/// section whose payload was edited is validated against what it holds now
153/// rather than against a stale stored value.
154///
155/// Returns `Ok(())` when `raw` cannot hold a long-form section at all
156/// (fewer than the 3-byte header plus the 5-byte extension header plus the 4
157/// CRC bytes): such a section carries no CRC.
158///
159/// # Errors
160///
161/// Returns [`Error::CrcMismatch`] when the computed CRC over
162/// `raw[..raw.len() - 4]` does not match the declared value at
163/// `raw[raw.len()-4..]`.
164pub fn validate_crc(raw: &[u8]) -> Result<()> {
165    if raw.len() < MIN_HEADER_LEN {
166        return Err(Error::BufferTooShort(
167            broadcast_core::error::BufferTooShort::new(
168                MIN_HEADER_LEN,
169                raw.len(),
170                "section header in validate_crc",
171            ),
172        ));
173    }
174    let section_syntax_indicator = (raw[1] & SSI_MASK) != 0;
175    if !section_syntax_indicator || raw.len() < MIN_HEADER_LEN + LONG_FORM_EXTRA + CRC_LEN {
176        return Ok(());
177    }
178    crc::verify_trailer(raw, SECTION_CRC_WHAT).map_or(Ok(()), |verdict| Ok(verdict?))
179}
180
181/// Whether `section` is a long-form section whose CRC_32 covers it exactly.
182///
183/// The strict counterpart of [`validate_crc`], for a caller that trusts a
184/// section only when its CRC proves it: a section that is short-form
185/// (`section_syntax_indicator` = 0), shorter than the header plus the 4 CRC
186/// bytes, or whose declared `section_length` runs past `section` is refused
187/// rather than passed. Only `3 + section_length` bytes are covered, so trailing
188/// bytes after the section are ignored.
189#[must_use]
190pub fn crc_ok(section: &[u8]) -> bool {
191    let Some(total) = crate::ts::section_total_len(section) else {
192        return false;
193    };
194    if section[1] & SSI_MASK == 0
195        || total < MIN_HEADER_LEN + LONG_FORM_EXTRA + CRC_LEN
196        || total > section.len()
197    {
198        return false;
199    }
200    matches!(
201        crc::verify_trailer(&section[..total], SECTION_CRC_WHAT),
202        Some(Ok(()))
203    )
204}
205
206impl<'a> Section<'a> {
207    /// The section as its own bytes: header, payload and, for a long-form
208    /// section, a freshly computed CRC_32.
209    ///
210    /// # Errors
211    ///
212    /// [`Error::FieldOverflow`] when a header field does not fit its wire
213    /// width (see [`section_length`](Self::section_length)).
214    pub fn serialize(&self) -> Result<alloc::vec::Vec<u8>> {
215        let mut buf = alloc::vec![0u8; self.serialized_len()];
216        self.serialize_into(&mut buf)?;
217        Ok(buf)
218    }
219
220    /// Return the payload slice (same as the `payload` field — convenience
221    /// getter for code that has a `&Section` reference).
222    #[inline]
223    pub fn payload(&self) -> &'a [u8] {
224        self.payload
225    }
226
227    /// `section_length` implied by [`payload`](Self::payload) and the syntax
228    /// indicator (ISO/IEC 13818-1 §2.4.4.1): the byte count after the 3-byte
229    /// header.
230    #[must_use]
231    pub fn section_length(&self) -> usize {
232        self.payload.len() + self.overhead()
233    }
234
235    /// Header bytes the syntax adds around the payload: the 5-byte extension
236    /// header plus the 4-byte CRC for long form, nothing for short form.
237    fn overhead(&self) -> usize {
238        if self.section_syntax_indicator {
239            LONG_FORM_EXTRA + CRC_LEN
240        } else {
241            0
242        }
243    }
244
245    /// The CRC_32 the section carried when it was parsed; `None` for
246    /// short-form sections.
247    #[must_use]
248    pub fn crc32(&self) -> Option<u32> {
249        self.parsed_crc32
250    }
251
252    fn header_bytes(&self) -> Result<[u8; MIN_HEADER_LEN]> {
253        let length = fit_bits(
254            self.section_length() as u64,
255            SECTION_LENGTH_BITS,
256            "section_length",
257        )? as u16;
258        Ok([
259            self.table_id,
260            (u8::from(self.section_syntax_indicator) << SSI_SHIFT)
261                | (u8::from(self.private_indicator) << PRIVATE_INDICATOR_SHIFT)
262                | self.byte1_reserved
263                | ((length >> HIGH_BYTE_SHIFT) as u8 & crate::ts::SECTION_LENGTH_HI_MASK),
264            length.to_be_bytes()[1],
265        ])
266    }
267
268    fn extension_header_bytes(&self) -> Result<[u8; LONG_FORM_EXTRA]> {
269        let version = fit_bits(
270            u64::from(self.version_number),
271            VERSION_NUMBER_BITS,
272            "version_number",
273        )? as u8;
274        Ok([
275            (self.extension_id >> HIGH_BYTE_SHIFT) as u8,
276            self.extension_id.to_be_bytes()[1],
277            fit_u8(
278                usize::from(self.byte5_reserved) << VERSION_BYTE_RESERVED_SHIFT
279                    | usize::from(version) << VERSION_NUMBER_SHIFT
280                    | usize::from(self.current_next_indicator),
281                "section byte 5",
282            )?,
283            self.section_number,
284            self.last_section_number,
285        ])
286    }
287
288    /// Validate the CRC_32 this section currently carries, recomputed from
289    /// its fields.
290    ///
291    /// The CRC is never stored: [`Serialize`] always recomputes it, so this
292    /// is the value a serialized section will carry, even after the payload
293    /// was edited.
294    ///
295    /// # Errors
296    ///
297    /// Returns [`Error::CrcMismatch`] when the recomputed CRC is not the one
298    /// the section was parsed from (only possible for bytes that carried a
299    /// wrong CRC). Always `Ok(())` for short-form sections.
300    pub fn validate_crc(&self) -> Result<()> {
301        let Some(expected) = self.parsed_crc32 else {
302            return Ok(());
303        };
304        let mut covered = alloc::vec::Vec::with_capacity(MIN_HEADER_LEN + LONG_FORM_EXTRA);
305        covered.extend_from_slice(&self.header_bytes()?);
306        covered.extend_from_slice(&self.extension_header_bytes()?);
307        covered.extend_from_slice(self.payload);
308        Ok(crc::verify(&covered, expected, SECTION_CRC_WHAT)?)
309    }
310}
311
312impl<'a> Parse<'a> for Section<'a> {
313    type Error = crate::error::Error;
314    /// Parse a complete section from `bytes`.
315    ///
316    /// # Errors
317    ///
318    /// - [`Error::BufferTooShort`] — fewer than 3 bytes supplied.
319    /// - [`Error::SectionLengthOverflow`] — `section_length` field declares
320    ///   more data than `bytes` contains.
321    fn parse(bytes: &'a [u8]) -> Result<Self> {
322        // ── 3-byte common header ────────────────────────────────────────────
323        need_in(bytes, MIN_HEADER_LEN, "section header")?;
324
325        let table_id = bytes[TABLE_ID_OFFSET];
326        let section_syntax_indicator = (bytes[FLAGS_BYTE_OFFSET] & SSI_MASK) != 0;
327        let private_indicator = (bytes[FLAGS_BYTE_OFFSET] & PRIVATE_INDICATOR_MASK) != 0;
328        let byte1_reserved =
329            (bytes[FLAGS_BYTE_OFFSET] & HEADER_RESERVED_MASK) & !crate::ts::SECTION_LENGTH_HI_MASK;
330
331        // Total section size is section_length + 3 (the 3-byte header itself
332        // is not counted by section_length). W14 (#1074): shared with the
333        // other three sites that used to decode this field separately.
334        // `need_in(bytes, MIN_HEADER_LEN, ..)` passed above, so the header is
335        // present and `section_total_len` cannot return `None`.
336        let total = match crate::ts::section_total_len(bytes) {
337            Some(t) => t,
338            None => {
339                return Err(Error::BufferTooShort(
340                    broadcast_core::error::BufferTooShort::new(
341                        MIN_HEADER_LEN,
342                        bytes.len(),
343                        "section header",
344                    ),
345                ));
346            }
347        };
348
349        if bytes.len() < total {
350            return Err(Error::SectionLengthOverflow {
351                declared: total,
352                available: bytes.len(),
353            });
354        }
355
356        // Work only inside the declared section boundary.
357        let section_bytes = &bytes[..total];
358
359        if !section_syntax_indicator {
360            // ── Short-form section (e.g. TDT) ──────────────────────────────
361            // No extension header, no CRC. Payload is everything after the
362            // 3-byte header.
363            let payload = &section_bytes[MIN_HEADER_LEN..];
364            return Ok(Section {
365                table_id,
366                section_syntax_indicator,
367                private_indicator,
368                extension_id: 0,
369                version_number: 0,
370                current_next_indicator: false,
371                section_number: 0,
372                last_section_number: 0,
373                payload,
374                byte1_reserved,
375                byte5_reserved: VERSION_BYTE_RESERVED_MASK >> VERSION_BYTE_RESERVED_SHIFT,
376                parsed_crc32: None,
377            });
378        }
379
380        // ── Long-form section ───────────────────────────────────────────────
381        // Minimum size for a valid long-form section:
382        //   3 (common header) + 5 (extension header) + 4 (CRC) = 12 bytes.
383        let min_long = MIN_HEADER_LEN + LONG_FORM_EXTRA + CRC_LEN;
384        need_in(
385            section_bytes,
386            min_long,
387            "long-form section extension header + CRC",
388        )?;
389
390        let extension_id =
391            u16::from_be_bytes([bytes[EXTENSION_ID_OFFSET], bytes[EXTENSION_ID_OFFSET + 1]]);
392        let byte5_reserved = (bytes[VERSION_BYTE_OFFSET] & VERSION_BYTE_RESERVED_MASK)
393            >> VERSION_BYTE_RESERVED_SHIFT;
394        let version_number =
395            (bytes[VERSION_BYTE_OFFSET] >> VERSION_NUMBER_SHIFT) & VERSION_NUMBER_MASK;
396        let current_next_indicator = (bytes[VERSION_BYTE_OFFSET] & CURRENT_NEXT_MASK) != 0;
397        let section_number = bytes[SECTION_NUMBER_OFFSET];
398        let last_section_number = bytes[LAST_SECTION_NUMBER_OFFSET];
399
400        // Payload: bytes[8 .. total-4]  (excludes 5-byte extension header
401        // counting from offset 3, and the 4-byte CRC at the end).
402        let payload_start = MIN_HEADER_LEN + LONG_FORM_EXTRA;
403        let payload_end = total - CRC_LEN;
404        let payload = &section_bytes[payload_start..payload_end];
405
406        let crc_offset = total - CRC_LEN;
407        let parsed_crc32 = Some(read_crc32(section_bytes, crc_offset));
408
409        Ok(Section {
410            table_id,
411            section_syntax_indicator,
412            private_indicator,
413            extension_id,
414            version_number,
415            current_next_indicator,
416            section_number,
417            last_section_number,
418            payload,
419            byte1_reserved,
420            byte5_reserved,
421            parsed_crc32,
422        })
423    }
424}
425
426impl Serialize for Section<'_> {
427    type Error = crate::error::Error;
428    fn serialized_len(&self) -> usize {
429        MIN_HEADER_LEN + self.section_length()
430    }
431
432    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
433        let need = self.serialized_len();
434        need_out(buf, need, "Section")?;
435
436        buf[..MIN_HEADER_LEN].copy_from_slice(&self.header_bytes()?);
437        if !self.section_syntax_indicator {
438            buf[MIN_HEADER_LEN..need].copy_from_slice(self.payload);
439            return Ok(need);
440        }
441
442        let payload_start = MIN_HEADER_LEN + LONG_FORM_EXTRA;
443        buf[MIN_HEADER_LEN..payload_start].copy_from_slice(&self.extension_header_bytes()?);
444        let payload_end = payload_start + self.payload.len();
445        buf[payload_start..payload_end].copy_from_slice(self.payload);
446
447        crc::seal(buf, payload_end)?;
448        Ok(need)
449    }
450}
451
452#[cfg(test)]
453mod tests {
454    use super::*;
455    use alloc::vec;
456    use alloc::vec::Vec;
457    use broadcast_common::crc32_mpeg2::compute as crc32;
458
459    // ── Helper: build a minimal long-form section with correct CRC ───────────
460
461    /// Build a syntactically valid long-form section byte vector.
462    ///
463    /// Layout: [table_id, flags+len_hi, len_lo, ext_hi, ext_lo,
464    ///          ver_cni, sec_num, last_sec_num, ...payload..., crc(4)]
465    fn make_long_section(
466        table_id: u8,
467        extension_id: u16,
468        version: u8,
469        current_next: bool,
470        section_number: u8,
471        last_section_number: u8,
472        payload: &[u8],
473    ) -> Vec<u8> {
474        // section_length = 5 (extension header) + payload.len() + 4 (CRC)
475        let section_length: u16 = (5 + payload.len() + 4) as u16;
476
477        // reserved(2) | version(5) | current_next(1)
478        let ver_cni = 0xC0u8 | ((version & 0x1F) << 1) | (current_next as u8);
479        let mut buf: Vec<u8> = vec![
480            table_id,
481            // section_syntax_indicator=1, private_indicator=0, reserved=0b11, upper 4 bits of section_length
482            0x80 | 0x30 | ((section_length >> 8) as u8 & 0x0F),
483            (section_length & 0xFF) as u8,
484            (extension_id >> 8) as u8,
485            (extension_id & 0xFF) as u8,
486            ver_cni,
487            section_number,
488            last_section_number,
489        ];
490        buf.extend_from_slice(payload);
491
492        // Compute CRC over bytes so far, append as big-endian u32.
493        let crc = crc32(&buf);
494        buf.push((crc >> 24) as u8);
495        buf.push((crc >> 16) as u8);
496        buf.push((crc >> 8) as u8);
497        buf.push(crc as u8);
498
499        buf
500    }
501
502    // ── Test 1 ───────────────────────────────────────────────────────────────
503
504    #[test]
505    fn parse_rejects_buffer_shorter_than_3_bytes() {
506        for bad_len in [0usize, 1, 2] {
507            let buf = vec![0x00u8; bad_len];
508            let err = Section::parse(&buf).unwrap_err();
509            assert!(
510                matches!(err, Error::BufferTooShort(broadcast_core::error::BufferTooShort { need: 3, have, .. }) if have == bad_len),
511                "expected BufferTooShort for len={bad_len}, got {err:?}"
512            );
513        }
514    }
515
516    // ── Test 2 ───────────────────────────────────────────────────────────────
517
518    #[test]
519    fn parse_reads_table_id_syntax_indicator_and_length() {
520        // Construct a minimal 13-byte long-form section with no payload.
521        // section_length = 5 (extension header) + 0 (payload) + 4 (CRC) = 9
522        // BUT we need section_length >= min for a valid section: 9 → total = 12, which is 12 bytes, not 13.
523        // Let's use 1 byte of payload so section_length = 10, total = 13.
524        let raw = make_long_section(0x42, 0x1234, 3, true, 0, 0, &[0xAB]);
525        assert_eq!(raw.len(), 13);
526
527        let section = Section::parse(&raw).unwrap();
528        assert_eq!(section.table_id, 0x42);
529        assert!(section.section_syntax_indicator);
530        // section_length = 5 + 1 + 4 = 10
531        assert_eq!(section.section_length(), 10);
532    }
533
534    // ── Test 3 ───────────────────────────────────────────────────────────────
535
536    #[test]
537    fn parse_rejects_when_section_length_exceeds_buffer() {
538        // Build a 3-byte header that claims section_length = 100 bytes of data.
539        // Buffer is only 3 bytes (just the header), so total = 103 > 3.
540        let buf = [
541            0x00u8, // table_id
542            0x80u8, // section_syntax_indicator=1, section_length upper nibble = 0
543            100u8,  // section_length lower byte = 100 → total = 103
544        ];
545        let err = Section::parse(&buf).unwrap_err();
546        assert!(
547            matches!(
548                err,
549                Error::SectionLengthOverflow {
550                    declared: 103,
551                    available: 3
552                }
553            ),
554            "expected SectionLengthOverflow, got {err:?}"
555        );
556    }
557
558    // ── Test 4 ───────────────────────────────────────────────────────────────
559
560    #[test]
561    fn parse_reads_extension_id_version_current_next_section_numbers() {
562        let raw = make_long_section(
563            0x02,          // PMT table_id
564            0xBEEF,        // extension_id / program_number
565            7,             // version_number
566            true,          // current_next
567            2,             // section_number
568            5,             // last_section_number
569            &[0x00, 0x00], // dummy payload
570        );
571
572        let section = Section::parse(&raw).unwrap();
573        assert_eq!(section.extension_id, 0xBEEF);
574        assert_eq!(section.version_number, 7);
575        assert!(section.current_next_indicator);
576        assert_eq!(section.section_number, 2);
577        assert_eq!(section.last_section_number, 5);
578    }
579
580    #[test]
581    fn parse_reads_current_next_indicator_false() {
582        // Same as test 4 but with current_next = false (bit 0 of byte 5 cleared).
583        let raw = make_long_section(
584            0x02,   // PMT table_id
585            0xBEEF, // extension_id
586            7,      // version_number
587            false,  // current_next — the field under test
588            2,      // section_number
589            5,      // last_section_number
590            &[0x00, 0x00],
591        );
592
593        let section = Section::parse(&raw).unwrap();
594        assert!(!section.current_next_indicator);
595        // Confirm the other fields are unaffected by flipping bit 0.
596        assert_eq!(section.extension_id, 0xBEEF);
597        assert_eq!(section.version_number, 7);
598        assert_eq!(section.section_number, 2);
599        assert_eq!(section.last_section_number, 5);
600    }
601
602    // ── Test 5 ───────────────────────────────────────────────────────────────
603
604    #[test]
605    fn payload_slice_excludes_header_and_crc() {
606        let inner_payload = &[0x01u8, 0x02, 0x03, 0x04, 0x05];
607        let raw = make_long_section(0x42, 0x0001, 0, true, 0, 0, inner_payload);
608
609        let section = Section::parse(&raw).unwrap();
610        assert_eq!(section.payload(), inner_payload);
611    }
612
613    // ── Test 6 ───────────────────────────────────────────────────────────────
614
615    #[test]
616    fn validate_crc_accepts_matching_crc32() {
617        let raw = make_long_section(0x00, 0x0001, 1, true, 0, 0, &[0xDE, 0xAD, 0xBE, 0xEF]);
618        let section = Section::parse(&raw).unwrap();
619        section.validate_crc().expect("CRC should match");
620        validate_crc(&raw).expect("CRC should match");
621    }
622
623    // ── Test 7 ───────────────────────────────────────────────────────────────
624
625    #[test]
626    fn validate_crc_rejects_flipped_bit() {
627        let mut raw = make_long_section(0x00, 0x0001, 1, true, 0, 0, &[0xDE, 0xAD, 0xBE, 0xEF]);
628        // Flip a bit inside the payload (byte 8 is the first payload byte) BEFORE
629        // parsing.  The 4-byte CRC at the tail of `raw` was computed over the
630        // original (un-flipped) bytes and is NOT updated here, so after the flip:
631        //   • `raw[..raw.len()-4]` contains corrupted data, and
632        //   • `raw[raw.len()-4..]` still holds the CRC of the original data.
633        // Parsing after the flip captures that old CRC, which the section no
634        // longer recomputes to; `validate_crc` detects the mismatch over the
635        // corrupted bytes in both forms — which is what we are testing.
636        // (Parsing before the flip would immutably borrow `raw` for the lifetime
637        // of `section` — the compiler would then reject `raw[8] ^= 0x01` because
638        // a mutable borrow conflicts with any live shared borrow.)
639        raw[8] ^= 0x01;
640
641        let section = Section::parse(&raw).unwrap();
642        let err = section.validate_crc().unwrap_err();
643        assert!(
644            matches!(err, Error::CrcMismatch(..)),
645            "expected CrcMismatch, got {err:?}"
646        );
647        let err = validate_crc(&raw).unwrap_err();
648        assert!(
649            matches!(err, Error::CrcMismatch(..)),
650            "expected CrcMismatch, got {err:?}"
651        );
652    }
653
654    // ── Test (Fix 1 TDD) ─────────────────────────────────────────────────────
655
656    #[test]
657    fn validate_crc_rejects_raw_slice_shorter_than_the_header() {
658        let raw = make_long_section(0x42, 0x0001, 0, true, 0, 0, &[0xDE, 0xAD]);
659        // Parse the section first: it must still parse, so the failure below
660        // comes from the raw-byte validator alone.
661        Section::parse(&raw).unwrap();
662        // Pass an empty slice — shorter than the 3-byte header itself.
663        let err = validate_crc(&[]).unwrap_err();
664        assert!(
665            matches!(
666                err,
667                Error::BufferTooShort(broadcast_core::error::BufferTooShort {
668                    need: MIN_HEADER_LEN,
669                    ..
670                })
671            ),
672            "expected BufferTooShort(need=MIN_HEADER_LEN), got {err:?}"
673        );
674    }
675
676    // ── Test 8 ───────────────────────────────────────────────────────────────
677
678    #[test]
679    fn short_form_section_has_no_crc() {
680        // TDT-style short-form section: section_syntax_indicator = 0.
681        // section_length = 5 (5 bytes of payload), total = 8 bytes.
682        let buf = [
683            0x70u8, // table_id (TDT)
684            0x70u8, // SSI=0, private=1, reserved=0b11, upper nibble of section_length=0
685            0x05u8, // section_length = 5
686            // 5 bytes of "UTC time" payload
687            0xE0, 0x00, 0x00, 0x00, 0x00,
688        ];
689
690        let section = Section::parse(&buf).unwrap();
691        assert!(!section.section_syntax_indicator);
692        assert_eq!(section.crc32(), None);
693        // validate_crc on short-form should return Ok(()) vacuously.
694        section
695            .validate_crc()
696            .expect("short-form: no CRC to validate");
697        validate_crc(&buf).expect("short-form: no CRC to validate");
698        // Payload is the 5 bytes after the 3-byte header.
699        assert_eq!(section.payload(), &buf[3..]);
700    }
701
702    // ── Serialize derives the length and recomputes the CRC (#2749) ──────────
703
704    #[test]
705    fn serialize_grows_with_an_edited_payload() {
706        // `section_length` used to be a public field independent of
707        // `payload`: a longer payload either errored or was truncated to the
708        // stale count. It is derived now, so the edit is simply written.
709        let raw = make_long_section(0x42, 0x0001, 0, true, 0, 0, &[0xAA, 0xBB]);
710        let mut section = Section::parse(&raw).unwrap();
711        let longer = [0xAAu8, 0xBB, 0xCC, 0xDD];
712        section.payload = &longer;
713
714        assert_eq!(
715            section.section_length(),
716            longer.len() + LONG_FORM_EXTRA + CRC_LEN
717        );
718        let mut buf = vec![0u8; section.serialized_len()];
719        let n = section.serialize_into(&mut buf).unwrap();
720        assert_eq!(n, raw.len() + 2);
721        assert_eq!(&buf[8..12], &longer);
722        validate_crc(&buf[..n]).expect("the recomputed CRC must validate");
723    }
724
725    #[test]
726    fn serialize_shrinks_with_an_edited_payload() {
727        let raw = make_long_section(0x42, 0x0001, 0, true, 0, 0, &[0xAA, 0xBB, 0xCC]);
728        let mut section = Section::parse(&raw).unwrap();
729        let shorter = &[0xAAu8][..];
730        section.payload = shorter;
731
732        assert_eq!(
733            section.section_length(),
734            shorter.len() + LONG_FORM_EXTRA + CRC_LEN
735        );
736        let mut buf = vec![0u8; section.serialized_len()];
737        let n = section.serialize_into(&mut buf).unwrap();
738        assert_eq!(n, raw.len() - 2);
739        validate_crc(&buf[..n]).expect("the recomputed CRC must validate");
740    }
741
742    #[test]
743    fn serialize_recomputes_the_crc_after_a_payload_edit() {
744        // The parsed section used to write its stored CRC back verbatim, so a
745        // payload edit produced a section that failed its own CRC.
746        let raw = make_long_section(0x42, 0x0001, 0, true, 0, 0, &[0xAA, 0xBB]);
747        let parsed = Section::parse(&raw).unwrap();
748        let mut section = parsed.clone();
749        let edited = [0x11u8, 0x22];
750        section.payload = &edited;
751
752        let mut buf = vec![0u8; section.serialized_len()];
753        assert!(matches!(
754            section.validate_crc(),
755            Err(Error::CrcMismatch(..))
756        ));
757        section.serialize_into(&mut buf).unwrap();
758        assert_ne!(
759            buf[buf.len() - CRC_LEN..],
760            raw[raw.len() - CRC_LEN..],
761            "the CRC must change"
762        );
763        validate_crc(&buf).expect("the serialized edited section's CRC");
764    }
765
766    #[test]
767    fn serialize_rejects_a_payload_too_large_for_section_length() {
768        let raw = make_long_section(0x42, 0x0001, 0, true, 0, 0, &[0xAA]);
769        let mut section = Section::parse(&raw).unwrap();
770        let too_long = vec![0u8; (1 << SECTION_LENGTH_BITS) - LONG_FORM_EXTRA - CRC_LEN + 1];
771        section.payload = &too_long;
772
773        let mut buf = vec![0u8; section.serialized_len()];
774        assert!(matches!(
775            section.serialize_into(&mut buf),
776            Err(Error::FieldOverflow(_))
777        ));
778    }
779
780    #[test]
781    fn serialize_accepts_consistent_section_round_trip() {
782        // Sanity: a self-consistent Section (as produced by `parse`) still
783        // serializes byte-identically after the new validation.
784        let raw = make_long_section(0x42, 0x0001, 3, true, 1, 2, &[0x01, 0x02, 0x03]);
785        let section = Section::parse(&raw).unwrap();
786        let mut buf = vec![0u8; section.serialized_len()];
787        let n = section.serialize_into(&mut buf).unwrap();
788        assert_eq!(&buf[..n], raw.as_slice());
789    }
790
791    #[test]
792    fn reserved_bits_that_are_not_both_set_round_trip() {
793        // Byte 1 and byte 5 reserved bits used to be forced to `11` on
794        // serialize, so such a section did not round-trip.
795        let mut raw = make_long_section(0x42, 0x0001, 3, true, 0, 0, &[0xAA]);
796        raw[1] = (raw[1] & !HEADER_RESERVED_MASK) | 0x10;
797        raw[5] &= !VERSION_BYTE_RESERVED_MASK;
798        let len = raw.len();
799        let crc = crc32(&raw[..len - CRC_LEN]);
800        raw[len - CRC_LEN..].copy_from_slice(&crc.to_be_bytes());
801
802        let section = Section::parse(&raw).unwrap();
803        assert_eq!(section.byte1_reserved, 0x10);
804        assert_eq!(section.byte5_reserved, 0x00);
805        let mut buf = vec![0u8; section.serialized_len()];
806        section.serialize_into(&mut buf).unwrap();
807        assert_eq!(buf, raw);
808    }
809
810    #[test]
811    fn serialize_rejects_an_over_range_version_number() {
812        let raw = make_long_section(0x42, 0x0001, 0, true, 0, 0, &[0xAA]);
813        let mut section = Section::parse(&raw).unwrap();
814        section.version_number = (1 << VERSION_NUMBER_BITS) as u8;
815
816        let mut buf = vec![0u8; section.serialized_len()];
817        assert!(matches!(
818            section.serialize_into(&mut buf),
819            Err(Error::FieldOverflow(_))
820        ));
821    }
822}