expression

Length-prefixed binary frames

The default length codec uses a four-byte big-endian size followed by payload bytes. Partial data remains buffered until a complete frame can be returned. Always define an explicit maximum for a real protocol. Tokio is an external dependency; see the proposed Cargo manifest. Expected stdout (not executed): true ABC Common mistake: Assuming a header guarantees the payload has already arrived.

Formal Syntax & Structure

rust syntaxrust
LengthDelimitedCodec::new(); Decoder::decode

Working Example

Example Snippetrust
fn main() {    use bytes::BytesMut;    use tokio_util::codec::{Decoder, LengthDelimitedCodec};    let mut c = LengthDelimitedCodec::builder().max_frame_length(16).new_codec();    let mut b = BytesMut::from(&[0, 0, 0, 3, 65][..]);    println!("{}", c.decode(&mut b).unwrap().is_none());    b.extend_from_slice(b"BC");    let frame = c.decode(&mut b).unwrap().unwrap();    println!("{}", std::str::from_utf8(&frame).unwrap());}
Rust Reference