Home | History | Annotate | Line # | Download | only in puff
puff.c revision 1.1
      1  1.1  christos /*
      2  1.1  christos  * puff.c
      3  1.1  christos  * Copyright (C) 2002-2010 Mark Adler
      4  1.1  christos  * For conditions of distribution and use, see copyright notice in puff.h
      5  1.1  christos  * version 2.2, 25 Apr 2010
      6  1.1  christos  *
      7  1.1  christos  * puff.c is a simple inflate written to be an unambiguous way to specify the
      8  1.1  christos  * deflate format.  It is not written for speed but rather simplicity.  As a
      9  1.1  christos  * side benefit, this code might actually be useful when small code is more
     10  1.1  christos  * important than speed, such as bootstrap applications.  For typical deflate
     11  1.1  christos  * data, zlib's inflate() is about four times as fast as puff().  zlib's
     12  1.1  christos  * inflate compiles to around 20K on my machine, whereas puff.c compiles to
     13  1.1  christos  * around 4K on my machine (a PowerPC using GNU cc).  If the faster decode()
     14  1.1  christos  * function here is used, then puff() is only twice as slow as zlib's
     15  1.1  christos  * inflate().
     16  1.1  christos  *
     17  1.1  christos  * All dynamically allocated memory comes from the stack.  The stack required
     18  1.1  christos  * is less than 2K bytes.  This code is compatible with 16-bit int's and
     19  1.1  christos  * assumes that long's are at least 32 bits.  puff.c uses the short data type,
     20  1.1  christos  * assumed to be 16 bits, for arrays in order to to conserve memory.  The code
     21  1.1  christos  * works whether integers are stored big endian or little endian.
     22  1.1  christos  *
     23  1.1  christos  * In the comments below are "Format notes" that describe the inflate process
     24  1.1  christos  * and document some of the less obvious aspects of the format.  This source
     25  1.1  christos  * code is meant to supplement RFC 1951, which formally describes the deflate
     26  1.1  christos  * format:
     27  1.1  christos  *
     28  1.1  christos  *    http://www.zlib.org/rfc-deflate.html
     29  1.1  christos  */
     30  1.1  christos 
     31  1.1  christos /*
     32  1.1  christos  * Change history:
     33  1.1  christos  *
     34  1.1  christos  * 1.0  10 Feb 2002     - First version
     35  1.1  christos  * 1.1  17 Feb 2002     - Clarifications of some comments and notes
     36  1.1  christos  *                      - Update puff() dest and source pointers on negative
     37  1.1  christos  *                        errors to facilitate debugging deflators
     38  1.1  christos  *                      - Remove longest from struct huffman -- not needed
     39  1.1  christos  *                      - Simplify offs[] index in construct()
     40  1.1  christos  *                      - Add input size and checking, using longjmp() to
     41  1.1  christos  *                        maintain easy readability
     42  1.1  christos  *                      - Use short data type for large arrays
     43  1.1  christos  *                      - Use pointers instead of long to specify source and
     44  1.1  christos  *                        destination sizes to avoid arbitrary 4 GB limits
     45  1.1  christos  * 1.2  17 Mar 2002     - Add faster version of decode(), doubles speed (!),
     46  1.1  christos  *                        but leave simple version for readabilty
     47  1.1  christos  *                      - Make sure invalid distances detected if pointers
     48  1.1  christos  *                        are 16 bits
     49  1.1  christos  *                      - Fix fixed codes table error
     50  1.1  christos  *                      - Provide a scanning mode for determining size of
     51  1.1  christos  *                        uncompressed data
     52  1.1  christos  * 1.3  20 Mar 2002     - Go back to lengths for puff() parameters [Gailly]
     53  1.1  christos  *                      - Add a puff.h file for the interface
     54  1.1  christos  *                      - Add braces in puff() for else do [Gailly]
     55  1.1  christos  *                      - Use indexes instead of pointers for readability
     56  1.1  christos  * 1.4  31 Mar 2002     - Simplify construct() code set check
     57  1.1  christos  *                      - Fix some comments
     58  1.1  christos  *                      - Add FIXLCODES #define
     59  1.1  christos  * 1.5   6 Apr 2002     - Minor comment fixes
     60  1.1  christos  * 1.6   7 Aug 2002     - Minor format changes
     61  1.1  christos  * 1.7   3 Mar 2003     - Added test code for distribution
     62  1.1  christos  *                      - Added zlib-like license
     63  1.1  christos  * 1.8   9 Jan 2004     - Added some comments on no distance codes case
     64  1.1  christos  * 1.9  21 Feb 2008     - Fix bug on 16-bit integer architectures [Pohland]
     65  1.1  christos  *                      - Catch missing end-of-block symbol error
     66  1.1  christos  * 2.0  25 Jul 2008     - Add #define to permit distance too far back
     67  1.1  christos  *                      - Add option in TEST code for puff to write the data
     68  1.1  christos  *                      - Add option in TEST code to skip input bytes
     69  1.1  christos  *                      - Allow TEST code to read from piped stdin
     70  1.1  christos  * 2.1   4 Apr 2010     - Avoid variable initialization for happier compilers
     71  1.1  christos  *                      - Avoid unsigned comparisons for even happier compilers
     72  1.1  christos  * 2.2  25 Apr 2010     - Fix bug in variable initializations [Oberhumer]
     73  1.1  christos  *                      - Add const where appropriate [Oberhumer]
     74  1.1  christos  *                      - Split if's and ?'s for coverage testing
     75  1.1  christos  *                      - Break out test code to separate file
     76  1.1  christos  *                      - Move NIL to puff.h
     77  1.1  christos  *                      - Allow incomplete code only if single code length is 1
     78  1.1  christos  *                      - Add full code coverage test to Makefile
     79  1.1  christos  */
     80  1.1  christos 
     81  1.1  christos #include <setjmp.h>             /* for setjmp(), longjmp(), and jmp_buf */
     82  1.1  christos #include "puff.h"               /* prototype for puff() */
     83  1.1  christos 
     84  1.1  christos #define local static            /* for local function definitions */
     85  1.1  christos 
     86  1.1  christos /*
     87  1.1  christos  * Maximums for allocations and loops.  It is not useful to change these --
     88  1.1  christos  * they are fixed by the deflate format.
     89  1.1  christos  */
     90  1.1  christos #define MAXBITS 15              /* maximum bits in a code */
     91  1.1  christos #define MAXLCODES 286           /* maximum number of literal/length codes */
     92  1.1  christos #define MAXDCODES 30            /* maximum number of distance codes */
     93  1.1  christos #define MAXCODES (MAXLCODES+MAXDCODES)  /* maximum codes lengths to read */
     94  1.1  christos #define FIXLCODES 288           /* number of fixed literal/length codes */
     95  1.1  christos 
     96  1.1  christos /* input and output state */
     97  1.1  christos struct state {
     98  1.1  christos     /* output state */
     99  1.1  christos     unsigned char *out;         /* output buffer */
    100  1.1  christos     unsigned long outlen;       /* available space at out */
    101  1.1  christos     unsigned long outcnt;       /* bytes written to out so far */
    102  1.1  christos 
    103  1.1  christos     /* input state */
    104  1.1  christos     const unsigned char *in;    /* input buffer */
    105  1.1  christos     unsigned long inlen;        /* available input at in */
    106  1.1  christos     unsigned long incnt;        /* bytes read so far */
    107  1.1  christos     int bitbuf;                 /* bit buffer */
    108  1.1  christos     int bitcnt;                 /* number of bits in bit buffer */
    109  1.1  christos 
    110  1.1  christos     /* input limit error return state for bits() and decode() */
    111  1.1  christos     jmp_buf env;
    112  1.1  christos };
    113  1.1  christos 
    114  1.1  christos /*
    115  1.1  christos  * Return need bits from the input stream.  This always leaves less than
    116  1.1  christos  * eight bits in the buffer.  bits() works properly for need == 0.
    117  1.1  christos  *
    118  1.1  christos  * Format notes:
    119  1.1  christos  *
    120  1.1  christos  * - Bits are stored in bytes from the least significant bit to the most
    121  1.1  christos  *   significant bit.  Therefore bits are dropped from the bottom of the bit
    122  1.1  christos  *   buffer, using shift right, and new bytes are appended to the top of the
    123  1.1  christos  *   bit buffer, using shift left.
    124  1.1  christos  */
    125  1.1  christos local int bits(struct state *s, int need)
    126  1.1  christos {
    127  1.1  christos     long val;           /* bit accumulator (can use up to 20 bits) */
    128  1.1  christos 
    129  1.1  christos     /* load at least need bits into val */
    130  1.1  christos     val = s->bitbuf;
    131  1.1  christos     while (s->bitcnt < need) {
    132  1.1  christos         if (s->incnt == s->inlen)
    133  1.1  christos             longjmp(s->env, 1);         /* out of input */
    134  1.1  christos         val |= (long)(s->in[s->incnt++]) << s->bitcnt;  /* load eight bits */
    135  1.1  christos         s->bitcnt += 8;
    136  1.1  christos     }
    137  1.1  christos 
    138  1.1  christos     /* drop need bits and update buffer, always zero to seven bits left */
    139  1.1  christos     s->bitbuf = (int)(val >> need);
    140  1.1  christos     s->bitcnt -= need;
    141  1.1  christos 
    142  1.1  christos     /* return need bits, zeroing the bits above that */
    143  1.1  christos     return (int)(val & ((1L << need) - 1));
    144  1.1  christos }
    145  1.1  christos 
    146  1.1  christos /*
    147  1.1  christos  * Process a stored block.
    148  1.1  christos  *
    149  1.1  christos  * Format notes:
    150  1.1  christos  *
    151  1.1  christos  * - After the two-bit stored block type (00), the stored block length and
    152  1.1  christos  *   stored bytes are byte-aligned for fast copying.  Therefore any leftover
    153  1.1  christos  *   bits in the byte that has the last bit of the type, as many as seven, are
    154  1.1  christos  *   discarded.  The value of the discarded bits are not defined and should not
    155  1.1  christos  *   be checked against any expectation.
    156  1.1  christos  *
    157  1.1  christos  * - The second inverted copy of the stored block length does not have to be
    158  1.1  christos  *   checked, but it's probably a good idea to do so anyway.
    159  1.1  christos  *
    160  1.1  christos  * - A stored block can have zero length.  This is sometimes used to byte-align
    161  1.1  christos  *   subsets of the compressed data for random access or partial recovery.
    162  1.1  christos  */
    163  1.1  christos local int stored(struct state *s)
    164  1.1  christos {
    165  1.1  christos     unsigned len;       /* length of stored block */
    166  1.1  christos 
    167  1.1  christos     /* discard leftover bits from current byte (assumes s->bitcnt < 8) */
    168  1.1  christos     s->bitbuf = 0;
    169  1.1  christos     s->bitcnt = 0;
    170  1.1  christos 
    171  1.1  christos     /* get length and check against its one's complement */
    172  1.1  christos     if (s->incnt + 4 > s->inlen)
    173  1.1  christos         return 2;                               /* not enough input */
    174  1.1  christos     len = s->in[s->incnt++];
    175  1.1  christos     len |= s->in[s->incnt++] << 8;
    176  1.1  christos     if (s->in[s->incnt++] != (~len & 0xff) ||
    177  1.1  christos         s->in[s->incnt++] != ((~len >> 8) & 0xff))
    178  1.1  christos         return -2;                              /* didn't match complement! */
    179  1.1  christos 
    180  1.1  christos     /* copy len bytes from in to out */
    181  1.1  christos     if (s->incnt + len > s->inlen)
    182  1.1  christos         return 2;                               /* not enough input */
    183  1.1  christos     if (s->out != NIL) {
    184  1.1  christos         if (s->outcnt + len > s->outlen)
    185  1.1  christos             return 1;                           /* not enough output space */
    186  1.1  christos         while (len--)
    187  1.1  christos             s->out[s->outcnt++] = s->in[s->incnt++];
    188  1.1  christos     }
    189  1.1  christos     else {                                      /* just scanning */
    190  1.1  christos         s->outcnt += len;
    191  1.1  christos         s->incnt += len;
    192  1.1  christos     }
    193  1.1  christos 
    194  1.1  christos     /* done with a valid stored block */
    195  1.1  christos     return 0;
    196  1.1  christos }
    197  1.1  christos 
    198  1.1  christos /*
    199  1.1  christos  * Huffman code decoding tables.  count[1..MAXBITS] is the number of symbols of
    200  1.1  christos  * each length, which for a canonical code are stepped through in order.
    201  1.1  christos  * symbol[] are the symbol values in canonical order, where the number of
    202  1.1  christos  * entries is the sum of the counts in count[].  The decoding process can be
    203  1.1  christos  * seen in the function decode() below.
    204  1.1  christos  */
    205  1.1  christos struct huffman {
    206  1.1  christos     short *count;       /* number of symbols of each length */
    207  1.1  christos     short *symbol;      /* canonically ordered symbols */
    208  1.1  christos };
    209  1.1  christos 
    210  1.1  christos /*
    211  1.1  christos  * Decode a code from the stream s using huffman table h.  Return the symbol or
    212  1.1  christos  * a negative value if there is an error.  If all of the lengths are zero, i.e.
    213  1.1  christos  * an empty code, or if the code is incomplete and an invalid code is received,
    214  1.1  christos  * then -10 is returned after reading MAXBITS bits.
    215  1.1  christos  *
    216  1.1  christos  * Format notes:
    217  1.1  christos  *
    218  1.1  christos  * - The codes as stored in the compressed data are bit-reversed relative to
    219  1.1  christos  *   a simple integer ordering of codes of the same lengths.  Hence below the
    220  1.1  christos  *   bits are pulled from the compressed data one at a time and used to
    221  1.1  christos  *   build the code value reversed from what is in the stream in order to
    222  1.1  christos  *   permit simple integer comparisons for decoding.  A table-based decoding
    223  1.1  christos  *   scheme (as used in zlib) does not need to do this reversal.
    224  1.1  christos  *
    225  1.1  christos  * - The first code for the shortest length is all zeros.  Subsequent codes of
    226  1.1  christos  *   the same length are simply integer increments of the previous code.  When
    227  1.1  christos  *   moving up a length, a zero bit is appended to the code.  For a complete
    228  1.1  christos  *   code, the last code of the longest length will be all ones.
    229  1.1  christos  *
    230  1.1  christos  * - Incomplete codes are handled by this decoder, since they are permitted
    231  1.1  christos  *   in the deflate format.  See the format notes for fixed() and dynamic().
    232  1.1  christos  */
    233  1.1  christos #ifdef SLOW
    234  1.1  christos local int decode(struct state *s, const struct huffman *h)
    235  1.1  christos {
    236  1.1  christos     int len;            /* current number of bits in code */
    237  1.1  christos     int code;           /* len bits being decoded */
    238  1.1  christos     int first;          /* first code of length len */
    239  1.1  christos     int count;          /* number of codes of length len */
    240  1.1  christos     int index;          /* index of first code of length len in symbol table */
    241  1.1  christos 
    242  1.1  christos     code = first = index = 0;
    243  1.1  christos     for (len = 1; len <= MAXBITS; len++) {
    244  1.1  christos         code |= bits(s, 1);             /* get next bit */
    245  1.1  christos         count = h->count[len];
    246  1.1  christos         if (code - count < first)       /* if length len, return symbol */
    247  1.1  christos             return h->symbol[index + (code - first)];
    248  1.1  christos         index += count;                 /* else update for next length */
    249  1.1  christos         first += count;
    250  1.1  christos         first <<= 1;
    251  1.1  christos         code <<= 1;
    252  1.1  christos     }
    253  1.1  christos     return -10;                         /* ran out of codes */
    254  1.1  christos }
    255  1.1  christos 
    256  1.1  christos /*
    257  1.1  christos  * A faster version of decode() for real applications of this code.   It's not
    258  1.1  christos  * as readable, but it makes puff() twice as fast.  And it only makes the code
    259  1.1  christos  * a few percent larger.
    260  1.1  christos  */
    261  1.1  christos #else /* !SLOW */
    262  1.1  christos local int decode(struct state *s, const struct huffman *h)
    263  1.1  christos {
    264  1.1  christos     int len;            /* current number of bits in code */
    265  1.1  christos     int code;           /* len bits being decoded */
    266  1.1  christos     int first;          /* first code of length len */
    267  1.1  christos     int count;          /* number of codes of length len */
    268  1.1  christos     int index;          /* index of first code of length len in symbol table */
    269  1.1  christos     int bitbuf;         /* bits from stream */
    270  1.1  christos     int left;           /* bits left in next or left to process */
    271  1.1  christos     short *next;        /* next number of codes */
    272  1.1  christos 
    273  1.1  christos     bitbuf = s->bitbuf;
    274  1.1  christos     left = s->bitcnt;
    275  1.1  christos     code = first = index = 0;
    276  1.1  christos     len = 1;
    277  1.1  christos     next = h->count + 1;
    278  1.1  christos     while (1) {
    279  1.1  christos         while (left--) {
    280  1.1  christos             code |= bitbuf & 1;
    281  1.1  christos             bitbuf >>= 1;
    282  1.1  christos             count = *next++;
    283  1.1  christos             if (code - count < first) { /* if length len, return symbol */
    284  1.1  christos                 s->bitbuf = bitbuf;
    285  1.1  christos                 s->bitcnt = (s->bitcnt - len) & 7;
    286  1.1  christos                 return h->symbol[index + (code - first)];
    287  1.1  christos             }
    288  1.1  christos             index += count;             /* else update for next length */
    289  1.1  christos             first += count;
    290  1.1  christos             first <<= 1;
    291  1.1  christos             code <<= 1;
    292  1.1  christos             len++;
    293  1.1  christos         }
    294  1.1  christos         left = (MAXBITS+1) - len;
    295  1.1  christos         if (left == 0)
    296  1.1  christos             break;
    297  1.1  christos         if (s->incnt == s->inlen)
    298  1.1  christos             longjmp(s->env, 1);         /* out of input */
    299  1.1  christos         bitbuf = s->in[s->incnt++];
    300  1.1  christos         if (left > 8)
    301  1.1  christos             left = 8;
    302  1.1  christos     }
    303  1.1  christos     return -10;                         /* ran out of codes */
    304  1.1  christos }
    305  1.1  christos #endif /* SLOW */
    306  1.1  christos 
    307  1.1  christos /*
    308  1.1  christos  * Given the list of code lengths length[0..n-1] representing a canonical
    309  1.1  christos  * Huffman code for n symbols, construct the tables required to decode those
    310  1.1  christos  * codes.  Those tables are the number of codes of each length, and the symbols
    311  1.1  christos  * sorted by length, retaining their original order within each length.  The
    312  1.1  christos  * return value is zero for a complete code set, negative for an over-
    313  1.1  christos  * subscribed code set, and positive for an incomplete code set.  The tables
    314  1.1  christos  * can be used if the return value is zero or positive, but they cannot be used
    315  1.1  christos  * if the return value is negative.  If the return value is zero, it is not
    316  1.1  christos  * possible for decode() using that table to return an error--any stream of
    317  1.1  christos  * enough bits will resolve to a symbol.  If the return value is positive, then
    318  1.1  christos  * it is possible for decode() using that table to return an error for received
    319  1.1  christos  * codes past the end of the incomplete lengths.
    320  1.1  christos  *
    321  1.1  christos  * Not used by decode(), but used for error checking, h->count[0] is the number
    322  1.1  christos  * of the n symbols not in the code.  So n - h->count[0] is the number of
    323  1.1  christos  * codes.  This is useful for checking for incomplete codes that have more than
    324  1.1  christos  * one symbol, which is an error in a dynamic block.
    325  1.1  christos  *
    326  1.1  christos  * Assumption: for all i in 0..n-1, 0 <= length[i] <= MAXBITS
    327  1.1  christos  * This is assured by the construction of the length arrays in dynamic() and
    328  1.1  christos  * fixed() and is not verified by construct().
    329  1.1  christos  *
    330  1.1  christos  * Format notes:
    331  1.1  christos  *
    332  1.1  christos  * - Permitted and expected examples of incomplete codes are one of the fixed
    333  1.1  christos  *   codes and any code with a single symbol which in deflate is coded as one
    334  1.1  christos  *   bit instead of zero bits.  See the format notes for fixed() and dynamic().
    335  1.1  christos  *
    336  1.1  christos  * - Within a given code length, the symbols are kept in ascending order for
    337  1.1  christos  *   the code bits definition.
    338  1.1  christos  */
    339  1.1  christos local int construct(struct huffman *h, const short *length, int n)
    340  1.1  christos {
    341  1.1  christos     int symbol;         /* current symbol when stepping through length[] */
    342  1.1  christos     int len;            /* current length when stepping through h->count[] */
    343  1.1  christos     int left;           /* number of possible codes left of current length */
    344  1.1  christos     short offs[MAXBITS+1];      /* offsets in symbol table for each length */
    345  1.1  christos 
    346  1.1  christos     /* count number of codes of each length */
    347  1.1  christos     for (len = 0; len <= MAXBITS; len++)
    348  1.1  christos         h->count[len] = 0;
    349  1.1  christos     for (symbol = 0; symbol < n; symbol++)
    350  1.1  christos         (h->count[length[symbol]])++;   /* assumes lengths are within bounds */
    351  1.1  christos     if (h->count[0] == n)               /* no codes! */
    352  1.1  christos         return 0;                       /* complete, but decode() will fail */
    353  1.1  christos 
    354  1.1  christos     /* check for an over-subscribed or incomplete set of lengths */
    355  1.1  christos     left = 1;                           /* one possible code of zero length */
    356  1.1  christos     for (len = 1; len <= MAXBITS; len++) {
    357  1.1  christos         left <<= 1;                     /* one more bit, double codes left */
    358  1.1  christos         left -= h->count[len];          /* deduct count from possible codes */
    359  1.1  christos         if (left < 0)
    360  1.1  christos             return left;                /* over-subscribed--return negative */
    361  1.1  christos     }                                   /* left > 0 means incomplete */
    362  1.1  christos 
    363  1.1  christos     /* generate offsets into symbol table for each length for sorting */
    364  1.1  christos     offs[1] = 0;
    365  1.1  christos     for (len = 1; len < MAXBITS; len++)
    366  1.1  christos         offs[len + 1] = offs[len] + h->count[len];
    367  1.1  christos 
    368  1.1  christos     /*
    369  1.1  christos      * put symbols in table sorted by length, by symbol order within each
    370  1.1  christos      * length
    371  1.1  christos      */
    372  1.1  christos     for (symbol = 0; symbol < n; symbol++)
    373  1.1  christos         if (length[symbol] != 0)
    374  1.1  christos             h->symbol[offs[length[symbol]]++] = symbol;
    375  1.1  christos 
    376  1.1  christos     /* return zero for complete set, positive for incomplete set */
    377  1.1  christos     return left;
    378  1.1  christos }
    379  1.1  christos 
    380  1.1  christos /*
    381  1.1  christos  * Decode literal/length and distance codes until an end-of-block code.
    382  1.1  christos  *
    383  1.1  christos  * Format notes:
    384  1.1  christos  *
    385  1.1  christos  * - Compressed data that is after the block type if fixed or after the code
    386  1.1  christos  *   description if dynamic is a combination of literals and length/distance
    387  1.1  christos  *   pairs terminated by and end-of-block code.  Literals are simply Huffman
    388  1.1  christos  *   coded bytes.  A length/distance pair is a coded length followed by a
    389  1.1  christos  *   coded distance to represent a string that occurs earlier in the
    390  1.1  christos  *   uncompressed data that occurs again at the current location.
    391  1.1  christos  *
    392  1.1  christos  * - Literals, lengths, and the end-of-block code are combined into a single
    393  1.1  christos  *   code of up to 286 symbols.  They are 256 literals (0..255), 29 length
    394  1.1  christos  *   symbols (257..285), and the end-of-block symbol (256).
    395  1.1  christos  *
    396  1.1  christos  * - There are 256 possible lengths (3..258), and so 29 symbols are not enough
    397  1.1  christos  *   to represent all of those.  Lengths 3..10 and 258 are in fact represented
    398  1.1  christos  *   by just a length symbol.  Lengths 11..257 are represented as a symbol and
    399  1.1  christos  *   some number of extra bits that are added as an integer to the base length
    400  1.1  christos  *   of the length symbol.  The number of extra bits is determined by the base
    401  1.1  christos  *   length symbol.  These are in the static arrays below, lens[] for the base
    402  1.1  christos  *   lengths and lext[] for the corresponding number of extra bits.
    403  1.1  christos  *
    404  1.1  christos  * - The reason that 258 gets its own symbol is that the longest length is used
    405  1.1  christos  *   often in highly redundant files.  Note that 258 can also be coded as the
    406  1.1  christos  *   base value 227 plus the maximum extra value of 31.  While a good deflate
    407  1.1  christos  *   should never do this, it is not an error, and should be decoded properly.
    408  1.1  christos  *
    409  1.1  christos  * - If a length is decoded, including its extra bits if any, then it is
    410  1.1  christos  *   followed a distance code.  There are up to 30 distance symbols.  Again
    411  1.1  christos  *   there are many more possible distances (1..32768), so extra bits are added
    412  1.1  christos  *   to a base value represented by the symbol.  The distances 1..4 get their
    413  1.1  christos  *   own symbol, but the rest require extra bits.  The base distances and
    414  1.1  christos  *   corresponding number of extra bits are below in the static arrays dist[]
    415  1.1  christos  *   and dext[].
    416  1.1  christos  *
    417  1.1  christos  * - Literal bytes are simply written to the output.  A length/distance pair is
    418  1.1  christos  *   an instruction to copy previously uncompressed bytes to the output.  The
    419  1.1  christos  *   copy is from distance bytes back in the output stream, copying for length
    420  1.1  christos  *   bytes.
    421  1.1  christos  *
    422  1.1  christos  * - Distances pointing before the beginning of the output data are not
    423  1.1  christos  *   permitted.
    424  1.1  christos  *
    425  1.1  christos  * - Overlapped copies, where the length is greater than the distance, are
    426  1.1  christos  *   allowed and common.  For example, a distance of one and a length of 258
    427  1.1  christos  *   simply copies the last byte 258 times.  A distance of four and a length of
    428  1.1  christos  *   twelve copies the last four bytes three times.  A simple forward copy
    429  1.1  christos  *   ignoring whether the length is greater than the distance or not implements
    430  1.1  christos  *   this correctly.  You should not use memcpy() since its behavior is not
    431  1.1  christos  *   defined for overlapped arrays.  You should not use memmove() or bcopy()
    432  1.1  christos  *   since though their behavior -is- defined for overlapping arrays, it is
    433  1.1  christos  *   defined to do the wrong thing in this case.
    434  1.1  christos  */
    435  1.1  christos local int codes(struct state *s,
    436  1.1  christos                 const struct huffman *lencode,
    437  1.1  christos                 const struct huffman *distcode)
    438  1.1  christos {
    439  1.1  christos     int symbol;         /* decoded symbol */
    440  1.1  christos     int len;            /* length for copy */
    441  1.1  christos     unsigned dist;      /* distance for copy */
    442  1.1  christos     static const short lens[29] = { /* Size base for length codes 257..285 */
    443  1.1  christos         3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
    444  1.1  christos         35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258};
    445  1.1  christos     static const short lext[29] = { /* Extra bits for length codes 257..285 */
    446  1.1  christos         0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
    447  1.1  christos         3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0};
    448  1.1  christos     static const short dists[30] = { /* Offset base for distance codes 0..29 */
    449  1.1  christos         1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
    450  1.1  christos         257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
    451  1.1  christos         8193, 12289, 16385, 24577};
    452  1.1  christos     static const short dext[30] = { /* Extra bits for distance codes 0..29 */
    453  1.1  christos         0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
    454  1.1  christos         7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
    455  1.1  christos         12, 12, 13, 13};
    456  1.1  christos 
    457  1.1  christos     /* decode literals and length/distance pairs */
    458  1.1  christos     do {
    459  1.1  christos         symbol = decode(s, lencode);
    460  1.1  christos         if (symbol < 0)
    461  1.1  christos             return symbol;              /* invalid symbol */
    462  1.1  christos         if (symbol < 256) {             /* literal: symbol is the byte */
    463  1.1  christos             /* write out the literal */
    464  1.1  christos             if (s->out != NIL) {
    465  1.1  christos                 if (s->outcnt == s->outlen)
    466  1.1  christos                     return 1;
    467  1.1  christos                 s->out[s->outcnt] = symbol;
    468  1.1  christos             }
    469  1.1  christos             s->outcnt++;
    470  1.1  christos         }
    471  1.1  christos         else if (symbol > 256) {        /* length */
    472  1.1  christos             /* get and compute length */
    473  1.1  christos             symbol -= 257;
    474  1.1  christos             if (symbol >= 29)
    475  1.1  christos                 return -10;             /* invalid fixed code */
    476  1.1  christos             len = lens[symbol] + bits(s, lext[symbol]);
    477  1.1  christos 
    478  1.1  christos             /* get and check distance */
    479  1.1  christos             symbol = decode(s, distcode);
    480  1.1  christos             if (symbol < 0)
    481  1.1  christos                 return symbol;          /* invalid symbol */
    482  1.1  christos             dist = dists[symbol] + bits(s, dext[symbol]);
    483  1.1  christos #ifndef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
    484  1.1  christos             if (dist > s->outcnt)
    485  1.1  christos                 return -11;     /* distance too far back */
    486  1.1  christos #endif
    487  1.1  christos 
    488  1.1  christos             /* copy length bytes from distance bytes back */
    489  1.1  christos             if (s->out != NIL) {
    490  1.1  christos                 if (s->outcnt + len > s->outlen)
    491  1.1  christos                     return 1;
    492  1.1  christos                 while (len--) {
    493  1.1  christos                     s->out[s->outcnt] =
    494  1.1  christos #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
    495  1.1  christos                         dist > s->outcnt ?
    496  1.1  christos                             0 :
    497  1.1  christos #endif
    498  1.1  christos                             s->out[s->outcnt - dist];
    499  1.1  christos                     s->outcnt++;
    500  1.1  christos                 }
    501  1.1  christos             }
    502  1.1  christos             else
    503  1.1  christos                 s->outcnt += len;
    504  1.1  christos         }
    505  1.1  christos     } while (symbol != 256);            /* end of block symbol */
    506  1.1  christos 
    507  1.1  christos     /* done with a valid fixed or dynamic block */
    508  1.1  christos     return 0;
    509  1.1  christos }
    510  1.1  christos 
    511  1.1  christos /*
    512  1.1  christos  * Process a fixed codes block.
    513  1.1  christos  *
    514  1.1  christos  * Format notes:
    515  1.1  christos  *
    516  1.1  christos  * - This block type can be useful for compressing small amounts of data for
    517  1.1  christos  *   which the size of the code descriptions in a dynamic block exceeds the
    518  1.1  christos  *   benefit of custom codes for that block.  For fixed codes, no bits are
    519  1.1  christos  *   spent on code descriptions.  Instead the code lengths for literal/length
    520  1.1  christos  *   codes and distance codes are fixed.  The specific lengths for each symbol
    521  1.1  christos  *   can be seen in the "for" loops below.
    522  1.1  christos  *
    523  1.1  christos  * - The literal/length code is complete, but has two symbols that are invalid
    524  1.1  christos  *   and should result in an error if received.  This cannot be implemented
    525  1.1  christos  *   simply as an incomplete code since those two symbols are in the "middle"
    526  1.1  christos  *   of the code.  They are eight bits long and the longest literal/length\
    527  1.1  christos  *   code is nine bits.  Therefore the code must be constructed with those
    528  1.1  christos  *   symbols, and the invalid symbols must be detected after decoding.
    529  1.1  christos  *
    530  1.1  christos  * - The fixed distance codes also have two invalid symbols that should result
    531  1.1  christos  *   in an error if received.  Since all of the distance codes are the same
    532  1.1  christos  *   length, this can be implemented as an incomplete code.  Then the invalid
    533  1.1  christos  *   codes are detected while decoding.
    534  1.1  christos  */
    535  1.1  christos local int fixed(struct state *s)
    536  1.1  christos {
    537  1.1  christos     static int virgin = 1;
    538  1.1  christos     static short lencnt[MAXBITS+1], lensym[FIXLCODES];
    539  1.1  christos     static short distcnt[MAXBITS+1], distsym[MAXDCODES];
    540  1.1  christos     static struct huffman lencode, distcode;
    541  1.1  christos 
    542  1.1  christos     /* build fixed huffman tables if first call (may not be thread safe) */
    543  1.1  christos     if (virgin) {
    544  1.1  christos         int symbol;
    545  1.1  christos         short lengths[FIXLCODES];
    546  1.1  christos 
    547  1.1  christos         /* construct lencode and distcode */
    548  1.1  christos         lencode.count = lencnt;
    549  1.1  christos         lencode.symbol = lensym;
    550  1.1  christos         distcode.count = distcnt;
    551  1.1  christos         distcode.symbol = distsym;
    552  1.1  christos 
    553  1.1  christos         /* literal/length table */
    554  1.1  christos         for (symbol = 0; symbol < 144; symbol++)
    555  1.1  christos             lengths[symbol] = 8;
    556  1.1  christos         for (; symbol < 256; symbol++)
    557  1.1  christos             lengths[symbol] = 9;
    558  1.1  christos         for (; symbol < 280; symbol++)
    559  1.1  christos             lengths[symbol] = 7;
    560  1.1  christos         for (; symbol < FIXLCODES; symbol++)
    561  1.1  christos             lengths[symbol] = 8;
    562  1.1  christos         construct(&lencode, lengths, FIXLCODES);
    563  1.1  christos 
    564  1.1  christos         /* distance table */
    565  1.1  christos         for (symbol = 0; symbol < MAXDCODES; symbol++)
    566  1.1  christos             lengths[symbol] = 5;
    567  1.1  christos         construct(&distcode, lengths, MAXDCODES);
    568  1.1  christos 
    569  1.1  christos         /* do this just once */
    570  1.1  christos         virgin = 0;
    571  1.1  christos     }
    572  1.1  christos 
    573  1.1  christos     /* decode data until end-of-block code */
    574  1.1  christos     return codes(s, &lencode, &distcode);
    575  1.1  christos }
    576  1.1  christos 
    577  1.1  christos /*
    578  1.1  christos  * Process a dynamic codes block.
    579  1.1  christos  *
    580  1.1  christos  * Format notes:
    581  1.1  christos  *
    582  1.1  christos  * - A dynamic block starts with a description of the literal/length and
    583  1.1  christos  *   distance codes for that block.  New dynamic blocks allow the compressor to
    584  1.1  christos  *   rapidly adapt to changing data with new codes optimized for that data.
    585  1.1  christos  *
    586  1.1  christos  * - The codes used by the deflate format are "canonical", which means that
    587  1.1  christos  *   the actual bits of the codes are generated in an unambiguous way simply
    588  1.1  christos  *   from the number of bits in each code.  Therefore the code descriptions
    589  1.1  christos  *   are simply a list of code lengths for each symbol.
    590  1.1  christos  *
    591  1.1  christos  * - The code lengths are stored in order for the symbols, so lengths are
    592  1.1  christos  *   provided for each of the literal/length symbols, and for each of the
    593  1.1  christos  *   distance symbols.
    594  1.1  christos  *
    595  1.1  christos  * - If a symbol is not used in the block, this is represented by a zero as
    596  1.1  christos  *   as the code length.  This does not mean a zero-length code, but rather
    597  1.1  christos  *   that no code should be created for this symbol.  There is no way in the
    598  1.1  christos  *   deflate format to represent a zero-length code.
    599  1.1  christos  *
    600  1.1  christos  * - The maximum number of bits in a code is 15, so the possible lengths for
    601  1.1  christos  *   any code are 1..15.
    602  1.1  christos  *
    603  1.1  christos  * - The fact that a length of zero is not permitted for a code has an
    604  1.1  christos  *   interesting consequence.  Normally if only one symbol is used for a given
    605  1.1  christos  *   code, then in fact that code could be represented with zero bits.  However
    606  1.1  christos  *   in deflate, that code has to be at least one bit.  So for example, if
    607  1.1  christos  *   only a single distance base symbol appears in a block, then it will be
    608  1.1  christos  *   represented by a single code of length one, in particular one 0 bit.  This
    609  1.1  christos  *   is an incomplete code, since if a 1 bit is received, it has no meaning,
    610  1.1  christos  *   and should result in an error.  So incomplete distance codes of one symbol
    611  1.1  christos  *   should be permitted, and the receipt of invalid codes should be handled.
    612  1.1  christos  *
    613  1.1  christos  * - It is also possible to have a single literal/length code, but that code
    614  1.1  christos  *   must be the end-of-block code, since every dynamic block has one.  This
    615  1.1  christos  *   is not the most efficient way to create an empty block (an empty fixed
    616  1.1  christos  *   block is fewer bits), but it is allowed by the format.  So incomplete
    617  1.1  christos  *   literal/length codes of one symbol should also be permitted.
    618  1.1  christos  *
    619  1.1  christos  * - If there are only literal codes and no lengths, then there are no distance
    620  1.1  christos  *   codes.  This is represented by one distance code with zero bits.
    621  1.1  christos  *
    622  1.1  christos  * - The list of up to 286 length/literal lengths and up to 30 distance lengths
    623  1.1  christos  *   are themselves compressed using Huffman codes and run-length encoding.  In
    624  1.1  christos  *   the list of code lengths, a 0 symbol means no code, a 1..15 symbol means
    625  1.1  christos  *   that length, and the symbols 16, 17, and 18 are run-length instructions.
    626  1.1  christos  *   Each of 16, 17, and 18 are follwed by extra bits to define the length of
    627  1.1  christos  *   the run.  16 copies the last length 3 to 6 times.  17 represents 3 to 10
    628  1.1  christos  *   zero lengths, and 18 represents 11 to 138 zero lengths.  Unused symbols
    629  1.1  christos  *   are common, hence the special coding for zero lengths.
    630  1.1  christos  *
    631  1.1  christos  * - The symbols for 0..18 are Huffman coded, and so that code must be
    632  1.1  christos  *   described first.  This is simply a sequence of up to 19 three-bit values
    633  1.1  christos  *   representing no code (0) or the code length for that symbol (1..7).
    634  1.1  christos  *
    635  1.1  christos  * - A dynamic block starts with three fixed-size counts from which is computed
    636  1.1  christos  *   the number of literal/length code lengths, the number of distance code
    637  1.1  christos  *   lengths, and the number of code length code lengths (ok, you come up with
    638  1.1  christos  *   a better name!) in the code descriptions.  For the literal/length and
    639  1.1  christos  *   distance codes, lengths after those provided are considered zero, i.e. no
    640  1.1  christos  *   code.  The code length code lengths are received in a permuted order (see
    641  1.1  christos  *   the order[] array below) to make a short code length code length list more
    642  1.1  christos  *   likely.  As it turns out, very short and very long codes are less likely
    643  1.1  christos  *   to be seen in a dynamic code description, hence what may appear initially
    644  1.1  christos  *   to be a peculiar ordering.
    645  1.1  christos  *
    646  1.1  christos  * - Given the number of literal/length code lengths (nlen) and distance code
    647  1.1  christos  *   lengths (ndist), then they are treated as one long list of nlen + ndist
    648  1.1  christos  *   code lengths.  Therefore run-length coding can and often does cross the
    649  1.1  christos  *   boundary between the two sets of lengths.
    650  1.1  christos  *
    651  1.1  christos  * - So to summarize, the code description at the start of a dynamic block is
    652  1.1  christos  *   three counts for the number of code lengths for the literal/length codes,
    653  1.1  christos  *   the distance codes, and the code length codes.  This is followed by the
    654  1.1  christos  *   code length code lengths, three bits each.  This is used to construct the
    655  1.1  christos  *   code length code which is used to read the remainder of the lengths.  Then
    656  1.1  christos  *   the literal/length code lengths and distance lengths are read as a single
    657  1.1  christos  *   set of lengths using the code length codes.  Codes are constructed from
    658  1.1  christos  *   the resulting two sets of lengths, and then finally you can start
    659  1.1  christos  *   decoding actual compressed data in the block.
    660  1.1  christos  *
    661  1.1  christos  * - For reference, a "typical" size for the code description in a dynamic
    662  1.1  christos  *   block is around 80 bytes.
    663  1.1  christos  */
    664  1.1  christos local int dynamic(struct state *s)
    665  1.1  christos {
    666  1.1  christos     int nlen, ndist, ncode;             /* number of lengths in descriptor */
    667  1.1  christos     int index;                          /* index of lengths[] */
    668  1.1  christos     int err;                            /* construct() return value */
    669  1.1  christos     short lengths[MAXCODES];            /* descriptor code lengths */
    670  1.1  christos     short lencnt[MAXBITS+1], lensym[MAXLCODES];         /* lencode memory */
    671  1.1  christos     short distcnt[MAXBITS+1], distsym[MAXDCODES];       /* distcode memory */
    672  1.1  christos     struct huffman lencode, distcode;   /* length and distance codes */
    673  1.1  christos     static const short order[19] =      /* permutation of code length codes */
    674  1.1  christos         {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
    675  1.1  christos 
    676  1.1  christos     /* construct lencode and distcode */
    677  1.1  christos     lencode.count = lencnt;
    678  1.1  christos     lencode.symbol = lensym;
    679  1.1  christos     distcode.count = distcnt;
    680  1.1  christos     distcode.symbol = distsym;
    681  1.1  christos 
    682  1.1  christos     /* get number of lengths in each table, check lengths */
    683  1.1  christos     nlen = bits(s, 5) + 257;
    684  1.1  christos     ndist = bits(s, 5) + 1;
    685  1.1  christos     ncode = bits(s, 4) + 4;
    686  1.1  christos     if (nlen > MAXLCODES || ndist > MAXDCODES)
    687  1.1  christos         return -3;                      /* bad counts */
    688  1.1  christos 
    689  1.1  christos     /* read code length code lengths (really), missing lengths are zero */
    690  1.1  christos     for (index = 0; index < ncode; index++)
    691  1.1  christos         lengths[order[index]] = bits(s, 3);
    692  1.1  christos     for (; index < 19; index++)
    693  1.1  christos         lengths[order[index]] = 0;
    694  1.1  christos 
    695  1.1  christos     /* build huffman table for code lengths codes (use lencode temporarily) */
    696  1.1  christos     err = construct(&lencode, lengths, 19);
    697  1.1  christos     if (err != 0)               /* require complete code set here */
    698  1.1  christos         return -4;
    699  1.1  christos 
    700  1.1  christos     /* read length/literal and distance code length tables */
    701  1.1  christos     index = 0;
    702  1.1  christos     while (index < nlen + ndist) {
    703  1.1  christos         int symbol;             /* decoded value */
    704  1.1  christos         int len;                /* last length to repeat */
    705  1.1  christos 
    706  1.1  christos         symbol = decode(s, &lencode);
    707  1.1  christos         if (symbol < 16)                /* length in 0..15 */
    708  1.1  christos             lengths[index++] = symbol;
    709  1.1  christos         else {                          /* repeat instruction */
    710  1.1  christos             len = 0;                    /* assume repeating zeros */
    711  1.1  christos             if (symbol == 16) {         /* repeat last length 3..6 times */
    712  1.1  christos                 if (index == 0)
    713  1.1  christos                     return -5;          /* no last length! */
    714  1.1  christos                 len = lengths[index - 1];       /* last length */
    715  1.1  christos                 symbol = 3 + bits(s, 2);
    716  1.1  christos             }
    717  1.1  christos             else if (symbol == 17)      /* repeat zero 3..10 times */
    718  1.1  christos                 symbol = 3 + bits(s, 3);
    719  1.1  christos             else                        /* == 18, repeat zero 11..138 times */
    720  1.1  christos                 symbol = 11 + bits(s, 7);
    721  1.1  christos             if (index + symbol > nlen + ndist)
    722  1.1  christos                 return -6;              /* too many lengths! */
    723  1.1  christos             while (symbol--)            /* repeat last or zero symbol times */
    724  1.1  christos                 lengths[index++] = len;
    725  1.1  christos         }
    726  1.1  christos     }
    727  1.1  christos 
    728  1.1  christos     /* check for end-of-block code -- there better be one! */
    729  1.1  christos     if (lengths[256] == 0)
    730  1.1  christos         return -9;
    731  1.1  christos 
    732  1.1  christos     /* build huffman table for literal/length codes */
    733  1.1  christos     err = construct(&lencode, lengths, nlen);
    734  1.1  christos     if (err && (err < 0 || nlen != lencode.count[0] + lencode.count[1]))
    735  1.1  christos         return -7;      /* incomplete code ok only for single length 1 code */
    736  1.1  christos 
    737  1.1  christos     /* build huffman table for distance codes */
    738  1.1  christos     err = construct(&distcode, lengths + nlen, ndist);
    739  1.1  christos     if (err && (err < 0 || ndist != distcode.count[0] + distcode.count[1]))
    740  1.1  christos         return -8;      /* incomplete code ok only for single length 1 code */
    741  1.1  christos 
    742  1.1  christos     /* decode data until end-of-block code */
    743  1.1  christos     return codes(s, &lencode, &distcode);
    744  1.1  christos }
    745  1.1  christos 
    746  1.1  christos /*
    747  1.1  christos  * Inflate source to dest.  On return, destlen and sourcelen are updated to the
    748  1.1  christos  * size of the uncompressed data and the size of the deflate data respectively.
    749  1.1  christos  * On success, the return value of puff() is zero.  If there is an error in the
    750  1.1  christos  * source data, i.e. it is not in the deflate format, then a negative value is
    751  1.1  christos  * returned.  If there is not enough input available or there is not enough
    752  1.1  christos  * output space, then a positive error is returned.  In that case, destlen and
    753  1.1  christos  * sourcelen are not updated to facilitate retrying from the beginning with the
    754  1.1  christos  * provision of more input data or more output space.  In the case of invalid
    755  1.1  christos  * inflate data (a negative error), the dest and source pointers are updated to
    756  1.1  christos  * facilitate the debugging of deflators.
    757  1.1  christos  *
    758  1.1  christos  * puff() also has a mode to determine the size of the uncompressed output with
    759  1.1  christos  * no output written.  For this dest must be (unsigned char *)0.  In this case,
    760  1.1  christos  * the input value of *destlen is ignored, and on return *destlen is set to the
    761  1.1  christos  * size of the uncompressed output.
    762  1.1  christos  *
    763  1.1  christos  * The return codes are:
    764  1.1  christos  *
    765  1.1  christos  *   2:  available inflate data did not terminate
    766  1.1  christos  *   1:  output space exhausted before completing inflate
    767  1.1  christos  *   0:  successful inflate
    768  1.1  christos  *  -1:  invalid block type (type == 3)
    769  1.1  christos  *  -2:  stored block length did not match one's complement
    770  1.1  christos  *  -3:  dynamic block code description: too many length or distance codes
    771  1.1  christos  *  -4:  dynamic block code description: code lengths codes incomplete
    772  1.1  christos  *  -5:  dynamic block code description: repeat lengths with no first length
    773  1.1  christos  *  -6:  dynamic block code description: repeat more than specified lengths
    774  1.1  christos  *  -7:  dynamic block code description: invalid literal/length code lengths
    775  1.1  christos  *  -8:  dynamic block code description: invalid distance code lengths
    776  1.1  christos  *  -9:  dynamic block code description: missing end-of-block code
    777  1.1  christos  * -10:  invalid literal/length or distance code in fixed or dynamic block
    778  1.1  christos  * -11:  distance is too far back in fixed or dynamic block
    779  1.1  christos  *
    780  1.1  christos  * Format notes:
    781  1.1  christos  *
    782  1.1  christos  * - Three bits are read for each block to determine the kind of block and
    783  1.1  christos  *   whether or not it is the last block.  Then the block is decoded and the
    784  1.1  christos  *   process repeated if it was not the last block.
    785  1.1  christos  *
    786  1.1  christos  * - The leftover bits in the last byte of the deflate data after the last
    787  1.1  christos  *   block (if it was a fixed or dynamic block) are undefined and have no
    788  1.1  christos  *   expected values to check.
    789  1.1  christos  */
    790  1.1  christos int puff(unsigned char *dest,           /* pointer to destination pointer */
    791  1.1  christos          unsigned long *destlen,        /* amount of output space */
    792  1.1  christos          const unsigned char *source,   /* pointer to source data pointer */
    793  1.1  christos          unsigned long *sourcelen)      /* amount of input available */
    794  1.1  christos {
    795  1.1  christos     struct state s;             /* input/output state */
    796  1.1  christos     int last, type;             /* block information */
    797  1.1  christos     int err;                    /* return value */
    798  1.1  christos 
    799  1.1  christos     /* initialize output state */
    800  1.1  christos     s.out = dest;
    801  1.1  christos     s.outlen = *destlen;                /* ignored if dest is NIL */
    802  1.1  christos     s.outcnt = 0;
    803  1.1  christos 
    804  1.1  christos     /* initialize input state */
    805  1.1  christos     s.in = source;
    806  1.1  christos     s.inlen = *sourcelen;
    807  1.1  christos     s.incnt = 0;
    808  1.1  christos     s.bitbuf = 0;
    809  1.1  christos     s.bitcnt = 0;
    810  1.1  christos 
    811  1.1  christos     /* return if bits() or decode() tries to read past available input */
    812  1.1  christos     if (setjmp(s.env) != 0)             /* if came back here via longjmp() */
    813  1.1  christos         err = 2;                        /* then skip do-loop, return error */
    814  1.1  christos     else {
    815  1.1  christos         /* process blocks until last block or error */
    816  1.1  christos         do {
    817  1.1  christos             last = bits(&s, 1);         /* one if last block */
    818  1.1  christos             type = bits(&s, 2);         /* block type 0..3 */
    819  1.1  christos             err = type == 0 ?
    820  1.1  christos                     stored(&s) :
    821  1.1  christos                     (type == 1 ?
    822  1.1  christos                         fixed(&s) :
    823  1.1  christos                         (type == 2 ?
    824  1.1  christos                             dynamic(&s) :
    825  1.1  christos                             -1));       /* type == 3, invalid */
    826  1.1  christos             if (err != 0)
    827  1.1  christos                 break;                  /* return with error */
    828  1.1  christos         } while (!last);
    829  1.1  christos     }
    830  1.1  christos 
    831  1.1  christos     /* update the lengths and return */
    832  1.1  christos     if (err <= 0) {
    833  1.1  christos         *destlen = s.outcnt;
    834  1.1  christos         *sourcelen = s.incnt;
    835  1.1  christos     }
    836  1.1  christos     return err;
    837  1.1  christos }
    838