kusano 7d535a
/* inftree9.c -- generate Huffman trees for efficient decoding
kusano 7d535a
 * Copyright (C) 1995-2012 Mark Adler
kusano 7d535a
 * For conditions of distribution and use, see copyright notice in zlib.h
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
#include "zutil.h"
kusano 7d535a
#include "inftree9.h"
kusano 7d535a
kusano 7d535a
#define MAXBITS 15
kusano 7d535a
kusano 7d535a
const char inflate9_copyright[] =
kusano 7d535a
   " inflate9 1.2.7 Copyright 1995-2012 Mark Adler ";
kusano 7d535a
/*
kusano 7d535a
  If you use the zlib library in a product, an acknowledgment is welcome
kusano 7d535a
  in the documentation of your product. If for some reason you cannot
kusano 7d535a
  include such an acknowledgment, I would appreciate that you keep this
kusano 7d535a
  copyright string in the executable of your product.
kusano 7d535a
 */
kusano 7d535a
kusano 7d535a
/*
kusano 7d535a
   Build a set of tables to decode the provided canonical Huffman code.
kusano 7d535a
   The code lengths are lens[0..codes-1].  The result starts at *table,
kusano 7d535a
   whose indices are 0..2^bits-1.  work is a writable array of at least
kusano 7d535a
   lens shorts, which is used as a work area.  type is the type of code
kusano 7d535a
   to be generated, CODES, LENS, or DISTS.  On return, zero is success,
kusano 7d535a
   -1 is an invalid code, and +1 means that ENOUGH isn't enough.  table
kusano 7d535a
   on return points to the next available entry's address.  bits is the
kusano 7d535a
   requested root table index bits, and on return it is the actual root
kusano 7d535a
   table index bits.  It will differ if the request is greater than the
kusano 7d535a
   longest code or if it is less than the shortest code.
kusano 7d535a
 */
kusano 7d535a
int inflate_table9(type, lens, codes, table, bits, work)
kusano 7d535a
codetype type;
kusano 7d535a
unsigned short FAR *lens;
kusano 7d535a
unsigned codes;
kusano 7d535a
code FAR * FAR *table;
kusano 7d535a
unsigned FAR *bits;
kusano 7d535a
unsigned short FAR *work;
kusano 7d535a
{
kusano 7d535a
    unsigned len;               /* a code's length in bits */
kusano 7d535a
    unsigned sym;               /* index of code symbols */
kusano 7d535a
    unsigned min, max;          /* minimum and maximum code lengths */
kusano 7d535a
    unsigned root;              /* number of index bits for root table */
kusano 7d535a
    unsigned curr;              /* number of index bits for current table */
kusano 7d535a
    unsigned drop;              /* code bits to drop for sub-table */
kusano 7d535a
    int left;                   /* number of prefix codes available */
kusano 7d535a
    unsigned used;              /* code entries in table used */
kusano 7d535a
    unsigned huff;              /* Huffman code */
kusano 7d535a
    unsigned incr;              /* for incrementing code, index */
kusano 7d535a
    unsigned fill;              /* index for replicating entries */
kusano 7d535a
    unsigned low;               /* low bits for current root entry */
kusano 7d535a
    unsigned mask;              /* mask for low root bits */
kusano 7d535a
    code this;                  /* table entry for duplication */
kusano 7d535a
    code FAR *next;             /* next available space in table */
kusano 7d535a
    const unsigned short FAR *base;     /* base value table to use */
kusano 7d535a
    const unsigned short FAR *extra;    /* extra bits table to use */
kusano 7d535a
    int end;                    /* use base and extra for symbol > end */
kusano 7d535a
    unsigned short count[MAXBITS+1];    /* number of codes of each length */
kusano 7d535a
    unsigned short offs[MAXBITS+1];     /* offsets in table for each length */
kusano 7d535a
    static const unsigned short lbase[31] = { /* Length codes 257..285 base */
kusano 7d535a
        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17,
kusano 7d535a
        19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115,
kusano 7d535a
        131, 163, 195, 227, 3, 0, 0};
kusano 7d535a
    static const unsigned short lext[31] = { /* Length codes 257..285 extra */
kusano 7d535a
        128, 128, 128, 128, 128, 128, 128, 128, 129, 129, 129, 129,
kusano 7d535a
        130, 130, 130, 130, 131, 131, 131, 131, 132, 132, 132, 132,
kusano 7d535a
        133, 133, 133, 133, 144, 78, 68};
kusano 7d535a
    static const unsigned short dbase[32] = { /* Distance codes 0..31 base */
kusano 7d535a
        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49,
kusano 7d535a
        65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073,
kusano 7d535a
        4097, 6145, 8193, 12289, 16385, 24577, 32769, 49153};
kusano 7d535a
    static const unsigned short dext[32] = { /* Distance codes 0..31 extra */
kusano 7d535a
        128, 128, 128, 128, 129, 129, 130, 130, 131, 131, 132, 132,
kusano 7d535a
        133, 133, 134, 134, 135, 135, 136, 136, 137, 137, 138, 138,
kusano 7d535a
        139, 139, 140, 140, 141, 141, 142, 142};
kusano 7d535a
kusano 7d535a
    /*
kusano 7d535a
       Process a set of code lengths to create a canonical Huffman code.  The
kusano 7d535a
       code lengths are lens[0..codes-1].  Each length corresponds to the
kusano 7d535a
       symbols 0..codes-1.  The Huffman code is generated by first sorting the
kusano 7d535a
       symbols by length from short to long, and retaining the symbol order
kusano 7d535a
       for codes with equal lengths.  Then the code starts with all zero bits
kusano 7d535a
       for the first code of the shortest length, and the codes are integer
kusano 7d535a
       increments for the same length, and zeros are appended as the length
kusano 7d535a
       increases.  For the deflate format, these bits are stored backwards
kusano 7d535a
       from their more natural integer increment ordering, and so when the
kusano 7d535a
       decoding tables are built in the large loop below, the integer codes
kusano 7d535a
       are incremented backwards.
kusano 7d535a
kusano 7d535a
       This routine assumes, but does not check, that all of the entries in
kusano 7d535a
       lens[] are in the range 0..MAXBITS.  The caller must assure this.
kusano 7d535a
       1..MAXBITS is interpreted as that code length.  zero means that that
kusano 7d535a
       symbol does not occur in this code.
kusano 7d535a
kusano 7d535a
       The codes are sorted by computing a count of codes for each length,
kusano 7d535a
       creating from that a table of starting indices for each length in the
kusano 7d535a
       sorted table, and then entering the symbols in order in the sorted
kusano 7d535a
       table.  The sorted table is work[], with that space being provided by
kusano 7d535a
       the caller.
kusano 7d535a
kusano 7d535a
       The length counts are used for other purposes as well, i.e. finding
kusano 7d535a
       the minimum and maximum length codes, determining if there are any
kusano 7d535a
       codes at all, checking for a valid set of lengths, and looking ahead
kusano 7d535a
       at length counts to determine sub-table sizes when building the
kusano 7d535a
       decoding tables.
kusano 7d535a
     */
kusano 7d535a
kusano 7d535a
    /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
kusano 7d535a
    for (len = 0; len <= MAXBITS; len++)
kusano 7d535a
        count[len] = 0;
kusano 7d535a
    for (sym = 0; sym < codes; sym++)
kusano 7d535a
        count[lens[sym]]++;
kusano 7d535a
kusano 7d535a
    /* bound code lengths, force root to be within code lengths */
kusano 7d535a
    root = *bits;
kusano 7d535a
    for (max = MAXBITS; max >= 1; max--)
kusano 7d535a
        if (count[max] != 0) break;
kusano 7d535a
    if (root > max) root = max;
kusano 7d535a
    if (max == 0) return -1;            /* no codes! */
kusano 7d535a
    for (min = 1; min <= MAXBITS; min++)
kusano 7d535a
        if (count[min] != 0) break;
kusano 7d535a
    if (root < min) root = min;
kusano 7d535a
kusano 7d535a
    /* check for an over-subscribed or incomplete set of lengths */
kusano 7d535a
    left = 1;
kusano 7d535a
    for (len = 1; len <= MAXBITS; len++) {
kusano 7d535a
        left <<= 1;
kusano 7d535a
        left -= count[len];
kusano 7d535a
        if (left < 0) return -1;        /* over-subscribed */
kusano 7d535a
    }
kusano 7d535a
    if (left > 0 && (type == CODES || max != 1))
kusano 7d535a
        return -1;                      /* incomplete set */
kusano 7d535a
kusano 7d535a
    /* generate offsets into symbol table for each length for sorting */
kusano 7d535a
    offs[1] = 0;
kusano 7d535a
    for (len = 1; len < MAXBITS; len++)
kusano 7d535a
        offs[len + 1] = offs[len] + count[len];
kusano 7d535a
kusano 7d535a
    /* sort symbols by length, by symbol order within each length */
kusano 7d535a
    for (sym = 0; sym < codes; sym++)
kusano 7d535a
        if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
kusano 7d535a
kusano 7d535a
    /*
kusano 7d535a
       Create and fill in decoding tables.  In this loop, the table being
kusano 7d535a
       filled is at next and has curr index bits.  The code being used is huff
kusano 7d535a
       with length len.  That code is converted to an index by dropping drop
kusano 7d535a
       bits off of the bottom.  For codes where len is less than drop + curr,
kusano 7d535a
       those top drop + curr - len bits are incremented through all values to
kusano 7d535a
       fill the table with replicated entries.
kusano 7d535a
kusano 7d535a
       root is the number of index bits for the root table.  When len exceeds
kusano 7d535a
       root, sub-tables are created pointed to by the root entry with an index
kusano 7d535a
       of the low root bits of huff.  This is saved in low to check for when a
kusano 7d535a
       new sub-table should be started.  drop is zero when the root table is
kusano 7d535a
       being filled, and drop is root when sub-tables are being filled.
kusano 7d535a
kusano 7d535a
       When a new sub-table is needed, it is necessary to look ahead in the
kusano 7d535a
       code lengths to determine what size sub-table is needed.  The length
kusano 7d535a
       counts are used for this, and so count[] is decremented as codes are
kusano 7d535a
       entered in the tables.
kusano 7d535a
kusano 7d535a
       used keeps track of how many table entries have been allocated from the
kusano 7d535a
       provided *table space.  It is checked for LENS and DIST tables against
kusano 7d535a
       the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
kusano 7d535a
       the initial root table size constants.  See the comments in inftree9.h
kusano 7d535a
       for more information.
kusano 7d535a
kusano 7d535a
       sym increments through all symbols, and the loop terminates when
kusano 7d535a
       all codes of length max, i.e. all codes, have been processed.  This
kusano 7d535a
       routine permits incomplete codes, so another loop after this one fills
kusano 7d535a
       in the rest of the decoding tables with invalid code markers.
kusano 7d535a
     */
kusano 7d535a
kusano 7d535a
    /* set up for code type */
kusano 7d535a
    switch (type) {
kusano 7d535a
    case CODES:
kusano 7d535a
        base = extra = work;    /* dummy value--not used */
kusano 7d535a
        end = 19;
kusano 7d535a
        break;
kusano 7d535a
    case LENS:
kusano 7d535a
        base = lbase;
kusano 7d535a
        base -= 257;
kusano 7d535a
        extra = lext;
kusano 7d535a
        extra -= 257;
kusano 7d535a
        end = 256;
kusano 7d535a
        break;
kusano 7d535a
    default:            /* DISTS */
kusano 7d535a
        base = dbase;
kusano 7d535a
        extra = dext;
kusano 7d535a
        end = -1;
kusano 7d535a
    }
kusano 7d535a
kusano 7d535a
    /* initialize state for loop */
kusano 7d535a
    huff = 0;                   /* starting code */
kusano 7d535a
    sym = 0;                    /* starting code symbol */
kusano 7d535a
    len = min;                  /* starting code length */
kusano 7d535a
    next = *table;              /* current table to fill in */
kusano 7d535a
    curr = root;                /* current table index bits */
kusano 7d535a
    drop = 0;                   /* current bits to drop from code for index */
kusano 7d535a
    low = (unsigned)(-1);       /* trigger new sub-table when len > root */
kusano 7d535a
    used = 1U << root;          /* use root table entries */
kusano 7d535a
    mask = used - 1;            /* mask for comparing low */
kusano 7d535a
kusano 7d535a
    /* check available table space */
kusano 7d535a
    if ((type == LENS && used >= ENOUGH_LENS) ||
kusano 7d535a
        (type == DISTS && used >= ENOUGH_DISTS))
kusano 7d535a
        return 1;
kusano 7d535a
kusano 7d535a
    /* process all codes and make table entries */
kusano 7d535a
    for (;;) {
kusano 7d535a
        /* create table entry */
kusano 7d535a
        this.bits = (unsigned char)(len - drop);
kusano 7d535a
        if ((int)(work[sym]) < end) {
kusano 7d535a
            this.op = (unsigned char)0;
kusano 7d535a
            this.val = work[sym];
kusano 7d535a
        }
kusano 7d535a
        else if ((int)(work[sym]) > end) {
kusano 7d535a
            this.op = (unsigned char)(extra[work[sym]]);
kusano 7d535a
            this.val = base[work[sym]];
kusano 7d535a
        }
kusano 7d535a
        else {
kusano 7d535a
            this.op = (unsigned char)(32 + 64);         /* end of block */
kusano 7d535a
            this.val = 0;
kusano 7d535a
        }
kusano 7d535a
kusano 7d535a
        /* replicate for those indices with low len bits equal to huff */
kusano 7d535a
        incr = 1U << (len - drop);
kusano 7d535a
        fill = 1U << curr;
kusano 7d535a
        do {
kusano 7d535a
            fill -= incr;
kusano 7d535a
            next[(huff >> drop) + fill] = this;
kusano 7d535a
        } while (fill != 0);
kusano 7d535a
kusano 7d535a
        /* backwards increment the len-bit code huff */
kusano 7d535a
        incr = 1U << (len - 1);
kusano 7d535a
        while (huff & incr)
kusano 7d535a
            incr >>= 1;
kusano 7d535a
        if (incr != 0) {
kusano 7d535a
            huff &= incr - 1;
kusano 7d535a
            huff += incr;
kusano 7d535a
        }
kusano 7d535a
        else
kusano 7d535a
            huff = 0;
kusano 7d535a
kusano 7d535a
        /* go to next symbol, update count, len */
kusano 7d535a
        sym++;
kusano 7d535a
        if (--(count[len]) == 0) {
kusano 7d535a
            if (len == max) break;
kusano 7d535a
            len = lens[work[sym]];
kusano 7d535a
        }
kusano 7d535a
kusano 7d535a
        /* create new sub-table if needed */
kusano 7d535a
        if (len > root && (huff & mask) != low) {
kusano 7d535a
            /* if first time, transition to sub-tables */
kusano 7d535a
            if (drop == 0)
kusano 7d535a
                drop = root;
kusano 7d535a
kusano 7d535a
            /* increment past last table */
kusano 7d535a
            next += 1U << curr;
kusano 7d535a
kusano 7d535a
            /* determine length of next table */
kusano 7d535a
            curr = len - drop;
kusano 7d535a
            left = (int)(1 << curr);
kusano 7d535a
            while (curr + drop < max) {
kusano 7d535a
                left -= count[curr + drop];
kusano 7d535a
                if (left <= 0) break;
kusano 7d535a
                curr++;
kusano 7d535a
                left <<= 1;
kusano 7d535a
            }
kusano 7d535a
kusano 7d535a
            /* check for enough space */
kusano 7d535a
            used += 1U << curr;
kusano 7d535a
            if ((type == LENS && used >= ENOUGH_LENS) ||
kusano 7d535a
                (type == DISTS && used >= ENOUGH_DISTS))
kusano 7d535a
                return 1;
kusano 7d535a
kusano 7d535a
            /* point entry in root table to sub-table */
kusano 7d535a
            low = huff & mask;
kusano 7d535a
            (*table)[low].op = (unsigned char)curr;
kusano 7d535a
            (*table)[low].bits = (unsigned char)root;
kusano 7d535a
            (*table)[low].val = (unsigned short)(next - *table);
kusano 7d535a
        }
kusano 7d535a
    }
kusano 7d535a
kusano 7d535a
    /*
kusano 7d535a
       Fill in rest of table for incomplete codes.  This loop is similar to the
kusano 7d535a
       loop above in incrementing huff for table indices.  It is assumed that
kusano 7d535a
       len is equal to curr + drop, so there is no loop needed to increment
kusano 7d535a
       through high index bits.  When the current sub-table is filled, the loop
kusano 7d535a
       drops back to the root table to fill in any remaining entries there.
kusano 7d535a
     */
kusano 7d535a
    this.op = (unsigned char)64;                /* invalid code marker */
kusano 7d535a
    this.bits = (unsigned char)(len - drop);
kusano 7d535a
    this.val = (unsigned short)0;
kusano 7d535a
    while (huff != 0) {
kusano 7d535a
        /* when done with sub-table, drop back to root table */
kusano 7d535a
        if (drop != 0 && (huff & mask) != low) {
kusano 7d535a
            drop = 0;
kusano 7d535a
            len = root;
kusano 7d535a
            next = *table;
kusano 7d535a
            curr = root;
kusano 7d535a
            this.bits = (unsigned char)len;
kusano 7d535a
        }
kusano 7d535a
kusano 7d535a
        /* put invalid code marker in table */
kusano 7d535a
        next[huff >> drop] = this;
kusano 7d535a
kusano 7d535a
        /* backwards increment the len-bit code huff */
kusano 7d535a
        incr = 1U << (len - 1);
kusano 7d535a
        while (huff & incr)
kusano 7d535a
            incr >>= 1;
kusano 7d535a
        if (incr != 0) {
kusano 7d535a
            huff &= incr - 1;
kusano 7d535a
            huff += incr;
kusano 7d535a
        }
kusano 7d535a
        else
kusano 7d535a
            huff = 0;
kusano 7d535a
    }
kusano 7d535a
kusano 7d535a
    /* set return parameters */
kusano 7d535a
    *table += used;
kusano 7d535a
    *bits = root;
kusano 7d535a
    return 0;
kusano 7d535a
}