Service workers: Allow HTTPS pages arrived at via HTTP redirect to use SW
[chromium-blink-merge.git] / third_party / zlib / deflate.c
blob55ec21570a1a99b54bae2ecaefb9ec4a085080e3
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
9 * The "deflation" process depends on being able to identify portions
10 * of the input text which are identical to earlier input (within a
11 * sliding window trailing behind the input currently being processed).
13 * The most straightforward technique turns out to be the fastest for
14 * most input files: try all possible matches and select the longest.
15 * The key feature of this algorithm is that insertions into the string
16 * dictionary are very simple and thus fast, and deletions are avoided
17 * completely. Insertions are performed at each input character, whereas
18 * string matches are performed only when the previous match ends. So it
19 * is preferable to spend more time in matches to allow very fast string
20 * insertions and avoid deletions. The matching algorithm for small
21 * strings is inspired from that of Rabin & Karp. A brute force approach
22 * is used to find longer strings when a small match has been found.
23 * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
24 * (by Leonid Broukhis).
25 * A previous version of this file used a more sophisticated algorithm
26 * (by Fiala and Greene) which is guaranteed to run in linear amortized
27 * time, but has a larger average cost, uses more memory and is patented.
28 * However the F&G algorithm may be faster for some highly redundant
29 * files if the parameter max_chain_length (described below) is too large.
31 * ACKNOWLEDGEMENTS
33 * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
34 * I found it in 'freeze' written by Leonid Broukhis.
35 * Thanks to many people for bug reports and testing.
37 * REFERENCES
39 * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
40 * Available in http://www.ietf.org/rfc/rfc1951.txt
42 * A description of the Rabin and Karp algorithm is given in the book
43 * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
45 * Fiala,E.R., and Greene,D.H.
46 * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
50 /* @(#) $Id$ */
52 #include <assert.h>
54 #include "deflate.h"
55 #include "x86.h"
57 const char deflate_copyright[] =
58 " deflate 1.2.5 Copyright 1995-2010 Jean-loup Gailly and Mark Adler ";
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 int clas));
78 /* Compression function. Returns the block state after the call. */
80 local void fill_window OF((deflate_state *s));
81 local block_state deflate_stored OF((deflate_state *s, int flush, int clas));
82 local block_state deflate_fast OF((deflate_state *s, int flush, int clas));
83 #ifndef FASTEST
84 local block_state deflate_slow OF((deflate_state *s, int flush, int clas));
85 #endif
86 local block_state deflate_rle OF((deflate_state *s, int flush));
87 local block_state deflate_huff OF((deflate_state *s, int flush));
88 local void lm_init OF((deflate_state *s));
89 local void putShortMSB OF((deflate_state *s, uInt b));
90 local void flush_pending OF((z_streamp strm));
92 #ifdef ASMV
93 void match_init OF((void)); /* asm code initialization */
94 uInt longest_match OF((deflate_state *s, IPos cur_match, int clas));
95 #else
96 local uInt longest_match OF((deflate_state *s, IPos cur_match, int clas));
97 #endif
99 #ifdef DEBUG
100 local void check_match OF((deflate_state *s, IPos start, IPos match,
101 int length));
102 #endif
104 /* For fill_window_sse.c to use */
105 ZLIB_INTERNAL int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
107 /* From crc32.c */
108 extern void ZLIB_INTERNAL crc_reset(deflate_state *const s);
109 extern void ZLIB_INTERNAL crc_finalize(deflate_state *const s);
110 extern void ZLIB_INTERNAL copy_with_crc(z_streamp strm, Bytef *dst, long size);
112 #ifdef _MSC_VER
113 #define INLINE __inline
114 #else
115 #define INLINE inline
116 #endif
118 /* Inline optimisation */
119 local INLINE Pos insert_string_sse(deflate_state *const s, const Pos str);
121 /* ===========================================================================
122 * Local data
125 #define NIL 0
126 /* Tail of hash chains */
128 #ifndef TOO_FAR
129 # define TOO_FAR 4096
130 #endif
131 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
133 /* Values for max_lazy_match, good_match and max_chain_length, depending on
134 * the desired pack level (0..9). The values given below have been tuned to
135 * exclude worst case performance for pathological files. Better values may be
136 * found for specific files.
138 typedef struct config_s {
139 ush good_length; /* reduce lazy search above this match length */
140 ush max_lazy; /* do not perform lazy search above this match length */
141 ush nice_length; /* quit search above this match length */
142 ush max_chain;
143 compress_func func;
144 } config;
146 #ifdef FASTEST
147 local const config configuration_table[2] = {
148 /* good lazy nice chain */
149 /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
150 /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
151 #else
152 local const config configuration_table[10] = {
153 /* good lazy nice chain */
154 /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
155 /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
156 /* 2 */ {4, 5, 16, 8, deflate_fast},
157 /* 3 */ {4, 6, 32, 32, deflate_fast},
159 /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
160 /* 5 */ {8, 16, 32, 32, deflate_slow},
161 /* 6 */ {8, 16, 128, 128, deflate_slow},
162 /* 7 */ {8, 32, 128, 256, deflate_slow},
163 /* 8 */ {32, 128, 258, 1024, deflate_slow},
164 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
165 #endif
167 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
168 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
169 * meaning.
172 #define EQUAL 0
173 /* result of memcmp for equal strings */
175 #ifndef NO_DUMMY_DECL
176 struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
177 #endif
179 /* ===========================================================================
180 * Update a hash value with the given input byte
181 * IN assertion: all calls to to UPDATE_HASH are made with consecutive
182 * input characters, so that a running hash key can be computed from the
183 * previous key instead of complete recalculation each time.
185 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
187 /* ===========================================================================
188 * Insert string str in the dictionary and set match_head to the previous head
189 * of the hash chain (the most recent string with same hash key). Return
190 * the previous length of the hash chain.
191 * If this file is compiled with -DFASTEST, the compression level is forced
192 * to 1, and no hash chains are maintained.
193 * IN assertion: all calls to to INSERT_STRING are made with consecutive
194 * input characters and the first MIN_MATCH bytes of str are valid
195 * (except for the last MIN_MATCH-1 bytes of the input file).
197 local INLINE Pos insert_string_c(deflate_state *const s, const Pos str)
199 Pos ret;
201 UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]);
202 #ifdef FASTEST
203 ret = s->head[s->ins_h];
204 #else
205 ret = s->prev[str & s->w_mask] = s->head[s->ins_h];
206 #endif
207 s->head[s->ins_h] = str;
209 return ret;
212 local INLINE Pos insert_string(deflate_state *const s, const Pos str)
214 if (x86_cpu_enable_simd)
215 return insert_string_sse(s, str);
216 return insert_string_c(s, str);
220 /* ===========================================================================
221 * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
222 * prev[] will be initialized on the fly.
224 #define CLEAR_HASH(s) \
225 s->head[s->hash_size-1] = NIL; \
226 zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
228 /* ========================================================================= */
229 int ZEXPORT deflateInit_(strm, level, version, stream_size)
230 z_streamp strm;
231 int level;
232 const char *version;
233 int stream_size;
235 return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
236 Z_DEFAULT_STRATEGY, version, stream_size);
237 /* To do: ignore strm->next_in if we use it as window */
240 /* ========================================================================= */
241 int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
242 version, stream_size)
243 z_streamp strm;
244 int level;
245 int method;
246 int windowBits;
247 int memLevel;
248 int strategy;
249 const char *version;
250 int stream_size;
252 unsigned window_padding = 8;
253 deflate_state *s;
254 int wrap = 1;
255 static const char my_version[] = ZLIB_VERSION;
257 ushf *overlay;
258 /* We overlay pending_buf and d_buf+l_buf. This works since the average
259 * output size for (length,distance) codes is <= 24 bits.
262 x86_check_features();
264 if (version == Z_NULL || version[0] != my_version[0] ||
265 stream_size != sizeof(z_stream)) {
266 return Z_VERSION_ERROR;
268 if (strm == Z_NULL) return Z_STREAM_ERROR;
270 strm->msg = Z_NULL;
271 if (strm->zalloc == (alloc_func)0) {
272 strm->zalloc = zcalloc;
273 strm->opaque = (voidpf)0;
275 if (strm->zfree == (free_func)0) strm->zfree = zcfree;
277 #ifdef FASTEST
278 if (level != 0) level = 1;
279 #else
280 if (level == Z_DEFAULT_COMPRESSION) level = 6;
281 #endif
283 if (windowBits < 0) { /* suppress zlib wrapper */
284 wrap = 0;
285 windowBits = -windowBits;
287 #ifdef GZIP
288 else if (windowBits > 15) {
289 wrap = 2; /* write gzip wrapper instead */
290 windowBits -= 16;
292 #endif
293 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
294 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
295 strategy < 0 || strategy > Z_FIXED) {
296 return Z_STREAM_ERROR;
298 if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
299 s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
300 if (s == Z_NULL) return Z_MEM_ERROR;
301 strm->state = (struct internal_state FAR *)s;
302 s->strm = strm;
304 s->wrap = wrap;
305 s->gzhead = Z_NULL;
306 s->w_bits = windowBits;
307 s->w_size = 1 << s->w_bits;
308 s->w_mask = s->w_size - 1;
310 if (x86_cpu_enable_simd) {
311 s->hash_bits = 15;
312 } else {
313 s->hash_bits = memLevel + 7;
316 s->hash_size = 1 << s->hash_bits;
317 s->hash_mask = s->hash_size - 1;
318 s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
320 s->window = (Bytef *) ZALLOC(strm, s->w_size + window_padding, 2*sizeof(Byte));
321 s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
322 s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
323 s->class_bitmap = NULL;
324 zmemzero(&s->cookie_locations, sizeof(s->cookie_locations));
325 strm->clas = 0;
327 s->high_water = 0; /* nothing written to s->window yet */
329 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
331 overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
332 s->pending_buf = (uchf *) overlay;
333 s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
335 if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
336 s->pending_buf == Z_NULL) {
337 s->status = FINISH_STATE;
338 strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
339 deflateEnd (strm);
340 return Z_MEM_ERROR;
342 s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
343 s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
345 s->level = level;
346 s->strategy = strategy;
347 s->method = (Byte)method;
349 return deflateReset(strm);
352 /* ========================================================================= */
353 int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
354 z_streamp strm;
355 const Bytef *dictionary;
356 uInt dictLength;
358 deflate_state *s;
359 uInt length = dictLength;
360 uInt n;
361 IPos hash_head = 0;
363 if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
364 strm->state->wrap == 2 ||
365 (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
366 return Z_STREAM_ERROR;
368 s = strm->state;
369 if (s->wrap)
370 strm->adler = adler32(strm->adler, dictionary, dictLength);
372 if (length < MIN_MATCH) return Z_OK;
373 if (length > s->w_size) {
374 length = s->w_size;
375 dictionary += dictLength - length; /* use the tail of the dictionary */
377 zmemcpy(s->window, dictionary, length);
378 s->strstart = length;
379 s->block_start = (long)length;
381 /* Insert all strings in the hash table (except for the last two bytes).
382 * s->lookahead stays null, so s->ins_h will be recomputed at the next
383 * call of fill_window.
385 s->ins_h = s->window[0];
386 UPDATE_HASH(s, s->ins_h, s->window[1]);
387 for (n = 0; n <= length - MIN_MATCH; n++) {
388 insert_string(s, n);
390 if (hash_head) hash_head = 0; /* to make compiler happy */
391 return Z_OK;
394 /* ========================================================================= */
395 int ZEXPORT deflateReset (strm)
396 z_streamp strm;
398 deflate_state *s;
400 if (strm == Z_NULL || strm->state == Z_NULL ||
401 strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
402 return Z_STREAM_ERROR;
405 strm->total_in = strm->total_out = 0;
406 strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
407 strm->data_type = Z_UNKNOWN;
409 s = (deflate_state *)strm->state;
410 s->pending = 0;
411 s->pending_out = s->pending_buf;
412 TRY_FREE(strm, s->class_bitmap);
413 s->class_bitmap = NULL;
415 if (s->wrap < 0) {
416 s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
418 s->status = s->wrap ? INIT_STATE : BUSY_STATE;
419 strm->adler =
420 #ifdef GZIP
421 s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
422 #endif
423 adler32(0L, Z_NULL, 0);
424 s->last_flush = Z_NO_FLUSH;
426 _tr_init(s);
427 lm_init(s);
429 return Z_OK;
432 /* ========================================================================= */
433 int ZEXPORT deflateSetHeader (strm, head)
434 z_streamp strm;
435 gz_headerp head;
437 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
438 if (strm->state->wrap != 2) return Z_STREAM_ERROR;
439 strm->state->gzhead = head;
440 return Z_OK;
443 /* ========================================================================= */
444 int ZEXPORT deflatePrime (strm, bits, value)
445 z_streamp strm;
446 int bits;
447 int value;
449 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
450 strm->state->bi_valid = bits;
451 strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
452 return Z_OK;
455 /* ========================================================================= */
456 int ZEXPORT deflateParams(strm, level, strategy)
457 z_streamp strm;
458 int level;
459 int strategy;
461 deflate_state *s;
462 compress_func func;
463 int err = Z_OK;
465 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
466 s = strm->state;
468 #ifdef FASTEST
469 if (level != 0) level = 1;
470 #else
471 if (level == Z_DEFAULT_COMPRESSION) level = 6;
472 #endif
473 if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
474 return Z_STREAM_ERROR;
476 func = configuration_table[s->level].func;
478 if ((strategy != s->strategy || func != configuration_table[level].func) &&
479 strm->total_in != 0) {
480 /* Flush the last buffer: */
481 err = deflate(strm, Z_BLOCK);
483 if (s->level != level) {
484 s->level = level;
485 s->max_lazy_match = configuration_table[level].max_lazy;
486 s->good_match = configuration_table[level].good_length;
487 s->nice_match = configuration_table[level].nice_length;
488 s->max_chain_length = configuration_table[level].max_chain;
490 s->strategy = strategy;
491 return err;
494 /* ========================================================================= */
495 int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
496 z_streamp strm;
497 int good_length;
498 int max_lazy;
499 int nice_length;
500 int max_chain;
502 deflate_state *s;
504 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
505 s = strm->state;
506 s->good_match = good_length;
507 s->max_lazy_match = max_lazy;
508 s->nice_match = nice_length;
509 s->max_chain_length = max_chain;
510 return Z_OK;
513 /* =========================================================================
514 * For the default windowBits of 15 and memLevel of 8, this function returns
515 * a close to exact, as well as small, upper bound on the compressed size.
516 * They are coded as constants here for a reason--if the #define's are
517 * changed, then this function needs to be changed as well. The return
518 * value for 15 and 8 only works for those exact settings.
520 * For any setting other than those defaults for windowBits and memLevel,
521 * the value returned is a conservative worst case for the maximum expansion
522 * resulting from using fixed blocks instead of stored blocks, which deflate
523 * can emit on compressed data for some combinations of the parameters.
525 * This function could be more sophisticated to provide closer upper bounds for
526 * every combination of windowBits and memLevel. But even the conservative
527 * upper bound of about 14% expansion does not seem onerous for output buffer
528 * allocation.
530 uLong ZEXPORT deflateBound(strm, sourceLen)
531 z_streamp strm;
532 uLong sourceLen;
534 deflate_state *s;
535 uLong complen, wraplen;
536 Bytef *str;
538 /* conservative upper bound for compressed data */
539 complen = sourceLen +
540 ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
542 /* if can't get parameters, return conservative bound plus zlib wrapper */
543 if (strm == Z_NULL || strm->state == Z_NULL)
544 return complen + 6;
546 /* compute wrapper length */
547 s = strm->state;
548 switch (s->wrap) {
549 case 0: /* raw deflate */
550 wraplen = 0;
551 break;
552 case 1: /* zlib wrapper */
553 wraplen = 6 + (s->strstart ? 4 : 0);
554 break;
555 case 2: /* gzip wrapper */
556 wraplen = 18;
557 if (s->gzhead != Z_NULL) { /* user-supplied gzip header */
558 if (s->gzhead->extra != Z_NULL)
559 wraplen += 2 + s->gzhead->extra_len;
560 str = s->gzhead->name;
561 if (str != Z_NULL)
562 do {
563 wraplen++;
564 } while (*str++);
565 str = s->gzhead->comment;
566 if (str != Z_NULL)
567 do {
568 wraplen++;
569 } while (*str++);
570 if (s->gzhead->hcrc)
571 wraplen += 2;
573 break;
574 default: /* for compiler happiness */
575 wraplen = 6;
578 /* if not default parameters, return conservative bound */
579 if (s->w_bits != 15 || s->hash_bits != 8 + 7)
580 return complen + wraplen;
582 /* default settings: return tight bound for that case */
583 return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
584 (sourceLen >> 25) + 13 - 6 + wraplen;
587 /* =========================================================================
588 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
589 * IN assertion: the stream state is correct and there is enough room in
590 * pending_buf.
592 local void putShortMSB (s, b)
593 deflate_state *s;
594 uInt b;
596 put_byte(s, (Byte)(b >> 8));
597 put_byte(s, (Byte)(b & 0xff));
600 /* =========================================================================
601 * Flush as much pending output as possible. All deflate() output goes
602 * through this function so some applications may wish to modify it
603 * to avoid allocating a large strm->next_out buffer and copying into it.
604 * (See also read_buf()).
606 local void flush_pending(strm)
607 z_streamp strm;
609 unsigned len = strm->state->pending;
611 if (len > strm->avail_out) len = strm->avail_out;
612 if (len == 0) return;
614 zmemcpy(strm->next_out, strm->state->pending_out, len);
615 strm->next_out += len;
616 strm->state->pending_out += len;
617 strm->total_out += len;
618 strm->avail_out -= len;
619 strm->state->pending -= len;
620 if (strm->state->pending == 0) {
621 strm->state->pending_out = strm->state->pending_buf;
625 /* ========================================================================= */
626 int ZEXPORT deflate (strm, flush)
627 z_streamp strm;
628 int flush;
630 int old_flush; /* value of flush param for previous deflate call */
631 deflate_state *s;
633 if (strm == Z_NULL || strm->state == Z_NULL ||
634 flush > Z_BLOCK || flush < 0) {
635 return Z_STREAM_ERROR;
637 s = strm->state;
639 if (strm->next_out == Z_NULL ||
640 (strm->next_in == Z_NULL && strm->avail_in != 0) ||
641 (s->status == FINISH_STATE && flush != Z_FINISH)) {
642 ERR_RETURN(strm, Z_STREAM_ERROR);
644 if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
646 s->strm = strm; /* just in case */
647 old_flush = s->last_flush;
648 s->last_flush = flush;
650 /* Write the header */
651 if (s->status == INIT_STATE) {
652 #ifdef GZIP
653 if (s->wrap == 2) {
654 crc_reset(s);
655 put_byte(s, 31);
656 put_byte(s, 139);
657 put_byte(s, 8);
658 if (s->gzhead == Z_NULL) {
659 put_byte(s, 0);
660 put_byte(s, 0);
661 put_byte(s, 0);
662 put_byte(s, 0);
663 put_byte(s, 0);
664 put_byte(s, s->level == 9 ? 2 :
665 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
666 4 : 0));
667 put_byte(s, OS_CODE);
668 s->status = BUSY_STATE;
670 else {
671 put_byte(s, (s->gzhead->text ? 1 : 0) +
672 (s->gzhead->hcrc ? 2 : 0) +
673 (s->gzhead->extra == Z_NULL ? 0 : 4) +
674 (s->gzhead->name == Z_NULL ? 0 : 8) +
675 (s->gzhead->comment == Z_NULL ? 0 : 16)
677 put_byte(s, (Byte)(s->gzhead->time & 0xff));
678 put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
679 put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
680 put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
681 put_byte(s, s->level == 9 ? 2 :
682 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
683 4 : 0));
684 put_byte(s, s->gzhead->os & 0xff);
685 if (s->gzhead->extra != Z_NULL) {
686 put_byte(s, s->gzhead->extra_len & 0xff);
687 put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
689 if (s->gzhead->hcrc)
690 strm->adler = crc32(strm->adler, s->pending_buf,
691 s->pending);
692 s->gzindex = 0;
693 s->status = EXTRA_STATE;
696 else
697 #endif
699 uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
700 uInt level_flags;
702 if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
703 level_flags = 0;
704 else if (s->level < 6)
705 level_flags = 1;
706 else if (s->level == 6)
707 level_flags = 2;
708 else
709 level_flags = 3;
710 header |= (level_flags << 6);
711 if (s->strstart != 0) header |= PRESET_DICT;
712 header += 31 - (header % 31);
714 s->status = BUSY_STATE;
715 putShortMSB(s, header);
717 /* Save the adler32 of the preset dictionary: */
718 if (s->strstart != 0) {
719 putShortMSB(s, (uInt)(strm->adler >> 16));
720 putShortMSB(s, (uInt)(strm->adler & 0xffff));
722 strm->adler = adler32(0L, Z_NULL, 0);
725 #ifdef GZIP
726 if (s->status == EXTRA_STATE) {
727 if (s->gzhead->extra != Z_NULL) {
728 uInt beg = s->pending; /* start of bytes to update crc */
730 while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
731 if (s->pending == s->pending_buf_size) {
732 if (s->gzhead->hcrc && s->pending > beg)
733 strm->adler = crc32(strm->adler, s->pending_buf + beg,
734 s->pending - beg);
735 flush_pending(strm);
736 beg = s->pending;
737 if (s->pending == s->pending_buf_size)
738 break;
740 put_byte(s, s->gzhead->extra[s->gzindex]);
741 s->gzindex++;
743 if (s->gzhead->hcrc && s->pending > beg)
744 strm->adler = crc32(strm->adler, s->pending_buf + beg,
745 s->pending - beg);
746 if (s->gzindex == s->gzhead->extra_len) {
747 s->gzindex = 0;
748 s->status = NAME_STATE;
751 else
752 s->status = NAME_STATE;
754 if (s->status == NAME_STATE) {
755 if (s->gzhead->name != Z_NULL) {
756 uInt beg = s->pending; /* start of bytes to update crc */
757 int val;
759 do {
760 if (s->pending == s->pending_buf_size) {
761 if (s->gzhead->hcrc && s->pending > beg)
762 strm->adler = crc32(strm->adler, s->pending_buf + beg,
763 s->pending - beg);
764 flush_pending(strm);
765 beg = s->pending;
766 if (s->pending == s->pending_buf_size) {
767 val = 1;
768 break;
771 val = s->gzhead->name[s->gzindex++];
772 put_byte(s, val);
773 } while (val != 0);
774 if (s->gzhead->hcrc && s->pending > beg)
775 strm->adler = crc32(strm->adler, s->pending_buf + beg,
776 s->pending - beg);
777 if (val == 0) {
778 s->gzindex = 0;
779 s->status = COMMENT_STATE;
782 else
783 s->status = COMMENT_STATE;
785 if (s->status == COMMENT_STATE) {
786 if (s->gzhead->comment != Z_NULL) {
787 uInt beg = s->pending; /* start of bytes to update crc */
788 int val;
790 do {
791 if (s->pending == s->pending_buf_size) {
792 if (s->gzhead->hcrc && s->pending > beg)
793 strm->adler = crc32(strm->adler, s->pending_buf + beg,
794 s->pending - beg);
795 flush_pending(strm);
796 beg = s->pending;
797 if (s->pending == s->pending_buf_size) {
798 val = 1;
799 break;
802 val = s->gzhead->comment[s->gzindex++];
803 put_byte(s, val);
804 } while (val != 0);
805 if (s->gzhead->hcrc && s->pending > beg)
806 strm->adler = crc32(strm->adler, s->pending_buf + beg,
807 s->pending - beg);
808 if (val == 0)
809 s->status = HCRC_STATE;
811 else
812 s->status = HCRC_STATE;
814 if (s->status == HCRC_STATE) {
815 if (s->gzhead->hcrc) {
816 if (s->pending + 2 > s->pending_buf_size)
817 flush_pending(strm);
818 if (s->pending + 2 <= s->pending_buf_size) {
819 put_byte(s, (Byte)(strm->adler & 0xff));
820 put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
821 strm->adler = crc32(0L, Z_NULL, 0);
822 s->status = BUSY_STATE;
825 else
826 s->status = BUSY_STATE;
828 #endif
830 /* Flush as much pending output as possible */
831 if (s->pending != 0) {
832 flush_pending(strm);
833 if (strm->avail_out == 0) {
834 /* Since avail_out is 0, deflate will be called again with
835 * more output space, but possibly with both pending and
836 * avail_in equal to zero. There won't be anything to do,
837 * but this is not an error situation so make sure we
838 * return OK instead of BUF_ERROR at next call of deflate:
840 s->last_flush = -1;
841 return Z_OK;
844 /* Make sure there is something to do and avoid duplicate consecutive
845 * flushes. For repeated and useless calls with Z_FINISH, we keep
846 * returning Z_STREAM_END instead of Z_BUF_ERROR.
848 } else if (strm->avail_in == 0 && flush <= old_flush &&
849 flush != Z_FINISH) {
850 ERR_RETURN(strm, Z_BUF_ERROR);
853 /* User must not provide more input after the first FINISH: */
854 if (s->status == FINISH_STATE && strm->avail_in != 0) {
855 ERR_RETURN(strm, Z_BUF_ERROR);
858 /* Start a new block or continue the current one.
860 if (strm->avail_in != 0 || s->lookahead != 0 ||
861 (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
862 block_state bstate;
864 if (strm->clas && s->class_bitmap == NULL) {
865 /* This is the first time that we have seen alternative class
866 * data. All data up till this point has been standard class. */
867 s->class_bitmap = (Bytef*) ZALLOC(strm, s->w_size/4, sizeof(Byte));
868 zmemzero(s->class_bitmap, s->w_size/4);
871 if (strm->clas && s->strategy == Z_RLE) {
872 /* We haven't patched deflate_rle. */
873 ERR_RETURN(strm, Z_BUF_ERROR);
876 if (s->strategy == Z_HUFFMAN_ONLY) {
877 bstate = deflate_huff(s, flush);
878 } else if (s->strategy == Z_RLE) {
879 bstate = deflate_rle(s, flush);
880 } else {
881 bstate = (*(configuration_table[s->level].func))
882 (s, flush, strm->clas);
885 if (bstate == finish_started || bstate == finish_done) {
886 s->status = FINISH_STATE;
888 if (bstate == need_more || bstate == finish_started) {
889 if (strm->avail_out == 0) {
890 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
892 return Z_OK;
893 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
894 * of deflate should use the same flush parameter to make sure
895 * that the flush is complete. So we don't have to output an
896 * empty block here, this will be done at next call. This also
897 * ensures that for a very small output buffer, we emit at most
898 * one empty block.
901 if (bstate == block_done) {
902 if (flush == Z_PARTIAL_FLUSH) {
903 _tr_align(s);
904 } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
905 _tr_stored_block(s, (char*)0, 0L, 0);
906 /* For a full flush, this empty block will be recognized
907 * as a special marker by inflate_sync().
909 if (flush == Z_FULL_FLUSH) {
910 CLEAR_HASH(s); /* forget history */
911 if (s->lookahead == 0) {
912 s->strstart = 0;
913 s->block_start = 0L;
917 flush_pending(strm);
918 if (strm->avail_out == 0) {
919 s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
920 return Z_OK;
924 Assert(strm->avail_out > 0, "bug2");
926 if (flush != Z_FINISH) return Z_OK;
927 if (s->wrap <= 0) return Z_STREAM_END;
929 /* Write the trailer */
930 #ifdef GZIP
931 if (s->wrap == 2) {
932 crc_finalize(s);
933 put_byte(s, (Byte)(strm->adler & 0xff));
934 put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
935 put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
936 put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
937 put_byte(s, (Byte)(strm->total_in & 0xff));
938 put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
939 put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
940 put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
942 else
943 #endif
945 putShortMSB(s, (uInt)(strm->adler >> 16));
946 putShortMSB(s, (uInt)(strm->adler & 0xffff));
948 flush_pending(strm);
949 /* If avail_out is zero, the application will call deflate again
950 * to flush the rest.
952 if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
953 return s->pending != 0 ? Z_OK : Z_STREAM_END;
956 /* ========================================================================= */
957 int ZEXPORT deflateEnd (strm)
958 z_streamp strm;
960 int status;
962 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
964 status = strm->state->status;
965 if (status != INIT_STATE &&
966 status != EXTRA_STATE &&
967 status != NAME_STATE &&
968 status != COMMENT_STATE &&
969 status != HCRC_STATE &&
970 status != BUSY_STATE &&
971 status != FINISH_STATE) {
972 return Z_STREAM_ERROR;
975 /* Deallocate in reverse order of allocations: */
976 TRY_FREE(strm, strm->state->pending_buf);
977 TRY_FREE(strm, strm->state->head);
978 TRY_FREE(strm, strm->state->prev);
979 TRY_FREE(strm, strm->state->window);
980 TRY_FREE(strm, strm->state->class_bitmap);
982 ZFREE(strm, strm->state);
983 strm->state = Z_NULL;
985 return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
988 /* =========================================================================
989 * Copy the source state to the destination state.
990 * To simplify the source, this is not supported for 16-bit MSDOS (which
991 * doesn't have enough memory anyway to duplicate compression states).
993 int ZEXPORT deflateCopy (dest, source)
994 z_streamp dest;
995 z_streamp source;
997 #ifdef MAXSEG_64K
998 return Z_STREAM_ERROR;
999 #else
1000 deflate_state *ds;
1001 deflate_state *ss;
1002 ushf *overlay;
1005 if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
1006 return Z_STREAM_ERROR;
1009 ss = source->state;
1011 zmemcpy(dest, source, sizeof(z_stream));
1013 ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
1014 if (ds == Z_NULL) return Z_MEM_ERROR;
1015 dest->state = (struct internal_state FAR *) ds;
1016 zmemcpy(ds, ss, sizeof(deflate_state));
1017 ds->strm = dest;
1019 ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
1020 ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
1021 ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
1022 overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
1023 ds->pending_buf = (uchf *) overlay;
1025 if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
1026 ds->pending_buf == Z_NULL) {
1027 deflateEnd (dest);
1028 return Z_MEM_ERROR;
1030 /* following zmemcpy do not work for 16-bit MSDOS */
1031 zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
1032 zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
1033 zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
1034 zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
1036 ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
1037 ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
1038 ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
1040 ds->l_desc.dyn_tree = ds->dyn_ltree;
1041 ds->d_desc.dyn_tree = ds->dyn_dtree;
1042 ds->bl_desc.dyn_tree = ds->bl_tree;
1044 return Z_OK;
1045 #endif /* MAXSEG_64K */
1048 /* ===========================================================================
1049 * Read a new buffer from the current input stream, update the adler32
1050 * and total number of bytes read. All deflate() input goes through
1051 * this function so some applications may wish to modify it to avoid
1052 * allocating a large strm->next_in buffer and copying from it.
1053 * (See also flush_pending()).
1055 ZLIB_INTERNAL int read_buf(strm, buf, size)
1056 z_streamp strm;
1057 Bytef *buf;
1058 unsigned size;
1060 unsigned len = strm->avail_in;
1062 if (len > size) len = size;
1063 if (len == 0) return 0;
1065 strm->avail_in -= len;
1067 #ifdef GZIP
1068 if (strm->state->wrap == 2) {
1069 copy_with_crc(strm, buf, len);
1071 else
1072 #endif
1074 zmemcpy(buf, strm->next_in, len);
1075 if (strm->state->wrap == 1)
1076 strm->adler = adler32(strm->adler, buf, len);
1078 strm->next_in += len;
1079 strm->total_in += len;
1081 return (int)len;
1084 /* ===========================================================================
1085 * Initialize the "longest match" routines for a new zlib stream
1087 local void lm_init (s)
1088 deflate_state *s;
1090 s->window_size = (ulg)2L*s->w_size;
1092 CLEAR_HASH(s);
1094 /* Set the default configuration parameters:
1096 s->max_lazy_match = configuration_table[s->level].max_lazy;
1097 s->good_match = configuration_table[s->level].good_length;
1098 s->nice_match = configuration_table[s->level].nice_length;
1099 s->max_chain_length = configuration_table[s->level].max_chain;
1101 s->strstart = 0;
1102 s->block_start = 0L;
1103 s->lookahead = 0;
1104 s->match_length = s->prev_length = MIN_MATCH-1;
1105 s->match_available = 0;
1106 s->ins_h = 0;
1107 #ifndef FASTEST
1108 #ifdef ASMV
1109 match_init(); /* initialize the asm code */
1110 #endif
1111 #endif
1114 /* class_set sets bits [offset,offset+len) in s->class_bitmap to either 1 (if
1115 * class != 0) or 0 (otherwise). */
1116 local void class_set(s, offset, len, clas)
1117 deflate_state *s;
1118 IPos offset;
1119 uInt len;
1120 int clas;
1122 IPos byte = offset >> 3;
1123 IPos bit = offset & 7;
1124 Bytef class_byte_value = clas ? 0xff : 0x00;
1125 Bytef class_bit_value = clas ? 1 : 0;
1126 static const Bytef mask[8] = {0xfe, 0xfd, 0xfb, 0xf7,
1127 0xef, 0xdf, 0xbf, 0x7f};
1129 if (bit) {
1130 while (len) {
1131 s->class_bitmap[byte] &= mask[bit];
1132 s->class_bitmap[byte] |= class_bit_value << bit;
1133 bit++;
1134 len--;
1135 if (bit == 8) {
1136 bit = 0;
1137 byte++;
1138 break;
1143 while (len >= 8) {
1144 s->class_bitmap[byte++] = class_byte_value;
1145 len -= 8;
1148 while (len) {
1149 s->class_bitmap[byte] &= mask[bit];
1150 s->class_bitmap[byte] |= class_bit_value << bit;
1151 bit++;
1152 len--;
1156 local int class_at(s, window_offset)
1157 deflate_state *s;
1158 IPos window_offset;
1160 IPos byte = window_offset >> 3;
1161 IPos bit = window_offset & 7;
1162 return (s->class_bitmap[byte] >> bit) & 1;
1165 #ifndef FASTEST
1166 /* ===========================================================================
1167 * Set match_start to the longest match starting at the given string and
1168 * return its length. Matches shorter or equal to prev_length are discarded,
1169 * in which case the result is equal to prev_length and match_start is
1170 * garbage.
1171 * IN assertions: cur_match is the head of the hash chain for the current
1172 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1173 * OUT assertion: the match length is not greater than s->lookahead.
1175 #ifndef ASMV
1176 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
1177 * match.S. The code will be functionally equivalent.
1179 local uInt longest_match(s, cur_match, clas)
1180 deflate_state *s;
1181 IPos cur_match; /* current match */
1182 int clas;
1184 unsigned chain_length = s->max_chain_length;/* max hash chain length */
1185 register Bytef *scan = s->window + s->strstart; /* current string */
1186 register Bytef *match; /* matched string */
1187 register int len; /* length of current match */
1188 int best_len = s->prev_length; /* best match length so far */
1189 int nice_match = s->nice_match; /* stop if match long enough */
1190 IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
1191 s->strstart - (IPos)MAX_DIST(s) : NIL;
1192 /* Stop when cur_match becomes <= limit. To simplify the code,
1193 * we prevent matches with the string of window index 0.
1195 Posf *prev = s->prev;
1196 uInt wmask = s->w_mask;
1198 #ifdef UNALIGNED_OK
1199 /* Compare two bytes at a time. Note: this is not always beneficial.
1200 * Try with and without -DUNALIGNED_OK to check.
1202 register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
1203 register ush scan_start = *(ushf*)scan;
1204 register ush scan_end = *(ushf*)(scan+best_len-1);
1205 #else
1206 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1207 register Byte scan_end1 = scan[best_len-1];
1208 register Byte scan_end = scan[best_len];
1209 #endif
1211 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1212 * It is easy to get rid of this optimization if necessary.
1214 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1216 /* Do not waste too much time if we already have a good match: */
1217 if (s->prev_length >= s->good_match) {
1218 chain_length >>= 2;
1220 /* Do not look for matches beyond the end of the input. This is necessary
1221 * to make deflate deterministic.
1223 if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
1225 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1227 do {
1228 Assert(cur_match < s->strstart, "no future");
1229 match = s->window + cur_match;
1230 /* If the matched data is in the wrong class, skip it. */
1231 if (s->class_bitmap && class_at(s, cur_match) != clas)
1232 continue;
1234 /* Skip to next match if the match length cannot increase
1235 * or if the match length is less than 2. Note that the checks below
1236 * for insufficient lookahead only occur occasionally for performance
1237 * reasons. Therefore uninitialized memory will be accessed, and
1238 * conditional jumps will be made that depend on those values.
1239 * However the length of the match is limited to the lookahead, so
1240 * the output of deflate is not affected by the uninitialized values.
1242 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
1243 /* This code assumes sizeof(unsigned short) == 2. Do not use
1244 * UNALIGNED_OK if your compiler uses a different size.
1246 if (*(ushf*)(match+best_len-1) != scan_end ||
1247 *(ushf*)match != scan_start) continue;
1249 /* It is not necessary to compare scan[2] and match[2] since they are
1250 * always equal when the other bytes match, given that the hash keys
1251 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
1252 * strstart+3, +5, ... up to strstart+257. We check for insufficient
1253 * lookahead only every 4th comparison; the 128th check will be made
1254 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
1255 * necessary to put more guard bytes at the end of the window, or
1256 * to check more often for insufficient lookahead.
1258 Assert(scan[2] == match[2], "scan[2]?");
1259 scan++, match++;
1260 do {
1261 } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1262 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1263 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1264 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1265 scan < strend);
1266 /* The funny "do {}" generates better code on most compilers */
1268 /* Here, scan <= window+strstart+257 */
1269 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1270 if (*scan == *match) scan++;
1272 len = (MAX_MATCH - 1) - (int)(strend-scan);
1273 scan = strend - (MAX_MATCH-1);
1275 #error "UNALIGNED_OK hasn't been patched."
1277 #else /* UNALIGNED_OK */
1279 if (match[best_len] != scan_end ||
1280 match[best_len-1] != scan_end1 ||
1281 *match != *scan ||
1282 *++match != scan[1]) continue;
1284 /* The check at best_len-1 can be removed because it will be made
1285 * again later. (This heuristic is not always a win.)
1286 * It is not necessary to compare scan[2] and match[2] since they
1287 * are always equal when the other bytes match, given that
1288 * the hash keys are equal and that HASH_BITS >= 8.
1290 scan += 2, match++;
1291 Assert(*scan == *match, "match[2]?");
1293 if (!s->class_bitmap) {
1294 /* We check for insufficient lookahead only every 8th comparison;
1295 * the 256th check will be made at strstart+258.
1297 do {
1298 } while (*++scan == *++match && *++scan == *++match &&
1299 *++scan == *++match && *++scan == *++match &&
1300 *++scan == *++match && *++scan == *++match &&
1301 *++scan == *++match && *++scan == *++match &&
1302 scan < strend);
1303 } else {
1304 /* We have to be mindful of the class of the data and not stray. */
1305 do {
1306 } while (*++scan == *++match &&
1307 class_at(s, match - s->window) == clas &&
1308 scan < strend);
1311 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1313 len = MAX_MATCH - (int)(strend - scan);
1314 scan = strend - MAX_MATCH;
1316 #endif /* UNALIGNED_OK */
1318 if (len > best_len) {
1319 s->match_start = cur_match;
1320 best_len = len;
1321 if (len >= nice_match) break;
1322 #ifdef UNALIGNED_OK
1323 scan_end = *(ushf*)(scan+best_len-1);
1324 #else
1325 scan_end1 = scan[best_len-1];
1326 scan_end = scan[best_len];
1327 #endif
1329 } while ((cur_match = prev[cur_match & wmask]) > limit
1330 && --chain_length != 0);
1332 if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
1333 return s->lookahead;
1335 #endif /* ASMV */
1337 /* cookie_match is a replacement for longest_match in the case of cookie data.
1338 * Here we only wish to match the entire value so trying the partial matches in
1339 * longest_match is both wasteful and often fails to find the correct match.
1341 * So we take the djb2 hash of the cookie and look up the last position for a
1342 * match in a special hash table. */
1343 local uInt cookie_match(s, start, len)
1344 deflate_state *s;
1345 IPos start;
1346 unsigned len;
1348 unsigned hash = 5381;
1349 Bytef *str = s->window + start;
1350 unsigned i;
1351 IPos cookie_location;
1353 if (len >= MAX_MATCH || len == 0)
1354 return 0;
1356 for (i = 0; i < len; i++)
1357 hash = ((hash << 5) + hash) + str[i];
1359 hash &= Z_COOKIE_HASH_MASK;
1360 cookie_location = s->cookie_locations[hash];
1361 s->cookie_locations[hash] = start;
1362 s->match_start = 0;
1363 if (cookie_location &&
1364 (start - cookie_location) > len &&
1365 (start - cookie_location) < MAX_DIST(s) &&
1366 len <= s->lookahead) {
1367 for (i = 0; i < len; i++) {
1368 if (s->window[start+i] != s->window[cookie_location+i] ||
1369 class_at(s, cookie_location+i) != 1) {
1370 return 0;
1373 /* Check that we aren't matching a prefix of another cookie by ensuring
1374 * that the final byte is either a semicolon (which cannot appear in a
1375 * cookie value), or the match is followed by non-cookie data. */
1376 if (s->window[cookie_location+len-1] != ';' &&
1377 class_at(s, cookie_location+len) != 0) {
1378 return 0;
1380 s->match_start = cookie_location;
1381 return len;
1384 return 0;
1388 #else /* FASTEST */
1390 /* ---------------------------------------------------------------------------
1391 * Optimized version for FASTEST only
1393 local uInt longest_match(s, cur_match, clas)
1394 deflate_state *s;
1395 IPos cur_match; /* current match */
1396 int clas;
1398 register Bytef *scan = s->window + s->strstart; /* current string */
1399 register Bytef *match; /* matched string */
1400 register int len; /* length of current match */
1401 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1403 #error "This code not patched"
1405 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1406 * It is easy to get rid of this optimization if necessary.
1408 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1410 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1412 Assert(cur_match < s->strstart, "no future");
1414 match = s->window + cur_match;
1416 /* Return failure if the match length is less than 2:
1418 if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
1420 /* The check at best_len-1 can be removed because it will be made
1421 * again later. (This heuristic is not always a win.)
1422 * It is not necessary to compare scan[2] and match[2] since they
1423 * are always equal when the other bytes match, given that
1424 * the hash keys are equal and that HASH_BITS >= 8.
1426 scan += 2, match += 2;
1427 Assert(*scan == *match, "match[2]?");
1429 /* We check for insufficient lookahead only every 8th comparison;
1430 * the 256th check will be made at strstart+258.
1432 do {
1433 } while (*++scan == *++match && *++scan == *++match &&
1434 *++scan == *++match && *++scan == *++match &&
1435 *++scan == *++match && *++scan == *++match &&
1436 *++scan == *++match && *++scan == *++match &&
1437 scan < strend);
1439 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1441 len = MAX_MATCH - (int)(strend - scan);
1443 if (len < MIN_MATCH) return MIN_MATCH - 1;
1445 s->match_start = cur_match;
1446 return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
1449 #endif /* FASTEST */
1451 #ifdef DEBUG
1452 /* ===========================================================================
1453 * Check that the match at match_start is indeed a match.
1455 local void check_match(s, start, match, length)
1456 deflate_state *s;
1457 IPos start, match;
1458 int length;
1460 /* check that the match is indeed a match */
1461 if (zmemcmp(s->window + match,
1462 s->window + start, length) != EQUAL) {
1463 fprintf(stderr, " start %u, match %u, length %d\n",
1464 start, match, length);
1465 do {
1466 fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
1467 } while (--length != 0);
1468 z_error("invalid match");
1470 if (z_verbose > 1) {
1471 fprintf(stderr,"\\[%d,%d]", start-match, length);
1472 do { putc(s->window[start++], stderr); } while (--length != 0);
1475 #else
1476 # define check_match(s, start, match, length)
1477 #endif /* DEBUG */
1479 /* ===========================================================================
1480 * Fill the window when the lookahead becomes insufficient.
1481 * Updates strstart and lookahead.
1483 * IN assertion: lookahead < MIN_LOOKAHEAD
1484 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1485 * At least one byte has been read, or avail_in == 0; reads are
1486 * performed for at least two bytes (required for the zip translate_eol
1487 * option -- not supported here).
1489 local void fill_window_c(deflate_state *s);
1491 local void fill_window(deflate_state *s)
1493 if (x86_cpu_enable_simd) {
1494 fill_window_sse(s);
1495 return;
1498 fill_window_c(s);
1501 local void fill_window_c(s)
1502 deflate_state *s;
1504 register unsigned n, m;
1505 register Posf *p;
1506 unsigned more; /* Amount of free space at the end of the window. */
1507 uInt wsize = s->w_size;
1509 do {
1510 more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
1512 /* Deal with !@#$% 64K limit: */
1513 if (sizeof(int) <= 2) {
1514 if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1515 more = wsize;
1517 } else if (more == (unsigned)(-1)) {
1518 /* Very unlikely, but possible on 16 bit machine if
1519 * strstart == 0 && lookahead == 1 (input done a byte at time)
1521 more--;
1525 /* If the window is almost full and there is insufficient lookahead,
1526 * move the upper half to the lower one to make room in the upper half.
1528 if (s->strstart >= wsize+MAX_DIST(s)) {
1530 zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
1531 s->match_start -= wsize;
1532 s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
1533 s->block_start -= (long) wsize;
1535 /* Slide the hash table (could be avoided with 32 bit values
1536 at the expense of memory usage). We slide even when level == 0
1537 to keep the hash table consistent if we switch back to level > 0
1538 later. (Using level 0 permanently is not an optimal usage of
1539 zlib, so we don't care about this pathological case.)
1541 n = s->hash_size;
1542 p = &s->head[n];
1543 do {
1544 m = *--p;
1545 *p = (Pos)(m >= wsize ? m-wsize : NIL);
1546 } while (--n);
1548 n = wsize;
1549 #ifndef FASTEST
1550 p = &s->prev[n];
1551 do {
1552 m = *--p;
1553 *p = (Pos)(m >= wsize ? m-wsize : NIL);
1554 /* If n is not on any hash chain, prev[n] is garbage but
1555 * its value will never be used.
1557 } while (--n);
1558 #endif
1560 for (n = 0; n < Z_COOKIE_HASH_SIZE; n++) {
1561 if (s->cookie_locations[n] > wsize) {
1562 s->cookie_locations[n] -= wsize;
1563 } else {
1564 s->cookie_locations[n] = 0;
1568 if (s->class_bitmap) {
1569 zmemcpy(s->class_bitmap, s->class_bitmap + s->w_size/8,
1570 s->w_size/8);
1571 zmemzero(s->class_bitmap + s->w_size/8, s->w_size/8);
1574 more += wsize;
1576 if (s->strm->avail_in == 0) return;
1578 /* If there was no sliding:
1579 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1580 * more == window_size - lookahead - strstart
1581 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1582 * => more >= window_size - 2*WSIZE + 2
1583 * In the BIG_MEM or MMAP case (not yet supported),
1584 * window_size == input_size + MIN_LOOKAHEAD &&
1585 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1586 * Otherwise, window_size == 2*WSIZE so more >= 2.
1587 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1589 Assert(more >= 2, "more < 2");
1591 n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1592 if (s->class_bitmap != NULL) {
1593 class_set(s, s->strstart + s->lookahead, n, s->strm->clas);
1595 s->lookahead += n;
1597 /* Initialize the hash value now that we have some input: */
1598 if (s->lookahead >= MIN_MATCH) {
1599 s->ins_h = s->window[s->strstart];
1600 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1601 #if MIN_MATCH != 3
1602 Call UPDATE_HASH() MIN_MATCH-3 more times
1603 #endif
1605 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1606 * but this is not important since only literal bytes will be emitted.
1609 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1611 /* If the WIN_INIT bytes after the end of the current data have never been
1612 * written, then zero those bytes in order to avoid memory check reports of
1613 * the use of uninitialized (or uninitialised as Julian writes) bytes by
1614 * the longest match routines. Update the high water mark for the next
1615 * time through here. WIN_INIT is set to MAX_MATCH since the longest match
1616 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
1618 if (s->high_water < s->window_size) {
1619 ulg curr = s->strstart + (ulg)(s->lookahead);
1620 ulg init;
1622 if (s->high_water < curr) {
1623 /* Previous high water mark below current data -- zero WIN_INIT
1624 * bytes or up to end of window, whichever is less.
1626 init = s->window_size - curr;
1627 if (init > WIN_INIT)
1628 init = WIN_INIT;
1629 zmemzero(s->window + curr, (unsigned)init);
1630 s->high_water = curr + init;
1632 else if (s->high_water < (ulg)curr + WIN_INIT) {
1633 /* High water mark at or above current data, but below current data
1634 * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
1635 * to end of window, whichever is less.
1637 init = (ulg)curr + WIN_INIT - s->high_water;
1638 if (init > s->window_size - s->high_water)
1639 init = s->window_size - s->high_water;
1640 zmemzero(s->window + s->high_water, (unsigned)init);
1641 s->high_water += init;
1646 /* ===========================================================================
1647 * Flush the current block, with given end-of-file flag.
1648 * IN assertion: strstart is set to the end of the current match.
1650 #define FLUSH_BLOCK_ONLY(s, last) { \
1651 _tr_flush_block(s, (s->block_start >= 0L ? \
1652 (charf *)&s->window[(unsigned)s->block_start] : \
1653 (charf *)Z_NULL), \
1654 (ulg)((long)s->strstart - s->block_start), \
1655 (last)); \
1656 s->block_start = s->strstart; \
1657 flush_pending(s->strm); \
1658 Tracev((stderr,"[FLUSH]")); \
1661 /* Same but force premature exit if necessary. */
1662 #define FLUSH_BLOCK(s, last) { \
1663 FLUSH_BLOCK_ONLY(s, last); \
1664 if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
1667 /* ===========================================================================
1668 * Copy without compression as much as possible from the input stream, return
1669 * the current block state.
1670 * This function does not insert new strings in the dictionary since
1671 * uncompressible data is probably not useful. This function is used
1672 * only for the level=0 compression option.
1673 * NOTE: this function should be optimized to avoid extra copying from
1674 * window to pending_buf.
1676 local block_state deflate_stored(s, flush, clas)
1677 deflate_state *s;
1678 int flush;
1679 int clas;
1681 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
1682 * to pending_buf_size, and each stored block has a 5 byte header:
1684 ulg max_block_size = 0xffff;
1685 ulg max_start;
1687 if (max_block_size > s->pending_buf_size - 5) {
1688 max_block_size = s->pending_buf_size - 5;
1691 /* Copy as much as possible from input to output: */
1692 for (;;) {
1693 /* Fill the window as much as possible: */
1694 if (s->lookahead <= 1) {
1696 Assert(s->strstart < s->w_size+MAX_DIST(s) ||
1697 s->block_start >= (long)s->w_size, "slide too late");
1699 fill_window(s);
1700 if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
1702 if (s->lookahead == 0) break; /* flush the current block */
1704 Assert(s->block_start >= 0L, "block gone");
1706 s->strstart += s->lookahead;
1707 s->lookahead = 0;
1709 /* Emit a stored block if pending_buf will be full: */
1710 max_start = s->block_start + max_block_size;
1711 if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
1712 /* strstart == 0 is possible when wraparound on 16-bit machine */
1713 s->lookahead = (uInt)(s->strstart - max_start);
1714 s->strstart = (uInt)max_start;
1715 FLUSH_BLOCK(s, 0);
1717 /* Flush if we may have to slide, otherwise block_start may become
1718 * negative and the data will be gone:
1720 if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
1721 FLUSH_BLOCK(s, 0);
1724 FLUSH_BLOCK(s, flush == Z_FINISH);
1725 return flush == Z_FINISH ? finish_done : block_done;
1728 /* ===========================================================================
1729 * Compress as much as possible from the input stream, return the current
1730 * block state.
1731 * This function does not perform lazy evaluation of matches and inserts
1732 * new strings in the dictionary only for unmatched strings or for short
1733 * matches. It is used only for the fast compression options.
1735 local block_state deflate_fast(s, flush, clas)
1736 deflate_state *s;
1737 int flush;
1738 int clas;
1740 IPos hash_head; /* head of the hash chain */
1741 int bflush; /* set if current block must be flushed */
1743 if (clas != 0) {
1744 /* We haven't patched this code for alternative class data. */
1745 return Z_BUF_ERROR;
1748 for (;;) {
1749 /* Make sure that we always have enough lookahead, except
1750 * at the end of the input file. We need MAX_MATCH bytes
1751 * for the next match, plus MIN_MATCH bytes to insert the
1752 * string following the next match.
1754 if (s->lookahead < MIN_LOOKAHEAD) {
1755 fill_window(s);
1756 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1757 return need_more;
1759 if (s->lookahead == 0) break; /* flush the current block */
1762 /* Insert the string window[strstart .. strstart+2] in the
1763 * dictionary, and set hash_head to the head of the hash chain:
1765 hash_head = NIL;
1766 if (s->lookahead >= MIN_MATCH) {
1767 hash_head = insert_string(s, s->strstart);
1770 /* Find the longest match, discarding those <= prev_length.
1771 * At this point we have always match_length < MIN_MATCH
1773 if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1774 /* To simplify the code, we prevent matches with the string
1775 * of window index 0 (in particular we have to avoid a match
1776 * of the string with itself at the start of the input file).
1778 s->match_length = longest_match (s, hash_head, clas);
1779 /* longest_match() sets match_start */
1781 if (s->match_length >= MIN_MATCH) {
1782 check_match(s, s->strstart, s->match_start, s->match_length);
1784 _tr_tally_dist(s, s->strstart - s->match_start,
1785 s->match_length - MIN_MATCH, bflush);
1787 s->lookahead -= s->match_length;
1789 /* Insert new strings in the hash table only if the match length
1790 * is not too large. This saves time but degrades compression.
1792 #ifndef FASTEST
1793 if (s->match_length <= s->max_insert_length &&
1794 s->lookahead >= MIN_MATCH) {
1795 s->match_length--; /* string at strstart already in table */
1796 do {
1797 s->strstart++;
1798 hash_head = insert_string(s, s->strstart);
1799 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1800 * always MIN_MATCH bytes ahead.
1802 } while (--s->match_length != 0);
1803 s->strstart++;
1804 } else
1805 #endif
1807 s->strstart += s->match_length;
1808 s->match_length = 0;
1809 s->ins_h = s->window[s->strstart];
1810 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1811 #if MIN_MATCH != 3
1812 Call UPDATE_HASH() MIN_MATCH-3 more times
1813 #endif
1814 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1815 * matter since it will be recomputed at next deflate call.
1818 } else {
1819 /* No match, output a literal byte */
1820 Tracevv((stderr,"%c", s->window[s->strstart]));
1821 _tr_tally_lit (s, s->window[s->strstart], bflush);
1822 s->lookahead--;
1823 s->strstart++;
1825 if (bflush) FLUSH_BLOCK(s, 0);
1827 FLUSH_BLOCK(s, flush == Z_FINISH);
1828 return flush == Z_FINISH ? finish_done : block_done;
1831 #ifndef FASTEST
1832 /* ===========================================================================
1833 * Same as above, but achieves better compression. We use a lazy
1834 * evaluation for matches: a match is finally adopted only if there is
1835 * no better match at the next window position.
1837 local block_state deflate_slow(s, flush, clas)
1838 deflate_state *s;
1839 int flush;
1840 int clas;
1842 IPos hash_head; /* head of hash chain */
1843 int bflush; /* set if current block must be flushed */
1844 uInt input_length ;
1845 int first = 1; /* first says whether this is the first iteration
1846 of the loop, below. */
1848 if (clas == Z_CLASS_COOKIE) {
1849 if (s->lookahead) {
1850 /* Alternative class data must always be presented at the beginning
1851 * of a block. */
1852 return Z_BUF_ERROR;
1854 input_length = s->strm->avail_in;
1857 /* Process the input block. */
1858 for (;;) {
1859 /* Make sure that we always have enough lookahead, except
1860 * at the end of the input file. We need MAX_MATCH bytes
1861 * for the next match, plus MIN_MATCH bytes to insert the
1862 * string following the next match.
1864 if (s->lookahead < MIN_LOOKAHEAD) {
1865 fill_window(s);
1866 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1867 return need_more;
1869 if (s->lookahead == 0) break; /* flush the current block */
1872 /* Insert the string window[strstart .. strstart+2] in the
1873 * dictionary, and set hash_head to the head of the hash chain:
1875 hash_head = NIL;
1876 if (s->lookahead >= MIN_MATCH) {
1877 hash_head = insert_string(s, s->strstart);
1880 /* Find the longest match, discarding those <= prev_length.
1882 s->prev_length = s->match_length, s->prev_match = s->match_start;
1883 s->match_length = MIN_MATCH-1;
1885 if (clas == Z_CLASS_COOKIE && first) {
1886 s->match_length = cookie_match(s, s->strstart, input_length);
1887 } else if (clas == Z_CLASS_STANDARD &&
1888 hash_head != NIL &&
1889 s->prev_length < s->max_lazy_match &&
1890 s->strstart - hash_head <= MAX_DIST(s)) {
1891 /* To simplify the code, we prevent matches with the string
1892 * of window index 0 (in particular we have to avoid a match
1893 * of the string with itself at the start of the input file).
1895 s->match_length = longest_match (s, hash_head, clas);
1897 /* longest_match() sets match_start */
1899 if (s->match_length <= 5 && (s->strategy == Z_FILTERED
1900 #if TOO_FAR <= 32767
1901 || (s->match_length == MIN_MATCH &&
1902 s->strstart - s->match_start > TOO_FAR)
1903 #endif
1904 )) {
1906 /* If prev_match is also MIN_MATCH, match_start is garbage
1907 * but we will ignore the current match anyway.
1909 s->match_length = MIN_MATCH-1;
1912 /* If there was a match at the previous step and the current
1913 * match is not better, output the previous match:
1915 first = 0;
1916 if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length &&
1917 /* We will only accept an exact match for Z_CLASS_COOKIE data and
1918 * we won't match Z_CLASS_HUFFMAN_ONLY data at all. */
1919 (clas == Z_CLASS_STANDARD || (clas == Z_CLASS_COOKIE &&
1920 s->prev_length == input_length &&
1921 s->prev_match > 0 &&
1922 /* We require that a Z_CLASS_COOKIE match be
1923 * preceded by either a semicolon (which cannot be
1924 * part of a cookie), or non-cookie data. This is
1925 * to prevent a cookie from being a suffix of
1926 * another. */
1927 (class_at(s, s->prev_match-1) == Z_CLASS_STANDARD ||
1928 *(s->window + s->prev_match-1) == ';')))) {
1929 uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
1930 /* Do not insert strings in hash table beyond this. */
1932 check_match(s, s->strstart-1, s->prev_match, s->prev_length);
1934 _tr_tally_dist(s, s->strstart -1 - s->prev_match,
1935 s->prev_length - MIN_MATCH, bflush);
1937 /* Insert in hash table all strings up to the end of the match.
1938 * strstart-1 and strstart are already inserted. If there is not
1939 * enough lookahead, the last two strings are not inserted in
1940 * the hash table.
1942 s->lookahead -= s->prev_length-1;
1943 s->prev_length -= 2;
1944 do {
1945 if (++s->strstart <= max_insert) {
1946 hash_head = insert_string(s, s->strstart);
1948 } while (--s->prev_length != 0);
1949 s->match_available = 0;
1950 s->match_length = MIN_MATCH-1;
1951 s->strstart++;
1953 if (bflush) FLUSH_BLOCK(s, 0);
1955 } else if (s->match_available) {
1956 /* If there was no match at the previous position, output a
1957 * single literal. If there was a match but the current match
1958 * is longer, truncate the previous match to a single literal.
1960 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1961 _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1962 if (bflush) {
1963 FLUSH_BLOCK_ONLY(s, 0);
1965 s->strstart++;
1966 s->lookahead--;
1967 if (s->strm->avail_out == 0) return need_more;
1968 } else {
1969 /* There is no previous match to compare with, wait for
1970 * the next step to decide.
1972 s->match_available = 1;
1973 s->strstart++;
1974 s->lookahead--;
1977 Assert (flush != Z_NO_FLUSH, "no flush?");
1978 if (s->match_available) {
1979 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1980 _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1981 s->match_available = 0;
1983 FLUSH_BLOCK(s, flush == Z_FINISH);
1984 return flush == Z_FINISH ? finish_done : block_done;
1986 #endif /* FASTEST */
1988 /* ===========================================================================
1989 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
1990 * one. Do not maintain a hash table. (It will be regenerated if this run of
1991 * deflate switches away from Z_RLE.)
1993 local block_state deflate_rle(s, flush)
1994 deflate_state *s;
1995 int flush;
1997 int bflush; /* set if current block must be flushed */
1998 uInt prev; /* byte at distance one to match */
1999 Bytef *scan, *strend; /* scan goes up to strend for length of run */
2001 for (;;) {
2002 /* Make sure that we always have enough lookahead, except
2003 * at the end of the input file. We need MAX_MATCH bytes
2004 * for the longest encodable run.
2006 if (s->lookahead < MAX_MATCH) {
2007 fill_window(s);
2008 if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
2009 return need_more;
2011 if (s->lookahead == 0) break; /* flush the current block */
2014 /* See how many times the previous byte repeats */
2015 s->match_length = 0;
2016 if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
2017 scan = s->window + s->strstart - 1;
2018 prev = *scan;
2019 if (prev == *++scan && prev == *++scan && prev == *++scan) {
2020 strend = s->window + s->strstart + MAX_MATCH;
2021 do {
2022 } while (prev == *++scan && prev == *++scan &&
2023 prev == *++scan && prev == *++scan &&
2024 prev == *++scan && prev == *++scan &&
2025 prev == *++scan && prev == *++scan &&
2026 scan < strend);
2027 s->match_length = MAX_MATCH - (int)(strend - scan);
2028 if (s->match_length > s->lookahead)
2029 s->match_length = s->lookahead;
2033 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
2034 if (s->match_length >= MIN_MATCH) {
2035 check_match(s, s->strstart, s->strstart - 1, s->match_length);
2037 _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
2039 s->lookahead -= s->match_length;
2040 s->strstart += s->match_length;
2041 s->match_length = 0;
2042 } else {
2043 /* No match, output a literal byte */
2044 Tracevv((stderr,"%c", s->window[s->strstart]));
2045 _tr_tally_lit (s, s->window[s->strstart], bflush);
2046 s->lookahead--;
2047 s->strstart++;
2049 if (bflush) FLUSH_BLOCK(s, 0);
2051 FLUSH_BLOCK(s, flush == Z_FINISH);
2052 return flush == Z_FINISH ? finish_done : block_done;
2055 /* ===========================================================================
2056 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
2057 * (It will be regenerated if this run of deflate switches away from Huffman.)
2059 local block_state deflate_huff(s, flush)
2060 deflate_state *s;
2061 int flush;
2063 int bflush; /* set if current block must be flushed */
2065 for (;;) {
2066 /* Make sure that we have a literal to write. */
2067 if (s->lookahead == 0) {
2068 fill_window(s);
2069 if (s->lookahead == 0) {
2070 if (flush == Z_NO_FLUSH)
2071 return need_more;
2072 break; /* flush the current block */
2076 /* Output a literal byte */
2077 s->match_length = 0;
2078 Tracevv((stderr,"%c", s->window[s->strstart]));
2079 _tr_tally_lit (s, s->window[s->strstart], bflush);
2080 s->lookahead--;
2081 s->strstart++;
2082 if (bflush) FLUSH_BLOCK(s, 0);
2084 FLUSH_BLOCK(s, flush == Z_FINISH);
2085 return flush == Z_FINISH ? finish_done : block_done;
2088 /* Safe to inline this as GCC/clang will use inline asm and Visual Studio will
2089 * use intrinsic without extra params
2091 local INLINE Pos insert_string_sse(deflate_state *const s, const Pos str)
2093 Pos ret;
2094 unsigned *ip, val, h = 0;
2096 ip = (unsigned *)&s->window[str];
2097 val = *ip;
2099 if (s->level >= 6)
2100 val &= 0xFFFFFF;
2102 /* Windows clang should use inline asm */
2103 #if defined(_MSC_VER) && !defined(__clang__)
2104 h = _mm_crc32_u32(h, val);
2105 #elif defined(__i386__) || defined(__amd64__)
2106 __asm__ __volatile__ (
2107 "crc32 %1,%0\n\t"
2108 : "+r" (h)
2109 : "r" (val)
2111 #else
2112 /* This should never happen */
2113 assert(0);
2114 #endif
2116 ret = s->head[h & s->hash_mask];
2117 s->head[h & s->hash_mask] = str;
2118 s->prev[str & s->w_mask] = ret;
2119 return ret;