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