use crate::error::{Error, Result};
use dvb_common::crc32_mpeg2 as crc;
use dvb_common::{Parse, Serialize};
const MIN_HEADER_LEN: usize = 3;
const LONG_FORM_EXTRA: usize = 5;
const CRC_LEN: usize = 4;
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Section<'a> {
pub table_id: u8,
pub section_syntax_indicator: bool,
pub private_indicator: bool,
pub section_length: u16,
pub extension_id: u16,
pub version_number: u8,
pub current_next_indicator: bool,
pub section_number: u8,
pub last_section_number: u8,
pub payload: &'a [u8],
pub crc32: Option<u32>,
}
impl<'a> Section<'a> {
#[inline]
pub fn payload(&self) -> &'a [u8] {
self.payload
}
pub fn validate_crc(&self, raw: &[u8]) -> Result<()> {
let expected = match self.crc32 {
None => return Ok(()), Some(v) => v,
};
if raw.len() < CRC_LEN {
return Err(Error::BufferTooShort {
need: CRC_LEN,
have: raw.len(),
what: "CRC suffix in validate_crc",
});
}
let covered = &raw[..raw.len() - CRC_LEN];
let computed = crc::compute(covered);
if computed != expected {
return Err(Error::CrcMismatch { computed, expected });
}
Ok(())
}
}
impl<'a> Parse<'a> for Section<'a> {
type Error = crate::error::Error;
fn parse(bytes: &'a [u8]) -> Result<Self> {
if bytes.len() < MIN_HEADER_LEN {
return Err(Error::BufferTooShort {
need: MIN_HEADER_LEN,
have: bytes.len(),
what: "section header",
});
}
let table_id = bytes[0];
let section_syntax_indicator = (bytes[1] & 0x80) != 0;
let private_indicator = (bytes[1] & 0x40) != 0;
let section_length = (((bytes[1] & 0x0F) as u16) << 8) | (bytes[2] as u16);
let total = (section_length as usize) + MIN_HEADER_LEN;
if bytes.len() < total {
return Err(Error::SectionLengthOverflow {
declared: total,
available: bytes.len(),
});
}
let section_bytes = &bytes[..total];
if !section_syntax_indicator {
let payload = §ion_bytes[MIN_HEADER_LEN..];
return Ok(Section {
table_id,
section_syntax_indicator,
private_indicator,
section_length,
extension_id: 0,
version_number: 0,
current_next_indicator: false,
section_number: 0,
last_section_number: 0,
payload,
crc32: None,
});
}
let min_long = MIN_HEADER_LEN + LONG_FORM_EXTRA + CRC_LEN;
if section_bytes.len() < min_long {
return Err(Error::BufferTooShort {
need: min_long,
have: section_bytes.len(),
what: "long-form section extension header + CRC",
});
}
let extension_id = ((bytes[3] as u16) << 8) | (bytes[4] as u16);
let version_number = (bytes[5] >> 1) & 0x1F;
let current_next_indicator = (bytes[5] & 0x01) != 0;
let section_number = bytes[6];
let last_section_number = bytes[7];
let payload_start = MIN_HEADER_LEN + LONG_FORM_EXTRA;
let payload_end = total - CRC_LEN;
let payload = §ion_bytes[payload_start..payload_end];
let crc_offset = total - CRC_LEN;
let crc32 = Some(
((section_bytes[crc_offset] as u32) << 24)
| ((section_bytes[crc_offset + 1] as u32) << 16)
| ((section_bytes[crc_offset + 2] as u32) << 8)
| (section_bytes[crc_offset + 3] as u32),
);
Ok(Section {
table_id,
section_syntax_indicator,
private_indicator,
section_length,
extension_id,
version_number,
current_next_indicator,
section_number,
last_section_number,
payload,
crc32,
})
}
}
impl Serialize for Section<'_> {
type Error = crate::error::Error;
fn serialized_len(&self) -> usize {
usize::from(self.section_length) + MIN_HEADER_LEN
}
fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
let need = self.serialized_len();
if buf.len() < need {
return Err(Error::OutputBufferTooSmall {
need,
have: buf.len(),
});
}
buf[0] = self.table_id;
let length_hi = ((self.section_length >> 8) as u8) & 0x0F;
let ssi = u8::from(self.section_syntax_indicator) << 7;
let pi = u8::from(self.private_indicator) << 6;
buf[1] = ssi | pi | 0x30 | length_hi;
buf[2] = (self.section_length & 0xFF) as u8;
if self.section_syntax_indicator {
buf[3] = (self.extension_id >> 8) as u8;
buf[4] = (self.extension_id & 0xFF) as u8;
let version = (self.version_number & 0x1F) << 1;
let cni = u8::from(self.current_next_indicator);
buf[5] = 0xC0 | version | cni;
buf[6] = self.section_number;
buf[7] = self.last_section_number;
let payload_start = MIN_HEADER_LEN + LONG_FORM_EXTRA;
let payload_end = payload_start + self.payload.len();
buf[payload_start..payload_end].copy_from_slice(self.payload);
let crc = self.crc32.expect("long-form section must carry a CRC");
let crc_start = payload_end;
buf[crc_start..crc_start + CRC_LEN].copy_from_slice(&crc.to_be_bytes());
} else {
let payload_end = MIN_HEADER_LEN + self.payload.len();
buf[MIN_HEADER_LEN..payload_end].copy_from_slice(self.payload);
}
Ok(need)
}
}
#[cfg(test)]
mod tests {
use super::*;
use dvb_common::crc32_mpeg2::compute as crc32;
fn make_long_section(
table_id: u8,
extension_id: u16,
version: u8,
current_next: bool,
section_number: u8,
last_section_number: u8,
payload: &[u8],
) -> Vec<u8> {
let section_length: u16 = (5 + payload.len() + 4) as u16;
let ver_cni = 0xC0u8 | ((version & 0x1F) << 1) | (current_next as u8);
let mut buf: Vec<u8> = vec![
table_id,
0x80 | 0x30 | ((section_length >> 8) as u8 & 0x0F),
(section_length & 0xFF) as u8,
(extension_id >> 8) as u8,
(extension_id & 0xFF) as u8,
ver_cni,
section_number,
last_section_number,
];
buf.extend_from_slice(payload);
let crc = crc32(&buf);
buf.push((crc >> 24) as u8);
buf.push((crc >> 16) as u8);
buf.push((crc >> 8) as u8);
buf.push(crc as u8);
buf
}
#[test]
fn parse_rejects_buffer_shorter_than_3_bytes() {
for bad_len in [0usize, 1, 2] {
let buf = vec![0x00u8; bad_len];
let err = Section::parse(&buf).unwrap_err();
assert!(
matches!(err, Error::BufferTooShort { need: 3, have, .. } if have == bad_len),
"expected BufferTooShort for len={bad_len}, got {err:?}"
);
}
}
#[test]
fn parse_reads_table_id_syntax_indicator_and_length() {
let raw = make_long_section(0x42, 0x1234, 3, true, 0, 0, &[0xAB]);
assert_eq!(raw.len(), 13);
let section = Section::parse(&raw).unwrap();
assert_eq!(section.table_id, 0x42);
assert!(section.section_syntax_indicator);
assert_eq!(section.section_length, 10);
}
#[test]
fn parse_rejects_when_section_length_exceeds_buffer() {
let buf = [
0x00u8, 0x80u8, 100u8, ];
let err = Section::parse(&buf).unwrap_err();
assert!(
matches!(
err,
Error::SectionLengthOverflow {
declared: 103,
available: 3
}
),
"expected SectionLengthOverflow, got {err:?}"
);
}
#[test]
fn parse_reads_extension_id_version_current_next_section_numbers() {
let raw = make_long_section(
0x02, 0xBEEF, 7, true, 2, 5, &[0x00, 0x00], );
let section = Section::parse(&raw).unwrap();
assert_eq!(section.extension_id, 0xBEEF);
assert_eq!(section.version_number, 7);
assert!(section.current_next_indicator);
assert_eq!(section.section_number, 2);
assert_eq!(section.last_section_number, 5);
}
#[test]
fn parse_reads_current_next_indicator_false() {
let raw = make_long_section(
0x02, 0xBEEF, 7, false, 2, 5, &[0x00, 0x00],
);
let section = Section::parse(&raw).unwrap();
assert!(!section.current_next_indicator);
assert_eq!(section.extension_id, 0xBEEF);
assert_eq!(section.version_number, 7);
assert_eq!(section.section_number, 2);
assert_eq!(section.last_section_number, 5);
}
#[test]
fn payload_slice_excludes_header_and_crc() {
let inner_payload = &[0x01u8, 0x02, 0x03, 0x04, 0x05];
let raw = make_long_section(0x42, 0x0001, 0, true, 0, 0, inner_payload);
let section = Section::parse(&raw).unwrap();
assert_eq!(section.payload(), inner_payload);
}
#[test]
fn validate_crc_accepts_matching_crc32() {
let raw = make_long_section(0x00, 0x0001, 1, true, 0, 0, &[0xDE, 0xAD, 0xBE, 0xEF]);
let section = Section::parse(&raw).unwrap();
section.validate_crc(&raw).expect("CRC should match");
}
#[test]
fn validate_crc_rejects_flipped_bit() {
let mut raw = make_long_section(0x00, 0x0001, 1, true, 0, 0, &[0xDE, 0xAD, 0xBE, 0xEF]);
raw[8] ^= 0x01;
let section = Section::parse(&raw).unwrap();
let err = section.validate_crc(&raw).unwrap_err();
assert!(
matches!(err, Error::CrcMismatch { .. }),
"expected CrcMismatch, got {err:?}"
);
}
#[test]
fn validate_crc_rejects_raw_slice_shorter_than_crc_len() {
let raw = make_long_section(0x42, 0x0001, 0, true, 0, 0, &[0xDE, 0xAD]);
let section = Section::parse(&raw).unwrap();
let err = section.validate_crc(&[]).unwrap_err();
assert!(
matches!(err, Error::BufferTooShort { need: CRC_LEN, .. }),
"expected BufferTooShort(need=CRC_LEN), got {err:?}"
);
}
#[test]
fn short_form_section_has_no_crc() {
let buf = [
0x70u8, 0x70u8, 0x05u8, 0xE0, 0x00, 0x00, 0x00, 0x00,
];
let section = Section::parse(&buf).unwrap();
assert!(!section.section_syntax_indicator);
assert!(section.crc32.is_none());
section
.validate_crc(&buf)
.expect("short-form: no CRC to validate");
assert_eq!(section.payload(), &buf[3..]);
}
}