Skip to main content

decode_varint

Function decode_varint 

Source
pub fn decode_varint(buf: &mut impl Buf) -> Result<u64, DecodeError>
Expand description

Decode a varint from a buffer.

Uses a chunk-based strategy for performance:

  1. Single-byte fast path for values < 128 (common for tags, small lengths).
  2. Unrolled slice decode when the contiguous chunk is large enough.
  3. Byte-at-a-time fallback for non-contiguous or fragmented buffers.

Only the single-byte check is inlinable into callers; paths 2 and 3 run in an out-of-line function that calls buf.chunk() again. That second call is free for &[u8] and Bytes and a real call for Chain, Take and dyn Buf.

§Errors

Returns DecodeError::UnexpectedEof if the buffer ends before the varint’s last byte, and DecodeError::VarintTooLong if the varint is longer than ten bytes or its tenth byte sets bits above bit 63. After an error the position of buf is unspecified.