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
//! Wrap-safe arithmetic on fixed-width counters: 16-bit RTP sequence
//! numbers, 31-bit SRT packet numbers, 32-bit RTP and FLV timestamps, the
//! 33-bit MPEG-2 PTS/DTS.
//!
//! A [`Modulus`] is a counter space of `2^bits` values (`1..=63` bits). On it,
//! [`forward`](Modulus::forward) is the modular distance, and
//! [`signed`](Modulus::signed) the shorter of the two directions (the
//! half-range rule, comparable to RFC 1982 serial-number arithmetic): a
//! distance of exactly half the space resolves **forward**, so `signed` is in
//! `(-half, half]`, and the ordering predicates treat that tie as no order at
//! all. Every input is reduced modulo the space first.
//!
//! [`Unwrapper`] carries a counter across its wraps onto an unbounded
//! timeline, one step at a time: each raw value moves the timeline by the
//! signed distance from the previous raw value, so a small backward step
//! (B-frame reordering) stays backward and only a near-full-range jump is a
//! wrap. [`Modulus::extend_near`] is the stateless form: the value congruent
//! to a raw counter nearest a reference.
//!
//! [`crate::clock33`] is the 33-bit face of this module (plus the 27 MHz PCR
//! clock, whose modulus is not a power of two); the 16-bit RTP and 31-bit SRT
//! sequence-number spaces are [`Modulus`] values their crates name.

/// Widest supported space: a signed distance must fit an `i64`.
const MAX_BITS: u32 = i64::BITS - 1;

/// A counter space of `2^bits` values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Modulus {
    bits: u32,
}

impl Modulus {
    /// The `BITS`-wide space; a width outside `1..=63` is a compile error.
    #[must_use]
    pub const fn new<const BITS: u32>() -> Self {
        const {
            assert!(
                BITS >= 1 && BITS <= MAX_BITS,
                "a modulus is 1..=63 bits wide"
            );
        }
        Self { bits: BITS }
    }

    /// The `bits`-wide space, or `None` when `bits` is outside `1..=63`.
    #[must_use]
    pub const fn try_new(bits: u32) -> Option<Self> {
        if bits >= 1 && bits <= MAX_BITS {
            Some(Self { bits })
        } else {
            None
        }
    }

    /// The width of the space, in bits.
    #[must_use]
    pub const fn bits(self) -> u32 {
        self.bits
    }

    /// The number of values: `2^bits`.
    #[must_use]
    pub const fn modulus(self) -> u64 {
        1u64 << self.bits
    }

    /// `2^bits - 1`: the mask selecting a value of the space.
    #[must_use]
    pub const fn mask(self) -> u64 {
        self.modulus() - 1
    }

    /// Half the space: the largest forward distance [`signed`](Self::signed)
    /// reports as positive.
    #[must_use]
    pub const fn half(self) -> u64 {
        self.modulus() >> 1
    }

    /// `value mod 2^bits`.
    #[must_use]
    pub const fn reduce(self, value: u64) -> u64 {
        value & self.mask()
    }

    /// `(a + n) mod 2^bits`.
    #[must_use]
    pub const fn add(self, a: u64, n: u64) -> u64 {
        self.reduce(a.wrapping_add(n))
    }

    /// `(a + delta) mod 2^bits`, `delta` of either sign; always in the space.
    #[must_use]
    pub const fn add_signed(self, a: u64, delta: i64) -> u64 {
        self.reduce(a.wrapping_add_signed(delta))
    }

    /// The forward distance from `from` to `to`: `(to - from) mod 2^bits`.
    #[must_use]
    pub const fn forward(self, from: u64, to: u64) -> u64 {
        self.reduce(to.wrapping_sub(from))
    }

    /// The shorter signed distance from `from` to `to`, in `(-half, half]`:
    /// crossing the wrap forward is a small positive step, stepping back
    /// across it a small negative one; exactly half the space apart is
    /// `+half`.
    #[must_use]
    pub const fn signed(self, from: u64, to: u64) -> i64 {
        let forward = self.forward(from, to);
        if forward <= self.half() {
            forward.cast_signed()
        } else {
            (forward.wrapping_sub(self.modulus())).cast_signed()
        }
    }

    /// `a` and `b` are exactly half the space apart, so neither precedes the
    /// other.
    #[must_use]
    pub const fn is_tie(self, a: u64, b: u64) -> bool {
        self.forward(b, a) == self.half()
    }

    /// `a` precedes `b`.
    #[must_use]
    pub const fn lt(self, a: u64, b: u64) -> bool {
        self.signed(b, a) < 0
    }

    /// `a` precedes or equals `b`; `false` at the half-space tie.
    #[must_use]
    pub const fn leq(self, a: u64, b: u64) -> bool {
        self.signed(b, a) <= 0
    }

    /// `a` follows `b`; `false` at the half-space tie.
    #[must_use]
    pub const fn gt(self, a: u64, b: u64) -> bool {
        self.signed(b, a) > 0 && !self.is_tie(a, b)
    }

    /// `a` follows or equals `b`; `false` at the half-space tie.
    #[must_use]
    pub const fn geq(self, a: u64, b: u64) -> bool {
        self.signed(b, a) >= 0 && !self.is_tie(a, b)
    }

    /// `value` lies in the inclusive range `first..=last`, walking forward
    /// from `first`. A `last` that precedes `first` is an empty range.
    #[must_use]
    pub const fn in_closed_range(self, value: u64, first: u64, last: u64) -> bool {
        let span = self.signed(first, last);
        if span < 0 {
            return false;
        }
        let offset = self.signed(first, value);
        offset >= 0 && offset <= span
    }

    /// The value congruent to `raw` that lies nearest `reference` on the
    /// unbounded timeline (the half-range rule decides a tie forward), or
    /// `None` when it does not fit an `i64`.
    #[must_use]
    pub const fn extend_near(self, reference: i64, raw: u64) -> Option<i64> {
        reference.checked_add(self.signed(reference.cast_unsigned(), raw))
    }
}

/// Carries a wrapping counter onto an unbounded timeline, one value at a
/// time.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Unwrapper {
    modulus: Modulus,
    last: Option<(u64, i128)>,
}

impl Unwrapper {
    /// An unwrapper whose first value lands on the timeline at its own raw
    /// value.
    #[must_use]
    pub const fn new(modulus: Modulus) -> Self {
        Self {
            modulus,
            last: None,
        }
    }

    /// An unwrapper whose timeline is already at `origin`: the first value
    /// lands nearest it.
    #[must_use]
    pub const fn seeded(modulus: Modulus, origin: i128) -> Self {
        Self {
            modulus,
            last: Some((origin.cast_unsigned() as u64, origin)),
        }
    }

    /// The space this unwrapper counts in.
    #[must_use]
    pub const fn modulus(&self) -> Modulus {
        self.modulus
    }

    /// The timeline position of the last value, or of the seed; `None`
    /// before either.
    #[must_use]
    pub const fn position(&self) -> Option<i128> {
        match self.last {
            Some((_, position)) => Some(position),
            None => None,
        }
    }

    /// The timeline position of `raw`: the previous position moved by the
    /// signed distance from the previous raw value (the raw value itself for
    /// the first one).
    pub fn unwrap(&mut self, raw: u64) -> i128 {
        let position = match self.last {
            Some((previous_raw, previous)) => {
                previous + i128::from(self.modulus.signed(previous_raw, raw))
            }
            None => i128::from(raw),
        };
        self.last = Some((raw, position));
        position
    }
}

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

    const S16: Modulus = Modulus::new::<16>();
    const S32: Modulus = Modulus::new::<32>();
    const S33: Modulus = Modulus::new::<33>();

    #[test]
    fn widths_outside_the_range_are_refused_at_runtime() {
        assert_eq!(Modulus::try_new(0), None);
        assert_eq!(Modulus::try_new(64), None);
        assert_eq!(Modulus::try_new(1), Some(Modulus::new::<1>()));
        assert_eq!(Modulus::try_new(63), Some(Modulus::new::<63>()));
        assert_eq!(Modulus::new::<63>().modulus(), 1 << 63);
        assert_eq!(S16.mask(), 0xFFFF);
        assert_eq!(S16.half(), 0x8000);
    }

    #[test]
    fn forward_and_signed_cross_the_wrap() {
        assert_eq!(S16.forward(0xFFFF, 0), 1);
        assert_eq!(S16.forward(0, 0xFFFF), 0xFFFF);
        assert_eq!(S16.signed(0xFFFF, 0), 1);
        assert_eq!(S16.signed(0, 0xFFFF), -1);
        assert_eq!(S16.signed(5, 5), 0);
        assert_eq!(S32.signed(u64::from(u32::MAX) - 9, 5), 15);
        assert_eq!(S33.signed(5, (1 << 33) - 10), -15);
    }

    #[test]
    fn the_half_space_tie_resolves_forward_and_orders_nothing() {
        assert_eq!(S16.signed(0, 0x8000), 0x8000);
        assert_eq!(S16.signed(0x8000, 0), 0x8000);
        assert!(S16.is_tie(0, 0x8000));
        for (a, b) in [(0, 0x8000), (0x8000, 0)] {
            assert!(!S16.lt(a, b));
            assert!(!S16.gt(a, b));
            assert!(!S16.leq(a, b));
            assert!(!S16.geq(a, b));
        }
        assert_eq!(S16.signed(0, 0x8001), -0x7FFF);
        assert_eq!(S16.signed(0, 0x7FFF), 0x7FFF);
    }

    #[test]
    fn ordering_predicates_follow_the_shorter_direction() {
        assert!(S16.lt(0xFFFF, 0));
        assert!(S16.gt(0, 0xFFFF));
        assert!(S16.leq(3, 3));
        assert!(S16.geq(3, 3));
        assert!(S16.in_closed_range(0, 0xFFFE, 2));
        assert!(!S16.in_closed_range(3, 0xFFFE, 2));
        assert!(!S16.in_closed_range(0, 2, 0xFFFE));
    }

    #[test]
    fn inputs_are_reduced_and_addition_wraps() {
        assert_eq!(S16.reduce(0x1_0005), 5);
        assert_eq!(S16.add(0xFFFF, 1), 0);
        assert_eq!(S16.add(u64::MAX, 1), 0);
        assert_eq!(S16.add_signed(5, -10), 0xFFFB);
        assert_eq!(S16.add_signed(0, i64::MIN), 0);
        assert_eq!(S33.add_signed(5, -10), (1 << 33) - 5);
        assert_eq!(S16.forward(0x1_0000, 0x2_0001), 1);
    }

    #[test]
    fn extend_near_picks_the_closest_congruent_value() {
        assert_eq!(S32.extend_near(0x1_0000_0005, 3), Some(0x1_0000_0003));
        assert_eq!(S32.extend_near(0x1_FFFF_FFFE, 2), Some(0x2_0000_0002));
        assert_eq!(S32.extend_near(2, u64::from(u32::MAX)), Some(-1));
        assert_eq!(
            S32.extend_near(i64::MAX, u64::from(u32::MAX)),
            Some(i64::MAX)
        );
        assert_eq!(S32.extend_near(i64::MAX, 0), None);
        assert_eq!(S32.extend_near(i64::MIN, u64::from(u32::MAX)), None);
    }

    #[test]
    fn the_unwrapper_carries_a_counter_across_its_wraps_in_both_directions() {
        let mut u = Unwrapper::new(S16);
        assert_eq!(u.unwrap(0xFFFE), 0xFFFE);
        assert_eq!(u.unwrap(1), 0x1_0001);
        assert_eq!(u.unwrap(0xFFFF), 0xFFFF);
        assert_eq!(u.unwrap(0x7FFF), 0x1_7FFF);
        assert_eq!(Unwrapper::new(S16).position(), None);
        assert_eq!(u.position(), Some(0x1_7FFF));
        let mut seeded = Unwrapper::seeded(S33, (1 << 33) + 10);
        assert_eq!(seeded.position(), Some((1 << 33) + 10));
        assert_eq!(seeded.unwrap(5), (1 << 33) + 5);
        assert_eq!(seeded.modulus(), S33);
        let mut back = Unwrapper::new(S33);
        assert_eq!(back.unwrap(2), 2);
        assert_eq!(back.unwrap((1 << 33) - 3), -3);
    }

    #[test]
    fn the_32_bit_unwrap_table_holds_for_every_edge() {
        const CASES: [(&[u32], &[i128]); 6] = [
            (
                &[0xFFFF_F000, 0xFFFF_FBB8, 0x0000_0770],
                &[0xFFFF_F000, 0xFFFF_FBB8, 0x1_0000_0770],
            ),
            (&[0x9000_0000], &[0x9000_0000]),
            (&[0x0001_0000, 0x0000_F448], &[0x1_0000, 0xF448]),
            (&[0, 0x8000_0000], &[0, 0x8000_0000]),
            (&[1000, 0xFFFF_F000], &[1000, -4096]),
            (&[0xFFFF_F000, 1000], &[0xFFFF_F000, 0x1_0000_03E8]),
        ];
        for (raws, expected) in CASES {
            let mut unwrapper = Unwrapper::new(S32);
            let got: alloc::vec::Vec<i128> = raws
                .iter()
                .map(|&raw| unwrapper.unwrap(u64::from(raw)))
                .collect();
            assert_eq!(got, expected, "{raws:x?}");
        }
    }
}