Skip to main content

brotli_decompressor/huffman/
mod.rs

1#![allow(non_snake_case)]
2#![allow(non_upper_case_globals)]
3mod tests;
4use ::core;
5use alloc;
6use alloc::Allocator;
7use alloc::SliceWrapper;
8use alloc::SliceWrapperMut;
9use core::convert::TryInto;
10use core::default::Default;
11pub const BROTLI_HUFFMAN_MAX_CODE_LENGTH: usize = 15;
12
13// For current format this constant equals to kNumInsertAndCopyCodes
14pub const BROTLI_HUFFMAN_MAX_CODE_LENGTHS_SIZE: usize = 704;
15
16// Outlined from `load_huffman_code` (no `#[inline]`) so rustc's MIR inliner
17// leaves `dst` as a pointer parameter until LLVM's CGSCC pass inlines
18// `copy_from_slice_impl` and folds the 4-byte `memcpy` into a single 32-bit
19// `load i32` + `store i32` before SROA sees the caller's stack slot.
20#[cfg(not(target_pointer_width = "64"))]
21fn load_huffman_code_into(dst: &mut [HuffmanCode; 1], table: &[HuffmanCode], idx: usize) {
22  match table.get(idx..idx + 1) {
23    Some(sub) => dst.clone_from_slice(sub),
24    None => debug_assert!(false, "Huffman table index {} out of range", idx),
25  }
26}
27
28#[inline(always)]
29pub fn load_huffman_code(table: &[HuffmanCode], idx: usize) -> HuffmanCode {
30  #[cfg(target_pointer_width = "64")]
31  {
32    fast!((table)[idx])
33  }
34  #[cfg(not(target_pointer_width = "64"))]
35  {
36    // Table builders fill every entry a valid code can reach, so the fallback
37    // is unreachable; it avoids a panic path in the hot loop.
38    let mut slot = [HuffmanCode { value: 0, bits: 0 }];
39    load_huffman_code_into(&mut slot, table, idx);
40    slot[0]
41  }
42}
43
44// Huffman table lookup.  A slice is bounds checked.  A fixed window clamps the
45// index to its last entry instead, which the compiler can see is in bounds, so
46// the hot decode loops pay no check: root lookups are below 256 already, and
47// second-level ones cost a conditional move.  A window holds a whole tree when
48// it is BrotliHuffmanMaxTableSize long, so a valid index is never clamped.
49pub trait HuffmanTable {
50  fn entry(&self, index: usize) -> HuffmanCode;
51}
52
53impl HuffmanTable for [HuffmanCode] {
54  #[inline(always)]
55  fn entry(&self, index: usize) -> HuffmanCode {
56    load_huffman_code(self, index)
57  }
58}
59
60// Window sizes for the literal and insert-and-copy trees, the ones decoded
61// several times per command: the largest tables of their 256- and 704-symbol
62// alphabets.  HuffmanTreeGroupDecode reserves BrotliHuffmanMaxTableSize of
63// the group's alphabet past every tree, so deriving the windows from the same
64// function keeps that room and the windows equal.  DISTANCE_ROOT_WINDOW covers
65// the 256-entry 8-bit root table of a distance tree.
66pub const LITERAL_TABLE_WINDOW: usize = BrotliHuffmanMaxTableSize(256);
67pub const INSERT_COPY_TABLE_WINDOW: usize = BrotliHuffmanMaxTableSize(704);
68pub const DISTANCE_ROOT_WINDOW: usize = 256;
69
70static EMPTY_TABLE: [HuffmanCode; INSERT_COPY_TABLE_WINDOW] =
71  [HuffmanCode { value: 0, bits: 0 }; INSERT_COPY_TABLE_WINDOW];
72
73// A fixed window type, cut out of a table group's codes by table_window.
74pub trait TableWindow: HuffmanTable {
75  fn window(codes: &[HuffmanCode], offset: Option<usize>) -> &Self;
76}
77
78// One impl per window size rather than over [HuffmanCode; N]: const generics
79// need Rust 1.51, and these three sizes are the only ones.
80macro_rules! fixed_table_window {
81  ($n:expr) => {
82    impl HuffmanTable for [HuffmanCode; $n] {
83      #[inline(always)]
84      fn entry(&self, index: usize) -> HuffmanCode {
85        // A valid table never reaches the clamp; it only keeps the lookup
86        // free of a bounds check.
87        debug_assert!(index < $n, "Huffman table index {} in a {}-entry window", index, $n);
88        load_huffman_code(self, core::cmp::min(index, $n - 1))
89      }
90    }
91
92    impl TableWindow for [HuffmanCode; $n] {
93      #[inline(always)]
94      fn window(codes: &[HuffmanCode], offset: Option<usize>) -> &Self {
95        let window = offset.and_then(|off| codes.get(off..).and_then(|s| s.get(..$n)));
96        debug_assert!(offset.is_none() || offset == Some(u32::MAX as usize) || window.is_some(),
97                      "no {}-entry window at offset {:?} of {} codes", $n, offset, codes.len());
98        match window {
99          Some(w) => w.try_into().unwrap(),
100          None => (&EMPTY_TABLE[..$n]).try_into().unwrap(),
101        }
102      }
103    }
104  };
105}
106fixed_table_window!(LITERAL_TABLE_WINDOW);
107fixed_table_window!(INSERT_COPY_TABLE_WINDOW);
108fixed_table_window!(DISTANCE_ROOT_WINDOW);
109
110// Upper bound on the table BrotliBuildHuffmanTable produces for an alphabet of
111// `alphabet_size_limit` symbols: a 256-entry root table plus at most
112// 4 + 7 + 15 + 31 + 63 second-level entries, as the C decoder computes it.
113// For the largest alphabet (704 insert-and-copy codes) it equals
114// INSERT_COPY_TABLE_WINDOW.
115pub const fn BrotliHuffmanMaxTableSize(alphabet_size_limit: u16) -> usize {
116  alphabet_size_limit as usize + 376
117}
118pub const BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH: u32 = 5;
119
120// Largest table (root table plus second-level tables) for a complete prefix
121// code over at most N symbols, with root bits 8 and code lengths up to 15, as
122// in c/dec/huffman.h. Block type codes have up to 258 symbols, block length
123// codes 26 and context map codes 272.
124pub const BROTLI_HUFFMAN_MAX_SIZE_26: u32 = 396;
125pub const BROTLI_HUFFMAN_MAX_SIZE_258: u32 = 632;
126pub const BROTLI_HUFFMAN_MAX_SIZE_272: u32 = 646;
127
128// No fixed table size exceeds INSERT_COPY_TABLE_WINDOW, which the no_std
129// brotli_decode sizes its table storage by.  Each line fails to compile, as an
130// array length mismatch, if one does (assert! in a const needs Rust 1.57).
131const _: [(); 1] = [(); (LITERAL_TABLE_WINDOW <= INSERT_COPY_TABLE_WINDOW) as usize];
132const _: [(); 1] = [(); (DISTANCE_ROOT_WINDOW <= INSERT_COPY_TABLE_WINDOW) as usize];
133const _: [(); 1] = [(); (BROTLI_HUFFMAN_MAX_SIZE_26 as usize <= INSERT_COPY_TABLE_WINDOW) as usize];
134const _: [(); 1] = [(); (BROTLI_HUFFMAN_MAX_SIZE_258 as usize <= INSERT_COPY_TABLE_WINDOW) as usize];
135const _: [(); 1] = [(); (BROTLI_HUFFMAN_MAX_SIZE_272 as usize <= INSERT_COPY_TABLE_WINDOW) as usize];
136
137// 4-byte aligned so that a copy, and the fill of a new table, is one 32-bit
138// access rather than separate 16- and 8-bit ones. On 64-bit targets `value` is
139// kept at offset 0 and `bits` at offset 2 (which produces faster codegen on
140// x86-64 and aarch64). On 32-bit targets `bits` is placed in the low byte and
141// `value` in the upper 16 bits (matching C's `BROTLI_HUFFMAN_CODE_FAST_LOAD`)
142// so a single 32-bit load extracts `bits` via `uxtb`/`uxtab` and `value` via
143// `lsr #16`. Keep `HuffmanCodeStruct` in `c/brotli/decode.h` in sync.
144#[repr(C, align(4))]
145#[derive(PartialEq, Copy, Clone, Debug)]
146pub struct HuffmanCode {
147  #[cfg(target_pointer_width = "64")]
148  pub value: u16, // symbol value or table offset
149  pub bits: u8, // number of bits used for this symbol
150  #[cfg(not(target_pointer_width = "64"))]
151  pub value: u16, // symbol value or table offset
152}
153
154impl HuffmanCode {
155  pub fn eq(&self, other: &Self) -> bool {
156    self.value == other.value && self.bits == other.bits
157  }
158}
159
160impl Default for HuffmanCode {
161  fn default() -> Self {
162    HuffmanCode {
163      value: 0,
164      bits: 0,
165    }
166  }
167}
168
169// Contains a collection of Huffman trees with the same alphabet size.
170pub struct HuffmanTreeGroup<Alloc32: Allocator<u32>, AllocHC: Allocator<HuffmanCode>> {
171  pub htrees: Alloc32::AllocatedMemory,
172  pub codes: AllocHC::AllocatedMemory,
173  pub alphabet_size: u16,
174  pub max_symbol: u16,
175  pub num_htrees: u16,
176}
177
178impl<AllocU32 : alloc::Allocator<u32>,
179     AllocHC : alloc::Allocator<HuffmanCode> > HuffmanTreeGroup<AllocU32, AllocHC> {
180    // Buffers from a previous metablock are kept when they are large enough.
181    // Every table entry a valid stream can reach is written by the table
182    // builder before it is read, and trees past num_htrees are never looked
183    // up, so stale contents are not observable.
184    pub fn init(self : &mut Self, alloc_u32 : &mut AllocU32, alloc_hc : &mut AllocHC,
185                alphabet_size : u16, max_symbol: u16, ntrees : u16) {
186        self.alphabet_size = alphabet_size;
187        self.max_symbol = max_symbol;
188        self.num_htrees = ntrees;
189        let nt = ntrees as usize;
190        // Keep `htrees` when large enough; mark entries past `nt` with `u32::MAX`
191        // so no lookup can reach a tree of an earlier metablock.
192        if self.htrees.slice().len() < nt {
193            alloc_u32.free_cell(core::mem::take(&mut self.htrees));
194            self.htrees = alloc_u32.alloc_cell(nt);
195        } else if self.htrees.slice().len() > nt {
196            for slot in self.htrees.slice_mut()[nt..].iter_mut() {
197                *slot = u32::MAX;
198            }
199        }
200        let codes_len = self.initial_codes_len();
201        if self.codes.slice().len() < codes_len {
202            alloc_hc.free_cell(core::mem::take(&mut self.codes));
203            self.codes = alloc_hc.alloc_cell(codes_len);
204        }
205    }
206
207    pub fn needs_codes_growth(&self, alphabet_size: u16, max_symbol: u16, ntrees: u16) -> bool {
208        let max = BrotliHuffmanMaxTableSize(alphabet_size.max(max_symbol));
209        let typical = 256 + (max - 256) / 4;
210        let codes_len = max + (ntrees as usize).saturating_sub(1) * typical;
211        let cur_len = self.codes.slice().len();
212        cur_len != 0 && cur_len < codes_len
213    }
214
215    pub fn max_table_size(&self) -> usize {
216        BrotliHuffmanMaxTableSize(self.alphabet_size.max(self.max_symbol))
217    }
218
219    // Room for one worst-case table and typical tables for the rest.  Real
220    // tables are rarely much over the 256-entry root table, and allocators
221    // must initialize what they return, so sizing every tree for the worst
222    // case cost more than decoding small streams did.  ensure_codes_room
223    // grows the buffer when a stream needs more.
224    fn initial_codes_len(&self) -> usize {
225        let max = self.max_table_size();
226        let typical = 256 + (max - 256) / 4;
227        max + (self.num_htrees as usize).saturating_sub(1) * typical
228    }
229}
230
231// The window of `codes` starting at `offset`; HuffmanTreeGroupDecode makes
232// room for it when it builds the tree there.  An all-zero table if there is no
233// such tree.
234#[inline(always)]
235pub fn table_window<T: TableWindow>(codes: &[HuffmanCode], offset: Option<usize>) -> &T {
236  T::window(codes, offset)
237}
238
239// Makes room for one more worst-case table at `offset` in `codes`, keeping the
240// tables already built below `offset`.  False if the allocation fails.
241pub fn ensure_codes_room<AllocHC: Allocator<HuffmanCode>>(codes: &mut AllocHC::AllocatedMemory,
242                                                          alloc_hc: &mut AllocHC,
243                                                          offset: usize, max_table_size: usize)
244                                                          -> bool {
245    let needed = offset + max_table_size;
246    let len = codes.slice().len();
247    if len >= needed {
248        return true;
249    }
250    let mut grown = alloc_hc.alloc_cell(core::cmp::max(needed, len + len / 2));
251    if grown.slice().len() < needed {
252        return false;
253    }
254    grown.slice_mut()[..offset].copy_from_slice(&codes.slice()[..offset]);
255    alloc_hc.free_cell(core::mem::replace(codes, grown));
256    true
257}
258
259impl<AllocU32 : alloc::Allocator<u32>,
260     AllocHC : alloc::Allocator<HuffmanCode> > HuffmanTreeGroup<AllocU32, AllocHC> {
261
262//  pub fn get_tree_mut<'a>(self :&'a mut Self, index : u32, mut tree_out : &'a mut [HuffmanCode]) {
263//        let start : usize = fast!((self.htrees)[index as usize]) as usize;
264//        let _ = core::mem::replace(&mut tree_out, fast_mut!((self.codes.slice_mut())[start;]));
265//    }
266//    pub fn get_tree<'a>(self :&'a Self, index : u32, mut tree_out : &'a [HuffmanCode]) {
267//        let start : usize = fast!((self.htrees)[index as usize]) as usize;
268//        let _ = core::mem::replace(&mut tree_out, fast_slice!((self.codes)[start;]));
269//    }
270    #[allow(dead_code)]
271    pub fn get_tree_mut(&mut self, index : u32) -> &mut [HuffmanCode] {
272        let start : usize = fast_slice!((self.htrees)[index as usize]) as usize;
273        fast_mut!((self.codes.slice_mut())[start;])
274    }
275    #[allow(dead_code)]
276    pub fn get_tree(&self, index : u32) -> &[HuffmanCode] {
277        let start : usize = fast_slice!((self.htrees)[index as usize]) as usize;
278        fast_slice!((self.codes)[start;])
279    }
280    pub fn reset(self : &mut Self, alloc_u32 : &mut AllocU32, alloc_hc : &mut AllocHC) {
281        alloc_u32.free_cell(core::mem::replace(&mut self.htrees,
282                                               AllocU32::AllocatedMemory::default()));
283        alloc_hc.free_cell(core::mem::replace(&mut self.codes,
284                                              AllocHC::AllocatedMemory::default()));
285
286// for mut iter in self.htrees[0..self.num_htrees as usize].iter_mut() {
287//    if iter.slice().len() > 0 {
288//        alloc_hc.free_cell(core::mem::replace(&mut iter,
289//                                              AllocHC::AllocatedMemory::default()));
290//    }
291// }
292
293    }
294    pub fn build_hgroup_cache(&self) -> [&[HuffmanCode]; 256] {
295      let mut ret : [&[HuffmanCode]; 256] = [&[]; 256];
296      self.fill_hgroup_cache(&mut ret);
297      ret
298    }
299    // As build_hgroup_cache, into an array the caller provides: returning the
300    // 4 KiB array by value costs a copy per call, and the decoder builds three
301    // of them each time it resumes decoding commands.
302    #[inline(always)]
303    pub(crate) fn fill_hgroup_cache<'a>(&'a self, cache: &mut [&'a [HuffmanCode]; 256]) {
304      for (entry, htree) in cache.iter_mut().zip(self.htrees.slice().iter()) {
305          *entry = fast_slice!((&self.codes)[*htree as usize ; ]);
306      }
307    }
308}
309
310impl<AllocU32 : alloc::Allocator<u32>,
311     AllocHC : alloc::Allocator<HuffmanCode> > Default for HuffmanTreeGroup<AllocU32, AllocHC> {
312    fn default() -> Self {
313        HuffmanTreeGroup::<AllocU32, AllocHC> {
314          htrees : AllocU32::AllocatedMemory::default(),
315          codes : AllocHC::AllocatedMemory::default(),
316          max_symbol: 0,
317          alphabet_size : 0,
318          num_htrees : 0,
319        }
320    }
321}
322
323
324
325const BROTLI_REVERSE_BITS_MAX: usize = 8;
326
327const BROTLI_REVERSE_BITS_BASE: u8 = 0;
328
329const BROTLI_REVERSE_BITS_LOWEST: u32 =
330  (1u32 << (BROTLI_REVERSE_BITS_MAX as u32 - 1 + BROTLI_REVERSE_BITS_BASE as u32));
331
332// Callers narrow their key with `as u8`, which is sound only because this port
333// uses BROTLI_REVERSE_BITS_BASE == 0: keys accumulate from
334// BROTLI_REVERSE_BITS_LOWEST and so stay under
335// 1 << (BROTLI_REVERSE_BITS_MAX + BROTLI_REVERSE_BITS_BASE).
336//
337// That is not a spec guarantee. The reference implementation sets
338// BROTLI_REVERSE_BITS_BASE = (sizeof(brotli_reg_t) << 3) - BROTLI_REVERSE_BITS_MAX
339// (56 on 64-bit) wherever BROTLI_RBIT is available, which puts the key in the
340// high bits of a full register and makes it far larger than a u8. If that is
341// ever mirrored here the narrowing below would silently truncate, so fail the
342// build instead.
343const _REVERSE_BITS_KEYS_FIT_IN_U8: [(); 256] =
344  [(); 1usize << (BROTLI_REVERSE_BITS_MAX + BROTLI_REVERSE_BITS_BASE as usize)];
345
346// Returns reverse(num >> BROTLI_REVERSE_BITS_BASE, BROTLI_REVERSE_BITS_MAX),
347// where reverse(value, len) is the bit-wise reversal of the len least
348// significant bits of value.
349//
350// Callers narrow to u8, which is sound because BrotliBuildHuffmanTable rejects
351// root_bits outside [1, BROTLI_REVERSE_BITS_MAX] up front and
352// BrotliBuildCodeLengthsHuffmanTable requires
353// BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH <= BROTLI_REVERSE_BITS_MAX, which
354// bounds every key by 1 << 8.
355#[inline(always)]
356fn BrotliReverseBits(num: u8) -> u32 {
357  num.reverse_bits() as u32
358}
359
360// Stores `code` in `table[offset]`, `table[offset + step]`, ...,
361// `table[offset + end - step]`.
362// Assumes that `end` is a positive integer multiple of `step`.
363//
364// `BrotliBuildCodeLengthsHuffmanTable` and `BrotliBuildHuffmanTable` always
365// pass `step = 1 << bits` and `end = 1 << table_bits` with `1 <= bits <= table_bits`,
366// so they call `replicate_value_pow2` directly to avoid per-symbol sign and
367// divisibility checks. `ReplicateValue` retains the full input validation for
368// white-box guard tests.
369#[cfg(test)]
370#[inline(always)]
371fn ReplicateValue(table: &mut [HuffmanCode],
372                  offset: u32,
373                  step: i32,
374                  end: i32,
375                  code: HuffmanCode) -> bool {
376  if step <= 0 || end <= 0 {
377    return false;
378  }
379  let step_u = step as usize;
380  let end_u = end as usize;
381  if if (step_u & (step_u - 1)) == 0 {
382    (end_u & (step_u - 1)) != 0
383  } else {
384    end_u % step_u != 0
385  } {
386    return false;
387  }
388  replicate_value_pow2(table, offset as usize, step_u, end_u, code)
389}
390
391// Do not mark `#[inline]` or `#[inline(always)]`: if rustc's MIR inliner
392// inlines this before LLVM IR lowering, `*slot = HuffmanCode::new(...)` is
393// lowered as three separate field stores (`bits`, `pad`, `value`). Leaving
394// inlining to LLVM's CGSCC pass coerces the 4-byte `#[repr(C, align(4))]`
395// `HuffmanCode` argument to `i32` on 32-bit targets and emits a single 32-bit
396// `str.w` per table slot.
397// Two-step slicing (`get_mut(offset..)` then `get_mut(..=last)`) uses
398// `RangeToInclusive` so the length `last + 1` is known non-zero and avoids
399// `RangeInclusive`'s extra overflow/empty-slice checks.
400fn replicate_value_pow2(table: &mut [HuffmanCode],
401                        offset: usize,
402                        step: usize,
403                        end: usize,
404                        code: HuffmanCode) -> bool {
405  debug_assert!(step > 0 && end >= step && (end % step) == 0);
406  let last = end.wrapping_sub(step);
407  let slice = match table.get_mut(offset..) {
408    Some(s) => match s.get_mut(..=last) {
409      Some(s) => s,
410      None => return false,
411    },
412    None => return false,
413  };
414  let mut pos = 0;
415  while let Some(slot) = slice.get_mut(pos) {
416    *slot = code;
417    pos += step;
418  }
419  true
420}
421
422// Returns the table width of the next 2nd level table. count is the histogram
423// of bit lengths for the remaining symbols, len is the code length of the next
424// processed symbol.
425//
426// The scan runs len up to BROTLI_HUFFMAN_MAX_CODE_LENGTH, which can be past the
427// caller's max_length, so `count` may run out underneath it.
428#[inline(always)]
429fn NextTableBitSize(count: &[u16], mut len: i32, root_bits: i32) -> Option<i32> {
430  debug_assert!(len > root_bits);
431  let mut left: i32 = 1i32 << (len - root_bits);
432  while len < BROTLI_HUFFMAN_MAX_CODE_LENGTH as i32 {
433    let c = match count.get(len as usize) {
434      Some(&c) => c,
435      None => return None,
436    };
437    left -= i32::from(c);
438    if left <= 0 {
439      break;
440    }
441    len += 1;
442    left <<= 1;
443  }
444  Some(len - root_bits)
445}
446
447// `symbol_lists` is indexed relative to `symbol_lists_offset`, and the relative
448// index is deliberately negative for the per-length list heads (the reference
449// implementation indexes backwards off a raw pointer here). Wrapping addition
450// in `isize` cast to `usize` maps negative out-of-bounds indices above
451// `isize::MAX as usize`, so a single `symbol_lists.get(index)` check covers
452// both directions without 64-bit arithmetic on 32-bit targets.
453#[inline(always)]
454fn symbol_list_value(symbol_lists: &[u16],
455                     symbol_lists_offset: usize,
456                     relative_index: i32) -> Option<u16> {
457  let index = (symbol_lists_offset as isize).wrapping_add(relative_index as isize) as usize;
458  symbol_lists.get(index).copied()
459}
460
461
462pub fn BrotliBuildCodeLengthsHuffmanTable(mut table: &mut [HuffmanCode],
463                                          code_lengths: &[u8],
464                                          count: &[u16]) -> bool {
465  let mut sorted: [i32; 18] = fast_uninitialized![18];     /* symbols sorted by code length */
466  // offsets in sorted table for each length
467  let mut offset: [i32; (BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH + 1) as usize] =
468    fast_uninitialized![(BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH + 1) as usize];
469  const table_size: i32 = 1 << BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH;
470  if BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH as usize > BROTLI_REVERSE_BITS_MAX ||
471     table.len() < table_size as usize ||
472     code_lengths.len() < sorted.len() ||
473     count.len() <= BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH as usize {
474    return false;
475  }
476  let mut actual_count =
477    [0u16; (BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH + 1) as usize];
478  for code_length in code_lengths.iter().take(sorted.len()) {
479    let code_length_index = *code_length as usize;
480    if code_length_index >= actual_count.len() {
481      return false;
482    }
483    actual_count[code_length_index] += 1;
484  }
485  // Avoid a `slice != slice` comparison, which lowers to a `bcmp` call for the
486  // 5-element (10-byte) histogram check on every Huffman table build.
487  let mut count_diff = 0u16;
488  for (a, c) in actual_count[1..].iter().zip(count[1..actual_count.len()].iter()) {
489    count_diff |= *a ^ *c;
490  }
491  if count_diff != 0 {
492    return false;
493  }
494
495  // generate offsets into sorted symbol table by code length
496  let mut symbol: i32 = -1;         /* symbol index in original or sorted table */
497  let mut bits: i32 = 1;
498  for _ in 0..BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH {
499    symbol += fast!((count)[bits as usize]) as i32;
500    fast_mut!((offset)[bits as usize]) = symbol;
501    bits += 1;
502  }
503  // Symbols with code length 0 are placed after all other symbols.
504  fast_mut!((offset)[0]) = 17;
505
506  // sort symbols by length, by symbol order within each length
507  symbol = 18;
508  loop {
509    for _ in 0..6 {
510      symbol -= 1;
511      let index = fast!((offset)[fast_inner!((code_lengths)[symbol as usize]) as usize]);
512      fast_mut!((offset)[fast_inner!((code_lengths)[symbol as usize]) as usize]) -= 1;
513      fast_mut!((sorted)[index as usize]) = symbol;
514    }
515    if symbol == 0 {
516      break;
517    }
518  }
519
520  // Special case: all symbols but one have 0 code length.
521  if fast!((offset)[0]) == 0 {
522    let code: HuffmanCode = HuffmanCode {
523      bits: 0,
524      value: fast!((sorted)[0]) as u16,
525    };
526    for val in fast_mut!((table)[0 ; table_size as usize]).iter_mut() {
527      *val = code;
528    }
529    return true;
530  }
531
532  // fill in table
533  //
534  // The caller only gets here with a complete prefix code (it rejects
535  // space != 0), so the keys below sum to exactly 1 << BROTLI_REVERSE_BITS_MAX
536  // and the last one used is 0xFF: `key as u8` cannot truncate.
537  let mut key: u32 = 0; /* prefix code */
538  let mut key_step: u32 = BROTLI_REVERSE_BITS_LOWEST; /* prefix code addend */
539  symbol = 0;
540  bits = 1;
541  let mut step: i32 = 2;
542  loop {
543    let mut code: HuffmanCode = HuffmanCode {
544      bits: (bits as u8),
545      value: 0,
546    };
547    let mut bits_count: i32 = fast!((count)[bits as usize]) as i32;
548
549    while bits_count != 0 {
550      code.value = fast!((sorted)[symbol as usize]) as u16;
551      symbol += 1;
552      let reversed_key = BrotliReverseBits(key as u8) as usize;
553      // Cannot fail while `table_size` is 32: `step` is `1 << bits` and
554      // `reversed_key < 1 << bits`, so the last index written is below `table_size`.
555      if !replicate_value_pow2(&mut table, reversed_key, step as usize, table_size as usize, code) {
556        return false;
557      }
558      key += key_step;
559      bits_count -= 1;
560    }
561    step <<= 1;
562    key_step >>= 1;
563    bits += 1;
564    if !(bits <= BROTLI_HUFFMAN_MAX_CODE_LENGTH_CODE_LENGTH as i32) {
565      break;
566    }
567  }
568  true
569}
570
571pub fn BrotliBuildHuffmanTable(mut root_table: &mut [HuffmanCode],
572                               root_bits: i32,
573                               symbol_lists: &[u16],
574                               symbol_lists_offset: usize, /* need negative-index to symbol_lists */
575                               count: &mut [u16])
576                               -> u32 {
577  let mut code: HuffmanCode = HuffmanCode {
578    bits: 0,
579    value: 0,
580  };       /* current table entry */
581  let mut max_length: i32 = -1;
582
583  // Entry preconditions. The body's index bounds all derive from these plus the
584  // max_length check below: root_bits <= 8 keeps every prefix key under 1 << 8,
585  // and max_length < count.len() keeps every code-length index in range.
586  if root_bits <= 0 ||
587     root_bits as usize > BROTLI_REVERSE_BITS_MAX ||
588     BROTLI_HUFFMAN_MAX_CODE_LENGTH as i32 - root_bits >
589       BROTLI_REVERSE_BITS_MAX as i32 ||
590     symbol_lists_offset >= symbol_lists.len() {
591    return 0;
592  }
593
594  while match symbol_list_value(symbol_lists, symbol_lists_offset, max_length) {
595    Some(value) => value == 0xFFFF,
596    None => return 0,
597  } {
598    max_length -= 1;
599  }
600  max_length += BROTLI_HUFFMAN_MAX_CODE_LENGTH as i32 + 1;
601  // The scan above can walk off the front of symbol_lists' head region, which is
602  // the one way max_length ends up negative. Callers may pass a count histogram
603  // only as long as the code lengths they used, hence the second bound.
604  if max_length < 0 || max_length as usize >= count.len() {
605    return 0;
606  }
607  debug_assert!(max_length <= BROTLI_HUFFMAN_MAX_CODE_LENGTH as i32);
608
609  let mut table_free_offset: u32 = 0;
610  let mut table_bits: i32 = root_bits;      /* key length of current table */
611  // root_bits <= 8, so every `1 << table_bits` below is at most 1 << 8.
612  let mut table_size: i32 = 1 << table_bits;/* size of current table */
613  let mut total_size: i32 = table_size;     /* sum of root table size and 2nd level table sizes */
614
615  // fill in root table
616  // let's reduce the table size to a smaller size if possible, and
617  // create the repetitions by memcpy if possible in the coming loop
618  if table_bits > max_length {
619    table_bits = max_length;
620    table_size = 1 << table_bits;
621  }
622  let mut key: u32 = 0; /* prefix code */
623  let mut key_step: u32 = BROTLI_REVERSE_BITS_LOWEST; /* prefix code addend */
624  let mut bits: i32 = 1;
625  let mut step: i32 = 2; /* step size to replicate values in current table */
626  loop {
627    code.bits = bits as u8;
628    let mut symbol: i32 = bits - (BROTLI_HUFFMAN_MAX_CODE_LENGTH as i32 + 1);
629    let mut bits_count: i32 = fast!((count)[bits as usize]) as i32;
630    while bits_count != 0 {
631      symbol = match symbol_list_value(symbol_lists, symbol_lists_offset, symbol) {
632        Some(symbol) => symbol as i32,
633        None => return 0,
634      };
635      code.value = symbol as u16;
636      let reversed_key = BrotliReverseBits(key as u8);
637      if !replicate_value_pow2(
638        &mut root_table,
639        (table_free_offset + reversed_key) as usize,
640        step as usize,
641        table_size as usize,
642        code,
643      ) {
644        return 0;
645      }
646      key += key_step;
647      bits_count -= 1;
648    }
649    step <<= 1;
650    key_step >>= 1;
651    bits += 1;
652    if !(bits <= table_bits) {
653      break;
654    }
655  }
656
657  // if root_bits != table_bits we only created one fraction of the
658  // table, and we need to replicate it now.
659  while total_size != table_size {
660    // Doubling the filled prefix in place; total_size bounds the loop.
661    let base = table_free_offset as usize;
662    let size = table_size as usize;
663    if base + 2 * size > root_table.len() {
664      return 0;
665    }
666    let (head, tail) = root_table.split_at_mut(base + size);
667    tail[..size].clone_from_slice(&head[base..]);
668    table_size <<= 1;
669  }
670
671  // fill in 2nd level tables and add pointers to root table
672  key_step = BROTLI_REVERSE_BITS_LOWEST >> (root_bits - 1);
673  let mut sub_key: u32 = BROTLI_REVERSE_BITS_LOWEST << 1;       /* 2nd level table prefix code */
674  let mut sub_key_step: u32 = BROTLI_REVERSE_BITS_LOWEST;   /* 2nd level table prefix code addend */
675
676  step = 2;
677
678  let mut len: i32 = root_bits + 1; /* current code length */
679  while len <= max_length {
680    let mut symbol: i32 = len - (BROTLI_HUFFMAN_MAX_CODE_LENGTH as i32 + 1);
681    while fast!((count)[len as usize]) != 0 {
682      if sub_key == (BROTLI_REVERSE_BITS_LOWEST << 1u32) {
683        table_free_offset += table_size as u32;
684        table_bits = match NextTableBitSize(count, len, root_bits) {
685          Some(table_bits) => table_bits,
686          None => return 0,
687        };
688        table_size = 1 << table_bits;
689        total_size += table_size;
690        sub_key = BrotliReverseBits(key as u8);
691        key += key_step;
692        // Checked rather than assumed: this is narrowed into the u16
693        // HuffmanCode::value, and sub_key then indexes a write.
694        let table_value = match (table_free_offset as usize).checked_sub(sub_key as usize) {
695          Some(table_value) if table_value <= u16::MAX as usize => table_value as u16,
696          _ => return 0,
697        };
698        match root_table.get_mut(sub_key as usize) {
699          Some(entry) => {
700            entry.bits = (table_bits + root_bits) as u8;
701            entry.value = table_value;
702          },
703          None => return 0,
704        }
705        sub_key = 0;
706      }
707      code.bits = (len - root_bits) as u8;
708      symbol = match symbol_list_value(symbol_lists, symbol_lists_offset, symbol) {
709        Some(symbol) => symbol as i32,
710        None => return 0,
711      };
712      code.value = symbol as u16;
713      let reversed_sub_key = BrotliReverseBits(sub_key as u8);
714      if !replicate_value_pow2(
715        &mut root_table,
716        (table_free_offset + reversed_sub_key) as usize,
717        step as usize,
718        table_size as usize,
719        code,
720      ) {
721        return 0;
722      }
723      sub_key += sub_key_step;
724      // len <= max_length < count.len(), and the loop condition just read a
725      // nonzero count[len].
726      fast_mut!((count)[len as usize]) -= 1;
727    }
728    step <<= 1;
729    sub_key_step >>= 1;
730    len += 1
731  }
732  total_size as u32
733}
734
735
736
737pub fn BrotliBuildSimpleHuffmanTable(table: &mut [HuffmanCode],
738                                     root_bits: i32,
739                                     val: &[u16],
740                                     num_symbols: u32)
741                                     -> u32 {
742  if root_bits <= 0 || root_bits >= 32 {
743    return 0;
744  }
745  // num_symbols is the raw 2-bit field (plus one extra bit when it reads 3), so
746  // 0..=4 are the only encodable values. This match rejects anything larger,
747  // which is why the branch chain below needs no final catch-all.
748  let required_symbols = match num_symbols {
749    0 => 1,
750    1 => 2,
751    2 | 3 => 3,
752    4 => 4,
753    _ => return 0,
754  };
755  if val.len() < required_symbols {
756    return 0;
757  }
758  let mut table_size: u32;
759  // root_bits is in 1..32 by the check above, so the shift is in range.
760  let goal_size: u32 = 1u32 << root_bits;
761  if table.len() < goal_size as usize {
762    return 0;
763  }
764  let table = &mut table[..goal_size as usize];
765  if num_symbols == 0 {
766    let code = HuffmanCode {
767      bits: 0,
768      value: fast!((val)[0]),
769    };
770    for entry in table.iter_mut() {
771      *entry = code;
772    }
773    return goal_size;
774  } else if num_symbols == 1 {
775    fast_mut!((table)[0]).bits = 1;
776    fast_mut!((table)[1]).bits = 1;
777    if fast!((val)[1]) > fast!((val)[0]) {
778      fast_mut!((table)[0]).value = fast!((val)[0]);
779      fast_mut!((table)[1]).value = fast!((val)[1]);
780    } else {
781      fast_mut!((table)[0]).value = fast!((val)[1]);
782      fast_mut!((table)[1]).value = fast!((val)[0]);
783    }
784    table_size = 2;
785  } else if num_symbols == 2 {
786    fast_mut!((table)[0]).bits = 1;
787    fast_mut!((table)[0]).value = fast!((val)[0]);
788    fast_mut!((table)[2]).bits = 1;
789    fast_mut!((table)[2]).value = fast!((val)[0]);
790    if fast!((val)[2]) > fast!((val)[1]) {
791      fast_mut!((table)[1]).value = fast!((val)[1]);
792      fast_mut!((table)[3]).value = fast!((val)[2]);
793    } else {
794      fast_mut!((table)[1]).value = fast!((val)[2]);
795      fast_mut!((table)[3]).value = fast!((val)[1]);
796    }
797    fast_mut!((table)[1]).bits = 2;
798    fast_mut!((table)[3]).bits = 2;
799    table_size = 4;
800  } else if num_symbols == 3 {
801    let last: u16 = if val.len() > 3 { fast!((val)[3]) } else { 65535 };
802    let mut mval: [u16; 4] = [fast!((val)[0]), fast!((val)[1]), fast!((val)[2]), last];
803    for i in 0..3 {
804      for k in i + 1..4 {
805        if mval[k] < mval[i] {
806          mval.swap(k, i);
807        }
808      }
809    }
810    for i in 0..4 {
811      fast_mut!((table)[i]).bits = 2;
812    }
813    fast_mut!((table)[0]).value = mval[0];
814    fast_mut!((table)[2]).value = mval[1];
815    fast_mut!((table)[1]).value = mval[2];
816    fast_mut!((table)[3]).value = mval[3];
817    table_size = 4;
818  } else {
819    debug_assert_eq!(num_symbols, 4);
820    let mut mval: [u16; 4] = [fast!((val)[0]), fast!((val)[1]), fast!((val)[2]), fast!((val)[3])];
821    if mval[3] < mval[2] {
822      mval.swap(3, 2)
823    }
824    for i in 0..7 {
825      fast_mut!((table)[i]).value = mval[0];
826      fast_mut!((table)[i]).bits = (1 + (i & 1)) as u8;
827    }
828    fast_mut!((table)[1]).value = mval[1];
829    fast_mut!((table)[3]).value = mval[2];
830    fast_mut!((table)[5]).value = mval[1];
831    fast_mut!((table)[7]).value = mval[3];
832    fast_mut!((table)[3]).bits = 3;
833    fast_mut!((table)[7]).bits = 3;
834    table_size = 8;
835  }
836  while table_size != goal_size {
837    let size = table_size as usize;
838    let (head, tail) = table.split_at_mut(size);
839    tail[..size].clone_from_slice(head);
840    table_size <<= 1;
841  }
842  goal_size
843}