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