]> git.lizzy.rs Git - zlib.git/blob - deflate.c
zlib 0.8
[zlib.git] / deflate.c
1 /* deflate.c -- compress data using the deflation algorithm
2  * Copyright (C) 1995 Jean-loup Gailly.
3  * For conditions of distribution and use, see copyright notice in zlib.h 
4  */
5
6 /*
7  *  ALGORITHM
8  *
9  *      The "deflation" process depends on being able to identify portions
10  *      of the input text which are identical to earlier input (within a
11  *      sliding window trailing behind the input currently being processed).
12  *
13  *      The most straightforward technique turns out to be the fastest for
14  *      most input files: try all possible matches and select the longest.
15  *      The key feature of this algorithm is that insertions into the string
16  *      dictionary are very simple and thus fast, and deletions are avoided
17  *      completely. Insertions are performed at each input character, whereas
18  *      string matches are performed only when the previous match ends. So it
19  *      is preferable to spend more time in matches to allow very fast string
20  *      insertions and avoid deletions. The matching algorithm for small
21  *      strings is inspired from that of Rabin & Karp. A brute force approach
22  *      is used to find longer strings when a small match has been found.
23  *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
24  *      (by Leonid Broukhis).
25  *         A previous version of this file used a more sophisticated algorithm
26  *      (by Fiala and Greene) which is guaranteed to run in linear amortized
27  *      time, but has a larger average cost, uses more memory and is patented.
28  *      However the F&G algorithm may be faster for some highly redundant
29  *      files if the parameter max_chain_length (described below) is too large.
30  *
31  *  ACKNOWLEDGEMENTS
32  *
33  *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
34  *      I found it in 'freeze' written by Leonid Broukhis.
35  *      Thanks to many people for bug reports and testing.
36  *
37  *  REFERENCES
38  *
39  *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
40  *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
41  *
42  *      A description of the Rabin and Karp algorithm is given in the book
43  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
44  *
45  *      Fiala,E.R., and Greene,D.H.
46  *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
47  *
48  */
49
50 /* $Id: deflate.c,v 1.5 1995/04/29 16:52:05 jloup Exp $ */
51
52 #include "deflate.h"
53
54 char copyright[] = " deflate Copyright 1995 Jean-loup Gailly ";
55 /*
56   If you use the zlib library in a product, an acknowledgment is welcome
57   in the documentation of your product. If for some reason you cannot
58   include such an acknowledgment, I would appreciate that you keep this
59   copyright string in the executable of your product.
60  */
61
62 #define NIL 0
63 /* Tail of hash chains */
64
65 #ifndef TOO_FAR
66 #  define TOO_FAR 4096
67 #endif
68 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
69
70 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
71 /* Minimum amount of lookahead, except at the end of the input file.
72  * See deflate.c for comments about the MIN_MATCH+1.
73  */
74
75 /* Values for max_lazy_match, good_match and max_chain_length, depending on
76  * the desired pack level (0..9). The values given below have been tuned to
77  * exclude worst case performance for pathological files. Better values may be
78  * found for specific files.
79  */
80
81 typedef struct config_s {
82    ush good_length; /* reduce lazy search above this match length */
83    ush max_lazy;    /* do not perform lazy search above this match length */
84    ush nice_length; /* quit search above this match length */
85    ush max_chain;
86 } config;
87
88 local config configuration_table[10] = {
89 /*      good lazy nice chain */
90 /* 0 */ {0,    0,  0,    0},  /* store only */
91 /* 1 */ {4,    4,  8,    4},  /* maximum speed, no lazy matches */
92 /* 2 */ {4,    5, 16,    8},
93 /* 3 */ {4,    6, 32,   32},
94
95 /* 4 */ {4,    4, 16,   16},  /* lazy matches */
96 /* 5 */ {8,   16, 32,   32},
97 /* 6 */ {8,   16, 128, 128},
98 /* 7 */ {8,   32, 128, 256},
99 /* 8 */ {32, 128, 258, 1024},
100 /* 9 */ {32, 258, 258, 4096}}; /* maximum compression */
101
102 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
103  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
104  * meaning.
105  */
106
107 #define EQUAL 0
108 /* result of memcmp for equal strings */
109
110 struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
111
112 /* ===========================================================================
113  *  Prototypes for local functions.
114  */
115
116 local void fill_window   __P((deflate_state *s));
117 local int  deflate_fast  __P((deflate_state *s, int flush));
118 local int  deflate_slow  __P((deflate_state *s, int flush));
119 local void lm_init       __P((deflate_state *s));
120 local int  longest_match __P((deflate_state *s, IPos cur_match));
121 local void putShortMSB   __P((deflate_state *s, uInt b));
122 local void flush_pending __P((z_stream *strm));
123 local int read_buf       __P((z_stream *strm, char *buf, unsigned size));
124 #ifdef ASMV
125       void match_init __P((void)); /* asm code initialization */
126 #endif
127
128 #ifdef DEBUG
129 local  void check_match __P((deflate_state *s, IPos start, IPos match,
130                              int length));
131 #endif
132
133
134 /* ===========================================================================
135  * Update a hash value with the given input byte
136  * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
137  *    input characters, so that a running hash key can be computed from the
138  *    previous key instead of complete recalculation each time.
139  */
140 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
141
142 /* ===========================================================================
143  * Insert string str in the dictionary and set match_head to the previous head
144  * of the hash chain (the most recent string with same hash key). Return
145  * the previous length of the hash chain.
146  * IN  assertion: all calls to to INSERT_STRING are made with consecutive
147  *    input characters and the first MIN_MATCH bytes of str are valid
148  *    (except for the last MIN_MATCH-1 bytes of the input file).
149  */
150 #define INSERT_STRING(s, str, match_head) \
151    (UPDATE_HASH(s, s->ins_h, s->window[(str) + MIN_MATCH-1]), \
152     s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \
153     s->head[s->ins_h] = (str))
154
155 /* ========================================================================= */
156 int deflateInit (strm, level)
157     z_stream *strm;
158     int level;
159 {
160     return deflateInit2 (strm, level, DEFLATED, WBITS, MEM_LEVEL, 0);
161     /* To do: ignore strm->next_in if we use it as window */
162 }
163
164 /* ========================================================================= */
165 int deflateInit2 (strm, level, method, windowBits, memLevel, strategy)
166     z_stream *strm;
167     int  level;
168     int  method;
169     int  windowBits;
170     int  memLevel;
171     int  strategy;
172 {
173     deflate_state *s;
174     int noheader = 0;
175
176     if (strm == Z_NULL) return Z_STREAM_ERROR;
177
178     strm->msg = Z_NULL;
179     if (strm->zalloc == Z_NULL) strm->zalloc = zcalloc;
180     if (strm->zfree == Z_NULL) strm->zfree = zcfree;
181
182     if (level == Z_DEFAULT_COMPRESSION) level = 6;
183
184     if (windowBits < 0) { /* undocumented feature: suppress zlib header */
185         noheader = 1;
186         windowBits = -windowBits;
187     }
188     if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != DEFLATED ||
189         windowBits < 8 || windowBits > 15 || level < 1 || level > 9) {
190         return Z_STREAM_ERROR;
191     }
192     s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
193     if (s == Z_NULL) return Z_MEM_ERROR;
194     strm->state = (struct internal_state *)s;
195     s->strm = strm;
196
197     s->noheader = noheader;
198     s->w_bits = windowBits;
199     s->w_size = 1 << s->w_bits;
200     s->w_mask = s->w_size - 1;
201
202     s->hash_bits = memLevel + 7;
203     s->hash_size = 1 << s->hash_bits;
204     s->hash_mask = s->hash_size - 1;
205     s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
206
207     s->window = (Byte*) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
208     s->prev   = (Pos*)  ZALLOC(strm, s->w_size, sizeof(Pos));
209     s->head   = (Pos*)  ZALLOC(strm, s->hash_size, sizeof(Pos));
210
211     s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
212
213     s->pending_buf = (uch*) ZALLOC(strm, s->lit_bufsize, 2*sizeof(ush));
214
215     if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
216         s->pending_buf == Z_NULL) {
217         strm->msg = z_errmsg[1-Z_MEM_ERROR];
218         deflateEnd (strm);
219         return Z_MEM_ERROR;
220     }
221     s->d_buf = (ush*) &(s->pending_buf[s->lit_bufsize]);
222     s->l_buf = (uch*) &(s->pending_buf[3*s->lit_bufsize]);
223     /* We overlay pending_buf and d_buf+l_buf. This works since the average
224      * output size for (length,distance) codes is <= 32 bits (worst case
225      * is 15+15+13=33).
226      */
227
228     s->level = level;
229     s->strategy = strategy;
230     s->method = (Byte)method;
231
232     return deflateReset(strm);
233 }
234
235 /* ========================================================================= */
236 int deflateReset (strm)
237     z_stream *strm;
238 {
239     deflate_state *s;
240     
241     if (strm == Z_NULL || strm->state == Z_NULL ||
242         strm->zalloc == Z_NULL || strm->zfree == Z_NULL) return Z_STREAM_ERROR;
243
244     strm->total_in = strm->total_out = 0;
245     strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
246     strm->data_type = Z_UNKNOWN;
247
248     s = (deflate_state *)strm->state;
249     s->pending = 0;
250     s->pending_out = s->pending_buf;
251
252     s->status = s->noheader ? BUSY_STATE : INIT_STATE;
253     s->adler = 1;
254
255     ct_init(s);
256     lm_init(s);
257
258     return Z_OK;
259 }
260
261 /* =========================================================================
262  * Put a short the pending_out buffer. The 16-bit value is put in MSB order.
263  * IN assertion: the stream state is correct and there is enough room in
264  * the pending_out buffer.
265  */
266 local void putShortMSB (s, b)
267     deflate_state *s;
268     uInt b;
269 {
270     put_byte(s, (Byte)(b >> 8));
271     put_byte(s, (Byte)(b & 0xff));
272 }   
273
274 /* =========================================================================
275  * Flush as much pending output as possible.
276  */
277 local void flush_pending(strm)
278     z_stream *strm;
279 {
280     unsigned len = strm->state->pending;
281
282     if (len > strm->avail_out) len = strm->avail_out;
283     if (len == 0) return;
284
285     zmemcpy(strm->next_out, strm->state->pending_out, len);
286     strm->next_out  += len;
287     strm->state->pending_out  += len;
288     strm->total_out += len;
289     strm->avail_out  -= len;
290     strm->state->pending -= len;
291     if (strm->state->pending == 0) {
292         strm->state->pending_out = strm->state->pending_buf;
293     }
294 }
295
296 /* ========================================================================= */
297 int deflate (strm, flush)
298     z_stream *strm;
299     int flush;
300 {
301     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
302     
303     if (strm->next_out == Z_NULL || strm->next_in == Z_NULL) {
304         ERR_RETURN(strm, Z_STREAM_ERROR);
305     }
306     if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
307
308     strm->state->strm = strm; /* just in case */
309
310     /* Write the zlib header */
311     if (strm->state->status == INIT_STATE) {
312
313         uInt header = (DEFLATED + ((strm->state->w_bits-8)<<4)) << 8;
314         uInt level_flags = (strm->state->level-1) >> 1;
315
316         if (level_flags > 3) level_flags = 3;
317         header |= (level_flags << 6);
318         header += 31 - (header % 31);
319
320         strm->state->status = BUSY_STATE;
321         putShortMSB(strm->state, header);
322     }
323
324     /* Flush as much pending output as possible */
325     if (strm->state->pending != 0) {
326         flush_pending(strm);
327         if (strm->avail_out == 0) return Z_OK;
328     }
329
330     /* User must not provide more input after the first FINISH: */
331     if (strm->state->status == FINISH_STATE && strm->avail_in != 0) {
332         ERR_RETURN(strm, Z_BUF_ERROR);
333     }
334
335     /* Start a new block or continue the current one.
336      */
337     if (strm->avail_in != 0 ||
338         (flush == Z_FINISH && strm->state->status != FINISH_STATE)) {
339         
340         if (flush == Z_FINISH) {
341             strm->state->status = FINISH_STATE;
342         }
343         if (strm->state->level <= 3) {
344             if (deflate_fast(strm->state, flush)) return Z_OK;
345         } else {
346             if (deflate_slow(strm->state, flush)) return Z_OK;
347         }
348     }
349     Assert(strm->avail_out > 0, "bug2");
350
351     if (flush != Z_FINISH) return Z_OK;
352     if (strm->state->noheader) return Z_STREAM_END;
353
354     /* Write the zlib trailer (adler32) */
355     putShortMSB(strm->state, (uInt)(strm->state->adler >> 16));
356     putShortMSB(strm->state, (uInt)(strm->state->adler & 0xffff));
357     flush_pending(strm);
358     /* If avail_out is zero, the application will call deflate again
359      * to flush the rest.
360      */
361     strm->state->noheader = 1; /* write the trailer only once! */
362     return strm->state->pending != 0 ? Z_OK : Z_STREAM_END;
363 }
364
365 /* ========================================================================= */
366 int deflateEnd (strm)
367     z_stream *strm;
368 {
369     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
370
371     TRY_FREE(strm, strm->state->window);
372     TRY_FREE(strm, strm->state->prev);
373     TRY_FREE(strm, strm->state->head);
374     TRY_FREE(strm, strm->state->pending_buf);
375
376     ZFREE(strm, strm->state);
377     strm->state = Z_NULL;
378
379     return Z_OK;
380 }
381
382 /* ========================================================================= */
383 int deflateCopy (dest, source)
384     z_stream *dest;
385     z_stream *source;
386 {
387     if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
388         return Z_STREAM_ERROR;
389     }
390     *dest = *source;
391     return Z_STREAM_ERROR; /* to be implemented */
392 #if 0
393     dest->state = (struct internal_state *)
394         (*dest->zalloc)(1, sizeof(deflate_state));
395     if (dest->state == Z_NULL) return Z_MEM_ERROR;
396
397     *(dest->state) = *(source->state);
398     return Z_OK;
399 #endif
400 }
401
402 /* ===========================================================================
403  * Read a new buffer from the current input stream, update the adler32
404  * and total number of bytes read.
405  */
406 local int read_buf(strm, buf, size)
407     z_stream *strm;
408     char *buf;
409     unsigned size;
410 {
411     unsigned len = strm->avail_in;
412
413     if (len > size) len = size;
414     if (len == 0) return 0;
415
416     strm->avail_in  -= len;
417
418     if (!strm->state->noheader) {
419         strm->state->adler = adler32(strm->state->adler, strm->next_in, len);
420     }
421     zmemcpy(buf, strm->next_in, len);
422     strm->next_in  += len;
423     strm->total_in += len;
424
425     return (int)len;
426 }
427
428 /* ===========================================================================
429  * Initialize the "longest match" routines for a new zlib stream
430  */
431 local void lm_init (s)
432     deflate_state *s;
433 {
434     register unsigned j;
435
436     s->window_size = (ulg)2L*s->w_size;
437
438
439     /* Initialize the hash table (avoiding 64K overflow for 16 bit systems).
440      * prev[] will be initialized on the fly.
441      */
442     s->head[s->hash_size-1] = NIL;
443     zmemzero((char*)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
444
445     /* Set the default configuration parameters:
446      */
447     s->max_lazy_match   = configuration_table[s->level].max_lazy;
448     s->good_match       = configuration_table[s->level].good_length;
449     s->nice_match       = configuration_table[s->level].nice_length;
450     s->max_chain_length = configuration_table[s->level].max_chain;
451
452     s->strstart = 0;
453     s->block_start = 0L;
454     s->lookahead = 0;
455     s->match_length = MIN_MATCH-1;
456     s->match_available = 0;
457 #ifdef ASMV
458     match_init(); /* initialize the asm code */
459 #endif
460
461     s->ins_h = 0;
462     for (j=0; j<MIN_MATCH-1; j++) UPDATE_HASH(s, s->ins_h, s->window[j]);
463     /* If lookahead < MIN_MATCH, ins_h is garbage, but this is
464      * not important since only literal bytes will be emitted.
465      */
466 }
467
468 /* ===========================================================================
469  * Set match_start to the longest match starting at the given string and
470  * return its length. Matches shorter or equal to prev_length are discarded,
471  * in which case the result is equal to prev_length and match_start is
472  * garbage.
473  * IN assertions: cur_match is the head of the hash chain for the current
474  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
475  */
476 #ifndef ASMV
477 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
478  * match.S. The code will be functionally equivalent.
479  */
480 local int longest_match(s, cur_match)
481     deflate_state *s;
482     IPos cur_match;                             /* current match */
483 {
484     unsigned chain_length = s->max_chain_length;/* max hash chain length */
485     register Byte *scan = s->window + s->strstart; /* current string */
486     register Byte *match;                       /* matched string */
487     register int len;                           /* length of current match */
488     int best_len = s->prev_length;              /* best match length so far */
489     IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
490         s->strstart - (IPos)MAX_DIST(s) : NIL;
491     /* Stop when cur_match becomes <= limit. To simplify the code,
492      * we prevent matches with the string of window index 0.
493      */
494
495 #ifdef UNALIGNED_OK
496     /* Compare two bytes at a time. Note: this is not always beneficial.
497      * Try with and without -DUNALIGNED_OK to check.
498      */
499     register Byte *strend = s->window + s->strstart + MAX_MATCH - 1;
500     register ush scan_start = *(ush*)scan;
501     register ush scan_end   = *(ush*)(scan+best_len-1);
502 #else
503     register Byte *strend = s->window + s->strstart + MAX_MATCH;
504     register Byte scan_end1  = scan[best_len-1];
505     register Byte scan_end   = scan[best_len];
506 #endif
507
508     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
509      * It is easy to get rid of this optimization if necessary.
510      */
511     Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
512
513     /* Do not waste too much time if we already have a good match: */
514     if (s->prev_length >= s->good_match) {
515         chain_length >>= 2;
516     }
517     Assert(s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
518
519     do {
520         Assert(cur_match < s->strstart, "no future");
521         match = s->window + cur_match;
522
523         /* Skip to next match if the match length cannot increase
524          * or if the match length is less than 2:
525          */
526 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
527         /* This code assumes sizeof(unsigned short) == 2. Do not use
528          * UNALIGNED_OK if your compiler uses a different size.
529          */
530         if (*(ush*)(match+best_len-1) != scan_end ||
531             *(ush*)match != scan_start) continue;
532
533         /* It is not necessary to compare scan[2] and match[2] since they are
534          * always equal when the other bytes match, given that the hash keys
535          * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
536          * strstart+3, +5, ... up to strstart+257. We check for insufficient
537          * lookahead only every 4th comparison; the 128th check will be made
538          * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
539          * necessary to put more guard bytes at the end of the window, or
540          * to check more often for insufficient lookahead.
541          */
542         scan++, match++;
543         do {
544         } while (*(ush*)(scan+=2) == *(ush*)(match+=2) &&
545                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
546                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
547                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
548                  scan < strend);
549         /* The funny "do {}" generates better code on most compilers */
550
551         /* Here, scan <= window+strstart+257 */
552         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
553         if (*scan == *match) scan++;
554
555         len = (MAX_MATCH - 1) - (int)(strend-scan);
556         scan = strend - (MAX_MATCH-1);
557
558 #else /* UNALIGNED_OK */
559
560         if (match[best_len]   != scan_end  ||
561             match[best_len-1] != scan_end1 ||
562             *match            != *scan     ||
563             *++match          != scan[1])      continue;
564
565         /* The check at best_len-1 can be removed because it will be made
566          * again later. (This heuristic is not always a win.)
567          * It is not necessary to compare scan[2] and match[2] since they
568          * are always equal when the other bytes match, given that
569          * the hash keys are equal and that HASH_BITS >= 8.
570          */
571         scan += 2, match++;
572
573         /* We check for insufficient lookahead only every 8th comparison;
574          * the 256th check will be made at strstart+258.
575          */
576         do {
577         } while (*++scan == *++match && *++scan == *++match &&
578                  *++scan == *++match && *++scan == *++match &&
579                  *++scan == *++match && *++scan == *++match &&
580                  *++scan == *++match && *++scan == *++match &&
581                  scan < strend);
582
583         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
584
585         len = MAX_MATCH - (int)(strend - scan);
586         scan = strend - MAX_MATCH;
587
588 #endif /* UNALIGNED_OK */
589
590         if (len > best_len) {
591             s->match_start = cur_match;
592             best_len = len;
593             if (len >= s->nice_match) break;
594 #ifdef UNALIGNED_OK
595             scan_end = *(ush*)(scan+best_len-1);
596 #else
597             scan_end1  = scan[best_len-1];
598             scan_end   = scan[best_len];
599 #endif
600         }
601     } while ((cur_match = s->prev[cur_match & s->w_mask]) > limit
602              && --chain_length != 0);
603
604     return best_len;
605 }
606 #endif /* ASMV */
607
608 #ifdef DEBUG
609 /* ===========================================================================
610  * Check that the match at match_start is indeed a match.
611  */
612 local void check_match(s, start, match, length)
613     deflate_state *s;
614     IPos start, match;
615     int length;
616 {
617     /* check that the match is indeed a match */
618     if (memcmp((char*)s->window + match,
619                 (char*)s->window + start, length) != EQUAL) {
620         fprintf(stderr,
621             " start %d, match %d, length %d\n",
622             start, match, length);
623         z_error("invalid match");
624     }
625     if (verbose > 1) {
626         fprintf(stderr,"\\[%d,%d]", start-match, length);
627         do { putc(s->window[start++], stderr); } while (--length != 0);
628     }
629 }
630 #else
631 #  define check_match(s, start, match, length)
632 #endif
633
634 /* ===========================================================================
635  * Fill the window when the lookahead becomes insufficient.
636  * Updates strstart and lookahead.
637  *
638  * IN assertion: lookahead < MIN_LOOKAHEAD
639  * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
640  *    At least one byte has been read, or avail_in == 0; reads are
641  *    performed for at least two bytes (required for the zip translate_eol
642  *    option -- not supported here).
643  */
644 local void fill_window(s)
645     deflate_state *s;
646 {
647     register unsigned n, m;
648     unsigned more;    /* Amount of free space at the end of the window. */
649
650     do {
651         more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
652
653         /* Deal with !@#$% 64K limit: */
654         if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
655             more = s->w_size;
656         } else if (more == (unsigned)(-1)) {
657             /* Very unlikely, but possible on 16 bit machine if strstart == 0
658              * and lookahead == 1 (input done one byte at time)
659              */
660             more--;
661
662         /* If the window is almost full and there is insufficient lookahead,
663          * move the upper half to the lower one to make room in the upper half.
664          */
665         } else if (s->strstart >= s->w_size+MAX_DIST(s)) {
666
667             /* By the IN assertion, the window is not empty so we can't confuse
668              * more == 0 with more == 64K on a 16 bit machine.
669              */
670             memcpy((char*)s->window, (char*)s->window+s->w_size,
671                    (unsigned)s->w_size);
672             s->match_start -= s->w_size;
673             s->strstart    -= s->w_size; /* we now have strstart >= MAX_DIST */
674
675             s->block_start -= (long) s->w_size;
676
677             for (n = 0; n < s->hash_size; n++) {
678                 m = s->head[n];
679                 s->head[n] = (Pos)(m >= s->w_size ? m-s->w_size : NIL);
680             }
681             for (n = 0; n < s->w_size; n++) {
682                 m = s->prev[n];
683                 s->prev[n] = (Pos)(m >= s->w_size ? m-s->w_size : NIL);
684                 /* If n is not on any hash chain, prev[n] is garbage but
685                  * its value will never be used.
686                  */
687             }
688             more += s->w_size;
689         }
690         if (s->strm->avail_in == 0) return;
691
692         /* If there was no sliding:
693          *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
694          *    more == window_size - lookahead - strstart
695          * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
696          * => more >= window_size - 2*WSIZE + 2
697          * In the BIG_MEM or MMAP case (not yet supported),
698          *   window_size == input_size + MIN_LOOKAHEAD  &&
699          *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
700          * Otherwise, window_size == 2*WSIZE so more >= 2.
701          * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
702          */
703         Assert(more >= 2, "more < 2");
704
705         n = read_buf(s->strm, (char*)s->window + s->strstart + s->lookahead,
706                      more);
707         s->lookahead += n;
708
709     } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
710 }
711
712 /* ===========================================================================
713  * Flush the current block, with given end-of-file flag.
714  * IN assertion: strstart is set to the end of the current match.
715  */
716 #define FLUSH_BLOCK_ONLY(s, eof) { \
717    ct_flush_block(s, (s->block_start >= 0L ? \
718                (char*)&s->window[(unsigned)s->block_start] : \
719                (char*)Z_NULL), (long)s->strstart - s->block_start, (eof)); \
720    s->block_start = s->strstart; \
721    flush_pending(s->strm); \
722 }
723
724 /* Same but force premature exit if necessary. */
725 #define FLUSH_BLOCK(s, eof) { \
726    FLUSH_BLOCK_ONLY(s, eof); \
727    if (s->strm->avail_out == 0) return 1; \
728 }
729
730 /* ===========================================================================
731  * Compress as much as possible from the input stream, return true if
732  * processing was terminated prematurely (no more input or output space).
733  * This function does not perform lazy evaluationof matches and inserts
734  * new strings in the dictionary only for unmatched strings or for short
735  * matches. It is used only for the fast compression options.
736  */
737 local int deflate_fast(s, flush)
738     deflate_state *s;
739     int flush;
740 {
741     IPos hash_head; /* head of the hash chain */
742     int bflush;     /* set if current block must be flushed */
743
744     s->prev_length = MIN_MATCH-1;
745
746     for (;;) {
747         /* Make sure that we always have enough lookahead, except
748          * at the end of the input file. We need MAX_MATCH bytes
749          * for the next match, plus MIN_MATCH bytes to insert the
750          * string following the next match.
751          */
752         if (s->lookahead < MIN_LOOKAHEAD) {
753             fill_window(s);
754             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) return 1;
755
756             if (s->lookahead == 0) break; /* flush the current block */
757         }
758
759         /* Insert the string window[strstart .. strstart+2] in the
760          * dictionary, and set hash_head to the head of the hash chain:
761          */
762         INSERT_STRING(s, s->strstart, hash_head);
763
764         /* Find the longest match, discarding those <= prev_length.
765          * At this point we have always match_length < MIN_MATCH
766          */
767         if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
768             /* To simplify the code, we prevent matches with the string
769              * of window index 0 (in particular we have to avoid a match
770              * of the string with itself at the start of the input file).
771              */
772             if (s->strategy != Z_HUFFMAN_ONLY) {
773                 s->match_length = longest_match (s, hash_head);
774             }
775             /* longest_match() sets match_start */
776
777             if (s->match_length > s->lookahead) s->match_length = s->lookahead;
778         }
779         if (s->match_length >= MIN_MATCH) {
780             check_match(s, s->strstart, s->match_start, s->match_length);
781
782             bflush = ct_tally(s, s->strstart - s->match_start,
783                               s->match_length - MIN_MATCH);
784
785             s->lookahead -= s->match_length;
786
787             /* Insert new strings in the hash table only if the match length
788              * is not too large. This saves time but degrades compression.
789              */
790             if (s->match_length <= s->max_insert_length) {
791                 s->match_length--; /* string at strstart already in hash table */
792                 do {
793                     s->strstart++;
794                     INSERT_STRING(s, s->strstart, hash_head);
795                     /* strstart never exceeds WSIZE-MAX_MATCH, so there are
796                      * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
797                      * these bytes are garbage, but it does not matter since
798                      * the next lookahead bytes will be emitted as literals.
799                      */
800                 } while (--s->match_length != 0);
801                 s->strstart++; 
802             } else {
803                 s->strstart += s->match_length;
804                 s->match_length = 0;
805                 s->ins_h = s->window[s->strstart];
806                 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
807 #if MIN_MATCH != 3
808                 Call UPDATE_HASH() MIN_MATCH-3 more times
809 #endif
810             }
811         } else {
812             /* No match, output a literal byte */
813             Tracevv((stderr,"%c", s->window[s->strstart]));
814             bflush = ct_tally (s, 0, s->window[s->strstart]);
815             s->lookahead--;
816             s->strstart++; 
817         }
818         if (bflush) FLUSH_BLOCK(s, 0);
819     }
820     FLUSH_BLOCK(s, flush == Z_FINISH);
821     return 0; /* normal exit */
822 }
823
824 /* ===========================================================================
825  * Same as above, but achieves better compression. We use a lazy
826  * evaluation for matches: a match is finally adopted only if there is
827  * no better match at the next window position.
828  */
829 local int deflate_slow(s, flush)
830     deflate_state *s;
831     int flush;
832 {
833     IPos hash_head;          /* head of hash chain */
834     int bflush;              /* set if current block must be flushed */
835
836     /* Process the input block. */
837     for (;;) {
838         /* Make sure that we always have enough lookahead, except
839          * at the end of the input file. We need MAX_MATCH bytes
840          * for the next match, plus MIN_MATCH bytes to insert the
841          * string following the next match.
842          */
843         if (s->lookahead < MIN_LOOKAHEAD) {
844             fill_window(s);
845             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) return 1;
846
847             if (s->lookahead == 0) break; /* flush the current block */
848         }
849
850         /* Insert the string window[strstart .. strstart+2] in the
851          * dictionary, and set hash_head to the head of the hash chain:
852          */
853         INSERT_STRING(s, s->strstart, hash_head);
854
855         /* Find the longest match, discarding those <= prev_length.
856          */
857         s->prev_length = s->match_length, s->prev_match = s->match_start;
858         s->match_length = MIN_MATCH-1;
859
860         if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
861             s->strstart - hash_head <= MAX_DIST(s)) {
862             /* To simplify the code, we prevent matches with the string
863              * of window index 0 (in particular we have to avoid a match
864              * of the string with itself at the start of the input file).
865              */
866             if (s->strategy != Z_HUFFMAN_ONLY) {
867                 s->match_length = longest_match (s, hash_head);
868             }
869             /* longest_match() sets match_start */
870             if (s->match_length > s->lookahead) s->match_length = s->lookahead;
871
872             if (s->match_length <= 5 && (s->strategy == Z_FILTERED ||
873                  (s->match_length == MIN_MATCH &&
874                   s->strstart - s->match_start > TOO_FAR))) {
875
876                 /* If prev_match is also MIN_MATCH, match_start is garbage
877                  * but we will ignore the current match anyway.
878                  */
879                 s->match_length = MIN_MATCH-1;
880             }
881         }
882         /* If there was a match at the previous step and the current
883          * match is not better, output the previous match:
884          */
885         if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
886
887             check_match(s, s->strstart-1, s->prev_match, s->prev_length);
888
889             bflush = ct_tally(s, s->strstart -1 - s->prev_match,
890                               s->prev_length - MIN_MATCH);
891
892             /* Insert in hash table all strings up to the end of the match.
893              * strstart-1 and strstart are already inserted.
894              */
895             s->lookahead -= s->prev_length-1;
896             s->prev_length -= 2;
897             do {
898                 s->strstart++;
899                 INSERT_STRING(s, s->strstart, hash_head);
900                 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
901                  * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
902                  * these bytes are garbage, but it does not matter since the
903                  * next lookahead bytes will always be emitted as literals.
904                  */
905             } while (--s->prev_length != 0);
906             s->match_available = 0;
907             s->match_length = MIN_MATCH-1;
908             s->strstart++;
909
910             if (bflush) FLUSH_BLOCK(s, 0);
911
912         } else if (s->match_available) {
913             /* If there was no match at the previous position, output a
914              * single literal. If there was a match but the current match
915              * is longer, truncate the previous match to a single literal.
916              */
917             Tracevv((stderr,"%c", s->window[s->strstart-1]));
918             if (ct_tally (s, 0, s->window[s->strstart-1])) {
919                 FLUSH_BLOCK_ONLY(s, 0);
920             }
921             s->strstart++;
922             s->lookahead--;
923             if (s->strm->avail_out == 0) return 1;
924         } else {
925             /* There is no previous match to compare with, wait for
926              * the next step to decide.
927              */
928             s->match_available = 1;
929             s->strstart++;
930             s->lookahead--;
931         }
932     }
933     if (s->match_available) ct_tally (s, 0, s->window[s->strstart-1]);
934
935     FLUSH_BLOCK(s, flush == Z_FINISH);
936     return 0;
937 }