oxideav_vp8/bool_decoder.rs
1//! VP8 boolean (range) entropy decoder.
2//!
3//! This module implements the decoder side of the VP8 boolean coder
4//! described in RFC 6386 §7. Essentially the entire VP8 elementary
5//! stream is encoded as a sequence of boolean values processed by this
6//! coder; every higher-level decode step (frame header, macroblock
7//! mode, motion vectors, DCT tokens) is built on top of it.
8//!
9//! The coder is a binary arithmetic decoder. State is just two
10//! 8-bit-domain registers (`range` and `value`) plus a single-bit
11//! shift counter and an input cursor. Decoding one bool requires only
12//! a comparison and an optional renormalisation that shifts new input
13//! bits in 8 at a time.
14//!
15//! See RFC 6386 §7.2 (algorithm description) and §7.3 (reference
16//! C pseudocode) for the authoritative specification.
17//!
18//! # Status
19//!
20//! Foundational primitive only. No frame header / macroblock decode is
21//! wired up against this yet — see the per-method docs and the
22//! crate-level scaffold notes.
23
24use core::fmt;
25
26/// Out-of-band conditions surfaced by [`BoolDecoder`].
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28#[non_exhaustive]
29pub enum BoolDecoderError {
30 /// Initialisation requested but fewer than two bytes of input are
31 /// available. The decoder reads two bytes into `value` during
32 /// `init` (RFC 6386 §7.3 `init_bool_decoder`) and cannot start
33 /// short of that.
34 InputTooShort,
35 /// Renormalisation tried to pull a fresh byte but the input cursor
36 /// has already passed the end of the partition. The spec relies on
37 /// the encoder having appended enough flushed bytes to satisfy any
38 /// reads the decoder issues; we surface this as an explicit error
39 /// rather than silently returning zero bits, so callers can
40 /// distinguish a truncated stream from a legitimate trailing
41 /// boolean.
42 EndOfStream,
43}
44
45impl fmt::Display for BoolDecoderError {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 match self {
48 BoolDecoderError::InputTooShort => {
49 write!(f, "vp8 bool decoder: input shorter than 2 bytes")
50 }
51 BoolDecoderError::EndOfStream => {
52 write!(f, "vp8 bool decoder: read past end of partition")
53 }
54 }
55 }
56}
57
58impl std::error::Error for BoolDecoderError {}
59
60/// VP8 boolean entropy decoder state per RFC 6386 §7.3
61/// (`bool_decoder`).
62///
63/// The decoder owns the input slice for its partition and walks it
64/// from front to back. Eight bits at a time are shifted into the
65/// `value` register during renormalisation; consumers never touch the
66/// underlying bytes directly.
67///
68/// # Invariants
69///
70/// After [`BoolDecoder::init`] returns `Ok(_)` and between any pair of
71/// successful [`BoolDecoder::read_bool`] / [`BoolDecoder::read_literal`]
72/// calls:
73///
74/// * `range` is in `128..=255` (RFC 6386 §7.2);
75/// * `value` is `< (range << 8)` interpreted with the unread tail of
76/// the partition appended on the right.
77#[derive(Debug, Clone)]
78pub struct BoolDecoder<'a> {
79 /// Remaining partition input; the next byte read by
80 /// renormalisation is `input[0]`.
81 input: &'a [u8],
82 /// `range` field of RFC 6386 §7.3 `bool_decoder`. Maintained in
83 /// `128..=255` outside renormalisation. We hold it in `u32` to
84 /// match the reference pseudocode's widening behaviour during
85 /// renormalisation; only the low 8 bits ever carry information.
86 range: u32,
87 /// `value` field of RFC 6386 §7.3 `bool_decoder`. Two-byte window
88 /// over the not-yet-consumed bool stream.
89 value: u32,
90 /// `bit_count` field of RFC 6386 §7.3 `bool_decoder`: the number
91 /// of bits already shifted out of `value` since the last full byte
92 /// was loaded. Range `0..=7`.
93 bit_count: u32,
94}
95
96impl<'a> BoolDecoder<'a> {
97 /// Initialise the decoder from the start of a partition.
98 ///
99 /// Per RFC 6386 §7.3 `init_bool_decoder` the first two bytes of
100 /// the partition are loaded into `value`, `range` starts at 255,
101 /// and the bit-shift counter is zero.
102 pub fn init(input: &'a [u8]) -> Result<Self, BoolDecoderError> {
103 if input.len() < 2 {
104 return Err(BoolDecoderError::InputTooShort);
105 }
106 let first = input[0] as u32;
107 let second = input[1] as u32;
108 let value = (first << 8) | second;
109 Ok(BoolDecoder {
110 input: &input[2..],
111 range: 255,
112 value,
113 bit_count: 0,
114 })
115 }
116
117 /// Initialise the decoder from a possibly-undersized partition.
118 ///
119 /// Mirrors the §20 reference's `init_bool_decoder`, which tolerates
120 /// `sz < 2` by zero-initialising the value register and presenting an
121 /// empty input. Tiny VP8 frames where the DCT partition rounds down
122 /// to a 0- or 1-byte slice can land here: the surrounding macroblock
123 /// layer reads only `mb_skip = 1` flags from this partition, which
124 /// is satisfiable from the `value = 0` initial state.
125 ///
126 /// Callers reading the §19.2 control partition or the §9.1 frame
127 /// header should keep using [`BoolDecoder::init`], which rejects
128 /// truncated input as an error (every valid VP8 frame's control
129 /// partition is at least 2 bytes).
130 pub fn init_partition(input: &'a [u8]) -> Self {
131 if input.len() >= 2 {
132 let first = input[0] as u32;
133 let second = input[1] as u32;
134 let value = (first << 8) | second;
135 BoolDecoder {
136 input: &input[2..],
137 range: 255,
138 value,
139 bit_count: 0,
140 }
141 } else {
142 // §20 reference: tiny partition → value = 0, no buffered input.
143 BoolDecoder {
144 input: &[],
145 range: 255,
146 value: 0,
147 bit_count: 0,
148 }
149 }
150 }
151
152 /// Read one boolean with probability `prob / 256` of being 0.
153 ///
154 /// Returns `Ok(false)` for a coded zero and `Ok(true)` for a coded
155 /// one. `prob` must lie in `1..=255` per the encoder's contract
156 /// (RFC 6386 §7.2); a probability of zero or 256 has no meaning
157 /// because `split` would degenerate.
158 #[inline]
159 pub fn read_bool(&mut self, prob: u8) -> Result<bool, BoolDecoderError> {
160 // split is approximately (range * prob) / 256 and is strictly
161 // greater than 0 and strictly less than range.
162 let split = 1 + (((self.range - 1) * prob as u32) >> 8);
163 // The comparison is between `value` and split << 8 because
164 // `value` lives in the upper byte of the 16-bit interval.
165 let big_split = split << 8;
166
167 let retval = if self.value >= big_split {
168 // Coded a one: subtract the left endpoint of the interval
169 // and reduce range.
170 self.value -= big_split;
171 self.range -= split;
172 true
173 } else {
174 // Coded a zero: reduce range, leave value alone.
175 self.range = split;
176 false
177 };
178
179 // Renormalise: double range/value until range is back in the
180 // 128..=255 band, pulling a fresh input byte whenever we run
181 // out of buffered bits.
182 self.renormalize()?;
183 Ok(retval)
184 }
185
186 /// Read an unsigned `num_bits`-wide literal — `num_bits` flag bits
187 /// at fixed probability 128, MSB first.
188 ///
189 /// Per the RFC 6386 §7.3 `read_literal` convenience function, the
190 /// returned value is the integer assembled left-to-right from the
191 /// individual flag reads. `num_bits` must be in `0..=32`; values
192 /// outside that range are rejected via the `bit_count` field's
193 /// natural width.
194 pub fn read_literal(&mut self, num_bits: u32) -> Result<u32, BoolDecoderError> {
195 debug_assert!(num_bits <= 32, "vp8 read_literal: num_bits must be <= 32");
196
197 // Hot-path specialisation of the §7.3 `read_literal` loop. The
198 // generic path calls `read_bool(128)` `num_bits` times; each call
199 // reloads the `range` / `value` / `bit_count` fields, recomputes the
200 // interval split with a 32-bit multiply (`(range - 1) * 128`), and
201 // re-enters `renormalize`. At the fixed probability 128 the split
202 // collapses to a pure shift — `1 + (((range - 1) * 128) >> 8)` is
203 // exactly `1 + ((range - 1) >> 1)`, an algebraic identity (`* 128 >> 8`
204 // == `>> 1`) — and hoisting the three registers into locals lets the
205 // whole accumulator loop run without touching `self` until the end.
206 // Byte-for-byte identical to the generic loop on every input
207 // (`read_literal_fast_matches_generic_loop`).
208 let mut range = self.range;
209 let mut value = self.value;
210 let mut bit_count = self.bit_count;
211 let mut input = self.input;
212
213 let mut v: u32 = 0;
214 for _ in 0..num_bits {
215 // split = 1 + ((range - 1) >> 1): the prob-128 form of the §7.2
216 // interval split, no multiply.
217 let split = 1 + ((range - 1) >> 1);
218 let big_split = split << 8;
219 let bit = if value >= big_split {
220 value -= big_split;
221 range -= split;
222 1
223 } else {
224 range = split;
225 0
226 };
227 v = (v << 1) | bit;
228
229 // Inline of `renormalize` over the local registers — identical
230 // leading-zeros batched shift + single byte pull.
231 let shift = range.leading_zeros() - 24;
232 if shift != 0 {
233 value <<= shift;
234 range <<= shift;
235 let next_bc = bit_count + shift;
236 if next_bc >= 8 {
237 let (next, rest) = match input.split_first() {
238 Some(pair) => pair,
239 None => {
240 // Commit consumed state before surfacing the
241 // error so the decoder is left exactly where the
242 // generic loop would leave it.
243 self.range = range;
244 self.value = value;
245 self.bit_count = bit_count;
246 self.input = input;
247 return Err(BoolDecoderError::EndOfStream);
248 }
249 };
250 bit_count = next_bc - 8;
251 value |= (*next as u32) << bit_count;
252 input = rest;
253 } else {
254 bit_count = next_bc;
255 }
256 }
257 }
258
259 self.range = range;
260 self.value = value;
261 self.bit_count = bit_count;
262 self.input = input;
263 Ok(v)
264 }
265
266 /// Read a signed `num_bits`-wide literal. A leading sign bit
267 /// (probability 128) is followed by `num_bits - 1` magnitude bits
268 /// when `num_bits > 0`; `num_bits == 0` returns 0. Per the
269 /// reference pseudocode the sign is realised by initialising the
270 /// accumulator to -1 when the sign bit is set.
271 pub fn read_signed_literal(&mut self, num_bits: u32) -> Result<i32, BoolDecoderError> {
272 debug_assert!(
273 num_bits <= 31,
274 "vp8 read_signed_literal: num_bits must be <= 31"
275 );
276 if num_bits == 0 {
277 return Ok(0);
278 }
279 let sign = self.read_bool(128)?;
280 let mut v: i32 = if sign { -1 } else { 0 };
281 for _ in 1..num_bits {
282 let bit = self.read_bool(128)? as i32;
283 v = (v << 1) | bit;
284 }
285 Ok(v)
286 }
287
288 /// Renormalise `range` and `value` until `range >= 128`, pulling
289 /// input bytes as needed.
290 ///
291 /// This is the inner loop of `read_bool` (RFC 6386 §7.3) lifted
292 /// out so it can be reused in `init`-time tests.
293 ///
294 /// The §7.3 listing doubles `range` / `value` one bit at a time
295 /// until `range` is back in `128..=255`. The number of doublings is
296 /// a pure function of `range` (which is in `1..=255` after a
297 /// `read_bool` interval split), so the loop is collapsed here into
298 /// a single shift computed from `range.leading_zeros()`. At most
299 /// one fresh input byte can be needed per renormalisation — the
300 /// shift caps at 7 and `bit_count` is at most 7, so the §7.3
301 /// "shift counter reaches 8" byte pull fires at most once — and it
302 /// lands in `value` at bit offset `bit_count + shift - 8`, exactly
303 /// where the bit-at-a-time listing accumulates it (the byte is
304 /// OR-ed in when the counter wraps, then shifted up by the
305 /// doublings still outstanding). The `EndOfStream` trigger
306 /// condition is unchanged: a byte is required iff
307 /// `bit_count + shift >= 8`. The batched form is bit-exact against
308 /// the §7.3 listing on every decode
309 /// (`batched_renormalize_matches_bit_at_a_time_listing`).
310 #[inline]
311 fn renormalize(&mut self) -> Result<(), BoolDecoderError> {
312 // `range` is in 1..=255 here; bringing it into 128..=255 takes
313 // exactly its leading-zero count above bit 7 (0..=7 doublings).
314 let shift = self.range.leading_zeros() - 24;
315 if shift == 0 {
316 return Ok(());
317 }
318 self.value <<= shift;
319 self.range <<= shift;
320 let bit_count = self.bit_count + shift;
321 if bit_count >= 8 {
322 let (next, rest) = match self.input.split_first() {
323 Some(pair) => pair,
324 None => return Err(BoolDecoderError::EndOfStream),
325 };
326 self.bit_count = bit_count - 8;
327 self.value |= (*next as u32) << self.bit_count;
328 self.input = rest;
329 } else {
330 self.bit_count = bit_count;
331 }
332 Ok(())
333 }
334
335 /// Current `range` register. Exposed for testing / auditing only.
336 pub fn range(&self) -> u32 {
337 self.range
338 }
339
340 /// Current `value` register. Exposed for testing / auditing only.
341 pub fn value(&self) -> u32 {
342 self.value
343 }
344
345 /// Bytes of the partition not yet shifted into `value`.
346 pub fn remaining_input(&self) -> &[u8] {
347 self.input
348 }
349}
350
351#[cfg(test)]
352mod tests {
353 use super::*;
354
355 // A 16-bit boolean encoder used only inside this test module to
356 // produce ground-truth byte sequences. It mirrors the encoder
357 // described in RFC 6386 §7.2: the same "split = 1 + ((range - 1)
358 // * prob) >> 8" arithmetic; the same renormalise-while-range<128
359 // loop. We need an encoder to exercise the decoder against; the
360 // alternative would be hand-rolling expected bytes for every test
361 // case which is much more error-prone.
362 //
363 // This encoder lives ONLY in tests and is NOT exported. The
364 // production codepath here is decode-only.
365 struct TestEncoder {
366 out: Vec<u8>,
367 range: u32,
368 bottom: u32,
369 bit_count: i32,
370 }
371
372 impl TestEncoder {
373 fn new() -> Self {
374 TestEncoder {
375 out: Vec::new(),
376 range: 255,
377 bottom: 0,
378 bit_count: 24,
379 }
380 }
381
382 fn write_bool(&mut self, prob: u8, val: bool) {
383 let split = 1 + (((self.range - 1) * prob as u32) >> 8);
384 if val {
385 self.bottom = self.bottom.wrapping_add(split);
386 self.range -= split;
387 } else {
388 self.range = split;
389 }
390 while self.range < 128 {
391 self.range <<= 1;
392 // Propagate carry into already-written bytes if the
393 // top bit of `bottom` is set. We replicate the
394 // reference encoder's `add_one_to_output` helper here.
395 if (self.bottom >> 31) & 1 == 1 {
396 let mut i = self.out.len();
397 while i > 0 {
398 i -= 1;
399 if self.out[i] == 255 {
400 self.out[i] = 0;
401 } else {
402 self.out[i] = self.out[i].wrapping_add(1);
403 break;
404 }
405 }
406 }
407 self.bottom <<= 1;
408 self.bit_count -= 1;
409 if self.bit_count == 0 {
410 let byte = (self.bottom >> 24) as u8;
411 self.out.push(byte);
412 self.bottom &= (1 << 24) - 1;
413 self.bit_count = 8;
414 }
415 }
416 }
417
418 fn write_literal(&mut self, value: u32, num_bits: u32) {
419 for i in (0..num_bits).rev() {
420 let bit = ((value >> i) & 1) == 1;
421 self.write_bool(128, bit);
422 }
423 }
424
425 fn finish(mut self) -> Vec<u8> {
426 // Flush per RFC 6386 §7.3 `flush_bool_encoder`. Note the
427 // bit_count field is treated as a signed int in the
428 // reference C.
429 let c = self.bit_count;
430 let mut v = self.bottom;
431 if v & (1u32 << (32 - c)) != 0 {
432 let mut i = self.out.len();
433 while i > 0 {
434 i -= 1;
435 if self.out[i] == 255 {
436 self.out[i] = 0;
437 } else {
438 self.out[i] = self.out[i].wrapping_add(1);
439 break;
440 }
441 }
442 }
443 v <<= c & 7;
444 let mut c_shift = c >> 3;
445 while c_shift > 0 {
446 v <<= 8;
447 c_shift -= 1;
448 }
449 for _ in 0..4 {
450 self.out.push((v >> 24) as u8);
451 v <<= 8;
452 }
453 self.out
454 }
455 }
456
457 #[test]
458 fn init_rejects_short_input() {
459 assert_eq!(
460 BoolDecoder::init(&[]).unwrap_err(),
461 BoolDecoderError::InputTooShort
462 );
463 assert_eq!(
464 BoolDecoder::init(&[0xAA]).unwrap_err(),
465 BoolDecoderError::InputTooShort
466 );
467 }
468
469 #[test]
470 fn init_loads_first_two_bytes_into_value() {
471 let d = BoolDecoder::init(&[0xAB, 0xCD, 0x00]).unwrap();
472 // value = (0xAB << 8) | 0xCD = 0xABCD
473 assert_eq!(d.value(), 0xABCD);
474 assert_eq!(d.range(), 255);
475 assert_eq!(d.remaining_input(), &[0x00]);
476 }
477
478 #[test]
479 fn roundtrip_alternating_bits_at_p128() {
480 // Probability 128 means each bit is a coin flip and the
481 // encoder's renormalisation triggers on every write. Good
482 // exercise of the byte-pulling path.
483 let bits = [true, false, true, true, false, false, true, false];
484 let mut enc = TestEncoder::new();
485 for &b in &bits {
486 enc.write_bool(128, b);
487 }
488 let buf = enc.finish();
489 let mut dec = BoolDecoder::init(&buf).unwrap();
490 for &expected in &bits {
491 let got = dec.read_bool(128).unwrap();
492 assert_eq!(got, expected);
493 }
494 }
495
496 #[test]
497 fn roundtrip_biased_probabilities() {
498 // Sweep both extremes of the legal probability range to be
499 // sure the renormalise-many-times-then-renormalise-not-at-all
500 // paths both work.
501 let probs: &[u8] = &[1, 16, 64, 128, 200, 240, 255];
502 let mut enc = TestEncoder::new();
503 // Write a value=true and value=false at every probability.
504 for &p in probs {
505 enc.write_bool(p, false);
506 enc.write_bool(p, true);
507 }
508 let buf = enc.finish();
509 let mut dec = BoolDecoder::init(&buf).unwrap();
510 for &p in probs {
511 assert!(!dec.read_bool(p).unwrap(), "prob={p}");
512 assert!(dec.read_bool(p).unwrap(), "prob={p}");
513 }
514 }
515
516 #[test]
517 fn roundtrip_literal_msb_first() {
518 // A 12-bit literal should round-trip unchanged and the bits
519 // should come out MSB-first per RFC 6386 §7.3.
520 let mut enc = TestEncoder::new();
521 enc.write_literal(0xABC, 12);
522 let buf = enc.finish();
523 let mut dec = BoolDecoder::init(&buf).unwrap();
524 assert_eq!(dec.read_literal(12).unwrap(), 0xABC);
525 }
526
527 #[test]
528 fn signed_literal_zero_width_returns_zero() {
529 // RFC 6386 §7.3 read_signed_literal returns 0 immediately
530 // when num_bits == 0 — no bits are read from the stream.
531 let mut enc = TestEncoder::new();
532 enc.write_bool(128, true); // arbitrary trailing data
533 let buf = enc.finish();
534 let mut dec = BoolDecoder::init(&buf).unwrap();
535 assert_eq!(dec.read_signed_literal(0).unwrap(), 0);
536 // The trailing bool is still available.
537 assert!(dec.read_bool(128).unwrap());
538 }
539
540 #[test]
541 fn signed_literal_roundtrip() {
542 // Encoder side: the spec defines the signed form as "sign bit
543 // then magnitude" but the *decoded* int is the result of
544 // accumulating with v = -1 when the sign is set. So encoding
545 // -3 (5-bit) under that convention is: sign=1 followed by the
546 // four bits that, when accumulated into v=-1 (0xFFFF_FFFF) as
547 // (v << 1) | bit, produce -3. Working backwards from -3 == 0b...11101:
548 // step 0: v=-1 (sign=1)
549 // step 1: v=(v<<1)|b1 = ... so we need bits 1,1,0,1
550 // Encode that bit pattern as the magnitude.
551 let mut enc = TestEncoder::new();
552 enc.write_bool(128, true); // sign
553 enc.write_bool(128, true);
554 enc.write_bool(128, true);
555 enc.write_bool(128, false);
556 enc.write_bool(128, true);
557 let buf = enc.finish();
558 let mut dec = BoolDecoder::init(&buf).unwrap();
559 assert_eq!(dec.read_signed_literal(5).unwrap(), -3);
560 }
561
562 #[test]
563 fn end_of_stream_surfaced() {
564 // Only 2 bytes available. After init, value=0 and range=255.
565 // Reading at prob=1: split = 1 + ((254 * 1) >> 8) = 1, so
566 // value(0) < (split<<8 == 256), retval=0, range=1.
567 // Renormalisation then needs to shift range from 1 up to 128
568 // — seven doublings, each pulling a new bit from value (also
569 // zero) and incrementing bit_count. After 8 increments the
570 // loop tries to load a fresh input byte; with no input left,
571 // we must surface EndOfStream rather than silently reading
572 // garbage.
573 let mut dec = BoolDecoder::init(&[0x00, 0x00]).unwrap();
574 // First read renormalises only as much as the buffered
575 // bit_count allows; it should succeed. The second read forces
576 // a fresh byte pull.
577 let _ = dec.read_bool(1).unwrap();
578 let err = dec.read_bool(1).unwrap_err();
579 assert_eq!(err, BoolDecoderError::EndOfStream);
580 }
581
582 /// Reference §7.3 `read_bool`: the same interval split as the
583 /// production method, but with the renormalisation written as the
584 /// literal bit-at-a-time listing (double `range`/`value`, count
585 /// shifted bits, pull a fresh byte when the counter reaches 8).
586 /// The production `renormalize` collapses that loop into a single
587 /// `leading_zeros`-derived shift; this is the ground truth it must
588 /// match state-for-state.
589 fn read_bool_reference(d: &mut BoolDecoder<'_>, prob: u8) -> Result<bool, BoolDecoderError> {
590 let split = 1 + (((d.range - 1) * prob as u32) >> 8);
591 let big_split = split << 8;
592 let retval = if d.value >= big_split {
593 d.value -= big_split;
594 d.range -= split;
595 true
596 } else {
597 d.range = split;
598 false
599 };
600 while d.range < 128 {
601 d.value <<= 1;
602 d.range <<= 1;
603 d.bit_count += 1;
604 if d.bit_count == 8 {
605 d.bit_count = 0;
606 let (next, rest) = match d.input.split_first() {
607 Some(pair) => pair,
608 None => return Err(BoolDecoderError::EndOfStream),
609 };
610 d.value |= *next as u32;
611 d.input = rest;
612 }
613 }
614 Ok(retval)
615 }
616
617 #[test]
618 fn batched_renormalize_matches_bit_at_a_time_listing() {
619 // Drive the production decoder and the bit-at-a-time reference
620 // in lockstep over a probability sweep that exercises every
621 // renormalisation depth (shift 0 through 7, byte pulls landing
622 // at every bit_count offset) and assert the full decoder state
623 // matches after every read.
624 let mut enc = TestEncoder::new();
625 let mut probs = Vec::new();
626 let mut bits = Vec::new();
627 let mut seed = 0x2545f491u32;
628 for _ in 0..4096 {
629 // xorshift32 — deterministic prob/bit stream.
630 seed ^= seed << 13;
631 seed ^= seed >> 17;
632 seed ^= seed << 5;
633 let p = (seed % 254 + 1) as u8;
634 let b = (seed >> 16) & 1 == 1;
635 probs.push(p);
636 bits.push(b);
637 enc.write_bool(p, b);
638 }
639 let buf = enc.finish();
640 let mut dec = BoolDecoder::init(&buf).unwrap();
641 let mut dec_ref = BoolDecoder::init(&buf).unwrap();
642 for (i, (&p, &expected)) in probs.iter().zip(bits.iter()).enumerate() {
643 let got = dec.read_bool(p).unwrap();
644 let got_ref = read_bool_reference(&mut dec_ref, p).unwrap();
645 assert_eq!(got, expected, "decoded bit {i} (prob {p})");
646 assert_eq!(got, got_ref, "reference disagreement at bit {i}");
647 assert_eq!(dec.range, dec_ref.range, "range diverged at bit {i}");
648 assert_eq!(dec.value, dec_ref.value, "value diverged at bit {i}");
649 assert_eq!(
650 dec.bit_count, dec_ref.bit_count,
651 "bit_count diverged at bit {i}"
652 );
653 assert_eq!(dec.input, dec_ref.input, "input cursor diverged at bit {i}");
654 }
655 }
656
657 /// Reference `read_literal`: the generic `num_bits × read_bool(128)`
658 /// loop the production method replaced with a register-local
659 /// specialisation. Used to prove the fast path is state-for-state
660 /// identical (including the mid-literal `EndOfStream` error path).
661 fn read_literal_reference(
662 d: &mut BoolDecoder<'_>,
663 num_bits: u32,
664 ) -> Result<u32, BoolDecoderError> {
665 let mut v: u32 = 0;
666 for _ in 0..num_bits {
667 let bit = d.read_bool(128)? as u32;
668 v = (v << 1) | bit;
669 }
670 Ok(v)
671 }
672
673 #[test]
674 fn read_literal_fast_matches_generic_loop() {
675 // Encode a long run of mixed-width literals, then decode the same
676 // partition with the production `read_literal` and the generic
677 // reference loop in lockstep, asserting both the returned value and
678 // the full decoder state (range / value / bit_count / input cursor)
679 // agree after every literal — across every literal width 1..=16.
680 let mut enc = TestEncoder::new();
681 let mut vals = Vec::new();
682 let mut widths = Vec::new();
683 let mut seed = 0x1357_9bdfu32;
684 for _ in 0..2048 {
685 seed ^= seed << 13;
686 seed ^= seed >> 17;
687 seed ^= seed << 5;
688 let w = seed % 16 + 1; // 1..=16
689 let mask = (1u32 << w) - 1;
690 let val = seed & mask;
691 enc.write_literal(val, w);
692 vals.push(val);
693 widths.push(w);
694 }
695 let buf = enc.finish();
696
697 let mut dec = BoolDecoder::init(&buf).unwrap();
698 let mut dec_ref = BoolDecoder::init(&buf).unwrap();
699 for (i, (&val, &w)) in vals.iter().zip(widths.iter()).enumerate() {
700 let got = dec.read_literal(w).unwrap();
701 let got_ref = read_literal_reference(&mut dec_ref, w).unwrap();
702 assert_eq!(got, val, "literal {i} (width {w}) wrong value");
703 assert_eq!(got, got_ref, "fast/generic disagreement at literal {i}");
704 assert_eq!(dec.range, dec_ref.range, "range diverged at literal {i}");
705 assert_eq!(dec.value, dec_ref.value, "value diverged at literal {i}");
706 assert_eq!(
707 dec.bit_count, dec_ref.bit_count,
708 "bit_count diverged at literal {i}"
709 );
710 assert_eq!(dec.input, dec_ref.input, "input diverged at literal {i}");
711 }
712 }
713
714 #[test]
715 fn read_literal_fast_matches_generic_on_end_of_stream() {
716 // Drive both paths to the EndOfStream boundary inside a literal and
717 // assert they fail identically and leave the decoder in the same
718 // committed state. A 2-byte all-zero partition exhausts after a few
719 // prob-128 reads (every renorm pulls a bit and there is no input to
720 // refill from).
721 let mut dec = BoolDecoder::init(&[0x00, 0x00]).unwrap();
722 let mut dec_ref = BoolDecoder::init(&[0x00, 0x00]).unwrap();
723 // A wide literal forces the byte-pull past the 2 buffered bytes.
724 let err = dec.read_literal(32).unwrap_err();
725 let err_ref = read_literal_reference(&mut dec_ref, 32).unwrap_err();
726 assert_eq!(err, err_ref);
727 assert_eq!(err, BoolDecoderError::EndOfStream);
728 assert_eq!(dec.range, dec_ref.range, "range diverged on EOS");
729 assert_eq!(dec.value, dec_ref.value, "value diverged on EOS");
730 assert_eq!(
731 dec.bit_count, dec_ref.bit_count,
732 "bit_count diverged on EOS"
733 );
734 assert_eq!(dec.input, dec_ref.input, "input diverged on EOS");
735 }
736
737 #[test]
738 fn range_invariant_holds_across_reads() {
739 // After every successful read_bool, range must be in 128..=255
740 // per RFC 6386 §7.2.
741 let mut enc = TestEncoder::new();
742 for i in 0..64 {
743 enc.write_bool(((i * 13 + 7) % 254 + 1) as u8, (i & 1) == 1);
744 }
745 let buf = enc.finish();
746 let mut dec = BoolDecoder::init(&buf).unwrap();
747 for i in 0..64 {
748 let _ = dec.read_bool(((i * 13 + 7) % 254 + 1) as u8).unwrap();
749 assert!(
750 (128..=255).contains(&dec.range()),
751 "range out of band after read {i}: {}",
752 dec.range()
753 );
754 }
755 }
756}