Geant4 11.2.2
Toolkit for the simulation of the passage of particles through matter
Loading...
Searching...
No Matches
deflate.c
Go to the documentation of this file.
1/* deflate.c -- compress data using the deflation algorithm
2 * Copyright (C) 1995-2022 Jean-loup Gailly and Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
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://tools.ietf.org/html/rfc1951
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 */
49
50/* @(#) $Id$ */
51
52#include "deflate.h"
53
54const char deflate_copyright[] =
55 " deflate 1.2.13 Copyright 1995-2022 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 */
62
63/* ===========================================================================
64 * Function prototypes.
65 */
66typedef 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 */
72
73typedef block_state (*compress_func) OF((deflate_state *s, int flush));
74/* Compression function. Returns the block state after the call. */
75
81#ifndef FASTEST
83#endif
86local void lm_init OF((deflate_state *s));
87local void putShortMSB OF((deflate_state *s, uInt b));
88local void flush_pending OF((z_streamp strm));
89local unsigned read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
90local uInt longest_match OF((deflate_state *s, IPos cur_match));
91
92#ifdef ZLIB_DEBUG
93local void check_match OF((deflate_state *s, IPos start, IPos match,
94 int length));
95#endif
96
97/* ===========================================================================
98 * Local data
99 */
100
101#define NIL 0
102/* Tail of hash chains */
103
104#ifndef TOO_FAR
105# define TOO_FAR 4096
106#endif
107/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
108
109/* Values for max_lazy_match, good_match and max_chain_length, depending on
110 * the desired pack level (0..9). The values given below have been tuned to
111 * exclude worst case performance for pathological files. Better values may be
112 * found for specific files.
113 */
114typedef struct config_s {
115 ush good_length; /* reduce lazy search above this match length */
116 ush max_lazy; /* do not perform lazy search above this match length */
117 ush nice_length; /* quit search above this match length */
119 compress_func func;
121
122#ifdef FASTEST
124/* good lazy nice chain */
125/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
126/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
127#else
129/* good lazy nice chain */
130/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
131/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
132/* 2 */ {4, 5, 16, 8, deflate_fast},
133/* 3 */ {4, 6, 32, 32, deflate_fast},
134
135/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
136/* 5 */ {8, 16, 32, 32, deflate_slow},
137/* 6 */ {8, 16, 128, 128, deflate_slow},
138/* 7 */ {8, 32, 128, 256, deflate_slow},
139/* 8 */ {32, 128, 258, 1024, deflate_slow},
140/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
141#endif
142
143/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
144 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
145 * meaning.
146 */
147
148/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */
149#define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0))
150
151/* ===========================================================================
152 * Update a hash value with the given input byte
153 * IN assertion: all calls to UPDATE_HASH are made with consecutive input
154 * characters, so that a running hash key can be computed from the previous
155 * key instead of complete recalculation each time.
156 */
157#define UPDATE_HASH(s,h,c) (h = (((h) << s->hash_shift) ^ (c)) & s->hash_mask)
158
159
160/* ===========================================================================
161 * Insert string str in the dictionary and set match_head to the previous head
162 * of the hash chain (the most recent string with same hash key). Return
163 * the previous length of the hash chain.
164 * If this file is compiled with -DFASTEST, the compression level is forced
165 * to 1, and no hash chains are maintained.
166 * IN assertion: all calls to INSERT_STRING are made with consecutive input
167 * characters and the first MIN_MATCH bytes of str are valid (except for
168 * the last MIN_MATCH-1 bytes of the input file).
169 */
170#ifdef FASTEST
171#define INSERT_STRING(s, str, match_head) \
172 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
173 match_head = s->head[s->ins_h], \
174 s->head[s->ins_h] = (Pos)(str))
175#else
176#define INSERT_STRING(s, str, match_head) \
177 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
178 match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
179 s->head[s->ins_h] = (Pos)(str))
180#endif
181
182/* ===========================================================================
183 * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
184 * prev[] will be initialized on the fly.
185 */
186#define CLEAR_HASH(s) \
187 do { \
188 s->head[s->hash_size - 1] = NIL; \
189 zmemzero((Bytef *)s->head, \
190 (unsigned)(s->hash_size - 1)*sizeof(*s->head)); \
191 } while (0)
192
193/* ===========================================================================
194 * Slide the hash table when sliding the window down (could be avoided with 32
195 * bit values at the expense of memory usage). We slide even when level == 0 to
196 * keep the hash table consistent if we switch back to level > 0 later.
197 */
199 deflate_state *s;
200{
201 unsigned n, m;
202 Posf *p;
203 uInt wsize = s->w_size;
204
205 n = s->hash_size;
206 p = &s->head[n];
207 do {
208 m = *--p;
209 *p = (Pos)(m >= wsize ? m - wsize : NIL);
210 } while (--n);
211 n = wsize;
212#ifndef FASTEST
213 p = &s->prev[n];
214 do {
215 m = *--p;
216 *p = (Pos)(m >= wsize ? m - wsize : NIL);
217 /* If n is not on any hash chain, prev[n] is garbage but
218 * its value will never be used.
219 */
220 } while (--n);
221#endif
222}
223
224/* ========================================================================= */
225int ZEXPORT deflateInit_(strm, level, version, stream_size)
226 z_streamp strm;
227 int level;
228 const char *version;
229 int stream_size;
230{
231 return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
232 Z_DEFAULT_STRATEGY, version, stream_size);
233 /* To do: ignore strm->next_in if we use it as window */
234}
235
236/* ========================================================================= */
237int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
238 version, stream_size)
239 z_streamp strm;
240 int level;
241 int method;
242 int windowBits;
243 int memLevel;
244 int strategy;
245 const char *version;
246 int stream_size;
247{
248 deflate_state *s;
249 int wrap = 1;
250 static const char my_version[] = ZLIB_VERSION;
251
252 if (version == Z_NULL || version[0] != my_version[0] ||
253 stream_size != sizeof(z_stream)) {
254 return Z_VERSION_ERROR;
255 }
256 if (strm == Z_NULL) return Z_STREAM_ERROR;
257
258 strm->msg = Z_NULL;
259 if (strm->zalloc == (alloc_func)0) {
260#ifdef Z_SOLO
261 return Z_STREAM_ERROR;
262#else
263 strm->zalloc = zcalloc;
264 strm->opaque = (voidpf)0;
265#endif
266 }
267 if (strm->zfree == (free_func)0)
268#ifdef Z_SOLO
269 return Z_STREAM_ERROR;
270#else
271 strm->zfree = zcfree;
272#endif
273
274#ifdef FASTEST
275 if (level != 0) level = 1;
276#else
277 if (level == Z_DEFAULT_COMPRESSION) level = 6;
278#endif
279
280 if (windowBits < 0) { /* suppress zlib wrapper */
281 wrap = 0;
282 if (windowBits < -15)
283 return Z_STREAM_ERROR;
284 windowBits = -windowBits;
285 }
286#ifdef GZIP
287 else if (windowBits > 15) {
288 wrap = 2; /* write gzip wrapper instead */
289 windowBits -= 16;
290 }
291#endif
292 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
293 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
294 strategy < 0 || strategy > Z_FIXED || (windowBits == 8 && wrap != 1)) {
295 return Z_STREAM_ERROR;
296 }
297 if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
298 s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
299 if (s == Z_NULL) return Z_MEM_ERROR;
300 strm->state = (struct internal_state FAR *)s;
301 s->strm = strm;
302 s->status = INIT_STATE; /* to pass state test in deflateReset() */
303
304 s->wrap = wrap;
305 s->gzhead = Z_NULL;
306 s->w_bits = (uInt)windowBits;
307 s->w_size = 1 << s->w_bits;
308 s->w_mask = s->w_size - 1;
309
310 s->hash_bits = (uInt)memLevel + 7;
311 s->hash_size = 1 << s->hash_bits;
312 s->hash_mask = s->hash_size - 1;
313 s->hash_shift = ((s->hash_bits + MIN_MATCH-1) / MIN_MATCH);
314
315 s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
316 s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
317 /* Avoid use of uninitialized value, see:
318 * https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=11360
319 */
320 zmemzero(s->prev, s->w_size * sizeof(Pos));
321 s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
322
323 s->high_water = 0; /* nothing written to s->window yet */
324
325 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
326
327 /* We overlay pending_buf and sym_buf. This works since the average size
328 * for length/distance pairs over any compressed block is assured to be 31
329 * bits or less.
330 *
331 * Analysis: The longest fixed codes are a length code of 8 bits plus 5
332 * extra bits, for lengths 131 to 257. The longest fixed distance codes are
333 * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest
334 * possible fixed-codes length/distance pair is then 31 bits total.
335 *
336 * sym_buf starts one-fourth of the way into pending_buf. So there are
337 * three bytes in sym_buf for every four bytes in pending_buf. Each symbol
338 * in sym_buf is three bytes -- two for the distance and one for the
339 * literal/length. As each symbol is consumed, the pointer to the next
340 * sym_buf value to read moves forward three bytes. From that symbol, up to
341 * 31 bits are written to pending_buf. The closest the written pending_buf
342 * bits gets to the next sym_buf symbol to read is just before the last
343 * code is written. At that time, 31*(n - 2) bits have been written, just
344 * after 24*(n - 2) bits have been consumed from sym_buf. sym_buf starts at
345 * 8*n bits into pending_buf. (Note that the symbol buffer fills when n - 1
346 * symbols are written.) The closest the writing gets to what is unread is
347 * then n + 14 bits. Here n is lit_bufsize, which is 16384 by default, and
348 * can range from 128 to 32768.
349 *
350 * Therefore, at a minimum, there are 142 bits of space between what is
351 * written and what is read in the overlain buffers, so the symbols cannot
352 * be overwritten by the compressed data. That space is actually 139 bits,
353 * due to the three-bit fixed-code block header.
354 *
355 * That covers the case where either Z_FIXED is specified, forcing fixed
356 * codes, or when the use of fixed codes is chosen, because that choice
357 * results in a smaller compressed block than dynamic codes. That latter
358 * condition then assures that the above analysis also covers all dynamic
359 * blocks. A dynamic-code block will only be chosen to be emitted if it has
360 * fewer bits than a fixed-code block would for the same set of symbols.
361 * Therefore its average symbol length is assured to be less than 31. So
362 * the compressed data for a dynamic block also cannot overwrite the
363 * symbols from which it is being constructed.
364 */
365
366 s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, 4);
367 s->pending_buf_size = (ulg)s->lit_bufsize * 4;
368
369 if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
370 s->pending_buf == Z_NULL) {
371 s->status = FINISH_STATE;
372 strm->msg = ERR_MSG(Z_MEM_ERROR);
374 return Z_MEM_ERROR;
375 }
376 s->sym_buf = s->pending_buf + s->lit_bufsize;
377 s->sym_end = (s->lit_bufsize - 1) * 3;
378 /* We avoid equality with lit_bufsize*3 because of wraparound at 64K
379 * on 16 bit machines and because stored blocks are restricted to
380 * 64K-1 bytes.
381 */
382
383 s->level = level;
384 s->strategy = strategy;
385 s->method = (Byte)method;
386
387 return deflateReset(strm);
388}
389
390/* =========================================================================
391 * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
392 */
395{
396 deflate_state *s;
397 if (strm == Z_NULL ||
398 strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
399 return 1;
400 s = strm->state;
401 if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE &&
402#ifdef GZIP
403 s->status != GZIP_STATE &&
404#endif
405 s->status != EXTRA_STATE &&
406 s->status != NAME_STATE &&
407 s->status != COMMENT_STATE &&
408 s->status != HCRC_STATE &&
409 s->status != BUSY_STATE &&
410 s->status != FINISH_STATE))
411 return 1;
412 return 0;
413}
414
415/* ========================================================================= */
416int ZEXPORT deflateSetDictionary(strm, dictionary, dictLength)
418 const Bytef *dictionary;
419 uInt dictLength;
420{
421 deflate_state *s;
422 uInt str, n;
423 int wrap;
424 unsigned avail;
425 z_const unsigned char *next;
426
427 if (deflateStateCheck(strm) || dictionary == Z_NULL)
428 return Z_STREAM_ERROR;
429 s = strm->state;
430 wrap = s->wrap;
431 if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
432 return Z_STREAM_ERROR;
433
434 /* when using zlib wrappers, compute Adler-32 for provided dictionary */
435 if (wrap == 1)
436 strm->adler = adler32(strm->adler, dictionary, dictLength);
437 s->wrap = 0; /* avoid computing Adler-32 in read_buf */
438
439 /* if dictionary would fill window, just replace the history */
440 if (dictLength >= s->w_size) {
441 if (wrap == 0) { /* already empty otherwise */
442 CLEAR_HASH(s);
443 s->strstart = 0;
444 s->block_start = 0L;
445 s->insert = 0;
446 }
447 dictionary += dictLength - s->w_size; /* use the tail */
448 dictLength = s->w_size;
449 }
450
451 /* insert dictionary into window and hash */
452 avail = strm->avail_in;
453 next = strm->next_in;
454 strm->avail_in = dictLength;
455 strm->next_in = (z_const Bytef *)dictionary;
456 fill_window(s);
457 while (s->lookahead >= MIN_MATCH) {
458 str = s->strstart;
459 n = s->lookahead - (MIN_MATCH-1);
460 do {
461 UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
462#ifndef FASTEST
463 s->prev[str & s->w_mask] = s->head[s->ins_h];
464#endif
465 s->head[s->ins_h] = (Pos)str;
466 str++;
467 } while (--n);
468 s->strstart = str;
469 s->lookahead = MIN_MATCH-1;
470 fill_window(s);
471 }
472 s->strstart += s->lookahead;
473 s->block_start = (long)s->strstart;
474 s->insert = s->lookahead;
475 s->lookahead = 0;
476 s->match_length = s->prev_length = MIN_MATCH-1;
477 s->match_available = 0;
478 strm->next_in = next;
479 strm->avail_in = avail;
480 s->wrap = wrap;
481 return Z_OK;
482}
483
484/* ========================================================================= */
485int ZEXPORT deflateGetDictionary(strm, dictionary, dictLength)
487 Bytef *dictionary;
488 uInt *dictLength;
489{
490 deflate_state *s;
491 uInt len;
492
494 return Z_STREAM_ERROR;
495 s = strm->state;
496 len = s->strstart + s->lookahead;
497 if (len > s->w_size)
498 len = s->w_size;
499 if (dictionary != Z_NULL && len)
500 zmemcpy(dictionary, s->window + s->strstart + s->lookahead - len, len);
501 if (dictLength != Z_NULL)
502 *dictLength = len;
503 return Z_OK;
504}
505
506/* ========================================================================= */
509{
510 deflate_state *s;
511
512 if (deflateStateCheck(strm)) {
513 return Z_STREAM_ERROR;
514 }
515
516 strm->total_in = strm->total_out = 0;
517 strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
518 strm->data_type = Z_UNKNOWN;
519
520 s = (deflate_state *)strm->state;
521 s->pending = 0;
522 s->pending_out = s->pending_buf;
523
524 if (s->wrap < 0) {
525 s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
526 }
527 s->status =
528#ifdef GZIP
529 s->wrap == 2 ? GZIP_STATE :
530#endif
532 strm->adler =
533#ifdef GZIP
534 s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
535#endif
536 adler32(0L, Z_NULL, 0);
537 s->last_flush = -2;
538
539 _tr_init(s);
540
541 return Z_OK;
542}
543
544/* ========================================================================= */
545int ZEXPORT deflateReset(strm)
547{
548 int ret;
549
550 ret = deflateResetKeep(strm);
551 if (ret == Z_OK)
552 lm_init(strm->state);
553 return ret;
554}
555
556/* ========================================================================= */
560{
561 if (deflateStateCheck(strm) || strm->state->wrap != 2)
562 return Z_STREAM_ERROR;
563 strm->state->gzhead = head;
564 return Z_OK;
565}
566
567/* ========================================================================= */
568int ZEXPORT deflatePending(strm, pending, bits)
569 unsigned *pending;
570 int *bits;
572{
574 if (pending != Z_NULL)
575 *pending = strm->state->pending;
576 if (bits != Z_NULL)
577 *bits = strm->state->bi_valid;
578 return Z_OK;
579}
580
581/* ========================================================================= */
582int ZEXPORT deflatePrime(strm, bits, value)
584 int bits;
585 int value;
586{
587 deflate_state *s;
588 int put;
589
591 s = strm->state;
592 if (bits < 0 || bits > 16 ||
593 s->sym_buf < s->pending_out + ((Buf_size + 7) >> 3))
594 return Z_BUF_ERROR;
595 do {
596 put = Buf_size - s->bi_valid;
597 if (put > bits)
598 put = bits;
599 s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);
600 s->bi_valid += put;
602 value >>= put;
603 bits -= put;
604 } while (bits);
605 return Z_OK;
606}
607
608/* ========================================================================= */
611 int level;
612 int strategy;
613{
614 deflate_state *s;
615 compress_func func;
616
618 s = strm->state;
619
620#ifdef FASTEST
621 if (level != 0) level = 1;
622#else
624#endif
626 return Z_STREAM_ERROR;
627 }
628 func = configuration_table[s->level].func;
629
630 if ((strategy != s->strategy || func != configuration_table[level].func) &&
631 s->last_flush != -2) {
632 /* Flush the last buffer: */
633 int err = deflate(strm, Z_BLOCK);
634 if (err == Z_STREAM_ERROR)
635 return err;
636 if (strm->avail_in || (s->strstart - s->block_start) + s->lookahead)
637 return Z_BUF_ERROR;
638 }
639 if (s->level != level) {
640 if (s->level == 0 && s->matches != 0) {
641 if (s->matches == 1)
642 slide_hash(s);
643 else
644 CLEAR_HASH(s);
645 s->matches = 0;
646 }
647 s->level = level;
648 s->max_lazy_match = configuration_table[level].max_lazy;
649 s->good_match = configuration_table[level].good_length;
650 s->nice_match = configuration_table[level].nice_length;
651 s->max_chain_length = configuration_table[level].max_chain;
652 }
653 s->strategy = strategy;
654 return Z_OK;
655}
656
657/* ========================================================================= */
658int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
660 int good_length;
661 int max_lazy;
662 int nice_length;
663 int max_chain;
664{
665 deflate_state *s;
666
668 s = strm->state;
669 s->good_match = (uInt)good_length;
670 s->max_lazy_match = (uInt)max_lazy;
671 s->nice_match = nice_length;
672 s->max_chain_length = (uInt)max_chain;
673 return Z_OK;
674}
675
676/* =========================================================================
677 * For the default windowBits of 15 and memLevel of 8, this function returns a
678 * close to exact, as well as small, upper bound on the compressed size. This
679 * is an expansion of ~0.03%, plus a small constant.
680 *
681 * For any setting other than those defaults for windowBits and memLevel, one
682 * of two worst case bounds is returned. This is at most an expansion of ~4% or
683 * ~13%, plus a small constant.
684 *
685 * Both the 0.03% and 4% derive from the overhead of stored blocks. The first
686 * one is for stored blocks of 16383 bytes (memLevel == 8), whereas the second
687 * is for stored blocks of 127 bytes (the worst case memLevel == 1). The
688 * expansion results from five bytes of header for each stored block.
689 *
690 * The larger expansion of 13% results from a window size less than or equal to
691 * the symbols buffer size (windowBits <= memLevel + 7). In that case some of
692 * the data being compressed may have slid out of the sliding window, impeding
693 * a stored block from being emitted. Then the only choice is a fixed or
694 * dynamic block, where a fixed block limits the maximum expansion to 9 bits
695 * per 8-bit byte, plus 10 bits for every block. The smallest block size for
696 * which this can occur is 255 (memLevel == 2).
697 *
698 * Shifts are used to approximate divisions, for speed.
699 */
700uLong ZEXPORT deflateBound(strm, sourceLen)
702 uLong sourceLen;
703{
704 deflate_state *s;
705 uLong fixedlen, storelen, wraplen;
706
707 /* upper bound for fixed blocks with 9-bit literals and length 255
708 (memLevel == 2, which is the lowest that may not use stored blocks) --
709 ~13% overhead plus a small constant */
710 fixedlen = sourceLen + (sourceLen >> 3) + (sourceLen >> 8) +
711 (sourceLen >> 9) + 4;
712
713 /* upper bound for stored blocks with length 127 (memLevel == 1) --
714 ~4% overhead plus a small constant */
715 storelen = sourceLen + (sourceLen >> 5) + (sourceLen >> 7) +
716 (sourceLen >> 11) + 7;
717
718 /* if can't get parameters, return larger bound plus a zlib wrapper */
720 return (fixedlen > storelen ? fixedlen : storelen) + 6;
721
722 /* compute wrapper length */
723 s = strm->state;
724 switch (s->wrap) {
725 case 0: /* raw deflate */
726 wraplen = 0;
727 break;
728 case 1: /* zlib wrapper */
729 wraplen = 6 + (s->strstart ? 4 : 0);
730 break;
731#ifdef GZIP
732 case 2: /* gzip wrapper */
733 wraplen = 18;
734 if (s->gzhead != Z_NULL) { /* user-supplied gzip header */
735 Bytef *str;
736 if (s->gzhead->extra != Z_NULL)
737 wraplen += 2 + s->gzhead->extra_len;
738 str = s->gzhead->name;
739 if (str != Z_NULL)
740 do {
741 wraplen++;
742 } while (*str++);
743 str = s->gzhead->comment;
744 if (str != Z_NULL)
745 do {
746 wraplen++;
747 } while (*str++);
748 if (s->gzhead->hcrc)
749 wraplen += 2;
750 }
751 break;
752#endif
753 default: /* for compiler happiness */
754 wraplen = 6;
755 }
756
757 /* if not default parameters, return one of the conservative bounds */
758 if (s->w_bits != 15 || s->hash_bits != 8 + 7)
759 return (s->w_bits <= s->hash_bits ? fixedlen : storelen) + wraplen;
760
761 /* default settings: return tight bound for that case -- ~0.03% overhead
762 plus a small constant */
763 return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
764 (sourceLen >> 25) + 13 - 6 + wraplen;
765}
766
767/* =========================================================================
768 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
769 * IN assertion: the stream state is correct and there is enough room in
770 * pending_buf.
771 */
773 deflate_state *s;
774 uInt b;
775{
776 put_byte(s, (Byte)(b >> 8));
777 put_byte(s, (Byte)(b & 0xff));
778}
779
780/* =========================================================================
781 * Flush as much pending output as possible. All deflate() output, except for
782 * some deflate_stored() output, goes through this function so some
783 * applications may wish to modify it to avoid allocating a large
784 * strm->next_out buffer and copying into it. (See also read_buf()).
785 */
788{
789 unsigned len;
790 deflate_state *s = strm->state;
791
793 len = s->pending;
794 if (len > strm->avail_out) len = strm->avail_out;
795 if (len == 0) return;
796
797 zmemcpy(strm->next_out, s->pending_out, len);
798 strm->next_out += len;
799 s->pending_out += len;
800 strm->total_out += len;
801 strm->avail_out -= len;
802 s->pending -= len;
803 if (s->pending == 0) {
804 s->pending_out = s->pending_buf;
805 }
806}
807
808/* ===========================================================================
809 * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1].
810 */
811#define HCRC_UPDATE(beg) \
812 do { \
813 if (s->gzhead->hcrc && s->pending > (beg)) \
814 strm->adler = crc32(strm->adler, s->pending_buf + (beg), \
815 s->pending - (beg)); \
816 } while (0)
817
818/* ========================================================================= */
819int ZEXPORT deflate(strm, flush)
821 int flush;
822{
823 int old_flush; /* value of flush param for previous deflate call */
824 deflate_state *s;
825
826 if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) {
827 return Z_STREAM_ERROR;
828 }
829 s = strm->state;
830
831 if (strm->next_out == Z_NULL ||
832 (strm->avail_in != 0 && strm->next_in == Z_NULL) ||
833 (s->status == FINISH_STATE && flush != Z_FINISH)) {
835 }
836 if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
837
838 old_flush = s->last_flush;
839 s->last_flush = flush;
840
841 /* Flush as much pending output as possible */
842 if (s->pending != 0) {
844 if (strm->avail_out == 0) {
845 /* Since avail_out is 0, deflate will be called again with
846 * more output space, but possibly with both pending and
847 * avail_in equal to zero. There won't be anything to do,
848 * but this is not an error situation so make sure we
849 * return OK instead of BUF_ERROR at next call of deflate:
850 */
851 s->last_flush = -1;
852 return Z_OK;
853 }
854
855 /* Make sure there is something to do and avoid duplicate consecutive
856 * flushes. For repeated and useless calls with Z_FINISH, we keep
857 * returning Z_STREAM_END instead of Z_BUF_ERROR.
858 */
859 } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&
860 flush != Z_FINISH) {
862 }
863
864 /* User must not provide more input after the first FINISH: */
865 if (s->status == FINISH_STATE && strm->avail_in != 0) {
867 }
868
869 /* Write the header */
870 if (s->status == INIT_STATE && s->wrap == 0)
871 s->status = BUSY_STATE;
872 if (s->status == INIT_STATE) {
873 /* zlib header */
874 uInt header = (Z_DEFLATED + ((s->w_bits - 8) << 4)) << 8;
875 uInt level_flags;
876
877 if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
878 level_flags = 0;
879 else if (s->level < 6)
880 level_flags = 1;
881 else if (s->level == 6)
882 level_flags = 2;
883 else
884 level_flags = 3;
885 header |= (level_flags << 6);
886 if (s->strstart != 0) header |= PRESET_DICT;
887 header += 31 - (header % 31);
888
889 putShortMSB(s, header);
890
891 /* Save the adler32 of the preset dictionary: */
892 if (s->strstart != 0) {
893 putShortMSB(s, (uInt)(strm->adler >> 16));
894 putShortMSB(s, (uInt)(strm->adler & 0xffff));
895 }
896 strm->adler = adler32(0L, Z_NULL, 0);
897 s->status = BUSY_STATE;
898
899 /* Compression must start with an empty pending buffer */
901 if (s->pending != 0) {
902 s->last_flush = -1;
903 return Z_OK;
904 }
905 }
906#ifdef GZIP
907 if (s->status == GZIP_STATE) {
908 /* gzip header */
909 strm->adler = crc32(0L, Z_NULL, 0);
910 put_byte(s, 31);
911 put_byte(s, 139);
912 put_byte(s, 8);
913 if (s->gzhead == Z_NULL) {
914 put_byte(s, 0);
915 put_byte(s, 0);
916 put_byte(s, 0);
917 put_byte(s, 0);
918 put_byte(s, 0);
919 put_byte(s, s->level == 9 ? 2 :
920 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
921 4 : 0));
922 put_byte(s, OS_CODE);
923 s->status = BUSY_STATE;
924
925 /* Compression must start with an empty pending buffer */
927 if (s->pending != 0) {
928 s->last_flush = -1;
929 return Z_OK;
930 }
931 }
932 else {
933 put_byte(s, (s->gzhead->text ? 1 : 0) +
934 (s->gzhead->hcrc ? 2 : 0) +
935 (s->gzhead->extra == Z_NULL ? 0 : 4) +
936 (s->gzhead->name == Z_NULL ? 0 : 8) +
937 (s->gzhead->comment == Z_NULL ? 0 : 16)
938 );
939 put_byte(s, (Byte)(s->gzhead->time & 0xff));
940 put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
941 put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
942 put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
943 put_byte(s, s->level == 9 ? 2 :
944 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
945 4 : 0));
946 put_byte(s, s->gzhead->os & 0xff);
947 if (s->gzhead->extra != Z_NULL) {
948 put_byte(s, s->gzhead->extra_len & 0xff);
949 put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
950 }
951 if (s->gzhead->hcrc)
952 strm->adler = crc32(strm->adler, s->pending_buf,
953 s->pending);
954 s->gzindex = 0;
955 s->status = EXTRA_STATE;
956 }
957 }
958 if (s->status == EXTRA_STATE) {
959 if (s->gzhead->extra != Z_NULL) {
960 ulg beg = s->pending; /* start of bytes to update crc */
961 uInt left = (s->gzhead->extra_len & 0xffff) - s->gzindex;
962 while (s->pending + left > s->pending_buf_size) {
963 uInt copy = s->pending_buf_size - s->pending;
964 zmemcpy(s->pending_buf + s->pending,
965 s->gzhead->extra + s->gzindex, copy);
966 s->pending = s->pending_buf_size;
967 HCRC_UPDATE(beg);
968 s->gzindex += copy;
970 if (s->pending != 0) {
971 s->last_flush = -1;
972 return Z_OK;
973 }
974 beg = 0;
975 left -= copy;
976 }
977 zmemcpy(s->pending_buf + s->pending,
978 s->gzhead->extra + s->gzindex, left);
979 s->pending += left;
980 HCRC_UPDATE(beg);
981 s->gzindex = 0;
982 }
983 s->status = NAME_STATE;
984 }
985 if (s->status == NAME_STATE) {
986 if (s->gzhead->name != Z_NULL) {
987 ulg beg = s->pending; /* start of bytes to update crc */
988 int val;
989 do {
990 if (s->pending == s->pending_buf_size) {
991 HCRC_UPDATE(beg);
993 if (s->pending != 0) {
994 s->last_flush = -1;
995 return Z_OK;
996 }
997 beg = 0;
998 }
999 val = s->gzhead->name[s->gzindex++];
1000 put_byte(s, val);
1001 } while (val != 0);
1002 HCRC_UPDATE(beg);
1003 s->gzindex = 0;
1004 }
1005 s->status = COMMENT_STATE;
1006 }
1007 if (s->status == COMMENT_STATE) {
1008 if (s->gzhead->comment != Z_NULL) {
1009 ulg beg = s->pending; /* start of bytes to update crc */
1010 int val;
1011 do {
1012 if (s->pending == s->pending_buf_size) {
1013 HCRC_UPDATE(beg);
1015 if (s->pending != 0) {
1016 s->last_flush = -1;
1017 return Z_OK;
1018 }
1019 beg = 0;
1020 }
1021 val = s->gzhead->comment[s->gzindex++];
1022 put_byte(s, val);
1023 } while (val != 0);
1024 HCRC_UPDATE(beg);
1025 }
1026 s->status = HCRC_STATE;
1027 }
1028 if (s->status == HCRC_STATE) {
1029 if (s->gzhead->hcrc) {
1030 if (s->pending + 2 > s->pending_buf_size) {
1032 if (s->pending != 0) {
1033 s->last_flush = -1;
1034 return Z_OK;
1035 }
1036 }
1037 put_byte(s, (Byte)(strm->adler & 0xff));
1038 put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
1039 strm->adler = crc32(0L, Z_NULL, 0);
1040 }
1041 s->status = BUSY_STATE;
1042
1043 /* Compression must start with an empty pending buffer */
1045 if (s->pending != 0) {
1046 s->last_flush = -1;
1047 return Z_OK;
1048 }
1049 }
1050#endif
1051
1052 /* Start a new block or continue the current one.
1053 */
1054 if (strm->avail_in != 0 || s->lookahead != 0 ||
1055 (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
1056 block_state bstate;
1057
1058 bstate = s->level == 0 ? deflate_stored(s, flush) :
1059 s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
1060 s->strategy == Z_RLE ? deflate_rle(s, flush) :
1061 (*(configuration_table[s->level].func))(s, flush);
1062
1063 if (bstate == finish_started || bstate == finish_done) {
1064 s->status = FINISH_STATE;
1065 }
1066 if (bstate == need_more || bstate == finish_started) {
1067 if (strm->avail_out == 0) {
1068 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
1069 }
1070 return Z_OK;
1071 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
1072 * of deflate should use the same flush parameter to make sure
1073 * that the flush is complete. So we don't have to output an
1074 * empty block here, this will be done at next call. This also
1075 * ensures that for a very small output buffer, we emit at most
1076 * one empty block.
1077 */
1078 }
1079 if (bstate == block_done) {
1080 if (flush == Z_PARTIAL_FLUSH) {
1081 _tr_align(s);
1082 } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
1083 _tr_stored_block(s, (char*)0, 0L, 0);
1084 /* For a full flush, this empty block will be recognized
1085 * as a special marker by inflate_sync().
1086 */
1087 if (flush == Z_FULL_FLUSH) {
1088 CLEAR_HASH(s); /* forget history */
1089 if (s->lookahead == 0) {
1090 s->strstart = 0;
1091 s->block_start = 0L;
1092 s->insert = 0;
1093 }
1094 }
1095 }
1097 if (strm->avail_out == 0) {
1098 s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
1099 return Z_OK;
1100 }
1101 }
1102 }
1103
1104 if (flush != Z_FINISH) return Z_OK;
1105 if (s->wrap <= 0) return Z_STREAM_END;
1106
1107 /* Write the trailer */
1108#ifdef GZIP
1109 if (s->wrap == 2) {
1110 put_byte(s, (Byte)(strm->adler & 0xff));
1111 put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
1112 put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
1113 put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
1114 put_byte(s, (Byte)(strm->total_in & 0xff));
1115 put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
1116 put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
1117 put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
1118 }
1119 else
1120#endif
1121 {
1122 putShortMSB(s, (uInt)(strm->adler >> 16));
1123 putShortMSB(s, (uInt)(strm->adler & 0xffff));
1124 }
1126 /* If avail_out is zero, the application will call deflate again
1127 * to flush the rest.
1128 */
1129 if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
1130 return s->pending != 0 ? Z_OK : Z_STREAM_END;
1131}
1132
1133/* ========================================================================= */
1134int ZEXPORT deflateEnd(strm)
1136{
1137 int status;
1138
1140
1141 status = strm->state->status;
1142
1143 /* Deallocate in reverse order of allocations: */
1144 TRY_FREE(strm, strm->state->pending_buf);
1145 TRY_FREE(strm, strm->state->head);
1146 TRY_FREE(strm, strm->state->prev);
1147 TRY_FREE(strm, strm->state->window);
1148
1149 ZFREE(strm, strm->state);
1150 strm->state = Z_NULL;
1151
1152 return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
1153}
1154
1155/* =========================================================================
1156 * Copy the source state to the destination state.
1157 * To simplify the source, this is not supported for 16-bit MSDOS (which
1158 * doesn't have enough memory anyway to duplicate compression states).
1159 */
1160int ZEXPORT deflateCopy(dest, source)
1161 z_streamp dest;
1162 z_streamp source;
1163{
1164#ifdef MAXSEG_64K
1165 return Z_STREAM_ERROR;
1166#else
1167 deflate_state *ds;
1168 deflate_state *ss;
1169
1170
1171 if (deflateStateCheck(source) || dest == Z_NULL) {
1172 return Z_STREAM_ERROR;
1173 }
1174
1175 ss = source->state;
1176
1177 zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
1178
1179 ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
1180 if (ds == Z_NULL) return Z_MEM_ERROR;
1181 dest->state = (struct internal_state FAR *) ds;
1182 zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));
1183 ds->strm = dest;
1184
1185 ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
1186 ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
1187 ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
1188 ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, 4);
1189
1190 if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
1191 ds->pending_buf == Z_NULL) {
1192 deflateEnd (dest);
1193 return Z_MEM_ERROR;
1194 }
1195 /* following zmemcpy do not work for 16-bit MSDOS */
1196 zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
1197 zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));
1198 zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));
1199 zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
1200
1201 ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
1202 ds->sym_buf = ds->pending_buf + ds->lit_bufsize;
1203
1204 ds->l_desc.dyn_tree = ds->dyn_ltree;
1205 ds->d_desc.dyn_tree = ds->dyn_dtree;
1206 ds->bl_desc.dyn_tree = ds->bl_tree;
1207
1208 return Z_OK;
1209#endif /* MAXSEG_64K */
1210}
1211
1212/* ===========================================================================
1213 * Read a new buffer from the current input stream, update the adler32
1214 * and total number of bytes read. All deflate() input goes through
1215 * this function so some applications may wish to modify it to avoid
1216 * allocating a large strm->next_in buffer and copying from it.
1217 * (See also flush_pending()).
1218 */
1219local unsigned read_buf(strm, buf, size)
1221 Bytef *buf;
1222 unsigned size;
1223{
1224 unsigned len = strm->avail_in;
1225
1226 if (len > size) len = size;
1227 if (len == 0) return 0;
1228
1229 strm->avail_in -= len;
1230
1231 zmemcpy(buf, strm->next_in, len);
1232 if (strm->state->wrap == 1) {
1233 strm->adler = adler32(strm->adler, buf, len);
1234 }
1235#ifdef GZIP
1236 else if (strm->state->wrap == 2) {
1237 strm->adler = crc32(strm->adler, buf, len);
1238 }
1239#endif
1240 strm->next_in += len;
1241 strm->total_in += len;
1242
1243 return len;
1244}
1245
1246/* ===========================================================================
1247 * Initialize the "longest match" routines for a new zlib stream
1248 */
1250 deflate_state *s;
1251{
1252 s->window_size = (ulg)2L*s->w_size;
1253
1254 CLEAR_HASH(s);
1255
1256 /* Set the default configuration parameters:
1257 */
1258 s->max_lazy_match = configuration_table[s->level].max_lazy;
1259 s->good_match = configuration_table[s->level].good_length;
1260 s->nice_match = configuration_table[s->level].nice_length;
1261 s->max_chain_length = configuration_table[s->level].max_chain;
1262
1263 s->strstart = 0;
1264 s->block_start = 0L;
1265 s->lookahead = 0;
1266 s->insert = 0;
1267 s->match_length = s->prev_length = MIN_MATCH-1;
1268 s->match_available = 0;
1269 s->ins_h = 0;
1270}
1271
1272#ifndef FASTEST
1273/* ===========================================================================
1274 * Set match_start to the longest match starting at the given string and
1275 * return its length. Matches shorter or equal to prev_length are discarded,
1276 * in which case the result is equal to prev_length and match_start is
1277 * garbage.
1278 * IN assertions: cur_match is the head of the hash chain for the current
1279 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1280 * OUT assertion: the match length is not greater than s->lookahead.
1281 */
1282local uInt longest_match(s, cur_match)
1283 deflate_state *s;
1284 IPos cur_match; /* current match */
1285{
1286 unsigned chain_length = s->max_chain_length;/* max hash chain length */
1287 register Bytef *scan = s->window + s->strstart; /* current string */
1288 register Bytef *match; /* matched string */
1289 register int len; /* length of current match */
1290 int best_len = (int)s->prev_length; /* best match length so far */
1291 int nice_match = s->nice_match; /* stop if match long enough */
1292 IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
1293 s->strstart - (IPos)MAX_DIST(s) : NIL;
1294 /* Stop when cur_match becomes <= limit. To simplify the code,
1295 * we prevent matches with the string of window index 0.
1296 */
1297 Posf *prev = s->prev;
1298 uInt wmask = s->w_mask;
1299
1300#ifdef UNALIGNED_OK
1301 /* Compare two bytes at a time. Note: this is not always beneficial.
1302 * Try with and without -DUNALIGNED_OK to check.
1303 */
1304 register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
1305 register ush scan_start = *(ushf*)scan;
1306 register ush scan_end = *(ushf*)(scan + best_len - 1);
1307#else
1308 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1309 register Byte scan_end1 = scan[best_len - 1];
1310 register Byte scan_end = scan[best_len];
1311#endif
1312
1313 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1314 * It is easy to get rid of this optimization if necessary.
1315 */
1316 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1317
1318 /* Do not waste too much time if we already have a good match: */
1319 if (s->prev_length >= s->good_match) {
1320 chain_length >>= 2;
1321 }
1322 /* Do not look for matches beyond the end of the input. This is necessary
1323 * to make deflate deterministic.
1324 */
1325 if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead;
1326
1327 Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1328 "need lookahead");
1329
1330 do {
1331 Assert(cur_match < s->strstart, "no future");
1332 match = s->window + cur_match;
1333
1334 /* Skip to next match if the match length cannot increase
1335 * or if the match length is less than 2. Note that the checks below
1336 * for insufficient lookahead only occur occasionally for performance
1337 * reasons. Therefore uninitialized memory will be accessed, and
1338 * conditional jumps will be made that depend on those values.
1339 * However the length of the match is limited to the lookahead, so
1340 * the output of deflate is not affected by the uninitialized values.
1341 */
1342#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
1343 /* This code assumes sizeof(unsigned short) == 2. Do not use
1344 * UNALIGNED_OK if your compiler uses a different size.
1345 */
1346 if (*(ushf*)(match + best_len - 1) != scan_end ||
1347 *(ushf*)match != scan_start) continue;
1348
1349 /* It is not necessary to compare scan[2] and match[2] since they are
1350 * always equal when the other bytes match, given that the hash keys
1351 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
1352 * strstart + 3, + 5, up to strstart + 257. We check for insufficient
1353 * lookahead only every 4th comparison; the 128th check will be made
1354 * at strstart + 257. If MAX_MATCH-2 is not a multiple of 8, it is
1355 * necessary to put more guard bytes at the end of the window, or
1356 * to check more often for insufficient lookahead.
1357 */
1358 Assert(scan[2] == match[2], "scan[2]?");
1359 scan++, match++;
1360 do {
1361 } while (*(ushf*)(scan += 2) == *(ushf*)(match += 2) &&
1362 *(ushf*)(scan += 2) == *(ushf*)(match += 2) &&
1363 *(ushf*)(scan += 2) == *(ushf*)(match += 2) &&
1364 *(ushf*)(scan += 2) == *(ushf*)(match += 2) &&
1365 scan < strend);
1366 /* The funny "do {}" generates better code on most compilers */
1367
1368 /* Here, scan <= window + strstart + 257 */
1369 Assert(scan <= s->window + (unsigned)(s->window_size - 1),
1370 "wild scan");
1371 if (*scan == *match) scan++;
1372
1373 len = (MAX_MATCH - 1) - (int)(strend - scan);
1374 scan = strend - (MAX_MATCH-1);
1375
1376#else /* UNALIGNED_OK */
1377
1378 if (match[best_len] != scan_end ||
1379 match[best_len - 1] != scan_end1 ||
1380 *match != *scan ||
1381 *++match != scan[1]) continue;
1382
1383 /* The check at best_len - 1 can be removed because it will be made
1384 * again later. (This heuristic is not always a win.)
1385 * It is not necessary to compare scan[2] and match[2] since they
1386 * are always equal when the other bytes match, given that
1387 * the hash keys are equal and that HASH_BITS >= 8.
1388 */
1389 scan += 2, match++;
1390 Assert(*scan == *match, "match[2]?");
1391
1392 /* We check for insufficient lookahead only every 8th comparison;
1393 * the 256th check will be made at strstart + 258.
1394 */
1395 do {
1396 } while (*++scan == *++match && *++scan == *++match &&
1397 *++scan == *++match && *++scan == *++match &&
1398 *++scan == *++match && *++scan == *++match &&
1399 *++scan == *++match && *++scan == *++match &&
1400 scan < strend);
1401
1402 Assert(scan <= s->window + (unsigned)(s->window_size - 1),
1403 "wild scan");
1404
1405 len = MAX_MATCH - (int)(strend - scan);
1406 scan = strend - MAX_MATCH;
1407
1408#endif /* UNALIGNED_OK */
1409
1410 if (len > best_len) {
1411 s->match_start = cur_match;
1412 best_len = len;
1413 if (len >= nice_match) break;
1414#ifdef UNALIGNED_OK
1415 scan_end = *(ushf*)(scan + best_len - 1);
1416#else
1417 scan_end1 = scan[best_len - 1];
1418 scan_end = scan[best_len];
1419#endif
1420 }
1421 } while ((cur_match = prev[cur_match & wmask]) > limit
1422 && --chain_length != 0);
1423
1424 if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
1425 return s->lookahead;
1426}
1427
1428#else /* FASTEST */
1429
1430/* ---------------------------------------------------------------------------
1431 * Optimized version for FASTEST only
1432 */
1433local uInt longest_match(s, cur_match)
1434 deflate_state *s;
1435 IPos cur_match; /* current match */
1436{
1437 register Bytef *scan = s->window + s->strstart; /* current string */
1438 register Bytef *match; /* matched string */
1439 register int len; /* length of current match */
1440 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1441
1442 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1443 * It is easy to get rid of this optimization if necessary.
1444 */
1445 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1446
1447 Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1448 "need lookahead");
1449
1450 Assert(cur_match < s->strstart, "no future");
1451
1452 match = s->window + cur_match;
1453
1454 /* Return failure if the match length is less than 2:
1455 */
1456 if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
1457
1458 /* The check at best_len - 1 can be removed because it will be made
1459 * again later. (This heuristic is not always a win.)
1460 * It is not necessary to compare scan[2] and match[2] since they
1461 * are always equal when the other bytes match, given that
1462 * the hash keys are equal and that HASH_BITS >= 8.
1463 */
1464 scan += 2, match += 2;
1465 Assert(*scan == *match, "match[2]?");
1466
1467 /* We check for insufficient lookahead only every 8th comparison;
1468 * the 256th check will be made at strstart + 258.
1469 */
1470 do {
1471 } while (*++scan == *++match && *++scan == *++match &&
1472 *++scan == *++match && *++scan == *++match &&
1473 *++scan == *++match && *++scan == *++match &&
1474 *++scan == *++match && *++scan == *++match &&
1475 scan < strend);
1476
1477 Assert(scan <= s->window + (unsigned)(s->window_size - 1), "wild scan");
1478
1479 len = MAX_MATCH - (int)(strend - scan);
1480
1481 if (len < MIN_MATCH) return MIN_MATCH - 1;
1482
1483 s->match_start = cur_match;
1484 return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
1485}
1486
1487#endif /* FASTEST */
1488
1489#ifdef ZLIB_DEBUG
1490
1491#define EQUAL 0
1492/* result of memcmp for equal strings */
1493
1494/* ===========================================================================
1495 * Check that the match at match_start is indeed a match.
1496 */
1497local void check_match(s, start, match, length)
1498 deflate_state *s;
1499 IPos start, match;
1500 int length;
1501{
1502 /* check that the match is indeed a match */
1503 if (zmemcmp(s->window + match,
1504 s->window + start, length) != EQUAL) {
1505 fprintf(stderr, " start %u, match %u, length %d\n",
1506 start, match, length);
1507 do {
1508 fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
1509 } while (--length != 0);
1510 z_error("invalid match");
1511 }
1512 if (z_verbose > 1) {
1513 fprintf(stderr,"\\[%d,%d]", start - match, length);
1514 do { putc(s->window[start++], stderr); } while (--length != 0);
1515 }
1516}
1517#else
1518# define check_match(s, start, match, length)
1519#endif /* ZLIB_DEBUG */
1520
1521/* ===========================================================================
1522 * Fill the window when the lookahead becomes insufficient.
1523 * Updates strstart and lookahead.
1524 *
1525 * IN assertion: lookahead < MIN_LOOKAHEAD
1526 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1527 * At least one byte has been read, or avail_in == 0; reads are
1528 * performed for at least two bytes (required for the zip translate_eol
1529 * option -- not supported here).
1530 */
1532 deflate_state *s;
1533{
1534 unsigned n;
1535 unsigned more; /* Amount of free space at the end of the window. */
1536 uInt wsize = s->w_size;
1537
1538 Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
1539
1540 do {
1541 more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
1542
1543 /* Deal with !@#$% 64K limit: */
1544 if (sizeof(int) <= 2) {
1545 if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1546 more = wsize;
1547
1548 } else if (more == (unsigned)(-1)) {
1549 /* Very unlikely, but possible on 16 bit machine if
1550 * strstart == 0 && lookahead == 1 (input done a byte at time)
1551 */
1552 more--;
1553 }
1554 }
1555
1556 /* If the window is almost full and there is insufficient lookahead,
1557 * move the upper half to the lower one to make room in the upper half.
1558 */
1559 if (s->strstart >= wsize + MAX_DIST(s)) {
1560
1561 zmemcpy(s->window, s->window + wsize, (unsigned)wsize - more);
1562 s->match_start -= wsize;
1563 s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
1564 s->block_start -= (long) wsize;
1565 if (s->insert > s->strstart)
1566 s->insert = s->strstart;
1567 slide_hash(s);
1568 more += wsize;
1569 }
1570 if (s->strm->avail_in == 0) break;
1571
1572 /* If there was no sliding:
1573 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1574 * more == window_size - lookahead - strstart
1575 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1576 * => more >= window_size - 2*WSIZE + 2
1577 * In the BIG_MEM or MMAP case (not yet supported),
1578 * window_size == input_size + MIN_LOOKAHEAD &&
1579 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1580 * Otherwise, window_size == 2*WSIZE so more >= 2.
1581 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1582 */
1583 Assert(more >= 2, "more < 2");
1584
1585 n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1586 s->lookahead += n;
1587
1588 /* Initialize the hash value now that we have some input: */
1589 if (s->lookahead + s->insert >= MIN_MATCH) {
1590 uInt str = s->strstart - s->insert;
1591 s->ins_h = s->window[str];
1592 UPDATE_HASH(s, s->ins_h, s->window[str + 1]);
1593#if MIN_MATCH != 3
1594 Call UPDATE_HASH() MIN_MATCH-3 more times
1595#endif
1596 while (s->insert) {
1597 UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
1598#ifndef FASTEST
1599 s->prev[str & s->w_mask] = s->head[s->ins_h];
1600#endif
1601 s->head[s->ins_h] = (Pos)str;
1602 str++;
1603 s->insert--;
1604 if (s->lookahead + s->insert < MIN_MATCH)
1605 break;
1606 }
1607 }
1608 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1609 * but this is not important since only literal bytes will be emitted.
1610 */
1611
1612 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1613
1614 /* If the WIN_INIT bytes after the end of the current data have never been
1615 * written, then zero those bytes in order to avoid memory check reports of
1616 * the use of uninitialized (or uninitialised as Julian writes) bytes by
1617 * the longest match routines. Update the high water mark for the next
1618 * time through here. WIN_INIT is set to MAX_MATCH since the longest match
1619 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
1620 */
1621 if (s->high_water < s->window_size) {
1622 ulg curr = s->strstart + (ulg)(s->lookahead);
1623 ulg init;
1624
1625 if (s->high_water < curr) {
1626 /* Previous high water mark below current data -- zero WIN_INIT
1627 * bytes or up to end of window, whichever is less.
1628 */
1629 init = s->window_size - curr;
1630 if (init > WIN_INIT)
1631 init = WIN_INIT;
1632 zmemzero(s->window + curr, (unsigned)init);
1633 s->high_water = curr + init;
1634 }
1635 else if (s->high_water < (ulg)curr + WIN_INIT) {
1636 /* High water mark at or above current data, but below current data
1637 * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
1638 * to end of window, whichever is less.
1639 */
1640 init = (ulg)curr + WIN_INIT - s->high_water;
1641 if (init > s->window_size - s->high_water)
1642 init = s->window_size - s->high_water;
1643 zmemzero(s->window + s->high_water, (unsigned)init);
1644 s->high_water += init;
1645 }
1646 }
1647
1648 Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1649 "not enough room for search");
1650}
1651
1652/* ===========================================================================
1653 * Flush the current block, with given end-of-file flag.
1654 * IN assertion: strstart is set to the end of the current match.
1655 */
1656#define FLUSH_BLOCK_ONLY(s, last) { \
1657 _tr_flush_block(s, (s->block_start >= 0L ? \
1658 (charf *)&s->window[(unsigned)s->block_start] : \
1659 (charf *)Z_NULL), \
1660 (ulg)((long)s->strstart - s->block_start), \
1661 (last)); \
1662 s->block_start = s->strstart; \
1663 flush_pending(s->strm); \
1664 Tracev((stderr,"[FLUSH]")); \
1665}
1666
1667/* Same but force premature exit if necessary. */
1668#define FLUSH_BLOCK(s, last) { \
1669 FLUSH_BLOCK_ONLY(s, last); \
1670 if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
1671}
1672
1673/* Maximum stored block length in deflate format (not including header). */
1674#define MAX_STORED 65535
1675
1676/* Minimum of a and b. */
1677#define MIN(a, b) ((a) > (b) ? (b) : (a))
1678
1679/* ===========================================================================
1680 * Copy without compression as much as possible from the input stream, return
1681 * the current block state.
1682 *
1683 * In case deflateParams() is used to later switch to a non-zero compression
1684 * level, s->matches (otherwise unused when storing) keeps track of the number
1685 * of hash table slides to perform. If s->matches is 1, then one hash table
1686 * slide will be done when switching. If s->matches is 2, the maximum value
1687 * allowed here, then the hash table will be cleared, since two or more slides
1688 * is the same as a clear.
1689 *
1690 * deflate_stored() is written to minimize the number of times an input byte is
1691 * copied. It is most efficient with large input and output buffers, which
1692 * maximizes the opportunities to have a single copy from next_in to next_out.
1693 */
1695 deflate_state *s;
1696 int flush;
1697{
1698 /* Smallest worthy block size when not flushing or finishing. By default
1699 * this is 32K. This can be as small as 507 bytes for memLevel == 1. For
1700 * large input and output buffers, the stored block size will be larger.
1701 */
1702 unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size);
1703
1704 /* Copy as many min_block or larger stored blocks directly to next_out as
1705 * possible. If flushing, copy the remaining available input to next_out as
1706 * stored blocks, if there is enough space.
1707 */
1708 unsigned len, left, have, last = 0;
1709 unsigned used = s->strm->avail_in;
1710 do {
1711 /* Set len to the maximum size block that we can copy directly with the
1712 * available input data and output space. Set left to how much of that
1713 * would be copied from what's left in the window.
1714 */
1715 len = MAX_STORED; /* maximum deflate stored block length */
1716 have = (s->bi_valid + 42) >> 3; /* number of header bytes */
1717 if (s->strm->avail_out < have) /* need room for header */
1718 break;
1719 /* maximum stored block length that will fit in avail_out: */
1720 have = s->strm->avail_out - have;
1721 left = s->strstart - s->block_start; /* bytes left in window */
1722 if (len > (ulg)left + s->strm->avail_in)
1723 len = left + s->strm->avail_in; /* limit len to the input */
1724 if (len > have)
1725 len = have; /* limit len to the output */
1726
1727 /* If the stored block would be less than min_block in length, or if
1728 * unable to copy all of the available input when flushing, then try
1729 * copying to the window and the pending buffer instead. Also don't
1730 * write an empty block when flushing -- deflate() does that.
1731 */
1732 if (len < min_block && ((len == 0 && flush != Z_FINISH) ||
1733 flush == Z_NO_FLUSH ||
1734 len != left + s->strm->avail_in))
1735 break;
1736
1737 /* Make a dummy stored block in pending to get the header bytes,
1738 * including any pending bits. This also updates the debugging counts.
1739 */
1740 last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0;
1741 _tr_stored_block(s, (char *)0, 0L, last);
1742
1743 /* Replace the lengths in the dummy stored block with len. */
1744 s->pending_buf[s->pending - 4] = len;
1745 s->pending_buf[s->pending - 3] = len >> 8;
1746 s->pending_buf[s->pending - 2] = ~len;
1747 s->pending_buf[s->pending - 1] = ~len >> 8;
1748
1749 /* Write the stored block header bytes. */
1750 flush_pending(s->strm);
1751
1752#ifdef ZLIB_DEBUG
1753 /* Update debugging counts for the data about to be copied. */
1754 s->compressed_len += len << 3;
1755 s->bits_sent += len << 3;
1756#endif
1757
1758 /* Copy uncompressed bytes from the window to next_out. */
1759 if (left) {
1760 if (left > len)
1761 left = len;
1762 zmemcpy(s->strm->next_out, s->window + s->block_start, left);
1763 s->strm->next_out += left;
1764 s->strm->avail_out -= left;
1765 s->strm->total_out += left;
1766 s->block_start += left;
1767 len -= left;
1768 }
1769
1770 /* Copy uncompressed bytes directly from next_in to next_out, updating
1771 * the check value.
1772 */
1773 if (len) {
1774 read_buf(s->strm, s->strm->next_out, len);
1775 s->strm->next_out += len;
1776 s->strm->avail_out -= len;
1777 s->strm->total_out += len;
1778 }
1779 } while (last == 0);
1780
1781 /* Update the sliding window with the last s->w_size bytes of the copied
1782 * data, or append all of the copied data to the existing window if less
1783 * than s->w_size bytes were copied. Also update the number of bytes to
1784 * insert in the hash tables, in the event that deflateParams() switches to
1785 * a non-zero compression level.
1786 */
1787 used -= s->strm->avail_in; /* number of input bytes directly copied */
1788 if (used) {
1789 /* If any input was used, then no unused input remains in the window,
1790 * therefore s->block_start == s->strstart.
1791 */
1792 if (used >= s->w_size) { /* supplant the previous history */
1793 s->matches = 2; /* clear hash */
1794 zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);
1795 s->strstart = s->w_size;
1796 s->insert = s->strstart;
1797 }
1798 else {
1799 if (s->window_size - s->strstart <= used) {
1800 /* Slide the window down. */
1801 s->strstart -= s->w_size;
1802 zmemcpy(s->window, s->window + s->w_size, s->strstart);
1803 if (s->matches < 2)
1804 s->matches++; /* add a pending slide_hash() */
1805 if (s->insert > s->strstart)
1806 s->insert = s->strstart;
1807 }
1808 zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);
1809 s->strstart += used;
1810 s->insert += MIN(used, s->w_size - s->insert);
1811 }
1812 s->block_start = s->strstart;
1813 }
1814 if (s->high_water < s->strstart)
1815 s->high_water = s->strstart;
1816
1817 /* If the last block was written to next_out, then done. */
1818 if (last)
1819 return finish_done;
1820
1821 /* If flushing and all input has been consumed, then done. */
1822 if (flush != Z_NO_FLUSH && flush != Z_FINISH &&
1823 s->strm->avail_in == 0 && (long)s->strstart == s->block_start)
1824 return block_done;
1825
1826 /* Fill the window with any remaining input. */
1827 have = s->window_size - s->strstart;
1828 if (s->strm->avail_in > have && s->block_start >= (long)s->w_size) {
1829 /* Slide the window down. */
1830 s->block_start -= s->w_size;
1831 s->strstart -= s->w_size;
1832 zmemcpy(s->window, s->window + s->w_size, s->strstart);
1833 if (s->matches < 2)
1834 s->matches++; /* add a pending slide_hash() */
1835 have += s->w_size; /* more space now */
1836 if (s->insert > s->strstart)
1837 s->insert = s->strstart;
1838 }
1839 if (have > s->strm->avail_in)
1840 have = s->strm->avail_in;
1841 if (have) {
1842 read_buf(s->strm, s->window + s->strstart, have);
1843 s->strstart += have;
1844 s->insert += MIN(have, s->w_size - s->insert);
1845 }
1846 if (s->high_water < s->strstart)
1847 s->high_water = s->strstart;
1848
1849 /* There was not enough avail_out to write a complete worthy or flushed
1850 * stored block to next_out. Write a stored block to pending instead, if we
1851 * have enough input for a worthy block, or if flushing and there is enough
1852 * room for the remaining input as a stored block in the pending buffer.
1853 */
1854 have = (s->bi_valid + 42) >> 3; /* number of header bytes */
1855 /* maximum stored block length that will fit in pending: */
1856 have = MIN(s->pending_buf_size - have, MAX_STORED);
1857 min_block = MIN(have, s->w_size);
1858 left = s->strstart - s->block_start;
1859 if (left >= min_block ||
1860 ((left || flush == Z_FINISH) && flush != Z_NO_FLUSH &&
1861 s->strm->avail_in == 0 && left <= have)) {
1862 len = MIN(left, have);
1863 last = flush == Z_FINISH && s->strm->avail_in == 0 &&
1864 len == left ? 1 : 0;
1865 _tr_stored_block(s, (charf *)s->window + s->block_start, len, last);
1866 s->block_start += len;
1867 flush_pending(s->strm);
1868 }
1869
1870 /* We've done all we can with the available input and output. */
1871 return last ? finish_started : need_more;
1872}
1873
1874/* ===========================================================================
1875 * Compress as much as possible from the input stream, return the current
1876 * block state.
1877 * This function does not perform lazy evaluation of matches and inserts
1878 * new strings in the dictionary only for unmatched strings or for short
1879 * matches. It is used only for the fast compression options.
1880 */
1882 deflate_state *s;
1883 int flush;
1884{
1885 IPos hash_head; /* head of the hash chain */
1886 int bflush; /* set if current block must be flushed */
1887
1888 for (;;) {
1889 /* Make sure that we always have enough lookahead, except
1890 * at the end of the input file. We need MAX_MATCH bytes
1891 * for the next match, plus MIN_MATCH bytes to insert the
1892 * string following the next match.
1893 */
1894 if (s->lookahead < MIN_LOOKAHEAD) {
1895 fill_window(s);
1896 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1897 return need_more;
1898 }
1899 if (s->lookahead == 0) break; /* flush the current block */
1900 }
1901
1902 /* Insert the string window[strstart .. strstart + 2] in the
1903 * dictionary, and set hash_head to the head of the hash chain:
1904 */
1905 hash_head = NIL;
1906 if (s->lookahead >= MIN_MATCH) {
1907 INSERT_STRING(s, s->strstart, hash_head);
1908 }
1909
1910 /* Find the longest match, discarding those <= prev_length.
1911 * At this point we have always match_length < MIN_MATCH
1912 */
1913 if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1914 /* To simplify the code, we prevent matches with the string
1915 * of window index 0 (in particular we have to avoid a match
1916 * of the string with itself at the start of the input file).
1917 */
1918 s->match_length = longest_match (s, hash_head);
1919 /* longest_match() sets match_start */
1920 }
1921 if (s->match_length >= MIN_MATCH) {
1922 check_match(s, s->strstart, s->match_start, s->match_length);
1923
1924 _tr_tally_dist(s, s->strstart - s->match_start,
1925 s->match_length - MIN_MATCH, bflush);
1926
1927 s->lookahead -= s->match_length;
1928
1929 /* Insert new strings in the hash table only if the match length
1930 * is not too large. This saves time but degrades compression.
1931 */
1932#ifndef FASTEST
1933 if (s->match_length <= s->max_insert_length &&
1934 s->lookahead >= MIN_MATCH) {
1935 s->match_length--; /* string at strstart already in table */
1936 do {
1937 s->strstart++;
1938 INSERT_STRING(s, s->strstart, hash_head);
1939 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1940 * always MIN_MATCH bytes ahead.
1941 */
1942 } while (--s->match_length != 0);
1943 s->strstart++;
1944 } else
1945#endif
1946 {
1947 s->strstart += s->match_length;
1948 s->match_length = 0;
1949 s->ins_h = s->window[s->strstart];
1950 UPDATE_HASH(s, s->ins_h, s->window[s->strstart + 1]);
1951#if MIN_MATCH != 3
1952 Call UPDATE_HASH() MIN_MATCH-3 more times
1953#endif
1954 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1955 * matter since it will be recomputed at next deflate call.
1956 */
1957 }
1958 } else {
1959 /* No match, output a literal byte */
1960 Tracevv((stderr,"%c", s->window[s->strstart]));
1961 _tr_tally_lit(s, s->window[s->strstart], bflush);
1962 s->lookahead--;
1963 s->strstart++;
1964 }
1965 if (bflush) FLUSH_BLOCK(s, 0);
1966 }
1967 s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
1968 if (flush == Z_FINISH) {
1969 FLUSH_BLOCK(s, 1);
1970 return finish_done;
1971 }
1972 if (s->sym_next)
1973 FLUSH_BLOCK(s, 0);
1974 return block_done;
1975}
1976
1977#ifndef FASTEST
1978/* ===========================================================================
1979 * Same as above, but achieves better compression. We use a lazy
1980 * evaluation for matches: a match is finally adopted only if there is
1981 * no better match at the next window position.
1982 */
1984 deflate_state *s;
1985 int flush;
1986{
1987 IPos hash_head; /* head of hash chain */
1988 int bflush; /* set if current block must be flushed */
1989
1990 /* Process the input block. */
1991 for (;;) {
1992 /* Make sure that we always have enough lookahead, except
1993 * at the end of the input file. We need MAX_MATCH bytes
1994 * for the next match, plus MIN_MATCH bytes to insert the
1995 * string following the next match.
1996 */
1997 if (s->lookahead < MIN_LOOKAHEAD) {
1998 fill_window(s);
1999 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
2000 return need_more;
2001 }
2002 if (s->lookahead == 0) break; /* flush the current block */
2003 }
2004
2005 /* Insert the string window[strstart .. strstart + 2] in the
2006 * dictionary, and set hash_head to the head of the hash chain:
2007 */
2008 hash_head = NIL;
2009 if (s->lookahead >= MIN_MATCH) {
2010 INSERT_STRING(s, s->strstart, hash_head);
2011 }
2012
2013 /* Find the longest match, discarding those <= prev_length.
2014 */
2015 s->prev_length = s->match_length, s->prev_match = s->match_start;
2016 s->match_length = MIN_MATCH-1;
2017
2018 if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
2019 s->strstart - hash_head <= MAX_DIST(s)) {
2020 /* To simplify the code, we prevent matches with the string
2021 * of window index 0 (in particular we have to avoid a match
2022 * of the string with itself at the start of the input file).
2023 */
2024 s->match_length = longest_match (s, hash_head);
2025 /* longest_match() sets match_start */
2026
2027 if (s->match_length <= 5 && (s->strategy == Z_FILTERED
2028#if TOO_FAR <= 32767
2029 || (s->match_length == MIN_MATCH &&
2030 s->strstart - s->match_start > TOO_FAR)
2031#endif
2032 )) {
2033
2034 /* If prev_match is also MIN_MATCH, match_start is garbage
2035 * but we will ignore the current match anyway.
2036 */
2037 s->match_length = MIN_MATCH-1;
2038 }
2039 }
2040 /* If there was a match at the previous step and the current
2041 * match is not better, output the previous match:
2042 */
2043 if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
2044 uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
2045 /* Do not insert strings in hash table beyond this. */
2046
2047 check_match(s, s->strstart - 1, s->prev_match, s->prev_length);
2048
2049 _tr_tally_dist(s, s->strstart - 1 - s->prev_match,
2050 s->prev_length - MIN_MATCH, bflush);
2051
2052 /* Insert in hash table all strings up to the end of the match.
2053 * strstart - 1 and strstart are already inserted. If there is not
2054 * enough lookahead, the last two strings are not inserted in
2055 * the hash table.
2056 */
2057 s->lookahead -= s->prev_length - 1;
2058 s->prev_length -= 2;
2059 do {
2060 if (++s->strstart <= max_insert) {
2061 INSERT_STRING(s, s->strstart, hash_head);
2062 }
2063 } while (--s->prev_length != 0);
2064 s->match_available = 0;
2065 s->match_length = MIN_MATCH-1;
2066 s->strstart++;
2067
2068 if (bflush) FLUSH_BLOCK(s, 0);
2069
2070 } else if (s->match_available) {
2071 /* If there was no match at the previous position, output a
2072 * single literal. If there was a match but the current match
2073 * is longer, truncate the previous match to a single literal.
2074 */
2075 Tracevv((stderr,"%c", s->window[s->strstart - 1]));
2076 _tr_tally_lit(s, s->window[s->strstart - 1], bflush);
2077 if (bflush) {
2078 FLUSH_BLOCK_ONLY(s, 0);
2079 }
2080 s->strstart++;
2081 s->lookahead--;
2082 if (s->strm->avail_out == 0) return need_more;
2083 } else {
2084 /* There is no previous match to compare with, wait for
2085 * the next step to decide.
2086 */
2087 s->match_available = 1;
2088 s->strstart++;
2089 s->lookahead--;
2090 }
2091 }
2092 Assert (flush != Z_NO_FLUSH, "no flush?");
2093 if (s->match_available) {
2094 Tracevv((stderr,"%c", s->window[s->strstart - 1]));
2095 _tr_tally_lit(s, s->window[s->strstart - 1], bflush);
2096 s->match_available = 0;
2097 }
2098 s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
2099 if (flush == Z_FINISH) {
2100 FLUSH_BLOCK(s, 1);
2101 return finish_done;
2102 }
2103 if (s->sym_next)
2104 FLUSH_BLOCK(s, 0);
2105 return block_done;
2106}
2107#endif /* FASTEST */
2108
2109/* ===========================================================================
2110 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
2111 * one. Do not maintain a hash table. (It will be regenerated if this run of
2112 * deflate switches away from Z_RLE.)
2113 */
2115 deflate_state *s;
2116 int flush;
2117{
2118 int bflush; /* set if current block must be flushed */
2119 uInt prev; /* byte at distance one to match */
2120 Bytef *scan, *strend; /* scan goes up to strend for length of run */
2121
2122 for (;;) {
2123 /* Make sure that we always have enough lookahead, except
2124 * at the end of the input file. We need MAX_MATCH bytes
2125 * for the longest run, plus one for the unrolled loop.
2126 */
2127 if (s->lookahead <= MAX_MATCH) {
2128 fill_window(s);
2129 if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {
2130 return need_more;
2131 }
2132 if (s->lookahead == 0) break; /* flush the current block */
2133 }
2134
2135 /* See how many times the previous byte repeats */
2136 s->match_length = 0;
2137 if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
2138 scan = s->window + s->strstart - 1;
2139 prev = *scan;
2140 if (prev == *++scan && prev == *++scan && prev == *++scan) {
2141 strend = s->window + s->strstart + MAX_MATCH;
2142 do {
2143 } while (prev == *++scan && prev == *++scan &&
2144 prev == *++scan && prev == *++scan &&
2145 prev == *++scan && prev == *++scan &&
2146 prev == *++scan && prev == *++scan &&
2147 scan < strend);
2148 s->match_length = MAX_MATCH - (uInt)(strend - scan);
2149 if (s->match_length > s->lookahead)
2150 s->match_length = s->lookahead;
2151 }
2152 Assert(scan <= s->window + (uInt)(s->window_size - 1),
2153 "wild scan");
2154 }
2155
2156 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
2157 if (s->match_length >= MIN_MATCH) {
2158 check_match(s, s->strstart, s->strstart - 1, s->match_length);
2159
2160 _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
2161
2162 s->lookahead -= s->match_length;
2163 s->strstart += s->match_length;
2164 s->match_length = 0;
2165 } else {
2166 /* No match, output a literal byte */
2167 Tracevv((stderr,"%c", s->window[s->strstart]));
2168 _tr_tally_lit(s, s->window[s->strstart], bflush);
2169 s->lookahead--;
2170 s->strstart++;
2171 }
2172 if (bflush) FLUSH_BLOCK(s, 0);
2173 }
2174 s->insert = 0;
2175 if (flush == Z_FINISH) {
2176 FLUSH_BLOCK(s, 1);
2177 return finish_done;
2178 }
2179 if (s->sym_next)
2180 FLUSH_BLOCK(s, 0);
2181 return block_done;
2182}
2183
2184/* ===========================================================================
2185 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
2186 * (It will be regenerated if this run of deflate switches away from Huffman.)
2187 */
2189 deflate_state *s;
2190 int flush;
2191{
2192 int bflush; /* set if current block must be flushed */
2193
2194 for (;;) {
2195 /* Make sure that we have a literal to write. */
2196 if (s->lookahead == 0) {
2197 fill_window(s);
2198 if (s->lookahead == 0) {
2199 if (flush == Z_NO_FLUSH)
2200 return need_more;
2201 break; /* flush the current block */
2202 }
2203 }
2204
2205 /* Output a literal byte */
2206 s->match_length = 0;
2207 Tracevv((stderr,"%c", s->window[s->strstart]));
2208 _tr_tally_lit(s, s->window[s->strstart], bflush);
2209 s->lookahead--;
2210 s->strstart++;
2211 if (bflush) FLUSH_BLOCK(s, 0);
2212 }
2213 s->insert = 0;
2214 if (flush == Z_FINISH) {
2215 FLUSH_BLOCK(s, 1);
2216 return finish_done;
2217 }
2218 if (s->sym_next)
2219 FLUSH_BLOCK(s, 0);
2220 return block_done;
2221}
uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
Definition adler32.c:134
unsigned long ZEXPORT crc32(unsigned long crc, const unsigned char FAR *buf, uInt len)
Definition crc32.c:1072
int ZEXPORT deflateSetHeader(z_streamp strm, gz_headerp head)
Definition deflate.c:557
int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
Definition deflate.c:225
block_state
Definition deflate.c:66
@ finish_started
Definition deflate.c:69
@ block_done
Definition deflate.c:68
@ need_more
Definition deflate.c:67
@ finish_done
Definition deflate.c:70
#define FLUSH_BLOCK_ONLY(s, last)
Definition deflate.c:1656
local block_state deflate_fast(deflate_state *s, int flush)
Definition deflate.c:1881
#define HCRC_UPDATE(beg)
Definition deflate.c:811
#define NIL
Definition deflate.c:101
int ZEXPORT deflatePending(z_streamp strm, unsigned *pending, int *bits)
Definition deflate.c:568
struct config_s config
#define MIN(a, b)
Definition deflate.c:1677
#define check_match(s, start, match, length)
Definition deflate.c:1518
#define UPDATE_HASH(s, h, c)
Definition deflate.c:157
int ZEXPORT deflateCopy(z_streamp dest, z_streamp source)
Definition deflate.c:1160
int ZEXPORT deflateSetDictionary(z_streamp strm, const Bytef *dictionary, uInt dictLength)
Definition deflate.c:416
int ZEXPORT deflateReset(z_streamp strm)
Definition deflate.c:545
block_state compress_func OF((deflate_state *s, int flush))
Definition deflate.c:73
#define INSERT_STRING(s, str, match_head)
Definition deflate.c:176
local block_state deflate_huff(deflate_state *s, int flush)
Definition deflate.c:2188
local block_state deflate_stored(deflate_state *s, int flush)
Definition deflate.c:1694
int ZEXPORT deflateParams(z_streamp strm, int level, int strategy)
Definition deflate.c:609
local void fill_window(deflate_state *s)
Definition deflate.c:1531
local void putShortMSB(deflate_state *s, uInt b)
Definition deflate.c:772
uLong ZEXPORT deflateBound(z_streamp strm, uLong sourceLen)
Definition deflate.c:700
const char deflate_copyright[]
Definition deflate.c:54
local int deflateStateCheck(z_streamp strm)
Definition deflate.c:393
local uInt longest_match(deflate_state *s, IPos cur_match)
Definition deflate.c:1282
local const config configuration_table[10]
Definition deflate.c:128
local block_state deflate_slow(deflate_state *s, int flush)
Definition deflate.c:1983
#define FLUSH_BLOCK(s, last)
Definition deflate.c:1668
int ZEXPORT deflateTune(z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
Definition deflate.c:658
int ZEXPORT deflatePrime(z_streamp strm, int bits, int value)
Definition deflate.c:582
local void lm_init(deflate_state *s)
Definition deflate.c:1249
local unsigned read_buf(z_streamp strm, Bytef *buf, unsigned size)
Definition deflate.c:1219
int ZEXPORT deflateGetDictionary(z_streamp strm, Bytef *dictionary, uInt *dictLength)
Definition deflate.c:485
#define TOO_FAR
Definition deflate.c:105
#define MAX_STORED
Definition deflate.c:1674
int ZEXPORT deflateResetKeep(z_streamp strm)
Definition deflate.c:507
int ZEXPORT deflateEnd(z_streamp strm)
Definition deflate.c:1134
local void slide_hash(deflate_state *s)
Definition deflate.c:198
int ZEXPORT deflateInit2_(z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
Definition deflate.c:237
#define RANK(f)
Definition deflate.c:149
local void flush_pending(z_streamp strm)
Definition deflate.c:786
local block_state deflate_rle(deflate_state *s, int flush)
Definition deflate.c:2114
int ZEXPORT deflate(z_streamp strm, int flush)
Definition deflate.c:819
#define CLEAR_HASH(s)
Definition deflate.c:186
#define FINISH_STATE
Definition deflate.h:63
#define COMMENT_STATE
Definition deflate.h:60
#define HCRC_STATE
Definition deflate.h:61
#define Buf_size
Definition deflate.h:51
#define GZIP_STATE
Definition deflate.h:56
#define MAX_DIST(s)
Definition deflate.h:284
#define BUSY_STATE
Definition deflate.h:62
#define put_byte(s, c)
Definition deflate.h:276
#define _tr_tally_dist(s, distance, length, flush)
Definition deflate.h:329
Pos FAR Posf
Definition deflate.h:93
ush Pos
Definition deflate.h:92
#define GZIP
Definition deflate.h:23
#define INIT_STATE
Definition deflate.h:54
#define MIN_LOOKAHEAD
Definition deflate.h:279
#define WIN_INIT
Definition deflate.h:289
#define NAME_STATE
Definition deflate.h:59
unsigned IPos
Definition deflate.h:94
#define _tr_tally_lit(s, c, flush)
Definition deflate.h:321
#define EXTRA_STATE
Definition deflate.h:58
#define local
Definition gzguts.h:114
#define DEF_MEM_LEVEL
Definition gzguts.h:151
ush good_length
Definition deflate.c:115
ush max_chain
Definition deflate.c:118
compress_func func
Definition deflate.c:119
ush nice_length
Definition deflate.c:117
ush max_lazy
Definition deflate.c:116
struct tree_desc_s l_desc
Definition deflate.h:202
uInt lit_bufsize
Definition deflate.h:222
struct ct_data_s dyn_dtree[2 *D_CODES+1]
Definition deflate.h:199
uInt good_match
Definition deflate.h:191
Bytef * pending_out
Definition deflate.h:105
Bytef * window
Definition deflate.h:119
ulg pending_buf_size
Definition deflate.h:104
Posf * prev
Definition deflate.h:134
struct ct_data_s bl_tree[2 *BL_CODES+1]
Definition deflate.h:200
struct tree_desc_s bl_desc
Definition deflate.h:204
z_streamp strm
Definition deflate.h:101
Posf * head
Definition deflate.h:140
struct tree_desc_s d_desc
Definition deflate.h:203
struct ct_data_s dyn_ltree[HEAP_SIZE]
Definition deflate.h:198
Bytef * pending_buf
Definition deflate.h:103
uchf * sym_buf
Definition deflate.h:220
ct_data * dyn_tree
Definition deflate.h:87
void ZLIB_INTERNAL _tr_init(deflate_state *s)
Definition trees.c:379
void ZLIB_INTERNAL _tr_stored_block(deflate_state *s, charf *buf, ulg stored_len, int last)
Definition trees.c:863
void ZLIB_INTERNAL _tr_flush_bits(deflate_state *s)
Definition trees.c:887
void ZLIB_INTERNAL _tr_align(deflate_state *s)
Definition trees.c:897
#define Z_HUFFMAN_ONLY
Definition zlib.h:197
#define Z_DEFLATED
Definition zlib.h:209
gz_header FAR * gz_headerp
Definition zlib.h:131
#define Z_BUF_ERROR
Definition zlib.h:184
#define Z_UNKNOWN
Definition zlib.h:206
#define ZLIB_VERSION
Definition zlib.h:40
#define Z_DEFAULT_STRATEGY
Definition zlib.h:200
z_stream FAR * z_streamp
Definition zlib.h:108
#define Z_BLOCK
Definition zlib.h:173
#define Z_VERSION_ERROR
Definition zlib.h:185
#define Z_STREAM_END
Definition zlib.h:178
#define Z_FINISH
Definition zlib.h:172
#define Z_OK
Definition zlib.h:177
#define Z_DATA_ERROR
Definition zlib.h:182
#define Z_FIXED
Definition zlib.h:199
#define Z_STREAM_ERROR
Definition zlib.h:181
#define Z_NO_FLUSH
Definition zlib.h:168
#define Z_NULL
Definition zlib.h:212
#define Z_PARTIAL_FLUSH
Definition zlib.h:169
#define Z_MEM_ERROR
Definition zlib.h:183
#define Z_FULL_FLUSH
Definition zlib.h:171
#define Z_FILTERED
Definition zlib.h:196
#define Z_RLE
Definition zlib.h:198
#define Z_DEFAULT_COMPRESSION
Definition zlib.h:193
void ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr)
Definition zutil.c:317
voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, unsigned size)
Definition zutil.c:307
void ZLIB_INTERNAL zmemzero(Bytef *dest, uInt len)
Definition zutil.c:175
void ZLIB_INTERNAL zmemcpy(Bytef *dest, const Bytef *source, uInt len)
Definition zutil.c:151
int ZLIB_INTERNAL zmemcmp(Bytef *s1, const Bytef *s2, uInt len) const
Definition zutil.c:162
#define ERR_RETURN(strm, err)
Definition zutil.h:61
#define PRESET_DICT
Definition zutil.h:88
unsigned short ush
Definition zutil.h:41
#define ZALLOC(strm, items, size)
Definition zutil.h:266
#define Assert(cond, msg)
Definition zutil.h:252
#define ERR_MSG(err)
Definition zutil.h:59
#define ZFREE(strm, addr)
Definition zutil.h:268
#define MIN_MATCH
Definition zutil.h:84
#define TRY_FREE(s, p)
Definition zutil.h:269
#define OS_CODE
Definition zutil.h:202
uch FAR uchf
Definition zutil.h:40
#define MAX_MATCH
Definition zutil.h:85
ush FAR ushf
Definition zutil.h:42
unsigned long ulg
Definition zutil.h:43
#define Tracevv(x)
Definition zutil.h:255