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