broadcast-core 0.1.0

Frozen wire-format contract for the rust-broadcast crates: symmetric Parse/Serialize traits, checked field-width helpers, MSB-first bit I/O, reserved-bit fields, media timescales, the shared error kinds and the CENC scheme identity. no_std + alloc.
Documentation
//! A typed run of `reserved` / `reserved_future_use` / unused bits inside a
//! fixed-width field.
//!
//! Policy (owner decision, mirroring `dvb-si`'s `SectionBits`, #1177): the
//! parser is tolerant — whatever a sender put in a reserved bit field is
//! accepted — and the serializer **writes back what was parsed**, so
//! `parse -> serialize` is byte-exact. A hand-built object defaults to the
//! value the specification fixes for the field (all ones for `reserved`
//! `'1…1'`, zero for a bit the spec says is `0`), which is what
//! [`Default`] yields. The bits are a wire artefact, not part of a decoded
//! view, so a struct carrying one usually marks the field `serde(skip)`.
//!
//! The width is a `const`, so a value wider than the field is unrepresentable
//! and a serializer never has to re-mask one.

use crate::error::FieldOverflow;

/// `BITS` reserved bits (1..=64) whose default is all ones when `ONES` is
/// `true` and all zeros when it is `false`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct Reserved<const BITS: u32, const ONES: bool>(u64);

/// A `BITS`-wide `reserved` field the specification fills with `'1'` bits.
pub type ReservedOnes<const BITS: u32> = Reserved<BITS, true>;
/// A `BITS`-wide field the specification fixes at `'0'` bits.
pub type ReservedZero<const BITS: u32> = Reserved<BITS, false>;

impl<const BITS: u32, const ONES: bool> Reserved<BITS, ONES> {
    /// Mask of the field's `BITS` bits.
    pub const MASK: u64 = {
        assert!(BITS >= 1 && BITS <= 64, "Reserved is 1..=64 bits wide");
        u64::MAX >> (u64::BITS - BITS)
    };

    /// The spec fill: all ones or all zeros.
    pub const FILL: Self = Self(if ONES { Self::MASK } else { 0 });

    /// The field's value taken from the low `BITS` bits of `value` (any
    /// higher bits are not part of the field and are dropped).
    ///
    /// This is a parse-side extractor: it takes the field out of a wider
    /// word that holds its neighbours too. A hand-built value goes through
    /// [`try_new`](Self::try_new), which never masks.
    #[must_use]
    pub const fn from_bits(value: u64) -> Self {
        Self(value & Self::MASK)
    }

    /// The field holding `value`, or a [`FieldOverflow`] naming `field` when
    /// `value` does not fit in `BITS` bits.
    ///
    /// # Errors
    /// [`FieldOverflow`] when `value` has bits set above the field.
    pub const fn try_new(value: u64, field: &'static str) -> Result<Self, FieldOverflow> {
        if value & !Self::MASK != 0 {
            return Err(FieldOverflow::new(field, value, Self::MASK));
        }
        Ok(Self(value))
    }

    /// The field value, right-aligned (`0..=MASK`).
    #[must_use]
    pub const fn get(self) -> u64 {
        self.0
    }
}

/// The value a spec enum's catch-all arm carries for a `BITS`-wide field
/// (1..=8), so the arm cannot hold a value the field cannot encode.
///
/// A parser takes the field out of its byte with [`from_bits`](Self::from_bits);
/// a hand-built value goes through [`try_new`](Self::try_new), which never
/// masks. An encoder therefore writes [`get`](Self::get) as it is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct FieldValue<const BITS: u32>(u8);

impl<const BITS: u32> FieldValue<BITS> {
    /// Mask of the field's `BITS` bits.
    pub const MASK: u8 = {
        assert!(
            BITS >= 1 && BITS <= u8::BITS,
            "FieldValue is 1..=8 bits wide"
        );
        u8::MAX >> (u8::BITS - BITS)
    };

    /// The field's value taken from the low `BITS` bits of `byte`, the
    /// parse-side extractor for a field that shares its byte with neighbours.
    #[must_use]
    pub const fn from_bits(byte: u8) -> Self {
        Self(byte & Self::MASK)
    }

    /// The field holding `value`, or a [`FieldOverflow`] naming `field` when
    /// `value` does not fit in `BITS` bits.
    ///
    /// # Errors
    /// [`FieldOverflow`] when `value` has bits set above the field.
    pub const fn try_new(value: u8, field: &'static str) -> Result<Self, FieldOverflow> {
        if value & !Self::MASK != 0 {
            return Err(FieldOverflow::new(field, value as u64, Self::MASK as u64));
        }
        Ok(Self(value))
    }

    /// The field value, right-aligned (`0..=MASK`).
    #[must_use]
    pub const fn get(self) -> u8 {
        self.0
    }
}

impl<const BITS: u32> core::fmt::UpperHex for FieldValue<BITS> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::UpperHex::fmt(&self.0, f)
    }
}

impl<const BITS: u32, const ONES: bool> Default for Reserved<BITS, ONES> {
    fn default() -> Self {
        Self::FILL
    }
}

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

    #[test]
    fn defaults_are_the_spec_fill_and_values_are_masked() {
        assert_eq!(ReservedOnes::<3>::default().get(), 0b111);
        assert_eq!(ReservedOnes::<8>::default().get(), 0xFF);
        assert_eq!(ReservedZero::<4>::default().get(), 0);
        assert_eq!(ReservedOnes::<2>::from_bits(0xF5).get(), 0b01);
        assert_eq!(ReservedZero::<1>::from_bits(0x03).get(), 1);
    }
    #[test]
    fn a_wide_field_holds_its_full_width() {
        assert_eq!(ReservedOnes::<12>::FILL.get(), 0x0FFF);
        assert_eq!(ReservedOnes::<12>::from_bits(0x1_2345).get(), 0x345);
        assert_eq!(ReservedZero::<64>::from_bits(u64::MAX).get(), u64::MAX);
    }

    #[test]
    fn field_value_holds_every_value_of_its_width_and_refuses_the_rest() {
        for value in 0..=u8::MAX {
            let narrow = FieldValue::<3>::try_new(value, "f");
            if value <= 0b111 {
                assert_eq!(narrow.map(FieldValue::get), Ok(value));
            } else {
                assert_eq!(
                    narrow,
                    Err(FieldOverflow::new("f", u64::from(value), 0b111))
                );
            }
            assert_eq!(FieldValue::<3>::from_bits(value).get(), value & 0b111);
            assert_eq!(
                FieldValue::<8>::try_new(value, "f").map(FieldValue::get),
                Ok(value)
            );
        }
    }

    #[test]
    fn try_new_refuses_a_value_wider_than_the_field() {
        assert_eq!(
            ReservedOnes::<3>::try_new(0b101, "r").map(Reserved::get),
            Ok(0b101)
        );
        assert_eq!(
            ReservedOnes::<3>::try_new(0b1000, "r"),
            Err(FieldOverflow::new("r", 0b1000, 0b111))
        );
        assert_eq!(
            ReservedZero::<64>::try_new(u64::MAX, "r").map(Reserved::get),
            Ok(u64::MAX)
        );
    }
}