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