1 /* deflate.c -- compress data using the deflation algorithm
2 * Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
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).
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.
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.
39 * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
40 * Available in http://tools.ietf.org/html/rfc1951
42 * A description of the Rabin and Karp algorithm is given in the book
43 * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
45 * Fiala,E.R., and Greene,D.H.
46 * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
54 const char deflate_copyright[] =
55 " deflate 1.2.8 Copyright 1995-2013 Jean-loup Gailly and Mark Adler ";
57 If you use the zlib library in a product, an acknowledgment is welcome
58 in the documentation of your product. If for some reason you cannot
59 include such an acknowledgment, I would appreciate that you keep this
60 copyright string in the executable of your product.
63 /* ===========================================================================
64 * Function prototypes.
67 need_more, /* block not completed, need more input or more output */
68 block_done, /* block flush performed */
69 finish_started, /* finish started, need only more output at next deflate */
70 finish_done /* finish done, accept no more input or output */
73 typedef block_state (*compress_func) OF((deflate_state *s, int flush));
74 /* Compression function. Returns the block state after the call. */
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));
80 local block_state deflate_slow OF((deflate_state *s, int flush));
82 local block_state deflate_rle OF((deflate_state *s, int flush));
83 local block_state deflate_huff OF((deflate_state *s, int flush));
84 local void lm_init OF((deflate_state *s));
85 local void putShortMSB OF((deflate_state *s, uInt b));
86 local void flush_pending OF((z_streamp strm));
87 local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
89 void match_init OF((void)); /* asm code initialization */
90 uInt longest_match OF((deflate_state *s, IPos cur_match));
92 local uInt longest_match OF((deflate_state *s, IPos cur_match));
96 local void check_match OF((deflate_state *s, IPos start, IPos match,
100 /* ===========================================================================
105 /* Tail of hash chains */
108 # define TOO_FAR 4096
110 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
112 /* Values for max_lazy_match, good_match and max_chain_length, depending on
113 * the desired pack level (0..9). The values given below have been tuned to
114 * exclude worst case performance for pathological files. Better values may be
115 * found for specific files.
117 typedef struct config_s {
118 ush good_length; /* reduce lazy search above this match length */
119 ush max_lazy; /* do not perform lazy search above this match length */
120 ush nice_length; /* quit search above this match length */
126 local const config configuration_table[2] = {
127 /* good lazy nice chain */
128 /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
129 /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
131 local const config configuration_table[10] = {
132 /* good lazy nice chain */
133 /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
134 /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
135 /* 2 */ {4, 5, 16, 8, deflate_fast},
136 /* 3 */ {4, 6, 32, 32, deflate_fast},
138 /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
139 /* 5 */ {8, 16, 32, 32, deflate_slow},
140 /* 6 */ {8, 16, 128, 128, deflate_slow},
141 /* 7 */ {8, 32, 128, 256, deflate_slow},
142 /* 8 */ {32, 128, 258, 1024, deflate_slow},
143 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
146 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
147 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
152 /* result of memcmp for equal strings */
154 /* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */
155 #define RANK(f) (((f) << 1) - ((f) > 4 ? 9 : 0))
157 /* ===========================================================================
158 * Update a hash value with the given input byte
159 * IN assertion: all calls to to UPDATE_HASH are made with consecutive
160 * input characters, so that a running hash key can be computed from the
161 * previous key instead of complete recalculation each time.
163 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
166 /* ===========================================================================
167 * Insert string str in the dictionary and set match_head to the previous head
168 * of the hash chain (the most recent string with same hash key). Return
169 * the previous length of the hash chain.
170 * If this file is compiled with -DFASTEST, the compression level is forced
171 * to 1, and no hash chains are maintained.
172 * IN assertion: all calls to to INSERT_STRING are made with consecutive
173 * input characters and the first MIN_MATCH bytes of str are valid
174 * (except for the last MIN_MATCH-1 bytes of the input file).
177 #define INSERT_STRING(s, str, match_head) \
178 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
179 match_head = s->head[s->ins_h], \
180 s->head[s->ins_h] = (Pos)(str))
182 #define INSERT_STRING(s, str, match_head) \
183 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
184 match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
185 s->head[s->ins_h] = (Pos)(str))
188 /* ===========================================================================
189 * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
190 * prev[] will be initialized on the fly.
192 #define CLEAR_HASH(s) \
193 s->head[s->hash_size-1] = NIL; \
194 zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
196 int ZEXPORT deflateResetKeep (z_streamp strm);
198 int ZEXPORT deflatePending (z_streamp strm, unsigned *pending, int *bits);
200 /* ========================================================================= */
201 int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
203 return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
204 Z_DEFAULT_STRATEGY, version, stream_size);
205 /* To do: ignore strm->next_in if we use it as window */
208 /* ========================================================================= */
209 int ZEXPORT deflateInit2_(z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy,
210 const char *version, int stream_size)
214 static const char my_version[] = ZLIB_VERSION;
217 /* We overlay pending_buf and d_buf+l_buf. This works since the average
218 * output size for (length,distance) codes is <= 24 bits.
221 if (version == Z_NULL || version[0] != my_version[0] ||
222 stream_size != sizeof(z_stream)) {
223 return Z_VERSION_ERROR;
225 if (strm == Z_NULL) return Z_STREAM_ERROR;
228 if (strm->zalloc == (alloc_func)0) {
230 return Z_STREAM_ERROR;
232 strm->zalloc = zcalloc;
233 strm->opaque = (voidpf)0;
236 if (strm->zfree == NULL)
238 return Z_STREAM_ERROR;
240 strm->zfree = zcfree;
244 if (level != 0) level = 1;
246 if (level == Z_DEFAULT_COMPRESSION) level = 6;
249 if (windowBits < 0) { /* suppress zlib wrapper */
251 windowBits = -windowBits;
254 else if (windowBits > 15) {
255 wrap = 2; /* write gzip wrapper instead */
259 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
260 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
261 strategy < 0 || strategy > Z_FIXED) {
262 return Z_STREAM_ERROR;
264 if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
265 s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
266 if (s == Z_NULL) return Z_MEM_ERROR;
267 strm->state = (struct internal_state*)s;
272 s->w_bits = windowBits;
273 s->w_size = 1 << s->w_bits;
274 s->w_mask = s->w_size - 1;
276 s->hash_bits = memLevel + 7;
277 s->hash_size = 1 << s->hash_bits;
278 s->hash_mask = s->hash_size - 1;
279 s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
281 s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
282 s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
283 s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
285 s->high_water = 0; /* nothing written to s->window yet */
287 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
289 overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
290 s->pending_buf = (uchf *) overlay;
291 s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
293 if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
294 s->pending_buf == Z_NULL) {
295 s->status = FINISH_STATE;
296 strm->msg = ERR_MSG(Z_MEM_ERROR);
300 s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
301 s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
304 s->strategy = strategy;
305 s->method = (Byte)method;
307 return deflateReset(strm);
310 /* ========================================================================= */
311 int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
319 if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL)
320 return Z_STREAM_ERROR;
321 s = (deflate_state*)strm->state;
323 if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
324 return Z_STREAM_ERROR;
326 /* when using zlib wrappers, compute Adler-32 for provided dictionary */
328 strm->adler = adler32(strm->adler, dictionary, dictLength);
329 s->wrap = 0; /* avoid computing Adler-32 in read_buf */
331 /* if dictionary would fill window, just replace the history */
332 if (dictLength >= s->w_size) {
333 if (wrap == 0) { /* already empty otherwise */
339 dictionary += dictLength - s->w_size; /* use the tail */
340 dictLength = s->w_size;
343 /* insert dictionary into window and hash */
344 avail = strm->avail_in;
345 next = strm->next_in;
346 strm->avail_in = dictLength;
347 strm->next_in = (Bytef *)dictionary;
349 while (s->lookahead >= MIN_MATCH) {
351 n = s->lookahead - (MIN_MATCH-1);
353 UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
355 s->prev[str & s->w_mask] = s->head[s->ins_h];
357 s->head[s->ins_h] = (Pos)str;
361 s->lookahead = MIN_MATCH-1;
364 s->strstart += s->lookahead;
365 s->block_start = (long)s->strstart;
366 s->insert = s->lookahead;
368 s->match_length = s->prev_length = MIN_MATCH-1;
369 s->match_available = 0;
370 strm->next_in = next;
371 strm->avail_in = avail;
376 /* ========================================================================= */
377 int ZEXPORT deflateResetKeep (z_streamp strm)
381 if (strm == Z_NULL || strm->state == Z_NULL ||
382 strm->zalloc == Z_NULL || strm->zfree == Z_NULL) {
383 return Z_STREAM_ERROR;
386 strm->total_in = strm->total_out = 0;
387 strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
388 strm->data_type = Z_UNKNOWN;
390 s = (deflate_state *)strm->state;
392 s->pending_out = s->pending_buf;
395 s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
397 s->status = s->wrap ? INIT_STATE : BUSY_STATE;
400 s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
402 adler32(0L, Z_NULL, 0);
403 s->last_flush = Z_NO_FLUSH;
410 /* ========================================================================= */
411 int ZEXPORT deflateReset (z_streamp strm)
415 ret = deflateResetKeep(strm);
417 lm_init((deflate_state*)strm->state);
421 /* ========================================================================= */
422 int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
424 struct internal_state_deflate *state = (struct internal_state_deflate*)strm->state;
425 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
426 if (state->wrap != 2)
427 return Z_STREAM_ERROR;
428 state->gzhead = head;
432 /* ========================================================================= */
433 int ZEXPORT deflatePending (z_streamp strm, unsigned *pending, int *bits)
435 struct internal_state_deflate *state = (struct internal_state_deflate*)strm->state;
436 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
437 if (pending != Z_NULL)
438 *pending = state->pending;
440 *bits = state->bi_valid;
444 /* ========================================================================= */
445 int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
450 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
451 s = (deflate_state*)strm->state;
452 if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3))
455 put = Buf_size - s->bi_valid;
458 s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);
467 /* ========================================================================= */
468 int ZEXPORT deflateParams(z_streamp strm, int level, int strategy)
474 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
475 s = (deflate_state*)strm->state;
478 if (level != 0) level = 1;
480 if (level == Z_DEFAULT_COMPRESSION) level = 6;
482 if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
483 return Z_STREAM_ERROR;
485 func = configuration_table[s->level].func;
487 if ((strategy != s->strategy || func != configuration_table[level].func) &&
488 strm->total_in != 0) {
489 /* Flush the last buffer: */
490 err = deflate(strm, Z_BLOCK);
491 if (err == Z_BUF_ERROR && s->pending == 0)
494 if (s->level != level) {
496 s->max_lazy_match = configuration_table[level].max_lazy;
497 s->good_match = configuration_table[level].good_length;
498 s->nice_match = configuration_table[level].nice_length;
499 s->max_chain_length = configuration_table[level].max_chain;
501 s->strategy = strategy;
505 /* ========================================================================= */
506 int ZEXPORT deflateTune(z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
510 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
511 s = (deflate_state*)strm->state;
512 s->good_match = good_length;
513 s->max_lazy_match = max_lazy;
514 s->nice_match = nice_length;
515 s->max_chain_length = max_chain;
519 /* =========================================================================
520 * For the default windowBits of 15 and memLevel of 8, this function returns
521 * a close to exact, as well as small, upper bound on the compressed size.
522 * They are coded as constants here for a reason--if the #define's are
523 * changed, then this function needs to be changed as well. The return
524 * value for 15 and 8 only works for those exact settings.
526 * For any setting other than those defaults for windowBits and memLevel,
527 * the value returned is a conservative worst case for the maximum expansion
528 * resulting from using fixed blocks instead of stored blocks, which deflate
529 * can emit on compressed data for some combinations of the parameters.
531 * This function could be more sophisticated to provide closer upper bounds for
532 * every combination of windowBits and memLevel. But even the conservative
533 * upper bound of about 14% expansion does not seem onerous for output buffer
536 uLong ZEXPORT deflateBound(z_streamp strm, uLong sourceLen)
539 uLong complen, wraplen;
542 /* conservative upper bound for compressed data */
543 complen = sourceLen +
544 ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
546 /* if can't get parameters, return conservative bound plus zlib wrapper */
547 if (strm == Z_NULL || strm->state == Z_NULL)
550 /* compute wrapper length */
551 s = (deflate_state*)strm->state;
553 case 0: /* raw deflate */
556 case 1: /* zlib wrapper */
557 wraplen = 6 + (s->strstart ? 4 : 0);
559 case 2: /* gzip wrapper */
561 if (s->gzhead != Z_NULL) { /* user-supplied gzip header */
562 if (s->gzhead->extra != Z_NULL)
563 wraplen += 2 + s->gzhead->extra_len;
564 str = s->gzhead->name;
569 str = s->gzhead->comment;
578 default: /* for compiler happiness */
582 /* if not default parameters, return conservative bound */
583 if (s->w_bits != 15 || s->hash_bits != 8 + 7)
584 return complen + wraplen;
586 /* default settings: return tight bound for that case */
587 return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
588 (sourceLen >> 25) + 13 - 6 + wraplen;
591 /* =========================================================================
592 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
593 * IN assertion: the stream state is correct and there is enough room in
596 local void putShortMSB (deflate_state *s, uInt b)
598 put_byte(s, (Byte)(b >> 8));
599 put_byte(s, (Byte)(b & 0xff));
602 /* =========================================================================
603 * Flush as much pending output as possible. All deflate() output goes
604 * through this function so some applications may wish to modify it
605 * to avoid allocating a large strm->next_out buffer and copying into it.
606 * (See also read_buf()).
608 local void flush_pending(z_streamp strm)
611 deflate_state *s = (deflate_state*)strm->state;
615 if (len > strm->avail_out) len = strm->avail_out;
616 if (len == 0) return;
618 zmemcpy(strm->next_out, s->pending_out, len);
619 strm->next_out += len;
620 s->pending_out += len;
621 strm->total_out += len;
622 strm->avail_out -= len;
624 if (s->pending == 0) {
625 s->pending_out = s->pending_buf;
629 /* ========================================================================= */
630 int ZEXPORT deflate (z_streamp strm, int flush)
632 int old_flush; /* value of flush param for previous deflate call */
635 if (strm == Z_NULL || strm->state == Z_NULL ||
636 flush > Z_BLOCK || flush < 0) {
637 return Z_STREAM_ERROR;
639 s = (deflate_state*)strm->state;
641 if (strm->next_out == Z_NULL ||
642 (strm->next_in == Z_NULL && strm->avail_in != 0) ||
643 (s->status == FINISH_STATE && flush != Z_FINISH)) {
644 ERR_RETURN(strm, Z_STREAM_ERROR);
646 if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
648 s->strm = strm; /* just in case */
649 old_flush = s->last_flush;
650 s->last_flush = flush;
652 /* Write the header */
653 if (s->status == INIT_STATE) {
656 strm->adler = crc32(0L, Z_NULL, 0);
660 if (s->gzhead == Z_NULL) {
666 put_byte(s, s->level == 9 ? 2 :
667 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
669 put_byte(s, OS_CODE);
670 s->status = BUSY_STATE;
673 put_byte(s, (s->gzhead->text ? 1 : 0) +
674 (s->gzhead->hcrc ? 2 : 0) +
675 (s->gzhead->extra == Z_NULL ? 0 : 4) +
676 (s->gzhead->name == Z_NULL ? 0 : 8) +
677 (s->gzhead->comment == Z_NULL ? 0 : 16)
679 put_byte(s, (Byte)(s->gzhead->time & 0xff));
680 put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
681 put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
682 put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
683 put_byte(s, s->level == 9 ? 2 :
684 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
686 put_byte(s, s->gzhead->os & 0xff);
687 if (s->gzhead->extra != Z_NULL) {
688 put_byte(s, s->gzhead->extra_len & 0xff);
689 put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
692 strm->adler = crc32(strm->adler, s->pending_buf,
695 s->status = EXTRA_STATE;
701 uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
704 if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
706 else if (s->level < 6)
708 else if (s->level == 6)
712 header |= (level_flags << 6);
713 if (s->strstart != 0) header |= PRESET_DICT;
714 header += 31 - (header % 31);
716 s->status = BUSY_STATE;
717 putShortMSB(s, header);
719 /* Save the adler32 of the preset dictionary: */
720 if (s->strstart != 0) {
721 putShortMSB(s, (uInt)(strm->adler >> 16));
722 putShortMSB(s, (uInt)(strm->adler & 0xffff));
724 strm->adler = adler32(0L, Z_NULL, 0);
728 if (s->status == EXTRA_STATE) {
729 if (s->gzhead->extra != Z_NULL) {
730 uInt beg = s->pending; /* start of bytes to update crc */
732 while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
733 if (s->pending == s->pending_buf_size) {
734 if (s->gzhead->hcrc && s->pending > beg)
735 strm->adler = crc32(strm->adler, s->pending_buf + beg,
739 if (s->pending == s->pending_buf_size)
742 put_byte(s, s->gzhead->extra[s->gzindex]);
745 if (s->gzhead->hcrc && s->pending > beg)
746 strm->adler = crc32(strm->adler, s->pending_buf + beg,
748 if (s->gzindex == s->gzhead->extra_len) {
750 s->status = NAME_STATE;
754 s->status = NAME_STATE;
756 if (s->status == NAME_STATE) {
757 if (s->gzhead->name != Z_NULL) {
758 uInt beg = s->pending; /* start of bytes to update crc */
762 if (s->pending == s->pending_buf_size) {
763 if (s->gzhead->hcrc && s->pending > beg)
764 strm->adler = crc32(strm->adler, s->pending_buf + beg,
768 if (s->pending == s->pending_buf_size) {
773 val = s->gzhead->name[s->gzindex++];
776 if (s->gzhead->hcrc && s->pending > beg)
777 strm->adler = crc32(strm->adler, s->pending_buf + beg,
781 s->status = COMMENT_STATE;
785 s->status = COMMENT_STATE;
787 if (s->status == COMMENT_STATE) {
788 if (s->gzhead->comment != Z_NULL) {
789 uInt beg = s->pending; /* start of bytes to update crc */
793 if (s->pending == s->pending_buf_size) {
794 if (s->gzhead->hcrc && s->pending > beg)
795 strm->adler = crc32(strm->adler, s->pending_buf + beg,
799 if (s->pending == s->pending_buf_size) {
804 val = s->gzhead->comment[s->gzindex++];
807 if (s->gzhead->hcrc && s->pending > beg)
808 strm->adler = crc32(strm->adler, s->pending_buf + beg,
811 s->status = HCRC_STATE;
814 s->status = HCRC_STATE;
816 if (s->status == HCRC_STATE) {
817 if (s->gzhead->hcrc) {
818 if (s->pending + 2 > s->pending_buf_size)
820 if (s->pending + 2 <= s->pending_buf_size) {
821 put_byte(s, (Byte)(strm->adler & 0xff));
822 put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
823 strm->adler = crc32(0L, Z_NULL, 0);
824 s->status = BUSY_STATE;
828 s->status = BUSY_STATE;
832 /* Flush as much pending output as possible */
833 if (s->pending != 0) {
835 if (strm->avail_out == 0) {
836 /* Since avail_out is 0, deflate will be called again with
837 * more output space, but possibly with both pending and
838 * avail_in equal to zero. There won't be anything to do,
839 * but this is not an error situation so make sure we
840 * return OK instead of BUF_ERROR at next call of deflate:
846 /* Make sure there is something to do and avoid duplicate consecutive
847 * flushes. For repeated and useless calls with Z_FINISH, we keep
848 * returning Z_STREAM_END instead of Z_BUF_ERROR.
850 } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&
852 ERR_RETURN(strm, Z_BUF_ERROR);
855 /* User must not provide more input after the first FINISH: */
856 if (s->status == FINISH_STATE && strm->avail_in != 0) {
857 ERR_RETURN(strm, Z_BUF_ERROR);
860 /* Start a new block or continue the current one.
862 if (strm->avail_in != 0 || s->lookahead != 0 ||
863 (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
866 bstate = s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
867 (s->strategy == Z_RLE ? deflate_rle(s, flush) :
868 (*(configuration_table[s->level].func))(s, flush));
870 if (bstate == finish_started || bstate == finish_done) {
871 s->status = FINISH_STATE;
873 if (bstate == need_more || bstate == finish_started) {
874 if (strm->avail_out == 0) {
875 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
878 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
879 * of deflate should use the same flush parameter to make sure
880 * that the flush is complete. So we don't have to output an
881 * empty block here, this will be done at next call. This also
882 * ensures that for a very small output buffer, we emit at most
886 if (bstate == block_done) {
887 if (flush == Z_PARTIAL_FLUSH) {
889 } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
890 _tr_stored_block(s, (char*)0, 0L, 0);
891 /* For a full flush, this empty block will be recognized
892 * as a special marker by inflate_sync().
894 if (flush == Z_FULL_FLUSH) {
895 CLEAR_HASH(s); /* forget history */
896 if (s->lookahead == 0) {
904 if (strm->avail_out == 0) {
905 s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
910 Assert(strm->avail_out > 0, "bug2");
912 if (flush != Z_FINISH) return Z_OK;
913 if (s->wrap <= 0) return Z_STREAM_END;
915 /* Write the trailer */
918 put_byte(s, (Byte)(strm->adler & 0xff));
919 put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
920 put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
921 put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
922 put_byte(s, (Byte)(strm->total_in & 0xff));
923 put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
924 put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
925 put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
930 putShortMSB(s, (uInt)(strm->adler >> 16));
931 putShortMSB(s, (uInt)(strm->adler & 0xffff));
934 /* If avail_out is zero, the application will call deflate again
937 if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
938 return s->pending != 0 ? Z_OK : Z_STREAM_END;
941 /* ========================================================================= */
942 int ZEXPORT deflateEnd (z_streamp strm)
944 struct internal_state_deflate *state;
947 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
948 state = (struct internal_state_deflate*)strm->state;
950 status = state->status;
951 if (status != INIT_STATE &&
952 status != EXTRA_STATE &&
953 status != NAME_STATE &&
954 status != COMMENT_STATE &&
955 status != HCRC_STATE &&
956 status != BUSY_STATE &&
957 status != FINISH_STATE) {
958 return Z_STREAM_ERROR;
961 /* Deallocate in reverse order of allocations: */
962 TRY_FREE(strm, state->pending_buf);
963 TRY_FREE(strm, state->head);
964 TRY_FREE(strm, state->prev);
965 TRY_FREE(strm, state->window);
970 return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
973 /* =========================================================================
974 * Copy the source state to the destination state.
975 * To simplify the source, this is not supported for 16-bit MSDOS (which
976 * doesn't have enough memory anyway to duplicate compression states).
978 int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
981 return Z_STREAM_ERROR;
988 if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
989 return Z_STREAM_ERROR;
992 ss = (deflate_state*)source->state;
994 zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
996 ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
997 if (ds == Z_NULL) return Z_MEM_ERROR;
998 dest->state = (struct internal_state FAR *) ds;
999 zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));
1002 ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
1003 ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
1004 ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
1005 overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
1006 ds->pending_buf = (uchf *) overlay;
1008 if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
1009 ds->pending_buf == Z_NULL) {
1013 /* following zmemcpy do not work for 16-bit MSDOS */
1014 zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
1015 zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));
1016 zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));
1017 zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
1019 ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
1020 ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
1021 ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
1023 ds->l_desc.dyn_tree = ds->dyn_ltree;
1024 ds->d_desc.dyn_tree = ds->dyn_dtree;
1025 ds->bl_desc.dyn_tree = ds->bl_tree;
1028 #endif /* MAXSEG_64K */
1031 /* ===========================================================================
1032 * Read a new buffer from the current input stream, update the adler32
1033 * and total number of bytes read. All deflate() input goes through
1034 * this function so some applications may wish to modify it to avoid
1035 * allocating a large strm->next_in buffer and copying from it.
1036 * (See also flush_pending()).
1038 local int read_buf(z_streamp strm, Bytef *buf, unsigned size)
1040 struct internal_state_deflate *state = (struct internal_state_deflate*)strm->state;
1041 unsigned len = strm->avail_in;
1043 if (len > size) len = size;
1044 if (len == 0) return 0;
1046 strm->avail_in -= len;
1048 zmemcpy(buf, strm->next_in, len);
1049 if (state->wrap == 1) {
1050 strm->adler = adler32(strm->adler, buf, len);
1053 else if (state->wrap == 2) {
1054 strm->adler = crc32(strm->adler, buf, len);
1057 strm->next_in += len;
1058 strm->total_in += len;
1063 /* ===========================================================================
1064 * Initialize the "longest match" routines for a new zlib stream
1066 local void lm_init (deflate_state *s)
1068 s->window_size = (ulg)2L*s->w_size;
1072 /* Set the default configuration parameters:
1074 s->max_lazy_match = configuration_table[s->level].max_lazy;
1075 s->good_match = configuration_table[s->level].good_length;
1076 s->nice_match = configuration_table[s->level].nice_length;
1077 s->max_chain_length = configuration_table[s->level].max_chain;
1080 s->block_start = 0L;
1083 s->match_length = s->prev_length = MIN_MATCH-1;
1084 s->match_available = 0;
1088 match_init(); /* initialize the asm code */
1094 /* ===========================================================================
1095 * Set match_start to the longest match starting at the given string and
1096 * return its length. Matches shorter or equal to prev_length are discarded,
1097 * in which case the result is equal to prev_length and match_start is
1099 * IN assertions: cur_match is the head of the hash chain for the current
1100 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1101 * OUT assertion: the match length is not greater than s->lookahead.
1104 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
1105 * match.S. The code will be functionally equivalent.
1107 local uInt longest_match(deflate_state *s, IPos cur_match)
1109 unsigned chain_length = s->max_chain_length;/* max hash chain length */
1110 register Bytef *scan = s->window + s->strstart; /* current string */
1111 register Bytef *match; /* matched string */
1112 register int len; /* length of current match */
1113 int best_len = s->prev_length; /* best match length so far */
1114 int nice_match = s->nice_match; /* stop if match long enough */
1115 IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
1116 s->strstart - (IPos)MAX_DIST(s) : NIL;
1117 /* Stop when cur_match becomes <= limit. To simplify the code,
1118 * we prevent matches with the string of window index 0.
1120 Posf *prev = s->prev;
1121 uInt wmask = s->w_mask;
1124 /* Compare two bytes at a time. Note: this is not always beneficial.
1125 * Try with and without -DUNALIGNED_OK to check.
1127 register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
1128 register ush scan_start = *(ushf*)scan;
1129 register ush scan_end = *(ushf*)(scan+best_len-1);
1131 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1132 register Byte scan_end1 = scan[best_len-1];
1133 register Byte scan_end = scan[best_len];
1136 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1137 * It is easy to get rid of this optimization if necessary.
1139 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1141 /* Do not waste too much time if we already have a good match: */
1142 if (s->prev_length >= s->good_match) {
1145 /* Do not look for matches beyond the end of the input. This is necessary
1146 * to make deflate deterministic.
1148 if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
1150 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1153 Assert(cur_match < s->strstart, "no future");
1154 match = s->window + cur_match;
1156 /* Skip to next match if the match length cannot increase
1157 * or if the match length is less than 2. Note that the checks below
1158 * for insufficient lookahead only occur occasionally for performance
1159 * reasons. Therefore uninitialized memory will be accessed, and
1160 * conditional jumps will be made that depend on those values.
1161 * However the length of the match is limited to the lookahead, so
1162 * the output of deflate is not affected by the uninitialized values.
1164 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
1165 /* This code assumes sizeof(unsigned short) == 2. Do not use
1166 * UNALIGNED_OK if your compiler uses a different size.
1168 if (*(ushf*)(match+best_len-1) != scan_end ||
1169 *(ushf*)match != scan_start) continue;
1171 /* It is not necessary to compare scan[2] and match[2] since they are
1172 * always equal when the other bytes match, given that the hash keys
1173 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
1174 * strstart+3, +5, ... up to strstart+257. We check for insufficient
1175 * lookahead only every 4th comparison; the 128th check will be made
1176 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
1177 * necessary to put more guard bytes at the end of the window, or
1178 * to check more often for insufficient lookahead.
1180 Assert(scan[2] == match[2], "scan[2]?");
1183 } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1184 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1185 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1186 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1188 /* The funny "do {}" generates better code on most compilers */
1190 /* Here, scan <= window+strstart+257 */
1191 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1192 if (*scan == *match) scan++;
1194 len = (MAX_MATCH - 1) - (int)(strend-scan);
1195 scan = strend - (MAX_MATCH-1);
1197 #else /* UNALIGNED_OK */
1199 if (match[best_len] != scan_end ||
1200 match[best_len-1] != scan_end1 ||
1202 *++match != scan[1]) continue;
1204 /* The check at best_len-1 can be removed because it will be made
1205 * again later. (This heuristic is not always a win.)
1206 * It is not necessary to compare scan[2] and match[2] since they
1207 * are always equal when the other bytes match, given that
1208 * the hash keys are equal and that HASH_BITS >= 8.
1211 Assert(*scan == *match, "match[2]?");
1213 /* We check for insufficient lookahead only every 8th comparison;
1214 * the 256th check will be made at strstart+258.
1217 } while (*++scan == *++match && *++scan == *++match &&
1218 *++scan == *++match && *++scan == *++match &&
1219 *++scan == *++match && *++scan == *++match &&
1220 *++scan == *++match && *++scan == *++match &&
1223 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1225 len = MAX_MATCH - (int)(strend - scan);
1226 scan = strend - MAX_MATCH;
1228 #endif /* UNALIGNED_OK */
1230 if (len > best_len) {
1231 s->match_start = cur_match;
1233 if (len >= nice_match) break;
1235 scan_end = *(ushf*)(scan+best_len-1);
1237 scan_end1 = scan[best_len-1];
1238 scan_end = scan[best_len];
1241 } while ((cur_match = prev[cur_match & wmask]) > limit
1242 && --chain_length != 0);
1244 if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
1245 return s->lookahead;
1251 /* ---------------------------------------------------------------------------
1252 * Optimized version for FASTEST only
1254 local uInt longest_match(s, cur_match)
1256 IPos cur_match; /* current match */
1258 register Bytef *scan = s->window + s->strstart; /* current string */
1259 register Bytef *match; /* matched string */
1260 register int len; /* length of current match */
1261 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1263 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1264 * It is easy to get rid of this optimization if necessary.
1266 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1268 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1270 Assert(cur_match < s->strstart, "no future");
1272 match = s->window + cur_match;
1274 /* Return failure if the match length is less than 2:
1276 if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
1278 /* The check at best_len-1 can be removed because it will be made
1279 * again later. (This heuristic is not always a win.)
1280 * It is not necessary to compare scan[2] and match[2] since they
1281 * are always equal when the other bytes match, given that
1282 * the hash keys are equal and that HASH_BITS >= 8.
1284 scan += 2, match += 2;
1285 Assert(*scan == *match, "match[2]?");
1287 /* We check for insufficient lookahead only every 8th comparison;
1288 * the 256th check will be made at strstart+258.
1291 } while (*++scan == *++match && *++scan == *++match &&
1292 *++scan == *++match && *++scan == *++match &&
1293 *++scan == *++match && *++scan == *++match &&
1294 *++scan == *++match && *++scan == *++match &&
1297 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1299 len = MAX_MATCH - (int)(strend - scan);
1301 if (len < MIN_MATCH) return MIN_MATCH - 1;
1303 s->match_start = cur_match;
1304 return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
1307 #endif /* FASTEST */
1310 /* ===========================================================================
1311 * Check that the match at match_start is indeed a match.
1313 local void check_match(s, start, match, length)
1318 /* check that the match is indeed a match */
1319 if (zmemcmp(s->window + match,
1320 s->window + start, length) != EQUAL) {
1321 fprintf(stderr, " start %u, match %u, length %d\n",
1322 start, match, length);
1324 fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
1325 } while (--length != 0);
1326 z_error("invalid match");
1328 if (z_verbose > 1) {
1329 fprintf(stderr,"\\[%d,%d]", start-match, length);
1330 do { putc(s->window[start++], stderr); } while (--length != 0);
1334 # define check_match(s, start, match, length)
1337 /* ===========================================================================
1338 * Fill the window when the lookahead becomes insufficient.
1339 * Updates strstart and lookahead.
1341 * IN assertion: lookahead < MIN_LOOKAHEAD
1342 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1343 * At least one byte has been read, or avail_in == 0; reads are
1344 * performed for at least two bytes (required for the zip translate_eol
1345 * option -- not supported here).
1347 local void fill_window(deflate_state *s)
1349 register unsigned n, m;
1351 unsigned more; /* Amount of free space at the end of the window. */
1352 uInt wsize = s->w_size;
1354 Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
1357 more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
1359 /* Deal with !@#$% 64K limit: */
1360 if (sizeof(int) <= 2) {
1361 if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1364 } else if (more == (unsigned)(-1)) {
1365 /* Very unlikely, but possible on 16 bit machine if
1366 * strstart == 0 && lookahead == 1 (input done a byte at time)
1372 /* If the window is almost full and there is insufficient lookahead,
1373 * move the upper half to the lower one to make room in the upper half.
1375 if (s->strstart >= wsize+MAX_DIST(s)) {
1377 zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
1378 s->match_start -= wsize;
1379 s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
1380 s->block_start -= (long) wsize;
1382 /* Slide the hash table (could be avoided with 32 bit values
1383 at the expense of memory usage). We slide even when level == 0
1384 to keep the hash table consistent if we switch back to level > 0
1385 later. (Using level 0 permanently is not an optimal usage of
1386 zlib, so we don't care about this pathological case.)
1392 *p = (Pos)(m >= wsize ? m-wsize : NIL);
1400 *p = (Pos)(m >= wsize ? m-wsize : NIL);
1401 /* If n is not on any hash chain, prev[n] is garbage but
1402 * its value will never be used.
1408 if (s->strm->avail_in == 0) break;
1410 /* If there was no sliding:
1411 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1412 * more == window_size - lookahead - strstart
1413 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1414 * => more >= window_size - 2*WSIZE + 2
1415 * In the BIG_MEM or MMAP case (not yet supported),
1416 * window_size == input_size + MIN_LOOKAHEAD &&
1417 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1418 * Otherwise, window_size == 2*WSIZE so more >= 2.
1419 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1421 Assert(more >= 2, "more < 2");
1423 n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1426 /* Initialize the hash value now that we have some input: */
1427 if (s->lookahead + s->insert >= MIN_MATCH) {
1428 uInt str = s->strstart - s->insert;
1429 s->ins_h = s->window[str];
1430 UPDATE_HASH(s, s->ins_h, s->window[str + 1]);
1432 Call UPDATE_HASH() MIN_MATCH-3 more times
1435 UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
1437 s->prev[str & s->w_mask] = s->head[s->ins_h];
1439 s->head[s->ins_h] = (Pos)str;
1442 if (s->lookahead + s->insert < MIN_MATCH)
1446 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1447 * but this is not important since only literal bytes will be emitted.
1450 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1452 /* If the WIN_INIT bytes after the end of the current data have never been
1453 * written, then zero those bytes in order to avoid memory check reports of
1454 * the use of uninitialized (or uninitialised as Julian writes) bytes by
1455 * the longest match routines. Update the high water mark for the next
1456 * time through here. WIN_INIT is set to MAX_MATCH since the longest match
1457 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
1459 if (s->high_water < s->window_size) {
1460 ulg curr = s->strstart + (ulg)(s->lookahead);
1463 if (s->high_water < curr) {
1464 /* Previous high water mark below current data -- zero WIN_INIT
1465 * bytes or up to end of window, whichever is less.
1467 init = s->window_size - curr;
1468 if (init > WIN_INIT)
1470 zmemzero(s->window + curr, (unsigned)init);
1471 s->high_water = curr + init;
1473 else if (s->high_water < (ulg)curr + WIN_INIT) {
1474 /* High water mark at or above current data, but below current data
1475 * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
1476 * to end of window, whichever is less.
1478 init = (ulg)curr + WIN_INIT - s->high_water;
1479 if (init > s->window_size - s->high_water)
1480 init = s->window_size - s->high_water;
1481 zmemzero(s->window + s->high_water, (unsigned)init);
1482 s->high_water += init;
1486 Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1487 "not enough room for search");
1490 /* ===========================================================================
1491 * Flush the current block, with given end-of-file flag.
1492 * IN assertion: strstart is set to the end of the current match.
1494 #define FLUSH_BLOCK_ONLY(s, last) { \
1495 _tr_flush_block(s, (s->block_start >= 0L ? \
1496 (charf *)&s->window[(unsigned)s->block_start] : \
1498 (ulg)((long)s->strstart - s->block_start), \
1500 s->block_start = s->strstart; \
1501 flush_pending(s->strm); \
1502 Tracev((stderr,"[FLUSH]")); \
1505 /* Same but force premature exit if necessary. */
1506 #define FLUSH_BLOCK(s, last) { \
1507 FLUSH_BLOCK_ONLY(s, last); \
1508 if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
1511 /* ===========================================================================
1512 * Copy without compression as much as possible from the input stream, return
1513 * the current block state.
1514 * This function does not insert new strings in the dictionary since
1515 * uncompressible data is probably not useful. This function is used
1516 * only for the level=0 compression option.
1517 * NOTE: this function should be optimized to avoid extra copying from
1518 * window to pending_buf.
1520 local block_state deflate_stored(deflate_state *s, int flush)
1522 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
1523 * to pending_buf_size, and each stored block has a 5 byte header:
1525 ulg max_block_size = 0xffff;
1528 if (max_block_size > s->pending_buf_size - 5) {
1529 max_block_size = s->pending_buf_size - 5;
1532 /* Copy as much as possible from input to output: */
1534 /* Fill the window as much as possible: */
1535 if (s->lookahead <= 1) {
1537 Assert(s->strstart < s->w_size+MAX_DIST(s) ||
1538 s->block_start >= (long)s->w_size, "slide too late");
1541 if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
1543 if (s->lookahead == 0) break; /* flush the current block */
1545 Assert(s->block_start >= 0L, "block gone");
1547 s->strstart += s->lookahead;
1550 /* Emit a stored block if pending_buf will be full: */
1551 max_start = s->block_start + max_block_size;
1552 if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
1553 /* strstart == 0 is possible when wraparound on 16-bit machine */
1554 s->lookahead = (uInt)(s->strstart - max_start);
1555 s->strstart = (uInt)max_start;
1558 /* Flush if we may have to slide, otherwise block_start may become
1559 * negative and the data will be gone:
1561 if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
1566 if (flush == Z_FINISH) {
1570 if ((long)s->strstart > s->block_start)
1575 /* ===========================================================================
1576 * Compress as much as possible from the input stream, return the current
1578 * This function does not perform lazy evaluation of matches and inserts
1579 * new strings in the dictionary only for unmatched strings or for short
1580 * matches. It is used only for the fast compression options.
1582 local block_state deflate_fast(deflate_state *s, int flush)
1584 IPos hash_head; /* head of the hash chain */
1585 int bflush; /* set if current block must be flushed */
1588 /* Make sure that we always have enough lookahead, except
1589 * at the end of the input file. We need MAX_MATCH bytes
1590 * for the next match, plus MIN_MATCH bytes to insert the
1591 * string following the next match.
1593 if (s->lookahead < MIN_LOOKAHEAD) {
1595 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1598 if (s->lookahead == 0) break; /* flush the current block */
1601 /* Insert the string window[strstart .. strstart+2] in the
1602 * dictionary, and set hash_head to the head of the hash chain:
1605 if (s->lookahead >= MIN_MATCH) {
1606 INSERT_STRING(s, s->strstart, hash_head);
1609 /* Find the longest match, discarding those <= prev_length.
1610 * At this point we have always match_length < MIN_MATCH
1612 if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1613 /* To simplify the code, we prevent matches with the string
1614 * of window index 0 (in particular we have to avoid a match
1615 * of the string with itself at the start of the input file).
1617 s->match_length = longest_match (s, hash_head);
1618 /* longest_match() sets match_start */
1620 if (s->match_length >= MIN_MATCH) {
1621 check_match(s, s->strstart, s->match_start, s->match_length);
1623 _tr_tally_dist(s, s->strstart - s->match_start,
1624 s->match_length - MIN_MATCH, bflush);
1626 s->lookahead -= s->match_length;
1628 /* Insert new strings in the hash table only if the match length
1629 * is not too large. This saves time but degrades compression.
1632 if (s->match_length <= s->max_insert_length &&
1633 s->lookahead >= MIN_MATCH) {
1634 s->match_length--; /* string at strstart already in table */
1637 INSERT_STRING(s, s->strstart, hash_head);
1638 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1639 * always MIN_MATCH bytes ahead.
1641 } while (--s->match_length != 0);
1646 s->strstart += s->match_length;
1647 s->match_length = 0;
1648 s->ins_h = s->window[s->strstart];
1649 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1651 Call UPDATE_HASH() MIN_MATCH-3 more times
1653 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1654 * matter since it will be recomputed at next deflate call.
1658 /* No match, output a literal byte */
1659 Tracevv((stderr,"%c", s->window[s->strstart]));
1660 _tr_tally_lit (s, s->window[s->strstart], bflush);
1664 if (bflush) FLUSH_BLOCK(s, 0);
1666 s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
1667 if (flush == Z_FINISH) {
1677 /* ===========================================================================
1678 * Same as above, but achieves better compression. We use a lazy
1679 * evaluation for matches: a match is finally adopted only if there is
1680 * no better match at the next window position.
1682 local block_state deflate_slow(deflate_state *s, int flush)
1684 IPos hash_head; /* head of hash chain */
1685 int bflush; /* set if current block must be flushed */
1687 /* Process the input block. */
1689 /* Make sure that we always have enough lookahead, except
1690 * at the end of the input file. We need MAX_MATCH bytes
1691 * for the next match, plus MIN_MATCH bytes to insert the
1692 * string following the next match.
1694 if (s->lookahead < MIN_LOOKAHEAD) {
1696 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1699 if (s->lookahead == 0) break; /* flush the current block */
1702 /* Insert the string window[strstart .. strstart+2] in the
1703 * dictionary, and set hash_head to the head of the hash chain:
1706 if (s->lookahead >= MIN_MATCH) {
1707 INSERT_STRING(s, s->strstart, hash_head);
1710 /* Find the longest match, discarding those <= prev_length.
1712 s->prev_length = s->match_length, s->prev_match = s->match_start;
1713 s->match_length = MIN_MATCH-1;
1715 if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
1716 s->strstart - hash_head <= MAX_DIST(s)) {
1717 /* To simplify the code, we prevent matches with the string
1718 * of window index 0 (in particular we have to avoid a match
1719 * of the string with itself at the start of the input file).
1721 s->match_length = longest_match (s, hash_head);
1722 /* longest_match() sets match_start */
1724 if (s->match_length <= 5 && (s->strategy == Z_FILTERED
1725 #if TOO_FAR <= 32767
1726 || (s->match_length == MIN_MATCH &&
1727 s->strstart - s->match_start > TOO_FAR)
1731 /* If prev_match is also MIN_MATCH, match_start is garbage
1732 * but we will ignore the current match anyway.
1734 s->match_length = MIN_MATCH-1;
1737 /* If there was a match at the previous step and the current
1738 * match is not better, output the previous match:
1740 if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
1741 uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
1742 /* Do not insert strings in hash table beyond this. */
1744 check_match(s, s->strstart-1, s->prev_match, s->prev_length);
1746 _tr_tally_dist(s, s->strstart -1 - s->prev_match,
1747 s->prev_length - MIN_MATCH, bflush);
1749 /* Insert in hash table all strings up to the end of the match.
1750 * strstart-1 and strstart are already inserted. If there is not
1751 * enough lookahead, the last two strings are not inserted in
1754 s->lookahead -= s->prev_length-1;
1755 s->prev_length -= 2;
1757 if (++s->strstart <= max_insert) {
1758 INSERT_STRING(s, s->strstart, hash_head);
1760 } while (--s->prev_length != 0);
1761 s->match_available = 0;
1762 s->match_length = MIN_MATCH-1;
1765 if (bflush) FLUSH_BLOCK(s, 0);
1767 } else if (s->match_available) {
1768 /* If there was no match at the previous position, output a
1769 * single literal. If there was a match but the current match
1770 * is longer, truncate the previous match to a single literal.
1772 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1773 _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1775 FLUSH_BLOCK_ONLY(s, 0);
1779 if (s->strm->avail_out == 0) return need_more;
1781 /* There is no previous match to compare with, wait for
1782 * the next step to decide.
1784 s->match_available = 1;
1789 Assert (flush != Z_NO_FLUSH, "no flush?");
1790 if (s->match_available) {
1791 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1792 _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1793 s->match_available = 0;
1795 s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
1796 if (flush == Z_FINISH) {
1804 #endif /* FASTEST */
1806 /* ===========================================================================
1807 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
1808 * one. Do not maintain a hash table. (It will be regenerated if this run of
1809 * deflate switches away from Z_RLE.)
1811 local block_state deflate_rle(deflate_state *s, int flush)
1813 int bflush; /* set if current block must be flushed */
1814 uInt prev; /* byte at distance one to match */
1815 Bytef *scan, *strend; /* scan goes up to strend for length of run */
1818 /* Make sure that we always have enough lookahead, except
1819 * at the end of the input file. We need MAX_MATCH bytes
1820 * for the longest run, plus one for the unrolled loop.
1822 if (s->lookahead <= MAX_MATCH) {
1824 if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {
1827 if (s->lookahead == 0) break; /* flush the current block */
1830 /* See how many times the previous byte repeats */
1831 s->match_length = 0;
1832 if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
1833 scan = s->window + s->strstart - 1;
1835 if (prev == *++scan && prev == *++scan && prev == *++scan) {
1836 strend = s->window + s->strstart + MAX_MATCH;
1838 } while (prev == *++scan && prev == *++scan &&
1839 prev == *++scan && prev == *++scan &&
1840 prev == *++scan && prev == *++scan &&
1841 prev == *++scan && prev == *++scan &&
1843 s->match_length = MAX_MATCH - (int)(strend - scan);
1844 if (s->match_length > s->lookahead)
1845 s->match_length = s->lookahead;
1847 Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
1850 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
1851 if (s->match_length >= MIN_MATCH) {
1852 check_match(s, s->strstart, s->strstart - 1, s->match_length);
1854 _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
1856 s->lookahead -= s->match_length;
1857 s->strstart += s->match_length;
1858 s->match_length = 0;
1860 /* No match, output a literal byte */
1861 Tracevv((stderr,"%c", s->window[s->strstart]));
1862 _tr_tally_lit (s, s->window[s->strstart], bflush);
1866 if (bflush) FLUSH_BLOCK(s, 0);
1869 if (flush == Z_FINISH) {
1878 /* ===========================================================================
1879 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
1880 * (It will be regenerated if this run of deflate switches away from Huffman.)
1882 local block_state deflate_huff(deflate_state *s, int flush)
1884 int bflush; /* set if current block must be flushed */
1887 /* Make sure that we have a literal to write. */
1888 if (s->lookahead == 0) {
1890 if (s->lookahead == 0) {
1891 if (flush == Z_NO_FLUSH)
1893 break; /* flush the current block */
1897 /* Output a literal byte */
1898 s->match_length = 0;
1899 Tracevv((stderr,"%c", s->window[s->strstart]));
1900 _tr_tally_lit (s, s->window[s->strstart], bflush);
1903 if (bflush) FLUSH_BLOCK(s, 0);
1906 if (flush == Z_FINISH) {