1 /* deflate.c -- compress data using the deflation algorithm
2 * Copyright (C) 1995-1996 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.8 1995/05/03 17:27:08 jloup Exp $ */
54 char deflate_copyright[] = " deflate 1.0 Copyright 1995-1996 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.
62 /* ===========================================================================
63 * Function prototypes.
65 local void fill_window OF((deflate_state *s));
66 local int deflate_stored OF((deflate_state *s, int flush));
67 local int deflate_fast OF((deflate_state *s, int flush));
68 local int deflate_slow OF((deflate_state *s, int flush));
69 local void lm_init OF((deflate_state *s));
70 local int longest_match OF((deflate_state *s, IPos cur_match));
71 local void putShortMSB OF((deflate_state *s, uInt b));
72 local void flush_pending OF((z_stream *strm));
73 local int read_buf OF((z_stream *strm, charf *buf, unsigned size));
75 void match_init OF((void)); /* asm code initialization */
79 local void check_match OF((deflate_state *s, IPos start, IPos match,
83 /* ===========================================================================
88 /* Tail of hash chains */
93 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
95 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
96 /* Minimum amount of lookahead, except at the end of the input file.
97 * See deflate.c for comments about the MIN_MATCH+1.
100 typedef int (*compress_func) OF((deflate_state *s, int flush));
101 /* Compressing function */
103 /* Values for max_lazy_match, good_match and max_chain_length, depending on
104 * the desired pack level (0..9). The values given below have been tuned to
105 * exclude worst case performance for pathological files. Better values may be
106 * found for specific files.
108 typedef struct config_s {
109 ush good_length; /* reduce lazy search above this match length */
110 ush max_lazy; /* do not perform lazy search above this match length */
111 ush nice_length; /* quit search above this match length */
116 local config configuration_table[10] = {
117 /* good lazy nice chain */
118 /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
119 /* 1 */ {4, 4, 8, 4, deflate_fast}, /* maximum speed, no lazy matches */
120 /* 2 */ {4, 5, 16, 8, deflate_fast},
121 /* 3 */ {4, 6, 32, 32, deflate_fast},
123 /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
124 /* 5 */ {8, 16, 32, 32, deflate_slow},
125 /* 6 */ {8, 16, 128, 128, deflate_slow},
126 /* 7 */ {8, 32, 128, 256, deflate_slow},
127 /* 8 */ {32, 128, 258, 1024, deflate_slow},
128 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* maximum compression */
130 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
131 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
136 /* result of memcmp for equal strings */
138 struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
140 /* ===========================================================================
141 * Update a hash value with the given input byte
142 * IN assertion: all calls to to UPDATE_HASH are made with consecutive
143 * input characters, so that a running hash key can be computed from the
144 * previous key instead of complete recalculation each time.
146 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
149 /* ===========================================================================
150 * Insert string str in the dictionary and set match_head to the previous head
151 * of the hash chain (the most recent string with same hash key). Return
152 * the previous length of the hash chain.
153 * IN assertion: all calls to to INSERT_STRING are made with consecutive
154 * input characters and the first MIN_MATCH bytes of str are valid
155 * (except for the last MIN_MATCH-1 bytes of the input file).
157 #define INSERT_STRING(s, str, match_head) \
158 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
159 s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \
160 s->head[s->ins_h] = (str))
162 /* ===========================================================================
163 * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
164 * prev[] will be initialized on the fly.
166 #define CLEAR_HASH(s) \
167 s->head[s->hash_size-1] = NIL; \
168 zmemzero((charf *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
170 /* ========================================================================= */
171 int deflateInit_(strm, level, version, stream_size)
177 return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
178 Z_DEFAULT_STRATEGY, version, stream_size);
179 /* To do: ignore strm->next_in if we use it as window */
182 /* ========================================================================= */
183 int deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
184 version, stream_size)
197 if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
198 stream_size != sizeof(z_stream)) {
199 return Z_VERSION_ERROR;
201 if (strm == Z_NULL) return Z_STREAM_ERROR;
204 if (strm->zalloc == Z_NULL) {
205 strm->zalloc = zcalloc;
206 strm->opaque = (voidpf)0;
208 if (strm->zfree == Z_NULL) strm->zfree = zcfree;
210 if (level == Z_DEFAULT_COMPRESSION) level = 6;
212 if (windowBits < 0) { /* undocumented feature: suppress zlib header */
214 windowBits = -windowBits;
216 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
217 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
218 strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
219 return Z_STREAM_ERROR;
221 s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
222 if (s == Z_NULL) return Z_MEM_ERROR;
223 strm->state = (struct internal_state FAR *)s;
226 s->noheader = noheader;
227 s->w_bits = windowBits;
228 s->w_size = 1 << s->w_bits;
229 s->w_mask = s->w_size - 1;
231 s->hash_bits = memLevel + 7;
232 s->hash_size = 1 << s->hash_bits;
233 s->hash_mask = s->hash_size - 1;
234 s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
236 s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
237 s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
238 s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
240 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
242 s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, 2*sizeof(ush));
244 if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
245 s->pending_buf == Z_NULL) {
246 strm->msg = ERR_MSG(Z_MEM_ERROR);
250 s->l_buf = (uchf *) &(s->pending_buf[s->lit_bufsize]);
251 s->d_buf = (ushf *) &(s->pending_buf[2*s->lit_bufsize]);
252 /* We overlay pending_buf and d_buf+l_buf. This works since the average
253 * output size for (length,distance) codes is <= 32 bits (worst case
254 * is 15+15+13=33). d_buf is put last in case sizeof(short)>2.
258 s->strategy = strategy;
259 s->method = (Byte)method;
261 return deflateReset(strm);
264 /* ========================================================================= */
265 int deflateSetDictionary (strm, dictionary, dictLength)
267 const Bytef *dictionary;
271 uInt length = dictLength;
275 if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
276 strm->state->status != INIT_STATE) return Z_STREAM_ERROR;
279 strm->adler = adler32(strm->adler, dictionary, dictLength);
281 if (length < MIN_MATCH) return Z_OK;
282 if (length > MAX_DIST(s)) {
283 length = MAX_DIST(s);
284 dictionary += dictLength - length;
286 zmemcpy((charf *)s->window, dictionary, length);
287 s->strstart = length;
288 s->block_start = (long)length;
290 /* Insert all strings in the hash table (except for the last two bytes).
291 * s->lookahead stays null, so s->ins_h will be recomputed at the next
292 * call of fill_window.
294 s->ins_h = s->window[0];
295 UPDATE_HASH(s, s->ins_h, s->window[1]);
296 for (n = 0; n <= length - MIN_MATCH; n++) {
297 INSERT_STRING(s, n, hash_head);
302 /* ========================================================================= */
303 int deflateReset (strm)
308 if (strm == Z_NULL || strm->state == Z_NULL ||
309 strm->zalloc == Z_NULL || strm->zfree == Z_NULL) return Z_STREAM_ERROR;
311 strm->total_in = strm->total_out = 0;
312 strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
313 strm->data_type = Z_UNKNOWN;
315 s = (deflate_state *)strm->state;
317 s->pending_out = s->pending_buf;
319 if (s->noheader < 0) {
320 s->noheader = 0; /* was set to -1 by deflate(..., Z_FINISH); */
322 s->status = s->noheader ? BUSY_STATE : INIT_STATE;
324 s->last_flush = Z_NO_FLUSH;
332 /* ========================================================================= */
333 int deflateParams(strm, level, strategy)
341 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
344 if (level == Z_DEFAULT_COMPRESSION) {
347 if (level < 0 || level > 9 || strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
348 return Z_STREAM_ERROR;
350 func = configuration_table[s->level].func;
352 if (func != configuration_table[level].func
353 && strm->state->lookahead != 0) {
355 /* Flush the last buffer: */
356 (void)(*func)(strm->state, Z_PARTIAL_FLUSH);
358 if (s->level != level) {
360 s->max_lazy_match = configuration_table[level].max_lazy;
361 s->good_match = configuration_table[level].good_length;
362 s->nice_match = configuration_table[level].nice_length;
363 s->max_chain_length = configuration_table[level].max_chain;
365 s->strategy = strategy;
369 /* =========================================================================
370 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
371 * IN assertion: the stream state is correct and there is enough room in
374 local void putShortMSB (s, b)
378 put_byte(s, (Byte)(b >> 8));
379 put_byte(s, (Byte)(b & 0xff));
382 /* =========================================================================
383 * Flush as much pending output as possible. All deflate() output goes
384 * through this function so some applications may wish to modify it
385 * to avoid allocating a large strm->next_out buffer and copying into it.
386 * (See also read_buf()).
388 local void flush_pending(strm)
391 unsigned len = strm->state->pending;
393 if (len > strm->avail_out) len = strm->avail_out;
394 if (len == 0) return;
396 zmemcpy(strm->next_out, strm->state->pending_out, len);
397 strm->next_out += len;
398 strm->state->pending_out += len;
399 strm->total_out += len;
400 strm->avail_out -= len;
401 strm->state->pending -= len;
402 if (strm->state->pending == 0) {
403 strm->state->pending_out = strm->state->pending_buf;
407 /* ========================================================================= */
408 int deflate (strm, flush)
412 int old_flush; /* value of flush param for previous deflate call */
415 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
419 if (strm->next_out == Z_NULL ||
420 (strm->next_in == Z_NULL && strm->avail_in != 0) ||
421 (s->status == FINISH_STATE && flush != Z_FINISH)) {
422 ERR_RETURN(strm, Z_STREAM_ERROR);
424 if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
426 s->strm = strm; /* just in case */
427 old_flush = s->last_flush;
428 s->last_flush = flush;
430 /* Write the zlib header */
431 if (s->status == INIT_STATE) {
433 uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
434 uInt level_flags = (s->level-1) >> 1;
436 if (level_flags > 3) level_flags = 3;
437 header |= (level_flags << 6);
438 if (s->strstart != 0) header |= PRESET_DICT;
439 header += 31 - (header % 31);
441 s->status = BUSY_STATE;
442 putShortMSB(s, header);
444 /* Save the adler32 of the preset dictionary: */
445 if (s->strstart != 0) {
446 putShortMSB(s, (uInt)(strm->adler >> 16));
447 putShortMSB(s, (uInt)(strm->adler & 0xffff));
452 /* Flush as much pending output as possible */
453 if (s->pending != 0) {
455 if (strm->avail_out == 0) return Z_OK;
457 /* Make sure there is something to do and avoid duplicate consecutive
458 * flushes. For repeated and useless calls with Z_FINISH, we keep
459 * returning Z_STREAM_END instead of Z_BUFF_ERROR.
461 } else if (strm->avail_in == 0 && flush <= old_flush &&
463 ERR_RETURN(strm, Z_BUF_ERROR);
466 /* User must not provide more input after the first FINISH: */
467 if (s->status == FINISH_STATE && strm->avail_in != 0) {
468 ERR_RETURN(strm, Z_BUF_ERROR);
471 /* Start a new block or continue the current one.
473 if (strm->avail_in != 0 || s->lookahead != 0 ||
474 (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
477 if (flush == Z_FINISH) {
478 s->status = FINISH_STATE;
480 quit = (*(configuration_table[s->level].func))(s, flush);
482 if (quit || strm->avail_out == 0) return Z_OK;
483 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
484 * of deflate should use the same flush parameter to make sure
485 * that the flush is complete. So we don't have to output an
486 * empty block here, this will be done at next call. This also
487 * ensures that for a very small output buffer, we emit at most
490 if (flush != Z_NO_FLUSH && flush != Z_FINISH) {
491 if (flush == Z_PARTIAL_FLUSH) {
493 } else { /* FULL_FLUSH or SYNC_FLUSH */
494 _tr_stored_block(s, (char*)0, 0L, 0);
495 /* For a full flush, this empty block will be recognized
496 * as a special marker by inflate_sync().
498 if (flush == Z_FULL_FLUSH) {
499 CLEAR_HASH(s); /* forget history */
503 if (strm->avail_out == 0) return Z_OK;
506 Assert(strm->avail_out > 0, "bug2");
508 if (flush != Z_FINISH) return Z_OK;
509 if (s->noheader) return Z_STREAM_END;
511 /* Write the zlib trailer (adler32) */
512 putShortMSB(s, (uInt)(strm->adler >> 16));
513 putShortMSB(s, (uInt)(strm->adler & 0xffff));
515 /* If avail_out is zero, the application will call deflate again
518 s->noheader = -1; /* write the trailer only once! */
519 return s->pending != 0 ? Z_OK : Z_STREAM_END;
522 /* ========================================================================= */
523 int deflateEnd (strm)
528 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
530 /* Deallocate in reverse order of allocations: */
531 TRY_FREE(strm, strm->state->pending_buf);
532 TRY_FREE(strm, strm->state->head);
533 TRY_FREE(strm, strm->state->prev);
534 TRY_FREE(strm, strm->state->window);
536 status = strm->state->status;
537 ZFREE(strm, strm->state);
538 strm->state = Z_NULL;
540 return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
543 /* ========================================================================= */
544 int deflateCopy (dest, source)
548 if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
549 return Z_STREAM_ERROR;
552 return Z_STREAM_ERROR; /* to be implemented */
554 dest->state = (struct internal_state FAR *)
555 (*dest->zalloc)(1, sizeof(deflate_state));
556 if (dest->state == Z_NULL) return Z_MEM_ERROR;
558 *(dest->state) = *(source->state);
563 /* ===========================================================================
564 * Read a new buffer from the current input stream, update the adler32
565 * and total number of bytes read. All deflate() input goes through
566 * this function so some applications may wish to modify it to avoid
567 * allocating a large strm->next_in buffer and copying from it.
568 * (See also flush_pending()).
570 local int read_buf(strm, buf, size)
575 unsigned len = strm->avail_in;
577 if (len > size) len = size;
578 if (len == 0) return 0;
580 strm->avail_in -= len;
582 if (!strm->state->noheader) {
583 strm->adler = adler32(strm->adler, strm->next_in, len);
585 zmemcpy(buf, strm->next_in, len);
586 strm->next_in += len;
587 strm->total_in += len;
592 /* ===========================================================================
593 * Initialize the "longest match" routines for a new zlib stream
595 local void lm_init (s)
598 s->window_size = (ulg)2L*s->w_size;
602 /* Set the default configuration parameters:
604 s->max_lazy_match = configuration_table[s->level].max_lazy;
605 s->good_match = configuration_table[s->level].good_length;
606 s->nice_match = configuration_table[s->level].nice_length;
607 s->max_chain_length = configuration_table[s->level].max_chain;
612 s->match_length = s->prev_length = MIN_MATCH-1;
613 s->match_available = 0;
616 match_init(); /* initialize the asm code */
620 /* ===========================================================================
621 * Set match_start to the longest match starting at the given string and
622 * return its length. Matches shorter or equal to prev_length are discarded,
623 * in which case the result is equal to prev_length and match_start is
625 * IN assertions: cur_match is the head of the hash chain for the current
626 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
627 * OUT assertion: the match length is not greater than s->lookahead.
630 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
631 * match.S. The code will be functionally equivalent.
633 local int longest_match(s, cur_match)
635 IPos cur_match; /* current match */
637 unsigned chain_length = s->max_chain_length;/* max hash chain length */
638 register Bytef *scan = s->window + s->strstart; /* current string */
639 register Bytef *match; /* matched string */
640 register int len; /* length of current match */
641 int best_len = s->prev_length; /* best match length so far */
642 int nice_match = s->nice_match; /* stop if match long enough */
643 IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
644 s->strstart - (IPos)MAX_DIST(s) : NIL;
645 /* Stop when cur_match becomes <= limit. To simplify the code,
646 * we prevent matches with the string of window index 0.
648 Posf *prev = s->prev;
649 uInt wmask = s->w_mask;
652 /* Compare two bytes at a time. Note: this is not always beneficial.
653 * Try with and without -DUNALIGNED_OK to check.
655 register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
656 register ush scan_start = *(ushf*)scan;
657 register ush scan_end = *(ushf*)(scan+best_len-1);
659 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
660 register Byte scan_end1 = scan[best_len-1];
661 register Byte scan_end = scan[best_len];
664 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
665 * It is easy to get rid of this optimization if necessary.
667 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
669 /* Do not waste too much time if we already have a good match: */
670 if (s->prev_length >= s->good_match) {
673 /* Do not look for matches beyond the end of the input. This is necessary
674 * to make deflate deterministic.
676 if (nice_match > s->lookahead) nice_match = s->lookahead;
678 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
681 Assert(cur_match < s->strstart, "no future");
682 match = s->window + cur_match;
684 /* Skip to next match if the match length cannot increase
685 * or if the match length is less than 2:
687 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
688 /* This code assumes sizeof(unsigned short) == 2. Do not use
689 * UNALIGNED_OK if your compiler uses a different size.
691 if (*(ushf*)(match+best_len-1) != scan_end ||
692 *(ushf*)match != scan_start) continue;
694 /* It is not necessary to compare scan[2] and match[2] since they are
695 * always equal when the other bytes match, given that the hash keys
696 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
697 * strstart+3, +5, ... up to strstart+257. We check for insufficient
698 * lookahead only every 4th comparison; the 128th check will be made
699 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
700 * necessary to put more guard bytes at the end of the window, or
701 * to check more often for insufficient lookahead.
703 Assert(scan[2] == match[2], "scan[2]?");
706 } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
707 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
708 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
709 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
711 /* The funny "do {}" generates better code on most compilers */
713 /* Here, scan <= window+strstart+257 */
714 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
715 if (*scan == *match) scan++;
717 len = (MAX_MATCH - 1) - (int)(strend-scan);
718 scan = strend - (MAX_MATCH-1);
720 #else /* UNALIGNED_OK */
722 if (match[best_len] != scan_end ||
723 match[best_len-1] != scan_end1 ||
725 *++match != scan[1]) continue;
727 /* The check at best_len-1 can be removed because it will be made
728 * again later. (This heuristic is not always a win.)
729 * It is not necessary to compare scan[2] and match[2] since they
730 * are always equal when the other bytes match, given that
731 * the hash keys are equal and that HASH_BITS >= 8.
734 Assert(*scan == *match, "match[2]?");
736 /* We check for insufficient lookahead only every 8th comparison;
737 * the 256th check will be made at strstart+258.
740 } while (*++scan == *++match && *++scan == *++match &&
741 *++scan == *++match && *++scan == *++match &&
742 *++scan == *++match && *++scan == *++match &&
743 *++scan == *++match && *++scan == *++match &&
746 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
748 len = MAX_MATCH - (int)(strend - scan);
749 scan = strend - MAX_MATCH;
751 #endif /* UNALIGNED_OK */
753 if (len > best_len) {
754 s->match_start = cur_match;
756 if (len >= nice_match) break;
758 scan_end = *(ushf*)(scan+best_len-1);
760 scan_end1 = scan[best_len-1];
761 scan_end = scan[best_len];
764 } while ((cur_match = prev[cur_match & wmask]) > limit
765 && --chain_length != 0);
767 if (best_len <= s->lookahead) return best_len;
773 /* ===========================================================================
774 * Check that the match at match_start is indeed a match.
776 local void check_match(s, start, match, length)
781 /* check that the match is indeed a match */
782 if (zmemcmp((charf *)s->window + match,
783 (charf *)s->window + start, length) != EQUAL) {
784 fprintf(stderr, " start %u, match %u, length %d\n",
785 start, match, length);
787 fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
788 } while (--length != 0);
789 z_error("invalid match");
792 fprintf(stderr,"\\[%d,%d]", start-match, length);
793 do { putc(s->window[start++], stderr); } while (--length != 0);
797 # define check_match(s, start, match, length)
800 /* ===========================================================================
801 * Fill the window when the lookahead becomes insufficient.
802 * Updates strstart and lookahead.
804 * IN assertion: lookahead < MIN_LOOKAHEAD
805 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
806 * At least one byte has been read, or avail_in == 0; reads are
807 * performed for at least two bytes (required for the zip translate_eol
808 * option -- not supported here).
810 local void fill_window(s)
813 register unsigned n, m;
815 unsigned more; /* Amount of free space at the end of the window. */
816 uInt wsize = s->w_size;
819 more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
821 /* Deal with !@#$% 64K limit: */
822 if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
825 } else if (more == (unsigned)(-1)) {
826 /* Very unlikely, but possible on 16 bit machine if strstart == 0
827 * and lookahead == 1 (input done one byte at time)
831 /* If the window is almost full and there is insufficient lookahead,
832 * move the upper half to the lower one to make room in the upper half.
834 } else if (s->strstart >= wsize+MAX_DIST(s)) {
836 zmemcpy((charf *)s->window, (charf *)s->window+wsize,
838 s->match_start -= wsize;
839 s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
841 s->block_start -= (long) wsize;
843 /* Slide the hash table (could be avoided with 32 bit values
844 at the expense of memory usage):
850 *p = (Pos)(m >= wsize ? m-wsize : NIL);
857 *p = (Pos)(m >= wsize ? m-wsize : NIL);
858 /* If n is not on any hash chain, prev[n] is garbage but
859 * its value will never be used.
865 if (s->strm->avail_in == 0) return;
867 /* If there was no sliding:
868 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
869 * more == window_size - lookahead - strstart
870 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
871 * => more >= window_size - 2*WSIZE + 2
872 * In the BIG_MEM or MMAP case (not yet supported),
873 * window_size == input_size + MIN_LOOKAHEAD &&
874 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
875 * Otherwise, window_size == 2*WSIZE so more >= 2.
876 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
878 Assert(more >= 2, "more < 2");
880 n = read_buf(s->strm, (charf *)s->window + s->strstart + s->lookahead,
884 /* Initialize the hash value now that we have some input: */
885 if (s->lookahead >= MIN_MATCH) {
886 s->ins_h = s->window[s->strstart];
887 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
889 Call UPDATE_HASH() MIN_MATCH-3 more times
892 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
893 * but this is not important since only literal bytes will be emitted.
896 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
899 /* ===========================================================================
900 * Flush the current block, with given end-of-file flag.
901 * IN assertion: strstart is set to the end of the current match.
903 #define FLUSH_BLOCK_ONLY(s, eof) { \
904 _tr_flush_block(s, (s->block_start >= 0L ? \
905 (charf *)&s->window[(unsigned)s->block_start] : \
907 (ulg)((long)s->strstart - s->block_start), \
909 s->block_start = s->strstart; \
910 flush_pending(s->strm); \
911 Tracev((stderr,"[FLUSH]")); \
914 /* Same but force premature exit if necessary. */
915 #define FLUSH_BLOCK(s, eof) { \
916 FLUSH_BLOCK_ONLY(s, eof); \
917 if (s->strm->avail_out == 0) return 1; \
920 /* ===========================================================================
921 * Copy without compression as much as possible from the input stream, return
922 * true if processing was terminated prematurely (no more input or output
923 * space). This function does not insert new strings in the dictionary
924 * since uncompressible data is probably not useful. This function is used
925 * only for the level=0 compression option.
926 * NOTE: this function should be optimized to avoid extra copying.
928 local int deflate_stored(s, flush)
933 /* Fill the window as much as possible: */
934 if (s->lookahead <= 1) {
936 Assert(s->strstart < s->w_size+MAX_DIST(s) ||
937 s->block_start >= (long)s->w_size, "slide too late");
940 if (s->lookahead == 0 && flush == Z_NO_FLUSH) return 1;
942 if (s->lookahead == 0) break; /* flush the current block */
944 Assert(s->block_start >= 0L, "block gone");
946 s->strstart += s->lookahead;
949 /* Stored blocks are limited to 0xffff bytes: */
950 if (s->strstart == 0 || s->strstart > 0xffff) {
951 /* strstart == 0 is possible when wraparound on 16-bit machine */
952 s->lookahead = s->strstart - 0xffff;
953 s->strstart = 0xffff;
956 /* Emit a stored block if it is large enough: */
957 if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
961 FLUSH_BLOCK(s, flush == Z_FINISH);
962 return 0; /* normal exit */
965 /* ===========================================================================
966 * Compress as much as possible from the input stream, return true if
967 * processing was terminated prematurely (no more input or output space).
968 * This function does not perform lazy evaluation of matches and inserts
969 * new strings in the dictionary only for unmatched strings or for short
970 * matches. It is used only for the fast compression options.
972 local int deflate_fast(s, flush)
976 IPos hash_head = NIL; /* head of the hash chain */
977 int bflush; /* set if current block must be flushed */
980 /* Make sure that we always have enough lookahead, except
981 * at the end of the input file. We need MAX_MATCH bytes
982 * for the next match, plus MIN_MATCH bytes to insert the
983 * string following the next match.
985 if (s->lookahead < MIN_LOOKAHEAD) {
987 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) return 1;
989 if (s->lookahead == 0) break; /* flush the current block */
992 /* Insert the string window[strstart .. strstart+2] in the
993 * dictionary, and set hash_head to the head of the hash chain:
995 if (s->lookahead >= MIN_MATCH) {
996 INSERT_STRING(s, s->strstart, hash_head);
999 /* Find the longest match, discarding those <= prev_length.
1000 * At this point we have always match_length < MIN_MATCH
1002 if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1003 /* To simplify the code, we prevent matches with the string
1004 * of window index 0 (in particular we have to avoid a match
1005 * of the string with itself at the start of the input file).
1007 if (s->strategy != Z_HUFFMAN_ONLY) {
1008 s->match_length = longest_match (s, hash_head);
1010 /* longest_match() sets match_start */
1012 if (s->match_length >= MIN_MATCH) {
1013 check_match(s, s->strstart, s->match_start, s->match_length);
1015 bflush = _tr_tally(s, s->strstart - s->match_start,
1016 s->match_length - MIN_MATCH);
1018 s->lookahead -= s->match_length;
1020 /* Insert new strings in the hash table only if the match length
1021 * is not too large. This saves time but degrades compression.
1023 if (s->match_length <= s->max_insert_length &&
1024 s->lookahead >= MIN_MATCH) {
1025 s->match_length--; /* string at strstart already in hash table */
1028 INSERT_STRING(s, s->strstart, hash_head);
1029 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1030 * always MIN_MATCH bytes ahead.
1032 } while (--s->match_length != 0);
1035 s->strstart += s->match_length;
1036 s->match_length = 0;
1037 s->ins_h = s->window[s->strstart];
1038 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1040 Call UPDATE_HASH() MIN_MATCH-3 more times
1042 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1043 * matter since it will be recomputed at next deflate call.
1047 /* No match, output a literal byte */
1048 Tracevv((stderr,"%c", s->window[s->strstart]));
1049 bflush = _tr_tally (s, 0, s->window[s->strstart]);
1053 if (bflush) FLUSH_BLOCK(s, 0);
1055 FLUSH_BLOCK(s, flush == Z_FINISH);
1056 return 0; /* normal exit */
1059 /* ===========================================================================
1060 * Same as above, but achieves better compression. We use a lazy
1061 * evaluation for matches: a match is finally adopted only if there is
1062 * no better match at the next window position.
1064 local int deflate_slow(s, flush)
1068 IPos hash_head = NIL; /* head of hash chain */
1069 int bflush; /* set if current block must be flushed */
1071 /* Process the input block. */
1073 /* Make sure that we always have enough lookahead, except
1074 * at the end of the input file. We need MAX_MATCH bytes
1075 * for the next match, plus MIN_MATCH bytes to insert the
1076 * string following the next match.
1078 if (s->lookahead < MIN_LOOKAHEAD) {
1080 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) return 1;
1082 if (s->lookahead == 0) break; /* flush the current block */
1085 /* Insert the string window[strstart .. strstart+2] in the
1086 * dictionary, and set hash_head to the head of the hash chain:
1088 if (s->lookahead >= MIN_MATCH) {
1089 INSERT_STRING(s, s->strstart, hash_head);
1092 /* Find the longest match, discarding those <= prev_length.
1094 s->prev_length = s->match_length, s->prev_match = s->match_start;
1095 s->match_length = MIN_MATCH-1;
1097 if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
1098 s->strstart - hash_head <= MAX_DIST(s)) {
1099 /* To simplify the code, we prevent matches with the string
1100 * of window index 0 (in particular we have to avoid a match
1101 * of the string with itself at the start of the input file).
1103 if (s->strategy != Z_HUFFMAN_ONLY) {
1104 s->match_length = longest_match (s, hash_head);
1106 /* longest_match() sets match_start */
1108 if (s->match_length <= 5 && (s->strategy == Z_FILTERED ||
1109 (s->match_length == MIN_MATCH &&
1110 s->strstart - s->match_start > TOO_FAR))) {
1112 /* If prev_match is also MIN_MATCH, match_start is garbage
1113 * but we will ignore the current match anyway.
1115 s->match_length = MIN_MATCH-1;
1118 /* If there was a match at the previous step and the current
1119 * match is not better, output the previous match:
1121 if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
1122 uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
1123 /* Do not insert strings in hash table beyond this. */
1125 check_match(s, s->strstart-1, s->prev_match, s->prev_length);
1127 bflush = _tr_tally(s, s->strstart -1 - s->prev_match,
1128 s->prev_length - MIN_MATCH);
1130 /* Insert in hash table all strings up to the end of the match.
1131 * strstart-1 and strstart are already inserted. If there is not
1132 * enough lookahead, the last two strings are not inserted in
1135 s->lookahead -= s->prev_length-1;
1136 s->prev_length -= 2;
1138 if (++s->strstart <= max_insert) {
1139 INSERT_STRING(s, s->strstart, hash_head);
1141 } while (--s->prev_length != 0);
1142 s->match_available = 0;
1143 s->match_length = MIN_MATCH-1;
1146 if (bflush) FLUSH_BLOCK(s, 0);
1148 } else if (s->match_available) {
1149 /* If there was no match at the previous position, output a
1150 * single literal. If there was a match but the current match
1151 * is longer, truncate the previous match to a single literal.
1153 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1154 if (_tr_tally (s, 0, s->window[s->strstart-1])) {
1155 FLUSH_BLOCK_ONLY(s, 0);
1159 if (s->strm->avail_out == 0) return 1;
1161 /* There is no previous match to compare with, wait for
1162 * the next step to decide.
1164 s->match_available = 1;
1169 Assert (flush != Z_NO_FLUSH, "no flush?");
1170 if (s->match_available) {
1171 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1172 _tr_tally (s, 0, s->window[s->strstart-1]);
1173 s->match_available = 0;
1175 FLUSH_BLOCK(s, flush == Z_FINISH);