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