Skip to main content

brotli_decompressor/bit_reader/
mod.rs

1#![allow(non_snake_case)]
2use core::default::Default;
3macro_rules! xprintln (
4  ($a : expr) => ();
5  ($a : expr, $b : expr) => ();
6  ($a : expr, $b : expr, $c : expr) => ();
7  ($a : expr, $b : expr, $c : expr, $d : expr) => ();
8  ($a : expr, $b : expr, $c : expr, $d : expr, $e : expr) => ();
9  ($a : expr, $b : expr, $c : expr, $d : expr, $e : expr, $f : expr) => ();
10);
11
12#[cfg(target_pointer_width = "64")]
13#[allow(non_camel_case_types)]
14pub type reg_t = u64;
15
16#[cfg(not(target_pointer_width = "64"))]
17#[allow(non_camel_case_types)]
18pub type reg_t = u32;
19
20pub const BROTLI_SHORT_FILL_BIT_WINDOW_READ: u32 = (::core::mem::size_of::<reg_t>() >> 1) as u32;
21const REG_BITS: u32 = (::core::mem::size_of::<reg_t>() as u32) << 3;
22const REG_SHIFT_MASK: u32 = REG_BITS - 1;
23
24#[cfg(test)]
25mod regression_tests;
26
27#[cfg(test)]
28#[allow(non_upper_case_globals)]
29const kBitMask: [u32; 33] =
30  [0x0000, 0x00000001, 0x00000003, 0x00000007, 0x0000000F, 0x0000001F, 0x0000003F, 0x0000007F,
31   0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF, 0x00000FFF, 0x00001FFF, 0x00003FFF, 0x00007FFF,
32   0x0000FFFF, 0x0001FFFF, 0x0003FFFF, 0x0007FFFF, 0x000FFFFF, 0x001FFFFF, 0x003FFFFF, 0x007FFFFF,
33   0x00FFFFFF, 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF, 0x0FFFFFFF, 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF,
34   0xFFFFFFFF];
35
36// Equals kBitMask[n] without the table load and its bounds check; C computes
37// it the same way wherever it has a bit-field extract instruction.
38// On 64-bit targets it is computed in 64 bits, so it holds for every n in
39// 0..=32. On 32-bit targets a 64-bit shift is a multi-instruction sequence,
40// and making n == 32 work costs the hot paths an extra compare and select
41// (+1.4% instructions on Cortex-A53), so it holds for n in 0..=31 only: the
42// 32-bit reader never needs a 32-bit mask, as it splits reads wider than 16
43// bits into two (`BrotliReadBits`, `BrotliSafeReadBits32Slow`) and peeks at
44// most 16 bits.
45#[inline(always)]
46pub fn BitMask(n: u32) -> u32 {
47  #[cfg(target_pointer_width = "64")]
48  {
49    (!(u64::MAX << (n & 63))) as u32
50  }
51  #[cfg(not(target_pointer_width = "64"))]
52  {
53    debug_assert!(n < 32, "BitMask({}) on a 32-bit target", n);
54    !(u32::MAX << (n & 31))
55  }
56}
57
58// The unread bits are kept right-aligned in val_, the next bit lowest, as in
59// the C decoder: peeking is a plain read of val_, and only dropping bits
60// shifts.  bit_pos_ is the number of valid bits in val_.  Bits of val_ above
61// bit_pos_ may hold bits of the bytes that follow, which a refill writes over
62// with the same values.
63#[derive(Clone, Copy)]
64pub struct BrotliBitReader {
65  pub val_: reg_t, // pre-fetched bits, next bit lowest
66  pub bit_pos_: u32, // number of valid bits in val_
67  pub next_in: u32, // the byte we're reading from
68  pub avail_in: u32,
69}
70
71impl Default for BrotliBitReader {
72  fn default() -> Self {
73    BrotliBitReader {
74      val_: 0,
75      bit_pos_: 0,
76      next_in: 0,
77      avail_in: 0,
78    }
79  }
80}
81
82pub struct BrotliBitReaderState {
83  pub val_: reg_t,
84  pub bit_pos_: u32,
85  pub next_in: u32,
86  pub avail_in: u32,
87}
88impl Default for BrotliBitReaderState {
89  #[inline]
90  fn default() -> Self {
91    BrotliBitReaderState {
92      val_: 0,
93      bit_pos_: 0,
94      next_in: 0,
95      avail_in: 0,
96    }
97  }
98}
99
100pub fn BrotliBitReaderSaveState(from: &BrotliBitReader) -> BrotliBitReaderState {
101  BrotliBitReaderState {
102    val_: from.val_,
103    bit_pos_: from.bit_pos_,
104    next_in: from.next_in,
105    avail_in: from.avail_in,
106  }
107}
108
109pub fn BrotliBitReaderRestoreState(to: &mut BrotliBitReader, from: &BrotliBitReaderState) {
110  to.val_ = from.val_;
111  to.bit_pos_ = from.bit_pos_;
112  to.next_in = from.next_in;
113  to.avail_in = from.avail_in;
114}
115
116#[inline(always)]
117pub fn BrotliGetAvailableBits(br: &BrotliBitReader) -> u32 {
118  br.bit_pos_
119}
120
121// The bit reader keeps its cursor in u32, so the one-past-the-end offset must
122// fit too: bounding the offset and the length separately would still let
123// consuming the last byte overflow next_in. usize may be 64 bits wide, so the
124// sum saturates rather than wraps.
125#[inline]
126pub fn is_valid_input_range(input_offset: usize, available_in: usize, input_len: usize) -> bool {
127  let end = (input_offset as u64).saturating_add(available_in as u64);
128  end <= input_len as u64 && end <= u64::from(u32::MAX)
129}
130
131pub fn is_valid_bit_reader(br: &BrotliBitReader, input: &[u8]) -> bool {
132  let register_bits = (::core::mem::size_of::<reg_t>() as u32) << 3;
133  br.bit_pos_ <= register_bits &&
134    u64::from(br.next_in) + u64::from(br.avail_in) <= input.len() as u64
135}
136
137// Returns amount of unread bytes the bit reader still has buffered from the
138// BrotliInput, including whole bytes in br->val_.
139pub fn BrotliGetRemainingBytes(br: &BrotliBitReader) -> u32 {
140  br.avail_in + (BrotliGetAvailableBits(br) >> 3)
141}
142
143// Checks if there is at least num bytes left in the input ringbuffer (excluding
144// the bits remaining in br->val_).
145#[inline(always)]
146pub fn BrotliCheckInputAmount(br: &BrotliBitReader, num: u32) -> bool {
147  br.avail_in >= num
148}
149
150#[inline(always)]
151// Callers refill only when the caller checked enough input is available, so
152// the zero fallback is unreachable; it replaces a panicking index.
153#[allow(dead_code)]
154fn BrotliLoad16LE(input: &[u8], next_in_u32: u32) -> u16 {
155  use core::convert::TryInto;
156  match input
157    .get(next_in_u32 as usize..)
158    .and_then(|rest| rest.get(..2))
159    .and_then(|bytes| bytes.try_into().ok())
160  {
161    Some(bytes) => u16::from_le_bytes(bytes),
162    None => {
163      debug_assert!(false, "BrotliLoad16LE past the end of the input");
164      0
165    }
166  }
167}
168
169// from_le_bytes compiles to one unaligned load; assembling the value byte by
170// byte let LLVM split the load into pieces once callers shift out high bytes.
171#[inline(always)]
172fn BrotliLoad32LE(input: &[u8], next_in_u32: u32) -> u32 {
173  let next_in: usize = next_in_u32 as usize;
174  let mut four_byte: [u8; 4] = fast_uninitialized![4];
175  four_byte.clone_from_slice(fast!((input)[next_in ; next_in + 4]));
176  u32::from_le_bytes(four_byte)
177}
178
179#[allow(dead_code)]
180#[inline(always)]
181fn BrotliLoad64LE(input: &[u8], next_in_u32: u32) -> u64 {
182  let next_in: usize = next_in_u32 as usize;
183  let mut eight_byte: [u8; 8] = fast_uninitialized![8];
184  eight_byte.clone_from_slice(fast!((input)[next_in ; next_in + 8]));
185  u64::from_le_bytes(eight_byte)
186}
187
188#[cold]
189#[inline(always)]
190fn cold_bit_reader_path() {}
191
192// Makes at least n_bits + 1 bits valid for n_bits <= 16, and at least 32 for
193// n_bits <= 32 on 64-bit targets (exactly 32 when the accumulator was empty).
194// The narrower cases load 64 bits (32 bits on 32-bit targets) and claim 7 or 6
195// bytes (3 bytes on 32-bit targets) of them; the bits of the byte past those
196// land above bit_pos_, where the next refill writes the same bits again.
197#[inline(always)]
198pub fn BrotliFillBitWindow(br: &mut BrotliBitReader, n_bits: u32, input: &[u8]) {
199  #[cfg(target_pointer_width = "64")]
200  {
201    if n_bits <= 8 {
202      if br.bit_pos_ <= 8 {
203        br.val_ |= BrotliLoad64LE(input, br.next_in) << br.bit_pos_;
204        br.bit_pos_ += 56;
205        br.avail_in -= 7;
206        br.next_in += 7;
207      }
208    } else if n_bits <= 16 {
209      if br.bit_pos_ <= 16 {
210        br.val_ |= BrotliLoad64LE(input, br.next_in) << br.bit_pos_;
211        br.bit_pos_ += 48;
212        br.avail_in -= 6;
213        br.next_in += 6;
214      }
215    } else if br.bit_pos_ <= 32 {
216      br.val_ |= (BrotliLoad32LE(input, br.next_in) as reg_t) << br.bit_pos_;
217      br.bit_pos_ += 32;
218      br.avail_in -= BROTLI_SHORT_FILL_BIT_WINDOW_READ;
219      br.next_in += BROTLI_SHORT_FILL_BIT_WINDOW_READ;
220    }
221  }
222  #[cfg(not(target_pointer_width = "64"))]
223  {
224    if n_bits <= 8 {
225      if br.bit_pos_ <= 8 {
226        br.val_ |= (BrotliLoad32LE(input, br.next_in) as reg_t) << br.bit_pos_;
227        br.bit_pos_ += 24;
228        br.avail_in -= 3;
229        br.next_in += 3;
230      }
231    } else if br.bit_pos_ <= 16 {
232      br.val_ |= (BrotliLoad16LE(input, br.next_in) as reg_t) << br.bit_pos_;
233      br.bit_pos_ += 16;
234      br.avail_in -= BROTLI_SHORT_FILL_BIT_WINDOW_READ;
235      br.next_in += BROTLI_SHORT_FILL_BIT_WINDOW_READ;
236    }
237  }
238}
239
240// Mostly like BrotliFillBitWindow, but guarantees only 16 bits and reads no
241// more than BROTLI_SHORT_FILL_BIT_WINDOW_READ bytes of input.
242#[allow(dead_code)]
243pub fn BrotliFillBitWindow16(br: &mut BrotliBitReader, input: &[u8]) {
244  BrotliFillBitWindow(br, 17, input);
245}
246
247// Pulls one byte of input to accumulator.
248#[inline(always)]
249pub fn BrotliPullByte(br: &mut BrotliBitReader, input: &[u8]) -> bool {
250  if br.avail_in == 0 {
251    return false;
252  }
253  let byte = match input.get(br.next_in as usize) {
254    Some(&b) => b as reg_t,
255    None => return false,
256  };
257  br.val_ |= byte << br.bit_pos_;
258  br.bit_pos_ += 8;
259  br.avail_in -= 1;
260  br.next_in += 1;
261  true
262}
263
264// Returns currently available bits, next bit lowest; the valid ones are the
265// low BrotliGetAvailableBits of them.
266#[inline(always)]
267pub fn BrotliGetBitsUnmasked(br: &BrotliBitReader) -> reg_t {
268  br.val_
269}
270
271// Like BrotliGetBits, but does not mask the result.
272// The result contains at least 16 valid bits.
273#[inline(always)]
274pub fn BrotliGet16BitsUnmasked(br: &mut BrotliBitReader, input: &[u8]) -> u32 {
275  BrotliFillBitWindow(br, 16, input);
276  BrotliGetBitsUnmasked(br) as u32
277}
278
279// Returns the specified number of bits from `br` without advancing bit pos.
280// On 32-bit targets a single refill guarantees at most 16 bits, so `n_bits`
281// must be `<= 16` (`<= 32` on 64-bit targets).
282#[inline(always)]
283pub fn BrotliGetBits(br: &mut BrotliBitReader, n_bits: u32, input: &[u8]) -> u32 {
284  debug_assert!(::core::mem::size_of::<reg_t>() == 8 || n_bits <= 16);
285  BrotliFillBitWindow(br, n_bits, input);
286  (BrotliGetBitsUnmasked(br) as u32) & BitMask(n_bits)
287}
288
289// Returns the specified number of bits from `br` without advancing bit pos.
290// On 32-bit targets a single refill guarantees at most 16 bits, so `n_bits`
291// must be `<= 16` (`<= 32` on 64-bit targets).
292#[allow (dead_code)]
293pub fn BrotliGetConstantNBits(br: &mut BrotliBitReader, n_bits: u32, input: &[u8]) -> u32 {
294  BrotliGetBits(br, n_bits, input)
295}
296
297// Tries to peek the specified amount of bits. Returns 0, if there is not
298// enough input.
299#[inline(always)]
300pub fn BrotliSafeGetBits(br: &mut BrotliBitReader,
301                         n_bits: u32,
302                         val: &mut u32,
303                         input: &[u8])
304                         -> bool {
305  while BrotliGetAvailableBits(br) < n_bits {
306    if !BrotliPullByte(br, input) {
307      return false;
308    }
309  }
310  *val = (BrotliGetBitsUnmasked(br) as u32) & BitMask(n_bits);
311  true
312}
313
314// Advances the bit pos by n_bits, at most 32.
315#[inline(always)]
316pub fn BrotliDropBits(br: &mut BrotliBitReader, n_bits: u32) {
317  // `& REG_SHIFT_MASK` turns a full-width drop into a no-op, so callers
318  // never drop all `REG_BITS` bits at once (wide reads are split).
319  debug_assert!(n_bits < REG_BITS && n_bits <= br.bit_pos_);
320  br.val_ >>= n_bits & REG_SHIFT_MASK;
321  br.bit_pos_ -= n_bits;
322}
323
324// Clears the bits above bit_pos_.  Callers that move next_in other than by
325// loading through val_ do it, since those bits belong to the byte at next_in.
326#[inline(always)]
327pub fn BrotliBitReaderClearUnclaimed(br: &mut BrotliBitReader) {
328  if br.bit_pos_ < REG_BITS {
329    br.val_ &= ((1 as reg_t) << br.bit_pos_) - 1;
330  }
331}
332
333pub fn BrotliBitReaderUnload(br: &mut BrotliBitReader) {
334  let unused_bytes: u32 = BrotliGetAvailableBits(br) >> 3;
335  br.avail_in += unused_bytes;
336  br.next_in -= unused_bytes;
337  br.bit_pos_ -= unused_bytes << 3;
338  BrotliBitReaderClearUnclaimed(br);
339}
340
341// Reads the specified number of bits from br and advances the bit pos.
342// Precondition: accumulator MUST contain at least n_bits.
343#[inline(always)]
344pub fn BrotliTakeBits(br: &mut BrotliBitReader, n_bits: u32, val: &mut u32) {
345  *val = (BrotliGetBitsUnmasked(br) as u32) & BitMask(n_bits);
346  xprintln!("[BrotliReadBits]  {:?} {:?} {:?} val: {:x}\n",
347           br.avail_in, br.bit_pos_, n_bits, *val);
348  BrotliDropBits(br, n_bits);
349}
350
351// Reads the specified number of bits from br and advances the bit pos.
352// Assumes that there is enough input to perform BrotliFillBitWindow.
353//
354// Callers pass a data-dependent n_bits (extra bits of lengths and distances),
355// for which C's BrotliReadBits24 compiles BrotliFillBitWindow to its generic
356// case alone: refill 32 bits once half the window is consumed, which leaves at
357// least 33 bits for any n_bits up to 32. Choosing among the narrower n_bits
358// cases at run time costs extra unpredictable branches.
359#[inline(always)]
360pub fn BrotliReadBits(br: &mut BrotliBitReader, n_bits: u32, input: &[u8]) -> u32 {
361  if ::core::mem::size_of::<reg_t>() == 8 {
362    let mut val: u32 = 0;
363    BrotliFillBitWindow(br, 32, input);
364    BrotliTakeBits(br, n_bits, &mut val);
365    val
366  } else if n_bits <= 16 {
367    let mut val: u32 = 0;
368    BrotliFillBitWindow(br, 16, input);
369    BrotliTakeBits(br, n_bits, &mut val);
370    val
371  } else {
372    cold_bit_reader_path();
373    let mut low_val: u32 = 0;
374    let mut high_val: u32 = 0;
375    BrotliFillBitWindow(br, 16, input);
376    BrotliTakeBits(br, 16, &mut low_val);
377    BrotliFillBitWindow(br, 16, input);
378    BrotliTakeBits(br, n_bits - 16, &mut high_val);
379    low_val | (high_val << 16)
380  }
381}
382
383// Reads the specified number of bits from br and advances the bit pos.
384// Assumes that there is enough input to perform BrotliFillBitWindow.
385#[allow (dead_code)]
386pub fn BrotliReadConstantNBits(br: &mut BrotliBitReader, n_bits: u32, input: &[u8]) -> u32 {
387  if ::core::mem::size_of::<reg_t>() == 8 || (n_bits <= 16) {
388    let mut val: u32 = 0;
389    BrotliFillBitWindow(br, n_bits, input);
390    BrotliTakeBits(br, n_bits, &mut val);
391    val
392  } else {
393    let mut low_val: u32 = 0;
394    let mut high_val: u32 = 0;
395    BrotliFillBitWindow(br, 16, input);
396    BrotliTakeBits(br, 16, &mut low_val);
397    // Refill 16 bits (not 8) so `n_bits` up to 32 (`n_bits - 16` up to 16) has
398    // enough bits buffered on 32-bit targets.
399    BrotliFillBitWindow(br, 16, input);
400    BrotliTakeBits(br, n_bits - 16, &mut high_val);
401    low_val | (high_val << 16)
402  }
403}
404
405#[cold]
406#[inline(never)]
407fn BrotliSafeReadBits32Slow(br: &mut BrotliBitReader,
408                            n_bits: u32,
409                            val: &mut u32,
410                            input: &[u8])
411                            -> bool {
412  let mut low_val: u32 = 0;
413  let mut high_val: u32 = 0;
414  let memento = BrotliBitReaderSaveState(br);
415  if !BrotliSafeReadBits(br, 16, &mut low_val, input) ||
416     !BrotliSafeReadBits(br, n_bits - 16, &mut high_val, input) {
417    BrotliBitReaderRestoreState(br, &memento);
418    return false;
419  }
420  *val = low_val | (high_val << 16);
421  true
422}
423
424// Tries to read the specified amount of bits. Returns 0, if there is not
425// enough input. n_bits MUST be positive.
426#[inline(always)]
427pub fn BrotliSafeReadBits(br: &mut BrotliBitReader,
428                          n_bits: u32,
429                          val: &mut u32,
430                          input: &[u8])
431                          -> bool {
432  if ::core::mem::size_of::<reg_t>() < 8 && n_bits > 24 {
433    return BrotliSafeReadBits32Slow(br, n_bits, val, input);
434  }
435  while BrotliGetAvailableBits(br) < n_bits {
436    if !BrotliPullByte(br, input) {
437      return false;
438    }
439  }
440  BrotliTakeBits(br, n_bits, val);
441  true
442}
443
444// Advances the bit reader position to the next byte boundary and verifies
445// that any skipped bits are set to zero.
446pub fn BrotliJumpToByteBoundary(br: &mut BrotliBitReader) -> bool {
447  let pad_bits_count: u32 = BrotliGetAvailableBits(br) & 0x7;
448  let mut pad_bits: u32 = 0;
449  if pad_bits_count != 0 {
450    BrotliTakeBits(br, pad_bits_count, &mut pad_bits);
451  }
452  pad_bits == 0
453}
454
455// Peeks a byte at specified offset.
456// Precondition: bit reader is parked to a byte boundary.
457// Returns -1 if operation is not feasible.
458pub fn BrotliPeekByte(br: &mut BrotliBitReader, mut offset: u32, input: &[u8]) -> i32 {
459  if !is_valid_bit_reader(br, input) {
460    return -1;
461  }
462  let available_bits: u32 = BrotliGetAvailableBits(br);
463  let bytes_left: u32 = (available_bits >> 3);
464  if (available_bits & 7) != 0 {
465    return -1;
466  }
467  if offset < bytes_left {
468    return ((BrotliGetBitsUnmasked(br) >> ((offset << 3)) as u32) & 0xFF) as i32;
469  }
470  offset -= bytes_left;
471  if offset < br.avail_in {
472    let input_index = u64::from(br.next_in) + u64::from(offset);
473    return match input.get(input_index as usize) {
474      Some(value) => *value as i32,
475      None => -1,
476    };
477  }
478  -1
479}
480
481// Copies remaining input bytes stored in the bit reader to the output. Value
482// num may not be larger than BrotliGetRemainingBytes. The bit reader must be
483// warmed up again after this.
484pub fn BrotliCopyBytes(dest: &mut [u8], br: &mut BrotliBitReader, mut num: u32, input: &[u8]) {
485  let mut offset: u32 = 0;
486  while BrotliGetAvailableBits(br) >= 8 && num > 0 {
487    fast_mut!((dest)[offset as usize]) = BrotliGetBitsUnmasked(br) as u8;
488    BrotliDropBits(br, 8);
489    offset += 1;
490    num -= 1;
491  }
492  // One bulk copy of the same bytes the per-byte loop used to copy.
493  let dest_start = offset as usize;
494  let input_start = br.next_in as usize;
495  fast_mut!((dest)[dest_start ; dest_start + num as usize])
496    .clone_from_slice(fast!((input)[input_start ; input_start + num as usize]));
497  br.avail_in -= num;
498  br.next_in += num;
499  BrotliBitReaderClearUnclaimed(br);
500}
501
502pub fn BrotliInitBitReader(br: &mut BrotliBitReader) {
503  br.val_ = 0;
504  br.bit_pos_ = 0;
505}
506
507pub fn BrotliWarmupBitReader(br: &mut BrotliBitReader, input: &[u8]) -> bool {
508  if BrotliGetAvailableBits(br) == 0 && !BrotliPullByte(br, input) {
509    return false;
510  }
511  true
512}
513
514// Register-friendly view over `(BrotliBitReader, &[u8])` for the non-streaming
515// hot loops (`ProcessCommands` and `ReadSymbolCodeLengths`): holds the
516// remaining input slice directly instead of separate `(input, next_in,
517// avail_in)` cursors, so refills need no index bounds checks. The bits have
518// the reader's layout, unread bits right-aligned with the count in
519// `avail_bits`, and bits above `avail_bits` may hold the bytes that follow,
520// which a refill writes over with the same values.
521#[derive(Copy, Clone)]
522pub(crate) struct BitReaderSlice<'a> {
523  pub val: reg_t,
524  pub avail_bits: u32,
525  pub rem: &'a [u8],
526}
527
528// Shift mask for `val`: `& REG_SHIFT_MASK` keeps every shift in range
529// without changing any valid shift amount.
530pub(crate) const SLICE_SHIFT_MASK: u32 = REG_SHIFT_MASK;
531
532impl<'a> BitReaderSlice<'a> {
533  #[inline(always)]
534  pub fn new(br: &BrotliBitReader, input: &'a [u8]) -> Option<Self> {
535    let rem = input
536      .get(br.next_in as usize..)
537      .and_then(|s| s.get(..br.avail_in as usize))?;
538    Some(BitReaderSlice {
539      val: br.val_,
540      avail_bits: br.bit_pos_,
541      rem: rem,
542    })
543  }
544
545  #[inline(always)]
546  pub fn empty() -> Self {
547    BitReaderSlice {
548      val: 0,
549      avail_bits: 0,
550      rem: &[],
551    }
552  }
553
554  #[inline(always)]
555  pub fn sync_to(self, br: &mut BrotliBitReader) {
556    br.val_ = self.val;
557    br.bit_pos_ = self.avail_bits;
558    let avail_in = self.rem.len() as u32;
559    let consumed = br.avail_in - avail_in;
560    br.next_in += consumed;
561    br.avail_in = avail_in;
562  }
563
564  #[inline(always)]
565  pub fn has_input(&self) -> bool {
566    self.rem.len() >= 28
567  }
568
569  #[inline(always)]
570  pub fn avail_in(&self) -> u32 {
571    self.rem.len() as u32
572  }
573
574  // Guarantees at least 16 valid bits (17 when any were left), as long as at
575  // least 8 (64-bit) or 2 (32-bit) bytes of input remain.
576  #[cfg(target_pointer_width = "64")]
577  #[inline(always)]
578  pub fn fill16(&mut self) {
579    if self.avail_bits <= 16 {
580      if let &[b0, b1, b2, b3, b4, b5, b6, b7, ..] = self.rem {
581        let next = u64::from_le_bytes([b0, b1, b2, b3, b4, b5, b6, b7]);
582        self.rem = &self.rem[6..];
583        self.val |= next << (self.avail_bits & 63);
584        self.avail_bits += 48;
585      } else {
586        debug_assert!(false, "BitReaderSlice::fill16 past the end of the input");
587      }
588    }
589  }
590
591  // On 32-bit targets `val` is a single register: refill 16 bits with one
592  // halfword load (`ldrh`) once at most 16 bits are left, instead of the
593  // 64-bit layout's two-register 8-byte load and 64-bit variable shift.
594  #[cfg(not(target_pointer_width = "64"))]
595  #[inline(always)]
596  pub fn fill16(&mut self) {
597    use core::convert::TryInto;
598    if self.avail_bits <= 16 {
599      if let Some(bytes) = self.rem.get(..2).and_then(|s| s.try_into().ok()) {
600        self.rem = &self.rem[2..];
601        self.val |= (u16::from_le_bytes(bytes) as reg_t) << (self.avail_bits & REG_SHIFT_MASK);
602        self.avail_bits += 16;
603      } else {
604        debug_assert!(false, "BitReaderSlice::fill16 past the end of the input");
605      }
606    }
607  }
608
609  // Same as `BrotliFillBitWindow16`: guarantees at least 16 bits while reading
610  // at most `BROTLI_SHORT_FILL_BIT_WINDOW_READ` bytes (4 on 64-bit, 2 on
611  // 32-bit).
612  #[inline(always)]
613  pub fn fill_short(&mut self) {
614    #[cfg(target_pointer_width = "64")]
615    {
616      self.fill32();
617    }
618    #[cfg(not(target_pointer_width = "64"))]
619    {
620      self.fill16();
621    }
622  }
623
624  // Separating the `< 8` failure exit from the hot `avail_bits > 16`
625  // fallthrough prevents SimplifyCFG from fusing `rem.len() >= 8` into every
626  // non-refill literal iteration.
627  #[cfg(target_pointer_width = "64")]
628  #[inline(always)]
629  pub fn fill16_checked(&mut self) -> bool {
630    #[cold]
631    #[inline(always)]
632    fn cold_underflow() {}
633
634    if self.avail_bits <= 16 {
635      let next = match *self.rem {
636        [b0, b1, b2, b3, b4, b5, b6, b7, ..] => u64::from_le_bytes([b0, b1, b2, b3, b4, b5, b6, b7]),
637        _ => {
638          cold_underflow();
639          return false;
640        }
641      };
642      self.rem = &self.rem[6..];
643      self.val |= next << (self.avail_bits & 63);
644      self.avail_bits += 48;
645    }
646    true
647  }
648
649  #[cfg(not(target_pointer_width = "64"))]
650  #[inline(always)]
651  pub fn fill16_checked(&mut self) -> bool {
652    use core::convert::TryInto;
653    #[cold]
654    #[inline(always)]
655    fn cold_underflow() {}
656
657    if self.avail_bits <= 16 {
658      let bytes: [u8; 2] = match self.rem.get(..2).and_then(|s| s.try_into().ok()) {
659        Some(bytes) => bytes,
660        None => {
661          cold_underflow();
662          return false;
663        }
664      };
665      self.rem = &self.rem[2..];
666      self.val |= (u16::from_le_bytes(bytes) as reg_t) << (self.avail_bits & REG_SHIFT_MASK);
667      self.avail_bits += 16;
668    }
669    true
670  }
671
672  #[cfg(target_pointer_width = "64")]
673  #[inline(always)]
674  pub fn fill32(&mut self) {
675    if self.avail_bits <= 32 {
676      if let &[b0, b1, b2, b3, ref rest @ ..] = self.rem {
677        let next = u32::from_le_bytes([b0, b1, b2, b3]) as u64;
678        self.rem = rest;
679        self.val |= next << (self.avail_bits & 63);
680        self.avail_bits += 32;
681      } else {
682        debug_assert!(false, "BitReaderSlice::fill32 past the end of the input");
683      }
684    }
685  }
686
687  #[inline(always)]
688  pub fn drop_bits(&mut self, n_bits: u32) {
689    debug_assert!(n_bits <= self.avail_bits);
690    self.avail_bits = self.avail_bits.wrapping_sub(n_bits);
691    self.val >>= n_bits & REG_SHIFT_MASK;
692  }
693
694  #[inline(always)]
695  pub fn take_bits(&mut self, n_bits: u32) -> u32 {
696    let out = (self.val as u32) & BitMask(n_bits);
697    self.drop_bits(n_bits);
698    out
699  }
700
701  #[cfg(target_pointer_width = "64")]
702  #[inline(always)]
703  pub fn read_bits(&mut self, n_bits: u32) -> u32 {
704    self.fill32();
705    self.take_bits(n_bits)
706  }
707
708  // A 32-bit register holds at least 16 valid bits after a refill, so reads
709  // wider than 16 bits (insert, copy and distance extra bits up to 24, or 30
710  // with large windows) are split in two, as in `BrotliReadBits`.
711  #[cfg(not(target_pointer_width = "64"))]
712  #[inline(always)]
713  pub fn read_bits(&mut self, n_bits: u32) -> u32 {
714    self.fill16();
715    if n_bits <= 16 {
716      self.take_bits(n_bits)
717    } else {
718      cold_bit_reader_path();
719      let low = self.take_bits(16);
720      self.fill16();
721      let high = self.take_bits(n_bits - 16);
722      low | (high << 16)
723    }
724  }
725}
726
727#[cfg(test)]
728mod tests {
729  use super::*;
730
731  // The tests below were written for a reader that kept consumed bits in val_
732  // and counted them in bit_pos_; these convert between the two layouts.
733  pub(super) fn old_layout(val: reg_t, consumed: u32, avail_in: u32, next_in: u32) -> BrotliBitReader {
734    BrotliBitReader {
735      val_: if consumed >= REG_BITS { 0 } else { val >> consumed },
736      bit_pos_: REG_BITS - consumed,
737      avail_in: avail_in,
738      next_in: next_in,
739    }
740  }
741
742  #[cfg(target_pointer_width = "64")]
743  fn consumed(br: &BrotliBitReader) -> u32 {
744    REG_BITS - br.bit_pos_
745  }
746
747  #[cfg(target_pointer_width = "64")]
748  fn valid_bits(br: &BrotliBitReader) -> reg_t {
749    let mut copy = *br;
750    BrotliBitReaderClearUnclaimed(&mut copy);
751    copy.val_
752  }
753
754  #[test]
755  fn bit_mask_matches_the_table() {
756    // 32-bit targets support n <= 31 only; see `BitMask`.
757    let max = if ::core::mem::size_of::<reg_t>() == 8 { 32 } else { 31 };
758    for n in 0..max + 1 {
759      assert_eq!(BitMask(n), kBitMask[n as usize]);
760    }
761  }
762
763  #[test]
764  fn input_range_checks_the_end_cursor() {
765    // Exercise the range arithmetic without allocating a multi-GiB input.
766    let max_cursor = u32::MAX as usize;
767    assert!(is_valid_input_range(0, 0, 0));
768    assert!(is_valid_input_range(3, 5, 8));
769    assert!(!is_valid_input_range(3, 6, 8));
770    assert!(!is_valid_input_range(9, 0, 8));
771    assert!(is_valid_input_range(0, max_cursor, max_cursor));
772    assert!(is_valid_input_range(max_cursor - 1, 1, max_cursor));
773    assert!(is_valid_input_range(max_cursor, 0, max_cursor));
774    assert!(!is_valid_input_range(max_cursor, 1, usize::MAX));
775    assert!(!is_valid_input_range(max_cursor - 1, 2, usize::MAX));
776    assert!(!is_valid_input_range(usize::MAX, 1, usize::MAX));
777  }
778
779  #[cfg(target_pointer_width="64")]
780  #[test]
781  fn a_large_input_slice_does_not_widen_the_cursor() {
782    let input_len = 1usize << 32;
783    assert!(is_valid_input_range(0, input_len - 1, input_len));
784    assert!(!is_valid_input_range(input_len - 1, 1, input_len));
785    assert!(!is_valid_input_range(1, input_len - 1, input_len));
786    assert!(!is_valid_input_range(0, input_len, input_len));
787    assert!(!is_valid_input_range(input_len, 0, input_len));
788  }
789
790  #[test]
791  fn peek_byte_rejects_invalid_state() {
792    let data: [u8; 1] = [0x7f];
793    let mut unaligned_reader = old_layout(0, 1, 0, 0);
794    assert_eq!(BrotliPeekByte(&mut unaligned_reader, 0, &data), -1);
795
796    let mut out_of_bounds_reader = old_layout(0, REG_BITS, 1, 1);
797    assert_eq!(BrotliPeekByte(&mut out_of_bounds_reader, 0, &data), -1);
798  }
799
800  // Hard-coded vectors for the 64-bit register; regression_tests.rs
801  // checks both register widths against a bit-at-a-time oracle.
802  #[cfg(target_pointer_width = "64")]
803  #[test]
804  fn warmup_works() {
805    let data: [u8; 37] = [0xde, 0xad, 0xbe, 0xef /* 4 bytes garbage at beginning */, 0x21,
806                          0xfd, 0xff, 0x87, 0x03, 0x6c, 0x63, 0x90, 0xde, 0xe9, 0x36, 0x04, 0xf8,
807                          0x89, 0xb4, 0x4d, 0x57, 0x96, 0x51, 0x0a, 0x54, 0xb7, 0x54, 0xee, 0xf4,
808                          0xdc, 0xa0, 0x05, 0x9b, 0xd2, 0x2b, 0x30, 0x8f]; // 33 b goods
809    let mut bit_reader = old_layout(0x0, 64, 33, 4);
810    let ret = BrotliWarmupBitReader(&mut bit_reader, &data[..]);
811    assert_eq!(ret, true);
812    assert_eq!(valid_bits(&bit_reader), 0x2100000000000000 >> 56);
813    assert_eq!(consumed(&bit_reader), 56);
814    assert_eq!(bit_reader.avail_in, 32);
815    assert_eq!(bit_reader.next_in, 5);
816  }
817  // Hard-coded vectors for the 64-bit register; regression_tests.rs
818  // checks both register widths against a bit-at-a-time oracle.
819  #[cfg(target_pointer_width = "64")]
820  #[test]
821  fn warmup_errcheck() {
822    let data: [u8; 3] = [0xde, 0xad, 0xeb]; // 3 bytes garbage at beginning
823    let mut bit_reader = old_layout(0x86e884e1ffff577b, 64, 0, 3);
824    let ret = BrotliWarmupBitReader(&mut bit_reader, &data[..]);
825    assert_eq!(ret, false);
826    assert_eq!(valid_bits(&bit_reader), 0);
827    assert_eq!(consumed(&bit_reader), 64);
828    assert_eq!(bit_reader.avail_in, 0);
829    assert_eq!(bit_reader.next_in, 3);
830  }
831  // Hard-coded vectors for the 64-bit register; regression_tests.rs
832  // checks both register widths against a bit-at-a-time oracle.
833  #[cfg(target_pointer_width = "64")]
834  #[test]
835  fn safe_read_tests() {
836    {
837      let data: [u8; 12] = [0x50, 0x3b, 0xbb, 0x5e, 0xc5, 0x96, 0x81, 0xb7, 0x52, 0x89, 0xea, 0x3d];
838      let mut bit_reader = old_layout(0xe1e56a736e04fbf5, 6, 12, 0);
839      let mut val: u32 = 0;
840      let ret = BrotliSafeReadBits(&mut bit_reader, 7, &mut val, &data[..]);
841      assert_eq!(ret, true);
842      assert_eq!(val, 0x6f);
843      assert_eq!(bit_reader.avail_in, 12);
844      assert_eq!(bit_reader.next_in, 0);
845      assert_eq!(consumed(&bit_reader), 13);
846    }
847    {
848      let data: [u8; 7] = [0xba, 0xd0, 0xf0, 0x0d, 0xc8, 0xcd, 0xcc];
849      let mut bit_reader = old_layout(0x17f115ae26916f0, 57, 3, 4);
850      let mut val: u32 = 0;
851      let ret = BrotliSafeReadBits(&mut bit_reader, 15, &mut val, &data[..]);
852      assert_eq!(ret, true);
853      assert_eq!(val, 0x6400);
854      assert_eq!(bit_reader.avail_in, 2);
855      assert_eq!(bit_reader.next_in, 5);
856      assert_eq!(consumed(&bit_reader), 64);
857    }
858    {
859      let data: [u8; 4] = [0xee, 0xee, 0xf0, 0xd5];
860      let mut bit_reader = old_layout(0x5f43f252c027e447, 53, 2, 2);
861      let mut val: u32 = 0;
862      let ret = BrotliSafeReadBits(&mut bit_reader, 14, &mut val, &data[..]);
863      assert_eq!(ret, true);
864      assert_eq!(bit_reader.avail_in, 1);
865      assert_eq!(bit_reader.next_in, 3);
866      assert_eq!(consumed(&bit_reader), 59);
867      assert_eq!(valid_bits(&bit_reader), 0xf05f43f252c027e4 >> 59);
868      assert_eq!(val, 0x2fa);
869    }
870    {
871      let data: [u8; 4] = [0xee, 0xee, 0xf0, 0xd5];
872      let mut bit_reader = old_layout(0x2f902339697460, 57, 0, 4);
873      let mut val: u32 = 0x74eca3f0;
874      let ret = BrotliSafeReadBits(&mut bit_reader, 14, &mut val, &data[..]);
875      assert_eq!(ret, false);
876      assert_eq!(bit_reader.avail_in, 0);
877      assert_eq!(bit_reader.next_in, 4);
878      assert_eq!(consumed(&bit_reader), 57);
879      assert_eq!(valid_bits(&bit_reader), 0x2f902339697460 >> 57);
880      assert_eq!(val, 0x74eca3f0);
881    }
882  }
883  // Hard-coded vectors for the 64-bit register; regression_tests.rs
884  // checks both register widths against a bit-at-a-time oracle.
885  #[cfg(target_pointer_width = "64")]
886  #[test]
887  fn bit_read_tests() {
888    {
889      let data: [u8; 32] = [0xba, 0xaa, 0xad, 0xdd, 0x57, 0x5c, 0xd9, 0xa3, 0x3e, 0xb3, 0x77,
890                            0xe7, 0xa0, 0x1e, 0x09, 0xd3, 0x12, 0xa1, 0x3f, 0xb8, 0x7e, 0x5a,
891                            0x06, 0x86, 0xe5, 0x36, 0xef, 0x9c, 0x9f, 0x6d, 0x9b, 0xcc];
892      let mut bit_reader = old_layout(0xf5917f07daaaeabb, 33, 29, 3);
893      let ret = BrotliReadBits(&mut bit_reader, 8, &data[..]);
894      assert_eq!(ret, 0x83);
895      assert_eq!(consumed(&bit_reader), 9);
896      assert_eq!(bit_reader.avail_in, 25);
897      assert_eq!(bit_reader.next_in, 7);
898    }
899    {
900      let data: [u8; 28] = [0xba, 0xaa, 0xaa, 0xad, 0x74, 0x40, 0x8e, 0xee, 0xd2, 0x38, 0xf1,
901                            0xf4, 0xf8, 0x1d, 0x9f, 0x24, 0x48, 0x1e, 0x82, 0xce, 0x48, 0x88,
902                            0xd7, 0x25, 0x74, 0xaf, 0xe3, 0xea];
903      let mut bit_reader = old_layout(0x27e33b2440d3feaf, 18, 24, 4);
904      let ret = BrotliReadBits(&mut bit_reader, 15, &data[..]);
905      assert_eq!(ret, 0x1034);
906      assert_eq!(consumed(&bit_reader), 33);
907      assert_eq!(bit_reader.avail_in, 24);
908      assert_eq!(bit_reader.next_in, 4);
909    }
910  }
911  // Hard-coded vectors for the 64-bit register; regression_tests.rs
912  // checks both register widths against a bit-at-a-time oracle.
913  #[cfg(target_pointer_width = "64")]
914  #[test]
915  fn const_fill_bit_window_tests() {
916    {
917      let data: [u8; 36] = [0xff, 0x9a, 0xa0, 0xde, 0x50, 0x99, 0x67, 0x67, 0x69, 0x87, 0x0e,
918                            0x69, 0xeb, 0x6a, 0xd1, 0x56, 0xc0, 0x32, 0x96, 0xed, 0x78, 0x0e,
919                            0x19, 0xdd, 0x0b, 0xe8, 0xf8, 0x33, 0x9f, 0xe0, 0x69, 0x55, 0x59,
920                            0x3f, 0x5d, 0xc8];
921      let mut bit_reader = old_layout(0xb3fc441e0181dc4, 59, 33, 1);
922      let ret = BrotliReadConstantNBits(&mut bit_reader, 4, &data[..]);
923      assert_eq!(ret, 0x1);
924      assert_eq!(consumed(&bit_reader), 7);
925      assert_eq!(bit_reader.avail_in, 26);
926      assert_eq!(bit_reader.next_in, 8);
927    }
928    {
929      let data: [u8; 67] = [0xf0, 0x0d, 0x7e, 0x18, 0x70, 0x1c, 0x18, 0x57, 0xbd, 0x73, 0x47,
930                            0xc1, 0xb4, 0xf7, 0xe2, 0xbe, 0x17, 0x6e, 0x26, 0x01, 0xb2, 0xd5,
931                            0x55, 0xd8, 0x68, 0x1b, 0xc2, 0x87, 0xb4, 0xb1, 0xd9, 0x42, 0xac,
932                            0x0d, 0x67, 0xb1, 0x93, 0x54, 0x49, 0xa4, 0x69, 0xf8, 0x16, 0x0e,
933                            0x61, 0xb3, 0xdb, 0x98, 0xbb, 0xeb, 0xfa, 0xcb, 0x14, 0xcd, 0x68,
934                            0x77, 0xa1, 0x33, 0x6c, 0x49, 0xfa, 0x35, 0xbb, 0xeb, 0xee, 0x7b, 0xae];
935      let mut bit_reader = old_layout(0x655b1fe0dd6f1e78, 63, 65, 2);
936      let ret = BrotliGet16BitsUnmasked(&mut bit_reader, &data[..]);
937      assert_eq!(ret, 0x38e030fc);
938      assert_eq!(consumed(&bit_reader), 15);
939      assert_eq!(bit_reader.avail_in, 59);
940      assert_eq!(bit_reader.next_in, 8);
941    }
942  }
943}