Skip to main content

broadcast_common/
modular.rs

1//! Wrap-safe arithmetic on fixed-width counters: 16-bit RTP sequence
2//! numbers, 31-bit SRT packet numbers, 32-bit RTP and FLV timestamps, the
3//! 33-bit MPEG-2 PTS/DTS.
4//!
5//! A [`Modulus`] is a counter space of `2^bits` values (`1..=63` bits). On it,
6//! [`forward`](Modulus::forward) is the modular distance, and
7//! [`signed`](Modulus::signed) the shorter of the two directions (the
8//! half-range rule, comparable to RFC 1982 serial-number arithmetic): a
9//! distance of exactly half the space resolves **forward**, so `signed` is in
10//! `(-half, half]`, and the ordering predicates treat that tie as no order at
11//! all. Every input is reduced modulo the space first.
12//!
13//! [`Unwrapper`] carries a counter across its wraps onto an unbounded
14//! timeline, one step at a time: each raw value moves the timeline by the
15//! signed distance from the previous raw value, so a small backward step
16//! (B-frame reordering) stays backward and only a near-full-range jump is a
17//! wrap. [`Modulus::extend_near`] is the stateless form: the value congruent
18//! to a raw counter nearest a reference.
19//!
20//! [`crate::clock33`] is the 33-bit face of this module (plus the 27 MHz PCR
21//! clock, whose modulus is not a power of two); the 16-bit RTP and 31-bit SRT
22//! sequence-number spaces are [`Modulus`] values their crates name.
23
24/// Widest supported space: a signed distance must fit an `i64`.
25const MAX_BITS: u32 = i64::BITS - 1;
26
27/// A counter space of `2^bits` values.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29pub struct Modulus {
30    bits: u32,
31}
32
33impl Modulus {
34    /// The `BITS`-wide space; a width outside `1..=63` is a compile error.
35    #[must_use]
36    pub const fn new<const BITS: u32>() -> Self {
37        const {
38            assert!(
39                BITS >= 1 && BITS <= MAX_BITS,
40                "a modulus is 1..=63 bits wide"
41            );
42        }
43        Self { bits: BITS }
44    }
45
46    /// The `bits`-wide space, or `None` when `bits` is outside `1..=63`.
47    #[must_use]
48    pub const fn try_new(bits: u32) -> Option<Self> {
49        if bits >= 1 && bits <= MAX_BITS {
50            Some(Self { bits })
51        } else {
52            None
53        }
54    }
55
56    /// The width of the space, in bits.
57    #[must_use]
58    pub const fn bits(self) -> u32 {
59        self.bits
60    }
61
62    /// The number of values: `2^bits`.
63    #[must_use]
64    pub const fn modulus(self) -> u64 {
65        1u64 << self.bits
66    }
67
68    /// `2^bits - 1`: the mask selecting a value of the space.
69    #[must_use]
70    pub const fn mask(self) -> u64 {
71        self.modulus() - 1
72    }
73
74    /// Half the space: the largest forward distance [`signed`](Self::signed)
75    /// reports as positive.
76    #[must_use]
77    pub const fn half(self) -> u64 {
78        self.modulus() >> 1
79    }
80
81    /// `value mod 2^bits`.
82    #[must_use]
83    pub const fn reduce(self, value: u64) -> u64 {
84        value & self.mask()
85    }
86
87    /// `(a + n) mod 2^bits`.
88    #[must_use]
89    pub const fn add(self, a: u64, n: u64) -> u64 {
90        self.reduce(a.wrapping_add(n))
91    }
92
93    /// `(a + delta) mod 2^bits`, `delta` of either sign; always in the space.
94    #[must_use]
95    pub const fn add_signed(self, a: u64, delta: i64) -> u64 {
96        self.reduce(a.wrapping_add_signed(delta))
97    }
98
99    /// The forward distance from `from` to `to`: `(to - from) mod 2^bits`.
100    #[must_use]
101    pub const fn forward(self, from: u64, to: u64) -> u64 {
102        self.reduce(to.wrapping_sub(from))
103    }
104
105    /// The shorter signed distance from `from` to `to`, in `(-half, half]`:
106    /// crossing the wrap forward is a small positive step, stepping back
107    /// across it a small negative one; exactly half the space apart is
108    /// `+half`.
109    #[must_use]
110    pub const fn signed(self, from: u64, to: u64) -> i64 {
111        let forward = self.forward(from, to);
112        if forward <= self.half() {
113            forward.cast_signed()
114        } else {
115            (forward.wrapping_sub(self.modulus())).cast_signed()
116        }
117    }
118
119    /// `a` and `b` are exactly half the space apart, so neither precedes the
120    /// other.
121    #[must_use]
122    pub const fn is_tie(self, a: u64, b: u64) -> bool {
123        self.forward(b, a) == self.half()
124    }
125
126    /// `a` precedes `b`.
127    #[must_use]
128    pub const fn lt(self, a: u64, b: u64) -> bool {
129        self.signed(b, a) < 0
130    }
131
132    /// `a` precedes or equals `b`; `false` at the half-space tie.
133    #[must_use]
134    pub const fn leq(self, a: u64, b: u64) -> bool {
135        self.signed(b, a) <= 0
136    }
137
138    /// `a` follows `b`; `false` at the half-space tie.
139    #[must_use]
140    pub const fn gt(self, a: u64, b: u64) -> bool {
141        self.signed(b, a) > 0 && !self.is_tie(a, b)
142    }
143
144    /// `a` follows or equals `b`; `false` at the half-space tie.
145    #[must_use]
146    pub const fn geq(self, a: u64, b: u64) -> bool {
147        self.signed(b, a) >= 0 && !self.is_tie(a, b)
148    }
149
150    /// `value` lies in the inclusive range `first..=last`, walking forward
151    /// from `first`. A `last` that precedes `first` is an empty range.
152    #[must_use]
153    pub const fn in_closed_range(self, value: u64, first: u64, last: u64) -> bool {
154        let span = self.signed(first, last);
155        if span < 0 {
156            return false;
157        }
158        let offset = self.signed(first, value);
159        offset >= 0 && offset <= span
160    }
161
162    /// The value congruent to `raw` that lies nearest `reference` on the
163    /// unbounded timeline (the half-range rule decides a tie forward), or
164    /// `None` when it does not fit an `i64`.
165    #[must_use]
166    pub const fn extend_near(self, reference: i64, raw: u64) -> Option<i64> {
167        reference.checked_add(self.signed(reference.cast_unsigned(), raw))
168    }
169}
170
171/// Carries a wrapping counter onto an unbounded timeline, one value at a
172/// time.
173#[derive(Debug, Clone, Copy, PartialEq, Eq)]
174pub struct Unwrapper {
175    modulus: Modulus,
176    last: Option<(u64, i128)>,
177}
178
179impl Unwrapper {
180    /// An unwrapper whose first value lands on the timeline at its own raw
181    /// value.
182    #[must_use]
183    pub const fn new(modulus: Modulus) -> Self {
184        Self {
185            modulus,
186            last: None,
187        }
188    }
189
190    /// An unwrapper whose timeline is already at `origin`: the first value
191    /// lands nearest it.
192    #[must_use]
193    pub const fn seeded(modulus: Modulus, origin: i128) -> Self {
194        Self {
195            modulus,
196            last: Some((origin.cast_unsigned() as u64, origin)),
197        }
198    }
199
200    /// The space this unwrapper counts in.
201    #[must_use]
202    pub const fn modulus(&self) -> Modulus {
203        self.modulus
204    }
205
206    /// The timeline position of the last value, or of the seed; `None`
207    /// before either.
208    #[must_use]
209    pub const fn position(&self) -> Option<i128> {
210        match self.last {
211            Some((_, position)) => Some(position),
212            None => None,
213        }
214    }
215
216    /// The timeline position of `raw`: the previous position moved by the
217    /// signed distance from the previous raw value (the raw value itself for
218    /// the first one).
219    pub fn unwrap(&mut self, raw: u64) -> i128 {
220        let position = match self.last {
221            Some((previous_raw, previous)) => {
222                previous + i128::from(self.modulus.signed(previous_raw, raw))
223            }
224            None => i128::from(raw),
225        };
226        self.last = Some((raw, position));
227        position
228    }
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    const S16: Modulus = Modulus::new::<16>();
236    const S32: Modulus = Modulus::new::<32>();
237    const S33: Modulus = Modulus::new::<33>();
238
239    #[test]
240    fn widths_outside_the_range_are_refused_at_runtime() {
241        assert_eq!(Modulus::try_new(0), None);
242        assert_eq!(Modulus::try_new(64), None);
243        assert_eq!(Modulus::try_new(1), Some(Modulus::new::<1>()));
244        assert_eq!(Modulus::try_new(63), Some(Modulus::new::<63>()));
245        assert_eq!(Modulus::new::<63>().modulus(), 1 << 63);
246        assert_eq!(S16.mask(), 0xFFFF);
247        assert_eq!(S16.half(), 0x8000);
248    }
249
250    #[test]
251    fn forward_and_signed_cross_the_wrap() {
252        assert_eq!(S16.forward(0xFFFF, 0), 1);
253        assert_eq!(S16.forward(0, 0xFFFF), 0xFFFF);
254        assert_eq!(S16.signed(0xFFFF, 0), 1);
255        assert_eq!(S16.signed(0, 0xFFFF), -1);
256        assert_eq!(S16.signed(5, 5), 0);
257        assert_eq!(S32.signed(u64::from(u32::MAX) - 9, 5), 15);
258        assert_eq!(S33.signed(5, (1 << 33) - 10), -15);
259    }
260
261    #[test]
262    fn the_half_space_tie_resolves_forward_and_orders_nothing() {
263        assert_eq!(S16.signed(0, 0x8000), 0x8000);
264        assert_eq!(S16.signed(0x8000, 0), 0x8000);
265        assert!(S16.is_tie(0, 0x8000));
266        for (a, b) in [(0, 0x8000), (0x8000, 0)] {
267            assert!(!S16.lt(a, b));
268            assert!(!S16.gt(a, b));
269            assert!(!S16.leq(a, b));
270            assert!(!S16.geq(a, b));
271        }
272        assert_eq!(S16.signed(0, 0x8001), -0x7FFF);
273        assert_eq!(S16.signed(0, 0x7FFF), 0x7FFF);
274    }
275
276    #[test]
277    fn ordering_predicates_follow_the_shorter_direction() {
278        assert!(S16.lt(0xFFFF, 0));
279        assert!(S16.gt(0, 0xFFFF));
280        assert!(S16.leq(3, 3));
281        assert!(S16.geq(3, 3));
282        assert!(S16.in_closed_range(0, 0xFFFE, 2));
283        assert!(!S16.in_closed_range(3, 0xFFFE, 2));
284        assert!(!S16.in_closed_range(0, 2, 0xFFFE));
285    }
286
287    #[test]
288    fn inputs_are_reduced_and_addition_wraps() {
289        assert_eq!(S16.reduce(0x1_0005), 5);
290        assert_eq!(S16.add(0xFFFF, 1), 0);
291        assert_eq!(S16.add(u64::MAX, 1), 0);
292        assert_eq!(S16.add_signed(5, -10), 0xFFFB);
293        assert_eq!(S16.add_signed(0, i64::MIN), 0);
294        assert_eq!(S33.add_signed(5, -10), (1 << 33) - 5);
295        assert_eq!(S16.forward(0x1_0000, 0x2_0001), 1);
296    }
297
298    #[test]
299    fn extend_near_picks_the_closest_congruent_value() {
300        assert_eq!(S32.extend_near(0x1_0000_0005, 3), Some(0x1_0000_0003));
301        assert_eq!(S32.extend_near(0x1_FFFF_FFFE, 2), Some(0x2_0000_0002));
302        assert_eq!(S32.extend_near(2, u64::from(u32::MAX)), Some(-1));
303        assert_eq!(
304            S32.extend_near(i64::MAX, u64::from(u32::MAX)),
305            Some(i64::MAX)
306        );
307        assert_eq!(S32.extend_near(i64::MAX, 0), None);
308        assert_eq!(S32.extend_near(i64::MIN, u64::from(u32::MAX)), None);
309    }
310
311    #[test]
312    fn the_unwrapper_carries_a_counter_across_its_wraps_in_both_directions() {
313        let mut u = Unwrapper::new(S16);
314        assert_eq!(u.unwrap(0xFFFE), 0xFFFE);
315        assert_eq!(u.unwrap(1), 0x1_0001);
316        assert_eq!(u.unwrap(0xFFFF), 0xFFFF);
317        assert_eq!(u.unwrap(0x7FFF), 0x1_7FFF);
318        assert_eq!(Unwrapper::new(S16).position(), None);
319        assert_eq!(u.position(), Some(0x1_7FFF));
320        let mut seeded = Unwrapper::seeded(S33, (1 << 33) + 10);
321        assert_eq!(seeded.position(), Some((1 << 33) + 10));
322        assert_eq!(seeded.unwrap(5), (1 << 33) + 5);
323        assert_eq!(seeded.modulus(), S33);
324        let mut back = Unwrapper::new(S33);
325        assert_eq!(back.unwrap(2), 2);
326        assert_eq!(back.unwrap((1 << 33) - 3), -3);
327    }
328
329    #[test]
330    fn the_32_bit_unwrap_table_holds_for_every_edge() {
331        const CASES: [(&[u32], &[i128]); 6] = [
332            (
333                &[0xFFFF_F000, 0xFFFF_FBB8, 0x0000_0770],
334                &[0xFFFF_F000, 0xFFFF_FBB8, 0x1_0000_0770],
335            ),
336            (&[0x9000_0000], &[0x9000_0000]),
337            (&[0x0001_0000, 0x0000_F448], &[0x1_0000, 0xF448]),
338            (&[0, 0x8000_0000], &[0, 0x8000_0000]),
339            (&[1000, 0xFFFF_F000], &[1000, -4096]),
340            (&[0xFFFF_F000, 1000], &[0xFFFF_F000, 0x1_0000_03E8]),
341        ];
342        for (raws, expected) in CASES {
343            let mut unwrapper = Unwrapper::new(S32);
344            let got: alloc::vec::Vec<i128> = raws
345                .iter()
346                .map(|&raw| unwrapper.unwrap(u64::from(raw)))
347                .collect();
348            assert_eq!(got, expected, "{raws:x?}");
349        }
350    }
351}