logicaffeine_compile/concurrency/stream.rs
1//! Streaming framing / deframing — process a byte STREAM of length-delimited messages
2//! INCREMENTALLY, as bytes arrive, without ever buffering the whole stream. This is the basis of
3//! every streaming protocol (gRPC, Arrow Flight, Kafka): a producer frames each message as
4//! `[uvarint length][body]`; a consumer feeds arriving chunks — ANY chunking, from byte-at-a-time
5//! to many frames at once to a frame split across chunks — to a [`StreamDeframer`], which hands
6//! back each complete frame the instant it is buffered, ZERO-COPY (the body is a borrowed slice, so
7//! pair it with [`crate::concurrency::marshal::view_message`] for a fully in-place stream read).
8//!
9//! Paired with the zero-copy `WireView` receive, this closes Cap'n Proto's streaming claim:
10//! incremental reads with no whole-stream buffering and no decode of untouched fields.
11
12/// Frame `body` for the stream: a LEB128 length prefix, then the bytes. Append-only into `out`, so
13/// a producer can concatenate many frames into one stream buffer.
14pub fn frame_for_stream(body: &[u8], out: &mut Vec<u8>) {
15 let mut len = body.len() as u64;
16 loop {
17 let mut byte = (len & 0x7f) as u8;
18 len >>= 7;
19 if len != 0 {
20 byte |= 0x80;
21 }
22 out.push(byte);
23 if len == 0 {
24 break;
25 }
26 }
27 out.extend_from_slice(body);
28}
29
30/// An incremental deframer. Feed it arriving bytes with [`push`](Self::push); pull complete frames
31/// with [`drain_frames`](Self::drain_frames). Holds only the bytes not yet delivered (a partial
32/// frame at most), so memory stays bounded regardless of stream length.
33#[derive(Default)]
34pub struct StreamDeframer {
35 buf: Vec<u8>,
36 start: usize,
37}
38
39impl StreamDeframer {
40 pub fn new() -> Self {
41 Self::default()
42 }
43
44 /// Append a newly-arrived chunk (any size, including empty).
45 pub fn push(&mut self, bytes: &[u8]) {
46 self.buf.extend_from_slice(bytes);
47 }
48
49 /// No un-delivered bytes remain (the stream is fully consumed up to a frame boundary).
50 pub fn is_empty(&self) -> bool {
51 self.start >= self.buf.len()
52 }
53
54 /// Bytes buffered but not yet delivered (a partial frame awaiting more input).
55 pub fn pending(&self) -> usize {
56 self.buf.len() - self.start
57 }
58
59 /// Hand every COMPLETE frame currently buffered, in arrival order, to `f` as a borrowed body
60 /// slice (zero-copy). Stops at the first incomplete frame — keeping its partial bytes for the
61 /// next [`push`](Self::push) — then compacts the consumed prefix so the buffer never grows
62 /// unbounded. Returns how many frames were delivered.
63 pub fn drain_frames(&mut self, mut f: impl FnMut(&[u8])) -> usize {
64 let mut count = 0;
65 loop {
66 let Some((len, header)) = read_uvarint(&self.buf[self.start..]) else {
67 break; // length prefix not fully arrived
68 };
69 let body_start = self.start + header;
70 let Some(body_end) = body_start.checked_add(len as usize) else {
71 break;
72 };
73 if body_end > self.buf.len() {
74 break; // body not fully arrived
75 }
76 f(&self.buf[body_start..body_end]);
77 self.start = body_end;
78 count += 1;
79 }
80 if self.start > 0 {
81 self.buf.drain(0..self.start);
82 self.start = 0;
83 }
84 count
85 }
86}
87
88/// LEB128 uvarint from the front of `buf`: `Some((value, bytes_consumed))`, or `None` if the varint
89/// is truncated mid-encoding (wait for more bytes — never a panic, never a misread).
90fn read_uvarint(buf: &[u8]) -> Option<(u64, usize)> {
91 let mut value = 0u64;
92 let mut shift = 0u32;
93 for (i, &b) in buf.iter().enumerate() {
94 value |= u64::from(b & 0x7f) << shift;
95 if b & 0x80 == 0 {
96 return Some((value, i + 1));
97 }
98 shift += 7;
99 if shift >= 64 {
100 return None; // malformed over-long varint — treat as "wait" (fail-closed)
101 }
102 }
103 None
104}
105
106#[cfg(test)]
107#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/concurrency/stream/tests.rs"]
108mod tests;