Skip to main content

count_varints

Function count_varints 

Source
pub fn count_varints(payload: &[u8]) -> usize
Expand description

Count the varints in a packed payload, i.e. the number of bytes whose continuation bit is clear (b < 0x80).

Every varint ends in exactly one such terminator byte, so for a well-formed packed payload this is the exact element count, computed in a single pass. The result is always <= payload.len() — equal only when every value is single-byte — so it never over-counts the way the raw byte length does for multi-byte varints. A truncated final varint (no terminator) makes the result one short, which is harmless when sizing a buffer: it costs at most one extra reallocation, and decoding then errors on the malformed bytes anyway.

Generated decode_view code uses this to size a packed varint field’s backing storage in a single allocation.