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