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