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