forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

bits.rs75 lines, 2.1 KiBHistoryRawDownload
1//! MSB-first bit reader over a byte slice with a 64-bit cache. Reads past the
2//! end return zeros, like the zero padding the reference decoder relies on.
3
4pub(crate) struct BitReader<'a> {
5 data: &'a [u8],
6 /// Next byte to load into the cache.
7 pos: usize,
8 /// Bits `[63 .. 64 - bits]` of `cache` are valid and next in the stream.
9 cache: u64,
10 bits: u32,
11}
12
13impl<'a> BitReader<'a> {
14 pub fn new(data: &'a [u8]) -> Self {
15 let mut r = BitReader { data, pos: 0, cache: 0, bits: 0 };
16 r.refill();
17 r
18 }
19
20 /// Make at least 56 bits available.
21 #[inline(always)]
22 pub fn refill(&mut self) {
23 if let Some(s) = self.data.get(self.pos..self.pos + 8) {
24 let v = u64::from_be_bytes(s.try_into().unwrap());
25 self.cache |= v >> self.bits;
26 let take = (63 - self.bits) >> 3;
27 self.pos += take as usize;
28 self.bits += take * 8;
29 } else {
30 self.refill_slow();
31 }
32 }
33
34 #[cold]
35 fn refill_slow(&mut self) {
36 while self.bits <= 56 {
37 let b = self.data.get(self.pos).copied().unwrap_or(0);
38 self.cache |= u64::from(b) << (56 - self.bits);
39 self.pos += 1;
40 self.bits += 8;
41 }
42 }
43
44 /// Peek `n` (1..=32) bits; the caller has refilled.
45 #[inline(always)]
46 pub fn peek(&self, n: u32) -> u32 {
47 (self.cache >> (64 - n)) as u32
48 }
49
50 /// Peek all 32 upper bits.
51 #[inline(always)]
52 pub fn peek32(&self) -> u32 {
53 (self.cache >> 32) as u32
54 }
55
56 #[inline(always)]
57 pub fn skip(&mut self, n: u32) {
58 self.cache <<= n;
59 self.bits -= n;
60 }
61
62 /// Read `n` (1..=32) bits; the caller has refilled.
63 #[inline(always)]
64 pub fn get(&mut self, n: u32) -> u32 {
65 let v = self.peek(n);
66 self.skip(n);
67 v
68 }
69
70 /// True when the cursor has moved beyond the data.
71 pub fn overrun(&self) -> bool {
72 // Bits consumed = loaded - still cached.
73 (self.pos as u64) * 8 - u64::from(self.bits) > self.data.len() as u64 * 8
74 }
75}