1c3423655Schristos /* enough.c -- determine the maximum size of inflate's Huffman code tables over
2*ec47cc4bSchristos * all possible valid and complete prefix codes, subject to a length limit.
3*ec47cc4bSchristos * Copyright (C) 2007, 2008, 2012, 2018 Mark Adler
4*ec47cc4bSchristos * Version 1.5 5 August 2018 Mark Adler
5c3423655Schristos */
6c3423655Schristos
7c3423655Schristos /* Version history:
8c3423655Schristos 1.0 3 Jan 2007 First version (derived from codecount.c version 1.4)
9c3423655Schristos 1.1 4 Jan 2007 Use faster incremental table usage computation
10c3423655Schristos Prune examine() search on previously visited states
11c3423655Schristos 1.2 5 Jan 2007 Comments clean up
12c3423655Schristos As inflate does, decrease root for short codes
13c3423655Schristos Refuse cases where inflate would increase root
14c3423655Schristos 1.3 17 Feb 2008 Add argument for initial root table size
15c3423655Schristos Fix bug for initial root table size == max - 1
16c3423655Schristos Use a macro to compute the history index
17c3423655Schristos 1.4 18 Aug 2012 Avoid shifts more than bits in type (caused endless loop!)
18c3423655Schristos Clean up comparisons of different types
19c3423655Schristos Clean up code indentation
20*ec47cc4bSchristos 1.5 5 Aug 2018 Clean up code style, formatting, and comments
21*ec47cc4bSchristos Show all the codes for the maximum, and only the maximum
22c3423655Schristos */
23c3423655Schristos
24c3423655Schristos /*
25*ec47cc4bSchristos Examine all possible prefix codes for a given number of symbols and a
26*ec47cc4bSchristos maximum code length in bits to determine the maximum table size for zlib's
27*ec47cc4bSchristos inflate. Only complete prefix codes are counted.
28c3423655Schristos
29c3423655Schristos Two codes are considered distinct if the vectors of the number of codes per
30c3423655Schristos length are not identical. So permutations of the symbol assignments result
31c3423655Schristos in the same code for the counting, as do permutations of the assignments of
32c3423655Schristos the bit values to the codes (i.e. only canonical codes are counted).
33c3423655Schristos
34c3423655Schristos We build a code from shorter to longer lengths, determining how many symbols
35c3423655Schristos are coded at each length. At each step, we have how many symbols remain to
36c3423655Schristos be coded, what the last code length used was, and how many bit patterns of
37c3423655Schristos that length remain unused. Then we add one to the code length and double the
38c3423655Schristos number of unused patterns to graduate to the next code length. We then
39c3423655Schristos assign all portions of the remaining symbols to that code length that
40c3423655Schristos preserve the properties of a correct and eventually complete code. Those
41c3423655Schristos properties are: we cannot use more bit patterns than are available; and when
42*ec47cc4bSchristos all the symbols are used, there are exactly zero possible bit patterns left
43*ec47cc4bSchristos unused.
44c3423655Schristos
45c3423655Schristos The inflate Huffman decoding algorithm uses two-level lookup tables for
46c3423655Schristos speed. There is a single first-level table to decode codes up to root bits
47*ec47cc4bSchristos in length (root == 9 for literal/length codes and root == 6 for distance
48*ec47cc4bSchristos codes, in the current inflate implementation). The base table has 1 << root
49*ec47cc4bSchristos entries and is indexed by the next root bits of input. Codes shorter than
50*ec47cc4bSchristos root bits have replicated table entries, so that the correct entry is
51*ec47cc4bSchristos pointed to regardless of the bits that follow the short code. If the code is
52*ec47cc4bSchristos longer than root bits, then the table entry points to a second-level table.
53*ec47cc4bSchristos The size of that table is determined by the longest code with that root-bit
54*ec47cc4bSchristos prefix. If that longest code has length len, then the table has size 1 <<
55*ec47cc4bSchristos (len - root), to index the remaining bits in that set of codes. Each
56*ec47cc4bSchristos subsequent root-bit prefix then has its own sub-table. The total number of
57*ec47cc4bSchristos table entries required by the code is calculated incrementally as the number
58*ec47cc4bSchristos of codes at each bit length is populated. When all of the codes are shorter
59*ec47cc4bSchristos than root bits, then root is reduced to the longest code length, resulting
60*ec47cc4bSchristos in a single, smaller, one-level table.
61c3423655Schristos
62c3423655Schristos The inflate algorithm also provides for small values of root (relative to
63c3423655Schristos the log2 of the number of symbols), where the shortest code has more bits
64c3423655Schristos than root. In that case, root is increased to the length of the shortest
65c3423655Schristos code. This program, by design, does not handle that case, so it is verified
66*ec47cc4bSchristos that the number of symbols is less than 1 << (root + 1).
67c3423655Schristos
68c3423655Schristos In order to speed up the examination (by about ten orders of magnitude for
69c3423655Schristos the default arguments), the intermediate states in the build-up of a code
70c3423655Schristos are remembered and previously visited branches are pruned. The memory
71c3423655Schristos required for this will increase rapidly with the total number of symbols and
72c3423655Schristos the maximum code length in bits. However this is a very small price to pay
73c3423655Schristos for the vast speedup.
74c3423655Schristos
75*ec47cc4bSchristos First, all of the possible prefix codes are counted, and reachable
76c3423655Schristos intermediate states are noted by a non-zero count in a saved-results array.
77c3423655Schristos Second, the intermediate states that lead to (root + 1) bit or longer codes
78c3423655Schristos are used to look at all sub-codes from those junctures for their inflate
79c3423655Schristos memory usage. (The amount of memory used is not affected by the number of
80c3423655Schristos codes of root bits or less in length.) Third, the visited states in the
81c3423655Schristos construction of those sub-codes and the associated calculation of the table
82c3423655Schristos size is recalled in order to avoid recalculating from the same juncture.
83c3423655Schristos Beginning the code examination at (root + 1) bit codes, which is enabled by
84c3423655Schristos identifying the reachable nodes, accounts for about six of the orders of
85c3423655Schristos magnitude of improvement for the default arguments. About another four
86c3423655Schristos orders of magnitude come from not revisiting previous states. Out of
87*ec47cc4bSchristos approximately 2x10^16 possible prefix codes, only about 2x10^6 sub-codes
88c3423655Schristos need to be examined to cover all of the possible table memory usage cases
89c3423655Schristos for the default arguments of 286 symbols limited to 15-bit codes.
90c3423655Schristos
91*ec47cc4bSchristos Note that the uintmax_t type is used for counting. It is quite easy to
92*ec47cc4bSchristos exceed the capacity of an eight-byte integer with a large number of symbols
93*ec47cc4bSchristos and a large maximum code length, so multiple-precision arithmetic would need
94*ec47cc4bSchristos to replace the integer arithmetic in that case. This program will abort if
95*ec47cc4bSchristos an overflow occurs. The big_t type identifies where the counting takes
96*ec47cc4bSchristos place.
97c3423655Schristos
98*ec47cc4bSchristos The uintmax_t type is also used for calculating the number of possible codes
99*ec47cc4bSchristos remaining at the maximum length. This limits the maximum code length to the
100*ec47cc4bSchristos number of bits in a long long minus the number of bits needed to represent
101*ec47cc4bSchristos the symbols in a flat code. The code_t type identifies where the bit-pattern
102*ec47cc4bSchristos counting takes place.
103c3423655Schristos */
104c3423655Schristos
105c3423655Schristos #include <stdio.h>
106c3423655Schristos #include <stdlib.h>
107c3423655Schristos #include <string.h>
108*ec47cc4bSchristos #include <stdarg.h>
109*ec47cc4bSchristos #include <stdint.h>
110c3423655Schristos #include <assert.h>
111c3423655Schristos
112c3423655Schristos #define local static
113c3423655Schristos
114*ec47cc4bSchristos // Special data types.
115*ec47cc4bSchristos typedef uintmax_t big_t; // type for code counting
116*ec47cc4bSchristos #define PRIbig "ju" // printf format for big_t
117*ec47cc4bSchristos typedef uintmax_t code_t; // type for bit pattern counting
118*ec47cc4bSchristos struct tab { // type for been-here check
119*ec47cc4bSchristos size_t len; // allocated length of bit vector in octets
120*ec47cc4bSchristos char *vec; // allocated bit vector
121c3423655Schristos };
122c3423655Schristos
123c3423655Schristos /* The array for saving results, num[], is indexed with this triplet:
124c3423655Schristos
125c3423655Schristos syms: number of symbols remaining to code
126c3423655Schristos left: number of available bit patterns at length len
127c3423655Schristos len: number of bits in the codes currently being assigned
128c3423655Schristos
129c3423655Schristos Those indices are constrained thusly when saving results:
130c3423655Schristos
131c3423655Schristos syms: 3..totsym (totsym == total symbols to code)
132c3423655Schristos left: 2..syms - 1, but only the evens (so syms == 8 -> 2, 4, 6)
133c3423655Schristos len: 1..max - 1 (max == maximum code length in bits)
134c3423655Schristos
135c3423655Schristos syms == 2 is not saved since that immediately leads to a single code. left
136c3423655Schristos must be even, since it represents the number of available bit patterns at
137*ec47cc4bSchristos the current length, which is double the number at the previous length. left
138*ec47cc4bSchristos ends at syms-1 since left == syms immediately results in a single code.
139c3423655Schristos (left > sym is not allowed since that would result in an incomplete code.)
140c3423655Schristos len is less than max, since the code completes immediately when len == max.
141c3423655Schristos
142*ec47cc4bSchristos The offset into the array is calculated for the three indices with the first
143*ec47cc4bSchristos one (syms) being outermost, and the last one (len) being innermost. We build
144*ec47cc4bSchristos the array with length max-1 lists for the len index, with syms-3 of those
145*ec47cc4bSchristos for each symbol. There are totsym-2 of those, with each one varying in
146*ec47cc4bSchristos length as a function of sym. See the calculation of index in map() for the
147*ec47cc4bSchristos index, and the calculation of size in main() for the size of the array.
148c3423655Schristos
149c3423655Schristos For the deflate example of 286 symbols limited to 15-bit codes, the array
150*ec47cc4bSchristos has 284,284 entries, taking up 2.17 MB for an 8-byte big_t. More than half
151*ec47cc4bSchristos of the space allocated for saved results is actually used -- not all
152*ec47cc4bSchristos possible triplets are reached in the generation of valid prefix codes.
153c3423655Schristos */
154c3423655Schristos
155c3423655Schristos /* The array for tracking visited states, done[], is itself indexed identically
156c3423655Schristos to the num[] array as described above for the (syms, left, len) triplet.
157c3423655Schristos Each element in the array is further indexed by the (mem, rem) doublet,
158c3423655Schristos where mem is the amount of inflate table space used so far, and rem is the
159c3423655Schristos remaining unused entries in the current inflate sub-table. Each indexed
160c3423655Schristos element is simply one bit indicating whether the state has been visited or
161c3423655Schristos not. Since the ranges for mem and rem are not known a priori, each bit
162c3423655Schristos vector is of a variable size, and grows as needed to accommodate the visited
163c3423655Schristos states. mem and rem are used to calculate a single index in a triangular
164c3423655Schristos array. Since the range of mem is expected in the default case to be about
165c3423655Schristos ten times larger than the range of rem, the array is skewed to reduce the
166c3423655Schristos memory usage, with eight times the range for mem than for rem. See the
167*ec47cc4bSchristos calculations for offset and bit in been_here() for the details.
168c3423655Schristos
169c3423655Schristos For the deflate example of 286 symbols limited to 15-bit codes, the bit
170*ec47cc4bSchristos vectors grow to total 5.5 MB, in addition to the 4.3 MB done array itself.
171c3423655Schristos */
172c3423655Schristos
173*ec47cc4bSchristos // Type for a variable-length, allocated string.
174*ec47cc4bSchristos typedef struct {
175*ec47cc4bSchristos char *str; // pointer to allocated string
176*ec47cc4bSchristos size_t size; // size of allocation
177*ec47cc4bSchristos size_t len; // length of string, not including terminating zero
178*ec47cc4bSchristos } string_t;
179c3423655Schristos
180*ec47cc4bSchristos // Clear a string_t.
string_clear(string_t * s)181*ec47cc4bSchristos local void string_clear(string_t *s) {
182*ec47cc4bSchristos s->str[0] = 0;
183*ec47cc4bSchristos s->len = 0;
184c3423655Schristos }
185c3423655Schristos
186*ec47cc4bSchristos // Initialize a string_t.
string_init(string_t * s)187*ec47cc4bSchristos local void string_init(string_t *s) {
188*ec47cc4bSchristos s->size = 16;
189*ec47cc4bSchristos s->str = malloc(s->size);
190*ec47cc4bSchristos assert(s->str != NULL && "out of memory");
191*ec47cc4bSchristos string_clear(s);
192*ec47cc4bSchristos }
193c3423655Schristos
194*ec47cc4bSchristos // Release the allocation of a string_t.
string_free(string_t * s)195*ec47cc4bSchristos local void string_free(string_t *s) {
196*ec47cc4bSchristos free(s->str);
197*ec47cc4bSchristos s->str = NULL;
198*ec47cc4bSchristos s->size = 0;
199*ec47cc4bSchristos s->len = 0;
200*ec47cc4bSchristos }
201*ec47cc4bSchristos
202*ec47cc4bSchristos // Save the results of printf with fmt and the subsequent argument list to s.
203*ec47cc4bSchristos // Each call appends to s. The allocated space for s is increased as needed.
string_printf(string_t * s,char * fmt,...)204*ec47cc4bSchristos local void string_printf(string_t *s, char *fmt, ...) {
205*ec47cc4bSchristos va_list ap;
206*ec47cc4bSchristos va_start(ap, fmt);
207*ec47cc4bSchristos size_t len = s->len;
208*ec47cc4bSchristos int ret = vsnprintf(s->str + len, s->size - len, fmt, ap);
209*ec47cc4bSchristos assert(ret >= 0 && "out of memory");
210*ec47cc4bSchristos s->len += ret;
211*ec47cc4bSchristos if (s->size < s->len + 1) {
212*ec47cc4bSchristos do {
213*ec47cc4bSchristos s->size <<= 1;
214*ec47cc4bSchristos assert(s->size != 0 && "overflow");
215*ec47cc4bSchristos } while (s->size < s->len + 1);
216*ec47cc4bSchristos s->str = realloc(s->str, s->size);
217*ec47cc4bSchristos assert(s->str != NULL && "out of memory");
218*ec47cc4bSchristos vsnprintf(s->str + len, s->size - len, fmt, ap);
219*ec47cc4bSchristos }
220*ec47cc4bSchristos va_end(ap);
221*ec47cc4bSchristos }
222*ec47cc4bSchristos
223*ec47cc4bSchristos // Globals to avoid propagating constants or constant pointers recursively.
224*ec47cc4bSchristos struct {
225*ec47cc4bSchristos int max; // maximum allowed bit length for the codes
226*ec47cc4bSchristos int root; // size of base code table in bits
227*ec47cc4bSchristos int large; // largest code table so far
228*ec47cc4bSchristos size_t size; // number of elements in num and done
229*ec47cc4bSchristos big_t tot; // total number of codes with maximum tables size
230*ec47cc4bSchristos string_t out; // display of subcodes for maximum tables size
231*ec47cc4bSchristos int *code; // number of symbols assigned to each bit length
232*ec47cc4bSchristos big_t *num; // saved results array for code counting
233*ec47cc4bSchristos struct tab *done; // states already evaluated array
234*ec47cc4bSchristos } g;
235*ec47cc4bSchristos
236*ec47cc4bSchristos // Index function for num[] and done[].
map(int syms,int left,int len)237*ec47cc4bSchristos local inline size_t map(int syms, int left, int len) {
238*ec47cc4bSchristos return ((size_t)((syms - 1) >> 1) * ((syms - 2) >> 1) +
239*ec47cc4bSchristos (left >> 1) - 1) * (g.max - 1) +
240*ec47cc4bSchristos len - 1;
241*ec47cc4bSchristos }
242*ec47cc4bSchristos
243*ec47cc4bSchristos // Free allocated space in globals.
cleanup(void)244*ec47cc4bSchristos local void cleanup(void) {
245*ec47cc4bSchristos if (g.done != NULL) {
246*ec47cc4bSchristos for (size_t n = 0; n < g.size; n++)
247*ec47cc4bSchristos if (g.done[n].len)
248*ec47cc4bSchristos free(g.done[n].vec);
249*ec47cc4bSchristos g.size = 0;
250*ec47cc4bSchristos free(g.done); g.done = NULL;
251*ec47cc4bSchristos }
252*ec47cc4bSchristos free(g.num); g.num = NULL;
253*ec47cc4bSchristos free(g.code); g.code = NULL;
254*ec47cc4bSchristos string_free(&g.out);
255*ec47cc4bSchristos }
256*ec47cc4bSchristos
257*ec47cc4bSchristos // Return the number of possible prefix codes using bit patterns of lengths len
258*ec47cc4bSchristos // through max inclusive, coding syms symbols, with left bit patterns of length
259*ec47cc4bSchristos // len unused -- return -1 if there is an overflow in the counting. Keep a
260*ec47cc4bSchristos // record of previous results in num to prevent repeating the same calculation.
count(int syms,int left,int len)261*ec47cc4bSchristos local big_t count(int syms, int left, int len) {
262*ec47cc4bSchristos // see if only one possible code
263c3423655Schristos if (syms == left)
264c3423655Schristos return 1;
265c3423655Schristos
266*ec47cc4bSchristos // note and verify the expected state
267*ec47cc4bSchristos assert(syms > left && left > 0 && len < g.max);
268c3423655Schristos
269*ec47cc4bSchristos // see if we've done this one already
270*ec47cc4bSchristos size_t index = map(syms, left, len);
271*ec47cc4bSchristos big_t got = g.num[index];
272c3423655Schristos if (got)
273*ec47cc4bSchristos return got; // we have -- return the saved result
274c3423655Schristos
275*ec47cc4bSchristos // we need to use at least this many bit patterns so that the code won't be
276*ec47cc4bSchristos // incomplete at the next length (more bit patterns than symbols)
277*ec47cc4bSchristos int least = (left << 1) - syms;
278c3423655Schristos if (least < 0)
279c3423655Schristos least = 0;
280c3423655Schristos
281*ec47cc4bSchristos // we can use at most this many bit patterns, lest there not be enough
282*ec47cc4bSchristos // available for the remaining symbols at the maximum length (if there were
283*ec47cc4bSchristos // no limit to the code length, this would become: most = left - 1)
284*ec47cc4bSchristos int most = (((code_t)left << (g.max - len)) - syms) /
285*ec47cc4bSchristos (((code_t)1 << (g.max - len)) - 1);
286c3423655Schristos
287*ec47cc4bSchristos // count all possible codes from this juncture and add them up
288*ec47cc4bSchristos big_t sum = 0;
289*ec47cc4bSchristos for (int use = least; use <= most; use++) {
290*ec47cc4bSchristos got = count(syms - use, (left - use) << 1, len + 1);
291c3423655Schristos sum += got;
292*ec47cc4bSchristos if (got == (big_t)-1 || sum < got) // overflow
293*ec47cc4bSchristos return (big_t)-1;
294c3423655Schristos }
295c3423655Schristos
296*ec47cc4bSchristos // verify that all recursive calls are productive
297c3423655Schristos assert(sum != 0);
298c3423655Schristos
299*ec47cc4bSchristos // save the result and return it
300*ec47cc4bSchristos g.num[index] = sum;
301c3423655Schristos return sum;
302c3423655Schristos }
303c3423655Schristos
304*ec47cc4bSchristos // Return true if we've been here before, set to true if not. Set a bit in a
305*ec47cc4bSchristos // bit vector to indicate visiting this state. Each (syms,len,left) state has a
306*ec47cc4bSchristos // variable size bit vector indexed by (mem,rem). The bit vector is lengthened
307*ec47cc4bSchristos // as needed to allow setting the (mem,rem) bit.
been_here(int syms,int left,int len,int mem,int rem)308*ec47cc4bSchristos local int been_here(int syms, int left, int len, int mem, int rem) {
309*ec47cc4bSchristos // point to vector for (syms,left,len), bit in vector for (mem,rem)
310*ec47cc4bSchristos size_t index = map(syms, left, len);
311*ec47cc4bSchristos mem -= 1 << g.root; // mem always includes the root table
312*ec47cc4bSchristos mem >>= 1; // mem and rem are always even
313*ec47cc4bSchristos rem >>= 1;
314*ec47cc4bSchristos size_t offset = (mem >> 3) + rem;
315c3423655Schristos offset = ((offset * (offset + 1)) >> 1) + rem;
316*ec47cc4bSchristos int bit = 1 << (mem & 7);
317c3423655Schristos
318*ec47cc4bSchristos // see if we've been here
319*ec47cc4bSchristos size_t length = g.done[index].len;
320*ec47cc4bSchristos if (offset < length && (g.done[index].vec[offset] & bit) != 0)
321*ec47cc4bSchristos return 1; // done this!
322c3423655Schristos
323*ec47cc4bSchristos // we haven't been here before -- set the bit to show we have now
324c3423655Schristos
325*ec47cc4bSchristos // see if we need to lengthen the vector in order to set the bit
326c3423655Schristos if (length <= offset) {
327*ec47cc4bSchristos // if we have one already, enlarge it, zero out the appended space
328*ec47cc4bSchristos char *vector;
329c3423655Schristos if (length) {
330c3423655Schristos do {
331c3423655Schristos length <<= 1;
332c3423655Schristos } while (length <= offset);
333*ec47cc4bSchristos vector = realloc(g.done[index].vec, length);
334*ec47cc4bSchristos assert(vector != NULL && "out of memory");
335*ec47cc4bSchristos memset(vector + g.done[index].len, 0, length - g.done[index].len);
336c3423655Schristos }
337c3423655Schristos
338*ec47cc4bSchristos // otherwise we need to make a new vector and zero it out
339c3423655Schristos else {
340*ec47cc4bSchristos length = 16;
341c3423655Schristos while (length <= offset)
342c3423655Schristos length <<= 1;
343*ec47cc4bSchristos vector = calloc(length, 1);
344*ec47cc4bSchristos assert(vector != NULL && "out of memory");
345c3423655Schristos }
346c3423655Schristos
347*ec47cc4bSchristos // install the new vector
348*ec47cc4bSchristos g.done[index].len = length;
349*ec47cc4bSchristos g.done[index].vec = vector;
350c3423655Schristos }
351c3423655Schristos
352*ec47cc4bSchristos // set the bit
353*ec47cc4bSchristos g.done[index].vec[offset] |= bit;
354c3423655Schristos return 0;
355c3423655Schristos }
356c3423655Schristos
357*ec47cc4bSchristos // Examine all possible codes from the given node (syms, len, left). Compute
358*ec47cc4bSchristos // the amount of memory required to build inflate's decoding tables, where the
359*ec47cc4bSchristos // number of code structures used so far is mem, and the number remaining in
360*ec47cc4bSchristos // the current sub-table is rem.
examine(int syms,int left,int len,int mem,int rem)361*ec47cc4bSchristos local void examine(int syms, int left, int len, int mem, int rem) {
362*ec47cc4bSchristos // see if we have a complete code
363c3423655Schristos if (syms == left) {
364*ec47cc4bSchristos // set the last code entry
365*ec47cc4bSchristos g.code[len] = left;
366c3423655Schristos
367*ec47cc4bSchristos // complete computation of memory used by this code
368c3423655Schristos while (rem < left) {
369c3423655Schristos left -= rem;
370*ec47cc4bSchristos rem = 1 << (len - g.root);
371c3423655Schristos mem += rem;
372c3423655Schristos }
373c3423655Schristos assert(rem == left);
374c3423655Schristos
375*ec47cc4bSchristos // if this is at the maximum, show the sub-code
376*ec47cc4bSchristos if (mem >= g.large) {
377*ec47cc4bSchristos // if this is a new maximum, update the maximum and clear out the
378*ec47cc4bSchristos // printed sub-codes from the previous maximum
379*ec47cc4bSchristos if (mem > g.large) {
380*ec47cc4bSchristos g.large = mem;
381*ec47cc4bSchristos string_clear(&g.out);
382c3423655Schristos }
383c3423655Schristos
384*ec47cc4bSchristos // compute the starting state for this sub-code
385*ec47cc4bSchristos syms = 0;
386*ec47cc4bSchristos left = 1 << g.max;
387*ec47cc4bSchristos for (int bits = g.max; bits > g.root; bits--) {
388*ec47cc4bSchristos syms += g.code[bits];
389*ec47cc4bSchristos left -= g.code[bits];
390*ec47cc4bSchristos assert((left & 1) == 0);
391*ec47cc4bSchristos left >>= 1;
392*ec47cc4bSchristos }
393*ec47cc4bSchristos
394*ec47cc4bSchristos // print the starting state and the resulting sub-code to g.out
395*ec47cc4bSchristos string_printf(&g.out, "<%u, %u, %u>:",
396*ec47cc4bSchristos syms, g.root + 1, ((1 << g.root) - left) << 1);
397*ec47cc4bSchristos for (int bits = g.root + 1; bits <= g.max; bits++)
398*ec47cc4bSchristos if (g.code[bits])
399*ec47cc4bSchristos string_printf(&g.out, " %d[%d]", g.code[bits], bits);
400*ec47cc4bSchristos string_printf(&g.out, "\n");
401*ec47cc4bSchristos }
402*ec47cc4bSchristos
403*ec47cc4bSchristos // remove entries as we drop back down in the recursion
404*ec47cc4bSchristos g.code[len] = 0;
405c3423655Schristos return;
406c3423655Schristos }
407c3423655Schristos
408*ec47cc4bSchristos // prune the tree if we can
409*ec47cc4bSchristos if (been_here(syms, left, len, mem, rem))
410c3423655Schristos return;
411c3423655Schristos
412*ec47cc4bSchristos // we need to use at least this many bit patterns so that the code won't be
413*ec47cc4bSchristos // incomplete at the next length (more bit patterns than symbols)
414*ec47cc4bSchristos int least = (left << 1) - syms;
415c3423655Schristos if (least < 0)
416c3423655Schristos least = 0;
417c3423655Schristos
418*ec47cc4bSchristos // we can use at most this many bit patterns, lest there not be enough
419*ec47cc4bSchristos // available for the remaining symbols at the maximum length (if there were
420*ec47cc4bSchristos // no limit to the code length, this would become: most = left - 1)
421*ec47cc4bSchristos int most = (((code_t)left << (g.max - len)) - syms) /
422*ec47cc4bSchristos (((code_t)1 << (g.max - len)) - 1);
423c3423655Schristos
424*ec47cc4bSchristos // occupy least table spaces, creating new sub-tables as needed
425*ec47cc4bSchristos int use = least;
426c3423655Schristos while (rem < use) {
427c3423655Schristos use -= rem;
428*ec47cc4bSchristos rem = 1 << (len - g.root);
429c3423655Schristos mem += rem;
430c3423655Schristos }
431c3423655Schristos rem -= use;
432c3423655Schristos
433*ec47cc4bSchristos // examine codes from here, updating table space as we go
434c3423655Schristos for (use = least; use <= most; use++) {
435*ec47cc4bSchristos g.code[len] = use;
436*ec47cc4bSchristos examine(syms - use, (left - use) << 1, len + 1,
437*ec47cc4bSchristos mem + (rem ? 1 << (len - g.root) : 0), rem << 1);
438c3423655Schristos if (rem == 0) {
439*ec47cc4bSchristos rem = 1 << (len - g.root);
440c3423655Schristos mem += rem;
441c3423655Schristos }
442c3423655Schristos rem--;
443c3423655Schristos }
444c3423655Schristos
445*ec47cc4bSchristos // remove entries as we drop back down in the recursion
446*ec47cc4bSchristos g.code[len] = 0;
447c3423655Schristos }
448c3423655Schristos
449*ec47cc4bSchristos // Look at all sub-codes starting with root + 1 bits. Look at only the valid
450*ec47cc4bSchristos // intermediate code states (syms, left, len). For each completed code,
451*ec47cc4bSchristos // calculate the amount of memory required by inflate to build the decoding
452*ec47cc4bSchristos // tables. Find the maximum amount of memory required and show the codes that
453*ec47cc4bSchristos // require that maximum.
enough(int syms)454*ec47cc4bSchristos local void enough(int syms) {
455*ec47cc4bSchristos // clear code
456*ec47cc4bSchristos for (int n = 0; n <= g.max; n++)
457*ec47cc4bSchristos g.code[n] = 0;
458c3423655Schristos
459*ec47cc4bSchristos // look at all (root + 1) bit and longer codes
460*ec47cc4bSchristos string_clear(&g.out); // empty saved results
461*ec47cc4bSchristos g.large = 1 << g.root; // base table
462*ec47cc4bSchristos if (g.root < g.max) // otherwise, there's only a base table
463*ec47cc4bSchristos for (int n = 3; n <= syms; n++)
464*ec47cc4bSchristos for (int left = 2; left < n; left += 2) {
465*ec47cc4bSchristos // look at all reachable (root + 1) bit nodes, and the
466*ec47cc4bSchristos // resulting codes (complete at root + 2 or more)
467*ec47cc4bSchristos size_t index = map(n, left, g.root + 1);
468*ec47cc4bSchristos if (g.root + 1 < g.max && g.num[index]) // reachable node
469*ec47cc4bSchristos examine(n, left, g.root + 1, 1 << g.root, 0);
470c3423655Schristos
471*ec47cc4bSchristos // also look at root bit codes with completions at root + 1
472*ec47cc4bSchristos // bits (not saved in num, since complete), just in case
473*ec47cc4bSchristos if (g.num[index - 1] && n <= left << 1)
474*ec47cc4bSchristos examine((n - left) << 1, (n - left) << 1, g.root + 1,
475*ec47cc4bSchristos 1 << g.root, 0);
476c3423655Schristos }
477c3423655Schristos
478*ec47cc4bSchristos // done
479*ec47cc4bSchristos printf("maximum of %d table entries for root = %d\n", g.large, g.root);
480*ec47cc4bSchristos fputs(g.out.str, stdout);
481c3423655Schristos }
482c3423655Schristos
483*ec47cc4bSchristos // Examine and show the total number of possible prefix codes for a given
484*ec47cc4bSchristos // maximum number of symbols, initial root table size, and maximum code length
485*ec47cc4bSchristos // in bits -- those are the command arguments in that order. The default values
486*ec47cc4bSchristos // are 286, 9, and 15 respectively, for the deflate literal/length code. The
487*ec47cc4bSchristos // possible codes are counted for each number of coded symbols from two to the
488*ec47cc4bSchristos // maximum. The counts for each of those and the total number of codes are
489*ec47cc4bSchristos // shown. The maximum number of inflate table entries is then calculated across
490*ec47cc4bSchristos // all possible codes. Each new maximum number of table entries and the
491*ec47cc4bSchristos // associated sub-code (starting at root + 1 == 10 bits) is shown.
492*ec47cc4bSchristos //
493*ec47cc4bSchristos // To count and examine prefix codes that are not length-limited, provide a
494*ec47cc4bSchristos // maximum length equal to the number of symbols minus one.
495*ec47cc4bSchristos //
496*ec47cc4bSchristos // For the deflate literal/length code, use "enough". For the deflate distance
497*ec47cc4bSchristos // code, use "enough 30 6".
main(int argc,char ** argv)498*ec47cc4bSchristos int main(int argc, char **argv) {
499*ec47cc4bSchristos // set up globals for cleanup()
500*ec47cc4bSchristos g.code = NULL;
501*ec47cc4bSchristos g.num = NULL;
502*ec47cc4bSchristos g.done = NULL;
503*ec47cc4bSchristos string_init(&g.out);
504c3423655Schristos
505*ec47cc4bSchristos // get arguments -- default to the deflate literal/length code
506*ec47cc4bSchristos int syms = 286;
507*ec47cc4bSchristos g.root = 9;
508*ec47cc4bSchristos g.max = 15;
509c3423655Schristos if (argc > 1) {
510c3423655Schristos syms = atoi(argv[1]);
511c3423655Schristos if (argc > 2) {
512*ec47cc4bSchristos g.root = atoi(argv[2]);
513c3423655Schristos if (argc > 3)
514*ec47cc4bSchristos g.max = atoi(argv[3]);
515c3423655Schristos }
516c3423655Schristos }
517*ec47cc4bSchristos if (argc > 4 || syms < 2 || g.root < 1 || g.max < 1) {
518c3423655Schristos fputs("invalid arguments, need: [sym >= 2 [root >= 1 [max >= 1]]]\n",
519c3423655Schristos stderr);
520c3423655Schristos return 1;
521c3423655Schristos }
522c3423655Schristos
523*ec47cc4bSchristos // if not restricting the code length, the longest is syms - 1
524*ec47cc4bSchristos if (g.max > syms - 1)
525*ec47cc4bSchristos g.max = syms - 1;
526c3423655Schristos
527*ec47cc4bSchristos // determine the number of bits in a code_t
528*ec47cc4bSchristos int bits = 0;
529*ec47cc4bSchristos for (code_t word = 1; word; word <<= 1)
530*ec47cc4bSchristos bits++;
531c3423655Schristos
532*ec47cc4bSchristos // make sure that the calculation of most will not overflow
533*ec47cc4bSchristos if (g.max > bits || (code_t)(syms - 2) >= ((code_t)-1 >> (g.max - 1))) {
534c3423655Schristos fputs("abort: code length too long for internal types\n", stderr);
535c3423655Schristos return 1;
536c3423655Schristos }
537c3423655Schristos
538*ec47cc4bSchristos // reject impossible code requests
539*ec47cc4bSchristos if ((code_t)(syms - 1) > ((code_t)1 << g.max) - 1) {
540c3423655Schristos fprintf(stderr, "%d symbols cannot be coded in %d bits\n",
541*ec47cc4bSchristos syms, g.max);
542c3423655Schristos return 1;
543c3423655Schristos }
544c3423655Schristos
545*ec47cc4bSchristos // allocate code vector
546*ec47cc4bSchristos g.code = calloc(g.max + 1, sizeof(int));
547*ec47cc4bSchristos assert(g.code != NULL && "out of memory");
548c3423655Schristos
549*ec47cc4bSchristos // determine size of saved results array, checking for overflows,
550*ec47cc4bSchristos // allocate and clear the array (set all to zero with calloc())
551*ec47cc4bSchristos if (syms == 2) // iff max == 1
552*ec47cc4bSchristos g.num = NULL; // won't be saving any results
553c3423655Schristos else {
554*ec47cc4bSchristos g.size = syms >> 1;
555*ec47cc4bSchristos int n = (syms - 1) >> 1;
556*ec47cc4bSchristos assert(g.size <= (size_t)-1 / n && "overflow");
557*ec47cc4bSchristos g.size *= n;
558*ec47cc4bSchristos n = g.max - 1;
559*ec47cc4bSchristos assert(g.size <= (size_t)-1 / n && "overflow");
560*ec47cc4bSchristos g.size *= n;
561*ec47cc4bSchristos g.num = calloc(g.size, sizeof(big_t));
562*ec47cc4bSchristos assert(g.num != NULL && "out of memory");
563c3423655Schristos }
564c3423655Schristos
565*ec47cc4bSchristos // count possible codes for all numbers of symbols, add up counts
566*ec47cc4bSchristos big_t sum = 0;
567*ec47cc4bSchristos for (int n = 2; n <= syms; n++) {
568*ec47cc4bSchristos big_t got = count(n, 2, 1);
569c3423655Schristos sum += got;
570*ec47cc4bSchristos assert(got != (big_t)-1 && sum >= got && "overflow");
571c3423655Schristos }
572*ec47cc4bSchristos printf("%"PRIbig" total codes for 2 to %d symbols", sum, syms);
573*ec47cc4bSchristos if (g.max < syms - 1)
574*ec47cc4bSchristos printf(" (%d-bit length limit)\n", g.max);
575c3423655Schristos else
576c3423655Schristos puts(" (no length limit)");
577c3423655Schristos
578*ec47cc4bSchristos // allocate and clear done array for been_here()
579c3423655Schristos if (syms == 2)
580*ec47cc4bSchristos g.done = NULL;
581*ec47cc4bSchristos else {
582*ec47cc4bSchristos g.done = calloc(g.size, sizeof(struct tab));
583*ec47cc4bSchristos assert(g.done != NULL && "out of memory");
584c3423655Schristos }
585c3423655Schristos
586*ec47cc4bSchristos // find and show maximum inflate table usage
587*ec47cc4bSchristos if (g.root > g.max) // reduce root to max length
588*ec47cc4bSchristos g.root = g.max;
589*ec47cc4bSchristos if ((code_t)syms < ((code_t)1 << (g.root + 1)))
590c3423655Schristos enough(syms);
591c3423655Schristos else
592*ec47cc4bSchristos fputs("cannot handle minimum code lengths > root", stderr);
593c3423655Schristos
594*ec47cc4bSchristos // done
595c3423655Schristos cleanup();
596c3423655Schristos return 0;
597c3423655Schristos }
598