[processor-sdk/open-amp.git] / obsolete / system / generic / machine / zynq7 / linux_firmware / src / zlib / deflate.c
1 /* deflate.c -- compress data using the deflation algorithm
2 * Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
6 /*
7 * ALGORITHM
8 *
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).
12 *
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.
30 *
31 * ACKNOWLEDGEMENTS
32 *
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.
36 *
37 * REFERENCES
38 *
39 * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
40 * Available in http://www.ietf.org/rfc/rfc1951.txt
41 *
42 * A description of the Rabin and Karp algorithm is given in the book
43 * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
44 *
45 * Fiala,E.R., and Greene,D.H.
46 * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
47 *
48 */
50 /* @(#) $Id$ */
52 #include "deflate.h"
54 const char deflate_copyright[] =
55 " deflate 1.2.5 Copyright 1995-2010 Jean-loup Gailly and Mark Adler ";
56 /*
57 If you use the zlib library in a product, an acknowledgment is welcome
58 in the documentation of your product. If for some reason you cannot
59 include such an acknowledgment, I would appreciate that you keep this
60 copyright string in the executable of your product.
61 */
63 /* ===========================================================================
64 * Function prototypes.
65 */
66 typedef enum {
67 need_more, /* block not completed, need more input or more output */
68 block_done, /* block flush performed */
69 finish_started, /* finish started, need only more output at next deflate */
70 finish_done /* finish done, accept no more input or output */
71 } block_state;
73 typedef block_state(*compress_func) OF((deflate_state * s, int flush));
74 /* Compression function. Returns the block state after the call. */
76 local void fill_window OF((deflate_state * s));
77 local block_state deflate_stored OF((deflate_state * s, int flush));
78 local block_state deflate_fast OF((deflate_state * s, int flush));
79 #ifndef FASTEST
80 local block_state deflate_slow OF((deflate_state * s, int flush));
81 #endif
82 local block_state deflate_rle OF((deflate_state * s, int flush));
83 local block_state deflate_huff OF((deflate_state * s, int flush));
84 local void lm_init OF((deflate_state * s));
85 local void putShortMSB OF((deflate_state * s, uInt b));
86 local void flush_pending OF((z_streamp strm));
87 local int read_buf OF((z_streamp strm, Bytef * buf, unsigned size));
88 #ifdef ASMV
89 void match_init OF((void)); /* asm code initialization */
90 uInt longest_match OF((deflate_state * s, IPos cur_match));
91 #else
92 local uInt longest_match OF((deflate_state * s, IPos cur_match));
93 #endif
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
102 */
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 /* Values for max_lazy_match, good_match and max_chain_length, depending on
113 * the desired pack level (0..9). The values given below have been tuned to
114 * exclude worst case performance for pathological files. Better values may be
115 * found for specific files.
116 */
117 typedef struct config_s {
118 ush good_length; /* reduce lazy search above this match length */
119 ush max_lazy; /* do not perform lazy search above this match length */
120 ush nice_length; /* quit search above this match length */
121 ush max_chain;
122 compress_func func;
123 } config;
125 #ifdef FASTEST
126 local const config configuration_table[2] = {
127 /* good lazy nice chain */
128 /* 0 */ {0, 0, 0, 0, deflate_stored},
129 /* store only */
130 /* 1 */ {4, 4, 8, 4, deflate_fast}
131 }; /* max speed, no lazy matches */
132 #else
133 local const config configuration_table[10] = {
134 /* good lazy nice chain */
135 /* 0 */ {0, 0, 0, 0, deflate_stored},
136 /* store only */
137 /* 1 */ {4, 4, 8, 4, deflate_fast},
138 /* max speed, no lazy matches */
139 /* 2 */ {4, 5, 16, 8, deflate_fast},
140 /* 3 */ {4, 6, 32, 32, deflate_fast},
142 /* 4 */ {4, 4, 16, 16, deflate_slow},
143 /* 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}
149 }; /* max compression */
150 #endif
152 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
153 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
154 * meaning.
155 */
157 #define EQUAL 0
158 /* result of memcmp for equal strings */
160 #ifndef NO_DUMMY_DECL
161 struct static_tree_desc_s {
162 int dummy;
163 }; /* for buggy compilers */
164 #endif
166 /* ===========================================================================
167 * Update a hash value with the given input byte
168 * IN assertion: all calls to to UPDATE_HASH are made with consecutive
169 * input characters, so that a running hash key can be computed from the
170 * previous key instead of complete recalculation each time.
171 */
172 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
174 /* ===========================================================================
175 * Insert string str in the dictionary and set match_head to the previous head
176 * of the hash chain (the most recent string with same hash key). Return
177 * the previous length of the hash chain.
178 * If this file is compiled with -DFASTEST, the compression level is forced
179 * to 1, and no hash chains are maintained.
180 * IN assertion: all calls to to INSERT_STRING are made with consecutive
181 * input characters and the first MIN_MATCH bytes of str are valid
182 * (except for the last MIN_MATCH-1 bytes of the input file).
183 */
184 #ifdef FASTEST
185 #define INSERT_STRING(s, str, match_head) \
186 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
187 match_head = s->head[s->ins_h], \
188 s->head[s->ins_h] = (Pos)(str))
189 #else
190 #define INSERT_STRING(s, str, match_head) \
191 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
192 match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
193 s->head[s->ins_h] = (Pos)(str))
194 #endif
196 /* ===========================================================================
197 * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
198 * prev[] will be initialized on the fly.
199 */
200 #define CLEAR_HASH(s) \
201 s->head[s->hash_size-1] = NIL; \
202 zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
204 /* ========================================================================= */
205 int ZEXPORT deflateInit_(strm, level, version, stream_size)
206 z_streamp strm;
207 int level;
208 const char *version;
209 int stream_size;
210 {
211 return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
212 Z_DEFAULT_STRATEGY, version, stream_size);
213 /* To do: ignore strm->next_in if we use it as window */
214 }
216 /* ========================================================================= */
217 int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
218 version, stream_size)
219 z_streamp strm;
220 int level;
221 int method;
222 int windowBits;
223 int memLevel;
224 int strategy;
225 const char *version;
226 int stream_size;
227 {
228 deflate_state *s;
229 int wrap = 1;
230 static const char my_version[] = ZLIB_VERSION;
232 ushf *overlay;
233 /* We overlay pending_buf and d_buf+l_buf. This works since the average
234 * output size for (length,distance) codes is <= 24 bits.
235 */
237 if (version == Z_NULL || version[0] != my_version[0] ||
238 stream_size != sizeof(z_stream)) {
239 return Z_VERSION_ERROR;
240 }
241 if (strm == Z_NULL)
242 return Z_STREAM_ERROR;
244 strm->msg = Z_NULL;
245 if (strm->zalloc == (alloc_func) 0) {
246 strm->zalloc = zcalloc;
247 strm->opaque = (voidpf) 0;
248 }
249 if (strm->zfree == (free_func) 0)
250 strm->zfree = zcfree;
252 #ifdef FASTEST
253 if (level != 0)
254 level = 1;
255 #else
256 if (level == Z_DEFAULT_COMPRESSION)
257 level = 6;
258 #endif
260 if (windowBits < 0) { /* suppress zlib wrapper */
261 wrap = 0;
262 windowBits = -windowBits;
263 }
264 #ifdef GZIP
265 else if (windowBits > 15) {
266 wrap = 2; /* write gzip wrapper instead */
267 windowBits -= 16;
268 }
269 #endif
270 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
271 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
272 strategy < 0 || strategy > Z_FIXED) {
273 return Z_STREAM_ERROR;
274 }
275 if (windowBits == 8)
276 windowBits = 9; /* until 256-byte window bug fixed */
277 s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
278 if (s == Z_NULL)
279 return Z_MEM_ERROR;
280 strm->state = (struct internal_state FAR *)s;
281 s->strm = strm;
283 s->wrap = wrap;
284 s->gzhead = Z_NULL;
285 s->w_bits = windowBits;
286 s->w_size = 1 << s->w_bits;
287 s->w_mask = s->w_size - 1;
289 s->hash_bits = memLevel + 7;
290 s->hash_size = 1 << s->hash_bits;
291 s->hash_mask = s->hash_size - 1;
292 s->hash_shift = ((s->hash_bits + MIN_MATCH - 1) / MIN_MATCH);
294 s->window = (Bytef *) ZALLOC(strm, s->w_size, 2 * sizeof(Byte));
295 s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
296 s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
298 s->high_water = 0; /* nothing written to s->window yet */
300 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
302 overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush) + 2);
303 s->pending_buf = (uchf *) overlay;
304 s->pending_buf_size = (ulg) s->lit_bufsize * (sizeof(ush) + 2L);
306 if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
307 s->pending_buf == Z_NULL) {
308 s->status = FINISH_STATE;
309 strm->msg = (char *)ERR_MSG(Z_MEM_ERROR);
310 deflateEnd(strm);
311 return Z_MEM_ERROR;
312 }
313 s->d_buf = overlay + s->lit_bufsize / sizeof(ush);
314 s->l_buf = s->pending_buf + (1 + sizeof(ush)) * s->lit_bufsize;
316 s->level = level;
317 s->strategy = strategy;
318 s->method = (Byte) method;
320 return deflateReset(strm);
321 }
323 /* ========================================================================= */
324 int ZEXPORT deflateSetDictionary(strm, dictionary, dictLength)
325 z_streamp strm;
326 const Bytef *dictionary;
327 uInt dictLength;
328 {
329 deflate_state *s;
330 uInt length = dictLength;
331 uInt n;
332 IPos hash_head = 0;
334 if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
335 strm->state->wrap == 2 ||
336 (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
337 return Z_STREAM_ERROR;
339 s = strm->state;
340 if (s->wrap)
341 strm->adler = adler32(strm->adler, dictionary, dictLength);
343 if (length < MIN_MATCH)
344 return Z_OK;
345 if (length > s->w_size) {
346 length = s->w_size;
347 dictionary += dictLength - length; /* use the tail of the dictionary */
348 }
349 zmemcpy(s->window, dictionary, length);
350 s->strstart = length;
351 s->block_start = (long)length;
353 /* Insert all strings in the hash table (except for the last two bytes).
354 * s->lookahead stays null, so s->ins_h will be recomputed at the next
355 * call of fill_window.
356 */
357 s->ins_h = s->window[0];
358 UPDATE_HASH(s, s->ins_h, s->window[1]);
359 for (n = 0; n <= length - MIN_MATCH; n++) {
360 INSERT_STRING(s, n, hash_head);
361 }
362 if (hash_head)
363 hash_head = 0; /* to make compiler happy */
364 return Z_OK;
365 }
367 /* ========================================================================= */
368 int ZEXPORT deflateReset(strm)
369 z_streamp strm;
370 {
371 deflate_state *s;
373 if (strm == Z_NULL || strm->state == Z_NULL ||
374 strm->zalloc == (alloc_func) 0 || strm->zfree == (free_func) 0) {
375 return Z_STREAM_ERROR;
376 }
378 strm->total_in = strm->total_out = 0;
379 strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
380 strm->data_type = Z_UNKNOWN;
382 s = (deflate_state *) strm->state;
383 s->pending = 0;
384 s->pending_out = s->pending_buf;
386 if (s->wrap < 0) {
387 s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
388 }
389 s->status = s->wrap ? INIT_STATE : BUSY_STATE;
390 strm->adler =
391 #ifdef GZIP
392 s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
393 #endif
394 adler32(0L, Z_NULL, 0);
395 s->last_flush = Z_NO_FLUSH;
397 _tr_init(s);
398 lm_init(s);
400 return Z_OK;
401 }
403 /* ========================================================================= */
404 int ZEXPORT deflateSetHeader(strm, head)
405 z_streamp strm;
406 gz_headerp head;
407 {
408 if (strm == Z_NULL || strm->state == Z_NULL)
409 return Z_STREAM_ERROR;
410 if (strm->state->wrap != 2)
411 return Z_STREAM_ERROR;
412 strm->state->gzhead = head;
413 return Z_OK;
414 }
416 /* ========================================================================= */
417 int ZEXPORT deflatePrime(strm, bits, value)
418 z_streamp strm;
419 int bits;
420 int value;
421 {
422 if (strm == Z_NULL || strm->state == Z_NULL)
423 return Z_STREAM_ERROR;
424 strm->state->bi_valid = bits;
425 strm->state->bi_buf = (ush) (value & ((1 << bits) - 1));
426 return Z_OK;
427 }
429 /* ========================================================================= */
430 int ZEXPORT deflateParams(strm, level, strategy)
431 z_streamp strm;
432 int level;
433 int strategy;
434 {
435 deflate_state *s;
436 compress_func func;
437 int err = Z_OK;
439 if (strm == Z_NULL || strm->state == Z_NULL)
440 return Z_STREAM_ERROR;
441 s = strm->state;
443 #ifdef FASTEST
444 if (level != 0)
445 level = 1;
446 #else
447 if (level == Z_DEFAULT_COMPRESSION)
448 level = 6;
449 #endif
450 if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
451 return Z_STREAM_ERROR;
452 }
453 func = configuration_table[s->level].func;
455 if ((strategy != s->strategy || func != configuration_table[level].func)
456 && strm->total_in != 0) {
457 /* Flush the last buffer: */
458 err = deflate(strm, Z_BLOCK);
459 }
460 if (s->level != level) {
461 s->level = level;
462 s->max_lazy_match = configuration_table[level].max_lazy;
463 s->good_match = configuration_table[level].good_length;
464 s->nice_match = configuration_table[level].nice_length;
465 s->max_chain_length = configuration_table[level].max_chain;
466 }
467 s->strategy = strategy;
468 return err;
469 }
471 /* ========================================================================= */
472 int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
473 z_streamp strm;
474 int good_length;
475 int max_lazy;
476 int nice_length;
477 int max_chain;
478 {
479 deflate_state *s;
481 if (strm == Z_NULL || strm->state == Z_NULL)
482 return Z_STREAM_ERROR;
483 s = strm->state;
484 s->good_match = good_length;
485 s->max_lazy_match = max_lazy;
486 s->nice_match = nice_length;
487 s->max_chain_length = max_chain;
488 return Z_OK;
489 }
491 /* =========================================================================
492 * For the default windowBits of 15 and memLevel of 8, this function returns
493 * a close to exact, as well as small, upper bound on the compressed size.
494 * They are coded as constants here for a reason--if the #define's are
495 * changed, then this function needs to be changed as well. The return
496 * value for 15 and 8 only works for those exact settings.
497 *
498 * For any setting other than those defaults for windowBits and memLevel,
499 * the value returned is a conservative worst case for the maximum expansion
500 * resulting from using fixed blocks instead of stored blocks, which deflate
501 * can emit on compressed data for some combinations of the parameters.
502 *
503 * This function could be more sophisticated to provide closer upper bounds for
504 * every combination of windowBits and memLevel. But even the conservative
505 * upper bound of about 14% expansion does not seem onerous for output buffer
506 * allocation.
507 */
508 uLong ZEXPORT deflateBound(strm, sourceLen)
509 z_streamp strm;
510 uLong sourceLen;
511 {
512 deflate_state *s;
513 uLong complen, wraplen;
514 Bytef *str;
516 /* conservative upper bound for compressed data */
517 complen = sourceLen +
518 ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
520 /* if can't get parameters, return conservative bound plus zlib wrapper */
521 if (strm == Z_NULL || strm->state == Z_NULL)
522 return complen + 6;
524 /* compute wrapper length */
525 s = strm->state;
526 switch (s->wrap) {
527 case 0: /* raw deflate */
528 wraplen = 0;
529 break;
530 case 1: /* zlib wrapper */
531 wraplen = 6 + (s->strstart ? 4 : 0);
532 break;
533 case 2: /* gzip wrapper */
534 wraplen = 18;
535 if (s->gzhead != Z_NULL) { /* user-supplied gzip header */
536 if (s->gzhead->extra != Z_NULL)
537 wraplen += 2 + s->gzhead->extra_len;
538 str = s->gzhead->name;
539 if (str != Z_NULL)
540 do {
541 wraplen++;
542 } while (*str++);
543 str = s->gzhead->comment;
544 if (str != Z_NULL)
545 do {
546 wraplen++;
547 } while (*str++);
548 if (s->gzhead->hcrc)
549 wraplen += 2;
550 }
551 break;
552 default: /* for compiler happiness */
553 wraplen = 6;
554 }
556 /* if not default parameters, return conservative bound */
557 if (s->w_bits != 15 || s->hash_bits != 8 + 7)
558 return complen + wraplen;
560 /* default settings: return tight bound for that case */
561 return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
562 (sourceLen >> 25) + 13 - 6 + wraplen;
563 }
565 /* =========================================================================
566 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
567 * IN assertion: the stream state is correct and there is enough room in
568 * pending_buf.
569 */
570 local void putShortMSB(s, b)
571 deflate_state *s;
572 uInt b;
573 {
574 put_byte(s, (Byte) (b >> 8));
575 put_byte(s, (Byte) (b & 0xff));
576 }
578 /* =========================================================================
579 * Flush as much pending output as possible. All deflate() output goes
580 * through this function so some applications may wish to modify it
581 * to avoid allocating a large strm->next_out buffer and copying into it.
582 * (See also read_buf()).
583 */
584 local void flush_pending(strm)
585 z_streamp strm;
586 {
587 unsigned len = strm->state->pending;
589 if (len > strm->avail_out)
590 len = strm->avail_out;
591 if (len == 0)
592 return;
594 zmemcpy(strm->next_out, strm->state->pending_out, len);
595 strm->next_out += len;
596 strm->state->pending_out += len;
597 strm->total_out += len;
598 strm->avail_out -= len;
599 strm->state->pending -= len;
600 if (strm->state->pending == 0) {
601 strm->state->pending_out = strm->state->pending_buf;
602 }
603 }
605 /* ========================================================================= */
606 int ZEXPORT deflate(strm, flush)
607 z_streamp strm;
608 int flush;
609 {
610 int old_flush; /* value of flush param for previous deflate call */
611 deflate_state *s;
613 if (strm == Z_NULL || strm->state == Z_NULL ||
614 flush > Z_BLOCK || flush < 0) {
615 return Z_STREAM_ERROR;
616 }
617 s = strm->state;
619 if (strm->next_out == Z_NULL ||
620 (strm->next_in == Z_NULL && strm->avail_in != 0) ||
621 (s->status == FINISH_STATE && flush != Z_FINISH)) {
622 ERR_RETURN(strm, Z_STREAM_ERROR);
623 }
624 if (strm->avail_out == 0)
625 ERR_RETURN(strm, Z_BUF_ERROR);
627 s->strm = strm; /* just in case */
628 old_flush = s->last_flush;
629 s->last_flush = flush;
631 /* Write the header */
632 if (s->status == INIT_STATE) {
633 #ifdef GZIP
634 if (s->wrap == 2) {
635 strm->adler = crc32(0L, Z_NULL, 0);
636 put_byte(s, 31);
637 put_byte(s, 139);
638 put_byte(s, 8);
639 if (s->gzhead == Z_NULL) {
640 put_byte(s, 0);
641 put_byte(s, 0);
642 put_byte(s, 0);
643 put_byte(s, 0);
644 put_byte(s, 0);
645 put_byte(s, s->level == 9 ? 2 :
646 (s->strategy >= Z_HUFFMAN_ONLY
647 || s->level < 2 ? 4 : 0));
648 put_byte(s, OS_CODE);
649 s->status = BUSY_STATE;
650 } else {
651 put_byte(s, (s->gzhead->text ? 1 : 0) +
652 (s->gzhead->hcrc ? 2 : 0) +
653 (s->gzhead->extra == Z_NULL ? 0 : 4) +
654 (s->gzhead->name == Z_NULL ? 0 : 8) +
655 (s->gzhead->comment == Z_NULL ? 0 : 16)
656 );
657 put_byte(s, (Byte) (s->gzhead->time & 0xff));
658 put_byte(s,
659 (Byte) ((s->gzhead->
660 time >> 8) & 0xff));
661 put_byte(s,
662 (Byte) ((s->gzhead->
663 time >> 16) & 0xff));
664 put_byte(s,
665 (Byte) ((s->gzhead->
666 time >> 24) & 0xff));
667 put_byte(s,
668 s->level == 9 ? 2 : (s->strategy >=
669 Z_HUFFMAN_ONLY
670 || s->level <
671 2 ? 4 : 0));
672 put_byte(s, s->gzhead->os & 0xff);
673 if (s->gzhead->extra != Z_NULL) {
674 put_byte(s,
675 s->gzhead->extra_len & 0xff);
676 put_byte(s,
677 (s->gzhead->
678 extra_len >> 8) & 0xff);
679 }
680 if (s->gzhead->hcrc)
681 strm->adler =
682 crc32(strm->adler, s->pending_buf,
683 s->pending);
684 s->gzindex = 0;
685 s->status = EXTRA_STATE;
686 }
687 } else
688 #endif
689 {
690 uInt header =
691 (Z_DEFLATED + ((s->w_bits - 8) << 4)) << 8;
692 uInt level_flags;
694 if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
695 level_flags = 0;
696 else if (s->level < 6)
697 level_flags = 1;
698 else if (s->level == 6)
699 level_flags = 2;
700 else
701 level_flags = 3;
702 header |= (level_flags << 6);
703 if (s->strstart != 0)
704 header |= PRESET_DICT;
705 header += 31 - (header % 31);
707 s->status = BUSY_STATE;
708 putShortMSB(s, header);
710 /* Save the adler32 of the preset dictionary: */
711 if (s->strstart != 0) {
712 putShortMSB(s, (uInt) (strm->adler >> 16));
713 putShortMSB(s, (uInt) (strm->adler & 0xffff));
714 }
715 strm->adler = adler32(0L, Z_NULL, 0);
716 }
717 }
718 #ifdef GZIP
719 if (s->status == EXTRA_STATE) {
720 if (s->gzhead->extra != Z_NULL) {
721 uInt beg = s->pending; /* start of bytes to update crc */
723 while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
724 if (s->pending == s->pending_buf_size) {
725 if (s->gzhead->hcrc && s->pending > beg)
726 strm->adler =
727 crc32(strm->adler,
728 s->pending_buf + beg,
729 s->pending - beg);
730 flush_pending(strm);
731 beg = s->pending;
732 if (s->pending == s->pending_buf_size)
733 break;
734 }
735 put_byte(s, s->gzhead->extra[s->gzindex]);
736 s->gzindex++;
737 }
738 if (s->gzhead->hcrc && s->pending > beg)
739 strm->adler =
740 crc32(strm->adler, s->pending_buf + beg,
741 s->pending - beg);
742 if (s->gzindex == s->gzhead->extra_len) {
743 s->gzindex = 0;
744 s->status = NAME_STATE;
745 }
746 } else
747 s->status = NAME_STATE;
748 }
749 if (s->status == NAME_STATE) {
750 if (s->gzhead->name != Z_NULL) {
751 uInt beg = s->pending; /* start of bytes to update crc */
752 int val;
754 do {
755 if (s->pending == s->pending_buf_size) {
756 if (s->gzhead->hcrc && s->pending > beg)
757 strm->adler =
758 crc32(strm->adler,
759 s->pending_buf + beg,
760 s->pending - beg);
761 flush_pending(strm);
762 beg = s->pending;
763 if (s->pending == s->pending_buf_size) {
764 val = 1;
765 break;
766 }
767 }
768 val = s->gzhead->name[s->gzindex++];
769 put_byte(s, val);
770 } while (val != 0);
771 if (s->gzhead->hcrc && s->pending > beg)
772 strm->adler =
773 crc32(strm->adler, s->pending_buf + beg,
774 s->pending - beg);
775 if (val == 0) {
776 s->gzindex = 0;
777 s->status = COMMENT_STATE;
778 }
779 } else
780 s->status = COMMENT_STATE;
781 }
782 if (s->status == COMMENT_STATE) {
783 if (s->gzhead->comment != Z_NULL) {
784 uInt beg = s->pending; /* start of bytes to update crc */
785 int val;
787 do {
788 if (s->pending == s->pending_buf_size) {
789 if (s->gzhead->hcrc && s->pending > beg)
790 strm->adler =
791 crc32(strm->adler,
792 s->pending_buf + beg,
793 s->pending - beg);
794 flush_pending(strm);
795 beg = s->pending;
796 if (s->pending == s->pending_buf_size) {
797 val = 1;
798 break;
799 }
800 }
801 val = s->gzhead->comment[s->gzindex++];
802 put_byte(s, val);
803 } while (val != 0);
804 if (s->gzhead->hcrc && s->pending > beg)
805 strm->adler =
806 crc32(strm->adler, s->pending_buf + beg,
807 s->pending - beg);
808 if (val == 0)
809 s->status = HCRC_STATE;
810 } else
811 s->status = HCRC_STATE;
812 }
813 if (s->status == HCRC_STATE) {
814 if (s->gzhead->hcrc) {
815 if (s->pending + 2 > s->pending_buf_size)
816 flush_pending(strm);
817 if (s->pending + 2 <= s->pending_buf_size) {
818 put_byte(s, (Byte) (strm->adler & 0xff));
819 put_byte(s, (Byte) ((strm->adler >> 8) & 0xff));
820 strm->adler = crc32(0L, Z_NULL, 0);
821 s->status = BUSY_STATE;
822 }
823 } else
824 s->status = BUSY_STATE;
825 }
826 #endif
828 /* Flush as much pending output as possible */
829 if (s->pending != 0) {
830 flush_pending(strm);
831 if (strm->avail_out == 0) {
832 /* Since avail_out is 0, deflate will be called again with
833 * more output space, but possibly with both pending and
834 * avail_in equal to zero. There won't be anything to do,
835 * but this is not an error situation so make sure we
836 * return OK instead of BUF_ERROR at next call of deflate:
837 */
838 s->last_flush = -1;
839 return Z_OK;
840 }
842 /* Make sure there is something to do and avoid duplicate consecutive
843 * flushes. For repeated and useless calls with Z_FINISH, we keep
844 * returning Z_STREAM_END instead of Z_BUF_ERROR.
845 */
846 } else if (strm->avail_in == 0 && flush <= old_flush &&
847 flush != Z_FINISH) {
848 ERR_RETURN(strm, Z_BUF_ERROR);
849 }
851 /* User must not provide more input after the first FINISH: */
852 if (s->status == FINISH_STATE && strm->avail_in != 0) {
853 ERR_RETURN(strm, Z_BUF_ERROR);
854 }
856 /* Start a new block or continue the current one.
857 */
858 if (strm->avail_in != 0 || s->lookahead != 0 ||
859 (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
860 block_state bstate;
862 bstate =
863 s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s,
864 flush) : (s->
865 strategy
866 ==
867 Z_RLE
868 ?
869 deflate_rle
870 (s,
871 flush)
872 : (*
873 (configuration_table
874 [s->
875 level].
876 func))
877 (s,
878 flush));
880 if (bstate == finish_started || bstate == finish_done) {
881 s->status = FINISH_STATE;
882 }
883 if (bstate == need_more || bstate == finish_started) {
884 if (strm->avail_out == 0) {
885 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
886 }
887 return Z_OK;
888 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
889 * of deflate should use the same flush parameter to make sure
890 * that the flush is complete. So we don't have to output an
891 * empty block here, this will be done at next call. This also
892 * ensures that for a very small output buffer, we emit at most
893 * one empty block.
894 */
895 }
896 if (bstate == block_done) {
897 if (flush == Z_PARTIAL_FLUSH) {
898 _tr_align(s);
899 } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
900 _tr_stored_block(s, (char *)0, 0L, 0);
901 /* For a full flush, this empty block will be recognized
902 * as a special marker by inflate_sync().
903 */
904 if (flush == Z_FULL_FLUSH) {
905 CLEAR_HASH(s); /* forget history */
906 if (s->lookahead == 0) {
907 s->strstart = 0;
908 s->block_start = 0L;
909 }
910 }
911 }
912 flush_pending(strm);
913 if (strm->avail_out == 0) {
914 s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
915 return Z_OK;
916 }
917 }
918 }
919 Assert(strm->avail_out > 0, "bug2");
921 if (flush != Z_FINISH)
922 return Z_OK;
923 if (s->wrap <= 0)
924 return Z_STREAM_END;
926 /* Write the trailer */
927 #ifdef GZIP
928 if (s->wrap == 2) {
929 put_byte(s, (Byte) (strm->adler & 0xff));
930 put_byte(s, (Byte) ((strm->adler >> 8) & 0xff));
931 put_byte(s, (Byte) ((strm->adler >> 16) & 0xff));
932 put_byte(s, (Byte) ((strm->adler >> 24) & 0xff));
933 put_byte(s, (Byte) (strm->total_in & 0xff));
934 put_byte(s, (Byte) ((strm->total_in >> 8) & 0xff));
935 put_byte(s, (Byte) ((strm->total_in >> 16) & 0xff));
936 put_byte(s, (Byte) ((strm->total_in >> 24) & 0xff));
937 } else
938 #endif
939 {
940 putShortMSB(s, (uInt) (strm->adler >> 16));
941 putShortMSB(s, (uInt) (strm->adler & 0xffff));
942 }
943 flush_pending(strm);
944 /* If avail_out is zero, the application will call deflate again
945 * to flush the rest.
946 */
947 if (s->wrap > 0)
948 s->wrap = -s->wrap; /* write the trailer only once! */
949 return s->pending != 0 ? Z_OK : Z_STREAM_END;
950 }
952 /* ========================================================================= */
953 int ZEXPORT deflateEnd(strm)
954 z_streamp strm;
955 {
956 int status;
958 if (strm == Z_NULL || strm->state == Z_NULL)
959 return Z_STREAM_ERROR;
961 status = strm->state->status;
962 if (status != INIT_STATE &&
963 status != EXTRA_STATE &&
964 status != NAME_STATE &&
965 status != COMMENT_STATE &&
966 status != HCRC_STATE &&
967 status != BUSY_STATE && status != FINISH_STATE) {
968 return Z_STREAM_ERROR;
969 }
971 /* Deallocate in reverse order of allocations: */
972 TRY_FREE(strm, strm->state->pending_buf);
973 TRY_FREE(strm, strm->state->head);
974 TRY_FREE(strm, strm->state->prev);
975 TRY_FREE(strm, strm->state->window);
977 ZFREE(strm, strm->state);
978 strm->state = Z_NULL;
980 return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
981 }
983 /* =========================================================================
984 * Copy the source state to the destination state.
985 * To simplify the source, this is not supported for 16-bit MSDOS (which
986 * doesn't have enough memory anyway to duplicate compression states).
987 */
988 int ZEXPORT deflateCopy(dest, source)
989 z_streamp dest;
990 z_streamp source;
991 {
992 #ifdef MAXSEG_64K
993 return Z_STREAM_ERROR;
994 #else
995 deflate_state *ds;
996 deflate_state *ss;
997 ushf *overlay;
999 if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
1000 return Z_STREAM_ERROR;
1001 }
1003 ss = source->state;
1005 zmemcpy(dest, source, sizeof(z_stream));
1007 ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
1008 if (ds == Z_NULL)
1009 return Z_MEM_ERROR;
1010 dest->state = (struct internal_state FAR *)ds;
1011 zmemcpy(ds, ss, sizeof(deflate_state));
1012 ds->strm = dest;
1014 ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2 * sizeof(Byte));
1015 ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
1016 ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
1017 overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush) + 2);
1018 ds->pending_buf = (uchf *) overlay;
1020 if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
1021 ds->pending_buf == Z_NULL) {
1022 deflateEnd(dest);
1023 return Z_MEM_ERROR;
1024 }
1025 /* following zmemcpy do not work for 16-bit MSDOS */
1026 zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
1027 zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
1028 zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
1029 zmemcpy(ds->pending_buf, ss->pending_buf, (uInt) ds->pending_buf_size);
1031 ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
1032 ds->d_buf = overlay + ds->lit_bufsize / sizeof(ush);
1033 ds->l_buf = ds->pending_buf + (1 + sizeof(ush)) * ds->lit_bufsize;
1035 ds->l_desc.dyn_tree = ds->dyn_ltree;
1036 ds->d_desc.dyn_tree = ds->dyn_dtree;
1037 ds->bl_desc.dyn_tree = ds->bl_tree;
1039 return Z_OK;
1040 #endif /* MAXSEG_64K */
1041 }
1043 /* ===========================================================================
1044 * Read a new buffer from the current input stream, update the adler32
1045 * and total number of bytes read. All deflate() input goes through
1046 * this function so some applications may wish to modify it to avoid
1047 * allocating a large strm->next_in buffer and copying from it.
1048 * (See also flush_pending()).
1049 */
1050 local int read_buf(strm, buf, size)
1051 z_streamp strm;
1052 Bytef *buf;
1053 unsigned size;
1054 {
1055 unsigned len = strm->avail_in;
1057 if (len > size)
1058 len = size;
1059 if (len == 0)
1060 return 0;
1062 strm->avail_in -= len;
1064 if (strm->state->wrap == 1) {
1065 strm->adler = adler32(strm->adler, strm->next_in, len);
1066 }
1067 #ifdef GZIP
1068 else if (strm->state->wrap == 2) {
1069 strm->adler = crc32(strm->adler, strm->next_in, len);
1070 }
1071 #endif
1072 zmemcpy(buf, strm->next_in, len);
1073 strm->next_in += len;
1074 strm->total_in += len;
1076 return (int)len;
1077 }
1079 /* ===========================================================================
1080 * Initialize the "longest match" routines for a new zlib stream
1081 */
1082 local void lm_init(s)
1083 deflate_state *s;
1084 {
1085 s->window_size = (ulg) 2L *s->w_size;
1087 CLEAR_HASH(s);
1089 /* Set the default configuration parameters:
1090 */
1091 s->max_lazy_match = configuration_table[s->level].max_lazy;
1092 s->good_match = configuration_table[s->level].good_length;
1093 s->nice_match = configuration_table[s->level].nice_length;
1094 s->max_chain_length = configuration_table[s->level].max_chain;
1096 s->strstart = 0;
1097 s->block_start = 0L;
1098 s->lookahead = 0;
1099 s->match_length = s->prev_length = MIN_MATCH - 1;
1100 s->match_available = 0;
1101 s->ins_h = 0;
1102 #ifndef FASTEST
1103 #ifdef ASMV
1104 match_init(); /* initialize the asm code */
1105 #endif
1106 #endif
1107 }
1109 #ifndef FASTEST
1110 /* ===========================================================================
1111 * Set match_start to the longest match starting at the given string and
1112 * return its length. Matches shorter or equal to prev_length are discarded,
1113 * in which case the result is equal to prev_length and match_start is
1114 * garbage.
1115 * IN assertions: cur_match is the head of the hash chain for the current
1116 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1117 * OUT assertion: the match length is not greater than s->lookahead.
1118 */
1119 #ifndef ASMV
1120 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
1121 * match.S. The code will be functionally equivalent.
1122 */
1123 local uInt longest_match(s, cur_match)
1124 deflate_state *s;
1125 IPos cur_match; /* current match */
1126 {
1127 unsigned chain_length = s->max_chain_length; /* max hash chain length */
1128 register Bytef *scan = s->window + s->strstart; /* current string */
1129 register Bytef *match; /* matched string */
1130 register int len; /* length of current match */
1131 int best_len = s->prev_length; /* best match length so far */
1132 int nice_match = s->nice_match; /* stop if match long enough */
1133 IPos limit = s->strstart > (IPos) MAX_DIST(s) ?
1134 s->strstart - (IPos) MAX_DIST(s) : NIL;
1135 /* Stop when cur_match becomes <= limit. To simplify the code,
1136 * we prevent matches with the string of window index 0.
1137 */
1138 Posf *prev = s->prev;
1139 uInt wmask = s->w_mask;
1141 #ifdef UNALIGNED_OK
1142 /* Compare two bytes at a time. Note: this is not always beneficial.
1143 * Try with and without -DUNALIGNED_OK to check.
1144 */
1145 register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
1146 register ush scan_start = *(ushf *) scan;
1147 register ush scan_end = *(ushf *) (scan + best_len - 1);
1148 #else
1149 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1150 register Byte scan_end1 = scan[best_len - 1];
1151 register Byte scan_end = scan[best_len];
1152 #endif
1154 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1155 * It is easy to get rid of this optimization if necessary.
1156 */
1157 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1159 /* Do not waste too much time if we already have a good match: */
1160 if (s->prev_length >= s->good_match) {
1161 chain_length >>= 2;
1162 }
1163 /* Do not look for matches beyond the end of the input. This is necessary
1164 * to make deflate deterministic.
1165 */
1166 if ((uInt) nice_match > s->lookahead)
1167 nice_match = s->lookahead;
1169 Assert((ulg) s->strstart <= s->window_size - MIN_LOOKAHEAD,
1170 "need lookahead");
1172 do {
1173 Assert(cur_match < s->strstart, "no future");
1174 match = s->window + cur_match;
1176 /* Skip to next match if the match length cannot increase
1177 * or if the match length is less than 2. Note that the checks below
1178 * for insufficient lookahead only occur occasionally for performance
1179 * reasons. Therefore uninitialized memory will be accessed, and
1180 * conditional jumps will be made that depend on those values.
1181 * However the length of the match is limited to the lookahead, so
1182 * the output of deflate is not affected by the uninitialized values.
1183 */
1184 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
1185 /* This code assumes sizeof(unsigned short) == 2. Do not use
1186 * UNALIGNED_OK if your compiler uses a different size.
1187 */
1188 if (*(ushf *) (match + best_len - 1) != scan_end ||
1189 *(ushf *) match != scan_start)
1190 continue;
1192 /* It is not necessary to compare scan[2] and match[2] since they are
1193 * always equal when the other bytes match, given that the hash keys
1194 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
1195 * strstart+3, +5, ... up to strstart+257. We check for insufficient
1196 * lookahead only every 4th comparison; the 128th check will be made
1197 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
1198 * necessary to put more guard bytes at the end of the window, or
1199 * to check more often for insufficient lookahead.
1200 */
1201 Assert(scan[2] == match[2], "scan[2]?");
1202 scan++, match++;
1203 do {
1204 } while (*(ushf *) (scan += 2) == *(ushf *) (match += 2) &&
1205 *(ushf *) (scan += 2) == *(ushf *) (match += 2) &&
1206 *(ushf *) (scan += 2) == *(ushf *) (match += 2) &&
1207 *(ushf *) (scan += 2) == *(ushf *) (match += 2) &&
1208 scan < strend);
1209 /* The funny "do {}" generates better code on most compilers */
1211 /* Here, scan <= window+strstart+257 */
1212 Assert(scan <= s->window + (unsigned)(s->window_size - 1),
1213 "wild scan");
1214 if (*scan == *match)
1215 scan++;
1217 len = (MAX_MATCH - 1) - (int)(strend - scan);
1218 scan = strend - (MAX_MATCH - 1);
1220 #else /* UNALIGNED_OK */
1222 if (match[best_len] != scan_end ||
1223 match[best_len - 1] != scan_end1 ||
1224 *match != *scan || *++match != scan[1])
1225 continue;
1227 /* The check at best_len-1 can be removed because it will be made
1228 * again later. (This heuristic is not always a win.)
1229 * It is not necessary to compare scan[2] and match[2] since they
1230 * are always equal when the other bytes match, given that
1231 * the hash keys are equal and that HASH_BITS >= 8.
1232 */
1233 scan += 2, match++;
1234 Assert(*scan == *match, "match[2]?");
1236 /* We check for insufficient lookahead only every 8th comparison;
1237 * the 256th check will be made at strstart+258.
1238 */
1239 do {
1240 } while (*++scan == *++match && *++scan == *++match &&
1241 *++scan == *++match && *++scan == *++match &&
1242 *++scan == *++match && *++scan == *++match &&
1243 *++scan == *++match && *++scan == *++match &&
1244 scan < strend);
1246 Assert(scan <= s->window + (unsigned)(s->window_size - 1),
1247 "wild scan");
1249 len = MAX_MATCH - (int)(strend - scan);
1250 scan = strend - MAX_MATCH;
1252 #endif /* UNALIGNED_OK */
1254 if (len > best_len) {
1255 s->match_start = cur_match;
1256 best_len = len;
1257 if (len >= nice_match)
1258 break;
1259 #ifdef UNALIGNED_OK
1260 scan_end = *(ushf *) (scan + best_len - 1);
1261 #else
1262 scan_end1 = scan[best_len - 1];
1263 scan_end = scan[best_len];
1264 #endif
1265 }
1266 } while ((cur_match = prev[cur_match & wmask]) > limit
1267 && --chain_length != 0);
1269 if ((uInt) best_len <= s->lookahead)
1270 return (uInt) best_len;
1271 return s->lookahead;
1272 }
1273 #endif /* ASMV */
1275 #else /* FASTEST */
1277 /* ---------------------------------------------------------------------------
1278 * Optimized version for FASTEST only
1279 */
1280 local uInt longest_match(s, cur_match)
1281 deflate_state *s;
1282 IPos cur_match; /* current match */
1283 {
1284 register Bytef *scan = s->window + s->strstart; /* current string */
1285 register Bytef *match; /* matched string */
1286 register int len; /* length of current match */
1287 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1289 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1290 * It is easy to get rid of this optimization if necessary.
1291 */
1292 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1294 Assert((ulg) s->strstart <= s->window_size - MIN_LOOKAHEAD,
1295 "need lookahead");
1297 Assert(cur_match < s->strstart, "no future");
1299 match = s->window + cur_match;
1301 /* Return failure if the match length is less than 2:
1302 */
1303 if (match[0] != scan[0] || match[1] != scan[1])
1304 return MIN_MATCH - 1;
1306 /* The check at best_len-1 can be removed because it will be made
1307 * again later. (This heuristic is not always a win.)
1308 * It is not necessary to compare scan[2] and match[2] since they
1309 * are always equal when the other bytes match, given that
1310 * the hash keys are equal and that HASH_BITS >= 8.
1311 */
1312 scan += 2, match += 2;
1313 Assert(*scan == *match, "match[2]?");
1315 /* We check for insufficient lookahead only every 8th comparison;
1316 * the 256th check will be made at strstart+258.
1317 */
1318 do {
1319 } while (*++scan == *++match && *++scan == *++match &&
1320 *++scan == *++match && *++scan == *++match &&
1321 *++scan == *++match && *++scan == *++match &&
1322 *++scan == *++match && *++scan == *++match && scan < strend);
1324 Assert(scan <= s->window + (unsigned)(s->window_size - 1), "wild scan");
1326 len = MAX_MATCH - (int)(strend - scan);
1328 if (len < MIN_MATCH)
1329 return MIN_MATCH - 1;
1331 s->match_start = cur_match;
1332 return (uInt) len <= s->lookahead ? (uInt) len : s->lookahead;
1333 }
1335 #endif /* FASTEST */
1337 #ifdef DEBUG
1338 /* ===========================================================================
1339 * Check that the match at match_start is indeed a match.
1340 */
1341 local void check_match(s, start, match, length)
1342 deflate_state *s;
1343 IPos start, match;
1344 int length;
1345 {
1346 /* check that the match is indeed a match */
1347 if (zmemcmp(s->window + match, s->window + start, length) != EQUAL) {
1348 fprintf(stderr, " start %u, match %u, length %d\n",
1349 start, match, length);
1350 do {
1351 fprintf(stderr, "%c%c", s->window[match++],
1352 s->window[start++]);
1353 } while (--length != 0);
1354 z_error("invalid match");
1355 }
1356 if (z_verbose > 1) {
1357 fprintf(stderr, "\\[%d,%d]", start - match, length);
1358 do {
1359 putc(s->window[start++], stderr);
1360 } while (--length != 0);
1361 }
1362 }
1363 #else
1364 #define check_match(s, start, match, length)
1365 #endif /* DEBUG */
1367 /* ===========================================================================
1368 * Fill the window when the lookahead becomes insufficient.
1369 * Updates strstart and lookahead.
1370 *
1371 * IN assertion: lookahead < MIN_LOOKAHEAD
1372 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1373 * At least one byte has been read, or avail_in == 0; reads are
1374 * performed for at least two bytes (required for the zip translate_eol
1375 * option -- not supported here).
1376 */
1377 local void fill_window(s)
1378 deflate_state *s;
1379 {
1380 register unsigned n, m;
1381 register Posf *p;
1382 unsigned more; /* Amount of free space at the end of the window. */
1383 uInt wsize = s->w_size;
1385 do {
1386 more =
1387 (unsigned)(s->window_size - (ulg) s->lookahead -
1388 (ulg) s->strstart);
1390 /* Deal with !@#$% 64K limit: */
1391 if (sizeof(int) <= 2) {
1392 if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1393 more = wsize;
1395 } else if (more == (unsigned)(-1)) {
1396 /* Very unlikely, but possible on 16 bit machine if
1397 * strstart == 0 && lookahead == 1 (input done a byte at time)
1398 */
1399 more--;
1400 }
1401 }
1403 /* If the window is almost full and there is insufficient lookahead,
1404 * move the upper half to the lower one to make room in the upper half.
1405 */
1406 if (s->strstart >= wsize + MAX_DIST(s)) {
1408 zmemcpy(s->window, s->window + wsize, (unsigned)wsize);
1409 s->match_start -= wsize;
1410 s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
1411 s->block_start -= (long)wsize;
1413 /* Slide the hash table (could be avoided with 32 bit values
1414 at the expense of memory usage). We slide even when level == 0
1415 to keep the hash table consistent if we switch back to level > 0
1416 later. (Using level 0 permanently is not an optimal usage of
1417 zlib, so we don't care about this pathological case.)
1418 */
1419 n = s->hash_size;
1420 p = &s->head[n];
1421 do {
1422 m = *--p;
1423 *p = (Pos) (m >= wsize ? m - wsize : NIL);
1424 } while (--n);
1426 n = wsize;
1427 #ifndef FASTEST
1428 p = &s->prev[n];
1429 do {
1430 m = *--p;
1431 *p = (Pos) (m >= wsize ? m - wsize : NIL);
1432 /* If n is not on any hash chain, prev[n] is garbage but
1433 * its value will never be used.
1434 */
1435 } while (--n);
1436 #endif
1437 more += wsize;
1438 }
1439 if (s->strm->avail_in == 0)
1440 return;
1442 /* If there was no sliding:
1443 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1444 * more == window_size - lookahead - strstart
1445 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1446 * => more >= window_size - 2*WSIZE + 2
1447 * In the BIG_MEM or MMAP case (not yet supported),
1448 * window_size == input_size + MIN_LOOKAHEAD &&
1449 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1450 * Otherwise, window_size == 2*WSIZE so more >= 2.
1451 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1452 */
1453 Assert(more >= 2, "more < 2");
1455 n = read_buf(s->strm, s->window + s->strstart + s->lookahead,
1456 more);
1457 s->lookahead += n;
1459 /* Initialize the hash value now that we have some input: */
1460 if (s->lookahead >= MIN_MATCH) {
1461 s->ins_h = s->window[s->strstart];
1462 UPDATE_HASH(s, s->ins_h, s->window[s->strstart + 1]);
1463 #if MIN_MATCH != 3
1464 Call UPDATE_HASH() MIN_MATCH - 3 more times
1465 #endif
1466 }
1467 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1468 * but this is not important since only literal bytes will be emitted.
1469 */ } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1471 /* If the WIN_INIT bytes after the end of the current data have never been
1472 * written, then zero those bytes in order to avoid memory check reports of
1473 * the use of uninitialized (or uninitialised as Julian writes) bytes by
1474 * the longest match routines. Update the high water mark for the next
1475 * time through here. WIN_INIT is set to MAX_MATCH since the longest match
1476 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
1477 */
1478 if (s->high_water < s->window_size) {
1479 ulg curr = s->strstart + (ulg) (s->lookahead);
1480 ulg init;
1482 if (s->high_water < curr) {
1483 /* Previous high water mark below current data -- zero WIN_INIT
1484 * bytes or up to end of window, whichever is less.
1485 */
1486 init = s->window_size - curr;
1487 if (init > WIN_INIT)
1488 init = WIN_INIT;
1489 zmemzero(s->window + curr, (unsigned)init);
1490 s->high_water = curr + init;
1491 } else if (s->high_water < (ulg) curr + WIN_INIT) {
1492 /* High water mark at or above current data, but below current data
1493 * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
1494 * to end of window, whichever is less.
1495 */
1496 init = (ulg) curr + WIN_INIT - s->high_water;
1497 if (init > s->window_size - s->high_water)
1498 init = s->window_size - s->high_water;
1499 zmemzero(s->window + s->high_water, (unsigned)init);
1500 s->high_water += init;
1501 }
1502 }
1503 }
1505 /* ===========================================================================
1506 * Flush the current block, with given end-of-file flag.
1507 * IN assertion: strstart is set to the end of the current match.
1508 */
1509 #define FLUSH_BLOCK_ONLY(s, last) { \
1510 _tr_flush_block(s, (s->block_start >= 0L ? \
1511 (charf *)&s->window[(unsigned)s->block_start] : \
1512 (charf *)Z_NULL), \
1513 (ulg)((long)s->strstart - s->block_start), \
1514 (last)); \
1515 s->block_start = s->strstart; \
1516 flush_pending(s->strm); \
1517 Tracev((stderr,"[FLUSH]")); \
1518 }
1520 /* Same but force premature exit if necessary. */
1521 #define FLUSH_BLOCK(s, last) { \
1522 FLUSH_BLOCK_ONLY(s, last); \
1523 if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
1524 }
1526 /* ===========================================================================
1527 * Copy without compression as much as possible from the input stream, return
1528 * the current block state.
1529 * This function does not insert new strings in the dictionary since
1530 * uncompressible data is probably not useful. This function is used
1531 * only for the level=0 compression option.
1532 * NOTE: this function should be optimized to avoid extra copying from
1533 * window to pending_buf.
1534 */
1535 local block_state deflate_stored(s, flush)
1536 deflate_state *s;
1537 int flush;
1538 {
1539 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
1540 * to pending_buf_size, and each stored block has a 5 byte header:
1541 */
1542 ulg max_block_size = 0xffff;
1543 ulg max_start;
1545 if (max_block_size > s->pending_buf_size - 5) {
1546 max_block_size = s->pending_buf_size - 5;
1547 }
1549 /* Copy as much as possible from input to output: */
1550 for (;;) {
1551 /* Fill the window as much as possible: */
1552 if (s->lookahead <= 1) {
1554 Assert(s->strstart < s->w_size + MAX_DIST(s) ||
1555 s->block_start >= (long)s->w_size,
1556 "slide too late");
1558 fill_window(s);
1559 if (s->lookahead == 0 && flush == Z_NO_FLUSH)
1560 return need_more;
1562 if (s->lookahead == 0)
1563 break; /* flush the current block */
1564 }
1565 Assert(s->block_start >= 0L, "block gone");
1567 s->strstart += s->lookahead;
1568 s->lookahead = 0;
1570 /* Emit a stored block if pending_buf will be full: */
1571 max_start = s->block_start + max_block_size;
1572 if (s->strstart == 0 || (ulg) s->strstart >= max_start) {
1573 /* strstart == 0 is possible when wraparound on 16-bit machine */
1574 s->lookahead = (uInt) (s->strstart - max_start);
1575 s->strstart = (uInt) max_start;
1576 FLUSH_BLOCK(s, 0);
1577 }
1578 /* Flush if we may have to slide, otherwise block_start may become
1579 * negative and the data will be gone:
1580 */
1581 if (s->strstart - (uInt) s->block_start >= MAX_DIST(s)) {
1582 FLUSH_BLOCK(s, 0);
1583 }
1584 }
1585 FLUSH_BLOCK(s, flush == Z_FINISH);
1586 return flush == Z_FINISH ? finish_done : block_done;
1587 }
1589 /* ===========================================================================
1590 * Compress as much as possible from the input stream, return the current
1591 * block state.
1592 * This function does not perform lazy evaluation of matches and inserts
1593 * new strings in the dictionary only for unmatched strings or for short
1594 * matches. It is used only for the fast compression options.
1595 */
1596 local block_state deflate_fast(s, flush)
1597 deflate_state *s;
1598 int flush;
1599 {
1600 IPos hash_head; /* head of the hash chain */
1601 int bflush; /* set if current block must be flushed */
1603 for (;;) {
1604 /* Make sure that we always have enough lookahead, except
1605 * at the end of the input file. We need MAX_MATCH bytes
1606 * for the next match, plus MIN_MATCH bytes to insert the
1607 * string following the next match.
1608 */
1609 if (s->lookahead < MIN_LOOKAHEAD) {
1610 fill_window(s);
1611 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1612 return need_more;
1613 }
1614 if (s->lookahead == 0)
1615 break; /* flush the current block */
1616 }
1618 /* Insert the string window[strstart .. strstart+2] in the
1619 * dictionary, and set hash_head to the head of the hash chain:
1620 */
1621 hash_head = NIL;
1622 if (s->lookahead >= MIN_MATCH) {
1623 INSERT_STRING(s, s->strstart, hash_head);
1624 }
1626 /* Find the longest match, discarding those <= prev_length.
1627 * At this point we have always match_length < MIN_MATCH
1628 */
1629 if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1630 /* To simplify the code, we prevent matches with the string
1631 * of window index 0 (in particular we have to avoid a match
1632 * of the string with itself at the start of the input file).
1633 */
1634 s->match_length = longest_match(s, hash_head);
1635 /* longest_match() sets match_start */
1636 }
1637 if (s->match_length >= MIN_MATCH) {
1638 check_match(s, s->strstart, s->match_start,
1639 s->match_length);
1641 _tr_tally_dist(s, s->strstart - s->match_start,
1642 s->match_length - MIN_MATCH, bflush);
1644 s->lookahead -= s->match_length;
1646 /* Insert new strings in the hash table only if the match length
1647 * is not too large. This saves time but degrades compression.
1648 */
1649 #ifndef FASTEST
1650 if (s->match_length <= s->max_insert_length &&
1651 s->lookahead >= MIN_MATCH) {
1652 s->match_length--; /* string at strstart already in table */
1653 do {
1654 s->strstart++;
1655 INSERT_STRING(s, s->strstart,
1656 hash_head);
1657 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1658 * always MIN_MATCH bytes ahead.
1659 */
1660 } while (--s->match_length != 0);
1661 s->strstart++;
1662 } else
1663 #endif
1664 {
1665 s->strstart += s->match_length;
1666 s->match_length = 0;
1667 s->ins_h = s->window[s->strstart];
1668 UPDATE_HASH(s, s->ins_h,
1669 s->window[s->strstart + 1]);
1670 #if MIN_MATCH != 3
1671 Call UPDATE_HASH() MIN_MATCH - 3 more times
1672 #endif
1673 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1674 * matter since it will be recomputed at next deflate call.
1675 */
1676 }} else {
1677 /* No match, output a literal byte */
1678 Tracevv((stderr, "%c", s->window[s->strstart]));
1679 _tr_tally_lit(s, s->window[s->strstart], bflush);
1680 s->lookahead--;
1681 s->strstart++;
1682 }
1683 if (bflush)
1684 FLUSH_BLOCK(s, 0);
1685 }
1686 FLUSH_BLOCK(s, flush == Z_FINISH);
1687 return flush == Z_FINISH ? finish_done : block_done;
1688 }
1690 #ifndef FASTEST
1691 /* ===========================================================================
1692 * Same as above, but achieves better compression. We use a lazy
1693 * evaluation for matches: a match is finally adopted only if there is
1694 * no better match at the next window position.
1695 */
1696 local block_state deflate_slow(s, flush)
1697 deflate_state *s;
1698 int flush;
1699 {
1700 IPos hash_head; /* head of hash chain */
1701 int bflush; /* set if current block must be flushed */
1703 /* Process the input block. */
1704 for (;;) {
1705 /* Make sure that we always have enough lookahead, except
1706 * at the end of the input file. We need MAX_MATCH bytes
1707 * for the next match, plus MIN_MATCH bytes to insert the
1708 * string following the next match.
1709 */
1710 if (s->lookahead < MIN_LOOKAHEAD) {
1711 fill_window(s);
1712 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1713 return need_more;
1714 }
1715 if (s->lookahead == 0)
1716 break; /* flush the current block */
1717 }
1719 /* Insert the string window[strstart .. strstart+2] in the
1720 * dictionary, and set hash_head to the head of the hash chain:
1721 */
1722 hash_head = NIL;
1723 if (s->lookahead >= MIN_MATCH) {
1724 INSERT_STRING(s, s->strstart, hash_head);
1725 }
1727 /* Find the longest match, discarding those <= prev_length.
1728 */
1729 s->prev_length = s->match_length, s->prev_match =
1730 s->match_start;
1731 s->match_length = MIN_MATCH - 1;
1733 if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
1734 s->strstart - hash_head <= MAX_DIST(s)) {
1735 /* To simplify the code, we prevent matches with the string
1736 * of window index 0 (in particular we have to avoid a match
1737 * of the string with itself at the start of the input file).
1738 */
1739 s->match_length = longest_match(s, hash_head);
1740 /* longest_match() sets match_start */
1742 if (s->match_length <= 5 && (s->strategy == Z_FILTERED
1743 #if TOO_FAR <= 32767
1744 || (s->match_length ==
1745 MIN_MATCH
1746 && s->strstart -
1747 s->match_start >
1748 TOO_FAR)
1749 #endif
1750 )) {
1752 /* If prev_match is also MIN_MATCH, match_start is garbage
1753 * but we will ignore the current match anyway.
1754 */
1755 s->match_length = MIN_MATCH - 1;
1756 }
1757 }
1758 /* If there was a match at the previous step and the current
1759 * match is not better, output the previous match:
1760 */
1761 if (s->prev_length >= MIN_MATCH
1762 && s->match_length <= s->prev_length) {
1763 uInt max_insert =
1764 s->strstart + s->lookahead - MIN_MATCH;
1765 /* Do not insert strings in hash table beyond this. */
1767 check_match(s, s->strstart - 1, s->prev_match,
1768 s->prev_length);
1770 _tr_tally_dist(s, s->strstart - 1 - s->prev_match,
1771 s->prev_length - MIN_MATCH, bflush);
1773 /* Insert in hash table all strings up to the end of the match.
1774 * strstart-1 and strstart are already inserted. If there is not
1775 * enough lookahead, the last two strings are not inserted in
1776 * the hash table.
1777 */
1778 s->lookahead -= s->prev_length - 1;
1779 s->prev_length -= 2;
1780 do {
1781 if (++s->strstart <= max_insert) {
1782 INSERT_STRING(s, s->strstart,
1783 hash_head);
1784 }
1785 } while (--s->prev_length != 0);
1786 s->match_available = 0;
1787 s->match_length = MIN_MATCH - 1;
1788 s->strstart++;
1790 if (bflush)
1791 FLUSH_BLOCK(s, 0);
1793 } else if (s->match_available) {
1794 /* If there was no match at the previous position, output a
1795 * single literal. If there was a match but the current match
1796 * is longer, truncate the previous match to a single literal.
1797 */
1798 Tracevv((stderr, "%c", s->window[s->strstart - 1]));
1799 _tr_tally_lit(s, s->window[s->strstart - 1], bflush);
1800 if (bflush) {
1801 FLUSH_BLOCK_ONLY(s, 0);
1802 }
1803 s->strstart++;
1804 s->lookahead--;
1805 if (s->strm->avail_out == 0)
1806 return need_more;
1807 } else {
1808 /* There is no previous match to compare with, wait for
1809 * the next step to decide.
1810 */
1811 s->match_available = 1;
1812 s->strstart++;
1813 s->lookahead--;
1814 }
1815 }
1816 Assert(flush != Z_NO_FLUSH, "no flush?");
1817 if (s->match_available) {
1818 Tracevv((stderr, "%c", s->window[s->strstart - 1]));
1819 _tr_tally_lit(s, s->window[s->strstart - 1], bflush);
1820 s->match_available = 0;
1821 }
1822 FLUSH_BLOCK(s, flush == Z_FINISH);
1823 return flush == Z_FINISH ? finish_done : block_done;
1824 }
1825 #endif /* FASTEST */
1827 /* ===========================================================================
1828 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
1829 * one. Do not maintain a hash table. (It will be regenerated if this run of
1830 * deflate switches away from Z_RLE.)
1831 */
1832 local block_state deflate_rle(s, flush)
1833 deflate_state *s;
1834 int flush;
1835 {
1836 int bflush; /* set if current block must be flushed */
1837 uInt prev; /* byte at distance one to match */
1838 Bytef *scan, *strend; /* scan goes up to strend for length of run */
1840 for (;;) {
1841 /* Make sure that we always have enough lookahead, except
1842 * at the end of the input file. We need MAX_MATCH bytes
1843 * for the longest encodable run.
1844 */
1845 if (s->lookahead < MAX_MATCH) {
1846 fill_window(s);
1847 if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
1848 return need_more;
1849 }
1850 if (s->lookahead == 0)
1851 break; /* flush the current block */
1852 }
1854 /* See how many times the previous byte repeats */
1855 s->match_length = 0;
1856 if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
1857 scan = s->window + s->strstart - 1;
1858 prev = *scan;
1859 if (prev == *++scan && prev == *++scan
1860 && prev == *++scan) {
1861 strend = s->window + s->strstart + MAX_MATCH;
1862 do {
1863 } while (prev == *++scan && prev == *++scan &&
1864 prev == *++scan && prev == *++scan &&
1865 prev == *++scan && prev == *++scan &&
1866 prev == *++scan && prev == *++scan &&
1867 scan < strend);
1868 s->match_length =
1869 MAX_MATCH - (int)(strend - scan);
1870 if (s->match_length > s->lookahead)
1871 s->match_length = s->lookahead;
1872 }
1873 }
1875 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
1876 if (s->match_length >= MIN_MATCH) {
1877 check_match(s, s->strstart, s->strstart - 1,
1878 s->match_length);
1880 _tr_tally_dist(s, 1, s->match_length - MIN_MATCH,
1881 bflush);
1883 s->lookahead -= s->match_length;
1884 s->strstart += s->match_length;
1885 s->match_length = 0;
1886 } else {
1887 /* No match, output a literal byte */
1888 Tracevv((stderr, "%c", s->window[s->strstart]));
1889 _tr_tally_lit(s, s->window[s->strstart], bflush);
1890 s->lookahead--;
1891 s->strstart++;
1892 }
1893 if (bflush)
1894 FLUSH_BLOCK(s, 0);
1895 }
1896 FLUSH_BLOCK(s, flush == Z_FINISH);
1897 return flush == Z_FINISH ? finish_done : block_done;
1898 }
1900 /* ===========================================================================
1901 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
1902 * (It will be regenerated if this run of deflate switches away from Huffman.)
1903 */
1904 local block_state deflate_huff(s, flush)
1905 deflate_state *s;
1906 int flush;
1907 {
1908 int bflush; /* set if current block must be flushed */
1910 for (;;) {
1911 /* Make sure that we have a literal to write. */
1912 if (s->lookahead == 0) {
1913 fill_window(s);
1914 if (s->lookahead == 0) {
1915 if (flush == Z_NO_FLUSH)
1916 return need_more;
1917 break; /* flush the current block */
1918 }
1919 }
1921 /* Output a literal byte */
1922 s->match_length = 0;
1923 Tracevv((stderr, "%c", s->window[s->strstart]));
1924 _tr_tally_lit(s, s->window[s->strstart], bflush);
1925 s->lookahead--;
1926 s->strstart++;
1927 if (bflush)
1928 FLUSH_BLOCK(s, 0);
1929 }
1930 FLUSH_BLOCK(s, flush == Z_FINISH);
1931 return flush == Z_FINISH ? finish_done : block_done;
1932 }