1 /*
   2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.  Oracle designates this
   7  * particular file as subject to the "Classpath" exception as provided
   8  * by Oracle in the LICENSE file that accompanied this code.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  */
  24 
  25 /* 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.
  47  *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  48  *      (by Leonid Broukhis).
  49  *         A previous version of this file used a more sophisticated algorithm
  50  *      (by Fiala and Greene) which is guaranteed to run in linear amortized
  51  *      time, but has a larger average cost, uses more memory and is patented.
  52  *      However the F&G algorithm may be faster for some highly redundant
  53  *      files if the parameter max_chain_length (described below) is too large.
  54  *
  55  *  ACKNOWLEDGEMENTS
  56  *
  57  *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  58  *      I found it in 'freeze' written by Leonid Broukhis.
  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 */
 124    ush max_lazy;    /* do not perform lazy search above this match length */
 125    ush nice_length; /* quit search above this match length */
 126    ush max_chain;
 127    compress_func func;
 128 } config;
 129 
 130 #ifdef FASTEST
 131 local const config configuration_table[2] = {
 132 /*      good lazy nice chain */
 133 /* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
 134 /* 1 */ {4,    4,  8,    4, deflate_fast}}; /* max speed, no lazy matches */
 135 #else
 136 local const config configuration_table[10] = {
 137 /*      good lazy nice chain */
 138 /* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
 139 /* 1 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */
 140 /* 2 */ {4,    5, 16,    8, deflate_fast},
 141 /* 3 */ {4,    6, 32,   32, deflate_fast},
 142 
 143 /* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
 144 /* 5 */ {8,   16, 32,   32, deflate_slow},
 145 /* 6 */ {8,   16, 128, 128, deflate_slow},
 146 /* 7 */ {8,   32, 128, 256, deflate_slow},
 147 /* 8 */ {32, 128, 258, 1024, deflate_slow},
 148 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
 149 #endif
 150 
 151 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
 152  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
 153  * meaning.
 154  */
 155 
 156 /* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */
 157 #define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0))
 158 
 159 /* ===========================================================================
 160  * Update a hash value with the given input byte
 161  * IN  assertion: all calls to UPDATE_HASH are made with consecutive input
 162  *    characters, so that a running hash key can be computed from the previous
 163  *    key instead of complete recalculation each time.
 164  */
 165 #define UPDATE_HASH(s,h,c) (h = (((h) << s->hash_shift) ^ (c)) & s->hash_mask)
 166 
 167 
 168 /* ===========================================================================
 169  * Insert string str in the dictionary and set match_head to the previous head
 170  * of the hash chain (the most recent string with same hash key). Return
 171  * the previous length of the hash chain.
 172  * If this file is compiled with -DFASTEST, the compression level is forced
 173  * to 1, and no hash chains are maintained.
 174  * IN  assertion: all calls to INSERT_STRING are made with consecutive input
 175  *    characters and the first MIN_MATCH bytes of str are valid (except for
 176  *    the last MIN_MATCH-1 bytes of the input file).
 177  */
 178 #ifdef FASTEST
 179 #define INSERT_STRING(s, str, match_head) \
 180    (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
 181     match_head = s->head[s->ins_h], \
 182     s->head[s->ins_h] = (Pos)(str))
 183 #else
 184 #define INSERT_STRING(s, str, match_head) \
 185    (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
 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)
 426 #ifdef Z_SOLO
 427         return Z_STREAM_ERROR;
 428 #else
 429         strm->zfree = zcfree;
 430 #endif
 431 
 432 #ifdef FASTEST
 433     if (level != 0) level = 1;
 434 #else
 435     if (level == Z_DEFAULT_COMPRESSION) level = 6;
 436 #endif
 437 
 438     if (windowBits < 0) { /* suppress zlib wrapper */
 439         wrap = 0;
 440         if (windowBits < -15)
 441             return Z_STREAM_ERROR;
 442         windowBits = -windowBits;
 443     }
 444 #ifdef GZIP
 445     else if (windowBits > 15) {
 446         wrap = 2;       /* write gzip wrapper instead */
 447         windowBits -= 16;
 448     }
 449 #endif
 450     if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
 451         windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
 452         strategy < 0 || strategy > Z_FIXED || (windowBits == 8 && wrap != 1)) {
 453         return Z_STREAM_ERROR;
 454     }
 455     if (windowBits == 8) windowBits = 9;  /* until 256-byte window bug fixed */
 456     s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
 457     if (s == Z_NULL) return Z_MEM_ERROR;
 458     strm->state = (struct internal_state FAR *)s;
 459     s->strm = strm;
 460     s->status = INIT_STATE;     /* to pass state test in deflateReset() */
 461 
 462     s->wrap = wrap;
 463     s->gzhead = Z_NULL;
 464     s->w_bits = (uInt)windowBits;
 465     s->w_size = 1 << s->w_bits;
 466     s->w_mask = s->w_size - 1;
 467 
 468     s->hash_bits = (uInt)memLevel + 7;
 469     s->hash_size = 1 << s->hash_bits;
 470     s->hash_mask = s->hash_size - 1;
 471     s->hash_shift =  ((s->hash_bits + MIN_MATCH-1) / MIN_MATCH);
 472 
 473     s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
 474     s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
 475     s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
 476 
 477     s->high_water = 0;      /* nothing written to s->window yet */
 478 
 479     s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
 480 
 481     /* We overlay pending_buf and sym_buf. This works since the average size
 482      * for length/distance pairs over any compressed block is assured to be 31
 483      * bits or less.
 484      *
 485      * Analysis: The longest fixed codes are a length code of 8 bits plus 5
 486      * extra bits, for lengths 131 to 257. The longest fixed distance codes are
 487      * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest
 488      * possible fixed-codes length/distance pair is then 31 bits total.
 489      *
 490      * sym_buf starts one-fourth of the way into pending_buf. So there are
 491      * three bytes in sym_buf for every four bytes in pending_buf. Each symbol
 492      * in sym_buf is three bytes -- two for the distance and one for the
 493      * literal/length. As each symbol is consumed, the pointer to the next
 494      * sym_buf value to read moves forward three bytes. From that symbol, up to
 495      * 31 bits are written to pending_buf. The closest the written pending_buf
 496      * bits gets to the next sym_buf symbol to read is just before the last
 497      * code is written. At that time, 31*(n - 2) bits have been written, just
 498      * after 24*(n - 2) bits have been consumed from sym_buf. sym_buf starts at
 499      * 8*n bits into pending_buf. (Note that the symbol buffer fills when n - 1
 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) {
 596         if (wrap == 0) {            /* already empty otherwise */
 597             CLEAR_HASH(s);
 598             s->strstart = 0;
 599             s->block_start = 0L;
 600             s->insert = 0;
 601         }
 602         dictionary += dictLength - s->w_size;  /* use the tail */
 603         dictLength = s->w_size;
 604     }
 605 
 606     /* insert dictionary into window and hash */
 607     avail = strm->avail_in;
 608     next = strm->next_in;
 609     strm->avail_in = dictLength;
 610     strm->next_in = (z_const Bytef *)dictionary;
 611     fill_window(s);
 612     while (s->lookahead >= MIN_MATCH) {
 613         str = s->strstart;
 614         n = s->lookahead - (MIN_MATCH-1);
 615         do {
 616             UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
 617 #ifndef FASTEST
 618             s->prev[str & s->w_mask] = s->head[s->ins_h];
 619 #endif
 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);
 797         if (err == Z_STREAM_ERROR)
 798             return err;
 799         if (strm->avail_in || (s->strstart - s->block_start) + s->lookahead)
 800             return Z_BUF_ERROR;
 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;
 879     switch (s->wrap) {
 880     case 0:                                 /* raw deflate */
 881         wraplen = 0;
 882         break;
 883     case 1:                                 /* zlib wrapper */
 884         wraplen = 6 + (s->strstart ? 4 : 0);
 885         break;
 886 #ifdef GZIP
 887     case 2:                                 /* gzip wrapper */
 888         wraplen = 18;
 889         if (s->gzhead != Z_NULL) {          /* user-supplied gzip header */
 890             Bytef *str;
 891             if (s->gzhead->extra != Z_NULL)
 892                 wraplen += 2 + s->gzhead->extra_len;
 893             str = s->gzhead->name;
 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) {
 991         flush_pending(strm);
 992         if (strm->avail_out == 0) {
 993             /* Since avail_out is 0, deflate will be called again with
 994              * more output space, but possibly with both pending and
 995              * avail_in equal to zero. There won't be anything to do,
 996              * but this is not an error situation so make sure we
 997              * return OK instead of BUF_ERROR at next call of deflate:
 998              */
 999             s->last_flush = -1;
1000             return Z_OK;
1001         }
1002 
1003     /* Make sure there is something to do and avoid duplicate consecutive
1004      * flushes. For repeated and useless calls with Z_FINISH, we keep
1005      * returning Z_STREAM_END instead of Z_BUF_ERROR.
1006      */
1007     } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&
1008                flush != Z_FINISH) {
1009         ERR_RETURN(strm, Z_BUF_ERROR);
1010     }
1011 
1012     /* User must not provide more input after the first FINISH: */
1013     if (s->status == FINISH_STATE && strm->avail_in != 0) {
1014         ERR_RETURN(strm, Z_BUF_ERROR);
1015     }
1016 
1017     /* Write the header */
1018     if (s->status == INIT_STATE && s->wrap == 0)
1019         s->status = BUSY_STATE;
1020     if (s->status == INIT_STATE) {
1021         /* zlib header */
1022         uInt header = (Z_DEFLATED + ((s->w_bits - 8) << 4)) << 8;
1023         uInt level_flags;
1024 
1025         if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
1026             level_flags = 0;
1027         else if (s->level < 6)
1028             level_flags = 1;
1029         else if (s->level == 6)
1030             level_flags = 2;
1031         else
1032             level_flags = 3;
1033         header |= (level_flags << 6);
1034         if (s->strstart != 0) header |= PRESET_DICT;
1035         header += 31 - (header % 31);
1036 
1037         putShortMSB(s, header);
1038 
1039         /* Save the adler32 of the preset dictionary: */
1040         if (s->strstart != 0) {
1041             putShortMSB(s, (uInt)(strm->adler >> 16));
1042             putShortMSB(s, (uInt)(strm->adler & 0xffff));
1043         }
1044         strm->adler = adler32(0L, Z_NULL, 0);
1045         s->status = BUSY_STATE;
1046 
1047         /* Compression must start with an empty pending buffer */
1048         flush_pending(strm);
1049         if (s->pending != 0) {
1050             s->last_flush = -1;
1051             return Z_OK;
1052         }
1053     }
1054 #ifdef GZIP
1055     if (s->status == GZIP_STATE) {
1056         /* gzip header */
1057         strm->adler = crc32(0L, Z_NULL, 0);
1058         put_byte(s, 31);
1059         put_byte(s, 139);
1060         put_byte(s, 8);
1061         if (s->gzhead == Z_NULL) {
1062             put_byte(s, 0);
1063             put_byte(s, 0);
1064             put_byte(s, 0);
1065             put_byte(s, 0);
1066             put_byte(s, 0);
1067             put_byte(s, s->level == 9 ? 2 :
1068                      (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
1069                       4 : 0));
1070             put_byte(s, OS_CODE);
1071             s->status = BUSY_STATE;
1072 
1073             /* Compression must start with an empty pending buffer */
1074             flush_pending(strm);
1075             if (s->pending != 0) {
1076                 s->last_flush = -1;
1077                 return Z_OK;
1078             }
1079         }
1080         else {
1081             put_byte(s, (s->gzhead->text ? 1 : 0) +
1082                      (s->gzhead->hcrc ? 2 : 0) +
1083                      (s->gzhead->extra == Z_NULL ? 0 : 4) +
1084                      (s->gzhead->name == Z_NULL ? 0 : 8) +
1085                      (s->gzhead->comment == Z_NULL ? 0 : 16)
1086                      );
1087             put_byte(s, (Byte)(s->gzhead->time & 0xff));
1088             put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
1089             put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
1090             put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
1091             put_byte(s, s->level == 9 ? 2 :
1092                      (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
1093                       4 : 0));
1094             put_byte(s, s->gzhead->os & 0xff);
1095             if (s->gzhead->extra != Z_NULL) {
1096                 put_byte(s, s->gzhead->extra_len & 0xff);
1097                 put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
1098             }
1099             if (s->gzhead->hcrc)
1100                 strm->adler = crc32(strm->adler, s->pending_buf,
1101                                     s->pending);
1102             s->gzindex = 0;
1103             s->status = EXTRA_STATE;
1104         }
1105     }
1106     if (s->status == EXTRA_STATE) {
1107         if (s->gzhead->extra != Z_NULL) {
1108             ulg beg = s->pending;   /* start of bytes to update crc */
1109             uInt left = (s->gzhead->extra_len & 0xffff) - s->gzindex;
1110             while (s->pending + left > s->pending_buf_size) {
1111                 uInt copy = s->pending_buf_size - s->pending;
1112                 zmemcpy(s->pending_buf + s->pending,
1113                         s->gzhead->extra + s->gzindex, copy);
1114                 s->pending = s->pending_buf_size;
1115                 HCRC_UPDATE(beg);
1116                 s->gzindex += copy;
1117                 flush_pending(strm);
1118                 if (s->pending != 0) {
1119                     s->last_flush = -1;
1120                     return Z_OK;
1121                 }
1122                 beg = 0;
1123                 left -= copy;
1124             }
1125             zmemcpy(s->pending_buf + s->pending,
1126                     s->gzhead->extra + s->gzindex, left);
1127             s->pending += left;
1128             HCRC_UPDATE(beg);
1129             s->gzindex = 0;
1130         }
1131         s->status = NAME_STATE;
1132     }
1133     if (s->status == NAME_STATE) {
1134         if (s->gzhead->name != Z_NULL) {
1135             ulg beg = s->pending;   /* start of bytes to update crc */
1136             int val;
1137             do {
1138                 if (s->pending == s->pending_buf_size) {
1139                     HCRC_UPDATE(beg);
1140                     flush_pending(strm);
1141                     if (s->pending != 0) {
1142                         s->last_flush = -1;
1143                         return Z_OK;
1144                     }
1145                     beg = 0;
1146                 }
1147                 val = s->gzhead->name[s->gzindex++];
1148                 put_byte(s, val);
1149             } while (val != 0);
1150             HCRC_UPDATE(beg);
1151             s->gzindex = 0;
1152         }
1153         s->status = COMMENT_STATE;
1154     }
1155     if (s->status == COMMENT_STATE) {
1156         if (s->gzhead->comment != Z_NULL) {
1157             ulg beg = s->pending;   /* start of bytes to update crc */
1158             int val;
1159             do {
1160                 if (s->pending == s->pending_buf_size) {
1161                     HCRC_UPDATE(beg);
1162                     flush_pending(strm);
1163                     if (s->pending != 0) {
1164                         s->last_flush = -1;
1165                         return Z_OK;
1166                     }
1167                     beg = 0;
1168                 }
1169                 val = s->gzhead->comment[s->gzindex++];
1170                 put_byte(s, val);
1171             } while (val != 0);
1172             HCRC_UPDATE(beg);
1173         }
1174         s->status = HCRC_STATE;
1175     }
1176     if (s->status == HCRC_STATE) {
1177         if (s->gzhead->hcrc) {
1178             if (s->pending + 2 > s->pending_buf_size) {
1179                 flush_pending(strm);
1180                 if (s->pending != 0) {
1181                     s->last_flush = -1;
1182                     return Z_OK;
1183                 }
1184             }
1185             put_byte(s, (Byte)(strm->adler & 0xff));
1186             put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
1187             strm->adler = crc32(0L, Z_NULL, 0);
1188         }
1189         s->status = BUSY_STATE;
1190 
1191         /* Compression must start with an empty pending buffer */
1192         flush_pending(strm);
1193         if (s->pending != 0) {
1194             s->last_flush = -1;
1195             return Z_OK;
1196         }
1197     }
1198 #endif
1199 
1200     /* Start a new block or continue the current one.
1201      */
1202     if (strm->avail_in != 0 || s->lookahead != 0 ||
1203         (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
1204         block_state bstate;
1205 
1206         bstate = s->level == 0 ? deflate_stored(s, flush) :
1207                  s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
1208                  s->strategy == Z_RLE ? deflate_rle(s, flush) :
1209                  (*(configuration_table[s->level].func))(s, flush);
1210 
1211         if (bstate == finish_started || bstate == finish_done) {
1212             s->status = FINISH_STATE;
1213         }
1214         if (bstate == need_more || bstate == finish_started) {
1215             if (strm->avail_out == 0) {
1216                 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
1217             }
1218             return Z_OK;
1219             /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
1220              * of deflate should use the same flush parameter to make sure
1221              * that the flush is complete. So we don't have to output an
1222              * empty block here, this will be done at next call. This also
1223              * ensures that for a very small output buffer, we emit at most
1224              * one empty block.
1225              */
1226         }
1227         if (bstate == block_done) {
1228             if (flush == Z_PARTIAL_FLUSH) {
1229                 _tr_align(s);
1230             } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
1231                 _tr_stored_block(s, (char*)0, 0L, 0);
1232                 /* For a full flush, this empty block will be recognized
1233                  * as a special marker by inflate_sync().
1234                  */
1235                 if (flush == Z_FULL_FLUSH) {
1236                     CLEAR_HASH(s);             /* forget history */
1237                     if (s->lookahead == 0) {
1238                         s->strstart = 0;
1239                         s->block_start = 0L;
1240                         s->insert = 0;
1241                     }
1242                 }
1243             }
1244             flush_pending(strm);
1245             if (strm->avail_out == 0) {
1246               s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
1247               return Z_OK;
1248             }
1249         }
1250     }
1251 
1252     if (flush != Z_FINISH) return Z_OK;
1253     if (s->wrap <= 0) return Z_STREAM_END;
1254 
1255     /* Write the trailer */
1256 #ifdef GZIP
1257     if (s->wrap == 2) {
1258         put_byte(s, (Byte)(strm->adler & 0xff));
1259         put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
1260         put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
1261         put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
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;
1393     register ush scan_end   = *(ushf*)(scan + best_len - 1);
1394 #else
1395     register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1396     register Byte scan_end1  = scan[best_len - 1];
1397     register Byte scan_end   = scan[best_len];
1398 #endif
1399 
1400     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1401      * It is easy to get rid of this optimization if necessary.
1402      */
1403     Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1404 
1405     /* Do not waste too much time if we already have a good match: */
1406     if (s->prev_length >= s->good_match) {
1407         chain_length >>= 2;
1408     }
1409     /* Do not look for matches beyond the end of the input. This is necessary
1410      * to make deflate deterministic.
1411      */
1412     if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead;
1413 
1414     Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1415            "need lookahead");
1416 
1417     do {
1418         Assert(cur_match < s->strstart, "no future");
1419         match = s->window + cur_match;
1420 
1421         /* Skip to next match if the match length cannot increase
1422          * or if the match length is less than 2.  Note that the checks below
1423          * for insufficient lookahead only occur occasionally for performance
1424          * reasons.  Therefore uninitialized memory will be accessed, and
1425          * conditional jumps will be made that depend on those values.
1426          * However the length of the match is limited to the lookahead, so
1427          * the output of deflate is not affected by the uninitialized values.
1428          */
1429 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
1430         /* This code assumes sizeof(unsigned short) == 2. Do not use
1431          * UNALIGNED_OK if your compiler uses a different size.
1432          */
1433         if (*(ushf*)(match + best_len - 1) != scan_end ||
1434             *(ushf*)match != scan_start) continue;
1435 
1436         /* It is not necessary to compare scan[2] and match[2] since they are
1437          * always equal when the other bytes match, given that the hash keys
1438          * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
1439          * strstart + 3, + 5, up to strstart + 257. We check for insufficient
1440          * lookahead only every 4th comparison; the 128th check will be made
1441          * at strstart + 257. If MAX_MATCH-2 is not a multiple of 8, it is
1442          * necessary to put more guard bytes at the end of the window, or
1443          * to check more often for insufficient lookahead.
1444          */
1445         Assert(scan[2] == match[2], "scan[2]?");
1446         scan++, match++;
1447         do {
1448         } while (*(ushf*)(scan += 2) == *(ushf*)(match += 2) &&
1449                  *(ushf*)(scan += 2) == *(ushf*)(match += 2) &&
1450                  *(ushf*)(scan += 2) == *(ushf*)(match += 2) &&
1451                  *(ushf*)(scan += 2) == *(ushf*)(match += 2) &&
1452                  scan < strend);
1453         /* The funny "do {}" generates better code on most compilers */
1454 
1455         /* Here, scan <= window + strstart + 257 */
1456         Assert(scan <= s->window + (unsigned)(s->window_size - 1),
1457                "wild scan");
1458         if (*scan == *match) scan++;
1459 
1460         len = (MAX_MATCH - 1) - (int)(strend - scan);
1461         scan = strend - (MAX_MATCH-1);
1462 
1463 #else /* UNALIGNED_OK */
1464 
1465         if (match[best_len]     != scan_end  ||
1466             match[best_len - 1] != scan_end1 ||
1467             *match              != *scan     ||
1468             *++match            != scan[1])      continue;
1469 
1470         /* The check at best_len - 1 can be removed because it will be made
1471          * again later. (This heuristic is not always a win.)
1472          * It is not necessary to compare scan[2] and match[2] since they
1473          * are always equal when the other bytes match, given that
1474          * the hash keys are equal and that HASH_BITS >= 8.
1475          */
1476         scan += 2, match++;
1477         Assert(*scan == *match, "match[2]?");
1478 
1479         /* We check for insufficient lookahead only every 8th comparison;
1480          * the 256th check will be made at strstart + 258.
1481          */
1482         do {
1483         } while (*++scan == *++match && *++scan == *++match &&
1484                  *++scan == *++match && *++scan == *++match &&
1485                  *++scan == *++match && *++scan == *++match &&
1486                  *++scan == *++match && *++scan == *++match &&
1487                  scan < strend);
1488 
1489         Assert(scan <= s->window + (unsigned)(s->window_size - 1),
1490                "wild scan");
1491 
1492         len = MAX_MATCH - (int)(strend - scan);
1493         scan = strend - MAX_MATCH;
1494 
1495 #endif /* UNALIGNED_OK */
1496 
1497         if (len > best_len) {
1498             s->match_start = cur_match;
1499             best_len = len;
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;
1541 
1542     /* The check at best_len - 1 can be removed because it will be made
1543      * again later. (This heuristic is not always a win.)
1544      * It is not necessary to compare scan[2] and match[2] since they
1545      * are always equal when the other bytes match, given that
1546      * the hash keys are equal and that HASH_BITS >= 8.
1547      */
1548     scan += 2, match += 2;
1549     Assert(*scan == *match, "match[2]?");
1550 
1551     /* We check for insufficient lookahead only every 8th comparison;
1552      * the 256th check will be made at strstart + 258.
1553      */
1554     do {
1555     } while (*++scan == *++match && *++scan == *++match &&
1556              *++scan == *++match && *++scan == *++match &&
1557              *++scan == *++match && *++scan == *++match &&
1558              *++scan == *++match && *++scan == *++match &&
1559              scan < strend);
1560 
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 }
1629 
1630 /* Maximum stored block length in deflate format (not including header). */
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 */
1672             break;
1673             /* maximum stored block length that will fit in avail_out: */
1674         have = s->strm->avail_out - have;
1675         left = s->strstart - s->block_start;    /* bytes left in window */
1676         if (len > (ulg)left + s->strm->avail_in)
1677             len = left + s->strm->avail_in;     /* limit len to the input */
1678         if (len > have)
1679             len = have;                         /* limit len to the output */
1680 
1681         /* If the stored block would be less than min_block in length, or if
1682          * unable to copy all of the available input when flushing, then try
1683          * copying to the window and the pending buffer instead. Also don't
1684          * write an empty block when flushing -- deflate() does that.
1685          */
1686         if (len < min_block && ((len == 0 && flush != Z_FINISH) ||
1687                                 flush == Z_NO_FLUSH ||
1688                                 len != left + s->strm->avail_in))
1689             break;
1690 
1691         /* Make a dummy stored block in pending to get the header bytes,
1692          * including any pending bits. This also updates the debugging counts.
1693          */
1694         last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0;
1695         _tr_stored_block(s, (char *)0, 0L, last);
1696 
1697         /* Replace the lengths in the dummy stored block with len. */
1698         s->pending_buf[s->pending - 4] = len;
1699         s->pending_buf[s->pending - 3] = len >> 8;
1700         s->pending_buf[s->pending - 2] = ~len;
1701         s->pending_buf[s->pending - 1] = ~len >> 8;
1702 
1703         /* Write the stored block header bytes. */
1704         flush_pending(s->strm);
1705 
1706 #ifdef ZLIB_DEBUG
1707         /* Update debugging counts for the data about to be copied. */
1708         s->compressed_len += len << 3;
1709         s->bits_sent += len << 3;
1710 #endif
1711 
1712         /* Copy uncompressed bytes from the window to next_out. */
1713         if (left) {
1714             if (left > len)
1715                 left = len;
1716             zmemcpy(s->strm->next_out, s->window + s->block_start, left);
1717             s->strm->next_out += left;
1718             s->strm->avail_out -= left;
1719             s->strm->total_out += left;
1720             s->block_start += left;
1721             len -= left;
1722         }
1723 
1724         /* Copy uncompressed bytes directly from next_in to next_out, updating
1725          * the check value.
1726          */
1727         if (len) {
1728             read_buf(s->strm, s->strm->next_out, len);
1729             s->strm->next_out += len;
1730             s->strm->avail_out -= len;
1731             s->strm->total_out += len;
1732         }
1733     } while (last == 0);
1734 
1735     /* Update the sliding window with the last s->w_size bytes of the copied
1736      * data, or append all of the copied data to the existing window if less
1737      * than s->w_size bytes were copied. Also update the number of bytes to
1738      * insert in the hash tables, in the event that deflateParams() switches to
1739      * a non-zero compression level.
1740      */
1741     used -= s->strm->avail_in;      /* number of input bytes directly copied */
1742     if (used) {
1743         /* If any input was used, then no unused input remains in the window,
1744          * therefore s->block_start == s->strstart.
1745          */
1746         if (used >= s->w_size) {    /* supplant the previous history */
1747             s->matches = 2;         /* clear hash */
1748             zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);
1749             s->strstart = s->w_size;
1750             s->insert = s->strstart;
1751         }
1752         else {
1753             if (s->window_size - s->strstart <= used) {
1754                 /* Slide the window down. */
1755                 s->strstart -= s->w_size;
1756                 zmemcpy(s->window, s->window + s->w_size, s->strstart);
1757                 if (s->matches < 2)
1758                     s->matches++;   /* add a pending slide_hash() */
1759                 if (s->insert > s->strstart)
1760                     s->insert = s->strstart;
1761             }
1762             zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);
1763             s->strstart += used;
1764             s->insert += MIN(used, s->w_size - s->insert);
1765         }
1766         s->block_start = s->strstart;
1767     }
1768     if (s->high_water < s->strstart)
1769         s->high_water = s->strstart;
1770 
1771     /* If the last block was written to next_out, then done. */
1772     if (last)
1773         return finish_done;
1774 
1775     /* If flushing and all input has been consumed, then done. */
1776     if (flush != Z_NO_FLUSH && flush != Z_FINISH &&
1777         s->strm->avail_in == 0 && (long)s->strstart == s->block_start)
1778         return block_done;
1779 
1780     /* Fill the window with any remaining input. */
1781     have = s->window_size - s->strstart;
1782     if (s->strm->avail_in > have && s->block_start >= (long)s->w_size) {
1783         /* Slide the window down. */
1784         s->block_start -= s->w_size;
1785         s->strstart -= s->w_size;
1786         zmemcpy(s->window, s->window + s->w_size, s->strstart);
1787         if (s->matches < 2)
1788             s->matches++;           /* add a pending slide_hash() */
1789         have += s->w_size;          /* more space now */
1790         if (s->insert > s->strstart)
1791             s->insert = s->strstart;
1792     }
1793     if (have > s->strm->avail_in)
1794         have = s->strm->avail_in;
1795     if (have) {
1796         read_buf(s->strm, s->window + s->strstart, have);
1797         s->strstart += have;
1798         s->insert += MIN(have, s->w_size - s->insert);
1799     }
1800     if (s->high_water < s->strstart)
1801         s->high_water = s->strstart;
1802 
1803     /* There was not enough avail_out to write a complete worthy or flushed
1804      * stored block to next_out. Write a stored block to pending instead, if we
1805      * have enough input for a worthy block, or if flushing and there is enough
1806      * room for the remaining input as a stored block in the pending buffer.
1807      */
1808     have = (s->bi_valid + 42) >> 3;         /* number of header bytes */
1809         /* maximum stored block length that will fit in pending: */
1810     have = MIN(s->pending_buf_size - have, MAX_STORED);
1811     min_block = MIN(have, s->w_size);
1812     left = s->strstart - s->block_start;
1813     if (left >= min_block ||
1814         ((left || flush == Z_FINISH) && flush != Z_NO_FLUSH &&
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          */
1856         hash_head = NIL;
1857         if (s->lookahead >= MIN_MATCH) {
1858             INSERT_STRING(s, s->strstart, hash_head);
1859         }
1860 
1861         /* Find the longest match, discarding those <= prev_length.
1862          * At this point we have always match_length < MIN_MATCH
1863          */
1864         if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1865             /* To simplify the code, we prevent matches with the string
1866              * of window index 0 (in particular we have to avoid a match
1867              * of the string with itself at the start of the input file).
1868              */
1869             s->match_length = longest_match (s, hash_head);
1870             /* longest_match() sets match_start */
1871         }
1872         if (s->match_length >= MIN_MATCH) {
1873             check_match(s, s->strstart, s->match_start, s->match_length);
1874 
1875             _tr_tally_dist(s, s->strstart - s->match_start,
1876                            s->match_length - MIN_MATCH, bflush);
1877 
1878             s->lookahead -= s->match_length;
1879 
1880             /* Insert new strings in the hash table only if the match length
1881              * is not too large. This saves time but degrades compression.
1882              */
1883 #ifndef FASTEST
1884             if (s->match_length <= s->max_insert_length &&
1885                 s->lookahead >= MIN_MATCH) {
1886                 s->match_length--; /* string at strstart already in table */
1887                 do {
1888                     s->strstart++;
1889                     INSERT_STRING(s, s->strstart, hash_head);
1890                     /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1891                      * always MIN_MATCH bytes ahead.
1892                      */
1893                 } while (--s->match_length != 0);
1894                 s->strstart++;
1895             } else
1896 #endif
1897             {
1898                 s->strstart += s->match_length;
1899                 s->match_length = 0;
1900                 s->ins_h = s->window[s->strstart];
1901                 UPDATE_HASH(s, s->ins_h, s->window[s->strstart + 1]);
1902 #if MIN_MATCH != 3
1903                 Call UPDATE_HASH() MIN_MATCH-3 more times
1904 #endif
1905                 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1906                  * matter since it will be recomputed at next deflate call.
1907                  */
1908             }
1909         } else {
1910             /* No match, output a literal byte */
1911             Tracevv((stderr,"%c", s->window[s->strstart]));
1912             _tr_tally_lit(s, s->window[s->strstart], bflush);
1913             s->lookahead--;
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:
1955          */
1956         hash_head = NIL;
1957         if (s->lookahead >= MIN_MATCH) {
1958             INSERT_STRING(s, s->strstart, hash_head);
1959         }
1960 
1961         /* Find the longest match, discarding those <= prev_length.
1962          */
1963         s->prev_length = s->match_length, s->prev_match = s->match_start;
1964         s->match_length = MIN_MATCH-1;
1965 
1966         if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
1967             s->strstart - hash_head <= MAX_DIST(s)) {
1968             /* To simplify the code, we prevent matches with the string
1969              * of window index 0 (in particular we have to avoid a match
1970              * of the string with itself at the start of the input file).
1971              */
1972             s->match_length = longest_match (s, hash_head);
1973             /* longest_match() sets match_start */
1974 
1975             if (s->match_length <= 5 && (s->strategy == Z_FILTERED
1976 #if TOO_FAR <= 32767
1977                 || (s->match_length == MIN_MATCH &&
1978                     s->strstart - s->match_start > TOO_FAR)
1979 #endif
1980                 )) {
1981 
1982                 /* If prev_match is also MIN_MATCH, match_start is garbage
1983                  * but we will ignore the current match anyway.
1984                  */
1985                 s->match_length = MIN_MATCH-1;
1986             }
1987         }
1988         /* If there was a match at the previous step and the current
1989          * match is not better, output the previous match:
1990          */
1991         if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
1992             uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
1993             /* Do not insert strings in hash table beyond this. */
1994 
1995             check_match(s, s->strstart - 1, s->prev_match, s->prev_length);
1996 
1997             _tr_tally_dist(s, s->strstart - 1 - s->prev_match,
1998                            s->prev_length - MIN_MATCH, bflush);
1999 
2000             /* Insert in hash table all strings up to the end of the match.
2001              * strstart - 1 and strstart are already inserted. If there is not
2002              * enough lookahead, the last two strings are not inserted in
2003              * the hash table.
2004              */
2005             s->lookahead -= s->prev_length - 1;
2006             s->prev_length -= 2;
2007             do {
2008                 if (++s->strstart <= max_insert) {
2009                     INSERT_STRING(s, s->strstart, hash_head);
2010                 }
2011             } while (--s->prev_length != 0);
2012             s->match_available = 0;
2013             s->match_length = MIN_MATCH-1;
2014             s->strstart++;
2015 
2016             if (bflush) FLUSH_BLOCK(s, 0);
2017 
2018         } else if (s->match_available) {
2019             /* If there was no match at the previous position, output a
2020              * single literal. If there was a match but the current match
2021              * is longer, truncate the previous match to a single literal.
2022              */
2023             Tracevv((stderr,"%c", s->window[s->strstart - 1]));
2024             _tr_tally_lit(s, s->window[s->strstart - 1], bflush);
2025             if (bflush) {
2026                 FLUSH_BLOCK_ONLY(s, 0);
2027             }
2028             s->strstart++;
2029             s->lookahead--;
2030             if (s->strm->avail_out == 0) return need_more;
2031         } else {
2032             /* There is no previous match to compare with, wait for
2033              * the next step to decide.
2034              */
2035             s->match_available = 1;
2036             s->strstart++;
2037             s->lookahead--;
2038         }
2039     }
2040     Assert (flush != Z_NO_FLUSH, "no flush?");
2041     if (s->match_available) {
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) {
2083             scan = s->window + s->strstart - 1;
2084             prev = *scan;
2085             if (prev == *++scan && prev == *++scan && prev == *++scan) {
2086                 strend = s->window + s->strstart + MAX_MATCH;
2087                 do {
2088                 } while (prev == *++scan && prev == *++scan &&
2089                          prev == *++scan && prev == *++scan &&
2090                          prev == *++scan && prev == *++scan &&
2091                          prev == *++scan && prev == *++scan &&
2092                          scan < strend);
2093                 s->match_length = MAX_MATCH - (uInt)(strend - scan);
2094                 if (s->match_length > s->lookahead)
2095                     s->match_length = s->lookahead;
2096             }
2097             Assert(scan <= s->window + (uInt)(s->window_size - 1),
2098                    "wild scan");
2099         }
2100 
2101         /* Emit match if have run of MIN_MATCH or longer, else emit literal */
2102         if (s->match_length >= MIN_MATCH) {
2103             check_match(s, s->strstart, s->strstart - 1, s->match_length);
2104 
2105             _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
2106 
2107             s->lookahead -= s->match_length;
2108             s->strstart += s->match_length;
2109             s->match_length = 0;
2110         } else {
2111             /* No match, output a literal byte */
2112             Tracevv((stderr,"%c", s->window[s->strstart]));
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);
2154     }
2155     s->insert = 0;
2156     if (flush == Z_FINISH) {
2157         FLUSH_BLOCK(s, 1);
2158         return finish_done;
2159     }
2160     if (s->sym_next)
2161         FLUSH_BLOCK(s, 0);
2162     return block_done;
2163 }