blob: 9270af326e895558ab91d2270525049eef830a8c [file] [log] [blame]
rjw1f884582022-01-06 17:20:42 +08001/* deflate.c -- compress data using the deflation algorithm
2 * Copyright (C) 1995-2005 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/*
7 * ALGORITHM
8 *
9 * The "deflation" process depends on being able to identify portions
10 * of the input text which are identical to earlier input (within a
11 * sliding window trailing behind the input currently being processed).
12 *
13 * The most straightforward technique turns out to be the fastest for
14 * most input files: try all possible matches and select the longest.
15 * The key feature of this algorithm is that insertions into the string
16 * dictionary are very simple and thus fast, and deletions are avoided
17 * completely. Insertions are performed at each input character, whereas
18 * string matches are performed only when the previous match ends. So it
19 * is preferable to spend more time in matches to allow very fast string
20 * insertions and avoid deletions. The matching algorithm for small
21 * strings is inspired from that of Rabin & Karp. A brute force approach
22 * is used to find longer strings when a small match has been found.
23 * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
24 * (by Leonid Broukhis).
25 * A previous version of this file used a more sophisticated algorithm
26 * (by Fiala and Greene) which is guaranteed to run in linear amortized
27 * time, but has a larger average cost, uses more memory and is patented.
28 * However the F&G algorithm may be faster for some highly redundant
29 * files if the parameter max_chain_length (described below) is too large.
30 *
31 * ACKNOWLEDGEMENTS
32 *
33 * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
34 * I found it in 'freeze' written by Leonid Broukhis.
35 * Thanks to many people for bug reports and testing.
36 *
37 * REFERENCES
38 *
39 * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
40 * Available in http://www.ietf.org/rfc/rfc1951.txt
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 "deflate.h"
53
54#undef Assert
55#define Assert(cond,msg)
56#undef Trace
57#define Trace(x)
58#undef Tracecv
59#define Tracecv(x,y)
60#undef Tracev
61#define Tracev(x)
62#undef Tracevv
63#define Tracevv(x)
64
65#if defined(DEBUG)
66#undef DEBUG
67#endif
68
69const char deflate_copyright[] =
70 " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
71/*
72 If you use the zlib library in a product, an acknowledgment is welcome
73 in the documentation of your product. If for some reason you cannot
74 include such an acknowledgment, I would appreciate that you keep this
75 copyright string in the executable of your product.
76 */
77
78/* ===========================================================================
79 * Function prototypes.
80 */
81typedef enum {
82 need_more, /* block not completed, need more input or more output */
83 block_done, /* block flush performed */
84 finish_started, /* finish started, need only more output at next deflate */
85 finish_done /* finish done, accept no more input or output */
86} block_state;
87
88typedef block_state (*compress_func) OF((deflate_state *s, int flush));
89/* Compression function. Returns the block state after the call. */
90
91local void fill_window OF((deflate_state *s));
92local block_state deflate_stored OF((deflate_state *s, int flush));
93local block_state deflate_fast OF((deflate_state *s, int flush));
94#ifndef FASTEST
95local block_state deflate_slow OF((deflate_state *s, int flush));
96#endif
97local void lm_init OF((deflate_state *s));
98local void putShortMSB OF((deflate_state *s, uInt b));
99local void flush_pending OF((z_streamp strm));
100local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
101#ifndef FASTEST
102#ifdef ASMV
103void match_init OF((void)); /* asm code initialization */
104uInt longest_match OF((deflate_state *s, IPos cur_match));
105#else
106local uInt longest_match OF((deflate_state *s, IPos cur_match));
107#endif
108#endif
109local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
110
111#ifdef DEBUG
112local void check_match OF((deflate_state *s, IPos start, IPos match,
113 int length));
114#endif
115
116/* ===========================================================================
117 * Local data
118 */
119
120#define NIL 0
121/* Tail of hash chains */
122
123#ifndef TOO_FAR
124# define TOO_FAR 4096
125#endif
126/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
127
128#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
129/* Minimum amount of lookahead, except at the end of the input file.
130 * See deflate.c for comments about the MIN_MATCH+1.
131 */
132
133/* Values for max_lazy_match, good_match and max_chain_length, depending on
134 * the desired pack level (0..9). The values given below have been tuned to
135 * exclude worst case performance for pathological files. Better values may be
136 * found for specific files.
137 */
138typedef struct config_s {
139 ush good_length; /* reduce lazy search above this match length */
140 ush max_lazy; /* do not perform lazy search above this match length */
141 ush nice_length; /* quit search above this match length */
142 ush max_chain;
143 compress_func func;
144} config;
145
146#ifdef FASTEST
147local const config configuration_table[2] = {
148 /* good lazy nice chain */
149 /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
150 /* 1 */ {4, 4, 8, 4, deflate_fast}
151}; /* max speed, no lazy matches */
152#else
153local const config configuration_table[10] = {
154 /* good lazy nice chain */
155 /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
156 /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
157 /* 2 */ {4, 5, 16, 8, deflate_fast},
158 /* 3 */ {4, 6, 32, 32, deflate_fast},
159
160 /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
161 /* 5 */ {8, 16, 32, 32, deflate_slow},
162 /* 6 */ {8, 16, 128, 128, deflate_slow},
163 /* 7 */ {8, 32, 128, 256, deflate_slow},
164 /* 8 */ {32, 128, 258, 1024, deflate_slow},
165 /* 9 */ {32, 258, 258, 4096, deflate_slow}
166}; /* max compression */
167#endif
168
169/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
170 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
171 * meaning.
172 */
173
174#define EQUAL 0
175/* result of memcmp for equal strings */
176
177#ifndef NO_DUMMY_DECL
178struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
179#endif
180
181/* ===========================================================================
182 * Update a hash value with the given input byte
183 * IN assertion: all calls to to UPDATE_HASH are made with consecutive
184 * input characters, so that a running hash key can be computed from the
185 * previous key instead of complete recalculation each time.
186 */
187#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
188
189
190/* ===========================================================================
191 * Insert string str in the dictionary and set match_head to the previous head
192 * of the hash chain (the most recent string with same hash key). Return
193 * the previous length of the hash chain.
194 * If this file is compiled with -DFASTEST, the compression level is forced
195 * to 1, and no hash chains are maintained.
196 * IN assertion: all calls to to INSERT_STRING are made with consecutive
197 * input characters and the first MIN_MATCH bytes of str are valid
198 * (except for the last MIN_MATCH-1 bytes of the input file).
199 */
200#ifdef FASTEST
201#define INSERT_STRING(s, str, match_head) \
202 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
203 match_head = s->head[s->ins_h], \
204 s->head[s->ins_h] = (Pos)(str))
205#else
206#define INSERT_STRING(s, str, match_head) \
207 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
208 match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
209 s->head[s->ins_h] = (Pos)(str))
210#endif
211
212/* ===========================================================================
213 * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
214 * prev[] will be initialized on the fly.
215 */
216#define CLEAR_HASH(s) \
217 s->head[s->hash_size-1] = NIL; \
218 zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
219
220/* ========================================================================= */
221int ZEXPORT deflateInit_(strm, level, version, stream_size)
222z_streamp strm;
223int level;
224const char *version;
225int stream_size;
226{
227 return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
228 Z_DEFAULT_STRATEGY, version, stream_size);
229 /* To do: ignore strm->next_in if we use it as window */
230}
231
232/* ========================================================================= */
233int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
234 version, stream_size)
235z_streamp strm;
236int level;
237int method;
238int windowBits;
239int memLevel;
240int strategy;
241const char *version;
242int stream_size;
243{
244 deflate_state *s;
245 int wrap = 1;
246 static const char my_version[] = ZLIB_VERSION;
247
248 ushf *overlay;
249 /* We overlay pending_buf and d_buf+l_buf. This works since the average
250 * output size for (length,distance) codes is <= 24 bits.
251 */
252
253 if (version == Z_NULL || version[0] != my_version[0] ||
254 stream_size != sizeof(z_stream)) {
255 return Z_VERSION_ERROR;
256 }
257 if (strm == Z_NULL) return Z_STREAM_ERROR;
258
259 strm->msg = Z_NULL;
260 if (strm->zalloc == (alloc_func)0) {
261 strm->zalloc = zcalloc;
262 strm->opaque = (voidpf)0;
263 }
264 if (strm->zfree == (free_func)0) strm->zfree = zcfree;
265
266#ifdef FASTEST
267 if (level != 0) level = 1;
268#else
269 if (level == Z_DEFAULT_COMPRESSION) level = 6;
270#endif
271
272 if (windowBits < 0) { /* suppress zlib wrapper */
273 wrap = 0;
274 windowBits = -windowBits;
275 }
276#ifdef GZIP
277 else if (windowBits > 15) {
278 wrap = 2; /* write gzip wrapper instead */
279 windowBits -= 16;
280 }
281#endif
282 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
283 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
284 strategy < 0 || strategy > Z_FIXED) {
285 return Z_STREAM_ERROR;
286 }
287 if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
288 s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
289 if (s == Z_NULL) return Z_MEM_ERROR;
290 strm->state = (struct internal_state FAR *)s;
291 s->strm = strm;
292
293 s->wrap = wrap;
294 s->gzhead = Z_NULL;
295 s->w_bits = windowBits;
296 s->w_size = 1 << s->w_bits;
297 s->w_mask = s->w_size - 1;
298
299 s->hash_bits = memLevel + 7;
300 s->hash_size = 1 << s->hash_bits;
301 s->hash_mask = s->hash_size - 1;
302 s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
303
304 s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
305 s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
306 s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
307
308 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
309
310 overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
311 s->pending_buf = (uchf *) overlay;
312 s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
313
314 if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
315 s->pending_buf == Z_NULL) {
316 s->status = FINISH_STATE;
317 strm->msg = (char *)ERR_MSG(Z_MEM_ERROR);
318 deflateEnd (strm);
319 return Z_MEM_ERROR;
320 }
321 s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
322 s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
323
324 s->level = level;
325 s->strategy = strategy;
326 s->method = (Byte)method;
327
328 return deflateReset(strm);
329}
330
331/* ========================================================================= */
332int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
333z_streamp strm;
334const Bytef *dictionary;
335uInt dictLength;
336{
337 deflate_state *s;
338 uInt length = dictLength;
339 uInt n;
340 IPos hash_head = 0;
341
342 if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
343 strm->state->wrap == 2 ||
344 (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
345 return Z_STREAM_ERROR;
346
347 s = strm->state;
348 if (s->wrap)
349 strm->adler = adler32(strm->adler, dictionary, dictLength);
350
351 if (length < MIN_MATCH) return Z_OK;
352 if (length > MAX_DIST(s)) {
353 length = MAX_DIST(s);
354 dictionary += dictLength - length; /* use the tail of the dictionary */
355 }
356 zmemcpy(s->window, dictionary, length);
357 s->strstart = length;
358 s->block_start = (long)length;
359
360 /* Insert all strings in the hash table (except for the last two bytes).
361 * s->lookahead stays null, so s->ins_h will be recomputed at the next
362 * call of fill_window.
363 */
364 s->ins_h = s->window[0];
365 UPDATE_HASH(s, s->ins_h, s->window[1]);
366 for (n = 0; n <= length - MIN_MATCH; n++) {
367 INSERT_STRING(s, n, hash_head);
368 }
369 if (hash_head) hash_head = 0; /* to make compiler happy */
370 return Z_OK;
371}
372
373/* ========================================================================= */
374int ZEXPORT deflateReset (strm)
375z_streamp strm;
376{
377 deflate_state *s;
378
379 if (strm == Z_NULL || strm->state == Z_NULL ||
380 strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
381 return Z_STREAM_ERROR;
382 }
383
384 strm->total_in = strm->total_out = 0;
385 strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
386 strm->data_type = Z_UNKNOWN;
387
388 s = (deflate_state *)strm->state;
389 s->pending = 0;
390 s->pending_out = s->pending_buf;
391
392 if (s->wrap < 0) {
393 s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
394 }
395 s->status = s->wrap ? INIT_STATE : BUSY_STATE;
396 strm->adler =
397#ifdef GZIP
398 s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
399#endif
400 adler32(0L, Z_NULL, 0);
401 s->last_flush = Z_NO_FLUSH;
402
403 _tr_init(s);
404 lm_init(s);
405
406 return Z_OK;
407}
408
409/* ========================================================================= */
410int ZEXPORT deflateSetHeader (strm, head)
411z_streamp strm;
412gz_headerp head;
413{
414 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
415 if (strm->state->wrap != 2) return Z_STREAM_ERROR;
416 strm->state->gzhead = head;
417 return Z_OK;
418}
419
420/* ========================================================================= */
421int ZEXPORT deflatePrime (strm, bits, value)
422z_streamp strm;
423int bits;
424int value;
425{
426 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
427 strm->state->bi_valid = bits;
428 strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
429 return Z_OK;
430}
431
432/* ========================================================================= */
433int ZEXPORT deflateParams(strm, level, strategy)
434z_streamp strm;
435int level;
436int strategy;
437{
438 deflate_state *s;
439 compress_func func;
440 int err = Z_OK;
441
442 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
443 s = strm->state;
444
445#ifdef FASTEST
446 if (level != 0) level = 1;
447#else
448 if (level == Z_DEFAULT_COMPRESSION) level = 6;
449#endif
450 if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
451 return Z_STREAM_ERROR;
452 }
453 func = configuration_table[s->level].func;
454
455 if (func != configuration_table[level].func && strm->total_in != 0) {
456 /* Flush the last buffer: */
457 err = deflate(strm, Z_PARTIAL_FLUSH);
458 }
459 if (s->level != level) {
460 s->level = level;
461 s->max_lazy_match = configuration_table[level].max_lazy;
462 s->good_match = configuration_table[level].good_length;
463 s->nice_match = configuration_table[level].nice_length;
464 s->max_chain_length = configuration_table[level].max_chain;
465 }
466 s->strategy = strategy;
467 return err;
468}
469
470/* ========================================================================= */
471int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
472z_streamp strm;
473int good_length;
474int max_lazy;
475int nice_length;
476int max_chain;
477{
478 deflate_state *s;
479
480 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
481 s = strm->state;
482 s->good_match = good_length;
483 s->max_lazy_match = max_lazy;
484 s->nice_match = nice_length;
485 s->max_chain_length = max_chain;
486 return Z_OK;
487}
488
489/* =========================================================================
490 * For the default windowBits of 15 and memLevel of 8, this function returns
491 * a close to exact, as well as small, upper bound on the compressed size.
492 * They are coded as constants here for a reason--if the #define's are
493 * changed, then this function needs to be changed as well. The return
494 * value for 15 and 8 only works for those exact settings.
495 *
496 * For any setting other than those defaults for windowBits and memLevel,
497 * the value returned is a conservative worst case for the maximum expansion
498 * resulting from using fixed blocks instead of stored blocks, which deflate
499 * can emit on compressed data for some combinations of the parameters.
500 *
501 * This function could be more sophisticated to provide closer upper bounds
502 * for every combination of windowBits and memLevel, as well as wrap.
503 * But even the conservative upper bound of about 14% expansion does not
504 * seem onerous for output buffer allocation.
505 */
506uLong ZEXPORT deflateBound(strm, sourceLen)
507z_streamp strm;
508uLong sourceLen;
509{
510 deflate_state *s;
511 uLong destLen;
512
513 /* conservative upper bound */
514 destLen = sourceLen +
515 ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
516
517 /* if can't get parameters, return conservative bound */
518 if (strm == Z_NULL || strm->state == Z_NULL)
519 return destLen;
520
521 /* if not default parameters, return conservative bound */
522 s = strm->state;
523 if (s->w_bits != 15 || s->hash_bits != 8 + 7)
524 return destLen;
525
526 /* default settings: return tight bound for that case */
527 return compressBound(sourceLen);
528}
529
530/* =========================================================================
531 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
532 * IN assertion: the stream state is correct and there is enough room in
533 * pending_buf.
534 */
535local void putShortMSB (s, b)
536deflate_state *s;
537uInt b;
538{
539 put_byte(s, (Byte)(b >> 8));
540 put_byte(s, (Byte)(b & 0xff));
541}
542
543/* =========================================================================
544 * Flush as much pending output as possible. All deflate() output goes
545 * through this function so some applications may wish to modify it
546 * to avoid allocating a large strm->next_out buffer and copying into it.
547 * (See also read_buf()).
548 */
549local void flush_pending(strm)
550z_streamp strm;
551{
552 unsigned len = strm->state->pending;
553
554 if (len > strm->avail_out) len = strm->avail_out;
555 if (len == 0) return;
556
557 zmemcpy(strm->next_out, strm->state->pending_out, len);
558 strm->next_out += len;
559 strm->state->pending_out += len;
560 strm->total_out += len;
561 strm->avail_out -= len;
562 strm->state->pending -= len;
563 if (strm->state->pending == 0) {
564 strm->state->pending_out = strm->state->pending_buf;
565 }
566}
567
568/* ========================================================================= */
569int ZEXPORT deflate (strm, flush)
570z_streamp strm;
571int flush;
572{
573 int old_flush; /* value of flush param for previous deflate call */
574 deflate_state *s;
575
576 if (strm == Z_NULL || strm->state == Z_NULL ||
577 flush > Z_FINISH || flush < 0) {
578 return Z_STREAM_ERROR;
579 }
580 s = strm->state;
581
582 if (strm->next_out == Z_NULL ||
583 (strm->next_in == Z_NULL && strm->avail_in != 0) ||
584 (s->status == FINISH_STATE && flush != Z_FINISH)) {
585 ERR_RETURN(strm, Z_STREAM_ERROR);
586 }
587 if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
588
589 s->strm = strm; /* just in case */
590 old_flush = s->last_flush;
591 s->last_flush = flush;
592
593 /* Write the header */
594 if (s->status == INIT_STATE) {
595#ifdef GZIP
596 if (s->wrap == 2) {
597 strm->adler = crc32(0L, Z_NULL, 0);
598 put_byte(s, 31);
599 put_byte(s, 139);
600 put_byte(s, 8);
601 if (s->gzhead == NULL) {
602 put_byte(s, 0);
603 put_byte(s, 0);
604 put_byte(s, 0);
605 put_byte(s, 0);
606 put_byte(s, 0);
607 put_byte(s, s->level == 9 ? 2 :
608 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
609 4 : 0));
610 put_byte(s, OS_CODE);
611 s->status = BUSY_STATE;
612 } else {
613 put_byte(s, (s->gzhead->text ? 1 : 0) +
614 (s->gzhead->hcrc ? 2 : 0) +
615 (s->gzhead->extra == Z_NULL ? 0 : 4) +
616 (s->gzhead->name == Z_NULL ? 0 : 8) +
617 (s->gzhead->comment == Z_NULL ? 0 : 16)
618 );
619 put_byte(s, (Byte)(s->gzhead->time & 0xff));
620 put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
621 put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
622 put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
623 put_byte(s, s->level == 9 ? 2 :
624 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
625 4 : 0));
626 put_byte(s, s->gzhead->os & 0xff);
627 if (s->gzhead->extra != NULL) {
628 put_byte(s, s->gzhead->extra_len & 0xff);
629 put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
630 }
631 if (s->gzhead->hcrc)
632 strm->adler = crc32(strm->adler, s->pending_buf,
633 s->pending);
634 s->gzindex = 0;
635 s->status = EXTRA_STATE;
636 }
637 } else
638#endif
639 {
640 uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
641 uInt level_flags;
642
643 if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
644 level_flags = 0;
645 else if (s->level < 6)
646 level_flags = 1;
647 else if (s->level == 6)
648 level_flags = 2;
649 else
650 level_flags = 3;
651 header |= (level_flags << 6);
652 if (s->strstart != 0) header |= PRESET_DICT;
653 header += 31 - (header % 31);
654
655 s->status = BUSY_STATE;
656 putShortMSB(s, header);
657
658 /* Save the adler32 of the preset dictionary: */
659 if (s->strstart != 0) {
660 putShortMSB(s, (uInt)(strm->adler >> 16));
661 putShortMSB(s, (uInt)(strm->adler & 0xffff));
662 }
663 strm->adler = adler32(0L, Z_NULL, 0);
664 }
665 }
666#ifdef GZIP
667 if (s->status == EXTRA_STATE) {
668 if (s->gzhead->extra != NULL) {
669 uInt beg = s->pending; /* start of bytes to update crc */
670
671 while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
672 if (s->pending == s->pending_buf_size) {
673 if (s->gzhead->hcrc && s->pending > beg)
674 strm->adler = crc32(strm->adler, s->pending_buf + beg,
675 s->pending - beg);
676 flush_pending(strm);
677 beg = s->pending;
678 if (s->pending == s->pending_buf_size)
679 break;
680 }
681 put_byte(s, s->gzhead->extra[s->gzindex]);
682 s->gzindex++;
683 }
684 if (s->gzhead->hcrc && s->pending > beg)
685 strm->adler = crc32(strm->adler, s->pending_buf + beg,
686 s->pending - beg);
687 if (s->gzindex == s->gzhead->extra_len) {
688 s->gzindex = 0;
689 s->status = NAME_STATE;
690 }
691 } else
692 s->status = NAME_STATE;
693 }
694 if (s->status == NAME_STATE) {
695 if (s->gzhead->name != NULL) {
696 uInt beg = s->pending; /* start of bytes to update crc */
697 int val;
698
699 do {
700 if (s->pending == s->pending_buf_size) {
701 if (s->gzhead->hcrc && s->pending > beg)
702 strm->adler = crc32(strm->adler, s->pending_buf + beg,
703 s->pending - beg);
704 flush_pending(strm);
705 beg = s->pending;
706 if (s->pending == s->pending_buf_size) {
707 val = 1;
708 break;
709 }
710 }
711 val = s->gzhead->name[s->gzindex++];
712 put_byte(s, val);
713 } while (val != 0);
714 if (s->gzhead->hcrc && s->pending > beg)
715 strm->adler = crc32(strm->adler, s->pending_buf + beg,
716 s->pending - beg);
717 if (val == 0) {
718 s->gzindex = 0;
719 s->status = COMMENT_STATE;
720 }
721 } else
722 s->status = COMMENT_STATE;
723 }
724 if (s->status == COMMENT_STATE) {
725 if (s->gzhead->comment != NULL) {
726 uInt beg = s->pending; /* start of bytes to update crc */
727 int val;
728
729 do {
730 if (s->pending == s->pending_buf_size) {
731 if (s->gzhead->hcrc && s->pending > beg)
732 strm->adler = crc32(strm->adler, s->pending_buf + beg,
733 s->pending - beg);
734 flush_pending(strm);
735 beg = s->pending;
736 if (s->pending == s->pending_buf_size) {
737 val = 1;
738 break;
739 }
740 }
741 val = s->gzhead->comment[s->gzindex++];
742 put_byte(s, val);
743 } while (val != 0);
744 if (s->gzhead->hcrc && s->pending > beg)
745 strm->adler = crc32(strm->adler, s->pending_buf + beg,
746 s->pending - beg);
747 if (val == 0)
748 s->status = HCRC_STATE;
749 } else
750 s->status = HCRC_STATE;
751 }
752 if (s->status == HCRC_STATE) {
753 if (s->gzhead->hcrc) {
754 if (s->pending + 2 > s->pending_buf_size)
755 flush_pending(strm);
756 if (s->pending + 2 <= s->pending_buf_size) {
757 put_byte(s, (Byte)(strm->adler & 0xff));
758 put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
759 strm->adler = crc32(0L, Z_NULL, 0);
760 s->status = BUSY_STATE;
761 }
762 } else
763 s->status = BUSY_STATE;
764 }
765#endif
766
767 /* Flush as much pending output as possible */
768 if (s->pending != 0) {
769 flush_pending(strm);
770 if (strm->avail_out == 0) {
771 /* Since avail_out is 0, deflate will be called again with
772 * more output space, but possibly with both pending and
773 * avail_in equal to zero. There won't be anything to do,
774 * but this is not an error situation so make sure we
775 * return OK instead of BUF_ERROR at next call of deflate:
776 */
777 s->last_flush = -1;
778 return Z_OK;
779 }
780
781 /* Make sure there is something to do and avoid duplicate consecutive
782 * flushes. For repeated and useless calls with Z_FINISH, we keep
783 * returning Z_STREAM_END instead of Z_BUF_ERROR.
784 */
785 } else if (strm->avail_in == 0 && flush <= old_flush &&
786 flush != Z_FINISH) {
787 ERR_RETURN(strm, Z_BUF_ERROR);
788 }
789
790 /* User must not provide more input after the first FINISH: */
791 if (s->status == FINISH_STATE && strm->avail_in != 0) {
792 ERR_RETURN(strm, Z_BUF_ERROR);
793 }
794
795 /* Start a new block or continue the current one.
796 */
797 if (strm->avail_in != 0 || s->lookahead != 0 ||
798 (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
799 block_state bstate;
800
801 bstate = (*(configuration_table[s->level].func))(s, flush);
802
803 if (bstate == finish_started || bstate == finish_done) {
804 s->status = FINISH_STATE;
805 }
806 if (bstate == need_more || bstate == finish_started) {
807 if (strm->avail_out == 0) {
808 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
809 }
810 return Z_OK;
811 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
812 * of deflate should use the same flush parameter to make sure
813 * that the flush is complete. So we don't have to output an
814 * empty block here, this will be done at next call. This also
815 * ensures that for a very small output buffer, we emit at most
816 * one empty block.
817 */
818 }
819 if (bstate == block_done) {
820 if (flush == Z_PARTIAL_FLUSH) {
821 _tr_align(s);
822 } else { /* FULL_FLUSH or SYNC_FLUSH */
823 _tr_stored_block(s, (char *)0, 0L, 0);
824 /* For a full flush, this empty block will be recognized
825 * as a special marker by inflate_sync().
826 */
827 if (flush == Z_FULL_FLUSH) {
828 CLEAR_HASH(s); /* forget history */
829 }
830 }
831 flush_pending(strm);
832 if (strm->avail_out == 0) {
833 s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
834 return Z_OK;
835 }
836 }
837 }
838 Assert(strm->avail_out > 0, "bug2");
839
840 if (flush != Z_FINISH) return Z_OK;
841 if (s->wrap <= 0) return Z_STREAM_END;
842
843 /* Write the trailer */
844#ifdef GZIP
845 if (s->wrap == 2) {
846 put_byte(s, (Byte)(strm->adler & 0xff));
847 put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
848 put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
849 put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
850 put_byte(s, (Byte)(strm->total_in & 0xff));
851 put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
852 put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
853 put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
854 } else
855#endif
856 {
857 putShortMSB(s, (uInt)(strm->adler >> 16));
858 putShortMSB(s, (uInt)(strm->adler & 0xffff));
859 }
860 flush_pending(strm);
861 /* If avail_out is zero, the application will call deflate again
862 * to flush the rest.
863 */
864 if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
865 return s->pending != 0 ? Z_OK : Z_STREAM_END;
866}
867
868/* ========================================================================= */
869int ZEXPORT deflateEnd (strm)
870z_streamp strm;
871{
872 int status;
873
874 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
875
876 status = strm->state->status;
877 if (status != INIT_STATE &&
878 status != EXTRA_STATE &&
879 status != NAME_STATE &&
880 status != COMMENT_STATE &&
881 status != HCRC_STATE &&
882 status != BUSY_STATE &&
883 status != FINISH_STATE) {
884 return Z_STREAM_ERROR;
885 }
886
887 /* Deallocate in reverse order of allocations: */
888 TRY_FREE(strm, strm->state->pending_buf);
889 TRY_FREE(strm, strm->state->head);
890 TRY_FREE(strm, strm->state->prev);
891 TRY_FREE(strm, strm->state->window);
892
893 ZFREE(strm, strm->state);
894 strm->state = Z_NULL;
895
896 return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
897}
898
899/* =========================================================================
900 * Copy the source state to the destination state.
901 * To simplify the source, this is not supported for 16-bit MSDOS (which
902 * doesn't have enough memory anyway to duplicate compression states).
903 */
904int ZEXPORT deflateCopy (dest, source)
905z_streamp dest;
906z_streamp source;
907{
908#ifdef MAXSEG_64K
909 return Z_STREAM_ERROR;
910#else
911 deflate_state *ds;
912 deflate_state *ss;
913 ushf *overlay;
914
915
916 if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
917 return Z_STREAM_ERROR;
918 }
919
920 ss = source->state;
921
922 zmemcpy(dest, source, sizeof(z_stream));
923
924 ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
925 if (ds == Z_NULL) return Z_MEM_ERROR;
926 dest->state = (struct internal_state FAR *) ds;
927 zmemcpy(ds, ss, sizeof(deflate_state));
928 ds->strm = dest;
929
930 ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
931 ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
932 ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
933 overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
934 ds->pending_buf = (uchf *) overlay;
935
936 if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
937 ds->pending_buf == Z_NULL) {
938 deflateEnd (dest);
939 return Z_MEM_ERROR;
940 }
941 /* following zmemcpy do not work for 16-bit MSDOS */
942 zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
943 zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
944 zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
945 zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
946
947 ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
948 ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
949 ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
950
951 ds->l_desc.dyn_tree = ds->dyn_ltree;
952 ds->d_desc.dyn_tree = ds->dyn_dtree;
953 ds->bl_desc.dyn_tree = ds->bl_tree;
954
955 return Z_OK;
956#endif /* MAXSEG_64K */
957}
958
959/* ===========================================================================
960 * Read a new buffer from the current input stream, update the adler32
961 * and total number of bytes read. All deflate() input goes through
962 * this function so some applications may wish to modify it to avoid
963 * allocating a large strm->next_in buffer and copying from it.
964 * (See also flush_pending()).
965 */
966local int read_buf(strm, buf, size)
967z_streamp strm;
968Bytef *buf;
969unsigned size;
970{
971 unsigned len = strm->avail_in;
972
973 if (len > size) len = size;
974 if (len == 0) return 0;
975
976 strm->avail_in -= len;
977
978 if (strm->state->wrap == 1) {
979 strm->adler = adler32(strm->adler, strm->next_in, len);
980 }
981#ifdef GZIP
982 else if (strm->state->wrap == 2) {
983 strm->adler = crc32(strm->adler, strm->next_in, len);
984 }
985#endif
986 zmemcpy(buf, strm->next_in, len);
987 strm->next_in += len;
988 strm->total_in += len;
989
990 return (int)len;
991}
992
993/* ===========================================================================
994 * Initialize the "longest match" routines for a new zlib stream
995 */
996local void lm_init (s)
997deflate_state *s;
998{
999 s->window_size = (ulg)2L*s->w_size;
1000
1001 CLEAR_HASH(s);
1002
1003 /* Set the default configuration parameters:
1004 */
1005 s->max_lazy_match = configuration_table[s->level].max_lazy;
1006 s->good_match = configuration_table[s->level].good_length;
1007 s->nice_match = configuration_table[s->level].nice_length;
1008 s->max_chain_length = configuration_table[s->level].max_chain;
1009
1010 s->strstart = 0;
1011 s->block_start = 0L;
1012 s->lookahead = 0;
1013 s->match_length = s->prev_length = MIN_MATCH-1;
1014 s->match_available = 0;
1015 s->ins_h = 0;
1016#ifndef FASTEST
1017#ifdef ASMV
1018 match_init(); /* initialize the asm code */
1019#endif
1020#endif
1021}
1022
1023#ifndef FASTEST
1024/* ===========================================================================
1025 * Set match_start to the longest match starting at the given string and
1026 * return its length. Matches shorter or equal to prev_length are discarded,
1027 * in which case the result is equal to prev_length and match_start is
1028 * garbage.
1029 * IN assertions: cur_match is the head of the hash chain for the current
1030 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1031 * OUT assertion: the match length is not greater than s->lookahead.
1032 */
1033#ifndef ASMV
1034/* For 80x86 and 680x0, an optimized version will be provided in match.asm or
1035 * match.S. The code will be functionally equivalent.
1036 */
1037local uInt longest_match(s, cur_match)
1038deflate_state *s;
1039IPos cur_match; /* current match */
1040{
1041 unsigned chain_length = s->max_chain_length;/* max hash chain length */
1042 register Bytef *scan = s->window + s->strstart; /* current string */
1043 register Bytef *match; /* matched string */
1044 register int len; /* length of current match */
1045 int best_len = s->prev_length; /* best match length so far */
1046 int nice_match = s->nice_match; /* stop if match long enough */
1047 IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
1048 s->strstart - (IPos)MAX_DIST(s) : NIL;
1049 /* Stop when cur_match becomes <= limit. To simplify the code,
1050 * we prevent matches with the string of window index 0.
1051 */
1052 Posf *prev = s->prev;
1053 uInt wmask = s->w_mask;
1054
1055#ifdef UNALIGNED_OK
1056 /* Compare two bytes at a time. Note: this is not always beneficial.
1057 * Try with and without -DUNALIGNED_OK to check.
1058 */
1059 register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
1060 register ush scan_start = *(ushf *)scan;
1061 register ush scan_end = *(ushf *)(scan+best_len-1);
1062#else
1063 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1064 register Byte scan_end1 = scan[best_len-1];
1065 register Byte scan_end = scan[best_len];
1066#endif
1067
1068 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1069 * It is easy to get rid of this optimization if necessary.
1070 */
1071 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1072
1073 /* Do not waste too much time if we already have a good match: */
1074 if (s->prev_length >= s->good_match) {
1075 chain_length >>= 2;
1076 }
1077 /* Do not look for matches beyond the end of the input. This is necessary
1078 * to make deflate deterministic.
1079 */
1080 if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
1081
1082 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1083
1084 do {
1085 Assert(cur_match < s->strstart, "no future");
1086 match = s->window + cur_match;
1087
1088 /* Skip to next match if the match length cannot increase
1089 * or if the match length is less than 2. Note that the checks below
1090 * for insufficient lookahead only occur occasionally for performance
1091 * reasons. Therefore uninitialized memory will be accessed, and
1092 * conditional jumps will be made that depend on those values.
1093 * However the length of the match is limited to the lookahead, so
1094 * the output of deflate is not affected by the uninitialized values.
1095 */
1096#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
1097 /* This code assumes sizeof(unsigned short) == 2. Do not use
1098 * UNALIGNED_OK if your compiler uses a different size.
1099 */
1100 if (*(ushf *)(match+best_len-1) != scan_end ||
1101 *(ushf *)match != scan_start) continue;
1102
1103 /* It is not necessary to compare scan[2] and match[2] since they are
1104 * always equal when the other bytes match, given that the hash keys
1105 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
1106 * strstart+3, +5, ... up to strstart+257. We check for insufficient
1107 * lookahead only every 4th comparison; the 128th check will be made
1108 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
1109 * necessary to put more guard bytes at the end of the window, or
1110 * to check more often for insufficient lookahead.
1111 */
1112 Assert(scan[2] == match[2], "scan[2]?");
1113 scan++, match++;
1114 do {
1115 } while (*(ushf *)(scan+=2) == *(ushf *)(match+=2) &&
1116 *(ushf *)(scan+=2) == *(ushf *)(match+=2) &&
1117 *(ushf *)(scan+=2) == *(ushf *)(match+=2) &&
1118 *(ushf *)(scan+=2) == *(ushf *)(match+=2) &&
1119 scan < strend);
1120 /* The funny "do {}" generates better code on most compilers */
1121
1122 /* Here, scan <= window+strstart+257 */
1123 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1124 if (*scan == *match) scan++;
1125
1126 len = (MAX_MATCH - 1) - (int)(strend-scan);
1127 scan = strend - (MAX_MATCH-1);
1128
1129#else /* UNALIGNED_OK */
1130
1131 if (match[best_len] != scan_end ||
1132 match[best_len-1] != scan_end1 ||
1133 *match != *scan ||
1134 *++match != scan[1]) continue;
1135
1136 /* The check at best_len-1 can be removed because it will be made
1137 * again later. (This heuristic is not always a win.)
1138 * It is not necessary to compare scan[2] and match[2] since they
1139 * are always equal when the other bytes match, given that
1140 * the hash keys are equal and that HASH_BITS >= 8.
1141 */
1142 scan += 2, match++;
1143 Assert(*scan == *match, "match[2]?");
1144
1145 /* We check for insufficient lookahead only every 8th comparison;
1146 * the 256th check will be made at strstart+258.
1147 */
1148 do {
1149 } while (*++scan == *++match && *++scan == *++match &&
1150 *++scan == *++match && *++scan == *++match &&
1151 *++scan == *++match && *++scan == *++match &&
1152 *++scan == *++match && *++scan == *++match &&
1153 scan < strend);
1154
1155 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1156
1157 len = MAX_MATCH - (int)(strend - scan);
1158 scan = strend - MAX_MATCH;
1159
1160#endif /* UNALIGNED_OK */
1161
1162 if (len > best_len) {
1163 s->match_start = cur_match;
1164 best_len = len;
1165 if (len >= nice_match) break;
1166#ifdef UNALIGNED_OK
1167 scan_end = *(ushf *)(scan+best_len-1);
1168#else
1169 scan_end1 = scan[best_len-1];
1170 scan_end = scan[best_len];
1171#endif
1172 }
1173 } while ((cur_match = prev[cur_match & wmask]) > limit
1174 && --chain_length != 0);
1175
1176 if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
1177 return s->lookahead;
1178}
1179#endif /* ASMV */
1180#endif /* FASTEST */
1181
1182/* ---------------------------------------------------------------------------
1183 * Optimized version for level == 1 or strategy == Z_RLE only
1184 */
1185local uInt longest_match_fast(s, cur_match)
1186deflate_state *s;
1187IPos cur_match; /* current match */
1188{
1189 register Bytef *scan = s->window + s->strstart; /* current string */
1190 register Bytef *match; /* matched string */
1191 register int len; /* length of current match */
1192 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1193
1194 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1195 * It is easy to get rid of this optimization if necessary.
1196 */
1197 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1198
1199 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1200
1201 Assert(cur_match < s->strstart, "no future");
1202
1203 match = s->window + cur_match;
1204
1205 /* Return failure if the match length is less than 2:
1206 */
1207 if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
1208
1209 /* The check at best_len-1 can be removed because it will be made
1210 * again later. (This heuristic is not always a win.)
1211 * It is not necessary to compare scan[2] and match[2] since they
1212 * are always equal when the other bytes match, given that
1213 * the hash keys are equal and that HASH_BITS >= 8.
1214 */
1215 scan += 2, match += 2;
1216 Assert(*scan == *match, "match[2]?");
1217
1218 /* We check for insufficient lookahead only every 8th comparison;
1219 * the 256th check will be made at strstart+258.
1220 */
1221 do {
1222 } while (*++scan == *++match && *++scan == *++match &&
1223 *++scan == *++match && *++scan == *++match &&
1224 *++scan == *++match && *++scan == *++match &&
1225 *++scan == *++match && *++scan == *++match &&
1226 scan < strend);
1227
1228 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1229
1230 len = MAX_MATCH - (int)(strend - scan);
1231
1232 if (len < MIN_MATCH) return MIN_MATCH - 1;
1233
1234 s->match_start = cur_match;
1235 return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
1236}
1237
1238#ifdef DEBUG
1239/* ===========================================================================
1240 * Check that the match at match_start is indeed a match.
1241 */
1242local void check_match(s, start, match, length)
1243deflate_state *s;
1244IPos start, match;
1245int length;
1246{
1247 /* check that the match is indeed a match */
1248 if (zmemcmp(s->window + match,
1249 s->window + start, length) != EQUAL) {
1250 fprintf(stderr, " start %u, match %u, length %d\n",
1251 start, match, length);
1252 do {
1253 fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
1254 } while (--length != 0);
1255 z_error("invalid match");
1256 }
1257 if (z_verbose > 1) {
1258 fprintf(stderr,"\\[%d,%d]", start-match, length);
1259 do { putc(s->window[start++], stderr); }
1260 while (--length != 0);
1261 }
1262}
1263#else
1264# define check_match(s, start, match, length)
1265#endif /* DEBUG */
1266
1267/* ===========================================================================
1268 * Fill the window when the lookahead becomes insufficient.
1269 * Updates strstart and lookahead.
1270 *
1271 * IN assertion: lookahead < MIN_LOOKAHEAD
1272 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1273 * At least one byte has been read, or avail_in == 0; reads are
1274 * performed for at least two bytes (required for the zip translate_eol
1275 * option -- not supported here).
1276 */
1277local void fill_window(s)
1278deflate_state *s;
1279{
1280 register unsigned n, m;
1281 register Posf *p;
1282 unsigned more; /* Amount of free space at the end of the window. */
1283 uInt wsize = s->w_size;
1284
1285 do {
1286 more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
1287
1288 /* Deal with !@#$% 64K limit: */
1289 if (sizeof(int) <= 2) {
1290 if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1291 more = wsize;
1292
1293 } else if (more == (unsigned)(-1)) {
1294 /* Very unlikely, but possible on 16 bit machine if
1295 * strstart == 0 && lookahead == 1 (input done a byte at time)
1296 */
1297 more--;
1298 }
1299 }
1300
1301 /* If the window is almost full and there is insufficient lookahead,
1302 * move the upper half to the lower one to make room in the upper half.
1303 */
1304 if (s->strstart >= wsize+MAX_DIST(s)) {
1305
1306 zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
1307 s->match_start -= wsize;
1308 s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
1309 s->block_start -= (long) wsize;
1310
1311 /* Slide the hash table (could be avoided with 32 bit values
1312 at the expense of memory usage). We slide even when level == 0
1313 to keep the hash table consistent if we switch back to level > 0
1314 later. (Using level 0 permanently is not an optimal usage of
1315 zlib, so we don't care about this pathological case.)
1316 */
1317 /* %%% avoid this when Z_RLE */
1318 n = s->hash_size;
1319 p = &s->head[n];
1320 do {
1321 m = *--p;
1322 *p = (Pos)(m >= wsize ? m-wsize : NIL);
1323 } while (--n);
1324
1325 n = wsize;
1326#ifndef FASTEST
1327 p = &s->prev[n];
1328 do {
1329 m = *--p;
1330 *p = (Pos)(m >= wsize ? m-wsize : NIL);
1331 /* If n is not on any hash chain, prev[n] is garbage but
1332 * its value will never be used.
1333 */
1334 } while (--n);
1335#endif
1336 more += wsize;
1337 }
1338 if (s->strm->avail_in == 0) return;
1339
1340 /* If there was no sliding:
1341 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1342 * more == window_size - lookahead - strstart
1343 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1344 * => more >= window_size - 2*WSIZE + 2
1345 * In the BIG_MEM or MMAP case (not yet supported),
1346 * window_size == input_size + MIN_LOOKAHEAD &&
1347 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1348 * Otherwise, window_size == 2*WSIZE so more >= 2.
1349 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1350 */
1351 Assert(more >= 2, "more < 2");
1352
1353 n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1354 s->lookahead += n;
1355
1356 /* Initialize the hash value now that we have some input: */
1357 if (s->lookahead >= MIN_MATCH) {
1358 s->ins_h = s->window[s->strstart];
1359 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1360#if MIN_MATCH != 3
1361 Call UPDATE_HASH() MIN_MATCH-3 more times
1362#endif
1363 }
1364 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1365 * but this is not important since only literal bytes will be emitted.
1366 */
1367
1368 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1369}
1370
1371/* ===========================================================================
1372 * Flush the current block, with given end-of-file flag.
1373 * IN assertion: strstart is set to the end of the current match.
1374 */
1375#define FLUSH_BLOCK_ONLY(s, eof) { \
1376 _tr_flush_block(s, (s->block_start >= 0L ? \
1377 (charf *)&s->window[(unsigned)s->block_start] : \
1378 (charf *)Z_NULL), \
1379 (ulg)((long)s->strstart - s->block_start), \
1380 (eof)); \
1381 s->block_start = s->strstart; \
1382 flush_pending(s->strm); \
1383 Tracev((stderr,"[FLUSH]")); \
1384}
1385
1386/* Same but force premature exit if necessary. */
1387#define FLUSH_BLOCK(s, eof) { \
1388 FLUSH_BLOCK_ONLY(s, eof); \
1389 if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
1390}
1391
1392/* ===========================================================================
1393 * Copy without compression as much as possible from the input stream, return
1394 * the current block state.
1395 * This function does not insert new strings in the dictionary since
1396 * uncompressible data is probably not useful. This function is used
1397 * only for the level=0 compression option.
1398 * NOTE: this function should be optimized to avoid extra copying from
1399 * window to pending_buf.
1400 */
1401local block_state deflate_stored(s, flush)
1402deflate_state *s;
1403int flush;
1404{
1405 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
1406 * to pending_buf_size, and each stored block has a 5 byte header:
1407 */
1408 ulg max_block_size = 0xffff;
1409 ulg max_start;
1410
1411 if (max_block_size > s->pending_buf_size - 5) {
1412 max_block_size = s->pending_buf_size - 5;
1413 }
1414
1415 /* Copy as much as possible from input to output: */
1416 for (;;) {
1417 /* Fill the window as much as possible: */
1418 if (s->lookahead <= 1) {
1419
1420 Assert(s->strstart < s->w_size+MAX_DIST(s) ||
1421 s->block_start >= (long)s->w_size, "slide too late");
1422
1423 fill_window(s);
1424 if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
1425
1426 if (s->lookahead == 0) break; /* flush the current block */
1427 }
1428 Assert(s->block_start >= 0L, "block gone");
1429
1430 s->strstart += s->lookahead;
1431 s->lookahead = 0;
1432
1433 /* Emit a stored block if pending_buf will be full: */
1434 max_start = s->block_start + max_block_size;
1435 if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
1436 /* strstart == 0 is possible when wraparound on 16-bit machine */
1437 s->lookahead = (uInt)(s->strstart - max_start);
1438 s->strstart = (uInt)max_start;
1439 FLUSH_BLOCK(s, 0);
1440 }
1441 /* Flush if we may have to slide, otherwise block_start may become
1442 * negative and the data will be gone:
1443 */
1444 if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
1445 FLUSH_BLOCK(s, 0);
1446 }
1447 }
1448 FLUSH_BLOCK(s, flush == Z_FINISH);
1449 return flush == Z_FINISH ? finish_done : block_done;
1450}
1451
1452/* ===========================================================================
1453 * Compress as much as possible from the input stream, return the current
1454 * block state.
1455 * This function does not perform lazy evaluation of matches and inserts
1456 * new strings in the dictionary only for unmatched strings or for short
1457 * matches. It is used only for the fast compression options.
1458 */
1459local block_state deflate_fast(s, flush)
1460deflate_state *s;
1461int flush;
1462{
1463 IPos hash_head = NIL; /* head of the hash chain */
1464 int bflush; /* set if current block must be flushed */
1465
1466 for (;;) {
1467 /* Make sure that we always have enough lookahead, except
1468 * at the end of the input file. We need MAX_MATCH bytes
1469 * for the next match, plus MIN_MATCH bytes to insert the
1470 * string following the next match.
1471 */
1472 if (s->lookahead < MIN_LOOKAHEAD) {
1473 fill_window(s);
1474 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1475 return need_more;
1476 }
1477 if (s->lookahead == 0) break; /* flush the current block */
1478 }
1479
1480 /* Insert the string window[strstart .. strstart+2] in the
1481 * dictionary, and set hash_head to the head of the hash chain:
1482 */
1483 if (s->lookahead >= MIN_MATCH) {
1484 INSERT_STRING(s, s->strstart, hash_head);
1485 }
1486
1487 /* Find the longest match, discarding those <= prev_length.
1488 * At this point we have always match_length < MIN_MATCH
1489 */
1490 if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1491 /* To simplify the code, we prevent matches with the string
1492 * of window index 0 (in particular we have to avoid a match
1493 * of the string with itself at the start of the input file).
1494 */
1495#ifdef FASTEST
1496 if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
1497 (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
1498 s->match_length = longest_match_fast (s, hash_head);
1499 }
1500#else
1501 if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
1502 s->match_length = longest_match (s, hash_head);
1503 } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
1504 s->match_length = longest_match_fast (s, hash_head);
1505 }
1506#endif
1507 /* longest_match() or longest_match_fast() sets match_start */
1508 }
1509 if (s->match_length >= MIN_MATCH) {
1510 check_match(s, s->strstart, s->match_start, s->match_length);
1511
1512 _tr_tally_dist(s, s->strstart - s->match_start,
1513 s->match_length - MIN_MATCH, bflush);
1514
1515 s->lookahead -= s->match_length;
1516
1517 /* Insert new strings in the hash table only if the match length
1518 * is not too large. This saves time but degrades compression.
1519 */
1520#ifndef FASTEST
1521 if (s->match_length <= s->max_insert_length &&
1522 s->lookahead >= MIN_MATCH) {
1523 s->match_length--; /* string at strstart already in table */
1524 do {
1525 s->strstart++;
1526 INSERT_STRING(s, s->strstart, hash_head);
1527 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1528 * always MIN_MATCH bytes ahead.
1529 */
1530 } while (--s->match_length != 0);
1531 s->strstart++;
1532 } else
1533#endif
1534 {
1535 s->strstart += s->match_length;
1536 s->match_length = 0;
1537 s->ins_h = s->window[s->strstart];
1538 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1539#if MIN_MATCH != 3
1540 Call UPDATE_HASH() MIN_MATCH-3 more times
1541#endif
1542 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1543 * matter since it will be recomputed at next deflate call.
1544 */
1545 }
1546 } else {
1547 /* No match, output a literal byte */
1548 Tracevv((stderr,"%c", s->window[s->strstart]));
1549 _tr_tally_lit (s, s->window[s->strstart], bflush);
1550 s->lookahead--;
1551 s->strstart++;
1552 }
1553 if (bflush) FLUSH_BLOCK(s, 0);
1554 }
1555 FLUSH_BLOCK(s, flush == Z_FINISH);
1556 return flush == Z_FINISH ? finish_done : block_done;
1557}
1558
1559#ifndef FASTEST
1560/* ===========================================================================
1561 * Same as above, but achieves better compression. We use a lazy
1562 * evaluation for matches: a match is finally adopted only if there is
1563 * no better match at the next window position.
1564 */
1565local block_state deflate_slow(s, flush)
1566deflate_state *s;
1567int flush;
1568{
1569 IPos hash_head = NIL; /* head of hash chain */
1570 int bflush; /* set if current block must be flushed */
1571
1572 /* Process the input block. */
1573 for (;;) {
1574 /* Make sure that we always have enough lookahead, except
1575 * at the end of the input file. We need MAX_MATCH bytes
1576 * for the next match, plus MIN_MATCH bytes to insert the
1577 * string following the next match.
1578 */
1579 if (s->lookahead < MIN_LOOKAHEAD) {
1580 fill_window(s);
1581 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1582 return need_more;
1583 }
1584 if (s->lookahead == 0) break; /* flush the current block */
1585 }
1586
1587 /* Insert the string window[strstart .. strstart+2] in the
1588 * dictionary, and set hash_head to the head of the hash chain:
1589 */
1590 if (s->lookahead >= MIN_MATCH) {
1591 INSERT_STRING(s, s->strstart, hash_head);
1592 }
1593
1594 /* Find the longest match, discarding those <= prev_length.
1595 */
1596 s->prev_length = s->match_length, s->prev_match = s->match_start;
1597 s->match_length = MIN_MATCH-1;
1598
1599 if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
1600 s->strstart - hash_head <= MAX_DIST(s)) {
1601 /* To simplify the code, we prevent matches with the string
1602 * of window index 0 (in particular we have to avoid a match
1603 * of the string with itself at the start of the input file).
1604 */
1605 if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
1606 s->match_length = longest_match (s, hash_head);
1607 } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
1608 s->match_length = longest_match_fast (s, hash_head);
1609 }
1610 /* longest_match() or longest_match_fast() sets match_start */
1611
1612 if (s->match_length <= 5 && (s->strategy == Z_FILTERED
1613#if TOO_FAR <= 32767
1614 || (s->match_length == MIN_MATCH &&
1615 s->strstart - s->match_start > TOO_FAR)
1616#endif
1617 )) {
1618
1619 /* If prev_match is also MIN_MATCH, match_start is garbage
1620 * but we will ignore the current match anyway.
1621 */
1622 s->match_length = MIN_MATCH-1;
1623 }
1624 }
1625 /* If there was a match at the previous step and the current
1626 * match is not better, output the previous match:
1627 */
1628 if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
1629 uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
1630 /* Do not insert strings in hash table beyond this. */
1631
1632 check_match(s, s->strstart-1, s->prev_match, s->prev_length);
1633
1634 _tr_tally_dist(s, s->strstart -1 - s->prev_match,
1635 s->prev_length - MIN_MATCH, bflush);
1636
1637 /* Insert in hash table all strings up to the end of the match.
1638 * strstart-1 and strstart are already inserted. If there is not
1639 * enough lookahead, the last two strings are not inserted in
1640 * the hash table.
1641 */
1642 s->lookahead -= s->prev_length-1;
1643 s->prev_length -= 2;
1644 do {
1645 if (++s->strstart <= max_insert) {
1646 INSERT_STRING(s, s->strstart, hash_head);
1647 }
1648 } while (--s->prev_length != 0);
1649 s->match_available = 0;
1650 s->match_length = MIN_MATCH-1;
1651 s->strstart++;
1652
1653 if (bflush) FLUSH_BLOCK(s, 0);
1654
1655 } else if (s->match_available) {
1656 /* If there was no match at the previous position, output a
1657 * single literal. If there was a match but the current match
1658 * is longer, truncate the previous match to a single literal.
1659 */
1660 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1661 _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1662 if (bflush) {
1663 FLUSH_BLOCK_ONLY(s, 0);
1664 }
1665 s->strstart++;
1666 s->lookahead--;
1667 if (s->strm->avail_out == 0) return need_more;
1668 } else {
1669 /* There is no previous match to compare with, wait for
1670 * the next step to decide.
1671 */
1672 s->match_available = 1;
1673 s->strstart++;
1674 s->lookahead--;
1675 }
1676 }
1677 Assert (flush != Z_NO_FLUSH, "no flush?");
1678 if (s->match_available) {
1679 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1680 _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1681 s->match_available = 0;
1682 }
1683 FLUSH_BLOCK(s, flush == Z_FINISH);
1684 return flush == Z_FINISH ? finish_done : block_done;
1685}
1686#endif /* FASTEST */
1687
1688#if 0
1689/* ===========================================================================
1690 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
1691 * one. Do not maintain a hash table. (It will be regenerated if this run of
1692 * deflate switches away from Z_RLE.)
1693 */
1694local block_state deflate_rle(s, flush)
1695deflate_state *s;
1696int flush;
1697{
1698 int bflush; /* set if current block must be flushed */
1699 uInt run; /* length of run */
1700 uInt max; /* maximum length of run */
1701 uInt prev; /* byte at distance one to match */
1702 Bytef *scan; /* scan for end of run */
1703
1704 for (;;) {
1705 /* Make sure that we always have enough lookahead, except
1706 * at the end of the input file. We need MAX_MATCH bytes
1707 * for the longest encodable run.
1708 */
1709 if (s->lookahead < MAX_MATCH) {
1710 fill_window(s);
1711 if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
1712 return need_more;
1713 }
1714 if (s->lookahead == 0) break; /* flush the current block */
1715 }
1716
1717 /* See how many times the previous byte repeats */
1718 run = 0;
1719 if (s->strstart > 0) { /* if there is a previous byte, that is */
1720 max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
1721 scan = s->window + s->strstart - 1;
1722 prev = *scan++;
1723 do {
1724 if (*scan++ != prev)
1725 break;
1726 } while (++run < max);
1727 }
1728
1729 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
1730 if (run >= MIN_MATCH) {
1731 check_match(s, s->strstart, s->strstart - 1, run);
1732 _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
1733 s->lookahead -= run;
1734 s->strstart += run;
1735 } else {
1736 /* No match, output a literal byte */
1737 Tracevv((stderr,"%c", s->window[s->strstart]));
1738 _tr_tally_lit (s, s->window[s->strstart], bflush);
1739 s->lookahead--;
1740 s->strstart++;
1741 }
1742 if (bflush) FLUSH_BLOCK(s, 0);
1743 }
1744 FLUSH_BLOCK(s, flush == Z_FINISH);
1745 return flush == Z_FINISH ? finish_done : block_done;
1746}
1747#endif