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