Skip to main content

bytepeel_core/
varint.rs

1//! LEB128 varints as used by protobuf.
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum VarintError {
5    /// The buffer ended before a byte without the continuation bit.
6    Truncated,
7    /// More than 64 bits of payload (10th byte > 0x01, or an 11th byte).
8    Overflow,
9}
10
11/// Decode a varint from the start of `buf`. Returns `(value, encoded_len)`.
12pub fn decode(buf: &[u8]) -> Result<(u64, usize), VarintError> {
13    let mut value: u64 = 0;
14    for i in 0..10 {
15        let Some(&b) = buf.get(i) else {
16            return Err(VarintError::Truncated);
17        };
18        if i == 9 && b > 1 {
19            return Err(VarintError::Overflow);
20        }
21        value |= u64::from(b & 0x7f) << (7 * i);
22        if b & 0x80 == 0 {
23            return Ok((value, i + 1));
24        }
25    }
26    Err(VarintError::Overflow)
27}
28
29/// Encode `value` as a varint.
30pub fn encode(mut value: u64) -> Vec<u8> {
31    let mut out = Vec::with_capacity(10);
32    loop {
33        let b = (value & 0x7f) as u8;
34        value >>= 7;
35        if value == 0 {
36            out.push(b);
37            return out;
38        }
39        out.push(b | 0x80);
40    }
41}
42
43/// ZigZag-decode (protobuf `sint32`/`sint64`).
44pub fn zigzag(n: u64) -> i64 {
45    ((n >> 1) as i64) ^ -((n & 1) as i64)
46}