Message Framing — length-prefix (Rust)
Topics: stream framing, length-prefix protocol, partial reads
Problem
TCP is a byte stream, not a message stream: one read can return several messages, half a message, or
even half of a message's header. Implement length-prefixed framing so a stream of bytes can be
split back into discrete messages.
Each frame is a 4-byte big-endian length followed by that many payload bytes.
pub fn encode(payload: &[u8]) -> Vec<u8>;
pub struct Decoder { /* … */ }
impl Decoder {
pub fn new() -> Self;
pub fn push(&mut self, data: &[u8]) -> Vec<Vec<u8>>;
}
encode prefixes the payload with its length.
push feeds an arbitrary chunk into the decoder and returns every frame that is now complete,
in order. Incomplete trailing bytes are buffered for the next push. It must handle:
- several frames in one chunk,
- a payload split across chunks,
- a header (the 4 length bytes) split across chunks,
- empty frames (length 0).
push(encode(b"a") + encode(b"bb")) → ["a", "bb"]
push(half) → [] ; push(rest) → ["whole"]
Key concepts
- Buffer until complete: keep leftover bytes; only emit a frame once both its 4-byte header and
full payload have arrived, then
drain the consumed prefix.
u32::from_be_bytes / to_be_bytes for the length prefix.
Grading
Your solution.rs is compiled together with a trusted tests.rs (which include!s it) using
rustc --test. Only solution.rs is yours to edit.
Sign in to submit your solution.