nightly: install bmake libs before dmake
[unleashed.git] / kernel / zmod / deflate.c
blob59beb0c78c8d6182253e448e3fd7f4670dcb4dcf
1 /*
2 * Copyright 2007 Sun Microsystems, Inc. All rights reserved.
3 * Use is subject to license terms.
4 */
6 /* deflate.c -- compress data using the deflation algorithm
7 * Copyright (C) 1995-2005 Jean-loup Gailly.
8 * For conditions of distribution and use, see copyright notice in zlib.h
9 */
12 * ALGORITHM
14 * The "deflation" process depends on being able to identify portions
15 * of the input text which are identical to earlier input (within a
16 * sliding window trailing behind the input currently being processed).
18 * The most straightforward technique turns out to be the fastest for
19 * most input files: try all possible matches and select the longest.
20 * The key feature of this algorithm is that insertions into the string
21 * dictionary are very simple and thus fast, and deletions are avoided
22 * completely. Insertions are performed at each input character, whereas
23 * string matches are performed only when the previous match ends. So it
24 * is preferable to spend more time in matches to allow very fast string
25 * insertions and avoid deletions. The matching algorithm for small
26 * strings is inspired from that of Rabin & Karp. A brute force approach
27 * is used to find longer strings when a small match has been found.
28 * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
29 * (by Leonid Broukhis).
30 * A previous version of this file used a more sophisticated algorithm
31 * (by Fiala and Greene) which is guaranteed to run in linear amortized
32 * time, but has a larger average cost, uses more memory and is patented.
33 * However the F&G algorithm may be faster for some highly redundant
34 * files if the parameter max_chain_length (described below) is too large.
36 * ACKNOWLEDGEMENTS
38 * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
39 * I found it in 'freeze' written by Leonid Broukhis.
40 * Thanks to many people for bug reports and testing.
42 * REFERENCES
44 * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
45 * Available in http://www.ietf.org/rfc/rfc1951.txt
47 * A description of the Rabin and Karp algorithm is given in the book
48 * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
50 * Fiala,E.R., and Greene,D.H.
51 * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
55 #include "deflate.h"
57 static const char deflate_copyright[] =
58 " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
60 If you use the zlib library in a product, an acknowledgment is welcome
61 in the documentation of your product. If for some reason you cannot
62 include such an acknowledgment, I would appreciate that you keep this
63 copyright string in the executable of your product.
66 /* ===========================================================================
67 * Function prototypes.
69 typedef enum {
70 need_more, /* block not completed, need more input or more output */
71 block_done, /* block flush performed */
72 finish_started, /* finish started, need only more output at next deflate */
73 finish_done /* finish done, accept no more input or output */
74 } block_state;
76 typedef block_state (*compress_func) OF((deflate_state *s, int flush));
77 /* Compression function. Returns the block state after the call. */
79 local void fill_window OF((deflate_state *s));
80 local block_state deflate_stored OF((deflate_state *s, int flush));
81 local block_state deflate_fast OF((deflate_state *s, int flush));
82 #ifndef FASTEST
83 local block_state deflate_slow OF((deflate_state *s, int flush));
84 #endif
85 local void lm_init OF((deflate_state *s));
86 local void putShortMSB OF((deflate_state *s, uInt b));
87 local void flush_pending OF((z_streamp strm));
88 local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
89 #ifndef FASTEST
90 #ifdef ASMV
91 void match_init OF((void)); /* asm code initialization */
92 uInt longest_match OF((deflate_state *s, IPos cur_match));
93 #else
94 local uInt longest_match OF((deflate_state *s, IPos cur_match));
95 #endif
96 #endif
97 local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
99 #ifdef DEBUG
100 local void check_match OF((deflate_state *s, IPos start, IPos match,
101 int length));
102 #endif
104 /* ===========================================================================
105 * Local data
108 #define NIL 0
109 /* Tail of hash chains */
111 #ifndef TOO_FAR
112 # define TOO_FAR 4096
113 #endif
114 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
116 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
117 /* Minimum amount of lookahead, except at the end of the input file.
118 * See deflate.c for comments about the MIN_MATCH+1.
121 /* Values for max_lazy_match, good_match and max_chain_length, depending on
122 * the desired pack level (0..9). The values given below have been tuned to
123 * exclude worst case performance for pathological files. Better values may be
124 * found for specific files.
126 typedef struct config_s {
127 ush good_length; /* reduce lazy search above this match length */
128 ush max_lazy; /* do not perform lazy search above this match length */
129 ush nice_length; /* quit search above this match length */
130 ush max_chain;
131 compress_func func;
132 } config;
134 #ifdef FASTEST
135 local const config configuration_table[2] = {
136 /* good lazy nice chain */
137 /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
138 /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
139 #else
140 local const config configuration_table[10] = {
141 /* good lazy nice chain */
142 /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
143 /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
144 /* 2 */ {4, 5, 16, 8, deflate_fast},
145 /* 3 */ {4, 6, 32, 32, deflate_fast},
147 /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
148 /* 5 */ {8, 16, 32, 32, deflate_slow},
149 /* 6 */ {8, 16, 128, 128, deflate_slow},
150 /* 7 */ {8, 32, 128, 256, deflate_slow},
151 /* 8 */ {32, 128, 258, 1024, deflate_slow},
152 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
153 #endif
155 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
156 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
157 * meaning.
160 #define EQUAL 0
161 /* result of memcmp for equal strings */
163 #ifndef NO_DUMMY_DECL
164 struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
165 #endif
167 /* ===========================================================================
168 * Update a hash value with the given input byte
169 * IN assertion: all calls to to UPDATE_HASH are made with consecutive
170 * input characters, so that a running hash key can be computed from the
171 * previous key instead of complete recalculation each time.
173 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
176 /* ===========================================================================
177 * Insert string str in the dictionary and set match_head to the previous head
178 * of the hash chain (the most recent string with same hash key). Return
179 * the previous length of the hash chain.
180 * If this file is compiled with -DFASTEST, the compression level is forced
181 * to 1, and no hash chains are maintained.
182 * IN assertion: all calls to to INSERT_STRING are made with consecutive
183 * input characters and the first MIN_MATCH bytes of str are valid
184 * (except for the last MIN_MATCH-1 bytes of the input file).
186 #ifdef FASTEST
187 #define INSERT_STRING(s, str, match_head) \
188 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
189 match_head = s->head[s->ins_h], \
190 s->head[s->ins_h] = (Pos)(str))
191 #else
192 #define INSERT_STRING(s, str, match_head) \
193 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
194 match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
195 s->head[s->ins_h] = (Pos)(str))
196 #endif
198 /* ===========================================================================
199 * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
200 * prev[] will be initialized on the fly.
202 #define CLEAR_HASH(s) \
203 s->head[s->hash_size-1] = NIL; \
204 (void) zmemzero((Bytef *)s->head, \
205 (unsigned)(s->hash_size-1)*sizeof(*s->head));
207 /* ========================================================================= */
208 int ZEXPORT deflateInit_(strm, level, version, stream_size)
209 z_streamp strm;
210 int level;
211 const char *version;
212 int stream_size;
214 return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
215 Z_DEFAULT_STRATEGY, version, stream_size);
216 /* To do: ignore strm->next_in if we use it as window */
219 /* ========================================================================= */
220 int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
221 version, stream_size)
222 z_streamp strm;
223 int level;
224 int method;
225 int windowBits;
226 int memLevel;
227 int strategy;
228 const char *version;
229 int stream_size;
231 deflate_state *s;
232 int wrap = 1;
233 static const char my_version[] = ZLIB_VERSION;
235 ushf *overlay;
236 /* We overlay pending_buf and d_buf+l_buf. This works since the average
237 * output size for (length,distance) codes is <= 24 bits.
240 if (version == Z_NULL || version[0] != my_version[0] ||
241 stream_size != sizeof(z_stream)) {
242 return Z_VERSION_ERROR;
244 if (strm == Z_NULL) return Z_STREAM_ERROR;
246 strm->msg = Z_NULL;
247 if (strm->zalloc == (alloc_func)0) {
248 strm->zalloc = zcalloc;
249 strm->opaque = (voidpf)0;
251 if (strm->zfree == (free_func)0) strm->zfree = zcfree;
253 #ifdef FASTEST
254 if (level != 0) level = 1;
255 #else
256 if (level == Z_DEFAULT_COMPRESSION) level = 6;
257 #endif
259 if (windowBits < 0) { /* suppress zlib wrapper */
260 wrap = 0;
261 windowBits = -windowBits;
263 #ifdef GZIP
264 else if (windowBits > 15) {
265 wrap = 2; /* write gzip wrapper instead */
266 windowBits -= 16;
268 #endif
269 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
270 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
271 strategy < 0 || strategy > Z_FIXED) {
272 return Z_STREAM_ERROR;
274 if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
275 s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
276 if (s == Z_NULL) return Z_MEM_ERROR;
277 strm->state = (struct internal_state FAR *)s;
278 s->strm = strm;
280 s->wrap = wrap;
281 s->gzhead = Z_NULL;
282 s->w_bits = windowBits;
283 s->w_size = 1 << s->w_bits;
284 s->w_mask = s->w_size - 1;
286 s->hash_bits = memLevel + 7;
287 s->hash_size = 1 << s->hash_bits;
288 s->hash_mask = s->hash_size - 1;
289 s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
291 s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
292 s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
293 s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
295 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
297 overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
298 s->pending_buf = (uchf *) overlay;
299 s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
301 if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
302 s->pending_buf == Z_NULL) {
303 s->status = FINISH_STATE;
304 strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
305 (void) deflateEnd (strm);
306 return Z_MEM_ERROR;
308 s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
309 s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
311 s->level = level;
312 s->strategy = strategy;
313 s->method = (Byte)method;
315 return deflateReset(strm);
318 /* ========================================================================= */
319 int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
320 z_streamp strm;
321 const Bytef *dictionary;
322 uInt dictLength;
324 deflate_state *s;
325 uInt length = dictLength;
326 uInt n;
327 IPos hash_head = 0;
329 if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
330 strm->state->wrap == 2 ||
331 (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
332 return Z_STREAM_ERROR;
334 s = strm->state;
335 if (s->wrap)
336 strm->adler = adler32(strm->adler, dictionary, dictLength);
338 if (length < MIN_MATCH) return Z_OK;
339 if (length > MAX_DIST(s)) {
340 length = MAX_DIST(s);
341 dictionary += dictLength - length; /* use the tail of the dictionary */
343 (void) zmemcpy(s->window, dictionary, length);
344 s->strstart = length;
345 s->block_start = (long)length;
347 /* Insert all strings in the hash table (except for the last two bytes).
348 * s->lookahead stays null, so s->ins_h will be recomputed at the next
349 * call of fill_window.
351 s->ins_h = s->window[0];
352 UPDATE_HASH(s, s->ins_h, s->window[1]);
353 for (n = 0; n <= length - MIN_MATCH; n++) {
354 INSERT_STRING(s, n, hash_head);
356 if (hash_head) hash_head = 0; /* to make compiler happy */
357 return Z_OK;
360 /* ========================================================================= */
361 int ZEXPORT deflateReset (strm)
362 z_streamp strm;
364 deflate_state *s;
366 if (strm == Z_NULL || strm->state == Z_NULL ||
367 strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
368 return Z_STREAM_ERROR;
371 strm->total_in = strm->total_out = 0;
372 strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
373 strm->data_type = Z_UNKNOWN;
375 s = (deflate_state *)strm->state;
376 s->pending = 0;
377 s->pending_out = s->pending_buf;
379 if (s->wrap < 0) {
380 s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
382 s->status = s->wrap ? INIT_STATE : BUSY_STATE;
383 strm->adler =
384 #ifdef GZIP
385 s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
386 #endif
387 adler32(0L, Z_NULL, 0);
388 s->last_flush = Z_NO_FLUSH;
390 _tr_init(s);
391 lm_init(s);
393 return Z_OK;
396 /* ========================================================================= */
397 int ZEXPORT deflateSetHeader (strm, head)
398 z_streamp strm;
399 gz_headerp head;
401 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
402 if (strm->state->wrap != 2) return Z_STREAM_ERROR;
403 strm->state->gzhead = head;
404 return Z_OK;
407 /* ========================================================================= */
408 int ZEXPORT deflatePrime (strm, bits, value)
409 z_streamp strm;
410 int bits;
411 int value;
413 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
414 strm->state->bi_valid = bits;
415 strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
416 return Z_OK;
419 /* ========================================================================= */
420 int ZEXPORT deflateParams(strm, level, strategy)
421 z_streamp strm;
422 int level;
423 int strategy;
425 deflate_state *s;
426 compress_func func;
427 int err = Z_OK;
429 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
430 s = strm->state;
432 #ifdef FASTEST
433 if (level != 0) level = 1;
434 #else
435 if (level == Z_DEFAULT_COMPRESSION) level = 6;
436 #endif
437 if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
438 return Z_STREAM_ERROR;
440 func = configuration_table[s->level].func;
442 if (func != configuration_table[level].func && strm->total_in != 0) {
443 /* Flush the last buffer: */
444 err = deflate(strm, Z_PARTIAL_FLUSH);
446 if (s->level != level) {
447 s->level = level;
448 s->max_lazy_match = configuration_table[level].max_lazy;
449 s->good_match = configuration_table[level].good_length;
450 s->nice_match = configuration_table[level].nice_length;
451 s->max_chain_length = configuration_table[level].max_chain;
453 s->strategy = strategy;
454 return err;
457 /* ========================================================================= */
458 int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
459 z_streamp strm;
460 int good_length;
461 int max_lazy;
462 int nice_length;
463 int max_chain;
465 deflate_state *s;
467 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
468 s = strm->state;
469 s->good_match = good_length;
470 s->max_lazy_match = max_lazy;
471 s->nice_match = nice_length;
472 s->max_chain_length = max_chain;
473 return Z_OK;
476 /* =========================================================================
477 * For the default windowBits of 15 and memLevel of 8, this function returns
478 * a close to exact, as well as small, upper bound on the compressed size.
479 * They are coded as constants here for a reason--if the #define's are
480 * changed, then this function needs to be changed as well. The return
481 * value for 15 and 8 only works for those exact settings.
483 * For any setting other than those defaults for windowBits and memLevel,
484 * the value returned is a conservative worst case for the maximum expansion
485 * resulting from using fixed blocks instead of stored blocks, which deflate
486 * can emit on compressed data for some combinations of the parameters.
488 * This function could be more sophisticated to provide closer upper bounds
489 * for every combination of windowBits and memLevel, as well as wrap.
490 * But even the conservative upper bound of about 14% expansion does not
491 * seem onerous for output buffer allocation.
493 uLong ZEXPORT deflateBound(strm, sourceLen)
494 z_streamp strm;
495 uLong sourceLen;
497 deflate_state *s;
498 uLong destLen;
500 /* conservative upper bound */
501 destLen = sourceLen +
502 ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
504 /* if can't get parameters, return conservative bound */
505 if (strm == Z_NULL || strm->state == Z_NULL)
506 return destLen;
508 /* if not default parameters, return conservative bound */
509 s = strm->state;
510 if (s->w_bits != 15 || s->hash_bits != 8 + 7)
511 return destLen;
513 /* default settings: return tight bound for that case */
514 return compressBound(sourceLen);
517 /* =========================================================================
518 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
519 * IN assertion: the stream state is correct and there is enough room in
520 * pending_buf.
522 local void putShortMSB (s, b)
523 deflate_state *s;
524 uInt b;
526 put_byte(s, (Byte)(b >> 8));
527 put_byte(s, (Byte)(b & 0xff));
530 /* =========================================================================
531 * Flush as much pending output as possible. All deflate() output goes
532 * through this function so some applications may wish to modify it
533 * to avoid allocating a large strm->next_out buffer and copying into it.
534 * (See also read_buf()).
536 local void flush_pending(strm)
537 z_streamp strm;
539 unsigned len = strm->state->pending;
541 if (len > strm->avail_out) len = strm->avail_out;
542 if (len == 0) return;
544 zmemcpy(strm->next_out, strm->state->pending_out, len);
545 strm->next_out += len;
546 strm->state->pending_out += len;
547 strm->total_out += len;
548 strm->avail_out -= len;
549 strm->state->pending -= len;
550 if (strm->state->pending == 0) {
551 strm->state->pending_out = strm->state->pending_buf;
555 /* ========================================================================= */
556 int ZEXPORT deflate (strm, flush)
557 z_streamp strm;
558 int flush;
560 int old_flush; /* value of flush param for previous deflate call */
561 deflate_state *s;
563 if (strm == Z_NULL || strm->state == Z_NULL ||
564 flush > Z_FINISH || flush < 0) {
565 return Z_STREAM_ERROR;
567 s = strm->state;
569 if (strm->next_out == Z_NULL ||
570 (strm->next_in == Z_NULL && strm->avail_in != 0) ||
571 (s->status == FINISH_STATE && flush != Z_FINISH)) {
572 ERR_RETURN(strm, Z_STREAM_ERROR);
574 if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
576 s->strm = strm; /* just in case */
577 old_flush = s->last_flush;
578 s->last_flush = flush;
580 /* Write the header */
581 if (s->status == INIT_STATE) {
582 #ifdef GZIP
583 if (s->wrap == 2) {
584 strm->adler = crc32(0L, Z_NULL, 0);
585 put_byte(s, 31);
586 put_byte(s, 139);
587 put_byte(s, 8);
588 if (s->gzhead == NULL) {
589 put_byte(s, 0);
590 put_byte(s, 0);
591 put_byte(s, 0);
592 put_byte(s, 0);
593 put_byte(s, 0);
594 put_byte(s, s->level == 9 ? 2 :
595 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
596 4 : 0));
597 put_byte(s, OS_CODE);
598 s->status = BUSY_STATE;
600 else {
601 put_byte(s, (s->gzhead->text ? 1 : 0) +
602 (s->gzhead->hcrc ? 2 : 0) +
603 (s->gzhead->extra == Z_NULL ? 0 : 4) +
604 (s->gzhead->name == Z_NULL ? 0 : 8) +
605 (s->gzhead->comment == Z_NULL ? 0 : 16)
607 put_byte(s, (Byte)(s->gzhead->time & 0xff));
608 put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
609 put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
610 put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
611 put_byte(s, s->level == 9 ? 2 :
612 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
613 4 : 0));
614 put_byte(s, s->gzhead->os & 0xff);
615 if (s->gzhead->extra != NULL) {
616 put_byte(s, s->gzhead->extra_len & 0xff);
617 put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
619 if (s->gzhead->hcrc)
620 strm->adler = crc32(strm->adler, s->pending_buf,
621 s->pending);
622 s->gzindex = 0;
623 s->status = EXTRA_STATE;
626 else
627 #endif
629 uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
630 uInt level_flags;
632 if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
633 level_flags = 0;
634 else if (s->level < 6)
635 level_flags = 1;
636 else if (s->level == 6)
637 level_flags = 2;
638 else
639 level_flags = 3;
640 header |= (level_flags << 6);
641 if (s->strstart != 0) header |= PRESET_DICT;
642 header += 31 - (header % 31);
644 s->status = BUSY_STATE;
645 putShortMSB(s, header);
647 /* Save the adler32 of the preset dictionary: */
648 if (s->strstart != 0) {
649 putShortMSB(s, (uInt)(strm->adler >> 16));
650 putShortMSB(s, (uInt)(strm->adler & 0xffff));
652 strm->adler = adler32(0L, Z_NULL, 0);
655 #ifdef GZIP
656 if (s->status == EXTRA_STATE) {
657 if (s->gzhead->extra != NULL) {
658 uInt beg = s->pending; /* start of bytes to update crc */
660 while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
661 if (s->pending == s->pending_buf_size) {
662 if (s->gzhead->hcrc && s->pending > beg)
663 strm->adler = crc32(strm->adler, s->pending_buf + beg,
664 s->pending - beg);
665 flush_pending(strm);
666 beg = s->pending;
667 if (s->pending == s->pending_buf_size)
668 break;
670 put_byte(s, s->gzhead->extra[s->gzindex]);
671 s->gzindex++;
673 if (s->gzhead->hcrc && s->pending > beg)
674 strm->adler = crc32(strm->adler, s->pending_buf + beg,
675 s->pending - beg);
676 if (s->gzindex == s->gzhead->extra_len) {
677 s->gzindex = 0;
678 s->status = NAME_STATE;
681 else
682 s->status = NAME_STATE;
684 if (s->status == NAME_STATE) {
685 if (s->gzhead->name != NULL) {
686 uInt beg = s->pending; /* start of bytes to update crc */
687 int val;
689 do {
690 if (s->pending == s->pending_buf_size) {
691 if (s->gzhead->hcrc && s->pending > beg)
692 strm->adler = crc32(strm->adler, s->pending_buf + beg,
693 s->pending - beg);
694 flush_pending(strm);
695 beg = s->pending;
696 if (s->pending == s->pending_buf_size) {
697 val = 1;
698 break;
701 val = s->gzhead->name[s->gzindex++];
702 put_byte(s, val);
703 } while (val != 0);
704 if (s->gzhead->hcrc && s->pending > beg)
705 strm->adler = crc32(strm->adler, s->pending_buf + beg,
706 s->pending - beg);
707 if (val == 0) {
708 s->gzindex = 0;
709 s->status = COMMENT_STATE;
712 else
713 s->status = COMMENT_STATE;
715 if (s->status == COMMENT_STATE) {
716 if (s->gzhead->comment != NULL) {
717 uInt beg = s->pending; /* start of bytes to update crc */
718 int val;
720 do {
721 if (s->pending == s->pending_buf_size) {
722 if (s->gzhead->hcrc && s->pending > beg)
723 strm->adler = crc32(strm->adler, s->pending_buf + beg,
724 s->pending - beg);
725 flush_pending(strm);
726 beg = s->pending;
727 if (s->pending == s->pending_buf_size) {
728 val = 1;
729 break;
732 val = s->gzhead->comment[s->gzindex++];
733 put_byte(s, val);
734 } while (val != 0);
735 if (s->gzhead->hcrc && s->pending > beg)
736 strm->adler = crc32(strm->adler, s->pending_buf + beg,
737 s->pending - beg);
738 if (val == 0)
739 s->status = HCRC_STATE;
741 else
742 s->status = HCRC_STATE;
744 if (s->status == HCRC_STATE) {
745 if (s->gzhead->hcrc) {
746 if (s->pending + 2 > s->pending_buf_size)
747 flush_pending(strm);
748 if (s->pending + 2 <= s->pending_buf_size) {
749 put_byte(s, (Byte)(strm->adler & 0xff));
750 put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
751 strm->adler = crc32(0L, Z_NULL, 0);
752 s->status = BUSY_STATE;
755 else
756 s->status = BUSY_STATE;
758 #endif
760 /* Flush as much pending output as possible */
761 if (s->pending != 0) {
762 flush_pending(strm);
763 if (strm->avail_out == 0) {
764 /* Since avail_out is 0, deflate will be called again with
765 * more output space, but possibly with both pending and
766 * avail_in equal to zero. There won't be anything to do,
767 * but this is not an error situation so make sure we
768 * return OK instead of BUF_ERROR at next call of deflate:
770 s->last_flush = -1;
771 return Z_OK;
774 /* Make sure there is something to do and avoid duplicate consecutive
775 * flushes. For repeated and useless calls with Z_FINISH, we keep
776 * returning Z_STREAM_END instead of Z_BUF_ERROR.
778 } else if (strm->avail_in == 0 && flush <= old_flush &&
779 flush != Z_FINISH) {
780 ERR_RETURN(strm, Z_BUF_ERROR);
783 /* User must not provide more input after the first FINISH: */
784 if (s->status == FINISH_STATE && strm->avail_in != 0) {
785 ERR_RETURN(strm, Z_BUF_ERROR);
788 /* Start a new block or continue the current one.
790 if (strm->avail_in != 0 || s->lookahead != 0 ||
791 (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
792 block_state bstate;
794 bstate = (*(configuration_table[s->level].func))(s, flush);
796 if (bstate == finish_started || bstate == finish_done) {
797 s->status = FINISH_STATE;
799 if (bstate == need_more || bstate == finish_started) {
800 if (strm->avail_out == 0) {
801 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
803 return Z_OK;
804 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
805 * of deflate should use the same flush parameter to make sure
806 * that the flush is complete. So we don't have to output an
807 * empty block here, this will be done at next call. This also
808 * ensures that for a very small output buffer, we emit at most
809 * one empty block.
812 if (bstate == block_done) {
813 if (flush == Z_PARTIAL_FLUSH) {
814 _tr_align(s);
815 } else { /* FULL_FLUSH or SYNC_FLUSH */
816 _tr_stored_block(s, (char*)0, 0L, 0);
817 /* For a full flush, this empty block will be recognized
818 * as a special marker by inflate_sync().
820 if (flush == Z_FULL_FLUSH) {
821 CLEAR_HASH(s); /* forget history */
824 flush_pending(strm);
825 if (strm->avail_out == 0) {
826 s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
827 return Z_OK;
831 Assert(strm->avail_out > 0, "bug2");
833 if (flush != Z_FINISH) return Z_OK;
834 if (s->wrap <= 0) return Z_STREAM_END;
836 /* Write the trailer */
837 #ifdef GZIP
838 if (s->wrap == 2) {
839 put_byte(s, (Byte)(strm->adler & 0xff));
840 put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
841 put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
842 put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
843 put_byte(s, (Byte)(strm->total_in & 0xff));
844 put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
845 put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
846 put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
848 else
849 #endif
851 putShortMSB(s, (uInt)(strm->adler >> 16));
852 putShortMSB(s, (uInt)(strm->adler & 0xffff));
854 flush_pending(strm);
855 /* If avail_out is zero, the application will call deflate again
856 * to flush the rest.
858 if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
859 return s->pending != 0 ? Z_OK : Z_STREAM_END;
862 /* ========================================================================= */
863 int ZEXPORT deflateEnd (strm)
864 z_streamp strm;
866 int status;
868 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
870 status = strm->state->status;
871 if (status != INIT_STATE &&
872 status != EXTRA_STATE &&
873 status != NAME_STATE &&
874 status != COMMENT_STATE &&
875 status != HCRC_STATE &&
876 status != BUSY_STATE &&
877 status != FINISH_STATE) {
878 return Z_STREAM_ERROR;
881 /* Deallocate in reverse order of allocations: */
882 TRY_FREE(strm, strm->state->pending_buf);
883 TRY_FREE(strm, strm->state->head);
884 TRY_FREE(strm, strm->state->prev);
885 TRY_FREE(strm, strm->state->window);
887 ZFREE(strm, strm->state);
888 strm->state = Z_NULL;
890 return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
893 /* =========================================================================
894 * Copy the source state to the destination state.
895 * To simplify the source, this is not supported for 16-bit MSDOS (which
896 * doesn't have enough memory anyway to duplicate compression states).
898 int ZEXPORT deflateCopy (dest, source)
899 z_streamp dest;
900 z_streamp source;
902 #ifdef MAXSEG_64K
903 return Z_STREAM_ERROR;
904 #else
905 deflate_state *ds;
906 deflate_state *ss;
907 ushf *overlay;
910 if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
911 return Z_STREAM_ERROR;
914 ss = source->state;
916 zmemcpy(dest, source, sizeof(z_stream));
918 ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
919 if (ds == Z_NULL) return Z_MEM_ERROR;
920 dest->state = (struct internal_state FAR *) ds;
921 zmemcpy(ds, ss, sizeof(deflate_state));
922 ds->strm = dest;
924 ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
925 ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
926 ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
927 overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
928 ds->pending_buf = (uchf *) overlay;
930 if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
931 ds->pending_buf == Z_NULL) {
932 deflateEnd (dest);
933 return Z_MEM_ERROR;
935 /* following zmemcpy do not work for 16-bit MSDOS */
936 zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
937 zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
938 zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
939 zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
941 ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
942 ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
943 ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
945 ds->l_desc.dyn_tree = ds->dyn_ltree;
946 ds->d_desc.dyn_tree = ds->dyn_dtree;
947 ds->bl_desc.dyn_tree = ds->bl_tree;
949 return Z_OK;
950 #endif /* MAXSEG_64K */
953 /* ===========================================================================
954 * Read a new buffer from the current input stream, update the adler32
955 * and total number of bytes read. All deflate() input goes through
956 * this function so some applications may wish to modify it to avoid
957 * allocating a large strm->next_in buffer and copying from it.
958 * (See also flush_pending()).
960 local int read_buf(strm, buf, size)
961 z_streamp strm;
962 Bytef *buf;
963 unsigned size;
965 unsigned len = strm->avail_in;
967 if (len > size) len = size;
968 if (len == 0) return 0;
970 strm->avail_in -= len;
972 if (strm->state->wrap == 1) {
973 strm->adler = adler32(strm->adler, strm->next_in, len);
975 #ifdef GZIP
976 else if (strm->state->wrap == 2) {
977 strm->adler = crc32(strm->adler, strm->next_in, len);
979 #endif
980 zmemcpy(buf, strm->next_in, len);
981 strm->next_in += len;
982 strm->total_in += len;
984 return (int)len;
987 /* ===========================================================================
988 * Initialize the "longest match" routines for a new zlib stream
990 local void lm_init (s)
991 deflate_state *s;
993 s->window_size = (ulg)2L*s->w_size;
995 CLEAR_HASH(s);
997 /* Set the default configuration parameters:
999 s->max_lazy_match = configuration_table[s->level].max_lazy;
1000 s->good_match = configuration_table[s->level].good_length;
1001 s->nice_match = configuration_table[s->level].nice_length;
1002 s->max_chain_length = configuration_table[s->level].max_chain;
1004 s->strstart = 0;
1005 s->block_start = 0L;
1006 s->lookahead = 0;
1007 s->match_length = s->prev_length = MIN_MATCH-1;
1008 s->match_available = 0;
1009 s->ins_h = 0;
1010 #ifndef FASTEST
1011 #ifdef ASMV
1012 match_init(); /* initialize the asm code */
1013 #endif
1014 #endif
1017 #ifndef FASTEST
1018 /* ===========================================================================
1019 * Set match_start to the longest match starting at the given string and
1020 * return its length. Matches shorter or equal to prev_length are discarded,
1021 * in which case the result is equal to prev_length and match_start is
1022 * garbage.
1023 * IN assertions: cur_match is the head of the hash chain for the current
1024 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1025 * OUT assertion: the match length is not greater than s->lookahead.
1027 #ifndef ASMV
1028 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
1029 * match.S. The code will be functionally equivalent.
1031 local uInt longest_match(s, cur_match)
1032 deflate_state *s;
1033 IPos cur_match; /* current match */
1035 unsigned chain_length = s->max_chain_length;/* max hash chain length */
1036 Bytef *scan = s->window + s->strstart; /* current string */
1037 Bytef *match; /* matched string */
1038 int len; /* length of current match */
1039 int best_len = s->prev_length; /* best match length so far */
1040 int nice_match = s->nice_match; /* stop if match long enough */
1041 IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
1042 s->strstart - (IPos)MAX_DIST(s) : NIL;
1043 /* Stop when cur_match becomes <= limit. To simplify the code,
1044 * we prevent matches with the string of window index 0.
1046 Posf *prev = s->prev;
1047 uInt wmask = s->w_mask;
1049 #ifdef UNALIGNED_OK
1050 /* Compare two bytes at a time. Note: this is not always beneficial.
1051 * Try with and without -DUNALIGNED_OK to check.
1053 Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
1054 ush scan_start = *(ushf*)scan;
1055 ush scan_end = *(ushf*)(scan+best_len-1);
1056 #else
1057 Bytef *strend = s->window + s->strstart + MAX_MATCH;
1058 Byte scan_end1 = scan[best_len-1];
1059 Byte scan_end = scan[best_len];
1060 #endif
1062 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1063 * It is easy to get rid of this optimization if necessary.
1065 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1067 /* Do not waste too much time if we already have a good match: */
1068 if (s->prev_length >= s->good_match) {
1069 chain_length >>= 2;
1071 /* Do not look for matches beyond the end of the input. This is necessary
1072 * to make deflate deterministic.
1074 if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
1076 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1078 do {
1079 Assert(cur_match < s->strstart, "no future");
1080 match = s->window + cur_match;
1082 /* Skip to next match if the match length cannot increase
1083 * or if the match length is less than 2. Note that the checks below
1084 * for insufficient lookahead only occur occasionally for performance
1085 * reasons. Therefore uninitialized memory will be accessed, and
1086 * conditional jumps will be made that depend on those values.
1087 * However the length of the match is limited to the lookahead, so
1088 * the output of deflate is not affected by the uninitialized values.
1090 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
1091 /* This code assumes sizeof(unsigned short) == 2. Do not use
1092 * UNALIGNED_OK if your compiler uses a different size.
1094 if (*(ushf*)(match+best_len-1) != scan_end ||
1095 *(ushf*)match != scan_start) continue;
1097 /* It is not necessary to compare scan[2] and match[2] since they are
1098 * always equal when the other bytes match, given that the hash keys
1099 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
1100 * strstart+3, +5, ... up to strstart+257. We check for insufficient
1101 * lookahead only every 4th comparison; the 128th check will be made
1102 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
1103 * necessary to put more guard bytes at the end of the window, or
1104 * to check more often for insufficient lookahead.
1106 Assert(scan[2] == match[2], "scan[2]?");
1107 scan++, match++;
1108 do {
1109 } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1110 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1111 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1112 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1113 scan < strend);
1114 /* The funny "do {}" generates better code on most compilers */
1116 /* Here, scan <= window+strstart+257 */
1117 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1118 if (*scan == *match) scan++;
1120 len = (MAX_MATCH - 1) - (int)(strend-scan);
1121 scan = strend - (MAX_MATCH-1);
1123 #else /* UNALIGNED_OK */
1125 if (match[best_len] != scan_end ||
1126 match[best_len-1] != scan_end1 ||
1127 *match != *scan ||
1128 *++match != scan[1]) continue;
1130 /* The check at best_len-1 can be removed because it will be made
1131 * again later. (This heuristic is not always a win.)
1132 * It is not necessary to compare scan[2] and match[2] since they
1133 * are always equal when the other bytes match, given that
1134 * the hash keys are equal and that HASH_BITS >= 8.
1136 scan += 2, match++;
1137 Assert(*scan == *match, "match[2]?");
1139 /* We check for insufficient lookahead only every 8th comparison;
1140 * the 256th check will be made at strstart+258.
1142 do {
1143 } while (*++scan == *++match && *++scan == *++match &&
1144 *++scan == *++match && *++scan == *++match &&
1145 *++scan == *++match && *++scan == *++match &&
1146 *++scan == *++match && *++scan == *++match &&
1147 scan < strend);
1149 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1151 len = MAX_MATCH - (int)(strend - scan);
1152 scan = strend - MAX_MATCH;
1154 #endif /* UNALIGNED_OK */
1156 if (len > best_len) {
1157 s->match_start = cur_match;
1158 best_len = len;
1159 if (len >= nice_match) break;
1160 #ifdef UNALIGNED_OK
1161 scan_end = *(ushf*)(scan+best_len-1);
1162 #else
1163 scan_end1 = scan[best_len-1];
1164 scan_end = scan[best_len];
1165 #endif
1167 } while ((cur_match = prev[cur_match & wmask]) > limit
1168 && --chain_length != 0);
1170 if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
1171 return s->lookahead;
1173 #endif /* ASMV */
1174 #endif /* FASTEST */
1176 /* ---------------------------------------------------------------------------
1177 * Optimized version for level == 1 or strategy == Z_RLE only
1179 local uInt longest_match_fast(s, cur_match)
1180 deflate_state *s;
1181 IPos cur_match; /* current match */
1183 Bytef *scan = s->window + s->strstart; /* current string */
1184 Bytef *match; /* matched string */
1185 int len; /* length of current match */
1186 Bytef *strend = s->window + s->strstart + MAX_MATCH;
1188 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1189 * It is easy to get rid of this optimization if necessary.
1191 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1193 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1195 Assert(cur_match < s->strstart, "no future");
1197 match = s->window + cur_match;
1199 /* Return failure if the match length is less than 2:
1201 if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
1203 /* The check at best_len-1 can be removed because it will be made
1204 * again later. (This heuristic is not always a win.)
1205 * It is not necessary to compare scan[2] and match[2] since they
1206 * are always equal when the other bytes match, given that
1207 * the hash keys are equal and that HASH_BITS >= 8.
1209 scan += 2, match += 2;
1210 Assert(*scan == *match, "match[2]?");
1212 /* We check for insufficient lookahead only every 8th comparison;
1213 * the 256th check will be made at strstart+258.
1215 do {
1216 } while (*++scan == *++match && *++scan == *++match &&
1217 *++scan == *++match && *++scan == *++match &&
1218 *++scan == *++match && *++scan == *++match &&
1219 *++scan == *++match && *++scan == *++match &&
1220 scan < strend);
1222 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1224 len = MAX_MATCH - (int)(strend - scan);
1226 if (len < MIN_MATCH) return MIN_MATCH - 1;
1228 s->match_start = cur_match;
1229 return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
1232 #ifdef DEBUG
1233 /* ===========================================================================
1234 * Check that the match at match_start is indeed a match.
1236 local void check_match(s, start, match, length)
1237 deflate_state *s;
1238 IPos start, match;
1239 int length;
1241 /* check that the match is indeed a match */
1242 if (zmemcmp(s->window + match,
1243 s->window + start, length) != EQUAL) {
1244 fprintf(stderr, " start %u, match %u, length %d\n",
1245 start, match, length);
1246 do {
1247 fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
1248 } while (--length != 0);
1249 z_error("invalid match");
1251 if (z_verbose > 1) {
1252 fprintf(stderr,"\\[%d,%d]", start-match, length);
1253 do { putc(s->window[start++], stderr); } while (--length != 0);
1256 #else
1257 # define check_match(s, start, match, length)
1258 #endif /* DEBUG */
1260 /* ===========================================================================
1261 * Fill the window when the lookahead becomes insufficient.
1262 * Updates strstart and lookahead.
1264 * IN assertion: lookahead < MIN_LOOKAHEAD
1265 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1266 * At least one byte has been read, or avail_in == 0; reads are
1267 * performed for at least two bytes (required for the zip translate_eol
1268 * option -- not supported here).
1270 local void fill_window(s)
1271 deflate_state *s;
1273 unsigned n, m;
1274 Posf *p;
1275 unsigned more; /* Amount of free space at the end of the window. */
1276 uInt wsize = s->w_size;
1278 do {
1279 more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
1281 /* Deal with !@#$% 64K limit: */
1282 if (sizeof(int) <= 2) {
1283 if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1284 more = wsize;
1286 } else if (more == (unsigned)(-1)) {
1287 /* Very unlikely, but possible on 16 bit machine if
1288 * strstart == 0 && lookahead == 1 (input done a byte at time)
1290 more--;
1294 /* If the window is almost full and there is insufficient lookahead,
1295 * move the upper half to the lower one to make room in the upper half.
1297 if (s->strstart >= wsize+MAX_DIST(s)) {
1299 zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
1300 s->match_start -= wsize;
1301 s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
1302 s->block_start -= (long) wsize;
1304 /* Slide the hash table (could be avoided with 32 bit values
1305 at the expense of memory usage). We slide even when level == 0
1306 to keep the hash table consistent if we switch back to level > 0
1307 later. (Using level 0 permanently is not an optimal usage of
1308 zlib, so we don't care about this pathological case.)
1310 /* %%% avoid this when Z_RLE */
1311 n = s->hash_size;
1312 p = &s->head[n];
1313 do {
1314 m = *--p;
1315 *p = (Pos)(m >= wsize ? m-wsize : NIL);
1316 } while (--n);
1318 n = wsize;
1319 #ifndef FASTEST
1320 p = &s->prev[n];
1321 do {
1322 m = *--p;
1323 *p = (Pos)(m >= wsize ? m-wsize : NIL);
1324 /* If n is not on any hash chain, prev[n] is garbage but
1325 * its value will never be used.
1327 } while (--n);
1328 #endif
1329 more += wsize;
1331 if (s->strm->avail_in == 0) return;
1333 /* If there was no sliding:
1334 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1335 * more == window_size - lookahead - strstart
1336 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1337 * => more >= window_size - 2*WSIZE + 2
1338 * In the BIG_MEM or MMAP case (not yet supported),
1339 * window_size == input_size + MIN_LOOKAHEAD &&
1340 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1341 * Otherwise, window_size == 2*WSIZE so more >= 2.
1342 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1344 Assert(more >= 2, "more < 2");
1346 n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1347 s->lookahead += n;
1349 /* Initialize the hash value now that we have some input: */
1350 if (s->lookahead >= MIN_MATCH) {
1351 s->ins_h = s->window[s->strstart];
1352 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1353 #if MIN_MATCH != 3
1354 Call UPDATE_HASH() MIN_MATCH-3 more times
1355 #endif
1357 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1358 * but this is not important since only literal bytes will be emitted.
1361 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1364 /* ===========================================================================
1365 * Flush the current block, with given end-of-file flag.
1366 * IN assertion: strstart is set to the end of the current match.
1368 #define FLUSH_BLOCK_ONLY(s, eof) { \
1369 _tr_flush_block(s, (s->block_start >= 0L ? \
1370 (charf *)&s->window[(unsigned)s->block_start] : \
1371 (charf *)Z_NULL), \
1372 (ulg)((long)s->strstart - s->block_start), \
1373 (eof)); \
1374 s->block_start = s->strstart; \
1375 flush_pending(s->strm); \
1376 Tracev((stderr,"[FLUSH]")); \
1379 /* Same but force premature exit if necessary. */
1380 #define FLUSH_BLOCK(s, eof) { \
1381 FLUSH_BLOCK_ONLY(s, eof); \
1382 if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
1385 /* ===========================================================================
1386 * Copy without compression as much as possible from the input stream, return
1387 * the current block state.
1388 * This function does not insert new strings in the dictionary since
1389 * uncompressible data is probably not useful. This function is used
1390 * only for the level=0 compression option.
1391 * NOTE: this function should be optimized to avoid extra copying from
1392 * window to pending_buf.
1394 local block_state deflate_stored(s, flush)
1395 deflate_state *s;
1396 int flush;
1398 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
1399 * to pending_buf_size, and each stored block has a 5 byte header:
1401 ulg max_block_size = 0xffff;
1402 ulg max_start;
1404 if (max_block_size > s->pending_buf_size - 5) {
1405 max_block_size = s->pending_buf_size - 5;
1408 /* Copy as much as possible from input to output: */
1409 for (;;) {
1410 /* Fill the window as much as possible: */
1411 if (s->lookahead <= 1) {
1413 Assert(s->strstart < s->w_size+MAX_DIST(s) ||
1414 s->block_start >= (long)s->w_size, "slide too late");
1416 fill_window(s);
1417 if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
1419 if (s->lookahead == 0) break; /* flush the current block */
1421 Assert(s->block_start >= 0L, "block gone");
1423 s->strstart += s->lookahead;
1424 s->lookahead = 0;
1426 /* Emit a stored block if pending_buf will be full: */
1427 max_start = s->block_start + max_block_size;
1428 if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
1429 /* strstart == 0 is possible when wraparound on 16-bit machine */
1430 s->lookahead = (uInt)(s->strstart - max_start);
1431 s->strstart = (uInt)max_start;
1432 FLUSH_BLOCK(s, 0);
1434 /* Flush if we may have to slide, otherwise block_start may become
1435 * negative and the data will be gone:
1437 if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
1438 FLUSH_BLOCK(s, 0);
1441 FLUSH_BLOCK(s, flush == Z_FINISH);
1442 return flush == Z_FINISH ? finish_done : block_done;
1445 /* ===========================================================================
1446 * Compress as much as possible from the input stream, return the current
1447 * block state.
1448 * This function does not perform lazy evaluation of matches and inserts
1449 * new strings in the dictionary only for unmatched strings or for short
1450 * matches. It is used only for the fast compression options.
1452 local block_state deflate_fast(s, flush)
1453 deflate_state *s;
1454 int flush;
1456 IPos hash_head = NIL; /* head of the hash chain */
1457 int bflush; /* set if current block must be flushed */
1459 for (;;) {
1460 /* Make sure that we always have enough lookahead, except
1461 * at the end of the input file. We need MAX_MATCH bytes
1462 * for the next match, plus MIN_MATCH bytes to insert the
1463 * string following the next match.
1465 if (s->lookahead < MIN_LOOKAHEAD) {
1466 fill_window(s);
1467 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1468 return need_more;
1470 if (s->lookahead == 0) break; /* flush the current block */
1473 /* Insert the string window[strstart .. strstart+2] in the
1474 * dictionary, and set hash_head to the head of the hash chain:
1476 if (s->lookahead >= MIN_MATCH) {
1477 INSERT_STRING(s, s->strstart, hash_head);
1480 /* Find the longest match, discarding those <= prev_length.
1481 * At this point we have always match_length < MIN_MATCH
1483 if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1484 /* To simplify the code, we prevent matches with the string
1485 * of window index 0 (in particular we have to avoid a match
1486 * of the string with itself at the start of the input file).
1488 #ifdef FASTEST
1489 if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
1490 (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
1491 s->match_length = longest_match_fast (s, hash_head);
1493 #else
1494 if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
1495 s->match_length = longest_match (s, hash_head);
1496 } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
1497 s->match_length = longest_match_fast (s, hash_head);
1499 #endif
1500 /* longest_match() or longest_match_fast() sets match_start */
1502 if (s->match_length >= MIN_MATCH) {
1503 check_match(s, s->strstart, s->match_start, s->match_length);
1505 _tr_tally_dist(s, s->strstart - s->match_start,
1506 s->match_length - MIN_MATCH, bflush);
1508 s->lookahead -= s->match_length;
1510 /* Insert new strings in the hash table only if the match length
1511 * is not too large. This saves time but degrades compression.
1513 #ifndef FASTEST
1514 if (s->match_length <= s->max_insert_length &&
1515 s->lookahead >= MIN_MATCH) {
1516 s->match_length--; /* string at strstart already in table */
1517 do {
1518 s->strstart++;
1519 INSERT_STRING(s, s->strstart, hash_head);
1520 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1521 * always MIN_MATCH bytes ahead.
1523 } while (--s->match_length != 0);
1524 s->strstart++;
1525 } else
1526 #endif
1528 s->strstart += s->match_length;
1529 s->match_length = 0;
1530 s->ins_h = s->window[s->strstart];
1531 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1532 #if MIN_MATCH != 3
1533 Call UPDATE_HASH() MIN_MATCH-3 more times
1534 #endif
1535 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1536 * matter since it will be recomputed at next deflate call.
1539 } else {
1540 /* No match, output a literal byte */
1541 Tracevv((stderr,"%c", s->window[s->strstart]));
1542 _tr_tally_lit (s, s->window[s->strstart], bflush);
1543 s->lookahead--;
1544 s->strstart++;
1546 if (bflush) FLUSH_BLOCK(s, 0);
1548 FLUSH_BLOCK(s, flush == Z_FINISH);
1549 return flush == Z_FINISH ? finish_done : block_done;
1552 #ifndef FASTEST
1553 /* ===========================================================================
1554 * Same as above, but achieves better compression. We use a lazy
1555 * evaluation for matches: a match is finally adopted only if there is
1556 * no better match at the next window position.
1558 local block_state deflate_slow(s, flush)
1559 deflate_state *s;
1560 int flush;
1562 IPos hash_head = NIL; /* head of hash chain */
1563 int bflush; /* set if current block must be flushed */
1565 /* Process the input block. */
1566 for (;;) {
1567 /* Make sure that we always have enough lookahead, except
1568 * at the end of the input file. We need MAX_MATCH bytes
1569 * for the next match, plus MIN_MATCH bytes to insert the
1570 * string following the next match.
1572 if (s->lookahead < MIN_LOOKAHEAD) {
1573 fill_window(s);
1574 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1575 return need_more;
1577 if (s->lookahead == 0) break; /* flush the current block */
1580 /* Insert the string window[strstart .. strstart+2] in the
1581 * dictionary, and set hash_head to the head of the hash chain:
1583 if (s->lookahead >= MIN_MATCH) {
1584 INSERT_STRING(s, s->strstart, hash_head);
1587 /* Find the longest match, discarding those <= prev_length.
1589 s->prev_length = s->match_length, s->prev_match = s->match_start;
1590 s->match_length = MIN_MATCH-1;
1592 if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
1593 s->strstart - hash_head <= MAX_DIST(s)) {
1594 /* To simplify the code, we prevent matches with the string
1595 * of window index 0 (in particular we have to avoid a match
1596 * of the string with itself at the start of the input file).
1598 if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
1599 s->match_length = longest_match (s, hash_head);
1600 } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
1601 s->match_length = longest_match_fast (s, hash_head);
1603 /* longest_match() or longest_match_fast() sets match_start */
1605 if (s->match_length <= 5 && (s->strategy == Z_FILTERED
1606 #if TOO_FAR <= 32767
1607 || (s->match_length == MIN_MATCH &&
1608 s->strstart - s->match_start > TOO_FAR)
1609 #endif
1610 )) {
1612 /* If prev_match is also MIN_MATCH, match_start is garbage
1613 * but we will ignore the current match anyway.
1615 s->match_length = MIN_MATCH-1;
1618 /* If there was a match at the previous step and the current
1619 * match is not better, output the previous match:
1621 if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
1622 uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
1623 /* Do not insert strings in hash table beyond this. */
1625 check_match(s, s->strstart-1, s->prev_match, s->prev_length);
1627 _tr_tally_dist(s, s->strstart -1 - s->prev_match,
1628 s->prev_length - MIN_MATCH, bflush);
1630 /* Insert in hash table all strings up to the end of the match.
1631 * strstart-1 and strstart are already inserted. If there is not
1632 * enough lookahead, the last two strings are not inserted in
1633 * the hash table.
1635 s->lookahead -= s->prev_length-1;
1636 s->prev_length -= 2;
1637 do {
1638 if (++s->strstart <= max_insert) {
1639 INSERT_STRING(s, s->strstart, hash_head);
1641 } while (--s->prev_length != 0);
1642 s->match_available = 0;
1643 s->match_length = MIN_MATCH-1;
1644 s->strstart++;
1646 if (bflush) FLUSH_BLOCK(s, 0);
1648 } else if (s->match_available) {
1649 /* If there was no match at the previous position, output a
1650 * single literal. If there was a match but the current match
1651 * is longer, truncate the previous match to a single literal.
1653 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1654 _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1655 if (bflush) {
1656 FLUSH_BLOCK_ONLY(s, 0);
1658 s->strstart++;
1659 s->lookahead--;
1660 if (s->strm->avail_out == 0) return need_more;
1661 } else {
1662 /* There is no previous match to compare with, wait for
1663 * the next step to decide.
1665 s->match_available = 1;
1666 s->strstart++;
1667 s->lookahead--;
1670 Assert (flush != Z_NO_FLUSH, "no flush?");
1671 if (s->match_available) {
1672 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1673 _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1674 s->match_available = 0;
1676 FLUSH_BLOCK(s, flush == Z_FINISH);
1677 return flush == Z_FINISH ? finish_done : block_done;
1679 #endif /* FASTEST */
1681 #if 0
1682 /* ===========================================================================
1683 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
1684 * one. Do not maintain a hash table. (It will be regenerated if this run of
1685 * deflate switches away from Z_RLE.)
1687 local block_state deflate_rle(s, flush)
1688 deflate_state *s;
1689 int flush;
1691 int bflush; /* set if current block must be flushed */
1692 uInt run; /* length of run */
1693 uInt max; /* maximum length of run */
1694 uInt prev; /* byte at distance one to match */
1695 Bytef *scan; /* scan for end of run */
1697 for (;;) {
1698 /* Make sure that we always have enough lookahead, except
1699 * at the end of the input file. We need MAX_MATCH bytes
1700 * for the longest encodable run.
1702 if (s->lookahead < MAX_MATCH) {
1703 fill_window(s);
1704 if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
1705 return need_more;
1707 if (s->lookahead == 0) break; /* flush the current block */
1710 /* See how many times the previous byte repeats */
1711 run = 0;
1712 if (s->strstart > 0) { /* if there is a previous byte, that is */
1713 max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
1714 scan = s->window + s->strstart - 1;
1715 prev = *scan++;
1716 do {
1717 if (*scan++ != prev)
1718 break;
1719 } while (++run < max);
1722 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
1723 if (run >= MIN_MATCH) {
1724 check_match(s, s->strstart, s->strstart - 1, run);
1725 _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
1726 s->lookahead -= run;
1727 s->strstart += run;
1728 } else {
1729 /* No match, output a literal byte */
1730 Tracevv((stderr,"%c", s->window[s->strstart]));
1731 _tr_tally_lit (s, s->window[s->strstart], bflush);
1732 s->lookahead--;
1733 s->strstart++;
1735 if (bflush) FLUSH_BLOCK(s, 0);
1737 FLUSH_BLOCK(s, flush == Z_FINISH);
1738 return flush == Z_FINISH ? finish_done : block_done;
1740 #endif