- /* Number of entries in the decode table. */
- u32 table_num_entries = 1 << num_bits;
-
- /* Current position in the decode table. */
- u32 decode_table_pos = 0;
-
- /* Fill entries for codes short enough for a direct mapping. Here we
- * are taking advantage of the ordering of the codes, since they are for
- * a canonical Huffman tree. It must be the case that all the codes of
- * some length @code_length, zero-extended or one-extended, numerically
- * precede all the codes of length @code_length + 1. Furthermore, if we
- * have 2 symbols A and B, such that A is listed before B in the lens
- * array, and both symbols have the same code length, then we know that
- * the code for A numerically precedes the code for B.
- * */
- for (unsigned code_len = 1; code_len <= num_bits; code_len++) {
-
- /* Number of entries that a code of length @code_length would
- * need. */
- u32 code_num_entries = 1 << (num_bits - code_len);
-
-
- /* For each symbol of length @code_len, fill in its entries in
- * the decode table. */
- for (unsigned sym = 0; sym < num_syms; sym++) {
-
- if (lens[sym] != code_len)
- continue;
-
-
- /* Check for table overrun. This can only happen if the
- * given lengths do not correspond to a valid Huffman
- * tree. */
- if (decode_table_pos >= table_num_entries) {
- ERROR("Huffman decoding table overrun: "
- "pos = %u, num_entries = %u",
- decode_table_pos, table_num_entries);
- return 1;
- }
-
- /* Fill all possible lookups of this symbol with
- * the symbol itself. */
- for (unsigned i = 0; i < code_num_entries; i++)
- decode_table[decode_table_pos + i] = sym;
+ unsigned len_counts[max_codeword_len + 1];
+ u16 sorted_syms[num_syms];
+ unsigned offsets[max_codeword_len + 1];
+ const unsigned table_num_entries = 1 << table_bits;
+
+ /* accumulate lengths for codes */
+ for (unsigned i = 0; i <= max_codeword_len; i++)
+ len_counts[i] = 0;
+
+ for (unsigned sym = 0; sym < num_syms; sym++) {
+ wimlib_assert2(lens[sym] <= max_codeword_len);
+ len_counts[lens[sym]]++;
+ }