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