expression
Protocol Buffers: unsigned varint encoding
Unsigned varints write seven payload bits per byte, lowest group first. The high bit signals continuation. This small encoder handles u64 values only and is for learning; use a maintained library for real messages. Expected stdout (not executed): 0: [0] 127: [127] 128: [128, 1] 300: [172, 2] Common mistake: Assuming a varint is always one byte or using this unsigned encoder directly for signed types.
Formal Syntax & Structure
rust syntaxrust
while value >= 128 { ... }Working Example
Example Snippetrust
fn main() { fn encode(mut value: u64) -> Vec<u8> { let mut bytes = Vec::new(); while value >= 128 { bytes.push(((value & 0x7f) as u8) | 0x80); value >>= 7; } bytes.push(value as u8); bytes } for value in [0, 127, 128, 300] { println!("{value}: {:?}", encode(value)); }}