1 /* enough.c -- determine the maximum size of inflate's Huffman code tables over
2 * all possible valid and complete Huffman codes, subject to a length limit.
3 * Copyright (C) 2007, 2008, 2012, 2018 Mark Adler
4 * Version 1.5 1 August 2018 Mark Adler
8 1.0 3 Jan 2007 First version (derived from codecount.c version 1.4)
9 1.1 4 Jan 2007 Use faster incremental table usage computation
10 Prune examine() search on previously visited states
11 1.2 5 Jan 2007 Comments clean up
12 As inflate does, decrease root for short codes
13 Refuse cases where inflate would increase root
14 1.3 17 Feb 2008 Add argument for initial root table size
15 Fix bug for initial root table size == max - 1
16 Use a macro to compute the history index
17 1.4 18 Aug 2012 Avoid shifts more than bits in type (caused endless loop!)
18 Clean up comparisons of different types
19 Clean up code indentation
20 1.5 1 Aug 2018 Clean up code style and formatting
24 Examine all possible Huffman codes for a given number of symbols and a
25 maximum code length in bits to determine the maximum table size for zlib's
26 inflate. Only complete Huffman codes are counted.
28 Two codes are considered distinct if the vectors of the number of codes per
29 length are not identical. So permutations of the symbol assignments result
30 in the same code for the counting, as do permutations of the assignments of
31 the bit values to the codes (i.e. only canonical codes are counted).
33 We build a code from shorter to longer lengths, determining how many symbols
34 are coded at each length. At each step, we have how many symbols remain to
35 be coded, what the last code length used was, and how many bit patterns of
36 that length remain unused. Then we add one to the code length and double the
37 number of unused patterns to graduate to the next code length. We then
38 assign all portions of the remaining symbols to that code length that
39 preserve the properties of a correct and eventually complete code. Those
40 properties are: we cannot use more bit patterns than are available; and when
41 all the symbols are used, there are exactly zero possible bit patterns
44 The inflate Huffman decoding algorithm uses two-level lookup tables for
45 speed. There is a single first-level table to decode codes up to root bits
46 in length (root == 9 in the current inflate implementation). The table has 1
47 << root entries and is indexed by the next root bits of input. Codes shorter
48 than root bits have replicated table entries, so that the correct entry is
49 pointed to regardless of the bits that follow the short code. If the code is
50 longer than root bits, then the table entry points to a second- level table.
51 The size of that table is determined by the longest code with that root-bit
52 prefix. If that longest code has length len, then the table has size 1 <<
53 (len - root), to index the remaining bits in that set of codes. Each
54 subsequent root-bit prefix then has its own sub-table. The total number of
55 table entries required by the code is calculated incrementally as the number
56 of codes at each bit length is populated. When all of the codes are shorter
57 than root bits, then root is reduced to the longest code length, resulting
58 in a single, smaller, one-level table.
60 The inflate algorithm also provides for small values of root (relative to
61 the log2 of the number of symbols), where the shortest code has more bits
62 than root. In that case, root is increased to the length of the shortest
63 code. This program, by design, does not handle that case, so it is verified
64 that the number of symbols is less than 2^(root + 1).
66 In order to speed up the examination (by about ten orders of magnitude for
67 the default arguments), the intermediate states in the build-up of a code
68 are remembered and previously visited branches are pruned. The memory
69 required for this will increase rapidly with the total number of symbols and
70 the maximum code length in bits. However this is a very small price to pay
73 First, all of the possible Huffman codes are counted, and reachable
74 intermediate states are noted by a non-zero count in a saved-results array.
75 Second, the intermediate states that lead to (root + 1) bit or longer codes
76 are used to look at all sub-codes from those junctures for their inflate
77 memory usage. (The amount of memory used is not affected by the number of
78 codes of root bits or less in length.) Third, the visited states in the
79 construction of those sub-codes and the associated calculation of the table
80 size is recalled in order to avoid recalculating from the same juncture.
81 Beginning the code examination at (root + 1) bit codes, which is enabled by
82 identifying the reachable nodes, accounts for about six of the orders of
83 magnitude of improvement for the default arguments. About another four
84 orders of magnitude come from not revisiting previous states. Out of
85 approximately 2x10^16 possible Huffman codes, only about 2x10^6 sub-codes
86 need to be examined to cover all of the possible table memory usage cases
87 for the default arguments of 286 symbols limited to 15-bit codes.
89 Note that an unsigned long long type is used for counting. It is quite easy
90 to exceed the capacity of an eight-byte integer with a large number of
91 symbols and a large maximum code length, so multiple-precision arithmetic
92 would need to replace the unsigned long long arithmetic in that case. This
93 program will abort if an overflow occurs. The big_t type identifies where
94 the counting takes place.
96 An unsigned long long type is also used for calculating the number of
97 possible codes remaining at the maximum length. This limits the maximum code
98 length to the number of bits in a long long minus the number of bits needed
99 to represent the symbols in a flat code. The code_t type identifies where
100 the bit pattern counting takes place.
110 // Special data types.
111 typedef unsigned long long big_t; // type for code counting
112 #define PRIbig "llu" // printf format for big_t
113 typedef unsigned long long code_t; // type for bit pattern counting
114 struct tab { // type for been here check
115 size_t len; // length of bit vector in char's
116 char *vec; // allocated bit vector
119 /* The array for saving results, num[], is indexed with this triplet:
121 syms: number of symbols remaining to code
122 left: number of available bit patterns at length len
123 len: number of bits in the codes currently being assigned
125 Those indices are constrained thusly when saving results:
127 syms: 3..totsym (totsym == total symbols to code)
128 left: 2..syms - 1, but only the evens (so syms == 8 -> 2, 4, 6)
129 len: 1..max - 1 (max == maximum code length in bits)
131 syms == 2 is not saved since that immediately leads to a single code. left
132 must be even, since it represents the number of available bit patterns at
133 the current length, which is double the number at the previous length. left
134 ends at syms-1 since left == syms immediately results in a single code.
135 (left > sym is not allowed since that would result in an incomplete code.)
136 len is less than max, since the code completes immediately when len == max.
138 The offset into the array is calculated for the three indices with the first
139 one (syms) being outermost, and the last one (len) being innermost. We build
140 the array with length max-1 lists for the len index, with syms-3 of those
141 for each symbol. There are totsym-2 of those, with each one varying in
142 length as a function of sym. See the calculation of index in map() for the
143 index, and the calculation of size in main() for the size of the array.
145 For the deflate example of 286 symbols limited to 15-bit codes, the array
146 has 284,284 entries, taking up 2.17 MB for an 8-byte big_t. More than half
147 of the space allocated for saved results is actually used -- not all
148 possible triplets are reached in the generation of valid Huffman codes.
151 /* The array for tracking visited states, done[], is itself indexed identically
152 to the num[] array as described above for the (syms, left, len) triplet.
153 Each element in the array is further indexed by the (mem, rem) doublet,
154 where mem is the amount of inflate table space used so far, and rem is the
155 remaining unused entries in the current inflate sub-table. Each indexed
156 element is simply one bit indicating whether the state has been visited or
157 not. Since the ranges for mem and rem are not known a priori, each bit
158 vector is of a variable size, and grows as needed to accommodate the visited
159 states. mem and rem are used to calculate a single index in a triangular
160 array. Since the range of mem is expected in the default case to be about
161 ten times larger than the range of rem, the array is skewed to reduce the
162 memory usage, with eight times the range for mem than for rem. See the
163 calculations for offset and bit in beenhere() for the details.
165 For the deflate example of 286 symbols limited to 15-bit codes, the bit
166 vectors grow to total approximately 21 MB, in addition to the 4.3 MB done[]
170 // Globals to avoid propagating constants or constant pointers recursively.
172 int max; // maximum allowed bit length for the codes
173 int root; // size of base code table in bits
174 int large; // largest code table so far
175 size_t size; // number of elements in num and done
176 int *code; // number of symbols assigned to each bit length
177 big_t *num; // saved results array for code counting
178 struct tab *done; // states already evaluated array
181 // Index function for num[] and done[].
182 #define INDEX(i,j,k) (((size_t)((i-1)>>1)*((i-2)>>1)+(j>>1)-1)*(g.max-1)+k-1)
184 // Free allocated space. Uses globals code, num, and done.
185 local void cleanup(void) {
188 if (g.done != NULL) {
189 for (n = 0; n < g.size; n++)
200 // Return the number of possible Huffman codes using bit patterns of lengths
201 // len through max inclusive, coding syms symbols, with left bit patterns of
202 // length len unused -- return -1 if there is an overflow in the counting. Keep
203 // a record of previous results in num to prevent repeating the same
204 // calculation. Uses the globals max and num.
205 local big_t count(int syms, int len, int left) {
206 big_t sum; // number of possible codes from this juncture
207 big_t got; // value returned from count()
208 int least; // least number of syms to use at this juncture
209 int most; // most number of syms to use at this juncture
210 int use; // number of bit patterns to use in next call
211 size_t index; // index of this case in *num
213 // see if only one possible code
217 // note and verify the expected state
218 assert(syms > left && left > 0 && len < g.max);
220 // see if we've done this one already
221 index = INDEX(syms, left, len);
224 return got; // we have -- return the saved result
226 // we need to use at least this many bit patterns so that the code won't be
227 // incomplete at the next length (more bit patterns than symbols)
228 least = (left << 1) - syms;
232 // we can use at most this many bit patterns, lest there not be enough
233 // available for the remaining symbols at the maximum length (if there were
234 // no limit to the code length, this would become: most = left - 1)
235 most = (((code_t)left << (g.max - len)) - syms) /
236 (((code_t)1 << (g.max - len)) - 1);
238 // count all possible codes from this juncture and add them up
240 for (use = least; use <= most; use++) {
241 got = count(syms - use, len + 1, (left - use) << 1);
243 if (got == (big_t)0 - 1 || sum < got) // overflow
247 // verify that all recursive calls are productive
250 // save the result and return it
255 // Return true if we've been here before, set to true if not. Set a bit in a
256 // bit vector to indicate visiting this state. Each (syms,len,left) state has a
257 // variable size bit vector indexed by (mem,rem). The bit vector is lengthened
258 // if needed to allow setting the (mem,rem) bit.
259 local int beenhere(int syms, int len, int left, int mem, int rem) {
260 size_t index; // index for this state's bit vector
261 size_t offset; // offset in this state's bit vector
262 int bit; // mask for this state's bit
263 size_t length; // length of the bit vector in bytes
264 char *vector; // new or enlarged bit vector
266 // point to vector for (syms,left,len), bit in vector for (mem,rem)
267 index = INDEX(syms, left, len);
269 offset = (mem >> 3) + rem;
270 offset = ((offset * (offset + 1)) >> 1) + rem;
271 bit = 1 << (mem & 7);
273 // see if we've been here
274 length = g.done[index].len;
275 if (offset < length && (g.done[index].vec[offset] & bit) != 0)
276 return 1; // done this!
278 // we haven't been here before -- set the bit to show we have now
280 // see if we need to lengthen the vector in order to set the bit
281 if (length <= offset) {
282 // if we have one already, enlarge it, zero out the appended space
286 } while (length <= offset);
287 vector = realloc(g.done[index].vec, length);
289 memset(vector + g.done[index].len, 0,
290 length - g.done[index].len);
293 // otherwise we need to make a new vector and zero it out
295 length = 1 << (len - g.root);
296 while (length <= offset)
298 vector = calloc(length, sizeof(char));
301 // in either case, bail if we can't get the memory
302 if (vector == NULL) {
303 fputs("abort: unable to allocate enough memory\n", stderr);
308 // install the new vector
309 g.done[index].len = length;
310 g.done[index].vec = vector;
314 g.done[index].vec[offset] |= bit;
318 // Examine all possible codes from the given node (syms, len, left). Compute
319 // the amount of memory required to build inflate's decoding tables, where the
320 // number of code structures used so far is mem, and the number remaining in
321 // the current sub-table is rem. Uses the globals max, code, root, large, and
323 local void examine(int syms, int len, int left, int mem, int rem) {
324 int least; // least number of syms to use at this juncture
325 int most; // most number of syms to use at this juncture
326 int use; // number of bit patterns to use in next call
328 // see if we have a complete code
330 // set the last code entry
333 // complete computation of memory used by this code
336 rem = 1 << (len - g.root);
341 // if this is a new maximum, show the entries used and the sub-code
344 printf("max %d: ", mem);
345 for (use = g.root + 1; use <= g.max; use++)
347 printf("%d[%d] ", g.code[use], use);
352 // remove entries as we drop back down in the recursion
357 // prune the tree if we can
358 if (beenhere(syms, len, left, mem, rem))
361 // we need to use at least this many bit patterns so that the code won't be
362 // incomplete at the next length (more bit patterns than symbols)
363 least = (left << 1) - syms;
367 // we can use at most this many bit patterns, lest there not be enough
368 // available for the remaining symbols at the maximum length (if there were
369 // no limit to the code length, this would become: most = left - 1)
370 most = (((code_t)left << (g.max - len)) - syms) /
371 (((code_t)1 << (g.max - len)) - 1);
373 // occupy least table spaces, creating new sub-tables as needed
377 rem = 1 << (len - g.root);
382 // examine codes from here, updating table space as we go
383 for (use = least; use <= most; use++) {
385 examine(syms - use, len + 1, (left - use) << 1,
386 mem + (rem ? 1 << (len - g.root) : 0), rem << 1);
388 rem = 1 << (len - g.root);
394 // remove entries as we drop back down in the recursion
398 // Look at all sub-codes starting with root + 1 bits. Look at only the valid
399 // intermediate code states (syms, left, len). For each completed code,
400 // calculate the amount of memory required by inflate to build the decoding
401 // tables. Find the maximum amount of memory required and show the code that
402 // requires that maximum. Uses the globals max, root, and num.
403 local void enough(int syms) {
404 int n; // number of remaing symbols for this node
405 int left; // number of unused bit patterns at this length
406 size_t index; // index of this case in *num
409 for (n = 0; n <= g.max; n++)
412 // look at all (root + 1) bit and longer codes
413 g.large = 1 << g.root; // base table
414 if (g.root < g.max) // otherwise, there's only a base table
415 for (n = 3; n <= syms; n++)
416 for (left = 2; left < n; left += 2) {
417 // look at all reachable (root + 1) bit nodes, and the
418 // resulting codes (complete at root + 2 or more)
419 index = INDEX(n, left, g.root + 1);
420 if (g.root + 1 < g.max && g.num[index]) // reachable node
421 examine(n, g.root + 1, left, 1 << g.root, 0);
423 // also look at root bit codes with completions at root + 1
424 // bits (not saved in num, since complete), just in case
425 if (g.num[index - 1] && n <= left << 1)
426 examine((n - left) << 1, g.root + 1, (n - left) << 1,
431 printf("done: maximum of %d table entries\n", g.large);
434 // Examine and show the total number of possible Huffman codes for a given
435 // maximum number of symbols, initial root table size, and maximum code length
436 // in bits -- those are the command arguments in that order. The default values
437 // are 286, 9, and 15 respectively, for the deflate literal/length code. The
438 // possible codes are counted for each number of coded symbols from two to the
439 // maximum. The counts for each of those and the total number of codes are
440 // shown. The maximum number of inflate table entires is then calculated across
441 // all possible codes. Each new maximum number of table entries and the
442 // associated sub-code (starting at root + 1 == 10 bits) is shown.
444 // To count and examine Huffman codes that are not length-limited, provide a
445 // maximum length equal to the number of symbols minus one.
447 // For the deflate literal/length code, use "enough". For the deflate distance
448 // code, use "enough 30 6".
449 int main(int argc, char **argv) {
450 int syms; // total number of symbols to code
451 int n; // number of symbols to code for this run
452 big_t got; // return value of count()
453 big_t sum; // accumulated number of codes over n
454 code_t word; // for counting bits in code_t
456 // set up globals for cleanup()
461 // get arguments -- default to the deflate literal/length code
466 syms = atoi(argv[1]);
468 g.root = atoi(argv[2]);
470 g.max = atoi(argv[3]);
473 if (argc > 4 || syms < 2 || g.root < 1 || g.max < 1) {
474 fputs("invalid arguments, need: [sym >= 2 [root >= 1 [max >= 1]]]\n",
479 // if not restricting the code length, the longest is syms - 1
480 if (g.max > syms - 1)
483 // determine the number of bits in a code_t
484 for (n = 0, word = 1; word; n++, word <<= 1)
487 // make sure that the calculation of most will not overflow
488 if (g.max > n || (code_t)(syms - 2) >= (((code_t)0 - 1) >> (g.max - 1))) {
489 fputs("abort: code length too long for internal types\n", stderr);
493 // reject impossible code requests
494 if ((code_t)(syms - 1) > ((code_t)1 << g.max) - 1) {
495 fprintf(stderr, "%d symbols cannot be coded in %d bits\n",
500 // allocate code vector
501 g.code = calloc(g.max + 1, sizeof(int));
502 if (g.code == NULL) {
503 fputs("abort: unable to allocate enough memory\n", stderr);
507 // determine size of saved results array, checking for overflows,
508 // allocate and clear the array (set all to zero with calloc())
509 if (syms == 2) // iff max == 1
510 g.num = NULL; // won't be saving any results
513 if (g.size > ((size_t)0 - 1) / (n = (syms - 1) >> 1) ||
514 (g.size *= n, g.size > ((size_t)0 - 1) / (n = g.max - 1)) ||
515 (g.size *= n, g.size > ((size_t)0 - 1) / sizeof(big_t)) ||
516 (g.num = calloc(g.size, sizeof(big_t))) == NULL) {
517 fputs("abort: unable to allocate enough memory\n", stderr);
523 // count possible codes for all numbers of symbols, add up counts
525 for (n = 2; n <= syms; n++) {
526 got = count(n, 1, 2);
528 if (got == (big_t)0 - 1 || sum < got) { // overflow
529 fputs("abort: can't count that high!\n", stderr);
533 printf("%"PRIbig" %d-codes\n", got, n);
535 printf("%"PRIbig" total codes for 2 to %d symbols", sum, syms);
536 if (g.max < syms - 1)
537 printf(" (%d-bit length limit)\n", g.max);
539 puts(" (no length limit)");
541 // allocate and clear done array for beenhere()
544 else if (g.size > ((size_t)0 - 1) / sizeof(struct tab) ||
545 (g.done = calloc(g.size, sizeof(struct tab))) == NULL) {
546 fputs("abort: unable to allocate enough memory\n", stderr);
551 // find and show maximum inflate table usage
552 if (g.root > g.max) // reduce root to max length
554 if ((code_t)syms < ((code_t)1 << (g.root + 1)))
557 puts("cannot handle minimum code lengths > root");