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