expression

Protocol Buffers: length-delimited string field

A string is encoded with a length-delimited tag, byte length, and UTF-8 payload. This example constructs field 2 with a short string whose length fits in one varint byte. Larger lengths need a complete varint encoder. Expected stdout (not executed): characters: 4 bytes: 8 prefix: [18, 8] Common mistake: Using character count instead of UTF-8 byte length.

Formal Syntax & Structure

rust syntaxrust
tag + varint(byte_length) + UTF-8 bytes

Working Example

Example Snippetrust
fn main() {    let text = "سلام";    let data = text.as_bytes();    assert!(data.len() < 128);    let mut wire = vec![0x12, data.len() as u8];    wire.extend_from_slice(data);    println!("characters: {}", text.chars().count());    println!("bytes: {}", data.len());    println!("prefix: {:?}", &wire[..2]);}
Rust Reference