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