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