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