55fd27b601d33e893a40ede06f2bc880ba76a3aa
[platform/upstream/libwebsockets.git] / win32port / zlib / inftrees.c
1 /* inftrees.c -- generate Huffman trees for efficient decoding\r
2  * Copyright (C) 1995-2003 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.1 Copyright 1995-2003 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 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 this;                  /* 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     int end;                    /* use base and extra for symbol > end */\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, 76, 66};\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) return -1;            /* no codes! */\r
118     for (min = 1; min <= MAXBITS; min++)\r
119         if (count[min] != 0) break;\r
120     if (root < min) root = min;\r
121 \r
122     /* check for an over-subscribed or incomplete set of lengths */\r
123     left = 1;\r
124     for (len = 1; len <= MAXBITS; len++) {\r
125         left <<= 1;\r
126         left -= count[len];\r
127         if (left < 0) return -1;        /* over-subscribed */\r
128     }\r
129     if (left > 0 && (type == CODES || (codes - count[0] != 1)))\r
130         return -1;                      /* incomplete set */\r
131 \r
132     /* generate offsets into symbol table for each length for sorting */\r
133     offs[1] = 0;\r
134     for (len = 1; len < MAXBITS; len++)\r
135         offs[len + 1] = offs[len] + count[len];\r
136 \r
137     /* sort symbols by length, by symbol order within each length */\r
138     for (sym = 0; sym < codes; sym++)\r
139         if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;\r
140 \r
141     /*\r
142        Create and fill in decoding tables.  In this loop, the table being\r
143        filled is at next and has curr index bits.  The code being used is huff\r
144        with length len.  That code is converted to an index by dropping drop\r
145        bits off of the bottom.  For codes where len is less than drop + curr,\r
146        those top drop + curr - len bits are incremented through all values to\r
147        fill the table with replicated entries.\r
148 \r
149        root is the number of index bits for the root table.  When len exceeds\r
150        root, sub-tables are created pointed to by the root entry with an index\r
151        of the low root bits of huff.  This is saved in low to check for when a\r
152        new sub-table should be started.  drop is zero when the root table is\r
153        being filled, and drop is root when sub-tables are being filled.\r
154 \r
155        When a new sub-table is needed, it is necessary to look ahead in the\r
156        code lengths to determine what size sub-table is needed.  The length\r
157        counts are used for this, and so count[] is decremented as codes are\r
158        entered in the tables.\r
159 \r
160        used keeps track of how many table entries have been allocated from the\r
161        provided *table space.  It is checked when a LENS table is being made\r
162        against the space in *table, ENOUGH, minus the maximum space needed by\r
163        the worst case distance code, MAXD.  This should never happen, but the\r
164        sufficiency of ENOUGH has not been proven exhaustively, hence the check.\r
165        This assumes that when type == LENS, bits == 9.\r
166 \r
167        sym increments through all symbols, and the loop terminates when\r
168        all codes of length max, i.e. all codes, have been processed.  This\r
169        routine permits incomplete codes, so another loop after this one fills\r
170        in the rest of the decoding tables with invalid code markers.\r
171      */\r
172 \r
173     /* set up for code type */\r
174     switch (type) {\r
175     case CODES:\r
176         base = extra = work;    /* dummy value--not used */\r
177         end = 19;\r
178         break;\r
179     case LENS:\r
180         base = lbase;\r
181         base -= 257;\r
182         extra = lext;\r
183         extra -= 257;\r
184         end = 256;\r
185         break;\r
186     default:            /* DISTS */\r
187         base = dbase;\r
188         extra = dext;\r
189         end = -1;\r
190     }\r
191 \r
192     /* initialize state for loop */\r
193     huff = 0;                   /* starting code */\r
194     sym = 0;                    /* starting code symbol */\r
195     len = min;                  /* starting code length */\r
196     next = *table;              /* current table to fill in */\r
197     curr = root;                /* current table index bits */\r
198     drop = 0;                   /* current bits to drop from code for index */\r
199     low = (unsigned)(-1);       /* trigger new sub-table when len > root */\r
200     used = 1U << root;          /* use root table entries */\r
201     mask = used - 1;            /* mask for comparing low */\r
202 \r
203     /* check available table space */\r
204     if (type == LENS && used >= ENOUGH - MAXD)\r
205         return 1;\r
206 \r
207     /* process all codes and make table entries */\r
208     for (;;) {\r
209         /* create table entry */\r
210         this.bits = (unsigned char)(len - drop);\r
211         if ((int)(work[sym]) < end) {\r
212             this.op = (unsigned char)0;\r
213             this.val = work[sym];\r
214         }\r
215         else if ((int)(work[sym]) > end) {\r
216             this.op = (unsigned char)(extra[work[sym]]);\r
217             this.val = base[work[sym]];\r
218         }\r
219         else {\r
220             this.op = (unsigned char)(32 + 64);         /* end of block */\r
221             this.val = 0;\r
222         }\r
223 \r
224         /* replicate for those indices with low len bits equal to huff */\r
225         incr = 1U << (len - drop);\r
226         fill = 1U << curr;\r
227         do {\r
228             fill -= incr;\r
229             next[(huff >> drop) + fill] = this;\r
230         } while (fill != 0);\r
231 \r
232         /* backwards increment the len-bit code huff */\r
233         incr = 1U << (len - 1);\r
234         while (huff & incr)\r
235             incr >>= 1;\r
236         if (incr != 0) {\r
237             huff &= incr - 1;\r
238             huff += incr;\r
239         }\r
240         else\r
241             huff = 0;\r
242 \r
243         /* go to next symbol, update count, len */\r
244         sym++;\r
245         if (--(count[len]) == 0) {\r
246             if (len == max) break;\r
247             len = lens[work[sym]];\r
248         }\r
249 \r
250         /* create new sub-table if needed */\r
251         if (len > root && (huff & mask) != low) {\r
252             /* if first time, transition to sub-tables */\r
253             if (drop == 0)\r
254                 drop = root;\r
255 \r
256             /* increment past last table */\r
257             next += 1U << curr;\r
258 \r
259             /* determine length of next table */\r
260             curr = len - drop;\r
261             left = (int)(1 << curr);\r
262             while (curr + drop < max) {\r
263                 left -= count[curr + drop];\r
264                 if (left <= 0) break;\r
265                 curr++;\r
266                 left <<= 1;\r
267             }\r
268 \r
269             /* check for enough space */\r
270             used += 1U << curr;\r
271             if (type == LENS && used >= ENOUGH - MAXD)\r
272                 return 1;\r
273 \r
274             /* point entry in root table to sub-table */\r
275             low = huff & mask;\r
276             (*table)[low].op = (unsigned char)curr;\r
277             (*table)[low].bits = (unsigned char)root;\r
278             (*table)[low].val = (unsigned short)(next - *table);\r
279         }\r
280     }\r
281 \r
282     /*\r
283        Fill in rest of table for incomplete codes.  This loop is similar to the\r
284        loop above in incrementing huff for table indices.  It is assumed that\r
285        len is equal to curr + drop, so there is no loop needed to increment\r
286        through high index bits.  When the current sub-table is filled, the loop\r
287        drops back to the root table to fill in any remaining entries there.\r
288      */\r
289     this.op = (unsigned char)64;                /* invalid code marker */\r
290     this.bits = (unsigned char)(len - drop);\r
291     this.val = (unsigned short)0;\r
292     while (huff != 0) {\r
293         /* when done with sub-table, drop back to root table */\r
294         if (drop != 0 && (huff & mask) != low) {\r
295             drop = 0;\r
296             len = root;\r
297             next = *table;\r
298             curr = root;\r
299             this.bits = (unsigned char)len;\r
300         }\r
301 \r
302         /* put invalid code marker in table */\r
303         next[huff >> drop] = this;\r
304 \r
305         /* backwards increment the len-bit code huff */\r
306         incr = 1U << (len - 1);\r
307         while (huff & incr)\r
308             incr >>= 1;\r
309         if (incr != 0) {\r
310             huff &= incr - 1;\r
311             huff += incr;\r
312         }\r
313         else\r
314             huff = 0;\r
315     }\r
316 \r
317     /* set return parameters */\r
318     *table += used;\r
319     *bits = root;\r
320     return 0;\r
321 }\r