broadcast-common 15.1.0

Foundation for the rust-broadcast crates: CRC-32/MPEG-2, BCD + MJD time codecs, hex and base64 codecs, 33-bit/PCR clock arithmetic, wrap-safe modular counters, SDP media sections and the bounded XML reader. no_std + alloc.
Documentation
//! CRC-32 MPEG-2 — Annex C of ETSI EN 300 468, Annex A of ETSI TS 102 773.
//!
//! Polynomial `0x04C1_1DB7`, initial shift-register value `0xFFFF_FFFF`,
//! MSB-first bit order, no reflection, no final XOR. Used by every PSI/SI
//! section trailer and every T2-MI packet trailer.

use broadcast_core::error::{CrcMismatch, OutputBufferTooSmall};

/// Length of the CRC-32 trailer of a PSI/SI section, a T2-MI packet, an SNDU
/// and every other structure this CRC protects.
pub const TRAILER_LEN: usize = 4;

/// CRC-32 MPEG-2 generator polynomial.
pub const POLY: u32 = 0x04C1_1DB7;

/// Width of the lookup table.
const TABLE_ENTRIES: usize = 256;
/// Bit shifts of one table/compute step (MSB-first, no reflection).
const CRC_HI_SHIFT: u32 = 24;
const CRC_STEP_BITS: u32 = 8;
/// Mask testing the shift register's most-significant bit.
const CRC_MSB_MASK: u32 = 0x8000_0000;
/// Canonical initial shift-register value.
const CRC_INIT: u32 = 0xFFFF_FFFF;

/// Precomputed 256-entry forward table, built at compile time — zero
/// runtime initialisation cost.
pub(crate) const TABLE: [u32; TABLE_ENTRIES] = {
    let mut t = [0u32; TABLE_ENTRIES];
    let mut i = 0u32;
    while i < TABLE_ENTRIES as u32 {
        let mut c = i << CRC_HI_SHIFT;
        let mut j = 0;
        while j < u8::BITS {
            c = if c & CRC_MSB_MASK != 0 {
                (c << 1) ^ POLY
            } else {
                c << 1
            };
            j += 1;
        }
        t[i as usize] = c;
        i += 1;
    }
    t
};

/// Compute CRC-32 MPEG-2 over `bytes`. Initial shift-register value is the
/// canonical `0xFFFF_FFFF`.
#[inline]
pub fn compute(bytes: &[u8]) -> u32 {
    let mut crc: u32 = CRC_INIT;
    for &b in bytes {
        crc = (crc << CRC_STEP_BITS) ^ TABLE[((crc >> CRC_HI_SHIFT) as u8 ^ b) as usize];
    }
    crc
}

/// Write the CRC-32 trailer of a structure: the CRC of `buf[..crc_pos]` goes,
/// big-endian, into `buf[crc_pos..crc_pos + TRAILER_LEN]`.
///
/// # Errors
///
/// [`OutputBufferTooSmall`] when `buf` ends before the trailer does.
pub fn seal(buf: &mut [u8], crc_pos: usize) -> Result<(), OutputBufferTooSmall> {
    let need = crc_pos.saturating_add(TRAILER_LEN);
    let have = buf.len();
    let (covered, rest) = buf
        .split_at_mut_checked(crc_pos)
        .ok_or(OutputBufferTooSmall::new(need, have, "seal"))?;
    let trailer = rest
        .get_mut(..TRAILER_LEN)
        .ok_or(OutputBufferTooSmall::new(need, have, "seal"))?;
    trailer.copy_from_slice(&compute(covered).to_be_bytes());
    Ok(())
}

/// Check `expected`, the CRC a structure carries, against the CRC of the
/// `covered` bytes it protects.
///
/// # Errors
///
/// [`CrcMismatch`], naming `what` the CRC protects.
pub fn verify(covered: &[u8], expected: u32, what: &'static str) -> Result<(), CrcMismatch> {
    let computed = compute(covered);
    if computed == expected {
        Ok(())
    } else {
        Err(CrcMismatch::new(what, computed, expected))
    }
}

/// Check the trailing [`TRAILER_LEN`] bytes of `bytes` against the CRC of
/// everything before them; `None` when `bytes` is too short to carry a
/// trailer, `Some` of the verdict otherwise.
#[must_use]
pub fn verify_trailer(bytes: &[u8], what: &'static str) -> Option<Result<(), CrcMismatch>> {
    let (covered, trailer) = bytes.split_last_chunk::<TRAILER_LEN>()?;
    Some(verify(covered, u32::from_be_bytes(*trailer), what))
}

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

    const SECTION: [u8; 8] = [0x00, 0xB0, 0x0D, 0x00, 0x01, 0xC1, 0x00, 0x00];

    #[test]
    fn seal_then_verify_trailer_round_trips() {
        let mut buf = [SECTION.as_slice(), &[0; TRAILER_LEN]].concat();
        seal(&mut buf, SECTION.len()).expect("room for the trailer");
        assert_eq!(&buf[..SECTION.len()], SECTION);
        assert_eq!(verify_trailer(&buf, "test"), Some(Ok(())));
        let crc = u32::from_be_bytes([buf[8], buf[9], buf[10], buf[11]]);
        assert_eq!(crc, compute(&SECTION));
    }

    #[test]
    fn a_flipped_bit_is_a_mismatch_naming_the_structure() {
        let mut buf = [SECTION.as_slice(), &[0; TRAILER_LEN]].concat();
        seal(&mut buf, SECTION.len()).expect("room");
        buf[2] ^= 1;
        let Some(Err(mismatch)) = verify_trailer(&buf, "PSM") else {
            panic!("the flipped bit went unnoticed");
        };
        assert_eq!(mismatch.what, "PSM");
        assert_ne!(mismatch.computed, mismatch.expected);
    }

    #[test]
    fn seal_refuses_a_buffer_that_ends_before_the_trailer() {
        let mut buf = [0u8; 6];
        assert_eq!(
            seal(&mut buf, 4),
            Err(OutputBufferTooSmall::new(8, 6, "seal"))
        );
        assert_eq!(
            seal(&mut buf, 9),
            Err(OutputBufferTooSmall::new(13, 6, "seal"))
        );
    }

    #[test]
    fn a_buffer_shorter_than_a_trailer_has_no_verdict() {
        assert_eq!(verify_trailer(&[1, 2, 3], "x"), None);
    }

    #[test]
    fn verify_checks_the_covered_bytes_against_the_carried_crc() {
        assert_eq!(verify(&SECTION, compute(&SECTION), "x"), Ok(()));
        assert!(verify(&SECTION, 0, "x").is_err());
    }
}