Skip to main content

labstream_proto/
seq.rs

1//! The sequence numbers of the `seq/1` feature. `docs/extensions.md`.
2//!
3//! A numbering record can stand between two samples. It gives the number of
4//! the next sample. The outlet writes one record at the start of each
5//! connection, and one more before each sample whose number is not one more
6//! than the number of the sample before it. The inlet counts the numbers
7//! that never arrived.
8
9/// The first byte of a numbering record.
10///
11/// The sample tags are 1 and 2 (`src/sample.h:19-20`, SPEC.md 7.1). This
12/// value is neither, so the first byte tells a record from a sample.
13pub const TAG: u8 = 0xFE;
14
15/// The length of a numbering record in bytes.
16pub const RECORD_LEN: usize = 9;
17
18/// Append a record that gives `number` to the next sample.
19///
20/// The number is always little-endian. The byte order of the connection does
21/// not apply to it.
22pub fn write_record(out: &mut Vec<u8>, number: u64) {
23    out.push(TAG);
24    out.extend_from_slice(&number.to_le_bytes());
25}
26
27/// What starts at a position in the sample stream.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum Next {
30    /// A complete record, with its number.
31    Record(u64),
32    /// A record that is cut. The caller reads more bytes.
33    Incomplete,
34    /// No record. The bytes start a sample, or nothing.
35    Sample,
36}
37
38/// Look at the start of `buf` for a record.
39pub fn peek(buf: &[u8]) -> Next {
40    match buf.first() {
41        Some(&TAG) if buf.len() >= RECORD_LEN => {
42            let mut b = [0u8; 8];
43            b.copy_from_slice(&buf[1..RECORD_LEN]);
44            Next::Record(u64::from_le_bytes(b))
45        }
46        Some(&TAG) => Next::Incomplete,
47        _ => Next::Sample,
48    }
49}
50
51/// The count of lost samples on the inlet side.
52///
53/// The counter keeps the number that it expects next. A record above that
54/// number adds the difference to the loss. Each sample moves the expected
55/// number by one.
56#[derive(Debug, Clone, Default, PartialEq, Eq)]
57pub struct Counter {
58    expected: Option<u64>,
59    lost: u64,
60    backwards: u64,
61}
62
63impl Counter {
64    /// A counter with no expected number yet.
65    pub fn new() -> Self {
66        Counter::default()
67    }
68
69    /// Read a record.
70    ///
71    /// The first record sets the expected number and counts no loss. A number
72    /// below the expected number counts no loss: it adds one to
73    /// [`Counter::backwards`], and the counter takes the new number.
74    pub fn record(&mut self, number: u64) {
75        if let Some(e) = self.expected {
76            if number > e {
77                self.lost = self.lost.saturating_add(number - e);
78            } else if number < e {
79                self.backwards = self.backwards.saturating_add(1);
80            }
81        }
82        self.expected = Some(number);
83    }
84
85    /// Count one sample.
86    pub fn sample(&mut self) {
87        if let Some(e) = self.expected {
88            self.expected = Some(e.saturating_add(1));
89        }
90    }
91
92    /// Take `number` as the expected number, and count nothing. An inlet that
93    /// merges two paths knows the expected number better than the count of
94    /// one path. `docs/extensions.md`, section `dgram`.
95    pub fn resync(&mut self, number: u64) {
96        self.expected = Some(number);
97    }
98
99    /// Forget the expected number. A new outlet has a new counter.
100    pub fn restart(&mut self) {
101        self.expected = None;
102    }
103
104    /// The samples that never arrived, since the counter was made.
105    pub fn lost(&self) -> u64 {
106        self.lost
107    }
108
109    /// How many records gave a number below the expected one.
110    pub fn backwards(&self) -> u64 {
111        self.backwards
112    }
113
114    /// The number that the counter expects next, if it has one.
115    pub fn expected(&self) -> Option<u64> {
116        self.expected
117    }
118}
119
120/// The record decision on the outlet side, for one connection.
121///
122/// The writer calls [`Numbering::before`] with the number of each sample that
123/// it is about to write. The result tells whether a record goes first.
124#[derive(Debug, Clone, Default, PartialEq, Eq)]
125pub struct Numbering {
126    next: Option<u64>,
127}
128
129impl Numbering {
130    /// A new connection, which starts with a record.
131    pub fn new() -> Self {
132        Numbering::default()
133    }
134
135    /// Write the record that opens a connection. `number` is the number
136    /// that the next sample will get.
137    ///
138    /// The record goes out at once, before any sample. A gap that happened
139    /// before this connection is then visible to the inlet at once, also on
140    /// a stream that sends no more samples for a long time.
141    pub fn start(&mut self, number: u64, out: &mut Vec<u8>) {
142        write_record(out, number);
143        self.next = Some(number);
144    }
145
146    /// Write a record into `out` if the sample with `number` needs one, then
147    /// expect the number after it.
148    pub fn before(&mut self, number: u64, out: &mut Vec<u8>) {
149        if self.next != Some(number) {
150            write_record(out, number);
151        }
152        self.next = Some(number.wrapping_add(1));
153    }
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    #[test]
161    fn a_record_reads_back() {
162        for n in [0u64, 1, 255, 1 << 40, u64::MAX] {
163            let mut out = Vec::new();
164            write_record(&mut out, n);
165            assert_eq!(out.len(), RECORD_LEN);
166            assert_eq!(peek(&out), Next::Record(n));
167        }
168    }
169
170    #[test]
171    fn the_number_is_little_endian() {
172        let mut out = Vec::new();
173        write_record(&mut out, 0x0102_0304_0506_0708);
174        assert_eq!(out, [0xFE, 8, 7, 6, 5, 4, 3, 2, 1]);
175    }
176
177    #[test]
178    fn a_cut_record_asks_for_more_bytes() {
179        let mut out = Vec::new();
180        write_record(&mut out, 42);
181        for cut in 1..RECORD_LEN {
182            assert_eq!(peek(&out[..cut]), Next::Incomplete);
183        }
184        assert_eq!(peek(&[]), Next::Sample);
185        assert_eq!(peek(&[1, 0, 0]), Next::Sample);
186        assert_eq!(peek(&[2]), Next::Sample);
187    }
188
189    #[test]
190    fn the_first_record_counts_no_loss() {
191        let mut c = Counter::new();
192        c.record(1000);
193        assert_eq!(c.lost(), 0);
194        assert_eq!(c.expected(), Some(1000));
195    }
196
197    #[test]
198    fn a_gap_counts_the_missing_numbers() {
199        let mut c = Counter::new();
200        c.record(10);
201        c.sample(); // 10
202        c.sample(); // 11
203        c.record(15); // 12, 13, 14 are lost
204        c.sample();
205        assert_eq!(c.lost(), 3);
206        assert_eq!(c.expected(), Some(16));
207    }
208
209    #[test]
210    fn a_number_that_goes_back_counts_no_loss_and_does_not_underflow() {
211        let mut c = Counter::new();
212        c.record(100);
213        c.sample();
214        c.record(5);
215        assert_eq!(c.lost(), 0);
216        assert_eq!(c.backwards(), 1);
217        assert_eq!(c.expected(), Some(5));
218    }
219
220    #[test]
221    fn a_restart_takes_a_new_baseline() {
222        let mut c = Counter::new();
223        c.record(50);
224        c.restart();
225        c.record(0);
226        c.record(3);
227        assert_eq!(c.lost(), 3);
228        assert_eq!(c.backwards(), 0);
229    }
230
231    #[test]
232    fn a_started_connection_needs_no_second_record_for_the_next_number() {
233        let mut w = Numbering::new();
234        let mut out = Vec::new();
235        w.start(30, &mut out);
236        assert_eq!(peek(&out), Next::Record(30));
237        let mut more = Vec::new();
238        w.before(30, &mut more);
239        assert!(more.is_empty(), "the next sample follows the record");
240        w.before(35, &mut more);
241        assert_eq!(peek(&more), Next::Record(35));
242    }
243
244    #[test]
245    fn the_writer_and_the_counter_agree() {
246        // The numbers that a writer sends, with gaps from dropped samples.
247        let numbers = [7u64, 8, 9, 12, 13, 20, 21, 22];
248        let mut w = Numbering::new();
249        let mut c = Counter::new();
250        let mut records = 0;
251        for n in numbers {
252            let mut out = Vec::new();
253            w.before(n, &mut out);
254            if let Next::Record(r) = peek(&out) {
255                records += 1;
256                c.record(r);
257            }
258            c.sample();
259        }
260        assert_eq!(records, 3, "one at the start and one at each gap");
261        assert_eq!(c.lost(), 2 + 6);
262        assert_eq!(c.expected(), Some(23));
263    }
264}