expression

Bounded length-prefixed TCP frame

Define an application record as a two-byte big-endian size followed by exactly that many bytes. Validate the size before allocating. A short header or payload is an error. This in-memory fixture tests framing logic, not the network stack. Expected stdout (not executed): cat true true Common mistake: Allocating a payload directly from an unchecked remote length field.

Formal Syntax & Structure

rust syntaxrust
read_exact(header); validate length; read_exact(payload)

Working Example

Example Snippetrust
fn main() {    use std::io::{self, Read, Cursor};    fn frame(mut r: impl Read) -> io::Result<Vec<u8>> {        let mut header = [0; 2];        r.read_exact(&mut header)?;        let n = usize::from(u16::from_be_bytes(header));        if n > 16 { return Err(io::Error::new(io::ErrorKind::InvalidData, "too large")); }        let mut out = vec![0; n];        r.read_exact(&mut out)?;        Ok(out)    }    println!("{}", String::from_utf8(frame(Cursor::new(b"\0\x03cat")).unwrap()).unwrap());    println!("{}", frame(Cursor::new(b"\0\x03ca")).is_err());    println!("{}", frame(Cursor::new(b"\0\x11")).is_err());}
Rust Reference