use std::{collections::HashMap, time::Instant};
use bytes::{Bytes, BytesMut};
pub const MAX_FRAGMENTS: usize = u16::MAX as usize;
struct Assembly {
total: u16,
received: u16,
pieces: Vec<Option<Bytes>>,
started_at: Instant,
}
pub struct FragAssembler {
in_flight: HashMap<u32, Assembly>,
}
impl FragAssembler {
#[must_use]
pub fn new() -> Self {
Self {
in_flight: HashMap::new(),
}
}
#[must_use]
pub fn insert(
&mut self,
msg_id: u32,
frag_idx: u16,
frag_total: u16,
payload: Bytes,
) -> Option<Bytes> {
let assembly = self.in_flight.entry(msg_id).or_insert_with(|| Assembly {
total: frag_total,
received: 0,
pieces: vec![None; frag_total as usize],
started_at: Instant::now(),
});
if assembly.pieces[frag_idx as usize]
.replace(payload)
.is_none()
{
assembly.received += 1;
}
if assembly.received < assembly.total {
return None;
}
let assembly = self.in_flight.remove(&msg_id)?;
let total_bytes: usize = assembly.pieces.iter().flatten().map(Bytes::len).sum();
let mut out = BytesMut::with_capacity(total_bytes);
for piece in assembly.pieces.into_iter().flatten() {
out.extend_from_slice(&piece);
}
Some(out.freeze())
}
pub fn prune(&mut self, max_age: std::time::Duration) {
let cutoff = Instant::now()
.checked_sub(max_age)
.unwrap_or(Instant::now());
self.in_flight.retain(|_, a| a.started_at > cutoff);
}
}
pub fn fragment(data: &Bytes, mtu: usize) -> Result<Vec<Bytes>, crate::Error> {
let total = data.len().div_ceil(mtu);
if total > MAX_FRAGMENTS {
return Err(crate::Error::MessageTooLarge {
got: total,
max: MAX_FRAGMENTS,
});
}
let chunks = (0..total)
.map(|i| data.slice(i * mtu..((i + 1) * mtu).min(data.len())))
.collect();
Ok(chunks)
}