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-2024 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 #ifdef NO_INIT_GLOBAL_POINTERS
 150 #  define TCONST
 151 #else
 152 #  define TCONST const
 153 #endif
 154 
 155 local TCONST static_tree_desc static_l_desc =
 156 {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
 157 
 158 local TCONST static_tree_desc static_d_desc =
 159 {static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
 160 
 161 local TCONST static_tree_desc static_bl_desc =
 162 {(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
 163 
 164 /* ===========================================================================
 165  * Output a short LSB first on the stream.
 166  * IN assertion: there is enough room in pendingBuf.
 167  */
 168 #define put_short(s, w) { \
 169     put_byte(s, (uch)((w) & 0xff)); \
 170     put_byte(s, (uch)((ush)(w) >> 8)); \
 171 }
 172 
 173 /* ===========================================================================
 174  * Reverse the first len bits of a code, using straightforward code (a faster
 175  * method would use a table)
 176  * IN assertion: 1 <= len <= 15
 177  */
 178 local unsigned bi_reverse(unsigned code, int len) {
 179     register unsigned res = 0;
 180     do {
 181         res |= code & 1;
 182         code >>= 1, res <<= 1;
 183     } while (--len > 0);
 184     return res >> 1;
 185 }
 186 
 187 /* ===========================================================================
 188  * Flush the bit buffer, keeping at most 7 bits in it.
 189  */
 190 local void bi_flush(deflate_state *s) {
 191     if (s->bi_valid == 16) {
 192         put_short(s, s->bi_buf);
 193         s->bi_buf = 0;
 194         s->bi_valid = 0;
 195     } else if (s->bi_valid >= 8) {
 196         put_byte(s, (Byte)s->bi_buf);
 197         s->bi_buf >>= 8;
 198         s->bi_valid -= 8;
 199     }
 200 }
 201 
 202 /* ===========================================================================
 203  * Flush the bit buffer and align the output on a byte boundary
 204  */
 205 local void bi_windup(deflate_state *s) {
 206     if (s->bi_valid > 8) {
 207         put_short(s, s->bi_buf);
 208     } else if (s->bi_valid > 0) {
 209         put_byte(s, (Byte)s->bi_buf);
 210     }
 211     s->bi_buf = 0;
 212     s->bi_valid = 0;
 213 #ifdef ZLIB_DEBUG
 214     s->bits_sent = (s->bits_sent + 7) & ~7;
 215 #endif
 216 }
 217 
 218 /* ===========================================================================
 219  * Generate the codes for a given tree and bit counts (which need not be
 220  * optimal).
 221  * IN assertion: the array bl_count contains the bit length statistics for
 222  * the given tree and the field len is set for all tree elements.
 223  * OUT assertion: the field code is set for all tree elements of non
 224  *     zero code length.
 225  */
 226 local void gen_codes(ct_data *tree, int max_code, ushf *bl_count) {
 227     ush next_code[MAX_BITS+1]; /* next code value for each bit length */
 228     unsigned code = 0;         /* running code value */
 229     int bits;                  /* bit index */
 230     int n;                     /* code index */
 231 
 232     /* The distribution counts are first used to generate the code values
 233      * without bit reversal.
 234      */
 235     for (bits = 1; bits <= MAX_BITS; bits++) {
 236         code = (code + bl_count[bits - 1]) << 1;
 237         next_code[bits] = (ush)code;
 238     }
 239     /* Check that the bit counts in bl_count are consistent. The last code
 240      * must be all ones.
 241      */
 242     Assert (code + bl_count[MAX_BITS] - 1 == (1 << MAX_BITS) - 1,
 243             "inconsistent bit counts");
 244     Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
 245 
 246     for (n = 0;  n <= max_code; n++) {
 247         int len = tree[n].Len;
 248         if (len == 0) continue;
 249         /* Now reverse the bits */
 250         tree[n].Code = (ush)bi_reverse(next_code[len]++, len);
 251 
 252         Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
 253             n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len] - 1));
 254     }
 255 }
 256 
 257 #ifdef GEN_TREES_H
 258 local void gen_trees_header(void);
 259 #endif
 260 
 261 #ifndef ZLIB_DEBUG
 262 #  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
 263    /* Send a code of the given tree. c and tree must not have side effects */
 264 
 265 #else /* !ZLIB_DEBUG */
 266 #  define send_code(s, c, tree) \
 267      { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
 268        send_bits(s, tree[c].Code, tree[c].Len); }
 269 #endif
 270 
 271 /* ===========================================================================
 272  * Send a value on a given number of bits.
 273  * IN assertion: length <= 16 and value fits in length bits.
 274  */
 275 #ifdef ZLIB_DEBUG
 276 local void send_bits(deflate_state *s, int value, int length) {
 277     Tracevv((stderr," l %2d v %4x ", length, value));
 278     Assert(length > 0 && length <= 15, "invalid length");
 279     s->bits_sent += (ulg)length;
 280 
 281     /* If not enough room in bi_buf, use (valid) bits from bi_buf and
 282      * (16 - bi_valid) bits from value, leaving (width - (16 - bi_valid))
 283      * unused bits in value.
 284      */
 285     if (s->bi_valid > (int)Buf_size - length) {
 286         s->bi_buf |= (ush)value << s->bi_valid;
 287         put_short(s, s->bi_buf);
 288         s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
 289         s->bi_valid += length - Buf_size;
 290     } else {
 291         s->bi_buf |= (ush)value << s->bi_valid;
 292         s->bi_valid += length;
 293     }
 294 }
 295 #else /* !ZLIB_DEBUG */
 296 
 297 #define send_bits(s, value, length) \
 298 { int len = length;\
 299   if (s->bi_valid > (int)Buf_size - len) {\
 300     int val = (int)value;\
 301     s->bi_buf |= (ush)val << s->bi_valid;\
 302     put_short(s, s->bi_buf);\
 303     s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
 304     s->bi_valid += len - Buf_size;\
 305   } else {\
 306     s->bi_buf |= (ush)(value) << s->bi_valid;\
 307     s->bi_valid += len;\
 308   }\
 309 }
 310 #endif /* ZLIB_DEBUG */
 311 
 312 
 313 /* the arguments must not have side effects */
 314 
 315 /* ===========================================================================
 316  * Initialize the various 'constant' tables.
 317  */
 318 local void tr_static_init(void) {
 319 #if defined(GEN_TREES_H) || !defined(STDC)
 320     static int static_init_done = 0;
 321     int n;        /* iterates over tree elements */
 322     int bits;     /* bit counter */
 323     int length;   /* length value */
 324     int code;     /* code value */
 325     int dist;     /* distance index */
 326     ush bl_count[MAX_BITS+1];
 327     /* number of codes at each bit length for an optimal tree */
 328 
 329     if (static_init_done) return;
 330 
 331     /* For some embedded targets, global variables are not initialized: */
 332 #ifdef NO_INIT_GLOBAL_POINTERS
 333     static_l_desc.static_tree = static_ltree;
 334     static_l_desc.extra_bits = extra_lbits;
 335     static_d_desc.static_tree = static_dtree;
 336     static_d_desc.extra_bits = extra_dbits;
 337     static_bl_desc.extra_bits = extra_blbits;
 338 #endif
 339 
 340     /* Initialize the mapping length (0..255) -> length code (0..28) */
 341     length = 0;
 342     for (code = 0; code < LENGTH_CODES-1; code++) {
 343         base_length[code] = length;
 344         for (n = 0; n < (1 << extra_lbits[code]); n++) {
 345             _length_code[length++] = (uch)code;
 346         }
 347     }
 348     Assert (length == 256, "tr_static_init: length != 256");
 349     /* Note that the length 255 (match length 258) can be represented
 350      * in two different ways: code 284 + 5 bits or code 285, so we
 351      * overwrite length_code[255] to use the best encoding:
 352      */
 353     _length_code[length - 1] = (uch)code;
 354 
 355     /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
 356     dist = 0;
 357     for (code = 0 ; code < 16; code++) {
 358         base_dist[code] = dist;
 359         for (n = 0; n < (1 << extra_dbits[code]); n++) {
 360             _dist_code[dist++] = (uch)code;
 361         }
 362     }
 363     Assert (dist == 256, "tr_static_init: dist != 256");
 364     dist >>= 7; /* from now on, all distances are divided by 128 */
 365     for ( ; code < D_CODES; code++) {
 366         base_dist[code] = dist << 7;
 367         for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
 368             _dist_code[256 + dist++] = (uch)code;
 369         }
 370     }
 371     Assert (dist == 256, "tr_static_init: 256 + dist != 512");
 372 
 373     /* Construct the codes of the static literal tree */
 374     for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
 375     n = 0;
 376     while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
 377     while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
 378     while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
 379     while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
 380     /* Codes 286 and 287 do not exist, but we must include them in the
 381      * tree construction to get a canonical Huffman tree (longest code
 382      * all ones)
 383      */
 384     gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
 385 
 386     /* The static distance tree is trivial: */
 387     for (n = 0; n < D_CODES; n++) {
 388         static_dtree[n].Len = 5;
 389         static_dtree[n].Code = bi_reverse((unsigned)n, 5);
 390     }
 391     static_init_done = 1;
 392 
 393 #  ifdef GEN_TREES_H
 394     gen_trees_header();
 395 #  endif
 396 #endif /* defined(GEN_TREES_H) || !defined(STDC) */
 397 }
 398 
 399 /* ===========================================================================
 400  * Generate the file trees.h describing the static trees.
 401  */
 402 #ifdef GEN_TREES_H
 403 #  ifndef ZLIB_DEBUG
 404 #    include <stdio.h>
 405 #  endif
 406 
 407 #  define SEPARATOR(i, last, width) \
 408       ((i) == (last)? "\n};\n\n" :    \
 409        ((i) % (width) == (width) - 1 ? ",\n" : ", "))
 410 
 411 void gen_trees_header(void) {
 412     FILE *header = fopen("trees.h", "w");
 413     int i;
 414 
 415     Assert (header != NULL, "Can't open trees.h");
 416     fprintf(header,
 417             "/* header created automatically with -DGEN_TREES_H */\n\n");
 418 
 419     fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
 420     for (i = 0; i < L_CODES+2; i++) {
 421         fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
 422                 static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
 423     }
 424 
 425     fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
 426     for (i = 0; i < D_CODES; i++) {
 427         fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
 428                 static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
 429     }
 430 
 431     fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
 432     for (i = 0; i < DIST_CODE_LEN; i++) {
 433         fprintf(header, "%2u%s", _dist_code[i],
 434                 SEPARATOR(i, DIST_CODE_LEN-1, 20));
 435     }
 436 
 437     fprintf(header,
 438         "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
 439     for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
 440         fprintf(header, "%2u%s", _length_code[i],
 441                 SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
 442     }
 443 
 444     fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
 445     for (i = 0; i < LENGTH_CODES; i++) {
 446         fprintf(header, "%1u%s", base_length[i],
 447                 SEPARATOR(i, LENGTH_CODES-1, 20));
 448     }
 449 
 450     fprintf(header, "local const int base_dist[D_CODES] = {\n");
 451     for (i = 0; i < D_CODES; i++) {
 452         fprintf(header, "%5u%s", base_dist[i],
 453                 SEPARATOR(i, D_CODES-1, 10));
 454     }
 455 
 456     fclose(header);
 457 }
 458 #endif /* GEN_TREES_H */
 459 
 460 /* ===========================================================================
 461  * Initialize a new block.
 462  */
 463 local void init_block(deflate_state *s) {
 464     int n; /* iterates over tree elements */
 465 
 466     /* Initialize the trees. */
 467     for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
 468     for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
 469     for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
 470 
 471     s->dyn_ltree[END_BLOCK].Freq = 1;
 472     s->opt_len = s->static_len = 0L;
 473     s->sym_next = s->matches = 0;
 474 }
 475 
 476 /* ===========================================================================
 477  * Initialize the tree data structures for a new zlib stream.
 478  */
 479 void ZLIB_INTERNAL _tr_init(deflate_state *s) {
 480     tr_static_init();
 481 
 482     s->l_desc.dyn_tree = s->dyn_ltree;
 483     s->l_desc.stat_desc = &static_l_desc;
 484 
 485     s->d_desc.dyn_tree = s->dyn_dtree;
 486     s->d_desc.stat_desc = &static_d_desc;
 487 
 488     s->bl_desc.dyn_tree = s->bl_tree;
 489     s->bl_desc.stat_desc = &static_bl_desc;
 490 
 491     s->bi_buf = 0;
 492     s->bi_valid = 0;
 493 #ifdef ZLIB_DEBUG
 494     s->compressed_len = 0L;
 495     s->bits_sent = 0L;
 496 #endif
 497 
 498     /* Initialize the first block of the first file: */
 499     init_block(s);
 500 }
 501 
 502 #define SMALLEST 1
 503 /* Index within the heap array of least frequent node in the Huffman tree */
 504 
 505 
 506 /* ===========================================================================
 507  * Remove the smallest element from the heap and recreate the heap with
 508  * one less element. Updates heap and heap_len.
 509  */
 510 #define pqremove(s, tree, top) \
 511 {\
 512     top = s->heap[SMALLEST]; \
 513     s->heap[SMALLEST] = s->heap[s->heap_len--]; \
 514     pqdownheap(s, tree, SMALLEST); \
 515 }
 516 
 517 /* ===========================================================================
 518  * Compares to subtrees, using the tree depth as tie breaker when
 519  * the subtrees have equal frequency. This minimizes the worst case length.
 520  */
 521 #define smaller(tree, n, m, depth) \
 522    (tree[n].Freq < tree[m].Freq || \
 523    (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
 524 
 525 /* ===========================================================================
 526  * Restore the heap property by moving down the tree starting at node k,
 527  * exchanging a node with the smallest of its two sons if necessary, stopping
 528  * when the heap property is re-established (each father smaller than its
 529  * two sons).
 530  */
 531 local void pqdownheap(deflate_state *s, ct_data *tree, int k) {
 532     int v = s->heap[k];
 533     int j = k << 1;  /* left son of k */
 534     while (j <= s->heap_len) {
 535         /* Set j to the smallest of the two sons: */
 536         if (j < s->heap_len &&
 537             smaller(tree, s->heap[j + 1], s->heap[j], s->depth)) {
 538             j++;
 539         }
 540         /* Exit if v is smaller than both sons */
 541         if (smaller(tree, v, s->heap[j], s->depth)) break;
 542 
 543         /* Exchange v with the smallest son */
 544         s->heap[k] = s->heap[j];  k = j;
 545 
 546         /* And continue down the tree, setting j to the left son of k */
 547         j <<= 1;
 548     }
 549     s->heap[k] = v;
 550 }
 551 
 552 /* ===========================================================================
 553  * Compute the optimal bit lengths for a tree and update the total bit length
 554  * for the current block.
 555  * IN assertion: the fields freq and dad are set, heap[heap_max] and
 556  *    above are the tree nodes sorted by increasing frequency.
 557  * OUT assertions: the field len is set to the optimal bit length, the
 558  *     array bl_count contains the frequencies for each bit length.
 559  *     The length opt_len is updated; static_len is also updated if stree is
 560  *     not null.
 561  */
 562 local void gen_bitlen(deflate_state *s, tree_desc *desc) {
 563     ct_data *tree        = desc->dyn_tree;
 564     int max_code         = desc->max_code;
 565     const ct_data *stree = desc->stat_desc->static_tree;
 566     const intf *extra    = desc->stat_desc->extra_bits;
 567     int base             = desc->stat_desc->extra_base;
 568     int max_length       = desc->stat_desc->max_length;
 569     int h;              /* heap index */
 570     int n, m;           /* iterate over the tree elements */
 571     int bits;           /* bit length */
 572     int xbits;          /* extra bits */
 573     ush f;              /* frequency */
 574     int overflow = 0;   /* number of elements with bit length too large */
 575 
 576     for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
 577 
 578     /* In a first pass, compute the optimal bit lengths (which may
 579      * overflow in the case of the bit length tree).
 580      */
 581     tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
 582 
 583     for (h = s->heap_max + 1; h < HEAP_SIZE; h++) {
 584         n = s->heap[h];
 585         bits = tree[tree[n].Dad].Len + 1;
 586         if (bits > max_length) bits = max_length, overflow++;
 587         tree[n].Len = (ush)bits;
 588         /* We overwrite tree[n].Dad which is no longer needed */
 589 
 590         if (n > max_code) continue; /* not a leaf node */
 591 
 592         s->bl_count[bits]++;
 593         xbits = 0;
 594         if (n >= base) xbits = extra[n - base];
 595         f = tree[n].Freq;
 596         s->opt_len += (ulg)f * (unsigned)(bits + xbits);
 597         if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits);
 598     }
 599     if (overflow == 0) return;
 600 
 601     Tracev((stderr,"\nbit length overflow\n"));
 602     /* This happens for example on obj2 and pic of the Calgary corpus */
 603 
 604     /* Find the first bit length which could increase: */
 605     do {
 606         bits = max_length - 1;
 607         while (s->bl_count[bits] == 0) bits--;
 608         s->bl_count[bits]--;        /* move one leaf down the tree */
 609         s->bl_count[bits + 1] += 2; /* move one overflow item as its brother */
 610         s->bl_count[max_length]--;
 611         /* The brother of the overflow item also moves one step up,
 612          * but this does not affect bl_count[max_length]
 613          */
 614         overflow -= 2;
 615     } while (overflow > 0);
 616 
 617     /* Now recompute all bit lengths, scanning in increasing frequency.
 618      * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
 619      * lengths instead of fixing only the wrong ones. This idea is taken
 620      * from 'ar' written by Haruhiko Okumura.)
 621      */
 622     for (bits = max_length; bits != 0; bits--) {
 623         n = s->bl_count[bits];
 624         while (n != 0) {
 625             m = s->heap[--h];
 626             if (m > max_code) continue;
 627             if ((unsigned) tree[m].Len != (unsigned) bits) {
 628                 Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
 629                 s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq;
 630                 tree[m].Len = (ush)bits;
 631             }
 632             n--;
 633         }
 634     }
 635 }
 636 
 637 #ifdef DUMP_BL_TREE
 638 #  include <stdio.h>
 639 #endif
 640 
 641 /* ===========================================================================
 642  * Construct one Huffman tree and assigns the code bit strings and lengths.
 643  * Update the total bit length for the current block.
 644  * IN assertion: the field freq is set for all tree elements.
 645  * OUT assertions: the fields len and code are set to the optimal bit length
 646  *     and corresponding code. The length opt_len is updated; static_len is
 647  *     also updated if stree is not null. The field max_code is set.
 648  */
 649 local void build_tree(deflate_state *s, tree_desc *desc) {
 650     ct_data *tree         = desc->dyn_tree;
 651     const ct_data *stree  = desc->stat_desc->static_tree;
 652     int elems             = desc->stat_desc->elems;
 653     int n, m;          /* iterate over heap elements */
 654     int max_code = -1; /* largest code with non zero frequency */
 655     int node;          /* new node being created */
 656 
 657     /* Construct the initial heap, with least frequent element in
 658      * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n + 1].
 659      * heap[0] is not used.
 660      */
 661     s->heap_len = 0, s->heap_max = HEAP_SIZE;
 662 
 663     for (n = 0; n < elems; n++) {
 664         if (tree[n].Freq != 0) {
 665             s->heap[++(s->heap_len)] = max_code = n;
 666             s->depth[n] = 0;
 667         } else {
 668             tree[n].Len = 0;
 669         }
 670     }
 671 
 672     /* The pkzip format requires that at least one distance code exists,
 673      * and that at least one bit should be sent even if there is only one
 674      * possible code. So to avoid special checks later on we force at least
 675      * two codes of non zero frequency.
 676      */
 677     while (s->heap_len < 2) {
 678         node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
 679         tree[node].Freq = 1;
 680         s->depth[node] = 0;
 681         s->opt_len--; if (stree) s->static_len -= stree[node].Len;
 682         /* node is 0 or 1 so it does not have extra bits */
 683     }
 684     desc->max_code = max_code;
 685 
 686     /* The elements heap[heap_len/2 + 1 .. heap_len] are leaves of the tree,
 687      * establish sub-heaps of increasing lengths:
 688      */
 689     for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
 690 
 691     /* Construct the Huffman tree by repeatedly combining the least two
 692      * frequent nodes.
 693      */
 694     node = elems;              /* next internal node of the tree */
 695     do {
 696         pqremove(s, tree, n);  /* n = node of least frequency */
 697         m = s->heap[SMALLEST]; /* m = node of next least frequency */
 698 
 699         s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
 700         s->heap[--(s->heap_max)] = m;
 701 
 702         /* Create a new node father of n and m */
 703         tree[node].Freq = tree[n].Freq + tree[m].Freq;
 704         s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
 705                                 s->depth[n] : s->depth[m]) + 1);
 706         tree[n].Dad = tree[m].Dad = (ush)node;
 707 #ifdef DUMP_BL_TREE
 708         if (tree == s->bl_tree) {
 709             fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
 710                     node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
 711         }
 712 #endif
 713         /* and insert the new node in the heap */
 714         s->heap[SMALLEST] = node++;
 715         pqdownheap(s, tree, SMALLEST);
 716 
 717     } while (s->heap_len >= 2);
 718 
 719     s->heap[--(s->heap_max)] = s->heap[SMALLEST];
 720 
 721     /* At this point, the fields freq and dad are set. We can now
 722      * generate the bit lengths.
 723      */
 724     gen_bitlen(s, (tree_desc *)desc);
 725 
 726     /* The field len is now set, we can generate the bit codes */
 727     gen_codes ((ct_data *)tree, max_code, s->bl_count);
 728 }
 729 
 730 /* ===========================================================================
 731  * Scan a literal or distance tree to determine the frequencies of the codes
 732  * in the bit length tree.
 733  */
 734 local void scan_tree(deflate_state *s, ct_data *tree, int max_code) {
 735     int n;                     /* iterates over all tree elements */
 736     int prevlen = -1;          /* last emitted length */
 737     int curlen;                /* length of current code */
 738     int nextlen = tree[0].Len; /* length of next code */
 739     int count = 0;             /* repeat count of the current code */
 740     int max_count = 7;         /* max repeat count */
 741     int min_count = 4;         /* min repeat count */
 742 
 743     if (nextlen == 0) max_count = 138, min_count = 3;
 744     tree[max_code + 1].Len = (ush)0xffff; /* guard */
 745 
 746     for (n = 0; n <= max_code; n++) {
 747         curlen = nextlen; nextlen = tree[n + 1].Len;
 748         if (++count < max_count && curlen == nextlen) {
 749             continue;
 750         } else if (count < min_count) {
 751             s->bl_tree[curlen].Freq += count;
 752         } else if (curlen != 0) {
 753             if (curlen != prevlen) s->bl_tree[curlen].Freq++;
 754             s->bl_tree[REP_3_6].Freq++;
 755         } else if (count <= 10) {
 756             s->bl_tree[REPZ_3_10].Freq++;
 757         } else {
 758             s->bl_tree[REPZ_11_138].Freq++;
 759         }
 760         count = 0; prevlen = curlen;
 761         if (nextlen == 0) {
 762             max_count = 138, min_count = 3;
 763         } else if (curlen == nextlen) {
 764             max_count = 6, min_count = 3;
 765         } else {
 766             max_count = 7, min_count = 4;
 767         }
 768     }
 769 }
 770 
 771 /* ===========================================================================
 772  * Send a literal or distance tree in compressed form, using the codes in
 773  * bl_tree.
 774  */
 775 local void send_tree(deflate_state *s, ct_data *tree, int max_code) {
 776     int n;                     /* iterates over all tree elements */
 777     int prevlen = -1;          /* last emitted length */
 778     int curlen;                /* length of current code */
 779     int nextlen = tree[0].Len; /* length of next code */
 780     int count = 0;             /* repeat count of the current code */
 781     int max_count = 7;         /* max repeat count */
 782     int min_count = 4;         /* min repeat count */
 783 
 784     /* tree[max_code + 1].Len = -1; */  /* guard already set */
 785     if (nextlen == 0) max_count = 138, min_count = 3;
 786 
 787     for (n = 0; n <= max_code; n++) {
 788         curlen = nextlen; nextlen = tree[n + 1].Len;
 789         if (++count < max_count && curlen == nextlen) {
 790             continue;
 791         } else if (count < min_count) {
 792             do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
 793 
 794         } else if (curlen != 0) {
 795             if (curlen != prevlen) {
 796                 send_code(s, curlen, s->bl_tree); count--;
 797             }
 798             Assert(count >= 3 && count <= 6, " 3_6?");
 799             send_code(s, REP_3_6, s->bl_tree); send_bits(s, count - 3, 2);
 800 
 801         } else if (count <= 10) {
 802             send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count - 3, 3);
 803 
 804         } else {
 805             send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count - 11, 7);
 806         }
 807         count = 0; prevlen = curlen;
 808         if (nextlen == 0) {
 809             max_count = 138, min_count = 3;
 810         } else if (curlen == nextlen) {
 811             max_count = 6, min_count = 3;
 812         } else {
 813             max_count = 7, min_count = 4;
 814         }
 815     }
 816 }
 817 
 818 /* ===========================================================================
 819  * Construct the Huffman tree for the bit lengths and return the index in
 820  * bl_order of the last bit length code to send.
 821  */
 822 local int build_bl_tree(deflate_state *s) {
 823     int max_blindex;  /* index of last bit length code of non zero freq */
 824 
 825     /* Determine the bit length frequencies for literal and distance trees */
 826     scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
 827     scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
 828 
 829     /* Build the bit length tree: */
 830     build_tree(s, (tree_desc *)(&(s->bl_desc)));
 831     /* opt_len now includes the length of the tree representations, except the
 832      * lengths of the bit lengths codes and the 5 + 5 + 4 bits for the counts.
 833      */
 834 
 835     /* Determine the number of bit length codes to send. The pkzip format
 836      * requires that at least 4 bit length codes be sent. (appnote.txt says
 837      * 3 but the actual value used is 4.)
 838      */
 839     for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
 840         if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
 841     }
 842     /* Update opt_len to include the bit length tree and counts */
 843     s->opt_len += 3*((ulg)max_blindex + 1) + 5 + 5 + 4;
 844     Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
 845             s->opt_len, s->static_len));
 846 
 847     return max_blindex;
 848 }
 849 
 850 /* ===========================================================================
 851  * Send the header for a block using dynamic Huffman trees: the counts, the
 852  * lengths of the bit length codes, the literal tree and the distance tree.
 853  * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
 854  */
 855 local void send_all_trees(deflate_state *s, int lcodes, int dcodes,
 856                           int blcodes) {
 857     int rank;                    /* index in bl_order */
 858 
 859     Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
 860     Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
 861             "too many codes");
 862     Tracev((stderr, "\nbl counts: "));
 863     send_bits(s, lcodes - 257, 5);  /* not +255 as stated in appnote.txt */
 864     send_bits(s, dcodes - 1,   5);
 865     send_bits(s, blcodes - 4,  4);  /* not -3 as stated in appnote.txt */
 866     for (rank = 0; rank < blcodes; rank++) {
 867         Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
 868         send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
 869     }
 870     Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
 871 
 872     send_tree(s, (ct_data *)s->dyn_ltree, lcodes - 1);  /* literal tree */
 873     Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
 874 
 875     send_tree(s, (ct_data *)s->dyn_dtree, dcodes - 1);  /* distance tree */
 876     Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
 877 }
 878 
 879 /* ===========================================================================
 880  * Send a stored block
 881  */
 882 void ZLIB_INTERNAL _tr_stored_block(deflate_state *s, charf *buf,
 883                                     ulg stored_len, int last) {
 884     send_bits(s, (STORED_BLOCK<<1) + last, 3);  /* send block type */
 885     bi_windup(s);        /* align on byte boundary */
 886     put_short(s, (ush)stored_len);
 887     put_short(s, (ush)~stored_len);
 888     if (stored_len)
 889         zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len);
 890     s->pending += stored_len;
 891 #ifdef ZLIB_DEBUG
 892     s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
 893     s->compressed_len += (stored_len + 4) << 3;
 894     s->bits_sent += 2*16;
 895     s->bits_sent += stored_len << 3;
 896 #endif
 897 }
 898 
 899 /* ===========================================================================
 900  * Flush the bits in the bit buffer to pending output (leaves at most 7 bits)
 901  */
 902 void ZLIB_INTERNAL _tr_flush_bits(deflate_state *s) {
 903     bi_flush(s);
 904 }
 905 
 906 /* ===========================================================================
 907  * Send one empty static block to give enough lookahead for inflate.
 908  * This takes 10 bits, of which 7 may remain in the bit buffer.
 909  */
 910 void ZLIB_INTERNAL _tr_align(deflate_state *s) {
 911     send_bits(s, STATIC_TREES<<1, 3);
 912     send_code(s, END_BLOCK, static_ltree);
 913 #ifdef ZLIB_DEBUG
 914     s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
 915 #endif
 916     bi_flush(s);
 917 }
 918 
 919 /* ===========================================================================
 920  * Send the block data compressed using the given Huffman trees
 921  */
 922 local void compress_block(deflate_state *s, const ct_data *ltree,
 923                           const ct_data *dtree) {
 924     unsigned dist;      /* distance of matched string */
 925     int lc;             /* match length or unmatched char (if dist == 0) */
 926     unsigned sx = 0;    /* running index in symbol buffers */
 927     unsigned code;      /* the code to send */
 928     int extra;          /* number of extra bits to send */
 929 
 930     if (s->sym_next != 0) do {
 931 #ifdef LIT_MEM
 932         dist = s->d_buf[sx];
 933         lc = s->l_buf[sx++];
 934 #else
 935         dist = s->sym_buf[sx++] & 0xff;
 936         dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8;
 937         lc = s->sym_buf[sx++];
 938 #endif
 939         if (dist == 0) {
 940             send_code(s, lc, ltree); /* send a literal byte */
 941             Tracecv(isgraph(lc), (stderr," '%c' ", lc));
 942         } else {
 943             /* Here, lc is the match length - MIN_MATCH */
 944             code = _length_code[lc];
 945             send_code(s, code + LITERALS + 1, ltree);   /* send length code */
 946             extra = extra_lbits[code];
 947             if (extra != 0) {
 948                 lc -= base_length[code];
 949                 send_bits(s, lc, extra);       /* send the extra length bits */
 950             }
 951             dist--; /* dist is now the match distance - 1 */
 952             code = d_code(dist);
 953             Assert (code < D_CODES, "bad d_code");
 954 
 955             send_code(s, code, dtree);       /* send the distance code */
 956             extra = extra_dbits[code];
 957             if (extra != 0) {
 958                 dist -= (unsigned)base_dist[code];
 959                 send_bits(s, dist, extra);   /* send the extra distance bits */
 960             }
 961         } /* literal or match pair ? */
 962 
 963         /* Check for no overlay of pending_buf on needed symbols */
 964 #ifdef LIT_MEM
 965         Assert(s->pending < 2 * (s->lit_bufsize + sx), "pendingBuf overflow");
 966 #else
 967         Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow");
 968 #endif
 969 
 970     } while (sx < s->sym_next);
 971 
 972     send_code(s, END_BLOCK, ltree);
 973 }
 974 
 975 /* ===========================================================================
 976  * Check if the data type is TEXT or BINARY, using the following algorithm:
 977  * - TEXT if the two conditions below are satisfied:
 978  *    a) There are no non-portable control characters belonging to the
 979  *       "block list" (0..6, 14..25, 28..31).
 980  *    b) There is at least one printable character belonging to the
 981  *       "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
 982  * - BINARY otherwise.
 983  * - The following partially-portable control characters form a
 984  *   "gray list" that is ignored in this detection algorithm:
 985  *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
 986  * IN assertion: the fields Freq of dyn_ltree are set.
 987  */
 988 local int detect_data_type(deflate_state *s) {
 989     /* block_mask is the bit mask of block-listed bytes
 990      * set bits 0..6, 14..25, and 28..31
 991      * 0xf3ffc07f = binary 11110011111111111100000001111111
 992      */
 993     unsigned long block_mask = 0xf3ffc07fUL;
 994     int n;
 995 
 996     /* Check for non-textual ("block-listed") bytes. */
 997     for (n = 0; n <= 31; n++, block_mask >>= 1)
 998         if ((block_mask & 1) && (s->dyn_ltree[n].Freq != 0))
 999             return Z_BINARY;
1000 
1001     /* Check for textual ("allow-listed") bytes. */
1002     if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
1003             || s->dyn_ltree[13].Freq != 0)
1004         return Z_TEXT;
1005     for (n = 32; n < LITERALS; n++)
1006         if (s->dyn_ltree[n].Freq != 0)
1007             return Z_TEXT;
1008 
1009     /* There are no "block-listed" or "allow-listed" bytes:
1010      * this stream either is empty or has tolerated ("gray-listed") bytes only.
1011      */
1012     return Z_BINARY;
1013 }
1014 
1015 /* ===========================================================================
1016  * Determine the best encoding for the current block: dynamic trees, static
1017  * trees or store, and write out the encoded block.
1018  */
1019 void ZLIB_INTERNAL _tr_flush_block(deflate_state *s, charf *buf,
1020                                    ulg stored_len, int last) {
1021     ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
1022     int max_blindex = 0;  /* index of last bit length code of non zero freq */
1023 
1024     /* Build the Huffman trees unless a stored block is forced */
1025     if (s->level > 0) {
1026 
1027         /* Check if the file is binary or text */
1028         if (s->strm->data_type == Z_UNKNOWN)
1029             s->strm->data_type = detect_data_type(s);
1030 
1031         /* Construct the literal and distance trees */
1032         build_tree(s, (tree_desc *)(&(s->l_desc)));
1033         Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
1034                 s->static_len));
1035 
1036         build_tree(s, (tree_desc *)(&(s->d_desc)));
1037         Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
1038                 s->static_len));
1039         /* At this point, opt_len and static_len are the total bit lengths of
1040          * the compressed block data, excluding the tree representations.
1041          */
1042 
1043         /* Build the bit length tree for the above two trees, and get the index
1044          * in bl_order of the last bit length code to send.
1045          */
1046         max_blindex = build_bl_tree(s);
1047 
1048         /* Determine the best encoding. Compute the block lengths in bytes. */
1049         opt_lenb = (s->opt_len + 3 + 7) >> 3;
1050         static_lenb = (s->static_len + 3 + 7) >> 3;
1051 
1052         Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
1053                 opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
1054                 s->sym_next / 3));
1055 
1056 #ifndef FORCE_STATIC
1057         if (static_lenb <= opt_lenb || s->strategy == Z_FIXED)
1058 #endif
1059             opt_lenb = static_lenb;
1060 
1061     } else {
1062         Assert(buf != (char*)0, "lost buf");
1063         opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
1064     }
1065 
1066 #ifdef FORCE_STORED
1067     if (buf != (char*)0) { /* force stored block */
1068 #else
1069     if (stored_len + 4 <= opt_lenb && buf != (char*)0) {
1070                        /* 4: two words for the lengths */
1071 #endif
1072         /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
1073          * Otherwise we can't have processed more than WSIZE input bytes since
1074          * the last block flush, because compression would have been
1075          * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
1076          * transform a block into a stored block.
1077          */
1078         _tr_stored_block(s, buf, stored_len, last);
1079 
1080     } else if (static_lenb == opt_lenb) {
1081         send_bits(s, (STATIC_TREES<<1) + last, 3);
1082         compress_block(s, (const ct_data *)static_ltree,
1083                        (const ct_data *)static_dtree);
1084 #ifdef ZLIB_DEBUG
1085         s->compressed_len += 3 + s->static_len;
1086 #endif
1087     } else {
1088         send_bits(s, (DYN_TREES<<1) + last, 3);
1089         send_all_trees(s, s->l_desc.max_code + 1, s->d_desc.max_code + 1,
1090                        max_blindex + 1);
1091         compress_block(s, (const ct_data *)s->dyn_ltree,
1092                        (const ct_data *)s->dyn_dtree);
1093 #ifdef ZLIB_DEBUG
1094         s->compressed_len += 3 + s->opt_len;
1095 #endif
1096     }
1097     Assert (s->compressed_len == s->bits_sent, "bad compressed size");
1098     /* The above check is made mod 2^32, for files larger than 512 MB
1099      * and uLong implemented on 32 bits.
1100      */
1101     init_block(s);
1102 
1103     if (last) {
1104         bi_windup(s);
1105 #ifdef ZLIB_DEBUG
1106         s->compressed_len += 7;  /* align on byte boundary */
1107 #endif
1108     }
1109     Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len >> 3,
1110            s->compressed_len - 7*last));
1111 }
1112 
1113 /* ===========================================================================
1114  * Save the match info and tally the frequency counts. Return true if
1115  * the current block must be flushed.
1116  */
1117 int ZLIB_INTERNAL _tr_tally(deflate_state *s, unsigned dist, unsigned lc) {
1118 #ifdef LIT_MEM
1119     s->d_buf[s->sym_next] = (ush)dist;
1120     s->l_buf[s->sym_next++] = (uch)lc;
1121 #else
1122     s->sym_buf[s->sym_next++] = (uch)dist;
1123     s->sym_buf[s->sym_next++] = (uch)(dist >> 8);
1124     s->sym_buf[s->sym_next++] = (uch)lc;
1125 #endif
1126     if (dist == 0) {
1127         /* lc is the unmatched char */
1128         s->dyn_ltree[lc].Freq++;
1129     } else {
1130         s->matches++;
1131         /* Here, lc is the match length - MIN_MATCH */
1132         dist--;             /* dist = match distance - 1 */
1133         Assert((ush)dist < (ush)MAX_DIST(s) &&
1134                (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
1135                (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
1136 
1137         s->dyn_ltree[_length_code[lc] + LITERALS + 1].Freq++;
1138         s->dyn_dtree[d_code(dist)].Freq++;
1139     }
1140     return (s->sym_next == s->sym_end);
1141 }