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