trees.c
Go to the documentation of this file.
00001 /* trees.c -- output deflated data using Huffman coding
00002  * Copyright (C) 1995-2005 Jean-loup Gailly
00003  * For conditions of distribution and use, see copyright notice in zlib.h
00004  */
00005 
00006 /*
00007  *  ALGORITHM
00008  *
00009  *      The "deflation" process uses several Huffman trees. The more
00010  *      common source values are represented by shorter bit sequences.
00011  *
00012  *      Each code tree is stored in a compressed form which is itself
00013  * a Huffman encoding of the lengths of all the code strings (in
00014  * ascending order by source values).  The actual code strings are
00015  * reconstructed from the lengths in the inflate process, as described
00016  * in the deflate specification.
00017  *
00018  *  REFERENCES
00019  *
00020  *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
00021  *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
00022  *
00023  *      Storer, James A.
00024  *          Data Compression:  Methods and Theory, pp. 49-50.
00025  *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
00026  *
00027  *      Sedgewick, R.
00028  *          Algorithms, p290.
00029  *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
00030  */
00031 
00032 /* @(#) $Id$ */
00033 
00034 /* #define GEN_TREES_H */
00035 
00036 #include "deflate.h"
00037 
00038 #ifdef DEBUG
00039 #  include <ctype.h>
00040 #endif
00041 
00042 /* ===========================================================================
00043  * Constants
00044  */
00045 
00046 #define MAX_BL_BITS 7
00047 /* Bit length codes must not exceed MAX_BL_BITS bits */
00048 
00049 #define END_BLOCK 256
00050 /* end of block literal code */
00051 
00052 #define REP_3_6      16
00053 /* repeat previous bit length 3-6 times (2 bits of repeat count) */
00054 
00055 #define REPZ_3_10    17
00056 /* repeat a zero length 3-10 times  (3 bits of repeat count) */
00057 
00058 #define REPZ_11_138  18
00059 /* repeat a zero length 11-138 times  (7 bits of repeat count) */
00060 
00061 local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
00062    = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
00063 
00064 local const int extra_dbits[D_CODES] /* extra bits for each distance code */
00065    = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
00066 
00067 local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
00068    = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
00069 
00070 local const uch bl_order[BL_CODES]
00071    = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
00072 /* The lengths of the bit length codes are sent in order of decreasing
00073  * probability, to avoid transmitting the lengths for unused bit length codes.
00074  */
00075 
00076 #define Buf_size (8 * 2*sizeof(char))
00077 /* Number of bits used within bi_buf. (bi_buf might be implemented on
00078  * more than 16 bits on some systems.)
00079  */
00080 
00081 /* ===========================================================================
00082  * Local data. These are initialized only once.
00083  */
00084 
00085 #define DIST_CODE_LEN  512 /* see definition of array dist_code below */
00086 
00087 #if defined(GEN_TREES_H) || !defined(STDC)
00088 /* non ANSI compilers may not accept trees.h */
00089 
00090 local ct_data static_ltree[L_CODES+2];
00091 /* The static literal tree. Since the bit lengths are imposed, there is no
00092  * need for the L_CODES extra codes used during heap construction. However
00093  * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
00094  * below).
00095  */
00096 
00097 local ct_data static_dtree[D_CODES];
00098 /* The static distance tree. (Actually a trivial tree since all codes use
00099  * 5 bits.)
00100  */
00101 
00102 uch _dist_code[DIST_CODE_LEN];
00103 /* Distance codes. The first 256 values correspond to the distances
00104  * 3 .. 258, the last 256 values correspond to the top 8 bits of
00105  * the 15 bit distances.
00106  */
00107 
00108 uch _length_code[MAX_MATCH-MIN_MATCH+1];
00109 /* length code for each normalized match length (0 == MIN_MATCH) */
00110 
00111 local int base_length[LENGTH_CODES];
00112 /* First normalized length for each code (0 = MIN_MATCH) */
00113 
00114 local int base_dist[D_CODES];
00115 /* First normalized distance for each code (0 = distance of 1) */
00116 
00117 #else
00118 #  include "trees.h"
00119 #endif /* GEN_TREES_H */
00120 
00121 struct static_tree_desc_s {
00122     const ct_data *static_tree;  /* static tree or NULL */
00123     const intf *extra_bits;      /* extra bits for each code or NULL */
00124     int     extra_base;          /* base index for extra_bits */
00125     int     elems;               /* max number of elements in the tree */
00126     int     max_length;          /* max bit length for the codes */
00127 };
00128 
00129 local static_tree_desc  static_l_desc =
00130 {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
00131 
00132 local static_tree_desc  static_d_desc =
00133 {static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
00134 
00135 local static_tree_desc  static_bl_desc =
00136 {(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
00137 
00138 /* ===========================================================================
00139  * Local (static) routines in this file.
00140  */
00141 
00142 local void tr_static_init OF((void));
00143 local void init_block     OF((deflate_state *s));
00144 local void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));
00145 local void gen_bitlen     OF((deflate_state *s, tree_desc *desc));
00146 local void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));
00147 local void build_tree     OF((deflate_state *s, tree_desc *desc));
00148 local void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));
00149 local void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));
00150 local int  build_bl_tree  OF((deflate_state *s));
00151 local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
00152                               int blcodes));
00153 local void compress_block OF((deflate_state *s, ct_data *ltree,
00154                               ct_data *dtree));
00155 local void set_data_type  OF((deflate_state *s));
00156 local unsigned bi_reverse OF((unsigned value, int length));
00157 local void bi_windup      OF((deflate_state *s));
00158 local void bi_flush       OF((deflate_state *s));
00159 local void copy_block     OF((deflate_state *s, charf *buf, unsigned len,
00160                               int header));
00161 
00162 #ifdef GEN_TREES_H
00163 local void gen_trees_header OF((void));
00164 #endif
00165 
00166 #ifndef DEBUG
00167 #  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
00168    /* Send a code of the given tree. c and tree must not have side effects */
00169 
00170 #else /* DEBUG */
00171 #  define send_code(s, c, tree) \
00172      { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
00173        send_bits(s, tree[c].Code, tree[c].Len); }
00174 #endif
00175 
00176 /* ===========================================================================
00177  * Output a short LSB first on the stream.
00178  * IN assertion: there is enough room in pendingBuf.
00179  */
00180 #define put_short(s, w) { \
00181     put_byte(s, (uch)((w) & 0xff)); \
00182     put_byte(s, (uch)((ush)(w) >> 8)); \
00183 }
00184 
00185 /* ===========================================================================
00186  * Send a value on a given number of bits.
00187  * IN assertion: length <= 16 and value fits in length bits.
00188  */
00189 #ifdef DEBUG
00190 local void send_bits      OF((deflate_state *s, int value, int length));
00191 
00192 local void send_bits(s, value, length)
00193     deflate_state *s;
00194     int value;  /* value to send */
00195     int length; /* number of bits */
00196 {
00197     Tracevv((stderr," l %2d v %4x ", length, value));
00198     Assert(length > 0 && length <= 15, "invalid length");
00199     s->bits_sent += (ulg)length;
00200 
00201     /* If not enough room in bi_buf, use (valid) bits from bi_buf and
00202      * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
00203      * unused bits in value.
00204      */
00205     if (s->bi_valid > (int)Buf_size - length) {
00206         s->bi_buf |= (value << s->bi_valid);
00207         put_short(s, s->bi_buf);
00208         s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
00209         s->bi_valid += length - Buf_size;
00210     } else {
00211         s->bi_buf |= value << s->bi_valid;
00212         s->bi_valid += length;
00213     }
00214 }
00215 #else /* !DEBUG */
00216 
00217 #define send_bits(s, value, length) \
00218 { int len = length;\
00219   if (s->bi_valid > (int)Buf_size - len) {\
00220     int val = value;\
00221     s->bi_buf |= (val << s->bi_valid);\
00222     put_short(s, s->bi_buf);\
00223     s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
00224     s->bi_valid += len - Buf_size;\
00225   } else {\
00226     s->bi_buf |= (value) << s->bi_valid;\
00227     s->bi_valid += len;\
00228   }\
00229 }
00230 #endif /* DEBUG */
00231 
00232 
00233 /* the arguments must not have side effects */
00234 
00235 /* ===========================================================================
00236  * Initialize the various 'constant' tables.
00237  */
00238 local void tr_static_init()
00239 {
00240 #if defined(GEN_TREES_H) || !defined(STDC)
00241     static int static_init_done = 0;
00242     int n;        /* iterates over tree elements */
00243     int bits;     /* bit counter */
00244     int length;   /* length value */
00245     int code;     /* code value */
00246     int dist;     /* distance index */
00247     ush bl_count[MAX_BITS+1];
00248     /* number of codes at each bit length for an optimal tree */
00249 
00250     if (static_init_done) return;
00251 
00252     /* For some embedded targets, global variables are not initialized: */
00253     static_l_desc.static_tree = static_ltree;
00254     static_l_desc.extra_bits = extra_lbits;
00255     static_d_desc.static_tree = static_dtree;
00256     static_d_desc.extra_bits = extra_dbits;
00257     static_bl_desc.extra_bits = extra_blbits;
00258 
00259     /* Initialize the mapping length (0..255) -> length code (0..28) */
00260     length = 0;
00261     for (code = 0; code < LENGTH_CODES-1; code++) {
00262         base_length[code] = length;
00263         for (n = 0; n < (1<<extra_lbits[code]); n++) {
00264             _length_code[length++] = (uch)code;
00265         }
00266     }
00267     Assert (length == 256, "tr_static_init: length != 256");
00268     /* Note that the length 255 (match length 258) can be represented
00269      * in two different ways: code 284 + 5 bits or code 285, so we
00270      * overwrite length_code[255] to use the best encoding:
00271      */
00272     _length_code[length-1] = (uch)code;
00273 
00274     /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
00275     dist = 0;
00276     for (code = 0 ; code < 16; code++) {
00277         base_dist[code] = dist;
00278         for (n = 0; n < (1<<extra_dbits[code]); n++) {
00279             _dist_code[dist++] = (uch)code;
00280         }
00281     }
00282     Assert (dist == 256, "tr_static_init: dist != 256");
00283     dist >>= 7; /* from now on, all distances are divided by 128 */
00284     for ( ; code < D_CODES; code++) {
00285         base_dist[code] = dist << 7;
00286         for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
00287             _dist_code[256 + dist++] = (uch)code;
00288         }
00289     }
00290     Assert (dist == 256, "tr_static_init: 256+dist != 512");
00291 
00292     /* Construct the codes of the static literal tree */
00293     for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
00294     n = 0;
00295     while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
00296     while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
00297     while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
00298     while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
00299     /* Codes 286 and 287 do not exist, but we must include them in the
00300      * tree construction to get a canonical Huffman tree (longest code
00301      * all ones)
00302      */
00303     gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
00304 
00305     /* The static distance tree is trivial: */
00306     for (n = 0; n < D_CODES; n++) {
00307         static_dtree[n].Len = 5;
00308         static_dtree[n].Code = bi_reverse((unsigned)n, 5);
00309     }
00310     static_init_done = 1;
00311 
00312 #  ifdef GEN_TREES_H
00313     gen_trees_header();
00314 #  endif
00315 #endif /* defined(GEN_TREES_H) || !defined(STDC) */
00316 }
00317 
00318 /* ===========================================================================
00319  * Genererate the file trees.h describing the static trees.
00320  */
00321 #ifdef GEN_TREES_H
00322 #  ifndef DEBUG
00323 #    include <stdio.h>
00324 #  endif
00325 
00326 #  define SEPARATOR(i, last, width) \
00327       ((i) == (last)? "\n};\n\n" :    \
00328        ((i) % (width) == (width)-1 ? ",\n" : ", "))
00329 
00330 void gen_trees_header()
00331 {
00332     FILE *header = fopen("trees.h", "w");
00333     int i;
00334 
00335     Assert (header != NULL, "Can't open trees.h");
00336     fprintf(header,
00337             "/* header created automatically with -DGEN_TREES_H */\n\n");
00338 
00339     fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
00340     for (i = 0; i < L_CODES+2; i++) {
00341         fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
00342                 static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
00343     }
00344 
00345     fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
00346     for (i = 0; i < D_CODES; i++) {
00347         fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
00348                 static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
00349     }
00350 
00351     fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
00352     for (i = 0; i < DIST_CODE_LEN; i++) {
00353         fprintf(header, "%2u%s", _dist_code[i],
00354                 SEPARATOR(i, DIST_CODE_LEN-1, 20));
00355     }
00356 
00357     fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
00358     for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
00359         fprintf(header, "%2u%s", _length_code[i],
00360                 SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
00361     }
00362 
00363     fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
00364     for (i = 0; i < LENGTH_CODES; i++) {
00365         fprintf(header, "%1u%s", base_length[i],
00366                 SEPARATOR(i, LENGTH_CODES-1, 20));
00367     }
00368 
00369     fprintf(header, "local const int base_dist[D_CODES] = {\n");
00370     for (i = 0; i < D_CODES; i++) {
00371         fprintf(header, "%5u%s", base_dist[i],
00372                 SEPARATOR(i, D_CODES-1, 10));
00373     }
00374 
00375     fclose(header);
00376 }
00377 #endif /* GEN_TREES_H */
00378 
00379 /* ===========================================================================
00380  * Initialize the tree data structures for a new zlib stream.
00381  */
00382 void _tr_init(s)
00383     deflate_state *s;
00384 {
00385     tr_static_init();
00386 
00387     s->l_desc.dyn_tree = s->dyn_ltree;
00388     s->l_desc.stat_desc = &static_l_desc;
00389 
00390     s->d_desc.dyn_tree = s->dyn_dtree;
00391     s->d_desc.stat_desc = &static_d_desc;
00392 
00393     s->bl_desc.dyn_tree = s->bl_tree;
00394     s->bl_desc.stat_desc = &static_bl_desc;
00395 
00396     s->bi_buf = 0;
00397     s->bi_valid = 0;
00398     s->last_eob_len = 8; /* enough lookahead for inflate */
00399 #ifdef DEBUG
00400     s->compressed_len = 0L;
00401     s->bits_sent = 0L;
00402 #endif
00403 
00404     /* Initialize the first block of the first file: */
00405     init_block(s);
00406 }
00407 
00408 /* ===========================================================================
00409  * Initialize a new block.
00410  */
00411 local void init_block(s)
00412     deflate_state *s;
00413 {
00414     int n; /* iterates over tree elements */
00415 
00416     /* Initialize the trees. */
00417     for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
00418     for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
00419     for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
00420 
00421     s->dyn_ltree[END_BLOCK].Freq = 1;
00422     s->opt_len = s->static_len = 0L;
00423     s->last_lit = s->matches = 0;
00424 }
00425 
00426 #define SMALLEST 1
00427 /* Index within the heap array of least frequent node in the Huffman tree */
00428 
00429 
00430 /* ===========================================================================
00431  * Remove the smallest element from the heap and recreate the heap with
00432  * one less element. Updates heap and heap_len.
00433  */
00434 #define pqremove(s, tree, top) \
00435 {\
00436     top = s->heap[SMALLEST]; \
00437     s->heap[SMALLEST] = s->heap[s->heap_len--]; \
00438     pqdownheap(s, tree, SMALLEST); \
00439 }
00440 
00441 /* ===========================================================================
00442  * Compares to subtrees, using the tree depth as tie breaker when
00443  * the subtrees have equal frequency. This minimizes the worst case length.
00444  */
00445 #define smaller(tree, n, m, depth) \
00446    (tree[n].Freq < tree[m].Freq || \
00447    (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
00448 
00449 /* ===========================================================================
00450  * Restore the heap property by moving down the tree starting at node k,
00451  * exchanging a node with the smallest of its two sons if necessary, stopping
00452  * when the heap property is re-established (each father smaller than its
00453  * two sons).
00454  */
00455 local void pqdownheap(s, tree, k)
00456     deflate_state *s;
00457     ct_data *tree;  /* the tree to restore */
00458     int k;               /* node to move down */
00459 {
00460     int v = s->heap[k];
00461     int j = k << 1;  /* left son of k */
00462     while (j <= s->heap_len) {
00463         /* Set j to the smallest of the two sons: */
00464         if (j < s->heap_len &&
00465             smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
00466             j++;
00467         }
00468         /* Exit if v is smaller than both sons */
00469         if (smaller(tree, v, s->heap[j], s->depth)) break;
00470 
00471         /* Exchange v with the smallest son */
00472         s->heap[k] = s->heap[j];  k = j;
00473 
00474         /* And continue down the tree, setting j to the left son of k */
00475         j <<= 1;
00476     }
00477     s->heap[k] = v;
00478 }
00479 
00480 /* ===========================================================================
00481  * Compute the optimal bit lengths for a tree and update the total bit length
00482  * for the current block.
00483  * IN assertion: the fields freq and dad are set, heap[heap_max] and
00484  *    above are the tree nodes sorted by increasing frequency.
00485  * OUT assertions: the field len is set to the optimal bit length, the
00486  *     array bl_count contains the frequencies for each bit length.
00487  *     The length opt_len is updated; static_len is also updated if stree is
00488  *     not null.
00489  */
00490 local void gen_bitlen(s, desc)
00491     deflate_state *s;
00492     tree_desc *desc;    /* the tree descriptor */
00493 {
00494     ct_data *tree        = desc->dyn_tree;
00495     int max_code         = desc->max_code;
00496     const ct_data *stree = desc->stat_desc->static_tree;
00497     const intf *extra    = desc->stat_desc->extra_bits;
00498     int base             = desc->stat_desc->extra_base;
00499     int max_length       = desc->stat_desc->max_length;
00500     int h;              /* heap index */
00501     int n, m;           /* iterate over the tree elements */
00502     int bits;           /* bit length */
00503     int xbits;          /* extra bits */
00504     ush f;              /* frequency */
00505     int overflow = 0;   /* number of elements with bit length too large */
00506 
00507     for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
00508 
00509     /* In a first pass, compute the optimal bit lengths (which may
00510      * overflow in the case of the bit length tree).
00511      */
00512     tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
00513 
00514     for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
00515         n = s->heap[h];
00516         bits = tree[tree[n].Dad].Len + 1;
00517         if (bits > max_length) bits = max_length, overflow++;
00518         tree[n].Len = (ush)bits;
00519         /* We overwrite tree[n].Dad which is no longer needed */
00520 
00521         if (n > max_code) continue; /* not a leaf node */
00522 
00523         s->bl_count[bits]++;
00524         xbits = 0;
00525         if (n >= base) xbits = extra[n-base];
00526         f = tree[n].Freq;
00527         s->opt_len += (ulg)f * (bits + xbits);
00528         if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
00529     }
00530     if (overflow == 0) return;
00531 
00532     Trace((stderr,"\nbit length overflow\n"));
00533     /* This happens for example on obj2 and pic of the Calgary corpus */
00534 
00535     /* Find the first bit length which could increase: */
00536     do {
00537         bits = max_length-1;
00538         while (s->bl_count[bits] == 0) bits--;
00539         s->bl_count[bits]--;      /* move one leaf down the tree */
00540         s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
00541         s->bl_count[max_length]--;
00542         /* The brother of the overflow item also moves one step up,
00543          * but this does not affect bl_count[max_length]
00544          */
00545         overflow -= 2;
00546     } while (overflow > 0);
00547 
00548     /* Now recompute all bit lengths, scanning in increasing frequency.
00549      * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
00550      * lengths instead of fixing only the wrong ones. This idea is taken
00551      * from 'ar' written by Haruhiko Okumura.)
00552      */
00553     for (bits = max_length; bits != 0; bits--) {
00554         n = s->bl_count[bits];
00555         while (n != 0) {
00556             m = s->heap[--h];
00557             if (m > max_code) continue;
00558             if ((unsigned) tree[m].Len != (unsigned) bits) {
00559                 Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
00560                 s->opt_len += ((long)bits - (long)tree[m].Len)
00561                               *(long)tree[m].Freq;
00562                 tree[m].Len = (ush)bits;
00563             }
00564             n--;
00565         }
00566     }
00567 }
00568 
00569 /* ===========================================================================
00570  * Generate the codes for a given tree and bit counts (which need not be
00571  * optimal).
00572  * IN assertion: the array bl_count contains the bit length statistics for
00573  * the given tree and the field len is set for all tree elements.
00574  * OUT assertion: the field code is set for all tree elements of non
00575  *     zero code length.
00576  */
00577 local void gen_codes (tree, max_code, bl_count)
00578     ct_data *tree;             /* the tree to decorate */
00579     int max_code;              /* largest code with non zero frequency */
00580     ushf *bl_count;            /* number of codes at each bit length */
00581 {
00582     ush next_code[MAX_BITS+1]; /* next code value for each bit length */
00583     ush code = 0;              /* running code value */
00584     int bits;                  /* bit index */
00585     int n;                     /* code index */
00586 
00587     /* The distribution counts are first used to generate the code values
00588      * without bit reversal.
00589      */
00590     for (bits = 1; bits <= MAX_BITS; bits++) {
00591         next_code[bits] = code = (code + bl_count[bits-1]) << 1;
00592     }
00593     /* Check that the bit counts in bl_count are consistent. The last code
00594      * must be all ones.
00595      */
00596     Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
00597             "inconsistent bit counts");
00598     Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
00599 
00600     for (n = 0;  n <= max_code; n++) {
00601         int len = tree[n].Len;
00602         if (len == 0) continue;
00603         /* Now reverse the bits */
00604         tree[n].Code = bi_reverse(next_code[len]++, len);
00605 
00606         Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
00607              n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
00608     }
00609 }
00610 
00611 /* ===========================================================================
00612  * Construct one Huffman tree and assigns the code bit strings and lengths.
00613  * Update the total bit length for the current block.
00614  * IN assertion: the field freq is set for all tree elements.
00615  * OUT assertions: the fields len and code are set to the optimal bit length
00616  *     and corresponding code. The length opt_len is updated; static_len is
00617  *     also updated if stree is not null. The field max_code is set.
00618  */
00619 local void build_tree(s, desc)
00620     deflate_state *s;
00621     tree_desc *desc; /* the tree descriptor */
00622 {
00623     ct_data *tree         = desc->dyn_tree;
00624     const ct_data *stree  = desc->stat_desc->static_tree;
00625     int elems             = desc->stat_desc->elems;
00626     int n, m;          /* iterate over heap elements */
00627     int max_code = -1; /* largest code with non zero frequency */
00628     int node;          /* new node being created */
00629 
00630     /* Construct the initial heap, with least frequent element in
00631      * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
00632      * heap[0] is not used.
00633      */
00634     s->heap_len = 0, s->heap_max = HEAP_SIZE;
00635 
00636     for (n = 0; n < elems; n++) {
00637         if (tree[n].Freq != 0) {
00638             s->heap[++(s->heap_len)] = max_code = n;
00639             s->depth[n] = 0;
00640         } else {
00641             tree[n].Len = 0;
00642         }
00643     }
00644 
00645     /* The pkzip format requires that at least one distance code exists,
00646      * and that at least one bit should be sent even if there is only one
00647      * possible code. So to avoid special checks later on we force at least
00648      * two codes of non zero frequency.
00649      */
00650     while (s->heap_len < 2) {
00651         node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
00652         tree[node].Freq = 1;
00653         s->depth[node] = 0;
00654         s->opt_len--; if (stree) s->static_len -= stree[node].Len;
00655         /* node is 0 or 1 so it does not have extra bits */
00656     }
00657     desc->max_code = max_code;
00658 
00659     /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
00660      * establish sub-heaps of increasing lengths:
00661      */
00662     for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
00663 
00664     /* Construct the Huffman tree by repeatedly combining the least two
00665      * frequent nodes.
00666      */
00667     node = elems;              /* next internal node of the tree */
00668     do {
00669         pqremove(s, tree, n);  /* n = node of least frequency */
00670         m = s->heap[SMALLEST]; /* m = node of next least frequency */
00671 
00672         s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
00673         s->heap[--(s->heap_max)] = m;
00674 
00675         /* Create a new node father of n and m */
00676         tree[node].Freq = tree[n].Freq + tree[m].Freq;
00677         s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
00678                                 s->depth[n] : s->depth[m]) + 1);
00679         tree[n].Dad = tree[m].Dad = (ush)node;
00680 #ifdef DUMP_BL_TREE
00681         if (tree == s->bl_tree) {
00682             fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
00683                     node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
00684         }
00685 #endif
00686         /* and insert the new node in the heap */
00687         s->heap[SMALLEST] = node++;
00688         pqdownheap(s, tree, SMALLEST);
00689 
00690     } while (s->heap_len >= 2);
00691 
00692     s->heap[--(s->heap_max)] = s->heap[SMALLEST];
00693 
00694     /* At this point, the fields freq and dad are set. We can now
00695      * generate the bit lengths.
00696      */
00697     gen_bitlen(s, (tree_desc *)desc);
00698 
00699     /* The field len is now set, we can generate the bit codes */
00700     gen_codes ((ct_data *)tree, max_code, s->bl_count);
00701 }
00702 
00703 /* ===========================================================================
00704  * Scan a literal or distance tree to determine the frequencies of the codes
00705  * in the bit length tree.
00706  */
00707 local void scan_tree (s, tree, max_code)
00708     deflate_state *s;
00709     ct_data *tree;   /* the tree to be scanned */
00710     int max_code;    /* and its largest code of non zero frequency */
00711 {
00712     int n;                     /* iterates over all tree elements */
00713     int prevlen = -1;          /* last emitted length */
00714     int curlen;                /* length of current code */
00715     int nextlen = tree[0].Len; /* length of next code */
00716     int count = 0;             /* repeat count of the current code */
00717     int max_count = 7;         /* max repeat count */
00718     int min_count = 4;         /* min repeat count */
00719 
00720     if (nextlen == 0) max_count = 138, min_count = 3;
00721     tree[max_code+1].Len = (ush)0xffff; /* guard */
00722 
00723     for (n = 0; n <= max_code; n++) {
00724         curlen = nextlen; nextlen = tree[n+1].Len;
00725         if (++count < max_count && curlen == nextlen) {
00726             continue;
00727         } else if (count < min_count) {
00728             s->bl_tree[curlen].Freq += count;
00729         } else if (curlen != 0) {
00730             if (curlen != prevlen) s->bl_tree[curlen].Freq++;
00731             s->bl_tree[REP_3_6].Freq++;
00732         } else if (count <= 10) {
00733             s->bl_tree[REPZ_3_10].Freq++;
00734         } else {
00735             s->bl_tree[REPZ_11_138].Freq++;
00736         }
00737         count = 0; prevlen = curlen;
00738         if (nextlen == 0) {
00739             max_count = 138, min_count = 3;
00740         } else if (curlen == nextlen) {
00741             max_count = 6, min_count = 3;
00742         } else {
00743             max_count = 7, min_count = 4;
00744         }
00745     }
00746 }
00747 
00748 /* ===========================================================================
00749  * Send a literal or distance tree in compressed form, using the codes in
00750  * bl_tree.
00751  */
00752 local void send_tree (s, tree, max_code)
00753     deflate_state *s;
00754     ct_data *tree; /* the tree to be scanned */
00755     int max_code;       /* and its largest code of non zero frequency */
00756 {
00757     int n;                     /* iterates over all tree elements */
00758     int prevlen = -1;          /* last emitted length */
00759     int curlen;                /* length of current code */
00760     int nextlen = tree[0].Len; /* length of next code */
00761     int count = 0;             /* repeat count of the current code */
00762     int max_count = 7;         /* max repeat count */
00763     int min_count = 4;         /* min repeat count */
00764 
00765     /* tree[max_code+1].Len = -1; */  /* guard already set */
00766     if (nextlen == 0) max_count = 138, min_count = 3;
00767 
00768     for (n = 0; n <= max_code; n++) {
00769         curlen = nextlen; nextlen = tree[n+1].Len;
00770         if (++count < max_count && curlen == nextlen) {
00771             continue;
00772         } else if (count < min_count) {
00773             do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
00774 
00775         } else if (curlen != 0) {
00776             if (curlen != prevlen) {
00777                 send_code(s, curlen, s->bl_tree); count--;
00778             }
00779             Assert(count >= 3 && count <= 6, " 3_6?");
00780             send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
00781 
00782         } else if (count <= 10) {
00783             send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
00784 
00785         } else {
00786             send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
00787         }
00788         count = 0; prevlen = curlen;
00789         if (nextlen == 0) {
00790             max_count = 138, min_count = 3;
00791         } else if (curlen == nextlen) {
00792             max_count = 6, min_count = 3;
00793         } else {
00794             max_count = 7, min_count = 4;
00795         }
00796     }
00797 }
00798 
00799 /* ===========================================================================
00800  * Construct the Huffman tree for the bit lengths and return the index in
00801  * bl_order of the last bit length code to send.
00802  */
00803 local int build_bl_tree(s)
00804     deflate_state *s;
00805 {
00806     int max_blindex;  /* index of last bit length code of non zero freq */
00807 
00808     /* Determine the bit length frequencies for literal and distance trees */
00809     scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
00810     scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
00811 
00812     /* Build the bit length tree: */
00813     build_tree(s, (tree_desc *)(&(s->bl_desc)));
00814     /* opt_len now includes the length of the tree representations, except
00815      * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
00816      */
00817 
00818     /* Determine the number of bit length codes to send. The pkzip format
00819      * requires that at least 4 bit length codes be sent. (appnote.txt says
00820      * 3 but the actual value used is 4.)
00821      */
00822     for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
00823         if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
00824     }
00825     /* Update opt_len to include the bit length tree and counts */
00826     s->opt_len += 3*(max_blindex+1) + 5+5+4;
00827     Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
00828             s->opt_len, s->static_len));
00829 
00830     return max_blindex;
00831 }
00832 
00833 /* ===========================================================================
00834  * Send the header for a block using dynamic Huffman trees: the counts, the
00835  * lengths of the bit length codes, the literal tree and the distance tree.
00836  * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
00837  */
00838 local void send_all_trees(s, lcodes, dcodes, blcodes)
00839     deflate_state *s;
00840     int lcodes, dcodes, blcodes; /* number of codes for each tree */
00841 {
00842     int rank;                    /* index in bl_order */
00843 
00844     Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
00845     Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
00846             "too many codes");
00847     Tracev((stderr, "\nbl counts: "));
00848     send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
00849     send_bits(s, dcodes-1,   5);
00850     send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
00851     for (rank = 0; rank < blcodes; rank++) {
00852         Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
00853         send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
00854     }
00855     Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
00856 
00857     send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
00858     Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
00859 
00860     send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
00861     Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
00862 }
00863 
00864 /* ===========================================================================
00865  * Send a stored block
00866  */
00867 void _tr_stored_block(s, buf, stored_len, eof)
00868     deflate_state *s;
00869     charf *buf;       /* input block */
00870     ulg stored_len;   /* length of input block */
00871     int eof;          /* true if this is the last block for a file */
00872 {
00873     send_bits(s, (STORED_BLOCK<<1)+eof, 3);  /* send block type */
00874 #ifdef DEBUG
00875     s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
00876     s->compressed_len += (stored_len + 4) << 3;
00877 #endif
00878     copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
00879 }
00880 
00881 /* ===========================================================================
00882  * Send one empty static block to give enough lookahead for inflate.
00883  * This takes 10 bits, of which 7 may remain in the bit buffer.
00884  * The current inflate code requires 9 bits of lookahead. If the
00885  * last two codes for the previous block (real code plus EOB) were coded
00886  * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
00887  * the last real code. In this case we send two empty static blocks instead
00888  * of one. (There are no problems if the previous block is stored or fixed.)
00889  * To simplify the code, we assume the worst case of last real code encoded
00890  * on one bit only.
00891  */
00892 void _tr_align(s)
00893     deflate_state *s;
00894 {
00895     send_bits(s, STATIC_TREES<<1, 3);
00896     send_code(s, END_BLOCK, static_ltree);
00897 #ifdef DEBUG
00898     s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
00899 #endif
00900     bi_flush(s);
00901     /* Of the 10 bits for the empty block, we have already sent
00902      * (10 - bi_valid) bits. The lookahead for the last real code (before
00903      * the EOB of the previous block) was thus at least one plus the length
00904      * of the EOB plus what we have just sent of the empty static block.
00905      */
00906     if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
00907         send_bits(s, STATIC_TREES<<1, 3);
00908         send_code(s, END_BLOCK, static_ltree);
00909 #ifdef DEBUG
00910         s->compressed_len += 10L;
00911 #endif
00912         bi_flush(s);
00913     }
00914     s->last_eob_len = 7;
00915 }
00916 
00917 /* ===========================================================================
00918  * Determine the best encoding for the current block: dynamic trees, static
00919  * trees or store, and output the encoded block to the zip file.
00920  */
00921 void _tr_flush_block(s, buf, stored_len, eof)
00922     deflate_state *s;
00923     charf *buf;       /* input block, or NULL if too old */
00924     ulg stored_len;   /* length of input block */
00925     int eof;          /* true if this is the last block for a file */
00926 {
00927     ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
00928     int max_blindex = 0;  /* index of last bit length code of non zero freq */
00929 
00930     /* Build the Huffman trees unless a stored block is forced */
00931     if (s->level > 0) {
00932 
00933         /* Check if the file is binary or text */
00934         if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
00935             set_data_type(s);
00936 
00937         /* Construct the literal and distance trees */
00938         build_tree(s, (tree_desc *)(&(s->l_desc)));
00939         Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
00940                 s->static_len));
00941 
00942         build_tree(s, (tree_desc *)(&(s->d_desc)));
00943         Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
00944                 s->static_len));
00945         /* At this point, opt_len and static_len are the total bit lengths of
00946          * the compressed block data, excluding the tree representations.
00947          */
00948 
00949         /* Build the bit length tree for the above two trees, and get the index
00950          * in bl_order of the last bit length code to send.
00951          */
00952         max_blindex = build_bl_tree(s);
00953 
00954         /* Determine the best encoding. Compute the block lengths in bytes. */
00955         opt_lenb = (s->opt_len+3+7)>>3;
00956         static_lenb = (s->static_len+3+7)>>3;
00957 
00958         Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
00959                 opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
00960                 s->last_lit));
00961 
00962         if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
00963 
00964     } else {
00965         Assert(buf != (char*)0, "lost buf");
00966         opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
00967     }
00968 
00969 #ifdef FORCE_STORED
00970     if (buf != (char*)0) { /* force stored block */
00971 #else
00972     if (stored_len+4 <= opt_lenb && buf != (char*)0) {
00973                        /* 4: two words for the lengths */
00974 #endif
00975         /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
00976          * Otherwise we can't have processed more than WSIZE input bytes since
00977          * the last block flush, because compression would have been
00978          * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
00979          * transform a block into a stored block.
00980          */
00981         _tr_stored_block(s, buf, stored_len, eof);
00982 
00983 #ifdef FORCE_STATIC
00984     } else if (static_lenb >= 0) { /* force static trees */
00985 #else
00986     } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
00987 #endif
00988         send_bits(s, (STATIC_TREES<<1)+eof, 3);
00989         compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
00990 #ifdef DEBUG
00991         s->compressed_len += 3 + s->static_len;
00992 #endif
00993     } else {
00994         send_bits(s, (DYN_TREES<<1)+eof, 3);
00995         send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
00996                        max_blindex+1);
00997         compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
00998 #ifdef DEBUG
00999         s->compressed_len += 3 + s->opt_len;
01000 #endif
01001     }
01002     Assert (s->compressed_len == s->bits_sent, "bad compressed size");
01003     /* The above check is made mod 2^32, for files larger than 512 MB
01004      * and uLong implemented on 32 bits.
01005      */
01006     init_block(s);
01007 
01008     if (eof) {
01009         bi_windup(s);
01010 #ifdef DEBUG
01011         s->compressed_len += 7;  /* align on byte boundary */
01012 #endif
01013     }
01014     Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
01015            s->compressed_len-7*eof));
01016 }
01017 
01018 /* ===========================================================================
01019  * Save the match info and tally the frequency counts. Return true if
01020  * the current block must be flushed.
01021  */
01022 int _tr_tally (s, dist, lc)
01023     deflate_state *s;
01024     unsigned dist;  /* distance of matched string */
01025     unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
01026 {
01027     s->d_buf[s->last_lit] = (ush)dist;
01028     s->l_buf[s->last_lit++] = (uch)lc;
01029     if (dist == 0) {
01030         /* lc is the unmatched char */
01031         s->dyn_ltree[lc].Freq++;
01032     } else {
01033         s->matches++;
01034         /* Here, lc is the match length - MIN_MATCH */
01035         dist--;             /* dist = match distance - 1 */
01036         Assert((ush)dist < (ush)MAX_DIST(s) &&
01037                (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
01038                (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
01039 
01040         s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
01041         s->dyn_dtree[d_code(dist)].Freq++;
01042     }
01043 
01044 #ifdef TRUNCATE_BLOCK
01045     /* Try to guess if it is profitable to stop the current block here */
01046     if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
01047         /* Compute an upper bound for the compressed length */
01048         ulg out_length = (ulg)s->last_lit*8L;
01049         ulg in_length = (ulg)((long)s->strstart - s->block_start);
01050         int dcode;
01051         for (dcode = 0; dcode < D_CODES; dcode++) {
01052             out_length += (ulg)s->dyn_dtree[dcode].Freq *
01053                 (5L+extra_dbits[dcode]);
01054         }
01055         out_length >>= 3;
01056         Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
01057                s->last_lit, in_length, out_length,
01058                100L - out_length*100L/in_length));
01059         if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
01060     }
01061 #endif
01062     return (s->last_lit == s->lit_bufsize-1);
01063     /* We avoid equality with lit_bufsize because of wraparound at 64K
01064      * on 16 bit machines and because stored blocks are restricted to
01065      * 64K-1 bytes.
01066      */
01067 }
01068 
01069 /* ===========================================================================
01070  * Send the block data compressed using the given Huffman trees
01071  */
01072 local void compress_block(s, ltree, dtree)
01073     deflate_state *s;
01074     ct_data *ltree; /* literal tree */
01075     ct_data *dtree; /* distance tree */
01076 {
01077     unsigned dist;      /* distance of matched string */
01078     int lc;             /* match length or unmatched char (if dist == 0) */
01079     unsigned lx = 0;    /* running index in l_buf */
01080     unsigned code;      /* the code to send */
01081     int extra;          /* number of extra bits to send */
01082 
01083     if (s->last_lit != 0) do {
01084         dist = s->d_buf[lx];
01085         lc = s->l_buf[lx++];
01086         if (dist == 0) {
01087             send_code(s, lc, ltree); /* send a literal byte */
01088             Tracecv(isgraph(lc), (stderr," '%c' ", lc));
01089         } else {
01090             /* Here, lc is the match length - MIN_MATCH */
01091             code = _length_code[lc];
01092             send_code(s, code+LITERALS+1, ltree); /* send the length code */
01093             extra = extra_lbits[code];
01094             if (extra != 0) {
01095                 lc -= base_length[code];
01096                 send_bits(s, lc, extra);       /* send the extra length bits */
01097             }
01098             dist--; /* dist is now the match distance - 1 */
01099             code = d_code(dist);
01100             Assert (code < D_CODES, "bad d_code");
01101 
01102             send_code(s, code, dtree);       /* send the distance code */
01103             extra = extra_dbits[code];
01104             if (extra != 0) {
01105                 dist -= base_dist[code];
01106                 send_bits(s, dist, extra);   /* send the extra distance bits */
01107             }
01108         } /* literal or match pair ? */
01109 
01110         /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
01111         Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
01112                "pendingBuf overflow");
01113 
01114     } while (lx < s->last_lit);
01115 
01116     send_code(s, END_BLOCK, ltree);
01117     s->last_eob_len = ltree[END_BLOCK].Len;
01118 }
01119 
01120 /* ===========================================================================
01121  * Set the data type to BINARY or TEXT, using a crude approximation:
01122  * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
01123  * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
01124  * IN assertion: the fields Freq of dyn_ltree are set.
01125  */
01126 local void set_data_type(s)
01127     deflate_state *s;
01128 {
01129     int n;
01130 
01131     for (n = 0; n < 9; n++)
01132         if (s->dyn_ltree[n].Freq != 0)
01133             break;
01134     if (n == 9)
01135         for (n = 14; n < 32; n++)
01136             if (s->dyn_ltree[n].Freq != 0)
01137                 break;
01138     s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
01139 }
01140 
01141 /* ===========================================================================
01142  * Reverse the first len bits of a code, using straightforward code (a faster
01143  * method would use a table)
01144  * IN assertion: 1 <= len <= 15
01145  */
01146 local unsigned bi_reverse(code, len)
01147     unsigned code; /* the value to invert */
01148     int len;       /* its bit length */
01149 {
01150     register unsigned res = 0;
01151     do {
01152         res |= code & 1;
01153         code >>= 1, res <<= 1;
01154     } while (--len > 0);
01155     return res >> 1;
01156 }
01157 
01158 /* ===========================================================================
01159  * Flush the bit buffer, keeping at most 7 bits in it.
01160  */
01161 local void bi_flush(s)
01162     deflate_state *s;
01163 {
01164     if (s->bi_valid == 16) {
01165         put_short(s, s->bi_buf);
01166         s->bi_buf = 0;
01167         s->bi_valid = 0;
01168     } else if (s->bi_valid >= 8) {
01169         put_byte(s, (Byte)s->bi_buf);
01170         s->bi_buf >>= 8;
01171         s->bi_valid -= 8;
01172     }
01173 }
01174 
01175 /* ===========================================================================
01176  * Flush the bit buffer and align the output on a byte boundary
01177  */
01178 local void bi_windup(s)
01179     deflate_state *s;
01180 {
01181     if (s->bi_valid > 8) {
01182         put_short(s, s->bi_buf);
01183     } else if (s->bi_valid > 0) {
01184         put_byte(s, (Byte)s->bi_buf);
01185     }
01186     s->bi_buf = 0;
01187     s->bi_valid = 0;
01188 #ifdef DEBUG
01189     s->bits_sent = (s->bits_sent+7) & ~7;
01190 #endif
01191 }
01192 
01193 /* ===========================================================================
01194  * Copy a stored block, storing first the length and its
01195  * one's complement if requested.
01196  */
01197 local void copy_block(s, buf, len, header)
01198     deflate_state *s;
01199     charf    *buf;    /* the input data */
01200     unsigned len;     /* its length */
01201     int      header;  /* true if block header must be written */
01202 {
01203     bi_windup(s);        /* align on byte boundary */
01204     s->last_eob_len = 8; /* enough lookahead for inflate */
01205 
01206     if (header) {
01207         put_short(s, (ush)len);
01208         put_short(s, (ush)~len);
01209 #ifdef DEBUG
01210         s->bits_sent += 2*16;
01211 #endif
01212     }
01213 #ifdef DEBUG
01214     s->bits_sent += (ulg)len<<3;
01215 #endif
01216     while (len--) {
01217         put_byte(s, *buf++);
01218     }
01219 }


openhrp3
Author(s): AIST, General Robotix Inc., Nakamura Lab of Dept. of Mechano Informatics at University of Tokyo
autogenerated on Thu Apr 11 2019 03:30:19