fbd81d745bb7ad76f914f29cbba1069f4af72bab
[platform/upstream/libwebsockets.git] / win32port / zlib / inftrees.c
1 /* inftrees.c -- generate Huffman trees for efficient decoding\r
2  * Copyright (C) 1995-2010 Mark Adler\r
3  * For conditions of distribution and use, see copyright notice in zlib.h\r
4  */\r
5 \r
6 #include "zutil.h"\r
7 #include "inftrees.h"\r
8 \r
9 #define MAXBITS 15\r
10 \r
11 const char inflate_copyright[] =\r
12    " inflate 1.2.5 Copyright 1995-2010 Mark Adler ";\r
13 /*\r
14   If you use the zlib library in a product, an acknowledgment is welcome\r
15   in the documentation of your product. If for some reason you cannot\r
16   include such an acknowledgment, I would appreciate that you keep this\r
17   copyright string in the executable of your product.\r
18  */\r
19 \r
20 /*\r
21    Build a set of tables to decode the provided canonical Huffman code.\r
22    The code lengths are lens[0..codes-1].  The result starts at *table,\r
23    whose indices are 0..2^bits-1.  work is a writable array of at least\r
24    lens shorts, which is used as a work area.  type is the type of code\r
25    to be generated, CODES, LENS, or DISTS.  On return, zero is success,\r
26    -1 is an invalid code, and +1 means that ENOUGH isn't enough.  table\r
27    on return points to the next available entry's address.  bits is the\r
28    requested root table index bits, and on return it is the actual root\r
29    table index bits.  It will differ if the request is greater than the\r
30    longest code or if it is less than the shortest code.\r
31  */\r
32 int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work)\r
33 codetype type;\r
34 unsigned short FAR *lens;\r
35 unsigned codes;\r
36 code FAR * FAR *table;\r
37 unsigned FAR *bits;\r
38 unsigned short FAR *work;\r
39 {\r
40     unsigned len;               /* a code's length in bits */\r
41     unsigned sym;               /* index of code symbols */\r
42     unsigned min, max;          /* minimum and maximum code lengths */\r
43     unsigned root;              /* number of index bits for root table */\r
44     unsigned curr;              /* number of index bits for current table */\r
45     unsigned drop;              /* code bits to drop for sub-table */\r
46     int left;                   /* number of prefix codes available */\r
47     unsigned used;              /* code entries in table used */\r
48     unsigned huff;              /* Huffman code */\r
49     unsigned incr;              /* for incrementing code, index */\r
50     unsigned fill;              /* index for replicating entries */\r
51     unsigned low;               /* low bits for current root entry */\r
52     unsigned mask;              /* mask for low root bits */\r
53     code here;                  /* table entry for duplication */\r
54     code FAR *next;             /* next available space in table */\r
55     const unsigned short FAR *base;     /* base value table to use */\r
56     const unsigned short FAR *extra;    /* extra bits table to use */\r
57     unsigned match;             /* use base and extra for symbol >= match */\r
58     unsigned short count[MAXBITS+1];    /* number of codes of each length */\r
59     unsigned short offs[MAXBITS+1];     /* offsets in table for each length */\r
60     static const unsigned short lbase[31] = { /* Length codes 257..285 base */\r
61         3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\r
62         35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};\r
63     static const unsigned short lext[31] = { /* Length codes 257..285 extra */\r
64         16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\r
65         19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 73, 195};\r
66     static const unsigned short dbase[32] = { /* Distance codes 0..29 base */\r
67         1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\r
68         257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\r
69         8193, 12289, 16385, 24577, 0, 0};\r
70     static const unsigned short dext[32] = { /* Distance codes 0..29 extra */\r
71         16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\r
72         23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\r
73         28, 28, 29, 29, 64, 64};\r
74 \r
75     /*\r
76        Process a set of code lengths to create a canonical Huffman code.  The\r
77        code lengths are lens[0..codes-1].  Each length corresponds to the\r
78        symbols 0..codes-1.  The Huffman code is generated by first sorting the\r
79        symbols by length from short to long, and retaining the symbol order\r
80        for codes with equal lengths.  Then the code starts with all zero bits\r
81        for the first code of the shortest length, and the codes are integer\r
82        increments for the same length, and zeros are appended as the length\r
83        increases.  For the deflate format, these bits are stored backwards\r
84        from their more natural integer increment ordering, and so when the\r
85        decoding tables are built in the large loop below, the integer codes\r
86        are incremented backwards.\r
87 \r
88        This routine assumes, but does not check, that all of the entries in\r
89        lens[] are in the range 0..MAXBITS.  The caller must assure this.\r
90        1..MAXBITS is interpreted as that code length.  zero means that that\r
91        symbol does not occur in this code.\r
92 \r
93        The codes are sorted by computing a count of codes for each length,\r
94        creating from that a table of starting indices for each length in the\r
95        sorted table, and then entering the symbols in order in the sorted\r
96        table.  The sorted table is work[], with that space being provided by\r
97        the caller.\r
98 \r
99        The length counts are used for other purposes as well, i.e. finding\r
100        the minimum and maximum length codes, determining if there are any\r
101        codes at all, checking for a valid set of lengths, and looking ahead\r
102        at length counts to determine sub-table sizes when building the\r
103        decoding tables.\r
104      */\r
105 \r
106     /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\r
107     for (len = 0; len <= MAXBITS; len++)\r
108         count[len] = 0;\r
109     for (sym = 0; sym < codes; sym++)\r
110         count[lens[sym]]++;\r
111 \r
112     /* bound code lengths, force root to be within code lengths */\r
113     root = *bits;\r
114     for (max = MAXBITS; max >= 1; max--)\r
115         if (count[max] != 0) break;\r
116     if (root > max) root = max;\r
117     if (max == 0) {                     /* no symbols to code at all */\r
118         here.op = (unsigned char)64;    /* invalid code marker */\r
119         here.bits = (unsigned char)1;\r
120         here.val = (unsigned short)0;\r
121         *(*table)++ = here;             /* make a table to force an error */\r
122         *(*table)++ = here;\r
123         *bits = 1;\r
124         return 0;     /* no symbols, but wait for decoding to report error */\r
125     }\r
126     for (min = 1; min < max; min++)\r
127         if (count[min] != 0) break;\r
128     if (root < min) root = min;\r
129 \r
130     /* check for an over-subscribed or incomplete set of lengths */\r
131     left = 1;\r
132     for (len = 1; len <= MAXBITS; len++) {\r
133         left <<= 1;\r
134         left -= count[len];\r
135         if (left < 0) return -1;        /* over-subscribed */\r
136     }\r
137     if (left > 0 && (type == CODES || max != 1))\r
138         return -1;                      /* incomplete set */\r
139 \r
140     /* generate offsets into symbol table for each length for sorting */\r
141     offs[1] = 0;\r
142     for (len = 1; len < MAXBITS; len++)\r
143         offs[len + 1] = offs[len] + count[len];\r
144 \r
145     /* sort symbols by length, by symbol order within each length */\r
146     for (sym = 0; sym < codes; sym++)\r
147         if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;\r
148 \r
149     /*\r
150        Create and fill in decoding tables.  In this loop, the table being\r
151        filled is at next and has curr index bits.  The code being used is huff\r
152        with length len.  That code is converted to an index by dropping drop\r
153        bits off of the bottom.  For codes where len is less than drop + curr,\r
154        those top drop + curr - len bits are incremented through all values to\r
155        fill the table with replicated entries.\r
156 \r
157        root is the number of index bits for the root table.  When len exceeds\r
158        root, sub-tables are created pointed to by the root entry with an index\r
159        of the low root bits of huff.  This is saved in low to check for when a\r
160        new sub-table should be started.  drop is zero when the root table is\r
161        being filled, and drop is root when sub-tables are being filled.\r
162 \r
163        When a new sub-table is needed, it is necessary to look ahead in the\r
164        code lengths to determine what size sub-table is needed.  The length\r
165        counts are used for this, and so count[] is decremented as codes are\r
166        entered in the tables.\r
167 \r
168        used keeps track of how many table entries have been allocated from the\r
169        provided *table space.  It is checked for LENS and DIST tables against\r
170        the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\r
171        the initial root table size constants.  See the comments in inftrees.h\r
172        for more information.\r
173 \r
174        sym increments through all symbols, and the loop terminates when\r
175        all codes of length max, i.e. all codes, have been processed.  This\r
176        routine permits incomplete codes, so another loop after this one fills\r
177        in the rest of the decoding tables with invalid code markers.\r
178      */\r
179 \r
180     /* set up for code type */\r
181     switch (type) {\r
182     case CODES:\r
183         base = extra = work;    /* dummy value--not used */\r
184         match = 20;\r
185         break;\r
186     case LENS:\r
187         base = lbase;\r
188         extra = lext;\r
189         match = 257;\r
190         break;\r
191     default:            /* DISTS */\r
192         base = dbase;\r
193         extra = dext;\r
194         match = 0;\r
195     }\r
196 \r
197     /* initialize state for loop */\r
198     huff = 0;                   /* starting code */\r
199     sym = 0;                    /* starting code symbol */\r
200     len = min;                  /* starting code length */\r
201     next = *table;              /* current table to fill in */\r
202     curr = root;                /* current table index bits */\r
203     drop = 0;                   /* current bits to drop from code for index */\r
204     low = (unsigned)(-1);       /* trigger new sub-table when len > root */\r
205     used = 1U << root;          /* use root table entries */\r
206     mask = used - 1;            /* mask for comparing low */\r
207 \r
208     /* check available table space */\r
209     if ((type == LENS && used >= ENOUGH_LENS) ||\r
210         (type == DISTS && used >= ENOUGH_DISTS))\r
211         return 1;\r
212 \r
213     /* process all codes and make table entries */\r
214     for (;;) {\r
215         /* create table entry */\r
216         here.bits = (unsigned char)(len - drop);\r
217         if (work[sym] + 1 < match) {\r
218             here.op = (unsigned char)0;\r
219             here.val = work[sym];\r
220         }\r
221         else if (work[sym] >= match) {\r
222             here.op = (unsigned char)(extra[work[sym] - match]);\r
223             here.val = base[work[sym] - match];\r
224         }\r
225         else {\r
226             here.op = (unsigned char)(32 + 64);         /* end of block */\r
227             here.val = 0;\r
228         }\r
229 \r
230         /* replicate for those indices with low len bits equal to huff */\r
231         incr = 1U << (len - drop);\r
232         fill = 1U << curr;\r
233         min = fill;                 /* save offset to next table */\r
234         do {\r
235             fill -= incr;\r
236             next[(huff >> drop) + fill] = here;\r
237         } while (fill != 0);\r
238 \r
239         /* backwards increment the len-bit code huff */\r
240         incr = 1U << (len - 1);\r
241         while (huff & incr)\r
242             incr >>= 1;\r
243         if (incr != 0) {\r
244             huff &= incr - 1;\r
245             huff += incr;\r
246         }\r
247         else\r
248             huff = 0;\r
249 \r
250         /* go to next symbol, update count, len */\r
251         sym++;\r
252         if (--(count[len]) == 0) {\r
253             if (len == max) break;\r
254             len = lens[work[sym]];\r
255         }\r
256 \r
257         /* create new sub-table if needed */\r
258         if (len > root && (huff & mask) != low) {\r
259             /* if first time, transition to sub-tables */\r
260             if (drop == 0)\r
261                 drop = root;\r
262 \r
263             /* increment past last table */\r
264             next += min;            /* here min is 1 << curr */\r
265 \r
266             /* determine length of next table */\r
267             curr = len - drop;\r
268             left = (int)(1 << curr);\r
269             while (curr + drop < max) {\r
270                 left -= count[curr + drop];\r
271                 if (left <= 0) break;\r
272                 curr++;\r
273                 left <<= 1;\r
274             }\r
275 \r
276             /* check for enough space */\r
277             used += 1U << curr;\r
278             if ((type == LENS && used >= ENOUGH_LENS) ||\r
279                 (type == DISTS && used >= ENOUGH_DISTS))\r
280                 return 1;\r
281 \r
282             /* point entry in root table to sub-table */\r
283             low = huff & mask;\r
284             (*table)[low].op = (unsigned char)curr;\r
285             (*table)[low].bits = (unsigned char)root;\r
286             (*table)[low].val = (unsigned short)(next - *table);\r
287         }\r
288     }\r
289 \r
290     /*\r
291        Fill in rest of table for incomplete codes.  This loop is similar to the\r
292        loop above in incrementing huff for table indices.  It is assumed that\r
293        len is equal to curr + drop, so there is no loop needed to increment\r
294        through high index bits.  When the current sub-table is filled, the loop\r
295        drops back to the root table to fill in any remaining entries there.\r
296      */\r
297     here.op = (unsigned char)64;                /* invalid code marker */\r
298     here.bits = (unsigned char)(len - drop);\r
299     here.val = (unsigned short)0;\r
300     while (huff != 0) {\r
301         /* when done with sub-table, drop back to root table */\r
302         if (drop != 0 && (huff & mask) != low) {\r
303             drop = 0;\r
304             len = root;\r
305             next = *table;\r
306             here.bits = (unsigned char)len;\r
307         }\r
308 \r
309         /* put invalid code marker in table */\r
310         next[huff >> drop] = here;\r
311 \r
312         /* backwards increment the len-bit code huff */\r
313         incr = 1U << (len - 1);\r
314         while (huff & incr)\r
315             incr >>= 1;\r
316         if (incr != 0) {\r
317             huff &= incr - 1;\r
318             huff += incr;\r
319         }\r
320         else\r
321             huff = 0;\r
322     }\r
323 \r
324     /* set return parameters */\r
325     *table += used;\r
326     *bits = root;\r
327     return 0;\r
328 }\r