1use alloc::collections::VecDeque;
38use alloc::vec::Vec;
39use core::num::NonZeroUsize;
40
41use bytes::{Bytes, BytesMut};
42
43use crate::ts::ContinuityCounter;
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47#[non_exhaustive]
48pub enum Fed {
49 Accepted,
51 Duplicate,
53}
54
55impl Fed {
56 #[must_use]
58 pub fn name(&self) -> &'static str {
59 match self {
60 Self::Accepted => "accepted",
61 Self::Duplicate => "duplicate",
62 }
63 }
64}
65broadcast_core::impl_spec_display!(Fed);
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69#[non_exhaustive]
70pub enum UnitLength {
71 Total(usize),
73 NeedMore,
75 Stuffing,
78}
79
80impl UnitLength {
81 #[must_use]
83 pub fn name(&self) -> &'static str {
84 match self {
85 Self::Total(_) => "total",
86 Self::NeedMore => "need_more",
87 Self::Stuffing => "stuffing",
88 }
89 }
90}
91broadcast_core::impl_spec_display!(UnitLength);
92
93pub trait Framing {
95 fn length(&self, buf: &[u8]) -> UnitLength;
97}
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103#[non_exhaustive]
104pub enum AfterContinuation {
105 DiscardRest,
107 ParseRest,
110}
111
112impl AfterContinuation {
113 #[must_use]
115 pub fn name(&self) -> &'static str {
116 match self {
117 Self::DiscardRest => "discard_rest",
118 Self::ParseRest => "parse_rest",
119 }
120 }
121}
122broadcast_core::impl_spec_display!(AfterContinuation);
123
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126#[non_exhaustive]
127pub enum PointerCheck {
128 Authoritative,
131 MatchRemaining,
134}
135
136impl PointerCheck {
137 #[must_use]
139 pub fn name(&self) -> &'static str {
140 match self {
141 Self::Authoritative => "authoritative",
142 Self::MatchRemaining => "match_remaining",
143 }
144 }
145}
146broadcast_core::impl_spec_display!(PointerCheck);
147
148#[derive(Debug, Clone, Copy, PartialEq, Eq)]
150#[non_exhaustive]
151pub enum Duplicates {
152 Any,
154 ContinuationOnly,
159}
160
161impl Duplicates {
162 #[must_use]
164 pub fn name(&self) -> &'static str {
165 match self {
166 Self::Any => "any",
167 Self::ContinuationOnly => "continuation_only",
168 }
169 }
170}
171broadcast_core::impl_spec_display!(Duplicates);
172
173#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175pub struct Continuity {
176 counter: ContinuityCounter,
177 discontinuity: bool,
178}
179
180impl Continuity {
181 #[must_use]
184 pub const fn new(counter: ContinuityCounter, discontinuity: bool) -> Self {
185 Self {
186 counter,
187 discontinuity,
188 }
189 }
190}
191
192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194pub struct UnitOptions {
195 after_continuation: AfterContinuation,
196 pointer_check: PointerCheck,
197 duplicates: Duplicates,
198 max_unit_size: NonZeroUsize,
199}
200
201impl UnitOptions {
202 #[must_use]
205 pub const fn new(
206 after_continuation: AfterContinuation,
207 pointer_check: PointerCheck,
208 duplicates: Duplicates,
209 max_unit_size: NonZeroUsize,
210 ) -> Self {
211 Self {
212 after_continuation,
213 pointer_check,
214 duplicates,
215 max_unit_size,
216 }
217 }
218}
219
220#[derive(Debug)]
222pub struct UnitReassembler<F> {
223 framing: F,
224 options: UnitOptions,
225 buf: BytesMut,
226 ready: VecDeque<Bytes>,
227 synced: bool,
228 last: Option<(ContinuityCounter, Vec<u8>)>,
229}
230
231impl<F: Framing> UnitReassembler<F> {
232 #[must_use]
234 pub fn new(framing: F, options: UnitOptions) -> Self {
235 Self {
236 framing,
237 options,
238 buf: BytesMut::new(),
239 ready: VecDeque::new(),
240 synced: false,
241 last: None,
242 }
243 }
244
245 pub fn feed(&mut self, payload: &[u8], pusi: bool, continuity: Option<Continuity>) -> Fed {
249 match continuity {
250 Some(c) => {
251 let duplicate = !c.discontinuity
252 && self
253 .last
254 .as_ref()
255 .is_some_and(|(counter, bytes)| *counter == c.counter && bytes == payload);
256 self.last = Some((c.counter, payload.to_vec()));
257 if duplicate && (!pusi || self.options.duplicates == Duplicates::Any) {
258 return Fed::Duplicate;
259 }
260 }
261 None => self.last = None,
262 }
263 if pusi {
264 self.feed_start(payload);
265 } else {
266 self.feed_continuation(payload);
267 }
268 Fed::Accepted
269 }
270
271 fn feed_start(&mut self, payload: &[u8]) {
272 let Some((&pointer, rest)) = payload.split_first() else {
273 self.buf.clear();
274 self.synced = false;
275 return;
276 };
277 let pointer = usize::from(pointer);
278 if self.synced && !self.buf.is_empty() && pointer > 0 {
279 let consistent = match self.options.pointer_check {
280 PointerCheck::Authoritative => true,
281 PointerCheck::MatchRemaining => match self.framing.length(&self.buf) {
282 UnitLength::Total(total) => {
283 let remaining = total.saturating_sub(self.buf.len());
284 remaining == 0 || remaining == pointer
285 }
286 _ => true,
287 },
288 };
289 if !consistent {
290 self.buf.clear();
291 } else {
292 let tail = pointer.min(rest.len());
293 if self.buf.len() + tail > self.options.max_unit_size.get() {
294 self.buf.clear();
295 } else {
296 self.buf.extend_from_slice(&rest[..tail]);
297 self.drain();
298 }
299 }
300 }
301 self.buf.clear();
302 if pointer > rest.len() {
303 self.synced = false;
304 return;
305 }
306 self.synced = true;
307 let fresh = &rest[pointer..];
308 if fresh.len() > self.options.max_unit_size.get() {
309 self.synced = false;
310 return;
311 }
312 self.buf.extend_from_slice(fresh);
313 self.drain();
314 }
315
316 fn feed_continuation(&mut self, payload: &[u8]) {
317 if !self.synced
318 || (self.buf.is_empty()
319 && self.options.after_continuation == AfterContinuation::DiscardRest)
320 {
321 return;
322 }
323 let max = self.options.max_unit_size.get();
324 let take = match self.options.after_continuation {
325 AfterContinuation::ParseRest => payload.len(),
326 AfterContinuation::DiscardRest => match self.framing.length(&self.buf) {
327 UnitLength::Total(total) => total.saturating_sub(self.buf.len()),
328 _ => max.saturating_sub(self.buf.len()),
329 }
330 .min(payload.len()),
331 };
332 if self.buf.len() + take > max {
333 self.buf.clear();
334 self.synced = false;
335 return;
336 }
337 self.buf.extend_from_slice(&payload[..take]);
338 self.drain();
339 }
340
341 fn drain(&mut self) {
342 let max = self.options.max_unit_size.get();
343 while !self.buf.is_empty() {
344 match self.framing.length(&self.buf) {
345 UnitLength::NeedMore => break,
346 UnitLength::Stuffing => {
347 self.buf.clear();
348 break;
349 }
350 UnitLength::Total(total) => {
351 if total == 0 || total > max {
352 self.buf.clear();
353 self.synced = false;
354 break;
355 }
356 if self.buf.len() < total {
357 break;
358 }
359 let unit = self.buf.split_to(total).freeze();
360 self.ready.push_back(unit);
361 }
362 }
363 }
364 }
365
366 pub fn pop(&mut self) -> Option<Bytes> {
368 self.ready.pop_front()
369 }
370
371 #[must_use]
373 pub fn len(&self) -> usize {
374 self.buf.len()
375 }
376
377 #[must_use]
379 pub fn is_empty(&self) -> bool {
380 self.buf.is_empty()
381 }
382
383 #[must_use]
385 pub fn is_synced(&self) -> bool {
386 self.synced
387 }
388
389 pub fn reset(&mut self) {
392 self.buf.clear();
393 self.synced = false;
394 }
395
396 pub fn take_buffered(&mut self) -> Bytes {
398 self.buf.split().freeze()
399 }
400
401 pub fn drop_buffered(&mut self) {
404 self.buf.clear();
405 }
406}
407
408#[cfg(test)]
409mod tests {
410 use super::*;
411 use alloc::vec;
412
413 struct Lengthed;
415
416 impl Framing for Lengthed {
417 fn length(&self, buf: &[u8]) -> UnitLength {
418 match buf[0] {
419 0xFF => UnitLength::Stuffing,
420 n => UnitLength::Total(usize::from(n) + 1),
421 }
422 }
423 }
424
425 fn reasm(after: AfterContinuation, check: PointerCheck) -> UnitReassembler<Lengthed> {
426 UnitReassembler::new(
427 Lengthed,
428 UnitOptions::new(
429 after,
430 check,
431 Duplicates::Any,
432 NonZeroUsize::MIN.saturating_add(63),
433 ),
434 )
435 }
436
437 fn cc(v: u8) -> Option<Continuity> {
438 Some(Continuity::new(
439 ContinuityCounter::try_new(v).expect("4-bit counter"),
440 false,
441 ))
442 }
443
444 fn drain(r: &mut UnitReassembler<Lengthed>) -> Vec<Vec<u8>> {
445 core::iter::from_fn(|| r.pop())
446 .map(|b| b.to_vec())
447 .collect()
448 }
449
450 #[test]
451 fn nothing_is_accepted_before_the_first_pusi() {
452 let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
453 r.feed(&[2, 1, 2], false, None);
454 assert!(drain(&mut r).is_empty());
455 r.feed(&[0, 2, 1, 2], true, None);
456 assert_eq!(drain(&mut r), [[2, 1, 2]]);
457 }
458
459 #[test]
460 fn a_legal_duplicate_continuation_is_discarded_once() {
461 for after in [AfterContinuation::DiscardRest, AfterContinuation::ParseRest] {
462 let mut r = reasm(after, PointerCheck::Authoritative);
463 r.feed(&[0, 8, 1, 2], true, cc(0));
464 r.feed(&[3, 4], false, cc(1));
465 let repeat = r.feed(&[3, 4], false, cc(1));
466 assert_eq!(repeat, Fed::Duplicate);
467 r.feed(&[5, 6, 7, 8], false, cc(2));
468 assert_eq!(drain(&mut r), [[8, 1, 2, 3, 4, 5, 6, 7, 8]], "{after}");
469 }
470 }
471
472 #[test]
473 fn a_repeated_counter_with_different_bytes_is_not_a_duplicate() {
474 let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
475 r.feed(&[0, 4, 1], true, cc(0));
476 r.feed(&[2], false, cc(1));
477 r.feed(&[3, 4], false, cc(1));
478 assert_eq!(drain(&mut r), [[4, 1, 2, 3, 4]]);
479 }
480
481 #[test]
482 fn a_discontinuity_makes_a_repeated_counter_legal_new_data() {
483 let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
484 r.feed(&[0, 3, 1], true, cc(0));
485 let flagged = Some(Continuity::new(
486 ContinuityCounter::try_new(0).expect("4-bit counter"),
487 true,
488 ));
489 r.feed(&[1], false, flagged);
490 assert!(drain(&mut r).is_empty());
491 assert_eq!(r.len(), 3);
492 }
493
494 #[test]
495 fn stuffing_after_a_unit_ends_the_payload() {
496 let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
497 r.feed(&[0, 1, 9, 0xFF, 0xFF, 0xFF], true, None);
498 assert_eq!(drain(&mut r), [[1, 9]]);
499 assert!(r.is_empty());
500 }
501
502 #[test]
503 fn the_pointer_tail_completes_the_unit_in_progress_before_new_units_start() {
504 let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
505 r.feed(&[0, 3, 1], true, None);
506 r.feed(&[2, 2, 3, 1, 7], true, None);
507 assert_eq!(drain(&mut r), [vec![3, 1, 2, 3], vec![1, 7]]);
508 }
509
510 #[test]
511 fn match_remaining_discards_a_partial_unit_whose_pointer_disagrees() {
512 let mut strict = reasm(AfterContinuation::DiscardRest, PointerCheck::MatchRemaining);
513 strict.feed(&[0, 5, 1], true, None);
514 strict.feed(&[1, 2, 1, 8], true, None);
515 assert_eq!(drain(&mut strict), [[1, 8]], "the partial unit is dropped");
516
517 let mut lax = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
518 lax.feed(&[0, 5, 1], true, None);
519 lax.feed(&[1, 2, 1, 8], true, None);
520 assert_eq!(
521 drain(&mut lax),
522 [[1, 8]],
523 "an incomplete tail is dropped too"
524 );
525
526 let mut agrees = reasm(AfterContinuation::DiscardRest, PointerCheck::MatchRemaining);
527 agrees.feed(&[0, 5, 1], true, None);
528 agrees.feed(&[4, 2, 3, 4, 5, 1, 8], true, None);
529 assert_eq!(drain(&mut agrees), [vec![5, 1, 2, 3, 4, 5], vec![1, 8]]);
530 }
531
532 #[test]
533 fn units_after_a_continuation_end_follow_the_option() {
534 let mut discard = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
535 discard.feed(&[0, 3, 1], true, None);
536 discard.feed(&[2, 3, 1, 9], false, None);
537 assert_eq!(drain(&mut discard), [[3, 1, 2, 3]]);
538
539 let mut parse = reasm(AfterContinuation::ParseRest, PointerCheck::Authoritative);
540 parse.feed(&[0, 3, 1], true, None);
541 parse.feed(&[2, 3, 1, 9], false, None);
542 assert_eq!(drain(&mut parse), [vec![3, 1, 2, 3], vec![1, 9]]);
543 parse.feed(&[1, 4], false, None);
544 assert_eq!(
545 drain(&mut parse),
546 [[1, 4]],
547 "a unit may start in a continuation"
548 );
549 discard.feed(&[1, 4], false, None);
550 assert!(drain(&mut discard).is_empty());
551 }
552
553 #[test]
554 fn a_pointer_past_the_payload_drops_sync_and_a_unit_over_the_cap_is_refused() {
555 let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
556 r.feed(&[9, 1], true, None);
557 assert!(!r.is_synced());
558 r.feed(&[0, 200, 1], true, None);
559 assert!(drain(&mut r).is_empty());
560 assert!(!r.is_synced());
561 }
562}