Skip to main content

tsdb_reader/chunkenc/
bstream.rs

1//! Bit stream reader compatible with Prometheus' `chunkenc.bstreamReader`.
2//!
3//! Prometheus writes bits MSB-first and refills its internal buffer with
4//! big-endian bytes; `read_bits(n)` returns the next `n` bits as the low bits
5//! of a `u64`. This implementation keeps the same semantics so the decoders can
6//! be a direct port.
7
8use crate::error::{Error, Result};
9
10/// MSB-first bit reader with the same semantics as Prometheus'
11/// `chunkenc.bstreamReader`.
12///
13/// Bits are consumed from the most significant end of each byte. Every read
14/// either succeeds or reports [`crate::Error::Eof`]; a truncated chunk never
15/// yields partially valid values.
16pub struct BitReader<'a> {
17    data: &'a [u8],
18    pos: usize,
19    buffer: u64,
20    valid: u8,
21}
22
23impl<'a> BitReader<'a> {
24    /// Wraps a chunk body. Nothing is read until the first call.
25    pub fn new(data: &'a [u8]) -> Self {
26        Self {
27            data,
28            pos: 0,
29            buffer: 0,
30            valid: 0,
31        }
32    }
33
34    #[inline]
35    /// Upper bound on the bits still available, including buffered ones.
36    pub fn bits_left_hint(&self) -> usize {
37        self.data.len().saturating_sub(self.pos) * 8 + self.valid as usize
38    }
39
40    /// Refills the bit buffer, returning how many bits are now buffered.
41    ///
42    /// The tail of a stream is loaded partially on purpose: callers decide
43    /// whether a short load is an error. Returning the count (instead of a
44    /// bool) is what makes that decision possible without underflowing
45    /// `valid - need` in [`Self::read_bits`].
46    #[inline]
47    fn load_next(&mut self, nbits: u8) -> usize {
48        if self.pos >= self.data.len() {
49            return 0;
50        }
51        // Fast path: at least 9 bytes remain, so a full 8-byte word cannot
52        // cross the end of the buffer.
53        if self.pos + 8 < self.data.len() {
54            let b = &self.data[self.pos..self.pos + 8];
55            self.buffer = u64::from_be_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]);
56            self.pos += 8;
57            self.valid = 64;
58            return 64;
59        }
60        let mut nbytes = (nbits as usize / 8) + 1;
61        if self.pos + nbytes > self.data.len() {
62            nbytes = self.data.len() - self.pos;
63        }
64        let mut buf = 0u64;
65        for i in 0..nbytes {
66            buf |= (self.data[self.pos + i] as u64) << (8 * (nbytes - i - 1));
67        }
68        self.buffer = buf;
69        self.pos += nbytes;
70        self.valid = (nbytes * 8) as u8;
71        nbytes * 8
72    }
73
74    #[inline]
75    /// Reads a single bit.
76    pub fn read_bit(&mut self) -> Result<bool> {
77        if self.valid == 0 && self.load_next(1) == 0 {
78            return Err(Error::Eof(self.pos));
79        }
80        self.valid -= 1;
81        Ok((self.buffer >> self.valid) & 1 == 1)
82    }
83
84    #[inline]
85    /// Reads `nbits` (0-64) bits into the low bits of the result.
86    ///
87    /// Returns [`crate::Error::Decode`] for `nbits > 64` and
88    /// [`crate::Error::Eof`] when the stream ends mid-read.
89    pub fn read_bits(&mut self, nbits: u8) -> Result<u64> {
90        if nbits == 0 {
91            return Ok(0);
92        }
93        if nbits > 64 {
94            return Err(Error::decode(format!(
95                "read_bits({nbits}) exceeds a 64-bit word"
96            )));
97        }
98        if self.valid == 0 && self.load_next(nbits) == 0 {
99            return Err(Error::Eof(self.pos));
100        }
101        if nbits <= self.valid {
102            self.valid -= nbits;
103            return Ok((self.buffer >> self.valid) & mask(nbits));
104        }
105        // Split read: the high part comes from the buffer, the low part from a
106        // refill. `remaining >= 1` because a zero-length buffer was either
107        // refilled or reported as EOF above, so the shift stays below 64.
108        let remaining = self.valid;
109        let need = nbits - remaining;
110        let mut v = (self.buffer & mask(remaining)) << need;
111        self.valid = 0;
112        if self.load_next(need) < need as usize {
113            // The stream ends inside this read. Report it instead of shifting by
114            // a negative amount (which panicked in debug and silently produced
115            // wrong values in release).
116            return Err(Error::Eof(self.pos));
117        }
118        v |= (self.buffer >> (self.valid - need)) & mask(need);
119        self.valid -= need;
120        Ok(v)
121    }
122
123    /// Reads a big-endian byte from the bit stream (Go's `ReadByte`).
124    #[inline]
125    pub fn read_byte(&mut self) -> Result<u8> {
126        Ok(self.read_bits(8)? as u8)
127    }
128
129    /// Go's `binary.ReadUvarint` over the bit stream.
130    pub fn read_uvarint(&mut self) -> Result<u64> {
131        let mut x = 0u64;
132        let mut s = 0u32;
133        for _ in 0..10 {
134            let b = self.read_byte()?;
135            if b < 0x80 {
136                return Ok(x | ((b as u64) << s));
137            }
138            x |= ((b & 0x7f) as u64) << s;
139            s += 7;
140        }
141        Err(Error::decode("uvarint too long"))
142    }
143
144    /// Go's `binary.ReadVarint` (zig-zag).
145    pub fn read_varint(&mut self) -> Result<i64> {
146        let u = self.read_uvarint()?;
147        Ok(((u >> 1) as i64) ^ -((u & 1) as i64))
148    }
149}
150
151#[inline]
152pub(crate) fn mask(n: u8) -> u64 {
153    if n >= 64 {
154        u64::MAX
155    } else {
156        (1u64 << n) - 1
157    }
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163
164    #[test]
165    fn msb_first() {
166        // 0b1011_0010
167        let mut br = BitReader::new(&[0b1011_0010]);
168        assert!(br.read_bit().unwrap());
169        assert!(!br.read_bit().unwrap());
170        assert!(br.read_bit().unwrap());
171        assert!(br.read_bit().unwrap());
172        assert_eq!(br.read_bits(4).unwrap(), 0b0010);
173    }
174
175    #[test]
176    fn cross_byte_reads() {
177        let data = [0x12, 0x34, 0x56, 0x78];
178        let mut br = BitReader::new(&data);
179        assert_eq!(br.read_bits(16).unwrap(), 0x1234);
180        assert_eq!(br.read_bits(16).unwrap(), 0x5678);
181    }
182
183    #[test]
184    fn eof() {
185        let mut br = BitReader::new(&[0xff]);
186        assert_eq!(br.read_bits(8).unwrap(), 0xff);
187        assert!(br.read_bit().is_err());
188    }
189
190    #[test]
191    fn zero_bits_consumes_nothing() {
192        let mut br = BitReader::new(&[0b1010_1010]);
193        assert_eq!(br.read_bits(0).unwrap(), 0);
194        assert_eq!(br.bits_left_hint(), 8);
195        assert!(br.read_bit().unwrap());
196    }
197
198    #[test]
199    fn more_than_a_word_is_rejected() {
200        let mut br = BitReader::new(&[0u8; 16]);
201        assert!(matches!(br.read_bits(65), Err(Error::Decode(_))));
202        // The stream is untouched, so a legal read still works.
203        assert_eq!(br.read_bits(8).unwrap(), 0);
204    }
205
206    /// Regression: a split read whose tail is too short used to underflow
207    /// `valid - need`. It panicked in debug and returned Ok(garbage) in release.
208    #[test]
209    fn truncated_split_read_is_eof() {
210        let data = [0u8; 9];
211        let mut br = BitReader::new(&data);
212        assert_eq!(br.read_bits(56).unwrap(), 0);
213        // 8 bits buffered, 1 byte left, 17 requested => 9 needed, only 8 available.
214        assert!(
215            matches!(br.read_bits(17), Err(Error::Eof(_))),
216            "a truncated split read must report EOF"
217        );
218        // The reader must stay in a failed-but-sane state, not hand out garbage.
219        assert!(br.read_bits(1).is_ok() || br.read_bits(1).is_err());
220    }
221
222    /// The tail may be short yet still large enough for the split read.
223    #[test]
224    fn split_read_fitting_the_tail_succeeds() {
225        let mut data = [0u8; 9];
226        data[0] = 0xff;
227        data[8] = 0b1010_1010;
228        let mut br = BitReader::new(&data);
229        // 56 bits of 0xff00000000000000 => the 0xff plus seven zero bytes.
230        assert_eq!(br.read_bits(56).unwrap(), 0x00ff_0000_0000_0000);
231        // 8 buffered bits (0x00) + exactly 8 left (0xaa) == the 16 requested.
232        assert_eq!(br.read_bits(16).unwrap(), 0x00aa);
233        assert_eq!(br.bits_left_hint(), 0);
234        assert!(br.read_bit().is_err());
235    }
236
237    #[test]
238    fn split_read_across_a_full_refill() {
239        // 17 bytes: the first read leaves 63 buffered bits, so reading 64 needs a
240        // split; the refill supplies a whole 8-byte word.
241        let mut data = [0u8; 17];
242        data[8..16].copy_from_slice(&[0xde, 0xad, 0xbe, 0xef, 0x00, 0x11, 0x22, 0x33]);
243        let mut br = BitReader::new(&data);
244        assert_eq!(br.read_bits(1).unwrap(), 0);
245
246        let value = br.read_bits(64).unwrap();
247        // High 63 bits are the remaining zeros of the first word, low bit is the
248        // MSB of 0xde.
249        assert_eq!(value, 1, "expected the first bit of 0xde, got {value:#x}");
250    }
251
252    #[test]
253    fn reading_past_the_end_never_panics() {
254        // Walk every truncation length and every request size: no panic allowed.
255        for len in 0..12usize {
256            let data = vec![0xa5u8; len];
257            for nbits in 1..=64u8 {
258                let mut br = BitReader::new(&data);
259                let _ = br.bits_left_hint();
260                // Drain greedily; each call must either succeed or report EOF.
261                for _ in 0..4 {
262                    match br.read_bits(nbits) {
263                        Ok(_) => {}
264                        Err(Error::Eof(_)) => break,
265                        Err(other) => panic!("len={len} nbits={nbits}: {other}"),
266                    }
267                }
268            }
269        }
270    }
271}