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