expression

Encode a binary length prefix

A length-prefixed encoder writes both the header and payload. The wire format must be agreed between peers, including byte order and size-field width. Tokio is an external dependency; see the proposed Cargo manifest. Expected stdout (not executed): [0, 0, 0, 2, 104, 105] Common mistake: Using native-endian integer bytes in a protocol that expects big-endian lengths.

Formal Syntax & Structure

rust syntaxrust
LengthDelimitedCodec; Encoder<Bytes>

Working Example

Example Snippetrust
fn main() {    use bytes::{Bytes, BytesMut};    use tokio_util::codec::{Encoder, LengthDelimitedCodec};    let mut c = LengthDelimitedCodec::builder().max_frame_length(16).new_codec();    let mut b = BytesMut::new();    c.encode(Bytes::from_static(b"hi"), &mut b).unwrap();    println!("{:?}", &b[..]);}
Rust Reference