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