Skip to main content

quic_parser/
varint.rs

1/* src/varint.rs */
2
3use crate::error::Error;
4
5/// Decode a QUIC variable-length integer from the start of `buf`.
6///
7/// Returns the decoded value and the number of bytes consumed (1, 2, 4, or 8).
8/// The encoding is defined in RFC 9000 Section 16.
9///
10/// # Errors
11///
12/// Returns [`Error::InvalidVarint`] when `buf` is empty or too short for the
13/// indicated encoding length.
14#[must_use = "returns the decoded value without modifying the buffer"]
15pub fn read_varint(buf: &[u8]) -> Result<(u64, usize), Error> {
16	let &first = buf.first().ok_or(Error::InvalidVarint)?;
17	let prefix = first >> 6;
18	let len = 1usize << prefix;
19
20	if buf.len() < len {
21		return Err(Error::InvalidVarint);
22	}
23
24	let mut val = u64::from(first & 0x3f);
25	for &b in &buf[1..len] {
26		val = (val << 8) | u64::from(b);
27	}
28	Ok((val, len))
29}