Coverage Report

Created: 2025-07-18 06:47

/src/c-blosc2/internal-complibs/zlib-ng-2.0.7/deflate.c
Line
Count
Source (jump to first uncovered line)
1
/* deflate.c -- compress data using the deflation algorithm
2
 * Copyright (C) 1995-2016 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 https://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
#include "zbuild.h"
51
#include "deflate.h"
52
#include "deflate_p.h"
53
#include "functable.h"
54
55
const char PREFIX(deflate_copyright)[] = " deflate 1.2.11 Copyright 1995-2022 Jean-loup Gailly and Mark Adler ";
56
/*
57
  If you use the zlib library in a product, an acknowledgment is welcome
58
  in the documentation of your product. If for some reason you cannot
59
  include such an acknowledgment, I would appreciate that you keep this
60
  copyright string in the executable of your product.
61
 */
62
63
/* ===========================================================================
64
 *  Architecture-specific hooks.
65
 */
66
#ifdef S390_DFLTCC_DEFLATE
67
#  include "arch/s390/dfltcc_deflate.h"
68
#else
69
/* Memory management for the deflate state. Useful for allocating arch-specific extension blocks. */
70
0
#  define ZALLOC_STATE(strm, items, size) ZALLOC(strm, items, size)
71
0
#  define ZFREE_STATE(strm, addr) ZFREE(strm, addr)
72
0
#  define ZCOPY_STATE(dst, src, size) memcpy(dst, src, size)
73
/* Memory management for the window. Useful for allocation the aligned window. */
74
0
#  define ZALLOC_WINDOW(strm, items, size) ZALLOC(strm, items, size)
75
0
#  define TRY_FREE_WINDOW(strm, addr) TRY_FREE(strm, addr)
76
/* Invoked at the beginning of deflateSetDictionary(). Useful for checking arch-specific window data. */
77
0
#  define DEFLATE_SET_DICTIONARY_HOOK(strm, dict, dict_len) do {} while (0)
78
/* Invoked at the beginning of deflateGetDictionary(). Useful for adjusting arch-specific window data. */
79
0
#  define DEFLATE_GET_DICTIONARY_HOOK(strm, dict, dict_len) do {} while (0)
80
/* Invoked at the end of deflateResetKeep(). Useful for initializing arch-specific extension blocks. */
81
0
#  define DEFLATE_RESET_KEEP_HOOK(strm) do {} while (0)
82
/* Invoked at the beginning of deflateParams(). Useful for updating arch-specific compression parameters. */
83
0
#  define DEFLATE_PARAMS_HOOK(strm, level, strategy, hook_flush) do {} while (0)
84
/* Returns whether the last deflate(flush) operation did everything it's supposed to do. */
85
0
# define DEFLATE_DONE(strm, flush) 1
86
/* Adjusts the upper bound on compressed data length based on compression parameters and uncompressed data length.
87
 * Useful when arch-specific deflation code behaves differently than regular zlib-ng algorithms. */
88
0
#  define DEFLATE_BOUND_ADJUST_COMPLEN(strm, complen, sourceLen) do {} while (0)
89
/* Returns whether an optimistic upper bound on compressed data length should *not* be used.
90
 * Useful when arch-specific deflation code behaves differently than regular zlib-ng algorithms. */
91
0
#  define DEFLATE_NEED_CONSERVATIVE_BOUND(strm) 0
92
/* Invoked for each deflate() call. Useful for plugging arch-specific deflation code. */
93
0
#  define DEFLATE_HOOK(strm, flush, bstate) 0
94
/* Returns whether zlib-ng should compute a checksum. Set to 0 if arch-specific deflation code already does that. */
95
0
#  define DEFLATE_NEED_CHECKSUM(strm) 1
96
/* Returns whether reproducibility parameter can be set to a given value. */
97
#  define DEFLATE_CAN_SET_REPRODUCIBLE(strm, reproducible) 1
98
#endif
99
100
/* ===========================================================================
101
 *  Function prototypes.
102
 */
103
typedef block_state (*compress_func) (deflate_state *s, int flush);
104
/* Compression function. Returns the block state after the call. */
105
106
static int deflateStateCheck      (PREFIX3(stream) *strm);
107
static block_state deflate_stored (deflate_state *s, int flush);
108
Z_INTERNAL block_state deflate_fast         (deflate_state *s, int flush);
109
Z_INTERNAL block_state deflate_quick        (deflate_state *s, int flush);
110
#ifndef NO_MEDIUM_STRATEGY
111
Z_INTERNAL block_state deflate_medium       (deflate_state *s, int flush);
112
#endif
113
Z_INTERNAL block_state deflate_slow         (deflate_state *s, int flush);
114
static block_state deflate_rle   (deflate_state *s, int flush);
115
static block_state deflate_huff  (deflate_state *s, int flush);
116
static void lm_init              (deflate_state *s);
117
Z_INTERNAL unsigned read_buf  (PREFIX3(stream) *strm, unsigned char *buf, unsigned size);
118
119
extern void crc_reset(deflate_state *const s);
120
#ifdef X86_PCLMULQDQ_CRC
121
extern void crc_finalize(deflate_state *const s);
122
#endif
123
extern void copy_with_crc(PREFIX3(stream) *strm, unsigned char *dst, unsigned long size);
124
125
/* ===========================================================================
126
 * Local data
127
 */
128
129
/* Values for max_lazy_match, good_match and max_chain_length, depending on
130
 * the desired pack level (0..9). The values given below have been tuned to
131
 * exclude worst case performance for pathological files. Better values may be
132
 * found for specific files.
133
 */
134
typedef struct config_s {
135
    uint16_t good_length; /* reduce lazy search above this match length */
136
    uint16_t max_lazy;    /* do not perform lazy search above this match length */
137
    uint16_t nice_length; /* quit search above this match length */
138
    uint16_t max_chain;
139
    compress_func func;
140
} config;
141
142
static const config configuration_table[10] = {
143
/*      good lazy nice chain */
144
/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
145
146
#ifndef NO_QUICK_STRATEGY
147
/* 1 */ {4,    4,  8,    4, deflate_quick},
148
/* 2 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */
149
#else
150
/* 1 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */
151
/* 2 */ {4,    5, 16,    8, deflate_fast},
152
#endif
153
154
/* 3 */ {4,    6, 32,   32, deflate_fast},
155
156
#ifdef NO_MEDIUM_STRATEGY
157
/* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
158
/* 5 */ {8,   16, 32,   32, deflate_slow},
159
/* 6 */ {8,   16, 128, 128, deflate_slow},
160
#else
161
/* 4 */ {4,    4, 16,   16, deflate_medium},  /* lazy matches */
162
/* 5 */ {8,   16, 32,   32, deflate_medium},
163
/* 6 */ {8,   16, 128, 128, deflate_medium},
164
#endif
165
166
/* 7 */ {8,   32, 128,  256, deflate_slow},
167
/* 8 */ {32, 128, 258, 1024, deflate_slow},
168
/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
169
170
/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
171
 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
172
 * meaning.
173
 */
174
175
/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */
176
0
#define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0))
177
178
179
/* ===========================================================================
180
 * Initialize the hash table. prev[] will be initialized on the fly.
181
 */
182
0
#define CLEAR_HASH(s) do {                                                                \
183
0
    memset((unsigned char *)s->head, 0, HASH_SIZE * sizeof(*s->head)); \
184
0
  } while (0)
185
186
/* ===========================================================================
187
 * Slide the hash table when sliding the window down (could be avoided with 32
188
 * bit values at the expense of memory usage). We slide even when level == 0 to
189
 * keep the hash table consistent if we switch back to level > 0 later.
190
 */
191
0
Z_INTERNAL void slide_hash_c(deflate_state *s) {
192
0
    Pos *p;
193
0
    unsigned n;
194
0
    unsigned int wsize = s->w_size;
195
196
0
    n = HASH_SIZE;
197
0
    p = &s->head[n];
198
#ifdef NOT_TWEAK_COMPILER
199
    do {
200
        unsigned m;
201
        m = *--p;
202
        *p = (Pos)(m >= wsize ? m-wsize : 0);
203
    } while (--n);
204
#else
205
    /* As of I make this change, gcc (4.8.*) isn't able to vectorize
206
     * this hot loop using saturated-subtraction on x86-64 architecture.
207
     * To avoid this defect, we can change the loop such that
208
     *    o. the pointer advance forward, and
209
     *    o. demote the variable 'm' to be local to the loop, and
210
     *       choose type "Pos" (instead of 'unsigned int') for the
211
     *       variable to avoid unnecessary zero-extension.
212
     */
213
0
    {
214
0
        unsigned int i;
215
0
        Pos *q = p - n;
216
0
        for (i = 0; i < n; i++) {
217
0
            Pos m = *q;
218
0
            Pos t = (Pos)wsize;
219
0
            *q++ = (Pos)(m >= t ? m-t: 0);
220
0
        }
221
0
    }
222
0
#endif /* NOT_TWEAK_COMPILER */
223
224
0
    n = wsize;
225
0
    p = &s->prev[n];
226
#ifdef NOT_TWEAK_COMPILER
227
    do {
228
        unsigned m;
229
        m = *--p;
230
        *p = (Pos)(m >= wsize ? m-wsize : 0);
231
        /* If n is not on any hash chain, prev[n] is garbage but
232
         * its value will never be used.
233
         */
234
    } while (--n);
235
#else
236
0
    {
237
0
        unsigned int i;
238
0
        Pos *q = p - n;
239
0
        for (i = 0; i < n; i++) {
240
0
            Pos m = *q;
241
0
            Pos t = (Pos)wsize;
242
0
            *q++ = (Pos)(m >= t ? m-t: 0);
243
0
        }
244
0
    }
245
0
#endif /* NOT_TWEAK_COMPILER */
246
0
}
247
248
/* ========================================================================= */
249
0
int32_t Z_EXPORT PREFIX(deflateInit_)(PREFIX3(stream) *strm, int32_t level, const char *version, int32_t stream_size) {
250
0
    return PREFIX(deflateInit2_)(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, version, stream_size);
251
    /* Todo: ignore strm->next_in if we use it as window */
252
0
}
253
254
/* ========================================================================= */
255
int32_t Z_EXPORT PREFIX(deflateInit2_)(PREFIX3(stream) *strm, int32_t level, int32_t method, int32_t windowBits,
256
0
                           int32_t memLevel, int32_t strategy, const char *version, int32_t stream_size) {
257
0
    uint32_t window_padding = 0;
258
0
    deflate_state *s;
259
0
    int wrap = 1;
260
0
    static const char my_version[] = PREFIX2(VERSION);
261
262
#if defined(X86_FEATURES)
263
    x86_check_features();
264
#elif defined(ARM_FEATURES)
265
    arm_check_features();
266
#endif
267
268
0
    if (version == NULL || version[0] != my_version[0] || stream_size != sizeof(PREFIX3(stream))) {
269
0
        return Z_VERSION_ERROR;
270
0
    }
271
0
    if (strm == NULL)
272
0
        return Z_STREAM_ERROR;
273
274
0
    strm->msg = NULL;
275
0
    if (strm->zalloc == NULL) {
276
0
        strm->zalloc = zng_calloc;
277
0
        strm->opaque = NULL;
278
0
    }
279
0
    if (strm->zfree == NULL)
280
0
        strm->zfree = zng_cfree;
281
282
0
    if (level == Z_DEFAULT_COMPRESSION)
283
0
        level = 6;
284
285
0
    if (windowBits < 0) { /* suppress zlib wrapper */
286
0
        wrap = 0;
287
0
        if (windowBits < -15)
288
0
            return Z_STREAM_ERROR;
289
0
        windowBits = -windowBits;
290
0
#ifdef GZIP
291
0
    } else if (windowBits > 15) {
292
0
        wrap = 2;       /* write gzip wrapper instead */
293
0
        windowBits -= 16;
294
0
#endif
295
0
    }
296
0
    if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || windowBits < 8 ||
297
0
        windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED ||
298
0
        (windowBits == 8 && wrap != 1)) {
299
0
        return Z_STREAM_ERROR;
300
0
    }
301
0
    if (windowBits == 8)
302
0
        windowBits = 9;  /* until 256-byte window bug fixed */
303
304
0
    s = (deflate_state *) ZALLOC_STATE(strm, 1, sizeof(deflate_state));
305
0
    if (s == NULL)
306
0
        return Z_MEM_ERROR;
307
0
    strm->state = (struct internal_state *)s;
308
0
    s->strm = strm;
309
0
    s->status = INIT_STATE;     /* to pass state test in deflateReset() */
310
311
0
    s->wrap = wrap;
312
0
    s->gzhead = NULL;
313
0
    s->w_bits = (unsigned int)windowBits;
314
0
    s->w_size = 1 << s->w_bits;
315
0
    s->w_mask = s->w_size - 1;
316
317
#ifdef X86_PCLMULQDQ_CRC
318
    window_padding = 8;
319
#endif
320
321
0
    s->window = (unsigned char *) ZALLOC_WINDOW(strm, s->w_size + window_padding, 2*sizeof(unsigned char));
322
0
    s->prev   = (Pos *)  ZALLOC(strm, s->w_size, sizeof(Pos));
323
0
    memset(s->prev, 0, s->w_size * sizeof(Pos));
324
0
    s->head   = (Pos *)  ZALLOC(strm, HASH_SIZE, sizeof(Pos));
325
326
0
    s->high_water = 0;      /* nothing written to s->window yet */
327
328
0
    s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
329
330
    /* We overlay pending_buf and sym_buf. This works since the average size
331
     * for length/distance pairs over any compressed block is assured to be 31
332
     * bits or less.
333
     *
334
     * Analysis: The longest fixed codes are a length code of 8 bits plus 5
335
     * extra bits, for lengths 131 to 257. The longest fixed distance codes are
336
     * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest
337
     * possible fixed-codes length/distance pair is then 31 bits total.
338
     *
339
     * sym_buf starts one-fourth of the way into pending_buf. So there are
340
     * three bytes in sym_buf for every four bytes in pending_buf. Each symbol
341
     * in sym_buf is three bytes -- two for the distance and one for the
342
     * literal/length. As each symbol is consumed, the pointer to the next
343
     * sym_buf value to read moves forward three bytes. From that symbol, up to
344
     * 31 bits are written to pending_buf. The closest the written pending_buf
345
     * bits gets to the next sym_buf symbol to read is just before the last
346
     * code is written. At that time, 31*(n-2) bits have been written, just
347
     * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at
348
     * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1
349
     * symbols are written.) The closest the writing gets to what is unread is
350
     * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and
351
     * can range from 128 to 32768.
352
     *
353
     * Therefore, at a minimum, there are 142 bits of space between what is
354
     * written and what is read in the overlain buffers, so the symbols cannot
355
     * be overwritten by the compressed data. That space is actually 139 bits,
356
     * due to the three-bit fixed-code block header.
357
     *
358
     * That covers the case where either Z_FIXED is specified, forcing fixed
359
     * codes, or when the use of fixed codes is chosen, because that choice
360
     * results in a smaller compressed block than dynamic codes. That latter
361
     * condition then assures that the above analysis also covers all dynamic
362
     * blocks. A dynamic-code block will only be chosen to be emitted if it has
363
     * fewer bits than a fixed-code block would for the same set of symbols.
364
     * Therefore its average symbol length is assured to be less than 31. So
365
     * the compressed data for a dynamic block also cannot overwrite the
366
     * symbols from which it is being constructed.
367
     */
368
369
0
    s->pending_buf = (unsigned char *) ZALLOC(strm, s->lit_bufsize, 4);
370
0
    s->pending_buf_size = s->lit_bufsize * 4;
371
372
0
    if (s->window == NULL || s->prev == NULL || s->head == NULL || s->pending_buf == NULL) {
373
0
        s->status = FINISH_STATE;
374
0
        strm->msg = ERR_MSG(Z_MEM_ERROR);
375
0
        PREFIX(deflateEnd)(strm);
376
0
        return Z_MEM_ERROR;
377
0
    }
378
0
    s->sym_buf = s->pending_buf + s->lit_bufsize;
379
0
    s->sym_end = (s->lit_bufsize - 1) * 3;
380
    /* We avoid equality with lit_bufsize*3 because of wraparound at 64K
381
     * on 16 bit machines and because stored blocks are restricted to
382
     * 64K-1 bytes.
383
     */
384
385
0
    s->level = level;
386
0
    s->strategy = strategy;
387
0
    s->block_open = 0;
388
0
    s->reproducible = 0;
389
390
0
    return PREFIX(deflateReset)(strm);
391
0
}
392
393
/* =========================================================================
394
 * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
395
 */
396
0
static int deflateStateCheck (PREFIX3(stream) *strm) {
397
0
    deflate_state *s;
398
0
    if (strm == NULL || strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
399
0
        return 1;
400
0
    s = strm->state;
401
0
    if (s == NULL || s->strm != strm || (s->status != INIT_STATE &&
402
0
#ifdef GZIP
403
0
                                           s->status != GZIP_STATE &&
404
0
                                           s->status != EXTRA_STATE &&
405
0
                                           s->status != NAME_STATE &&
406
0
                                           s->status != COMMENT_STATE &&
407
0
                                           s->status != HCRC_STATE &&
408
0
#endif
409
0
                                           s->status != BUSY_STATE &&
410
0
                                           s->status != FINISH_STATE))
411
0
        return 1;
412
0
    return 0;
413
0
}
414
415
/* ========================================================================= */
416
0
int32_t Z_EXPORT PREFIX(deflateSetDictionary)(PREFIX3(stream) *strm, const uint8_t *dictionary, uint32_t dictLength) {
417
0
    deflate_state *s;
418
0
    unsigned int str, n;
419
0
    int wrap;
420
0
    uint32_t avail;
421
0
    const unsigned char *next;
422
423
0
    if (deflateStateCheck(strm) || dictionary == NULL)
424
0
        return Z_STREAM_ERROR;
425
0
    s = strm->state;
426
0
    wrap = s->wrap;
427
0
    if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
428
0
        return Z_STREAM_ERROR;
429
430
    /* when using zlib wrappers, compute Adler-32 for provided dictionary */
431
0
    if (wrap == 1)
432
0
        strm->adler = functable.adler32(strm->adler, dictionary, dictLength);
433
0
    DEFLATE_SET_DICTIONARY_HOOK(strm, dictionary, dictLength);  /* hook for IBM Z DFLTCC */
434
0
    s->wrap = 0;                    /* avoid computing Adler-32 in read_buf */
435
436
    /* if dictionary would fill window, just replace the history */
437
0
    if (dictLength >= s->w_size) {
438
0
        if (wrap == 0) {            /* already empty otherwise */
439
0
            CLEAR_HASH(s);
440
0
            s->strstart = 0;
441
0
            s->block_start = 0;
442
0
            s->insert = 0;
443
0
        }
444
0
        dictionary += dictLength - s->w_size;  /* use the tail */
445
0
        dictLength = s->w_size;
446
0
    }
447
448
    /* insert dictionary into window and hash */
449
0
    avail = strm->avail_in;
450
0
    next = strm->next_in;
451
0
    strm->avail_in = dictLength;
452
0
    strm->next_in = (z_const unsigned char *)dictionary;
453
0
    fill_window(s);
454
0
    while (s->lookahead >= MIN_MATCH) {
455
0
        str = s->strstart;
456
0
        n = s->lookahead - (MIN_MATCH-1);
457
0
        functable.insert_string(s, str, n);
458
0
        s->strstart = str + n;
459
0
        s->lookahead = MIN_MATCH-1;
460
0
        fill_window(s);
461
0
    }
462
0
    s->strstart += s->lookahead;
463
0
    s->block_start = (int)s->strstart;
464
0
    s->insert = s->lookahead;
465
0
    s->lookahead = 0;
466
0
    s->prev_length = MIN_MATCH-1;
467
0
    s->match_available = 0;
468
0
    strm->next_in = (z_const unsigned char *)next;
469
0
    strm->avail_in = avail;
470
0
    s->wrap = wrap;
471
0
    return Z_OK;
472
0
}
473
474
/* ========================================================================= */
475
0
int32_t Z_EXPORT PREFIX(deflateGetDictionary)(PREFIX3(stream) *strm, uint8_t *dictionary, uint32_t *dictLength) {
476
0
    deflate_state *s;
477
0
    unsigned int len;
478
479
0
    if (deflateStateCheck(strm))
480
0
        return Z_STREAM_ERROR;
481
0
    DEFLATE_GET_DICTIONARY_HOOK(strm, dictionary, dictLength);  /* hook for IBM Z DFLTCC */
482
0
    s = strm->state;
483
0
    len = s->strstart + s->lookahead;
484
0
    if (len > s->w_size)
485
0
        len = s->w_size;
486
0
    if (dictionary != NULL && len)
487
0
        memcpy(dictionary, s->window + s->strstart + s->lookahead - len, len);
488
0
    if (dictLength != NULL)
489
0
        *dictLength = len;
490
0
    return Z_OK;
491
0
}
492
493
/* ========================================================================= */
494
0
int32_t Z_EXPORT PREFIX(deflateResetKeep)(PREFIX3(stream) *strm) {
495
0
    deflate_state *s;
496
497
0
    if (deflateStateCheck(strm))
498
0
        return Z_STREAM_ERROR;
499
500
0
    strm->total_in = strm->total_out = 0;
501
0
    strm->msg = NULL; /* use zfree if we ever allocate msg dynamically */
502
0
    strm->data_type = Z_UNKNOWN;
503
504
0
    s = (deflate_state *)strm->state;
505
0
    s->pending = 0;
506
0
    s->pending_out = s->pending_buf;
507
508
0
    if (s->wrap < 0)
509
0
        s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
510
511
0
    s->status =
512
0
#ifdef GZIP
513
0
        s->wrap == 2 ? GZIP_STATE :
514
0
#endif
515
0
        INIT_STATE;
516
517
0
#ifdef GZIP
518
0
    if (s->wrap == 2)
519
0
        crc_reset(s);
520
0
    else
521
0
#endif
522
0
        strm->adler = ADLER32_INITIAL_VALUE;
523
0
    s->last_flush = -2;
524
525
0
    zng_tr_init(s);
526
527
0
    DEFLATE_RESET_KEEP_HOOK(strm);  /* hook for IBM Z DFLTCC */
528
529
0
    return Z_OK;
530
0
}
531
532
/* ========================================================================= */
533
0
int32_t Z_EXPORT PREFIX(deflateReset)(PREFIX3(stream) *strm) {
534
0
    int ret;
535
536
0
    ret = PREFIX(deflateResetKeep)(strm);
537
0
    if (ret == Z_OK)
538
0
        lm_init(strm->state);
539
0
    return ret;
540
0
}
541
542
/* ========================================================================= */
543
0
int32_t Z_EXPORT PREFIX(deflateSetHeader)(PREFIX3(stream) *strm, PREFIX(gz_headerp) head) {
544
0
    if (deflateStateCheck(strm) || strm->state->wrap != 2)
545
0
        return Z_STREAM_ERROR;
546
0
    strm->state->gzhead = head;
547
0
    return Z_OK;
548
0
}
549
550
/* ========================================================================= */
551
0
int32_t Z_EXPORT PREFIX(deflatePending)(PREFIX3(stream) *strm, uint32_t *pending, int32_t *bits) {
552
0
    if (deflateStateCheck(strm))
553
0
        return Z_STREAM_ERROR;
554
0
    if (pending != NULL)
555
0
        *pending = strm->state->pending;
556
0
    if (bits != NULL)
557
0
        *bits = strm->state->bi_valid;
558
0
    return Z_OK;
559
0
}
560
561
/* ========================================================================= */
562
0
int32_t Z_EXPORT PREFIX(deflatePrime)(PREFIX3(stream) *strm, int32_t bits, int32_t value) {
563
0
    deflate_state *s;
564
0
    uint64_t value64 = (uint64_t)value;
565
0
    int32_t put;
566
567
0
    if (deflateStateCheck(strm))
568
0
        return Z_STREAM_ERROR;
569
0
    s = strm->state;
570
0
    if (bits < 0 || bits > BIT_BUF_SIZE || bits > (int32_t)(sizeof(value) << 3) ||
571
0
        s->sym_buf < s->pending_out + ((BIT_BUF_SIZE + 7) >> 3))
572
0
        return Z_BUF_ERROR;
573
0
    do {
574
0
        put = BIT_BUF_SIZE - s->bi_valid;
575
0
        if (put > bits)
576
0
            put = bits;
577
0
        if (s->bi_valid == 0)
578
0
            s->bi_buf = value64;
579
0
        else
580
0
            s->bi_buf |= (value64 & ((UINT64_C(1) << put) - 1)) << s->bi_valid;
581
0
        s->bi_valid += put;
582
0
        zng_tr_flush_bits(s);
583
0
        value64 >>= put;
584
0
        bits -= put;
585
0
    } while (bits);
586
0
    return Z_OK;
587
0
}
588
589
/* ========================================================================= */
590
0
int32_t Z_EXPORT PREFIX(deflateParams)(PREFIX3(stream) *strm, int32_t level, int32_t strategy) {
591
0
    deflate_state *s;
592
0
    compress_func func;
593
0
    int hook_flush = Z_NO_FLUSH;
594
595
0
    if (deflateStateCheck(strm))
596
0
        return Z_STREAM_ERROR;
597
0
    s = strm->state;
598
599
0
    if (level == Z_DEFAULT_COMPRESSION)
600
0
        level = 6;
601
0
    if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED)
602
0
        return Z_STREAM_ERROR;
603
0
    DEFLATE_PARAMS_HOOK(strm, level, strategy, &hook_flush);  /* hook for IBM Z DFLTCC */
604
0
    func = configuration_table[s->level].func;
605
606
0
    if (((strategy != s->strategy || func != configuration_table[level].func) && s->last_flush != -2)
607
0
        || hook_flush != Z_NO_FLUSH) {
608
        /* Flush the last buffer. Use Z_BLOCK mode, unless the hook requests a "stronger" one. */
609
0
        int flush = RANK(hook_flush) > RANK(Z_BLOCK) ? hook_flush : Z_BLOCK;
610
0
        int err = PREFIX(deflate)(strm, flush);
611
0
        if (err == Z_STREAM_ERROR)
612
0
            return err;
613
0
        if (strm->avail_in || ((int)s->strstart - s->block_start) + s->lookahead || !DEFLATE_DONE(strm, flush))
614
0
            return Z_BUF_ERROR;
615
0
    }
616
0
    if (s->level != level) {
617
0
        if (s->level == 0 && s->matches != 0) {
618
0
            if (s->matches == 1) {
619
0
                functable.slide_hash(s);
620
0
            } else {
621
0
                CLEAR_HASH(s);
622
0
            }
623
0
            s->matches = 0;
624
0
        }
625
0
        s->level = level;
626
0
        s->max_lazy_match   = configuration_table[level].max_lazy;
627
0
        s->good_match       = configuration_table[level].good_length;
628
0
        s->nice_match       = configuration_table[level].nice_length;
629
0
        s->max_chain_length = configuration_table[level].max_chain;
630
0
    }
631
0
    s->strategy = strategy;
632
0
    return Z_OK;
633
0
}
634
635
/* ========================================================================= */
636
0
int32_t Z_EXPORT PREFIX(deflateTune)(PREFIX3(stream) *strm, int32_t good_length, int32_t max_lazy, int32_t nice_length, int32_t max_chain) {
637
0
    deflate_state *s;
638
639
0
    if (deflateStateCheck(strm))
640
0
        return Z_STREAM_ERROR;
641
0
    s = strm->state;
642
0
    s->good_match = (unsigned int)good_length;
643
0
    s->max_lazy_match = (unsigned int)max_lazy;
644
0
    s->nice_match = nice_length;
645
0
    s->max_chain_length = (unsigned int)max_chain;
646
0
    return Z_OK;
647
0
}
648
649
/* =========================================================================
650
 * For the default windowBits of 15 and memLevel of 8, this function returns
651
 * a close to exact, as well as small, upper bound on the compressed size.
652
 * They are coded as constants here for a reason--if the #define's are
653
 * changed, then this function needs to be changed as well.  The return
654
 * value for 15 and 8 only works for those exact settings.
655
 *
656
 * For any setting other than those defaults for windowBits and memLevel,
657
 * the value returned is a conservative worst case for the maximum expansion
658
 * resulting from using fixed blocks instead of stored blocks, which deflate
659
 * can emit on compressed data for some combinations of the parameters.
660
 *
661
 * This function could be more sophisticated to provide closer upper bounds for
662
 * every combination of windowBits and memLevel.  But even the conservative
663
 * upper bound of about 14% expansion does not seem onerous for output buffer
664
 * allocation.
665
 */
666
0
unsigned long Z_EXPORT PREFIX(deflateBound)(PREFIX3(stream) *strm, unsigned long sourceLen) {
667
0
    deflate_state *s;
668
0
    unsigned long complen, wraplen;
669
670
    /* conservative upper bound for compressed data */
671
0
    complen = sourceLen + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
672
0
    DEFLATE_BOUND_ADJUST_COMPLEN(strm, complen, sourceLen);  /* hook for IBM Z DFLTCC */
673
674
    /* if can't get parameters, return conservative bound plus zlib wrapper */
675
0
    if (deflateStateCheck(strm))
676
0
        return complen + 6;
677
678
    /* compute wrapper length */
679
0
    s = strm->state;
680
0
    switch (s->wrap) {
681
0
    case 0:                                 /* raw deflate */
682
0
        wraplen = 0;
683
0
        break;
684
0
    case 1:                                 /* zlib wrapper */
685
0
        wraplen = ZLIB_WRAPLEN + (s->strstart ? 4 : 0);
686
0
        break;
687
0
#ifdef GZIP
688
0
    case 2:                                 /* gzip wrapper */
689
0
        wraplen = GZIP_WRAPLEN;
690
0
        if (s->gzhead != NULL) {            /* user-supplied gzip header */
691
0
            unsigned char *str;
692
0
            if (s->gzhead->extra != NULL) {
693
0
                wraplen += 2 + s->gzhead->extra_len;
694
0
            }
695
0
            str = s->gzhead->name;
696
0
            if (str != NULL) {
697
0
                do {
698
0
                    wraplen++;
699
0
                } while (*str++);
700
0
            }
701
0
            str = s->gzhead->comment;
702
0
            if (str != NULL) {
703
0
                do {
704
0
                    wraplen++;
705
0
                } while (*str++);
706
0
            }
707
0
            if (s->gzhead->hcrc)
708
0
                wraplen += 2;
709
0
        }
710
0
        break;
711
0
#endif
712
0
    default:                                /* for compiler happiness */
713
0
        wraplen = ZLIB_WRAPLEN;
714
0
    }
715
716
    /* if not default parameters, return conservative bound */
717
0
    if (DEFLATE_NEED_CONSERVATIVE_BOUND(strm) ||  /* hook for IBM Z DFLTCC */
718
0
            s->w_bits != 15 || HASH_BITS < 15) {
719
0
        if (s->level == 0) {
720
            /* upper bound for stored blocks with length 127 (memLevel == 1) --
721
               ~4% overhead plus a small constant */
722
0
            complen = sourceLen + (sourceLen >> 5) + (sourceLen >> 7) + (sourceLen >> 11) + 7;
723
0
        }
724
725
0
        return complen + wraplen;
726
0
    }
727
728
0
#ifndef NO_QUICK_STRATEGY
729
0
    return sourceLen                       /* The source size itself */
730
0
      + (sourceLen == 0 ? 1 : 0)           /* Always at least one byte for any input */
731
0
      + (sourceLen < 9 ? 1 : 0)            /* One extra byte for lengths less than 9 */
732
0
      + DEFLATE_QUICK_OVERHEAD(sourceLen)  /* Source encoding overhead, padded to next full byte */
733
0
      + DEFLATE_BLOCK_OVERHEAD             /* Deflate block overhead bytes */
734
0
      + wraplen;                           /* none, zlib or gzip wrapper */
735
#else
736
    return sourceLen + (sourceLen >> 4) + 7 + wraplen;
737
#endif
738
0
}
739
740
/* =========================================================================
741
 * Flush as much pending output as possible. All deflate() output, except for
742
 * some deflate_stored() output, goes through this function so some
743
 * applications may wish to modify it to avoid allocating a large
744
 * strm->next_out buffer and copying into it. (See also read_buf()).
745
 */
746
0
Z_INTERNAL void flush_pending(PREFIX3(stream) *strm) {
747
0
    uint32_t len;
748
0
    deflate_state *s = strm->state;
749
750
0
    zng_tr_flush_bits(s);
751
0
    len = s->pending;
752
0
    if (len > strm->avail_out)
753
0
        len = strm->avail_out;
754
0
    if (len == 0)
755
0
        return;
756
757
0
    Tracev((stderr, "[FLUSH]"));
758
0
    memcpy(strm->next_out, s->pending_out, len);
759
0
    strm->next_out  += len;
760
0
    s->pending_out  += len;
761
0
    strm->total_out += len;
762
0
    strm->avail_out -= len;
763
0
    s->pending      -= len;
764
0
    if (s->pending == 0)
765
0
        s->pending_out = s->pending_buf;
766
0
}
767
768
/* ===========================================================================
769
 * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1].
770
 */
771
#define HCRC_UPDATE(beg) \
772
0
    do { \
773
0
        if (s->gzhead->hcrc && s->pending > (beg)) \
774
0
            strm->adler = PREFIX(crc32)(strm->adler, s->pending_buf + (beg), s->pending - (beg)); \
775
0
    } while (0)
776
777
/* ========================================================================= */
778
0
int32_t Z_EXPORT PREFIX(deflate)(PREFIX3(stream) *strm, int32_t flush) {
779
0
    int32_t old_flush; /* value of flush param for previous deflate call */
780
0
    deflate_state *s;
781
782
0
    if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0)
783
0
        return Z_STREAM_ERROR;
784
0
    s = strm->state;
785
786
0
    if (strm->next_out == NULL || (strm->avail_in != 0 && strm->next_in == NULL)
787
0
        || (s->status == FINISH_STATE && flush != Z_FINISH)) {
788
0
        ERR_RETURN(strm, Z_STREAM_ERROR);
789
0
    }
790
0
    if (strm->avail_out == 0) {
791
0
        ERR_RETURN(strm, Z_BUF_ERROR);
792
0
    }
793
794
0
    old_flush = s->last_flush;
795
0
    s->last_flush = flush;
796
797
    /* Flush as much pending output as possible */
798
0
    if (s->pending != 0) {
799
0
        flush_pending(strm);
800
0
        if (strm->avail_out == 0) {
801
            /* Since avail_out is 0, deflate will be called again with
802
             * more output space, but possibly with both pending and
803
             * avail_in equal to zero. There won't be anything to do,
804
             * but this is not an error situation so make sure we
805
             * return OK instead of BUF_ERROR at next call of deflate:
806
             */
807
0
            s->last_flush = -1;
808
0
            return Z_OK;
809
0
        }
810
811
        /* Make sure there is something to do and avoid duplicate consecutive
812
         * flushes. For repeated and useless calls with Z_FINISH, we keep
813
         * returning Z_STREAM_END instead of Z_BUF_ERROR.
814
         */
815
0
    } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) && flush != Z_FINISH) {
816
0
        ERR_RETURN(strm, Z_BUF_ERROR);
817
0
    }
818
819
    /* User must not provide more input after the first FINISH: */
820
0
    if (s->status == FINISH_STATE && strm->avail_in != 0)   {
821
0
        ERR_RETURN(strm, Z_BUF_ERROR);
822
0
    }
823
824
    /* Write the header */
825
0
    if (s->status == INIT_STATE && s->wrap == 0)
826
0
        s->status = BUSY_STATE;
827
0
    if (s->status == INIT_STATE) {
828
        /* zlib header */
829
0
        unsigned int header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
830
0
        unsigned int level_flags;
831
832
0
        if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
833
0
            level_flags = 0;
834
0
        else if (s->level < 6)
835
0
            level_flags = 1;
836
0
        else if (s->level == 6)
837
0
            level_flags = 2;
838
0
        else
839
0
            level_flags = 3;
840
0
        header |= (level_flags << 6);
841
0
        if (s->strstart != 0)
842
0
            header |= PRESET_DICT;
843
0
        header += 31 - (header % 31);
844
845
0
        put_short_msb(s, (uint16_t)header);
846
847
        /* Save the adler32 of the preset dictionary: */
848
0
        if (s->strstart != 0)
849
0
            put_uint32_msb(s, strm->adler);
850
0
        strm->adler = ADLER32_INITIAL_VALUE;
851
0
        s->status = BUSY_STATE;
852
853
        /* Compression must start with an empty pending buffer */
854
0
        flush_pending(strm);
855
0
        if (s->pending != 0) {
856
0
            s->last_flush = -1;
857
0
            return Z_OK;
858
0
        }
859
0
    }
860
0
#ifdef GZIP
861
0
    if (s->status == GZIP_STATE) {
862
        /* gzip header */
863
0
        crc_reset(s);
864
0
        put_byte(s, 31);
865
0
        put_byte(s, 139);
866
0
        put_byte(s, 8);
867
0
        if (s->gzhead == NULL) {
868
0
            put_uint32(s, 0);
869
0
            put_byte(s, 0);
870
0
            put_byte(s, s->level == 9 ? 2 :
871
0
                     (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 4 : 0));
872
0
            put_byte(s, OS_CODE);
873
0
            s->status = BUSY_STATE;
874
875
            /* Compression must start with an empty pending buffer */
876
0
            flush_pending(strm);
877
0
            if (s->pending != 0) {
878
0
                s->last_flush = -1;
879
0
                return Z_OK;
880
0
            }
881
0
        } else {
882
0
            put_byte(s, (s->gzhead->text ? 1 : 0) +
883
0
                     (s->gzhead->hcrc ? 2 : 0) +
884
0
                     (s->gzhead->extra == NULL ? 0 : 4) +
885
0
                     (s->gzhead->name == NULL ? 0 : 8) +
886
0
                     (s->gzhead->comment == NULL ? 0 : 16)
887
0
                     );
888
0
            put_uint32(s, s->gzhead->time);
889
0
            put_byte(s, s->level == 9 ? 2 : (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 4 : 0));
890
0
            put_byte(s, s->gzhead->os & 0xff);
891
0
            if (s->gzhead->extra != NULL)
892
0
                put_short(s, (uint16_t)s->gzhead->extra_len);
893
0
            if (s->gzhead->hcrc)
894
0
                strm->adler = PREFIX(crc32)(strm->adler, s->pending_buf, s->pending);
895
0
            s->gzindex = 0;
896
0
            s->status = EXTRA_STATE;
897
0
        }
898
0
    }
899
0
    if (s->status == EXTRA_STATE) {
900
0
        if (s->gzhead->extra != NULL) {
901
0
            uint32_t beg = s->pending;   /* start of bytes to update crc */
902
0
            uint32_t left = (s->gzhead->extra_len & 0xffff) - s->gzindex;
903
904
0
            while (s->pending + left > s->pending_buf_size) {
905
0
                uint32_t copy = s->pending_buf_size - s->pending;
906
0
                memcpy(s->pending_buf + s->pending, s->gzhead->extra + s->gzindex, copy);
907
0
                s->pending = s->pending_buf_size;
908
0
                HCRC_UPDATE(beg);
909
0
                s->gzindex += copy;
910
0
                flush_pending(strm);
911
0
                if (s->pending != 0) {
912
0
                    s->last_flush = -1;
913
0
                    return Z_OK;
914
0
                }
915
0
                beg = 0;
916
0
                left -= copy;
917
0
            }
918
0
            memcpy(s->pending_buf + s->pending, s->gzhead->extra + s->gzindex, left);
919
0
            s->pending += left;
920
0
            HCRC_UPDATE(beg);
921
0
            s->gzindex = 0;
922
0
        }
923
0
        s->status = NAME_STATE;
924
0
    }
925
0
    if (s->status == NAME_STATE) {
926
0
        if (s->gzhead->name != NULL) {
927
0
            uint32_t beg = s->pending;   /* start of bytes to update crc */
928
0
            unsigned char val;
929
930
0
            do {
931
0
                if (s->pending == s->pending_buf_size) {
932
0
                    HCRC_UPDATE(beg);
933
0
                    flush_pending(strm);
934
0
                    if (s->pending != 0) {
935
0
                        s->last_flush = -1;
936
0
                        return Z_OK;
937
0
                    }
938
0
                    beg = 0;
939
0
                }
940
0
                val = s->gzhead->name[s->gzindex++];
941
0
                put_byte(s, val);
942
0
            } while (val != 0);
943
0
            HCRC_UPDATE(beg);
944
0
            s->gzindex = 0;
945
0
        }
946
0
        s->status = COMMENT_STATE;
947
0
    }
948
0
    if (s->status == COMMENT_STATE) {
949
0
        if (s->gzhead->comment != NULL) {
950
0
            uint32_t beg = s->pending;  /* start of bytes to update crc */
951
0
            unsigned char val;
952
953
0
            do {
954
0
                if (s->pending == s->pending_buf_size) {
955
0
                    HCRC_UPDATE(beg);
956
0
                    flush_pending(strm);
957
0
                    if (s->pending != 0) {
958
0
                        s->last_flush = -1;
959
0
                        return Z_OK;
960
0
                    }
961
0
                    beg = 0;
962
0
                }
963
0
                val = s->gzhead->comment[s->gzindex++];
964
0
                put_byte(s, val);
965
0
            } while (val != 0);
966
0
            HCRC_UPDATE(beg);
967
0
        }
968
0
        s->status = HCRC_STATE;
969
0
    }
970
0
    if (s->status == HCRC_STATE) {
971
0
        if (s->gzhead->hcrc) {
972
0
            if (s->pending + 2 > s->pending_buf_size) {
973
0
                flush_pending(strm);
974
0
                if (s->pending != 0) {
975
0
                    s->last_flush = -1;
976
0
                    return Z_OK;
977
0
                }
978
0
            }
979
0
            put_short(s, (uint16_t)strm->adler);
980
0
            crc_reset(s);
981
0
        }
982
0
        s->status = BUSY_STATE;
983
984
        /* Compression must start with an empty pending buffer */
985
0
        flush_pending(strm);
986
0
        if (s->pending != 0) {
987
0
            s->last_flush = -1;
988
0
            return Z_OK;
989
0
        }
990
0
    }
991
0
#endif
992
993
    /* Start a new block or continue the current one.
994
     */
995
0
    if (strm->avail_in != 0 || s->lookahead != 0 || (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
996
0
        block_state bstate;
997
998
0
        bstate = DEFLATE_HOOK(strm, flush, &bstate) ? bstate :  /* hook for IBM Z DFLTCC */
999
0
                 s->level == 0 ? deflate_stored(s, flush) :
1000
0
                 s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
1001
0
                 s->strategy == Z_RLE ? deflate_rle(s, flush) :
1002
0
                 (*(configuration_table[s->level].func))(s, flush);
1003
1004
0
        if (bstate == finish_started || bstate == finish_done) {
1005
0
            s->status = FINISH_STATE;
1006
0
        }
1007
0
        if (bstate == need_more || bstate == finish_started) {
1008
0
            if (strm->avail_out == 0) {
1009
0
                s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
1010
0
            }
1011
0
            return Z_OK;
1012
            /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
1013
             * of deflate should use the same flush parameter to make sure
1014
             * that the flush is complete. So we don't have to output an
1015
             * empty block here, this will be done at next call. This also
1016
             * ensures that for a very small output buffer, we emit at most
1017
             * one empty block.
1018
             */
1019
0
        }
1020
0
        if (bstate == block_done) {
1021
0
            if (flush == Z_PARTIAL_FLUSH) {
1022
0
                zng_tr_align(s);
1023
0
            } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
1024
0
                zng_tr_stored_block(s, (char*)0, 0L, 0);
1025
                /* For a full flush, this empty block will be recognized
1026
                 * as a special marker by inflate_sync().
1027
                 */
1028
0
                if (flush == Z_FULL_FLUSH) {
1029
0
                    CLEAR_HASH(s);             /* forget history */
1030
0
                    if (s->lookahead == 0) {
1031
0
                        s->strstart = 0;
1032
0
                        s->block_start = 0;
1033
0
                        s->insert = 0;
1034
0
                    }
1035
0
                }
1036
0
            }
1037
0
            flush_pending(strm);
1038
0
            if (strm->avail_out == 0) {
1039
0
                s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
1040
0
                return Z_OK;
1041
0
            }
1042
0
        }
1043
0
    }
1044
1045
0
    if (flush != Z_FINISH)
1046
0
        return Z_OK;
1047
1048
    /* Write the trailer */
1049
0
#ifdef GZIP
1050
0
    if (s->wrap == 2) {
1051
#  ifdef X86_PCLMULQDQ_CRC
1052
        crc_finalize(s);
1053
#  endif
1054
0
        put_uint32(s, strm->adler);
1055
0
        put_uint32(s, (uint32_t)strm->total_in);
1056
0
    } else
1057
0
#endif
1058
0
    if (s->wrap == 1)
1059
0
        put_uint32_msb(s, strm->adler);
1060
0
    flush_pending(strm);
1061
    /* If avail_out is zero, the application will call deflate again
1062
     * to flush the rest.
1063
     */
1064
0
    if (s->wrap > 0)
1065
0
        s->wrap = -s->wrap; /* write the trailer only once! */
1066
0
    if (s->pending == 0) {
1067
0
        Assert(s->bi_valid == 0, "bi_buf not flushed");
1068
0
        return Z_STREAM_END;
1069
0
    }
1070
0
    return Z_OK;
1071
0
}
1072
1073
/* ========================================================================= */
1074
0
int32_t Z_EXPORT PREFIX(deflateEnd)(PREFIX3(stream) *strm) {
1075
0
    int32_t status;
1076
1077
0
    if (deflateStateCheck(strm))
1078
0
        return Z_STREAM_ERROR;
1079
1080
0
    status = strm->state->status;
1081
1082
    /* Deallocate in reverse order of allocations: */
1083
0
    TRY_FREE(strm, strm->state->pending_buf);
1084
0
    TRY_FREE(strm, strm->state->head);
1085
0
    TRY_FREE(strm, strm->state->prev);
1086
0
    TRY_FREE_WINDOW(strm, strm->state->window);
1087
1088
0
    ZFREE_STATE(strm, strm->state);
1089
0
    strm->state = NULL;
1090
1091
0
    return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
1092
0
}
1093
1094
/* =========================================================================
1095
 * Copy the source state to the destination state.
1096
 */
1097
0
int32_t Z_EXPORT PREFIX(deflateCopy)(PREFIX3(stream) *dest, PREFIX3(stream) *source) {
1098
0
    deflate_state *ds;
1099
0
    deflate_state *ss;
1100
0
    uint32_t window_padding = 0;
1101
1102
0
    if (deflateStateCheck(source) || dest == NULL)
1103
0
        return Z_STREAM_ERROR;
1104
1105
0
    ss = source->state;
1106
1107
0
    memcpy((void *)dest, (void *)source, sizeof(PREFIX3(stream)));
1108
1109
0
    ds = (deflate_state *) ZALLOC_STATE(dest, 1, sizeof(deflate_state));
1110
0
    if (ds == NULL)
1111
0
        return Z_MEM_ERROR;
1112
0
    dest->state = (struct internal_state *) ds;
1113
0
    ZCOPY_STATE((void *)ds, (void *)ss, sizeof(deflate_state));
1114
0
    ds->strm = dest;
1115
1116
#ifdef X86_PCLMULQDQ_CRC
1117
    window_padding = 8;
1118
#endif
1119
1120
0
    ds->window = (unsigned char *) ZALLOC_WINDOW(dest, ds->w_size + window_padding, 2*sizeof(unsigned char));
1121
0
    ds->prev   = (Pos *)  ZALLOC(dest, ds->w_size, sizeof(Pos));
1122
0
    ds->head   = (Pos *)  ZALLOC(dest, HASH_SIZE, sizeof(Pos));
1123
0
    ds->pending_buf = (unsigned char *) ZALLOC(dest, ds->lit_bufsize, 4);
1124
1125
0
    if (ds->window == NULL || ds->prev == NULL || ds->head == NULL || ds->pending_buf == NULL) {
1126
0
        PREFIX(deflateEnd)(dest);
1127
0
        return Z_MEM_ERROR;
1128
0
    }
1129
1130
0
    memcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(unsigned char));
1131
0
    memcpy((void *)ds->prev, (void *)ss->prev, ds->w_size * sizeof(Pos));
1132
0
    memcpy((void *)ds->head, (void *)ss->head, HASH_SIZE * sizeof(Pos));
1133
0
    memcpy(ds->pending_buf, ss->pending_buf, ds->pending_buf_size);
1134
1135
0
    ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
1136
0
    ds->sym_buf = ds->pending_buf + ds->lit_bufsize;
1137
1138
0
    ds->l_desc.dyn_tree = ds->dyn_ltree;
1139
0
    ds->d_desc.dyn_tree = ds->dyn_dtree;
1140
0
    ds->bl_desc.dyn_tree = ds->bl_tree;
1141
1142
0
    return Z_OK;
1143
0
}
1144
1145
/* ===========================================================================
1146
 * Read a new buffer from the current input stream, update the adler32
1147
 * and total number of bytes read.  All deflate() input goes through
1148
 * this function so some applications may wish to modify it to avoid
1149
 * allocating a large strm->next_in buffer and copying from it.
1150
 * (See also flush_pending()).
1151
 */
1152
0
Z_INTERNAL unsigned read_buf(PREFIX3(stream) *strm, unsigned char *buf, unsigned size) {
1153
0
    uint32_t len = strm->avail_in;
1154
1155
0
    if (len > size)
1156
0
        len = size;
1157
0
    if (len == 0)
1158
0
        return 0;
1159
1160
0
    strm->avail_in  -= len;
1161
1162
0
    if (!DEFLATE_NEED_CHECKSUM(strm)) {
1163
0
        memcpy(buf, strm->next_in, len);
1164
0
#ifdef GZIP
1165
0
    } else if (strm->state->wrap == 2) {
1166
0
        copy_with_crc(strm, buf, len);
1167
0
#endif
1168
0
    } else {
1169
0
        memcpy(buf, strm->next_in, len);
1170
0
        if (strm->state->wrap == 1)
1171
0
            strm->adler = functable.adler32(strm->adler, buf, len);
1172
0
    }
1173
0
    strm->next_in  += len;
1174
0
    strm->total_in += len;
1175
1176
0
    return len;
1177
0
}
1178
1179
/* ===========================================================================
1180
 * Initialize the "longest match" routines for a new zlib stream
1181
 */
1182
0
static void lm_init(deflate_state *s) {
1183
0
    s->window_size = 2 * s->w_size;
1184
1185
0
    CLEAR_HASH(s);
1186
1187
    /* Set the default configuration parameters:
1188
     */
1189
0
    s->max_lazy_match   = configuration_table[s->level].max_lazy;
1190
0
    s->good_match       = configuration_table[s->level].good_length;
1191
0
    s->nice_match       = configuration_table[s->level].nice_length;
1192
0
    s->max_chain_length = configuration_table[s->level].max_chain;
1193
1194
0
    s->strstart = 0;
1195
0
    s->block_start = 0;
1196
0
    s->lookahead = 0;
1197
0
    s->insert = 0;
1198
0
    s->prev_length = MIN_MATCH-1;
1199
0
    s->match_available = 0;
1200
0
    s->match_start = 0;
1201
0
}
1202
1203
#ifdef ZLIB_DEBUG
1204
#define EQUAL 0
1205
/* result of memcmp for equal strings */
1206
1207
/* ===========================================================================
1208
 * Check that the match at match_start is indeed a match.
1209
 */
1210
void check_match(deflate_state *s, Pos start, Pos match, int length) {
1211
    /* check that the match length is valid*/
1212
    if (length < MIN_MATCH || length > MAX_MATCH) {
1213
        fprintf(stderr, " start %u, match %u, length %d\n", start, match, length);
1214
        z_error("invalid match length");
1215
    }
1216
    /* check that the match isn't at the same position as the start string */
1217
    if (match == start) {
1218
        fprintf(stderr, " start %u, match %u, length %d\n", start, match, length);
1219
        z_error("invalid match position");
1220
    }
1221
    /* check that the match is indeed a match */
1222
    if (memcmp(s->window + match, s->window + start, length) != EQUAL) {
1223
        int32_t i = 0;
1224
        fprintf(stderr, " start %u, match %u, length %d\n", start, match, length);
1225
        do {
1226
            fprintf(stderr, "  %03d: match [%02x] start [%02x]\n", i++, s->window[match++], s->window[start++]);
1227
        } while (--length != 0);
1228
        z_error("invalid match");
1229
    }
1230
    if (z_verbose > 1) {
1231
        fprintf(stderr, "\\[%u,%d]", start-match, length);
1232
        do {
1233
            putc(s->window[start++], stderr);
1234
        } while (--length != 0);
1235
    }
1236
}
1237
#else
1238
#  define check_match(s, start, match, length)
1239
#endif /* ZLIB_DEBUG */
1240
1241
/* ===========================================================================
1242
 * Fill the window when the lookahead becomes insufficient.
1243
 * Updates strstart and lookahead.
1244
 *
1245
 * IN assertion: lookahead < MIN_LOOKAHEAD
1246
 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1247
 *    At least one byte has been read, or avail_in == 0; reads are
1248
 *    performed for at least two bytes (required for the zip translate_eol
1249
 *    option -- not supported here).
1250
 */
1251
1252
0
void Z_INTERNAL fill_window(deflate_state *s) {
1253
0
    unsigned n;
1254
0
    unsigned int more;    /* Amount of free space at the end of the window. */
1255
0
    unsigned int wsize = s->w_size;
1256
1257
0
    Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
1258
1259
0
    do {
1260
0
        more = s->window_size - s->lookahead - s->strstart;
1261
1262
        /* If the window is almost full and there is insufficient lookahead,
1263
         * move the upper half to the lower one to make room in the upper half.
1264
         */
1265
0
        if (s->strstart >= wsize+MAX_DIST(s)) {
1266
0
            memcpy(s->window, s->window+wsize, (unsigned)wsize);
1267
0
            if (s->match_start >= wsize) {
1268
0
                s->match_start -= wsize;
1269
0
            } else {
1270
0
                s->match_start = 0;
1271
0
                s->prev_length = 0;
1272
0
            }
1273
0
            s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
1274
0
            s->block_start -= (int)wsize;
1275
0
            if (s->insert > s->strstart)
1276
0
                s->insert = s->strstart;
1277
0
            functable.slide_hash(s);
1278
0
            more += wsize;
1279
0
        }
1280
0
        if (s->strm->avail_in == 0)
1281
0
            break;
1282
1283
        /* If there was no sliding:
1284
         *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1285
         *    more == window_size - lookahead - strstart
1286
         * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1287
         * => more >= window_size - 2*WSIZE + 2
1288
         * In the BIG_MEM or MMAP case (not yet supported),
1289
         *   window_size == input_size + MIN_LOOKAHEAD  &&
1290
         *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1291
         * Otherwise, window_size == 2*WSIZE so more >= 2.
1292
         * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1293
         */
1294
0
        Assert(more >= 2, "more < 2");
1295
1296
0
        n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1297
0
        s->lookahead += n;
1298
1299
        /* Initialize the hash value now that we have some input: */
1300
0
        if (s->lookahead + s->insert >= MIN_MATCH) {
1301
0
            unsigned int str = s->strstart - s->insert;
1302
0
            if (str >= 1)
1303
0
                functable.quick_insert_string(s, str + 2 - MIN_MATCH);
1304
#if MIN_MATCH != 3
1305
#error Call insert_string() MIN_MATCH-3 more times
1306
            while (s->insert) {
1307
                functable.quick_insert_string(s, str);
1308
                str++;
1309
                s->insert--;
1310
                if (s->lookahead + s->insert < MIN_MATCH)
1311
                    break;
1312
            }
1313
#else
1314
0
            unsigned int count;
1315
0
            if (UNLIKELY(s->lookahead == 1)) {
1316
0
                count = s->insert - 1;
1317
0
            } else {
1318
0
                count = s->insert;
1319
0
            }
1320
0
            if (count > 0) {
1321
0
                functable.insert_string(s, str, count);
1322
0
                s->insert -= count;
1323
0
            }
1324
0
#endif
1325
0
        }
1326
        /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1327
         * but this is not important since only literal bytes will be emitted.
1328
         */
1329
0
    } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1330
1331
    /* If the WIN_INIT bytes after the end of the current data have never been
1332
     * written, then zero those bytes in order to avoid memory check reports of
1333
     * the use of uninitialized (or uninitialised as Julian writes) bytes by
1334
     * the longest match routines.  Update the high water mark for the next
1335
     * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
1336
     * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
1337
     */
1338
0
    if (s->high_water < s->window_size) {
1339
0
        unsigned int curr = s->strstart + s->lookahead;
1340
0
        unsigned int init;
1341
1342
0
        if (s->high_water < curr) {
1343
            /* Previous high water mark below current data -- zero WIN_INIT
1344
             * bytes or up to end of window, whichever is less.
1345
             */
1346
0
            init = s->window_size - curr;
1347
0
            if (init > WIN_INIT)
1348
0
                init = WIN_INIT;
1349
0
            memset(s->window + curr, 0, init);
1350
0
            s->high_water = curr + init;
1351
0
        } else if (s->high_water < curr + WIN_INIT) {
1352
            /* High water mark at or above current data, but below current data
1353
             * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
1354
             * to end of window, whichever is less.
1355
             */
1356
0
            init = curr + WIN_INIT - s->high_water;
1357
0
            if (init > s->window_size - s->high_water)
1358
0
                init = s->window_size - s->high_water;
1359
0
            memset(s->window + s->high_water, 0, init);
1360
0
            s->high_water += init;
1361
0
        }
1362
0
    }
1363
1364
0
    Assert((unsigned long)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1365
0
           "not enough room for search");
1366
0
}
1367
1368
/* ===========================================================================
1369
 * Copy without compression as much as possible from the input stream, return
1370
 * the current block state.
1371
 *
1372
 * In case deflateParams() is used to later switch to a non-zero compression
1373
 * level, s->matches (otherwise unused when storing) keeps track of the number
1374
 * of hash table slides to perform. If s->matches is 1, then one hash table
1375
 * slide will be done when switching. If s->matches is 2, the maximum value
1376
 * allowed here, then the hash table will be cleared, since two or more slides
1377
 * is the same as a clear.
1378
 *
1379
 * deflate_stored() is written to minimize the number of times an input byte is
1380
 * copied. It is most efficient with large input and output buffers, which
1381
 * maximizes the opportunites to have a single copy from next_in to next_out.
1382
 */
1383
0
static block_state deflate_stored(deflate_state *s, int flush) {
1384
    /* Smallest worthy block size when not flushing or finishing. By default
1385
     * this is 32K. This can be as small as 507 bytes for memLevel == 1. For
1386
     * large input and output buffers, the stored block size will be larger.
1387
     */
1388
0
    unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size);
1389
1390
    /* Copy as many min_block or larger stored blocks directly to next_out as
1391
     * possible. If flushing, copy the remaining available input to next_out as
1392
     * stored blocks, if there is enough space.
1393
     */
1394
0
    unsigned len, left, have, last = 0;
1395
0
    unsigned used = s->strm->avail_in;
1396
0
    do {
1397
        /* Set len to the maximum size block that we can copy directly with the
1398
         * available input data and output space. Set left to how much of that
1399
         * would be copied from what's left in the window.
1400
         */
1401
0
        len = MAX_STORED;       /* maximum deflate stored block length */
1402
0
        have = (s->bi_valid + 42) >> 3;         /* number of header bytes */
1403
0
        if (s->strm->avail_out < have)          /* need room for header */
1404
0
            break;
1405
            /* maximum stored block length that will fit in avail_out: */
1406
0
        have = s->strm->avail_out - have;
1407
0
        left = (int)s->strstart - s->block_start;    /* bytes left in window */
1408
0
        if (len > (unsigned long)left + s->strm->avail_in)
1409
0
            len = left + s->strm->avail_in;     /* limit len to the input */
1410
0
        if (len > have)
1411
0
            len = have;                         /* limit len to the output */
1412
1413
        /* If the stored block would be less than min_block in length, or if
1414
         * unable to copy all of the available input when flushing, then try
1415
         * copying to the window and the pending buffer instead. Also don't
1416
         * write an empty block when flushing -- deflate() does that.
1417
         */
1418
0
        if (len < min_block && ((len == 0 && flush != Z_FINISH) || flush == Z_NO_FLUSH || len != left + s->strm->avail_in))
1419
0
            break;
1420
1421
        /* Make a dummy stored block in pending to get the header bytes,
1422
         * including any pending bits. This also updates the debugging counts.
1423
         */
1424
0
        last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0;
1425
0
        zng_tr_stored_block(s, (char *)0, 0L, last);
1426
1427
        /* Replace the lengths in the dummy stored block with len. */
1428
0
        s->pending -= 4;
1429
0
        put_short(s, (uint16_t)len);
1430
0
        put_short(s, (uint16_t)~len);
1431
1432
        /* Write the stored block header bytes. */
1433
0
        flush_pending(s->strm);
1434
1435
        /* Update debugging counts for the data about to be copied. */
1436
0
        cmpr_bits_add(s, len << 3);
1437
0
        sent_bits_add(s, len << 3);
1438
1439
        /* Copy uncompressed bytes from the window to next_out. */
1440
0
        if (left) {
1441
0
            if (left > len)
1442
0
                left = len;
1443
0
            memcpy(s->strm->next_out, s->window + s->block_start, left);
1444
0
            s->strm->next_out += left;
1445
0
            s->strm->avail_out -= left;
1446
0
            s->strm->total_out += left;
1447
0
            s->block_start += (int)left;
1448
0
            len -= left;
1449
0
        }
1450
1451
        /* Copy uncompressed bytes directly from next_in to next_out, updating
1452
         * the check value.
1453
         */
1454
0
        if (len) {
1455
0
            read_buf(s->strm, s->strm->next_out, len);
1456
0
            s->strm->next_out += len;
1457
0
            s->strm->avail_out -= len;
1458
0
            s->strm->total_out += len;
1459
0
        }
1460
0
    } while (last == 0);
1461
1462
    /* Update the sliding window with the last s->w_size bytes of the copied
1463
     * data, or append all of the copied data to the existing window if less
1464
     * than s->w_size bytes were copied. Also update the number of bytes to
1465
     * insert in the hash tables, in the event that deflateParams() switches to
1466
     * a non-zero compression level.
1467
     */
1468
0
    used -= s->strm->avail_in;      /* number of input bytes directly copied */
1469
0
    if (used) {
1470
        /* If any input was used, then no unused input remains in the window,
1471
         * therefore s->block_start == s->strstart.
1472
         */
1473
0
        if (used >= s->w_size) {    /* supplant the previous history */
1474
0
            s->matches = 2;         /* clear hash */
1475
0
            memcpy(s->window, s->strm->next_in - s->w_size, s->w_size);
1476
0
            s->strstart = s->w_size;
1477
0
            s->insert = s->strstart;
1478
0
        } else {
1479
0
            if (s->window_size - s->strstart <= used) {
1480
                /* Slide the window down. */
1481
0
                s->strstart -= s->w_size;
1482
0
                memcpy(s->window, s->window + s->w_size, s->strstart);
1483
0
                if (s->matches < 2)
1484
0
                    s->matches++;   /* add a pending slide_hash() */
1485
0
                if (s->insert > s->strstart)
1486
0
                    s->insert = s->strstart;
1487
0
            }
1488
0
            memcpy(s->window + s->strstart, s->strm->next_in - used, used);
1489
0
            s->strstart += used;
1490
0
            s->insert += MIN(used, s->w_size - s->insert);
1491
0
        }
1492
0
        s->block_start = (int)s->strstart;
1493
0
    }
1494
0
    if (s->high_water < s->strstart)
1495
0
        s->high_water = s->strstart;
1496
1497
    /* If the last block was written to next_out, then done. */
1498
0
    if (last)
1499
0
        return finish_done;
1500
1501
    /* If flushing and all input has been consumed, then done. */
1502
0
    if (flush != Z_NO_FLUSH && flush != Z_FINISH && s->strm->avail_in == 0 && (int)s->strstart == s->block_start)
1503
0
        return block_done;
1504
1505
    /* Fill the window with any remaining input. */
1506
0
    have = s->window_size - s->strstart;
1507
0
    if (s->strm->avail_in > have && s->block_start >= (int)s->w_size) {
1508
        /* Slide the window down. */
1509
0
        s->block_start -= (int)s->w_size;
1510
0
        s->strstart -= s->w_size;
1511
0
        memcpy(s->window, s->window + s->w_size, s->strstart);
1512
0
        if (s->matches < 2)
1513
0
            s->matches++;           /* add a pending slide_hash() */
1514
0
        have += s->w_size;          /* more space now */
1515
0
        if (s->insert > s->strstart)
1516
0
            s->insert = s->strstart;
1517
0
    }
1518
0
    if (have > s->strm->avail_in)
1519
0
        have = s->strm->avail_in;
1520
0
    if (have) {
1521
0
        read_buf(s->strm, s->window + s->strstart, have);
1522
0
        s->strstart += have;
1523
0
        s->insert += MIN(have, s->w_size - s->insert);
1524
0
    }
1525
0
    if (s->high_water < s->strstart)
1526
0
        s->high_water = s->strstart;
1527
1528
    /* There was not enough avail_out to write a complete worthy or flushed
1529
     * stored block to next_out. Write a stored block to pending instead, if we
1530
     * have enough input for a worthy block, or if flushing and there is enough
1531
     * room for the remaining input as a stored block in the pending buffer.
1532
     */
1533
0
    have = (s->bi_valid + 42) >> 3;         /* number of header bytes */
1534
        /* maximum stored block length that will fit in pending: */
1535
0
    have = MIN(s->pending_buf_size - have, MAX_STORED);
1536
0
    min_block = MIN(have, s->w_size);
1537
0
    left = (int)s->strstart - s->block_start;
1538
0
    if (left >= min_block || ((left || flush == Z_FINISH) && flush != Z_NO_FLUSH && s->strm->avail_in == 0 && left <= have)) {
1539
0
        len = MIN(left, have);
1540
0
        last = flush == Z_FINISH && s->strm->avail_in == 0 && len == left ? 1 : 0;
1541
0
        zng_tr_stored_block(s, (char *)s->window + s->block_start, len, last);
1542
0
        s->block_start += (int)len;
1543
0
        flush_pending(s->strm);
1544
0
    }
1545
1546
    /* We've done all we can with the available input and output. */
1547
0
    return last ? finish_started : need_more;
1548
0
}
1549
1550
1551
/* ===========================================================================
1552
 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
1553
 * one.  Do not maintain a hash table.  (It will be regenerated if this run of
1554
 * deflate switches away from Z_RLE.)
1555
 */
1556
0
static block_state deflate_rle(deflate_state *s, int flush) {
1557
0
    int bflush = 0;                 /* set if current block must be flushed */
1558
0
    unsigned int prev;              /* byte at distance one to match */
1559
0
    unsigned char *scan, *strend;   /* scan goes up to strend for length of run */
1560
0
    uint32_t match_len = 0;
1561
1562
0
    for (;;) {
1563
        /* Make sure that we always have enough lookahead, except
1564
         * at the end of the input file. We need MAX_MATCH bytes
1565
         * for the longest run, plus one for the unrolled loop.
1566
         */
1567
0
        if (s->lookahead <= MAX_MATCH) {
1568
0
            fill_window(s);
1569
0
            if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH)
1570
0
                return need_more;
1571
0
            if (s->lookahead == 0)
1572
0
                break; /* flush the current block */
1573
0
        }
1574
1575
        /* See how many times the previous byte repeats */
1576
0
        if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
1577
0
            scan = s->window + s->strstart - 1;
1578
0
            prev = *scan;
1579
0
            if (prev == *++scan && prev == *++scan && prev == *++scan) {
1580
0
                strend = s->window + s->strstart + MAX_MATCH;
1581
0
                do {
1582
0
                } while (prev == *++scan && prev == *++scan &&
1583
0
                         prev == *++scan && prev == *++scan &&
1584
0
                         prev == *++scan && prev == *++scan &&
1585
0
                         prev == *++scan && prev == *++scan &&
1586
0
                         scan < strend);
1587
0
                match_len = MAX_MATCH - (unsigned int)(strend - scan);
1588
0
                if (match_len > s->lookahead)
1589
0
                    match_len = s->lookahead;
1590
0
            }
1591
0
            Assert(scan <= s->window + s->window_size - 1, "wild scan");
1592
0
        }
1593
1594
        /* Emit match if have run of MIN_MATCH or longer, else emit literal */
1595
0
        if (match_len >= MIN_MATCH) {
1596
0
            check_match(s, s->strstart, s->strstart - 1, match_len);
1597
1598
0
            bflush = zng_tr_tally_dist(s, 1, match_len - MIN_MATCH);
1599
1600
0
            s->lookahead -= match_len;
1601
0
            s->strstart += match_len;
1602
0
            match_len = 0;
1603
0
        } else {
1604
            /* No match, output a literal byte */
1605
0
            bflush = zng_tr_tally_lit(s, s->window[s->strstart]);
1606
0
            s->lookahead--;
1607
0
            s->strstart++;
1608
0
        }
1609
0
        if (bflush)
1610
0
            FLUSH_BLOCK(s, 0);
1611
0
    }
1612
0
    s->insert = 0;
1613
0
    if (flush == Z_FINISH) {
1614
0
        FLUSH_BLOCK(s, 1);
1615
0
        return finish_done;
1616
0
    }
1617
0
    if (s->sym_next)
1618
0
        FLUSH_BLOCK(s, 0);
1619
0
    return block_done;
1620
0
}
1621
1622
/* ===========================================================================
1623
 * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
1624
 * (It will be regenerated if this run of deflate switches away from Huffman.)
1625
 */
1626
0
static block_state deflate_huff(deflate_state *s, int flush) {
1627
0
    int bflush = 0;         /* set if current block must be flushed */
1628
1629
0
    for (;;) {
1630
        /* Make sure that we have a literal to write. */
1631
0
        if (s->lookahead == 0) {
1632
0
            fill_window(s);
1633
0
            if (s->lookahead == 0) {
1634
0
                if (flush == Z_NO_FLUSH)
1635
0
                    return need_more;
1636
0
                break;      /* flush the current block */
1637
0
            }
1638
0
        }
1639
1640
        /* Output a literal byte */
1641
0
        bflush = zng_tr_tally_lit(s, s->window[s->strstart]);
1642
0
        s->lookahead--;
1643
0
        s->strstart++;
1644
0
        if (bflush)
1645
0
            FLUSH_BLOCK(s, 0);
1646
0
    }
1647
0
    s->insert = 0;
1648
0
    if (flush == Z_FINISH) {
1649
0
        FLUSH_BLOCK(s, 1);
1650
0
        return finish_done;
1651
0
    }
1652
0
    if (s->sym_next)
1653
0
        FLUSH_BLOCK(s, 0);
1654
0
    return block_done;
1655
0
}
1656
1657
#ifndef ZLIB_COMPAT
1658
/* =========================================================================
1659
 * Checks whether buffer size is sufficient and whether this parameter is a duplicate.
1660
 */
1661
static int32_t deflateSetParamPre(zng_deflate_param_value **out, size_t min_size, zng_deflate_param_value *param) {
1662
    int32_t buf_error = param->size < min_size;
1663
1664
    if (*out != NULL) {
1665
        (*out)->status = Z_BUF_ERROR;
1666
        buf_error = 1;
1667
    }
1668
    *out = param;
1669
    return buf_error;
1670
}
1671
1672
/* ========================================================================= */
1673
int32_t Z_EXPORT zng_deflateSetParams(zng_stream *strm, zng_deflate_param_value *params, size_t count) {
1674
    size_t i;
1675
    deflate_state *s;
1676
    zng_deflate_param_value *new_level = NULL;
1677
    zng_deflate_param_value *new_strategy = NULL;
1678
    zng_deflate_param_value *new_reproducible = NULL;
1679
    int param_buf_error;
1680
    int version_error = 0;
1681
    int buf_error = 0;
1682
    int stream_error = 0;
1683
    int ret;
1684
    int val;
1685
1686
    /* Initialize the statuses. */
1687
    for (i = 0; i < count; i++)
1688
        params[i].status = Z_OK;
1689
1690
    /* Check whether the stream state is consistent. */
1691
    if (deflateStateCheck(strm))
1692
        return Z_STREAM_ERROR;
1693
    s = strm->state;
1694
1695
    /* Check buffer sizes and detect duplicates. */
1696
    for (i = 0; i < count; i++) {
1697
        switch (params[i].param) {
1698
            case Z_DEFLATE_LEVEL:
1699
                param_buf_error = deflateSetParamPre(&new_level, sizeof(int), &params[i]);
1700
                break;
1701
            case Z_DEFLATE_STRATEGY:
1702
                param_buf_error = deflateSetParamPre(&new_strategy, sizeof(int), &params[i]);
1703
                break;
1704
            case Z_DEFLATE_REPRODUCIBLE:
1705
                param_buf_error = deflateSetParamPre(&new_reproducible, sizeof(int), &params[i]);
1706
                break;
1707
            default:
1708
                params[i].status = Z_VERSION_ERROR;
1709
                version_error = 1;
1710
                param_buf_error = 0;
1711
                break;
1712
        }
1713
        if (param_buf_error) {
1714
            params[i].status = Z_BUF_ERROR;
1715
            buf_error = 1;
1716
        }
1717
    }
1718
    /* Exit early if small buffers or duplicates are detected. */
1719
    if (buf_error)
1720
        return Z_BUF_ERROR;
1721
1722
    /* Apply changes, remember if there were errors. */
1723
    if (new_level != NULL || new_strategy != NULL) {
1724
        ret = PREFIX(deflateParams)(strm, new_level == NULL ? s->level : *(int *)new_level->buf,
1725
                                    new_strategy == NULL ? s->strategy : *(int *)new_strategy->buf);
1726
        if (ret != Z_OK) {
1727
            if (new_level != NULL)
1728
                new_level->status = Z_STREAM_ERROR;
1729
            if (new_strategy != NULL)
1730
                new_strategy->status = Z_STREAM_ERROR;
1731
            stream_error = 1;
1732
        }
1733
    }
1734
    if (new_reproducible != NULL) {
1735
        val = *(int *)new_reproducible->buf;
1736
        if (DEFLATE_CAN_SET_REPRODUCIBLE(strm, val)) {
1737
            s->reproducible = val;
1738
        } else {
1739
            new_reproducible->status = Z_STREAM_ERROR;
1740
            stream_error = 1;
1741
        }
1742
    }
1743
1744
    /* Report version errors only if there are no real errors. */
1745
    return stream_error ? Z_STREAM_ERROR : (version_error ? Z_VERSION_ERROR : Z_OK);
1746
}
1747
1748
/* ========================================================================= */
1749
int32_t Z_EXPORT zng_deflateGetParams(zng_stream *strm, zng_deflate_param_value *params, size_t count) {
1750
    deflate_state *s;
1751
    size_t i;
1752
    int32_t buf_error = 0;
1753
    int32_t version_error = 0;
1754
1755
    /* Initialize the statuses. */
1756
    for (i = 0; i < count; i++)
1757
        params[i].status = Z_OK;
1758
1759
    /* Check whether the stream state is consistent. */
1760
    if (deflateStateCheck(strm))
1761
        return Z_STREAM_ERROR;
1762
    s = strm->state;
1763
1764
    for (i = 0; i < count; i++) {
1765
        switch (params[i].param) {
1766
            case Z_DEFLATE_LEVEL:
1767
                if (params[i].size < sizeof(int))
1768
                    params[i].status = Z_BUF_ERROR;
1769
                else
1770
                    *(int *)params[i].buf = s->level;
1771
                break;
1772
            case Z_DEFLATE_STRATEGY:
1773
                if (params[i].size < sizeof(int))
1774
                    params[i].status = Z_BUF_ERROR;
1775
                else
1776
                    *(int *)params[i].buf = s->strategy;
1777
                break;
1778
            case Z_DEFLATE_REPRODUCIBLE:
1779
                if (params[i].size < sizeof(int))
1780
                    params[i].status = Z_BUF_ERROR;
1781
                else
1782
                    *(int *)params[i].buf = s->reproducible;
1783
                break;
1784
            default:
1785
                params[i].status = Z_VERSION_ERROR;
1786
                version_error = 1;
1787
                break;
1788
        }
1789
        if (params[i].status == Z_BUF_ERROR)
1790
            buf_error = 1;
1791
    }
1792
    return buf_error ? Z_BUF_ERROR : (version_error ? Z_VERSION_ERROR : Z_OK);
1793
}
1794
#endif