/* inftrees.c -- generate Huffman trees for efficient decoding1* Copyright (C) 1995-2005 Mark Adler2* For conditions of distribution and use, see copyright notice in zlib.h3*/45#include "zutil.h"6#include "inftrees.h"78#define MAXBITS 15910const char inflate_copyright[] =11" inflate 1.2.3 Copyright 1995-2005 Mark Adler ";12/*13If you use the zlib library in a product, an acknowledgment is welcome14in the documentation of your product. If for some reason you cannot15include such an acknowledgment, I would appreciate that you keep this16copyright string in the executable of your product.17*/1819/*20Build a set of tables to decode the provided canonical Huffman code.21The code lengths are lens[0..codes-1]. The result starts at *table,22whose indices are 0..2^bits-1. work is a writable array of at least23lens shorts, which is used as a work area. type is the type of code24to be generated, CODES, LENS, or DISTS. On return, zero is success,25-1 is an invalid code, and +1 means that ENOUGH isn't enough. table26on return points to the next available entry's address. bits is the27requested root table index bits, and on return it is the actual root28table index bits. It will differ if the request is greater than the29longest code or if it is less than the shortest code.30*/31#ifdef ZLIB_STDC32/* __MVS__ complains hard about this one K&R prototype -- go figure */33int inflate_table(codetype type, unsigned short FAR *lens, unsigned codes,34code FAR * FAR *table, unsigned FAR *bits, unsigned short FAR *work)35#else36int inflate_table(type, lens, codes, table, bits, work)37codetype type;38unsigned short FAR *lens;39unsigned codes;40code FAR * FAR *table;41unsigned FAR *bits;42unsigned short FAR *work;43#endif44{45unsigned len; /* a code's length in bits */46unsigned sym; /* index of code symbols */47unsigned min, max; /* minimum and maximum code lengths */48unsigned root; /* number of index bits for root table */49unsigned curr; /* number of index bits for current table */50unsigned drop; /* code bits to drop for sub-table */51int left; /* number of prefix codes available */52unsigned used; /* code entries in table used */53unsigned huff; /* Huffman code */54unsigned incr; /* for incrementing code, index */55unsigned fill; /* index for replicating entries */56unsigned low; /* low bits for current root entry */57unsigned mask; /* mask for low root bits */58code this; /* table entry for duplication */59code FAR *next; /* next available space in table */60const unsigned short FAR *base; /* base value table to use */61const unsigned short FAR *extra; /* extra bits table to use */62int end; /* use base and extra for symbol > end */63unsigned short count[MAXBITS+1]; /* number of codes of each length */64unsigned short offs[MAXBITS+1]; /* offsets in table for each length */65static const unsigned short lbase[31] = { /* Length codes 257..285 base */663, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,6735, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};68static const unsigned short lext[31] = { /* Length codes 257..285 extra */6916, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,7019, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};71static const unsigned short dbase[32] = { /* Distance codes 0..29 base */721, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,73257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,748193, 12289, 16385, 24577, 0, 0};75static const unsigned short dext[32] = { /* Distance codes 0..29 extra */7616, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,7723, 23, 24, 24, 25, 25, 26, 26, 27, 27,7828, 28, 29, 29, 64, 64};7980/*81Process a set of code lengths to create a canonical Huffman code. The82code lengths are lens[0..codes-1]. Each length corresponds to the83symbols 0..codes-1. The Huffman code is generated by first sorting the84symbols by length from short to long, and retaining the symbol order85for codes with equal lengths. Then the code starts with all zero bits86for the first code of the shortest length, and the codes are integer87increments for the same length, and zeros are appended as the length88increases. For the deflate format, these bits are stored backwards89from their more natural integer increment ordering, and so when the90decoding tables are built in the large loop below, the integer codes91are incremented backwards.9293This routine assumes, but does not check, that all of the entries in94lens[] are in the range 0..MAXBITS. The caller must assure this.951..MAXBITS is interpreted as that code length. zero means that that96symbol does not occur in this code.9798The codes are sorted by computing a count of codes for each length,99creating from that a table of starting indices for each length in the100sorted table, and then entering the symbols in order in the sorted101table. The sorted table is work[], with that space being provided by102the caller.103104The length counts are used for other purposes as well, i.e. finding105the minimum and maximum length codes, determining if there are any106codes at all, checking for a valid set of lengths, and looking ahead107at length counts to determine sub-table sizes when building the108decoding tables.109*/110111/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */112for (len = 0; len <= MAXBITS; len++)113count[len] = 0;114for (sym = 0; sym < codes; sym++)115count[lens[sym]]++;116117/* bound code lengths, force root to be within code lengths */118root = *bits;119for (max = MAXBITS; max >= 1; max--)120if (count[max] != 0) break;121if (root > max) root = max;122if (max == 0) { /* no symbols to code at all */123this.op = (unsigned char)64; /* invalid code marker */124this.bits = (unsigned char)1;125this.val = (unsigned short)0;126*(*table)++ = this; /* make a table to force an error */127*(*table)++ = this;128*bits = 1;129return 0; /* no symbols, but wait for decoding to report error */130}131for (min = 1; min <= MAXBITS; min++)132if (count[min] != 0) break;133if (root < min) root = min;134135/* check for an over-subscribed or incomplete set of lengths */136left = 1;137for (len = 1; len <= MAXBITS; len++) {138left <<= 1;139left -= count[len];140if (left < 0) return -1; /* over-subscribed */141}142if (left > 0 && (type == CODES || max != 1))143return -1; /* incomplete set */144145/* generate offsets into symbol table for each length for sorting */146offs[1] = 0;147for (len = 1; len < MAXBITS; len++)148offs[len + 1] = offs[len] + count[len];149150/* sort symbols by length, by symbol order within each length */151for (sym = 0; sym < codes; sym++)152if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;153154/*155Create and fill in decoding tables. In this loop, the table being156filled is at next and has curr index bits. The code being used is huff157with length len. That code is converted to an index by dropping drop158bits off of the bottom. For codes where len is less than drop + curr,159those top drop + curr - len bits are incremented through all values to160fill the table with replicated entries.161162root is the number of index bits for the root table. When len exceeds163root, sub-tables are created pointed to by the root entry with an index164of the low root bits of huff. This is saved in low to check for when a165new sub-table should be started. drop is zero when the root table is166being filled, and drop is root when sub-tables are being filled.167168When a new sub-table is needed, it is necessary to look ahead in the169code lengths to determine what size sub-table is needed. The length170counts are used for this, and so count[] is decremented as codes are171entered in the tables.172173used keeps track of how many table entries have been allocated from the174provided *table space. It is checked when a LENS table is being made175against the space in *table, ENOUGH, minus the maximum space needed by176the worst case distance code, MAXD. This should never happen, but the177sufficiency of ENOUGH has not been proven exhaustively, hence the check.178This assumes that when type == LENS, bits == 9.179180sym increments through all symbols, and the loop terminates when181all codes of length max, i.e. all codes, have been processed. This182routine permits incomplete codes, so another loop after this one fills183in the rest of the decoding tables with invalid code markers.184*/185186/* set up for code type */187switch (type) {188case CODES:189base = extra = work; /* dummy value--not used */190end = 19;191break;192case LENS:193base = lbase;194base -= 257;195extra = lext;196extra -= 257;197end = 256;198break;199default: /* DISTS */200base = dbase;201extra = dext;202end = -1;203}204205/* initialize state for loop */206huff = 0; /* starting code */207sym = 0; /* starting code symbol */208len = min; /* starting code length */209next = *table; /* current table to fill in */210curr = root; /* current table index bits */211drop = 0; /* current bits to drop from code for index */212low = (unsigned)(-1); /* trigger new sub-table when len > root */213used = 1U << root; /* use root table entries */214mask = used - 1; /* mask for comparing low */215216/* check available table space */217if (type == LENS && used >= ENOUGH - MAXD)218return 1;219220/* process all codes and make table entries */221for (;;) {222/* create table entry */223this.bits = (unsigned char)(len - drop);224if ((int)(work[sym]) < end) {225this.op = (unsigned char)0;226this.val = work[sym];227}228else if ((int)(work[sym]) > end) {229this.op = (unsigned char)(extra[work[sym]]);230this.val = base[work[sym]];231}232else {233this.op = (unsigned char)(32 + 64); /* end of block */234this.val = 0;235}236237/* replicate for those indices with low len bits equal to huff */238incr = 1U << (len - drop);239fill = 1U << curr;240min = fill; /* save offset to next table */241do {242fill -= incr;243next[(huff >> drop) + fill] = this;244} while (fill != 0);245246/* backwards increment the len-bit code huff */247incr = 1U << (len - 1);248while (huff & incr)249incr >>= 1;250if (incr != 0) {251huff &= incr - 1;252huff += incr;253}254else255huff = 0;256257/* go to next symbol, update count, len */258sym++;259if (--(count[len]) == 0) {260if (len == max) break;261len = lens[work[sym]];262}263264/* create new sub-table if needed */265if (len > root && (huff & mask) != low) {266/* if first time, transition to sub-tables */267if (drop == 0)268drop = root;269270/* increment past last table */271next += min; /* here min is 1 << curr */272273/* determine length of next table */274curr = len - drop;275left = (int)(1 << curr);276while (curr + drop < max) {277left -= count[curr + drop];278if (left <= 0) break;279curr++;280left <<= 1;281}282283/* check for enough space */284used += 1U << curr;285if (type == LENS && used >= ENOUGH - MAXD)286return 1;287288/* point entry in root table to sub-table */289low = huff & mask;290(*table)[low].op = (unsigned char)curr;291(*table)[low].bits = (unsigned char)root;292(*table)[low].val = (unsigned short)(next - *table);293}294}295296/*297Fill in rest of table for incomplete codes. This loop is similar to the298loop above in incrementing huff for table indices. It is assumed that299len is equal to curr + drop, so there is no loop needed to increment300through high index bits. When the current sub-table is filled, the loop301drops back to the root table to fill in any remaining entries there.302*/303this.op = (unsigned char)64; /* invalid code marker */304this.bits = (unsigned char)(len - drop);305this.val = (unsigned short)0;306while (huff != 0) {307/* when done with sub-table, drop back to root table */308if (drop != 0 && (huff & mask) != low) {309drop = 0;310len = root;311next = *table;312this.bits = (unsigned char)len;313}314315/* put invalid code marker in table */316next[huff >> drop] = this;317318/* backwards increment the len-bit code huff */319incr = 1U << (len - 1);320while (huff & incr)321incr >>= 1;322if (incr != 0) {323huff &= incr - 1;324huff += incr;325}326else327huff = 0;328}329330/* set return parameters */331*table += used;332*bits = root;333return 0;334}335336337