xref: /netbsd-src/external/gpl3/gdb.old/dist/zlib/examples/enough.c (revision 6881a4007f077b54e5f51159c52b9b25f57deb0d)
14e00368fSchristos /* enough.c -- determine the maximum size of inflate's Huffman code tables over
2*6881a400Schristos  * all possible valid and complete prefix codes, subject to a length limit.
3*6881a400Schristos  * Copyright (C) 2007, 2008, 2012, 2018 Mark Adler
4*6881a400Schristos  * Version 1.5  5 August 2018  Mark Adler
54e00368fSchristos  */
64e00368fSchristos 
74e00368fSchristos /* Version history:
84e00368fSchristos    1.0   3 Jan 2007  First version (derived from codecount.c version 1.4)
94e00368fSchristos    1.1   4 Jan 2007  Use faster incremental table usage computation
104e00368fSchristos                      Prune examine() search on previously visited states
114e00368fSchristos    1.2   5 Jan 2007  Comments clean up
124e00368fSchristos                      As inflate does, decrease root for short codes
134e00368fSchristos                      Refuse cases where inflate would increase root
144e00368fSchristos    1.3  17 Feb 2008  Add argument for initial root table size
154e00368fSchristos                      Fix bug for initial root table size == max - 1
164e00368fSchristos                      Use a macro to compute the history index
17ed8eb4c2Schristos    1.4  18 Aug 2012  Avoid shifts more than bits in type (caused endless loop!)
18ed8eb4c2Schristos                      Clean up comparisons of different types
19ed8eb4c2Schristos                      Clean up code indentation
20*6881a400Schristos    1.5   5 Aug 2018  Clean up code style, formatting, and comments
21*6881a400Schristos                      Show all the codes for the maximum, and only the maximum
224e00368fSchristos  */
234e00368fSchristos 
244e00368fSchristos /*
25*6881a400Schristos    Examine all possible prefix codes for a given number of symbols and a
26*6881a400Schristos    maximum code length in bits to determine the maximum table size for zlib's
27*6881a400Schristos    inflate. Only complete prefix codes are counted.
284e00368fSchristos 
294e00368fSchristos    Two codes are considered distinct if the vectors of the number of codes per
304e00368fSchristos    length are not identical. So permutations of the symbol assignments result
314e00368fSchristos    in the same code for the counting, as do permutations of the assignments of
324e00368fSchristos    the bit values to the codes (i.e. only canonical codes are counted).
334e00368fSchristos 
344e00368fSchristos    We build a code from shorter to longer lengths, determining how many symbols
354e00368fSchristos    are coded at each length. At each step, we have how many symbols remain to
364e00368fSchristos    be coded, what the last code length used was, and how many bit patterns of
374e00368fSchristos    that length remain unused. Then we add one to the code length and double the
384e00368fSchristos    number of unused patterns to graduate to the next code length. We then
394e00368fSchristos    assign all portions of the remaining symbols to that code length that
404e00368fSchristos    preserve the properties of a correct and eventually complete code. Those
414e00368fSchristos    properties are: we cannot use more bit patterns than are available; and when
42*6881a400Schristos    all the symbols are used, there are exactly zero possible bit patterns left
43*6881a400Schristos    unused.
444e00368fSchristos 
454e00368fSchristos    The inflate Huffman decoding algorithm uses two-level lookup tables for
464e00368fSchristos    speed. There is a single first-level table to decode codes up to root bits
47*6881a400Schristos    in length (root == 9 for literal/length codes and root == 6 for distance
48*6881a400Schristos    codes, in the current inflate implementation). The base table has 1 << root
49*6881a400Schristos    entries and is indexed by the next root bits of input. Codes shorter than
50*6881a400Schristos    root bits have replicated table entries, so that the correct entry is
51*6881a400Schristos    pointed to regardless of the bits that follow the short code. If the code is
52*6881a400Schristos    longer than root bits, then the table entry points to a second-level table.
53*6881a400Schristos    The size of that table is determined by the longest code with that root-bit
54*6881a400Schristos    prefix. If that longest code has length len, then the table has size 1 <<
55*6881a400Schristos    (len - root), to index the remaining bits in that set of codes. Each
56*6881a400Schristos    subsequent root-bit prefix then has its own sub-table. The total number of
57*6881a400Schristos    table entries required by the code is calculated incrementally as the number
58*6881a400Schristos    of codes at each bit length is populated. When all of the codes are shorter
59*6881a400Schristos    than root bits, then root is reduced to the longest code length, resulting
60*6881a400Schristos    in a single, smaller, one-level table.
614e00368fSchristos 
624e00368fSchristos    The inflate algorithm also provides for small values of root (relative to
634e00368fSchristos    the log2 of the number of symbols), where the shortest code has more bits
644e00368fSchristos    than root. In that case, root is increased to the length of the shortest
654e00368fSchristos    code. This program, by design, does not handle that case, so it is verified
66*6881a400Schristos    that the number of symbols is less than 1 << (root + 1).
674e00368fSchristos 
684e00368fSchristos    In order to speed up the examination (by about ten orders of magnitude for
694e00368fSchristos    the default arguments), the intermediate states in the build-up of a code
704e00368fSchristos    are remembered and previously visited branches are pruned. The memory
714e00368fSchristos    required for this will increase rapidly with the total number of symbols and
724e00368fSchristos    the maximum code length in bits. However this is a very small price to pay
734e00368fSchristos    for the vast speedup.
744e00368fSchristos 
75*6881a400Schristos    First, all of the possible prefix codes are counted, and reachable
764e00368fSchristos    intermediate states are noted by a non-zero count in a saved-results array.
774e00368fSchristos    Second, the intermediate states that lead to (root + 1) bit or longer codes
784e00368fSchristos    are used to look at all sub-codes from those junctures for their inflate
794e00368fSchristos    memory usage. (The amount of memory used is not affected by the number of
804e00368fSchristos    codes of root bits or less in length.)  Third, the visited states in the
814e00368fSchristos    construction of those sub-codes and the associated calculation of the table
824e00368fSchristos    size is recalled in order to avoid recalculating from the same juncture.
834e00368fSchristos    Beginning the code examination at (root + 1) bit codes, which is enabled by
844e00368fSchristos    identifying the reachable nodes, accounts for about six of the orders of
854e00368fSchristos    magnitude of improvement for the default arguments. About another four
864e00368fSchristos    orders of magnitude come from not revisiting previous states. Out of
87*6881a400Schristos    approximately 2x10^16 possible prefix codes, only about 2x10^6 sub-codes
884e00368fSchristos    need to be examined to cover all of the possible table memory usage cases
894e00368fSchristos    for the default arguments of 286 symbols limited to 15-bit codes.
904e00368fSchristos 
91*6881a400Schristos    Note that the uintmax_t type is used for counting. It is quite easy to
92*6881a400Schristos    exceed the capacity of an eight-byte integer with a large number of symbols
93*6881a400Schristos    and a large maximum code length, so multiple-precision arithmetic would need
94*6881a400Schristos    to replace the integer arithmetic in that case. This program will abort if
95*6881a400Schristos    an overflow occurs. The big_t type identifies where the counting takes
96*6881a400Schristos    place.
974e00368fSchristos 
98*6881a400Schristos    The uintmax_t type is also used for calculating the number of possible codes
99*6881a400Schristos    remaining at the maximum length. This limits the maximum code length to the
100*6881a400Schristos    number of bits in a long long minus the number of bits needed to represent
101*6881a400Schristos    the symbols in a flat code. The code_t type identifies where the bit-pattern
102*6881a400Schristos    counting takes place.
1034e00368fSchristos  */
1044e00368fSchristos 
1054e00368fSchristos #include <stdio.h>
1064e00368fSchristos #include <stdlib.h>
1074e00368fSchristos #include <string.h>
108*6881a400Schristos #include <stdarg.h>
109*6881a400Schristos #include <stdint.h>
1104e00368fSchristos #include <assert.h>
1114e00368fSchristos 
1124e00368fSchristos #define local static
1134e00368fSchristos 
114*6881a400Schristos // Special data types.
115*6881a400Schristos typedef uintmax_t big_t;    // type for code counting
116*6881a400Schristos #define PRIbig "ju"         // printf format for big_t
117*6881a400Schristos typedef uintmax_t code_t;   // type for bit pattern counting
118*6881a400Schristos struct tab {                // type for been-here check
119*6881a400Schristos     size_t len;             // allocated length of bit vector in octets
120*6881a400Schristos     char *vec;              // allocated bit vector
1214e00368fSchristos };
1224e00368fSchristos 
1234e00368fSchristos /* The array for saving results, num[], is indexed with this triplet:
1244e00368fSchristos 
1254e00368fSchristos       syms: number of symbols remaining to code
1264e00368fSchristos       left: number of available bit patterns at length len
1274e00368fSchristos       len: number of bits in the codes currently being assigned
1284e00368fSchristos 
1294e00368fSchristos    Those indices are constrained thusly when saving results:
1304e00368fSchristos 
1314e00368fSchristos       syms: 3..totsym (totsym == total symbols to code)
1324e00368fSchristos       left: 2..syms - 1, but only the evens (so syms == 8 -> 2, 4, 6)
1334e00368fSchristos       len: 1..max - 1 (max == maximum code length in bits)
1344e00368fSchristos 
1354e00368fSchristos    syms == 2 is not saved since that immediately leads to a single code. left
1364e00368fSchristos    must be even, since it represents the number of available bit patterns at
137*6881a400Schristos    the current length, which is double the number at the previous length. left
138*6881a400Schristos    ends at syms-1 since left == syms immediately results in a single code.
1394e00368fSchristos    (left > sym is not allowed since that would result in an incomplete code.)
1404e00368fSchristos    len is less than max, since the code completes immediately when len == max.
1414e00368fSchristos 
142*6881a400Schristos    The offset into the array is calculated for the three indices with the first
143*6881a400Schristos    one (syms) being outermost, and the last one (len) being innermost. We build
144*6881a400Schristos    the array with length max-1 lists for the len index, with syms-3 of those
145*6881a400Schristos    for each symbol. There are totsym-2 of those, with each one varying in
146*6881a400Schristos    length as a function of sym. See the calculation of index in map() for the
147*6881a400Schristos    index, and the calculation of size in main() for the size of the array.
1484e00368fSchristos 
1494e00368fSchristos    For the deflate example of 286 symbols limited to 15-bit codes, the array
150*6881a400Schristos    has 284,284 entries, taking up 2.17 MB for an 8-byte big_t. More than half
151*6881a400Schristos    of the space allocated for saved results is actually used -- not all
152*6881a400Schristos    possible triplets are reached in the generation of valid prefix codes.
1534e00368fSchristos  */
1544e00368fSchristos 
1554e00368fSchristos /* The array for tracking visited states, done[], is itself indexed identically
1564e00368fSchristos    to the num[] array as described above for the (syms, left, len) triplet.
1574e00368fSchristos    Each element in the array is further indexed by the (mem, rem) doublet,
1584e00368fSchristos    where mem is the amount of inflate table space used so far, and rem is the
1594e00368fSchristos    remaining unused entries in the current inflate sub-table. Each indexed
1604e00368fSchristos    element is simply one bit indicating whether the state has been visited or
1614e00368fSchristos    not. Since the ranges for mem and rem are not known a priori, each bit
1624e00368fSchristos    vector is of a variable size, and grows as needed to accommodate the visited
1634e00368fSchristos    states. mem and rem are used to calculate a single index in a triangular
1644e00368fSchristos    array. Since the range of mem is expected in the default case to be about
1654e00368fSchristos    ten times larger than the range of rem, the array is skewed to reduce the
1664e00368fSchristos    memory usage, with eight times the range for mem than for rem. See the
167*6881a400Schristos    calculations for offset and bit in been_here() for the details.
1684e00368fSchristos 
1694e00368fSchristos    For the deflate example of 286 symbols limited to 15-bit codes, the bit
170*6881a400Schristos    vectors grow to total 5.5 MB, in addition to the 4.3 MB done array itself.
1714e00368fSchristos  */
1724e00368fSchristos 
173*6881a400Schristos // Type for a variable-length, allocated string.
174*6881a400Schristos typedef struct {
175*6881a400Schristos     char *str;          // pointer to allocated string
176*6881a400Schristos     size_t size;        // size of allocation
177*6881a400Schristos     size_t len;         // length of string, not including terminating zero
178*6881a400Schristos } string_t;
1794e00368fSchristos 
180*6881a400Schristos // Clear a string_t.
181*6881a400Schristos local void string_clear(string_t *s) {
182*6881a400Schristos     s->str[0] = 0;
183*6881a400Schristos     s->len = 0;
1844e00368fSchristos }
1854e00368fSchristos 
186*6881a400Schristos // Initialize a string_t.
187*6881a400Schristos local void string_init(string_t *s) {
188*6881a400Schristos     s->size = 16;
189*6881a400Schristos     s->str = malloc(s->size);
190*6881a400Schristos     assert(s->str != NULL && "out of memory");
191*6881a400Schristos     string_clear(s);
192*6881a400Schristos }
1934e00368fSchristos 
194*6881a400Schristos // Release the allocation of a string_t.
195*6881a400Schristos local void string_free(string_t *s) {
196*6881a400Schristos     free(s->str);
197*6881a400Schristos     s->str = NULL;
198*6881a400Schristos     s->size = 0;
199*6881a400Schristos     s->len = 0;
200*6881a400Schristos }
201*6881a400Schristos 
202*6881a400Schristos // Save the results of printf with fmt and the subsequent argument list to s.
203*6881a400Schristos // Each call appends to s. The allocated space for s is increased as needed.
204*6881a400Schristos local void string_printf(string_t *s, char *fmt, ...) {
205*6881a400Schristos     va_list ap;
206*6881a400Schristos     va_start(ap, fmt);
207*6881a400Schristos     size_t len = s->len;
208*6881a400Schristos     int ret = vsnprintf(s->str + len, s->size - len, fmt, ap);
209*6881a400Schristos     assert(ret >= 0 && "out of memory");
210*6881a400Schristos     s->len += ret;
211*6881a400Schristos     if (s->size < s->len + 1) {
212*6881a400Schristos         do {
213*6881a400Schristos             s->size <<= 1;
214*6881a400Schristos             assert(s->size != 0 && "overflow");
215*6881a400Schristos         } while (s->size < s->len + 1);
216*6881a400Schristos         s->str = realloc(s->str, s->size);
217*6881a400Schristos         assert(s->str != NULL && "out of memory");
218*6881a400Schristos         vsnprintf(s->str + len, s->size - len, fmt, ap);
219*6881a400Schristos     }
220*6881a400Schristos     va_end(ap);
221*6881a400Schristos }
222*6881a400Schristos 
223*6881a400Schristos // Globals to avoid propagating constants or constant pointers recursively.
224*6881a400Schristos struct {
225*6881a400Schristos     int max;            // maximum allowed bit length for the codes
226*6881a400Schristos     int root;           // size of base code table in bits
227*6881a400Schristos     int large;          // largest code table so far
228*6881a400Schristos     size_t size;        // number of elements in num and done
229*6881a400Schristos     big_t tot;          // total number of codes with maximum tables size
230*6881a400Schristos     string_t out;       // display of subcodes for maximum tables size
231*6881a400Schristos     int *code;          // number of symbols assigned to each bit length
232*6881a400Schristos     big_t *num;         // saved results array for code counting
233*6881a400Schristos     struct tab *done;   // states already evaluated array
234*6881a400Schristos } g;
235*6881a400Schristos 
236*6881a400Schristos // Index function for num[] and done[].
237*6881a400Schristos local inline size_t map(int syms, int left, int len) {
238*6881a400Schristos     return ((size_t)((syms - 1) >> 1) * ((syms - 2) >> 1) +
239*6881a400Schristos             (left >> 1) - 1) * (g.max - 1) +
240*6881a400Schristos            len - 1;
241*6881a400Schristos }
242*6881a400Schristos 
243*6881a400Schristos // Free allocated space in globals.
244*6881a400Schristos local void cleanup(void) {
245*6881a400Schristos     if (g.done != NULL) {
246*6881a400Schristos         for (size_t n = 0; n < g.size; n++)
247*6881a400Schristos             if (g.done[n].len)
248*6881a400Schristos                 free(g.done[n].vec);
249*6881a400Schristos         g.size = 0;
250*6881a400Schristos         free(g.done);   g.done = NULL;
251*6881a400Schristos     }
252*6881a400Schristos     free(g.num);    g.num = NULL;
253*6881a400Schristos     free(g.code);   g.code = NULL;
254*6881a400Schristos     string_free(&g.out);
255*6881a400Schristos }
256*6881a400Schristos 
257*6881a400Schristos // Return the number of possible prefix codes using bit patterns of lengths len
258*6881a400Schristos // through max inclusive, coding syms symbols, with left bit patterns of length
259*6881a400Schristos // len unused -- return -1 if there is an overflow in the counting. Keep a
260*6881a400Schristos // record of previous results in num to prevent repeating the same calculation.
261*6881a400Schristos local big_t count(int syms, int left, int len) {
262*6881a400Schristos     // see if only one possible code
2634e00368fSchristos     if (syms == left)
2644e00368fSchristos         return 1;
2654e00368fSchristos 
266*6881a400Schristos     // note and verify the expected state
267*6881a400Schristos     assert(syms > left && left > 0 && len < g.max);
2684e00368fSchristos 
269*6881a400Schristos     // see if we've done this one already
270*6881a400Schristos     size_t index = map(syms, left, len);
271*6881a400Schristos     big_t got = g.num[index];
2724e00368fSchristos     if (got)
273*6881a400Schristos         return got;         // we have -- return the saved result
2744e00368fSchristos 
275*6881a400Schristos     // we need to use at least this many bit patterns so that the code won't be
276*6881a400Schristos     // incomplete at the next length (more bit patterns than symbols)
277*6881a400Schristos     int least = (left << 1) - syms;
2784e00368fSchristos     if (least < 0)
2794e00368fSchristos         least = 0;
2804e00368fSchristos 
281*6881a400Schristos     // we can use at most this many bit patterns, lest there not be enough
282*6881a400Schristos     // available for the remaining symbols at the maximum length (if there were
283*6881a400Schristos     // no limit to the code length, this would become: most = left - 1)
284*6881a400Schristos     int most = (((code_t)left << (g.max - len)) - syms) /
285*6881a400Schristos                (((code_t)1 << (g.max - len)) - 1);
2864e00368fSchristos 
287*6881a400Schristos     // count all possible codes from this juncture and add them up
288*6881a400Schristos     big_t sum = 0;
289*6881a400Schristos     for (int use = least; use <= most; use++) {
290*6881a400Schristos         got = count(syms - use, (left - use) << 1, len + 1);
2914e00368fSchristos         sum += got;
292*6881a400Schristos         if (got == (big_t)-1 || sum < got)      // overflow
293*6881a400Schristos             return (big_t)-1;
2944e00368fSchristos     }
2954e00368fSchristos 
296*6881a400Schristos     // verify that all recursive calls are productive
2974e00368fSchristos     assert(sum != 0);
2984e00368fSchristos 
299*6881a400Schristos     // save the result and return it
300*6881a400Schristos     g.num[index] = sum;
3014e00368fSchristos     return sum;
3024e00368fSchristos }
3034e00368fSchristos 
304*6881a400Schristos // Return true if we've been here before, set to true if not. Set a bit in a
305*6881a400Schristos // bit vector to indicate visiting this state. Each (syms,len,left) state has a
306*6881a400Schristos // variable size bit vector indexed by (mem,rem). The bit vector is lengthened
307*6881a400Schristos // as needed to allow setting the (mem,rem) bit.
308*6881a400Schristos local int been_here(int syms, int left, int len, int mem, int rem) {
309*6881a400Schristos     // point to vector for (syms,left,len), bit in vector for (mem,rem)
310*6881a400Schristos     size_t index = map(syms, left, len);
311*6881a400Schristos     mem -= 1 << g.root;             // mem always includes the root table
312*6881a400Schristos     mem >>= 1;                      // mem and rem are always even
313*6881a400Schristos     rem >>= 1;
314*6881a400Schristos     size_t offset = (mem >> 3) + rem;
3154e00368fSchristos     offset = ((offset * (offset + 1)) >> 1) + rem;
316*6881a400Schristos     int bit = 1 << (mem & 7);
3174e00368fSchristos 
318*6881a400Schristos     // see if we've been here
319*6881a400Schristos     size_t length = g.done[index].len;
320*6881a400Schristos     if (offset < length && (g.done[index].vec[offset] & bit) != 0)
321*6881a400Schristos         return 1;       // done this!
3224e00368fSchristos 
323*6881a400Schristos     // we haven't been here before -- set the bit to show we have now
3244e00368fSchristos 
325*6881a400Schristos     // see if we need to lengthen the vector in order to set the bit
3264e00368fSchristos     if (length <= offset) {
327*6881a400Schristos         // if we have one already, enlarge it, zero out the appended space
328*6881a400Schristos         char *vector;
3294e00368fSchristos         if (length) {
3304e00368fSchristos             do {
3314e00368fSchristos                 length <<= 1;
3324e00368fSchristos             } while (length <= offset);
333*6881a400Schristos             vector = realloc(g.done[index].vec, length);
334*6881a400Schristos             assert(vector != NULL && "out of memory");
335*6881a400Schristos             memset(vector + g.done[index].len, 0, length - g.done[index].len);
3364e00368fSchristos         }
3374e00368fSchristos 
338*6881a400Schristos         // otherwise we need to make a new vector and zero it out
3394e00368fSchristos         else {
340*6881a400Schristos             length = 16;
3414e00368fSchristos             while (length <= offset)
3424e00368fSchristos                 length <<= 1;
343*6881a400Schristos             vector = calloc(length, 1);
344*6881a400Schristos             assert(vector != NULL && "out of memory");
3454e00368fSchristos         }
3464e00368fSchristos 
347*6881a400Schristos         // install the new vector
348*6881a400Schristos         g.done[index].len = length;
349*6881a400Schristos         g.done[index].vec = vector;
3504e00368fSchristos     }
3514e00368fSchristos 
352*6881a400Schristos     // set the bit
353*6881a400Schristos     g.done[index].vec[offset] |= bit;
3544e00368fSchristos     return 0;
3554e00368fSchristos }
3564e00368fSchristos 
357*6881a400Schristos // Examine all possible codes from the given node (syms, len, left). Compute
358*6881a400Schristos // the amount of memory required to build inflate's decoding tables, where the
359*6881a400Schristos // number of code structures used so far is mem, and the number remaining in
360*6881a400Schristos // the current sub-table is rem.
361*6881a400Schristos local void examine(int syms, int left, int len, int mem, int rem) {
362*6881a400Schristos     // see if we have a complete code
3634e00368fSchristos     if (syms == left) {
364*6881a400Schristos         // set the last code entry
365*6881a400Schristos         g.code[len] = left;
3664e00368fSchristos 
367*6881a400Schristos         // complete computation of memory used by this code
3684e00368fSchristos         while (rem < left) {
3694e00368fSchristos             left -= rem;
370*6881a400Schristos             rem = 1 << (len - g.root);
3714e00368fSchristos             mem += rem;
3724e00368fSchristos         }
3734e00368fSchristos         assert(rem == left);
3744e00368fSchristos 
375*6881a400Schristos         // if this is at the maximum, show the sub-code
376*6881a400Schristos         if (mem >= g.large) {
377*6881a400Schristos             // if this is a new maximum, update the maximum and clear out the
378*6881a400Schristos             // printed sub-codes from the previous maximum
379*6881a400Schristos             if (mem > g.large) {
380*6881a400Schristos                 g.large = mem;
381*6881a400Schristos                 string_clear(&g.out);
3824e00368fSchristos             }
3834e00368fSchristos 
384*6881a400Schristos             // compute the starting state for this sub-code
385*6881a400Schristos             syms = 0;
386*6881a400Schristos             left = 1 << g.max;
387*6881a400Schristos             for (int bits = g.max; bits > g.root; bits--) {
388*6881a400Schristos                 syms += g.code[bits];
389*6881a400Schristos                 left -= g.code[bits];
390*6881a400Schristos                 assert((left & 1) == 0);
391*6881a400Schristos                 left >>= 1;
392*6881a400Schristos             }
393*6881a400Schristos 
394*6881a400Schristos             // print the starting state and the resulting sub-code to g.out
395*6881a400Schristos             string_printf(&g.out, "<%u, %u, %u>:",
396*6881a400Schristos                           syms, g.root + 1, ((1 << g.root) - left) << 1);
397*6881a400Schristos             for (int bits = g.root + 1; bits <= g.max; bits++)
398*6881a400Schristos                 if (g.code[bits])
399*6881a400Schristos                     string_printf(&g.out, " %d[%d]", g.code[bits], bits);
400*6881a400Schristos             string_printf(&g.out, "\n");
401*6881a400Schristos         }
402*6881a400Schristos 
403*6881a400Schristos         // remove entries as we drop back down in the recursion
404*6881a400Schristos         g.code[len] = 0;
4054e00368fSchristos         return;
4064e00368fSchristos     }
4074e00368fSchristos 
408*6881a400Schristos     // prune the tree if we can
409*6881a400Schristos     if (been_here(syms, left, len, mem, rem))
4104e00368fSchristos         return;
4114e00368fSchristos 
412*6881a400Schristos     // we need to use at least this many bit patterns so that the code won't be
413*6881a400Schristos     // incomplete at the next length (more bit patterns than symbols)
414*6881a400Schristos     int least = (left << 1) - syms;
4154e00368fSchristos     if (least < 0)
4164e00368fSchristos         least = 0;
4174e00368fSchristos 
418*6881a400Schristos     // we can use at most this many bit patterns, lest there not be enough
419*6881a400Schristos     // available for the remaining symbols at the maximum length (if there were
420*6881a400Schristos     // no limit to the code length, this would become: most = left - 1)
421*6881a400Schristos     int most = (((code_t)left << (g.max - len)) - syms) /
422*6881a400Schristos                (((code_t)1 << (g.max - len)) - 1);
4234e00368fSchristos 
424*6881a400Schristos     // occupy least table spaces, creating new sub-tables as needed
425*6881a400Schristos     int use = least;
4264e00368fSchristos     while (rem < use) {
4274e00368fSchristos         use -= rem;
428*6881a400Schristos         rem = 1 << (len - g.root);
4294e00368fSchristos         mem += rem;
4304e00368fSchristos     }
4314e00368fSchristos     rem -= use;
4324e00368fSchristos 
433*6881a400Schristos     // examine codes from here, updating table space as we go
4344e00368fSchristos     for (use = least; use <= most; use++) {
435*6881a400Schristos         g.code[len] = use;
436*6881a400Schristos         examine(syms - use, (left - use) << 1, len + 1,
437*6881a400Schristos                 mem + (rem ? 1 << (len - g.root) : 0), rem << 1);
4384e00368fSchristos         if (rem == 0) {
439*6881a400Schristos             rem = 1 << (len - g.root);
4404e00368fSchristos             mem += rem;
4414e00368fSchristos         }
4424e00368fSchristos         rem--;
4434e00368fSchristos     }
4444e00368fSchristos 
445*6881a400Schristos     // remove entries as we drop back down in the recursion
446*6881a400Schristos     g.code[len] = 0;
4474e00368fSchristos }
4484e00368fSchristos 
449*6881a400Schristos // Look at all sub-codes starting with root + 1 bits. Look at only the valid
450*6881a400Schristos // intermediate code states (syms, left, len). For each completed code,
451*6881a400Schristos // calculate the amount of memory required by inflate to build the decoding
452*6881a400Schristos // tables. Find the maximum amount of memory required and show the codes that
453*6881a400Schristos // require that maximum.
454*6881a400Schristos local void enough(int syms) {
455*6881a400Schristos     // clear code
456*6881a400Schristos     for (int n = 0; n <= g.max; n++)
457*6881a400Schristos         g.code[n] = 0;
4584e00368fSchristos 
459*6881a400Schristos     // look at all (root + 1) bit and longer codes
460*6881a400Schristos     string_clear(&g.out);           // empty saved results
461*6881a400Schristos     g.large = 1 << g.root;          // base table
462*6881a400Schristos     if (g.root < g.max)             // otherwise, there's only a base table
463*6881a400Schristos         for (int n = 3; n <= syms; n++)
464*6881a400Schristos             for (int left = 2; left < n; left += 2) {
465*6881a400Schristos                 // look at all reachable (root + 1) bit nodes, and the
466*6881a400Schristos                 // resulting codes (complete at root + 2 or more)
467*6881a400Schristos                 size_t index = map(n, left, g.root + 1);
468*6881a400Schristos                 if (g.root + 1 < g.max && g.num[index]) // reachable node
469*6881a400Schristos                     examine(n, left, g.root + 1, 1 << g.root, 0);
4704e00368fSchristos 
471*6881a400Schristos                 // also look at root bit codes with completions at root + 1
472*6881a400Schristos                 // bits (not saved in num, since complete), just in case
473*6881a400Schristos                 if (g.num[index - 1] && n <= left << 1)
474*6881a400Schristos                     examine((n - left) << 1, (n - left) << 1, g.root + 1,
475*6881a400Schristos                             1 << g.root, 0);
4764e00368fSchristos             }
4774e00368fSchristos 
478*6881a400Schristos     // done
479*6881a400Schristos     printf("maximum of %d table entries for root = %d\n", g.large, g.root);
480*6881a400Schristos     fputs(g.out.str, stdout);
4814e00368fSchristos }
4824e00368fSchristos 
483*6881a400Schristos // Examine and show the total number of possible prefix codes for a given
484*6881a400Schristos // maximum number of symbols, initial root table size, and maximum code length
485*6881a400Schristos // in bits -- those are the command arguments in that order. The default values
486*6881a400Schristos // are 286, 9, and 15 respectively, for the deflate literal/length code. The
487*6881a400Schristos // possible codes are counted for each number of coded symbols from two to the
488*6881a400Schristos // maximum. The counts for each of those and the total number of codes are
489*6881a400Schristos // shown. The maximum number of inflate table entires is then calculated across
490*6881a400Schristos // all possible codes. Each new maximum number of table entries and the
491*6881a400Schristos // associated sub-code (starting at root + 1 == 10 bits) is shown.
492*6881a400Schristos //
493*6881a400Schristos // To count and examine prefix codes that are not length-limited, provide a
494*6881a400Schristos // maximum length equal to the number of symbols minus one.
495*6881a400Schristos //
496*6881a400Schristos // For the deflate literal/length code, use "enough". For the deflate distance
497*6881a400Schristos // code, use "enough 30 6".
498*6881a400Schristos int main(int argc, char **argv) {
499*6881a400Schristos     // set up globals for cleanup()
500*6881a400Schristos     g.code = NULL;
501*6881a400Schristos     g.num = NULL;
502*6881a400Schristos     g.done = NULL;
503*6881a400Schristos     string_init(&g.out);
5044e00368fSchristos 
505*6881a400Schristos     // get arguments -- default to the deflate literal/length code
506*6881a400Schristos     int syms = 286;
507*6881a400Schristos     g.root = 9;
508*6881a400Schristos     g.max = 15;
5094e00368fSchristos     if (argc > 1) {
5104e00368fSchristos         syms = atoi(argv[1]);
5114e00368fSchristos         if (argc > 2) {
512*6881a400Schristos             g.root = atoi(argv[2]);
5134e00368fSchristos             if (argc > 3)
514*6881a400Schristos                 g.max = atoi(argv[3]);
5154e00368fSchristos         }
5164e00368fSchristos     }
517*6881a400Schristos     if (argc > 4 || syms < 2 || g.root < 1 || g.max < 1) {
5184e00368fSchristos         fputs("invalid arguments, need: [sym >= 2 [root >= 1 [max >= 1]]]\n",
5194e00368fSchristos               stderr);
5204e00368fSchristos         return 1;
5214e00368fSchristos     }
5224e00368fSchristos 
523*6881a400Schristos     // if not restricting the code length, the longest is syms - 1
524*6881a400Schristos     if (g.max > syms - 1)
525*6881a400Schristos         g.max = syms - 1;
5264e00368fSchristos 
527*6881a400Schristos     // determine the number of bits in a code_t
528*6881a400Schristos     int bits = 0;
529*6881a400Schristos     for (code_t word = 1; word; word <<= 1)
530*6881a400Schristos         bits++;
5314e00368fSchristos 
532*6881a400Schristos     // make sure that the calculation of most will not overflow
533*6881a400Schristos     if (g.max > bits || (code_t)(syms - 2) >= ((code_t)-1 >> (g.max - 1))) {
5344e00368fSchristos         fputs("abort: code length too long for internal types\n", stderr);
5354e00368fSchristos         return 1;
5364e00368fSchristos     }
5374e00368fSchristos 
538*6881a400Schristos     // reject impossible code requests
539*6881a400Schristos     if ((code_t)(syms - 1) > ((code_t)1 << g.max) - 1) {
5404e00368fSchristos         fprintf(stderr, "%d symbols cannot be coded in %d bits\n",
541*6881a400Schristos                 syms, g.max);
5424e00368fSchristos         return 1;
5434e00368fSchristos     }
5444e00368fSchristos 
545*6881a400Schristos     // allocate code vector
546*6881a400Schristos     g.code = calloc(g.max + 1, sizeof(int));
547*6881a400Schristos     assert(g.code != NULL && "out of memory");
5484e00368fSchristos 
549*6881a400Schristos     // determine size of saved results array, checking for overflows,
550*6881a400Schristos     // allocate and clear the array (set all to zero with calloc())
551*6881a400Schristos     if (syms == 2)              // iff max == 1
552*6881a400Schristos         g.num = NULL;           // won't be saving any results
5534e00368fSchristos     else {
554*6881a400Schristos         g.size = syms >> 1;
555*6881a400Schristos         int n = (syms - 1) >> 1;
556*6881a400Schristos         assert(g.size <= (size_t)-1 / n && "overflow");
557*6881a400Schristos         g.size *= n;
558*6881a400Schristos         n = g.max - 1;
559*6881a400Schristos         assert(g.size <= (size_t)-1 / n && "overflow");
560*6881a400Schristos         g.size *= n;
561*6881a400Schristos         g.num = calloc(g.size, sizeof(big_t));
562*6881a400Schristos         assert(g.num != NULL && "out of memory");
5634e00368fSchristos     }
5644e00368fSchristos 
565*6881a400Schristos     // count possible codes for all numbers of symbols, add up counts
566*6881a400Schristos     big_t sum = 0;
567*6881a400Schristos     for (int n = 2; n <= syms; n++) {
568*6881a400Schristos         big_t got = count(n, 2, 1);
5694e00368fSchristos         sum += got;
570*6881a400Schristos         assert(got != (big_t)-1 && sum >= got && "overflow");
5714e00368fSchristos     }
572*6881a400Schristos     printf("%"PRIbig" total codes for 2 to %d symbols", sum, syms);
573*6881a400Schristos     if (g.max < syms - 1)
574*6881a400Schristos         printf(" (%d-bit length limit)\n", g.max);
5754e00368fSchristos     else
5764e00368fSchristos         puts(" (no length limit)");
5774e00368fSchristos 
578*6881a400Schristos     // allocate and clear done array for been_here()
5794e00368fSchristos     if (syms == 2)
580*6881a400Schristos         g.done = NULL;
581*6881a400Schristos     else {
582*6881a400Schristos         g.done = calloc(g.size, sizeof(struct tab));
583*6881a400Schristos         assert(g.done != NULL && "out of memory");
5844e00368fSchristos     }
5854e00368fSchristos 
586*6881a400Schristos     // find and show maximum inflate table usage
587*6881a400Schristos     if (g.root > g.max)             // reduce root to max length
588*6881a400Schristos         g.root = g.max;
589*6881a400Schristos     if ((code_t)syms < ((code_t)1 << (g.root + 1)))
5904e00368fSchristos         enough(syms);
5914e00368fSchristos     else
592*6881a400Schristos         fputs("cannot handle minimum code lengths > root", stderr);
5934e00368fSchristos 
594*6881a400Schristos     // done
5954e00368fSchristos     cleanup();
5964e00368fSchristos     return 0;
5974e00368fSchristos }
598