1 /*
   2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.  Oracle designates this
   7  * particular file as subject to the "Classpath" exception as provided
   8  * by Oracle in the LICENSE file that accompanied this code.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  */
  24 
  25 /* trees.c -- output deflated data using Huffman coding
  26  * Copyright (C) 1995-2017 Jean-loup Gailly
  27  * detect_data_type() function provided freely by Cosmin Truta, 2006
  28  * For conditions of distribution and use, see copyright notice in zlib.h
  29  */
  30 
  31 /*
  32  *  ALGORITHM
  33  *
  34  *      The "deflation" process uses several Huffman trees. The more
  35  *      common source values are represented by shorter bit sequences.
  36  *
  37  *      Each code tree is stored in a compressed form which is itself
  38  * a Huffman encoding of the lengths of all the code strings (in
  39  * ascending order by source values).  The actual code strings are
  40  * reconstructed from the lengths in the inflate process, as described
  41  * in the deflate specification.
  42  *
  43  *  REFERENCES
  44  *
  45  *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  46  *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  47  *
  48  *      Storer, James A.
  49  *          Data Compression:  Methods and Theory, pp. 49-50.
  50  *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
  51  *
  52  *      Sedgewick, R.
  53  *          Algorithms, p290.
  54  *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
  55  */
  56 
  57 /* @(#) $Id$ */
  58 
  59 /* #define GEN_TREES_H */
  60 
  61 #include "deflate.h"
  62 
  63 #ifdef ZLIB_DEBUG
  64 #  include <ctype.h>
  65 #endif
  66 
  67 /* ===========================================================================
  68  * Constants
  69  */
  70 
  71 #define MAX_BL_BITS 7
  72 /* Bit length codes must not exceed MAX_BL_BITS bits */
  73 
  74 #define END_BLOCK 256
  75 /* end of block literal code */
  76 
  77 #define REP_3_6      16
  78 /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  79 
  80 #define REPZ_3_10    17
  81 /* repeat a zero length 3-10 times  (3 bits of repeat count) */
  82 
  83 #define REPZ_11_138  18
  84 /* repeat a zero length 11-138 times  (7 bits of repeat count) */
  85 
  86 local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  87    = {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};
  88 
  89 local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  90    = {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};
  91 
  92 local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  93    = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  94 
  95 local const uch bl_order[BL_CODES]
  96    = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  97 /* The lengths of the bit length codes are sent in order of decreasing
  98  * probability, to avoid transmitting the lengths for unused bit length codes.
  99  */
 100 
 101 /* ===========================================================================
 102  * Local data. These are initialized only once.
 103  */
 104 
 105 #define DIST_CODE_LEN  512 /* see definition of array dist_code below */
 106 
 107 #if defined(GEN_TREES_H) || !defined(STDC)
 108 /* non ANSI compilers may not accept trees.h */
 109 
 110 local ct_data static_ltree[L_CODES+2];
 111 /* The static literal tree. Since the bit lengths are imposed, there is no
 112  * need for the L_CODES extra codes used during heap construction. However
 113  * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
 114  * below).
 115  */
 116 
 117 local ct_data static_dtree[D_CODES];
 118 /* The static distance tree. (Actually a trivial tree since all codes use
 119  * 5 bits.)
 120  */
 121 
 122 uch _dist_code[DIST_CODE_LEN];
 123 /* Distance codes. The first 256 values correspond to the distances
 124  * 3 .. 258, the last 256 values correspond to the top 8 bits of
 125  * the 15 bit distances.
 126  */
 127 
 128 uch _length_code[MAX_MATCH-MIN_MATCH+1];
 129 /* length code for each normalized match length (0 == MIN_MATCH) */
 130 
 131 local int base_length[LENGTH_CODES];
 132 /* First normalized length for each code (0 = MIN_MATCH) */
 133 
 134 local int base_dist[D_CODES];
 135 /* First normalized distance for each code (0 = distance of 1) */
 136 
 137 #else
 138 #  include "trees.h"
 139 #endif /* GEN_TREES_H */
 140 
 141 struct static_tree_desc_s {
 142     const ct_data *static_tree;  /* static tree or NULL */
 143     const intf *extra_bits;      /* extra bits for each code or NULL */
 144     int     extra_base;          /* base index for extra_bits */
 145     int     elems;               /* max number of elements in the tree */
 146     int     max_length;          /* max bit length for the codes */
 147 };
 148 
 149 local const static_tree_desc  static_l_desc =
 150 {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
 151 
 152 local const static_tree_desc  static_d_desc =
 153 {static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
 154 
 155 local const static_tree_desc  static_bl_desc =
 156 {(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
 157 
 158 /* ===========================================================================
 159  * Local (static) routines in this file.
 160  */
 161 
 162 local void tr_static_init OF((void));
 163 local void init_block     OF((deflate_state *s));
 164 local void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));
 165 local void gen_bitlen     OF((deflate_state *s, tree_desc *desc));
 166 local void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));
 167 local void build_tree     OF((deflate_state *s, tree_desc *desc));
 168 local void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));
 169 local void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));
 170 local int  build_bl_tree  OF((deflate_state *s));
 171 local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
 172                               int blcodes));
 173 local void compress_block OF((deflate_state *s, const ct_data *ltree,
 174                               const ct_data *dtree));
 175 local int  detect_data_type OF((deflate_state *s));
 176 local unsigned bi_reverse OF((unsigned value, int length));
 177 local void bi_windup      OF((deflate_state *s));
 178 local void bi_flush       OF((deflate_state *s));
 179 
 180 #ifdef GEN_TREES_H
 181 local void gen_trees_header OF((void));
 182 #endif
 183 
 184 #ifndef ZLIB_DEBUG
 185 #  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
 186    /* Send a code of the given tree. c and tree must not have side effects */
 187 
 188 #else /* !ZLIB_DEBUG */
 189 #  define send_code(s, c, tree) \
 190      { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
 191        send_bits(s, tree[c].Code, tree[c].Len); }
 192 #endif
 193 
 194 /* ===========================================================================
 195  * Output a short LSB first on the stream.
 196  * IN assertion: there is enough room in pendingBuf.
 197  */
 198 #define put_short(s, w) { \
 199     put_byte(s, (uch)((w) & 0xff)); \
 200     put_byte(s, (uch)((ush)(w) >> 8)); \
 201 }
 202 
 203 /* ===========================================================================
 204  * Send a value on a given number of bits.
 205  * IN assertion: length <= 16 and value fits in length bits.
 206  */
 207 #ifdef ZLIB_DEBUG
 208 local void send_bits      OF((deflate_state *s, int value, int length));
 209 
 210 local void send_bits(s, value, length)
 211     deflate_state *s;
 212     int value;  /* value to send */
 213     int length; /* number of bits */
 214 {
 215     Tracevv((stderr," l %2d v %4x ", length, value));
 216     Assert(length > 0 && length <= 15, "invalid length");
 217     s->bits_sent += (ulg)length;
 218 
 219     /* If not enough room in bi_buf, use (valid) bits from bi_buf and
 220      * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
 221      * unused bits in value.
 222      */
 223     if (s->bi_valid > (int)Buf_size - length) {
 224         s->bi_buf |= (ush)value << s->bi_valid;
 225         put_short(s, s->bi_buf);
 226         s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
 227         s->bi_valid += length - Buf_size;
 228     } else {
 229         s->bi_buf |= (ush)value << s->bi_valid;
 230         s->bi_valid += length;
 231     }
 232 }
 233 #else /* !ZLIB_DEBUG */
 234 
 235 #define send_bits(s, value, length) \
 236 { int len = length;\
 237   if (s->bi_valid > (int)Buf_size - len) {\
 238     int val = (int)value;\
 239     s->bi_buf |= (ush)val << s->bi_valid;\
 240     put_short(s, s->bi_buf);\
 241     s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
 242     s->bi_valid += len - Buf_size;\
 243   } else {\
 244     s->bi_buf |= (ush)(value) << s->bi_valid;\
 245     s->bi_valid += len;\
 246   }\
 247 }
 248 #endif /* ZLIB_DEBUG */
 249 
 250 
 251 /* the arguments must not have side effects */
 252 
 253 /* ===========================================================================
 254  * Initialize the various 'constant' tables.
 255  */
 256 local void tr_static_init()
 257 {
 258 #if defined(GEN_TREES_H) || !defined(STDC)
 259     static int static_init_done = 0;
 260     int n;        /* iterates over tree elements */
 261     int bits;     /* bit counter */
 262     int length;   /* length value */
 263     int code;     /* code value */
 264     int dist;     /* distance index */
 265     ush bl_count[MAX_BITS+1];
 266     /* number of codes at each bit length for an optimal tree */
 267 
 268     if (static_init_done) return;
 269 
 270     /* For some embedded targets, global variables are not initialized: */
 271 #ifdef NO_INIT_GLOBAL_POINTERS
 272     static_l_desc.static_tree = static_ltree;
 273     static_l_desc.extra_bits = extra_lbits;
 274     static_d_desc.static_tree = static_dtree;
 275     static_d_desc.extra_bits = extra_dbits;
 276     static_bl_desc.extra_bits = extra_blbits;
 277 #endif
 278 
 279     /* Initialize the mapping length (0..255) -> length code (0..28) */
 280     length = 0;
 281     for (code = 0; code < LENGTH_CODES-1; code++) {
 282         base_length[code] = length;
 283         for (n = 0; n < (1<<extra_lbits[code]); n++) {
 284             _length_code[length++] = (uch)code;
 285         }
 286     }
 287     Assert (length == 256, "tr_static_init: length != 256");
 288     /* Note that the length 255 (match length 258) can be represented
 289      * in two different ways: code 284 + 5 bits or code 285, so we
 290      * overwrite length_code[255] to use the best encoding:
 291      */
 292     _length_code[length-1] = (uch)code;
 293 
 294     /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
 295     dist = 0;
 296     for (code = 0 ; code < 16; code++) {
 297         base_dist[code] = dist;
 298         for (n = 0; n < (1<<extra_dbits[code]); n++) {
 299             _dist_code[dist++] = (uch)code;
 300         }
 301     }
 302     Assert (dist == 256, "tr_static_init: dist != 256");
 303     dist >>= 7; /* from now on, all distances are divided by 128 */
 304     for ( ; code < D_CODES; code++) {
 305         base_dist[code] = dist << 7;
 306         for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
 307             _dist_code[256 + dist++] = (uch)code;
 308         }
 309     }
 310     Assert (dist == 256, "tr_static_init: 256+dist != 512");
 311 
 312     /* Construct the codes of the static literal tree */
 313     for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
 314     n = 0;
 315     while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
 316     while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
 317     while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
 318     while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
 319     /* Codes 286 and 287 do not exist, but we must include them in the
 320      * tree construction to get a canonical Huffman tree (longest code
 321      * all ones)
 322      */
 323     gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
 324 
 325     /* The static distance tree is trivial: */
 326     for (n = 0; n < D_CODES; n++) {
 327         static_dtree[n].Len = 5;
 328         static_dtree[n].Code = bi_reverse((unsigned)n, 5);
 329     }
 330     static_init_done = 1;
 331 
 332 #  ifdef GEN_TREES_H
 333     gen_trees_header();
 334 #  endif
 335 #endif /* defined(GEN_TREES_H) || !defined(STDC) */
 336 }
 337 
 338 /* ===========================================================================
 339  * Genererate the file trees.h describing the static trees.
 340  */
 341 #ifdef GEN_TREES_H
 342 #  ifndef ZLIB_DEBUG
 343 #    include <stdio.h>
 344 #  endif
 345 
 346 #  define SEPARATOR(i, last, width) \
 347       ((i) == (last)? "\n};\n\n" :    \
 348        ((i) % (width) == (width)-1 ? ",\n" : ", "))
 349 
 350 void gen_trees_header()
 351 {
 352     FILE *header = fopen("trees.h", "w");
 353     int i;
 354 
 355     Assert (header != NULL, "Can't open trees.h");
 356     fprintf(header,
 357             "/* header created automatically with -DGEN_TREES_H */\n\n");
 358 
 359     fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
 360     for (i = 0; i < L_CODES+2; i++) {
 361         fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
 362                 static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
 363     }
 364 
 365     fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
 366     for (i = 0; i < D_CODES; i++) {
 367         fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
 368                 static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
 369     }
 370 
 371     fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
 372     for (i = 0; i < DIST_CODE_LEN; i++) {
 373         fprintf(header, "%2u%s", _dist_code[i],
 374                 SEPARATOR(i, DIST_CODE_LEN-1, 20));
 375     }
 376 
 377     fprintf(header,
 378         "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
 379     for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
 380         fprintf(header, "%2u%s", _length_code[i],
 381                 SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
 382     }
 383 
 384     fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
 385     for (i = 0; i < LENGTH_CODES; i++) {
 386         fprintf(header, "%1u%s", base_length[i],
 387                 SEPARATOR(i, LENGTH_CODES-1, 20));
 388     }
 389 
 390     fprintf(header, "local const int base_dist[D_CODES] = {\n");
 391     for (i = 0; i < D_CODES; i++) {
 392         fprintf(header, "%5u%s", base_dist[i],
 393                 SEPARATOR(i, D_CODES-1, 10));
 394     }
 395 
 396     fclose(header);
 397 }
 398 #endif /* GEN_TREES_H */
 399 
 400 /* ===========================================================================
 401  * Initialize the tree data structures for a new zlib stream.
 402  */
 403 void ZLIB_INTERNAL _tr_init(s)
 404     deflate_state *s;
 405 {
 406     tr_static_init();
 407 
 408     s->l_desc.dyn_tree = s->dyn_ltree;
 409     s->l_desc.stat_desc = &static_l_desc;
 410 
 411     s->d_desc.dyn_tree = s->dyn_dtree;
 412     s->d_desc.stat_desc = &static_d_desc;
 413 
 414     s->bl_desc.dyn_tree = s->bl_tree;
 415     s->bl_desc.stat_desc = &static_bl_desc;
 416 
 417     s->bi_buf = 0;
 418     s->bi_valid = 0;
 419 #ifdef ZLIB_DEBUG
 420     s->compressed_len = 0L;
 421     s->bits_sent = 0L;
 422 #endif
 423 
 424     /* Initialize the first block of the first file: */
 425     init_block(s);
 426 }
 427 
 428 /* ===========================================================================
 429  * Initialize a new block.
 430  */
 431 local void init_block(s)
 432     deflate_state *s;
 433 {
 434     int n; /* iterates over tree elements */
 435 
 436     /* Initialize the trees. */
 437     for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
 438     for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
 439     for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
 440 
 441     s->dyn_ltree[END_BLOCK].Freq = 1;
 442     s->opt_len = s->static_len = 0L;
 443     s->last_lit = s->matches = 0;
 444 }
 445 
 446 #define SMALLEST 1
 447 /* Index within the heap array of least frequent node in the Huffman tree */
 448 
 449 
 450 /* ===========================================================================
 451  * Remove the smallest element from the heap and recreate the heap with
 452  * one less element. Updates heap and heap_len.
 453  */
 454 #define pqremove(s, tree, top) \
 455 {\
 456     top = s->heap[SMALLEST]; \
 457     s->heap[SMALLEST] = s->heap[s->heap_len--]; \
 458     pqdownheap(s, tree, SMALLEST); \
 459 }
 460 
 461 /* ===========================================================================
 462  * Compares to subtrees, using the tree depth as tie breaker when
 463  * the subtrees have equal frequency. This minimizes the worst case length.
 464  */
 465 #define smaller(tree, n, m, depth) \
 466    (tree[n].Freq < tree[m].Freq || \
 467    (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
 468 
 469 /* ===========================================================================
 470  * Restore the heap property by moving down the tree starting at node k,
 471  * exchanging a node with the smallest of its two sons if necessary, stopping
 472  * when the heap property is re-established (each father smaller than its
 473  * two sons).
 474  */
 475 local void pqdownheap(s, tree, k)
 476     deflate_state *s;
 477     ct_data *tree;  /* the tree to restore */
 478     int k;               /* node to move down */
 479 {
 480     int v = s->heap[k];
 481     int j = k << 1;  /* left son of k */
 482     while (j <= s->heap_len) {
 483         /* Set j to the smallest of the two sons: */
 484         if (j < s->heap_len &&
 485             smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
 486             j++;
 487         }
 488         /* Exit if v is smaller than both sons */
 489         if (smaller(tree, v, s->heap[j], s->depth)) break;
 490 
 491         /* Exchange v with the smallest son */
 492         s->heap[k] = s->heap[j];  k = j;
 493 
 494         /* And continue down the tree, setting j to the left son of k */
 495         j <<= 1;
 496     }
 497     s->heap[k] = v;
 498 }
 499 
 500 /* ===========================================================================
 501  * Compute the optimal bit lengths for a tree and update the total bit length
 502  * for the current block.
 503  * IN assertion: the fields freq and dad are set, heap[heap_max] and
 504  *    above are the tree nodes sorted by increasing frequency.
 505  * OUT assertions: the field len is set to the optimal bit length, the
 506  *     array bl_count contains the frequencies for each bit length.
 507  *     The length opt_len is updated; static_len is also updated if stree is
 508  *     not null.
 509  */
 510 local void gen_bitlen(s, desc)
 511     deflate_state *s;
 512     tree_desc *desc;    /* the tree descriptor */
 513 {
 514     ct_data *tree        = desc->dyn_tree;
 515     int max_code         = desc->max_code;
 516     const ct_data *stree = desc->stat_desc->static_tree;
 517     const intf *extra    = desc->stat_desc->extra_bits;
 518     int base             = desc->stat_desc->extra_base;
 519     int max_length       = desc->stat_desc->max_length;
 520     int h;              /* heap index */
 521     int n, m;           /* iterate over the tree elements */
 522     int bits;           /* bit length */
 523     int xbits;          /* extra bits */
 524     ush f;              /* frequency */
 525     int overflow = 0;   /* number of elements with bit length too large */
 526 
 527     for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
 528 
 529     /* In a first pass, compute the optimal bit lengths (which may
 530      * overflow in the case of the bit length tree).
 531      */
 532     tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
 533 
 534     for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
 535         n = s->heap[h];
 536         bits = tree[tree[n].Dad].Len + 1;
 537         if (bits > max_length) bits = max_length, overflow++;
 538         tree[n].Len = (ush)bits;
 539         /* We overwrite tree[n].Dad which is no longer needed */
 540 
 541         if (n > max_code) continue; /* not a leaf node */
 542 
 543         s->bl_count[bits]++;
 544         xbits = 0;
 545         if (n >= base) xbits = extra[n-base];
 546         f = tree[n].Freq;
 547         s->opt_len += (ulg)f * (unsigned)(bits + xbits);
 548         if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits);
 549     }
 550     if (overflow == 0) return;
 551 
 552     Tracev((stderr,"\nbit length overflow\n"));
 553     /* This happens for example on obj2 and pic of the Calgary corpus */
 554 
 555     /* Find the first bit length which could increase: */
 556     do {
 557         bits = max_length-1;
 558         while (s->bl_count[bits] == 0) bits--;
 559         s->bl_count[bits]--;      /* move one leaf down the tree */
 560         s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
 561         s->bl_count[max_length]--;
 562         /* The brother of the overflow item also moves one step up,
 563          * but this does not affect bl_count[max_length]
 564          */
 565         overflow -= 2;
 566     } while (overflow > 0);
 567 
 568     /* Now recompute all bit lengths, scanning in increasing frequency.
 569      * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
 570      * lengths instead of fixing only the wrong ones. This idea is taken
 571      * from 'ar' written by Haruhiko Okumura.)
 572      */
 573     for (bits = max_length; bits != 0; bits--) {
 574         n = s->bl_count[bits];
 575         while (n != 0) {
 576             m = s->heap[--h];
 577             if (m > max_code) continue;
 578             if ((unsigned) tree[m].Len != (unsigned) bits) {
 579                 Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
 580                 s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq;
 581                 tree[m].Len = (ush)bits;
 582             }
 583             n--;
 584         }
 585     }
 586 }
 587 
 588 /* ===========================================================================
 589  * Generate the codes for a given tree and bit counts (which need not be
 590  * optimal).
 591  * IN assertion: the array bl_count contains the bit length statistics for
 592  * the given tree and the field len is set for all tree elements.
 593  * OUT assertion: the field code is set for all tree elements of non
 594  *     zero code length.
 595  */
 596 local void gen_codes (tree, max_code, bl_count)
 597     ct_data *tree;             /* the tree to decorate */
 598     int max_code;              /* largest code with non zero frequency */
 599     ushf *bl_count;            /* number of codes at each bit length */
 600 {
 601     ush next_code[MAX_BITS+1]; /* next code value for each bit length */
 602     unsigned code = 0;         /* running code value */
 603     int bits;                  /* bit index */
 604     int n;                     /* code index */
 605 
 606     /* The distribution counts are first used to generate the code values
 607      * without bit reversal.
 608      */
 609     for (bits = 1; bits <= MAX_BITS; bits++) {
 610         code = (code + bl_count[bits-1]) << 1;
 611         next_code[bits] = (ush)code;
 612     }
 613     /* Check that the bit counts in bl_count are consistent. The last code
 614      * must be all ones.
 615      */
 616     Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
 617             "inconsistent bit counts");
 618     Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
 619 
 620     for (n = 0;  n <= max_code; n++) {
 621         int len = tree[n].Len;
 622         if (len == 0) continue;
 623         /* Now reverse the bits */
 624         tree[n].Code = (ush)bi_reverse(next_code[len]++, len);
 625 
 626         Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
 627              n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
 628     }
 629 }
 630 
 631 /* ===========================================================================
 632  * Construct one Huffman tree and assigns the code bit strings and lengths.
 633  * Update the total bit length for the current block.
 634  * IN assertion: the field freq is set for all tree elements.
 635  * OUT assertions: the fields len and code are set to the optimal bit length
 636  *     and corresponding code. The length opt_len is updated; static_len is
 637  *     also updated if stree is not null. The field max_code is set.
 638  */
 639 local void build_tree(s, desc)
 640     deflate_state *s;
 641     tree_desc *desc; /* the tree descriptor */
 642 {
 643     ct_data *tree         = desc->dyn_tree;
 644     const ct_data *stree  = desc->stat_desc->static_tree;
 645     int elems             = desc->stat_desc->elems;
 646     int n, m;          /* iterate over heap elements */
 647     int max_code = -1; /* largest code with non zero frequency */
 648     int node;          /* new node being created */
 649 
 650     /* Construct the initial heap, with least frequent element in
 651      * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
 652      * heap[0] is not used.
 653      */
 654     s->heap_len = 0, s->heap_max = HEAP_SIZE;
 655 
 656     for (n = 0; n < elems; n++) {
 657         if (tree[n].Freq != 0) {
 658             s->heap[++(s->heap_len)] = max_code = n;
 659             s->depth[n] = 0;
 660         } else {
 661             tree[n].Len = 0;
 662         }
 663     }
 664 
 665     /* The pkzip format requires that at least one distance code exists,
 666      * and that at least one bit should be sent even if there is only one
 667      * possible code. So to avoid special checks later on we force at least
 668      * two codes of non zero frequency.
 669      */
 670     while (s->heap_len < 2) {
 671         node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
 672         tree[node].Freq = 1;
 673         s->depth[node] = 0;
 674         s->opt_len--; if (stree) s->static_len -= stree[node].Len;
 675         /* node is 0 or 1 so it does not have extra bits */
 676     }
 677     desc->max_code = max_code;
 678 
 679     /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
 680      * establish sub-heaps of increasing lengths:
 681      */
 682     for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
 683 
 684     /* Construct the Huffman tree by repeatedly combining the least two
 685      * frequent nodes.
 686      */
 687     node = elems;              /* next internal node of the tree */
 688     do {
 689         pqremove(s, tree, n);  /* n = node of least frequency */
 690         m = s->heap[SMALLEST]; /* m = node of next least frequency */
 691 
 692         s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
 693         s->heap[--(s->heap_max)] = m;
 694 
 695         /* Create a new node father of n and m */
 696         tree[node].Freq = tree[n].Freq + tree[m].Freq;
 697         s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
 698                                 s->depth[n] : s->depth[m]) + 1);
 699         tree[n].Dad = tree[m].Dad = (ush)node;
 700 #ifdef DUMP_BL_TREE
 701         if (tree == s->bl_tree) {
 702             fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
 703                     node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
 704         }
 705 #endif
 706         /* and insert the new node in the heap */
 707         s->heap[SMALLEST] = node++;
 708         pqdownheap(s, tree, SMALLEST);
 709 
 710     } while (s->heap_len >= 2);
 711 
 712     s->heap[--(s->heap_max)] = s->heap[SMALLEST];
 713 
 714     /* At this point, the fields freq and dad are set. We can now
 715      * generate the bit lengths.
 716      */
 717     gen_bitlen(s, (tree_desc *)desc);
 718 
 719     /* The field len is now set, we can generate the bit codes */
 720     gen_codes ((ct_data *)tree, max_code, s->bl_count);
 721 }
 722 
 723 /* ===========================================================================
 724  * Scan a literal or distance tree to determine the frequencies of the codes
 725  * in the bit length tree.
 726  */
 727 local void scan_tree (s, tree, max_code)
 728     deflate_state *s;
 729     ct_data *tree;   /* the tree to be scanned */
 730     int max_code;    /* and its largest code of non zero frequency */
 731 {
 732     int n;                     /* iterates over all tree elements */
 733     int prevlen = -1;          /* last emitted length */
 734     int curlen;                /* length of current code */
 735     int nextlen = tree[0].Len; /* length of next code */
 736     int count = 0;             /* repeat count of the current code */
 737     int max_count = 7;         /* max repeat count */
 738     int min_count = 4;         /* min repeat count */
 739 
 740     if (nextlen == 0) max_count = 138, min_count = 3;
 741     tree[max_code+1].Len = (ush)0xffff; /* guard */
 742 
 743     for (n = 0; n <= max_code; n++) {
 744         curlen = nextlen; nextlen = tree[n+1].Len;
 745         if (++count < max_count && curlen == nextlen) {
 746             continue;
 747         } else if (count < min_count) {
 748             s->bl_tree[curlen].Freq += count;
 749         } else if (curlen != 0) {
 750             if (curlen != prevlen) s->bl_tree[curlen].Freq++;
 751             s->bl_tree[REP_3_6].Freq++;
 752         } else if (count <= 10) {
 753             s->bl_tree[REPZ_3_10].Freq++;
 754         } else {
 755             s->bl_tree[REPZ_11_138].Freq++;
 756         }
 757         count = 0; prevlen = curlen;
 758         if (nextlen == 0) {
 759             max_count = 138, min_count = 3;
 760         } else if (curlen == nextlen) {
 761             max_count = 6, min_count = 3;
 762         } else {
 763             max_count = 7, min_count = 4;
 764         }
 765     }
 766 }
 767 
 768 /* ===========================================================================
 769  * Send a literal or distance tree in compressed form, using the codes in
 770  * bl_tree.
 771  */
 772 local void send_tree (s, tree, max_code)
 773     deflate_state *s;
 774     ct_data *tree; /* the tree to be scanned */
 775     int max_code;       /* and its largest code of non zero frequency */
 776 {
 777     int n;                     /* iterates over all tree elements */
 778     int prevlen = -1;          /* last emitted length */
 779     int curlen;                /* length of current code */
 780     int nextlen = tree[0].Len; /* length of next code */
 781     int count = 0;             /* repeat count of the current code */
 782     int max_count = 7;         /* max repeat count */
 783     int min_count = 4;         /* min repeat count */
 784 
 785     /* tree[max_code+1].Len = -1; */  /* guard already set */
 786     if (nextlen == 0) max_count = 138, min_count = 3;
 787 
 788     for (n = 0; n <= max_code; n++) {
 789         curlen = nextlen; nextlen = tree[n+1].Len;
 790         if (++count < max_count && curlen == nextlen) {
 791             continue;
 792         } else if (count < min_count) {
 793             do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
 794 
 795         } else if (curlen != 0) {
 796             if (curlen != prevlen) {
 797                 send_code(s, curlen, s->bl_tree); count--;
 798             }
 799             Assert(count >= 3 && count <= 6, " 3_6?");
 800             send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
 801 
 802         } else if (count <= 10) {
 803             send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
 804 
 805         } else {
 806             send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
 807         }
 808         count = 0; prevlen = curlen;
 809         if (nextlen == 0) {
 810             max_count = 138, min_count = 3;
 811         } else if (curlen == nextlen) {
 812             max_count = 6, min_count = 3;
 813         } else {
 814             max_count = 7, min_count = 4;
 815         }
 816     }
 817 }
 818 
 819 /* ===========================================================================
 820  * Construct the Huffman tree for the bit lengths and return the index in
 821  * bl_order of the last bit length code to send.
 822  */
 823 local int build_bl_tree(s)
 824     deflate_state *s;
 825 {
 826     int max_blindex;  /* index of last bit length code of non zero freq */
 827 
 828     /* Determine the bit length frequencies for literal and distance trees */
 829     scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
 830     scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
 831 
 832     /* Build the bit length tree: */
 833     build_tree(s, (tree_desc *)(&(s->bl_desc)));
 834     /* opt_len now includes the length of the tree representations, except
 835      * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
 836      */
 837 
 838     /* Determine the number of bit length codes to send. The pkzip format
 839      * requires that at least 4 bit length codes be sent. (appnote.txt says
 840      * 3 but the actual value used is 4.)
 841      */
 842     for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
 843         if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
 844     }
 845     /* Update opt_len to include the bit length tree and counts */
 846     s->opt_len += 3*((ulg)max_blindex+1) + 5+5+4;
 847     Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
 848             s->opt_len, s->static_len));
 849 
 850     return max_blindex;
 851 }
 852 
 853 /* ===========================================================================
 854  * Send the header for a block using dynamic Huffman trees: the counts, the
 855  * lengths of the bit length codes, the literal tree and the distance tree.
 856  * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
 857  */
 858 local void send_all_trees(s, lcodes, dcodes, blcodes)
 859     deflate_state *s;
 860     int lcodes, dcodes, blcodes; /* number of codes for each tree */
 861 {
 862     int rank;                    /* index in bl_order */
 863 
 864     Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
 865     Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
 866             "too many codes");
 867     Tracev((stderr, "\nbl counts: "));
 868     send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
 869     send_bits(s, dcodes-1,   5);
 870     send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
 871     for (rank = 0; rank < blcodes; rank++) {
 872         Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
 873         send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
 874     }
 875     Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
 876 
 877     send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
 878     Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
 879 
 880     send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
 881     Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
 882 }
 883 
 884 /* ===========================================================================
 885  * Send a stored block
 886  */
 887 void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)
 888     deflate_state *s;
 889     charf *buf;       /* input block */
 890     ulg stored_len;   /* length of input block */
 891     int last;         /* one if this is the last block for a file */
 892 {
 893     send_bits(s, (STORED_BLOCK<<1)+last, 3);    /* send block type */
 894     bi_windup(s);        /* align on byte boundary */
 895     put_short(s, (ush)stored_len);
 896     put_short(s, (ush)~stored_len);
 897     zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len);
 898     s->pending += stored_len;
 899 #ifdef ZLIB_DEBUG
 900     s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
 901     s->compressed_len += (stored_len + 4) << 3;
 902     s->bits_sent += 2*16;
 903     s->bits_sent += stored_len<<3;
 904 #endif
 905 }
 906 
 907 /* ===========================================================================
 908  * Flush the bits in the bit buffer to pending output (leaves at most 7 bits)
 909  */
 910 void ZLIB_INTERNAL _tr_flush_bits(s)
 911     deflate_state *s;
 912 {
 913     bi_flush(s);
 914 }
 915 
 916 /* ===========================================================================
 917  * Send one empty static block to give enough lookahead for inflate.
 918  * This takes 10 bits, of which 7 may remain in the bit buffer.
 919  */
 920 void ZLIB_INTERNAL _tr_align(s)
 921     deflate_state *s;
 922 {
 923     send_bits(s, STATIC_TREES<<1, 3);
 924     send_code(s, END_BLOCK, static_ltree);
 925 #ifdef ZLIB_DEBUG
 926     s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
 927 #endif
 928     bi_flush(s);
 929 }
 930 
 931 /* ===========================================================================
 932  * Determine the best encoding for the current block: dynamic trees, static
 933  * trees or store, and write out the encoded block.
 934  */
 935 void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)
 936     deflate_state *s;
 937     charf *buf;       /* input block, or NULL if too old */
 938     ulg stored_len;   /* length of input block */
 939     int last;         /* one if this is the last block for a file */
 940 {
 941     ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
 942     int max_blindex = 0;  /* index of last bit length code of non zero freq */
 943 
 944     /* Build the Huffman trees unless a stored block is forced */
 945     if (s->level > 0) {
 946 
 947         /* Check if the file is binary or text */
 948         if (s->strm->data_type == Z_UNKNOWN)
 949             s->strm->data_type = detect_data_type(s);
 950 
 951         /* Construct the literal and distance trees */
 952         build_tree(s, (tree_desc *)(&(s->l_desc)));
 953         Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
 954                 s->static_len));
 955 
 956         build_tree(s, (tree_desc *)(&(s->d_desc)));
 957         Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
 958                 s->static_len));
 959         /* At this point, opt_len and static_len are the total bit lengths of
 960          * the compressed block data, excluding the tree representations.
 961          */
 962 
 963         /* Build the bit length tree for the above two trees, and get the index
 964          * in bl_order of the last bit length code to send.
 965          */
 966         max_blindex = build_bl_tree(s);
 967 
 968         /* Determine the best encoding. Compute the block lengths in bytes. */
 969         opt_lenb = (s->opt_len+3+7)>>3;
 970         static_lenb = (s->static_len+3+7)>>3;
 971 
 972         Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
 973                 opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
 974                 s->last_lit));
 975 
 976         if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
 977 
 978     } else {
 979         Assert(buf != (char*)0, "lost buf");
 980         opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
 981     }
 982 
 983 #ifdef FORCE_STORED
 984     if (buf != (char*)0) { /* force stored block */
 985 #else
 986     if (stored_len+4 <= opt_lenb && buf != (char*)0) {
 987                        /* 4: two words for the lengths */
 988 #endif
 989         /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
 990          * Otherwise we can't have processed more than WSIZE input bytes since
 991          * the last block flush, because compression would have been
 992          * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
 993          * transform a block into a stored block.
 994          */
 995         _tr_stored_block(s, buf, stored_len, last);
 996 
 997 #ifdef FORCE_STATIC
 998     } else if (static_lenb >= 0) { /* force static trees */
 999 #else
1000     } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
1001 #endif
1002         send_bits(s, (STATIC_TREES<<1)+last, 3);
1003         compress_block(s, (const ct_data *)static_ltree,
1004                        (const ct_data *)static_dtree);
1005 #ifdef ZLIB_DEBUG
1006         s->compressed_len += 3 + s->static_len;
1007 #endif
1008     } else {
1009         send_bits(s, (DYN_TREES<<1)+last, 3);
1010         send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
1011                        max_blindex+1);
1012         compress_block(s, (const ct_data *)s->dyn_ltree,
1013                        (const ct_data *)s->dyn_dtree);
1014 #ifdef ZLIB_DEBUG
1015         s->compressed_len += 3 + s->opt_len;
1016 #endif
1017     }
1018     Assert (s->compressed_len == s->bits_sent, "bad compressed size");
1019     /* The above check is made mod 2^32, for files larger than 512 MB
1020      * and uLong implemented on 32 bits.
1021      */
1022     init_block(s);
1023 
1024     if (last) {
1025         bi_windup(s);
1026 #ifdef ZLIB_DEBUG
1027         s->compressed_len += 7;  /* align on byte boundary */
1028 #endif
1029     }
1030     Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
1031            s->compressed_len-7*last));
1032 }
1033 
1034 /* ===========================================================================
1035  * Save the match info and tally the frequency counts. Return true if
1036  * the current block must be flushed.
1037  */
1038 int ZLIB_INTERNAL _tr_tally (s, dist, lc)
1039     deflate_state *s;
1040     unsigned dist;  /* distance of matched string */
1041     unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
1042 {
1043     s->d_buf[s->last_lit] = (ush)dist;
1044     s->l_buf[s->last_lit++] = (uch)lc;
1045     if (dist == 0) {
1046         /* lc is the unmatched char */
1047         s->dyn_ltree[lc].Freq++;
1048     } else {
1049         s->matches++;
1050         /* Here, lc is the match length - MIN_MATCH */
1051         dist--;             /* dist = match distance - 1 */
1052         Assert((ush)dist < (ush)MAX_DIST(s) &&
1053                (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
1054                (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
1055 
1056         s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
1057         s->dyn_dtree[d_code(dist)].Freq++;
1058     }
1059 
1060 #ifdef TRUNCATE_BLOCK
1061     /* Try to guess if it is profitable to stop the current block here */
1062     if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
1063         /* Compute an upper bound for the compressed length */
1064         ulg out_length = (ulg)s->last_lit*8L;
1065         ulg in_length = (ulg)((long)s->strstart - s->block_start);
1066         int dcode;
1067         for (dcode = 0; dcode < D_CODES; dcode++) {
1068             out_length += (ulg)s->dyn_dtree[dcode].Freq *
1069                 (5L+extra_dbits[dcode]);
1070         }
1071         out_length >>= 3;
1072         Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
1073                s->last_lit, in_length, out_length,
1074                100L - out_length*100L/in_length));
1075         if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
1076     }
1077 #endif
1078     return (s->last_lit == s->lit_bufsize-1);
1079     /* We avoid equality with lit_bufsize because of wraparound at 64K
1080      * on 16 bit machines and because stored blocks are restricted to
1081      * 64K-1 bytes.
1082      */
1083 }
1084 
1085 /* ===========================================================================
1086  * Send the block data compressed using the given Huffman trees
1087  */
1088 local void compress_block(s, ltree, dtree)
1089     deflate_state *s;
1090     const ct_data *ltree; /* literal tree */
1091     const ct_data *dtree; /* distance tree */
1092 {
1093     unsigned dist;      /* distance of matched string */
1094     int lc;             /* match length or unmatched char (if dist == 0) */
1095     unsigned lx = 0;    /* running index in l_buf */
1096     unsigned code;      /* the code to send */
1097     int extra;          /* number of extra bits to send */
1098 
1099     if (s->last_lit != 0) do {
1100         dist = s->d_buf[lx];
1101         lc = s->l_buf[lx++];
1102         if (dist == 0) {
1103             send_code(s, lc, ltree); /* send a literal byte */
1104             Tracecv(isgraph(lc), (stderr," '%c' ", lc));
1105         } else {
1106             /* Here, lc is the match length - MIN_MATCH */
1107             code = _length_code[lc];
1108             send_code(s, code+LITERALS+1, ltree); /* send the length code */
1109             extra = extra_lbits[code];
1110             if (extra != 0) {
1111                 lc -= base_length[code];
1112                 send_bits(s, lc, extra);       /* send the extra length bits */
1113             }
1114             dist--; /* dist is now the match distance - 1 */
1115             code = d_code(dist);
1116             Assert (code < D_CODES, "bad d_code");
1117 
1118             send_code(s, code, dtree);       /* send the distance code */
1119             extra = extra_dbits[code];
1120             if (extra != 0) {
1121                 dist -= (unsigned)base_dist[code];
1122                 send_bits(s, dist, extra);   /* send the extra distance bits */
1123             }
1124         } /* literal or match pair ? */
1125 
1126         /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
1127         Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
1128                "pendingBuf overflow");
1129 
1130     } while (lx < s->last_lit);
1131 
1132     send_code(s, END_BLOCK, ltree);
1133 }
1134 
1135 /* ===========================================================================
1136  * Check if the data type is TEXT or BINARY, using the following algorithm:
1137  * - TEXT if the two conditions below are satisfied:
1138  *    a) There are no non-portable control characters belonging to the
1139  *       "black list" (0..6, 14..25, 28..31).
1140  *    b) There is at least one printable character belonging to the
1141  *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
1142  * - BINARY otherwise.
1143  * - The following partially-portable control characters form a
1144  *   "gray list" that is ignored in this detection algorithm:
1145  *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
1146  * IN assertion: the fields Freq of dyn_ltree are set.
1147  */
1148 local int detect_data_type(s)
1149     deflate_state *s;
1150 {
1151     /* black_mask is the bit mask of black-listed bytes
1152      * set bits 0..6, 14..25, and 28..31
1153      * 0xf3ffc07f = binary 11110011111111111100000001111111
1154      */
1155     unsigned long black_mask = 0xf3ffc07fUL;
1156     int n;
1157 
1158     /* Check for non-textual ("black-listed") bytes. */
1159     for (n = 0; n <= 31; n++, black_mask >>= 1)
1160         if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))
1161             return Z_BINARY;
1162 
1163     /* Check for textual ("white-listed") bytes. */
1164     if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
1165             || s->dyn_ltree[13].Freq != 0)
1166         return Z_TEXT;
1167     for (n = 32; n < LITERALS; n++)
1168         if (s->dyn_ltree[n].Freq != 0)
1169             return Z_TEXT;
1170 
1171     /* There are no "black-listed" or "white-listed" bytes:
1172      * this stream either is empty or has tolerated ("gray-listed") bytes only.
1173      */
1174     return Z_BINARY;
1175 }
1176 
1177 /* ===========================================================================
1178  * Reverse the first len bits of a code, using straightforward code (a faster
1179  * method would use a table)
1180  * IN assertion: 1 <= len <= 15
1181  */
1182 local unsigned bi_reverse(code, len)
1183     unsigned code; /* the value to invert */
1184     int len;       /* its bit length */
1185 {
1186     register unsigned res = 0;
1187     do {
1188         res |= code & 1;
1189         code >>= 1, res <<= 1;
1190     } while (--len > 0);
1191     return res >> 1;
1192 }
1193 
1194 /* ===========================================================================
1195  * Flush the bit buffer, keeping at most 7 bits in it.
1196  */
1197 local void bi_flush(s)
1198     deflate_state *s;
1199 {
1200     if (s->bi_valid == 16) {
1201         put_short(s, s->bi_buf);
1202         s->bi_buf = 0;
1203         s->bi_valid = 0;
1204     } else if (s->bi_valid >= 8) {
1205         put_byte(s, (Byte)s->bi_buf);
1206         s->bi_buf >>= 8;
1207         s->bi_valid -= 8;
1208     }
1209 }
1210 
1211 /* ===========================================================================
1212  * Flush the bit buffer and align the output on a byte boundary
1213  */
1214 local void bi_windup(s)
1215     deflate_state *s;
1216 {
1217     if (s->bi_valid > 8) {
1218         put_short(s, s->bi_buf);
1219     } else if (s->bi_valid > 0) {
1220         put_byte(s, (Byte)s->bi_buf);
1221     }
1222     s->bi_buf = 0;
1223     s->bi_valid = 0;
1224 #ifdef ZLIB_DEBUG
1225     s->bits_sent = (s->bits_sent+7) & ~7;
1226 #endif
1227 }