Debian Codegraph @

src/lib/deflate.c

raw symbols SCIP
1 /* deflate9.c -- compress data using the deflation64 algorithm
2 * Copyright (C) 1995-2022 Jean-loup Gailly and Mark Adler
3 * Copyright (C) 2022 Hiroshi Miura
4 */
5
6 /*
7 * ALGORITHM
8 *
9 * The "deflation" process depends on being able to identify portions
10 * of the input text which are identical to earlier input (within a
11 * sliding window trailing behind the input currently being processed).
12 *
13 * The most straightforward technique turns out to be the fastest for
14 * most input files: try all possible matches and select the longest.
15 * The key feature of this algorithm is that insertions into the string
16 * dictionary are very simple and thus fast, and deletions are avoided
17 * completely. Insertions are performed at each input character, whereas
18 * string matches are performed only when the previous match ends. So it
19 * is preferable to spend more time in matches to allow very fast string
20 * insertions and avoid deletions. The matching algorithm for small
21 * strings is inspired from that of Rabin & Karp. A brute force approach
22 * is used to find longer strings when a small match has been found.
23 * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
24 * (by Leonid Broukhis).
25 * A previous version of this file used a more sophisticated algorithm
26 * (by Fiala and Greene) which is guaranteed to run in linear amortized
27 * time, but has a larger average cost, uses more memory and is patented.
28 * However the F&G algorithm may be faster for some highly redundant
29 * files if the parameter max_chain_length (described below) is too large.
30 *
31 * ACKNOWLEDGEMENTS
32 *
33 * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
34 * I found it in 'freeze' written by Leonid Broukhis.
35 * Thanks to many people for bug reports and testing.
36 *
37 * REFERENCES
38 *
39 * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
40 * Available in http://tools.ietf.org/html/rfc1951
41 *
42 * A description of the Rabin and Karp algorithm is given in the book
43 * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
44 *
45 * Fiala,E.R., and Greene,D.H.
46 * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
47 *
48 */
49
50 /* @(#) $Id$ */
51
52 #include "inflate64.h"
53 #include "deflate.h"
54
55 /* ===========================================================================
56 * Function prototypes.
57 */
58 typedef enum {
59 need_more, /* block not completed, need more input or more output */
60 block_done, /* block flush performed */
61 finish_started, /* finish started, need only more output at next deflate */
62 finish_done /* finish done, accept no more input or output */
63 } block_state;
64
65 local int deflateStateCheck OF((z_streamp strm));
66 local void slide_hash OF((deflate_state *s));
67 local void fill_window OF((deflate_state *s));
68 local block_state deflate9_ OF((deflate_state *s, int flush));
69 local void lm_init OF((deflate_state *s));
70 local void flush_pending OF((z_streamp strm));
71 local unsigned read_buf OF((z_streamp strm, Byte FAR *buf, unsigned size));
72 local uInt longest_match OF((deflate_state *s, IPos cur_match));
73
74 #ifdef ZLIB_DEBUG
75 local void check_match OF((deflate_state *s, IPos start, IPos match, int length));
76 #endif
77
78 /* ===========================================================================
79 * Local data
80 */
81
82 #define NIL 0
83 /* Tail of hash chains */
84
85 #ifndef TOO_FAR
86 # define TOO_FAR 4096
87 #endif
88 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
89
90 /* Note: deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
91 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
92 * meaning.
93 */
94
95 /* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */
96 #define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0))
97
98 /* ===========================================================================
99 * Update a hash value with the given input byte
100 * IN assertion: all calls to UPDATE_HASH are made with consecutive input
101 * characters, so that a running hash key can be computed from the previous
102 * key instead of complete recalculation each time.
103 */
104 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
105
106
107 /* ===========================================================================
108 * Insert string str in the dictionary and set match_head to the previous head
109 * of the hash chain (the most recent string with same hash key). Return
110 * the previous length of the hash chain.
111 * IN assertion: all calls to INSERT_STRING are made with consecutive input
112 * characters and the first MIN_MATCH bytes of str are valid (except for
113 * the last MIN_MATCH-1 bytes of the input file).
114 */
115 #define INSERT_STRING(s, str, match_head) \
116 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
117 match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
118 s->head[s->ins_h] = (Pos)(str))
119
120 /* ===========================================================================
121 * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
122 * prev[] will be initialized on the fly.
123 */
124 #define CLEAR_HASH(s) \
125 do { \
126 s->head[s->hash_size-1] = NIL; \
127 zmemzero((Byte FAR *)s->head, \
128 (unsigned)(s->hash_size-1)*sizeof(*s->head)); \
129 } while (0)
130
131 /* ===========================================================================
132 * Slide the hash table when sliding the window down (could be avoided with 32
133 * bit values at the expense of memory usage). We slide even when level == 0 to
134 * keep the hash table consistent if we switch back to level > 0 later.
135 */
136 local void slide_hash(s)
137 deflate_state *s;
138 {
139 unsigned n, m;
140 Posf *p;
141 uInt wsize = s->w_size;
142
143 n = s->hash_size;
144 p = &s->head[n];
145 do {
146 m = *--p;
147 *p = (Pos)(m >= wsize ? m - wsize : NIL);
148 } while (--n);
149 n = wsize;
150 p = &s->prev[n];
151 do {
152 m = *--p;
153 *p = (Pos)(m >= wsize ? m - wsize : NIL);
154 /* If n is not on any hash chain, prev[n] is garbage but
155 * its value will never be used.
156 */
157 } while (--n);
158 }
159
160 /* ========================================================================= */
161 int ZEXPORT deflate9Init2(strm)
162 z_streamp strm;
163 {
164 deflate_state *s;
165
166 if (strm == Z_NULL) return Z_STREAM_ERROR;
167
168 strm->msg = Z_NULL;
169 if (strm->zalloc == (alloc_func)0) {
170 return Z_STREAM_ERROR;
171 }
172 if (strm->zfree == (free_func)0) {
173 return Z_STREAM_ERROR;
174 }
175
176 s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
177 if (s == Z_NULL) return Z_MEM_ERROR;
178 strm->state = (struct internal_state FAR *)s;
179 s->strm = strm;
180 s->status = INIT_STATE; /* to pass state test in deflateReset() */
181
182 s->w_bits = WBITS64;
183 s->w_size = 1 << s->w_bits;
184 s->w_mask = s->w_size - 1;
185
186 s->hash_bits = MEM_LEVEL64 + 7;
187 s->hash_size = 1 << s->hash_bits;
188 s->hash_mask = s->hash_size - 1;
189 s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
190
191 s->window = (Byte FAR *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
192 s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
193 s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
194
195 s->high_water = 0; /* nothing written to s->window yet */
196
197 s->lit_bufsize = 1 << (s->hash_bits - 1); /* 32K elements by default */
198
199 s->pending_buf = (unsigned char FAR *) ZALLOC(strm, s->lit_bufsize, 4);
200 s->pending_buf_size = (unsigned long)s->lit_bufsize * 4;
201 s->sym_buf = (unsigned char FAR *) ZALLOC(strm, s->lit_bufsize, 4);
202 s->sym_end = s->lit_bufsize * 4;
203
204 if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
205 s->pending_buf == Z_NULL || s->sym_buf == Z_NULL) {
206 s->status = FINISH_STATE;
207 strm->msg = ERR_MSG(Z_MEM_ERROR);
208 deflate9End (strm);
209 return Z_MEM_ERROR;
210 }
211 return deflate9Reset(strm);
212 }
213
214 /* =========================================================================
215 * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
216 */
217 local int deflateStateCheck (strm)
218 z_streamp strm;
219 {
220 deflate_state *s;
221 if (strm == Z_NULL ||
222 strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
223 return 1;
224 s = strm->state;
225 if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE &&
226 s->status != BUSY_STATE &&
227 s->status != FINISH_STATE))
228 return 1;
229 return 0;
230 }
231
232 /* ========================================================================= */
233 int ZEXPORT deflate9ResetKeep (strm)
234 z_streamp strm;
235 {
236 deflate_state *s;
237
238 if (deflateStateCheck(strm)) {
239 return Z_STREAM_ERROR;
240 }
241
242 strm->total_in = strm->total_out = 0;
243 strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
244 strm->data_type = Z_UNKNOWN;
245
246 s = (deflate_state *)strm->state;
247 s->pending = 0;
248 s->pending_out = s->pending_buf;
249
250 s->status = INIT_STATE;
251 s->last_flush = -2;
252
253 _tr_init(s);
254
255 return Z_OK;
256 }
257
258 /* ========================================================================= */
259 int ZEXPORT deflate9Reset (strm)
260 z_streamp strm;
261 {
262 int ret = deflate9ResetKeep(strm);
263 if (ret == Z_OK) {
264 lm_init(strm->state);
265 }
266 return ret;
267 }
268
269 /* =========================================================================
270 * Flush as much pending output as possible. All deflate() output, except for
271 * some deflate_stored() output, goes through this function so some
272 * applications may wish to modify it to avoid allocating a large
273 * strm->next_out buffer and copying into it. (See also read_buf()).
274 */
275 local void flush_pending(strm)
276 z_streamp strm;
277 {
278 unsigned len;
279 deflate_state *s = strm->state;
280
281 _tr_flush_bits(s);
282 len = s->pending;
283 if (len > strm->avail_out) {
284 len = strm->avail_out;
285 }
286 if (len == 0) {
287 return;
288 }
289
290 zmemcpy(strm->next_out, s->pending_out, len);
291 strm->next_out += len;
292 s->pending_out += len;
293 strm->total_out += len;
294 strm->avail_out -= len;
295 s->pending -= len;
296 if (s->pending == 0) {
297 s->pending_out = s->pending_buf;
298 }
299 }
300
301 /* ========================================================================= */
302 int ZEXPORT deflate9 (strm, flush)
303 z_streamp strm;
304 int flush;
305 {
306 int old_flush; /* value of flush param for previous deflate call */
307 deflate_state *s;
308
309 /* Only accept Z_FINISH or Z_NO_FLUSH */
310 if (deflateStateCheck(strm) || (flush != Z_FINISH && flush != Z_NO_FLUSH)) {
311 return Z_STREAM_ERROR;
312 }
313 s = strm->state;
314
315 if (strm->next_out == Z_NULL ||
316 (strm->avail_in != 0 && strm->next_in == Z_NULL) ||
317 (s->status == FINISH_STATE && flush != Z_FINISH)) {
318 ERR_RETURN(strm, Z_STREAM_ERROR);
319 }
320 if (strm->avail_out == 0) { ERR_RETURN(strm, Z_BUF_ERROR); }
321
322 old_flush = s->last_flush;
323 s->last_flush = flush;
324
325 /* Flush as much pending output as possible */
326 if (s->pending != 0) {
327 flush_pending(strm);
328 if (strm->avail_out == 0) {
329 /* Since avail_out is 0, deflate will be called again with
330 * more output space, but possibly with both pending and
331 * avail_in equal to zero. There won't be anything to do,
332 * but this is not an error situation so make sure we
333 * return OK instead of BUF_ERROR at next call of deflate:
334 */
335 s->last_flush = -1;
336 return Z_OK;
337 }
338
339 /* Make sure there is something to do and avoid duplicate consecutive
340 * flushes. For repeated and useless calls with Z_FINISH, we keep
341 * returning Z_STREAM_END instead of Z_BUF_ERROR.
342 */
343 } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) && flush != Z_FINISH) {
344 ERR_RETURN(strm, Z_BUF_ERROR);
345 }
346
347 /* User must not provide more input after the first FINISH: */
348 if (s->status == FINISH_STATE && strm->avail_in != 0) {
349 ERR_RETURN(strm, Z_BUF_ERROR);
350 }
351
352 /* raw deflate only */
353 if (s->status == INIT_STATE) { s->status = BUSY_STATE; }
354
355 /* Start a new block or continue the current one.
356 */
357 if (strm->avail_in != 0 || s->lookahead != 0 ||
358 (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
359 block_state bstate;
360
361 bstate = deflate9_(s, flush);
362
363 if (bstate == finish_started || bstate == finish_done) {
364 s->status = FINISH_STATE;
365 }
366 if (bstate == need_more || bstate == finish_started) {
367 if (strm->avail_out == 0) {
368 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
369 }
370 return Z_OK;
371 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
372 * of deflate should use the same flush parameter to make sure
373 * that the flush is complete. So we don't have to output an
374 * empty block here, this will be done at next call. This also
375 * ensures that for a very small output buffer, we emit at most
376 * one empty block.
377 */
378 }
379 if (bstate == block_done) {
380 flush_pending(strm);
381 if (strm->avail_out == 0) {
382 s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
383 return Z_OK;
384 }
385 }
386 }
387
388 if (flush != Z_FINISH) return Z_OK;
389 return Z_STREAM_END;
390 }
391
392 /* ========================================================================= */
393 int ZEXPORT deflate9End (z_streamp strm) {
394 int status;
395
396 if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
397
398 status = strm->state->status;
399
400 /* Deallocate in reverse order of allocations: */
401 TRY_FREE(strm, strm->state->sym_buf);
402 TRY_FREE(strm, strm->state->pending_buf);
403 TRY_FREE(strm, strm->state->head);
404 TRY_FREE(strm, strm->state->prev);
405 TRY_FREE(strm, strm->state->window);
406
407 ZFREE(strm, strm->state);
408 strm->state = Z_NULL;
409
410 return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
411 }
412
413 /* ===========================================================================
414 * Read a new buffer from the current input stream, * and total number of bytes read.
415 * All deflate() input goes through
416 * this function so some applications may wish to modify it to avoid
417 * allocating a large strm->next_in buffer and copying from it.
418 * (See also flush_pending()).
419 */
420 local unsigned read_buf(strm, buf, size)
421 z_streamp strm;
422 Byte FAR *buf;
423 unsigned size;
424 {
425 unsigned len = strm->avail_in;
426
427 if (len > size) len = size;
428 if (len == 0) return 0;
429
430 strm->avail_in -= len;
431
432 zmemcpy(buf, strm->next_in, len);
433 strm->next_in += len;
434 strm->total_in += len;
435
436 return len;
437 }
438
439 /* ===========================================================================
440 * Initialize the "longest match" routines for a new zlib stream
441 */
442 local void lm_init (s)
443 deflate_state *s;
444 {
445 s->window_size = (unsigned long) 2L * s->w_size;
446
447 CLEAR_HASH(s);
448
449 /* Set the default configuration parameters:
450 */
451 s->max_lazy_match = 258;
452 s->good_match = 32;
453 s->nice_match = 258;
454 s->max_chain_length = 4096;
455
456 s->strstart = 0;
457 s->block_start = 0L;
458 s->lookahead = 0;
459 s->insert = 0;
460 s->match_length = s->prev_length = MIN_MATCH - 1;
461 s->match_available = 0;
462 s->ins_h = 0;
463 }
464
465 /* ===========================================================================
466 * Set match_start to the longest match starting at the given string and
467 * return its length. Matches shorter or equal to prev_length are discarded,
468 * in which case the result is equal to prev_length and match_start is
469 * garbage.
470 * IN assertions: cur_match is the head of the hash chain for the current
471 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
472 * OUT assertion: the match length is not greater than s->lookahead.
473 */
474 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
475 * match.S. The code will be functionally equivalent.
476 */
477 local uInt longest_match(s, cur_match)
478 deflate_state *s;
479 IPos cur_match; /* current match */
480 {
481 unsigned chain_length = s->max_chain_length;/* max hash chain length */
482 register Byte FAR *scan = s->window + s->strstart; /* current string */
483 register Byte FAR *match; /* matched string */
484 register int len; /* length of current match */
485 int best_len = (int)s->prev_length; /* best match length so far */
486 int nice_match = s->nice_match; /* stop if match long enough */
487 IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
488 s->strstart - (IPos)MAX_DIST(s) : NIL;
489 /* Stop when cur_match becomes <= limit. To simplify the code,
490 * we prevent matches with the string of window index 0.
491 */
492 Posf *prev = s->prev;
493 uInt wmask = s->w_mask;
494 register Byte FAR *strend = s->window + s->strstart + MAX_MATCH;
495 register Byte scan_end1 = scan[best_len-1];
496 register Byte scan_end = scan[best_len];
497
498 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
499 * It is easy to get rid of this optimization if necessary.
500 */
501 // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
502
503 /* Do not waste too much time if we already have a good match: */
504 if (s->prev_length >= s->good_match) {
505 chain_length >>= 2;
506 }
507 /* Do not look for matches beyond the end of the input. This is necessary
508 * to make deflate deterministic.
509 */
510 if ((uInt) nice_match > s->lookahead) {
511 nice_match = (int) s->lookahead;
512 }
513
514 Assert((unsigned long)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
515
516 do {
517 Assert(cur_match < s->strstart, "no future");
518 match = s->window + cur_match;
519
520 /* Skip to next match if the match length cannot increase
521 * or if the match length is less than 2. Note that the checks below
522 * for insufficient lookahead only occur occasionally for performance
523 * reasons. Therefore uninitialized memory will be accessed, and
524 * conditional jumps will be made that depend on those values.
525 * However the length of the match is limited to the lookahead, so
526 * the output of deflate is not affected by the uninitialized values.
527 */
528 if (match[best_len] != scan_end ||
529 match[best_len-1] != scan_end1 ||
530 *match != *scan ||
531 *++match != scan[1]) continue;
532
533 /* The check at best_len-1 can be removed because it will be made
534 * again later. (This heuristic is not always a win.)
535 * It is not necessary to compare scan[2] and match[2] since they
536 * are always equal when the other bytes match, given that
537 * the hash keys are equal and that HASH_BITS >= 8.
538 */
539 scan += 2, match++;
540 Assert(*scan == *match, "match[2]?");
541
542 /* We check for insufficient lookahead only every 8th comparison;
543 * the 256th check will be made at strstart+258.
544 */
545 do {
546 } while (*++scan == *++match && *++scan == *++match &&
547 *++scan == *++match && *++scan == *++match &&
548 *++scan == *++match && *++scan == *++match &&
549 *++scan == *++match && *++scan == *++match &&
550 scan < strend);
551
552 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
553
554 len = MAX_MATCH - (int)(strend - scan);
555 scan = strend - MAX_MATCH;
556
557 if (len > best_len) {
558 s->match_start = cur_match;
559 best_len = len;
560 if (len >= nice_match) {
561 break;
562 }
563 scan_end1 = scan[best_len - 1];
564 scan_end = scan[best_len];
565 }
566 } while ((cur_match = prev[cur_match & wmask]) > limit
567 && --chain_length != 0);
568
569 if ((uInt) best_len <= s->lookahead) {
570 return (uInt) best_len;
571 }
572 return s->lookahead;
573 }
574
575
576 #ifdef ZLIB_DEBUG
577
578 #define EQUAL 0
579 /* result of memcmp for equal strings */
580
581 /* ===========================================================================
582 * Check that the match at match_start is indeed a match.
583 */
584 local void check_match(s, start, match, length)
585 deflate_state *s;
586 IPos start, match;
587 int length;
588 {
589 /* check that the match is indeed a match */
590 if (zmemcmp(s->window + match,
591 s->window + start, length) != EQUAL) {
592 fprintf(stderr, " start %u, match %u, length %d\n",
593 start, match, length);
594 do {
595 fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
596 } while (--length != 0);
597 z_error("invalid match");
598 }
599 if (z_verbose > 1) {
600 fprintf(stderr,"\\[%d,%d]", start-match, length);
601 do { putc(s->window[start++], stderr); } while (--length != 0);
602 }
603 }
604 #else
605 # define check_match(s, start, match, length)
606 #endif /* ZLIB_DEBUG */
607
608 /* ===========================================================================
609 * Fill the window when the lookahead becomes insufficient.
610 * Updates strstart and lookahead.
611 *
612 * IN assertion: lookahead < MIN_LOOKAHEAD
613 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
614 * At least one byte has been read, or avail_in == 0; reads are
615 * performed for at least two bytes (required for the zip translate_eol
616 * option -- not supported here).
617 */
618 local void fill_window(s)
619 deflate_state *s;
620 {
621 unsigned n;
622 unsigned more; /* Amount of free space at the end of the window. */
623 uInt wsize = s->w_size;
624
625 Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
626
627 do {
628 more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
629
630 /* Deal with !@#$% 64K limit: */
631 if (sizeof(int) <= 2) {
632 if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
633 more = wsize;
634
635 } else if (more == (unsigned)(-1)) {
636 /* Very unlikely, but possible on 16 bit machine if
637 * strstart == 0 && lookahead == 1 (input done a byte at time)
638 */
639 more--;
640 }
641 }
642
643 /* If the window is almost full and there is insufficient lookahead,
644 * move the upper half to the lower one to make room in the upper half.
645 */
646 if (s->strstart >= wsize+MAX_DIST(s)) {
647
648 zmemcpy(s->window, s->window+wsize, (unsigned)wsize - more);
649 s->match_start -= wsize;
650 s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
651 s->block_start -= (long) wsize;
652 if (s->insert > s->strstart) {
653 s->insert = s->strstart;
654 }
655 slide_hash(s);
656 more += wsize;
657 }
658 if (s->strm->avail_in == 0) break;
659
660 /* If there was no sliding:
661 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
662 * more == window_size - lookahead - strstart
663 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
664 * => more >= window_size - 2*WSIZE + 2
665 * In the BIG_MEM or MMAP case (not yet supported),
666 * window_size == input_size + MIN_LOOKAHEAD &&
667 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
668 * Otherwise, window_size == 2*WSIZE so more >= 2.
669 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
670 */
671 Assert(more >= 2, "more < 2");
672
673 n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
674 s->lookahead += n;
675
676 /* Initialize the hash value now that we have some input: */
677 if (s->lookahead + s->insert >= MIN_MATCH) {
678 uInt str = s->strstart - s->insert;
679 s->ins_h = s->window[str];
680 UPDATE_HASH(s, s->ins_h, s->window[str + 1]);
681 #if MIN_MATCH != 3
682 Call UPDATE_HASH() MIN_MATCH-3 more times
683 #endif
684 while (s->insert) {
685 UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH - 1]);
686 s->prev[str & s->w_mask] = s->head[s->ins_h];
687 s->head[s->ins_h] = (Pos)str;
688 str++;
689 s->insert--;
690 if (s->lookahead + s->insert < MIN_MATCH)
691 break;
692 }
693 }
694 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
695 * but this is not important since only literal bytes will be emitted.
696 */
697
698 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
699
700 /* If the WIN_INIT bytes after the end of the current data have never been
701 * written, then zero those bytes in order to avoid memory check reports of
702 * the use of uninitialized (or uninitialised as Julian writes) bytes by
703 * the longest match routines. Update the high water mark for the next
704 * time through here. WIN_INIT is set to MAX_MATCH since the longest match
705 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
706 */
707 if (s->high_water < s->window_size) {
708 unsigned long curr = s->strstart + (ulg)(s->lookahead);
709 unsigned long init;
710
711 if (s->high_water < curr) {
712 /* Previous high water mark below current data -- zero WIN_INIT
713 * bytes or up to end of window, whichever is less.
714 */
715 init = s->window_size - curr;
716 if (init > WIN_INIT) {
717 init = WIN_INIT;
718 }
719 zmemzero(s->window + curr, (unsigned)init);
720 s->high_water = curr + init;
721 }
722 else if (s->high_water < (ulg)curr + WIN_INIT) {
723 /* High water mark at or above current data, but below current data
724 * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
725 * to end of window, whichever is less.
726 */
727 init = (unsigned long)curr + WIN_INIT - s->high_water;
728 if (init > s->window_size - s->high_water) {
729 init = s->window_size - s->high_water;
730 }
731 zmemzero(s->window + s->high_water, (unsigned)init);
732 s->high_water += init;
733 }
734 }
735
736 Assert((unsigned long)s->strstart <= s->window_size - MIN_LOOKAHEAD,
737 "not enough room for search");
738 }
739
740 /* ===========================================================================
741 * Flush the current block, with given end-of-file flag.
742 * IN assertion: strstart is set to the end of the current match.
743 */
744 #define FLUSH_BLOCK_ONLY(s, last) { \
745 _tr_flush_block(s, (s->block_start >= 0L ? \
746 (char FAR *)&s->window[(unsigned)s->block_start] : \
747 (char FAR *)Z_NULL), \
748 (unsigned long)((long)s->strstart - s->block_start), \
749 (last)); \
750 s->block_start = s->strstart; \
751 flush_pending(s->strm); \
752 Tracev((stderr,"[FLUSH]\n")); \
753 }
754
755 /* ===========================================================================
756 * Same as above, but achieves better compression. We use a lazy
757 * evaluation for matches: a match is finally adopted only if there is
758 * no better match at the next window position.
759 */
760 local block_state deflate9_(s, flush)
761 deflate_state *s;
762 int flush;
763 {
764 IPos hash_head; /* head of hash chain */
765 int bflush; /* set if current block must be flushed */
766
767 /* Process the input block. */
768 for (;;) {
769 /* Make sure that we always have enough lookahead, except
770 * at the end of the input file. We need MAX_MATCH bytes
771 * for the next match, plus MIN_MATCH bytes to insert the
772 * string following the next match.
773 */
774 if (s->lookahead < MIN_LOOKAHEAD) {
775 fill_window(s);
776 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
777 return need_more;
778 }
779 if (s->lookahead == 0) break; /* flush the current block */
780 }
781
782 /* Insert the string window[strstart .. strstart+2] in the
783 * dictionary, and set hash_head to the head of the hash chain:
784 */
785 hash_head = NIL;
786 if (s->lookahead >= MIN_MATCH) {
787 INSERT_STRING(s, s->strstart, hash_head);
788 }
789
790 /* Find the longest match, discarding those <= prev_length.
791 */
792 s->prev_length = s->match_length, s->prev_match = s->match_start;
793 s->match_length = MIN_MATCH-1;
794
795 if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
796 s->strstart - hash_head <= MAX_DIST(s)) {
797 /* To simplify the code, we prevent matches with the string
798 * of window index 0 (in particular we have to avoid a match
799 * of the string with itself at the start of the input file).
800 */
801 s->match_length = longest_match (s, hash_head);
802 /* longest_match() sets match_start */
803 }
804 /* If there was a match at the previous step and the current
805 * match is not better, output the previous match:
806 */
807 if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
808 uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
809 /* Do not insert strings in hash table beyond this. */
810
811 check_match(s, s->strstart-1, s->prev_match, s->prev_length);
812
813 bflush = _tr_tally(s, s->strstart -1 - s->prev_match, s->prev_length - MIN_MATCH);
814
815 /* Insert in hash table all strings up to the end of the match.
816 * strstart-1 and strstart are already inserted. If there is not
817 * enough lookahead, the last two strings are not inserted in
818 * the hash table.
819 */
820 s->lookahead -= s->prev_length-1;
821 s->prev_length -= 2;
822 do {
823 if (++s->strstart <= max_insert) {
824 INSERT_STRING(s, s->strstart, hash_head);
825 }
826 } while (--s->prev_length != 0);
827 s->match_available = 0;
828 s->match_length = MIN_MATCH-1;
829 s->strstart++;
830
831 if (bflush) {
832 FLUSH_BLOCK_ONLY(s, 0);
833 if (s->strm->avail_out == 0) {
834 return need_more;
835 }
836 }
837
838 } else if (s->match_available) {
839 /* If there was no match at the previous position, output a
840 * single literal. If there was a match but the current match
841 * is longer, truncate the previous match to a single literal.
842 */
843 Tracevv((stderr,"%c", s->window[s->strstart-1]));
844 bflush = _tr_tally(s, 0, s->window[s->strstart-1]);
845 if (bflush) {
846 FLUSH_BLOCK_ONLY(s, 0);
847 }
848 s->strstart++;
849 s->lookahead--;
850 if (s->strm->avail_out == 0) return need_more;
851 } else {
852 /* There is no previous match to compare with, wait for
853 * the next step to decide.
854 */
855 s->match_available = 1;
856 s->strstart++;
857 s->lookahead--;
858 }
859 }
860 Assert (flush != Z_NO_FLUSH, "no flush?");
861 if (s->match_available) {
862 Tracevv((stderr,"%c", s->window[s->strstart-1]));
863 bflush = _tr_tally(s, 0, s->window[s->strstart-1]);
864 s->match_available = 0;
865 }
866 s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
867 if (flush == Z_FINISH) {
868 FLUSH_BLOCK_ONLY(s, 1);
869 if (s->strm->avail_out == 0) {
870 return finish_started;
871 } else {
872 return finish_done;
873 }
874 }
875 if (s->sym_next) {
876 FLUSH_BLOCK_ONLY(s, 0);
877 if (s->strm->avail_out == 0) {
878 return need_more;
879 }
880 }
881 return block_done;
882 }