Adding upstream version 3.20.
[syslinux-debian/hramrach.git] / com32 / lib / zlib / deflate.c
blobfeb1d16ffc814600901e293bd4873930a244d9f5
1 /* deflate.c -- compress data using the deflation algorithm
2 * Copyright (C) 1995-2003 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
6 /*
7 * ALGORITHM
9 * The "deflation" process depends on being able to identify portions
10 * of the input text which are identical to earlier input (within a
11 * sliding window trailing behind the input currently being processed).
13 * The most straightforward technique turns out to be the fastest for
14 * most input files: try all possible matches and select the longest.
15 * The key feature of this algorithm is that insertions into the string
16 * dictionary are very simple and thus fast, and deletions are avoided
17 * completely. Insertions are performed at each input character, whereas
18 * string matches are performed only when the previous match ends. So it
19 * is preferable to spend more time in matches to allow very fast string
20 * insertions and avoid deletions. The matching algorithm for small
21 * strings is inspired from that of Rabin & Karp. A brute force approach
22 * is used to find longer strings when a small match has been found.
23 * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
24 * (by Leonid Broukhis).
25 * A previous version of this file used a more sophisticated algorithm
26 * (by Fiala and Greene) which is guaranteed to run in linear amortized
27 * time, but has a larger average cost, uses more memory and is patented.
28 * However the F&G algorithm may be faster for some highly redundant
29 * files if the parameter max_chain_length (described below) is too large.
31 * ACKNOWLEDGEMENTS
33 * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
34 * I found it in 'freeze' written by Leonid Broukhis.
35 * Thanks to many people for bug reports and testing.
37 * REFERENCES
39 * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
40 * Available in http://www.ietf.org/rfc/rfc1951.txt
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
51 #include "deflate.h"
53 const char deflate_copyright[] =
54 " deflate 1.2.1 Copyright 1995-2003 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 typedef enum {
66 need_more, /* block not completed, need more input or more output */
67 block_done, /* block flush performed */
68 finish_started, /* finish started, need only more output at next deflate */
69 finish_done /* finish done, accept no more input or output */
70 } block_state;
72 typedef block_state (*compress_func) OF((deflate_state *s, int flush));
73 /* Compression function. Returns the block state after the call. */
75 local void fill_window OF((deflate_state *s));
76 local block_state deflate_stored OF((deflate_state *s, int flush));
77 local block_state deflate_fast OF((deflate_state *s, int flush));
78 #ifndef FASTEST
79 local block_state deflate_slow OF((deflate_state *s, int flush));
80 #endif
81 local void lm_init OF((deflate_state *s));
82 local void putShortMSB OF((deflate_state *s, uInt b));
83 local void flush_pending OF((z_streamp strm));
84 local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
85 #ifndef FASTEST
86 #ifdef ASMV
87 void match_init OF((void)); /* asm code initialization */
88 uInt longest_match OF((deflate_state *s, IPos cur_match));
89 #else
90 local uInt longest_match OF((deflate_state *s, IPos cur_match));
91 #endif
92 #endif
93 local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
95 #ifdef DEBUG
96 local void check_match OF((deflate_state *s, IPos start, IPos match,
97 int length));
98 #endif
100 /* ===========================================================================
101 * Local data
104 #define NIL 0
105 /* Tail of hash chains */
107 #ifndef TOO_FAR
108 # define TOO_FAR 4096
109 #endif
110 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
112 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
113 /* Minimum amount of lookahead, except at the end of the input file.
114 * See deflate.c for comments about the MIN_MATCH+1.
117 /* Values for max_lazy_match, good_match and max_chain_length, depending on
118 * the desired pack level (0..9). The values given below have been tuned to
119 * exclude worst case performance for pathological files. Better values may be
120 * found for specific files.
122 typedef struct config_s {
123 ush good_length; /* reduce lazy search above this match length */
124 ush max_lazy; /* do not perform lazy search above this match length */
125 ush nice_length; /* quit search above this match length */
126 ush max_chain;
127 compress_func func;
128 } config;
130 #ifdef FASTEST
131 local const config configuration_table[2] = {
132 /* good lazy nice chain */
133 /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
134 /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
135 #else
136 local const config configuration_table[10] = {
137 /* good lazy nice chain */
138 /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
139 /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
140 /* 2 */ {4, 5, 16, 8, deflate_fast},
141 /* 3 */ {4, 6, 32, 32, deflate_fast},
143 /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
144 /* 5 */ {8, 16, 32, 32, deflate_slow},
145 /* 6 */ {8, 16, 128, 128, deflate_slow},
146 /* 7 */ {8, 32, 128, 256, deflate_slow},
147 /* 8 */ {32, 128, 258, 1024, deflate_slow},
148 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
149 #endif
151 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
152 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
153 * meaning.
156 #define EQUAL 0
157 /* result of memcmp for equal strings */
159 #ifndef NO_DUMMY_DECL
160 struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
161 #endif
163 /* ===========================================================================
164 * Update a hash value with the given input byte
165 * IN assertion: all calls to to UPDATE_HASH are made with consecutive
166 * input characters, so that a running hash key can be computed from the
167 * previous key instead of complete recalculation each time.
169 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
172 /* ===========================================================================
173 * Insert string str in the dictionary and set match_head to the previous head
174 * of the hash chain (the most recent string with same hash key). Return
175 * the previous length of the hash chain.
176 * If this file is compiled with -DFASTEST, the compression level is forced
177 * to 1, and no hash chains are maintained.
178 * IN assertion: all calls to to INSERT_STRING are made with consecutive
179 * input characters and the first MIN_MATCH bytes of str are valid
180 * (except for the last MIN_MATCH-1 bytes of the input file).
182 #ifdef FASTEST
183 #define INSERT_STRING(s, str, match_head) \
184 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
185 match_head = s->head[s->ins_h], \
186 s->head[s->ins_h] = (Pos)(str))
187 #else
188 #define INSERT_STRING(s, str, match_head) \
189 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
190 match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
191 s->head[s->ins_h] = (Pos)(str))
192 #endif
194 /* ===========================================================================
195 * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
196 * prev[] will be initialized on the fly.
198 #define CLEAR_HASH(s) \
199 s->head[s->hash_size-1] = NIL; \
200 zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
202 /* ========================================================================= */
203 int ZEXPORT deflateInit_(strm, level, version, stream_size)
204 z_streamp strm;
205 int level;
206 const char *version;
207 int stream_size;
209 return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
210 Z_DEFAULT_STRATEGY, version, stream_size);
211 /* To do: ignore strm->next_in if we use it as window */
214 /* ========================================================================= */
215 int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
216 version, stream_size)
217 z_streamp strm;
218 int level;
219 int method;
220 int windowBits;
221 int memLevel;
222 int strategy;
223 const char *version;
224 int stream_size;
226 deflate_state *s;
227 int wrap = 1;
228 static const char my_version[] = ZLIB_VERSION;
230 ushf *overlay;
231 /* We overlay pending_buf and d_buf+l_buf. This works since the average
232 * output size for (length,distance) codes is <= 24 bits.
235 if (version == Z_NULL || version[0] != my_version[0] ||
236 stream_size != sizeof(z_stream)) {
237 return Z_VERSION_ERROR;
239 if (strm == Z_NULL) return Z_STREAM_ERROR;
241 strm->msg = Z_NULL;
242 if (strm->zalloc == (alloc_func)0) {
243 strm->zalloc = zcalloc;
244 strm->opaque = (voidpf)0;
246 if (strm->zfree == (free_func)0) strm->zfree = zcfree;
248 #ifdef FASTEST
249 if (level != 0) level = 1;
250 #else
251 if (level == Z_DEFAULT_COMPRESSION) level = 6;
252 #endif
254 if (windowBits < 0) { /* suppress zlib wrapper */
255 wrap = 0;
256 windowBits = -windowBits;
258 #ifdef GZIP
259 else if (windowBits > 15) {
260 wrap = 2; /* write gzip wrapper instead */
261 windowBits -= 16;
263 #endif
264 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
265 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
266 strategy < 0 || strategy > Z_RLE) {
267 return Z_STREAM_ERROR;
269 if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
270 s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
271 if (s == Z_NULL) return Z_MEM_ERROR;
272 strm->state = (struct internal_state FAR *)s;
273 s->strm = strm;
275 s->wrap = wrap;
276 s->w_bits = windowBits;
277 s->w_size = 1 << s->w_bits;
278 s->w_mask = s->w_size - 1;
280 s->hash_bits = memLevel + 7;
281 s->hash_size = 1 << s->hash_bits;
282 s->hash_mask = s->hash_size - 1;
283 s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
285 s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
286 s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
287 s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
289 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
291 overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
292 s->pending_buf = (uchf *) overlay;
293 s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
295 if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
296 s->pending_buf == Z_NULL) {
297 s->status = FINISH_STATE;
298 strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
299 deflateEnd (strm);
300 return Z_MEM_ERROR;
302 s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
303 s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
305 s->level = level;
306 s->strategy = strategy;
307 s->method = (Byte)method;
309 return deflateReset(strm);
312 /* ========================================================================= */
313 int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
314 z_streamp strm;
315 const Bytef *dictionary;
316 uInt dictLength;
318 deflate_state *s;
319 uInt length = dictLength;
320 uInt n;
321 IPos hash_head = 0;
323 if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
324 strm->state->wrap == 2 ||
325 (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
326 return Z_STREAM_ERROR;
328 s = strm->state;
329 if (s->wrap)
330 strm->adler = adler32(strm->adler, dictionary, dictLength);
332 if (length < MIN_MATCH) return Z_OK;
333 if (length > MAX_DIST(s)) {
334 length = MAX_DIST(s);
335 #ifndef USE_DICT_HEAD
336 dictionary += dictLength - length; /* use the tail of the dictionary */
337 #endif
339 zmemcpy(s->window, dictionary, length);
340 s->strstart = length;
341 s->block_start = (long)length;
343 /* Insert all strings in the hash table (except for the last two bytes).
344 * s->lookahead stays null, so s->ins_h will be recomputed at the next
345 * call of fill_window.
347 s->ins_h = s->window[0];
348 UPDATE_HASH(s, s->ins_h, s->window[1]);
349 for (n = 0; n <= length - MIN_MATCH; n++) {
350 INSERT_STRING(s, n, hash_head);
352 if (hash_head) hash_head = 0; /* to make compiler happy */
353 return Z_OK;
356 /* ========================================================================= */
357 int ZEXPORT deflateReset (strm)
358 z_streamp strm;
360 deflate_state *s;
362 if (strm == Z_NULL || strm->state == Z_NULL ||
363 strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
364 return Z_STREAM_ERROR;
367 strm->total_in = strm->total_out = 0;
368 strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
369 strm->data_type = Z_UNKNOWN;
371 s = (deflate_state *)strm->state;
372 s->pending = 0;
373 s->pending_out = s->pending_buf;
375 if (s->wrap < 0) {
376 s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
378 s->status = s->wrap ? INIT_STATE : BUSY_STATE;
379 strm->adler =
380 #ifdef GZIP
381 s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
382 #endif
383 adler32(0L, Z_NULL, 0);
384 s->last_flush = Z_NO_FLUSH;
386 _tr_init(s);
387 lm_init(s);
389 return Z_OK;
392 /* ========================================================================= */
393 int ZEXPORT deflatePrime (strm, bits, value)
394 z_streamp strm;
395 int bits;
396 int value;
398 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
399 strm->state->bi_valid = bits;
400 strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
401 return Z_OK;
404 /* ========================================================================= */
405 int ZEXPORT deflateParams(strm, level, strategy)
406 z_streamp strm;
407 int level;
408 int strategy;
410 deflate_state *s;
411 compress_func func;
412 int err = Z_OK;
414 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
415 s = strm->state;
417 #ifdef FASTEST
418 if (level != 0) level = 1;
419 #else
420 if (level == Z_DEFAULT_COMPRESSION) level = 6;
421 #endif
422 if (level < 0 || level > 9 || strategy < 0 || strategy > Z_RLE) {
423 return Z_STREAM_ERROR;
425 func = configuration_table[s->level].func;
427 if (func != configuration_table[level].func && strm->total_in != 0) {
428 /* Flush the last buffer: */
429 err = deflate(strm, Z_PARTIAL_FLUSH);
431 if (s->level != level) {
432 s->level = level;
433 s->max_lazy_match = configuration_table[level].max_lazy;
434 s->good_match = configuration_table[level].good_length;
435 s->nice_match = configuration_table[level].nice_length;
436 s->max_chain_length = configuration_table[level].max_chain;
438 s->strategy = strategy;
439 return err;
442 /* =========================================================================
443 * For the default windowBits of 15 and memLevel of 8, this function returns
444 * a close to exact, as well as small, upper bound on the compressed size.
445 * They are coded as constants here for a reason--if the #define's are
446 * changed, then this function needs to be changed as well. The return
447 * value for 15 and 8 only works for those exact settings.
449 * For any setting other than those defaults for windowBits and memLevel,
450 * the value returned is a conservative worst case for the maximum expansion
451 * resulting from using fixed blocks instead of stored blocks, which deflate
452 * can emit on compressed data for some combinations of the parameters.
454 * This function could be more sophisticated to provide closer upper bounds
455 * for every combination of windowBits and memLevel, as well as wrap.
456 * But even the conservative upper bound of about 14% expansion does not
457 * seem onerous for output buffer allocation.
459 uLong ZEXPORT deflateBound(strm, sourceLen)
460 z_streamp strm;
461 uLong sourceLen;
463 deflate_state *s;
464 uLong destLen;
466 /* conservative upper bound */
467 destLen = sourceLen +
468 ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
470 /* if can't get parameters, return conservative bound */
471 if (strm == Z_NULL || strm->state == Z_NULL)
472 return destLen;
474 /* if not default parameters, return conservative bound */
475 s = strm->state;
476 if (s->w_bits != 15 || s->hash_bits != 8 + 7)
477 return destLen;
479 /* default settings: return tight bound for that case */
480 return compressBound(sourceLen);
483 /* =========================================================================
484 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
485 * IN assertion: the stream state is correct and there is enough room in
486 * pending_buf.
488 local void putShortMSB (s, b)
489 deflate_state *s;
490 uInt b;
492 put_byte(s, (Byte)(b >> 8));
493 put_byte(s, (Byte)(b & 0xff));
496 /* =========================================================================
497 * Flush as much pending output as possible. All deflate() output goes
498 * through this function so some applications may wish to modify it
499 * to avoid allocating a large strm->next_out buffer and copying into it.
500 * (See also read_buf()).
502 local void flush_pending(strm)
503 z_streamp strm;
505 unsigned len = strm->state->pending;
507 if (len > strm->avail_out) len = strm->avail_out;
508 if (len == 0) return;
510 zmemcpy(strm->next_out, strm->state->pending_out, len);
511 strm->next_out += len;
512 strm->state->pending_out += len;
513 strm->total_out += len;
514 strm->avail_out -= len;
515 strm->state->pending -= len;
516 if (strm->state->pending == 0) {
517 strm->state->pending_out = strm->state->pending_buf;
521 /* ========================================================================= */
522 int ZEXPORT deflate (strm, flush)
523 z_streamp strm;
524 int flush;
526 int old_flush; /* value of flush param for previous deflate call */
527 deflate_state *s;
529 if (strm == Z_NULL || strm->state == Z_NULL ||
530 flush > Z_FINISH || flush < 0) {
531 return Z_STREAM_ERROR;
533 s = strm->state;
535 if (strm->next_out == Z_NULL ||
536 (strm->next_in == Z_NULL && strm->avail_in != 0) ||
537 (s->status == FINISH_STATE && flush != Z_FINISH)) {
538 ERR_RETURN(strm, Z_STREAM_ERROR);
540 if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
542 s->strm = strm; /* just in case */
543 old_flush = s->last_flush;
544 s->last_flush = flush;
546 /* Write the header */
547 if (s->status == INIT_STATE) {
548 #ifdef GZIP
549 if (s->wrap == 2) {
550 put_byte(s, 31);
551 put_byte(s, 139);
552 put_byte(s, 8);
553 put_byte(s, 0);
554 put_byte(s, 0);
555 put_byte(s, 0);
556 put_byte(s, 0);
557 put_byte(s, 0);
558 put_byte(s, s->level == 9 ? 2 :
559 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
560 4 : 0));
561 put_byte(s, 255);
562 s->status = BUSY_STATE;
563 strm->adler = crc32(0L, Z_NULL, 0);
565 else
566 #endif
568 uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
569 uInt level_flags;
571 if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
572 level_flags = 0;
573 else if (s->level < 6)
574 level_flags = 1;
575 else if (s->level == 6)
576 level_flags = 2;
577 else
578 level_flags = 3;
579 header |= (level_flags << 6);
580 if (s->strstart != 0) header |= PRESET_DICT;
581 header += 31 - (header % 31);
583 s->status = BUSY_STATE;
584 putShortMSB(s, header);
586 /* Save the adler32 of the preset dictionary: */
587 if (s->strstart != 0) {
588 putShortMSB(s, (uInt)(strm->adler >> 16));
589 putShortMSB(s, (uInt)(strm->adler & 0xffff));
591 strm->adler = adler32(0L, Z_NULL, 0);
595 /* Flush as much pending output as possible */
596 if (s->pending != 0) {
597 flush_pending(strm);
598 if (strm->avail_out == 0) {
599 /* Since avail_out is 0, deflate will be called again with
600 * more output space, but possibly with both pending and
601 * avail_in equal to zero. There won't be anything to do,
602 * but this is not an error situation so make sure we
603 * return OK instead of BUF_ERROR at next call of deflate:
605 s->last_flush = -1;
606 return Z_OK;
609 /* Make sure there is something to do and avoid duplicate consecutive
610 * flushes. For repeated and useless calls with Z_FINISH, we keep
611 * returning Z_STREAM_END instead of Z_BUF_ERROR.
613 } else if (strm->avail_in == 0 && flush <= old_flush &&
614 flush != Z_FINISH) {
615 ERR_RETURN(strm, Z_BUF_ERROR);
618 /* User must not provide more input after the first FINISH: */
619 if (s->status == FINISH_STATE && strm->avail_in != 0) {
620 ERR_RETURN(strm, Z_BUF_ERROR);
623 /* Start a new block or continue the current one.
625 if (strm->avail_in != 0 || s->lookahead != 0 ||
626 (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
627 block_state bstate;
629 bstate = (*(configuration_table[s->level].func))(s, flush);
631 if (bstate == finish_started || bstate == finish_done) {
632 s->status = FINISH_STATE;
634 if (bstate == need_more || bstate == finish_started) {
635 if (strm->avail_out == 0) {
636 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
638 return Z_OK;
639 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
640 * of deflate should use the same flush parameter to make sure
641 * that the flush is complete. So we don't have to output an
642 * empty block here, this will be done at next call. This also
643 * ensures that for a very small output buffer, we emit at most
644 * one empty block.
647 if (bstate == block_done) {
648 if (flush == Z_PARTIAL_FLUSH) {
649 _tr_align(s);
650 } else { /* FULL_FLUSH or SYNC_FLUSH */
651 _tr_stored_block(s, (char*)0, 0L, 0);
652 /* For a full flush, this empty block will be recognized
653 * as a special marker by inflate_sync().
655 if (flush == Z_FULL_FLUSH) {
656 CLEAR_HASH(s); /* forget history */
659 flush_pending(strm);
660 if (strm->avail_out == 0) {
661 s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
662 return Z_OK;
666 Assert(strm->avail_out > 0, "bug2");
668 if (flush != Z_FINISH) return Z_OK;
669 if (s->wrap <= 0) return Z_STREAM_END;
671 /* Write the trailer */
672 #ifdef GZIP
673 if (s->wrap == 2) {
674 put_byte(s, (Byte)(strm->adler & 0xff));
675 put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
676 put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
677 put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
678 put_byte(s, (Byte)(strm->total_in & 0xff));
679 put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
680 put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
681 put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
683 else
684 #endif
686 putShortMSB(s, (uInt)(strm->adler >> 16));
687 putShortMSB(s, (uInt)(strm->adler & 0xffff));
689 flush_pending(strm);
690 /* If avail_out is zero, the application will call deflate again
691 * to flush the rest.
693 if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
694 return s->pending != 0 ? Z_OK : Z_STREAM_END;
697 /* ========================================================================= */
698 int ZEXPORT deflateEnd (strm)
699 z_streamp strm;
701 int status;
703 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
705 status = strm->state->status;
706 if (status != INIT_STATE && status != BUSY_STATE &&
707 status != FINISH_STATE) {
708 return Z_STREAM_ERROR;
711 /* Deallocate in reverse order of allocations: */
712 TRY_FREE(strm, strm->state->pending_buf);
713 TRY_FREE(strm, strm->state->head);
714 TRY_FREE(strm, strm->state->prev);
715 TRY_FREE(strm, strm->state->window);
717 ZFREE(strm, strm->state);
718 strm->state = Z_NULL;
720 return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
723 /* =========================================================================
724 * Copy the source state to the destination state.
725 * To simplify the source, this is not supported for 16-bit MSDOS (which
726 * doesn't have enough memory anyway to duplicate compression states).
728 int ZEXPORT deflateCopy (dest, source)
729 z_streamp dest;
730 z_streamp source;
732 #ifdef MAXSEG_64K
733 return Z_STREAM_ERROR;
734 #else
735 deflate_state *ds;
736 deflate_state *ss;
737 ushf *overlay;
740 if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
741 return Z_STREAM_ERROR;
744 ss = source->state;
746 *dest = *source;
748 ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
749 if (ds == Z_NULL) return Z_MEM_ERROR;
750 dest->state = (struct internal_state FAR *) ds;
751 *ds = *ss;
752 ds->strm = dest;
754 ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
755 ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
756 ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
757 overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
758 ds->pending_buf = (uchf *) overlay;
760 if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
761 ds->pending_buf == Z_NULL) {
762 deflateEnd (dest);
763 return Z_MEM_ERROR;
765 /* following zmemcpy do not work for 16-bit MSDOS */
766 zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
767 zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
768 zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
769 zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
771 ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
772 ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
773 ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
775 ds->l_desc.dyn_tree = ds->dyn_ltree;
776 ds->d_desc.dyn_tree = ds->dyn_dtree;
777 ds->bl_desc.dyn_tree = ds->bl_tree;
779 return Z_OK;
780 #endif /* MAXSEG_64K */
783 /* ===========================================================================
784 * Read a new buffer from the current input stream, update the adler32
785 * and total number of bytes read. All deflate() input goes through
786 * this function so some applications may wish to modify it to avoid
787 * allocating a large strm->next_in buffer and copying from it.
788 * (See also flush_pending()).
790 local int read_buf(strm, buf, size)
791 z_streamp strm;
792 Bytef *buf;
793 unsigned size;
795 unsigned len = strm->avail_in;
797 if (len > size) len = size;
798 if (len == 0) return 0;
800 strm->avail_in -= len;
802 if (strm->state->wrap == 1) {
803 strm->adler = adler32(strm->adler, strm->next_in, len);
805 #ifdef GZIP
806 else if (strm->state->wrap == 2) {
807 strm->adler = crc32(strm->adler, strm->next_in, len);
809 #endif
810 zmemcpy(buf, strm->next_in, len);
811 strm->next_in += len;
812 strm->total_in += len;
814 return (int)len;
817 /* ===========================================================================
818 * Initialize the "longest match" routines for a new zlib stream
820 local void lm_init (s)
821 deflate_state *s;
823 s->window_size = (ulg)2L*s->w_size;
825 CLEAR_HASH(s);
827 /* Set the default configuration parameters:
829 s->max_lazy_match = configuration_table[s->level].max_lazy;
830 s->good_match = configuration_table[s->level].good_length;
831 s->nice_match = configuration_table[s->level].nice_length;
832 s->max_chain_length = configuration_table[s->level].max_chain;
834 s->strstart = 0;
835 s->block_start = 0L;
836 s->lookahead = 0;
837 s->match_length = s->prev_length = MIN_MATCH-1;
838 s->match_available = 0;
839 s->ins_h = 0;
840 #ifdef ASMV
841 match_init(); /* initialize the asm code */
842 #endif
845 #ifndef FASTEST
846 /* ===========================================================================
847 * Set match_start to the longest match starting at the given string and
848 * return its length. Matches shorter or equal to prev_length are discarded,
849 * in which case the result is equal to prev_length and match_start is
850 * garbage.
851 * IN assertions: cur_match is the head of the hash chain for the current
852 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
853 * OUT assertion: the match length is not greater than s->lookahead.
855 #ifndef ASMV
856 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
857 * match.S. The code will be functionally equivalent.
859 local uInt longest_match(s, cur_match)
860 deflate_state *s;
861 IPos cur_match; /* current match */
863 unsigned chain_length = s->max_chain_length;/* max hash chain length */
864 register Bytef *scan = s->window + s->strstart; /* current string */
865 register Bytef *match; /* matched string */
866 register int len; /* length of current match */
867 int best_len = s->prev_length; /* best match length so far */
868 int nice_match = s->nice_match; /* stop if match long enough */
869 IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
870 s->strstart - (IPos)MAX_DIST(s) : NIL;
871 /* Stop when cur_match becomes <= limit. To simplify the code,
872 * we prevent matches with the string of window index 0.
874 Posf *prev = s->prev;
875 uInt wmask = s->w_mask;
877 #ifdef UNALIGNED_OK
878 /* Compare two bytes at a time. Note: this is not always beneficial.
879 * Try with and without -DUNALIGNED_OK to check.
881 register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
882 register ush scan_start = *(ushf*)scan;
883 register ush scan_end = *(ushf*)(scan+best_len-1);
884 #else
885 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
886 register Byte scan_end1 = scan[best_len-1];
887 register Byte scan_end = scan[best_len];
888 #endif
890 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
891 * It is easy to get rid of this optimization if necessary.
893 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
895 /* Do not waste too much time if we already have a good match: */
896 if (s->prev_length >= s->good_match) {
897 chain_length >>= 2;
899 /* Do not look for matches beyond the end of the input. This is necessary
900 * to make deflate deterministic.
902 if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
904 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
906 do {
907 Assert(cur_match < s->strstart, "no future");
908 match = s->window + cur_match;
910 /* Skip to next match if the match length cannot increase
911 * or if the match length is less than 2:
913 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
914 /* This code assumes sizeof(unsigned short) == 2. Do not use
915 * UNALIGNED_OK if your compiler uses a different size.
917 if (*(ushf*)(match+best_len-1) != scan_end ||
918 *(ushf*)match != scan_start) continue;
920 /* It is not necessary to compare scan[2] and match[2] since they are
921 * always equal when the other bytes match, given that the hash keys
922 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
923 * strstart+3, +5, ... up to strstart+257. We check for insufficient
924 * lookahead only every 4th comparison; the 128th check will be made
925 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
926 * necessary to put more guard bytes at the end of the window, or
927 * to check more often for insufficient lookahead.
929 Assert(scan[2] == match[2], "scan[2]?");
930 scan++, match++;
931 do {
932 } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
933 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
934 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
935 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
936 scan < strend);
937 /* The funny "do {}" generates better code on most compilers */
939 /* Here, scan <= window+strstart+257 */
940 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
941 if (*scan == *match) scan++;
943 len = (MAX_MATCH - 1) - (int)(strend-scan);
944 scan = strend - (MAX_MATCH-1);
946 #else /* UNALIGNED_OK */
948 if (match[best_len] != scan_end ||
949 match[best_len-1] != scan_end1 ||
950 *match != *scan ||
951 *++match != scan[1]) continue;
953 /* The check at best_len-1 can be removed because it will be made
954 * again later. (This heuristic is not always a win.)
955 * It is not necessary to compare scan[2] and match[2] since they
956 * are always equal when the other bytes match, given that
957 * the hash keys are equal and that HASH_BITS >= 8.
959 scan += 2, match++;
960 Assert(*scan == *match, "match[2]?");
962 /* We check for insufficient lookahead only every 8th comparison;
963 * the 256th check will be made at strstart+258.
965 do {
966 } while (*++scan == *++match && *++scan == *++match &&
967 *++scan == *++match && *++scan == *++match &&
968 *++scan == *++match && *++scan == *++match &&
969 *++scan == *++match && *++scan == *++match &&
970 scan < strend);
972 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
974 len = MAX_MATCH - (int)(strend - scan);
975 scan = strend - MAX_MATCH;
977 #endif /* UNALIGNED_OK */
979 if (len > best_len) {
980 s->match_start = cur_match;
981 best_len = len;
982 if (len >= nice_match) break;
983 #ifdef UNALIGNED_OK
984 scan_end = *(ushf*)(scan+best_len-1);
985 #else
986 scan_end1 = scan[best_len-1];
987 scan_end = scan[best_len];
988 #endif
990 } while ((cur_match = prev[cur_match & wmask]) > limit
991 && --chain_length != 0);
993 if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
994 return s->lookahead;
996 #endif /* ASMV */
997 #endif /* FASTEST */
999 /* ---------------------------------------------------------------------------
1000 * Optimized version for level == 1 or strategy == Z_RLE only
1002 local uInt longest_match_fast(s, cur_match)
1003 deflate_state *s;
1004 IPos cur_match; /* current match */
1006 register Bytef *scan = s->window + s->strstart; /* current string */
1007 register Bytef *match; /* matched string */
1008 register int len; /* length of current match */
1009 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1011 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1012 * It is easy to get rid of this optimization if necessary.
1014 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1016 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1018 Assert(cur_match < s->strstart, "no future");
1020 match = s->window + cur_match;
1022 /* Return failure if the match length is less than 2:
1024 if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
1026 /* The check at best_len-1 can be removed because it will be made
1027 * again later. (This heuristic is not always a win.)
1028 * It is not necessary to compare scan[2] and match[2] since they
1029 * are always equal when the other bytes match, given that
1030 * the hash keys are equal and that HASH_BITS >= 8.
1032 scan += 2, match += 2;
1033 Assert(*scan == *match, "match[2]?");
1035 /* We check for insufficient lookahead only every 8th comparison;
1036 * the 256th check will be made at strstart+258.
1038 do {
1039 } while (*++scan == *++match && *++scan == *++match &&
1040 *++scan == *++match && *++scan == *++match &&
1041 *++scan == *++match && *++scan == *++match &&
1042 *++scan == *++match && *++scan == *++match &&
1043 scan < strend);
1045 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1047 len = MAX_MATCH - (int)(strend - scan);
1049 if (len < MIN_MATCH) return MIN_MATCH - 1;
1051 s->match_start = cur_match;
1052 return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
1055 #ifdef DEBUG
1056 /* ===========================================================================
1057 * Check that the match at match_start is indeed a match.
1059 local void check_match(s, start, match, length)
1060 deflate_state *s;
1061 IPos start, match;
1062 int length;
1064 /* check that the match is indeed a match */
1065 if (zmemcmp(s->window + match,
1066 s->window + start, length) != EQUAL) {
1067 fprintf(stderr, " start %u, match %u, length %d\n",
1068 start, match, length);
1069 do {
1070 fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
1071 } while (--length != 0);
1072 z_error("invalid match");
1074 if (z_verbose > 1) {
1075 fprintf(stderr,"\\[%d,%d]", start-match, length);
1076 do { putc(s->window[start++], stderr); } while (--length != 0);
1079 #else
1080 # define check_match(s, start, match, length)
1081 #endif /* DEBUG */
1083 /* ===========================================================================
1084 * Fill the window when the lookahead becomes insufficient.
1085 * Updates strstart and lookahead.
1087 * IN assertion: lookahead < MIN_LOOKAHEAD
1088 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1089 * At least one byte has been read, or avail_in == 0; reads are
1090 * performed for at least two bytes (required for the zip translate_eol
1091 * option -- not supported here).
1093 local void fill_window(s)
1094 deflate_state *s;
1096 register unsigned n, m;
1097 register Posf *p;
1098 unsigned more; /* Amount of free space at the end of the window. */
1099 uInt wsize = s->w_size;
1101 do {
1102 more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
1104 /* Deal with !@#$% 64K limit: */
1105 if (sizeof(int) <= 2) {
1106 if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1107 more = wsize;
1109 } else if (more == (unsigned)(-1)) {
1110 /* Very unlikely, but possible on 16 bit machine if
1111 * strstart == 0 && lookahead == 1 (input done a byte at time)
1113 more--;
1117 /* If the window is almost full and there is insufficient lookahead,
1118 * move the upper half to the lower one to make room in the upper half.
1120 if (s->strstart >= wsize+MAX_DIST(s)) {
1122 zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
1123 s->match_start -= wsize;
1124 s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
1125 s->block_start -= (long) wsize;
1127 /* Slide the hash table (could be avoided with 32 bit values
1128 at the expense of memory usage). We slide even when level == 0
1129 to keep the hash table consistent if we switch back to level > 0
1130 later. (Using level 0 permanently is not an optimal usage of
1131 zlib, so we don't care about this pathological case.)
1133 n = s->hash_size;
1134 p = &s->head[n];
1135 do {
1136 m = *--p;
1137 *p = (Pos)(m >= wsize ? m-wsize : NIL);
1138 } while (--n);
1140 n = wsize;
1141 #ifndef FASTEST
1142 p = &s->prev[n];
1143 do {
1144 m = *--p;
1145 *p = (Pos)(m >= wsize ? m-wsize : NIL);
1146 /* If n is not on any hash chain, prev[n] is garbage but
1147 * its value will never be used.
1149 } while (--n);
1150 #endif
1151 more += wsize;
1153 if (s->strm->avail_in == 0) return;
1155 /* If there was no sliding:
1156 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1157 * more == window_size - lookahead - strstart
1158 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1159 * => more >= window_size - 2*WSIZE + 2
1160 * In the BIG_MEM or MMAP case (not yet supported),
1161 * window_size == input_size + MIN_LOOKAHEAD &&
1162 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1163 * Otherwise, window_size == 2*WSIZE so more >= 2.
1164 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1166 Assert(more >= 2, "more < 2");
1168 n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1169 s->lookahead += n;
1171 /* Initialize the hash value now that we have some input: */
1172 if (s->lookahead >= MIN_MATCH) {
1173 s->ins_h = s->window[s->strstart];
1174 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1175 #if MIN_MATCH != 3
1176 Call UPDATE_HASH() MIN_MATCH-3 more times
1177 #endif
1179 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1180 * but this is not important since only literal bytes will be emitted.
1183 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1186 /* ===========================================================================
1187 * Flush the current block, with given end-of-file flag.
1188 * IN assertion: strstart is set to the end of the current match.
1190 #define FLUSH_BLOCK_ONLY(s, eof) { \
1191 _tr_flush_block(s, (s->block_start >= 0L ? \
1192 (charf *)&s->window[(unsigned)s->block_start] : \
1193 (charf *)Z_NULL), \
1194 (ulg)((long)s->strstart - s->block_start), \
1195 (eof)); \
1196 s->block_start = s->strstart; \
1197 flush_pending(s->strm); \
1198 Tracev((stderr,"[FLUSH]")); \
1201 /* Same but force premature exit if necessary. */
1202 #define FLUSH_BLOCK(s, eof) { \
1203 FLUSH_BLOCK_ONLY(s, eof); \
1204 if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
1207 /* ===========================================================================
1208 * Copy without compression as much as possible from the input stream, return
1209 * the current block state.
1210 * This function does not insert new strings in the dictionary since
1211 * uncompressible data is probably not useful. This function is used
1212 * only for the level=0 compression option.
1213 * NOTE: this function should be optimized to avoid extra copying from
1214 * window to pending_buf.
1216 local block_state deflate_stored(s, flush)
1217 deflate_state *s;
1218 int flush;
1220 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
1221 * to pending_buf_size, and each stored block has a 5 byte header:
1223 ulg max_block_size = 0xffff;
1224 ulg max_start;
1226 if (max_block_size > s->pending_buf_size - 5) {
1227 max_block_size = s->pending_buf_size - 5;
1230 /* Copy as much as possible from input to output: */
1231 for (;;) {
1232 /* Fill the window as much as possible: */
1233 if (s->lookahead <= 1) {
1235 Assert(s->strstart < s->w_size+MAX_DIST(s) ||
1236 s->block_start >= (long)s->w_size, "slide too late");
1238 fill_window(s);
1239 if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
1241 if (s->lookahead == 0) break; /* flush the current block */
1243 Assert(s->block_start >= 0L, "block gone");
1245 s->strstart += s->lookahead;
1246 s->lookahead = 0;
1248 /* Emit a stored block if pending_buf will be full: */
1249 max_start = s->block_start + max_block_size;
1250 if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
1251 /* strstart == 0 is possible when wraparound on 16-bit machine */
1252 s->lookahead = (uInt)(s->strstart - max_start);
1253 s->strstart = (uInt)max_start;
1254 FLUSH_BLOCK(s, 0);
1256 /* Flush if we may have to slide, otherwise block_start may become
1257 * negative and the data will be gone:
1259 if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
1260 FLUSH_BLOCK(s, 0);
1263 FLUSH_BLOCK(s, flush == Z_FINISH);
1264 return flush == Z_FINISH ? finish_done : block_done;
1267 /* ===========================================================================
1268 * Compress as much as possible from the input stream, return the current
1269 * block state.
1270 * This function does not perform lazy evaluation of matches and inserts
1271 * new strings in the dictionary only for unmatched strings or for short
1272 * matches. It is used only for the fast compression options.
1274 local block_state deflate_fast(s, flush)
1275 deflate_state *s;
1276 int flush;
1278 IPos hash_head = NIL; /* head of the hash chain */
1279 int bflush; /* set if current block must be flushed */
1281 for (;;) {
1282 /* Make sure that we always have enough lookahead, except
1283 * at the end of the input file. We need MAX_MATCH bytes
1284 * for the next match, plus MIN_MATCH bytes to insert the
1285 * string following the next match.
1287 if (s->lookahead < MIN_LOOKAHEAD) {
1288 fill_window(s);
1289 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1290 return need_more;
1292 if (s->lookahead == 0) break; /* flush the current block */
1295 /* Insert the string window[strstart .. strstart+2] in the
1296 * dictionary, and set hash_head to the head of the hash chain:
1298 if (s->lookahead >= MIN_MATCH) {
1299 INSERT_STRING(s, s->strstart, hash_head);
1302 /* Find the longest match, discarding those <= prev_length.
1303 * At this point we have always match_length < MIN_MATCH
1305 if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1306 /* To simplify the code, we prevent matches with the string
1307 * of window index 0 (in particular we have to avoid a match
1308 * of the string with itself at the start of the input file).
1310 #ifdef FASTEST
1311 if ((s->strategy < Z_HUFFMAN_ONLY) ||
1312 (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
1313 s->match_length = longest_match_fast (s, hash_head);
1315 #else
1316 if (s->strategy < Z_HUFFMAN_ONLY) {
1317 s->match_length = longest_match (s, hash_head);
1318 } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
1319 s->match_length = longest_match_fast (s, hash_head);
1321 #endif
1322 /* longest_match() or longest_match_fast() sets match_start */
1324 if (s->match_length >= MIN_MATCH) {
1325 check_match(s, s->strstart, s->match_start, s->match_length);
1327 _tr_tally_dist(s, s->strstart - s->match_start,
1328 s->match_length - MIN_MATCH, bflush);
1330 s->lookahead -= s->match_length;
1332 /* Insert new strings in the hash table only if the match length
1333 * is not too large. This saves time but degrades compression.
1335 #ifndef FASTEST
1336 if (s->match_length <= s->max_insert_length &&
1337 s->lookahead >= MIN_MATCH) {
1338 s->match_length--; /* string at strstart already in table */
1339 do {
1340 s->strstart++;
1341 INSERT_STRING(s, s->strstart, hash_head);
1342 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1343 * always MIN_MATCH bytes ahead.
1345 } while (--s->match_length != 0);
1346 s->strstart++;
1347 } else
1348 #endif
1350 s->strstart += s->match_length;
1351 s->match_length = 0;
1352 s->ins_h = s->window[s->strstart];
1353 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1354 #if MIN_MATCH != 3
1355 Call UPDATE_HASH() MIN_MATCH-3 more times
1356 #endif
1357 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1358 * matter since it will be recomputed at next deflate call.
1361 } else {
1362 /* No match, output a literal byte */
1363 Tracevv((stderr,"%c", s->window[s->strstart]));
1364 _tr_tally_lit (s, s->window[s->strstart], bflush);
1365 s->lookahead--;
1366 s->strstart++;
1368 if (bflush) FLUSH_BLOCK(s, 0);
1370 FLUSH_BLOCK(s, flush == Z_FINISH);
1371 return flush == Z_FINISH ? finish_done : block_done;
1374 #ifndef FASTEST
1375 /* ===========================================================================
1376 * Same as above, but achieves better compression. We use a lazy
1377 * evaluation for matches: a match is finally adopted only if there is
1378 * no better match at the next window position.
1380 local block_state deflate_slow(s, flush)
1381 deflate_state *s;
1382 int flush;
1384 IPos hash_head = NIL; /* head of hash chain */
1385 int bflush; /* set if current block must be flushed */
1387 /* Process the input block. */
1388 for (;;) {
1389 /* Make sure that we always have enough lookahead, except
1390 * at the end of the input file. We need MAX_MATCH bytes
1391 * for the next match, plus MIN_MATCH bytes to insert the
1392 * string following the next match.
1394 if (s->lookahead < MIN_LOOKAHEAD) {
1395 fill_window(s);
1396 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1397 return need_more;
1399 if (s->lookahead == 0) break; /* flush the current block */
1402 /* Insert the string window[strstart .. strstart+2] in the
1403 * dictionary, and set hash_head to the head of the hash chain:
1405 if (s->lookahead >= MIN_MATCH) {
1406 INSERT_STRING(s, s->strstart, hash_head);
1409 /* Find the longest match, discarding those <= prev_length.
1411 s->prev_length = s->match_length, s->prev_match = s->match_start;
1412 s->match_length = MIN_MATCH-1;
1414 if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
1415 s->strstart - hash_head <= MAX_DIST(s)) {
1416 /* To simplify the code, we prevent matches with the string
1417 * of window index 0 (in particular we have to avoid a match
1418 * of the string with itself at the start of the input file).
1420 if (s->strategy < Z_HUFFMAN_ONLY) {
1421 s->match_length = longest_match (s, hash_head);
1422 } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
1423 s->match_length = longest_match_fast (s, hash_head);
1425 /* longest_match() or longest_match_fast() sets match_start */
1427 if (s->match_length <= 5 && (s->strategy == Z_FILTERED
1428 #if TOO_FAR <= 32767
1429 || (s->match_length == MIN_MATCH &&
1430 s->strstart - s->match_start > TOO_FAR)
1431 #endif
1432 )) {
1434 /* If prev_match is also MIN_MATCH, match_start is garbage
1435 * but we will ignore the current match anyway.
1437 s->match_length = MIN_MATCH-1;
1440 /* If there was a match at the previous step and the current
1441 * match is not better, output the previous match:
1443 if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
1444 uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
1445 /* Do not insert strings in hash table beyond this. */
1447 check_match(s, s->strstart-1, s->prev_match, s->prev_length);
1449 _tr_tally_dist(s, s->strstart -1 - s->prev_match,
1450 s->prev_length - MIN_MATCH, bflush);
1452 /* Insert in hash table all strings up to the end of the match.
1453 * strstart-1 and strstart are already inserted. If there is not
1454 * enough lookahead, the last two strings are not inserted in
1455 * the hash table.
1457 s->lookahead -= s->prev_length-1;
1458 s->prev_length -= 2;
1459 do {
1460 if (++s->strstart <= max_insert) {
1461 INSERT_STRING(s, s->strstart, hash_head);
1463 } while (--s->prev_length != 0);
1464 s->match_available = 0;
1465 s->match_length = MIN_MATCH-1;
1466 s->strstart++;
1468 if (bflush) FLUSH_BLOCK(s, 0);
1470 } else if (s->match_available) {
1471 /* If there was no match at the previous position, output a
1472 * single literal. If there was a match but the current match
1473 * is longer, truncate the previous match to a single literal.
1475 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1476 _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1477 if (bflush) {
1478 FLUSH_BLOCK_ONLY(s, 0);
1480 s->strstart++;
1481 s->lookahead--;
1482 if (s->strm->avail_out == 0) return need_more;
1483 } else {
1484 /* There is no previous match to compare with, wait for
1485 * the next step to decide.
1487 s->match_available = 1;
1488 s->strstart++;
1489 s->lookahead--;
1492 Assert (flush != Z_NO_FLUSH, "no flush?");
1493 if (s->match_available) {
1494 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1495 _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1496 s->match_available = 0;
1498 FLUSH_BLOCK(s, flush == Z_FINISH);
1499 return flush == Z_FINISH ? finish_done : block_done;
1501 #endif /* FASTEST */