File Coverage

deps/libgit2/deps/zlib/deflate.c
Criterion Covered Total %
statement 327 721 45.3
branch 227 660 34.3
condition n/a
subroutine n/a
pod n/a
total 554 1381 40.1


line stmt bran cond sub pod time code
1             /* deflate.c -- compress data using the deflation algorithm
2             * Copyright (C) 1995-2022 Jean-loup Gailly and Mark Adler
3             * For conditions of distribution and use, see copyright notice in zlib.h
4             */
5              
6             /*
7             * ALGORITHM
8             *
9             * The "deflation" process depends on being able to identify portions
10             * of the input text which are identical to earlier input (within a
11             * sliding window trailing behind the input currently being processed).
12             *
13             * The most straightforward technique turns out to be the fastest for
14             * most input files: try all possible matches and select the longest.
15             * The key feature of this algorithm is that insertions into the string
16             * dictionary are very simple and thus fast, and deletions are avoided
17             * completely. Insertions are performed at each input character, whereas
18             * string matches are performed only when the previous match ends. So it
19             * is preferable to spend more time in matches to allow very fast string
20             * insertions and avoid deletions. The matching algorithm for small
21             * strings is inspired from that of Rabin & Karp. A brute force approach
22             * is used to find longer strings when a small match has been found.
23             * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
24             * (by Leonid Broukhis).
25             * A previous version of this file used a more sophisticated algorithm
26             * (by Fiala and Greene) which is guaranteed to run in linear amortized
27             * time, but has a larger average cost, uses more memory and is patented.
28             * However the F&G algorithm may be faster for some highly redundant
29             * files if the parameter max_chain_length (described below) is too large.
30             *
31             * ACKNOWLEDGEMENTS
32             *
33             * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
34             * I found it in 'freeze' written by Leonid Broukhis.
35             * Thanks to many people for bug reports and testing.
36             *
37             * REFERENCES
38             *
39             * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
40             * Available in http://tools.ietf.org/html/rfc1951
41             *
42             * A description of the Rabin and Karp algorithm is given in the book
43             * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
44             *
45             * Fiala,E.R., and Greene,D.H.
46             * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
47             *
48             */
49              
50             /* @(#) $Id$ */
51              
52             #include "deflate.h"
53              
54             const char deflate_copyright[] =
55             " deflate 1.2.12 Copyright 1995-2022 Jean-loup Gailly and Mark Adler ";
56             /*
57             If you use the zlib library in a product, an acknowledgment is welcome
58             in the documentation of your product. If for some reason you cannot
59             include such an acknowledgment, I would appreciate that you keep this
60             copyright string in the executable of your product.
61             */
62              
63             /* ===========================================================================
64             * Function prototypes.
65             */
66             typedef enum {
67             need_more, /* block not completed, need more input or more output */
68             block_done, /* block flush performed */
69             finish_started, /* finish started, need only more output at next deflate */
70             finish_done /* finish done, accept no more input or output */
71             } block_state;
72              
73             typedef block_state (*compress_func) OF((deflate_state *s, int flush));
74             /* Compression function. Returns the block state after the call. */
75              
76             local int deflateStateCheck OF((z_streamp strm));
77             local void slide_hash OF((deflate_state *s));
78             local void fill_window OF((deflate_state *s));
79             local block_state deflate_stored OF((deflate_state *s, int flush));
80             local block_state deflate_fast OF((deflate_state *s, int flush));
81             #ifndef FASTEST
82             local block_state deflate_slow OF((deflate_state *s, int flush));
83             #endif
84             local block_state deflate_rle OF((deflate_state *s, int flush));
85             local block_state deflate_huff OF((deflate_state *s, int flush));
86             local void lm_init OF((deflate_state *s));
87             local void putShortMSB OF((deflate_state *s, uInt b));
88             local void flush_pending OF((z_streamp strm));
89             local unsigned read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
90             #ifdef ASMV
91             # pragma message("Assembler code may have bugs -- use at your own risk")
92             void match_init OF((void)); /* asm code initialization */
93             uInt longest_match OF((deflate_state *s, IPos cur_match));
94             #else
95             local uInt longest_match OF((deflate_state *s, IPos cur_match));
96             #endif
97              
98             #ifdef ZLIB_DEBUG
99             local void check_match OF((deflate_state *s, IPos start, IPos match,
100             int length));
101             #endif
102              
103             /* ===========================================================================
104             * Local data
105             */
106              
107             #define NIL 0
108             /* Tail of hash chains */
109              
110             #ifndef TOO_FAR
111             # define TOO_FAR 4096
112             #endif
113             /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
114              
115             /* Values for max_lazy_match, good_match and max_chain_length, depending on
116             * the desired pack level (0..9). The values given below have been tuned to
117             * exclude worst case performance for pathological files. Better values may be
118             * found for specific files.
119             */
120             typedef struct config_s {
121             ush good_length; /* reduce lazy search above this match length */
122             ush max_lazy; /* do not perform lazy search above this match length */
123             ush nice_length; /* quit search above this match length */
124             ush max_chain;
125             compress_func func;
126             } config;
127              
128             #ifdef FASTEST
129             local const config configuration_table[2] = {
130             /* good lazy nice chain */
131             /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
132             /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
133             #else
134             local const config configuration_table[10] = {
135             /* good lazy nice chain */
136             /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
137             /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
138             /* 2 */ {4, 5, 16, 8, deflate_fast},
139             /* 3 */ {4, 6, 32, 32, deflate_fast},
140              
141             /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
142             /* 5 */ {8, 16, 32, 32, deflate_slow},
143             /* 6 */ {8, 16, 128, 128, deflate_slow},
144             /* 7 */ {8, 32, 128, 256, deflate_slow},
145             /* 8 */ {32, 128, 258, 1024, deflate_slow},
146             /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
147             #endif
148              
149             /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
150             * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
151             * meaning.
152             */
153              
154             /* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */
155             #define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0))
156              
157             /* ===========================================================================
158             * Update a hash value with the given input byte
159             * IN assertion: all calls to UPDATE_HASH are made with consecutive input
160             * characters, so that a running hash key can be computed from the previous
161             * key instead of complete recalculation each time.
162             */
163             #define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask)
164              
165              
166             /* ===========================================================================
167             * Insert string str in the dictionary and set match_head to the previous head
168             * of the hash chain (the most recent string with same hash key). Return
169             * the previous length of the hash chain.
170             * If this file is compiled with -DFASTEST, the compression level is forced
171             * to 1, and no hash chains are maintained.
172             * IN assertion: all calls to INSERT_STRING are made with consecutive input
173             * characters and the first MIN_MATCH bytes of str are valid (except for
174             * the last MIN_MATCH-1 bytes of the input file).
175             */
176             #ifdef FASTEST
177             #define INSERT_STRING(s, str, match_head) \
178             (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
179             match_head = s->head[s->ins_h], \
180             s->head[s->ins_h] = (Pos)(str))
181             #else
182             #define INSERT_STRING(s, str, match_head) \
183             (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
184             match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
185             s->head[s->ins_h] = (Pos)(str))
186             #endif
187              
188             /* ===========================================================================
189             * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
190             * prev[] will be initialized on the fly.
191             */
192             #define CLEAR_HASH(s) \
193             do { \
194             s->head[s->hash_size-1] = NIL; \
195             zmemzero((Bytef *)s->head, \
196             (unsigned)(s->hash_size-1)*sizeof(*s->head)); \
197             } while (0)
198              
199             /* ===========================================================================
200             * Slide the hash table when sliding the window down (could be avoided with 32
201             * bit values at the expense of memory usage). We slide even when level == 0 to
202             * keep the hash table consistent if we switch back to level > 0 later.
203             */
204             #if defined(__has_feature)
205             # if __has_feature(memory_sanitizer)
206             __attribute__((no_sanitize("memory")))
207             # endif
208             #endif
209 0           local void slide_hash(s)
210             deflate_state *s;
211             {
212             unsigned n, m;
213             Posf *p;
214 0           uInt wsize = s->w_size;
215              
216 0           n = s->hash_size;
217 0           p = &s->head[n];
218             do {
219 0           m = *--p;
220 0 0         *p = (Pos)(m >= wsize ? m - wsize : NIL);
221 0 0         } while (--n);
222 0           n = wsize;
223             #ifndef FASTEST
224 0           p = &s->prev[n];
225             do {
226 0           m = *--p;
227 0 0         *p = (Pos)(m >= wsize ? m - wsize : NIL);
228             /* If n is not on any hash chain, prev[n] is garbage but
229             * its value will never be used.
230             */
231 0 0         } while (--n);
232             #endif
233 0           }
234              
235             /* ========================================================================= */
236 191           int ZEXPORT deflateInit_(strm, level, version, stream_size)
237             z_streamp strm;
238             int level;
239             const char *version;
240             int stream_size;
241             {
242 191           return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
243             Z_DEFAULT_STRATEGY, version, stream_size);
244             /* To do: ignore strm->next_in if we use it as window */
245             }
246              
247             /* ========================================================================= */
248 191           int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
249             version, stream_size)
250             z_streamp strm;
251             int level;
252             int method;
253             int windowBits;
254             int memLevel;
255             int strategy;
256             const char *version;
257             int stream_size;
258             {
259             deflate_state *s;
260 191           int wrap = 1;
261             static const char my_version[] = ZLIB_VERSION;
262              
263 191 50         if (version == Z_NULL || version[0] != my_version[0] ||
    50          
    50          
264             stream_size != sizeof(z_stream)) {
265 0           return Z_VERSION_ERROR;
266             }
267 191 50         if (strm == Z_NULL) return Z_STREAM_ERROR;
268              
269 191           strm->msg = Z_NULL;
270 191 50         if (strm->zalloc == (alloc_func)0) {
271             #ifdef Z_SOLO
272             return Z_STREAM_ERROR;
273             #else
274 191           strm->zalloc = zcalloc;
275 191           strm->opaque = (voidpf)0;
276             #endif
277             }
278 191 50         if (strm->zfree == (free_func)0)
279             #ifdef Z_SOLO
280             return Z_STREAM_ERROR;
281             #else
282 191           strm->zfree = zcfree;
283             #endif
284              
285             #ifdef FASTEST
286             if (level != 0) level = 1;
287             #else
288 191 100         if (level == Z_DEFAULT_COMPRESSION) level = 6;
289             #endif
290              
291 191 50         if (windowBits < 0) { /* suppress zlib wrapper */
292 0           wrap = 0;
293 0           windowBits = -windowBits;
294             }
295             #ifdef GZIP
296             else if (windowBits > 15) {
297             wrap = 2; /* write gzip wrapper instead */
298             windowBits -= 16;
299             }
300             #endif
301 191 50         if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
    50          
    50          
    50          
302 191 50         windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
    50          
    50          
    50          
303 191 50         strategy < 0 || strategy > Z_FIXED || (windowBits == 8 && wrap != 1)) {
    50          
    0          
304 0           return Z_STREAM_ERROR;
305             }
306 191 50         if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
307 191           s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
308 191 50         if (s == Z_NULL) return Z_MEM_ERROR;
309 191           strm->state = (struct internal_state FAR *)s;
310 191           s->strm = strm;
311 191           s->status = INIT_STATE; /* to pass state test in deflateReset() */
312              
313 191           s->wrap = wrap;
314 191           s->gzhead = Z_NULL;
315 191           s->w_bits = (uInt)windowBits;
316 191           s->w_size = 1 << s->w_bits;
317 191           s->w_mask = s->w_size - 1;
318              
319 191           s->hash_bits = (uInt)memLevel + 7;
320 191           s->hash_size = 1 << s->hash_bits;
321 191           s->hash_mask = s->hash_size - 1;
322 191           s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
323              
324 191           s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
325 191           s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
326 191           s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
327              
328 191           s->high_water = 0; /* nothing written to s->window yet */
329              
330 191           s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
331              
332             /* We overlay pending_buf and sym_buf. This works since the average size
333             * for length/distance pairs over any compressed block is assured to be 31
334             * bits or less.
335             *
336             * Analysis: The longest fixed codes are a length code of 8 bits plus 5
337             * extra bits, for lengths 131 to 257. The longest fixed distance codes are
338             * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest
339             * possible fixed-codes length/distance pair is then 31 bits total.
340             *
341             * sym_buf starts one-fourth of the way into pending_buf. So there are
342             * three bytes in sym_buf for every four bytes in pending_buf. Each symbol
343             * in sym_buf is three bytes -- two for the distance and one for the
344             * literal/length. As each symbol is consumed, the pointer to the next
345             * sym_buf value to read moves forward three bytes. From that symbol, up to
346             * 31 bits are written to pending_buf. The closest the written pending_buf
347             * bits gets to the next sym_buf symbol to read is just before the last
348             * code is written. At that time, 31*(n-2) bits have been written, just
349             * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at
350             * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1
351             * symbols are written.) The closest the writing gets to what is unread is
352             * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and
353             * can range from 128 to 32768.
354             *
355             * Therefore, at a minimum, there are 142 bits of space between what is
356             * written and what is read in the overlain buffers, so the symbols cannot
357             * be overwritten by the compressed data. That space is actually 139 bits,
358             * due to the three-bit fixed-code block header.
359             *
360             * That covers the case where either Z_FIXED is specified, forcing fixed
361             * codes, or when the use of fixed codes is chosen, because that choice
362             * results in a smaller compressed block than dynamic codes. That latter
363             * condition then assures that the above analysis also covers all dynamic
364             * blocks. A dynamic-code block will only be chosen to be emitted if it has
365             * fewer bits than a fixed-code block would for the same set of symbols.
366             * Therefore its average symbol length is assured to be less than 31. So
367             * the compressed data for a dynamic block also cannot overwrite the
368             * symbols from which it is being constructed.
369             */
370              
371 191           s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, 4);
372 191           s->pending_buf_size = (ulg)s->lit_bufsize * 4;
373              
374 191 50         if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
    50          
    50          
    50          
375 191           s->pending_buf == Z_NULL) {
376 0           s->status = FINISH_STATE;
377 0           strm->msg = ERR_MSG(Z_MEM_ERROR);
378 0           deflateEnd (strm);
379 0           return Z_MEM_ERROR;
380             }
381 191           s->sym_buf = s->pending_buf + s->lit_bufsize;
382 191           s->sym_end = (s->lit_bufsize - 1) * 3;
383             /* We avoid equality with lit_bufsize*3 because of wraparound at 64K
384             * on 16 bit machines and because stored blocks are restricted to
385             * 64K-1 bytes.
386             */
387              
388 191           s->level = level;
389 191           s->strategy = strategy;
390 191           s->method = (Byte)method;
391              
392 191           return deflateReset(strm);
393             }
394              
395             /* =========================================================================
396             * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
397             */
398 651           local int deflateStateCheck (strm)
399             z_streamp strm;
400             {
401             deflate_state *s;
402 651 50         if (strm == Z_NULL ||
    50          
403 651 50         strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
404 0           return 1;
405 651           s = strm->state;
406 651 50         if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE &&
    50          
    100          
    50          
407             #ifdef GZIP
408             s->status != GZIP_STATE &&
409             #endif
410 219 50         s->status != EXTRA_STATE &&
411 219 50         s->status != NAME_STATE &&
412 219 50         s->status != COMMENT_STATE &&
413 219 50         s->status != HCRC_STATE &&
414 219 50         s->status != BUSY_STATE &&
415 219           s->status != FINISH_STATE))
416 0           return 1;
417 651           return 0;
418             }
419              
420             /* ========================================================================= */
421 0           int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
422             z_streamp strm;
423             const Bytef *dictionary;
424             uInt dictLength;
425             {
426             deflate_state *s;
427             uInt str, n;
428             int wrap;
429             unsigned avail;
430             z_const unsigned char *next;
431              
432 0 0         if (deflateStateCheck(strm) || dictionary == Z_NULL)
    0          
433 0           return Z_STREAM_ERROR;
434 0           s = strm->state;
435 0           wrap = s->wrap;
436 0 0         if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
    0          
    0          
    0          
437 0           return Z_STREAM_ERROR;
438              
439             /* when using zlib wrappers, compute Adler-32 for provided dictionary */
440 0 0         if (wrap == 1)
441 0           strm->adler = adler32(strm->adler, dictionary, dictLength);
442 0           s->wrap = 0; /* avoid computing Adler-32 in read_buf */
443              
444             /* if dictionary would fill window, just replace the history */
445 0 0         if (dictLength >= s->w_size) {
446 0 0         if (wrap == 0) { /* already empty otherwise */
447 0           CLEAR_HASH(s);
448 0           s->strstart = 0;
449 0           s->block_start = 0L;
450 0           s->insert = 0;
451             }
452 0           dictionary += dictLength - s->w_size; /* use the tail */
453 0           dictLength = s->w_size;
454             }
455              
456             /* insert dictionary into window and hash */
457 0           avail = strm->avail_in;
458 0           next = strm->next_in;
459 0           strm->avail_in = dictLength;
460 0           strm->next_in = (z_const Bytef *)dictionary;
461 0           fill_window(s);
462 0 0         while (s->lookahead >= MIN_MATCH) {
463 0           str = s->strstart;
464 0           n = s->lookahead - (MIN_MATCH-1);
465             do {
466 0           UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
467             #ifndef FASTEST
468 0           s->prev[str & s->w_mask] = s->head[s->ins_h];
469             #endif
470 0           s->head[s->ins_h] = (Pos)str;
471 0           str++;
472 0 0         } while (--n);
473 0           s->strstart = str;
474 0           s->lookahead = MIN_MATCH-1;
475 0           fill_window(s);
476             }
477 0           s->strstart += s->lookahead;
478 0           s->block_start = (long)s->strstart;
479 0           s->insert = s->lookahead;
480 0           s->lookahead = 0;
481 0           s->match_length = s->prev_length = MIN_MATCH-1;
482 0           s->match_available = 0;
483 0           strm->next_in = next;
484 0           strm->avail_in = avail;
485 0           s->wrap = wrap;
486 0           return Z_OK;
487             }
488              
489             /* ========================================================================= */
490 0           int ZEXPORT deflateGetDictionary (strm, dictionary, dictLength)
491             z_streamp strm;
492             Bytef *dictionary;
493             uInt *dictLength;
494             {
495             deflate_state *s;
496             uInt len;
497              
498 0 0         if (deflateStateCheck(strm))
499 0           return Z_STREAM_ERROR;
500 0           s = strm->state;
501 0           len = s->strstart + s->lookahead;
502 0 0         if (len > s->w_size)
503 0           len = s->w_size;
504 0 0         if (dictionary != Z_NULL && len)
    0          
505 0           zmemcpy(dictionary, s->window + s->strstart + s->lookahead - len, len);
506 0 0         if (dictLength != Z_NULL)
507 0           *dictLength = len;
508 0           return Z_OK;
509             }
510              
511             /* ========================================================================= */
512 241           int ZEXPORT deflateResetKeep (strm)
513             z_streamp strm;
514             {
515             deflate_state *s;
516              
517 241 50         if (deflateStateCheck(strm)) {
518 0           return Z_STREAM_ERROR;
519             }
520              
521 241           strm->total_in = strm->total_out = 0;
522 241           strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
523 241           strm->data_type = Z_UNKNOWN;
524              
525 241           s = (deflate_state *)strm->state;
526 241           s->pending = 0;
527 241           s->pending_out = s->pending_buf;
528              
529 241 100         if (s->wrap < 0) {
530 44           s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
531             }
532 241           s->status =
533             #ifdef GZIP
534             s->wrap == 2 ? GZIP_STATE :
535             #endif
536             INIT_STATE;
537 241           strm->adler =
538             #ifdef GZIP
539             s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
540             #endif
541 241           adler32(0L, Z_NULL, 0);
542 241           s->last_flush = -2;
543              
544 241           _tr_init(s);
545              
546 241           return Z_OK;
547             }
548              
549             /* ========================================================================= */
550 241           int ZEXPORT deflateReset (strm)
551             z_streamp strm;
552             {
553             int ret;
554              
555 241           ret = deflateResetKeep(strm);
556 241 50         if (ret == Z_OK)
557 241           lm_init(strm->state);
558 241           return ret;
559             }
560              
561             /* ========================================================================= */
562 0           int ZEXPORT deflateSetHeader (strm, head)
563             z_streamp strm;
564             gz_headerp head;
565             {
566 0 0         if (deflateStateCheck(strm) || strm->state->wrap != 2)
    0          
567 0           return Z_STREAM_ERROR;
568 0           strm->state->gzhead = head;
569 0           return Z_OK;
570             }
571              
572             /* ========================================================================= */
573 0           int ZEXPORT deflatePending (strm, pending, bits)
574             unsigned *pending;
575             int *bits;
576             z_streamp strm;
577             {
578 0 0         if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
579 0 0         if (pending != Z_NULL)
580 0           *pending = strm->state->pending;
581 0 0         if (bits != Z_NULL)
582 0           *bits = strm->state->bi_valid;
583 0           return Z_OK;
584             }
585              
586             /* ========================================================================= */
587 0           int ZEXPORT deflatePrime (strm, bits, value)
588             z_streamp strm;
589             int bits;
590             int value;
591             {
592             deflate_state *s;
593             int put;
594              
595 0 0         if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
596 0           s = strm->state;
597 0 0         if (bits < 0 || bits > 16 ||
    0          
    0          
598 0           s->sym_buf < s->pending_out + ((Buf_size + 7) >> 3))
599 0           return Z_BUF_ERROR;
600             do {
601 0           put = Buf_size - s->bi_valid;
602 0 0         if (put > bits)
603 0           put = bits;
604 0           s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);
605 0           s->bi_valid += put;
606 0           _tr_flush_bits(s);
607 0           value >>= put;
608 0           bits -= put;
609 0 0         } while (bits);
610 0           return Z_OK;
611             }
612              
613             /* ========================================================================= */
614 0           int ZEXPORT deflateParams(strm, level, strategy)
615             z_streamp strm;
616             int level;
617             int strategy;
618             {
619             deflate_state *s;
620             compress_func func;
621              
622 0 0         if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
623 0           s = strm->state;
624              
625             #ifdef FASTEST
626             if (level != 0) level = 1;
627             #else
628 0 0         if (level == Z_DEFAULT_COMPRESSION) level = 6;
629             #endif
630 0 0         if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
    0          
    0          
    0          
631 0           return Z_STREAM_ERROR;
632             }
633 0           func = configuration_table[s->level].func;
634              
635 0 0         if ((strategy != s->strategy || func != configuration_table[level].func) &&
    0          
    0          
636 0           s->last_flush != -2) {
637             /* Flush the last buffer: */
638 0           int err = deflate(strm, Z_BLOCK);
639 0 0         if (err == Z_STREAM_ERROR)
640 0           return err;
641 0 0         if (strm->avail_in || (s->strstart - s->block_start) + s->lookahead)
    0          
642 0           return Z_BUF_ERROR;
643             }
644 0 0         if (s->level != level) {
645 0 0         if (s->level == 0 && s->matches != 0) {
    0          
646 0 0         if (s->matches == 1)
647 0           slide_hash(s);
648             else
649 0           CLEAR_HASH(s);
650 0           s->matches = 0;
651             }
652 0           s->level = level;
653 0           s->max_lazy_match = configuration_table[level].max_lazy;
654 0           s->good_match = configuration_table[level].good_length;
655 0           s->nice_match = configuration_table[level].nice_length;
656 0           s->max_chain_length = configuration_table[level].max_chain;
657             }
658 0           s->strategy = strategy;
659 0           return Z_OK;
660             }
661              
662             /* ========================================================================= */
663 0           int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
664             z_streamp strm;
665             int good_length;
666             int max_lazy;
667             int nice_length;
668             int max_chain;
669             {
670             deflate_state *s;
671              
672 0 0         if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
673 0           s = strm->state;
674 0           s->good_match = (uInt)good_length;
675 0           s->max_lazy_match = (uInt)max_lazy;
676 0           s->nice_match = nice_length;
677 0           s->max_chain_length = (uInt)max_chain;
678 0           return Z_OK;
679             }
680              
681             /* =========================================================================
682             * For the default windowBits of 15 and memLevel of 8, this function returns
683             * a close to exact, as well as small, upper bound on the compressed size.
684             * They are coded as constants here for a reason--if the #define's are
685             * changed, then this function needs to be changed as well. The return
686             * value for 15 and 8 only works for those exact settings.
687             *
688             * For any setting other than those defaults for windowBits and memLevel,
689             * the value returned is a conservative worst case for the maximum expansion
690             * resulting from using fixed blocks instead of stored blocks, which deflate
691             * can emit on compressed data for some combinations of the parameters.
692             *
693             * This function could be more sophisticated to provide closer upper bounds for
694             * every combination of windowBits and memLevel. But even the conservative
695             * upper bound of about 14% expansion does not seem onerous for output buffer
696             * allocation.
697             */
698 0           uLong ZEXPORT deflateBound(strm, sourceLen)
699             z_streamp strm;
700             uLong sourceLen;
701             {
702             deflate_state *s;
703             uLong complen, wraplen;
704              
705             /* conservative upper bound for compressed data */
706 0           complen = sourceLen +
707 0           ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
708              
709             /* if can't get parameters, return conservative bound plus zlib wrapper */
710 0 0         if (deflateStateCheck(strm))
711 0           return complen + 6;
712              
713             /* compute wrapper length */
714 0           s = strm->state;
715 0           switch (s->wrap) {
716             case 0: /* raw deflate */
717 0           wraplen = 0;
718 0           break;
719             case 1: /* zlib wrapper */
720 0 0         wraplen = 6 + (s->strstart ? 4 : 0);
721 0           break;
722             #ifdef GZIP
723             case 2: /* gzip wrapper */
724             wraplen = 18;
725             if (s->gzhead != Z_NULL) { /* user-supplied gzip header */
726             Bytef *str;
727             if (s->gzhead->extra != Z_NULL)
728             wraplen += 2 + s->gzhead->extra_len;
729             str = s->gzhead->name;
730             if (str != Z_NULL)
731             do {
732             wraplen++;
733             } while (*str++);
734             str = s->gzhead->comment;
735             if (str != Z_NULL)
736             do {
737             wraplen++;
738             } while (*str++);
739             if (s->gzhead->hcrc)
740             wraplen += 2;
741             }
742             break;
743             #endif
744             default: /* for compiler happiness */
745 0           wraplen = 6;
746             }
747              
748             /* if not default parameters, return conservative bound */
749 0 0         if (s->w_bits != 15 || s->hash_bits != 8 + 7)
    0          
750 0           return complen + wraplen;
751              
752             /* default settings: return tight bound for that case */
753 0           return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
754 0           (sourceLen >> 25) + 13 - 6 + wraplen;
755             }
756              
757             /* =========================================================================
758             * Put a short in the pending buffer. The 16-bit value is put in MSB order.
759             * IN assertion: the stream state is correct and there is enough room in
760             * pending_buf.
761             */
762 642           local void putShortMSB (s, b)
763             deflate_state *s;
764             uInt b;
765             {
766 642           put_byte(s, (Byte)(b >> 8));
767 642           put_byte(s, (Byte)(b & 0xff));
768 642           }
769              
770             /* =========================================================================
771             * Flush as much pending output as possible. All deflate() output, except for
772             * some deflate_stored() output, goes through this function so some
773             * applications may wish to modify it to avoid allocating a large
774             * strm->next_out buffer and copying into it. (See also read_buf()).
775             */
776 645           local void flush_pending(strm)
777             z_streamp strm;
778             {
779             unsigned len;
780 645           deflate_state *s = strm->state;
781              
782 645           _tr_flush_bits(s);
783 645           len = s->pending;
784 645 100         if (len > strm->avail_out) len = strm->avail_out;
785 645 50         if (len == 0) return;
786              
787 645           zmemcpy(strm->next_out, s->pending_out, len);
788 645           strm->next_out += len;
789 645           s->pending_out += len;
790 645           strm->total_out += len;
791 645           strm->avail_out -= len;
792 645           s->pending -= len;
793 645 100         if (s->pending == 0) {
794 642           s->pending_out = s->pending_buf;
795             }
796             }
797              
798             /* ===========================================================================
799             * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1].
800             */
801             #define HCRC_UPDATE(beg) \
802             do { \
803             if (s->gzhead->hcrc && s->pending > (beg)) \
804             strm->adler = crc32(strm->adler, s->pending_buf + (beg), \
805             s->pending - (beg)); \
806             } while (0)
807              
808             /* ========================================================================= */
809 219           int ZEXPORT deflate (strm, flush)
810             z_streamp strm;
811             int flush;
812             {
813             int old_flush; /* value of flush param for previous deflate call */
814             deflate_state *s;
815              
816 219 50         if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) {
    50          
    50          
817 0           return Z_STREAM_ERROR;
818             }
819 219           s = strm->state;
820              
821 219 50         if (strm->next_out == Z_NULL ||
    100          
822 219 50         (strm->avail_in != 0 && strm->next_in == Z_NULL) ||
    100          
823 5 50         (s->status == FINISH_STATE && flush != Z_FINISH)) {
824 0           ERR_RETURN(strm, Z_STREAM_ERROR);
825             }
826 219 50         if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
827              
828 219           old_flush = s->last_flush;
829 219           s->last_flush = flush;
830              
831             /* Flush as much pending output as possible */
832 219 100         if (s->pending != 0) {
833 3           flush_pending(strm);
834 3 50         if (strm->avail_out == 0) {
835             /* Since avail_out is 0, deflate will be called again with
836             * more output space, but possibly with both pending and
837             * avail_in equal to zero. There won't be anything to do,
838             * but this is not an error situation so make sure we
839             * return OK instead of BUF_ERROR at next call of deflate:
840             */
841 0           s->last_flush = -1;
842 0           return Z_OK;
843             }
844              
845             /* Make sure there is something to do and avoid duplicate consecutive
846             * flushes. For repeated and useless calls with Z_FINISH, we keep
847             * returning Z_STREAM_END instead of Z_BUF_ERROR.
848             */
849 216 100         } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&
    50          
    50          
    50          
    0          
850             flush != Z_FINISH) {
851 0           ERR_RETURN(strm, Z_BUF_ERROR);
852             }
853              
854             /* User must not provide more input after the first FINISH: */
855 219 100         if (s->status == FINISH_STATE && strm->avail_in != 0) {
    50          
856 0           ERR_RETURN(strm, Z_BUF_ERROR);
857             }
858              
859             /* Write the header */
860 219 100         if (s->status == INIT_STATE && s->wrap == 0)
    50          
861 0           s->status = BUSY_STATE;
862 219 100         if (s->status == INIT_STATE) {
863             /* zlib header */
864 214           uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
865             uInt level_flags;
866              
867 214 50         if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
    100          
868 157           level_flags = 0;
869 57 50         else if (s->level < 6)
870 0           level_flags = 1;
871 57 50         else if (s->level == 6)
872 57           level_flags = 2;
873             else
874 0           level_flags = 3;
875 214           header |= (level_flags << 6);
876 214 50         if (s->strstart != 0) header |= PRESET_DICT;
877 214           header += 31 - (header % 31);
878              
879 214           putShortMSB(s, header);
880              
881             /* Save the adler32 of the preset dictionary: */
882 214 50         if (s->strstart != 0) {
883 0           putShortMSB(s, (uInt)(strm->adler >> 16));
884 0           putShortMSB(s, (uInt)(strm->adler & 0xffff));
885             }
886 214           strm->adler = adler32(0L, Z_NULL, 0);
887 214           s->status = BUSY_STATE;
888              
889             /* Compression must start with an empty pending buffer */
890 214           flush_pending(strm);
891 214 50         if (s->pending != 0) {
892 0           s->last_flush = -1;
893 0           return Z_OK;
894             }
895             }
896             #ifdef GZIP
897             if (s->status == GZIP_STATE) {
898             /* gzip header */
899             strm->adler = crc32(0L, Z_NULL, 0);
900             put_byte(s, 31);
901             put_byte(s, 139);
902             put_byte(s, 8);
903             if (s->gzhead == Z_NULL) {
904             put_byte(s, 0);
905             put_byte(s, 0);
906             put_byte(s, 0);
907             put_byte(s, 0);
908             put_byte(s, 0);
909             put_byte(s, s->level == 9 ? 2 :
910             (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
911             4 : 0));
912             put_byte(s, OS_CODE);
913             s->status = BUSY_STATE;
914              
915             /* Compression must start with an empty pending buffer */
916             flush_pending(strm);
917             if (s->pending != 0) {
918             s->last_flush = -1;
919             return Z_OK;
920             }
921             }
922             else {
923             put_byte(s, (s->gzhead->text ? 1 : 0) +
924             (s->gzhead->hcrc ? 2 : 0) +
925             (s->gzhead->extra == Z_NULL ? 0 : 4) +
926             (s->gzhead->name == Z_NULL ? 0 : 8) +
927             (s->gzhead->comment == Z_NULL ? 0 : 16)
928             );
929             put_byte(s, (Byte)(s->gzhead->time & 0xff));
930             put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
931             put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
932             put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
933             put_byte(s, s->level == 9 ? 2 :
934             (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
935             4 : 0));
936             put_byte(s, s->gzhead->os & 0xff);
937             if (s->gzhead->extra != Z_NULL) {
938             put_byte(s, s->gzhead->extra_len & 0xff);
939             put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
940             }
941             if (s->gzhead->hcrc)
942             strm->adler = crc32(strm->adler, s->pending_buf,
943             s->pending);
944             s->gzindex = 0;
945             s->status = EXTRA_STATE;
946             }
947             }
948             if (s->status == EXTRA_STATE) {
949             if (s->gzhead->extra != Z_NULL) {
950             ulg beg = s->pending; /* start of bytes to update crc */
951             uInt left = (s->gzhead->extra_len & 0xffff) - s->gzindex;
952             while (s->pending + left > s->pending_buf_size) {
953             uInt copy = s->pending_buf_size - s->pending;
954             zmemcpy(s->pending_buf + s->pending,
955             s->gzhead->extra + s->gzindex, copy);
956             s->pending = s->pending_buf_size;
957             HCRC_UPDATE(beg);
958             s->gzindex += copy;
959             flush_pending(strm);
960             if (s->pending != 0) {
961             s->last_flush = -1;
962             return Z_OK;
963             }
964             beg = 0;
965             left -= copy;
966             }
967             zmemcpy(s->pending_buf + s->pending,
968             s->gzhead->extra + s->gzindex, left);
969             s->pending += left;
970             HCRC_UPDATE(beg);
971             s->gzindex = 0;
972             }
973             s->status = NAME_STATE;
974             }
975             if (s->status == NAME_STATE) {
976             if (s->gzhead->name != Z_NULL) {
977             ulg beg = s->pending; /* start of bytes to update crc */
978             int val;
979             do {
980             if (s->pending == s->pending_buf_size) {
981             HCRC_UPDATE(beg);
982             flush_pending(strm);
983             if (s->pending != 0) {
984             s->last_flush = -1;
985             return Z_OK;
986             }
987             beg = 0;
988             }
989             val = s->gzhead->name[s->gzindex++];
990             put_byte(s, val);
991             } while (val != 0);
992             HCRC_UPDATE(beg);
993             s->gzindex = 0;
994             }
995             s->status = COMMENT_STATE;
996             }
997             if (s->status == COMMENT_STATE) {
998             if (s->gzhead->comment != Z_NULL) {
999             ulg beg = s->pending; /* start of bytes to update crc */
1000             int val;
1001             do {
1002             if (s->pending == s->pending_buf_size) {
1003             HCRC_UPDATE(beg);
1004             flush_pending(strm);
1005             if (s->pending != 0) {
1006             s->last_flush = -1;
1007             return Z_OK;
1008             }
1009             beg = 0;
1010             }
1011             val = s->gzhead->comment[s->gzindex++];
1012             put_byte(s, val);
1013             } while (val != 0);
1014             HCRC_UPDATE(beg);
1015             }
1016             s->status = HCRC_STATE;
1017             }
1018             if (s->status == HCRC_STATE) {
1019             if (s->gzhead->hcrc) {
1020             if (s->pending + 2 > s->pending_buf_size) {
1021             flush_pending(strm);
1022             if (s->pending != 0) {
1023             s->last_flush = -1;
1024             return Z_OK;
1025             }
1026             }
1027             put_byte(s, (Byte)(strm->adler & 0xff));
1028             put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
1029             strm->adler = crc32(0L, Z_NULL, 0);
1030             }
1031             s->status = BUSY_STATE;
1032              
1033             /* Compression must start with an empty pending buffer */
1034             flush_pending(strm);
1035             if (s->pending != 0) {
1036             s->last_flush = -1;
1037             return Z_OK;
1038             }
1039             }
1040             #endif
1041              
1042             /* Start a new block or continue the current one.
1043             */
1044 219 100         if (strm->avail_in != 0 || s->lookahead != 0 ||
    50          
    50          
1045 7 100         (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
1046             block_state bstate;
1047              
1048 214 50         bstate = s->level == 0 ? deflate_stored(s, flush) :
    50          
    50          
1049 214           s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
1050 214           s->strategy == Z_RLE ? deflate_rle(s, flush) :
1051 214           (*(configuration_table[s->level].func))(s, flush);
1052              
1053 214 100         if (bstate == finish_started || bstate == finish_done) {
    50          
1054 214           s->status = FINISH_STATE;
1055             }
1056 214 50         if (bstate == need_more || bstate == finish_started) {
    100          
1057 4 50         if (strm->avail_out == 0) {
1058 4           s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
1059             }
1060 4           return Z_OK;
1061             /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
1062             * of deflate should use the same flush parameter to make sure
1063             * that the flush is complete. So we don't have to output an
1064             * empty block here, this will be done at next call. This also
1065             * ensures that for a very small output buffer, we emit at most
1066             * one empty block.
1067             */
1068             }
1069 210 50         if (bstate == block_done) {
1070 0 0         if (flush == Z_PARTIAL_FLUSH) {
1071 0           _tr_align(s);
1072 0 0         } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
1073 0           _tr_stored_block(s, (char*)0, 0L, 0);
1074             /* For a full flush, this empty block will be recognized
1075             * as a special marker by inflate_sync().
1076             */
1077 0 0         if (flush == Z_FULL_FLUSH) {
1078 0           CLEAR_HASH(s); /* forget history */
1079 0 0         if (s->lookahead == 0) {
1080 0           s->strstart = 0;
1081 0           s->block_start = 0L;
1082 0           s->insert = 0;
1083             }
1084             }
1085             }
1086 0           flush_pending(strm);
1087 0 0         if (strm->avail_out == 0) {
1088 0           s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
1089 0           return Z_OK;
1090             }
1091             }
1092             }
1093              
1094 215 50         if (flush != Z_FINISH) return Z_OK;
1095 215 100         if (s->wrap <= 0) return Z_STREAM_END;
1096              
1097             /* Write the trailer */
1098             #ifdef GZIP
1099             if (s->wrap == 2) {
1100             put_byte(s, (Byte)(strm->adler & 0xff));
1101             put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
1102             put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
1103             put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
1104             put_byte(s, (Byte)(strm->total_in & 0xff));
1105             put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
1106             put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
1107             put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
1108             }
1109             else
1110             #endif
1111             {
1112 214           putShortMSB(s, (uInt)(strm->adler >> 16));
1113 214           putShortMSB(s, (uInt)(strm->adler & 0xffff));
1114             }
1115 214           flush_pending(strm);
1116             /* If avail_out is zero, the application will call deflate again
1117             * to flush the rest.
1118             */
1119 214 50         if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
1120 214           return s->pending != 0 ? Z_OK : Z_STREAM_END;
1121             }
1122              
1123             /* ========================================================================= */
1124 191           int ZEXPORT deflateEnd (strm)
1125             z_streamp strm;
1126             {
1127             int status;
1128              
1129 191 50         if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
1130              
1131 191           status = strm->state->status;
1132              
1133             /* Deallocate in reverse order of allocations: */
1134 191 50         TRY_FREE(strm, strm->state->pending_buf);
1135 191 50         TRY_FREE(strm, strm->state->head);
1136 191 50         TRY_FREE(strm, strm->state->prev);
1137 191 50         TRY_FREE(strm, strm->state->window);
1138              
1139 191           ZFREE(strm, strm->state);
1140 191           strm->state = Z_NULL;
1141              
1142 191 50         return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
1143             }
1144              
1145             /* =========================================================================
1146             * Copy the source state to the destination state.
1147             * To simplify the source, this is not supported for 16-bit MSDOS (which
1148             * doesn't have enough memory anyway to duplicate compression states).
1149             */
1150 0           int ZEXPORT deflateCopy (dest, source)
1151             z_streamp dest;
1152             z_streamp source;
1153             {
1154             #ifdef MAXSEG_64K
1155             return Z_STREAM_ERROR;
1156             #else
1157             deflate_state *ds;
1158             deflate_state *ss;
1159              
1160              
1161 0 0         if (deflateStateCheck(source) || dest == Z_NULL) {
    0          
1162 0           return Z_STREAM_ERROR;
1163             }
1164              
1165 0           ss = source->state;
1166              
1167 0           zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
1168              
1169 0           ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
1170 0 0         if (ds == Z_NULL) return Z_MEM_ERROR;
1171 0           dest->state = (struct internal_state FAR *) ds;
1172 0           zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));
1173 0           ds->strm = dest;
1174              
1175 0           ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
1176 0           ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
1177 0           ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
1178 0           ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, 4);
1179              
1180 0 0         if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
    0          
    0          
    0          
1181 0           ds->pending_buf == Z_NULL) {
1182 0           deflateEnd (dest);
1183 0           return Z_MEM_ERROR;
1184             }
1185             /* following zmemcpy do not work for 16-bit MSDOS */
1186 0           zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
1187 0           zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));
1188 0           zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));
1189 0           zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
1190              
1191 0           ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
1192 0           ds->sym_buf = ds->pending_buf + ds->lit_bufsize;
1193              
1194 0           ds->l_desc.dyn_tree = ds->dyn_ltree;
1195 0           ds->d_desc.dyn_tree = ds->dyn_dtree;
1196 0           ds->bl_desc.dyn_tree = ds->bl_tree;
1197              
1198 0           return Z_OK;
1199             #endif /* MAXSEG_64K */
1200             }
1201              
1202             /* ===========================================================================
1203             * Read a new buffer from the current input stream, update the adler32
1204             * and total number of bytes read. All deflate() input goes through
1205             * this function so some applications may wish to modify it to avoid
1206             * allocating a large strm->next_in buffer and copying from it.
1207             * (See also flush_pending()).
1208             */
1209 212           local unsigned read_buf(strm, buf, size)
1210             z_streamp strm;
1211             Bytef *buf;
1212             unsigned size;
1213             {
1214 212           unsigned len = strm->avail_in;
1215              
1216 212 50         if (len > size) len = size;
1217 212 50         if (len == 0) return 0;
1218              
1219 212           strm->avail_in -= len;
1220              
1221 212           zmemcpy(buf, strm->next_in, len);
1222 212 50         if (strm->state->wrap == 1) {
1223 212           strm->adler = adler32(strm->adler, buf, len);
1224             }
1225             #ifdef GZIP
1226             else if (strm->state->wrap == 2) {
1227             strm->adler = crc32(strm->adler, buf, len);
1228             }
1229             #endif
1230 212           strm->next_in += len;
1231 212           strm->total_in += len;
1232              
1233 212           return len;
1234             }
1235              
1236             /* ===========================================================================
1237             * Initialize the "longest match" routines for a new zlib stream
1238             */
1239 241           local void lm_init (s)
1240             deflate_state *s;
1241             {
1242 241           s->window_size = (ulg)2L*s->w_size;
1243              
1244 241           CLEAR_HASH(s);
1245              
1246             /* Set the default configuration parameters:
1247             */
1248 241           s->max_lazy_match = configuration_table[s->level].max_lazy;
1249 241           s->good_match = configuration_table[s->level].good_length;
1250 241           s->nice_match = configuration_table[s->level].nice_length;
1251 241           s->max_chain_length = configuration_table[s->level].max_chain;
1252              
1253 241           s->strstart = 0;
1254 241           s->block_start = 0L;
1255 241           s->lookahead = 0;
1256 241           s->insert = 0;
1257 241           s->match_length = s->prev_length = MIN_MATCH-1;
1258 241           s->match_available = 0;
1259 241           s->ins_h = 0;
1260             #ifndef FASTEST
1261             #ifdef ASMV
1262             match_init(); /* initialize the asm code */
1263             #endif
1264             #endif
1265 241           }
1266              
1267             #ifndef FASTEST
1268             /* ===========================================================================
1269             * Set match_start to the longest match starting at the given string and
1270             * return its length. Matches shorter or equal to prev_length are discarded,
1271             * in which case the result is equal to prev_length and match_start is
1272             * garbage.
1273             * IN assertions: cur_match is the head of the hash chain for the current
1274             * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1275             * OUT assertion: the match length is not greater than s->lookahead.
1276             */
1277             #ifndef ASMV
1278             /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
1279             * match.S. The code will be functionally equivalent.
1280             */
1281 746           local uInt longest_match(s, cur_match)
1282             deflate_state *s;
1283             IPos cur_match; /* current match */
1284             {
1285 746           unsigned chain_length = s->max_chain_length;/* max hash chain length */
1286 746           register Bytef *scan = s->window + s->strstart; /* current string */
1287             register Bytef *match; /* matched string */
1288             register int len; /* length of current match */
1289 746           int best_len = (int)s->prev_length; /* best match length so far */
1290 746           int nice_match = s->nice_match; /* stop if match long enough */
1291 1492           IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
1292 746 50         s->strstart - (IPos)MAX_DIST(s) : NIL;
1293             /* Stop when cur_match becomes <= limit. To simplify the code,
1294             * we prevent matches with the string of window index 0.
1295             */
1296 746           Posf *prev = s->prev;
1297 746           uInt wmask = s->w_mask;
1298              
1299             #ifdef UNALIGNED_OK
1300             /* Compare two bytes at a time. Note: this is not always beneficial.
1301             * Try with and without -DUNALIGNED_OK to check.
1302             */
1303             register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
1304             register ush scan_start = *(ushf*)scan;
1305             register ush scan_end = *(ushf*)(scan+best_len-1);
1306             #else
1307 746           register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1308 746           register Byte scan_end1 = scan[best_len-1];
1309 746           register Byte scan_end = scan[best_len];
1310             #endif
1311              
1312             /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1313             * It is easy to get rid of this optimization if necessary.
1314             */
1315             Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1316              
1317             /* Do not waste too much time if we already have a good match: */
1318 746 100         if (s->prev_length >= s->good_match) {
1319 10           chain_length >>= 2;
1320             }
1321             /* Do not look for matches beyond the end of the input. This is necessary
1322             * to make deflate deterministic.
1323             */
1324 746 100         if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead;
1325              
1326             Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1327              
1328             do {
1329             Assert(cur_match < s->strstart, "no future");
1330 829           match = s->window + cur_match;
1331              
1332             /* Skip to next match if the match length cannot increase
1333             * or if the match length is less than 2. Note that the checks below
1334             * for insufficient lookahead only occur occasionally for performance
1335             * reasons. Therefore uninitialized memory will be accessed, and
1336             * conditional jumps will be made that depend on those values.
1337             * However the length of the match is limited to the lookahead, so
1338             * the output of deflate is not affected by the uninitialized values.
1339             */
1340             #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
1341             /* This code assumes sizeof(unsigned short) == 2. Do not use
1342             * UNALIGNED_OK if your compiler uses a different size.
1343             */
1344             if (*(ushf*)(match+best_len-1) != scan_end ||
1345             *(ushf*)match != scan_start) continue;
1346              
1347             /* It is not necessary to compare scan[2] and match[2] since they are
1348             * always equal when the other bytes match, given that the hash keys
1349             * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
1350             * strstart+3, +5, ... up to strstart+257. We check for insufficient
1351             * lookahead only every 4th comparison; the 128th check will be made
1352             * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
1353             * necessary to put more guard bytes at the end of the window, or
1354             * to check more often for insufficient lookahead.
1355             */
1356             Assert(scan[2] == match[2], "scan[2]?");
1357             scan++, match++;
1358             do {
1359             } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1360             *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1361             *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1362             *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1363             scan < strend);
1364             /* The funny "do {}" generates better code on most compilers */
1365              
1366             /* Here, scan <= window+strstart+257 */
1367             Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1368             if (*scan == *match) scan++;
1369              
1370             len = (MAX_MATCH - 1) - (int)(strend-scan);
1371             scan = strend - (MAX_MATCH-1);
1372              
1373             #else /* UNALIGNED_OK */
1374              
1375 829 100         if (match[best_len] != scan_end ||
    100          
1376 700 100         match[best_len-1] != scan_end1 ||
1377 630 50         *match != *scan ||
1378 199           *++match != scan[1]) continue;
1379              
1380             /* The check at best_len-1 can be removed because it will be made
1381             * again later. (This heuristic is not always a win.)
1382             * It is not necessary to compare scan[2] and match[2] since they
1383             * are always equal when the other bytes match, given that
1384             * the hash keys are equal and that HASH_BITS >= 8.
1385             */
1386 630           scan += 2, match++;
1387             Assert(*scan == *match, "match[2]?");
1388              
1389             /* We check for insufficient lookahead only every 8th comparison;
1390             * the 256th check will be made at strstart+258.
1391             */
1392             do {
1393 708 100         } while (*++scan == *++match && *++scan == *++match &&
    100          
1394 654 100         *++scan == *++match && *++scan == *++match &&
    100          
1395 516 100         *++scan == *++match && *++scan == *++match &&
    100          
1396 433 100         *++scan == *++match && *++scan == *++match &&
    50          
1397 1052 100         scan < strend);
1398              
1399             Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1400              
1401 630           len = MAX_MATCH - (int)(strend - scan);
1402 630           scan = strend - MAX_MATCH;
1403              
1404             #endif /* UNALIGNED_OK */
1405              
1406 630 50         if (len > best_len) {
1407 630           s->match_start = cur_match;
1408 630           best_len = len;
1409 630 100         if (len >= nice_match) break;
1410             #ifdef UNALIGNED_OK
1411             scan_end = *(ushf*)(scan+best_len-1);
1412             #else
1413 511           scan_end1 = scan[best_len-1];
1414 511           scan_end = scan[best_len];
1415             #endif
1416             }
1417 710           } while ((cur_match = prev[cur_match & wmask]) > limit
1418 710 100         && --chain_length != 0);
    100          
1419              
1420 746 50         if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
1421 0           return s->lookahead;
1422             }
1423             #endif /* ASMV */
1424              
1425             #else /* FASTEST */
1426              
1427             /* ---------------------------------------------------------------------------
1428             * Optimized version for FASTEST only
1429             */
1430             local uInt longest_match(s, cur_match)
1431             deflate_state *s;
1432             IPos cur_match; /* current match */
1433             {
1434             register Bytef *scan = s->window + s->strstart; /* current string */
1435             register Bytef *match; /* matched string */
1436             register int len; /* length of current match */
1437             register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1438              
1439             /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1440             * It is easy to get rid of this optimization if necessary.
1441             */
1442             Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1443              
1444             Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1445              
1446             Assert(cur_match < s->strstart, "no future");
1447              
1448             match = s->window + cur_match;
1449              
1450             /* Return failure if the match length is less than 2:
1451             */
1452             if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
1453              
1454             /* The check at best_len-1 can be removed because it will be made
1455             * again later. (This heuristic is not always a win.)
1456             * It is not necessary to compare scan[2] and match[2] since they
1457             * are always equal when the other bytes match, given that
1458             * the hash keys are equal and that HASH_BITS >= 8.
1459             */
1460             scan += 2, match += 2;
1461             Assert(*scan == *match, "match[2]?");
1462              
1463             /* We check for insufficient lookahead only every 8th comparison;
1464             * the 256th check will be made at strstart+258.
1465             */
1466             do {
1467             } while (*++scan == *++match && *++scan == *++match &&
1468             *++scan == *++match && *++scan == *++match &&
1469             *++scan == *++match && *++scan == *++match &&
1470             *++scan == *++match && *++scan == *++match &&
1471             scan < strend);
1472              
1473             Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1474              
1475             len = MAX_MATCH - (int)(strend - scan);
1476              
1477             if (len < MIN_MATCH) return MIN_MATCH - 1;
1478              
1479             s->match_start = cur_match;
1480             return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
1481             }
1482              
1483             #endif /* FASTEST */
1484              
1485             #ifdef ZLIB_DEBUG
1486              
1487             #define EQUAL 0
1488             /* result of memcmp for equal strings */
1489              
1490             /* ===========================================================================
1491             * Check that the match at match_start is indeed a match.
1492             */
1493             local void check_match(s, start, match, length)
1494             deflate_state *s;
1495             IPos start, match;
1496             int length;
1497             {
1498             /* check that the match is indeed a match */
1499             if (zmemcmp(s->window + match,
1500             s->window + start, length) != EQUAL) {
1501             fprintf(stderr, " start %u, match %u, length %d\n",
1502             start, match, length);
1503             do {
1504             fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
1505             } while (--length != 0);
1506             z_error("invalid match");
1507             }
1508             if (z_verbose > 1) {
1509             fprintf(stderr,"\\[%d,%d]", start-match, length);
1510             do { putc(s->window[start++], stderr); } while (--length != 0);
1511             }
1512             }
1513             #else
1514             # define check_match(s, start, match, length)
1515             #endif /* ZLIB_DEBUG */
1516              
1517             /* ===========================================================================
1518             * Fill the window when the lookahead becomes insufficient.
1519             * Updates strstart and lookahead.
1520             *
1521             * IN assertion: lookahead < MIN_LOOKAHEAD
1522             * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1523             * At least one byte has been read, or avail_in == 0; reads are
1524             * performed for at least two bytes (required for the zip translate_eol
1525             * option -- not supported here).
1526             */
1527 16702           local void fill_window(s)
1528             deflate_state *s;
1529             {
1530             unsigned n;
1531             unsigned more; /* Amount of free space at the end of the window. */
1532 16702           uInt wsize = s->w_size;
1533              
1534             Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
1535              
1536             do {
1537 16702           more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
1538              
1539             /* Deal with !@#$% 64K limit: */
1540             if (sizeof(int) <= 2) {
1541             if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1542             more = wsize;
1543              
1544             } else if (more == (unsigned)(-1)) {
1545             /* Very unlikely, but possible on 16 bit machine if
1546             * strstart == 0 && lookahead == 1 (input done a byte at time)
1547             */
1548             more--;
1549             }
1550             }
1551              
1552             /* If the window is almost full and there is insufficient lookahead,
1553             * move the upper half to the lower one to make room in the upper half.
1554             */
1555 16702 50         if (s->strstart >= wsize+MAX_DIST(s)) {
1556              
1557 0           zmemcpy(s->window, s->window+wsize, (unsigned)wsize - more);
1558 0           s->match_start -= wsize;
1559 0           s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
1560 0           s->block_start -= (long) wsize;
1561 0 0         if (s->insert > s->strstart)
1562 0           s->insert = s->strstart;
1563 0           slide_hash(s);
1564 0           more += wsize;
1565             }
1566 16702 100         if (s->strm->avail_in == 0) break;
1567              
1568             /* If there was no sliding:
1569             * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1570             * more == window_size - lookahead - strstart
1571             * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1572             * => more >= window_size - 2*WSIZE + 2
1573             * In the BIG_MEM or MMAP case (not yet supported),
1574             * window_size == input_size + MIN_LOOKAHEAD &&
1575             * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1576             * Otherwise, window_size == 2*WSIZE so more >= 2.
1577             * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1578             */
1579             Assert(more >= 2, "more < 2");
1580              
1581 212           n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1582 212           s->lookahead += n;
1583              
1584             /* Initialize the hash value now that we have some input: */
1585 212 50         if (s->lookahead + s->insert >= MIN_MATCH) {
1586 212           uInt str = s->strstart - s->insert;
1587 212           s->ins_h = s->window[str];
1588 212           UPDATE_HASH(s, s->ins_h, s->window[str + 1]);
1589             #if MIN_MATCH != 3
1590             Call UPDATE_HASH() MIN_MATCH-3 more times
1591             #endif
1592 212 50         while (s->insert) {
1593 0           UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
1594             #ifndef FASTEST
1595 0           s->prev[str & s->w_mask] = s->head[s->ins_h];
1596             #endif
1597 0           s->head[s->ins_h] = (Pos)str;
1598 0           str++;
1599 0           s->insert--;
1600 0 0         if (s->lookahead + s->insert < MIN_MATCH)
1601 0           break;
1602             }
1603             }
1604             /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1605             * but this is not important since only literal bytes will be emitted.
1606             */
1607              
1608 212 100         } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
    50          
1609              
1610             /* If the WIN_INIT bytes after the end of the current data have never been
1611             * written, then zero those bytes in order to avoid memory check reports of
1612             * the use of uninitialized (or uninitialised as Julian writes) bytes by
1613             * the longest match routines. Update the high water mark for the next
1614             * time through here. WIN_INIT is set to MAX_MATCH since the longest match
1615             * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
1616             */
1617 16702 50         if (s->high_water < s->window_size) {
1618 16702           ulg curr = s->strstart + (ulg)(s->lookahead);
1619             ulg init;
1620              
1621 16702 100         if (s->high_water < curr) {
1622             /* Previous high water mark below current data -- zero WIN_INIT
1623             * bytes or up to end of window, whichever is less.
1624             */
1625 168           init = s->window_size - curr;
1626 168 50         if (init > WIN_INIT)
1627 168           init = WIN_INIT;
1628 168           zmemzero(s->window + curr, (unsigned)init);
1629 168           s->high_water = curr + init;
1630             }
1631 16534 100         else if (s->high_water < (ulg)curr + WIN_INIT) {
1632             /* High water mark at or above current data, but below current data
1633             * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
1634             * to end of window, whichever is less.
1635             */
1636 4           init = (ulg)curr + WIN_INIT - s->high_water;
1637 4 50         if (init > s->window_size - s->high_water)
1638 0           init = s->window_size - s->high_water;
1639 4           zmemzero(s->window + s->high_water, (unsigned)init);
1640 4           s->high_water += init;
1641             }
1642             }
1643              
1644             Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1645             "not enough room for search");
1646 16702           }
1647              
1648             /* ===========================================================================
1649             * Flush the current block, with given end-of-file flag.
1650             * IN assertion: strstart is set to the end of the current match.
1651             */
1652             #define FLUSH_BLOCK_ONLY(s, last) { \
1653             _tr_flush_block(s, (s->block_start >= 0L ? \
1654             (charf *)&s->window[(unsigned)s->block_start] : \
1655             (charf *)Z_NULL), \
1656             (ulg)((long)s->strstart - s->block_start), \
1657             (last)); \
1658             s->block_start = s->strstart; \
1659             flush_pending(s->strm); \
1660             Tracev((stderr,"[FLUSH]")); \
1661             }
1662              
1663             /* Same but force premature exit if necessary. */
1664             #define FLUSH_BLOCK(s, last) { \
1665             FLUSH_BLOCK_ONLY(s, last); \
1666             if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
1667             }
1668              
1669             /* Maximum stored block length in deflate format (not including header). */
1670             #define MAX_STORED 65535
1671              
1672             /* Minimum of a and b. */
1673             #define MIN(a, b) ((a) > (b) ? (b) : (a))
1674              
1675             /* ===========================================================================
1676             * Copy without compression as much as possible from the input stream, return
1677             * the current block state.
1678             *
1679             * In case deflateParams() is used to later switch to a non-zero compression
1680             * level, s->matches (otherwise unused when storing) keeps track of the number
1681             * of hash table slides to perform. If s->matches is 1, then one hash table
1682             * slide will be done when switching. If s->matches is 2, the maximum value
1683             * allowed here, then the hash table will be cleared, since two or more slides
1684             * is the same as a clear.
1685             *
1686             * deflate_stored() is written to minimize the number of times an input byte is
1687             * copied. It is most efficient with large input and output buffers, which
1688             * maximizes the opportunites to have a single copy from next_in to next_out.
1689             */
1690 0           local block_state deflate_stored(s, flush)
1691             deflate_state *s;
1692             int flush;
1693             {
1694             /* Smallest worthy block size when not flushing or finishing. By default
1695             * this is 32K. This can be as small as 507 bytes for memLevel == 1. For
1696             * large input and output buffers, the stored block size will be larger.
1697             */
1698 0           unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size);
1699              
1700             /* Copy as many min_block or larger stored blocks directly to next_out as
1701             * possible. If flushing, copy the remaining available input to next_out as
1702             * stored blocks, if there is enough space.
1703             */
1704 0           unsigned len, left, have, last = 0;
1705 0           unsigned used = s->strm->avail_in;
1706             do {
1707             /* Set len to the maximum size block that we can copy directly with the
1708             * available input data and output space. Set left to how much of that
1709             * would be copied from what's left in the window.
1710             */
1711 0           len = MAX_STORED; /* maximum deflate stored block length */
1712 0           have = (s->bi_valid + 42) >> 3; /* number of header bytes */
1713 0 0         if (s->strm->avail_out < have) /* need room for header */
1714 0           break;
1715             /* maximum stored block length that will fit in avail_out: */
1716 0           have = s->strm->avail_out - have;
1717 0           left = s->strstart - s->block_start; /* bytes left in window */
1718 0 0         if (len > (ulg)left + s->strm->avail_in)
1719 0           len = left + s->strm->avail_in; /* limit len to the input */
1720 0 0         if (len > have)
1721 0           len = have; /* limit len to the output */
1722              
1723             /* If the stored block would be less than min_block in length, or if
1724             * unable to copy all of the available input when flushing, then try
1725             * copying to the window and the pending buffer instead. Also don't
1726             * write an empty block when flushing -- deflate() does that.
1727             */
1728 0 0         if (len < min_block && ((len == 0 && flush != Z_FINISH) ||
    0          
    0          
    0          
1729 0 0         flush == Z_NO_FLUSH ||
1730 0           len != left + s->strm->avail_in))
1731             break;
1732              
1733             /* Make a dummy stored block in pending to get the header bytes,
1734             * including any pending bits. This also updates the debugging counts.
1735             */
1736 0 0         last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0;
    0          
1737 0           _tr_stored_block(s, (char *)0, 0L, last);
1738              
1739             /* Replace the lengths in the dummy stored block with len. */
1740 0           s->pending_buf[s->pending - 4] = len;
1741 0           s->pending_buf[s->pending - 3] = len >> 8;
1742 0           s->pending_buf[s->pending - 2] = ~len;
1743 0           s->pending_buf[s->pending - 1] = ~len >> 8;
1744              
1745             /* Write the stored block header bytes. */
1746 0           flush_pending(s->strm);
1747              
1748             #ifdef ZLIB_DEBUG
1749             /* Update debugging counts for the data about to be copied. */
1750             s->compressed_len += len << 3;
1751             s->bits_sent += len << 3;
1752             #endif
1753              
1754             /* Copy uncompressed bytes from the window to next_out. */
1755 0 0         if (left) {
1756 0 0         if (left > len)
1757 0           left = len;
1758 0           zmemcpy(s->strm->next_out, s->window + s->block_start, left);
1759 0           s->strm->next_out += left;
1760 0           s->strm->avail_out -= left;
1761 0           s->strm->total_out += left;
1762 0           s->block_start += left;
1763 0           len -= left;
1764             }
1765              
1766             /* Copy uncompressed bytes directly from next_in to next_out, updating
1767             * the check value.
1768             */
1769 0 0         if (len) {
1770 0           read_buf(s->strm, s->strm->next_out, len);
1771 0           s->strm->next_out += len;
1772 0           s->strm->avail_out -= len;
1773 0           s->strm->total_out += len;
1774             }
1775 0 0         } while (last == 0);
1776              
1777             /* Update the sliding window with the last s->w_size bytes of the copied
1778             * data, or append all of the copied data to the existing window if less
1779             * than s->w_size bytes were copied. Also update the number of bytes to
1780             * insert in the hash tables, in the event that deflateParams() switches to
1781             * a non-zero compression level.
1782             */
1783 0           used -= s->strm->avail_in; /* number of input bytes directly copied */
1784 0 0         if (used) {
1785             /* If any input was used, then no unused input remains in the window,
1786             * therefore s->block_start == s->strstart.
1787             */
1788 0 0         if (used >= s->w_size) { /* supplant the previous history */
1789 0           s->matches = 2; /* clear hash */
1790 0           zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);
1791 0           s->strstart = s->w_size;
1792 0           s->insert = s->strstart;
1793             }
1794             else {
1795 0 0         if (s->window_size - s->strstart <= used) {
1796             /* Slide the window down. */
1797 0           s->strstart -= s->w_size;
1798 0           zmemcpy(s->window, s->window + s->w_size, s->strstart);
1799 0 0         if (s->matches < 2)
1800 0           s->matches++; /* add a pending slide_hash() */
1801 0 0         if (s->insert > s->strstart)
1802 0           s->insert = s->strstart;
1803             }
1804 0           zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);
1805 0           s->strstart += used;
1806 0           s->insert += MIN(used, s->w_size - s->insert);
1807             }
1808 0           s->block_start = s->strstart;
1809             }
1810 0 0         if (s->high_water < s->strstart)
1811 0           s->high_water = s->strstart;
1812              
1813             /* If the last block was written to next_out, then done. */
1814 0 0         if (last)
1815 0           return finish_done;
1816              
1817             /* If flushing and all input has been consumed, then done. */
1818 0 0         if (flush != Z_NO_FLUSH && flush != Z_FINISH &&
    0          
    0          
1819 0 0         s->strm->avail_in == 0 && (long)s->strstart == s->block_start)
1820 0           return block_done;
1821              
1822             /* Fill the window with any remaining input. */
1823 0           have = s->window_size - s->strstart;
1824 0 0         if (s->strm->avail_in > have && s->block_start >= (long)s->w_size) {
    0          
1825             /* Slide the window down. */
1826 0           s->block_start -= s->w_size;
1827 0           s->strstart -= s->w_size;
1828 0           zmemcpy(s->window, s->window + s->w_size, s->strstart);
1829 0 0         if (s->matches < 2)
1830 0           s->matches++; /* add a pending slide_hash() */
1831 0           have += s->w_size; /* more space now */
1832 0 0         if (s->insert > s->strstart)
1833 0           s->insert = s->strstart;
1834             }
1835 0 0         if (have > s->strm->avail_in)
1836 0           have = s->strm->avail_in;
1837 0 0         if (have) {
1838 0           read_buf(s->strm, s->window + s->strstart, have);
1839 0           s->strstart += have;
1840 0           s->insert += MIN(have, s->w_size - s->insert);
1841             }
1842 0 0         if (s->high_water < s->strstart)
1843 0           s->high_water = s->strstart;
1844              
1845             /* There was not enough avail_out to write a complete worthy or flushed
1846             * stored block to next_out. Write a stored block to pending instead, if we
1847             * have enough input for a worthy block, or if flushing and there is enough
1848             * room for the remaining input as a stored block in the pending buffer.
1849             */
1850 0           have = (s->bi_valid + 42) >> 3; /* number of header bytes */
1851             /* maximum stored block length that will fit in pending: */
1852 0           have = MIN(s->pending_buf_size - have, MAX_STORED);
1853 0           min_block = MIN(have, s->w_size);
1854 0           left = s->strstart - s->block_start;
1855 0 0         if (left >= min_block ||
    0          
1856 0 0         ((left || flush == Z_FINISH) && flush != Z_NO_FLUSH &&
    0          
    0          
1857 0 0         s->strm->avail_in == 0 && left <= have)) {
1858 0           len = MIN(left, have);
1859 0 0         last = flush == Z_FINISH && s->strm->avail_in == 0 &&
1860 0 0         len == left ? 1 : 0;
    0          
1861 0           _tr_stored_block(s, (charf *)s->window + s->block_start, len, last);
1862 0           s->block_start += len;
1863 0           flush_pending(s->strm);
1864             }
1865              
1866             /* We've done all we can with the available input and output. */
1867 0 0         return last ? finish_started : need_more;
1868             }
1869              
1870             /* ===========================================================================
1871             * Compress as much as possible from the input stream, return the current
1872             * block state.
1873             * This function does not perform lazy evaluation of matches and inserts
1874             * new strings in the dictionary only for unmatched strings or for short
1875             * matches. It is used only for the fast compression options.
1876             */
1877 157           local block_state deflate_fast(s, flush)
1878             deflate_state *s;
1879             int flush;
1880             {
1881             IPos hash_head; /* head of the hash chain */
1882             int bflush; /* set if current block must be flushed */
1883              
1884             for (;;) {
1885             /* Make sure that we always have enough lookahead, except
1886             * at the end of the input file. We need MAX_MATCH bytes
1887             * for the next match, plus MIN_MATCH bytes to insert the
1888             * string following the next match.
1889             */
1890 13960 100         if (s->lookahead < MIN_LOOKAHEAD) {
1891 13550           fill_window(s);
1892 13550 100         if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
    50          
1893 0           return need_more;
1894             }
1895 13550 100         if (s->lookahead == 0) break; /* flush the current block */
1896             }
1897              
1898             /* Insert the string window[strstart .. strstart+2] in the
1899             * dictionary, and set hash_head to the head of the hash chain:
1900             */
1901 13803           hash_head = NIL;
1902 13803 100         if (s->lookahead >= MIN_MATCH) {
1903 13541           INSERT_STRING(s, s->strstart, hash_head);
1904             }
1905              
1906             /* Find the longest match, discarding those <= prev_length.
1907             * At this point we have always match_length < MIN_MATCH
1908             */
1909 13803 100         if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
    50          
1910             /* To simplify the code, we prevent matches with the string
1911             * of window index 0 (in particular we have to avoid a match
1912             * of the string with itself at the start of the input file).
1913             */
1914 597           s->match_length = longest_match (s, hash_head);
1915             /* longest_match() sets match_start */
1916             }
1917 13803 100         if (s->match_length >= MIN_MATCH) {
1918             check_match(s, s->strstart, s->match_start, s->match_length);
1919              
1920 515 100         _tr_tally_dist(s, s->strstart - s->match_start,
1921             s->match_length - MIN_MATCH, bflush);
1922              
1923 515           s->lookahead -= s->match_length;
1924              
1925             /* Insert new strings in the hash table only if the match length
1926             * is not too large. This saves time but degrades compression.
1927             */
1928             #ifndef FASTEST
1929 515 100         if (s->match_length <= s->max_insert_length &&
    100          
1930 266           s->lookahead >= MIN_MATCH) {
1931 260           s->match_length--; /* string at strstart already in table */
1932             do {
1933 536           s->strstart++;
1934 536           INSERT_STRING(s, s->strstart, hash_head);
1935             /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1936             * always MIN_MATCH bytes ahead.
1937             */
1938 536 100         } while (--s->match_length != 0);
1939 260           s->strstart++;
1940             } else
1941             #endif
1942             {
1943 255           s->strstart += s->match_length;
1944 255           s->match_length = 0;
1945 255           s->ins_h = s->window[s->strstart];
1946 515           UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1947             #if MIN_MATCH != 3
1948             Call UPDATE_HASH() MIN_MATCH-3 more times
1949             #endif
1950             /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1951             * matter since it will be recomputed at next deflate call.
1952             */
1953             }
1954             } else {
1955             /* No match, output a literal byte */
1956             Tracevv((stderr,"%c", s->window[s->strstart]));
1957 13288           _tr_tally_lit (s, s->window[s->strstart], bflush);
1958 13288           s->lookahead--;
1959 13288           s->strstart++;
1960             }
1961 13803 50         if (bflush) FLUSH_BLOCK(s, 0);
    0          
    0          
1962 13803           }
1963 157           s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
1964 157 50         if (flush == Z_FINISH) {
1965 157 50         FLUSH_BLOCK(s, 1);
    50          
1966 157           return finish_done;
1967             }
1968 0 0         if (s->sym_next)
1969 0 0         FLUSH_BLOCK(s, 0);
    0          
1970 0           return block_done;
1971             }
1972              
1973             #ifndef FASTEST
1974             /* ===========================================================================
1975             * Same as above, but achieves better compression. We use a lazy
1976             * evaluation for matches: a match is finally adopted only if there is
1977             * no better match at the next window position.
1978             */
1979 57           local block_state deflate_slow(s, flush)
1980             deflate_state *s;
1981             int flush;
1982             {
1983             IPos hash_head; /* head of hash chain */
1984             int bflush; /* set if current block must be flushed */
1985              
1986             /* Process the input block. */
1987             for (;;) {
1988             /* Make sure that we always have enough lookahead, except
1989             * at the end of the input file. We need MAX_MATCH bytes
1990             * for the next match, plus MIN_MATCH bytes to insert the
1991             * string following the next match.
1992             */
1993 3152 50         if (s->lookahead < MIN_LOOKAHEAD) {
1994 3152           fill_window(s);
1995 3152 50         if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
    50          
1996 0           return need_more;
1997             }
1998 3152 100         if (s->lookahead == 0) break; /* flush the current block */
1999             }
2000              
2001             /* Insert the string window[strstart .. strstart+2] in the
2002             * dictionary, and set hash_head to the head of the hash chain:
2003             */
2004 3095           hash_head = NIL;
2005 3095 100         if (s->lookahead >= MIN_MATCH) {
2006 2997           INSERT_STRING(s, s->strstart, hash_head);
2007             }
2008              
2009             /* Find the longest match, discarding those <= prev_length.
2010             */
2011 3095           s->prev_length = s->match_length, s->prev_match = s->match_start;
2012 3095           s->match_length = MIN_MATCH-1;
2013              
2014 3095 100         if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
    100          
    50          
2015 149           s->strstart - hash_head <= MAX_DIST(s)) {
2016             /* To simplify the code, we prevent matches with the string
2017             * of window index 0 (in particular we have to avoid a match
2018             * of the string with itself at the start of the input file).
2019             */
2020 149           s->match_length = longest_match (s, hash_head);
2021             /* longest_match() sets match_start */
2022              
2023 149 100         if (s->match_length <= 5 && (s->strategy == Z_FILTERED
    50          
2024             #if TOO_FAR <= 32767
2025 72 100         || (s->match_length == MIN_MATCH &&
    50          
2026 56           s->strstart - s->match_start > TOO_FAR)
2027             #endif
2028             )) {
2029              
2030             /* If prev_match is also MIN_MATCH, match_start is garbage
2031             * but we will ignore the current match anyway.
2032             */
2033 0           s->match_length = MIN_MATCH-1;
2034             }
2035             }
2036             /* If there was a match at the previous step and the current
2037             * match is not better, output the previous match:
2038             */
2039 3197 100         if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
    50          
2040 102           uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
2041             /* Do not insert strings in hash table beyond this. */
2042              
2043             check_match(s, s->strstart-1, s->prev_match, s->prev_length);
2044              
2045 102 50         _tr_tally_dist(s, s->strstart -1 - s->prev_match,
2046             s->prev_length - MIN_MATCH, bflush);
2047              
2048             /* Insert in hash table all strings up to the end of the match.
2049             * strstart-1 and strstart are already inserted. If there is not
2050             * enough lookahead, the last two strings are not inserted in
2051             * the hash table.
2052             */
2053 102           s->lookahead -= s->prev_length-1;
2054 102           s->prev_length -= 2;
2055             do {
2056 854 100         if (++s->strstart <= max_insert) {
2057 842           INSERT_STRING(s, s->strstart, hash_head);
2058             }
2059 854 100         } while (--s->prev_length != 0);
2060 102           s->match_available = 0;
2061 102           s->match_length = MIN_MATCH-1;
2062 102           s->strstart++;
2063              
2064 102 50         if (bflush) FLUSH_BLOCK(s, 0);
    0          
    0          
2065              
2066 2993 100         } else if (s->match_available) {
2067             /* If there was no match at the previous position, output a
2068             * single literal. If there was a match but the current match
2069             * is longer, truncate the previous match to a single literal.
2070             */
2071             Tracevv((stderr,"%c", s->window[s->strstart-1]));
2072 2838           _tr_tally_lit(s, s->window[s->strstart-1], bflush);
2073 2838 50         if (bflush) {
2074 0 0         FLUSH_BLOCK_ONLY(s, 0);
2075             }
2076 2838           s->strstart++;
2077 2838           s->lookahead--;
2078 2838 50         if (s->strm->avail_out == 0) return need_more;
2079             } else {
2080             /* There is no previous match to compare with, wait for
2081             * the next step to decide.
2082             */
2083 155           s->match_available = 1;
2084 155           s->strstart++;
2085 155           s->lookahead--;
2086             }
2087 3095           }
2088             Assert (flush != Z_NO_FLUSH, "no flush?");
2089 57 100         if (s->match_available) {
2090             Tracevv((stderr,"%c", s->window[s->strstart-1]));
2091 53           _tr_tally_lit(s, s->window[s->strstart-1], bflush);
2092 53           s->match_available = 0;
2093             }
2094 57           s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
2095 57 50         if (flush == Z_FINISH) {
2096 57 50         FLUSH_BLOCK(s, 1);
    100          
2097 53           return finish_done;
2098             }
2099 0 0         if (s->sym_next)
2100 0 0         FLUSH_BLOCK(s, 0);
    0          
2101 0           return block_done;
2102             }
2103             #endif /* FASTEST */
2104              
2105             /* ===========================================================================
2106             * For Z_RLE, simply look for runs of bytes, generate matches only of distance
2107             * one. Do not maintain a hash table. (It will be regenerated if this run of
2108             * deflate switches away from Z_RLE.)
2109             */
2110 0           local block_state deflate_rle(s, flush)
2111             deflate_state *s;
2112             int flush;
2113             {
2114             int bflush; /* set if current block must be flushed */
2115             uInt prev; /* byte at distance one to match */
2116             Bytef *scan, *strend; /* scan goes up to strend for length of run */
2117              
2118             for (;;) {
2119             /* Make sure that we always have enough lookahead, except
2120             * at the end of the input file. We need MAX_MATCH bytes
2121             * for the longest run, plus one for the unrolled loop.
2122             */
2123 0 0         if (s->lookahead <= MAX_MATCH) {
2124 0           fill_window(s);
2125 0 0         if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {
    0          
2126 0           return need_more;
2127             }
2128 0 0         if (s->lookahead == 0) break; /* flush the current block */
2129             }
2130              
2131             /* See how many times the previous byte repeats */
2132 0           s->match_length = 0;
2133 0 0         if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
    0          
2134 0           scan = s->window + s->strstart - 1;
2135 0           prev = *scan;
2136 0 0         if (prev == *++scan && prev == *++scan && prev == *++scan) {
    0          
    0          
2137 0           strend = s->window + s->strstart + MAX_MATCH;
2138             do {
2139 0 0         } while (prev == *++scan && prev == *++scan &&
    0          
2140 0 0         prev == *++scan && prev == *++scan &&
    0          
2141 0 0         prev == *++scan && prev == *++scan &&
    0          
2142 0 0         prev == *++scan && prev == *++scan &&
    0          
2143 0 0         scan < strend);
2144 0           s->match_length = MAX_MATCH - (uInt)(strend - scan);
2145 0 0         if (s->match_length > s->lookahead)
2146 0           s->match_length = s->lookahead;
2147             }
2148             Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
2149             }
2150              
2151             /* Emit match if have run of MIN_MATCH or longer, else emit literal */
2152 0 0         if (s->match_length >= MIN_MATCH) {
2153             check_match(s, s->strstart, s->strstart - 1, s->match_length);
2154              
2155 0 0         _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
2156              
2157 0           s->lookahead -= s->match_length;
2158 0           s->strstart += s->match_length;
2159 0           s->match_length = 0;
2160             } else {
2161             /* No match, output a literal byte */
2162             Tracevv((stderr,"%c", s->window[s->strstart]));
2163 0           _tr_tally_lit (s, s->window[s->strstart], bflush);
2164 0           s->lookahead--;
2165 0           s->strstart++;
2166             }
2167 0 0         if (bflush) FLUSH_BLOCK(s, 0);
    0          
    0          
2168 0           }
2169 0           s->insert = 0;
2170 0 0         if (flush == Z_FINISH) {
2171 0 0         FLUSH_BLOCK(s, 1);
    0          
2172 0           return finish_done;
2173             }
2174 0 0         if (s->sym_next)
2175 0 0         FLUSH_BLOCK(s, 0);
    0          
2176 0           return block_done;
2177             }
2178              
2179             /* ===========================================================================
2180             * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
2181             * (It will be regenerated if this run of deflate switches away from Huffman.)
2182             */
2183 0           local block_state deflate_huff(s, flush)
2184             deflate_state *s;
2185             int flush;
2186             {
2187             int bflush; /* set if current block must be flushed */
2188              
2189             for (;;) {
2190             /* Make sure that we have a literal to write. */
2191 0 0         if (s->lookahead == 0) {
2192 0           fill_window(s);
2193 0 0         if (s->lookahead == 0) {
2194 0 0         if (flush == Z_NO_FLUSH)
2195 0           return need_more;
2196 0           break; /* flush the current block */
2197             }
2198             }
2199              
2200             /* Output a literal byte */
2201 0           s->match_length = 0;
2202             Tracevv((stderr,"%c", s->window[s->strstart]));
2203 0           _tr_tally_lit (s, s->window[s->strstart], bflush);
2204 0           s->lookahead--;
2205 0           s->strstart++;
2206 0 0         if (bflush) FLUSH_BLOCK(s, 0);
    0          
    0          
2207 0           }
2208 0           s->insert = 0;
2209 0 0         if (flush == Z_FINISH) {
2210 0 0         FLUSH_BLOCK(s, 1);
    0          
2211 0           return finish_done;
2212             }
2213 0 0         if (s->sym_next)
2214 0 0         FLUSH_BLOCK(s, 0);
    0          
2215 0           return block_done;
2216             }