Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / gnu / usr.bin / gzip / deflate.c
1 /* deflate.c -- compress data using the deflation algorithm
2  * Copyright (C) 1992-1993 Jean-loup Gailly
3  * This is free software; you can redistribute it and/or modify it under the
4  * terms of the GNU General Public License, see the file COPYING.
5  *
6  * $FreeBSD: src/gnu/usr.bin/gzip/deflate.c,v 1.7 1999/08/27 23:35:50 peter Exp $
7  * $DragonFly: src/gnu/usr.bin/gzip/Attic/deflate.c,v 1.2 2003/06/17 04:25:46 dillon Exp $
8
9 /*
10  *  PURPOSE
11  *
12  *      Identify new text as repetitions of old text within a fixed-
13  *      length sliding window trailing behind the new text.
14  *
15  *  DISCUSSION
16  *
17  *      The "deflation" process depends on being able to identify portions
18  *      of the input text which are identical to earlier input (within a
19  *      sliding window trailing behind the input currently being processed).
20  *
21  *      The most straightforward technique turns out to be the fastest for
22  *      most input files: try all possible matches and select the longest.
23  *      The key feature of this algorithm is that insertions into the string
24  *      dictionary are very simple and thus fast, and deletions are avoided
25  *      completely. Insertions are performed at each input character, whereas
26  *      string matches are performed only when the previous match ends. So it
27  *      is preferable to spend more time in matches to allow very fast string
28  *      insertions and avoid deletions. The matching algorithm for small
29  *      strings is inspired from that of Rabin & Karp. A brute force approach
30  *      is used to find longer strings when a small match has been found.
31  *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
32  *      (by Leonid Broukhis).
33  *         A previous version of this file used a more sophisticated algorithm
34  *      (by Fiala and Greene) which is guaranteed to run in linear amortized
35  *      time, but has a larger average cost, uses more memory and is patented.
36  *      However the F&G algorithm may be faster for some highly redundant
37  *      files if the parameter max_chain_length (described below) is too large.
38  *
39  *  ACKNOWLEDGEMENTS
40  *
41  *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
42  *      I found it in 'freeze' written by Leonid Broukhis.
43  *      Thanks to many info-zippers for bug reports and testing.
44  *
45  *  REFERENCES
46  *
47  *      APPNOTE.TXT documentation file in PKZIP 1.93a distribution.
48  *
49  *      A description of the Rabin and Karp algorithm is given in the book
50  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
51  *
52  *      Fiala,E.R., and Greene,D.H.
53  *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
54  *
55  *  INTERFACE
56  *
57  *      void lm_init (int pack_level, ush *flags)
58  *          Initialize the "longest match" routines for a new file
59  *
60  *      ulg deflate (void)
61  *          Processes a new input file and return its compressed length. Sets
62  *          the compressed length, crc, deflate flags and internal file
63  *          attributes.
64  */
65
66 #include <stdio.h>
67
68 #include "tailor.h"
69 #include "gzip.h"
70 #include "lzw.h" /* just for consistency checking */
71
72 /* ===========================================================================
73  * Configuration parameters
74  */
75
76 /* Compile with MEDIUM_MEM to reduce the memory requirements or
77  * with SMALL_MEM to use as little memory as possible. Use BIG_MEM if the
78  * entire input file can be held in memory (not possible on 16 bit systems).
79  * Warning: defining these symbols affects HASH_BITS (see below) and thus
80  * affects the compression ratio. The compressed output
81  * is still correct, and might even be smaller in some cases.
82  */
83
84 #ifdef SMALL_MEM
85 #   define HASH_BITS  13  /* Number of bits used to hash strings */
86 #endif
87 #ifdef MEDIUM_MEM
88 #   define HASH_BITS  14
89 #endif
90 #ifndef HASH_BITS
91 #   define HASH_BITS  15
92    /* For portability to 16 bit machines, do not use values above 15. */
93 #endif
94
95 /* To save space (see unlzw.c), we overlay prev+head with tab_prefix and
96  * window with tab_suffix. Check that we can do this:
97  */
98 #if (WSIZE<<1) > (1<<BITS)
99    error: cannot overlay window with tab_suffix and prev with tab_prefix0
100 #endif
101 #if HASH_BITS > BITS-1
102    error: cannot overlay head with tab_prefix1
103 #endif
104
105 #define HASH_SIZE (unsigned)(1<<HASH_BITS)
106 #define HASH_MASK (HASH_SIZE-1)
107 #define WMASK     (WSIZE-1)
108 /* HASH_SIZE and WSIZE must be powers of two */
109
110 #define NIL 0
111 /* Tail of hash chains */
112
113 #define FAST 4
114 #define SLOW 2
115 /* speed options for the general purpose bit flag */
116
117 #ifndef TOO_FAR
118 #  define TOO_FAR 4096
119 #endif
120 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
121
122 /* ===========================================================================
123  * Local data used by the "longest match" routines.
124  */
125
126 typedef ush Pos;
127 typedef unsigned IPos;
128 /* A Pos is an index in the character window. We use short instead of int to
129  * save space in the various tables. IPos is used only for parameter passing.
130  */
131
132 /* DECLARE(uch, window, 2L*WSIZE); */
133 /* Sliding window. Input bytes are read into the second half of the window,
134  * and move to the first half later to keep a dictionary of at least WSIZE
135  * bytes. With this organization, matches are limited to a distance of
136  * WSIZE-MAX_MATCH bytes, but this ensures that IO is always
137  * performed with a length multiple of the block size. Also, it limits
138  * the window size to 64K, which is quite useful on MSDOS.
139  * To do: limit the window size to WSIZE+BSZ if SMALL_MEM (the code would
140  * be less efficient).
141  */
142
143 /* DECLARE(Pos, prev, WSIZE); */
144 /* Link to older string with same hash index. To limit the size of this
145  * array to 64K, this link is maintained only for the last 32K strings.
146  * An index in this array is thus a window index modulo 32K.
147  */
148
149 /* DECLARE(Pos, head, 1<<HASH_BITS); */
150 /* Heads of the hash chains or NIL. */
151
152 ulg window_size = (ulg)2*WSIZE;
153 /* window size, 2*WSIZE except for MMAP or BIG_MEM, where it is the
154  * input file length plus MIN_LOOKAHEAD.
155  */
156
157 long block_start;
158 /* window position at the beginning of the current output block. Gets
159  * negative when the window is moved backwards.
160  */
161
162 local unsigned ins_h;  /* hash index of string to be inserted */
163
164 #define H_SHIFT  ((HASH_BITS+MIN_MATCH-1)/MIN_MATCH)
165 /* Number of bits by which ins_h and del_h must be shifted at each
166  * input step. It must be such that after MIN_MATCH steps, the oldest
167  * byte no longer takes part in the hash key, that is:
168  *   H_SHIFT * MIN_MATCH >= HASH_BITS
169  */
170
171 unsigned int near prev_length;
172 /* Length of the best match at previous step. Matches not greater than this
173  * are discarded. This is used in the lazy match evaluation.
174  */
175
176       unsigned near strstart;      /* start of string to insert */
177       unsigned near match_start;   /* start of matching string */
178 local int           eofile;        /* flag set at end of input file */
179 local unsigned      lookahead;     /* number of valid bytes ahead in window */
180
181 unsigned near max_chain_length;
182 /* To speed up deflation, hash chains are never searched beyond this length.
183  * A higher limit improves compression ratio but degrades the speed.
184  */
185
186 local unsigned int max_lazy_match;
187 /* Attempt to find a better match only when the current match is strictly
188  * smaller than this value. This mechanism is used only for compression
189  * levels >= 4.
190  */
191 #define max_insert_length  max_lazy_match
192 /* Insert new strings in the hash table only if the match length
193  * is not greater than this length. This saves time but degrades compression.
194  * max_insert_length is used only for compression levels <= 3.
195  */
196
197 local int compr_level;
198 /* compression level (1..9) */
199
200 unsigned near good_match;
201 /* Use a faster search when the previous match is longer than this */
202
203
204 /* Values for max_lazy_match, good_match and max_chain_length, depending on
205  * the desired pack level (0..9). The values given below have been tuned to
206  * exclude worst case performance for pathological files. Better values may be
207  * found for specific files.
208  */
209
210 typedef struct config {
211    ush good_length; /* reduce lazy search above this match length */
212    ush max_lazy;    /* do not perform lazy search above this match length */
213    ush nice_length; /* quit search above this match length */
214    ush max_chain;
215 } config;
216
217 #ifdef  FULL_SEARCH
218 # define nice_match MAX_MATCH
219 #else
220   int near nice_match; /* Stop searching when current match exceeds this */
221 #endif
222
223 local config configuration_table[10] = {
224 /*      good lazy nice chain */
225 /* 0 */ {0,    0,  0,    0},  /* store only */
226 /* 1 */ {4,    4,  8,    4},  /* maximum speed, no lazy matches */
227 /* 2 */ {4,    5, 16,    8},
228 /* 3 */ {4,    6, 32,   32},
229
230 /* 4 */ {4,    4, 16,   16},  /* lazy matches */
231 /* 5 */ {8,   16, 32,   32},
232 /* 6 */ {8,   16, 128, 128},
233 /* 7 */ {8,   32, 128, 256},
234 /* 8 */ {32, 128, 258, 1024},
235 /* 9 */ {32, 258, 258, 4096}}; /* maximum compression */
236
237 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
238  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
239  * meaning.
240  */
241
242 #define EQUAL 0
243 /* result of memcmp for equal strings */
244
245 /* ===========================================================================
246  *  Prototypes for local functions.
247  */
248 local void fill_window   OF((void));
249 local ulg deflate_fast   OF((void));
250
251       int  longest_match OF((IPos cur_match));
252 #ifdef ASMV
253       void match_init OF((void)); /* asm code initialization */
254 #endif
255
256 #ifdef DEBUG
257 local  void check_match OF((IPos start, IPos match, int length));
258 #endif
259
260 /* ===========================================================================
261  * Update a hash value with the given input byte
262  * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
263  *    input characters, so that a running hash key can be computed from the
264  *    previous key instead of complete recalculation each time.
265  */
266 #define UPDATE_HASH(h,c) (h = (((h)<<H_SHIFT) ^ (c)) & HASH_MASK)
267
268 /* ===========================================================================
269  * Insert string s in the dictionary and set match_head to the previous head
270  * of the hash chain (the most recent string with same hash key). Return
271  * the previous length of the hash chain.
272  * IN  assertion: all calls to to INSERT_STRING are made with consecutive
273  *    input characters and the first MIN_MATCH bytes of s are valid
274  *    (except for the last MIN_MATCH-1 bytes of the input file).
275  */
276 #define INSERT_STRING(s, match_head) \
277    (UPDATE_HASH(ins_h, window[(s) + MIN_MATCH-1]), \
278     prev[(s) & WMASK] = match_head = head[ins_h], \
279     head[ins_h] = (s))
280
281 /* ===========================================================================
282  * Initialize the "longest match" routines for a new file
283  */
284 void lm_init (pack_level, flags)
285     int pack_level; /* 0: store, 1: best speed, 9: best compression */
286     ush *flags;     /* general purpose bit flag */
287 {
288     register unsigned j;
289
290     if (pack_level < 1 || pack_level > 9) error("bad pack level");
291     compr_level = pack_level;
292
293     /* Initialize the hash table. */
294 #if defined(MAXSEG_64K) && HASH_BITS == 15
295     for (j = 0;  j < HASH_SIZE; j++) head[j] = NIL;
296 #else
297     memzero((char*)head, HASH_SIZE*sizeof(*head));
298 #endif
299     /* prev will be initialized on the fly */
300
301     /* Set the default configuration parameters:
302      */
303     max_lazy_match   = configuration_table[pack_level].max_lazy;
304     good_match       = configuration_table[pack_level].good_length;
305 #ifndef FULL_SEARCH
306     nice_match       = configuration_table[pack_level].nice_length;
307 #endif
308     max_chain_length = configuration_table[pack_level].max_chain;
309     if (pack_level == 1) {
310        *flags |= FAST;
311     } else if (pack_level == 9) {
312        *flags |= SLOW;
313     }
314     /* ??? reduce max_chain_length for binary files */
315
316     strstart = 0;
317     block_start = 0L;
318 #ifdef ASMV
319     match_init(); /* initialize the asm code */
320 #endif
321
322     lookahead = read_buf((char*)window,
323                          sizeof(int) <= 2 ? (unsigned)WSIZE : 2*WSIZE);
324
325     if (lookahead == 0 || lookahead == (unsigned)EOF) {
326        eofile = 1, lookahead = 0;
327        return;
328     }
329     eofile = 0;
330     /* Make sure that we always have enough lookahead. This is important
331      * if input comes from a device such as a tty.
332      */
333     while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
334
335     ins_h = 0;
336     for (j=0; j<MIN_MATCH-1; j++) UPDATE_HASH(ins_h, window[j]);
337     /* If lookahead < MIN_MATCH, ins_h is garbage, but this is
338      * not important since only literal bytes will be emitted.
339      */
340 }
341
342 /* ===========================================================================
343  * Set match_start to the longest match starting at the given string and
344  * return its length. Matches shorter or equal to prev_length are discarded,
345  * in which case the result is equal to prev_length and match_start is
346  * garbage.
347  * IN assertions: cur_match is the head of the hash chain for the current
348  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
349  */
350 #ifndef ASMV
351 /* For MSDOS, OS/2 and 386 Unix, an optimized version is in match.asm or
352  * match.s. The code is functionally equivalent, so you can use the C version
353  * if desired.
354  */
355 int longest_match(cur_match)
356     IPos cur_match;                             /* current match */
357 {
358     unsigned chain_length = max_chain_length;   /* max hash chain length */
359     register uch *scan = window + strstart;     /* current string */
360     register uch *match;                        /* matched string */
361     register int len;                           /* length of current match */
362     int best_len = prev_length;                 /* best match length so far */
363     IPos limit = strstart > (IPos)MAX_DIST ? strstart - (IPos)MAX_DIST : NIL;
364     /* Stop when cur_match becomes <= limit. To simplify the code,
365      * we prevent matches with the string of window index 0.
366      */
367
368 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
369  * It is easy to get rid of this optimization if necessary.
370  */
371 #if HASH_BITS < 8 || MAX_MATCH != 258
372    error: Code too clever
373 #endif
374
375 #ifdef UNALIGNED_OK
376     /* Compare two bytes at a time. Note: this is not always beneficial.
377      * Try with and without -DUNALIGNED_OK to check.
378      */
379     register uch *strend = window + strstart + MAX_MATCH - 1;
380     register ush scan_start = *(ush*)scan;
381     register ush scan_end   = *(ush*)(scan+best_len-1);
382 #else
383     register uch *strend = window + strstart + MAX_MATCH;
384     register uch scan_end1  = scan[best_len-1];
385     register uch scan_end   = scan[best_len];
386 #endif
387
388     /* Do not waste too much time if we already have a good match: */
389     if (prev_length >= good_match) {
390         chain_length >>= 2;
391     }
392     Assert(strstart <= window_size-MIN_LOOKAHEAD, "insufficient lookahead");
393
394     do {
395         Assert(cur_match < strstart, "no future");
396         match = window + cur_match;
397
398         /* Skip to next match if the match length cannot increase
399          * or if the match length is less than 2:
400          */
401 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
402         /* This code assumes sizeof(unsigned short) == 2. Do not use
403          * UNALIGNED_OK if your compiler uses a different size.
404          */
405         if (*(ush*)(match+best_len-1) != scan_end ||
406             *(ush*)match != scan_start) continue;
407
408         /* It is not necessary to compare scan[2] and match[2] since they are
409          * always equal when the other bytes match, given that the hash keys
410          * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
411          * strstart+3, +5, ... up to strstart+257. We check for insufficient
412          * lookahead only every 4th comparison; the 128th check will be made
413          * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
414          * necessary to put more guard bytes at the end of the window, or
415          * to check more often for insufficient lookahead.
416          */
417         scan++, match++;
418         do {
419         } while (*(ush*)(scan+=2) == *(ush*)(match+=2) &&
420                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
421                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
422                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
423                  scan < strend);
424         /* The funny "do {}" generates better code on most compilers */
425
426         /* Here, scan <= window+strstart+257 */
427         Assert(scan <= window+(unsigned)(window_size-1), "wild scan");
428         if (*scan == *match) scan++;
429
430         len = (MAX_MATCH - 1) - (int)(strend-scan);
431         scan = strend - (MAX_MATCH-1);
432
433 #else /* UNALIGNED_OK */
434
435         if (match[best_len]   != scan_end  ||
436             match[best_len-1] != scan_end1 ||
437             *match            != *scan     ||
438             *++match          != scan[1])      continue;
439
440         /* The check at best_len-1 can be removed because it will be made
441          * again later. (This heuristic is not always a win.)
442          * It is not necessary to compare scan[2] and match[2] since they
443          * are always equal when the other bytes match, given that
444          * the hash keys are equal and that HASH_BITS >= 8.
445          */
446         scan += 2, match++;
447
448         /* We check for insufficient lookahead only every 8th comparison;
449          * the 256th check will be made at strstart+258.
450          */
451         do {
452         } while (*++scan == *++match && *++scan == *++match &&
453                  *++scan == *++match && *++scan == *++match &&
454                  *++scan == *++match && *++scan == *++match &&
455                  *++scan == *++match && *++scan == *++match &&
456                  scan < strend);
457
458         len = MAX_MATCH - (int)(strend - scan);
459         scan = strend - MAX_MATCH;
460
461 #endif /* UNALIGNED_OK */
462
463         if (len > best_len) {
464             match_start = cur_match;
465             best_len = len;
466             if (len >= nice_match) break;
467 #ifdef UNALIGNED_OK
468             scan_end = *(ush*)(scan+best_len-1);
469 #else
470             scan_end1  = scan[best_len-1];
471             scan_end   = scan[best_len];
472 #endif
473         }
474     } while ((cur_match = prev[cur_match & WMASK]) > limit
475              && --chain_length != 0);
476
477     return best_len;
478 }
479 #endif /* ASMV */
480
481 #ifdef DEBUG
482 /* ===========================================================================
483  * Check that the match at match_start is indeed a match.
484  */
485 local void check_match(start, match, length)
486     IPos start, match;
487     int length;
488 {
489     /* check that the match is indeed a match */
490     if (memcmp((char*)window + match,
491                 (char*)window + start, length) != EQUAL) {
492         fprintf(stderr,
493             " start %d, match %d, length %d\n",
494             start, match, length);
495         error("invalid match");
496     }
497     if (verbose > 1) {
498         fprintf(stderr,"\\[%d,%d]", start-match, length);
499         do { putc(window[start++], stderr); } while (--length != 0);
500     }
501 }
502 #else
503 #  define check_match(start, match, length)
504 #endif
505
506 /* ===========================================================================
507  * Fill the window when the lookahead becomes insufficient.
508  * Updates strstart and lookahead, and sets eofile if end of input file.
509  * IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0
510  * OUT assertions: at least one byte has been read, or eofile is set;
511  *    file reads are performed for at least two bytes (required for the
512  *    translate_eol option).
513  */
514 local void fill_window()
515 {
516     register unsigned n, m;
517     unsigned more = (unsigned)(window_size - (ulg)lookahead - (ulg)strstart);
518     /* Amount of free space at the end of the window. */
519
520     /* If the window is almost full and there is insufficient lookahead,
521      * move the upper half to the lower one to make room in the upper half.
522      */
523     if (more == (unsigned)EOF) {
524         /* Very unlikely, but possible on 16 bit machine if strstart == 0
525          * and lookahead == 1 (input done one byte at time)
526          */
527         more--;
528     } else if (strstart >= WSIZE+MAX_DIST) {
529         /* By the IN assertion, the window is not empty so we can't confuse
530          * more == 0 with more == 64K on a 16 bit machine.
531          */
532         Assert(window_size == (ulg)2*WSIZE, "no sliding with BIG_MEM");
533
534         memcpy((char*)window, (char*)window+WSIZE, (unsigned)WSIZE);
535         match_start -= WSIZE;
536         strstart    -= WSIZE; /* we now have strstart >= MAX_DIST: */
537
538         block_start -= (long) WSIZE;
539
540         for (n = 0; n < HASH_SIZE; n++) {
541             m = head[n];
542             head[n] = (Pos)(m >= WSIZE ? m-WSIZE : NIL);
543         }
544         for (n = 0; n < WSIZE; n++) {
545             m = prev[n];
546             prev[n] = (Pos)(m >= WSIZE ? m-WSIZE : NIL);
547             /* If n is not on any hash chain, prev[n] is garbage but
548              * its value will never be used.
549              */
550         }
551         more += WSIZE;
552     }
553     /* At this point, more >= 2 */
554     if (!eofile) {
555         n = read_buf((char*)window+strstart+lookahead, more);
556         if (n == 0 || n == (unsigned)EOF) {
557             eofile = 1;
558         } else {
559             lookahead += n;
560         }
561     }
562 }
563
564 /* ===========================================================================
565  * Flush the current block, with given end-of-file flag.
566  * IN assertion: strstart is set to the end of the current match.
567  */
568 #define FLUSH_BLOCK(eof) \
569    flush_block(block_start >= 0L ? (char*)&window[(unsigned)block_start] : \
570                 (char*)NULL, (long)strstart - block_start, (eof))
571
572 /* ===========================================================================
573  * Processes a new input file and return its compressed length. This
574  * function does not perform lazy evaluationof matches and inserts
575  * new strings in the dictionary only for unmatched strings or for short
576  * matches. It is used only for the fast compression options.
577  */
578 local ulg deflate_fast()
579 {
580     IPos hash_head; /* head of the hash chain */
581     int flush;      /* set if current block must be flushed */
582     unsigned match_length = 0;  /* length of best match */
583
584     prev_length = MIN_MATCH-1;
585     while (lookahead != 0) {
586         /* Insert the string window[strstart .. strstart+2] in the
587          * dictionary, and set hash_head to the head of the hash chain:
588          */
589         INSERT_STRING(strstart, hash_head);
590
591         /* Find the longest match, discarding those <= prev_length.
592          * At this point we have always match_length < MIN_MATCH
593          */
594         if (hash_head != NIL && strstart - hash_head <= MAX_DIST) {
595             /* To simplify the code, we prevent matches with the string
596              * of window index 0 (in particular we have to avoid a match
597              * of the string with itself at the start of the input file).
598              */
599             match_length = longest_match (hash_head);
600             /* longest_match() sets match_start */
601             if (match_length > lookahead) match_length = lookahead;
602         }
603         if (match_length >= MIN_MATCH) {
604             check_match(strstart, match_start, match_length);
605
606             flush = ct_tally(strstart-match_start, match_length - MIN_MATCH);
607
608             lookahead -= match_length;
609
610             /* Insert new strings in the hash table only if the match length
611              * is not too large. This saves time but degrades compression.
612              */
613             if (match_length <= max_insert_length) {
614                 match_length--; /* string at strstart already in hash table */
615                 do {
616                     strstart++;
617                     INSERT_STRING(strstart, hash_head);
618                     /* strstart never exceeds WSIZE-MAX_MATCH, so there are
619                      * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
620                      * these bytes are garbage, but it does not matter since
621                      * the next lookahead bytes will be emitted as literals.
622                      */
623                 } while (--match_length != 0);
624                 strstart++;
625             } else {
626                 strstart += match_length;
627                 match_length = 0;
628                 ins_h = window[strstart];
629                 UPDATE_HASH(ins_h, window[strstart+1]);
630 #if MIN_MATCH != 3
631                 Call UPDATE_HASH() MIN_MATCH-3 more times
632 #endif
633             }
634         } else {
635             /* No match, output a literal byte */
636             Tracevv((stderr,"%c",window[strstart]));
637             flush = ct_tally (0, window[strstart]);
638             lookahead--;
639             strstart++;
640         }
641         if (flush) FLUSH_BLOCK(0), block_start = strstart;
642
643         /* Make sure that we always have enough lookahead, except
644          * at the end of the input file. We need MAX_MATCH bytes
645          * for the next match, plus MIN_MATCH bytes to insert the
646          * string following the next match.
647          */
648         while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
649
650     }
651     return FLUSH_BLOCK(1); /* eof */
652 }
653
654 /* ===========================================================================
655  * Same as above, but achieves better compression. We use a lazy
656  * evaluation for matches: a match is finally adopted only if there is
657  * no better match at the next window position.
658  */
659 ulg deflate()
660 {
661     IPos hash_head;          /* head of hash chain */
662     IPos prev_match;         /* previous match */
663     int flush;               /* set if current block must be flushed */
664     int match_available = 0; /* set if previous match exists */
665     register unsigned match_length = MIN_MATCH-1; /* length of best match */
666 #ifdef DEBUG
667     extern long isize;        /* byte length of input file, for debug only */
668 #endif
669
670     if (compr_level <= 3) return deflate_fast(); /* optimized for speed */
671
672     /* Process the input block. */
673     while (lookahead != 0) {
674         /* Insert the string window[strstart .. strstart+2] in the
675          * dictionary, and set hash_head to the head of the hash chain:
676          */
677         INSERT_STRING(strstart, hash_head);
678
679         /* Find the longest match, discarding those <= prev_length.
680          */
681         prev_length = match_length, prev_match = match_start;
682         match_length = MIN_MATCH-1;
683
684         if (hash_head != NIL && prev_length < max_lazy_match &&
685             strstart - hash_head <= MAX_DIST) {
686             /* To simplify the code, we prevent matches with the string
687              * of window index 0 (in particular we have to avoid a match
688              * of the string with itself at the start of the input file).
689              */
690             match_length = longest_match (hash_head);
691             /* longest_match() sets match_start */
692             if (match_length > lookahead) match_length = lookahead;
693
694             /* Ignore a length 3 match if it is too distant: */
695             if (match_length == MIN_MATCH && strstart-match_start > TOO_FAR){
696                 /* If prev_match is also MIN_MATCH, match_start is garbage
697                  * but we will ignore the current match anyway.
698                  */
699                 match_length--;
700             }
701         }
702         /* If there was a match at the previous step and the current
703          * match is not better, output the previous match:
704          */
705         if (prev_length >= MIN_MATCH && match_length <= prev_length) {
706
707             check_match(strstart-1, prev_match, prev_length);
708
709             flush = ct_tally(strstart-1-prev_match, prev_length - MIN_MATCH);
710
711             /* Insert in hash table all strings up to the end of the match.
712              * strstart-1 and strstart are already inserted.
713              */
714             lookahead -= prev_length-1;
715             prev_length -= 2;
716             do {
717                 strstart++;
718                 INSERT_STRING(strstart, hash_head);
719                 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
720                  * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
721                  * these bytes are garbage, but it does not matter since the
722                  * next lookahead bytes will always be emitted as literals.
723                  */
724             } while (--prev_length != 0);
725             match_available = 0;
726             match_length = MIN_MATCH-1;
727             strstart++;
728             if (flush) FLUSH_BLOCK(0), block_start = strstart;
729
730         } else if (match_available) {
731             /* If there was no match at the previous position, output a
732              * single literal. If there was a match but the current match
733              * is longer, truncate the previous match to a single literal.
734              */
735             Tracevv((stderr,"%c",window[strstart-1]));
736             if (ct_tally (0, window[strstart-1])) {
737                 FLUSH_BLOCK(0), block_start = strstart;
738             }
739             strstart++;
740             lookahead--;
741         } else {
742             /* There is no previous match to compare with, wait for
743              * the next step to decide.
744              */
745             match_available = 1;
746             strstart++;
747             lookahead--;
748         }
749         Assert (strstart <= isize && lookahead <= isize, "a bit too far");
750
751         /* Make sure that we always have enough lookahead, except
752          * at the end of the input file. We need MAX_MATCH bytes
753          * for the next match, plus MIN_MATCH bytes to insert the
754          * string following the next match.
755          */
756         while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
757     }
758     if (match_available) ct_tally (0, window[strstart-1]);
759
760     return FLUSH_BLOCK(1); /* eof */
761 }