Geant4  9.6.p02
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
deflate.cc
Go to the documentation of this file.
1 /* deflate.c -- compress data using the deflation algorithm
2  * Copyright (C) 1995-2004 Jean-loup Gailly.
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: deflate.cc,v 1.1 2005-05-12 21:04:53 duns Exp $ */
51 
52 #include "deflate.h"
53 
54 const char deflate_copyright[] =
55  " deflate 1.2.2 Copyright 1995-2004 Jean-loup Gailly ";
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  */
66 typedef enum {
67  need_more, /* block not completed, need more input or more output */
68  block_done, /* block flush performed */
69  finish_started, /* finish started, need only more output at next deflate */
70  finish_done /* finish done, accept no more input or output */
71 } block_state;
72 
73 typedef block_state (*compress_func) OF((deflate_state *s, int flush));
74 /* Compression function. Returns the block state after the call. */
75 
79 #ifndef FASTEST
81 #endif
82 local void lm_init OF((deflate_state *s));
84 local void flush_pending OF((z_streamp strm));
85 local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
86 #ifndef FASTEST
87 #ifdef ASMV
88  void match_init OF((void)); /* asm code initialization */
89  uInt longest_match OF((deflate_state *s, IPos cur_match));
90 #else
91 local uInt longest_match OF((deflate_state *s, IPos cur_match));
92 #endif
93 #endif
95 
96 #ifdef DEBUG
97 local void check_match OF((deflate_state *s, IPos start, IPos match,
98  int length));
99 #endif
100 
101 /* ===========================================================================
102  * Local data
103  */
104 
105 #define NIL 0
106 /* Tail of hash chains */
107 
108 #ifndef TOO_FAR
109 # define TOO_FAR 4096
110 #endif
111 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
112 
113 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
114 /* Minimum amount of lookahead, except at the end of the input file.
115  * See deflate.c for comments about the MIN_MATCH+1.
116  */
117 
118 /* Values for max_lazy_match, good_match and max_chain_length, depending on
119  * the desired pack level (0..9). The values given below have been tuned to
120  * exclude worst case performance for pathological files. Better values may be
121  * found for specific files.
122  */
123 typedef struct config_s {
124  ush good_length; /* reduce lazy search above this match length */
125  ush max_lazy; /* do not perform lazy search above this match length */
126  ush nice_length; /* quit search above this match length */
128  compress_func func;
129 } config;
130 
131 #ifdef FASTEST
132 local const config configuration_table[2] = {
133 /* good lazy nice chain */
134 /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
135 /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
136 #else
137 local const config configuration_table[10] = {
138 /* good lazy nice chain */
139 /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
140 /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
141 /* 2 */ {4, 5, 16, 8, deflate_fast},
142 /* 3 */ {4, 6, 32, 32, deflate_fast},
143 
144 /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
145 /* 5 */ {8, 16, 32, 32, deflate_slow},
146 /* 6 */ {8, 16, 128, 128, deflate_slow},
147 /* 7 */ {8, 32, 128, 256, deflate_slow},
148 /* 8 */ {32, 128, 258, 1024, deflate_slow},
149 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
150 #endif
151 
152 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
153  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
154  * meaning.
155  */
156 
157 #define EQUAL 0
158 /* result of memcmp for equal strings */
159 
160 #ifndef NO_DUMMY_DECL
161 struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
162 #endif
163 
164 /* ===========================================================================
165  * Update a hash value with the given input byte
166  * IN assertion: all calls to to UPDATE_HASH are made with consecutive
167  * input characters, so that a running hash key can be computed from the
168  * previous key instead of complete recalculation each time.
169  */
170 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
171 
172 
173 /* ===========================================================================
174  * Insert string str in the dictionary and set match_head to the previous head
175  * of the hash chain (the most recent string with same hash key). Return
176  * the previous length of the hash chain.
177  * If this file is compiled with -DFASTEST, the compression level is forced
178  * to 1, and no hash chains are maintained.
179  * IN assertion: all calls to to INSERT_STRING are made with consecutive
180  * input characters and the first MIN_MATCH bytes of str are valid
181  * (except for the last MIN_MATCH-1 bytes of the input file).
182  */
183 #ifdef FASTEST
184 #define INSERT_STRING(s, str, match_head) \
185  (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
186  match_head = s->head[s->ins_h], \
187  s->head[s->ins_h] = (Pos)(str))
188 #else
189 #define INSERT_STRING(s, str, match_head) \
190  (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
191  match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
192  s->head[s->ins_h] = (Pos)(str))
193 #endif
194 
195 /* ===========================================================================
196  * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
197  * prev[] will be initialized on the fly.
198  */
199 #define CLEAR_HASH(s) \
200  s->head[s->hash_size-1] = NIL; \
201  zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
202 
203 /* ========================================================================= */
204 int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
205 {
206  return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
207  Z_DEFAULT_STRATEGY, version, stream_size);
208  /* To do: ignore strm->next_in if we use it as window */
209 }
210 
211 /* ========================================================================= */
212 int ZEXPORT deflateInit2_(z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy,
213  const char *version, int stream_size)
214 {
215  deflate_state *s;
216  int wrap = 1;
217  static const char my_version[] = ZLIB_VERSION;
218 
219  ushf *overlay;
220  /* We overlay pending_buf and d_buf+l_buf. This works since the average
221  * output size for (length,distance) codes is <= 24 bits.
222  */
223 
224  if (version == Z_NULL || version[0] != my_version[0] ||
225  stream_size != sizeof(z_stream)) {
226  return Z_VERSION_ERROR;
227  }
228  if (strm == Z_NULL) return Z_STREAM_ERROR;
229 
230  strm->msg = Z_NULL;
231  if (strm->zalloc == (alloc_func)0) {
232  strm->zalloc = zcalloc;
233  strm->opaque = (voidpf)0;
234  }
235  if (strm->zfree == (free_func)0) strm->zfree = zcfree;
236 
237 #ifdef FASTEST
238  if (level != 0) level = 1;
239 #else
240  if (level == Z_DEFAULT_COMPRESSION) level = 6;
241 #endif
242 
243  if (windowBits < 0) { /* suppress zlib wrapper */
244  wrap = 0;
245  windowBits = -windowBits;
246  }
247 #ifdef GZIP
248  else if (windowBits > 15) {
249  wrap = 2; /* write gzip wrapper instead */
250  windowBits -= 16;
251  }
252 #endif
253  if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
254  windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
255  strategy < 0 || strategy > Z_RLE) {
256  return Z_STREAM_ERROR;
257  }
258  if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
259  s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
260  if (s == Z_NULL) return Z_MEM_ERROR;
261  strm->state = (struct internal_state FAR *)s;
262  s->strm = strm;
263 
264  s->wrap = wrap;
265  s->w_bits = windowBits;
266  s->w_size = 1 << s->w_bits;
267  s->w_mask = s->w_size - 1;
268 
269  s->hash_bits = memLevel + 7;
270  s->hash_size = 1 << s->hash_bits;
271  s->hash_mask = s->hash_size - 1;
272  s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
273 
274  s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
275  s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
276  s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
277 
278  s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
279 
280  overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
281  s->pending_buf = (uchf *) overlay;
282  s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
283 
284  if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
285  s->pending_buf == Z_NULL) {
286  s->status = FINISH_STATE;
287  strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
288  deflateEnd (strm);
289  return Z_MEM_ERROR;
290  }
291  s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
292  s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
293 
294  s->level = level;
295  s->strategy = strategy;
296  s->method = (Byte)method;
297 
298  return deflateReset(strm);
299 }
300 
301 /* ========================================================================= */
302 int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
303 {
304  deflate_state *s;
305  uInt length = dictLength;
306  uInt n;
307  IPos hash_head = 0;
308 
309  if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
310  strm->state->wrap == 2 ||
311  (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
312  return Z_STREAM_ERROR;
313 
314  s = strm->state;
315  if (s->wrap)
316  strm->adler = adler32(strm->adler, dictionary, dictLength);
317 
318  if (length < MIN_MATCH) return Z_OK;
319  if (length > MAX_DIST(s)) {
320  length = MAX_DIST(s);
321 #ifndef USE_DICT_HEAD
322  dictionary += dictLength - length; /* use the tail of the dictionary */
323 #endif
324  }
325  zmemcpy(s->window, dictionary, length);
326  s->strstart = length;
327  s->block_start = (long)length;
328 
329  /* Insert all strings in the hash table (except for the last two bytes).
330  * s->lookahead stays null, so s->ins_h will be recomputed at the next
331  * call of fill_window.
332  */
333  s->ins_h = s->window[0];
334  UPDATE_HASH(s, s->ins_h, s->window[1]);
335  for (n = 0; n <= length - MIN_MATCH; n++) {
336  INSERT_STRING(s, n, hash_head);
337  }
338  if (hash_head) hash_head = 0; /* to make compiler happy */
339  return Z_OK;
340 }
341 
342 /* ========================================================================= */
344 {
345  deflate_state *s;
346 
347  if (strm == Z_NULL || strm->state == Z_NULL ||
348  strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
349  return Z_STREAM_ERROR;
350  }
351 
352  strm->total_in = strm->total_out = 0;
353  strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
354  strm->data_type = Z_UNKNOWN;
355 
356  s = (deflate_state *)strm->state;
357  s->pending = 0;
358  s->pending_out = s->pending_buf;
359 
360  if (s->wrap < 0) {
361  s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
362  }
363  s->status = s->wrap ? INIT_STATE : BUSY_STATE;
364  strm->adler =
365 #ifdef GZIP
366  s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
367 #endif
368  adler32(0L, Z_NULL, 0);
369  s->last_flush = Z_NO_FLUSH;
370 
371  _tr_init(s);
372  lm_init(s);
373 
374  return Z_OK;
375 }
376 
377 /* ========================================================================= */
379 {
380  if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
381  strm->state->bi_valid = bits;
382  strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
383  return Z_OK;
384 }
385 
386 /* ========================================================================= */
388 {
389  deflate_state *s;
390  compress_func func;
391  int err = Z_OK;
392 
393  if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
394  s = strm->state;
395 
396 #ifdef FASTEST
397  if (level != 0) level = 1;
398 #else
399  if (level == Z_DEFAULT_COMPRESSION) level = 6;
400 #endif
401  if (level < 0 || level > 9 || strategy < 0 || strategy > Z_RLE) {
402  return Z_STREAM_ERROR;
403  }
404  func = configuration_table[s->level].func;
405 
406  if (func != configuration_table[level].func && strm->total_in != 0) {
407  /* Flush the last buffer: */
408  err = deflate(strm, Z_PARTIAL_FLUSH);
409  }
410  if (s->level != level) {
411  s->level = level;
412  s->max_lazy_match = configuration_table[level].max_lazy;
413  s->good_match = configuration_table[level].good_length;
414  s->nice_match = configuration_table[level].nice_length;
415  s->max_chain_length = configuration_table[level].max_chain;
416  }
417  s->strategy = strategy;
418  return err;
419 }
420 
421 /* =========================================================================
422  * For the default windowBits of 15 and memLevel of 8, this function returns
423  * a close to exact, as well as small, upper bound on the compressed size.
424  * They are coded as constants here for a reason--if the #define's are
425  * changed, then this function needs to be changed as well. The return
426  * value for 15 and 8 only works for those exact settings.
427  *
428  * For any setting other than those defaults for windowBits and memLevel,
429  * the value returned is a conservative worst case for the maximum expansion
430  * resulting from using fixed blocks instead of stored blocks, which deflate
431  * can emit on compressed data for some combinations of the parameters.
432  *
433  * This function could be more sophisticated to provide closer upper bounds
434  * for every combination of windowBits and memLevel, as well as wrap.
435  * But even the conservative upper bound of about 14% expansion does not
436  * seem onerous for output buffer allocation.
437  */
439 {
440  deflate_state *s;
441  uLong destLen;
442 
443  /* conservative upper bound */
444  destLen = sourceLen +
445  ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
446 
447  /* if can't get parameters, return conservative bound */
448  if (strm == Z_NULL || strm->state == Z_NULL)
449  return destLen;
450 
451  /* if not default parameters, return conservative bound */
452  s = strm->state;
453  if (s->w_bits != 15 || s->hash_bits != 8 + 7)
454  return destLen;
455 
456  /* default settings: return tight bound for that case */
457  return compressBound(sourceLen);
458 }
459 
460 /* =========================================================================
461  * Put a short in the pending buffer. The 16-bit value is put in MSB order.
462  * IN assertion: the stream state is correct and there is enough room in
463  * pending_buf.
464  */
466 {
467  put_byte(s, (Byte)(b >> 8));
468  put_byte(s, (Byte)(b & 0xff));
469 }
470 
471 /* =========================================================================
472  * Flush as much pending output as possible. All deflate() output goes
473  * through this function so some applications may wish to modify it
474  * to avoid allocating a large strm->next_out buffer and copying into it.
475  * (See also read_buf()).
476  */
478 {
479  unsigned len = strm->state->pending;
480 
481  if (len > strm->avail_out) len = strm->avail_out;
482  if (len == 0) return;
483 
484  zmemcpy(strm->next_out, strm->state->pending_out, len);
485  strm->next_out += len;
486  strm->state->pending_out += len;
487  strm->total_out += len;
488  strm->avail_out -= len;
489  strm->state->pending -= len;
490  if (strm->state->pending == 0) {
491  strm->state->pending_out = strm->state->pending_buf;
492  }
493 }
494 
495 /* ========================================================================= */
496 int ZEXPORT deflate (z_streamp strm, int flush)
497 {
498  int old_flush; /* value of flush param for previous deflate call */
499  deflate_state *s;
500 
501  if (strm == Z_NULL || strm->state == Z_NULL ||
502  flush > Z_FINISH || flush < 0) {
503  return Z_STREAM_ERROR;
504  }
505  s = strm->state;
506 
507  if (strm->next_out == Z_NULL ||
508  (strm->next_in == Z_NULL && strm->avail_in != 0) ||
509  (s->status == FINISH_STATE && flush != Z_FINISH)) {
510  ERR_RETURN(strm, Z_STREAM_ERROR);
511  }
512  if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
513 
514  s->strm = strm; /* just in case */
515  old_flush = s->last_flush;
516  s->last_flush = flush;
517 
518  /* Write the header */
519  if (s->status == INIT_STATE) {
520 #ifdef GZIP
521  if (s->wrap == 2) {
522  put_byte(s, 31);
523  put_byte(s, 139);
524  put_byte(s, 8);
525  put_byte(s, 0);
526  put_byte(s, 0);
527  put_byte(s, 0);
528  put_byte(s, 0);
529  put_byte(s, 0);
530  put_byte(s, s->level == 9 ? 2 :
531  (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
532  4 : 0));
533  put_byte(s, 255);
534  s->status = BUSY_STATE;
535  strm->adler = crc32(0L, Z_NULL, 0);
536  }
537  else
538 #endif
539  {
540  uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
541  uInt level_flags;
542 
543  if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
544  level_flags = 0;
545  else if (s->level < 6)
546  level_flags = 1;
547  else if (s->level == 6)
548  level_flags = 2;
549  else
550  level_flags = 3;
551  header |= (level_flags << 6);
552  if (s->strstart != 0) header |= PRESET_DICT;
553  header += 31 - (header % 31);
554 
555  s->status = BUSY_STATE;
556  putShortMSB(s, header);
557 
558  /* Save the adler32 of the preset dictionary: */
559  if (s->strstart != 0) {
560  putShortMSB(s, (uInt)(strm->adler >> 16));
561  putShortMSB(s, (uInt)(strm->adler & 0xffff));
562  }
563  strm->adler = adler32(0L, Z_NULL, 0);
564  }
565  }
566 
567  /* Flush as much pending output as possible */
568  if (s->pending != 0) {
569  flush_pending(strm);
570  if (strm->avail_out == 0) {
571  /* Since avail_out is 0, deflate will be called again with
572  * more output space, but possibly with both pending and
573  * avail_in equal to zero. There won't be anything to do,
574  * but this is not an error situation so make sure we
575  * return OK instead of BUF_ERROR at next call of deflate:
576  */
577  s->last_flush = -1;
578  return Z_OK;
579  }
580 
581  /* Make sure there is something to do and avoid duplicate consecutive
582  * flushes. For repeated and useless calls with Z_FINISH, we keep
583  * returning Z_STREAM_END instead of Z_BUF_ERROR.
584  */
585  } else if (strm->avail_in == 0 && flush <= old_flush &&
586  flush != Z_FINISH) {
587  ERR_RETURN(strm, Z_BUF_ERROR);
588  }
589 
590  /* User must not provide more input after the first FINISH: */
591  if (s->status == FINISH_STATE && strm->avail_in != 0) {
592  ERR_RETURN(strm, Z_BUF_ERROR);
593  }
594 
595  /* Start a new block or continue the current one.
596  */
597  if (strm->avail_in != 0 || s->lookahead != 0 ||
598  (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
599  block_state bstate;
600 
601  bstate = (*(configuration_table[s->level].func))(s, flush);
602 
603  if (bstate == finish_started || bstate == finish_done) {
604  s->status = FINISH_STATE;
605  }
606  if (bstate == need_more || bstate == finish_started) {
607  if (strm->avail_out == 0) {
608  s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
609  }
610  return Z_OK;
611  /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
612  * of deflate should use the same flush parameter to make sure
613  * that the flush is complete. So we don't have to output an
614  * empty block here, this will be done at next call. This also
615  * ensures that for a very small output buffer, we emit at most
616  * one empty block.
617  */
618  }
619  if (bstate == block_done) {
620  if (flush == Z_PARTIAL_FLUSH) {
621  _tr_align(s);
622  } else { /* FULL_FLUSH or SYNC_FLUSH */
623  _tr_stored_block(s, (char*)0, 0L, 0);
624  /* For a full flush, this empty block will be recognized
625  * as a special marker by inflate_sync().
626  */
627  if (flush == Z_FULL_FLUSH) {
628  CLEAR_HASH(s); /* forget history */
629  }
630  }
631  flush_pending(strm);
632  if (strm->avail_out == 0) {
633  s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
634  return Z_OK;
635  }
636  }
637  }
638  Assert(strm->avail_out > 0, (char*)"bug2");
639 
640  if (flush != Z_FINISH) return Z_OK;
641  if (s->wrap <= 0) return Z_STREAM_END;
642 
643  /* Write the trailer */
644 #ifdef GZIP
645  if (s->wrap == 2) {
646  put_byte(s, (Byte)(strm->adler & 0xff));
647  put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
648  put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
649  put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
650  put_byte(s, (Byte)(strm->total_in & 0xff));
651  put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
652  put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
653  put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
654  }
655  else
656 #endif
657  {
658  putShortMSB(s, (uInt)(strm->adler >> 16));
659  putShortMSB(s, (uInt)(strm->adler & 0xffff));
660  }
661  flush_pending(strm);
662  /* If avail_out is zero, the application will call deflate again
663  * to flush the rest.
664  */
665  if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
666  return s->pending != 0 ? Z_OK : Z_STREAM_END;
667 }
668 
669 /* ========================================================================= */
671 {
672  int status;
673 
674  if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
675 
676  status = strm->state->status;
677  if (status != INIT_STATE && status != BUSY_STATE &&
678  status != FINISH_STATE) {
679  return Z_STREAM_ERROR;
680  }
681 
682  /* Deallocate in reverse order of allocations: */
683  TRY_FREE(strm, strm->state->pending_buf);
684  TRY_FREE(strm, strm->state->head);
685  TRY_FREE(strm, strm->state->prev);
686  TRY_FREE(strm, strm->state->window);
687 
688  ZFREE(strm, strm->state);
689  strm->state = Z_NULL;
690 
691  return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
692 }
693 
694 /* =========================================================================
695  * Copy the source state to the destination state.
696  * To simplify the source, this is not supported for 16-bit MSDOS (which
697  * doesn't have enough memory anyway to duplicate compression states).
698  */
700 {
701 #ifdef MAXSEG_64K
702  return Z_STREAM_ERROR;
703 #else
704  deflate_state *ds;
705  deflate_state *ss;
706  ushf *overlay;
707 
708 
709  if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
710  return Z_STREAM_ERROR;
711  }
712 
713  ss = source->state;
714 
715  *dest = *source;
716 
717  ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
718  if (ds == Z_NULL) return Z_MEM_ERROR;
719  dest->state = (struct internal_state FAR *) ds;
720  *ds = *ss;
721  ds->strm = dest;
722 
723  ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
724  ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
725  ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
726  overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
727  ds->pending_buf = (uchf *) overlay;
728 
729  if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
730  ds->pending_buf == Z_NULL) {
731  deflateEnd (dest);
732  return Z_MEM_ERROR;
733  }
734  /* following zmemcpy do not work for 16-bit MSDOS */
735  zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
736  zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
737  zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
739 
740  ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
741  ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
742  ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
743 
744  ds->l_desc.dyn_tree = ds->dyn_ltree;
745  ds->d_desc.dyn_tree = ds->dyn_dtree;
746  ds->bl_desc.dyn_tree = ds->bl_tree;
747 
748  return Z_OK;
749 #endif /* MAXSEG_64K */
750 }
751 
752 /* ===========================================================================
753  * Read a new buffer from the current input stream, update the adler32
754  * and total number of bytes read. All deflate() input goes through
755  * this function so some applications may wish to modify it to avoid
756  * allocating a large strm->next_in buffer and copying from it.
757  * (See also flush_pending()).
758  */
759 local int read_buf(z_streamp strm, Bytef *buf, unsigned size)
760 {
761  unsigned len = strm->avail_in;
762 
763  if (len > size) len = size;
764  if (len == 0) return 0;
765 
766  strm->avail_in -= len;
767 
768  if (strm->state->wrap == 1) {
769  strm->adler = adler32(strm->adler, strm->next_in, len);
770  }
771 #ifdef GZIP
772  else if (strm->state->wrap == 2) {
773  strm->adler = crc32(strm->adler, strm->next_in, len);
774  }
775 #endif
776  zmemcpy(buf, strm->next_in, len);
777  strm->next_in += len;
778  strm->total_in += len;
779 
780  return (int)len;
781 }
782 
783 /* ===========================================================================
784  * Initialize the "longest match" routines for a new zlib stream
785  */
787 {
788  s->window_size = (ulg)2L*s->w_size;
789 
790  CLEAR_HASH(s);
791 
792  /* Set the default configuration parameters:
793  */
794  s->max_lazy_match = configuration_table[s->level].max_lazy;
795  s->good_match = configuration_table[s->level].good_length;
796  s->nice_match = configuration_table[s->level].nice_length;
797  s->max_chain_length = configuration_table[s->level].max_chain;
798 
799  s->strstart = 0;
800  s->block_start = 0L;
801  s->lookahead = 0;
802  s->match_length = s->prev_length = MIN_MATCH-1;
803  s->match_available = 0;
804  s->ins_h = 0;
805 #ifdef ASMV
806  match_init(); /* initialize the asm code */
807 #endif
808 }
809 
810 #ifndef FASTEST
811 /* ===========================================================================
812  * Set match_start to the longest match starting at the given string and
813  * return its length. Matches shorter or equal to prev_length are discarded,
814  * in which case the result is equal to prev_length and match_start is
815  * garbage.
816  * IN assertions: cur_match is the head of the hash chain for the current
817  * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
818  * OUT assertion: the match length is not greater than s->lookahead.
819  */
820 #ifndef ASMV
821 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
822  * match.S. The code will be functionally equivalent.
823  */
825 {
826  unsigned chain_length = s->max_chain_length;/* max hash chain length */
827  register Bytef *scan = s->window + s->strstart; /* current string */
828  register Bytef *match; /* matched string */
829  register int len; /* length of current match */
830  int best_len = s->prev_length; /* best match length so far */
831  int nice_match = s->nice_match; /* stop if match long enough */
832  IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
833  s->strstart - (IPos)MAX_DIST(s) : NIL;
834  /* Stop when cur_match becomes <= limit. To simplify the code,
835  * we prevent matches with the string of window index 0.
836  */
837  Posf *prev = s->prev;
838  uInt wmask = s->w_mask;
839 
840 #ifdef UNALIGNED_OK
841  /* Compare two bytes at a time. Note: this is not always beneficial.
842  * Try with and without -DUNALIGNED_OK to check.
843  */
844  register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
845  register ush scan_start = *(ushf*)scan;
846  register ush scan_end = *(ushf*)(scan+best_len-1);
847 #else
848  register Bytef *strend = s->window + s->strstart + MAX_MATCH;
849  register Byte scan_end1 = scan[best_len-1];
850  register Byte scan_end = scan[best_len];
851 #endif
852 
853  /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
854  * It is easy to get rid of this optimization if necessary.
855  */
856  Assert(s->hash_bits >= 8 && MAX_MATCH == 258, (char*)"Code too clever");
857 
858  /* Do not waste too much time if we already have a good match: */
859  if (s->prev_length >= s->good_match) {
860  chain_length >>= 2;
861  }
862  /* Do not look for matches beyond the end of the input. This is necessary
863  * to make deflate deterministic.
864  */
865  if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
866 
867  Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, (char*)"need lookahead");
868 
869  do {
870  Assert(cur_match < s->strstart, (char*)"no future");
871  match = s->window + cur_match;
872 
873  /* Skip to next match if the match length cannot increase
874  * or if the match length is less than 2:
875  */
876 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
877  /* This code assumes sizeof(unsigned short) == 2. Do not use
878  * UNALIGNED_OK if your compiler uses a different size.
879  */
880  if (*(ushf*)(match+best_len-1) != scan_end ||
881  *(ushf*)match != scan_start) continue;
882 
883  /* It is not necessary to compare scan[2] and match[2] since they are
884  * always equal when the other bytes match, given that the hash keys
885  * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
886  * strstart+3, +5, ... up to strstart+257. We check for insufficient
887  * lookahead only every 4th comparison; the 128th check will be made
888  * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
889  * necessary to put more guard bytes at the end of the window, or
890  * to check more often for insufficient lookahead.
891  */
892  Assert(scan[2] == match[2], (char*)"scan[2]?");
893  scan++, match++;
894  do {
895  } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
896  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
897  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
898  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
899  scan < strend);
900  /* The funny "do {}" generates better code on most compilers */
901 
902  /* Here, scan <= window+strstart+257 */
903  Assert(scan <= s->window+(unsigned)(s->window_size-1), (char*)"wild scan");
904  if (*scan == *match) scan++;
905 
906  len = (MAX_MATCH - 1) - (int)(strend-scan);
907  scan = strend - (MAX_MATCH-1);
908 
909 #else /* UNALIGNED_OK */
910 
911  if (match[best_len] != scan_end ||
912  match[best_len-1] != scan_end1 ||
913  *match != *scan ||
914  *++match != scan[1]) continue;
915 
916  /* The check at best_len-1 can be removed because it will be made
917  * again later. (This heuristic is not always a win.)
918  * It is not necessary to compare scan[2] and match[2] since they
919  * are always equal when the other bytes match, given that
920  * the hash keys are equal and that HASH_BITS >= 8.
921  */
922  scan += 2, match++;
923  Assert(*scan == *match, (char*)"match[2]?");
924 
925  /* We check for insufficient lookahead only every 8th comparison;
926  * the 256th check will be made at strstart+258.
927  */
928  do {
929  } while (*++scan == *++match && *++scan == *++match &&
930  *++scan == *++match && *++scan == *++match &&
931  *++scan == *++match && *++scan == *++match &&
932  *++scan == *++match && *++scan == *++match &&
933  scan < strend);
934 
935  Assert(scan <= s->window+(unsigned)(s->window_size-1), (char*)"wild scan");
936 
937  len = MAX_MATCH - (int)(strend - scan);
938  scan = strend - MAX_MATCH;
939 
940 #endif /* UNALIGNED_OK */
941 
942  if (len > best_len) {
943  s->match_start = cur_match;
944  best_len = len;
945  if (len >= nice_match) break;
946 #ifdef UNALIGNED_OK
947  scan_end = *(ushf*)(scan+best_len-1);
948 #else
949  scan_end1 = scan[best_len-1];
950  scan_end = scan[best_len];
951 #endif
952  }
953  } while ((cur_match = prev[cur_match & wmask]) > limit
954  && --chain_length != 0);
955 
956  if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
957  return s->lookahead;
958 }
959 #endif /* ASMV */
960 #endif /* FASTEST */
961 
962 /* ---------------------------------------------------------------------------
963  * Optimized version for level == 1 or strategy == Z_RLE only
964  */
966 {
967  register Bytef *scan = s->window + s->strstart; /* current string */
968  register Bytef *match; /* matched string */
969  register int len; /* length of current match */
970  register Bytef *strend = s->window + s->strstart + MAX_MATCH;
971 
972  /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
973  * It is easy to get rid of this optimization if necessary.
974  */
975  Assert(s->hash_bits >= 8 && MAX_MATCH == 258, (char*)"Code too clever");
976 
977  Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, (char*)"need lookahead");
978 
979  Assert(cur_match < s->strstart, (char*)"no future");
980 
981  match = s->window + cur_match;
982 
983  /* Return failure if the match length is less than 2:
984  */
985  if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
986 
987  /* The check at best_len-1 can be removed because it will be made
988  * again later. (This heuristic is not always a win.)
989  * It is not necessary to compare scan[2] and match[2] since they
990  * are always equal when the other bytes match, given that
991  * the hash keys are equal and that HASH_BITS >= 8.
992  */
993  scan += 2, match += 2;
994  Assert(*scan == *match, (char*)"match[2]?");
995 
996  /* We check for insufficient lookahead only every 8th comparison;
997  * the 256th check will be made at strstart+258.
998  */
999  do {
1000  } while (*++scan == *++match && *++scan == *++match &&
1001  *++scan == *++match && *++scan == *++match &&
1002  *++scan == *++match && *++scan == *++match &&
1003  *++scan == *++match && *++scan == *++match &&
1004  scan < strend);
1005 
1006  Assert(scan <= s->window+(unsigned)(s->window_size-1), (char*)"wild scan");
1007 
1008  len = MAX_MATCH - (int)(strend - scan);
1009 
1010  if (len < MIN_MATCH) return MIN_MATCH - 1;
1011 
1012  s->match_start = cur_match;
1013  return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
1014 }
1015 
1016 #ifdef DEBUG
1017 /* ===========================================================================
1018  * Check that the match at match_start is indeed a match.
1019  */
1020 local void check_match(deflate_state *s, IPos start, IPos match, int length)
1021 {
1022  /* check that the match is indeed a match */
1023  if (zmemcmp(s->window + match,
1024  s->window + start, length) != EQUAL) {
1025  fprintf(stderr, (char*)" start %u, match %u, length %d\n",
1026  start, match, length);
1027  do {
1028  fprintf(stderr, (char*)"%c%c", s->window[match++], s->window[start++]);
1029  } while (--length != 0);
1030  z_error((char*)"invalid match");
1031  }
1032  if (z_verbose > 1) {
1033  fprintf(stderr,(char*)"\\[%d,%d]", start-match, length);
1034  do { putc(s->window[start++], stderr); } while (--length != 0);
1035  }
1036 }
1037 #else
1038 # define check_match(s, start, match, length)
1039 #endif /* DEBUG */
1040 
1041 /* ===========================================================================
1042  * Fill the window when the lookahead becomes insufficient.
1043  * Updates strstart and lookahead.
1044  *
1045  * IN assertion: lookahead < MIN_LOOKAHEAD
1046  * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1047  * At least one byte has been read, or avail_in == 0; reads are
1048  * performed for at least two bytes (required for the zip translate_eol
1049  * option -- not supported here).
1050  */
1052 {
1053  register unsigned n, m;
1054  register Posf *p;
1055  unsigned more; /* Amount of free space at the end of the window. */
1056  uInt wsize = s->w_size;
1057 
1058  do {
1059  more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
1060 
1061  /* Deal with !@#$% 64K limit: */
1062  if (sizeof(int) <= 2) {
1063  if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1064  more = wsize;
1065 
1066  } else if (more == (unsigned)(-1)) {
1067  /* Very unlikely, but possible on 16 bit machine if
1068  * strstart == 0 && lookahead == 1 (input done a byte at time)
1069  */
1070  more--;
1071  }
1072  }
1073 
1074  /* If the window is almost full and there is insufficient lookahead,
1075  * move the upper half to the lower one to make room in the upper half.
1076  */
1077  if (s->strstart >= wsize+MAX_DIST(s)) {
1078 
1079  zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
1080  s->match_start -= wsize;
1081  s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
1082  s->block_start -= (long) wsize;
1083 
1084  /* Slide the hash table (could be avoided with 32 bit values
1085  at the expense of memory usage). We slide even when level == 0
1086  to keep the hash table consistent if we switch back to level > 0
1087  later. (Using level 0 permanently is not an optimal usage of
1088  zlib, so we don't care about this pathological case.)
1089  */
1090  n = s->hash_size;
1091  p = &s->head[n];
1092  do {
1093  m = *--p;
1094  *p = (Pos)(m >= wsize ? m-wsize : NIL);
1095  } while (--n);
1096 
1097  n = wsize;
1098 #ifndef FASTEST
1099  p = &s->prev[n];
1100  do {
1101  m = *--p;
1102  *p = (Pos)(m >= wsize ? m-wsize : NIL);
1103  /* If n is not on any hash chain, prev[n] is garbage but
1104  * its value will never be used.
1105  */
1106  } while (--n);
1107 #endif
1108  more += wsize;
1109  }
1110  if (s->strm->avail_in == 0) return;
1111 
1112  /* If there was no sliding:
1113  * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1114  * more == window_size - lookahead - strstart
1115  * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1116  * => more >= window_size - 2*WSIZE + 2
1117  * In the BIG_MEM or MMAP case (not yet supported),
1118  * window_size == input_size + MIN_LOOKAHEAD &&
1119  * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1120  * Otherwise, window_size == 2*WSIZE so more >= 2.
1121  * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1122  */
1123  Assert(more >= 2, (char*)"more < 2");
1124 
1125  n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1126  s->lookahead += n;
1127 
1128  /* Initialize the hash value now that we have some input: */
1129  if (s->lookahead >= MIN_MATCH) {
1130  s->ins_h = s->window[s->strstart];
1131  UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1132 #if MIN_MATCH != 3
1133  Call UPDATE_HASH() MIN_MATCH-3 more times
1134 #endif
1135  }
1136  /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1137  * but this is not important since only literal bytes will be emitted.
1138  */
1139 
1140  } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1141 }
1142 
1143 /* ===========================================================================
1144  * Flush the current block, with given end-of-file flag.
1145  * IN assertion: strstart is set to the end of the current match.
1146  */
1147 #define FLUSH_BLOCK_ONLY(s, eof) { \
1148  _tr_flush_block(s, (s->block_start >= 0L ? \
1149  (charf *)&s->window[(unsigned)s->block_start] : \
1150  (charf *)Z_NULL), \
1151  (ulg)((long)s->strstart - s->block_start), \
1152  (eof)); \
1153  s->block_start = s->strstart; \
1154  flush_pending(s->strm); \
1155  Tracev((stderr,(char*)"[FLUSH]")); \
1156 }
1157 
1158 /* Same but force premature exit if necessary. */
1159 #define FLUSH_BLOCK(s, eof) { \
1160  FLUSH_BLOCK_ONLY(s, eof); \
1161  if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
1162 }
1163 
1164 /* ===========================================================================
1165  * Copy without compression as much as possible from the input stream, return
1166  * the current block state.
1167  * This function does not insert new strings in the dictionary since
1168  * uncompressible data is probably not useful. This function is used
1169  * only for the level=0 compression option.
1170  * NOTE: this function should be optimized to avoid extra copying from
1171  * window to pending_buf.
1172  */
1174 {
1175  /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
1176  * to pending_buf_size, and each stored block has a 5 byte header:
1177  */
1178  ulg max_block_size = 0xffff;
1179  ulg max_start;
1180 
1181  if (max_block_size > s->pending_buf_size - 5) {
1182  max_block_size = s->pending_buf_size - 5;
1183  }
1184 
1185  /* Copy as much as possible from input to output: */
1186  for (;;) {
1187  /* Fill the window as much as possible: */
1188  if (s->lookahead <= 1) {
1189 
1190  Assert(s->strstart < s->w_size+MAX_DIST(s) ||
1191  s->block_start >= (long)s->w_size, (char*)"slide too late");
1192 
1193  fill_window(s);
1194  if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
1195 
1196  if (s->lookahead == 0) break; /* flush the current block */
1197  }
1198  Assert(s->block_start >= 0L, (char*)"block gone");
1199 
1200  s->strstart += s->lookahead;
1201  s->lookahead = 0;
1202 
1203  /* Emit a stored block if pending_buf will be full: */
1204  max_start = s->block_start + max_block_size;
1205  if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
1206  /* strstart == 0 is possible when wraparound on 16-bit machine */
1207  s->lookahead = (uInt)(s->strstart - max_start);
1208  s->strstart = (uInt)max_start;
1209  FLUSH_BLOCK(s, 0);
1210  }
1211  /* Flush if we may have to slide, otherwise block_start may become
1212  * negative and the data will be gone:
1213  */
1214  if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
1215  FLUSH_BLOCK(s, 0);
1216  }
1217  }
1218  FLUSH_BLOCK(s, flush == Z_FINISH);
1219  return flush == Z_FINISH ? finish_done : block_done;
1220 }
1221 
1222 /* ===========================================================================
1223  * Compress as much as possible from the input stream, return the current
1224  * block state.
1225  * This function does not perform lazy evaluation of matches and inserts
1226  * new strings in the dictionary only for unmatched strings or for short
1227  * matches. It is used only for the fast compression options.
1228  */
1230 {
1231  IPos hash_head = NIL; /* head of the hash chain */
1232  int bflush; /* set if current block must be flushed */
1233 
1234  for (;;) {
1235  /* Make sure that we always have enough lookahead, except
1236  * at the end of the input file. We need MAX_MATCH bytes
1237  * for the next match, plus MIN_MATCH bytes to insert the
1238  * string following the next match.
1239  */
1240  if (s->lookahead < MIN_LOOKAHEAD) {
1241  fill_window(s);
1242  if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1243  return need_more;
1244  }
1245  if (s->lookahead == 0) break; /* flush the current block */
1246  }
1247 
1248  /* Insert the string window[strstart .. strstart+2] in the
1249  * dictionary, and set hash_head to the head of the hash chain:
1250  */
1251  if (s->lookahead >= MIN_MATCH) {
1252  INSERT_STRING(s, s->strstart, hash_head);
1253  }
1254 
1255  /* Find the longest match, discarding those <= prev_length.
1256  * At this point we have always match_length < MIN_MATCH
1257  */
1258  if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1259  /* To simplify the code, we prevent matches with the string
1260  * of window index 0 (in particular we have to avoid a match
1261  * of the string with itself at the start of the input file).
1262  */
1263 #ifdef FASTEST
1264  if ((s->strategy < Z_HUFFMAN_ONLY) ||
1265  (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
1266  s->match_length = longest_match_fast (s, hash_head);
1267  }
1268 #else
1269  if (s->strategy < Z_HUFFMAN_ONLY) {
1270  s->match_length = longest_match (s, hash_head);
1271  } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
1272  s->match_length = longest_match_fast (s, hash_head);
1273  }
1274 #endif
1275  /* longest_match() or longest_match_fast() sets match_start */
1276  }
1277  if (s->match_length >= MIN_MATCH) {
1279 
1280  _tr_tally_dist(s, s->strstart - s->match_start,
1281  s->match_length - MIN_MATCH, bflush);
1282 
1283  s->lookahead -= s->match_length;
1284 
1285  /* Insert new strings in the hash table only if the match length
1286  * is not too large. This saves time but degrades compression.
1287  */
1288 #ifndef FASTEST
1289  if (s->match_length <= s->max_insert_length &&
1290  s->lookahead >= MIN_MATCH) {
1291  s->match_length--; /* string at strstart already in table */
1292  do {
1293  s->strstart++;
1294  INSERT_STRING(s, s->strstart, hash_head);
1295  /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1296  * always MIN_MATCH bytes ahead.
1297  */
1298  } while (--s->match_length != 0);
1299  s->strstart++;
1300  } else
1301 #endif
1302  {
1303  s->strstart += s->match_length;
1304  s->match_length = 0;
1305  s->ins_h = s->window[s->strstart];
1306  UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1307 #if MIN_MATCH != 3
1308  Call UPDATE_HASH() MIN_MATCH-3 more times
1309 #endif
1310  /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1311  * matter since it will be recomputed at next deflate call.
1312  */
1313  }
1314  } else {
1315  /* No match, output a literal byte */
1316  Tracevv((stderr,"%c", s->window[s->strstart]));
1317  _tr_tally_lit (s, s->window[s->strstart], bflush);
1318  s->lookahead--;
1319  s->strstart++;
1320  }
1321  if (bflush) FLUSH_BLOCK(s, 0);
1322  }
1323  FLUSH_BLOCK(s, flush == Z_FINISH);
1324  return flush == Z_FINISH ? finish_done : block_done;
1325 }
1326 
1327 #ifndef FASTEST
1328 /* ===========================================================================
1329  * Same as above, but achieves better compression. We use a lazy
1330  * evaluation for matches: a match is finally adopted only if there is
1331  * no better match at the next window position.
1332  */
1334 {
1335  IPos hash_head = NIL; /* head of hash chain */
1336  int bflush; /* set if current block must be flushed */
1337 
1338  /* Process the input block. */
1339  for (;;) {
1340  /* Make sure that we always have enough lookahead, except
1341  * at the end of the input file. We need MAX_MATCH bytes
1342  * for the next match, plus MIN_MATCH bytes to insert the
1343  * string following the next match.
1344  */
1345  if (s->lookahead < MIN_LOOKAHEAD) {
1346  fill_window(s);
1347  if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1348  return need_more;
1349  }
1350  if (s->lookahead == 0) break; /* flush the current block */
1351  }
1352 
1353  /* Insert the string window[strstart .. strstart+2] in the
1354  * dictionary, and set hash_head to the head of the hash chain:
1355  */
1356  if (s->lookahead >= MIN_MATCH) {
1357  INSERT_STRING(s, s->strstart, hash_head);
1358  }
1359 
1360  /* Find the longest match, discarding those <= prev_length.
1361  */
1363  s->match_length = MIN_MATCH-1;
1364 
1365  if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
1366  s->strstart - hash_head <= MAX_DIST(s)) {
1367  /* To simplify the code, we prevent matches with the string
1368  * of window index 0 (in particular we have to avoid a match
1369  * of the string with itself at the start of the input file).
1370  */
1371  if (s->strategy < Z_HUFFMAN_ONLY) {
1372  s->match_length = longest_match (s, hash_head);
1373  } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
1374  s->match_length = longest_match_fast (s, hash_head);
1375  }
1376  /* longest_match() or longest_match_fast() sets match_start */
1377 
1378  if (s->match_length <= 5 && (s->strategy == Z_FILTERED
1379 #if TOO_FAR <= 32767
1380  || (s->match_length == MIN_MATCH &&
1381  s->strstart - s->match_start > TOO_FAR)
1382 #endif
1383  )) {
1384 
1385  /* If prev_match is also MIN_MATCH, match_start is garbage
1386  * but we will ignore the current match anyway.
1387  */
1388  s->match_length = MIN_MATCH-1;
1389  }
1390  }
1391  /* If there was a match at the previous step and the current
1392  * match is not better, output the previous match:
1393  */
1394  if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
1395  uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
1396  /* Do not insert strings in hash table beyond this. */
1397 
1398  check_match(s, s->strstart-1, s->prev_match, s->prev_length);
1399 
1400  _tr_tally_dist(s, s->strstart -1 - s->prev_match,
1401  s->prev_length - MIN_MATCH, bflush);
1402 
1403  /* Insert in hash table all strings up to the end of the match.
1404  * strstart-1 and strstart are already inserted. If there is not
1405  * enough lookahead, the last two strings are not inserted in
1406  * the hash table.
1407  */
1408  s->lookahead -= s->prev_length-1;
1409  s->prev_length -= 2;
1410  do {
1411  if (++s->strstart <= max_insert) {
1412  INSERT_STRING(s, s->strstart, hash_head);
1413  }
1414  } while (--s->prev_length != 0);
1415  s->match_available = 0;
1416  s->match_length = MIN_MATCH-1;
1417  s->strstart++;
1418 
1419  if (bflush) FLUSH_BLOCK(s, 0);
1420 
1421  } else if (s->match_available) {
1422  /* If there was no match at the previous position, output a
1423  * single literal. If there was a match but the current match
1424  * is longer, truncate the previous match to a single literal.
1425  */
1426  Tracevv((stderr,(char*)"%c", s->window[s->strstart-1]));
1427  _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1428  if (bflush) {
1429  FLUSH_BLOCK_ONLY(s, 0);
1430  }
1431  s->strstart++;
1432  s->lookahead--;
1433  if (s->strm->avail_out == 0) return need_more;
1434  } else {
1435  /* There is no previous match to compare with, wait for
1436  * the next step to decide.
1437  */
1438  s->match_available = 1;
1439  s->strstart++;
1440  s->lookahead--;
1441  }
1442  }
1443  Assert (flush != Z_NO_FLUSH, (char*)"no flush?");
1444  if (s->match_available) {
1445  Tracevv((stderr,(char*)"%c", s->window[s->strstart-1]));
1446  _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1447  s->match_available = 0;
1448  }
1449  FLUSH_BLOCK(s, flush == Z_FINISH);
1450  return flush == Z_FINISH ? finish_done : block_done;
1451 }
1452 #endif /* FASTEST */