< prev index next >

src/java.base/share/native/libzip/zlib/deflate.c

Print this page

   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 /* deflate.c -- compress data using the deflation algorithm
  26  * Copyright (C) 1995-2022 Jean-loup Gailly and Mark Adler
  27  * For conditions of distribution and use, see copyright notice in zlib.h
  28  */
  29 
  30 /*
  31  *  ALGORITHM
  32  *
  33  *      The "deflation" process depends on being able to identify portions
  34  *      of the input text which are identical to earlier input (within a
  35  *      sliding window trailing behind the input currently being processed).
  36  *
  37  *      The most straightforward technique turns out to be the fastest for
  38  *      most input files: try all possible matches and select the longest.
  39  *      The key feature of this algorithm is that insertions into the string
  40  *      dictionary are very simple and thus fast, and deletions are avoided
  41  *      completely. Insertions are performed at each input character, whereas
  42  *      string matches are performed only when the previous match ends. So it
  43  *      is preferable to spend more time in matches to allow very fast string
  44  *      insertions and avoid deletions. The matching algorithm for small
  45  *      strings is inspired from that of Rabin & Karp. A brute force approach
  46  *      is used to find longer strings when a small match has been found.

  59  *      Thanks to many people for bug reports and testing.
  60  *
  61  *  REFERENCES
  62  *
  63  *      Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  64  *      Available in http://tools.ietf.org/html/rfc1951
  65  *
  66  *      A description of the Rabin and Karp algorithm is given in the book
  67  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  68  *
  69  *      Fiala,E.R., and Greene,D.H.
  70  *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  71  *
  72  */
  73 
  74 /* @(#) $Id$ */
  75 
  76 #include "deflate.h"
  77 
  78 const char deflate_copyright[] =
  79    " deflate 1.2.13 Copyright 1995-2022 Jean-loup Gailly and Mark Adler ";
  80 /*
  81   If you use the zlib library in a product, an acknowledgment is welcome
  82   in the documentation of your product. If for some reason you cannot
  83   include such an acknowledgment, I would appreciate that you keep this
  84   copyright string in the executable of your product.
  85  */
  86 
  87 /* ===========================================================================
  88  *  Function prototypes.
  89  */
  90 typedef enum {
  91     need_more,      /* block not completed, need more input or more output */
  92     block_done,     /* block flush performed */
  93     finish_started, /* finish started, need only more output at next deflate */
  94     finish_done     /* finish done, accept no more input or output */
  95 } block_state;
  96 
  97 typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  98 /* Compression function. Returns the block state after the call. */
  99 
 100 local int deflateStateCheck      OF((z_streamp strm));
 101 local void slide_hash     OF((deflate_state *s));
 102 local void fill_window    OF((deflate_state *s));
 103 local block_state deflate_stored OF((deflate_state *s, int flush));
 104 local block_state deflate_fast   OF((deflate_state *s, int flush));
 105 #ifndef FASTEST
 106 local block_state deflate_slow   OF((deflate_state *s, int flush));
 107 #endif
 108 local block_state deflate_rle    OF((deflate_state *s, int flush));
 109 local block_state deflate_huff   OF((deflate_state *s, int flush));
 110 local void lm_init        OF((deflate_state *s));
 111 local void putShortMSB    OF((deflate_state *s, uInt b));
 112 local void flush_pending  OF((z_streamp strm));
 113 local unsigned read_buf   OF((z_streamp strm, Bytef *buf, unsigned size));
 114 local uInt longest_match  OF((deflate_state *s, IPos cur_match));
 115 
 116 #ifdef ZLIB_DEBUG
 117 local  void check_match OF((deflate_state *s, IPos start, IPos match,
 118                             int length));
 119 #endif


 120 
 121 /* ===========================================================================
 122  * Local data
 123  */
 124 
 125 #define NIL 0
 126 /* Tail of hash chains */
 127 
 128 #ifndef TOO_FAR
 129 #  define TOO_FAR 4096
 130 #endif
 131 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
 132 
 133 /* Values for max_lazy_match, good_match and max_chain_length, depending on
 134  * the desired pack level (0..9). The values given below have been tuned to
 135  * exclude worst case performance for pathological files. Better values may be
 136  * found for specific files.
 137  */
 138 typedef struct config_s {
 139    ush good_length; /* reduce lazy search above this match length */

 202     match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
 203     s->head[s->ins_h] = (Pos)(str))
 204 #endif
 205 
 206 /* ===========================================================================
 207  * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
 208  * prev[] will be initialized on the fly.
 209  */
 210 #define CLEAR_HASH(s) \
 211     do { \
 212         s->head[s->hash_size - 1] = NIL; \
 213         zmemzero((Bytef *)s->head, \
 214                  (unsigned)(s->hash_size - 1)*sizeof(*s->head)); \
 215     } while (0)
 216 
 217 /* ===========================================================================
 218  * Slide the hash table when sliding the window down (could be avoided with 32
 219  * bit values at the expense of memory usage). We slide even when level == 0 to
 220  * keep the hash table consistent if we switch back to level > 0 later.
 221  */
 222 local void slide_hash(s)
 223     deflate_state *s;
 224 {



 225     unsigned n, m;
 226     Posf *p;
 227     uInt wsize = s->w_size;
 228 
 229     n = s->hash_size;
 230     p = &s->head[n];
 231     do {
 232         m = *--p;
 233         *p = (Pos)(m >= wsize ? m - wsize : NIL);
 234     } while (--n);
 235     n = wsize;
 236 #ifndef FASTEST
 237     p = &s->prev[n];
 238     do {
 239         m = *--p;
 240         *p = (Pos)(m >= wsize ? m - wsize : NIL);
 241         /* If n is not on any hash chain, prev[n] is garbage but
 242          * its value will never be used.
 243          */
 244     } while (--n);
 245 #endif
 246 }
 247 































































































































































 248 /* ========================================================================= */
 249 int ZEXPORT deflateInit_(strm, level, version, stream_size)
 250     z_streamp strm;
 251     int level;
 252     const char *version;
 253     int stream_size;
 254 {
 255     return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
 256                          Z_DEFAULT_STRATEGY, version, stream_size);
 257     /* To do: ignore strm->next_in if we use it as window */
 258 }
 259 
 260 /* ========================================================================= */
 261 int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
 262                   version, stream_size)
 263     z_streamp strm;
 264     int  level;
 265     int  method;
 266     int  windowBits;
 267     int  memLevel;
 268     int  strategy;
 269     const char *version;
 270     int stream_size;
 271 {
 272     deflate_state *s;
 273     int wrap = 1;
 274     static const char my_version[] = ZLIB_VERSION;
 275 
 276     if (version == Z_NULL || version[0] != my_version[0] ||
 277         stream_size != sizeof(z_stream)) {
 278         return Z_VERSION_ERROR;
 279     }
 280     if (strm == Z_NULL) return Z_STREAM_ERROR;
 281 
 282     strm->msg = Z_NULL;
 283     if (strm->zalloc == (alloc_func)0) {
 284 #ifdef Z_SOLO
 285         return Z_STREAM_ERROR;
 286 #else
 287         strm->zalloc = zcalloc;
 288         strm->opaque = (voidpf)0;
 289 #endif
 290     }
 291     if (strm->zfree == (free_func)0)

 366      * symbols are written.) The closest the writing gets to what is unread is
 367      * then n + 14 bits. Here n is lit_bufsize, which is 16384 by default, and
 368      * can range from 128 to 32768.
 369      *
 370      * Therefore, at a minimum, there are 142 bits of space between what is
 371      * written and what is read in the overlain buffers, so the symbols cannot
 372      * be overwritten by the compressed data. That space is actually 139 bits,
 373      * due to the three-bit fixed-code block header.
 374      *
 375      * That covers the case where either Z_FIXED is specified, forcing fixed
 376      * codes, or when the use of fixed codes is chosen, because that choice
 377      * results in a smaller compressed block than dynamic codes. That latter
 378      * condition then assures that the above analysis also covers all dynamic
 379      * blocks. A dynamic-code block will only be chosen to be emitted if it has
 380      * fewer bits than a fixed-code block would for the same set of symbols.
 381      * Therefore its average symbol length is assured to be less than 31. So
 382      * the compressed data for a dynamic block also cannot overwrite the
 383      * symbols from which it is being constructed.
 384      */
 385 
 386     s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, 4);
 387     s->pending_buf_size = (ulg)s->lit_bufsize * 4;
 388 
 389     if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
 390         s->pending_buf == Z_NULL) {
 391         s->status = FINISH_STATE;
 392         strm->msg = ERR_MSG(Z_MEM_ERROR);
 393         deflateEnd (strm);
 394         return Z_MEM_ERROR;
 395     }





 396     s->sym_buf = s->pending_buf + s->lit_bufsize;
 397     s->sym_end = (s->lit_bufsize - 1) * 3;

 398     /* We avoid equality with lit_bufsize*3 because of wraparound at 64K
 399      * on 16 bit machines and because stored blocks are restricted to
 400      * 64K-1 bytes.
 401      */
 402 
 403     s->level = level;
 404     s->strategy = strategy;
 405     s->method = (Byte)method;
 406 
 407     return deflateReset(strm);
 408 }
 409 
 410 /* =========================================================================
 411  * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
 412  */
 413 local int deflateStateCheck(strm)
 414     z_streamp strm;
 415 {
 416     deflate_state *s;
 417     if (strm == Z_NULL ||
 418         strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
 419         return 1;
 420     s = strm->state;
 421     if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE &&
 422 #ifdef GZIP
 423                                            s->status != GZIP_STATE &&
 424 #endif
 425                                            s->status != EXTRA_STATE &&
 426                                            s->status != NAME_STATE &&
 427                                            s->status != COMMENT_STATE &&
 428                                            s->status != HCRC_STATE &&
 429                                            s->status != BUSY_STATE &&
 430                                            s->status != FINISH_STATE))
 431         return 1;
 432     return 0;
 433 }
 434 
 435 /* ========================================================================= */
 436 int ZEXPORT deflateSetDictionary(strm, dictionary, dictLength)
 437     z_streamp strm;
 438     const Bytef *dictionary;
 439     uInt  dictLength;
 440 {
 441     deflate_state *s;
 442     uInt str, n;
 443     int wrap;
 444     unsigned avail;
 445     z_const unsigned char *next;
 446 
 447     if (deflateStateCheck(strm) || dictionary == Z_NULL)
 448         return Z_STREAM_ERROR;
 449     s = strm->state;
 450     wrap = s->wrap;
 451     if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
 452         return Z_STREAM_ERROR;
 453 
 454     /* when using zlib wrappers, compute Adler-32 for provided dictionary */
 455     if (wrap == 1)
 456         strm->adler = adler32(strm->adler, dictionary, dictLength);
 457     s->wrap = 0;                    /* avoid computing Adler-32 in read_buf */
 458 
 459     /* if dictionary would fill window, just replace the history */
 460     if (dictLength >= s->w_size) {

 485             s->head[s->ins_h] = (Pos)str;
 486             str++;
 487         } while (--n);
 488         s->strstart = str;
 489         s->lookahead = MIN_MATCH-1;
 490         fill_window(s);
 491     }
 492     s->strstart += s->lookahead;
 493     s->block_start = (long)s->strstart;
 494     s->insert = s->lookahead;
 495     s->lookahead = 0;
 496     s->match_length = s->prev_length = MIN_MATCH-1;
 497     s->match_available = 0;
 498     strm->next_in = next;
 499     strm->avail_in = avail;
 500     s->wrap = wrap;
 501     return Z_OK;
 502 }
 503 
 504 /* ========================================================================= */
 505 int ZEXPORT deflateGetDictionary(strm, dictionary, dictLength)
 506     z_streamp strm;
 507     Bytef *dictionary;
 508     uInt  *dictLength;
 509 {
 510     deflate_state *s;
 511     uInt len;
 512 
 513     if (deflateStateCheck(strm))
 514         return Z_STREAM_ERROR;
 515     s = strm->state;
 516     len = s->strstart + s->lookahead;
 517     if (len > s->w_size)
 518         len = s->w_size;
 519     if (dictionary != Z_NULL && len)
 520         zmemcpy(dictionary, s->window + s->strstart + s->lookahead - len, len);
 521     if (dictLength != Z_NULL)
 522         *dictLength = len;
 523     return Z_OK;
 524 }
 525 
 526 /* ========================================================================= */
 527 int ZEXPORT deflateResetKeep(strm)
 528     z_streamp strm;
 529 {
 530     deflate_state *s;
 531 
 532     if (deflateStateCheck(strm)) {
 533         return Z_STREAM_ERROR;
 534     }
 535 
 536     strm->total_in = strm->total_out = 0;
 537     strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
 538     strm->data_type = Z_UNKNOWN;
 539 
 540     s = (deflate_state *)strm->state;
 541     s->pending = 0;
 542     s->pending_out = s->pending_buf;
 543 
 544     if (s->wrap < 0) {
 545         s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
 546     }
 547     s->status =
 548 #ifdef GZIP
 549         s->wrap == 2 ? GZIP_STATE :
 550 #endif
 551         INIT_STATE;
 552     strm->adler =
 553 #ifdef GZIP
 554         s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
 555 #endif
 556         adler32(0L, Z_NULL, 0);
 557     s->last_flush = -2;
 558 
 559     _tr_init(s);
 560 
 561     return Z_OK;
 562 }
 563 
























 564 /* ========================================================================= */
 565 int ZEXPORT deflateReset(strm)
 566     z_streamp strm;
 567 {
 568     int ret;
 569 
 570     ret = deflateResetKeep(strm);
 571     if (ret == Z_OK)
 572         lm_init(strm->state);
 573     return ret;
 574 }
 575 
 576 /* ========================================================================= */
 577 int ZEXPORT deflateSetHeader(strm, head)
 578     z_streamp strm;
 579     gz_headerp head;
 580 {
 581     if (deflateStateCheck(strm) || strm->state->wrap != 2)
 582         return Z_STREAM_ERROR;
 583     strm->state->gzhead = head;
 584     return Z_OK;
 585 }
 586 
 587 /* ========================================================================= */
 588 int ZEXPORT deflatePending(strm, pending, bits)
 589     unsigned *pending;
 590     int *bits;
 591     z_streamp strm;
 592 {
 593     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
 594     if (pending != Z_NULL)
 595         *pending = strm->state->pending;
 596     if (bits != Z_NULL)
 597         *bits = strm->state->bi_valid;
 598     return Z_OK;
 599 }
 600 
 601 /* ========================================================================= */
 602 int ZEXPORT deflatePrime(strm, bits, value)
 603     z_streamp strm;
 604     int bits;
 605     int value;
 606 {
 607     deflate_state *s;
 608     int put;
 609 
 610     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
 611     s = strm->state;





 612     if (bits < 0 || bits > 16 ||
 613         s->sym_buf < s->pending_out + ((Buf_size + 7) >> 3))
 614         return Z_BUF_ERROR;

 615     do {
 616         put = Buf_size - s->bi_valid;
 617         if (put > bits)
 618             put = bits;
 619         s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);
 620         s->bi_valid += put;
 621         _tr_flush_bits(s);
 622         value >>= put;
 623         bits -= put;
 624     } while (bits);
 625     return Z_OK;
 626 }
 627 
 628 /* ========================================================================= */
 629 int ZEXPORT deflateParams(strm, level, strategy)
 630     z_streamp strm;
 631     int level;
 632     int strategy;
 633 {
 634     deflate_state *s;
 635     compress_func func;
 636 
 637     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
 638     s = strm->state;
 639 
 640 #ifdef FASTEST
 641     if (level != 0) level = 1;
 642 #else
 643     if (level == Z_DEFAULT_COMPRESSION) level = 6;
 644 #endif
 645     if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
 646         return Z_STREAM_ERROR;
 647     }
 648     func = configuration_table[s->level].func;
 649 
 650     if ((strategy != s->strategy || func != configuration_table[level].func) &&
 651         s->last_flush != -2) {
 652         /* Flush the last buffer: */
 653         int err = deflate(strm, Z_BLOCK);

 658     }
 659     if (s->level != level) {
 660         if (s->level == 0 && s->matches != 0) {
 661             if (s->matches == 1)
 662                 slide_hash(s);
 663             else
 664                 CLEAR_HASH(s);
 665             s->matches = 0;
 666         }
 667         s->level = level;
 668         s->max_lazy_match   = configuration_table[level].max_lazy;
 669         s->good_match       = configuration_table[level].good_length;
 670         s->nice_match       = configuration_table[level].nice_length;
 671         s->max_chain_length = configuration_table[level].max_chain;
 672     }
 673     s->strategy = strategy;
 674     return Z_OK;
 675 }
 676 
 677 /* ========================================================================= */
 678 int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
 679     z_streamp strm;
 680     int good_length;
 681     int max_lazy;
 682     int nice_length;
 683     int max_chain;
 684 {
 685     deflate_state *s;
 686 
 687     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
 688     s = strm->state;
 689     s->good_match = (uInt)good_length;
 690     s->max_lazy_match = (uInt)max_lazy;
 691     s->nice_match = nice_length;
 692     s->max_chain_length = (uInt)max_chain;
 693     return Z_OK;
 694 }
 695 
 696 /* =========================================================================
 697  * For the default windowBits of 15 and memLevel of 8, this function returns a
 698  * close to exact, as well as small, upper bound on the compressed size. This
 699  * is an expansion of ~0.03%, plus a small constant.
 700  *
 701  * For any setting other than those defaults for windowBits and memLevel, one
 702  * of two worst case bounds is returned. This is at most an expansion of ~4% or
 703  * ~13%, plus a small constant.
 704  *
 705  * Both the 0.03% and 4% derive from the overhead of stored blocks. The first
 706  * one is for stored blocks of 16383 bytes (memLevel == 8), whereas the second
 707  * is for stored blocks of 127 bytes (the worst case memLevel == 1). The
 708  * expansion results from five bytes of header for each stored block.
 709  *
 710  * The larger expansion of 13% results from a window size less than or equal to
 711  * the symbols buffer size (windowBits <= memLevel + 7). In that case some of
 712  * the data being compressed may have slid out of the sliding window, impeding
 713  * a stored block from being emitted. Then the only choice is a fixed or
 714  * dynamic block, where a fixed block limits the maximum expansion to 9 bits
 715  * per 8-bit byte, plus 10 bits for every block. The smallest block size for
 716  * which this can occur is 255 (memLevel == 2).
 717  *
 718  * Shifts are used to approximate divisions, for speed.
 719  */
 720 uLong ZEXPORT deflateBound(strm, sourceLen)
 721     z_streamp strm;
 722     uLong sourceLen;
 723 {
 724     deflate_state *s;
 725     uLong fixedlen, storelen, wraplen;
 726 
 727     /* upper bound for fixed blocks with 9-bit literals and length 255
 728        (memLevel == 2, which is the lowest that may not use stored blocks) --
 729        ~13% overhead plus a small constant */
 730     fixedlen = sourceLen + (sourceLen >> 3) + (sourceLen >> 8) +
 731                (sourceLen >> 9) + 4;
 732 
 733     /* upper bound for stored blocks with length 127 (memLevel == 1) --
 734        ~4% overhead plus a small constant */
 735     storelen = sourceLen + (sourceLen >> 5) + (sourceLen >> 7) +
 736                (sourceLen >> 11) + 7;
 737 
 738     /* if can't get parameters, return larger bound plus a zlib wrapper */
 739     if (deflateStateCheck(strm))
 740         return (fixedlen > storelen ? fixedlen : storelen) + 6;
 741 
 742     /* compute wrapper length */
 743     s = strm->state;

 759             if (str != Z_NULL)
 760                 do {
 761                     wraplen++;
 762                 } while (*str++);
 763             str = s->gzhead->comment;
 764             if (str != Z_NULL)
 765                 do {
 766                     wraplen++;
 767                 } while (*str++);
 768             if (s->gzhead->hcrc)
 769                 wraplen += 2;
 770         }
 771         break;
 772 #endif
 773     default:                                /* for compiler happiness */
 774         wraplen = 6;
 775     }
 776 
 777     /* if not default parameters, return one of the conservative bounds */
 778     if (s->w_bits != 15 || s->hash_bits != 8 + 7)
 779         return (s->w_bits <= s->hash_bits ? fixedlen : storelen) + wraplen;

 780 
 781     /* default settings: return tight bound for that case -- ~0.03% overhead
 782        plus a small constant */
 783     return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
 784            (sourceLen >> 25) + 13 - 6 + wraplen;
 785 }
 786 
 787 /* =========================================================================
 788  * Put a short in the pending buffer. The 16-bit value is put in MSB order.
 789  * IN assertion: the stream state is correct and there is enough room in
 790  * pending_buf.
 791  */
 792 local void putShortMSB(s, b)
 793     deflate_state *s;
 794     uInt b;
 795 {
 796     put_byte(s, (Byte)(b >> 8));
 797     put_byte(s, (Byte)(b & 0xff));
 798 }
 799 
 800 /* =========================================================================
 801  * Flush as much pending output as possible. All deflate() output, except for
 802  * some deflate_stored() output, goes through this function so some
 803  * applications may wish to modify it to avoid allocating a large
 804  * strm->next_out buffer and copying into it. (See also read_buf()).
 805  */
 806 local void flush_pending(strm)
 807     z_streamp strm;
 808 {
 809     unsigned len;
 810     deflate_state *s = strm->state;
 811 
 812     _tr_flush_bits(s);
 813     len = s->pending;
 814     if (len > strm->avail_out) len = strm->avail_out;
 815     if (len == 0) return;
 816 
 817     zmemcpy(strm->next_out, s->pending_out, len);
 818     strm->next_out  += len;
 819     s->pending_out  += len;
 820     strm->total_out += len;
 821     strm->avail_out -= len;
 822     s->pending      -= len;
 823     if (s->pending == 0) {
 824         s->pending_out = s->pending_buf;
 825     }
 826 }
 827 
 828 /* ===========================================================================
 829  * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1].
 830  */
 831 #define HCRC_UPDATE(beg) \
 832     do { \
 833         if (s->gzhead->hcrc && s->pending > (beg)) \
 834             strm->adler = crc32(strm->adler, s->pending_buf + (beg), \
 835                                 s->pending - (beg)); \
 836     } while (0)
 837 
 838 /* ========================================================================= */
 839 int ZEXPORT deflate(strm, flush)
 840     z_streamp strm;
 841     int flush;
 842 {
 843     int old_flush; /* value of flush param for previous deflate call */
 844     deflate_state *s;
 845 
 846     if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) {
 847         return Z_STREAM_ERROR;
 848     }
 849     s = strm->state;
 850 
 851     if (strm->next_out == Z_NULL ||
 852         (strm->avail_in != 0 && strm->next_in == Z_NULL) ||
 853         (s->status == FINISH_STATE && flush != Z_FINISH)) {
 854         ERR_RETURN(strm, Z_STREAM_ERROR);
 855     }
 856     if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
 857 
 858     old_flush = s->last_flush;
 859     s->last_flush = flush;
 860 
 861     /* Flush as much pending output as possible */
 862     if (s->pending != 0) {

1134         put_byte(s, (Byte)(strm->total_in & 0xff));
1135         put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
1136         put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
1137         put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
1138     }
1139     else
1140 #endif
1141     {
1142         putShortMSB(s, (uInt)(strm->adler >> 16));
1143         putShortMSB(s, (uInt)(strm->adler & 0xffff));
1144     }
1145     flush_pending(strm);
1146     /* If avail_out is zero, the application will call deflate again
1147      * to flush the rest.
1148      */
1149     if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
1150     return s->pending != 0 ? Z_OK : Z_STREAM_END;
1151 }
1152 
1153 /* ========================================================================= */
1154 int ZEXPORT deflateEnd(strm)
1155     z_streamp strm;
1156 {
1157     int status;
1158 
1159     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
1160 
1161     status = strm->state->status;
1162 
1163     /* Deallocate in reverse order of allocations: */
1164     TRY_FREE(strm, strm->state->pending_buf);
1165     TRY_FREE(strm, strm->state->head);
1166     TRY_FREE(strm, strm->state->prev);
1167     TRY_FREE(strm, strm->state->window);
1168 
1169     ZFREE(strm, strm->state);
1170     strm->state = Z_NULL;
1171 
1172     return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
1173 }
1174 
1175 /* =========================================================================
1176  * Copy the source state to the destination state.
1177  * To simplify the source, this is not supported for 16-bit MSDOS (which
1178  * doesn't have enough memory anyway to duplicate compression states).
1179  */
1180 int ZEXPORT deflateCopy(dest, source)
1181     z_streamp dest;
1182     z_streamp source;
1183 {
1184 #ifdef MAXSEG_64K


1185     return Z_STREAM_ERROR;
1186 #else
1187     deflate_state *ds;
1188     deflate_state *ss;
1189 
1190 
1191     if (deflateStateCheck(source) || dest == Z_NULL) {
1192         return Z_STREAM_ERROR;
1193     }
1194 
1195     ss = source->state;
1196 
1197     zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
1198 
1199     ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
1200     if (ds == Z_NULL) return Z_MEM_ERROR;
1201     dest->state = (struct internal_state FAR *) ds;
1202     zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));
1203     ds->strm = dest;
1204 
1205     ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
1206     ds->prev   = (Posf *)  ZALLOC(dest, ds->w_size, sizeof(Pos));
1207     ds->head   = (Posf *)  ZALLOC(dest, ds->hash_size, sizeof(Pos));
1208     ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, 4);
1209 
1210     if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
1211         ds->pending_buf == Z_NULL) {
1212         deflateEnd (dest);
1213         return Z_MEM_ERROR;
1214     }
1215     /* following zmemcpy do not work for 16-bit MSDOS */
1216     zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
1217     zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));
1218     zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));
1219     zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
1220 
1221     ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);




1222     ds->sym_buf = ds->pending_buf + ds->lit_bufsize;

1223 
1224     ds->l_desc.dyn_tree = ds->dyn_ltree;
1225     ds->d_desc.dyn_tree = ds->dyn_dtree;
1226     ds->bl_desc.dyn_tree = ds->bl_tree;
1227 
1228     return Z_OK;
1229 #endif /* MAXSEG_64K */
1230 }
1231 
1232 /* ===========================================================================
1233  * Read a new buffer from the current input stream, update the adler32
1234  * and total number of bytes read.  All deflate() input goes through
1235  * this function so some applications may wish to modify it to avoid
1236  * allocating a large strm->next_in buffer and copying from it.
1237  * (See also flush_pending()).
1238  */
1239 local unsigned read_buf(strm, buf, size)
1240     z_streamp strm;
1241     Bytef *buf;
1242     unsigned size;
1243 {
1244     unsigned len = strm->avail_in;
1245 
1246     if (len > size) len = size;
1247     if (len == 0) return 0;
1248 
1249     strm->avail_in  -= len;
1250 
1251     zmemcpy(buf, strm->next_in, len);
1252     if (strm->state->wrap == 1) {
1253         strm->adler = adler32(strm->adler, buf, len);
1254     }
1255 #ifdef GZIP
1256     else if (strm->state->wrap == 2) {
1257         strm->adler = crc32(strm->adler, buf, len);
1258     }
1259 #endif
1260     strm->next_in  += len;
1261     strm->total_in += len;
1262 
1263     return len;
1264 }
1265 
1266 /* ===========================================================================
1267  * Initialize the "longest match" routines for a new zlib stream
1268  */
1269 local void lm_init(s)
1270     deflate_state *s;
1271 {
1272     s->window_size = (ulg)2L*s->w_size;
1273 
1274     CLEAR_HASH(s);
1275 
1276     /* Set the default configuration parameters:
1277      */
1278     s->max_lazy_match   = configuration_table[s->level].max_lazy;
1279     s->good_match       = configuration_table[s->level].good_length;
1280     s->nice_match       = configuration_table[s->level].nice_length;
1281     s->max_chain_length = configuration_table[s->level].max_chain;
1282 
1283     s->strstart = 0;
1284     s->block_start = 0L;
1285     s->lookahead = 0;
1286     s->insert = 0;
1287     s->match_length = s->prev_length = MIN_MATCH-1;
1288     s->match_available = 0;
1289     s->ins_h = 0;
1290 }
1291 
1292 #ifndef FASTEST
1293 /* ===========================================================================
1294  * Set match_start to the longest match starting at the given string and
1295  * return its length. Matches shorter or equal to prev_length are discarded,
1296  * in which case the result is equal to prev_length and match_start is
1297  * garbage.
1298  * IN assertions: cur_match is the head of the hash chain for the current
1299  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1300  * OUT assertion: the match length is not greater than s->lookahead.
1301  */
1302 local uInt longest_match(s, cur_match)
1303     deflate_state *s;
1304     IPos cur_match;                             /* current match */
1305 {
1306     unsigned chain_length = s->max_chain_length;/* max hash chain length */
1307     register Bytef *scan = s->window + s->strstart; /* current string */
1308     register Bytef *match;                      /* matched string */
1309     register int len;                           /* length of current match */
1310     int best_len = (int)s->prev_length;         /* best match length so far */
1311     int nice_match = s->nice_match;             /* stop if match long enough */
1312     IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
1313         s->strstart - (IPos)MAX_DIST(s) : NIL;
1314     /* Stop when cur_match becomes <= limit. To simplify the code,
1315      * we prevent matches with the string of window index 0.
1316      */
1317     Posf *prev = s->prev;
1318     uInt wmask = s->w_mask;
1319 
1320 #ifdef UNALIGNED_OK
1321     /* Compare two bytes at a time. Note: this is not always beneficial.
1322      * Try with and without -DUNALIGNED_OK to check.
1323      */
1324     register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
1325     register ush scan_start = *(ushf*)scan;

1433             if (len >= nice_match) break;
1434 #ifdef UNALIGNED_OK
1435             scan_end = *(ushf*)(scan + best_len - 1);
1436 #else
1437             scan_end1  = scan[best_len - 1];
1438             scan_end   = scan[best_len];
1439 #endif
1440         }
1441     } while ((cur_match = prev[cur_match & wmask]) > limit
1442              && --chain_length != 0);
1443 
1444     if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
1445     return s->lookahead;
1446 }
1447 
1448 #else /* FASTEST */
1449 
1450 /* ---------------------------------------------------------------------------
1451  * Optimized version for FASTEST only
1452  */
1453 local uInt longest_match(s, cur_match)
1454     deflate_state *s;
1455     IPos cur_match;                             /* current match */
1456 {
1457     register Bytef *scan = s->window + s->strstart; /* current string */
1458     register Bytef *match;                       /* matched string */
1459     register int len;                           /* length of current match */
1460     register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1461 
1462     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1463      * It is easy to get rid of this optimization if necessary.
1464      */
1465     Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1466 
1467     Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1468            "need lookahead");
1469 
1470     Assert(cur_match < s->strstart, "no future");
1471 
1472     match = s->window + cur_match;
1473 
1474     /* Return failure if the match length is less than 2:
1475      */
1476     if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;

1497     Assert(scan <= s->window + (unsigned)(s->window_size - 1), "wild scan");
1498 
1499     len = MAX_MATCH - (int)(strend - scan);
1500 
1501     if (len < MIN_MATCH) return MIN_MATCH - 1;
1502 
1503     s->match_start = cur_match;
1504     return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
1505 }
1506 
1507 #endif /* FASTEST */
1508 
1509 #ifdef ZLIB_DEBUG
1510 
1511 #define EQUAL 0
1512 /* result of memcmp for equal strings */
1513 
1514 /* ===========================================================================
1515  * Check that the match at match_start is indeed a match.
1516  */
1517 local void check_match(s, start, match, length)
1518     deflate_state *s;
1519     IPos start, match;
1520     int length;
1521 {
1522     /* check that the match is indeed a match */
1523     if (zmemcmp(s->window + match,
1524                 s->window + start, length) != EQUAL) {
1525         fprintf(stderr, " start %u, match %u, length %d\n",
1526                 start, match, length);








1527         do {
1528             fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
1529         } while (--length != 0);
1530         z_error("invalid match");
1531     }
1532     if (z_verbose > 1) {
1533         fprintf(stderr,"\\[%d,%d]", start - match, length);
1534         do { putc(s->window[start++], stderr); } while (--length != 0);
1535     }
1536 }
1537 #else
1538 #  define check_match(s, start, match, length)
1539 #endif /* ZLIB_DEBUG */
1540 
1541 /* ===========================================================================
1542  * Fill the window when the lookahead becomes insufficient.
1543  * Updates strstart and lookahead.
1544  *
1545  * IN assertion: lookahead < MIN_LOOKAHEAD
1546  * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1547  *    At least one byte has been read, or avail_in == 0; reads are
1548  *    performed for at least two bytes (required for the zip translate_eol
1549  *    option -- not supported here).
1550  */
1551 local void fill_window(s)
1552     deflate_state *s;
1553 {
1554     unsigned n;
1555     unsigned more;    /* Amount of free space at the end of the window. */
1556     uInt wsize = s->w_size;
1557 
1558     Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
1559 
1560     do {
1561         more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
1562 
1563         /* Deal with !@#$% 64K limit: */
1564         if (sizeof(int) <= 2) {
1565             if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1566                 more = wsize;
1567 
1568             } else if (more == (unsigned)(-1)) {
1569                 /* Very unlikely, but possible on 16 bit machine if
1570                  * strstart == 0 && lookahead == 1 (input done a byte at time)
1571                  */
1572                 more--;
1573             }
1574         }
1575 
1576         /* If the window is almost full and there is insufficient lookahead,
1577          * move the upper half to the lower one to make room in the upper half.
1578          */
1579         if (s->strstart >= wsize + MAX_DIST(s)) {
1580 
1581             zmemcpy(s->window, s->window + wsize, (unsigned)wsize - more);
1582             s->match_start -= wsize;
1583             s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
1584             s->block_start -= (long) wsize;
1585             if (s->insert > s->strstart)
1586                 s->insert = s->strstart;
1587             slide_hash(s);
1588             more += wsize;
1589         }
1590         if (s->strm->avail_in == 0) break;
1591 
1592         /* If there was no sliding:
1593          *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1594          *    more == window_size - lookahead - strstart
1595          * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1596          * => more >= window_size - 2*WSIZE + 2
1597          * In the BIG_MEM or MMAP case (not yet supported),
1598          *   window_size == input_size + MIN_LOOKAHEAD  &&
1599          *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1600          * Otherwise, window_size == 2*WSIZE so more >= 2.
1601          * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1602          */
1603         Assert(more >= 2, "more < 2");
1604 
1605         n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1606         s->lookahead += n;
1607 
1608         /* Initialize the hash value now that we have some input: */
1609         if (s->lookahead + s->insert >= MIN_MATCH) {
1610             uInt str = s->strstart - s->insert;
1611             s->ins_h = s->window[str];
1612             UPDATE_HASH(s, s->ins_h, s->window[str + 1]);
1613 #if MIN_MATCH != 3
1614             Call UPDATE_HASH() MIN_MATCH-3 more times
1615 #endif
1616             while (s->insert) {
1617                 UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
1618 #ifndef FASTEST
1619                 s->prev[str & s->w_mask] = s->head[s->ins_h];
1620 #endif
1621                 s->head[s->ins_h] = (Pos)str;
1622                 str++;
1623                 s->insert--;
1624                 if (s->lookahead + s->insert < MIN_MATCH)
1625                     break;
1626             }
1627         }
1628         /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1629          * but this is not important since only literal bytes will be emitted.
1630          */
1631 
1632     } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1633 
1634     /* If the WIN_INIT bytes after the end of the current data have never been
1635      * written, then zero those bytes in order to avoid memory check reports of
1636      * the use of uninitialized (or uninitialised as Julian writes) bytes by
1637      * the longest match routines.  Update the high water mark for the next
1638      * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
1639      * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
1640      */
1641     if (s->high_water < s->window_size) {
1642         ulg curr = s->strstart + (ulg)(s->lookahead);
1643         ulg init;
1644 
1645         if (s->high_water < curr) {
1646             /* Previous high water mark below current data -- zero WIN_INIT
1647              * bytes or up to end of window, whichever is less.
1648              */
1649             init = s->window_size - curr;
1650             if (init > WIN_INIT)
1651                 init = WIN_INIT;
1652             zmemzero(s->window + curr, (unsigned)init);
1653             s->high_water = curr + init;
1654         }
1655         else if (s->high_water < (ulg)curr + WIN_INIT) {
1656             /* High water mark at or above current data, but below current data
1657              * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
1658              * to end of window, whichever is less.
1659              */
1660             init = (ulg)curr + WIN_INIT - s->high_water;
1661             if (init > s->window_size - s->high_water)
1662                 init = s->window_size - s->high_water;
1663             zmemzero(s->window + s->high_water, (unsigned)init);
1664             s->high_water += init;
1665         }
1666     }
1667 
1668     Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1669            "not enough room for search");
1670 }
1671 
1672 /* ===========================================================================
1673  * Flush the current block, with given end-of-file flag.
1674  * IN assertion: strstart is set to the end of the current match.
1675  */
1676 #define FLUSH_BLOCK_ONLY(s, last) { \
1677    _tr_flush_block(s, (s->block_start >= 0L ? \
1678                    (charf *)&s->window[(unsigned)s->block_start] : \
1679                    (charf *)Z_NULL), \
1680                 (ulg)((long)s->strstart - s->block_start), \
1681                 (last)); \
1682    s->block_start = s->strstart; \
1683    flush_pending(s->strm); \
1684    Tracev((stderr,"[FLUSH]")); \
1685 }
1686 
1687 /* Same but force premature exit if necessary. */
1688 #define FLUSH_BLOCK(s, last) { \
1689    FLUSH_BLOCK_ONLY(s, last); \
1690    if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
1691 }

1694 #define MAX_STORED 65535
1695 
1696 /* Minimum of a and b. */
1697 #define MIN(a, b) ((a) > (b) ? (b) : (a))
1698 
1699 /* ===========================================================================
1700  * Copy without compression as much as possible from the input stream, return
1701  * the current block state.
1702  *
1703  * In case deflateParams() is used to later switch to a non-zero compression
1704  * level, s->matches (otherwise unused when storing) keeps track of the number
1705  * of hash table slides to perform. If s->matches is 1, then one hash table
1706  * slide will be done when switching. If s->matches is 2, the maximum value
1707  * allowed here, then the hash table will be cleared, since two or more slides
1708  * is the same as a clear.
1709  *
1710  * deflate_stored() is written to minimize the number of times an input byte is
1711  * copied. It is most efficient with large input and output buffers, which
1712  * maximizes the opportunities to have a single copy from next_in to next_out.
1713  */
1714 local block_state deflate_stored(s, flush)
1715     deflate_state *s;
1716     int flush;
1717 {
1718     /* Smallest worthy block size when not flushing or finishing. By default
1719      * this is 32K. This can be as small as 507 bytes for memLevel == 1. For
1720      * large input and output buffers, the stored block size will be larger.
1721      */
1722     unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size);
1723 
1724     /* Copy as many min_block or larger stored blocks directly to next_out as
1725      * possible. If flushing, copy the remaining available input to next_out as
1726      * stored blocks, if there is enough space.
1727      */
1728     unsigned len, left, have, last = 0;
1729     unsigned used = s->strm->avail_in;
1730     do {
1731         /* Set len to the maximum size block that we can copy directly with the
1732          * available input data and output space. Set left to how much of that
1733          * would be copied from what's left in the window.
1734          */
1735         len = MAX_STORED;       /* maximum deflate stored block length */
1736         have = (s->bi_valid + 42) >> 3;         /* number of header bytes */
1737         if (s->strm->avail_out < have)          /* need room for header */

1881          s->strm->avail_in == 0 && left <= have)) {
1882         len = MIN(left, have);
1883         last = flush == Z_FINISH && s->strm->avail_in == 0 &&
1884                len == left ? 1 : 0;
1885         _tr_stored_block(s, (charf *)s->window + s->block_start, len, last);
1886         s->block_start += len;
1887         flush_pending(s->strm);
1888     }
1889 
1890     /* We've done all we can with the available input and output. */
1891     return last ? finish_started : need_more;
1892 }
1893 
1894 /* ===========================================================================
1895  * Compress as much as possible from the input stream, return the current
1896  * block state.
1897  * This function does not perform lazy evaluation of matches and inserts
1898  * new strings in the dictionary only for unmatched strings or for short
1899  * matches. It is used only for the fast compression options.
1900  */
1901 local block_state deflate_fast(s, flush)
1902     deflate_state *s;
1903     int flush;
1904 {
1905     IPos hash_head;       /* head of the hash chain */
1906     int bflush;           /* set if current block must be flushed */
1907 
1908     for (;;) {
1909         /* Make sure that we always have enough lookahead, except
1910          * at the end of the input file. We need MAX_MATCH bytes
1911          * for the next match, plus MIN_MATCH bytes to insert the
1912          * string following the next match.
1913          */
1914         if (s->lookahead < MIN_LOOKAHEAD) {
1915             fill_window(s);
1916             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1917                 return need_more;
1918             }
1919             if (s->lookahead == 0) break; /* flush the current block */
1920         }
1921 
1922         /* Insert the string window[strstart .. strstart + 2] in the
1923          * dictionary, and set hash_head to the head of the hash chain:
1924          */

1983             s->strstart++;
1984         }
1985         if (bflush) FLUSH_BLOCK(s, 0);
1986     }
1987     s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
1988     if (flush == Z_FINISH) {
1989         FLUSH_BLOCK(s, 1);
1990         return finish_done;
1991     }
1992     if (s->sym_next)
1993         FLUSH_BLOCK(s, 0);
1994     return block_done;
1995 }
1996 
1997 #ifndef FASTEST
1998 /* ===========================================================================
1999  * Same as above, but achieves better compression. We use a lazy
2000  * evaluation for matches: a match is finally adopted only if there is
2001  * no better match at the next window position.
2002  */
2003 local block_state deflate_slow(s, flush)
2004     deflate_state *s;
2005     int flush;
2006 {
2007     IPos hash_head;          /* head of hash chain */
2008     int bflush;              /* set if current block must be flushed */
2009 
2010     /* Process the input block. */
2011     for (;;) {
2012         /* Make sure that we always have enough lookahead, except
2013          * at the end of the input file. We need MAX_MATCH bytes
2014          * for the next match, plus MIN_MATCH bytes to insert the
2015          * string following the next match.
2016          */
2017         if (s->lookahead < MIN_LOOKAHEAD) {
2018             fill_window(s);
2019             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
2020                 return need_more;
2021             }
2022             if (s->lookahead == 0) break; /* flush the current block */
2023         }
2024 
2025         /* Insert the string window[strstart .. strstart + 2] in the
2026          * dictionary, and set hash_head to the head of the hash chain:

2114         Tracevv((stderr,"%c", s->window[s->strstart - 1]));
2115         _tr_tally_lit(s, s->window[s->strstart - 1], bflush);
2116         s->match_available = 0;
2117     }
2118     s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
2119     if (flush == Z_FINISH) {
2120         FLUSH_BLOCK(s, 1);
2121         return finish_done;
2122     }
2123     if (s->sym_next)
2124         FLUSH_BLOCK(s, 0);
2125     return block_done;
2126 }
2127 #endif /* FASTEST */
2128 
2129 /* ===========================================================================
2130  * For Z_RLE, simply look for runs of bytes, generate matches only of distance
2131  * one.  Do not maintain a hash table.  (It will be regenerated if this run of
2132  * deflate switches away from Z_RLE.)
2133  */
2134 local block_state deflate_rle(s, flush)
2135     deflate_state *s;
2136     int flush;
2137 {
2138     int bflush;             /* set if current block must be flushed */
2139     uInt prev;              /* byte at distance one to match */
2140     Bytef *scan, *strend;   /* scan goes up to strend for length of run */
2141 
2142     for (;;) {
2143         /* Make sure that we always have enough lookahead, except
2144          * at the end of the input file. We need MAX_MATCH bytes
2145          * for the longest run, plus one for the unrolled loop.
2146          */
2147         if (s->lookahead <= MAX_MATCH) {
2148             fill_window(s);
2149             if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {
2150                 return need_more;
2151             }
2152             if (s->lookahead == 0) break; /* flush the current block */
2153         }
2154 
2155         /* See how many times the previous byte repeats */
2156         s->match_length = 0;
2157         if (s->lookahead >= MIN_MATCH && s->strstart > 0) {

2188             _tr_tally_lit(s, s->window[s->strstart], bflush);
2189             s->lookahead--;
2190             s->strstart++;
2191         }
2192         if (bflush) FLUSH_BLOCK(s, 0);
2193     }
2194     s->insert = 0;
2195     if (flush == Z_FINISH) {
2196         FLUSH_BLOCK(s, 1);
2197         return finish_done;
2198     }
2199     if (s->sym_next)
2200         FLUSH_BLOCK(s, 0);
2201     return block_done;
2202 }
2203 
2204 /* ===========================================================================
2205  * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
2206  * (It will be regenerated if this run of deflate switches away from Huffman.)
2207  */
2208 local block_state deflate_huff(s, flush)
2209     deflate_state *s;
2210     int flush;
2211 {
2212     int bflush;             /* set if current block must be flushed */
2213 
2214     for (;;) {
2215         /* Make sure that we have a literal to write. */
2216         if (s->lookahead == 0) {
2217             fill_window(s);
2218             if (s->lookahead == 0) {
2219                 if (flush == Z_NO_FLUSH)
2220                     return need_more;
2221                 break;      /* flush the current block */
2222             }
2223         }
2224 
2225         /* Output a literal byte */
2226         s->match_length = 0;
2227         Tracevv((stderr,"%c", s->window[s->strstart]));
2228         _tr_tally_lit(s, s->window[s->strstart], bflush);
2229         s->lookahead--;
2230         s->strstart++;
2231         if (bflush) FLUSH_BLOCK(s, 0);

   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 /* deflate.c -- compress data using the deflation algorithm
  26  * Copyright (C) 1995-2024 Jean-loup Gailly and Mark Adler
  27  * For conditions of distribution and use, see copyright notice in zlib.h
  28  */
  29 
  30 /*
  31  *  ALGORITHM
  32  *
  33  *      The "deflation" process depends on being able to identify portions
  34  *      of the input text which are identical to earlier input (within a
  35  *      sliding window trailing behind the input currently being processed).
  36  *
  37  *      The most straightforward technique turns out to be the fastest for
  38  *      most input files: try all possible matches and select the longest.
  39  *      The key feature of this algorithm is that insertions into the string
  40  *      dictionary are very simple and thus fast, and deletions are avoided
  41  *      completely. Insertions are performed at each input character, whereas
  42  *      string matches are performed only when the previous match ends. So it
  43  *      is preferable to spend more time in matches to allow very fast string
  44  *      insertions and avoid deletions. The matching algorithm for small
  45  *      strings is inspired from that of Rabin & Karp. A brute force approach
  46  *      is used to find longer strings when a small match has been found.

  59  *      Thanks to many people for bug reports and testing.
  60  *
  61  *  REFERENCES
  62  *
  63  *      Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  64  *      Available in http://tools.ietf.org/html/rfc1951
  65  *
  66  *      A description of the Rabin and Karp algorithm is given in the book
  67  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  68  *
  69  *      Fiala,E.R., and Greene,D.H.
  70  *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  71  *
  72  */
  73 
  74 /* @(#) $Id$ */
  75 
  76 #include "deflate.h"
  77 
  78 const char deflate_copyright[] =
  79    " deflate 1.3.1 Copyright 1995-2024 Jean-loup Gailly and Mark Adler ";
  80 /*
  81   If you use the zlib library in a product, an acknowledgment is welcome
  82   in the documentation of your product. If for some reason you cannot
  83   include such an acknowledgment, I would appreciate that you keep this
  84   copyright string in the executable of your product.
  85  */
  86 



  87 typedef enum {
  88     need_more,      /* block not completed, need more input or more output */
  89     block_done,     /* block flush performed */
  90     finish_started, /* finish started, need only more output at next deflate */
  91     finish_done     /* finish done, accept no more input or output */
  92 } block_state;
  93 
  94 typedef block_state (*compress_func)(deflate_state *s, int flush);
  95 /* Compression function. Returns the block state after the call. */
  96 
  97 local block_state deflate_stored(deflate_state *s, int flush);
  98 local block_state deflate_fast(deflate_state *s, int flush);



  99 #ifndef FASTEST
 100 local block_state deflate_slow(deflate_state *s, int flush);












 101 #endif
 102 local block_state deflate_rle(deflate_state *s, int flush);
 103 local block_state deflate_huff(deflate_state *s, int flush);
 104 
 105 /* ===========================================================================
 106  * Local data
 107  */
 108 
 109 #define NIL 0
 110 /* Tail of hash chains */
 111 
 112 #ifndef TOO_FAR
 113 #  define TOO_FAR 4096
 114 #endif
 115 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
 116 
 117 /* Values for max_lazy_match, good_match and max_chain_length, depending on
 118  * the desired pack level (0..9). The values given below have been tuned to
 119  * exclude worst case performance for pathological files. Better values may be
 120  * found for specific files.
 121  */
 122 typedef struct config_s {
 123    ush good_length; /* reduce lazy search above this match length */

 186     match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
 187     s->head[s->ins_h] = (Pos)(str))
 188 #endif
 189 
 190 /* ===========================================================================
 191  * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
 192  * prev[] will be initialized on the fly.
 193  */
 194 #define CLEAR_HASH(s) \
 195     do { \
 196         s->head[s->hash_size - 1] = NIL; \
 197         zmemzero((Bytef *)s->head, \
 198                  (unsigned)(s->hash_size - 1)*sizeof(*s->head)); \
 199     } while (0)
 200 
 201 /* ===========================================================================
 202  * Slide the hash table when sliding the window down (could be avoided with 32
 203  * bit values at the expense of memory usage). We slide even when level == 0 to
 204  * keep the hash table consistent if we switch back to level > 0 later.
 205  */
 206 #if defined(__has_feature)
 207 #  if __has_feature(memory_sanitizer)
 208      __attribute__((no_sanitize("memory")))
 209 #  endif
 210 #endif
 211 local void slide_hash(deflate_state *s) {
 212     unsigned n, m;
 213     Posf *p;
 214     uInt wsize = s->w_size;
 215 
 216     n = s->hash_size;
 217     p = &s->head[n];
 218     do {
 219         m = *--p;
 220         *p = (Pos)(m >= wsize ? m - wsize : NIL);
 221     } while (--n);
 222     n = wsize;
 223 #ifndef FASTEST
 224     p = &s->prev[n];
 225     do {
 226         m = *--p;
 227         *p = (Pos)(m >= wsize ? m - wsize : NIL);
 228         /* If n is not on any hash chain, prev[n] is garbage but
 229          * its value will never be used.
 230          */
 231     } while (--n);
 232 #endif
 233 }
 234 
 235 /* ===========================================================================
 236  * Read a new buffer from the current input stream, update the adler32
 237  * and total number of bytes read.  All deflate() input goes through
 238  * this function so some applications may wish to modify it to avoid
 239  * allocating a large strm->next_in buffer and copying from it.
 240  * (See also flush_pending()).
 241  */
 242 local unsigned read_buf(z_streamp strm, Bytef *buf, unsigned size) {
 243     unsigned len = strm->avail_in;
 244 
 245     if (len > size) len = size;
 246     if (len == 0) return 0;
 247 
 248     strm->avail_in  -= len;
 249 
 250     zmemcpy(buf, strm->next_in, len);
 251     if (strm->state->wrap == 1) {
 252         strm->adler = adler32(strm->adler, buf, len);
 253     }
 254 #ifdef GZIP
 255     else if (strm->state->wrap == 2) {
 256         strm->adler = crc32(strm->adler, buf, len);
 257     }
 258 #endif
 259     strm->next_in  += len;
 260     strm->total_in += len;
 261 
 262     return len;
 263 }
 264 
 265 /* ===========================================================================
 266  * Fill the window when the lookahead becomes insufficient.
 267  * Updates strstart and lookahead.
 268  *
 269  * IN assertion: lookahead < MIN_LOOKAHEAD
 270  * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
 271  *    At least one byte has been read, or avail_in == 0; reads are
 272  *    performed for at least two bytes (required for the zip translate_eol
 273  *    option -- not supported here).
 274  */
 275 local void fill_window(deflate_state *s) {
 276     unsigned n;
 277     unsigned more;    /* Amount of free space at the end of the window. */
 278     uInt wsize = s->w_size;
 279 
 280     Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
 281 
 282     do {
 283         more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
 284 
 285         /* Deal with !@#$% 64K limit: */
 286         if (sizeof(int) <= 2) {
 287             if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
 288                 more = wsize;
 289 
 290             } else if (more == (unsigned)(-1)) {
 291                 /* Very unlikely, but possible on 16 bit machine if
 292                  * strstart == 0 && lookahead == 1 (input done a byte at time)
 293                  */
 294                 more--;
 295             }
 296         }
 297 
 298         /* If the window is almost full and there is insufficient lookahead,
 299          * move the upper half to the lower one to make room in the upper half.
 300          */
 301         if (s->strstart >= wsize + MAX_DIST(s)) {
 302 
 303             zmemcpy(s->window, s->window + wsize, (unsigned)wsize - more);
 304             s->match_start -= wsize;
 305             s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
 306             s->block_start -= (long) wsize;
 307             if (s->insert > s->strstart)
 308                 s->insert = s->strstart;
 309             slide_hash(s);
 310             more += wsize;
 311         }
 312         if (s->strm->avail_in == 0) break;
 313 
 314         /* If there was no sliding:
 315          *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
 316          *    more == window_size - lookahead - strstart
 317          * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
 318          * => more >= window_size - 2*WSIZE + 2
 319          * In the BIG_MEM or MMAP case (not yet supported),
 320          *   window_size == input_size + MIN_LOOKAHEAD  &&
 321          *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
 322          * Otherwise, window_size == 2*WSIZE so more >= 2.
 323          * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
 324          */
 325         Assert(more >= 2, "more < 2");
 326 
 327         n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
 328         s->lookahead += n;
 329 
 330         /* Initialize the hash value now that we have some input: */
 331         if (s->lookahead + s->insert >= MIN_MATCH) {
 332             uInt str = s->strstart - s->insert;
 333             s->ins_h = s->window[str];
 334             UPDATE_HASH(s, s->ins_h, s->window[str + 1]);
 335 #if MIN_MATCH != 3
 336             Call UPDATE_HASH() MIN_MATCH-3 more times
 337 #endif
 338             while (s->insert) {
 339                 UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
 340 #ifndef FASTEST
 341                 s->prev[str & s->w_mask] = s->head[s->ins_h];
 342 #endif
 343                 s->head[s->ins_h] = (Pos)str;
 344                 str++;
 345                 s->insert--;
 346                 if (s->lookahead + s->insert < MIN_MATCH)
 347                     break;
 348             }
 349         }
 350         /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
 351          * but this is not important since only literal bytes will be emitted.
 352          */
 353 
 354     } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
 355 
 356     /* If the WIN_INIT bytes after the end of the current data have never been
 357      * written, then zero those bytes in order to avoid memory check reports of
 358      * the use of uninitialized (or uninitialised as Julian writes) bytes by
 359      * the longest match routines.  Update the high water mark for the next
 360      * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
 361      * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
 362      */
 363     if (s->high_water < s->window_size) {
 364         ulg curr = s->strstart + (ulg)(s->lookahead);
 365         ulg init;
 366 
 367         if (s->high_water < curr) {
 368             /* Previous high water mark below current data -- zero WIN_INIT
 369              * bytes or up to end of window, whichever is less.
 370              */
 371             init = s->window_size - curr;
 372             if (init > WIN_INIT)
 373                 init = WIN_INIT;
 374             zmemzero(s->window + curr, (unsigned)init);
 375             s->high_water = curr + init;
 376         }
 377         else if (s->high_water < (ulg)curr + WIN_INIT) {
 378             /* High water mark at or above current data, but below current data
 379              * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
 380              * to end of window, whichever is less.
 381              */
 382             init = (ulg)curr + WIN_INIT - s->high_water;
 383             if (init > s->window_size - s->high_water)
 384                 init = s->window_size - s->high_water;
 385             zmemzero(s->window + s->high_water, (unsigned)init);
 386             s->high_water += init;
 387         }
 388     }
 389 
 390     Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
 391            "not enough room for search");
 392 }
 393 
 394 /* ========================================================================= */
 395 int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version,
 396                          int stream_size) {




 397     return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
 398                          Z_DEFAULT_STRATEGY, version, stream_size);
 399     /* To do: ignore strm->next_in if we use it as window */
 400 }
 401 
 402 /* ========================================================================= */
 403 int ZEXPORT deflateInit2_(z_streamp strm, int level, int method,
 404                           int windowBits, int memLevel, int strategy,
 405                           const char *version, int stream_size) {








 406     deflate_state *s;
 407     int wrap = 1;
 408     static const char my_version[] = ZLIB_VERSION;
 409 
 410     if (version == Z_NULL || version[0] != my_version[0] ||
 411         stream_size != sizeof(z_stream)) {
 412         return Z_VERSION_ERROR;
 413     }
 414     if (strm == Z_NULL) return Z_STREAM_ERROR;
 415 
 416     strm->msg = Z_NULL;
 417     if (strm->zalloc == (alloc_func)0) {
 418 #ifdef Z_SOLO
 419         return Z_STREAM_ERROR;
 420 #else
 421         strm->zalloc = zcalloc;
 422         strm->opaque = (voidpf)0;
 423 #endif
 424     }
 425     if (strm->zfree == (free_func)0)

 500      * symbols are written.) The closest the writing gets to what is unread is
 501      * then n + 14 bits. Here n is lit_bufsize, which is 16384 by default, and
 502      * can range from 128 to 32768.
 503      *
 504      * Therefore, at a minimum, there are 142 bits of space between what is
 505      * written and what is read in the overlain buffers, so the symbols cannot
 506      * be overwritten by the compressed data. That space is actually 139 bits,
 507      * due to the three-bit fixed-code block header.
 508      *
 509      * That covers the case where either Z_FIXED is specified, forcing fixed
 510      * codes, or when the use of fixed codes is chosen, because that choice
 511      * results in a smaller compressed block than dynamic codes. That latter
 512      * condition then assures that the above analysis also covers all dynamic
 513      * blocks. A dynamic-code block will only be chosen to be emitted if it has
 514      * fewer bits than a fixed-code block would for the same set of symbols.
 515      * Therefore its average symbol length is assured to be less than 31. So
 516      * the compressed data for a dynamic block also cannot overwrite the
 517      * symbols from which it is being constructed.
 518      */
 519 
 520     s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, LIT_BUFS);
 521     s->pending_buf_size = (ulg)s->lit_bufsize * 4;
 522 
 523     if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
 524         s->pending_buf == Z_NULL) {
 525         s->status = FINISH_STATE;
 526         strm->msg = ERR_MSG(Z_MEM_ERROR);
 527         deflateEnd (strm);
 528         return Z_MEM_ERROR;
 529     }
 530 #ifdef LIT_MEM
 531     s->d_buf = (ushf *)(s->pending_buf + (s->lit_bufsize << 1));
 532     s->l_buf = s->pending_buf + (s->lit_bufsize << 2);
 533     s->sym_end = s->lit_bufsize - 1;
 534 #else
 535     s->sym_buf = s->pending_buf + s->lit_bufsize;
 536     s->sym_end = (s->lit_bufsize - 1) * 3;
 537 #endif
 538     /* We avoid equality with lit_bufsize*3 because of wraparound at 64K
 539      * on 16 bit machines and because stored blocks are restricted to
 540      * 64K-1 bytes.
 541      */
 542 
 543     s->level = level;
 544     s->strategy = strategy;
 545     s->method = (Byte)method;
 546 
 547     return deflateReset(strm);
 548 }
 549 
 550 /* =========================================================================
 551  * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
 552  */
 553 local int deflateStateCheck(z_streamp strm) {


 554     deflate_state *s;
 555     if (strm == Z_NULL ||
 556         strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
 557         return 1;
 558     s = strm->state;
 559     if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE &&
 560 #ifdef GZIP
 561                                            s->status != GZIP_STATE &&
 562 #endif
 563                                            s->status != EXTRA_STATE &&
 564                                            s->status != NAME_STATE &&
 565                                            s->status != COMMENT_STATE &&
 566                                            s->status != HCRC_STATE &&
 567                                            s->status != BUSY_STATE &&
 568                                            s->status != FINISH_STATE))
 569         return 1;
 570     return 0;
 571 }
 572 
 573 /* ========================================================================= */
 574 int ZEXPORT deflateSetDictionary(z_streamp strm, const Bytef *dictionary,
 575                                  uInt  dictLength) {



 576     deflate_state *s;
 577     uInt str, n;
 578     int wrap;
 579     unsigned avail;
 580     z_const unsigned char *next;
 581 
 582     if (deflateStateCheck(strm) || dictionary == Z_NULL)
 583         return Z_STREAM_ERROR;
 584     s = strm->state;
 585     wrap = s->wrap;
 586     if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
 587         return Z_STREAM_ERROR;
 588 
 589     /* when using zlib wrappers, compute Adler-32 for provided dictionary */
 590     if (wrap == 1)
 591         strm->adler = adler32(strm->adler, dictionary, dictLength);
 592     s->wrap = 0;                    /* avoid computing Adler-32 in read_buf */
 593 
 594     /* if dictionary would fill window, just replace the history */
 595     if (dictLength >= s->w_size) {

 620             s->head[s->ins_h] = (Pos)str;
 621             str++;
 622         } while (--n);
 623         s->strstart = str;
 624         s->lookahead = MIN_MATCH-1;
 625         fill_window(s);
 626     }
 627     s->strstart += s->lookahead;
 628     s->block_start = (long)s->strstart;
 629     s->insert = s->lookahead;
 630     s->lookahead = 0;
 631     s->match_length = s->prev_length = MIN_MATCH-1;
 632     s->match_available = 0;
 633     strm->next_in = next;
 634     strm->avail_in = avail;
 635     s->wrap = wrap;
 636     return Z_OK;
 637 }
 638 
 639 /* ========================================================================= */
 640 int ZEXPORT deflateGetDictionary(z_streamp strm, Bytef *dictionary,
 641                                  uInt *dictLength) {



 642     deflate_state *s;
 643     uInt len;
 644 
 645     if (deflateStateCheck(strm))
 646         return Z_STREAM_ERROR;
 647     s = strm->state;
 648     len = s->strstart + s->lookahead;
 649     if (len > s->w_size)
 650         len = s->w_size;
 651     if (dictionary != Z_NULL && len)
 652         zmemcpy(dictionary, s->window + s->strstart + s->lookahead - len, len);
 653     if (dictLength != Z_NULL)
 654         *dictLength = len;
 655     return Z_OK;
 656 }
 657 
 658 /* ========================================================================= */
 659 int ZEXPORT deflateResetKeep(z_streamp strm) {


 660     deflate_state *s;
 661 
 662     if (deflateStateCheck(strm)) {
 663         return Z_STREAM_ERROR;
 664     }
 665 
 666     strm->total_in = strm->total_out = 0;
 667     strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
 668     strm->data_type = Z_UNKNOWN;
 669 
 670     s = (deflate_state *)strm->state;
 671     s->pending = 0;
 672     s->pending_out = s->pending_buf;
 673 
 674     if (s->wrap < 0) {
 675         s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
 676     }
 677     s->status =
 678 #ifdef GZIP
 679         s->wrap == 2 ? GZIP_STATE :
 680 #endif
 681         INIT_STATE;
 682     strm->adler =
 683 #ifdef GZIP
 684         s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
 685 #endif
 686         adler32(0L, Z_NULL, 0);
 687     s->last_flush = -2;
 688 
 689     _tr_init(s);
 690 
 691     return Z_OK;
 692 }
 693 
 694 /* ===========================================================================
 695  * Initialize the "longest match" routines for a new zlib stream
 696  */
 697 local void lm_init(deflate_state *s) {
 698     s->window_size = (ulg)2L*s->w_size;
 699 
 700     CLEAR_HASH(s);
 701 
 702     /* Set the default configuration parameters:
 703      */
 704     s->max_lazy_match   = configuration_table[s->level].max_lazy;
 705     s->good_match       = configuration_table[s->level].good_length;
 706     s->nice_match       = configuration_table[s->level].nice_length;
 707     s->max_chain_length = configuration_table[s->level].max_chain;
 708 
 709     s->strstart = 0;
 710     s->block_start = 0L;
 711     s->lookahead = 0;
 712     s->insert = 0;
 713     s->match_length = s->prev_length = MIN_MATCH-1;
 714     s->match_available = 0;
 715     s->ins_h = 0;
 716 }
 717 
 718 /* ========================================================================= */
 719 int ZEXPORT deflateReset(z_streamp strm) {


 720     int ret;
 721 
 722     ret = deflateResetKeep(strm);
 723     if (ret == Z_OK)
 724         lm_init(strm->state);
 725     return ret;
 726 }
 727 
 728 /* ========================================================================= */
 729 int ZEXPORT deflateSetHeader(z_streamp strm, gz_headerp head) {



 730     if (deflateStateCheck(strm) || strm->state->wrap != 2)
 731         return Z_STREAM_ERROR;
 732     strm->state->gzhead = head;
 733     return Z_OK;
 734 }
 735 
 736 /* ========================================================================= */
 737 int ZEXPORT deflatePending(z_streamp strm, unsigned *pending, int *bits) {




 738     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
 739     if (pending != Z_NULL)
 740         *pending = strm->state->pending;
 741     if (bits != Z_NULL)
 742         *bits = strm->state->bi_valid;
 743     return Z_OK;
 744 }
 745 
 746 /* ========================================================================= */
 747 int ZEXPORT deflatePrime(z_streamp strm, int bits, int value) {




 748     deflate_state *s;
 749     int put;
 750 
 751     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
 752     s = strm->state;
 753 #ifdef LIT_MEM
 754     if (bits < 0 || bits > 16 ||
 755         (uchf *)s->d_buf < s->pending_out + ((Buf_size + 7) >> 3))
 756         return Z_BUF_ERROR;
 757 #else
 758     if (bits < 0 || bits > 16 ||
 759         s->sym_buf < s->pending_out + ((Buf_size + 7) >> 3))
 760         return Z_BUF_ERROR;
 761 #endif
 762     do {
 763         put = Buf_size - s->bi_valid;
 764         if (put > bits)
 765             put = bits;
 766         s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);
 767         s->bi_valid += put;
 768         _tr_flush_bits(s);
 769         value >>= put;
 770         bits -= put;
 771     } while (bits);
 772     return Z_OK;
 773 }
 774 
 775 /* ========================================================================= */
 776 int ZEXPORT deflateParams(z_streamp strm, int level, int strategy) {




 777     deflate_state *s;
 778     compress_func func;
 779 
 780     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
 781     s = strm->state;
 782 
 783 #ifdef FASTEST
 784     if (level != 0) level = 1;
 785 #else
 786     if (level == Z_DEFAULT_COMPRESSION) level = 6;
 787 #endif
 788     if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
 789         return Z_STREAM_ERROR;
 790     }
 791     func = configuration_table[s->level].func;
 792 
 793     if ((strategy != s->strategy || func != configuration_table[level].func) &&
 794         s->last_flush != -2) {
 795         /* Flush the last buffer: */
 796         int err = deflate(strm, Z_BLOCK);

 801     }
 802     if (s->level != level) {
 803         if (s->level == 0 && s->matches != 0) {
 804             if (s->matches == 1)
 805                 slide_hash(s);
 806             else
 807                 CLEAR_HASH(s);
 808             s->matches = 0;
 809         }
 810         s->level = level;
 811         s->max_lazy_match   = configuration_table[level].max_lazy;
 812         s->good_match       = configuration_table[level].good_length;
 813         s->nice_match       = configuration_table[level].nice_length;
 814         s->max_chain_length = configuration_table[level].max_chain;
 815     }
 816     s->strategy = strategy;
 817     return Z_OK;
 818 }
 819 
 820 /* ========================================================================= */
 821 int ZEXPORT deflateTune(z_streamp strm, int good_length, int max_lazy,
 822                         int nice_length, int max_chain) {





 823     deflate_state *s;
 824 
 825     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
 826     s = strm->state;
 827     s->good_match = (uInt)good_length;
 828     s->max_lazy_match = (uInt)max_lazy;
 829     s->nice_match = nice_length;
 830     s->max_chain_length = (uInt)max_chain;
 831     return Z_OK;
 832 }
 833 
 834 /* =========================================================================
 835  * For the default windowBits of 15 and memLevel of 8, this function returns a
 836  * close to exact, as well as small, upper bound on the compressed size. This
 837  * is an expansion of ~0.03%, plus a small constant.
 838  *
 839  * For any setting other than those defaults for windowBits and memLevel, one
 840  * of two worst case bounds is returned. This is at most an expansion of ~4% or
 841  * ~13%, plus a small constant.
 842  *
 843  * Both the 0.03% and 4% derive from the overhead of stored blocks. The first
 844  * one is for stored blocks of 16383 bytes (memLevel == 8), whereas the second
 845  * is for stored blocks of 127 bytes (the worst case memLevel == 1). The
 846  * expansion results from five bytes of header for each stored block.
 847  *
 848  * The larger expansion of 13% results from a window size less than or equal to
 849  * the symbols buffer size (windowBits <= memLevel + 7). In that case some of
 850  * the data being compressed may have slid out of the sliding window, impeding
 851  * a stored block from being emitted. Then the only choice is a fixed or
 852  * dynamic block, where a fixed block limits the maximum expansion to 9 bits
 853  * per 8-bit byte, plus 10 bits for every block. The smallest block size for
 854  * which this can occur is 255 (memLevel == 2).
 855  *
 856  * Shifts are used to approximate divisions, for speed.
 857  */
 858 uLong ZEXPORT deflateBound(z_streamp strm, uLong sourceLen) {



 859     deflate_state *s;
 860     uLong fixedlen, storelen, wraplen;
 861 
 862     /* upper bound for fixed blocks with 9-bit literals and length 255
 863        (memLevel == 2, which is the lowest that may not use stored blocks) --
 864        ~13% overhead plus a small constant */
 865     fixedlen = sourceLen + (sourceLen >> 3) + (sourceLen >> 8) +
 866                (sourceLen >> 9) + 4;
 867 
 868     /* upper bound for stored blocks with length 127 (memLevel == 1) --
 869        ~4% overhead plus a small constant */
 870     storelen = sourceLen + (sourceLen >> 5) + (sourceLen >> 7) +
 871                (sourceLen >> 11) + 7;
 872 
 873     /* if can't get parameters, return larger bound plus a zlib wrapper */
 874     if (deflateStateCheck(strm))
 875         return (fixedlen > storelen ? fixedlen : storelen) + 6;
 876 
 877     /* compute wrapper length */
 878     s = strm->state;

 894             if (str != Z_NULL)
 895                 do {
 896                     wraplen++;
 897                 } while (*str++);
 898             str = s->gzhead->comment;
 899             if (str != Z_NULL)
 900                 do {
 901                     wraplen++;
 902                 } while (*str++);
 903             if (s->gzhead->hcrc)
 904                 wraplen += 2;
 905         }
 906         break;
 907 #endif
 908     default:                                /* for compiler happiness */
 909         wraplen = 6;
 910     }
 911 
 912     /* if not default parameters, return one of the conservative bounds */
 913     if (s->w_bits != 15 || s->hash_bits != 8 + 7)
 914         return (s->w_bits <= s->hash_bits && s->level ? fixedlen : storelen) +
 915                wraplen;
 916 
 917     /* default settings: return tight bound for that case -- ~0.03% overhead
 918        plus a small constant */
 919     return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
 920            (sourceLen >> 25) + 13 - 6 + wraplen;
 921 }
 922 
 923 /* =========================================================================
 924  * Put a short in the pending buffer. The 16-bit value is put in MSB order.
 925  * IN assertion: the stream state is correct and there is enough room in
 926  * pending_buf.
 927  */
 928 local void putShortMSB(deflate_state *s, uInt b) {



 929     put_byte(s, (Byte)(b >> 8));
 930     put_byte(s, (Byte)(b & 0xff));
 931 }
 932 
 933 /* =========================================================================
 934  * Flush as much pending output as possible. All deflate() output, except for
 935  * some deflate_stored() output, goes through this function so some
 936  * applications may wish to modify it to avoid allocating a large
 937  * strm->next_out buffer and copying into it. (See also read_buf()).
 938  */
 939 local void flush_pending(z_streamp strm) {


 940     unsigned len;
 941     deflate_state *s = strm->state;
 942 
 943     _tr_flush_bits(s);
 944     len = s->pending;
 945     if (len > strm->avail_out) len = strm->avail_out;
 946     if (len == 0) return;
 947 
 948     zmemcpy(strm->next_out, s->pending_out, len);
 949     strm->next_out  += len;
 950     s->pending_out  += len;
 951     strm->total_out += len;
 952     strm->avail_out -= len;
 953     s->pending      -= len;
 954     if (s->pending == 0) {
 955         s->pending_out = s->pending_buf;
 956     }
 957 }
 958 
 959 /* ===========================================================================
 960  * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1].
 961  */
 962 #define HCRC_UPDATE(beg) \
 963     do { \
 964         if (s->gzhead->hcrc && s->pending > (beg)) \
 965             strm->adler = crc32(strm->adler, s->pending_buf + (beg), \
 966                                 s->pending - (beg)); \
 967     } while (0)
 968 
 969 /* ========================================================================= */
 970 int ZEXPORT deflate(z_streamp strm, int flush) {



 971     int old_flush; /* value of flush param for previous deflate call */
 972     deflate_state *s;
 973 
 974     if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) {
 975         return Z_STREAM_ERROR;
 976     }
 977     s = strm->state;
 978 
 979     if (strm->next_out == Z_NULL ||
 980         (strm->avail_in != 0 && strm->next_in == Z_NULL) ||
 981         (s->status == FINISH_STATE && flush != Z_FINISH)) {
 982         ERR_RETURN(strm, Z_STREAM_ERROR);
 983     }
 984     if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
 985 
 986     old_flush = s->last_flush;
 987     s->last_flush = flush;
 988 
 989     /* Flush as much pending output as possible */
 990     if (s->pending != 0) {

1262         put_byte(s, (Byte)(strm->total_in & 0xff));
1263         put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
1264         put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
1265         put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
1266     }
1267     else
1268 #endif
1269     {
1270         putShortMSB(s, (uInt)(strm->adler >> 16));
1271         putShortMSB(s, (uInt)(strm->adler & 0xffff));
1272     }
1273     flush_pending(strm);
1274     /* If avail_out is zero, the application will call deflate again
1275      * to flush the rest.
1276      */
1277     if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
1278     return s->pending != 0 ? Z_OK : Z_STREAM_END;
1279 }
1280 
1281 /* ========================================================================= */
1282 int ZEXPORT deflateEnd(z_streamp strm) {


1283     int status;
1284 
1285     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
1286 
1287     status = strm->state->status;
1288 
1289     /* Deallocate in reverse order of allocations: */
1290     TRY_FREE(strm, strm->state->pending_buf);
1291     TRY_FREE(strm, strm->state->head);
1292     TRY_FREE(strm, strm->state->prev);
1293     TRY_FREE(strm, strm->state->window);
1294 
1295     ZFREE(strm, strm->state);
1296     strm->state = Z_NULL;
1297 
1298     return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
1299 }
1300 
1301 /* =========================================================================
1302  * Copy the source state to the destination state.
1303  * To simplify the source, this is not supported for 16-bit MSDOS (which
1304  * doesn't have enough memory anyway to duplicate compression states).
1305  */
1306 int ZEXPORT deflateCopy(z_streamp dest, z_streamp source) {



1307 #ifdef MAXSEG_64K
1308     (void)dest;
1309     (void)source;
1310     return Z_STREAM_ERROR;
1311 #else
1312     deflate_state *ds;
1313     deflate_state *ss;
1314 
1315 
1316     if (deflateStateCheck(source) || dest == Z_NULL) {
1317         return Z_STREAM_ERROR;
1318     }
1319 
1320     ss = source->state;
1321 
1322     zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
1323 
1324     ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
1325     if (ds == Z_NULL) return Z_MEM_ERROR;
1326     dest->state = (struct internal_state FAR *) ds;
1327     zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));
1328     ds->strm = dest;
1329 
1330     ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
1331     ds->prev   = (Posf *)  ZALLOC(dest, ds->w_size, sizeof(Pos));
1332     ds->head   = (Posf *)  ZALLOC(dest, ds->hash_size, sizeof(Pos));
1333     ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, LIT_BUFS);
1334 
1335     if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
1336         ds->pending_buf == Z_NULL) {
1337         deflateEnd (dest);
1338         return Z_MEM_ERROR;
1339     }
1340     /* following zmemcpy do not work for 16-bit MSDOS */
1341     zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
1342     zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));
1343     zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));
1344     zmemcpy(ds->pending_buf, ss->pending_buf, ds->lit_bufsize * LIT_BUFS);
1345 
1346     ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
1347 #ifdef LIT_MEM
1348     ds->d_buf = (ushf *)(ds->pending_buf + (ds->lit_bufsize << 1));
1349     ds->l_buf = ds->pending_buf + (ds->lit_bufsize << 2);
1350 #else
1351     ds->sym_buf = ds->pending_buf + ds->lit_bufsize;
1352 #endif
1353 
1354     ds->l_desc.dyn_tree = ds->dyn_ltree;
1355     ds->d_desc.dyn_tree = ds->dyn_dtree;
1356     ds->bl_desc.dyn_tree = ds->bl_tree;
1357 
1358     return Z_OK;
1359 #endif /* MAXSEG_64K */
1360 }
1361 




























































1362 #ifndef FASTEST
1363 /* ===========================================================================
1364  * Set match_start to the longest match starting at the given string and
1365  * return its length. Matches shorter or equal to prev_length are discarded,
1366  * in which case the result is equal to prev_length and match_start is
1367  * garbage.
1368  * IN assertions: cur_match is the head of the hash chain for the current
1369  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1370  * OUT assertion: the match length is not greater than s->lookahead.
1371  */
1372 local uInt longest_match(deflate_state *s, IPos cur_match) {



1373     unsigned chain_length = s->max_chain_length;/* max hash chain length */
1374     register Bytef *scan = s->window + s->strstart; /* current string */
1375     register Bytef *match;                      /* matched string */
1376     register int len;                           /* length of current match */
1377     int best_len = (int)s->prev_length;         /* best match length so far */
1378     int nice_match = s->nice_match;             /* stop if match long enough */
1379     IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
1380         s->strstart - (IPos)MAX_DIST(s) : NIL;
1381     /* Stop when cur_match becomes <= limit. To simplify the code,
1382      * we prevent matches with the string of window index 0.
1383      */
1384     Posf *prev = s->prev;
1385     uInt wmask = s->w_mask;
1386 
1387 #ifdef UNALIGNED_OK
1388     /* Compare two bytes at a time. Note: this is not always beneficial.
1389      * Try with and without -DUNALIGNED_OK to check.
1390      */
1391     register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
1392     register ush scan_start = *(ushf*)scan;

1500             if (len >= nice_match) break;
1501 #ifdef UNALIGNED_OK
1502             scan_end = *(ushf*)(scan + best_len - 1);
1503 #else
1504             scan_end1  = scan[best_len - 1];
1505             scan_end   = scan[best_len];
1506 #endif
1507         }
1508     } while ((cur_match = prev[cur_match & wmask]) > limit
1509              && --chain_length != 0);
1510 
1511     if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
1512     return s->lookahead;
1513 }
1514 
1515 #else /* FASTEST */
1516 
1517 /* ---------------------------------------------------------------------------
1518  * Optimized version for FASTEST only
1519  */
1520 local uInt longest_match(deflate_state *s, IPos cur_match) {



1521     register Bytef *scan = s->window + s->strstart; /* current string */
1522     register Bytef *match;                       /* matched string */
1523     register int len;                           /* length of current match */
1524     register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1525 
1526     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1527      * It is easy to get rid of this optimization if necessary.
1528      */
1529     Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1530 
1531     Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1532            "need lookahead");
1533 
1534     Assert(cur_match < s->strstart, "no future");
1535 
1536     match = s->window + cur_match;
1537 
1538     /* Return failure if the match length is less than 2:
1539      */
1540     if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;

1561     Assert(scan <= s->window + (unsigned)(s->window_size - 1), "wild scan");
1562 
1563     len = MAX_MATCH - (int)(strend - scan);
1564 
1565     if (len < MIN_MATCH) return MIN_MATCH - 1;
1566 
1567     s->match_start = cur_match;
1568     return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
1569 }
1570 
1571 #endif /* FASTEST */
1572 
1573 #ifdef ZLIB_DEBUG
1574 
1575 #define EQUAL 0
1576 /* result of memcmp for equal strings */
1577 
1578 /* ===========================================================================
1579  * Check that the match at match_start is indeed a match.
1580  */
1581 local void check_match(deflate_state *s, IPos start, IPos match, int length) {




1582     /* check that the match is indeed a match */
1583     Bytef *back = s->window + (int)match, *here = s->window + start;
1584     IPos len = length;
1585     if (match == (IPos)-1) {
1586         /* match starts one byte before the current window -- just compare the
1587            subsequent length-1 bytes */
1588         back++;
1589         here++;
1590         len--;
1591     }
1592     if (zmemcmp(back, here, len) != EQUAL) {
1593         fprintf(stderr, " start %u, match %d, length %d\n",
1594                 start, (int)match, length);
1595         do {
1596             fprintf(stderr, "(%02x %02x)", *back++, *here++);
1597         } while (--len != 0);
1598         z_error("invalid match");
1599     }
1600     if (z_verbose > 1) {
1601         fprintf(stderr,"\\[%d,%d]", start - match, length);
1602         do { putc(s->window[start++], stderr); } while (--length != 0);
1603     }
1604 }
1605 #else
1606 #  define check_match(s, start, match, length)
1607 #endif /* ZLIB_DEBUG */
1608 



































































































































1609 /* ===========================================================================
1610  * Flush the current block, with given end-of-file flag.
1611  * IN assertion: strstart is set to the end of the current match.
1612  */
1613 #define FLUSH_BLOCK_ONLY(s, last) { \
1614    _tr_flush_block(s, (s->block_start >= 0L ? \
1615                    (charf *)&s->window[(unsigned)s->block_start] : \
1616                    (charf *)Z_NULL), \
1617                 (ulg)((long)s->strstart - s->block_start), \
1618                 (last)); \
1619    s->block_start = s->strstart; \
1620    flush_pending(s->strm); \
1621    Tracev((stderr,"[FLUSH]")); \
1622 }
1623 
1624 /* Same but force premature exit if necessary. */
1625 #define FLUSH_BLOCK(s, last) { \
1626    FLUSH_BLOCK_ONLY(s, last); \
1627    if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
1628 }

1631 #define MAX_STORED 65535
1632 
1633 /* Minimum of a and b. */
1634 #define MIN(a, b) ((a) > (b) ? (b) : (a))
1635 
1636 /* ===========================================================================
1637  * Copy without compression as much as possible from the input stream, return
1638  * the current block state.
1639  *
1640  * In case deflateParams() is used to later switch to a non-zero compression
1641  * level, s->matches (otherwise unused when storing) keeps track of the number
1642  * of hash table slides to perform. If s->matches is 1, then one hash table
1643  * slide will be done when switching. If s->matches is 2, the maximum value
1644  * allowed here, then the hash table will be cleared, since two or more slides
1645  * is the same as a clear.
1646  *
1647  * deflate_stored() is written to minimize the number of times an input byte is
1648  * copied. It is most efficient with large input and output buffers, which
1649  * maximizes the opportunities to have a single copy from next_in to next_out.
1650  */
1651 local block_state deflate_stored(deflate_state *s, int flush) {



1652     /* Smallest worthy block size when not flushing or finishing. By default
1653      * this is 32K. This can be as small as 507 bytes for memLevel == 1. For
1654      * large input and output buffers, the stored block size will be larger.
1655      */
1656     unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size);
1657 
1658     /* Copy as many min_block or larger stored blocks directly to next_out as
1659      * possible. If flushing, copy the remaining available input to next_out as
1660      * stored blocks, if there is enough space.
1661      */
1662     unsigned len, left, have, last = 0;
1663     unsigned used = s->strm->avail_in;
1664     do {
1665         /* Set len to the maximum size block that we can copy directly with the
1666          * available input data and output space. Set left to how much of that
1667          * would be copied from what's left in the window.
1668          */
1669         len = MAX_STORED;       /* maximum deflate stored block length */
1670         have = (s->bi_valid + 42) >> 3;         /* number of header bytes */
1671         if (s->strm->avail_out < have)          /* need room for header */

1815          s->strm->avail_in == 0 && left <= have)) {
1816         len = MIN(left, have);
1817         last = flush == Z_FINISH && s->strm->avail_in == 0 &&
1818                len == left ? 1 : 0;
1819         _tr_stored_block(s, (charf *)s->window + s->block_start, len, last);
1820         s->block_start += len;
1821         flush_pending(s->strm);
1822     }
1823 
1824     /* We've done all we can with the available input and output. */
1825     return last ? finish_started : need_more;
1826 }
1827 
1828 /* ===========================================================================
1829  * Compress as much as possible from the input stream, return the current
1830  * block state.
1831  * This function does not perform lazy evaluation of matches and inserts
1832  * new strings in the dictionary only for unmatched strings or for short
1833  * matches. It is used only for the fast compression options.
1834  */
1835 local block_state deflate_fast(deflate_state *s, int flush) {



1836     IPos hash_head;       /* head of the hash chain */
1837     int bflush;           /* set if current block must be flushed */
1838 
1839     for (;;) {
1840         /* Make sure that we always have enough lookahead, except
1841          * at the end of the input file. We need MAX_MATCH bytes
1842          * for the next match, plus MIN_MATCH bytes to insert the
1843          * string following the next match.
1844          */
1845         if (s->lookahead < MIN_LOOKAHEAD) {
1846             fill_window(s);
1847             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1848                 return need_more;
1849             }
1850             if (s->lookahead == 0) break; /* flush the current block */
1851         }
1852 
1853         /* Insert the string window[strstart .. strstart + 2] in the
1854          * dictionary, and set hash_head to the head of the hash chain:
1855          */

1914             s->strstart++;
1915         }
1916         if (bflush) FLUSH_BLOCK(s, 0);
1917     }
1918     s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
1919     if (flush == Z_FINISH) {
1920         FLUSH_BLOCK(s, 1);
1921         return finish_done;
1922     }
1923     if (s->sym_next)
1924         FLUSH_BLOCK(s, 0);
1925     return block_done;
1926 }
1927 
1928 #ifndef FASTEST
1929 /* ===========================================================================
1930  * Same as above, but achieves better compression. We use a lazy
1931  * evaluation for matches: a match is finally adopted only if there is
1932  * no better match at the next window position.
1933  */
1934 local block_state deflate_slow(deflate_state *s, int flush) {



1935     IPos hash_head;          /* head of hash chain */
1936     int bflush;              /* set if current block must be flushed */
1937 
1938     /* Process the input block. */
1939     for (;;) {
1940         /* Make sure that we always have enough lookahead, except
1941          * at the end of the input file. We need MAX_MATCH bytes
1942          * for the next match, plus MIN_MATCH bytes to insert the
1943          * string following the next match.
1944          */
1945         if (s->lookahead < MIN_LOOKAHEAD) {
1946             fill_window(s);
1947             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1948                 return need_more;
1949             }
1950             if (s->lookahead == 0) break; /* flush the current block */
1951         }
1952 
1953         /* Insert the string window[strstart .. strstart + 2] in the
1954          * dictionary, and set hash_head to the head of the hash chain:

2042         Tracevv((stderr,"%c", s->window[s->strstart - 1]));
2043         _tr_tally_lit(s, s->window[s->strstart - 1], bflush);
2044         s->match_available = 0;
2045     }
2046     s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
2047     if (flush == Z_FINISH) {
2048         FLUSH_BLOCK(s, 1);
2049         return finish_done;
2050     }
2051     if (s->sym_next)
2052         FLUSH_BLOCK(s, 0);
2053     return block_done;
2054 }
2055 #endif /* FASTEST */
2056 
2057 /* ===========================================================================
2058  * For Z_RLE, simply look for runs of bytes, generate matches only of distance
2059  * one.  Do not maintain a hash table.  (It will be regenerated if this run of
2060  * deflate switches away from Z_RLE.)
2061  */
2062 local block_state deflate_rle(deflate_state *s, int flush) {



2063     int bflush;             /* set if current block must be flushed */
2064     uInt prev;              /* byte at distance one to match */
2065     Bytef *scan, *strend;   /* scan goes up to strend for length of run */
2066 
2067     for (;;) {
2068         /* Make sure that we always have enough lookahead, except
2069          * at the end of the input file. We need MAX_MATCH bytes
2070          * for the longest run, plus one for the unrolled loop.
2071          */
2072         if (s->lookahead <= MAX_MATCH) {
2073             fill_window(s);
2074             if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {
2075                 return need_more;
2076             }
2077             if (s->lookahead == 0) break; /* flush the current block */
2078         }
2079 
2080         /* See how many times the previous byte repeats */
2081         s->match_length = 0;
2082         if (s->lookahead >= MIN_MATCH && s->strstart > 0) {

2113             _tr_tally_lit(s, s->window[s->strstart], bflush);
2114             s->lookahead--;
2115             s->strstart++;
2116         }
2117         if (bflush) FLUSH_BLOCK(s, 0);
2118     }
2119     s->insert = 0;
2120     if (flush == Z_FINISH) {
2121         FLUSH_BLOCK(s, 1);
2122         return finish_done;
2123     }
2124     if (s->sym_next)
2125         FLUSH_BLOCK(s, 0);
2126     return block_done;
2127 }
2128 
2129 /* ===========================================================================
2130  * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
2131  * (It will be regenerated if this run of deflate switches away from Huffman.)
2132  */
2133 local block_state deflate_huff(deflate_state *s, int flush) {



2134     int bflush;             /* set if current block must be flushed */
2135 
2136     for (;;) {
2137         /* Make sure that we have a literal to write. */
2138         if (s->lookahead == 0) {
2139             fill_window(s);
2140             if (s->lookahead == 0) {
2141                 if (flush == Z_NO_FLUSH)
2142                     return need_more;
2143                 break;      /* flush the current block */
2144             }
2145         }
2146 
2147         /* Output a literal byte */
2148         s->match_length = 0;
2149         Tracevv((stderr,"%c", s->window[s->strstart]));
2150         _tr_tally_lit(s, s->window[s->strstart], bflush);
2151         s->lookahead--;
2152         s->strstart++;
2153         if (bflush) FLUSH_BLOCK(s, 0);
< prev index next >