1212397c6Schristos /* enough.c -- determine the maximum size of inflate's Huffman code tables over
2*4b169a6bSchristos * all possible valid and complete prefix codes, subject to a length limit.
3*4b169a6bSchristos * Copyright (C) 2007, 2008, 2012, 2018 Mark Adler
4*4b169a6bSchristos * Version 1.5 5 August 2018 Mark Adler
5212397c6Schristos */
6212397c6Schristos
7212397c6Schristos /* Version history:
8212397c6Schristos 1.0 3 Jan 2007 First version (derived from codecount.c version 1.4)
9212397c6Schristos 1.1 4 Jan 2007 Use faster incremental table usage computation
10212397c6Schristos Prune examine() search on previously visited states
11212397c6Schristos 1.2 5 Jan 2007 Comments clean up
12212397c6Schristos As inflate does, decrease root for short codes
13212397c6Schristos Refuse cases where inflate would increase root
14212397c6Schristos 1.3 17 Feb 2008 Add argument for initial root table size
15212397c6Schristos Fix bug for initial root table size == max - 1
16212397c6Schristos Use a macro to compute the history index
17ba340e45Schristos 1.4 18 Aug 2012 Avoid shifts more than bits in type (caused endless loop!)
18ba340e45Schristos Clean up comparisons of different types
19ba340e45Schristos Clean up code indentation
20*4b169a6bSchristos 1.5 5 Aug 2018 Clean up code style, formatting, and comments
21*4b169a6bSchristos Show all the codes for the maximum, and only the maximum
22212397c6Schristos */
23212397c6Schristos
24212397c6Schristos /*
25*4b169a6bSchristos Examine all possible prefix codes for a given number of symbols and a
26*4b169a6bSchristos maximum code length in bits to determine the maximum table size for zlib's
27*4b169a6bSchristos inflate. Only complete prefix codes are counted.
28212397c6Schristos
29212397c6Schristos Two codes are considered distinct if the vectors of the number of codes per
30212397c6Schristos length are not identical. So permutations of the symbol assignments result
31212397c6Schristos in the same code for the counting, as do permutations of the assignments of
32212397c6Schristos the bit values to the codes (i.e. only canonical codes are counted).
33212397c6Schristos
34212397c6Schristos We build a code from shorter to longer lengths, determining how many symbols
35212397c6Schristos are coded at each length. At each step, we have how many symbols remain to
36212397c6Schristos be coded, what the last code length used was, and how many bit patterns of
37212397c6Schristos that length remain unused. Then we add one to the code length and double the
38212397c6Schristos number of unused patterns to graduate to the next code length. We then
39212397c6Schristos assign all portions of the remaining symbols to that code length that
40212397c6Schristos preserve the properties of a correct and eventually complete code. Those
41212397c6Schristos properties are: we cannot use more bit patterns than are available; and when
42*4b169a6bSchristos all the symbols are used, there are exactly zero possible bit patterns left
43*4b169a6bSchristos unused.
44212397c6Schristos
45212397c6Schristos The inflate Huffman decoding algorithm uses two-level lookup tables for
46212397c6Schristos speed. There is a single first-level table to decode codes up to root bits
47*4b169a6bSchristos in length (root == 9 for literal/length codes and root == 6 for distance
48*4b169a6bSchristos codes, in the current inflate implementation). The base table has 1 << root
49*4b169a6bSchristos entries and is indexed by the next root bits of input. Codes shorter than
50*4b169a6bSchristos root bits have replicated table entries, so that the correct entry is
51*4b169a6bSchristos pointed to regardless of the bits that follow the short code. If the code is
52*4b169a6bSchristos longer than root bits, then the table entry points to a second-level table.
53*4b169a6bSchristos The size of that table is determined by the longest code with that root-bit
54*4b169a6bSchristos prefix. If that longest code has length len, then the table has size 1 <<
55*4b169a6bSchristos (len - root), to index the remaining bits in that set of codes. Each
56*4b169a6bSchristos subsequent root-bit prefix then has its own sub-table. The total number of
57*4b169a6bSchristos table entries required by the code is calculated incrementally as the number
58*4b169a6bSchristos of codes at each bit length is populated. When all of the codes are shorter
59*4b169a6bSchristos than root bits, then root is reduced to the longest code length, resulting
60*4b169a6bSchristos in a single, smaller, one-level table.
61212397c6Schristos
62212397c6Schristos The inflate algorithm also provides for small values of root (relative to
63212397c6Schristos the log2 of the number of symbols), where the shortest code has more bits
64212397c6Schristos than root. In that case, root is increased to the length of the shortest
65212397c6Schristos code. This program, by design, does not handle that case, so it is verified
66*4b169a6bSchristos that the number of symbols is less than 1 << (root + 1).
67212397c6Schristos
68212397c6Schristos In order to speed up the examination (by about ten orders of magnitude for
69212397c6Schristos the default arguments), the intermediate states in the build-up of a code
70212397c6Schristos are remembered and previously visited branches are pruned. The memory
71212397c6Schristos required for this will increase rapidly with the total number of symbols and
72212397c6Schristos the maximum code length in bits. However this is a very small price to pay
73212397c6Schristos for the vast speedup.
74212397c6Schristos
75*4b169a6bSchristos First, all of the possible prefix codes are counted, and reachable
76212397c6Schristos intermediate states are noted by a non-zero count in a saved-results array.
77212397c6Schristos Second, the intermediate states that lead to (root + 1) bit or longer codes
78212397c6Schristos are used to look at all sub-codes from those junctures for their inflate
79212397c6Schristos memory usage. (The amount of memory used is not affected by the number of
80212397c6Schristos codes of root bits or less in length.) Third, the visited states in the
81212397c6Schristos construction of those sub-codes and the associated calculation of the table
82212397c6Schristos size is recalled in order to avoid recalculating from the same juncture.
83212397c6Schristos Beginning the code examination at (root + 1) bit codes, which is enabled by
84212397c6Schristos identifying the reachable nodes, accounts for about six of the orders of
85212397c6Schristos magnitude of improvement for the default arguments. About another four
86212397c6Schristos orders of magnitude come from not revisiting previous states. Out of
87*4b169a6bSchristos approximately 2x10^16 possible prefix codes, only about 2x10^6 sub-codes
88212397c6Schristos need to be examined to cover all of the possible table memory usage cases
89212397c6Schristos for the default arguments of 286 symbols limited to 15-bit codes.
90212397c6Schristos
91*4b169a6bSchristos Note that the uintmax_t type is used for counting. It is quite easy to
92*4b169a6bSchristos exceed the capacity of an eight-byte integer with a large number of symbols
93*4b169a6bSchristos and a large maximum code length, so multiple-precision arithmetic would need
94*4b169a6bSchristos to replace the integer arithmetic in that case. This program will abort if
95*4b169a6bSchristos an overflow occurs. The big_t type identifies where the counting takes
96*4b169a6bSchristos place.
97212397c6Schristos
98*4b169a6bSchristos The uintmax_t type is also used for calculating the number of possible codes
99*4b169a6bSchristos remaining at the maximum length. This limits the maximum code length to the
100*4b169a6bSchristos number of bits in a long long minus the number of bits needed to represent
101*4b169a6bSchristos the symbols in a flat code. The code_t type identifies where the bit-pattern
102*4b169a6bSchristos counting takes place.
103212397c6Schristos */
104212397c6Schristos
105212397c6Schristos #include <stdio.h>
106212397c6Schristos #include <stdlib.h>
107212397c6Schristos #include <string.h>
108*4b169a6bSchristos #include <stdarg.h>
109*4b169a6bSchristos #include <stdint.h>
110212397c6Schristos #include <assert.h>
111212397c6Schristos
112212397c6Schristos #define local static
113212397c6Schristos
114*4b169a6bSchristos // Special data types.
115*4b169a6bSchristos typedef uintmax_t big_t; // type for code counting
116*4b169a6bSchristos #define PRIbig "ju" // printf format for big_t
117*4b169a6bSchristos typedef uintmax_t code_t; // type for bit pattern counting
118*4b169a6bSchristos struct tab { // type for been-here check
119*4b169a6bSchristos size_t len; // allocated length of bit vector in octets
120*4b169a6bSchristos char *vec; // allocated bit vector
121212397c6Schristos };
122212397c6Schristos
123212397c6Schristos /* The array for saving results, num[], is indexed with this triplet:
124212397c6Schristos
125212397c6Schristos syms: number of symbols remaining to code
126212397c6Schristos left: number of available bit patterns at length len
127212397c6Schristos len: number of bits in the codes currently being assigned
128212397c6Schristos
129212397c6Schristos Those indices are constrained thusly when saving results:
130212397c6Schristos
131212397c6Schristos syms: 3..totsym (totsym == total symbols to code)
132212397c6Schristos left: 2..syms - 1, but only the evens (so syms == 8 -> 2, 4, 6)
133212397c6Schristos len: 1..max - 1 (max == maximum code length in bits)
134212397c6Schristos
135212397c6Schristos syms == 2 is not saved since that immediately leads to a single code. left
136212397c6Schristos must be even, since it represents the number of available bit patterns at
137*4b169a6bSchristos the current length, which is double the number at the previous length. left
138*4b169a6bSchristos ends at syms-1 since left == syms immediately results in a single code.
139212397c6Schristos (left > sym is not allowed since that would result in an incomplete code.)
140212397c6Schristos len is less than max, since the code completes immediately when len == max.
141212397c6Schristos
142*4b169a6bSchristos The offset into the array is calculated for the three indices with the first
143*4b169a6bSchristos one (syms) being outermost, and the last one (len) being innermost. We build
144*4b169a6bSchristos the array with length max-1 lists for the len index, with syms-3 of those
145*4b169a6bSchristos for each symbol. There are totsym-2 of those, with each one varying in
146*4b169a6bSchristos length as a function of sym. See the calculation of index in map() for the
147*4b169a6bSchristos index, and the calculation of size in main() for the size of the array.
148212397c6Schristos
149212397c6Schristos For the deflate example of 286 symbols limited to 15-bit codes, the array
150*4b169a6bSchristos has 284,284 entries, taking up 2.17 MB for an 8-byte big_t. More than half
151*4b169a6bSchristos of the space allocated for saved results is actually used -- not all
152*4b169a6bSchristos possible triplets are reached in the generation of valid prefix codes.
153212397c6Schristos */
154212397c6Schristos
155212397c6Schristos /* The array for tracking visited states, done[], is itself indexed identically
156212397c6Schristos to the num[] array as described above for the (syms, left, len) triplet.
157212397c6Schristos Each element in the array is further indexed by the (mem, rem) doublet,
158212397c6Schristos where mem is the amount of inflate table space used so far, and rem is the
159212397c6Schristos remaining unused entries in the current inflate sub-table. Each indexed
160212397c6Schristos element is simply one bit indicating whether the state has been visited or
161212397c6Schristos not. Since the ranges for mem and rem are not known a priori, each bit
162212397c6Schristos vector is of a variable size, and grows as needed to accommodate the visited
163212397c6Schristos states. mem and rem are used to calculate a single index in a triangular
164212397c6Schristos array. Since the range of mem is expected in the default case to be about
165212397c6Schristos ten times larger than the range of rem, the array is skewed to reduce the
166212397c6Schristos memory usage, with eight times the range for mem than for rem. See the
167*4b169a6bSchristos calculations for offset and bit in been_here() for the details.
168212397c6Schristos
169212397c6Schristos For the deflate example of 286 symbols limited to 15-bit codes, the bit
170*4b169a6bSchristos vectors grow to total 5.5 MB, in addition to the 4.3 MB done array itself.
171212397c6Schristos */
172212397c6Schristos
173*4b169a6bSchristos // Type for a variable-length, allocated string.
174*4b169a6bSchristos typedef struct {
175*4b169a6bSchristos char *str; // pointer to allocated string
176*4b169a6bSchristos size_t size; // size of allocation
177*4b169a6bSchristos size_t len; // length of string, not including terminating zero
178*4b169a6bSchristos } string_t;
179212397c6Schristos
180*4b169a6bSchristos // Clear a string_t.
string_clear(string_t * s)181*4b169a6bSchristos local void string_clear(string_t *s) {
182*4b169a6bSchristos s->str[0] = 0;
183*4b169a6bSchristos s->len = 0;
184212397c6Schristos }
185212397c6Schristos
186*4b169a6bSchristos // Initialize a string_t.
string_init(string_t * s)187*4b169a6bSchristos local void string_init(string_t *s) {
188*4b169a6bSchristos s->size = 16;
189*4b169a6bSchristos s->str = malloc(s->size);
190*4b169a6bSchristos assert(s->str != NULL && "out of memory");
191*4b169a6bSchristos string_clear(s);
192*4b169a6bSchristos }
193212397c6Schristos
194*4b169a6bSchristos // Release the allocation of a string_t.
string_free(string_t * s)195*4b169a6bSchristos local void string_free(string_t *s) {
196*4b169a6bSchristos free(s->str);
197*4b169a6bSchristos s->str = NULL;
198*4b169a6bSchristos s->size = 0;
199*4b169a6bSchristos s->len = 0;
200*4b169a6bSchristos }
201*4b169a6bSchristos
202*4b169a6bSchristos // Save the results of printf with fmt and the subsequent argument list to s.
203*4b169a6bSchristos // Each call appends to s. The allocated space for s is increased as needed.
string_printf(string_t * s,char * fmt,...)204*4b169a6bSchristos local void string_printf(string_t *s, char *fmt, ...) {
205*4b169a6bSchristos va_list ap;
206*4b169a6bSchristos va_start(ap, fmt);
207*4b169a6bSchristos size_t len = s->len;
208*4b169a6bSchristos int ret = vsnprintf(s->str + len, s->size - len, fmt, ap);
209*4b169a6bSchristos assert(ret >= 0 && "out of memory");
210*4b169a6bSchristos s->len += ret;
211*4b169a6bSchristos if (s->size < s->len + 1) {
212*4b169a6bSchristos do {
213*4b169a6bSchristos s->size <<= 1;
214*4b169a6bSchristos assert(s->size != 0 && "overflow");
215*4b169a6bSchristos } while (s->size < s->len + 1);
216*4b169a6bSchristos s->str = realloc(s->str, s->size);
217*4b169a6bSchristos assert(s->str != NULL && "out of memory");
218*4b169a6bSchristos vsnprintf(s->str + len, s->size - len, fmt, ap);
219*4b169a6bSchristos }
220*4b169a6bSchristos va_end(ap);
221*4b169a6bSchristos }
222*4b169a6bSchristos
223*4b169a6bSchristos // Globals to avoid propagating constants or constant pointers recursively.
224*4b169a6bSchristos struct {
225*4b169a6bSchristos int max; // maximum allowed bit length for the codes
226*4b169a6bSchristos int root; // size of base code table in bits
227*4b169a6bSchristos int large; // largest code table so far
228*4b169a6bSchristos size_t size; // number of elements in num and done
229*4b169a6bSchristos big_t tot; // total number of codes with maximum tables size
230*4b169a6bSchristos string_t out; // display of subcodes for maximum tables size
231*4b169a6bSchristos int *code; // number of symbols assigned to each bit length
232*4b169a6bSchristos big_t *num; // saved results array for code counting
233*4b169a6bSchristos struct tab *done; // states already evaluated array
234*4b169a6bSchristos } g;
235*4b169a6bSchristos
236*4b169a6bSchristos // Index function for num[] and done[].
map(int syms,int left,int len)237*4b169a6bSchristos local inline size_t map(int syms, int left, int len) {
238*4b169a6bSchristos return ((size_t)((syms - 1) >> 1) * ((syms - 2) >> 1) +
239*4b169a6bSchristos (left >> 1) - 1) * (g.max - 1) +
240*4b169a6bSchristos len - 1;
241*4b169a6bSchristos }
242*4b169a6bSchristos
243*4b169a6bSchristos // Free allocated space in globals.
cleanup(void)244*4b169a6bSchristos local void cleanup(void) {
245*4b169a6bSchristos if (g.done != NULL) {
246*4b169a6bSchristos for (size_t n = 0; n < g.size; n++)
247*4b169a6bSchristos if (g.done[n].len)
248*4b169a6bSchristos free(g.done[n].vec);
249*4b169a6bSchristos g.size = 0;
250*4b169a6bSchristos free(g.done); g.done = NULL;
251*4b169a6bSchristos }
252*4b169a6bSchristos free(g.num); g.num = NULL;
253*4b169a6bSchristos free(g.code); g.code = NULL;
254*4b169a6bSchristos string_free(&g.out);
255*4b169a6bSchristos }
256*4b169a6bSchristos
257*4b169a6bSchristos // Return the number of possible prefix codes using bit patterns of lengths len
258*4b169a6bSchristos // through max inclusive, coding syms symbols, with left bit patterns of length
259*4b169a6bSchristos // len unused -- return -1 if there is an overflow in the counting. Keep a
260*4b169a6bSchristos // record of previous results in num to prevent repeating the same calculation.
count(int syms,int left,int len)261*4b169a6bSchristos local big_t count(int syms, int left, int len) {
262*4b169a6bSchristos // see if only one possible code
263212397c6Schristos if (syms == left)
264212397c6Schristos return 1;
265212397c6Schristos
266*4b169a6bSchristos // note and verify the expected state
267*4b169a6bSchristos assert(syms > left && left > 0 && len < g.max);
268212397c6Schristos
269*4b169a6bSchristos // see if we've done this one already
270*4b169a6bSchristos size_t index = map(syms, left, len);
271*4b169a6bSchristos big_t got = g.num[index];
272212397c6Schristos if (got)
273*4b169a6bSchristos return got; // we have -- return the saved result
274212397c6Schristos
275*4b169a6bSchristos // we need to use at least this many bit patterns so that the code won't be
276*4b169a6bSchristos // incomplete at the next length (more bit patterns than symbols)
277*4b169a6bSchristos int least = (left << 1) - syms;
278212397c6Schristos if (least < 0)
279212397c6Schristos least = 0;
280212397c6Schristos
281*4b169a6bSchristos // we can use at most this many bit patterns, lest there not be enough
282*4b169a6bSchristos // available for the remaining symbols at the maximum length (if there were
283*4b169a6bSchristos // no limit to the code length, this would become: most = left - 1)
284*4b169a6bSchristos int most = (((code_t)left << (g.max - len)) - syms) /
285*4b169a6bSchristos (((code_t)1 << (g.max - len)) - 1);
286212397c6Schristos
287*4b169a6bSchristos // count all possible codes from this juncture and add them up
288*4b169a6bSchristos big_t sum = 0;
289*4b169a6bSchristos for (int use = least; use <= most; use++) {
290*4b169a6bSchristos got = count(syms - use, (left - use) << 1, len + 1);
291212397c6Schristos sum += got;
292*4b169a6bSchristos if (got == (big_t)-1 || sum < got) // overflow
293*4b169a6bSchristos return (big_t)-1;
294212397c6Schristos }
295212397c6Schristos
296*4b169a6bSchristos // verify that all recursive calls are productive
297212397c6Schristos assert(sum != 0);
298212397c6Schristos
299*4b169a6bSchristos // save the result and return it
300*4b169a6bSchristos g.num[index] = sum;
301212397c6Schristos return sum;
302212397c6Schristos }
303212397c6Schristos
304*4b169a6bSchristos // Return true if we've been here before, set to true if not. Set a bit in a
305*4b169a6bSchristos // bit vector to indicate visiting this state. Each (syms,len,left) state has a
306*4b169a6bSchristos // variable size bit vector indexed by (mem,rem). The bit vector is lengthened
307*4b169a6bSchristos // as needed to allow setting the (mem,rem) bit.
been_here(int syms,int left,int len,int mem,int rem)308*4b169a6bSchristos local int been_here(int syms, int left, int len, int mem, int rem) {
309*4b169a6bSchristos // point to vector for (syms,left,len), bit in vector for (mem,rem)
310*4b169a6bSchristos size_t index = map(syms, left, len);
311*4b169a6bSchristos mem -= 1 << g.root; // mem always includes the root table
312*4b169a6bSchristos mem >>= 1; // mem and rem are always even
313*4b169a6bSchristos rem >>= 1;
314*4b169a6bSchristos size_t offset = (mem >> 3) + rem;
315212397c6Schristos offset = ((offset * (offset + 1)) >> 1) + rem;
316*4b169a6bSchristos int bit = 1 << (mem & 7);
317212397c6Schristos
318*4b169a6bSchristos // see if we've been here
319*4b169a6bSchristos size_t length = g.done[index].len;
320*4b169a6bSchristos if (offset < length && (g.done[index].vec[offset] & bit) != 0)
321*4b169a6bSchristos return 1; // done this!
322212397c6Schristos
323*4b169a6bSchristos // we haven't been here before -- set the bit to show we have now
324212397c6Schristos
325*4b169a6bSchristos // see if we need to lengthen the vector in order to set the bit
326212397c6Schristos if (length <= offset) {
327*4b169a6bSchristos // if we have one already, enlarge it, zero out the appended space
328*4b169a6bSchristos char *vector;
329212397c6Schristos if (length) {
330212397c6Schristos do {
331212397c6Schristos length <<= 1;
332212397c6Schristos } while (length <= offset);
333*4b169a6bSchristos vector = realloc(g.done[index].vec, length);
334*4b169a6bSchristos assert(vector != NULL && "out of memory");
335*4b169a6bSchristos memset(vector + g.done[index].len, 0, length - g.done[index].len);
336212397c6Schristos }
337212397c6Schristos
338*4b169a6bSchristos // otherwise we need to make a new vector and zero it out
339212397c6Schristos else {
340*4b169a6bSchristos length = 16;
341212397c6Schristos while (length <= offset)
342212397c6Schristos length <<= 1;
343*4b169a6bSchristos vector = calloc(length, 1);
344*4b169a6bSchristos assert(vector != NULL && "out of memory");
345212397c6Schristos }
346212397c6Schristos
347*4b169a6bSchristos // install the new vector
348*4b169a6bSchristos g.done[index].len = length;
349*4b169a6bSchristos g.done[index].vec = vector;
350212397c6Schristos }
351212397c6Schristos
352*4b169a6bSchristos // set the bit
353*4b169a6bSchristos g.done[index].vec[offset] |= bit;
354212397c6Schristos return 0;
355212397c6Schristos }
356212397c6Schristos
357*4b169a6bSchristos // Examine all possible codes from the given node (syms, len, left). Compute
358*4b169a6bSchristos // the amount of memory required to build inflate's decoding tables, where the
359*4b169a6bSchristos // number of code structures used so far is mem, and the number remaining in
360*4b169a6bSchristos // the current sub-table is rem.
examine(int syms,int left,int len,int mem,int rem)361*4b169a6bSchristos local void examine(int syms, int left, int len, int mem, int rem) {
362*4b169a6bSchristos // see if we have a complete code
363212397c6Schristos if (syms == left) {
364*4b169a6bSchristos // set the last code entry
365*4b169a6bSchristos g.code[len] = left;
366212397c6Schristos
367*4b169a6bSchristos // complete computation of memory used by this code
368212397c6Schristos while (rem < left) {
369212397c6Schristos left -= rem;
370*4b169a6bSchristos rem = 1 << (len - g.root);
371212397c6Schristos mem += rem;
372212397c6Schristos }
373212397c6Schristos assert(rem == left);
374212397c6Schristos
375*4b169a6bSchristos // if this is at the maximum, show the sub-code
376*4b169a6bSchristos if (mem >= g.large) {
377*4b169a6bSchristos // if this is a new maximum, update the maximum and clear out the
378*4b169a6bSchristos // printed sub-codes from the previous maximum
379*4b169a6bSchristos if (mem > g.large) {
380*4b169a6bSchristos g.large = mem;
381*4b169a6bSchristos string_clear(&g.out);
382212397c6Schristos }
383212397c6Schristos
384*4b169a6bSchristos // compute the starting state for this sub-code
385*4b169a6bSchristos syms = 0;
386*4b169a6bSchristos left = 1 << g.max;
387*4b169a6bSchristos for (int bits = g.max; bits > g.root; bits--) {
388*4b169a6bSchristos syms += g.code[bits];
389*4b169a6bSchristos left -= g.code[bits];
390*4b169a6bSchristos assert((left & 1) == 0);
391*4b169a6bSchristos left >>= 1;
392*4b169a6bSchristos }
393*4b169a6bSchristos
394*4b169a6bSchristos // print the starting state and the resulting sub-code to g.out
395*4b169a6bSchristos string_printf(&g.out, "<%u, %u, %u>:",
396*4b169a6bSchristos syms, g.root + 1, ((1 << g.root) - left) << 1);
397*4b169a6bSchristos for (int bits = g.root + 1; bits <= g.max; bits++)
398*4b169a6bSchristos if (g.code[bits])
399*4b169a6bSchristos string_printf(&g.out, " %d[%d]", g.code[bits], bits);
400*4b169a6bSchristos string_printf(&g.out, "\n");
401*4b169a6bSchristos }
402*4b169a6bSchristos
403*4b169a6bSchristos // remove entries as we drop back down in the recursion
404*4b169a6bSchristos g.code[len] = 0;
405212397c6Schristos return;
406212397c6Schristos }
407212397c6Schristos
408*4b169a6bSchristos // prune the tree if we can
409*4b169a6bSchristos if (been_here(syms, left, len, mem, rem))
410212397c6Schristos return;
411212397c6Schristos
412*4b169a6bSchristos // we need to use at least this many bit patterns so that the code won't be
413*4b169a6bSchristos // incomplete at the next length (more bit patterns than symbols)
414*4b169a6bSchristos int least = (left << 1) - syms;
415212397c6Schristos if (least < 0)
416212397c6Schristos least = 0;
417212397c6Schristos
418*4b169a6bSchristos // we can use at most this many bit patterns, lest there not be enough
419*4b169a6bSchristos // available for the remaining symbols at the maximum length (if there were
420*4b169a6bSchristos // no limit to the code length, this would become: most = left - 1)
421*4b169a6bSchristos int most = (((code_t)left << (g.max - len)) - syms) /
422*4b169a6bSchristos (((code_t)1 << (g.max - len)) - 1);
423212397c6Schristos
424*4b169a6bSchristos // occupy least table spaces, creating new sub-tables as needed
425*4b169a6bSchristos int use = least;
426212397c6Schristos while (rem < use) {
427212397c6Schristos use -= rem;
428*4b169a6bSchristos rem = 1 << (len - g.root);
429212397c6Schristos mem += rem;
430212397c6Schristos }
431212397c6Schristos rem -= use;
432212397c6Schristos
433*4b169a6bSchristos // examine codes from here, updating table space as we go
434212397c6Schristos for (use = least; use <= most; use++) {
435*4b169a6bSchristos g.code[len] = use;
436*4b169a6bSchristos examine(syms - use, (left - use) << 1, len + 1,
437*4b169a6bSchristos mem + (rem ? 1 << (len - g.root) : 0), rem << 1);
438212397c6Schristos if (rem == 0) {
439*4b169a6bSchristos rem = 1 << (len - g.root);
440212397c6Schristos mem += rem;
441212397c6Schristos }
442212397c6Schristos rem--;
443212397c6Schristos }
444212397c6Schristos
445*4b169a6bSchristos // remove entries as we drop back down in the recursion
446*4b169a6bSchristos g.code[len] = 0;
447212397c6Schristos }
448212397c6Schristos
449*4b169a6bSchristos // Look at all sub-codes starting with root + 1 bits. Look at only the valid
450*4b169a6bSchristos // intermediate code states (syms, left, len). For each completed code,
451*4b169a6bSchristos // calculate the amount of memory required by inflate to build the decoding
452*4b169a6bSchristos // tables. Find the maximum amount of memory required and show the codes that
453*4b169a6bSchristos // require that maximum.
enough(int syms)454*4b169a6bSchristos local void enough(int syms) {
455*4b169a6bSchristos // clear code
456*4b169a6bSchristos for (int n = 0; n <= g.max; n++)
457*4b169a6bSchristos g.code[n] = 0;
458212397c6Schristos
459*4b169a6bSchristos // look at all (root + 1) bit and longer codes
460*4b169a6bSchristos string_clear(&g.out); // empty saved results
461*4b169a6bSchristos g.large = 1 << g.root; // base table
462*4b169a6bSchristos if (g.root < g.max) // otherwise, there's only a base table
463*4b169a6bSchristos for (int n = 3; n <= syms; n++)
464*4b169a6bSchristos for (int left = 2; left < n; left += 2) {
465*4b169a6bSchristos // look at all reachable (root + 1) bit nodes, and the
466*4b169a6bSchristos // resulting codes (complete at root + 2 or more)
467*4b169a6bSchristos size_t index = map(n, left, g.root + 1);
468*4b169a6bSchristos if (g.root + 1 < g.max && g.num[index]) // reachable node
469*4b169a6bSchristos examine(n, left, g.root + 1, 1 << g.root, 0);
470212397c6Schristos
471*4b169a6bSchristos // also look at root bit codes with completions at root + 1
472*4b169a6bSchristos // bits (not saved in num, since complete), just in case
473*4b169a6bSchristos if (g.num[index - 1] && n <= left << 1)
474*4b169a6bSchristos examine((n - left) << 1, (n - left) << 1, g.root + 1,
475*4b169a6bSchristos 1 << g.root, 0);
476212397c6Schristos }
477212397c6Schristos
478*4b169a6bSchristos // done
479*4b169a6bSchristos printf("maximum of %d table entries for root = %d\n", g.large, g.root);
480*4b169a6bSchristos fputs(g.out.str, stdout);
481212397c6Schristos }
482212397c6Schristos
483*4b169a6bSchristos // Examine and show the total number of possible prefix codes for a given
484*4b169a6bSchristos // maximum number of symbols, initial root table size, and maximum code length
485*4b169a6bSchristos // in bits -- those are the command arguments in that order. The default values
486*4b169a6bSchristos // are 286, 9, and 15 respectively, for the deflate literal/length code. The
487*4b169a6bSchristos // possible codes are counted for each number of coded symbols from two to the
488*4b169a6bSchristos // maximum. The counts for each of those and the total number of codes are
489*4b169a6bSchristos // shown. The maximum number of inflate table entires is then calculated across
490*4b169a6bSchristos // all possible codes. Each new maximum number of table entries and the
491*4b169a6bSchristos // associated sub-code (starting at root + 1 == 10 bits) is shown.
492*4b169a6bSchristos //
493*4b169a6bSchristos // To count and examine prefix codes that are not length-limited, provide a
494*4b169a6bSchristos // maximum length equal to the number of symbols minus one.
495*4b169a6bSchristos //
496*4b169a6bSchristos // For the deflate literal/length code, use "enough". For the deflate distance
497*4b169a6bSchristos // code, use "enough 30 6".
main(int argc,char ** argv)498*4b169a6bSchristos int main(int argc, char **argv) {
499*4b169a6bSchristos // set up globals for cleanup()
500*4b169a6bSchristos g.code = NULL;
501*4b169a6bSchristos g.num = NULL;
502*4b169a6bSchristos g.done = NULL;
503*4b169a6bSchristos string_init(&g.out);
504212397c6Schristos
505*4b169a6bSchristos // get arguments -- default to the deflate literal/length code
506*4b169a6bSchristos int syms = 286;
507*4b169a6bSchristos g.root = 9;
508*4b169a6bSchristos g.max = 15;
509212397c6Schristos if (argc > 1) {
510212397c6Schristos syms = atoi(argv[1]);
511212397c6Schristos if (argc > 2) {
512*4b169a6bSchristos g.root = atoi(argv[2]);
513212397c6Schristos if (argc > 3)
514*4b169a6bSchristos g.max = atoi(argv[3]);
515212397c6Schristos }
516212397c6Schristos }
517*4b169a6bSchristos if (argc > 4 || syms < 2 || g.root < 1 || g.max < 1) {
518212397c6Schristos fputs("invalid arguments, need: [sym >= 2 [root >= 1 [max >= 1]]]\n",
519212397c6Schristos stderr);
520212397c6Schristos return 1;
521212397c6Schristos }
522212397c6Schristos
523*4b169a6bSchristos // if not restricting the code length, the longest is syms - 1
524*4b169a6bSchristos if (g.max > syms - 1)
525*4b169a6bSchristos g.max = syms - 1;
526212397c6Schristos
527*4b169a6bSchristos // determine the number of bits in a code_t
528*4b169a6bSchristos int bits = 0;
529*4b169a6bSchristos for (code_t word = 1; word; word <<= 1)
530*4b169a6bSchristos bits++;
531212397c6Schristos
532*4b169a6bSchristos // make sure that the calculation of most will not overflow
533*4b169a6bSchristos if (g.max > bits || (code_t)(syms - 2) >= ((code_t)-1 >> (g.max - 1))) {
534212397c6Schristos fputs("abort: code length too long for internal types\n", stderr);
535212397c6Schristos return 1;
536212397c6Schristos }
537212397c6Schristos
538*4b169a6bSchristos // reject impossible code requests
539*4b169a6bSchristos if ((code_t)(syms - 1) > ((code_t)1 << g.max) - 1) {
540212397c6Schristos fprintf(stderr, "%d symbols cannot be coded in %d bits\n",
541*4b169a6bSchristos syms, g.max);
542212397c6Schristos return 1;
543212397c6Schristos }
544212397c6Schristos
545*4b169a6bSchristos // allocate code vector
546*4b169a6bSchristos g.code = calloc(g.max + 1, sizeof(int));
547*4b169a6bSchristos assert(g.code != NULL && "out of memory");
548212397c6Schristos
549*4b169a6bSchristos // determine size of saved results array, checking for overflows,
550*4b169a6bSchristos // allocate and clear the array (set all to zero with calloc())
551*4b169a6bSchristos if (syms == 2) // iff max == 1
552*4b169a6bSchristos g.num = NULL; // won't be saving any results
553212397c6Schristos else {
554*4b169a6bSchristos g.size = syms >> 1;
555*4b169a6bSchristos int n = (syms - 1) >> 1;
556*4b169a6bSchristos assert(g.size <= (size_t)-1 / n && "overflow");
557*4b169a6bSchristos g.size *= n;
558*4b169a6bSchristos n = g.max - 1;
559*4b169a6bSchristos assert(g.size <= (size_t)-1 / n && "overflow");
560*4b169a6bSchristos g.size *= n;
561*4b169a6bSchristos g.num = calloc(g.size, sizeof(big_t));
562*4b169a6bSchristos assert(g.num != NULL && "out of memory");
563212397c6Schristos }
564212397c6Schristos
565*4b169a6bSchristos // count possible codes for all numbers of symbols, add up counts
566*4b169a6bSchristos big_t sum = 0;
567*4b169a6bSchristos for (int n = 2; n <= syms; n++) {
568*4b169a6bSchristos big_t got = count(n, 2, 1);
569212397c6Schristos sum += got;
570*4b169a6bSchristos assert(got != (big_t)-1 && sum >= got && "overflow");
571212397c6Schristos }
572*4b169a6bSchristos printf("%"PRIbig" total codes for 2 to %d symbols", sum, syms);
573*4b169a6bSchristos if (g.max < syms - 1)
574*4b169a6bSchristos printf(" (%d-bit length limit)\n", g.max);
575212397c6Schristos else
576212397c6Schristos puts(" (no length limit)");
577212397c6Schristos
578*4b169a6bSchristos // allocate and clear done array for been_here()
579212397c6Schristos if (syms == 2)
580*4b169a6bSchristos g.done = NULL;
581*4b169a6bSchristos else {
582*4b169a6bSchristos g.done = calloc(g.size, sizeof(struct tab));
583*4b169a6bSchristos assert(g.done != NULL && "out of memory");
584212397c6Schristos }
585212397c6Schristos
586*4b169a6bSchristos // find and show maximum inflate table usage
587*4b169a6bSchristos if (g.root > g.max) // reduce root to max length
588*4b169a6bSchristos g.root = g.max;
589*4b169a6bSchristos if ((code_t)syms < ((code_t)1 << (g.root + 1)))
590212397c6Schristos enough(syms);
591212397c6Schristos else
592*4b169a6bSchristos fputs("cannot handle minimum code lengths > root", stderr);
593212397c6Schristos
594*4b169a6bSchristos // done
595212397c6Schristos cleanup();
596212397c6Schristos return 0;
597212397c6Schristos }
598