1 /* deflate.c -- compress data using the deflation algorithm
2 * Copyright (C) 1995 Jean-loup Gailly.
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 ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
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: deflate.c,v 1.5 1995/04/29 16:52:05 jloup Exp $ */
54 char copyright[] = " deflate Copyright 1995 Jean-loup Gailly ";
56 If you use the zlib library in a product, an acknowledgment is welcome
57 in the documentation of your product. If for some reason you cannot
58 include such an acknowledgment, I would appreciate that you keep this
59 copyright string in the executable of your product.
63 /* Tail of hash chains */
68 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
70 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
71 /* Minimum amount of lookahead, except at the end of the input file.
72 * See deflate.c for comments about the MIN_MATCH+1.
75 /* Values for max_lazy_match, good_match and max_chain_length, depending on
76 * the desired pack level (0..9). The values given below have been tuned to
77 * exclude worst case performance for pathological files. Better values may be
78 * found for specific files.
81 typedef struct config_s {
82 ush good_length; /* reduce lazy search above this match length */
83 ush max_lazy; /* do not perform lazy search above this match length */
84 ush nice_length; /* quit search above this match length */
88 local config configuration_table[10] = {
89 /* good lazy nice chain */
90 /* 0 */ {0, 0, 0, 0}, /* store only */
91 /* 1 */ {4, 4, 8, 4}, /* maximum speed, no lazy matches */
92 /* 2 */ {4, 5, 16, 8},
93 /* 3 */ {4, 6, 32, 32},
95 /* 4 */ {4, 4, 16, 16}, /* lazy matches */
96 /* 5 */ {8, 16, 32, 32},
97 /* 6 */ {8, 16, 128, 128},
98 /* 7 */ {8, 32, 128, 256},
99 /* 8 */ {32, 128, 258, 1024},
100 /* 9 */ {32, 258, 258, 4096}}; /* maximum compression */
102 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
103 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
108 /* result of memcmp for equal strings */
110 struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
112 /* ===========================================================================
113 * Prototypes for local functions.
116 local void fill_window __P((deflate_state *s));
117 local int deflate_fast __P((deflate_state *s, int flush));
118 local int deflate_slow __P((deflate_state *s, int flush));
119 local void lm_init __P((deflate_state *s));
120 local int longest_match __P((deflate_state *s, IPos cur_match));
121 local void putShortMSB __P((deflate_state *s, uInt b));
122 local void flush_pending __P((z_stream *strm));
123 local int read_buf __P((z_stream *strm, char *buf, unsigned size));
125 void match_init __P((void)); /* asm code initialization */
129 local void check_match __P((deflate_state *s, IPos start, IPos match,
134 /* ===========================================================================
135 * Update a hash value with the given input byte
136 * IN assertion: all calls to to UPDATE_HASH are made with consecutive
137 * input characters, so that a running hash key can be computed from the
138 * previous key instead of complete recalculation each time.
140 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
142 /* ===========================================================================
143 * Insert string str in the dictionary and set match_head to the previous head
144 * of the hash chain (the most recent string with same hash key). Return
145 * the previous length of the hash chain.
146 * IN assertion: all calls to to INSERT_STRING are made with consecutive
147 * input characters and the first MIN_MATCH bytes of str are valid
148 * (except for the last MIN_MATCH-1 bytes of the input file).
150 #define INSERT_STRING(s, str, match_head) \
151 (UPDATE_HASH(s, s->ins_h, s->window[(str) + MIN_MATCH-1]), \
152 s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \
153 s->head[s->ins_h] = (str))
155 /* ========================================================================= */
156 int deflateInit (strm, level)
160 return deflateInit2 (strm, level, DEFLATED, WBITS, MEM_LEVEL, 0);
161 /* To do: ignore strm->next_in if we use it as window */
164 /* ========================================================================= */
165 int deflateInit2 (strm, level, method, windowBits, memLevel, strategy)
176 if (strm == Z_NULL) return Z_STREAM_ERROR;
179 if (strm->zalloc == Z_NULL) strm->zalloc = zcalloc;
180 if (strm->zfree == Z_NULL) strm->zfree = zcfree;
182 if (level == Z_DEFAULT_COMPRESSION) level = 6;
184 if (windowBits < 0) { /* undocumented feature: suppress zlib header */
186 windowBits = -windowBits;
188 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != DEFLATED ||
189 windowBits < 8 || windowBits > 15 || level < 1 || level > 9) {
190 return Z_STREAM_ERROR;
192 s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
193 if (s == Z_NULL) return Z_MEM_ERROR;
194 strm->state = (struct internal_state *)s;
197 s->noheader = noheader;
198 s->w_bits = windowBits;
199 s->w_size = 1 << s->w_bits;
200 s->w_mask = s->w_size - 1;
202 s->hash_bits = memLevel + 7;
203 s->hash_size = 1 << s->hash_bits;
204 s->hash_mask = s->hash_size - 1;
205 s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
207 s->window = (Byte*) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
208 s->prev = (Pos*) ZALLOC(strm, s->w_size, sizeof(Pos));
209 s->head = (Pos*) ZALLOC(strm, s->hash_size, sizeof(Pos));
211 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
213 s->pending_buf = (uch*) ZALLOC(strm, s->lit_bufsize, 2*sizeof(ush));
215 if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
216 s->pending_buf == Z_NULL) {
217 strm->msg = z_errmsg[1-Z_MEM_ERROR];
221 s->d_buf = (ush*) &(s->pending_buf[s->lit_bufsize]);
222 s->l_buf = (uch*) &(s->pending_buf[3*s->lit_bufsize]);
223 /* We overlay pending_buf and d_buf+l_buf. This works since the average
224 * output size for (length,distance) codes is <= 32 bits (worst case
229 s->strategy = strategy;
230 s->method = (Byte)method;
232 return deflateReset(strm);
235 /* ========================================================================= */
236 int deflateReset (strm)
241 if (strm == Z_NULL || strm->state == Z_NULL ||
242 strm->zalloc == Z_NULL || strm->zfree == Z_NULL) return Z_STREAM_ERROR;
244 strm->total_in = strm->total_out = 0;
245 strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
246 strm->data_type = Z_UNKNOWN;
248 s = (deflate_state *)strm->state;
250 s->pending_out = s->pending_buf;
252 s->status = s->noheader ? BUSY_STATE : INIT_STATE;
261 /* =========================================================================
262 * Put a short the pending_out buffer. The 16-bit value is put in MSB order.
263 * IN assertion: the stream state is correct and there is enough room in
264 * the pending_out buffer.
266 local void putShortMSB (s, b)
270 put_byte(s, (Byte)(b >> 8));
271 put_byte(s, (Byte)(b & 0xff));
274 /* =========================================================================
275 * Flush as much pending output as possible.
277 local void flush_pending(strm)
280 unsigned len = strm->state->pending;
282 if (len > strm->avail_out) len = strm->avail_out;
283 if (len == 0) return;
285 zmemcpy(strm->next_out, strm->state->pending_out, len);
286 strm->next_out += len;
287 strm->state->pending_out += len;
288 strm->total_out += len;
289 strm->avail_out -= len;
290 strm->state->pending -= len;
291 if (strm->state->pending == 0) {
292 strm->state->pending_out = strm->state->pending_buf;
296 /* ========================================================================= */
297 int deflate (strm, flush)
301 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
303 if (strm->next_out == Z_NULL || strm->next_in == Z_NULL) {
304 ERR_RETURN(strm, Z_STREAM_ERROR);
306 if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
308 strm->state->strm = strm; /* just in case */
310 /* Write the zlib header */
311 if (strm->state->status == INIT_STATE) {
313 uInt header = (DEFLATED + ((strm->state->w_bits-8)<<4)) << 8;
314 uInt level_flags = (strm->state->level-1) >> 1;
316 if (level_flags > 3) level_flags = 3;
317 header |= (level_flags << 6);
318 header += 31 - (header % 31);
320 strm->state->status = BUSY_STATE;
321 putShortMSB(strm->state, header);
324 /* Flush as much pending output as possible */
325 if (strm->state->pending != 0) {
327 if (strm->avail_out == 0) return Z_OK;
330 /* User must not provide more input after the first FINISH: */
331 if (strm->state->status == FINISH_STATE && strm->avail_in != 0) {
332 ERR_RETURN(strm, Z_BUF_ERROR);
335 /* Start a new block or continue the current one.
337 if (strm->avail_in != 0 ||
338 (flush == Z_FINISH && strm->state->status != FINISH_STATE)) {
340 if (flush == Z_FINISH) {
341 strm->state->status = FINISH_STATE;
343 if (strm->state->level <= 3) {
344 if (deflate_fast(strm->state, flush)) return Z_OK;
346 if (deflate_slow(strm->state, flush)) return Z_OK;
349 Assert(strm->avail_out > 0, "bug2");
351 if (flush != Z_FINISH) return Z_OK;
352 if (strm->state->noheader) return Z_STREAM_END;
354 /* Write the zlib trailer (adler32) */
355 putShortMSB(strm->state, (uInt)(strm->state->adler >> 16));
356 putShortMSB(strm->state, (uInt)(strm->state->adler & 0xffff));
358 /* If avail_out is zero, the application will call deflate again
361 strm->state->noheader = 1; /* write the trailer only once! */
362 return strm->state->pending != 0 ? Z_OK : Z_STREAM_END;
365 /* ========================================================================= */
366 int deflateEnd (strm)
369 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
371 TRY_FREE(strm, strm->state->window);
372 TRY_FREE(strm, strm->state->prev);
373 TRY_FREE(strm, strm->state->head);
374 TRY_FREE(strm, strm->state->pending_buf);
376 ZFREE(strm, strm->state);
377 strm->state = Z_NULL;
382 /* ========================================================================= */
383 int deflateCopy (dest, source)
387 if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
388 return Z_STREAM_ERROR;
391 return Z_STREAM_ERROR; /* to be implemented */
393 dest->state = (struct internal_state *)
394 (*dest->zalloc)(1, sizeof(deflate_state));
395 if (dest->state == Z_NULL) return Z_MEM_ERROR;
397 *(dest->state) = *(source->state);
402 /* ===========================================================================
403 * Read a new buffer from the current input stream, update the adler32
404 * and total number of bytes read.
406 local int read_buf(strm, buf, size)
411 unsigned len = strm->avail_in;
413 if (len > size) len = size;
414 if (len == 0) return 0;
416 strm->avail_in -= len;
418 if (!strm->state->noheader) {
419 strm->state->adler = adler32(strm->state->adler, strm->next_in, len);
421 zmemcpy(buf, strm->next_in, len);
422 strm->next_in += len;
423 strm->total_in += len;
428 /* ===========================================================================
429 * Initialize the "longest match" routines for a new zlib stream
431 local void lm_init (s)
436 s->window_size = (ulg)2L*s->w_size;
439 /* Initialize the hash table (avoiding 64K overflow for 16 bit systems).
440 * prev[] will be initialized on the fly.
442 s->head[s->hash_size-1] = NIL;
443 zmemzero((char*)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
445 /* Set the default configuration parameters:
447 s->max_lazy_match = configuration_table[s->level].max_lazy;
448 s->good_match = configuration_table[s->level].good_length;
449 s->nice_match = configuration_table[s->level].nice_length;
450 s->max_chain_length = configuration_table[s->level].max_chain;
455 s->match_length = MIN_MATCH-1;
456 s->match_available = 0;
458 match_init(); /* initialize the asm code */
462 for (j=0; j<MIN_MATCH-1; j++) UPDATE_HASH(s, s->ins_h, s->window[j]);
463 /* If lookahead < MIN_MATCH, ins_h is garbage, but this is
464 * not important since only literal bytes will be emitted.
468 /* ===========================================================================
469 * Set match_start to the longest match starting at the given string and
470 * return its length. Matches shorter or equal to prev_length are discarded,
471 * in which case the result is equal to prev_length and match_start is
473 * IN assertions: cur_match is the head of the hash chain for the current
474 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
477 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
478 * match.S. The code will be functionally equivalent.
480 local int longest_match(s, cur_match)
482 IPos cur_match; /* current match */
484 unsigned chain_length = s->max_chain_length;/* max hash chain length */
485 register Byte *scan = s->window + s->strstart; /* current string */
486 register Byte *match; /* matched string */
487 register int len; /* length of current match */
488 int best_len = s->prev_length; /* best match length so far */
489 IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
490 s->strstart - (IPos)MAX_DIST(s) : NIL;
491 /* Stop when cur_match becomes <= limit. To simplify the code,
492 * we prevent matches with the string of window index 0.
496 /* Compare two bytes at a time. Note: this is not always beneficial.
497 * Try with and without -DUNALIGNED_OK to check.
499 register Byte *strend = s->window + s->strstart + MAX_MATCH - 1;
500 register ush scan_start = *(ush*)scan;
501 register ush scan_end = *(ush*)(scan+best_len-1);
503 register Byte *strend = s->window + s->strstart + MAX_MATCH;
504 register Byte scan_end1 = scan[best_len-1];
505 register Byte scan_end = scan[best_len];
508 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
509 * It is easy to get rid of this optimization if necessary.
511 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
513 /* Do not waste too much time if we already have a good match: */
514 if (s->prev_length >= s->good_match) {
517 Assert(s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
520 Assert(cur_match < s->strstart, "no future");
521 match = s->window + cur_match;
523 /* Skip to next match if the match length cannot increase
524 * or if the match length is less than 2:
526 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
527 /* This code assumes sizeof(unsigned short) == 2. Do not use
528 * UNALIGNED_OK if your compiler uses a different size.
530 if (*(ush*)(match+best_len-1) != scan_end ||
531 *(ush*)match != scan_start) continue;
533 /* It is not necessary to compare scan[2] and match[2] since they are
534 * always equal when the other bytes match, given that the hash keys
535 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
536 * strstart+3, +5, ... up to strstart+257. We check for insufficient
537 * lookahead only every 4th comparison; the 128th check will be made
538 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
539 * necessary to put more guard bytes at the end of the window, or
540 * to check more often for insufficient lookahead.
544 } while (*(ush*)(scan+=2) == *(ush*)(match+=2) &&
545 *(ush*)(scan+=2) == *(ush*)(match+=2) &&
546 *(ush*)(scan+=2) == *(ush*)(match+=2) &&
547 *(ush*)(scan+=2) == *(ush*)(match+=2) &&
549 /* The funny "do {}" generates better code on most compilers */
551 /* Here, scan <= window+strstart+257 */
552 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
553 if (*scan == *match) scan++;
555 len = (MAX_MATCH - 1) - (int)(strend-scan);
556 scan = strend - (MAX_MATCH-1);
558 #else /* UNALIGNED_OK */
560 if (match[best_len] != scan_end ||
561 match[best_len-1] != scan_end1 ||
563 *++match != scan[1]) continue;
565 /* The check at best_len-1 can be removed because it will be made
566 * again later. (This heuristic is not always a win.)
567 * It is not necessary to compare scan[2] and match[2] since they
568 * are always equal when the other bytes match, given that
569 * the hash keys are equal and that HASH_BITS >= 8.
573 /* We check for insufficient lookahead only every 8th comparison;
574 * the 256th check will be made at strstart+258.
577 } while (*++scan == *++match && *++scan == *++match &&
578 *++scan == *++match && *++scan == *++match &&
579 *++scan == *++match && *++scan == *++match &&
580 *++scan == *++match && *++scan == *++match &&
583 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
585 len = MAX_MATCH - (int)(strend - scan);
586 scan = strend - MAX_MATCH;
588 #endif /* UNALIGNED_OK */
590 if (len > best_len) {
591 s->match_start = cur_match;
593 if (len >= s->nice_match) break;
595 scan_end = *(ush*)(scan+best_len-1);
597 scan_end1 = scan[best_len-1];
598 scan_end = scan[best_len];
601 } while ((cur_match = s->prev[cur_match & s->w_mask]) > limit
602 && --chain_length != 0);
609 /* ===========================================================================
610 * Check that the match at match_start is indeed a match.
612 local void check_match(s, start, match, length)
617 /* check that the match is indeed a match */
618 if (memcmp((char*)s->window + match,
619 (char*)s->window + start, length) != EQUAL) {
621 " start %d, match %d, length %d\n",
622 start, match, length);
623 z_error("invalid match");
626 fprintf(stderr,"\\[%d,%d]", start-match, length);
627 do { putc(s->window[start++], stderr); } while (--length != 0);
631 # define check_match(s, start, match, length)
634 /* ===========================================================================
635 * Fill the window when the lookahead becomes insufficient.
636 * Updates strstart and lookahead.
638 * IN assertion: lookahead < MIN_LOOKAHEAD
639 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
640 * At least one byte has been read, or avail_in == 0; reads are
641 * performed for at least two bytes (required for the zip translate_eol
642 * option -- not supported here).
644 local void fill_window(s)
647 register unsigned n, m;
648 unsigned more; /* Amount of free space at the end of the window. */
651 more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
653 /* Deal with !@#$% 64K limit: */
654 if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
656 } else if (more == (unsigned)(-1)) {
657 /* Very unlikely, but possible on 16 bit machine if strstart == 0
658 * and lookahead == 1 (input done one byte at time)
662 /* If the window is almost full and there is insufficient lookahead,
663 * move the upper half to the lower one to make room in the upper half.
665 } else if (s->strstart >= s->w_size+MAX_DIST(s)) {
667 /* By the IN assertion, the window is not empty so we can't confuse
668 * more == 0 with more == 64K on a 16 bit machine.
670 memcpy((char*)s->window, (char*)s->window+s->w_size,
671 (unsigned)s->w_size);
672 s->match_start -= s->w_size;
673 s->strstart -= s->w_size; /* we now have strstart >= MAX_DIST */
675 s->block_start -= (long) s->w_size;
677 for (n = 0; n < s->hash_size; n++) {
679 s->head[n] = (Pos)(m >= s->w_size ? m-s->w_size : NIL);
681 for (n = 0; n < s->w_size; n++) {
683 s->prev[n] = (Pos)(m >= s->w_size ? m-s->w_size : NIL);
684 /* If n is not on any hash chain, prev[n] is garbage but
685 * its value will never be used.
690 if (s->strm->avail_in == 0) return;
692 /* If there was no sliding:
693 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
694 * more == window_size - lookahead - strstart
695 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
696 * => more >= window_size - 2*WSIZE + 2
697 * In the BIG_MEM or MMAP case (not yet supported),
698 * window_size == input_size + MIN_LOOKAHEAD &&
699 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
700 * Otherwise, window_size == 2*WSIZE so more >= 2.
701 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
703 Assert(more >= 2, "more < 2");
705 n = read_buf(s->strm, (char*)s->window + s->strstart + s->lookahead,
709 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
712 /* ===========================================================================
713 * Flush the current block, with given end-of-file flag.
714 * IN assertion: strstart is set to the end of the current match.
716 #define FLUSH_BLOCK_ONLY(s, eof) { \
717 ct_flush_block(s, (s->block_start >= 0L ? \
718 (char*)&s->window[(unsigned)s->block_start] : \
719 (char*)Z_NULL), (long)s->strstart - s->block_start, (eof)); \
720 s->block_start = s->strstart; \
721 flush_pending(s->strm); \
724 /* Same but force premature exit if necessary. */
725 #define FLUSH_BLOCK(s, eof) { \
726 FLUSH_BLOCK_ONLY(s, eof); \
727 if (s->strm->avail_out == 0) return 1; \
730 /* ===========================================================================
731 * Compress as much as possible from the input stream, return true if
732 * processing was terminated prematurely (no more input or output space).
733 * This function does not perform lazy evaluationof matches and inserts
734 * new strings in the dictionary only for unmatched strings or for short
735 * matches. It is used only for the fast compression options.
737 local int deflate_fast(s, flush)
741 IPos hash_head; /* head of the hash chain */
742 int bflush; /* set if current block must be flushed */
744 s->prev_length = MIN_MATCH-1;
747 /* Make sure that we always have enough lookahead, except
748 * at the end of the input file. We need MAX_MATCH bytes
749 * for the next match, plus MIN_MATCH bytes to insert the
750 * string following the next match.
752 if (s->lookahead < MIN_LOOKAHEAD) {
754 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) return 1;
756 if (s->lookahead == 0) break; /* flush the current block */
759 /* Insert the string window[strstart .. strstart+2] in the
760 * dictionary, and set hash_head to the head of the hash chain:
762 INSERT_STRING(s, s->strstart, hash_head);
764 /* Find the longest match, discarding those <= prev_length.
765 * At this point we have always match_length < MIN_MATCH
767 if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
768 /* To simplify the code, we prevent matches with the string
769 * of window index 0 (in particular we have to avoid a match
770 * of the string with itself at the start of the input file).
772 if (s->strategy != Z_HUFFMAN_ONLY) {
773 s->match_length = longest_match (s, hash_head);
775 /* longest_match() sets match_start */
777 if (s->match_length > s->lookahead) s->match_length = s->lookahead;
779 if (s->match_length >= MIN_MATCH) {
780 check_match(s, s->strstart, s->match_start, s->match_length);
782 bflush = ct_tally(s, s->strstart - s->match_start,
783 s->match_length - MIN_MATCH);
785 s->lookahead -= s->match_length;
787 /* Insert new strings in the hash table only if the match length
788 * is not too large. This saves time but degrades compression.
790 if (s->match_length <= s->max_insert_length) {
791 s->match_length--; /* string at strstart already in hash table */
794 INSERT_STRING(s, s->strstart, hash_head);
795 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
796 * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
797 * these bytes are garbage, but it does not matter since
798 * the next lookahead bytes will be emitted as literals.
800 } while (--s->match_length != 0);
803 s->strstart += s->match_length;
805 s->ins_h = s->window[s->strstart];
806 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
808 Call UPDATE_HASH() MIN_MATCH-3 more times
812 /* No match, output a literal byte */
813 Tracevv((stderr,"%c", s->window[s->strstart]));
814 bflush = ct_tally (s, 0, s->window[s->strstart]);
818 if (bflush) FLUSH_BLOCK(s, 0);
820 FLUSH_BLOCK(s, flush == Z_FINISH);
821 return 0; /* normal exit */
824 /* ===========================================================================
825 * Same as above, but achieves better compression. We use a lazy
826 * evaluation for matches: a match is finally adopted only if there is
827 * no better match at the next window position.
829 local int deflate_slow(s, flush)
833 IPos hash_head; /* head of hash chain */
834 int bflush; /* set if current block must be flushed */
836 /* Process the input block. */
838 /* Make sure that we always have enough lookahead, except
839 * at the end of the input file. We need MAX_MATCH bytes
840 * for the next match, plus MIN_MATCH bytes to insert the
841 * string following the next match.
843 if (s->lookahead < MIN_LOOKAHEAD) {
845 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) return 1;
847 if (s->lookahead == 0) break; /* flush the current block */
850 /* Insert the string window[strstart .. strstart+2] in the
851 * dictionary, and set hash_head to the head of the hash chain:
853 INSERT_STRING(s, s->strstart, hash_head);
855 /* Find the longest match, discarding those <= prev_length.
857 s->prev_length = s->match_length, s->prev_match = s->match_start;
858 s->match_length = MIN_MATCH-1;
860 if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
861 s->strstart - hash_head <= MAX_DIST(s)) {
862 /* To simplify the code, we prevent matches with the string
863 * of window index 0 (in particular we have to avoid a match
864 * of the string with itself at the start of the input file).
866 if (s->strategy != Z_HUFFMAN_ONLY) {
867 s->match_length = longest_match (s, hash_head);
869 /* longest_match() sets match_start */
870 if (s->match_length > s->lookahead) s->match_length = s->lookahead;
872 if (s->match_length <= 5 && (s->strategy == Z_FILTERED ||
873 (s->match_length == MIN_MATCH &&
874 s->strstart - s->match_start > TOO_FAR))) {
876 /* If prev_match is also MIN_MATCH, match_start is garbage
877 * but we will ignore the current match anyway.
879 s->match_length = MIN_MATCH-1;
882 /* If there was a match at the previous step and the current
883 * match is not better, output the previous match:
885 if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
887 check_match(s, s->strstart-1, s->prev_match, s->prev_length);
889 bflush = ct_tally(s, s->strstart -1 - s->prev_match,
890 s->prev_length - MIN_MATCH);
892 /* Insert in hash table all strings up to the end of the match.
893 * strstart-1 and strstart are already inserted.
895 s->lookahead -= s->prev_length-1;
899 INSERT_STRING(s, s->strstart, hash_head);
900 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
901 * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
902 * these bytes are garbage, but it does not matter since the
903 * next lookahead bytes will always be emitted as literals.
905 } while (--s->prev_length != 0);
906 s->match_available = 0;
907 s->match_length = MIN_MATCH-1;
910 if (bflush) FLUSH_BLOCK(s, 0);
912 } else if (s->match_available) {
913 /* If there was no match at the previous position, output a
914 * single literal. If there was a match but the current match
915 * is longer, truncate the previous match to a single literal.
917 Tracevv((stderr,"%c", s->window[s->strstart-1]));
918 if (ct_tally (s, 0, s->window[s->strstart-1])) {
919 FLUSH_BLOCK_ONLY(s, 0);
923 if (s->strm->avail_out == 0) return 1;
925 /* There is no previous match to compare with, wait for
926 * the next step to decide.
928 s->match_available = 1;
933 if (s->match_available) ct_tally (s, 0, s->window[s->strstart-1]);
935 FLUSH_BLOCK(s, flush == Z_FINISH);