root/cherokee/trunk/cherokee/zlib/deflate.c

Revision 1, 43.5 kB (checked in by alo, 4 years ago)

--

Line 
1 /* +++ deflate.c */
2 /* deflate.c -- compress data using the deflation algorithm
3  * Copyright (C) 1995-1996 Jean-loup Gailly.
4  * For conditions of distribution and use, see copyright notice in zlib.h
5  */
6
7 /*
8  *  ALGORITHM
9  *
10  *      The "deflation" process depends on being able to identify portions
11  *      of the input text which are identical to earlier input (within a
12  *      sliding window trailing behind the input currently being processed).
13  *
14  *      The most straightforward technique turns out to be the fastest for
15  *      most input files: try all possible matches and select the longest.
16  *      The key feature of this algorithm is that insertions into the string
17  *      dictionary are very simple and thus fast, and deletions are avoided
18  *      completely. Insertions are performed at each input character, whereas
19  *      string matches are performed only when the previous match ends. So it
20  *      is preferable to spend more time in matches to allow very fast string
21  *      insertions and avoid deletions. The matching algorithm for small
22  *      strings is inspired from that of Rabin & Karp. A brute force approach
23  *      is used to find longer strings when a small match has been found.
24  *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
25  *      (by Leonid Broukhis).
26  *         A previous version of this file used a more sophisticated algorithm
27  *      (by Fiala and Greene) which is guaranteed to run in linear amortized
28  *      time, but has a larger average cost, uses more memory and is patented.
29  *      However the F&G algorithm may be faster for some highly redundant
30  *      files if the parameter max_chain_length (described below) is too large.
31  *
32  *  ACKNOWLEDGEMENTS
33  *
34  *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
35  *      I found it in 'freeze' written by Leonid Broukhis.
36  *      Thanks to many people for bug reports and testing.
37  *
38  *  REFERENCES
39  *
40  *      Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
41  *      Available in ftp://ds.internic.net/rfc/rfc1951.txt
42  *
43  *      A description of the Rabin and Karp algorithm is given in the book
44  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
45  *
46  *      Fiala,E.R., and Greene,D.H.
47  *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
48  *
49  */
50
51 #include "zutil.h"
52 #include "defutil.h"
53
54
55 /* ===========================================================================
56  *  Function prototypes.
57  */
58 typedef enum {
59     need_more,      /* block not completed, need more input or more output */
60     block_done,     /* block flush performed */
61     finish_started, /* finish started, need only more output at next deflate */
62     finish_done     /* finish done, accept no more input or output */
63 } block_state;
64
65 typedef block_state (*compress_func) (deflate_state *s, int flush);
66 /* Compression function. Returns the block state after the call. */
67
68 static void fill_window    (deflate_state *s);
69 static block_state deflate_stored (deflate_state *s, int flush);
70 static block_state deflate_fast   (deflate_state *s, int flush);
71 static block_state deflate_slow   (deflate_state *s, int flush);
72 static void lm_init        (deflate_state *s);
73 static void putShortMSB    (deflate_state *s, uInt b);
74 static void flush_pending  (z_streamp strm);
75 static int read_buf        (z_streamp strm, Byte *buf, unsigned size);
76 static uInt longest_match  (deflate_state *s, IPos cur_match);
77
78 #ifdef DEBUG_ZLIB
79 static  void check_match (deflate_state *s, IPos start, IPos match,
80                          int length);
81 #endif
82
83 /* ===========================================================================
84  * Local data
85  */
86
87 #define NIL 0
88 /* Tail of hash chains */
89
90 #ifndef TOO_FAR
91 #  define TOO_FAR 4096
92 #endif
93 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
94
95 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
96 /* Minimum amount of lookahead, except at the end of the input file.
97  * See deflate.c for comments about the MIN_MATCH+1.
98  */
99
100 /* Values for max_lazy_match, good_match and max_chain_length, depending on
101  * the desired pack level (0..9). The values given below have been tuned to
102  * exclude worst case performance for pathological files. Better values may be
103  * found for specific files.
104  */
105 typedef struct config_s {
106    ush good_length; /* reduce lazy search above this match length */
107    ush max_lazy;    /* do not perform lazy search above this match length */
108    ush nice_length; /* quit search above this match length */
109    ush max_chain;
110    compress_func func;
111 } config;
112
113 static const config configuration_table[10] = {
114 /*      good lazy nice chain */
115 /* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
116 /* 1 */ {4,    4,  8,    4, deflate_fast}, /* maximum speed, no lazy matches */
117 /* 2 */ {4,    5, 16,    8, deflate_fast},
118 /* 3 */ {4,    6, 32,   32, deflate_fast},
119
120 /* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
121 /* 5 */ {8,   16, 32,   32, deflate_slow},
122 /* 6 */ {8,   16, 128, 128, deflate_slow},
123 /* 7 */ {8,   32, 128, 256, deflate_slow},
124 /* 8 */ {32, 128, 258, 1024, deflate_slow},
125 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* maximum compression */
126
127 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
128  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
129  * meaning.
130  */
131
132 #define EQUAL 0
133 /* result of memcmp for equal strings */
134
135 /* ===========================================================================
136  * Update a hash value with the given input byte
137  * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
138  *    input characters, so that a running hash key can be computed from the
139  *    previous key instead of complete recalculation each time.
140  */
141 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
142
143
144 /* ===========================================================================
145  * Insert string str in the dictionary and set match_head to the previous head
146  * of the hash chain (the most recent string with same hash key). Return
147  * the previous length of the hash chain.
148  * IN  assertion: all calls to to INSERT_STRING are made with consecutive
149  *    input characters and the first MIN_MATCH bytes of str are valid
150  *    (except for the last MIN_MATCH-1 bytes of the input file).
151  */
152 #define INSERT_STRING(s, str, match_head) \
153    (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
154     s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \
155     s->head[s->ins_h] = (Pos)(str))
156
157 /* ===========================================================================
158  * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
159  * prev[] will be initialized on the fly.
160  */
161 #define CLEAR_HASH(s) \
162     s->head[s->hash_size-1] = NIL; \
163     memset((char *)s->head, 0, (unsigned)(s->hash_size-1)*sizeof(*s->head));
164
165 /* ========================================================================= */
166 int zlib_deflateInit_(
167         z_streamp strm,
168         int level,
169         const char *version,
170         int stream_size
171 )
172 {
173     return zlib_deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS,
174                               DEF_MEM_LEVEL,
175                               Z_DEFAULT_STRATEGY, version, stream_size);
176     /* To do: ignore strm->next_in if we use it as window */
177 }
178
179 /* ========================================================================= */
180 int zlib_deflateInit2_(
181         z_streamp strm,
182         int  level,
183         int  method,
184         int  windowBits,
185         int  memLevel,
186         int  strategy,
187         const char *version,
188         int stream_size
189 )
190 {
191     deflate_state *s;
192     int noheader = 0;
193     static char* my_version = ZLIB_VERSION;
194     deflate_workspace *mem;
195
196     ush *overlay;
197     /* We overlay pending_buf and d_buf+l_buf. This works since the average
198      * output size for (length,distance) codes is <= 24 bits.
199      */
200
201     if (version == NULL || version[0] != my_version[0] ||
202         stream_size != sizeof(z_stream)) {
203         return Z_VERSION_ERROR;
204     }
205     if (strm == NULL) return Z_STREAM_ERROR;
206
207     strm->msg = NULL;
208
209     if (level == Z_DEFAULT_COMPRESSION) level = 6;
210
211     mem = (deflate_workspace *) strm->workspace;
212
213     if (windowBits < 0) { /* undocumented feature: suppress zlib header */
214         noheader = 1;
215         windowBits = -windowBits;
216     }
217     if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
218         windowBits < 9 || windowBits > 15 || level < 0 || level > 9 ||
219         strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
220         return Z_STREAM_ERROR;
221     }
222     s = (deflate_state *) &(mem->deflate_memory);
223     strm->state = (struct internal_state *)s;
224     s->strm = strm;
225
226     s->noheader = noheader;
227     s->w_bits = windowBits;
228     s->w_size = 1 << s->w_bits;
229     s->w_mask = s->w_size - 1;
230
231     s->hash_bits = memLevel + 7;
232     s->hash_size = 1 << s->hash_bits;
233     s->hash_mask = s->hash_size - 1;
234     s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
235
236     s->window = (Byte *) mem->window_memory;
237     s->prev   = (Pos *)  mem->prev_memory;
238     s->head   = (Pos *)  mem->head_memory;
239
240     s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
241
242     overlay = (ush *) mem->overlay_memory;
243     s->pending_buf = (uch *) overlay;
244     s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
245
246     s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
247     s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
248
249     s->level = level;
250     s->strategy = strategy;
251     s->method = (Byte)method;
252
253     return zlib_deflateReset(strm);
254 }
255
256 /* ========================================================================= */
257 int zlib_deflateSetDictionary(
258         z_streamp strm,
259         const Byte *dictionary,
260         uInt  dictLength
261 )
262 {
263     deflate_state *s;
264     uInt length = dictLength;
265     uInt n;
266     IPos hash_head = 0;
267
268     if (strm == NULL || strm->state == NULL || dictionary == NULL)
269         return Z_STREAM_ERROR;
270
271     s = (deflate_state *) strm->state;
272     if (s->status != INIT_STATE) return Z_STREAM_ERROR;
273
274     strm->adler = zlib_adler32(strm->adler, dictionary, dictLength);
275
276     if (length < MIN_MATCH) return Z_OK;
277     if (length > MAX_DIST(s)) {
278         length = MAX_DIST(s);
279 #ifndef USE_DICT_HEAD
280         dictionary += dictLength - length; /* use the tail of the dictionary */
281 #endif
282     }
283     memcpy((char *)s->window, dictionary, length);
284     s->strstart = length;
285     s->block_start = (long)length;
286
287     /* Insert all strings in the hash table (except for the last two bytes).
288      * s->lookahead stays null, so s->ins_h will be recomputed at the next
289      * call of fill_window.
290      */
291     s->ins_h = s->window[0];
292     UPDATE_HASH(s, s->ins_h, s->window[1]);
293     for (n = 0; n <= length - MIN_MATCH; n++) {
294         INSERT_STRING(s, n, hash_head);
295     }
296     if (hash_head) hash_head = 0;  /* to make compiler happy */
297     return Z_OK;
298 }
299
300 /* ========================================================================= */
301 int zlib_deflateReset(
302         z_streamp strm
303 )
304 {
305     deflate_state *s;
306    
307     if (strm == NULL || strm->state == NULL)
308         return Z_STREAM_ERROR;
309
310     strm->total_in = strm->total_out = 0;
311     strm->msg = NULL;
312     strm->data_type = Z_UNKNOWN;
313
314     s = (deflate_state *)strm->state;
315     s->pending = 0;
316     s->pending_out = s->pending_buf;
317
318     if (s->noheader < 0) {
319         s->noheader = 0; /* was set to -1 by deflate(..., Z_FINISH); */
320     }
321     s->status = s->noheader ? BUSY_STATE : INIT_STATE;
322     strm->adler = 1;
323     s->last_flush = Z_NO_FLUSH;
324
325     zlib_tr_init(s);
326     lm_init(s);
327
328     return Z_OK;
329 }
330
331 /* ========================================================================= */
332 int zlib_deflateParams(
333         z_streamp strm,
334         int level,
335         int strategy
336 )
337 {
338     deflate_state *s;
339     compress_func func;
340     int err = Z_OK;
341
342     if (strm == NULL || strm->state == NULL) return Z_STREAM_ERROR;
343     s = (deflate_state *) strm->state;
344
345     if (level == Z_DEFAULT_COMPRESSION) {
346         level = 6;
347     }
348     if (level < 0 || level > 9 || strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
349         return Z_STREAM_ERROR;
350     }
351     func = configuration_table[s->level].func;
352
353     if (func != configuration_table[level].func && strm->total_in != 0) {
354         /* Flush the last buffer: */
355         err = zlib_deflate(strm, Z_PARTIAL_FLUSH);
356     }
357     if (s->level != level) {
358         s->level = level;
359         s->max_lazy_match   = configuration_table[level].max_lazy;
360         s->good_match       = configuration_table[level].good_length;
361         s->nice_match       = configuration_table[level].nice_length;
362         s->max_chain_length = configuration_table[level].max_chain;
363     }
364     s->strategy = strategy;
365     return err;
366 }
367
368 /* =========================================================================
369  * Put a short in the pending buffer. The 16-bit value is put in MSB order.
370  * IN assertion: the stream state is correct and there is enough room in
371  * pending_buf.
372  */
373 static void putShortMSB(
374         deflate_state *s,
375         uInt b
376 )
377 {
378     put_byte(s, (Byte)(b >> 8));
379     put_byte(s, (Byte)(b & 0xff));
380 }   
381
382 /* =========================================================================
383  * Flush as much pending output as possible. All deflate() output goes
384  * through this function so some applications may wish to modify it
385  * to avoid allocating a large strm->next_out buffer and copying into it.
386  * (See also read_buf()).
387  */
388 static void flush_pending(
389         z_streamp strm
390 )
391 {
392     deflate_state *s = (deflate_state *) strm->state;
393     unsigned len = s->pending;
394
395     if (len > strm->avail_out) len = strm->avail_out;
396     if (len == 0) return;
397
398     if (strm->next_out != NULL) {
399         memcpy(strm->next_out, s->pending_out, len);
400         strm->next_out += len;
401     }
402     s->pending_out += len;
403     strm->total_out += len;
404     strm->avail_out  -= len;
405     s->pending -= len;
406     if (s->pending == 0) {
407         s->pending_out = s->pending_buf;
408     }
409 }
410
411 /* ========================================================================= */
412 int zlib_deflate(
413         z_streamp strm,
414         int flush
415 )
416 {
417     int old_flush; /* value of flush param for previous deflate call */
418     deflate_state *s;
419
420     if (strm == NULL || strm->state == NULL ||
421         flush > Z_FINISH || flush < 0) {
422         return Z_STREAM_ERROR;
423     }
424     s = (deflate_state *) strm->state;
425
426     if ((strm->next_in == NULL && strm->avail_in != 0) ||
427         (s->status == FINISH_STATE && flush != Z_FINISH)) {
428         return Z_STREAM_ERROR;
429     }
430     if (strm->avail_out == 0) return Z_BUF_ERROR;
431
432     s->strm = strm; /* just in case */
433     old_flush = s->last_flush;
434     s->last_flush = flush;
435
436     /* Write the zlib header */
437     if (s->status == INIT_STATE) {
438
439         uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
440         uInt level_flags = (s->level-1) >> 1;
441
442         if (level_flags > 3) level_flags = 3;
443         header |= (level_flags << 6);
444         if (s->strstart != 0) header |= PRESET_DICT;
445         header += 31 - (header % 31);
446
447         s->status = BUSY_STATE;
448         putShortMSB(s, header);
449
450         /* Save the adler32 of the preset dictionary: */
451         if (s->strstart != 0) {
452             putShortMSB(s, (uInt)(strm->adler >> 16));
453             putShortMSB(s, (uInt)(strm->adler & 0xffff));
454         }
455         strm->adler = 1L;
456     }
457
458     /* Flush as much pending output as possible */
459     if (s->pending != 0) {
460         flush_pending(strm);
461         if (strm->avail_out == 0) {
462             /* Since avail_out is 0, deflate will be called again with
463              * more output space, but possibly with both pending and
464              * avail_in equal to zero. There won't be anything to do,
465              * but this is not an error situation so make sure we
466              * return OK instead of BUF_ERROR at next call of deflate:
467              */
468             s->last_flush = -1;
469             return Z_OK;
470         }
471
472     /* Make sure there is something to do and avoid duplicate consecutive
473      * flushes. For repeated and useless calls with Z_FINISH, we keep
474      * returning Z_STREAM_END instead of Z_BUFF_ERROR.
475      */
476     } else if (strm->avail_in == 0 && flush <= old_flush &&
477                flush != Z_FINISH) {
478         return Z_BUF_ERROR;
479     }
480
481     /* User must not provide more input after the first FINISH: */
482     if (s->status == FINISH_STATE && strm->avail_in != 0) {
483         return Z_BUF_ERROR;
484     }
485
486     /* Start a new block or continue the current one.
487      */
488     if (strm->avail_in != 0 || s->lookahead != 0 ||
489         (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
490         block_state bstate;
491
492         bstate = (*(configuration_table[s->level].func))(s, flush);
493
494         if (bstate == finish_started || bstate == finish_done) {
495             s->status = FINISH_STATE;
496         }
497         if (bstate == need_more || bstate == finish_started) {
498             if (strm->avail_out == 0) {
499                 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
500             }
501             return Z_OK;
502             /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
503              * of deflate should use the same flush parameter to make sure
504              * that the flush is complete. So we don't have to output an
505              * empty block here, this will be done at next call. This also
506              * ensures that for a very small output buffer, we emit at most
507              * one empty block.
508              */
509         }
510         if (bstate == block_done) {
511             if (flush == Z_PARTIAL_FLUSH) {
512                 zlib_tr_align(s);
513             } else if (flush == Z_PACKET_FLUSH) {
514                 /* Output just the 3-bit `stored' block type value,
515                    but not a zero length. */
516                 zlib_tr_stored_type_only(s);
517             } else { /* FULL_FLUSH or SYNC_FLUSH */
518                 zlib_tr_stored_block(s, (char*)0, 0L, 0);
519                 /* For a full flush, this empty block will be recognized
520                  * as a special marker by inflate_sync().
521                  */
522                 if (flush == Z_FULL_FLUSH) {
523                     CLEAR_HASH(s);             /* forget history */
524                 }
525             }
526             flush_pending(strm);
527             if (strm->avail_out == 0) {
528               s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
529               return Z_OK;
530             }
531         }
532     }
533     Assert(strm->avail_out > 0, "bug2");
534
535     if (flush != Z_FINISH) return Z_OK;
536     if (s->noheader) return Z_STREAM_END;
537
538     /* Write the zlib trailer (adler32) */
539     putShortMSB(s, (uInt)(strm->adler >> 16));
540     putShortMSB(s, (uInt)(strm->adler & 0xffff));
541     flush_pending(strm);
542     /* If avail_out is zero, the application will call deflate again
543      * to flush the rest.
544      */
545     s->noheader = -1; /* write the trailer only once! */
546     return s->pending != 0 ? Z_OK : Z_STREAM_END;
547 }
548
549 /* ========================================================================= */
550 int zlib_deflateEnd(
551         z_streamp strm
552 )
553 {
554     int status;
555     deflate_state *s;
556
557     if (strm == NULL || strm->state == NULL) return Z_STREAM_ERROR;
558     s = (deflate_state *) strm->state;
559
560     status = s->status;
561     if (status != INIT_STATE && status != BUSY_STATE &&
562         status != FINISH_STATE) {
563       return Z_STREAM_ERROR;
564     }
565
566     strm->state = NULL;
567
568     return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
569 }
570
571 /* =========================================================================
572  * Copy the source state to the destination state.
573  */
574 int zlib_deflateCopy (
575         z_streamp dest,
576         z_streamp source
577 )
578 {
579 #ifdef MAXSEG_64K
580     return Z_STREAM_ERROR;
581 #else
582     deflate_state *ds;
583     deflate_state *ss;
584     ush *overlay;
585     deflate_workspace *mem;
586
587
588     if (source == NULL || dest == NULL || source->state == NULL) {
589         return Z_STREAM_ERROR;
590     }
591
592     ss = (deflate_state *) source->state;
593
594     *dest = *source;
595
596     mem = (deflate_workspace *) dest->workspace;
597
598     ds = &(mem->deflate_memory);
599
600     dest->state = (struct internal_state *) ds;
601     *ds = *ss;
602     ds->strm = dest;
603
604     ds->window = (Byte *) mem->window_memory;
605     ds->prev   = (Pos *)  mem->prev_memory;
606     ds->head   = (Pos *)  mem->head_memory;
607     overlay = (ush *) mem->overlay_memory;
608     ds->pending_buf = (uch *) overlay;
609
610     memcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
611     memcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
612     memcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
613     memcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
614
615     ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
616     ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
617     ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
618
619     ds->l_desc.dyn_tree = ds->dyn_ltree;
620     ds->d_desc.dyn_tree = ds->dyn_dtree;
621     ds->bl_desc.dyn_tree = ds->bl_tree;
622
623     return Z_OK;
624 #endif
625 }
626
627 /* ===========================================================================
628  * Read a new buffer from the current input stream, update the adler32
629  * and total number of bytes read.  All deflate() input goes through
630  * this function so some applications may wish to modify it to avoid
631  * allocating a large strm->next_in buffer and copying from it.
632  * (See also flush_pending()).
633  */
634 static int read_buf(
635         z_streamp strm,
636         Byte *buf,
637         unsigned size
638 )
639 {
640     unsigned len = strm->avail_in;
641
642     if (len > size) len = size;
643     if (len == 0) return 0;
644
645     strm->avail_in  -= len;
646
647     if (!((deflate_state *)(strm->state))->noheader) {
648         strm->adler = zlib_adler32(strm->adler, strm->next_in, len);
649     }
650     memcpy(buf, strm->next_in, len);
651     strm->next_in  += len;
652     strm->total_in += len;
653
654     return (int)len;
655 }
656
657 /* ===========================================================================
658  * Initialize the "longest match" routines for a new zlib stream
659  */
660 static void lm_init(
661         deflate_state *s
662 )
663 {
664     s->window_size = (ulg)2L*s->w_size;
665
666     CLEAR_HASH(s);
667
668     /* Set the default configuration parameters:
669      */
670     s->max_lazy_match   = configuration_table[s->level].max_lazy;
671     s->good_match       = configuration_table[s->level].good_length;
672     s->nice_match       = configuration_table[s->level].nice_length;
673     s->max_chain_length = configuration_table[s->level].max_chain;
674
675     s->strstart = 0;
676     s->block_start = 0L;
677     s->lookahead = 0;
678     s->match_length = s->prev_length = MIN_MATCH-1;
679     s->match_available = 0;
680     s->ins_h = 0;
681 }
682
683 /* ===========================================================================
684  * Set match_start to the longest match starting at the given string and
685  * return its length. Matches shorter or equal to prev_length are discarded,
686  * in which case the result is equal to prev_length and match_start is
687  * garbage.
688  * IN assertions: cur_match is the head of the hash chain for the current
689  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
690  * OUT assertion: the match length is not greater than s->lookahead.
691  */
692 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
693  * match.S. The code will be functionally equivalent.
694  */
695 static uInt longest_match(
696         deflate_state *s,
697         IPos cur_match                  /* current match */
698 )
699 {
700     unsigned chain_length = s->max_chain_length;/* max hash chain length */
701     register Byte *scan = s->window + s->strstart; /* current string */
702     register Byte *match;                       /* matched string */
703     register int len;                           /* length of current match */
704     int best_len = s->prev_length;              /* best match length so far */
705     int nice_match = s->nice_match;             /* stop if match long enough */
706     IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
707         s->strstart - (IPos)MAX_DIST(s) : NIL;
708     /* Stop when cur_match becomes <= limit. To simplify the code,
709      * we prevent matches with the string of window index 0.
710      */
711     Pos *prev = s->prev;
712     uInt wmask = s->w_mask;
713
714 #ifdef UNALIGNED_OK
715     /* Compare two bytes at a time. Note: this is not always beneficial.
716      * Try with and without -DUNALIGNED_OK to check.
717      */
718     register Byte *strend = s->window + s->strstart + MAX_MATCH - 1;
719     register ush scan_start = *(ush*)scan;
720     register ush scan_end   = *(ush*)(scan+best_len-1);
721 #else
722     register Byte *strend = s->window + s->strstart + MAX_MATCH;
723     register Byte scan_end1  = scan[best_len-1];
724     register Byte scan_end   = scan[best_len];
725 #endif
726
727     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
728      * It is easy to get rid of this optimization if necessary.
729      */
730     Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
731
732     /* Do not waste too much time if we already have a good match: */
733     if (s->prev_length >= s->good_match) {
734         chain_length >>= 2;
735     }
736     /* Do not look for matches beyond the end of the input. This is necessary
737      * to make deflate deterministic.
738      */
739     if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
740
741     Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
742
743     do {
744         Assert(cur_match < s->strstart, "no future");
745         match = s->window + cur_match;
746
747         /* Skip to next match if the match length cannot increase
748          * or if the match length is less than 2:
749          */
750 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
751         /* This code assumes sizeof(unsigned short) == 2. Do not use
752          * UNALIGNED_OK if your compiler uses a different size.
753          */
754         if (*(ush*)(match+best_len-1) != scan_end ||
755             *(ush*)match != scan_start) continue;
756
757         /* It is not necessary to compare scan[2] and match[2] since they are
758          * always equal when the other bytes match, given that the hash keys
759          * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
760          * strstart+3, +5, ... up to strstart+257. We check for insufficient
761          * lookahead only every 4th comparison; the 128th check will be made
762          * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
763          * necessary to put more guard bytes at the end of the window, or
764          * to check more often for insufficient lookahead.
765          */
766         Assert(scan[2] == match[2], "scan[2]?");
767         scan++, match++;
768         do {
769         } while (*(ush*)(scan+=2) == *(ush*)(match+=2) &&
770                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
771                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
772                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
773                  scan < strend);
774         /* The funny "do {}" generates better code on most compilers */
775
776         /* Here, scan <= window+strstart+257 */
777         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
778         if (*scan == *match) scan++;
779
780         len = (MAX_MATCH - 1) - (int)(strend-scan);
781         scan = strend - (MAX_MATCH-1);
782
783 #else /* UNALIGNED_OK */
784
785         if (match[best_len]   != scan_end  ||
786             match[best_len-1] != scan_end1 ||
787             *match            != *scan     ||
788             *++match          != scan[1])      continue;
789
790         /* The check at best_len-1 can be removed because it will be made
791          * again later. (This heuristic is not always a win.)
792          * It is not necessary to compare scan[2] and match[2] since they
793          * are always equal when the other bytes match, given that
794          * the hash keys are equal and that HASH_BITS >= 8.
795          */
796         scan += 2, match++;
797         Assert(*scan == *match, "match[2]?");
798
799         /* We check for insufficient lookahead only every 8th comparison;
800          * the 256th check will be made at strstart+258.
801          */
802         do {
803         } while (*++scan == *++match && *++scan == *++match &&
804                  *++scan == *++match && *++scan == *++match &&
805                  *++scan == *++match && *++scan == *++match &&
806                  *++scan == *++match && *++scan == *++match &&
807                  scan < strend);
808
809         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
810
811         len = MAX_MATCH - (int)(strend - scan);
812         scan = strend - MAX_MATCH;
813
814 #endif /* UNALIGNED_OK */
815
816         if (len > best_len) {
817             s->match_start = cur_match;
818             best_len = len;
819             if (len >= nice_match) break;
820 #ifdef UNALIGNED_OK
821             scan_end = *(ush*)(scan+best_len-1);
822 #else
823             scan_end1  = scan[best_len-1];
824             scan_end   = scan[best_len];
825 #endif
826         }
827     } while ((cur_match = prev[cur_match & wmask]) > limit
828              && --chain_length != 0);
829
830     if ((uInt)best_len <= s->lookahead) return best_len;
831     return s->lookahead;
832 }
833
834 #ifdef DEBUG_ZLIB
835 /* ===========================================================================
836  * Check that the match at match_start is indeed a match.
837  */
838 static void check_match(
839         deflate_state *s,
840         IPos start,
841         IPos match,
842         int length
843 )
844 {
845     /* check that the match is indeed a match */
846     if (memcmp((char *)s->window + match,
847                 (char *)s->window + start, length) != EQUAL) {
848         fprintf(stderr, " start %u, match %u, length %d\n",
849                 start, match, length);
850         do {
851             fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
852         } while (--length != 0);
853         z_error("invalid match");
854     }
855     if (z_verbose > 1) {
856         fprintf(stderr,"\\[%d,%d]", start-match, length);
857         do { putc(s->window[start++], stderr); } while (--length != 0);
858     }
859 }
860 #else
861 #  define check_match(s, start, match, length)
862 #endif
863
864 /* ===========================================================================
865  * Fill the window when the lookahead becomes insufficient.
866  * Updates strstart and lookahead.
867  *
868  * IN assertion: lookahead < MIN_LOOKAHEAD
869  * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
870  *    At least one byte has been read, or avail_in == 0; reads are
871  *    performed for at least two bytes (required for the zip translate_eol
872  *    option -- not supported here).
873  */
874 static void fill_window(
875         deflate_state *s
876 )
877 {
878     register unsigned n, m;
879     register Pos *p;
880     unsigned more;    /* Amount of free space at the end of the window. */
881     uInt wsize = s->w_size;
882
883     do {
884         more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
885
886         /* Deal with !@#$% 64K limit: */
887         if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
888             more = wsize;
889
890         } else if (more == (unsigned)(-1)) {
891             /* Very unlikely, but possible on 16 bit machine if strstart == 0
892              * and lookahead == 1 (input done one byte at time)
893              */
894             more--;
895
896         /* If the window is almost full and there is insufficient lookahead,
897          * move the upper half to the lower one to make room in the upper half.
898          */
899         } else if (s->strstart >= wsize+MAX_DIST(s)) {
900
901             memcpy((char *)s->window, (char *)s->window+wsize,
902                    (unsigned)wsize);
903             s->match_start -= wsize;
904             s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
905             s->block_start -= (long) wsize;
906
907             /* Slide the hash table (could be avoided with 32 bit values
908                at the expense of memory usage). We slide even when level == 0
909                to keep the hash table consistent if we switch back to level > 0
910                later. (Using level 0 permanently is not an optimal usage of
911                zlib, so we don't care about this pathological case.)
912              */
913             n = s->hash_size;
914             p = &s->head[n];
915             do {
916                 m = *--p;
917                 *p = (Pos)(m >= wsize ? m-wsize : NIL);
918             } while (--n);
919
920             n = wsize;
921             p = &s->prev[n];
922             do {
923                 m = *--p;
924                 *p = (Pos)(m >= wsize ? m-wsize : NIL);
925                 /* If n is not on any hash chain, prev[n] is garbage but
926                  * its value will never be used.
927                  */
928             } while (--n);
929             more += wsize;
930         }
931         if (s->strm->avail_in == 0) return;
932
933         /* If there was no sliding:
934          *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
935          *    more == window_size - lookahead - strstart
936          * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
937          * => more >= window_size - 2*WSIZE + 2
938          * In the BIG_MEM or MMAP case (not yet supported),
939          *   window_size == input_size + MIN_LOOKAHEAD  &&
940          *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
941          * Otherwise, window_size == 2*WSIZE so more >= 2.
942          * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
943          */
944         Assert(more >= 2, "more < 2");
945
946         n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
947         s->lookahead += n;
948
949         /* Initialize the hash value now that we have some input: */
950         if (s->lookahead >= MIN_MATCH) {
951             s->ins_h = s->window[s->strstart];
952             UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
953 #if MIN_MATCH != 3
954             Call UPDATE_HASH() MIN_MATCH-3 more times
955 #endif
956         }
957         /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
958          * but this is not important since only literal bytes will be emitted.
959          */
960
961     } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
962 }
963
964 /* ===========================================================================
965  * Flush the current block, with given end-of-file flag.
966  * IN assertion: strstart is set to the end of the current match.
967  */
968 #define FLUSH_BLOCK_ONLY(s, eof) { \
969    zlib_tr_flush_block(s, (s->block_start >= 0L ? \
970                    (char *)&s->window[(unsigned)s->block_start] : \
971                    NULL), \
972                 (ulg)((long)s->strstart - s->block_start), \
973                 (eof)); \
974    s->block_start = s->strstart; \
975    flush_pending(s->strm); \
976    Tracev((stderr,"[FLUSH]")); \
977 }
978
979 /* Same but force premature exit if necessary. */
980 #define FLUSH_BLOCK(s, eof) { \
981    FLUSH_BLOCK_ONLY(s, eof); \
982    if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
983 }
984
985 /* ===========================================================================
986  * Copy without compression as much as possible from the input stream, return
987  * the current block state.
988  * This function does not insert new strings in the dictionary since
989  * uncompressible data is probably not useful. This function is used
990  * only for the level=0 compression option.
991  * NOTE: this function should be optimized to avoid extra copying from
992  * window to pending_buf.
993  */
994 static block_state deflate_stored(
995         deflate_state *s,
996         int flush
997 )
998 {
999     /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
1000      * to pending_buf_size, and each stored block has a 5 byte header:
1001      */
1002     ulg max_block_size = 0xffff;
1003     ulg max_start;
1004
1005     if (max_block_size > s->pending_buf_size - 5) {
1006         max_block_size = s->pending_buf_size - 5;
1007     }
1008
1009     /* Copy as much as possible from input to output: */
1010     for (;;) {
1011         /* Fill the window as much as possible: */
1012         if (s->lookahead <= 1) {
1013
1014             Assert(s->strstart < s->w_size+MAX_DIST(s) ||
1015                    s->block_start >= (long)s->w_size, "slide too late");
1016
1017             fill_window(s);
1018             if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
1019
1020             if (s->lookahead == 0) break; /* flush the current block */
1021         }
1022         Assert(s->block_start >= 0L, "block gone");
1023
1024         s->strstart += s->lookahead;
1025         s->lookahead = 0;
1026
1027         /* Emit a stored block if pending_buf will be full: */
1028         max_start = s->block_start + max_block_size;
1029         if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
1030             /* strstart == 0 is possible when wraparound on 16-bit machine */
1031             s->lookahead = (uInt)(s->strstart - max_start);
1032             s->strstart = (uInt)max_start;
1033             FLUSH_BLOCK(s, 0);
1034         }
1035         /* Flush if we may have to slide, otherwise block_start may become
1036          * negative and the data will be gone:
1037          */
1038         if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
1039             FLUSH_BLOCK(s, 0);
1040         }
1041     }
1042     FLUSH_BLOCK(s, flush == Z_FINISH);
1043     return flush == Z_FINISH ? finish_done : block_done;
1044 }
1045
1046 /* ===========================================================================
1047  * Compress as much as possible from the input stream, return the current
1048  * block state.
1049  * This function does not perform lazy evaluation of matches and inserts
1050  * new strings in the dictionary only for unmatched strings or for short
1051  * matches. It is used only for the fast compression options.
1052  */
1053 static block_state deflate_fast(
1054         deflate_state *s,
1055         int flush
1056 )
1057 {
1058     IPos hash_head = NIL; /* head of the hash chain */
1059     int bflush;           /* set if current block must be flushed */
1060
1061     for (;;) {
1062         /* Make sure that we always have enough lookahead, except
1063          * at the end of the input file. We need MAX_MATCH bytes
1064          * for the next match, plus MIN_MATCH bytes to insert the
1065          * string following the next match.
1066          */
1067         if (s->lookahead < MIN_LOOKAHEAD) {
1068             fill_window(s);
1069             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1070                 return need_more;
1071             }
1072             if (s->lookahead == 0) break; /* flush the current block */
1073         }
1074
1075         /* Insert the string window[strstart .. strstart+2] in the
1076          * dictionary, and set hash_head to the head of the hash chain:
1077          */
1078         if (s->lookahead >= MIN_MATCH) {
1079             INSERT_STRING(s, s->strstart, hash_head);
1080         }
1081
1082         /* Find the longest match, discarding those <= prev_length.
1083          * At this point we have always match_length < MIN_MATCH
1084          */
1085         if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1086             /* To simplify the code, we prevent matches with the string
1087              * of window index 0 (in particular we have to avoid a match
1088              * of the string with itself at the start of the input file).
1089              */
1090             if (s->strategy != Z_HUFFMAN_ONLY) {
1091                 s->match_length = longest_match (s, hash_head);
1092             }
1093             /* longest_match() sets match_start */
1094         }
1095         if (s->match_length >= MIN_MATCH) {
1096             check_match(s, s->strstart, s->match_start, s->match_length);
1097
1098             bflush = zlib_tr_tally(s, s->strstart - s->match_start,
1099                                s->match_length - MIN_MATCH);
1100
1101             s->lookahead -= s->match_length;
1102
1103             /* Insert new strings in the hash table only if the match length
1104              * is not too large. This saves time but degrades compression.
1105              */
1106             if (s->match_length <= s->max_insert_length &&
1107                 s->lookahead >= MIN_MATCH) {
1108                 s->match_length--; /* string at strstart already in hash table */
1109                 do {
1110                     s->strstart++;
1111                     INSERT_STRING(s, s->strstart, hash_head);
1112                     /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1113                      * always MIN_MATCH bytes ahead.
1114                      */
1115                 } while (--s->match_length != 0);