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-2022 Jean-loup Gailly and Mark Adler
  27  * For conditions of distribution and use, see copyright notice in zlib.h
  28  */
  29 
  30 /*
  31  *  ALGORITHM
  32  *
  33  *      The "deflation" process depends on being able to identify portions
  34  *      of the input text which are identical to earlier input (within a
  35  *      sliding window trailing behind the input currently being processed).
  36  *
  37  *      The most straightforward technique turns out to be the fastest for
  38  *      most input files: try all possible matches and select the longest.
  39  *      The key feature of this algorithm is that insertions into the string
  40  *      dictionary are very simple and thus fast, and deletions are avoided
  41  *      completely. Insertions are performed at each input character, whereas
  42  *      string matches are performed only when the previous match ends. So it
  43  *      is preferable to spend more time in matches to allow very fast string
  44  *      insertions and avoid deletions. The matching algorithm for small
  45  *      strings is inspired from that of Rabin & Karp. A brute force approach
  46  *      is used to find longer strings when a small match has been found.
  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.2.13 Copyright 1995-2022 Jean-loup Gailly and Mark Adler ";
  80 /*
  81   If you use the zlib library in a product, an acknowledgment is welcome
  82   in the documentation of your product. If for some reason you cannot
  83   include such an acknowledgment, I would appreciate that you keep this
  84   copyright string in the executable of your product.
  85  */
  86 
  87 /* ===========================================================================
  88  *  Function prototypes.
  89  */
  90 typedef enum {
  91     need_more,      /* block not completed, need more input or more output */
  92     block_done,     /* block flush performed */
  93     finish_started, /* finish started, need only more output at next deflate */
  94     finish_done     /* finish done, accept no more input or output */
  95 } block_state;
  96 
  97 typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  98 /* Compression function. Returns the block state after the call. */
  99 
 100 local int deflateStateCheck      OF((z_streamp strm));
 101 local void slide_hash     OF((deflate_state *s));
 102 local void fill_window    OF((deflate_state *s));
 103 local block_state deflate_stored OF((deflate_state *s, int flush));
 104 local block_state deflate_fast   OF((deflate_state *s, int flush));
 105 #ifndef FASTEST
 106 local block_state deflate_slow   OF((deflate_state *s, int flush));
 107 #endif
 108 local block_state deflate_rle    OF((deflate_state *s, int flush));
 109 local block_state deflate_huff   OF((deflate_state *s, int flush));
 110 local void lm_init        OF((deflate_state *s));
 111 local void putShortMSB    OF((deflate_state *s, uInt b));
 112 local void flush_pending  OF((z_streamp strm));
 113 local unsigned read_buf   OF((z_streamp strm, Bytef *buf, unsigned size));
 114 local uInt longest_match  OF((deflate_state *s, IPos cur_match));
 115 
 116 #ifdef ZLIB_DEBUG
 117 local  void check_match OF((deflate_state *s, IPos start, IPos match,
 118                             int length));
 119 #endif
 120 
 121 /* ===========================================================================
 122  * Local data
 123  */
 124 
 125 #define NIL 0
 126 /* Tail of hash chains */
 127 
 128 #ifndef TOO_FAR
 129 #  define TOO_FAR 4096
 130 #endif
 131 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
 132 
 133 /* Values for max_lazy_match, good_match and max_chain_length, depending on
 134  * the desired pack level (0..9). The values given below have been tuned to
 135  * exclude worst case performance for pathological files. Better values may be
 136  * found for specific files.
 137  */
 138 typedef struct config_s {
 139    ush good_length; /* reduce lazy search above this match length */
 140    ush max_lazy;    /* do not perform lazy search above this match length */
 141    ush nice_length; /* quit search above this match length */
 142    ush max_chain;
 143    compress_func func;
 144 } config;
 145 
 146 #ifdef FASTEST
 147 local const config configuration_table[2] = {
 148 /*      good lazy nice chain */
 149 /* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
 150 /* 1 */ {4,    4,  8,    4, deflate_fast}}; /* max speed, no lazy matches */
 151 #else
 152 local const config configuration_table[10] = {
 153 /*      good lazy nice chain */
 154 /* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
 155 /* 1 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */
 156 /* 2 */ {4,    5, 16,    8, deflate_fast},
 157 /* 3 */ {4,    6, 32,   32, deflate_fast},
 158 
 159 /* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
 160 /* 5 */ {8,   16, 32,   32, deflate_slow},
 161 /* 6 */ {8,   16, 128, 128, deflate_slow},
 162 /* 7 */ {8,   32, 128, 256, deflate_slow},
 163 /* 8 */ {32, 128, 258, 1024, deflate_slow},
 164 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
 165 #endif
 166 
 167 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
 168  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
 169  * meaning.
 170  */
 171 
 172 /* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */
 173 #define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0))
 174 
 175 /* ===========================================================================
 176  * Update a hash value with the given input byte
 177  * IN  assertion: all calls to UPDATE_HASH are made with consecutive input
 178  *    characters, so that a running hash key can be computed from the previous
 179  *    key instead of complete recalculation each time.
 180  */
 181 #define UPDATE_HASH(s,h,c) (h = (((h) << s->hash_shift) ^ (c)) & s->hash_mask)
 182 
 183 
 184 /* ===========================================================================
 185  * Insert string str in the dictionary and set match_head to the previous head
 186  * of the hash chain (the most recent string with same hash key). Return
 187  * the previous length of the hash chain.
 188  * If this file is compiled with -DFASTEST, the compression level is forced
 189  * to 1, and no hash chains are maintained.
 190  * IN  assertion: all calls to INSERT_STRING are made with consecutive input
 191  *    characters and the first MIN_MATCH bytes of str are valid (except for
 192  *    the last MIN_MATCH-1 bytes of the input file).
 193  */
 194 #ifdef FASTEST
 195 #define INSERT_STRING(s, str, match_head) \
 196    (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
 197     match_head = s->head[s->ins_h], \
 198     s->head[s->ins_h] = (Pos)(str))
 199 #else
 200 #define INSERT_STRING(s, str, match_head) \
 201    (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
 202     match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
 203     s->head[s->ins_h] = (Pos)(str))
 204 #endif
 205 
 206 /* ===========================================================================
 207  * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
 208  * prev[] will be initialized on the fly.
 209  */
 210 #define CLEAR_HASH(s) \
 211     do { \
 212         s->head[s->hash_size - 1] = NIL; \
 213         zmemzero((Bytef *)s->head, \
 214                  (unsigned)(s->hash_size - 1)*sizeof(*s->head)); \
 215     } while (0)
 216 
 217 /* ===========================================================================
 218  * Slide the hash table when sliding the window down (could be avoided with 32
 219  * bit values at the expense of memory usage). We slide even when level == 0 to
 220  * keep the hash table consistent if we switch back to level > 0 later.
 221  */
 222 local void slide_hash(s)
 223     deflate_state *s;
 224 {
 225     unsigned n, m;
 226     Posf *p;
 227     uInt wsize = s->w_size;
 228 
 229     n = s->hash_size;
 230     p = &s->head[n];
 231     do {
 232         m = *--p;
 233         *p = (Pos)(m >= wsize ? m - wsize : NIL);
 234     } while (--n);
 235     n = wsize;
 236 #ifndef FASTEST
 237     p = &s->prev[n];
 238     do {
 239         m = *--p;
 240         *p = (Pos)(m >= wsize ? m - wsize : NIL);
 241         /* If n is not on any hash chain, prev[n] is garbage but
 242          * its value will never be used.
 243          */
 244     } while (--n);
 245 #endif
 246 }
 247 
 248 /* ========================================================================= */
 249 int ZEXPORT deflateInit_(strm, level, version, stream_size)
 250     z_streamp strm;
 251     int level;
 252     const char *version;
 253     int stream_size;
 254 {
 255     return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
 256                          Z_DEFAULT_STRATEGY, version, stream_size);
 257     /* To do: ignore strm->next_in if we use it as window */
 258 }
 259 
 260 /* ========================================================================= */
 261 int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
 262                   version, stream_size)
 263     z_streamp strm;
 264     int  level;
 265     int  method;
 266     int  windowBits;
 267     int  memLevel;
 268     int  strategy;
 269     const char *version;
 270     int stream_size;
 271 {
 272     deflate_state *s;
 273     int wrap = 1;
 274     static const char my_version[] = ZLIB_VERSION;
 275 
 276     if (version == Z_NULL || version[0] != my_version[0] ||
 277         stream_size != sizeof(z_stream)) {
 278         return Z_VERSION_ERROR;
 279     }
 280     if (strm == Z_NULL) return Z_STREAM_ERROR;
 281 
 282     strm->msg = Z_NULL;
 283     if (strm->zalloc == (alloc_func)0) {
 284 #ifdef Z_SOLO
 285         return Z_STREAM_ERROR;
 286 #else
 287         strm->zalloc = zcalloc;
 288         strm->opaque = (voidpf)0;
 289 #endif
 290     }
 291     if (strm->zfree == (free_func)0)
 292 #ifdef Z_SOLO
 293         return Z_STREAM_ERROR;
 294 #else
 295         strm->zfree = zcfree;
 296 #endif
 297 
 298 #ifdef FASTEST
 299     if (level != 0) level = 1;
 300 #else
 301     if (level == Z_DEFAULT_COMPRESSION) level = 6;
 302 #endif
 303 
 304     if (windowBits < 0) { /* suppress zlib wrapper */
 305         wrap = 0;
 306         if (windowBits < -15)
 307             return Z_STREAM_ERROR;
 308         windowBits = -windowBits;
 309     }
 310 #ifdef GZIP
 311     else if (windowBits > 15) {
 312         wrap = 2;       /* write gzip wrapper instead */
 313         windowBits -= 16;
 314     }
 315 #endif
 316     if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
 317         windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
 318         strategy < 0 || strategy > Z_FIXED || (windowBits == 8 && wrap != 1)) {
 319         return Z_STREAM_ERROR;
 320     }
 321     if (windowBits == 8) windowBits = 9;  /* until 256-byte window bug fixed */
 322     s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
 323     if (s == Z_NULL) return Z_MEM_ERROR;
 324     strm->state = (struct internal_state FAR *)s;
 325     s->strm = strm;
 326     s->status = INIT_STATE;     /* to pass state test in deflateReset() */
 327 
 328     s->wrap = wrap;
 329     s->gzhead = Z_NULL;
 330     s->w_bits = (uInt)windowBits;
 331     s->w_size = 1 << s->w_bits;
 332     s->w_mask = s->w_size - 1;
 333 
 334     s->hash_bits = (uInt)memLevel + 7;
 335     s->hash_size = 1 << s->hash_bits;
 336     s->hash_mask = s->hash_size - 1;
 337     s->hash_shift =  ((s->hash_bits + MIN_MATCH-1) / MIN_MATCH);
 338 
 339     s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
 340     s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
 341     s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
 342 
 343     s->high_water = 0;      /* nothing written to s->window yet */
 344 
 345     s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
 346 
 347     /* We overlay pending_buf and sym_buf. This works since the average size
 348      * for length/distance pairs over any compressed block is assured to be 31
 349      * bits or less.
 350      *
 351      * Analysis: The longest fixed codes are a length code of 8 bits plus 5
 352      * extra bits, for lengths 131 to 257. The longest fixed distance codes are
 353      * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest
 354      * possible fixed-codes length/distance pair is then 31 bits total.
 355      *
 356      * sym_buf starts one-fourth of the way into pending_buf. So there are
 357      * three bytes in sym_buf for every four bytes in pending_buf. Each symbol
 358      * in sym_buf is three bytes -- two for the distance and one for the
 359      * literal/length. As each symbol is consumed, the pointer to the next
 360      * sym_buf value to read moves forward three bytes. From that symbol, up to
 361      * 31 bits are written to pending_buf. The closest the written pending_buf
 362      * bits gets to the next sym_buf symbol to read is just before the last
 363      * code is written. At that time, 31*(n - 2) bits have been written, just
 364      * after 24*(n - 2) bits have been consumed from sym_buf. sym_buf starts at
 365      * 8*n bits into pending_buf. (Note that the symbol buffer fills when n - 1
 366      * symbols are written.) The closest the writing gets to what is unread is
 367      * then n + 14 bits. Here n is lit_bufsize, which is 16384 by default, and
 368      * can range from 128 to 32768.
 369      *
 370      * Therefore, at a minimum, there are 142 bits of space between what is
 371      * written and what is read in the overlain buffers, so the symbols cannot
 372      * be overwritten by the compressed data. That space is actually 139 bits,
 373      * due to the three-bit fixed-code block header.
 374      *
 375      * That covers the case where either Z_FIXED is specified, forcing fixed
 376      * codes, or when the use of fixed codes is chosen, because that choice
 377      * results in a smaller compressed block than dynamic codes. That latter
 378      * condition then assures that the above analysis also covers all dynamic
 379      * blocks. A dynamic-code block will only be chosen to be emitted if it has
 380      * fewer bits than a fixed-code block would for the same set of symbols.
 381      * Therefore its average symbol length is assured to be less than 31. So
 382      * the compressed data for a dynamic block also cannot overwrite the
 383      * symbols from which it is being constructed.
 384      */
 385 
 386     s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, 4);
 387     s->pending_buf_size = (ulg)s->lit_bufsize * 4;
 388 
 389     if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
 390         s->pending_buf == Z_NULL) {
 391         s->status = FINISH_STATE;
 392         strm->msg = ERR_MSG(Z_MEM_ERROR);
 393         deflateEnd (strm);
 394         return Z_MEM_ERROR;
 395     }
 396     s->sym_buf = s->pending_buf + s->lit_bufsize;
 397     s->sym_end = (s->lit_bufsize - 1) * 3;
 398     /* We avoid equality with lit_bufsize*3 because of wraparound at 64K
 399      * on 16 bit machines and because stored blocks are restricted to
 400      * 64K-1 bytes.
 401      */
 402 
 403     s->level = level;
 404     s->strategy = strategy;
 405     s->method = (Byte)method;
 406 
 407     return deflateReset(strm);
 408 }
 409 
 410 /* =========================================================================
 411  * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
 412  */
 413 local int deflateStateCheck(strm)
 414     z_streamp strm;
 415 {
 416     deflate_state *s;
 417     if (strm == Z_NULL ||
 418         strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
 419         return 1;
 420     s = strm->state;
 421     if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE &&
 422 #ifdef GZIP
 423                                            s->status != GZIP_STATE &&
 424 #endif
 425                                            s->status != EXTRA_STATE &&
 426                                            s->status != NAME_STATE &&
 427                                            s->status != COMMENT_STATE &&
 428                                            s->status != HCRC_STATE &&
 429                                            s->status != BUSY_STATE &&
 430                                            s->status != FINISH_STATE))
 431         return 1;
 432     return 0;
 433 }
 434 
 435 /* ========================================================================= */
 436 int ZEXPORT deflateSetDictionary(strm, dictionary, dictLength)
 437     z_streamp strm;
 438     const Bytef *dictionary;
 439     uInt  dictLength;
 440 {
 441     deflate_state *s;
 442     uInt str, n;
 443     int wrap;
 444     unsigned avail;
 445     z_const unsigned char *next;
 446 
 447     if (deflateStateCheck(strm) || dictionary == Z_NULL)
 448         return Z_STREAM_ERROR;
 449     s = strm->state;
 450     wrap = s->wrap;
 451     if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
 452         return Z_STREAM_ERROR;
 453 
 454     /* when using zlib wrappers, compute Adler-32 for provided dictionary */
 455     if (wrap == 1)
 456         strm->adler = adler32(strm->adler, dictionary, dictLength);
 457     s->wrap = 0;                    /* avoid computing Adler-32 in read_buf */
 458 
 459     /* if dictionary would fill window, just replace the history */
 460     if (dictLength >= s->w_size) {
 461         if (wrap == 0) {            /* already empty otherwise */
 462             CLEAR_HASH(s);
 463             s->strstart = 0;
 464             s->block_start = 0L;
 465             s->insert = 0;
 466         }
 467         dictionary += dictLength - s->w_size;  /* use the tail */
 468         dictLength = s->w_size;
 469     }
 470 
 471     /* insert dictionary into window and hash */
 472     avail = strm->avail_in;
 473     next = strm->next_in;
 474     strm->avail_in = dictLength;
 475     strm->next_in = (z_const Bytef *)dictionary;
 476     fill_window(s);
 477     while (s->lookahead >= MIN_MATCH) {
 478         str = s->strstart;
 479         n = s->lookahead - (MIN_MATCH-1);
 480         do {
 481             UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
 482 #ifndef FASTEST
 483             s->prev[str & s->w_mask] = s->head[s->ins_h];
 484 #endif
 485             s->head[s->ins_h] = (Pos)str;
 486             str++;
 487         } while (--n);
 488         s->strstart = str;
 489         s->lookahead = MIN_MATCH-1;
 490         fill_window(s);
 491     }
 492     s->strstart += s->lookahead;
 493     s->block_start = (long)s->strstart;
 494     s->insert = s->lookahead;
 495     s->lookahead = 0;
 496     s->match_length = s->prev_length = MIN_MATCH-1;
 497     s->match_available = 0;
 498     strm->next_in = next;
 499     strm->avail_in = avail;
 500     s->wrap = wrap;
 501     return Z_OK;
 502 }
 503 
 504 /* ========================================================================= */
 505 int ZEXPORT deflateGetDictionary(strm, dictionary, dictLength)
 506     z_streamp strm;
 507     Bytef *dictionary;
 508     uInt  *dictLength;
 509 {
 510     deflate_state *s;
 511     uInt len;
 512 
 513     if (deflateStateCheck(strm))
 514         return Z_STREAM_ERROR;
 515     s = strm->state;
 516     len = s->strstart + s->lookahead;
 517     if (len > s->w_size)
 518         len = s->w_size;
 519     if (dictionary != Z_NULL && len)
 520         zmemcpy(dictionary, s->window + s->strstart + s->lookahead - len, len);
 521     if (dictLength != Z_NULL)
 522         *dictLength = len;
 523     return Z_OK;
 524 }
 525 
 526 /* ========================================================================= */
 527 int ZEXPORT deflateResetKeep(strm)
 528     z_streamp strm;
 529 {
 530     deflate_state *s;
 531 
 532     if (deflateStateCheck(strm)) {
 533         return Z_STREAM_ERROR;
 534     }
 535 
 536     strm->total_in = strm->total_out = 0;
 537     strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
 538     strm->data_type = Z_UNKNOWN;
 539 
 540     s = (deflate_state *)strm->state;
 541     s->pending = 0;
 542     s->pending_out = s->pending_buf;
 543 
 544     if (s->wrap < 0) {
 545         s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
 546     }
 547     s->status =
 548 #ifdef GZIP
 549         s->wrap == 2 ? GZIP_STATE :
 550 #endif
 551         INIT_STATE;
 552     strm->adler =
 553 #ifdef GZIP
 554         s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
 555 #endif
 556         adler32(0L, Z_NULL, 0);
 557     s->last_flush = -2;
 558 
 559     _tr_init(s);
 560 
 561     return Z_OK;
 562 }
 563 
 564 /* ========================================================================= */
 565 int ZEXPORT deflateReset(strm)
 566     z_streamp strm;
 567 {
 568     int ret;
 569 
 570     ret = deflateResetKeep(strm);
 571     if (ret == Z_OK)
 572         lm_init(strm->state);
 573     return ret;
 574 }
 575 
 576 /* ========================================================================= */
 577 int ZEXPORT deflateSetHeader(strm, head)
 578     z_streamp strm;
 579     gz_headerp head;
 580 {
 581     if (deflateStateCheck(strm) || strm->state->wrap != 2)
 582         return Z_STREAM_ERROR;
 583     strm->state->gzhead = head;
 584     return Z_OK;
 585 }
 586 
 587 /* ========================================================================= */
 588 int ZEXPORT deflatePending(strm, pending, bits)
 589     unsigned *pending;
 590     int *bits;
 591     z_streamp strm;
 592 {
 593     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
 594     if (pending != Z_NULL)
 595         *pending = strm->state->pending;
 596     if (bits != Z_NULL)
 597         *bits = strm->state->bi_valid;
 598     return Z_OK;
 599 }
 600 
 601 /* ========================================================================= */
 602 int ZEXPORT deflatePrime(strm, bits, value)
 603     z_streamp strm;
 604     int bits;
 605     int value;
 606 {
 607     deflate_state *s;
 608     int put;
 609 
 610     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
 611     s = strm->state;
 612     if (bits < 0 || bits > 16 ||
 613         s->sym_buf < s->pending_out + ((Buf_size + 7) >> 3))
 614         return Z_BUF_ERROR;
 615     do {
 616         put = Buf_size - s->bi_valid;
 617         if (put > bits)
 618             put = bits;
 619         s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);
 620         s->bi_valid += put;
 621         _tr_flush_bits(s);
 622         value >>= put;
 623         bits -= put;
 624     } while (bits);
 625     return Z_OK;
 626 }
 627 
 628 /* ========================================================================= */
 629 int ZEXPORT deflateParams(strm, level, strategy)
 630     z_streamp strm;
 631     int level;
 632     int strategy;
 633 {
 634     deflate_state *s;
 635     compress_func func;
 636 
 637     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
 638     s = strm->state;
 639 
 640 #ifdef FASTEST
 641     if (level != 0) level = 1;
 642 #else
 643     if (level == Z_DEFAULT_COMPRESSION) level = 6;
 644 #endif
 645     if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
 646         return Z_STREAM_ERROR;
 647     }
 648     func = configuration_table[s->level].func;
 649 
 650     if ((strategy != s->strategy || func != configuration_table[level].func) &&
 651         s->last_flush != -2) {
 652         /* Flush the last buffer: */
 653         int err = deflate(strm, Z_BLOCK);
 654         if (err == Z_STREAM_ERROR)
 655             return err;
 656         if (strm->avail_in || (s->strstart - s->block_start) + s->lookahead)
 657             return Z_BUF_ERROR;
 658     }
 659     if (s->level != level) {
 660         if (s->level == 0 && s->matches != 0) {
 661             if (s->matches == 1)
 662                 slide_hash(s);
 663             else
 664                 CLEAR_HASH(s);
 665             s->matches = 0;
 666         }
 667         s->level = level;
 668         s->max_lazy_match   = configuration_table[level].max_lazy;
 669         s->good_match       = configuration_table[level].good_length;
 670         s->nice_match       = configuration_table[level].nice_length;
 671         s->max_chain_length = configuration_table[level].max_chain;
 672     }
 673     s->strategy = strategy;
 674     return Z_OK;
 675 }
 676 
 677 /* ========================================================================= */
 678 int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
 679     z_streamp strm;
 680     int good_length;
 681     int max_lazy;
 682     int nice_length;
 683     int max_chain;
 684 {
 685     deflate_state *s;
 686 
 687     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
 688     s = strm->state;
 689     s->good_match = (uInt)good_length;
 690     s->max_lazy_match = (uInt)max_lazy;
 691     s->nice_match = nice_length;
 692     s->max_chain_length = (uInt)max_chain;
 693     return Z_OK;
 694 }
 695 
 696 /* =========================================================================
 697  * For the default windowBits of 15 and memLevel of 8, this function returns a
 698  * close to exact, as well as small, upper bound on the compressed size. This
 699  * is an expansion of ~0.03%, plus a small constant.
 700  *
 701  * For any setting other than those defaults for windowBits and memLevel, one
 702  * of two worst case bounds is returned. This is at most an expansion of ~4% or
 703  * ~13%, plus a small constant.
 704  *
 705  * Both the 0.03% and 4% derive from the overhead of stored blocks. The first
 706  * one is for stored blocks of 16383 bytes (memLevel == 8), whereas the second
 707  * is for stored blocks of 127 bytes (the worst case memLevel == 1). The
 708  * expansion results from five bytes of header for each stored block.
 709  *
 710  * The larger expansion of 13% results from a window size less than or equal to
 711  * the symbols buffer size (windowBits <= memLevel + 7). In that case some of
 712  * the data being compressed may have slid out of the sliding window, impeding
 713  * a stored block from being emitted. Then the only choice is a fixed or
 714  * dynamic block, where a fixed block limits the maximum expansion to 9 bits
 715  * per 8-bit byte, plus 10 bits for every block. The smallest block size for
 716  * which this can occur is 255 (memLevel == 2).
 717  *
 718  * Shifts are used to approximate divisions, for speed.
 719  */
 720 uLong ZEXPORT deflateBound(strm, sourceLen)
 721     z_streamp strm;
 722     uLong sourceLen;
 723 {
 724     deflate_state *s;
 725     uLong fixedlen, storelen, wraplen;
 726 
 727     /* upper bound for fixed blocks with 9-bit literals and length 255
 728        (memLevel == 2, which is the lowest that may not use stored blocks) --
 729        ~13% overhead plus a small constant */
 730     fixedlen = sourceLen + (sourceLen >> 3) + (sourceLen >> 8) +
 731                (sourceLen >> 9) + 4;
 732 
 733     /* upper bound for stored blocks with length 127 (memLevel == 1) --
 734        ~4% overhead plus a small constant */
 735     storelen = sourceLen + (sourceLen >> 5) + (sourceLen >> 7) +
 736                (sourceLen >> 11) + 7;
 737 
 738     /* if can't get parameters, return larger bound plus a zlib wrapper */
 739     if (deflateStateCheck(strm))
 740         return (fixedlen > storelen ? fixedlen : storelen) + 6;
 741 
 742     /* compute wrapper length */
 743     s = strm->state;
 744     switch (s->wrap) {
 745     case 0:                                 /* raw deflate */
 746         wraplen = 0;
 747         break;
 748     case 1:                                 /* zlib wrapper */
 749         wraplen = 6 + (s->strstart ? 4 : 0);
 750         break;
 751 #ifdef GZIP
 752     case 2:                                 /* gzip wrapper */
 753         wraplen = 18;
 754         if (s->gzhead != Z_NULL) {          /* user-supplied gzip header */
 755             Bytef *str;
 756             if (s->gzhead->extra != Z_NULL)
 757                 wraplen += 2 + s->gzhead->extra_len;
 758             str = s->gzhead->name;
 759             if (str != Z_NULL)
 760                 do {
 761                     wraplen++;
 762                 } while (*str++);
 763             str = s->gzhead->comment;
 764             if (str != Z_NULL)
 765                 do {
 766                     wraplen++;
 767                 } while (*str++);
 768             if (s->gzhead->hcrc)
 769                 wraplen += 2;
 770         }
 771         break;
 772 #endif
 773     default:                                /* for compiler happiness */
 774         wraplen = 6;
 775     }
 776 
 777     /* if not default parameters, return one of the conservative bounds */
 778     if (s->w_bits != 15 || s->hash_bits != 8 + 7)
 779         return (s->w_bits <= s->hash_bits ? fixedlen : storelen) + wraplen;
 780 
 781     /* default settings: return tight bound for that case -- ~0.03% overhead
 782        plus a small constant */
 783     return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
 784            (sourceLen >> 25) + 13 - 6 + wraplen;
 785 }
 786 
 787 /* =========================================================================
 788  * Put a short in the pending buffer. The 16-bit value is put in MSB order.
 789  * IN assertion: the stream state is correct and there is enough room in
 790  * pending_buf.
 791  */
 792 local void putShortMSB(s, b)
 793     deflate_state *s;
 794     uInt b;
 795 {
 796     put_byte(s, (Byte)(b >> 8));
 797     put_byte(s, (Byte)(b & 0xff));
 798 }
 799 
 800 /* =========================================================================
 801  * Flush as much pending output as possible. All deflate() output, except for
 802  * some deflate_stored() output, goes through this function so some
 803  * applications may wish to modify it to avoid allocating a large
 804  * strm->next_out buffer and copying into it. (See also read_buf()).
 805  */
 806 local void flush_pending(strm)
 807     z_streamp strm;
 808 {
 809     unsigned len;
 810     deflate_state *s = strm->state;
 811 
 812     _tr_flush_bits(s);
 813     len = s->pending;
 814     if (len > strm->avail_out) len = strm->avail_out;
 815     if (len == 0) return;
 816 
 817     zmemcpy(strm->next_out, s->pending_out, len);
 818     strm->next_out  += len;
 819     s->pending_out  += len;
 820     strm->total_out += len;
 821     strm->avail_out -= len;
 822     s->pending      -= len;
 823     if (s->pending == 0) {
 824         s->pending_out = s->pending_buf;
 825     }
 826 }
 827 
 828 /* ===========================================================================
 829  * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1].
 830  */
 831 #define HCRC_UPDATE(beg) \
 832     do { \
 833         if (s->gzhead->hcrc && s->pending > (beg)) \
 834             strm->adler = crc32(strm->adler, s->pending_buf + (beg), \
 835                                 s->pending - (beg)); \
 836     } while (0)
 837 
 838 /* ========================================================================= */
 839 int ZEXPORT deflate(strm, flush)
 840     z_streamp strm;
 841     int flush;
 842 {
 843     int old_flush; /* value of flush param for previous deflate call */
 844     deflate_state *s;
 845 
 846     if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) {
 847         return Z_STREAM_ERROR;
 848     }
 849     s = strm->state;
 850 
 851     if (strm->next_out == Z_NULL ||
 852         (strm->avail_in != 0 && strm->next_in == Z_NULL) ||
 853         (s->status == FINISH_STATE && flush != Z_FINISH)) {
 854         ERR_RETURN(strm, Z_STREAM_ERROR);
 855     }
 856     if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
 857 
 858     old_flush = s->last_flush;
 859     s->last_flush = flush;
 860 
 861     /* Flush as much pending output as possible */
 862     if (s->pending != 0) {
 863         flush_pending(strm);
 864         if (strm->avail_out == 0) {
 865             /* Since avail_out is 0, deflate will be called again with
 866              * more output space, but possibly with both pending and
 867              * avail_in equal to zero. There won't be anything to do,
 868              * but this is not an error situation so make sure we
 869              * return OK instead of BUF_ERROR at next call of deflate:
 870              */
 871             s->last_flush = -1;
 872             return Z_OK;
 873         }
 874 
 875     /* Make sure there is something to do and avoid duplicate consecutive
 876      * flushes. For repeated and useless calls with Z_FINISH, we keep
 877      * returning Z_STREAM_END instead of Z_BUF_ERROR.
 878      */
 879     } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&
 880                flush != Z_FINISH) {
 881         ERR_RETURN(strm, Z_BUF_ERROR);
 882     }
 883 
 884     /* User must not provide more input after the first FINISH: */
 885     if (s->status == FINISH_STATE && strm->avail_in != 0) {
 886         ERR_RETURN(strm, Z_BUF_ERROR);
 887     }
 888 
 889     /* Write the header */
 890     if (s->status == INIT_STATE && s->wrap == 0)
 891         s->status = BUSY_STATE;
 892     if (s->status == INIT_STATE) {
 893         /* zlib header */
 894         uInt header = (Z_DEFLATED + ((s->w_bits - 8) << 4)) << 8;
 895         uInt level_flags;
 896 
 897         if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
 898             level_flags = 0;
 899         else if (s->level < 6)
 900             level_flags = 1;
 901         else if (s->level == 6)
 902             level_flags = 2;
 903         else
 904             level_flags = 3;
 905         header |= (level_flags << 6);
 906         if (s->strstart != 0) header |= PRESET_DICT;
 907         header += 31 - (header % 31);
 908 
 909         putShortMSB(s, header);
 910 
 911         /* Save the adler32 of the preset dictionary: */
 912         if (s->strstart != 0) {
 913             putShortMSB(s, (uInt)(strm->adler >> 16));
 914             putShortMSB(s, (uInt)(strm->adler & 0xffff));
 915         }
 916         strm->adler = adler32(0L, Z_NULL, 0);
 917         s->status = BUSY_STATE;
 918 
 919         /* Compression must start with an empty pending buffer */
 920         flush_pending(strm);
 921         if (s->pending != 0) {
 922             s->last_flush = -1;
 923             return Z_OK;
 924         }
 925     }
 926 #ifdef GZIP
 927     if (s->status == GZIP_STATE) {
 928         /* gzip header */
 929         strm->adler = crc32(0L, Z_NULL, 0);
 930         put_byte(s, 31);
 931         put_byte(s, 139);
 932         put_byte(s, 8);
 933         if (s->gzhead == Z_NULL) {
 934             put_byte(s, 0);
 935             put_byte(s, 0);
 936             put_byte(s, 0);
 937             put_byte(s, 0);
 938             put_byte(s, 0);
 939             put_byte(s, s->level == 9 ? 2 :
 940                      (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
 941                       4 : 0));
 942             put_byte(s, OS_CODE);
 943             s->status = BUSY_STATE;
 944 
 945             /* Compression must start with an empty pending buffer */
 946             flush_pending(strm);
 947             if (s->pending != 0) {
 948                 s->last_flush = -1;
 949                 return Z_OK;
 950             }
 951         }
 952         else {
 953             put_byte(s, (s->gzhead->text ? 1 : 0) +
 954                      (s->gzhead->hcrc ? 2 : 0) +
 955                      (s->gzhead->extra == Z_NULL ? 0 : 4) +
 956                      (s->gzhead->name == Z_NULL ? 0 : 8) +
 957                      (s->gzhead->comment == Z_NULL ? 0 : 16)
 958                      );
 959             put_byte(s, (Byte)(s->gzhead->time & 0xff));
 960             put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
 961             put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
 962             put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
 963             put_byte(s, s->level == 9 ? 2 :
 964                      (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
 965                       4 : 0));
 966             put_byte(s, s->gzhead->os & 0xff);
 967             if (s->gzhead->extra != Z_NULL) {
 968                 put_byte(s, s->gzhead->extra_len & 0xff);
 969                 put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
 970             }
 971             if (s->gzhead->hcrc)
 972                 strm->adler = crc32(strm->adler, s->pending_buf,
 973                                     s->pending);
 974             s->gzindex = 0;
 975             s->status = EXTRA_STATE;
 976         }
 977     }
 978     if (s->status == EXTRA_STATE) {
 979         if (s->gzhead->extra != Z_NULL) {
 980             ulg beg = s->pending;   /* start of bytes to update crc */
 981             uInt left = (s->gzhead->extra_len & 0xffff) - s->gzindex;
 982             while (s->pending + left > s->pending_buf_size) {
 983                 uInt copy = s->pending_buf_size - s->pending;
 984                 zmemcpy(s->pending_buf + s->pending,
 985                         s->gzhead->extra + s->gzindex, copy);
 986                 s->pending = s->pending_buf_size;
 987                 HCRC_UPDATE(beg);
 988                 s->gzindex += copy;
 989                 flush_pending(strm);
 990                 if (s->pending != 0) {
 991                     s->last_flush = -1;
 992                     return Z_OK;
 993                 }
 994                 beg = 0;
 995                 left -= copy;
 996             }
 997             zmemcpy(s->pending_buf + s->pending,
 998                     s->gzhead->extra + s->gzindex, left);
 999             s->pending += left;
1000             HCRC_UPDATE(beg);
1001             s->gzindex = 0;
1002         }
1003         s->status = NAME_STATE;
1004     }
1005     if (s->status == NAME_STATE) {
1006         if (s->gzhead->name != Z_NULL) {
1007             ulg beg = s->pending;   /* start of bytes to update crc */
1008             int val;
1009             do {
1010                 if (s->pending == s->pending_buf_size) {
1011                     HCRC_UPDATE(beg);
1012                     flush_pending(strm);
1013                     if (s->pending != 0) {
1014                         s->last_flush = -1;
1015                         return Z_OK;
1016                     }
1017                     beg = 0;
1018                 }
1019                 val = s->gzhead->name[s->gzindex++];
1020                 put_byte(s, val);
1021             } while (val != 0);
1022             HCRC_UPDATE(beg);
1023             s->gzindex = 0;
1024         }
1025         s->status = COMMENT_STATE;
1026     }
1027     if (s->status == COMMENT_STATE) {
1028         if (s->gzhead->comment != Z_NULL) {
1029             ulg beg = s->pending;   /* start of bytes to update crc */
1030             int val;
1031             do {
1032                 if (s->pending == s->pending_buf_size) {
1033                     HCRC_UPDATE(beg);
1034                     flush_pending(strm);
1035                     if (s->pending != 0) {
1036                         s->last_flush = -1;
1037                         return Z_OK;
1038                     }
1039                     beg = 0;
1040                 }
1041                 val = s->gzhead->comment[s->gzindex++];
1042                 put_byte(s, val);
1043             } while (val != 0);
1044             HCRC_UPDATE(beg);
1045         }
1046         s->status = HCRC_STATE;
1047     }
1048     if (s->status == HCRC_STATE) {
1049         if (s->gzhead->hcrc) {
1050             if (s->pending + 2 > s->pending_buf_size) {
1051                 flush_pending(strm);
1052                 if (s->pending != 0) {
1053                     s->last_flush = -1;
1054                     return Z_OK;
1055                 }
1056             }
1057             put_byte(s, (Byte)(strm->adler & 0xff));
1058             put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
1059             strm->adler = crc32(0L, Z_NULL, 0);
1060         }
1061         s->status = BUSY_STATE;
1062 
1063         /* Compression must start with an empty pending buffer */
1064         flush_pending(strm);
1065         if (s->pending != 0) {
1066             s->last_flush = -1;
1067             return Z_OK;
1068         }
1069     }
1070 #endif
1071 
1072     /* Start a new block or continue the current one.
1073      */
1074     if (strm->avail_in != 0 || s->lookahead != 0 ||
1075         (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
1076         block_state bstate;
1077 
1078         bstate = s->level == 0 ? deflate_stored(s, flush) :
1079                  s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
1080                  s->strategy == Z_RLE ? deflate_rle(s, flush) :
1081                  (*(configuration_table[s->level].func))(s, flush);
1082 
1083         if (bstate == finish_started || bstate == finish_done) {
1084             s->status = FINISH_STATE;
1085         }
1086         if (bstate == need_more || bstate == finish_started) {
1087             if (strm->avail_out == 0) {
1088                 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
1089             }
1090             return Z_OK;
1091             /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
1092              * of deflate should use the same flush parameter to make sure
1093              * that the flush is complete. So we don't have to output an
1094              * empty block here, this will be done at next call. This also
1095              * ensures that for a very small output buffer, we emit at most
1096              * one empty block.
1097              */
1098         }
1099         if (bstate == block_done) {
1100             if (flush == Z_PARTIAL_FLUSH) {
1101                 _tr_align(s);
1102             } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
1103                 _tr_stored_block(s, (char*)0, 0L, 0);
1104                 /* For a full flush, this empty block will be recognized
1105                  * as a special marker by inflate_sync().
1106                  */
1107                 if (flush == Z_FULL_FLUSH) {
1108                     CLEAR_HASH(s);             /* forget history */
1109                     if (s->lookahead == 0) {
1110                         s->strstart = 0;
1111                         s->block_start = 0L;
1112                         s->insert = 0;
1113                     }
1114                 }
1115             }
1116             flush_pending(strm);
1117             if (strm->avail_out == 0) {
1118               s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
1119               return Z_OK;
1120             }
1121         }
1122     }
1123 
1124     if (flush != Z_FINISH) return Z_OK;
1125     if (s->wrap <= 0) return Z_STREAM_END;
1126 
1127     /* Write the trailer */
1128 #ifdef GZIP
1129     if (s->wrap == 2) {
1130         put_byte(s, (Byte)(strm->adler & 0xff));
1131         put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
1132         put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
1133         put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
1134         put_byte(s, (Byte)(strm->total_in & 0xff));
1135         put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
1136         put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
1137         put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
1138     }
1139     else
1140 #endif
1141     {
1142         putShortMSB(s, (uInt)(strm->adler >> 16));
1143         putShortMSB(s, (uInt)(strm->adler & 0xffff));
1144     }
1145     flush_pending(strm);
1146     /* If avail_out is zero, the application will call deflate again
1147      * to flush the rest.
1148      */
1149     if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
1150     return s->pending != 0 ? Z_OK : Z_STREAM_END;
1151 }
1152 
1153 /* ========================================================================= */
1154 int ZEXPORT deflateEnd(strm)
1155     z_streamp strm;
1156 {
1157     int status;
1158 
1159     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
1160 
1161     status = strm->state->status;
1162 
1163     /* Deallocate in reverse order of allocations: */
1164     TRY_FREE(strm, strm->state->pending_buf);
1165     TRY_FREE(strm, strm->state->head);
1166     TRY_FREE(strm, strm->state->prev);
1167     TRY_FREE(strm, strm->state->window);
1168 
1169     ZFREE(strm, strm->state);
1170     strm->state = Z_NULL;
1171 
1172     return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
1173 }
1174 
1175 /* =========================================================================
1176  * Copy the source state to the destination state.
1177  * To simplify the source, this is not supported for 16-bit MSDOS (which
1178  * doesn't have enough memory anyway to duplicate compression states).
1179  */
1180 int ZEXPORT deflateCopy(dest, source)
1181     z_streamp dest;
1182     z_streamp source;
1183 {
1184 #ifdef MAXSEG_64K
1185     return Z_STREAM_ERROR;
1186 #else
1187     deflate_state *ds;
1188     deflate_state *ss;
1189 
1190 
1191     if (deflateStateCheck(source) || dest == Z_NULL) {
1192         return Z_STREAM_ERROR;
1193     }
1194 
1195     ss = source->state;
1196 
1197     zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
1198 
1199     ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
1200     if (ds == Z_NULL) return Z_MEM_ERROR;
1201     dest->state = (struct internal_state FAR *) ds;
1202     zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));
1203     ds->strm = dest;
1204 
1205     ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
1206     ds->prev   = (Posf *)  ZALLOC(dest, ds->w_size, sizeof(Pos));
1207     ds->head   = (Posf *)  ZALLOC(dest, ds->hash_size, sizeof(Pos));
1208     ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, 4);
1209 
1210     if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
1211         ds->pending_buf == Z_NULL) {
1212         deflateEnd (dest);
1213         return Z_MEM_ERROR;
1214     }
1215     /* following zmemcpy do not work for 16-bit MSDOS */
1216     zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
1217     zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));
1218     zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));
1219     zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
1220 
1221     ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
1222     ds->sym_buf = ds->pending_buf + ds->lit_bufsize;
1223 
1224     ds->l_desc.dyn_tree = ds->dyn_ltree;
1225     ds->d_desc.dyn_tree = ds->dyn_dtree;
1226     ds->bl_desc.dyn_tree = ds->bl_tree;
1227 
1228     return Z_OK;
1229 #endif /* MAXSEG_64K */
1230 }
1231 
1232 /* ===========================================================================
1233  * Read a new buffer from the current input stream, update the adler32
1234  * and total number of bytes read.  All deflate() input goes through
1235  * this function so some applications may wish to modify it to avoid
1236  * allocating a large strm->next_in buffer and copying from it.
1237  * (See also flush_pending()).
1238  */
1239 local unsigned read_buf(strm, buf, size)
1240     z_streamp strm;
1241     Bytef *buf;
1242     unsigned size;
1243 {
1244     unsigned len = strm->avail_in;
1245 
1246     if (len > size) len = size;
1247     if (len == 0) return 0;
1248 
1249     strm->avail_in  -= len;
1250 
1251     zmemcpy(buf, strm->next_in, len);
1252     if (strm->state->wrap == 1) {
1253         strm->adler = adler32(strm->adler, buf, len);
1254     }
1255 #ifdef GZIP
1256     else if (strm->state->wrap == 2) {
1257         strm->adler = crc32(strm->adler, buf, len);
1258     }
1259 #endif
1260     strm->next_in  += len;
1261     strm->total_in += len;
1262 
1263     return len;
1264 }
1265 
1266 /* ===========================================================================
1267  * Initialize the "longest match" routines for a new zlib stream
1268  */
1269 local void lm_init(s)
1270     deflate_state *s;
1271 {
1272     s->window_size = (ulg)2L*s->w_size;
1273 
1274     CLEAR_HASH(s);
1275 
1276     /* Set the default configuration parameters:
1277      */
1278     s->max_lazy_match   = configuration_table[s->level].max_lazy;
1279     s->good_match       = configuration_table[s->level].good_length;
1280     s->nice_match       = configuration_table[s->level].nice_length;
1281     s->max_chain_length = configuration_table[s->level].max_chain;
1282 
1283     s->strstart = 0;
1284     s->block_start = 0L;
1285     s->lookahead = 0;
1286     s->insert = 0;
1287     s->match_length = s->prev_length = MIN_MATCH-1;
1288     s->match_available = 0;
1289     s->ins_h = 0;
1290 }
1291 
1292 #ifndef FASTEST
1293 /* ===========================================================================
1294  * Set match_start to the longest match starting at the given string and
1295  * return its length. Matches shorter or equal to prev_length are discarded,
1296  * in which case the result is equal to prev_length and match_start is
1297  * garbage.
1298  * IN assertions: cur_match is the head of the hash chain for the current
1299  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1300  * OUT assertion: the match length is not greater than s->lookahead.
1301  */
1302 local uInt longest_match(s, cur_match)
1303     deflate_state *s;
1304     IPos cur_match;                             /* current match */
1305 {
1306     unsigned chain_length = s->max_chain_length;/* max hash chain length */
1307     register Bytef *scan = s->window + s->strstart; /* current string */
1308     register Bytef *match;                      /* matched string */
1309     register int len;                           /* length of current match */
1310     int best_len = (int)s->prev_length;         /* best match length so far */
1311     int nice_match = s->nice_match;             /* stop if match long enough */
1312     IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
1313         s->strstart - (IPos)MAX_DIST(s) : NIL;
1314     /* Stop when cur_match becomes <= limit. To simplify the code,
1315      * we prevent matches with the string of window index 0.
1316      */
1317     Posf *prev = s->prev;
1318     uInt wmask = s->w_mask;
1319 
1320 #ifdef UNALIGNED_OK
1321     /* Compare two bytes at a time. Note: this is not always beneficial.
1322      * Try with and without -DUNALIGNED_OK to check.
1323      */
1324     register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
1325     register ush scan_start = *(ushf*)scan;
1326     register ush scan_end   = *(ushf*)(scan + best_len - 1);
1327 #else
1328     register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1329     register Byte scan_end1  = scan[best_len - 1];
1330     register Byte scan_end   = scan[best_len];
1331 #endif
1332 
1333     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1334      * It is easy to get rid of this optimization if necessary.
1335      */
1336     Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1337 
1338     /* Do not waste too much time if we already have a good match: */
1339     if (s->prev_length >= s->good_match) {
1340         chain_length >>= 2;
1341     }
1342     /* Do not look for matches beyond the end of the input. This is necessary
1343      * to make deflate deterministic.
1344      */
1345     if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead;
1346 
1347     Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1348            "need lookahead");
1349 
1350     do {
1351         Assert(cur_match < s->strstart, "no future");
1352         match = s->window + cur_match;
1353 
1354         /* Skip to next match if the match length cannot increase
1355          * or if the match length is less than 2.  Note that the checks below
1356          * for insufficient lookahead only occur occasionally for performance
1357          * reasons.  Therefore uninitialized memory will be accessed, and
1358          * conditional jumps will be made that depend on those values.
1359          * However the length of the match is limited to the lookahead, so
1360          * the output of deflate is not affected by the uninitialized values.
1361          */
1362 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
1363         /* This code assumes sizeof(unsigned short) == 2. Do not use
1364          * UNALIGNED_OK if your compiler uses a different size.
1365          */
1366         if (*(ushf*)(match + best_len - 1) != scan_end ||
1367             *(ushf*)match != scan_start) continue;
1368 
1369         /* It is not necessary to compare scan[2] and match[2] since they are
1370          * always equal when the other bytes match, given that the hash keys
1371          * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
1372          * strstart + 3, + 5, up to strstart + 257. We check for insufficient
1373          * lookahead only every 4th comparison; the 128th check will be made
1374          * at strstart + 257. If MAX_MATCH-2 is not a multiple of 8, it is
1375          * necessary to put more guard bytes at the end of the window, or
1376          * to check more often for insufficient lookahead.
1377          */
1378         Assert(scan[2] == match[2], "scan[2]?");
1379         scan++, match++;
1380         do {
1381         } while (*(ushf*)(scan += 2) == *(ushf*)(match += 2) &&
1382                  *(ushf*)(scan += 2) == *(ushf*)(match += 2) &&
1383                  *(ushf*)(scan += 2) == *(ushf*)(match += 2) &&
1384                  *(ushf*)(scan += 2) == *(ushf*)(match += 2) &&
1385                  scan < strend);
1386         /* The funny "do {}" generates better code on most compilers */
1387 
1388         /* Here, scan <= window + strstart + 257 */
1389         Assert(scan <= s->window + (unsigned)(s->window_size - 1),
1390                "wild scan");
1391         if (*scan == *match) scan++;
1392 
1393         len = (MAX_MATCH - 1) - (int)(strend - scan);
1394         scan = strend - (MAX_MATCH-1);
1395 
1396 #else /* UNALIGNED_OK */
1397 
1398         if (match[best_len]     != scan_end  ||
1399             match[best_len - 1] != scan_end1 ||
1400             *match              != *scan     ||
1401             *++match            != scan[1])      continue;
1402 
1403         /* The check at best_len - 1 can be removed because it will be made
1404          * again later. (This heuristic is not always a win.)
1405          * It is not necessary to compare scan[2] and match[2] since they
1406          * are always equal when the other bytes match, given that
1407          * the hash keys are equal and that HASH_BITS >= 8.
1408          */
1409         scan += 2, match++;
1410         Assert(*scan == *match, "match[2]?");
1411 
1412         /* We check for insufficient lookahead only every 8th comparison;
1413          * the 256th check will be made at strstart + 258.
1414          */
1415         do {
1416         } while (*++scan == *++match && *++scan == *++match &&
1417                  *++scan == *++match && *++scan == *++match &&
1418                  *++scan == *++match && *++scan == *++match &&
1419                  *++scan == *++match && *++scan == *++match &&
1420                  scan < strend);
1421 
1422         Assert(scan <= s->window + (unsigned)(s->window_size - 1),
1423                "wild scan");
1424 
1425         len = MAX_MATCH - (int)(strend - scan);
1426         scan = strend - MAX_MATCH;
1427 
1428 #endif /* UNALIGNED_OK */
1429 
1430         if (len > best_len) {
1431             s->match_start = cur_match;
1432             best_len = len;
1433             if (len >= nice_match) break;
1434 #ifdef UNALIGNED_OK
1435             scan_end = *(ushf*)(scan + best_len - 1);
1436 #else
1437             scan_end1  = scan[best_len - 1];
1438             scan_end   = scan[best_len];
1439 #endif
1440         }
1441     } while ((cur_match = prev[cur_match & wmask]) > limit
1442              && --chain_length != 0);
1443 
1444     if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
1445     return s->lookahead;
1446 }
1447 
1448 #else /* FASTEST */
1449 
1450 /* ---------------------------------------------------------------------------
1451  * Optimized version for FASTEST only
1452  */
1453 local uInt longest_match(s, cur_match)
1454     deflate_state *s;
1455     IPos cur_match;                             /* current match */
1456 {
1457     register Bytef *scan = s->window + s->strstart; /* current string */
1458     register Bytef *match;                       /* matched string */
1459     register int len;                           /* length of current match */
1460     register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1461 
1462     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1463      * It is easy to get rid of this optimization if necessary.
1464      */
1465     Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1466 
1467     Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1468            "need lookahead");
1469 
1470     Assert(cur_match < s->strstart, "no future");
1471 
1472     match = s->window + cur_match;
1473 
1474     /* Return failure if the match length is less than 2:
1475      */
1476     if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
1477 
1478     /* The check at best_len - 1 can be removed because it will be made
1479      * again later. (This heuristic is not always a win.)
1480      * It is not necessary to compare scan[2] and match[2] since they
1481      * are always equal when the other bytes match, given that
1482      * the hash keys are equal and that HASH_BITS >= 8.
1483      */
1484     scan += 2, match += 2;
1485     Assert(*scan == *match, "match[2]?");
1486 
1487     /* We check for insufficient lookahead only every 8th comparison;
1488      * the 256th check will be made at strstart + 258.
1489      */
1490     do {
1491     } while (*++scan == *++match && *++scan == *++match &&
1492              *++scan == *++match && *++scan == *++match &&
1493              *++scan == *++match && *++scan == *++match &&
1494              *++scan == *++match && *++scan == *++match &&
1495              scan < strend);
1496 
1497     Assert(scan <= s->window + (unsigned)(s->window_size - 1), "wild scan");
1498 
1499     len = MAX_MATCH - (int)(strend - scan);
1500 
1501     if (len < MIN_MATCH) return MIN_MATCH - 1;
1502 
1503     s->match_start = cur_match;
1504     return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
1505 }
1506 
1507 #endif /* FASTEST */
1508 
1509 #ifdef ZLIB_DEBUG
1510 
1511 #define EQUAL 0
1512 /* result of memcmp for equal strings */
1513 
1514 /* ===========================================================================
1515  * Check that the match at match_start is indeed a match.
1516  */
1517 local void check_match(s, start, match, length)
1518     deflate_state *s;
1519     IPos start, match;
1520     int length;
1521 {
1522     /* check that the match is indeed a match */
1523     if (zmemcmp(s->window + match,
1524                 s->window + start, length) != EQUAL) {
1525         fprintf(stderr, " start %u, match %u, length %d\n",
1526                 start, match, length);
1527         do {
1528             fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
1529         } while (--length != 0);
1530         z_error("invalid match");
1531     }
1532     if (z_verbose > 1) {
1533         fprintf(stderr,"\\[%d,%d]", start - match, length);
1534         do { putc(s->window[start++], stderr); } while (--length != 0);
1535     }
1536 }
1537 #else
1538 #  define check_match(s, start, match, length)
1539 #endif /* ZLIB_DEBUG */
1540 
1541 /* ===========================================================================
1542  * Fill the window when the lookahead becomes insufficient.
1543  * Updates strstart and lookahead.
1544  *
1545  * IN assertion: lookahead < MIN_LOOKAHEAD
1546  * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1547  *    At least one byte has been read, or avail_in == 0; reads are
1548  *    performed for at least two bytes (required for the zip translate_eol
1549  *    option -- not supported here).
1550  */
1551 local void fill_window(s)
1552     deflate_state *s;
1553 {
1554     unsigned n;
1555     unsigned more;    /* Amount of free space at the end of the window. */
1556     uInt wsize = s->w_size;
1557 
1558     Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
1559 
1560     do {
1561         more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
1562 
1563         /* Deal with !@#$% 64K limit: */
1564         if (sizeof(int) <= 2) {
1565             if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1566                 more = wsize;
1567 
1568             } else if (more == (unsigned)(-1)) {
1569                 /* Very unlikely, but possible on 16 bit machine if
1570                  * strstart == 0 && lookahead == 1 (input done a byte at time)
1571                  */
1572                 more--;
1573             }
1574         }
1575 
1576         /* If the window is almost full and there is insufficient lookahead,
1577          * move the upper half to the lower one to make room in the upper half.
1578          */
1579         if (s->strstart >= wsize + MAX_DIST(s)) {
1580 
1581             zmemcpy(s->window, s->window + wsize, (unsigned)wsize - more);
1582             s->match_start -= wsize;
1583             s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
1584             s->block_start -= (long) wsize;
1585             if (s->insert > s->strstart)
1586                 s->insert = s->strstart;
1587             slide_hash(s);
1588             more += wsize;
1589         }
1590         if (s->strm->avail_in == 0) break;
1591 
1592         /* If there was no sliding:
1593          *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1594          *    more == window_size - lookahead - strstart
1595          * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1596          * => more >= window_size - 2*WSIZE + 2
1597          * In the BIG_MEM or MMAP case (not yet supported),
1598          *   window_size == input_size + MIN_LOOKAHEAD  &&
1599          *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1600          * Otherwise, window_size == 2*WSIZE so more >= 2.
1601          * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1602          */
1603         Assert(more >= 2, "more < 2");
1604 
1605         n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1606         s->lookahead += n;
1607 
1608         /* Initialize the hash value now that we have some input: */
1609         if (s->lookahead + s->insert >= MIN_MATCH) {
1610             uInt str = s->strstart - s->insert;
1611             s->ins_h = s->window[str];
1612             UPDATE_HASH(s, s->ins_h, s->window[str + 1]);
1613 #if MIN_MATCH != 3
1614             Call UPDATE_HASH() MIN_MATCH-3 more times
1615 #endif
1616             while (s->insert) {
1617                 UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
1618 #ifndef FASTEST
1619                 s->prev[str & s->w_mask] = s->head[s->ins_h];
1620 #endif
1621                 s->head[s->ins_h] = (Pos)str;
1622                 str++;
1623                 s->insert--;
1624                 if (s->lookahead + s->insert < MIN_MATCH)
1625                     break;
1626             }
1627         }
1628         /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1629          * but this is not important since only literal bytes will be emitted.
1630          */
1631 
1632     } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1633 
1634     /* If the WIN_INIT bytes after the end of the current data have never been
1635      * written, then zero those bytes in order to avoid memory check reports of
1636      * the use of uninitialized (or uninitialised as Julian writes) bytes by
1637      * the longest match routines.  Update the high water mark for the next
1638      * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
1639      * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
1640      */
1641     if (s->high_water < s->window_size) {
1642         ulg curr = s->strstart + (ulg)(s->lookahead);
1643         ulg init;
1644 
1645         if (s->high_water < curr) {
1646             /* Previous high water mark below current data -- zero WIN_INIT
1647              * bytes or up to end of window, whichever is less.
1648              */
1649             init = s->window_size - curr;
1650             if (init > WIN_INIT)
1651                 init = WIN_INIT;
1652             zmemzero(s->window + curr, (unsigned)init);
1653             s->high_water = curr + init;
1654         }
1655         else if (s->high_water < (ulg)curr + WIN_INIT) {
1656             /* High water mark at or above current data, but below current data
1657              * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
1658              * to end of window, whichever is less.
1659              */
1660             init = (ulg)curr + WIN_INIT - s->high_water;
1661             if (init > s->window_size - s->high_water)
1662                 init = s->window_size - s->high_water;
1663             zmemzero(s->window + s->high_water, (unsigned)init);
1664             s->high_water += init;
1665         }
1666     }
1667 
1668     Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1669            "not enough room for search");
1670 }
1671 
1672 /* ===========================================================================
1673  * Flush the current block, with given end-of-file flag.
1674  * IN assertion: strstart is set to the end of the current match.
1675  */
1676 #define FLUSH_BLOCK_ONLY(s, last) { \
1677    _tr_flush_block(s, (s->block_start >= 0L ? \
1678                    (charf *)&s->window[(unsigned)s->block_start] : \
1679                    (charf *)Z_NULL), \
1680                 (ulg)((long)s->strstart - s->block_start), \
1681                 (last)); \
1682    s->block_start = s->strstart; \
1683    flush_pending(s->strm); \
1684    Tracev((stderr,"[FLUSH]")); \
1685 }
1686 
1687 /* Same but force premature exit if necessary. */
1688 #define FLUSH_BLOCK(s, last) { \
1689    FLUSH_BLOCK_ONLY(s, last); \
1690    if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
1691 }
1692 
1693 /* Maximum stored block length in deflate format (not including header). */
1694 #define MAX_STORED 65535
1695 
1696 /* Minimum of a and b. */
1697 #define MIN(a, b) ((a) > (b) ? (b) : (a))
1698 
1699 /* ===========================================================================
1700  * Copy without compression as much as possible from the input stream, return
1701  * the current block state.
1702  *
1703  * In case deflateParams() is used to later switch to a non-zero compression
1704  * level, s->matches (otherwise unused when storing) keeps track of the number
1705  * of hash table slides to perform. If s->matches is 1, then one hash table
1706  * slide will be done when switching. If s->matches is 2, the maximum value
1707  * allowed here, then the hash table will be cleared, since two or more slides
1708  * is the same as a clear.
1709  *
1710  * deflate_stored() is written to minimize the number of times an input byte is
1711  * copied. It is most efficient with large input and output buffers, which
1712  * maximizes the opportunities to have a single copy from next_in to next_out.
1713  */
1714 local block_state deflate_stored(s, flush)
1715     deflate_state *s;
1716     int flush;
1717 {
1718     /* Smallest worthy block size when not flushing or finishing. By default
1719      * this is 32K. This can be as small as 507 bytes for memLevel == 1. For
1720      * large input and output buffers, the stored block size will be larger.
1721      */
1722     unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size);
1723 
1724     /* Copy as many min_block or larger stored blocks directly to next_out as
1725      * possible. If flushing, copy the remaining available input to next_out as
1726      * stored blocks, if there is enough space.
1727      */
1728     unsigned len, left, have, last = 0;
1729     unsigned used = s->strm->avail_in;
1730     do {
1731         /* Set len to the maximum size block that we can copy directly with the
1732          * available input data and output space. Set left to how much of that
1733          * would be copied from what's left in the window.
1734          */
1735         len = MAX_STORED;       /* maximum deflate stored block length */
1736         have = (s->bi_valid + 42) >> 3;         /* number of header bytes */
1737         if (s->strm->avail_out < have)          /* need room for header */
1738             break;
1739             /* maximum stored block length that will fit in avail_out: */
1740         have = s->strm->avail_out - have;
1741         left = s->strstart - s->block_start;    /* bytes left in window */
1742         if (len > (ulg)left + s->strm->avail_in)
1743             len = left + s->strm->avail_in;     /* limit len to the input */
1744         if (len > have)
1745             len = have;                         /* limit len to the output */
1746 
1747         /* If the stored block would be less than min_block in length, or if
1748          * unable to copy all of the available input when flushing, then try
1749          * copying to the window and the pending buffer instead. Also don't
1750          * write an empty block when flushing -- deflate() does that.
1751          */
1752         if (len < min_block && ((len == 0 && flush != Z_FINISH) ||
1753                                 flush == Z_NO_FLUSH ||
1754                                 len != left + s->strm->avail_in))
1755             break;
1756 
1757         /* Make a dummy stored block in pending to get the header bytes,
1758          * including any pending bits. This also updates the debugging counts.
1759          */
1760         last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0;
1761         _tr_stored_block(s, (char *)0, 0L, last);
1762 
1763         /* Replace the lengths in the dummy stored block with len. */
1764         s->pending_buf[s->pending - 4] = len;
1765         s->pending_buf[s->pending - 3] = len >> 8;
1766         s->pending_buf[s->pending - 2] = ~len;
1767         s->pending_buf[s->pending - 1] = ~len >> 8;
1768 
1769         /* Write the stored block header bytes. */
1770         flush_pending(s->strm);
1771 
1772 #ifdef ZLIB_DEBUG
1773         /* Update debugging counts for the data about to be copied. */
1774         s->compressed_len += len << 3;
1775         s->bits_sent += len << 3;
1776 #endif
1777 
1778         /* Copy uncompressed bytes from the window to next_out. */
1779         if (left) {
1780             if (left > len)
1781                 left = len;
1782             zmemcpy(s->strm->next_out, s->window + s->block_start, left);
1783             s->strm->next_out += left;
1784             s->strm->avail_out -= left;
1785             s->strm->total_out += left;
1786             s->block_start += left;
1787             len -= left;
1788         }
1789 
1790         /* Copy uncompressed bytes directly from next_in to next_out, updating
1791          * the check value.
1792          */
1793         if (len) {
1794             read_buf(s->strm, s->strm->next_out, len);
1795             s->strm->next_out += len;
1796             s->strm->avail_out -= len;
1797             s->strm->total_out += len;
1798         }
1799     } while (last == 0);
1800 
1801     /* Update the sliding window with the last s->w_size bytes of the copied
1802      * data, or append all of the copied data to the existing window if less
1803      * than s->w_size bytes were copied. Also update the number of bytes to
1804      * insert in the hash tables, in the event that deflateParams() switches to
1805      * a non-zero compression level.
1806      */
1807     used -= s->strm->avail_in;      /* number of input bytes directly copied */
1808     if (used) {
1809         /* If any input was used, then no unused input remains in the window,
1810          * therefore s->block_start == s->strstart.
1811          */
1812         if (used >= s->w_size) {    /* supplant the previous history */
1813             s->matches = 2;         /* clear hash */
1814             zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);
1815             s->strstart = s->w_size;
1816             s->insert = s->strstart;
1817         }
1818         else {
1819             if (s->window_size - s->strstart <= used) {
1820                 /* Slide the window down. */
1821                 s->strstart -= s->w_size;
1822                 zmemcpy(s->window, s->window + s->w_size, s->strstart);
1823                 if (s->matches < 2)
1824                     s->matches++;   /* add a pending slide_hash() */
1825                 if (s->insert > s->strstart)
1826                     s->insert = s->strstart;
1827             }
1828             zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);
1829             s->strstart += used;
1830             s->insert += MIN(used, s->w_size - s->insert);
1831         }
1832         s->block_start = s->strstart;
1833     }
1834     if (s->high_water < s->strstart)
1835         s->high_water = s->strstart;
1836 
1837     /* If the last block was written to next_out, then done. */
1838     if (last)
1839         return finish_done;
1840 
1841     /* If flushing and all input has been consumed, then done. */
1842     if (flush != Z_NO_FLUSH && flush != Z_FINISH &&
1843         s->strm->avail_in == 0 && (long)s->strstart == s->block_start)
1844         return block_done;
1845 
1846     /* Fill the window with any remaining input. */
1847     have = s->window_size - s->strstart;
1848     if (s->strm->avail_in > have && s->block_start >= (long)s->w_size) {
1849         /* Slide the window down. */
1850         s->block_start -= s->w_size;
1851         s->strstart -= s->w_size;
1852         zmemcpy(s->window, s->window + s->w_size, s->strstart);
1853         if (s->matches < 2)
1854             s->matches++;           /* add a pending slide_hash() */
1855         have += s->w_size;          /* more space now */
1856         if (s->insert > s->strstart)
1857             s->insert = s->strstart;
1858     }
1859     if (have > s->strm->avail_in)
1860         have = s->strm->avail_in;
1861     if (have) {
1862         read_buf(s->strm, s->window + s->strstart, have);
1863         s->strstart += have;
1864         s->insert += MIN(have, s->w_size - s->insert);
1865     }
1866     if (s->high_water < s->strstart)
1867         s->high_water = s->strstart;
1868 
1869     /* There was not enough avail_out to write a complete worthy or flushed
1870      * stored block to next_out. Write a stored block to pending instead, if we
1871      * have enough input for a worthy block, or if flushing and there is enough
1872      * room for the remaining input as a stored block in the pending buffer.
1873      */
1874     have = (s->bi_valid + 42) >> 3;         /* number of header bytes */
1875         /* maximum stored block length that will fit in pending: */
1876     have = MIN(s->pending_buf_size - have, MAX_STORED);
1877     min_block = MIN(have, s->w_size);
1878     left = s->strstart - s->block_start;
1879     if (left >= min_block ||
1880         ((left || flush == Z_FINISH) && flush != Z_NO_FLUSH &&
1881          s->strm->avail_in == 0 && left <= have)) {
1882         len = MIN(left, have);
1883         last = flush == Z_FINISH && s->strm->avail_in == 0 &&
1884                len == left ? 1 : 0;
1885         _tr_stored_block(s, (charf *)s->window + s->block_start, len, last);
1886         s->block_start += len;
1887         flush_pending(s->strm);
1888     }
1889 
1890     /* We've done all we can with the available input and output. */
1891     return last ? finish_started : need_more;
1892 }
1893 
1894 /* ===========================================================================
1895  * Compress as much as possible from the input stream, return the current
1896  * block state.
1897  * This function does not perform lazy evaluation of matches and inserts
1898  * new strings in the dictionary only for unmatched strings or for short
1899  * matches. It is used only for the fast compression options.
1900  */
1901 local block_state deflate_fast(s, flush)
1902     deflate_state *s;
1903     int flush;
1904 {
1905     IPos hash_head;       /* head of the hash chain */
1906     int bflush;           /* set if current block must be flushed */
1907 
1908     for (;;) {
1909         /* Make sure that we always have enough lookahead, except
1910          * at the end of the input file. We need MAX_MATCH bytes
1911          * for the next match, plus MIN_MATCH bytes to insert the
1912          * string following the next match.
1913          */
1914         if (s->lookahead < MIN_LOOKAHEAD) {
1915             fill_window(s);
1916             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1917                 return need_more;
1918             }
1919             if (s->lookahead == 0) break; /* flush the current block */
1920         }
1921 
1922         /* Insert the string window[strstart .. strstart + 2] in the
1923          * dictionary, and set hash_head to the head of the hash chain:
1924          */
1925         hash_head = NIL;
1926         if (s->lookahead >= MIN_MATCH) {
1927             INSERT_STRING(s, s->strstart, hash_head);
1928         }
1929 
1930         /* Find the longest match, discarding those <= prev_length.
1931          * At this point we have always match_length < MIN_MATCH
1932          */
1933         if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1934             /* To simplify the code, we prevent matches with the string
1935              * of window index 0 (in particular we have to avoid a match
1936              * of the string with itself at the start of the input file).
1937              */
1938             s->match_length = longest_match (s, hash_head);
1939             /* longest_match() sets match_start */
1940         }
1941         if (s->match_length >= MIN_MATCH) {
1942             check_match(s, s->strstart, s->match_start, s->match_length);
1943 
1944             _tr_tally_dist(s, s->strstart - s->match_start,
1945                            s->match_length - MIN_MATCH, bflush);
1946 
1947             s->lookahead -= s->match_length;
1948 
1949             /* Insert new strings in the hash table only if the match length
1950              * is not too large. This saves time but degrades compression.
1951              */
1952 #ifndef FASTEST
1953             if (s->match_length <= s->max_insert_length &&
1954                 s->lookahead >= MIN_MATCH) {
1955                 s->match_length--; /* string at strstart already in table */
1956                 do {
1957                     s->strstart++;
1958                     INSERT_STRING(s, s->strstart, hash_head);
1959                     /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1960                      * always MIN_MATCH bytes ahead.
1961                      */
1962                 } while (--s->match_length != 0);
1963                 s->strstart++;
1964             } else
1965 #endif
1966             {
1967                 s->strstart += s->match_length;
1968                 s->match_length = 0;
1969                 s->ins_h = s->window[s->strstart];
1970                 UPDATE_HASH(s, s->ins_h, s->window[s->strstart + 1]);
1971 #if MIN_MATCH != 3
1972                 Call UPDATE_HASH() MIN_MATCH-3 more times
1973 #endif
1974                 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1975                  * matter since it will be recomputed at next deflate call.
1976                  */
1977             }
1978         } else {
1979             /* No match, output a literal byte */
1980             Tracevv((stderr,"%c", s->window[s->strstart]));
1981             _tr_tally_lit(s, s->window[s->strstart], bflush);
1982             s->lookahead--;
1983             s->strstart++;
1984         }
1985         if (bflush) FLUSH_BLOCK(s, 0);
1986     }
1987     s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
1988     if (flush == Z_FINISH) {
1989         FLUSH_BLOCK(s, 1);
1990         return finish_done;
1991     }
1992     if (s->sym_next)
1993         FLUSH_BLOCK(s, 0);
1994     return block_done;
1995 }
1996 
1997 #ifndef FASTEST
1998 /* ===========================================================================
1999  * Same as above, but achieves better compression. We use a lazy
2000  * evaluation for matches: a match is finally adopted only if there is
2001  * no better match at the next window position.
2002  */
2003 local block_state deflate_slow(s, flush)
2004     deflate_state *s;
2005     int flush;
2006 {
2007     IPos hash_head;          /* head of hash chain */
2008     int bflush;              /* set if current block must be flushed */
2009 
2010     /* Process the input block. */
2011     for (;;) {
2012         /* Make sure that we always have enough lookahead, except
2013          * at the end of the input file. We need MAX_MATCH bytes
2014          * for the next match, plus MIN_MATCH bytes to insert the
2015          * string following the next match.
2016          */
2017         if (s->lookahead < MIN_LOOKAHEAD) {
2018             fill_window(s);
2019             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
2020                 return need_more;
2021             }
2022             if (s->lookahead == 0) break; /* flush the current block */
2023         }
2024 
2025         /* Insert the string window[strstart .. strstart + 2] in the
2026          * dictionary, and set hash_head to the head of the hash chain:
2027          */
2028         hash_head = NIL;
2029         if (s->lookahead >= MIN_MATCH) {
2030             INSERT_STRING(s, s->strstart, hash_head);
2031         }
2032 
2033         /* Find the longest match, discarding those <= prev_length.
2034          */
2035         s->prev_length = s->match_length, s->prev_match = s->match_start;
2036         s->match_length = MIN_MATCH-1;
2037 
2038         if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
2039             s->strstart - hash_head <= MAX_DIST(s)) {
2040             /* To simplify the code, we prevent matches with the string
2041              * of window index 0 (in particular we have to avoid a match
2042              * of the string with itself at the start of the input file).
2043              */
2044             s->match_length = longest_match (s, hash_head);
2045             /* longest_match() sets match_start */
2046 
2047             if (s->match_length <= 5 && (s->strategy == Z_FILTERED
2048 #if TOO_FAR <= 32767
2049                 || (s->match_length == MIN_MATCH &&
2050                     s->strstart - s->match_start > TOO_FAR)
2051 #endif
2052                 )) {
2053 
2054                 /* If prev_match is also MIN_MATCH, match_start is garbage
2055                  * but we will ignore the current match anyway.
2056                  */
2057                 s->match_length = MIN_MATCH-1;
2058             }
2059         }
2060         /* If there was a match at the previous step and the current
2061          * match is not better, output the previous match:
2062          */
2063         if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
2064             uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
2065             /* Do not insert strings in hash table beyond this. */
2066 
2067             check_match(s, s->strstart - 1, s->prev_match, s->prev_length);
2068 
2069             _tr_tally_dist(s, s->strstart - 1 - s->prev_match,
2070                            s->prev_length - MIN_MATCH, bflush);
2071 
2072             /* Insert in hash table all strings up to the end of the match.
2073              * strstart - 1 and strstart are already inserted. If there is not
2074              * enough lookahead, the last two strings are not inserted in
2075              * the hash table.
2076              */
2077             s->lookahead -= s->prev_length - 1;
2078             s->prev_length -= 2;
2079             do {
2080                 if (++s->strstart <= max_insert) {
2081                     INSERT_STRING(s, s->strstart, hash_head);
2082                 }
2083             } while (--s->prev_length != 0);
2084             s->match_available = 0;
2085             s->match_length = MIN_MATCH-1;
2086             s->strstart++;
2087 
2088             if (bflush) FLUSH_BLOCK(s, 0);
2089 
2090         } else if (s->match_available) {
2091             /* If there was no match at the previous position, output a
2092              * single literal. If there was a match but the current match
2093              * is longer, truncate the previous match to a single literal.
2094              */
2095             Tracevv((stderr,"%c", s->window[s->strstart - 1]));
2096             _tr_tally_lit(s, s->window[s->strstart - 1], bflush);
2097             if (bflush) {
2098                 FLUSH_BLOCK_ONLY(s, 0);
2099             }
2100             s->strstart++;
2101             s->lookahead--;
2102             if (s->strm->avail_out == 0) return need_more;
2103         } else {
2104             /* There is no previous match to compare with, wait for
2105              * the next step to decide.
2106              */
2107             s->match_available = 1;
2108             s->strstart++;
2109             s->lookahead--;
2110         }
2111     }
2112     Assert (flush != Z_NO_FLUSH, "no flush?");
2113     if (s->match_available) {
2114         Tracevv((stderr,"%c", s->window[s->strstart - 1]));
2115         _tr_tally_lit(s, s->window[s->strstart - 1], bflush);
2116         s->match_available = 0;
2117     }
2118     s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
2119     if (flush == Z_FINISH) {
2120         FLUSH_BLOCK(s, 1);
2121         return finish_done;
2122     }
2123     if (s->sym_next)
2124         FLUSH_BLOCK(s, 0);
2125     return block_done;
2126 }
2127 #endif /* FASTEST */
2128 
2129 /* ===========================================================================
2130  * For Z_RLE, simply look for runs of bytes, generate matches only of distance
2131  * one.  Do not maintain a hash table.  (It will be regenerated if this run of
2132  * deflate switches away from Z_RLE.)
2133  */
2134 local block_state deflate_rle(s, flush)
2135     deflate_state *s;
2136     int flush;
2137 {
2138     int bflush;             /* set if current block must be flushed */
2139     uInt prev;              /* byte at distance one to match */
2140     Bytef *scan, *strend;   /* scan goes up to strend for length of run */
2141 
2142     for (;;) {
2143         /* Make sure that we always have enough lookahead, except
2144          * at the end of the input file. We need MAX_MATCH bytes
2145          * for the longest run, plus one for the unrolled loop.
2146          */
2147         if (s->lookahead <= MAX_MATCH) {
2148             fill_window(s);
2149             if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {
2150                 return need_more;
2151             }
2152             if (s->lookahead == 0) break; /* flush the current block */
2153         }
2154 
2155         /* See how many times the previous byte repeats */
2156         s->match_length = 0;
2157         if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
2158             scan = s->window + s->strstart - 1;
2159             prev = *scan;
2160             if (prev == *++scan && prev == *++scan && prev == *++scan) {
2161                 strend = s->window + s->strstart + MAX_MATCH;
2162                 do {
2163                 } while (prev == *++scan && prev == *++scan &&
2164                          prev == *++scan && prev == *++scan &&
2165                          prev == *++scan && prev == *++scan &&
2166                          prev == *++scan && prev == *++scan &&
2167                          scan < strend);
2168                 s->match_length = MAX_MATCH - (uInt)(strend - scan);
2169                 if (s->match_length > s->lookahead)
2170                     s->match_length = s->lookahead;
2171             }
2172             Assert(scan <= s->window + (uInt)(s->window_size - 1),
2173                    "wild scan");
2174         }
2175 
2176         /* Emit match if have run of MIN_MATCH or longer, else emit literal */
2177         if (s->match_length >= MIN_MATCH) {
2178             check_match(s, s->strstart, s->strstart - 1, s->match_length);
2179 
2180             _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
2181 
2182             s->lookahead -= s->match_length;
2183             s->strstart += s->match_length;
2184             s->match_length = 0;
2185         } else {
2186             /* No match, output a literal byte */
2187             Tracevv((stderr,"%c", s->window[s->strstart]));
2188             _tr_tally_lit(s, s->window[s->strstart], bflush);
2189             s->lookahead--;
2190             s->strstart++;
2191         }
2192         if (bflush) FLUSH_BLOCK(s, 0);
2193     }
2194     s->insert = 0;
2195     if (flush == Z_FINISH) {
2196         FLUSH_BLOCK(s, 1);
2197         return finish_done;
2198     }
2199     if (s->sym_next)
2200         FLUSH_BLOCK(s, 0);
2201     return block_done;
2202 }
2203 
2204 /* ===========================================================================
2205  * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
2206  * (It will be regenerated if this run of deflate switches away from Huffman.)
2207  */
2208 local block_state deflate_huff(s, flush)
2209     deflate_state *s;
2210     int flush;
2211 {
2212     int bflush;             /* set if current block must be flushed */
2213 
2214     for (;;) {
2215         /* Make sure that we have a literal to write. */
2216         if (s->lookahead == 0) {
2217             fill_window(s);
2218             if (s->lookahead == 0) {
2219                 if (flush == Z_NO_FLUSH)
2220                     return need_more;
2221                 break;      /* flush the current block */
2222             }
2223         }
2224 
2225         /* Output a literal byte */
2226         s->match_length = 0;
2227         Tracevv((stderr,"%c", s->window[s->strstart]));
2228         _tr_tally_lit(s, s->window[s->strstart], bflush);
2229         s->lookahead--;
2230         s->strstart++;
2231         if (bflush) FLUSH_BLOCK(s, 0);
2232     }
2233     s->insert = 0;
2234     if (flush == Z_FINISH) {
2235         FLUSH_BLOCK(s, 1);
2236         return finish_done;
2237     }
2238     if (s->sym_next)
2239         FLUSH_BLOCK(s, 0);
2240     return block_done;
2241 }