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