Coverage Report

Created: 2024-05-20 07:14

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