fix typo in manual page
[rsync.git] / zlib / deflate.c
blob2cbc4fc2fa34633afc70442f21f87a8daabde285
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
4 */
6 /*
7 * ALGORITHM
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.
31 * ACKNOWLEDGEMENTS
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.
37 * REFERENCES
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
50 /* @(#) $Id$ */
52 #include "deflate.h"
54 #define read_buf dread_buf
56 const char deflate_copyright[] =
57 " deflate 1.2.8 Copyright 1995-2013 Jean-loup Gailly and Mark Adler ";
59 If you use the zlib library in a product, an acknowledgment is welcome
60 in the documentation of your product. If for some reason you cannot
61 include such an acknowledgment, I would appreciate that you keep this
62 copyright string in the executable of your product.
65 /* ===========================================================================
66 * Function prototypes.
68 typedef enum {
69 need_more, /* block not completed, need more input or more output */
70 block_done, /* block flush performed */
71 finish_started, /* finish started, need only more output at next deflate */
72 finish_done /* finish done, accept no more input or output */
73 } block_state;
75 typedef block_state (*compress_func) OF((deflate_state *s, int flush));
76 /* Compression function. Returns the block state after the call. */
78 local void fill_window OF((deflate_state *s));
79 local block_state deflate_stored OF((deflate_state *s, int flush));
80 local block_state deflate_fast OF((deflate_state *s, int flush));
81 #ifndef FASTEST
82 local block_state deflate_slow OF((deflate_state *s, int flush));
83 #endif
84 local block_state deflate_rle OF((deflate_state *s, int flush));
85 local block_state deflate_huff OF((deflate_state *s, int flush));
86 local void lm_init OF((deflate_state *s));
87 local void putShortMSB OF((deflate_state *s, uInt b));
88 local void flush_pending OF((z_streamp strm));
89 local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
90 #ifdef ASMV
91 void match_init OF((void)); /* asm code initialization */
92 uInt longest_match OF((deflate_state *s, IPos cur_match));
93 #else
94 local uInt longest_match OF((deflate_state *s, IPos cur_match));
95 #endif
97 #ifdef DEBUG
98 local void check_match OF((deflate_state *s, IPos start, IPos match,
99 int length));
100 #endif
102 /* ===========================================================================
103 * Local data
106 #define NIL 0
107 /* Tail of hash chains */
109 #ifndef TOO_FAR
110 # define TOO_FAR 4096
111 #endif
112 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
114 /* Values for max_lazy_match, good_match and max_chain_length, depending on
115 * the desired pack level (0..9). The values given below have been tuned to
116 * exclude worst case performance for pathological files. Better values may be
117 * found for specific files.
119 typedef struct config_s {
120 ush good_length; /* reduce lazy search above this match length */
121 ush max_lazy; /* do not perform lazy search above this match length */
122 ush nice_length; /* quit search above this match length */
123 ush max_chain;
124 compress_func func;
125 } config;
127 #ifdef FASTEST
128 local const config configuration_table[2] = {
129 /* good lazy nice chain */
130 /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
131 /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
132 #else
133 local const config configuration_table[10] = {
134 /* good lazy nice chain */
135 /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
136 /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
137 /* 2 */ {4, 5, 16, 8, deflate_fast},
138 /* 3 */ {4, 6, 32, 32, deflate_fast},
140 /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
141 /* 5 */ {8, 16, 32, 32, deflate_slow},
142 /* 6 */ {8, 16, 128, 128, deflate_slow},
143 /* 7 */ {8, 32, 128, 256, deflate_slow},
144 /* 8 */ {32, 128, 258, 1024, deflate_slow},
145 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
146 #endif
148 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
149 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
150 * meaning.
153 #define EQUAL 0
154 /* result of memcmp for equal strings */
156 #ifndef NO_DUMMY_DECL
157 struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
158 #endif
160 /* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */
161 #define RANK(f) (((f) << 1) - ((f) > 4 ? 9 : 0))
163 /* ===========================================================================
164 * Update a hash value with the given input byte
165 * IN assertion: all calls to to UPDATE_HASH are made with consecutive
166 * input characters, so that a running hash key can be computed from the
167 * previous key instead of complete recalculation each time.
169 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
172 /* ===========================================================================
173 * Insert string str in the dictionary and set match_head to the previous head
174 * of the hash chain (the most recent string with same hash key). Return
175 * the previous length of the hash chain.
176 * If this file is compiled with -DFASTEST, the compression level is forced
177 * to 1, and no hash chains are maintained.
178 * IN assertion: all calls to to INSERT_STRING are made with consecutive
179 * input characters and the first MIN_MATCH bytes of str are valid
180 * (except for the last MIN_MATCH-1 bytes of the input file).
182 #ifdef FASTEST
183 #define INSERT_STRING(s, str, match_head) \
184 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
185 match_head = s->head[s->ins_h], \
186 s->head[s->ins_h] = (Pos)(str))
187 #else
188 #define INSERT_STRING(s, str, match_head) \
189 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
190 match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
191 s->head[s->ins_h] = (Pos)(str))
192 #endif
194 /* ===========================================================================
195 * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
196 * prev[] will be initialized on the fly.
198 #define CLEAR_HASH(s) \
199 s->head[s->hash_size-1] = NIL; \
200 zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
202 /* ========================================================================= */
203 int ZEXPORT deflateInit_(strm, level, version, stream_size)
204 z_streamp strm;
205 int level;
206 const char *version;
207 int stream_size;
209 return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
210 Z_DEFAULT_STRATEGY, version, stream_size);
211 /* To do: ignore strm->next_in if we use it as window */
214 /* ========================================================================= */
215 int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
216 version, stream_size)
217 z_streamp strm;
218 int level;
219 int method;
220 int windowBits;
221 int memLevel;
222 int strategy;
223 const char *version;
224 int stream_size;
226 deflate_state *s;
227 int wrap = 1;
228 static const char my_version[] = ZLIB_VERSION;
230 if (version == Z_NULL || version[0] != my_version[0] ||
231 stream_size != sizeof(z_stream)) {
232 return Z_VERSION_ERROR;
234 if (strm == Z_NULL) return Z_STREAM_ERROR;
236 strm->msg = Z_NULL;
237 if (strm->zalloc == (alloc_func)0) {
238 #ifdef Z_SOLO
239 return Z_STREAM_ERROR;
240 #else
241 strm->zalloc = zcalloc;
242 strm->opaque = (voidpf)0;
243 #endif
245 if (strm->zfree == (free_func)0)
246 #ifdef Z_SOLO
247 return Z_STREAM_ERROR;
248 #else
249 strm->zfree = zcfree;
250 #endif
252 #ifdef FASTEST
253 if (level != 0) level = 1;
254 #else
255 if (level == Z_DEFAULT_COMPRESSION) level = 6;
256 #endif
258 if (windowBits < 0) { /* suppress zlib wrapper */
259 wrap = 0;
260 windowBits = -windowBits;
262 #ifdef GZIP
263 else if (windowBits > 15) {
264 wrap = 2; /* write gzip wrapper instead */
265 windowBits -= 16;
267 #endif
268 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
269 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
270 strategy < 0 || strategy > Z_FIXED) {
271 return Z_STREAM_ERROR;
273 if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
274 s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
275 if (s == Z_NULL) return Z_MEM_ERROR;
276 strm->state = (struct internal_state FAR *)s;
277 s->strm = strm;
279 s->wrap = wrap;
280 s->gzhead = Z_NULL;
281 s->w_bits = windowBits;
282 s->w_size = 1 << s->w_bits;
283 s->w_mask = s->w_size - 1;
285 s->hash_bits = memLevel + 7;
286 s->hash_size = 1 << s->hash_bits;
287 s->hash_mask = s->hash_size - 1;
288 s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
290 s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
291 s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
292 s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
294 s->high_water = 0; /* nothing written to s->window yet */
296 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
298 /* We overlay pending_buf and sym_buf. This works since the average size
299 * for length/distance pairs over any compressed block is assured to be 31
300 * bits or less.
302 * Analysis: The longest fixed codes are a length code of 8 bits plus 5
303 * extra bits, for lengths 131 to 257. The longest fixed distance codes are
304 * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest
305 * possible fixed-codes length/distance pair is then 31 bits total.
307 * sym_buf starts one-fourth of the way into pending_buf. So there are
308 * three bytes in sym_buf for every four bytes in pending_buf. Each symbol
309 * in sym_buf is three bytes -- two for the distance and one for the
310 * literal/length. As each symbol is consumed, the pointer to the next
311 * sym_buf value to read moves forward three bytes. From that symbol, up to
312 * 31 bits are written to pending_buf. The closest the written pending_buf
313 * bits gets to the next sym_buf symbol to read is just before the last
314 * code is written. At that time, 31*(n-2) bits have been written, just
315 * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at
316 * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1
317 * symbols are written.) The closest the writing gets to what is unread is
318 * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and
319 * can range from 128 to 32768.
321 * Therefore, at a minimum, there are 142 bits of space between what is
322 * written and what is read in the overlain buffers, so the symbols cannot
323 * be overwritten by the compressed data. That space is actually 139 bits,
324 * due to the three-bit fixed-code block header.
326 * That covers the case where either Z_FIXED is specified, forcing fixed
327 * codes, or when the use of fixed codes is chosen, because that choice
328 * results in a smaller compressed block than dynamic codes. That latter
329 * condition then assures that the above analysis also covers all dynamic
330 * blocks. A dynamic-code block will only be chosen to be emitted if it has
331 * fewer bits than a fixed-code block would for the same set of symbols.
332 * Therefore its average symbol length is assured to be less than 31. So
333 * the compressed data for a dynamic block also cannot overwrite the
334 * symbols from which it is being constructed.
337 s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, 4);
338 s->pending_buf_size = (ulg)s->lit_bufsize * 4;
340 if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
341 s->pending_buf == Z_NULL) {
342 s->status = FINISH_STATE;
343 strm->msg = ERR_MSG(Z_MEM_ERROR);
344 deflateEnd (strm);
345 return Z_MEM_ERROR;
347 s->sym_buf = s->pending_buf + s->lit_bufsize;
348 s->sym_end = (s->lit_bufsize - 1) * 3;
349 /* We avoid equality with lit_bufsize*3 because of wraparound at 64K
350 * on 16 bit machines and because stored blocks are restricted to
351 * 64K-1 bytes.
354 s->level = level;
355 s->strategy = strategy;
356 s->method = (Byte)method;
358 return deflateReset(strm);
361 /* ========================================================================= */
362 int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
363 z_streamp strm;
364 const Bytef *dictionary;
365 uInt dictLength;
367 deflate_state *s;
368 uInt str, n;
369 int wrap;
370 unsigned avail;
371 z_const unsigned char *next;
373 if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL)
374 return Z_STREAM_ERROR;
375 s = strm->state;
376 wrap = s->wrap;
377 if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
378 return Z_STREAM_ERROR;
380 /* when using zlib wrappers, compute Adler-32 for provided dictionary */
381 if (wrap == 1)
382 strm->adler = adler32(strm->adler, dictionary, dictLength);
383 s->wrap = 0; /* avoid computing Adler-32 in read_buf */
385 /* if dictionary would fill window, just replace the history */
386 if (dictLength >= s->w_size) {
387 if (wrap == 0) { /* already empty otherwise */
388 CLEAR_HASH(s);
389 s->strstart = 0;
390 s->block_start = 0L;
391 s->insert = 0;
393 dictionary += dictLength - s->w_size; /* use the tail */
394 dictLength = s->w_size;
397 /* insert dictionary into window and hash */
398 avail = strm->avail_in;
399 next = strm->next_in;
400 strm->avail_in = dictLength;
401 strm->next_in = (z_const Bytef *)dictionary;
402 fill_window(s);
403 while (s->lookahead >= MIN_MATCH) {
404 str = s->strstart;
405 n = s->lookahead - (MIN_MATCH-1);
406 do {
407 UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
408 #ifndef FASTEST
409 s->prev[str & s->w_mask] = s->head[s->ins_h];
410 #endif
411 s->head[s->ins_h] = (Pos)str;
412 str++;
413 } while (--n);
414 s->strstart = str;
415 s->lookahead = MIN_MATCH-1;
416 fill_window(s);
418 s->strstart += s->lookahead;
419 s->block_start = (long)s->strstart;
420 s->insert = s->lookahead;
421 s->lookahead = 0;
422 s->match_length = s->prev_length = MIN_MATCH-1;
423 s->match_available = 0;
424 strm->next_in = next;
425 strm->avail_in = avail;
426 s->wrap = wrap;
427 return Z_OK;
430 /* ========================================================================= */
431 int ZEXPORT deflateResetKeep (strm)
432 z_streamp strm;
434 deflate_state *s;
436 if (strm == Z_NULL || strm->state == Z_NULL ||
437 strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
438 return Z_STREAM_ERROR;
441 strm->total_in = strm->total_out = 0;
442 strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
443 strm->data_type = Z_UNKNOWN;
445 s = (deflate_state *)strm->state;
446 s->pending = 0;
447 s->pending_out = s->pending_buf;
449 if (s->wrap < 0) {
450 s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
452 s->status = s->wrap ? INIT_STATE : BUSY_STATE;
453 strm->adler =
454 #ifdef GZIP
455 s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
456 #endif
457 adler32(0L, Z_NULL, 0);
458 s->last_flush = Z_NO_FLUSH;
460 _tr_init(s);
462 return Z_OK;
465 /* ========================================================================= */
466 int ZEXPORT deflateReset (strm)
467 z_streamp strm;
469 int ret;
471 ret = deflateResetKeep(strm);
472 if (ret == Z_OK)
473 lm_init(strm->state);
474 return ret;
477 /* ========================================================================= */
478 int ZEXPORT deflateSetHeader (strm, head)
479 z_streamp strm;
480 gz_headerp head;
482 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
483 if (strm->state->wrap != 2) return Z_STREAM_ERROR;
484 strm->state->gzhead = head;
485 return Z_OK;
488 /* ========================================================================= */
489 int ZEXPORT deflatePending (strm, pending, bits)
490 unsigned *pending;
491 int *bits;
492 z_streamp strm;
494 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
495 if (pending != Z_NULL)
496 *pending = strm->state->pending;
497 if (bits != Z_NULL)
498 *bits = strm->state->bi_valid;
499 return Z_OK;
502 /* ========================================================================= */
503 int ZEXPORT deflatePrime (strm, bits, value)
504 z_streamp strm;
505 int bits;
506 int value;
508 deflate_state *s;
509 int put;
511 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
512 s = strm->state;
513 if (s->sym_buf < s->pending_out + ((Buf_size + 7) >> 3))
514 return Z_BUF_ERROR;
515 do {
516 put = Buf_size - s->bi_valid;
517 if (put > bits)
518 put = bits;
519 s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);
520 s->bi_valid += put;
521 _tr_flush_bits(s);
522 value >>= put;
523 bits -= put;
524 } while (bits);
525 return Z_OK;
528 /* ========================================================================= */
529 int ZEXPORT deflateParams(strm, level, strategy)
530 z_streamp strm;
531 int level;
532 int strategy;
534 deflate_state *s;
535 compress_func func;
536 int err = Z_OK;
538 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
539 s = strm->state;
541 #ifdef FASTEST
542 if (level != 0) level = 1;
543 #else
544 if (level == Z_DEFAULT_COMPRESSION) level = 6;
545 #endif
546 if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
547 return Z_STREAM_ERROR;
549 func = configuration_table[s->level].func;
551 if ((strategy != s->strategy || func != configuration_table[level].func) &&
552 strm->total_in != 0) {
553 /* Flush the last buffer: */
554 err = deflate(strm, Z_BLOCK);
555 if (err == Z_BUF_ERROR && s->pending == 0)
556 err = Z_OK;
558 if (s->level != level) {
559 s->level = level;
560 s->max_lazy_match = configuration_table[level].max_lazy;
561 s->good_match = configuration_table[level].good_length;
562 s->nice_match = configuration_table[level].nice_length;
563 s->max_chain_length = configuration_table[level].max_chain;
565 s->strategy = strategy;
566 return err;
569 /* ========================================================================= */
570 int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
571 z_streamp strm;
572 int good_length;
573 int max_lazy;
574 int nice_length;
575 int max_chain;
577 deflate_state *s;
579 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
580 s = strm->state;
581 s->good_match = good_length;
582 s->max_lazy_match = max_lazy;
583 s->nice_match = nice_length;
584 s->max_chain_length = max_chain;
585 return Z_OK;
588 /* =========================================================================
589 * For the default windowBits of 15 and memLevel of 8, this function returns
590 * a close to exact, as well as small, upper bound on the compressed size.
591 * They are coded as constants here for a reason--if the #define's are
592 * changed, then this function needs to be changed as well. The return
593 * value for 15 and 8 only works for those exact settings.
595 * For any setting other than those defaults for windowBits and memLevel,
596 * the value returned is a conservative worst case for the maximum expansion
597 * resulting from using fixed blocks instead of stored blocks, which deflate
598 * can emit on compressed data for some combinations of the parameters.
600 * This function could be more sophisticated to provide closer upper bounds for
601 * every combination of windowBits and memLevel. But even the conservative
602 * upper bound of about 14% expansion does not seem onerous for output buffer
603 * allocation.
605 uLong ZEXPORT deflateBound(strm, sourceLen)
606 z_streamp strm;
607 uLong sourceLen;
609 deflate_state *s;
610 uLong complen, wraplen;
611 Bytef *str;
613 /* conservative upper bound for compressed data */
614 complen = sourceLen +
615 ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
617 /* if can't get parameters, return conservative bound plus zlib wrapper */
618 if (strm == Z_NULL || strm->state == Z_NULL)
619 return complen + 6;
621 /* compute wrapper length */
622 s = strm->state;
623 switch (s->wrap) {
624 case 0: /* raw deflate */
625 wraplen = 0;
626 break;
627 case 1: /* zlib wrapper */
628 wraplen = 6 + (s->strstart ? 4 : 0);
629 break;
630 case 2: /* gzip wrapper */
631 wraplen = 18;
632 if (s->gzhead != Z_NULL) { /* user-supplied gzip header */
633 if (s->gzhead->extra != Z_NULL)
634 wraplen += 2 + s->gzhead->extra_len;
635 str = s->gzhead->name;
636 if (str != Z_NULL)
637 do {
638 wraplen++;
639 } while (*str++);
640 str = s->gzhead->comment;
641 if (str != Z_NULL)
642 do {
643 wraplen++;
644 } while (*str++);
645 if (s->gzhead->hcrc)
646 wraplen += 2;
648 break;
649 default: /* for compiler happiness */
650 wraplen = 6;
653 /* if not default parameters, return conservative bound */
654 if (s->w_bits != 15 || s->hash_bits != 8 + 7)
655 return complen + wraplen;
657 /* default settings: return tight bound for that case */
658 return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
659 (sourceLen >> 25) + 13 - 6 + wraplen;
662 /* =========================================================================
663 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
664 * IN assertion: the stream state is correct and there is enough room in
665 * pending_buf.
667 local void putShortMSB (s, b)
668 deflate_state *s;
669 uInt b;
671 put_byte(s, (Byte)(b >> 8));
672 put_byte(s, (Byte)(b & 0xff));
675 /* =========================================================================
676 * Flush as much pending output as possible. All deflate() output goes
677 * through this function so some applications may wish to modify it
678 * to avoid allocating a large strm->next_out buffer and copying into it.
679 * (See also read_buf()).
681 local void flush_pending(strm)
682 z_streamp strm;
684 unsigned len;
685 deflate_state *s = strm->state;
687 _tr_flush_bits(s);
688 len = s->pending;
689 if (len > strm->avail_out) len = strm->avail_out;
690 if (len == 0) return;
692 zmemcpy(strm->next_out, s->pending_out, len);
693 strm->next_out += len;
694 s->pending_out += len;
695 strm->total_out += len;
696 strm->avail_out -= len;
697 s->pending -= len;
698 if (s->pending == 0) {
699 s->pending_out = s->pending_buf;
703 /* ========================================================================= */
704 int ZEXPORT deflate (strm, flush)
705 z_streamp strm;
706 int flush;
708 int old_flush; /* value of flush param for previous deflate call */
709 deflate_state *s;
711 if (strm == Z_NULL || strm->state == Z_NULL ||
712 (flush > Z_BLOCK && flush != Z_INSERT_ONLY) || flush < 0) {
713 return Z_STREAM_ERROR;
715 s = strm->state;
717 if (strm->next_out == Z_NULL ||
718 (strm->next_in == Z_NULL && strm->avail_in != 0) ||
719 (s->status == FINISH_STATE && flush != Z_FINISH)) {
720 ERR_RETURN(strm, Z_STREAM_ERROR);
722 if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
724 s->strm = strm; /* just in case */
725 old_flush = s->last_flush;
726 s->last_flush = flush;
728 /* Write the header */
729 if (s->status == INIT_STATE) {
730 #ifdef GZIP
731 if (s->wrap == 2) {
732 strm->adler = crc32(0L, Z_NULL, 0);
733 put_byte(s, 31);
734 put_byte(s, 139);
735 put_byte(s, 8);
736 if (s->gzhead == Z_NULL) {
737 put_byte(s, 0);
738 put_byte(s, 0);
739 put_byte(s, 0);
740 put_byte(s, 0);
741 put_byte(s, 0);
742 put_byte(s, s->level == 9 ? 2 :
743 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
744 4 : 0));
745 put_byte(s, OS_CODE);
746 s->status = BUSY_STATE;
748 else {
749 put_byte(s, (s->gzhead->text ? 1 : 0) +
750 (s->gzhead->hcrc ? 2 : 0) +
751 (s->gzhead->extra == Z_NULL ? 0 : 4) +
752 (s->gzhead->name == Z_NULL ? 0 : 8) +
753 (s->gzhead->comment == Z_NULL ? 0 : 16)
755 put_byte(s, (Byte)(s->gzhead->time & 0xff));
756 put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
757 put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
758 put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
759 put_byte(s, s->level == 9 ? 2 :
760 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
761 4 : 0));
762 put_byte(s, s->gzhead->os & 0xff);
763 if (s->gzhead->extra != Z_NULL) {
764 put_byte(s, s->gzhead->extra_len & 0xff);
765 put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
767 if (s->gzhead->hcrc)
768 strm->adler = crc32(strm->adler, s->pending_buf,
769 s->pending);
770 s->gzindex = 0;
771 s->status = EXTRA_STATE;
774 else
775 #endif
777 uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
778 uInt level_flags;
780 if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
781 level_flags = 0;
782 else if (s->level < 6)
783 level_flags = 1;
784 else if (s->level == 6)
785 level_flags = 2;
786 else
787 level_flags = 3;
788 header |= (level_flags << 6);
789 if (s->strstart != 0) header |= PRESET_DICT;
790 header += 31 - (header % 31);
792 s->status = BUSY_STATE;
793 putShortMSB(s, header);
795 /* Save the adler32 of the preset dictionary: */
796 if (s->strstart != 0) {
797 putShortMSB(s, (uInt)(strm->adler >> 16));
798 putShortMSB(s, (uInt)(strm->adler & 0xffff));
800 strm->adler = adler32(0L, Z_NULL, 0);
803 #ifdef GZIP
804 if (s->status == EXTRA_STATE) {
805 if (s->gzhead->extra != Z_NULL) {
806 uInt beg = s->pending; /* start of bytes to update crc */
808 while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
809 if (s->pending == s->pending_buf_size) {
810 if (s->gzhead->hcrc && s->pending > beg)
811 strm->adler = crc32(strm->adler, s->pending_buf + beg,
812 s->pending - beg);
813 flush_pending(strm);
814 beg = s->pending;
815 if (s->pending == s->pending_buf_size)
816 break;
818 put_byte(s, s->gzhead->extra[s->gzindex]);
819 s->gzindex++;
821 if (s->gzhead->hcrc && s->pending > beg)
822 strm->adler = crc32(strm->adler, s->pending_buf + beg,
823 s->pending - beg);
824 if (s->gzindex == s->gzhead->extra_len) {
825 s->gzindex = 0;
826 s->status = NAME_STATE;
829 else
830 s->status = NAME_STATE;
832 if (s->status == NAME_STATE) {
833 if (s->gzhead->name != Z_NULL) {
834 uInt beg = s->pending; /* start of bytes to update crc */
835 int val;
837 do {
838 if (s->pending == s->pending_buf_size) {
839 if (s->gzhead->hcrc && s->pending > beg)
840 strm->adler = crc32(strm->adler, s->pending_buf + beg,
841 s->pending - beg);
842 flush_pending(strm);
843 beg = s->pending;
844 if (s->pending == s->pending_buf_size) {
845 val = 1;
846 break;
849 val = s->gzhead->name[s->gzindex++];
850 put_byte(s, val);
851 } while (val != 0);
852 if (s->gzhead->hcrc && s->pending > beg)
853 strm->adler = crc32(strm->adler, s->pending_buf + beg,
854 s->pending - beg);
855 if (val == 0) {
856 s->gzindex = 0;
857 s->status = COMMENT_STATE;
860 else
861 s->status = COMMENT_STATE;
863 if (s->status == COMMENT_STATE) {
864 if (s->gzhead->comment != Z_NULL) {
865 uInt beg = s->pending; /* start of bytes to update crc */
866 int val;
868 do {
869 if (s->pending == s->pending_buf_size) {
870 if (s->gzhead->hcrc && s->pending > beg)
871 strm->adler = crc32(strm->adler, s->pending_buf + beg,
872 s->pending - beg);
873 flush_pending(strm);
874 beg = s->pending;
875 if (s->pending == s->pending_buf_size) {
876 val = 1;
877 break;
880 val = s->gzhead->comment[s->gzindex++];
881 put_byte(s, val);
882 } while (val != 0);
883 if (s->gzhead->hcrc && s->pending > beg)
884 strm->adler = crc32(strm->adler, s->pending_buf + beg,
885 s->pending - beg);
886 if (val == 0)
887 s->status = HCRC_STATE;
889 else
890 s->status = HCRC_STATE;
892 if (s->status == HCRC_STATE) {
893 if (s->gzhead->hcrc) {
894 if (s->pending + 2 > s->pending_buf_size)
895 flush_pending(strm);
896 if (s->pending + 2 <= s->pending_buf_size) {
897 put_byte(s, (Byte)(strm->adler & 0xff));
898 put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
899 strm->adler = crc32(0L, Z_NULL, 0);
900 s->status = BUSY_STATE;
903 else
904 s->status = BUSY_STATE;
906 #endif
908 /* Flush as much pending output as possible */
909 if (s->pending != 0) {
910 flush_pending(strm);
911 if (strm->avail_out == 0) {
912 /* Since avail_out is 0, deflate will be called again with
913 * more output space, but possibly with both pending and
914 * avail_in equal to zero. There won't be anything to do,
915 * but this is not an error situation so make sure we
916 * return OK instead of BUF_ERROR at next call of deflate:
918 s->last_flush = -1;
919 return Z_OK;
922 /* Make sure there is something to do and avoid duplicate consecutive
923 * flushes. For repeated and useless calls with Z_FINISH, we keep
924 * returning Z_STREAM_END instead of Z_BUF_ERROR.
926 } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&
927 flush != Z_FINISH) {
928 ERR_RETURN(strm, Z_BUF_ERROR);
931 /* User must not provide more input after the first FINISH: */
932 if (s->status == FINISH_STATE && strm->avail_in != 0) {
933 ERR_RETURN(strm, Z_BUF_ERROR);
936 /* Start a new block or continue the current one.
938 if (strm->avail_in != 0 || s->lookahead != 0 ||
939 (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
940 block_state bstate;
942 bstate = s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
943 (s->strategy == Z_RLE ? deflate_rle(s, flush) :
944 (*(configuration_table[s->level].func))(s, flush));
946 if (bstate == finish_started || bstate == finish_done) {
947 s->status = FINISH_STATE;
949 if (bstate == need_more || bstate == finish_started) {
950 if (strm->avail_out == 0) {
951 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
953 return Z_OK;
954 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
955 * of deflate should use the same flush parameter to make sure
956 * that the flush is complete. So we don't have to output an
957 * empty block here, this will be done at next call. This also
958 * ensures that for a very small output buffer, we emit at most
959 * one empty block.
962 if (bstate == block_done) {
963 if (flush == Z_PARTIAL_FLUSH) {
964 _tr_align(s);
965 } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
966 _tr_stored_block(s, (char*)0, 0L, 0);
967 /* For a full flush, this empty block will be recognized
968 * as a special marker by inflate_sync().
970 if (flush == Z_FULL_FLUSH) {
971 CLEAR_HASH(s); /* forget history */
972 if (s->lookahead == 0) {
973 s->strstart = 0;
974 s->block_start = 0L;
975 s->insert = 0;
979 flush_pending(strm);
980 if (strm->avail_out == 0) {
981 s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
982 return Z_OK;
986 Assert(strm->avail_out > 0, "bug2");
988 if (flush != Z_FINISH) return Z_OK;
989 if (s->wrap <= 0) return Z_STREAM_END;
991 /* Write the trailer */
992 #ifdef GZIP
993 if (s->wrap == 2) {
994 put_byte(s, (Byte)(strm->adler & 0xff));
995 put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
996 put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
997 put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
998 put_byte(s, (Byte)(strm->total_in & 0xff));
999 put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
1000 put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
1001 put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
1003 else
1004 #endif
1006 putShortMSB(s, (uInt)(strm->adler >> 16));
1007 putShortMSB(s, (uInt)(strm->adler & 0xffff));
1009 flush_pending(strm);
1010 /* If avail_out is zero, the application will call deflate again
1011 * to flush the rest.
1013 if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
1014 return s->pending != 0 ? Z_OK : Z_STREAM_END;
1017 /* ========================================================================= */
1018 int ZEXPORT deflateEnd (strm)
1019 z_streamp strm;
1021 int status;
1023 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
1025 status = strm->state->status;
1026 if (status != INIT_STATE &&
1027 status != EXTRA_STATE &&
1028 status != NAME_STATE &&
1029 status != COMMENT_STATE &&
1030 status != HCRC_STATE &&
1031 status != BUSY_STATE &&
1032 status != FINISH_STATE) {
1033 return Z_STREAM_ERROR;
1036 /* Deallocate in reverse order of allocations: */
1037 TRY_FREE(strm, strm->state->pending_buf);
1038 TRY_FREE(strm, strm->state->head);
1039 TRY_FREE(strm, strm->state->prev);
1040 TRY_FREE(strm, strm->state->window);
1042 ZFREE(strm, strm->state);
1043 strm->state = Z_NULL;
1045 return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
1048 /* =========================================================================
1049 * Copy the source state to the destination state.
1050 * To simplify the source, this is not supported for 16-bit MSDOS (which
1051 * doesn't have enough memory anyway to duplicate compression states).
1053 int ZEXPORT deflateCopy (dest, source)
1054 z_streamp dest;
1055 z_streamp source;
1057 #ifdef MAXSEG_64K
1058 return Z_STREAM_ERROR;
1059 #else
1060 deflate_state *ds;
1061 deflate_state *ss;
1064 if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
1065 return Z_STREAM_ERROR;
1068 ss = source->state;
1070 zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
1072 ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
1073 if (ds == Z_NULL) return Z_MEM_ERROR;
1074 dest->state = (struct internal_state FAR *) ds;
1075 zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));
1076 ds->strm = dest;
1078 ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
1079 ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
1080 ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
1081 ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, 4);
1083 if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
1084 ds->pending_buf == Z_NULL) {
1085 deflateEnd (dest);
1086 return Z_MEM_ERROR;
1088 /* following zmemcpy do not work for 16-bit MSDOS */
1089 zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
1090 zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));
1091 zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));
1092 zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
1094 ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
1095 ds->sym_buf = ds->pending_buf + ds->lit_bufsize;
1097 ds->l_desc.dyn_tree = ds->dyn_ltree;
1098 ds->d_desc.dyn_tree = ds->dyn_dtree;
1099 ds->bl_desc.dyn_tree = ds->bl_tree;
1101 return Z_OK;
1102 #endif /* MAXSEG_64K */
1105 /* ===========================================================================
1106 * Read a new buffer from the current input stream, update the adler32
1107 * and total number of bytes read. All deflate() input goes through
1108 * this function so some applications may wish to modify it to avoid
1109 * allocating a large strm->next_in buffer and copying from it.
1110 * (See also flush_pending()).
1112 local int read_buf(strm, buf, size)
1113 z_streamp strm;
1114 Bytef *buf;
1115 unsigned size;
1117 unsigned len = strm->avail_in;
1119 if (len > size) len = size;
1120 if (len == 0) return 0;
1122 strm->avail_in -= len;
1124 zmemcpy(buf, strm->next_in, len);
1125 if (strm->state->wrap == 1) {
1126 strm->adler = adler32(strm->adler, buf, len);
1128 #ifdef GZIP
1129 else if (strm->state->wrap == 2) {
1130 strm->adler = crc32(strm->adler, buf, len);
1132 #endif
1133 strm->next_in += len;
1134 strm->total_in += len;
1136 return (int)len;
1139 /* ===========================================================================
1140 * Initialize the "longest match" routines for a new zlib stream
1142 local void lm_init (s)
1143 deflate_state *s;
1145 s->window_size = (ulg)2L*s->w_size;
1147 CLEAR_HASH(s);
1149 /* Set the default configuration parameters:
1151 s->max_lazy_match = configuration_table[s->level].max_lazy;
1152 s->good_match = configuration_table[s->level].good_length;
1153 s->nice_match = configuration_table[s->level].nice_length;
1154 s->max_chain_length = configuration_table[s->level].max_chain;
1156 s->strstart = 0;
1157 s->block_start = 0L;
1158 s->lookahead = 0;
1159 s->insert = 0;
1160 s->match_length = s->prev_length = MIN_MATCH-1;
1161 s->match_available = 0;
1162 s->ins_h = 0;
1163 #ifndef FASTEST
1164 #ifdef ASMV
1165 match_init(); /* initialize the asm code */
1166 #endif
1167 #endif
1170 #ifndef FASTEST
1171 /* ===========================================================================
1172 * Set match_start to the longest match starting at the given string and
1173 * return its length. Matches shorter or equal to prev_length are discarded,
1174 * in which case the result is equal to prev_length and match_start is
1175 * garbage.
1176 * IN assertions: cur_match is the head of the hash chain for the current
1177 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1178 * OUT assertion: the match length is not greater than s->lookahead.
1180 #ifndef ASMV
1181 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
1182 * match.S. The code will be functionally equivalent.
1184 local uInt longest_match(s, cur_match)
1185 deflate_state *s;
1186 IPos cur_match; /* current match */
1188 unsigned chain_length = s->max_chain_length;/* max hash chain length */
1189 register Bytef *scan = s->window + s->strstart; /* current string */
1190 register Bytef *match; /* matched string */
1191 register int len; /* length of current match */
1192 int best_len = s->prev_length; /* best match length so far */
1193 int nice_match = s->nice_match; /* stop if match long enough */
1194 IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
1195 s->strstart - (IPos)MAX_DIST(s) : NIL;
1196 /* Stop when cur_match becomes <= limit. To simplify the code,
1197 * we prevent matches with the string of window index 0.
1199 Posf *prev = s->prev;
1200 uInt wmask = s->w_mask;
1202 #ifdef UNALIGNED_OK
1203 /* Compare two bytes at a time. Note: this is not always beneficial.
1204 * Try with and without -DUNALIGNED_OK to check.
1206 register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
1207 register ush scan_start = *(ushf*)scan;
1208 register ush scan_end = *(ushf*)(scan+best_len-1);
1209 #else
1210 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1211 register Byte scan_end1 = scan[best_len-1];
1212 register Byte scan_end = scan[best_len];
1213 #endif
1215 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1216 * It is easy to get rid of this optimization if necessary.
1218 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1220 /* Do not waste too much time if we already have a good match: */
1221 if (s->prev_length >= s->good_match) {
1222 chain_length >>= 2;
1224 /* Do not look for matches beyond the end of the input. This is necessary
1225 * to make deflate deterministic.
1227 if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
1229 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1231 do {
1232 Assert(cur_match < s->strstart, "no future");
1233 match = s->window + cur_match;
1235 /* Skip to next match if the match length cannot increase
1236 * or if the match length is less than 2. Note that the checks below
1237 * for insufficient lookahead only occur occasionally for performance
1238 * reasons. Therefore uninitialized memory will be accessed, and
1239 * conditional jumps will be made that depend on those values.
1240 * However the length of the match is limited to the lookahead, so
1241 * the output of deflate is not affected by the uninitialized values.
1243 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
1244 /* This code assumes sizeof(unsigned short) == 2. Do not use
1245 * UNALIGNED_OK if your compiler uses a different size.
1247 if (*(ushf*)(match+best_len-1) != scan_end ||
1248 *(ushf*)match != scan_start) continue;
1250 /* It is not necessary to compare scan[2] and match[2] since they are
1251 * always equal when the other bytes match, given that the hash keys
1252 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
1253 * strstart+3, +5, ... up to strstart+257. We check for insufficient
1254 * lookahead only every 4th comparison; the 128th check will be made
1255 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
1256 * necessary to put more guard bytes at the end of the window, or
1257 * to check more often for insufficient lookahead.
1259 Assert(scan[2] == match[2], "scan[2]?");
1260 scan++, match++;
1261 do {
1262 } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1263 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1264 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1265 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1266 scan < strend);
1267 /* The funny "do {}" generates better code on most compilers */
1269 /* Here, scan <= window+strstart+257 */
1270 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1271 if (*scan == *match) scan++;
1273 len = (MAX_MATCH - 1) - (int)(strend-scan);
1274 scan = strend - (MAX_MATCH-1);
1276 #else /* UNALIGNED_OK */
1278 if (match[best_len] != scan_end ||
1279 match[best_len-1] != scan_end1 ||
1280 *match != *scan ||
1281 *++match != scan[1]) continue;
1283 /* The check at best_len-1 can be removed because it will be made
1284 * again later. (This heuristic is not always a win.)
1285 * It is not necessary to compare scan[2] and match[2] since they
1286 * are always equal when the other bytes match, given that
1287 * the hash keys are equal and that HASH_BITS >= 8.
1289 scan += 2, match++;
1290 Assert(*scan == *match, "match[2]?");
1292 /* We check for insufficient lookahead only every 8th comparison;
1293 * the 256th check will be made at strstart+258.
1295 do {
1296 } while (*++scan == *++match && *++scan == *++match &&
1297 *++scan == *++match && *++scan == *++match &&
1298 *++scan == *++match && *++scan == *++match &&
1299 *++scan == *++match && *++scan == *++match &&
1300 scan < strend);
1302 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1304 len = MAX_MATCH - (int)(strend - scan);
1305 scan = strend - MAX_MATCH;
1307 #endif /* UNALIGNED_OK */
1309 if (len > best_len) {
1310 s->match_start = cur_match;
1311 best_len = len;
1312 if (len >= nice_match) break;
1313 #ifdef UNALIGNED_OK
1314 scan_end = *(ushf*)(scan+best_len-1);
1315 #else
1316 scan_end1 = scan[best_len-1];
1317 scan_end = scan[best_len];
1318 #endif
1320 } while ((cur_match = prev[cur_match & wmask]) > limit
1321 && --chain_length != 0);
1323 if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
1324 return s->lookahead;
1326 #endif /* ASMV */
1328 #else /* FASTEST */
1330 /* ---------------------------------------------------------------------------
1331 * Optimized version for FASTEST only
1333 local uInt longest_match(s, cur_match)
1334 deflate_state *s;
1335 IPos cur_match; /* current match */
1337 register Bytef *scan = s->window + s->strstart; /* current string */
1338 register Bytef *match; /* matched string */
1339 register int len; /* length of current match */
1340 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1342 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1343 * It is easy to get rid of this optimization if necessary.
1345 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1347 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1349 Assert(cur_match < s->strstart, "no future");
1351 match = s->window + cur_match;
1353 /* Return failure if the match length is less than 2:
1355 if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
1357 /* The check at best_len-1 can be removed because it will be made
1358 * again later. (This heuristic is not always a win.)
1359 * It is not necessary to compare scan[2] and match[2] since they
1360 * are always equal when the other bytes match, given that
1361 * the hash keys are equal and that HASH_BITS >= 8.
1363 scan += 2, match += 2;
1364 Assert(*scan == *match, "match[2]?");
1366 /* We check for insufficient lookahead only every 8th comparison;
1367 * the 256th check will be made at strstart+258.
1369 do {
1370 } while (*++scan == *++match && *++scan == *++match &&
1371 *++scan == *++match && *++scan == *++match &&
1372 *++scan == *++match && *++scan == *++match &&
1373 *++scan == *++match && *++scan == *++match &&
1374 scan < strend);
1376 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1378 len = MAX_MATCH - (int)(strend - scan);
1380 if (len < MIN_MATCH) return MIN_MATCH - 1;
1382 s->match_start = cur_match;
1383 return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
1386 #endif /* FASTEST */
1388 #ifdef DEBUG
1389 /* ===========================================================================
1390 * Check that the match at match_start is indeed a match.
1392 local void check_match(s, start, match, length)
1393 deflate_state *s;
1394 IPos start, match;
1395 int length;
1397 /* check that the match is indeed a match */
1398 if (zmemcmp(s->window + match,
1399 s->window + start, length) != EQUAL) {
1400 fprintf(stderr, " start %u, match %u, length %d\n",
1401 start, match, length);
1402 do {
1403 fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
1404 } while (--length != 0);
1405 z_error("invalid match");
1407 if (z_verbose > 1) {
1408 fprintf(stderr,"\\[%d,%d]", start-match, length);
1409 do { putc(s->window[start++], stderr); } while (--length != 0);
1412 #else
1413 # define check_match(s, start, match, length)
1414 #endif /* DEBUG */
1416 /* ===========================================================================
1417 * Fill the window when the lookahead becomes insufficient.
1418 * Updates strstart and lookahead.
1420 * IN assertion: lookahead < MIN_LOOKAHEAD
1421 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1422 * At least one byte has been read, or avail_in == 0; reads are
1423 * performed for at least two bytes (required for the zip translate_eol
1424 * option -- not supported here).
1426 local void fill_window(s)
1427 deflate_state *s;
1429 register unsigned n, m;
1430 register Posf *p;
1431 unsigned more; /* Amount of free space at the end of the window. */
1432 uInt wsize = s->w_size;
1434 Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
1436 do {
1437 more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
1439 /* Deal with !@#$% 64K limit: */
1440 if (sizeof(int) <= 2) {
1441 if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1442 more = wsize;
1444 } else if (more == (unsigned)(-1)) {
1445 /* Very unlikely, but possible on 16 bit machine if
1446 * strstart == 0 && lookahead == 1 (input done a byte at time)
1448 more--;
1452 /* If the window is almost full and there is insufficient lookahead,
1453 * move the upper half to the lower one to make room in the upper half.
1455 if (s->strstart >= wsize+MAX_DIST(s)) {
1457 zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
1458 s->match_start -= wsize;
1459 s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
1460 s->block_start -= (long) wsize;
1462 /* Slide the hash table (could be avoided with 32 bit values
1463 at the expense of memory usage). We slide even when level == 0
1464 to keep the hash table consistent if we switch back to level > 0
1465 later. (Using level 0 permanently is not an optimal usage of
1466 zlib, so we don't care about this pathological case.)
1468 n = s->hash_size;
1469 p = &s->head[n];
1470 do {
1471 m = *--p;
1472 *p = (Pos)(m >= wsize ? m-wsize : NIL);
1473 } while (--n);
1475 n = wsize;
1476 #ifndef FASTEST
1477 p = &s->prev[n];
1478 do {
1479 m = *--p;
1480 *p = (Pos)(m >= wsize ? m-wsize : NIL);
1481 /* If n is not on any hash chain, prev[n] is garbage but
1482 * its value will never be used.
1484 } while (--n);
1485 #endif
1486 more += wsize;
1488 if (s->strm->avail_in == 0) break;
1490 /* If there was no sliding:
1491 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1492 * more == window_size - lookahead - strstart
1493 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1494 * => more >= window_size - 2*WSIZE + 2
1495 * In the BIG_MEM or MMAP case (not yet supported),
1496 * window_size == input_size + MIN_LOOKAHEAD &&
1497 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1498 * Otherwise, window_size == 2*WSIZE so more >= 2.
1499 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1501 Assert(more >= 2, "more < 2");
1503 n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1504 s->lookahead += n;
1506 /* Initialize the hash value now that we have some input: */
1507 if (s->lookahead + s->insert >= MIN_MATCH) {
1508 uInt str = s->strstart - s->insert;
1509 s->ins_h = s->window[str];
1510 UPDATE_HASH(s, s->ins_h, s->window[str + 1]);
1511 #if MIN_MATCH != 3
1512 Call UPDATE_HASH() MIN_MATCH-3 more times
1513 #endif
1514 while (s->insert) {
1515 UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
1516 #ifndef FASTEST
1517 s->prev[str & s->w_mask] = s->head[s->ins_h];
1518 #endif
1519 s->head[s->ins_h] = (Pos)str;
1520 str++;
1521 s->insert--;
1522 if (s->lookahead + s->insert < MIN_MATCH)
1523 break;
1526 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1527 * but this is not important since only literal bytes will be emitted.
1530 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1532 /* If the WIN_INIT bytes after the end of the current data have never been
1533 * written, then zero those bytes in order to avoid memory check reports of
1534 * the use of uninitialized (or uninitialised as Julian writes) bytes by
1535 * the longest match routines. Update the high water mark for the next
1536 * time through here. WIN_INIT is set to MAX_MATCH since the longest match
1537 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
1539 if (s->high_water < s->window_size) {
1540 ulg curr = s->strstart + (ulg)(s->lookahead);
1541 ulg init;
1543 if (s->high_water < curr) {
1544 /* Previous high water mark below current data -- zero WIN_INIT
1545 * bytes or up to end of window, whichever is less.
1547 init = s->window_size - curr;
1548 if (init > WIN_INIT)
1549 init = WIN_INIT;
1550 zmemzero(s->window + curr, (unsigned)init);
1551 s->high_water = curr + init;
1553 else if (s->high_water < (ulg)curr + WIN_INIT) {
1554 /* High water mark at or above current data, but below current data
1555 * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
1556 * to end of window, whichever is less.
1558 init = (ulg)curr + WIN_INIT - s->high_water;
1559 if (init > s->window_size - s->high_water)
1560 init = s->window_size - s->high_water;
1561 zmemzero(s->window + s->high_water, (unsigned)init);
1562 s->high_water += init;
1566 Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1567 "not enough room for search");
1570 /* ===========================================================================
1571 * Flush the current block, with given end-of-file flag.
1572 * IN assertion: strstart is set to the end of the current match.
1574 #define FLUSH_BLOCK_ONLY(s, last) { \
1575 _tr_flush_block(s, (s->block_start >= 0L ? \
1576 (charf *)&s->window[(unsigned)s->block_start] : \
1577 (charf *)Z_NULL), \
1578 (ulg)((long)s->strstart - s->block_start), \
1579 (last)); \
1580 s->block_start = s->strstart; \
1581 flush_pending(s->strm); \
1582 Tracev((stderr,"[FLUSH]")); \
1585 /* Same but force premature exit if necessary. */
1586 #define FLUSH_BLOCK(s, last) { \
1587 FLUSH_BLOCK_ONLY(s, last); \
1588 if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
1591 /* ===========================================================================
1592 * Copy without compression as much as possible from the input stream, return
1593 * the current block state.
1594 * This function does not insert new strings in the dictionary since
1595 * uncompressible data is probably not useful. This function is used
1596 * only for the level=0 compression option.
1597 * NOTE: this function should be optimized to avoid extra copying from
1598 * window to pending_buf.
1600 local block_state deflate_stored(s, flush)
1601 deflate_state *s;
1602 int flush;
1604 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
1605 * to pending_buf_size, and each stored block has a 5 byte header:
1607 ulg max_block_size = 0xffff;
1608 ulg max_start;
1610 if (max_block_size > s->pending_buf_size - 5) {
1611 max_block_size = s->pending_buf_size - 5;
1614 /* Copy as much as possible from input to output: */
1615 for (;;) {
1616 /* Fill the window as much as possible: */
1617 if (s->lookahead <= 1) {
1619 Assert(s->strstart < s->w_size+MAX_DIST(s) ||
1620 s->block_start >= (long)s->w_size, "slide too late");
1622 fill_window(s);
1623 if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
1625 if (s->lookahead == 0) break; /* flush the current block */
1627 Assert(s->block_start >= 0L, "block gone");
1629 s->strstart += s->lookahead;
1630 s->lookahead = 0;
1632 if (flush == Z_INSERT_ONLY) {
1633 s->block_start = s->strstart;
1634 continue;
1637 /* Emit a stored block if pending_buf will be full: */
1638 max_start = s->block_start + max_block_size;
1639 if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
1640 /* strstart == 0 is possible when wraparound on 16-bit machine */
1641 s->lookahead = (uInt)(s->strstart - max_start);
1642 s->strstart = (uInt)max_start;
1643 FLUSH_BLOCK(s, 0);
1645 /* Flush if we may have to slide, otherwise block_start may become
1646 * negative and the data will be gone:
1648 if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
1649 FLUSH_BLOCK(s, 0);
1652 s->insert = 0;
1653 if (flush == Z_INSERT_ONLY) {
1654 s->block_start = s->strstart;
1655 return need_more;
1657 if (flush == Z_FINISH) {
1658 FLUSH_BLOCK(s, 1);
1659 return finish_done;
1661 if ((long)s->strstart > s->block_start)
1662 FLUSH_BLOCK(s, 0);
1663 return block_done;
1666 /* ===========================================================================
1667 * Compress as much as possible from the input stream, return the current
1668 * block state.
1669 * This function does not perform lazy evaluation of matches and inserts
1670 * new strings in the dictionary only for unmatched strings or for short
1671 * matches. It is used only for the fast compression options.
1673 local block_state deflate_fast(s, flush)
1674 deflate_state *s;
1675 int flush;
1677 IPos hash_head; /* head of the hash chain */
1678 int bflush; /* set if current block must be flushed */
1680 for (;;) {
1681 /* Make sure that we always have enough lookahead, except
1682 * at the end of the input file. We need MAX_MATCH bytes
1683 * for the next match, plus MIN_MATCH bytes to insert the
1684 * string following the next match.
1686 if (s->lookahead < MIN_LOOKAHEAD) {
1687 fill_window(s);
1688 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1689 return need_more;
1691 if (s->lookahead == 0) break; /* flush the current block */
1694 /* Insert the string window[strstart .. strstart+2] in the
1695 * dictionary, and set hash_head to the head of the hash chain:
1697 hash_head = NIL;
1698 if (s->lookahead >= MIN_MATCH) {
1699 INSERT_STRING(s, s->strstart, hash_head);
1702 if (flush == Z_INSERT_ONLY) {
1703 s->strstart++;
1704 s->lookahead--;
1705 continue;
1708 /* Find the longest match, discarding those <= prev_length.
1709 * At this point we have always match_length < MIN_MATCH
1711 if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1712 /* To simplify the code, we prevent matches with the string
1713 * of window index 0 (in particular we have to avoid a match
1714 * of the string with itself at the start of the input file).
1716 s->match_length = longest_match (s, hash_head);
1717 /* longest_match() sets match_start */
1719 if (s->match_length >= MIN_MATCH) {
1720 check_match(s, s->strstart, s->match_start, s->match_length);
1722 _tr_tally_dist(s, s->strstart - s->match_start,
1723 s->match_length - MIN_MATCH, bflush);
1725 s->lookahead -= s->match_length;
1727 /* Insert new strings in the hash table only if the match length
1728 * is not too large. This saves time but degrades compression.
1730 #ifndef FASTEST
1731 if (s->match_length <= s->max_insert_length &&
1732 s->lookahead >= MIN_MATCH) {
1733 s->match_length--; /* string at strstart already in table */
1734 do {
1735 s->strstart++;
1736 INSERT_STRING(s, s->strstart, hash_head);
1737 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1738 * always MIN_MATCH bytes ahead.
1740 } while (--s->match_length != 0);
1741 s->strstart++;
1742 } else
1743 #endif
1745 s->strstart += s->match_length;
1746 s->match_length = 0;
1747 s->ins_h = s->window[s->strstart];
1748 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1749 #if MIN_MATCH != 3
1750 Call UPDATE_HASH() MIN_MATCH-3 more times
1751 #endif
1752 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1753 * matter since it will be recomputed at next deflate call.
1756 } else {
1757 /* No match, output a literal byte */
1758 Tracevv((stderr,"%c", s->window[s->strstart]));
1759 _tr_tally_lit (s, s->window[s->strstart], bflush);
1760 s->lookahead--;
1761 s->strstart++;
1763 if (bflush) FLUSH_BLOCK(s, 0);
1765 if (flush == Z_INSERT_ONLY) {
1766 s->block_start = s->strstart;
1767 return need_more;
1769 s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
1770 if (flush == Z_FINISH) {
1771 FLUSH_BLOCK(s, 1);
1772 return finish_done;
1774 if (s->sym_next)
1775 FLUSH_BLOCK(s, 0);
1776 return block_done;
1779 #ifndef FASTEST
1780 /* ===========================================================================
1781 * Same as above, but achieves better compression. We use a lazy
1782 * evaluation for matches: a match is finally adopted only if there is
1783 * no better match at the next window position.
1785 local block_state deflate_slow(s, flush)
1786 deflate_state *s;
1787 int flush;
1789 IPos hash_head; /* head of hash chain */
1790 int bflush; /* set if current block must be flushed */
1792 /* Process the input block. */
1793 for (;;) {
1794 /* Make sure that we always have enough lookahead, except
1795 * at the end of the input file. We need MAX_MATCH bytes
1796 * for the next match, plus MIN_MATCH bytes to insert the
1797 * string following the next match.
1799 if (s->lookahead < MIN_LOOKAHEAD) {
1800 fill_window(s);
1801 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1802 return need_more;
1804 if (s->lookahead == 0) break; /* flush the current block */
1807 /* Insert the string window[strstart .. strstart+2] in the
1808 * dictionary, and set hash_head to the head of the hash chain:
1810 hash_head = NIL;
1811 if (s->lookahead >= MIN_MATCH) {
1812 INSERT_STRING(s, s->strstart, hash_head);
1815 if (flush == Z_INSERT_ONLY) {
1816 s->strstart++;
1817 s->lookahead--;
1818 continue;
1821 /* Find the longest match, discarding those <= prev_length.
1823 s->prev_length = s->match_length, s->prev_match = s->match_start;
1824 s->match_length = MIN_MATCH-1;
1826 if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
1827 s->strstart - hash_head <= MAX_DIST(s)) {
1828 /* To simplify the code, we prevent matches with the string
1829 * of window index 0 (in particular we have to avoid a match
1830 * of the string with itself at the start of the input file).
1832 s->match_length = longest_match (s, hash_head);
1833 /* longest_match() sets match_start */
1835 if (s->match_length <= 5 && (s->strategy == Z_FILTERED
1836 #if TOO_FAR <= 32767
1837 || (s->match_length == MIN_MATCH &&
1838 s->strstart - s->match_start > TOO_FAR)
1839 #endif
1840 )) {
1842 /* If prev_match is also MIN_MATCH, match_start is garbage
1843 * but we will ignore the current match anyway.
1845 s->match_length = MIN_MATCH-1;
1848 /* If there was a match at the previous step and the current
1849 * match is not better, output the previous match:
1851 if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
1852 uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
1853 /* Do not insert strings in hash table beyond this. */
1855 check_match(s, s->strstart-1, s->prev_match, s->prev_length);
1857 _tr_tally_dist(s, s->strstart -1 - s->prev_match,
1858 s->prev_length - MIN_MATCH, bflush);
1860 /* Insert in hash table all strings up to the end of the match.
1861 * strstart-1 and strstart are already inserted. If there is not
1862 * enough lookahead, the last two strings are not inserted in
1863 * the hash table.
1865 s->lookahead -= s->prev_length-1;
1866 s->prev_length -= 2;
1867 do {
1868 if (++s->strstart <= max_insert) {
1869 INSERT_STRING(s, s->strstart, hash_head);
1871 } while (--s->prev_length != 0);
1872 s->match_available = 0;
1873 s->match_length = MIN_MATCH-1;
1874 s->strstart++;
1876 if (bflush) FLUSH_BLOCK(s, 0);
1878 } else if (s->match_available) {
1879 /* If there was no match at the previous position, output a
1880 * single literal. If there was a match but the current match
1881 * is longer, truncate the previous match to a single literal.
1883 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1884 _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1885 if (bflush) {
1886 FLUSH_BLOCK_ONLY(s, 0);
1888 s->strstart++;
1889 s->lookahead--;
1890 if (s->strm->avail_out == 0) return need_more;
1891 } else {
1892 /* There is no previous match to compare with, wait for
1893 * the next step to decide.
1895 s->match_available = 1;
1896 s->strstart++;
1897 s->lookahead--;
1900 if (flush == Z_INSERT_ONLY) {
1901 s->block_start = s->strstart;
1902 return need_more;
1904 Assert (flush != Z_NO_FLUSH, "no flush?");
1905 if (s->match_available) {
1906 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1907 _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1908 s->match_available = 0;
1910 s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
1911 if (flush == Z_FINISH) {
1912 FLUSH_BLOCK(s, 1);
1913 return finish_done;
1915 if (s->sym_next)
1916 FLUSH_BLOCK(s, 0);
1917 return block_done;
1919 #endif /* FASTEST */
1921 /* ===========================================================================
1922 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
1923 * one. Do not maintain a hash table. (It will be regenerated if this run of
1924 * deflate switches away from Z_RLE.)
1926 local block_state deflate_rle(s, flush)
1927 deflate_state *s;
1928 int flush;
1930 int bflush; /* set if current block must be flushed */
1931 uInt prev; /* byte at distance one to match */
1932 Bytef *scan, *strend; /* scan goes up to strend for length of run */
1934 for (;;) {
1935 /* Make sure that we always have enough lookahead, except
1936 * at the end of the input file. We need MAX_MATCH bytes
1937 * for the longest run, plus one for the unrolled loop.
1939 if (s->lookahead <= MAX_MATCH) {
1940 fill_window(s);
1941 if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {
1942 return need_more;
1944 if (s->lookahead == 0) break; /* flush the current block */
1947 /* See how many times the previous byte repeats */
1948 s->match_length = 0;
1949 if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
1950 scan = s->window + s->strstart - 1;
1951 prev = *scan;
1952 if (prev == *++scan && prev == *++scan && prev == *++scan) {
1953 strend = s->window + s->strstart + MAX_MATCH;
1954 do {
1955 } while (prev == *++scan && prev == *++scan &&
1956 prev == *++scan && prev == *++scan &&
1957 prev == *++scan && prev == *++scan &&
1958 prev == *++scan && prev == *++scan &&
1959 scan < strend);
1960 s->match_length = MAX_MATCH - (int)(strend - scan);
1961 if (s->match_length > s->lookahead)
1962 s->match_length = s->lookahead;
1964 Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
1967 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
1968 if (s->match_length >= MIN_MATCH) {
1969 check_match(s, s->strstart, s->strstart - 1, s->match_length);
1971 _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
1973 s->lookahead -= s->match_length;
1974 s->strstart += s->match_length;
1975 s->match_length = 0;
1976 } else {
1977 /* No match, output a literal byte */
1978 Tracevv((stderr,"%c", s->window[s->strstart]));
1979 _tr_tally_lit (s, s->window[s->strstart], bflush);
1980 s->lookahead--;
1981 s->strstart++;
1983 if (bflush) FLUSH_BLOCK(s, 0);
1985 s->insert = 0;
1986 if (flush == Z_FINISH) {
1987 FLUSH_BLOCK(s, 1);
1988 return finish_done;
1990 if (s->sym_next)
1991 FLUSH_BLOCK(s, 0);
1992 return block_done;
1995 /* ===========================================================================
1996 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
1997 * (It will be regenerated if this run of deflate switches away from Huffman.)
1999 local block_state deflate_huff(s, flush)
2000 deflate_state *s;
2001 int flush;
2003 int bflush; /* set if current block must be flushed */
2005 for (;;) {
2006 /* Make sure that we have a literal to write. */
2007 if (s->lookahead == 0) {
2008 fill_window(s);
2009 if (s->lookahead == 0) {
2010 if (flush == Z_NO_FLUSH)
2011 return need_more;
2012 break; /* flush the current block */
2016 /* Output a literal byte */
2017 s->match_length = 0;
2018 Tracevv((stderr,"%c", s->window[s->strstart]));
2019 _tr_tally_lit (s, s->window[s->strstart], bflush);
2020 s->lookahead--;
2021 s->strstart++;
2022 if (bflush) FLUSH_BLOCK(s, 0);
2024 s->insert = 0;
2025 if (flush == Z_FINISH) {
2026 FLUSH_BLOCK(s, 1);
2027 return finish_done;
2029 if (s->sym_next)
2030 FLUSH_BLOCK(s, 0);
2031 return block_done;