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