use alloc::collections::VecDeque;
use alloc::vec::Vec;
use core::num::NonZeroUsize;
use bytes::{Bytes, BytesMut};
use crate::ts::ContinuityCounter;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Fed {
Accepted,
Duplicate,
}
impl Fed {
#[must_use]
pub fn name(&self) -> &'static str {
match self {
Self::Accepted => "accepted",
Self::Duplicate => "duplicate",
}
}
}
broadcast_core::impl_spec_display!(Fed);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum UnitLength {
Total(usize),
NeedMore,
Stuffing,
}
impl UnitLength {
#[must_use]
pub fn name(&self) -> &'static str {
match self {
Self::Total(_) => "total",
Self::NeedMore => "need_more",
Self::Stuffing => "stuffing",
}
}
}
broadcast_core::impl_spec_display!(UnitLength);
pub trait Framing {
fn length(&self, buf: &[u8]) -> UnitLength;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AfterContinuation {
DiscardRest,
ParseRest,
}
impl AfterContinuation {
#[must_use]
pub fn name(&self) -> &'static str {
match self {
Self::DiscardRest => "discard_rest",
Self::ParseRest => "parse_rest",
}
}
}
broadcast_core::impl_spec_display!(AfterContinuation);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PointerCheck {
Authoritative,
MatchRemaining,
}
impl PointerCheck {
#[must_use]
pub fn name(&self) -> &'static str {
match self {
Self::Authoritative => "authoritative",
Self::MatchRemaining => "match_remaining",
}
}
}
broadcast_core::impl_spec_display!(PointerCheck);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Duplicates {
Any,
ContinuationOnly,
}
impl Duplicates {
#[must_use]
pub fn name(&self) -> &'static str {
match self {
Self::Any => "any",
Self::ContinuationOnly => "continuation_only",
}
}
}
broadcast_core::impl_spec_display!(Duplicates);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Continuity {
counter: ContinuityCounter,
discontinuity: bool,
}
impl Continuity {
#[must_use]
pub const fn new(counter: ContinuityCounter, discontinuity: bool) -> Self {
Self {
counter,
discontinuity,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UnitOptions {
after_continuation: AfterContinuation,
pointer_check: PointerCheck,
duplicates: Duplicates,
max_unit_size: NonZeroUsize,
}
impl UnitOptions {
#[must_use]
pub const fn new(
after_continuation: AfterContinuation,
pointer_check: PointerCheck,
duplicates: Duplicates,
max_unit_size: NonZeroUsize,
) -> Self {
Self {
after_continuation,
pointer_check,
duplicates,
max_unit_size,
}
}
}
#[derive(Debug)]
pub struct UnitReassembler<F> {
framing: F,
options: UnitOptions,
buf: BytesMut,
ready: VecDeque<Bytes>,
synced: bool,
last: Option<(ContinuityCounter, Vec<u8>)>,
}
impl<F: Framing> UnitReassembler<F> {
#[must_use]
pub fn new(framing: F, options: UnitOptions) -> Self {
Self {
framing,
options,
buf: BytesMut::new(),
ready: VecDeque::new(),
synced: false,
last: None,
}
}
pub fn feed(&mut self, payload: &[u8], pusi: bool, continuity: Option<Continuity>) -> Fed {
match continuity {
Some(c) => {
let duplicate = !c.discontinuity
&& self
.last
.as_ref()
.is_some_and(|(counter, bytes)| *counter == c.counter && bytes == payload);
self.last = Some((c.counter, payload.to_vec()));
if duplicate && (!pusi || self.options.duplicates == Duplicates::Any) {
return Fed::Duplicate;
}
}
None => self.last = None,
}
if pusi {
self.feed_start(payload);
} else {
self.feed_continuation(payload);
}
Fed::Accepted
}
fn feed_start(&mut self, payload: &[u8]) {
let Some((&pointer, rest)) = payload.split_first() else {
self.buf.clear();
self.synced = false;
return;
};
let pointer = usize::from(pointer);
if self.synced && !self.buf.is_empty() && pointer > 0 {
let consistent = match self.options.pointer_check {
PointerCheck::Authoritative => true,
PointerCheck::MatchRemaining => match self.framing.length(&self.buf) {
UnitLength::Total(total) => {
let remaining = total.saturating_sub(self.buf.len());
remaining == 0 || remaining == pointer
}
_ => true,
},
};
if !consistent {
self.buf.clear();
} else {
let tail = pointer.min(rest.len());
if self.buf.len() + tail > self.options.max_unit_size.get() {
self.buf.clear();
} else {
self.buf.extend_from_slice(&rest[..tail]);
self.drain();
}
}
}
self.buf.clear();
if pointer > rest.len() {
self.synced = false;
return;
}
self.synced = true;
let fresh = &rest[pointer..];
if fresh.len() > self.options.max_unit_size.get() {
self.synced = false;
return;
}
self.buf.extend_from_slice(fresh);
self.drain();
}
fn feed_continuation(&mut self, payload: &[u8]) {
if !self.synced
|| (self.buf.is_empty()
&& self.options.after_continuation == AfterContinuation::DiscardRest)
{
return;
}
let max = self.options.max_unit_size.get();
let take = match self.options.after_continuation {
AfterContinuation::ParseRest => payload.len(),
AfterContinuation::DiscardRest => match self.framing.length(&self.buf) {
UnitLength::Total(total) => total.saturating_sub(self.buf.len()),
_ => max.saturating_sub(self.buf.len()),
}
.min(payload.len()),
};
if self.buf.len() + take > max {
self.buf.clear();
self.synced = false;
return;
}
self.buf.extend_from_slice(&payload[..take]);
self.drain();
}
fn drain(&mut self) {
let max = self.options.max_unit_size.get();
while !self.buf.is_empty() {
match self.framing.length(&self.buf) {
UnitLength::NeedMore => break,
UnitLength::Stuffing => {
self.buf.clear();
break;
}
UnitLength::Total(total) => {
if total == 0 || total > max {
self.buf.clear();
self.synced = false;
break;
}
if self.buf.len() < total {
break;
}
let unit = self.buf.split_to(total).freeze();
self.ready.push_back(unit);
}
}
}
}
pub fn pop(&mut self) -> Option<Bytes> {
self.ready.pop_front()
}
#[must_use]
pub fn len(&self) -> usize {
self.buf.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.buf.is_empty()
}
#[must_use]
pub fn is_synced(&self) -> bool {
self.synced
}
pub fn reset(&mut self) {
self.buf.clear();
self.synced = false;
}
pub fn take_buffered(&mut self) -> Bytes {
self.buf.split().freeze()
}
pub fn drop_buffered(&mut self) {
self.buf.clear();
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
struct Lengthed;
impl Framing for Lengthed {
fn length(&self, buf: &[u8]) -> UnitLength {
match buf[0] {
0xFF => UnitLength::Stuffing,
n => UnitLength::Total(usize::from(n) + 1),
}
}
}
fn reasm(after: AfterContinuation, check: PointerCheck) -> UnitReassembler<Lengthed> {
UnitReassembler::new(
Lengthed,
UnitOptions::new(
after,
check,
Duplicates::Any,
NonZeroUsize::MIN.saturating_add(63),
),
)
}
fn cc(v: u8) -> Option<Continuity> {
Some(Continuity::new(
ContinuityCounter::try_new(v).expect("4-bit counter"),
false,
))
}
fn drain(r: &mut UnitReassembler<Lengthed>) -> Vec<Vec<u8>> {
core::iter::from_fn(|| r.pop())
.map(|b| b.to_vec())
.collect()
}
#[test]
fn nothing_is_accepted_before_the_first_pusi() {
let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
r.feed(&[2, 1, 2], false, None);
assert!(drain(&mut r).is_empty());
r.feed(&[0, 2, 1, 2], true, None);
assert_eq!(drain(&mut r), [[2, 1, 2]]);
}
#[test]
fn a_legal_duplicate_continuation_is_discarded_once() {
for after in [AfterContinuation::DiscardRest, AfterContinuation::ParseRest] {
let mut r = reasm(after, PointerCheck::Authoritative);
r.feed(&[0, 8, 1, 2], true, cc(0));
r.feed(&[3, 4], false, cc(1));
let repeat = r.feed(&[3, 4], false, cc(1));
assert_eq!(repeat, Fed::Duplicate);
r.feed(&[5, 6, 7, 8], false, cc(2));
assert_eq!(drain(&mut r), [[8, 1, 2, 3, 4, 5, 6, 7, 8]], "{after}");
}
}
#[test]
fn a_repeated_counter_with_different_bytes_is_not_a_duplicate() {
let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
r.feed(&[0, 4, 1], true, cc(0));
r.feed(&[2], false, cc(1));
r.feed(&[3, 4], false, cc(1));
assert_eq!(drain(&mut r), [[4, 1, 2, 3, 4]]);
}
#[test]
fn a_discontinuity_makes_a_repeated_counter_legal_new_data() {
let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
r.feed(&[0, 3, 1], true, cc(0));
let flagged = Some(Continuity::new(
ContinuityCounter::try_new(0).expect("4-bit counter"),
true,
));
r.feed(&[1], false, flagged);
assert!(drain(&mut r).is_empty());
assert_eq!(r.len(), 3);
}
#[test]
fn stuffing_after_a_unit_ends_the_payload() {
let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
r.feed(&[0, 1, 9, 0xFF, 0xFF, 0xFF], true, None);
assert_eq!(drain(&mut r), [[1, 9]]);
assert!(r.is_empty());
}
#[test]
fn the_pointer_tail_completes_the_unit_in_progress_before_new_units_start() {
let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
r.feed(&[0, 3, 1], true, None);
r.feed(&[2, 2, 3, 1, 7], true, None);
assert_eq!(drain(&mut r), [vec![3, 1, 2, 3], vec![1, 7]]);
}
#[test]
fn match_remaining_discards_a_partial_unit_whose_pointer_disagrees() {
let mut strict = reasm(AfterContinuation::DiscardRest, PointerCheck::MatchRemaining);
strict.feed(&[0, 5, 1], true, None);
strict.feed(&[1, 2, 1, 8], true, None);
assert_eq!(drain(&mut strict), [[1, 8]], "the partial unit is dropped");
let mut lax = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
lax.feed(&[0, 5, 1], true, None);
lax.feed(&[1, 2, 1, 8], true, None);
assert_eq!(
drain(&mut lax),
[[1, 8]],
"an incomplete tail is dropped too"
);
let mut agrees = reasm(AfterContinuation::DiscardRest, PointerCheck::MatchRemaining);
agrees.feed(&[0, 5, 1], true, None);
agrees.feed(&[4, 2, 3, 4, 5, 1, 8], true, None);
assert_eq!(drain(&mut agrees), [vec![5, 1, 2, 3, 4, 5], vec![1, 8]]);
}
#[test]
fn units_after_a_continuation_end_follow_the_option() {
let mut discard = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
discard.feed(&[0, 3, 1], true, None);
discard.feed(&[2, 3, 1, 9], false, None);
assert_eq!(drain(&mut discard), [[3, 1, 2, 3]]);
let mut parse = reasm(AfterContinuation::ParseRest, PointerCheck::Authoritative);
parse.feed(&[0, 3, 1], true, None);
parse.feed(&[2, 3, 1, 9], false, None);
assert_eq!(drain(&mut parse), [vec![3, 1, 2, 3], vec![1, 9]]);
parse.feed(&[1, 4], false, None);
assert_eq!(
drain(&mut parse),
[[1, 4]],
"a unit may start in a continuation"
);
discard.feed(&[1, 4], false, None);
assert!(drain(&mut discard).is_empty());
}
#[test]
fn a_pointer_past_the_payload_drops_sync_and_a_unit_over_the_cap_is_refused() {
let mut r = reasm(AfterContinuation::DiscardRest, PointerCheck::Authoritative);
r.feed(&[9, 1], true, None);
assert!(!r.is_synced());
r.feed(&[0, 200, 1], true, None);
assert!(drain(&mut r).is_empty());
assert!(!r.is_synced());
}
}