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.4 1995/04/14 19:49:46 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));
121 local int longest_match __P((deflate_state *s, IPos cur_match));
123 void match_init __P((void)); /* asm code initialization */
127 local void check_match __P((deflate_state *s, IPos start, IPos match,
132 /* ===========================================================================
133 * Update a hash value with the given input byte
134 * IN assertion: all calls to to UPDATE_HASH are made with consecutive
135 * input characters, so that a running hash key can be computed from the
136 * previous key instead of complete recalculation each time.
138 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
140 /* ===========================================================================
141 * Insert string str in the dictionary and set match_head to the previous head
142 * of the hash chain (the most recent string with same hash key). Return
143 * the previous length of the hash chain.
144 * IN assertion: all calls to to INSERT_STRING are made with consecutive
145 * input characters and the first MIN_MATCH bytes of str are valid
146 * (except for the last MIN_MATCH-1 bytes of the input file).
148 #define INSERT_STRING(s, str, match_head) \
149 (UPDATE_HASH(s, s->ins_h, s->window[(str) + MIN_MATCH-1]), \
150 s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \
151 s->head[s->ins_h] = (str))
153 /* ========================================================================= */
154 int deflateInit (strm, level)
158 return deflateInit2 (strm, level, DEFLATED, WBITS, MEM_LEVEL, 0);
159 /* To do: ignore strm->next_in if we use it as window */
162 /* ========================================================================= */
163 int deflateInit2 (strm, level, method, windowBits, memLevel, strategy)
174 if (strm == Z_NULL) return Z_STREAM_ERROR;
177 if (strm->zalloc == Z_NULL) strm->zalloc = zcalloc;
178 if (strm->zfree == Z_NULL) strm->zfree = zcfree;
180 if (level == Z_DEFAULT_COMPRESSION) level = 6;
182 if (windowBits < 0) { /* undocumented feature: suppress zlib header */
184 windowBits = -windowBits;
186 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != DEFLATED ||
187 windowBits < 8 || windowBits > 15 || level < 1 || level > 9) {
188 return Z_STREAM_ERROR;
190 s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
191 if (s == Z_NULL) return Z_MEM_ERROR;
192 strm->state = (struct internal_state *)s;
195 s->noheader = noheader;
196 s->w_bits = windowBits;
197 s->w_size = 1 << s->w_bits;
198 s->w_mask = s->w_size - 1;
200 s->hash_bits = memLevel + 7;
201 s->hash_size = 1 << s->hash_bits;
202 s->hash_mask = s->hash_size - 1;
203 s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
205 s->window = (Byte*) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
206 s->prev = (Pos*) ZALLOC(strm, s->w_size, sizeof(Pos));
207 s->head = (Pos*) ZALLOC(strm, s->hash_size, sizeof(Pos));
209 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
211 s->pending_buf = (uch*) ZALLOC(strm, s->lit_bufsize, 2*sizeof(ush));
213 if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
214 s->pending_buf == Z_NULL) {
215 strm->msg = z_errmsg[1-Z_MEM_ERROR];
219 s->d_buf = (ush*) &(s->pending_buf[s->lit_bufsize]);
220 s->l_buf = (uch*) &(s->pending_buf[3*s->lit_bufsize]);
221 /* We overlay pending_buf and d_buf+l_buf. This works since the average
222 * output size for (length,distance) codes is <= 32 bits (worst case
227 s->strategy = strategy;
230 return deflateReset(strm);
233 /* ========================================================================= */
234 int deflateReset (strm)
239 if (strm == Z_NULL || strm->state == Z_NULL ||
240 strm->zalloc == Z_NULL || strm->zfree == Z_NULL) return Z_STREAM_ERROR;
242 strm->total_in = strm->total_out = 0;
243 strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
244 strm->data_type = Z_UNKNOWN;
246 s = (deflate_state *)strm->state;
248 s->pending_out = s->pending_buf;
250 s->status = s->noheader ? BUSY_STATE : INIT_STATE;
259 /* =========================================================================
260 * Put a short the pending_out buffer. The 16-bit value is put in MSB order.
261 * IN assertion: the stream state is correct and there is enough room in
262 * the pending_out buffer.
264 local void putShortMSB (s, b)
269 put_byte(s, b & 0xff);
272 /* =========================================================================
273 * Flush as much pending output as possible.
275 local void flush_pending(strm)
278 unsigned len = strm->state->pending;
280 if (len > strm->avail_out) len = strm->avail_out;
281 if (len == 0) return;
283 zmemcpy(strm->next_out, strm->state->pending_out, len);
284 strm->next_out += len;
285 strm->state->pending_out += len;
286 strm->total_out += len;
287 strm->avail_out -= len;
288 strm->state->pending -= len;
289 if (strm->state->pending == 0) {
290 strm->state->pending_out = strm->state->pending_buf;
294 /* ========================================================================= */
295 int deflate (strm, flush)
299 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
301 if (strm->next_out == Z_NULL || strm->next_in == Z_NULL) {
302 ERR_RETURN(strm, Z_STREAM_ERROR);
304 if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
306 strm->state->strm = strm; /* just in case */
308 /* Write the zlib header */
309 if (strm->state->status == INIT_STATE) {
311 uInt header = (DEFLATED + ((strm->state->w_bits-8)<<4)) << 8;
312 uInt level_flags = (strm->state->level-1) >> 1;
314 if (level_flags > 3) level_flags = 3;
315 header |= (level_flags << 6);
316 header += 31 - (header % 31);
318 strm->state->status = BUSY_STATE;
319 putShortMSB(strm->state, header);
322 /* Flush as much pending output as possible */
323 if (strm->state->pending != 0) {
325 if (strm->avail_out == 0) return Z_OK;
328 /* User must not provide more input after the first FINISH: */
329 if (strm->state->status == FINISH_STATE && strm->avail_in != 0) {
330 ERR_RETURN(strm, Z_BUF_ERROR);
333 /* Start a new block or continue the current one.
335 if (strm->avail_in != 0 ||
336 (flush == Z_FINISH && strm->state->status != FINISH_STATE)) {
338 if (flush == Z_FINISH) {
339 strm->state->status = FINISH_STATE;
341 if (strm->state->level <= 3) {
342 if (deflate_fast(strm->state, flush)) return Z_OK;
344 if (deflate_slow(strm->state, flush)) return Z_OK;
347 Assert(strm->avail_out > 0, "bug2");
349 if (flush != Z_FINISH || strm->state->noheader) return Z_OK;
351 /* Write the zlib trailer (adler32) */
352 putShortMSB(strm->state, strm->state->adler >> 16);
353 putShortMSB(strm->state, strm->state->adler & 0xffff);
355 /* If avail_out is zero, the application will call deflate again
358 strm->state->noheader = 1; /* write the trailer only once! */
362 /* ========================================================================= */
363 int deflateEnd (strm)
366 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
368 TRY_FREE(strm, strm->state->window);
369 TRY_FREE(strm, strm->state->prev);
370 TRY_FREE(strm, strm->state->head);
371 TRY_FREE(strm, strm->state->pending_buf);
373 ZFREE(strm, strm->state);
374 strm->state = Z_NULL;
379 /* ========================================================================= */
380 int deflateCopy (dest, source)
384 if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
385 return Z_STREAM_ERROR;
388 return Z_STREAM_ERROR; /* to be implemented */
390 dest->state = (struct internal_state *)
391 (*dest->zalloc)(1, sizeof(deflate_state));
392 if (dest->state == Z_NULL) return Z_MEM_ERROR;
394 *(dest->state) = *(source->state);
399 /* ===========================================================================
400 * Read a new buffer from the current input stream, update the adler32
401 * and total number of bytes read.
403 local int read_buf(strm, buf, size)
408 unsigned len = strm->avail_in;
410 if (len > size) len = size;
411 if (len == 0) return 0;
413 strm->avail_in -= len;
415 if (!strm->state->noheader) {
416 strm->state->adler = adler32(strm->state->adler, strm->next_in, len);
418 zmemcpy(buf, strm->next_in, len);
419 strm->next_in += len;
420 strm->total_in += len;
425 /* ===========================================================================
426 * Initialize the "longest match" routines for a new zlib stream
428 local void lm_init (s)
433 s->window_size = (ulg)2L*s->w_size;
436 /* Initialize the hash table (avoiding 64K overflow for 16 bit systems).
437 * prev[] will be initialized on the fly.
439 s->head[s->hash_size-1] = NIL;
440 zmemzero((char*)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
442 /* Set the default configuration parameters:
444 s->max_lazy_match = configuration_table[s->level].max_lazy;
445 s->good_match = configuration_table[s->level].good_length;
446 s->nice_match = configuration_table[s->level].nice_length;
447 s->max_chain_length = configuration_table[s->level].max_chain;
452 s->match_length = MIN_MATCH-1;
453 s->match_available = 0;
455 match_init(); /* initialize the asm code */
459 for (j=0; j<MIN_MATCH-1; j++) UPDATE_HASH(s, s->ins_h, s->window[j]);
460 /* If lookahead < MIN_MATCH, ins_h is garbage, but this is
461 * not important since only literal bytes will be emitted.
465 /* ===========================================================================
466 * Set match_start to the longest match starting at the given string and
467 * return its length. Matches shorter or equal to prev_length are discarded,
468 * in which case the result is equal to prev_length and match_start is
470 * IN assertions: cur_match is the head of the hash chain for the current
471 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
474 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
475 * match.S. The code will be functionally equivalent.
477 local int longest_match(s, cur_match)
479 IPos cur_match; /* current match */
481 unsigned chain_length = s->max_chain_length;/* max hash chain length */
482 register Byte *scan = s->window + s->strstart; /* current string */
483 register Byte *match; /* matched string */
484 register int len; /* length of current match */
485 int best_len = s->prev_length; /* best match length so far */
486 IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
487 s->strstart - (IPos)MAX_DIST(s) : NIL;
488 /* Stop when cur_match becomes <= limit. To simplify the code,
489 * we prevent matches with the string of window index 0.
493 /* Compare two bytes at a time. Note: this is not always beneficial.
494 * Try with and without -DUNALIGNED_OK to check.
496 register Byte *strend = s->window + s->strstart + MAX_MATCH - 1;
497 register ush scan_start = *(ush*)scan;
498 register ush scan_end = *(ush*)(scan+best_len-1);
500 register Byte *strend = s->window + s->strstart + MAX_MATCH;
501 register Byte scan_end1 = scan[best_len-1];
502 register Byte scan_end = scan[best_len];
505 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
506 * It is easy to get rid of this optimization if necessary.
508 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
510 /* Do not waste too much time if we already have a good match: */
511 if (s->prev_length >= s->good_match) {
514 Assert(s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
517 Assert(cur_match < s->strstart, "no future");
518 match = s->window + cur_match;
520 /* Skip to next match if the match length cannot increase
521 * or if the match length is less than 2:
523 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
524 /* This code assumes sizeof(unsigned short) == 2. Do not use
525 * UNALIGNED_OK if your compiler uses a different size.
527 if (*(ush*)(match+best_len-1) != scan_end ||
528 *(ush*)match != scan_start) continue;
530 /* It is not necessary to compare scan[2] and match[2] since they are
531 * always equal when the other bytes match, given that the hash keys
532 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
533 * strstart+3, +5, ... up to strstart+257. We check for insufficient
534 * lookahead only every 4th comparison; the 128th check will be made
535 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
536 * necessary to put more guard bytes at the end of the window, or
537 * to check more often for insufficient lookahead.
541 } while (*(ush*)(scan+=2) == *(ush*)(match+=2) &&
542 *(ush*)(scan+=2) == *(ush*)(match+=2) &&
543 *(ush*)(scan+=2) == *(ush*)(match+=2) &&
544 *(ush*)(scan+=2) == *(ush*)(match+=2) &&
546 /* The funny "do {}" generates better code on most compilers */
548 /* Here, scan <= window+strstart+257 */
549 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
550 if (*scan == *match) scan++;
552 len = (MAX_MATCH - 1) - (int)(strend-scan);
553 scan = strend - (MAX_MATCH-1);
555 #else /* UNALIGNED_OK */
557 if (match[best_len] != scan_end ||
558 match[best_len-1] != scan_end1 ||
560 *++match != scan[1]) continue;
562 /* The check at best_len-1 can be removed because it will be made
563 * again later. (This heuristic is not always a win.)
564 * It is not necessary to compare scan[2] and match[2] since they
565 * are always equal when the other bytes match, given that
566 * the hash keys are equal and that HASH_BITS >= 8.
570 /* We check for insufficient lookahead only every 8th comparison;
571 * the 256th check will be made at strstart+258.
574 } while (*++scan == *++match && *++scan == *++match &&
575 *++scan == *++match && *++scan == *++match &&
576 *++scan == *++match && *++scan == *++match &&
577 *++scan == *++match && *++scan == *++match &&
580 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
582 len = MAX_MATCH - (int)(strend - scan);
583 scan = strend - MAX_MATCH;
585 #endif /* UNALIGNED_OK */
587 if (len > best_len) {
588 s->match_start = cur_match;
590 if (len >= s->nice_match) break;
592 scan_end = *(ush*)(scan+best_len-1);
594 scan_end1 = scan[best_len-1];
595 scan_end = scan[best_len];
598 } while ((cur_match = s->prev[cur_match & s->w_mask]) > limit
599 && --chain_length != 0);
606 /* ===========================================================================
607 * Check that the match at match_start is indeed a match.
609 local void check_match(s, start, match, length)
614 /* check that the match is indeed a match */
615 if (memcmp((char*)s->window + match,
616 (char*)s->window + start, length) != EQUAL) {
618 " start %d, match %d, length %d\n",
619 start, match, length);
620 z_error("invalid match");
623 fprintf(stderr,"\\[%d,%d]", start-match, length);
624 do { putc(s->window[start++], stderr); } while (--length != 0);
628 # define check_match(s, start, match, length)
631 /* ===========================================================================
632 * Fill the window when the lookahead becomes insufficient.
633 * Updates strstart and lookahead.
635 * IN assertion: lookahead < MIN_LOOKAHEAD
636 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
637 * At least one byte has been read, or avail_in == 0; reads are
638 * performed for at least two bytes (required for the zip translate_eol
639 * option -- not supported here).
641 local void fill_window(s)
644 register unsigned n, m;
645 unsigned more; /* Amount of free space at the end of the window. */
648 more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
650 /* Deal with !@#$% 64K limit: */
651 if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
653 } else if (more == (unsigned)(-1)) {
654 /* Very unlikely, but possible on 16 bit machine if strstart == 0
655 * and lookahead == 1 (input done one byte at time)
659 /* If the window is almost full and there is insufficient lookahead,
660 * move the upper half to the lower one to make room in the upper half.
662 } else if (s->strstart >= s->w_size+MAX_DIST(s)) {
664 /* By the IN assertion, the window is not empty so we can't confuse
665 * more == 0 with more == 64K on a 16 bit machine.
667 memcpy((char*)s->window, (char*)s->window+s->w_size,
668 (unsigned)s->w_size);
669 s->match_start -= s->w_size;
670 s->strstart -= s->w_size; /* we now have strstart >= MAX_DIST */
672 s->block_start -= (long) s->w_size;
674 for (n = 0; n < s->hash_size; n++) {
676 s->head[n] = (Pos)(m >= s->w_size ? m-s->w_size : NIL);
678 for (n = 0; n < s->w_size; n++) {
680 s->prev[n] = (Pos)(m >= s->w_size ? m-s->w_size : NIL);
681 /* If n is not on any hash chain, prev[n] is garbage but
682 * its value will never be used.
687 if (s->strm->avail_in == 0) return;
689 /* If there was no sliding:
690 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
691 * more == window_size - lookahead - strstart
692 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
693 * => more >= window_size - 2*WSIZE + 2
694 * In the BIG_MEM or MMAP case (not yet supported),
695 * window_size == input_size + MIN_LOOKAHEAD &&
696 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
697 * Otherwise, window_size == 2*WSIZE so more >= 2.
698 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
700 Assert(more >= 2, "more < 2");
702 n = read_buf(s->strm, (char*)s->window + s->strstart + s->lookahead,
706 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
709 /* ===========================================================================
710 * Flush the current block, with given end-of-file flag.
711 * IN assertion: strstart is set to the end of the current match.
713 #define FLUSH_BLOCK_ONLY(s, eof) { \
714 ct_flush_block(s, (s->block_start >= 0L ? \
715 (char*)&s->window[(unsigned)s->block_start] : \
716 (char*)Z_NULL), (long)s->strstart - s->block_start, (eof)); \
717 s->block_start = s->strstart; \
718 flush_pending(s->strm); \
721 /* Same but force premature exit if necessary. */
722 #define FLUSH_BLOCK(s, eof) { \
723 FLUSH_BLOCK_ONLY(s, eof); \
724 if (s->strm->avail_out == 0) return 1; \
727 /* ===========================================================================
728 * Compress as much as possible from the input stream, return true if
729 * processing was terminated prematurely (no more input or output space).
730 * This function does not perform lazy evaluationof matches and inserts
731 * new strings in the dictionary only for unmatched strings or for short
732 * matches. It is used only for the fast compression options.
734 local int deflate_fast(s, flush)
738 IPos hash_head; /* head of the hash chain */
739 int bflush; /* set if current block must be flushed */
741 s->prev_length = MIN_MATCH-1;
744 /* Make sure that we always have enough lookahead, except
745 * at the end of the input file. We need MAX_MATCH bytes
746 * for the next match, plus MIN_MATCH bytes to insert the
747 * string following the next match.
749 if (s->lookahead < MIN_LOOKAHEAD) {
751 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) return 1;
753 if (s->lookahead == 0) break; /* flush the current block */
756 /* Insert the string window[strstart .. strstart+2] in the
757 * dictionary, and set hash_head to the head of the hash chain:
759 INSERT_STRING(s, s->strstart, hash_head);
761 /* Find the longest match, discarding those <= prev_length.
762 * At this point we have always match_length < MIN_MATCH
764 if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
765 /* To simplify the code, we prevent matches with the string
766 * of window index 0 (in particular we have to avoid a match
767 * of the string with itself at the start of the input file).
769 if (s->strategy != Z_HUFFMAN_ONLY) {
770 s->match_length = longest_match (s, hash_head);
772 /* longest_match() sets match_start */
774 if (s->match_length > s->lookahead) s->match_length = s->lookahead;
776 if (s->match_length >= MIN_MATCH) {
777 check_match(s, s->strstart, s->match_start, s->match_length);
779 bflush = ct_tally(s, s->strstart - s->match_start,
780 s->match_length - MIN_MATCH);
782 s->lookahead -= s->match_length;
784 /* Insert new strings in the hash table only if the match length
785 * is not too large. This saves time but degrades compression.
787 if (s->match_length <= s->max_insert_length) {
788 s->match_length--; /* string at strstart already in hash table */
791 INSERT_STRING(s, s->strstart, hash_head);
792 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
793 * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
794 * these bytes are garbage, but it does not matter since
795 * the next lookahead bytes will be emitted as literals.
797 } while (--s->match_length != 0);
800 s->strstart += s->match_length;
802 s->ins_h = s->window[s->strstart];
803 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
805 Call UPDATE_HASH() MIN_MATCH-3 more times
809 /* No match, output a literal byte */
810 Tracevv((stderr,"%c", s->window[s->strstart]));
811 bflush = ct_tally (s, 0, s->window[s->strstart]);
815 if (bflush) FLUSH_BLOCK(s, 0);
817 FLUSH_BLOCK(s, flush == Z_FINISH);
818 return 0; /* normal exit */
821 /* ===========================================================================
822 * Same as above, but achieves better compression. We use a lazy
823 * evaluation for matches: a match is finally adopted only if there is
824 * no better match at the next window position.
826 local int deflate_slow(s, flush)
830 IPos hash_head; /* head of hash chain */
831 int bflush; /* set if current block must be flushed */
833 /* Process the input block. */
835 /* Make sure that we always have enough lookahead, except
836 * at the end of the input file. We need MAX_MATCH bytes
837 * for the next match, plus MIN_MATCH bytes to insert the
838 * string following the next match.
840 if (s->lookahead < MIN_LOOKAHEAD) {
842 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) return 1;
844 if (s->lookahead == 0) break; /* flush the current block */
847 /* Insert the string window[strstart .. strstart+2] in the
848 * dictionary, and set hash_head to the head of the hash chain:
850 INSERT_STRING(s, s->strstart, hash_head);
852 /* Find the longest match, discarding those <= prev_length.
854 s->prev_length = s->match_length, s->prev_match = s->match_start;
855 s->match_length = MIN_MATCH-1;
857 if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
858 s->strstart - hash_head <= MAX_DIST(s)) {
859 /* To simplify the code, we prevent matches with the string
860 * of window index 0 (in particular we have to avoid a match
861 * of the string with itself at the start of the input file).
863 if (s->strategy != Z_HUFFMAN_ONLY) {
864 s->match_length = longest_match (s, hash_head);
866 /* longest_match() sets match_start */
867 if (s->match_length > s->lookahead) s->match_length = s->lookahead;
869 if (s->match_length <= 5 && (s->strategy == Z_FILTERED ||
870 (s->match_length == MIN_MATCH &&
871 s->strstart - s->match_start > TOO_FAR))) {
873 /* If prev_match is also MIN_MATCH, match_start is garbage
874 * but we will ignore the current match anyway.
876 s->match_length = MIN_MATCH-1;
879 /* If there was a match at the previous step and the current
880 * match is not better, output the previous match:
882 if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
884 check_match(s, s->strstart-1, s->prev_match, s->prev_length);
886 bflush = ct_tally(s, s->strstart -1 - s->prev_match,
887 s->prev_length - MIN_MATCH);
889 /* Insert in hash table all strings up to the end of the match.
890 * strstart-1 and strstart are already inserted.
892 s->lookahead -= s->prev_length-1;
896 INSERT_STRING(s, s->strstart, hash_head);
897 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
898 * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
899 * these bytes are garbage, but it does not matter since the
900 * next lookahead bytes will always be emitted as literals.
902 } while (--s->prev_length != 0);
903 s->match_available = 0;
904 s->match_length = MIN_MATCH-1;
907 if (bflush) FLUSH_BLOCK(s, 0);
909 } else if (s->match_available) {
910 /* If there was no match at the previous position, output a
911 * single literal. If there was a match but the current match
912 * is longer, truncate the previous match to a single literal.
914 Tracevv((stderr,"%c", s->window[s->strstart-1]));
915 if (ct_tally (s, 0, s->window[s->strstart-1])) {
916 FLUSH_BLOCK_ONLY(s, 0);
920 if (s->strm->avail_out == 0) return 1;
922 /* There is no previous match to compare with, wait for
923 * the next step to decide.
925 s->match_available = 1;
930 if (s->match_available) ct_tally (s, 0, s->window[s->strstart-1]);
932 FLUSH_BLOCK(s, flush == Z_FINISH);