]> git.lizzy.rs Git - zlib.git/blob - deflate.c
zlib 0.99
[zlib.git] / deflate.c
1 /* deflate.c -- compress data using the deflation algorithm
2  * Copyright (C) 1995-1996 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.8 1995/05/03 17:27:08 jloup Exp $ */
51
52 #include "deflate.h"
53
54 char deflate_copyright[] = " deflate 1.0 Copyright 1995-1996 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 /* ===========================================================================
63  *  Function prototypes.
64  */
65 local void fill_window    OF((deflate_state *s));
66 local int  deflate_stored OF((deflate_state *s, int flush));
67 local int  deflate_fast   OF((deflate_state *s, int flush));
68 local int  deflate_slow   OF((deflate_state *s, int flush));
69 local void lm_init        OF((deflate_state *s));
70 local int longest_match   OF((deflate_state *s, IPos cur_match));
71 local void putShortMSB    OF((deflate_state *s, uInt b));
72 local void flush_pending  OF((z_stream *strm));
73 local int read_buf        OF((z_stream *strm, charf *buf, unsigned size));
74 #ifdef ASMV
75       void match_init OF((void)); /* asm code initialization */
76 #endif
77
78 #ifdef DEBUG
79 local  void check_match OF((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 typedef int (*compress_func) OF((deflate_state *s, int flush));
101 /* Compressing function */
102
103 /* Values for max_lazy_match, good_match and max_chain_length, depending on
104  * the desired pack level (0..9). The values given below have been tuned to
105  * exclude worst case performance for pathological files. Better values may be
106  * found for specific files.
107  */
108 typedef struct config_s {
109    ush good_length; /* reduce lazy search above this match length */
110    ush max_lazy;    /* do not perform lazy search above this match length */
111    ush nice_length; /* quit search above this match length */
112    ush max_chain;
113    compress_func func;
114 } config;
115
116 local config configuration_table[10] = {
117 /*      good lazy nice chain */
118 /* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
119 /* 1 */ {4,    4,  8,    4, deflate_fast}, /* maximum speed, no lazy matches */
120 /* 2 */ {4,    5, 16,    8, deflate_fast},
121 /* 3 */ {4,    6, 32,   32, deflate_fast},
122
123 /* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
124 /* 5 */ {8,   16, 32,   32, deflate_slow},
125 /* 6 */ {8,   16, 128, 128, deflate_slow},
126 /* 7 */ {8,   32, 128, 256, deflate_slow},
127 /* 8 */ {32, 128, 258, 1024, deflate_slow},
128 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* maximum compression */
129
130 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
131  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
132  * meaning.
133  */
134
135 #define EQUAL 0
136 /* result of memcmp for equal strings */
137
138 struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
139
140 /* ===========================================================================
141  * Update a hash value with the given input byte
142  * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
143  *    input characters, so that a running hash key can be computed from the
144  *    previous key instead of complete recalculation each time.
145  */
146 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
147
148
149 /* ===========================================================================
150  * Insert string str in the dictionary and set match_head to the previous head
151  * of the hash chain (the most recent string with same hash key). Return
152  * the previous length of the hash chain.
153  * IN  assertion: all calls to to INSERT_STRING are made with consecutive
154  *    input characters and the first MIN_MATCH bytes of str are valid
155  *    (except for the last MIN_MATCH-1 bytes of the input file).
156  */
157 #define INSERT_STRING(s, str, match_head) \
158    (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
159     s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \
160     s->head[s->ins_h] = (str))
161
162 /* ===========================================================================
163  * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
164  * prev[] will be initialized on the fly.
165  */
166 #define CLEAR_HASH(s) \
167     s->head[s->hash_size-1] = NIL; \
168     zmemzero((charf *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
169
170 /* ========================================================================= */
171 int deflateInit_(strm, level, version, stream_size)
172     z_stream *strm;
173     int level;
174     const char *version;
175     int stream_size;
176 {
177     return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
178                          Z_DEFAULT_STRATEGY, version, stream_size);
179     /* To do: ignore strm->next_in if we use it as window */
180 }
181
182 /* ========================================================================= */
183 int deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
184                   version, stream_size)
185     z_stream *strm;
186     int  level;
187     int  method;
188     int  windowBits;
189     int  memLevel;
190     int  strategy;
191     const char *version;
192     int stream_size;
193 {
194     deflate_state *s;
195     int noheader = 0;
196
197     if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
198         stream_size != sizeof(z_stream)) {
199         return Z_VERSION_ERROR;
200     }
201     if (strm == Z_NULL) return Z_STREAM_ERROR;
202
203     strm->msg = Z_NULL;
204     if (strm->zalloc == Z_NULL) {
205         strm->zalloc = zcalloc;
206         strm->opaque = (voidpf)0;
207     }
208     if (strm->zfree == Z_NULL) strm->zfree = zcfree;
209
210     if (level == Z_DEFAULT_COMPRESSION) level = 6;
211
212     if (windowBits < 0) { /* undocumented feature: suppress zlib header */
213         noheader = 1;
214         windowBits = -windowBits;
215     }
216     if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
217         windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
218         strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
219         return Z_STREAM_ERROR;
220     }
221     s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
222     if (s == Z_NULL) return Z_MEM_ERROR;
223     strm->state = (struct internal_state FAR *)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 = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
237     s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
238     s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
239
240     s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
241
242     s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, 2*sizeof(ush));
243
244     if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
245         s->pending_buf == Z_NULL) {
246         strm->msg = ERR_MSG(Z_MEM_ERROR);
247         deflateEnd (strm);
248         return Z_MEM_ERROR;
249     }
250     s->l_buf = (uchf *) &(s->pending_buf[s->lit_bufsize]);
251     s->d_buf = (ushf *) &(s->pending_buf[2*s->lit_bufsize]);
252     /* We overlay pending_buf and d_buf+l_buf. This works since the average
253      * output size for (length,distance) codes is <= 32 bits (worst case
254      * is 15+15+13=33). d_buf is put last in case sizeof(short)>2.
255      */
256
257     s->level = level;
258     s->strategy = strategy;
259     s->method = (Byte)method;
260
261     return deflateReset(strm);
262 }
263
264 /* ========================================================================= */
265 int deflateSetDictionary (strm, dictionary, dictLength)
266     z_stream *strm;
267     const Bytef *dictionary;
268     uInt  dictLength;
269 {
270     deflate_state *s;
271     uInt length = dictLength;
272     uInt n;
273     IPos hash_head;
274
275     if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
276         strm->state->status != INIT_STATE) return Z_STREAM_ERROR;
277
278     s = strm->state;
279     strm->adler = adler32(strm->adler, dictionary, dictLength);
280
281     if (length < MIN_MATCH) return Z_OK;
282     if (length > MAX_DIST(s)) {
283         length = MAX_DIST(s);
284         dictionary += dictLength - length;
285     }
286     zmemcpy((charf *)s->window, dictionary, length);
287     s->strstart = length;
288     s->block_start = (long)length;
289
290     /* Insert all strings in the hash table (except for the last two bytes).
291      * s->lookahead stays null, so s->ins_h will be recomputed at the next
292      * call of fill_window.
293      */
294     s->ins_h = s->window[0];
295     UPDATE_HASH(s, s->ins_h, s->window[1]);
296     for (n = 0; n <= length - MIN_MATCH; n++) {
297         INSERT_STRING(s, n, hash_head);
298     }
299     return Z_OK;
300 }
301
302 /* ========================================================================= */
303 int deflateReset (strm)
304     z_stream *strm;
305 {
306     deflate_state *s;
307     
308     if (strm == Z_NULL || strm->state == Z_NULL ||
309         strm->zalloc == Z_NULL || strm->zfree == Z_NULL) return Z_STREAM_ERROR;
310
311     strm->total_in = strm->total_out = 0;
312     strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
313     strm->data_type = Z_UNKNOWN;
314
315     s = (deflate_state *)strm->state;
316     s->pending = 0;
317     s->pending_out = s->pending_buf;
318
319     if (s->noheader < 0) {
320         s->noheader = 0; /* was set to -1 by deflate(..., Z_FINISH); */
321     }
322     s->status = s->noheader ? BUSY_STATE : INIT_STATE;
323     strm->adler = 1;
324     s->last_flush = Z_NO_FLUSH;
325
326     _tr_init(s);
327     lm_init(s);
328
329     return Z_OK;
330 }
331
332 /* ========================================================================= */
333 int deflateParams(strm, level, strategy)
334     z_stream *strm;
335     int level;
336     int strategy;
337 {
338     deflate_state *s;
339     compress_func func;
340
341     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
342     s = strm->state;
343
344     if (level == Z_DEFAULT_COMPRESSION) {
345         level = 6;
346     }
347     if (level < 0 || level > 9 || strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
348         return Z_STREAM_ERROR;
349     }
350     func = configuration_table[s->level].func;
351
352     if (func != configuration_table[level].func
353         && strm->state->lookahead != 0) {
354
355         /* Flush the last buffer: */
356         (void)(*func)(strm->state, Z_PARTIAL_FLUSH);
357     }
358     if (s->level != level) {
359         s->level = level;
360         s->max_lazy_match   = configuration_table[level].max_lazy;
361         s->good_match       = configuration_table[level].good_length;
362         s->nice_match       = configuration_table[level].nice_length;
363         s->max_chain_length = configuration_table[level].max_chain;
364     }
365     s->strategy = strategy;
366     return Z_OK;
367 }
368
369 /* =========================================================================
370  * Put a short in the pending buffer. The 16-bit value is put in MSB order.
371  * IN assertion: the stream state is correct and there is enough room in
372  * pending_buf.
373  */
374 local void putShortMSB (s, b)
375     deflate_state *s;
376     uInt b;
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 local void flush_pending(strm)
389     z_stream *strm;
390 {
391     unsigned len = strm->state->pending;
392
393     if (len > strm->avail_out) len = strm->avail_out;
394     if (len == 0) return;
395
396     zmemcpy(strm->next_out, strm->state->pending_out, len);
397     strm->next_out  += len;
398     strm->state->pending_out  += len;
399     strm->total_out += len;
400     strm->avail_out  -= len;
401     strm->state->pending -= len;
402     if (strm->state->pending == 0) {
403         strm->state->pending_out = strm->state->pending_buf;
404     }
405 }
406
407 /* ========================================================================= */
408 int deflate (strm, flush)
409     z_stream *strm;
410     int flush;
411 {
412     int old_flush; /* value of flush param for previous deflate call */
413     deflate_state *s;
414
415     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
416     
417     s = strm->state;
418
419     if (strm->next_out == Z_NULL ||
420         (strm->next_in == Z_NULL && strm->avail_in != 0) ||
421         (s->status == FINISH_STATE && flush != Z_FINISH)) {
422         ERR_RETURN(strm, Z_STREAM_ERROR);
423     }
424     if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
425
426     s->strm = strm; /* just in case */
427     old_flush = s->last_flush;
428     s->last_flush = flush;
429
430     /* Write the zlib header */
431     if (s->status == INIT_STATE) {
432
433         uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
434         uInt level_flags = (s->level-1) >> 1;
435
436         if (level_flags > 3) level_flags = 3;
437         header |= (level_flags << 6);
438         if (s->strstart != 0) header |= PRESET_DICT;
439         header += 31 - (header % 31);
440
441         s->status = BUSY_STATE;
442         putShortMSB(s, header);
443
444         /* Save the adler32 of the preset dictionary: */
445         if (s->strstart != 0) {
446             putShortMSB(s, (uInt)(strm->adler >> 16));
447             putShortMSB(s, (uInt)(strm->adler & 0xffff));
448             strm->adler = 1L;
449         }
450     }
451
452     /* Flush as much pending output as possible */
453     if (s->pending != 0) {
454         flush_pending(strm);
455         if (strm->avail_out == 0) return Z_OK;
456
457     /* Make sure there is something to do and avoid duplicate consecutive
458      * flushes. For repeated and useless calls with Z_FINISH, we keep
459      * returning Z_STREAM_END instead of Z_BUFF_ERROR.
460      */
461     } else if (strm->avail_in == 0 && flush <= old_flush &&
462                flush != Z_FINISH) {
463         ERR_RETURN(strm, Z_BUF_ERROR);
464     }
465
466     /* User must not provide more input after the first FINISH: */
467     if (s->status == FINISH_STATE && strm->avail_in != 0) {
468         ERR_RETURN(strm, Z_BUF_ERROR);
469     }
470
471     /* Start a new block or continue the current one.
472      */
473     if (strm->avail_in != 0 || s->lookahead != 0 ||
474         (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
475         int quit;
476
477         if (flush == Z_FINISH) {
478             s->status = FINISH_STATE;
479         }
480         quit = (*(configuration_table[s->level].func))(s, flush);
481
482         if (quit || strm->avail_out == 0) return Z_OK;
483         /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
484          * of deflate should use the same flush parameter to make sure
485          * that the flush is complete. So we don't have to output an
486          * empty block here, this will be done at next call. This also
487          * ensures that for a very small output buffer, we emit at most
488          * one empty block.
489          */
490         if (flush != Z_NO_FLUSH && flush != Z_FINISH) {
491             if (flush == Z_PARTIAL_FLUSH) {
492                 _tr_align(s);
493             } else { /* FULL_FLUSH or SYNC_FLUSH */
494                 _tr_stored_block(s, (char*)0, 0L, 0);
495                 /* For a full flush, this empty block will be recognized
496                  * as a special marker by inflate_sync().
497                  */
498                 if (flush == Z_FULL_FLUSH) {
499                     CLEAR_HASH(s);             /* forget history */
500                 }
501             }
502             flush_pending(strm);
503             if (strm->avail_out == 0) return Z_OK;
504         }
505     }
506     Assert(strm->avail_out > 0, "bug2");
507
508     if (flush != Z_FINISH) return Z_OK;
509     if (s->noheader) return Z_STREAM_END;
510
511     /* Write the zlib trailer (adler32) */
512     putShortMSB(s, (uInt)(strm->adler >> 16));
513     putShortMSB(s, (uInt)(strm->adler & 0xffff));
514     flush_pending(strm);
515     /* If avail_out is zero, the application will call deflate again
516      * to flush the rest.
517      */
518     s->noheader = -1; /* write the trailer only once! */
519     return s->pending != 0 ? Z_OK : Z_STREAM_END;
520 }
521
522 /* ========================================================================= */
523 int deflateEnd (strm)
524     z_stream *strm;
525 {
526     int status;
527
528     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
529
530     /* Deallocate in reverse order of allocations: */
531     TRY_FREE(strm, strm->state->pending_buf);
532     TRY_FREE(strm, strm->state->head);
533     TRY_FREE(strm, strm->state->prev);
534     TRY_FREE(strm, strm->state->window);
535
536     status = strm->state->status;
537     ZFREE(strm, strm->state);
538     strm->state = Z_NULL;
539
540     return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
541 }
542
543 /* ========================================================================= */
544 int deflateCopy (dest, source)
545     z_stream *dest;
546     z_stream *source;
547 {
548     if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
549         return Z_STREAM_ERROR;
550     }
551     *dest = *source;
552     return Z_STREAM_ERROR; /* to be implemented */
553 #if 0
554     dest->state = (struct internal_state FAR *)
555         (*dest->zalloc)(1, sizeof(deflate_state));
556     if (dest->state == Z_NULL) return Z_MEM_ERROR;
557
558     *(dest->state) = *(source->state);
559     return Z_OK;
560 #endif
561 }
562
563 /* ===========================================================================
564  * Read a new buffer from the current input stream, update the adler32
565  * and total number of bytes read.  All deflate() input goes through
566  * this function so some applications may wish to modify it to avoid
567  * allocating a large strm->next_in buffer and copying from it.
568  * (See also flush_pending()).
569  */
570 local int read_buf(strm, buf, size)
571     z_stream *strm;
572     charf *buf;
573     unsigned size;
574 {
575     unsigned len = strm->avail_in;
576
577     if (len > size) len = size;
578     if (len == 0) return 0;
579
580     strm->avail_in  -= len;
581
582     if (!strm->state->noheader) {
583         strm->adler = adler32(strm->adler, strm->next_in, len);
584     }
585     zmemcpy(buf, strm->next_in, len);
586     strm->next_in  += len;
587     strm->total_in += len;
588
589     return (int)len;
590 }
591
592 /* ===========================================================================
593  * Initialize the "longest match" routines for a new zlib stream
594  */
595 local void lm_init (s)
596     deflate_state *s;
597 {
598     s->window_size = (ulg)2L*s->w_size;
599
600     CLEAR_HASH(s);
601
602     /* Set the default configuration parameters:
603      */
604     s->max_lazy_match   = configuration_table[s->level].max_lazy;
605     s->good_match       = configuration_table[s->level].good_length;
606     s->nice_match       = configuration_table[s->level].nice_length;
607     s->max_chain_length = configuration_table[s->level].max_chain;
608
609     s->strstart = 0;
610     s->block_start = 0L;
611     s->lookahead = 0;
612     s->match_length = s->prev_length = MIN_MATCH-1;
613     s->match_available = 0;
614     s->ins_h = 0;
615 #ifdef ASMV
616     match_init(); /* initialize the asm code */
617 #endif
618 }
619
620 /* ===========================================================================
621  * Set match_start to the longest match starting at the given string and
622  * return its length. Matches shorter or equal to prev_length are discarded,
623  * in which case the result is equal to prev_length and match_start is
624  * garbage.
625  * IN assertions: cur_match is the head of the hash chain for the current
626  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
627  * OUT assertion: the match length is not greater than s->lookahead.
628  */
629 #ifndef ASMV
630 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
631  * match.S. The code will be functionally equivalent.
632  */
633 local int longest_match(s, cur_match)
634     deflate_state *s;
635     IPos cur_match;                             /* current match */
636 {
637     unsigned chain_length = s->max_chain_length;/* max hash chain length */
638     register Bytef *scan = s->window + s->strstart; /* current string */
639     register Bytef *match;                       /* matched string */
640     register int len;                           /* length of current match */
641     int best_len = s->prev_length;              /* best match length so far */
642     int nice_match = s->nice_match;             /* stop if match long enough */
643     IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
644         s->strstart - (IPos)MAX_DIST(s) : NIL;
645     /* Stop when cur_match becomes <= limit. To simplify the code,
646      * we prevent matches with the string of window index 0.
647      */
648     Posf *prev = s->prev;
649     uInt wmask = s->w_mask;
650
651 #ifdef UNALIGNED_OK
652     /* Compare two bytes at a time. Note: this is not always beneficial.
653      * Try with and without -DUNALIGNED_OK to check.
654      */
655     register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
656     register ush scan_start = *(ushf*)scan;
657     register ush scan_end   = *(ushf*)(scan+best_len-1);
658 #else
659     register Bytef *strend = s->window + s->strstart + MAX_MATCH;
660     register Byte scan_end1  = scan[best_len-1];
661     register Byte scan_end   = scan[best_len];
662 #endif
663
664     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
665      * It is easy to get rid of this optimization if necessary.
666      */
667     Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
668
669     /* Do not waste too much time if we already have a good match: */
670     if (s->prev_length >= s->good_match) {
671         chain_length >>= 2;
672     }
673     /* Do not look for matches beyond the end of the input. This is necessary
674      * to make deflate deterministic.
675      */
676     if (nice_match > s->lookahead) nice_match = s->lookahead;
677
678     Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
679
680     do {
681         Assert(cur_match < s->strstart, "no future");
682         match = s->window + cur_match;
683
684         /* Skip to next match if the match length cannot increase
685          * or if the match length is less than 2:
686          */
687 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
688         /* This code assumes sizeof(unsigned short) == 2. Do not use
689          * UNALIGNED_OK if your compiler uses a different size.
690          */
691         if (*(ushf*)(match+best_len-1) != scan_end ||
692             *(ushf*)match != scan_start) continue;
693
694         /* It is not necessary to compare scan[2] and match[2] since they are
695          * always equal when the other bytes match, given that the hash keys
696          * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
697          * strstart+3, +5, ... up to strstart+257. We check for insufficient
698          * lookahead only every 4th comparison; the 128th check will be made
699          * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
700          * necessary to put more guard bytes at the end of the window, or
701          * to check more often for insufficient lookahead.
702          */
703         Assert(scan[2] == match[2], "scan[2]?");
704         scan++, match++;
705         do {
706         } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
707                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
708                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
709                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
710                  scan < strend);
711         /* The funny "do {}" generates better code on most compilers */
712
713         /* Here, scan <= window+strstart+257 */
714         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
715         if (*scan == *match) scan++;
716
717         len = (MAX_MATCH - 1) - (int)(strend-scan);
718         scan = strend - (MAX_MATCH-1);
719
720 #else /* UNALIGNED_OK */
721
722         if (match[best_len]   != scan_end  ||
723             match[best_len-1] != scan_end1 ||
724             *match            != *scan     ||
725             *++match          != scan[1])      continue;
726
727         /* The check at best_len-1 can be removed because it will be made
728          * again later. (This heuristic is not always a win.)
729          * It is not necessary to compare scan[2] and match[2] since they
730          * are always equal when the other bytes match, given that
731          * the hash keys are equal and that HASH_BITS >= 8.
732          */
733         scan += 2, match++;
734         Assert(*scan == *match, "match[2]?");
735
736         /* We check for insufficient lookahead only every 8th comparison;
737          * the 256th check will be made at strstart+258.
738          */
739         do {
740         } while (*++scan == *++match && *++scan == *++match &&
741                  *++scan == *++match && *++scan == *++match &&
742                  *++scan == *++match && *++scan == *++match &&
743                  *++scan == *++match && *++scan == *++match &&
744                  scan < strend);
745
746         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
747
748         len = MAX_MATCH - (int)(strend - scan);
749         scan = strend - MAX_MATCH;
750
751 #endif /* UNALIGNED_OK */
752
753         if (len > best_len) {
754             s->match_start = cur_match;
755             best_len = len;
756             if (len >= nice_match) break;
757 #ifdef UNALIGNED_OK
758             scan_end = *(ushf*)(scan+best_len-1);
759 #else
760             scan_end1  = scan[best_len-1];
761             scan_end   = scan[best_len];
762 #endif
763         }
764     } while ((cur_match = prev[cur_match & wmask]) > limit
765              && --chain_length != 0);
766
767     if (best_len <= s->lookahead) return best_len;
768     return s->lookahead;
769 }
770 #endif /* ASMV */
771
772 #ifdef DEBUG
773 /* ===========================================================================
774  * Check that the match at match_start is indeed a match.
775  */
776 local void check_match(s, start, match, length)
777     deflate_state *s;
778     IPos start, match;
779     int length;
780 {
781     /* check that the match is indeed a match */
782     if (zmemcmp((charf *)s->window + match,
783                 (charf *)s->window + start, length) != EQUAL) {
784         fprintf(stderr, " start %u, match %u, length %d\n",
785                 start, match, length);
786         do {
787             fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
788         } while (--length != 0);
789         z_error("invalid match");
790     }
791     if (verbose > 1) {
792         fprintf(stderr,"\\[%d,%d]", start-match, length);
793         do { putc(s->window[start++], stderr); } while (--length != 0);
794     }
795 }
796 #else
797 #  define check_match(s, start, match, length)
798 #endif
799
800 /* ===========================================================================
801  * Fill the window when the lookahead becomes insufficient.
802  * Updates strstart and lookahead.
803  *
804  * IN assertion: lookahead < MIN_LOOKAHEAD
805  * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
806  *    At least one byte has been read, or avail_in == 0; reads are
807  *    performed for at least two bytes (required for the zip translate_eol
808  *    option -- not supported here).
809  */
810 local void fill_window(s)
811     deflate_state *s;
812 {
813     register unsigned n, m;
814     register Posf *p;
815     unsigned more;    /* Amount of free space at the end of the window. */
816     uInt wsize = s->w_size;
817
818     do {
819         more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
820
821         /* Deal with !@#$% 64K limit: */
822         if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
823             more = wsize;
824
825         } else if (more == (unsigned)(-1)) {
826             /* Very unlikely, but possible on 16 bit machine if strstart == 0
827              * and lookahead == 1 (input done one byte at time)
828              */
829             more--;
830
831         /* If the window is almost full and there is insufficient lookahead,
832          * move the upper half to the lower one to make room in the upper half.
833          */
834         } else if (s->strstart >= wsize+MAX_DIST(s)) {
835
836             zmemcpy((charf *)s->window, (charf *)s->window+wsize,
837                    (unsigned)wsize);
838             s->match_start -= wsize;
839             s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
840
841             s->block_start -= (long) wsize;
842
843             /* Slide the hash table (could be avoided with 32 bit values
844                at the expense of memory usage):
845              */
846             n = s->hash_size;
847             p = &s->head[n];
848             do {
849                 m = *--p;
850                 *p = (Pos)(m >= wsize ? m-wsize : NIL);
851             } while (--n);
852
853             n = wsize;
854             p = &s->prev[n];
855             do {
856                 m = *--p;
857                 *p = (Pos)(m >= wsize ? m-wsize : NIL);
858                 /* If n is not on any hash chain, prev[n] is garbage but
859                  * its value will never be used.
860                  */
861             } while (--n);
862
863             more += wsize;
864         }
865         if (s->strm->avail_in == 0) return;
866
867         /* If there was no sliding:
868          *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
869          *    more == window_size - lookahead - strstart
870          * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
871          * => more >= window_size - 2*WSIZE + 2
872          * In the BIG_MEM or MMAP case (not yet supported),
873          *   window_size == input_size + MIN_LOOKAHEAD  &&
874          *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
875          * Otherwise, window_size == 2*WSIZE so more >= 2.
876          * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
877          */
878         Assert(more >= 2, "more < 2");
879
880         n = read_buf(s->strm, (charf *)s->window + s->strstart + s->lookahead,
881                      more);
882         s->lookahead += n;
883
884         /* Initialize the hash value now that we have some input: */
885         if (s->lookahead >= MIN_MATCH) {
886             s->ins_h = s->window[s->strstart];
887             UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
888 #if MIN_MATCH != 3
889             Call UPDATE_HASH() MIN_MATCH-3 more times
890 #endif
891         }
892         /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
893          * but this is not important since only literal bytes will be emitted.
894          */
895
896     } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
897 }
898
899 /* ===========================================================================
900  * Flush the current block, with given end-of-file flag.
901  * IN assertion: strstart is set to the end of the current match.
902  */
903 #define FLUSH_BLOCK_ONLY(s, eof) { \
904    _tr_flush_block(s, (s->block_start >= 0L ? \
905                    (charf *)&s->window[(unsigned)s->block_start] : \
906                    (charf *)Z_NULL), \
907                 (ulg)((long)s->strstart - s->block_start), \
908                 (eof)); \
909    s->block_start = s->strstart; \
910    flush_pending(s->strm); \
911    Tracev((stderr,"[FLUSH]")); \
912 }
913
914 /* Same but force premature exit if necessary. */
915 #define FLUSH_BLOCK(s, eof) { \
916    FLUSH_BLOCK_ONLY(s, eof); \
917    if (s->strm->avail_out == 0) return 1; \
918 }
919
920 /* ===========================================================================
921  * Copy without compression as much as possible from the input stream, return
922  * true if processing was terminated prematurely (no more input or output
923  * space).  This function does not insert new strings in the dictionary
924  * since uncompressible data is probably not useful. This function is used
925  * only for the level=0 compression option.
926  * NOTE: this function should be optimized to avoid extra copying.
927  */
928 local int deflate_stored(s, flush)
929     deflate_state *s;
930     int flush;
931 {
932     for (;;) {
933         /* Fill the window as much as possible: */
934         if (s->lookahead <= 1) {
935
936             Assert(s->strstart < s->w_size+MAX_DIST(s) ||
937                    s->block_start >= (long)s->w_size, "slide too late");
938
939             fill_window(s);
940             if (s->lookahead == 0 && flush == Z_NO_FLUSH) return 1;
941
942             if (s->lookahead == 0) break; /* flush the current block */
943         }
944         Assert(s->block_start >= 0L, "block gone");
945
946         s->strstart += s->lookahead;
947         s->lookahead = 0;
948
949         /* Stored blocks are limited to 0xffff bytes: */
950         if (s->strstart == 0 || s->strstart > 0xffff) {
951             /* strstart == 0 is possible when wraparound on 16-bit machine */
952             s->lookahead = s->strstart - 0xffff;
953             s->strstart = 0xffff;
954         }
955
956         /* Emit a stored block if it is large enough: */
957         if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
958             FLUSH_BLOCK(s, 0);
959         }
960     }
961     FLUSH_BLOCK(s, flush == Z_FINISH);
962     return 0; /* normal exit */
963 }
964
965 /* ===========================================================================
966  * Compress as much as possible from the input stream, return true if
967  * processing was terminated prematurely (no more input or output space).
968  * This function does not perform lazy evaluation of matches and inserts
969  * new strings in the dictionary only for unmatched strings or for short
970  * matches. It is used only for the fast compression options.
971  */
972 local int deflate_fast(s, flush)
973     deflate_state *s;
974     int flush;
975 {
976     IPos hash_head = NIL; /* head of the hash chain */
977     int bflush;           /* set if current block must be flushed */
978
979     for (;;) {
980         /* Make sure that we always have enough lookahead, except
981          * at the end of the input file. We need MAX_MATCH bytes
982          * for the next match, plus MIN_MATCH bytes to insert the
983          * string following the next match.
984          */
985         if (s->lookahead < MIN_LOOKAHEAD) {
986             fill_window(s);
987             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) return 1;
988
989             if (s->lookahead == 0) break; /* flush the current block */
990         }
991
992         /* Insert the string window[strstart .. strstart+2] in the
993          * dictionary, and set hash_head to the head of the hash chain:
994          */
995         if (s->lookahead >= MIN_MATCH) {
996             INSERT_STRING(s, s->strstart, hash_head);
997         }
998
999         /* Find the longest match, discarding those <= prev_length.
1000          * At this point we have always match_length < MIN_MATCH
1001          */
1002         if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1003             /* To simplify the code, we prevent matches with the string
1004              * of window index 0 (in particular we have to avoid a match
1005              * of the string with itself at the start of the input file).
1006              */
1007             if (s->strategy != Z_HUFFMAN_ONLY) {
1008                 s->match_length = longest_match (s, hash_head);
1009             }
1010             /* longest_match() sets match_start */
1011         }
1012         if (s->match_length >= MIN_MATCH) {
1013             check_match(s, s->strstart, s->match_start, s->match_length);
1014
1015             bflush = _tr_tally(s, s->strstart - s->match_start,
1016                                s->match_length - MIN_MATCH);
1017
1018             s->lookahead -= s->match_length;
1019
1020             /* Insert new strings in the hash table only if the match length
1021              * is not too large. This saves time but degrades compression.
1022              */
1023             if (s->match_length <= s->max_insert_length &&
1024                 s->lookahead >= MIN_MATCH) {
1025                 s->match_length--; /* string at strstart already in hash table */
1026                 do {
1027                     s->strstart++;
1028                     INSERT_STRING(s, s->strstart, hash_head);
1029                     /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1030                      * always MIN_MATCH bytes ahead.
1031                      */
1032                 } while (--s->match_length != 0);
1033                 s->strstart++; 
1034             } else {
1035                 s->strstart += s->match_length;
1036                 s->match_length = 0;
1037                 s->ins_h = s->window[s->strstart];
1038                 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1039 #if MIN_MATCH != 3
1040                 Call UPDATE_HASH() MIN_MATCH-3 more times
1041 #endif
1042                 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1043                  * matter since it will be recomputed at next deflate call.
1044                  */
1045             }
1046         } else {
1047             /* No match, output a literal byte */
1048             Tracevv((stderr,"%c", s->window[s->strstart]));
1049             bflush = _tr_tally (s, 0, s->window[s->strstart]);
1050             s->lookahead--;
1051             s->strstart++; 
1052         }
1053         if (bflush) FLUSH_BLOCK(s, 0);
1054     }
1055     FLUSH_BLOCK(s, flush == Z_FINISH);
1056     return 0; /* normal exit */
1057 }
1058
1059 /* ===========================================================================
1060  * Same as above, but achieves better compression. We use a lazy
1061  * evaluation for matches: a match is finally adopted only if there is
1062  * no better match at the next window position.
1063  */
1064 local int deflate_slow(s, flush)
1065     deflate_state *s;
1066     int flush;
1067 {
1068     IPos hash_head = NIL;    /* head of hash chain */
1069     int bflush;              /* set if current block must be flushed */
1070
1071     /* Process the input block. */
1072     for (;;) {
1073         /* Make sure that we always have enough lookahead, except
1074          * at the end of the input file. We need MAX_MATCH bytes
1075          * for the next match, plus MIN_MATCH bytes to insert the
1076          * string following the next match.
1077          */
1078         if (s->lookahead < MIN_LOOKAHEAD) {
1079             fill_window(s);
1080             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) return 1;
1081
1082             if (s->lookahead == 0) break; /* flush the current block */
1083         }
1084
1085         /* Insert the string window[strstart .. strstart+2] in the
1086          * dictionary, and set hash_head to the head of the hash chain:
1087          */
1088         if (s->lookahead >= MIN_MATCH) {
1089             INSERT_STRING(s, s->strstart, hash_head);
1090         }
1091
1092         /* Find the longest match, discarding those <= prev_length.
1093          */
1094         s->prev_length = s->match_length, s->prev_match = s->match_start;
1095         s->match_length = MIN_MATCH-1;
1096
1097         if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
1098             s->strstart - hash_head <= MAX_DIST(s)) {
1099             /* To simplify the code, we prevent matches with the string
1100              * of window index 0 (in particular we have to avoid a match
1101              * of the string with itself at the start of the input file).
1102              */
1103             if (s->strategy != Z_HUFFMAN_ONLY) {
1104                 s->match_length = longest_match (s, hash_head);
1105             }
1106             /* longest_match() sets match_start */
1107
1108             if (s->match_length <= 5 && (s->strategy == Z_FILTERED ||
1109                  (s->match_length == MIN_MATCH &&
1110                   s->strstart - s->match_start > TOO_FAR))) {
1111
1112                 /* If prev_match is also MIN_MATCH, match_start is garbage
1113                  * but we will ignore the current match anyway.
1114                  */
1115                 s->match_length = MIN_MATCH-1;
1116             }
1117         }
1118         /* If there was a match at the previous step and the current
1119          * match is not better, output the previous match:
1120          */
1121         if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
1122             uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
1123             /* Do not insert strings in hash table beyond this. */
1124
1125             check_match(s, s->strstart-1, s->prev_match, s->prev_length);
1126
1127             bflush = _tr_tally(s, s->strstart -1 - s->prev_match,
1128                                s->prev_length - MIN_MATCH);
1129
1130             /* Insert in hash table all strings up to the end of the match.
1131              * strstart-1 and strstart are already inserted. If there is not
1132              * enough lookahead, the last two strings are not inserted in
1133              * the hash table.
1134              */
1135             s->lookahead -= s->prev_length-1;
1136             s->prev_length -= 2;
1137             do {
1138                 if (++s->strstart <= max_insert) {
1139                     INSERT_STRING(s, s->strstart, hash_head);
1140                 }
1141             } while (--s->prev_length != 0);
1142             s->match_available = 0;
1143             s->match_length = MIN_MATCH-1;
1144             s->strstart++;
1145
1146             if (bflush) FLUSH_BLOCK(s, 0);
1147
1148         } else if (s->match_available) {
1149             /* If there was no match at the previous position, output a
1150              * single literal. If there was a match but the current match
1151              * is longer, truncate the previous match to a single literal.
1152              */
1153             Tracevv((stderr,"%c", s->window[s->strstart-1]));
1154             if (_tr_tally (s, 0, s->window[s->strstart-1])) {
1155                 FLUSH_BLOCK_ONLY(s, 0);
1156             }
1157             s->strstart++;
1158             s->lookahead--;
1159             if (s->strm->avail_out == 0) return 1;
1160         } else {
1161             /* There is no previous match to compare with, wait for
1162              * the next step to decide.
1163              */
1164             s->match_available = 1;
1165             s->strstart++;
1166             s->lookahead--;
1167         }
1168     }
1169     Assert (flush != Z_NO_FLUSH, "no flush?");
1170     if (s->match_available) {
1171         Tracevv((stderr,"%c", s->window[s->strstart-1]));
1172         _tr_tally (s, 0, s->window[s->strstart-1]);
1173         s->match_available = 0;
1174     }
1175     FLUSH_BLOCK(s, flush == Z_FINISH);
1176     return 0;
1177 }
1178