openbutler_protocol/frame.rs
1//! Length-limited newline-delimited framing.
2//!
3//! A TCP chunk is not a frame: one chunk may contain many complete messages,
4//! and a message can span chunks. The decoder retains only an owned copy of an
5//! unfinished tail, never a view of a large read (the TypeScript header's
6//! memory rule, mirrored here by `Vec<u8>`'s ownership).
7
8use crate::error::FrameError;
9
10/// Splits a byte stream into newline-delimited frames with a hard cap.
11#[derive(Debug, Default)]
12pub struct FrameDecoder {
13 pending: Vec<u8>,
14 max_frame_bytes: usize,
15}
16
17impl FrameDecoder {
18 /// A decoder whose frames never exceed `max_frame_bytes`.
19 pub fn new(max_frame_bytes: usize) -> Self {
20 Self {
21 pending: Vec::new(),
22 max_frame_bytes,
23 }
24 }
25
26 /// Feeds one received chunk, returning every frame completed by it.
27 ///
28 /// The cap is enforced across all chunks belonging to one frame: a peer
29 /// cannot bypass it by sending a large frame in small pieces. On breach
30 /// the decoder returns [`FrameError::ExceededLimit`] and the caller must
31 /// destroy the connection (both directions, both languages).
32 pub fn append(&mut self, chunk: &[u8]) -> Result<Vec<Vec<u8>>, FrameError> {
33 let mut frames = Vec::new();
34 let mut start = 0;
35 while start < chunk.len() {
36 let Some(rel) = chunk[start..].iter().position(|&b| b == b'\n') else {
37 // No newline: everything left is an unfinished tail.
38 let tail = &chunk[start..];
39 self.push_tail(tail)?;
40 return Ok(frames);
41 };
42 let newline = start + rel;
43 let part = &chunk[start..newline];
44 self.push_tail(part)?;
45 frames.push(std::mem::take(&mut self.pending));
46 start = newline + 1;
47 }
48 Ok(frames)
49 }
50
51 /// Bytes of the frame currently being assembled.
52 pub fn pending_bytes(&self) -> usize {
53 self.pending.len()
54 }
55
56 /// Borrows the unfinished tail so a bounded admission decoder can hand it
57 /// to the regular decoder after the first frame is accepted.
58 pub fn pending(&self) -> &[u8] {
59 &self.pending
60 }
61
62 fn push_tail(&mut self, bytes: &[u8]) -> Result<(), FrameError> {
63 if self.pending.len() + bytes.len() > self.max_frame_bytes {
64 return Err(FrameError::ExceededLimit);
65 }
66 self.pending.extend_from_slice(bytes);
67 Ok(())
68 }
69}