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