Coverage Report

Created: 2026-11-12 06:30

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