Skip to main content

tsdb_reader/
varint.rs

1//! Go-compatible varint decoding (binary.PutUvarint / PutVarint).
2//!
3//! Prometheus uses Go's unsigned LEB128 and zig-zag signed varints in both the
4//! index format and chunk bit streams. Error behaviour follows Go's
5//! `binary.Uvarint`: overflow and truncation are reported separately.
6
7use crate::error::{Error, Result};
8
9/// Maximum bytes a 64-bit varint can occupy.
10pub const MAX_VARINT_LEN: usize = 10;
11
12/// Reads an unsigned LEB128 varint, advancing `pos`.
13pub fn uvarint(buf: &[u8], pos: &mut usize) -> Result<u64> {
14    let start = *pos;
15    let mut x: u64 = 0;
16    let mut s: u32 = 0;
17    for i in 0..MAX_VARINT_LEN {
18        let b = *buf.get(*pos).ok_or(Error::Eof(start))?;
19        *pos += 1;
20        if b < 0x80 {
21            if i == 9 && b > 1 {
22                return Err(Error::format("uvarint overflows 64 bits"));
23            }
24            return Ok(x | ((b as u64) << s));
25        }
26        x |= ((b & 0x7f) as u64) << s;
27        s += 7;
28    }
29    Err(Error::format("uvarint too long"))
30}
31
32/// Reads a zig-zag encoded signed varint, advancing `pos`.
33pub fn varint(buf: &[u8], pos: &mut usize) -> Result<i64> {
34    let u = uvarint(buf, pos)?;
35    Ok(((u >> 1) as i64) ^ -((u & 1) as i64))
36}
37
38/// Reads a varint without advancing `pos`, returning (value, next_pos).
39pub fn peek_uvarint(buf: &[u8], pos: usize) -> Result<(u64, usize)> {
40    let mut p = pos;
41    let v = uvarint(buf, &mut p)?;
42    Ok((v, p))
43}
44
45/// Upper bound for a 32-bit length field (used by index sections).
46pub fn uvarint32(buf: &[u8], pos: &mut usize) -> Result<u32> {
47    let v = uvarint(buf, pos)?;
48    u32::try_from(v).map_err(|_| Error::format(format!("uvarint {v} does not fit in u32")))
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    #[test]
56    fn roundtrip_examples() {
57        let cases: &[(&[u8], u64)] = &[
58            (&[0x00], 0),
59            (&[0x01], 1),
60            (&[0x7f], 127),
61            (&[0x80, 0x01], 128),
62            (&[0xff, 0x01], 255),
63            (&[0xac, 0x02], 300),
64            (&[0x80, 0x80, 0x80, 0x80, 0x10], 1 << 32),
65        ];
66        for (bytes, want) in cases {
67            let mut pos = 0;
68            assert_eq!(uvarint(bytes, &mut pos).unwrap(), *want);
69            assert_eq!(pos, bytes.len());
70        }
71    }
72
73    #[test]
74    fn zigzag() {
75        for (bytes, want) in [
76            (&[0x00u8][..], 0i64),
77            (&[0x01][..], -1),
78            (&[0x02][..], 1),
79            (&[0x03][..], -2),
80            (&[0x04][..], 2),
81        ] {
82            let mut pos = 0;
83            assert_eq!(varint(bytes, &mut pos).unwrap(), want);
84        }
85    }
86
87    #[test]
88    fn truncated_is_error() {
89        let mut pos = 0;
90        assert!(matches!(uvarint(&[0x80], &mut pos), Err(Error::Eof(0))));
91    }
92}