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