Coverage Report

Created: 2026-07-10 07:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/c-blosc2/_deps/zlib_ng-src/deflate.c
Line
Count
Source
1
/* deflate.c -- compress data using the deflation algorithm
2
 * Copyright (C) 1995-2024 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 "functable.h"
52
#include "deflate.h"
53
#include "deflate_p.h"
54
55
/* Avoid conflicts with zlib.h macros */
56
#ifdef ZLIB_COMPAT
57
# undef deflateInit
58
# undef deflateInit2
59
#endif
60
61
const char PREFIX(deflate_copyright)[] = " deflate 1.3.1 Copyright 1995-2024 Jean-loup Gailly and Mark Adler ";
62
/*
63
  If you use the zlib library in a product, an acknowledgment is welcome
64
  in the documentation of your product. If for some reason you cannot
65
  include such an acknowledgment, I would appreciate that you keep this
66
  copyright string in the executable of your product.
67
 */
68
69
/* ===========================================================================
70
 *  Function prototypes.
71
 */
72
static int deflateStateCheck      (PREFIX3(stream) *strm);
73
Z_INTERNAL block_state deflate_stored(deflate_state *s, int flush);
74
Z_INTERNAL block_state deflate_fast  (deflate_state *s, int flush);
75
Z_INTERNAL block_state deflate_quick (deflate_state *s, int flush);
76
#ifndef NO_MEDIUM_STRATEGY
77
Z_INTERNAL block_state deflate_medium(deflate_state *s, int flush);
78
#endif
79
Z_INTERNAL block_state deflate_slow  (deflate_state *s, int flush);
80
Z_INTERNAL block_state deflate_rle   (deflate_state *s, int flush);
81
Z_INTERNAL block_state deflate_huff  (deflate_state *s, int flush);
82
static void lm_set_level         (deflate_state *s, int level);
83
static void lm_init              (deflate_state *s);
84
85
/* ===========================================================================
86
 * Local data
87
 */
88
89
/* Values for max_lazy_match, good_match and max_chain_length, depending on
90
 * the desired pack level (0..9). The values given below have been tuned to
91
 * exclude worst case performance for pathological files. Better values may be
92
 * found for specific files.
93
 */
94
typedef struct config_s {
95
    uint16_t good_length; /* reduce lazy search above this match length */
96
    uint16_t max_lazy;    /* do not perform lazy search above this match length */
97
    uint16_t nice_length; /* quit search above this match length */
98
    uint16_t max_chain;
99
    compress_func func;
100
} config;
101
102
static const config configuration_table[10] = {
103
/*      good lazy nice chain */
104
/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
105
106
#ifdef NO_QUICK_STRATEGY
107
/* 1 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */
108
/* 2 */ {4,    5, 16,    8, deflate_fast},
109
#else
110
/* 1 */ {0,    0,  0,    0, deflate_quick},
111
/* 2 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */
112
#endif
113
114
#ifdef NO_MEDIUM_STRATEGY
115
/* 3 */ {4,    6, 32,   32, deflate_fast},
116
/* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
117
/* 5 */ {8,   16, 32,   32, deflate_slow},
118
/* 6 */ {8,   16, 128, 128, deflate_slow},
119
#else
120
/* 3 */ {4,    6, 16,    6, deflate_medium},
121
/* 4 */ {4,   12, 32,   24, deflate_medium},  /* lazy matches */
122
/* 5 */ {8,   16, 32,   32, deflate_medium},
123
/* 6 */ {8,   16, 128, 128, deflate_medium},
124
#endif
125
126
/* 7 */ {8,   32, 128,  256, deflate_slow},
127
/* 8 */ {32, 128, 258, 1024, deflate_slow},
128
/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
129
130
/* Note: the deflate() code requires max_lazy >= STD_MIN_MATCH and max_chain >= 4
131
 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
132
 * meaning.
133
 */
134
135
/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */
136
36.5k
#define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0))
137
138
139
/* ===========================================================================
140
 * Initialize the hash table. prev[] will be initialized on the fly.
141
 */
142
36.5k
#define CLEAR_HASH(s) do { \
143
36.5k
    memset((unsigned char *)s->head, 0, HASH_SIZE * sizeof(*s->head)); \
144
36.5k
  } while (0)
145
146
147
#ifdef DEF_ALLOC_DEBUG
148
#  include <stdio.h>
149
#  define LOGSZ(name,size)           fprintf(stderr, "%s is %d bytes\n", name, size)
150
#  define LOGSZP(name,size,loc,pad)  fprintf(stderr, "%s is %d bytes, offset %d, padded %d\n", name, size, loc, pad)
151
#  define LOGSZPL(name,size,loc,pad) fprintf(stderr, "%s is %d bytes, offset %ld, padded %d\n", name, size, loc, pad)
152
#else
153
#  define LOGSZ(name,size)
154
#  define LOGSZP(name,size,loc,pad)
155
#  define LOGSZPL(name,size,loc,pad)
156
#endif
157
158
/* ===========================================================================
159
 * Allocate a big buffer and divide it up into the various buffers deflate needs.
160
 * Handles alignment of allocated buffer and alignment of individual buffers.
161
 */
162
36.5k
Z_INTERNAL deflate_allocs* alloc_deflate(PREFIX3(stream) *strm, int windowBits, int lit_bufsize) {
163
36.5k
    int curr_size = 0;
164
165
    /* Define sizes */
166
36.5k
    int window_size = DEFLATE_ADJUST_WINDOW_SIZE((1 << windowBits) * 2);
167
36.5k
    int prev_size = (1 << windowBits) * (int)sizeof(Pos);
168
36.5k
    int head_size = HASH_SIZE * sizeof(Pos);
169
36.5k
    int pending_size = lit_bufsize * LIT_BUFS;
170
36.5k
    int state_size = sizeof(deflate_state);
171
36.5k
    int alloc_size = sizeof(deflate_allocs);
172
173
    /* Calculate relative buffer positions and paddings */
174
36.5k
    LOGSZP("window", window_size, PAD_WINDOW(curr_size), PADSZ(curr_size,WINDOW_PAD_SIZE));
175
36.5k
    int window_pos = PAD_WINDOW(curr_size);
176
36.5k
    curr_size = window_pos + window_size;
177
178
36.5k
    LOGSZP("prev", prev_size, PAD_64(curr_size), PADSZ(curr_size,64));
179
36.5k
    int prev_pos = PAD_64(curr_size);
180
36.5k
    curr_size = prev_pos + prev_size;
181
182
36.5k
    LOGSZP("head", head_size, PAD_64(curr_size), PADSZ(curr_size,64));
183
36.5k
    int head_pos = PAD_64(curr_size);
184
36.5k
    curr_size = head_pos + head_size;
185
186
36.5k
    LOGSZP("pending", pending_size, PAD_64(curr_size), PADSZ(curr_size,64));
187
36.5k
    int pending_pos = PAD_64(curr_size);
188
36.5k
    curr_size = pending_pos + pending_size;
189
190
36.5k
    LOGSZP("state", state_size, PAD_64(curr_size), PADSZ(curr_size,64));
191
36.5k
    int state_pos = PAD_64(curr_size);
192
36.5k
    curr_size = state_pos + state_size;
193
194
36.5k
    LOGSZP("alloc", alloc_size, PAD_16(curr_size), PADSZ(curr_size,16));
195
36.5k
    int alloc_pos = PAD_16(curr_size);
196
36.5k
    curr_size = alloc_pos + alloc_size;
197
198
    /* Add 64-1 or 4096-1 to allow window alignment, and round size of buffer up to multiple of 64 */
199
36.5k
    int total_size = PAD_64(curr_size + (WINDOW_PAD_SIZE - 1));
200
201
    /* Allocate buffer, align to 64-byte cacheline, and zerofill the resulting buffer */
202
36.5k
    char *original_buf = (char *)strm->zalloc(strm->opaque, 1, total_size);
203
36.5k
    if (original_buf == NULL)
204
0
        return NULL;
205
206
36.5k
    char *buff = (char *)HINT_ALIGNED_WINDOW((char *)PAD_WINDOW(original_buf));
207
36.5k
    LOGSZPL("Buffer alloc", total_size, PADSZ((uintptr_t)original_buf,WINDOW_PAD_SIZE), PADSZ(curr_size,WINDOW_PAD_SIZE));
208
209
    /* Initialize alloc_bufs */
210
36.5k
    deflate_allocs *alloc_bufs  = (struct deflate_allocs_s *)(buff + alloc_pos);
211
36.5k
    alloc_bufs->buf_start = original_buf;
212
36.5k
    alloc_bufs->zfree = strm->zfree;
213
214
    /* Assign buffers */
215
36.5k
    alloc_bufs->window = (unsigned char *)HINT_ALIGNED_WINDOW(buff + window_pos);
216
36.5k
    alloc_bufs->prev = (Pos *)HINT_ALIGNED_64(buff + prev_pos);
217
36.5k
    alloc_bufs->head = (Pos *)HINT_ALIGNED_64(buff + head_pos);
218
36.5k
    alloc_bufs->pending_buf = (unsigned char *)HINT_ALIGNED_64(buff + pending_pos);
219
36.5k
    alloc_bufs->state = (deflate_state *)HINT_ALIGNED_16(buff + state_pos);
220
221
36.5k
    memset((char *)alloc_bufs->prev, 0, prev_size);
222
223
36.5k
    return alloc_bufs;
224
36.5k
}
225
226
/* ===========================================================================
227
 * Free all allocated deflate buffers
228
 */
229
36.5k
static inline void free_deflate(PREFIX3(stream) *strm) {
230
36.5k
    deflate_state *state = (deflate_state *)strm->state;
231
232
36.5k
    if (state->alloc_bufs != NULL) {
233
36.5k
        deflate_allocs *alloc_bufs = state->alloc_bufs;
234
36.5k
        alloc_bufs->zfree(strm->opaque, alloc_bufs->buf_start);
235
36.5k
        strm->state = NULL;
236
36.5k
    }
237
36.5k
}
238
239
/* ===========================================================================
240
 * Initialize deflate state and buffers.
241
 * This function is hidden in ZLIB_COMPAT builds.
242
 */
243
int32_t ZNG_CONDEXPORT PREFIX(deflateInit2)(PREFIX3(stream) *strm, int32_t level, int32_t method, int32_t windowBits,
244
36.5k
                                            int32_t memLevel, int32_t strategy) {
245
    /* Todo: ignore strm->next_in if we use it as window */
246
36.5k
    deflate_state *s;
247
36.5k
    int wrap = 1;
248
249
    /* Initialize functable */
250
36.5k
    FUNCTABLE_INIT;
251
252
36.5k
    if (strm == NULL)
253
0
        return Z_STREAM_ERROR;
254
255
36.5k
    strm->msg = NULL;
256
36.5k
    if (strm->zalloc == NULL) {
257
36.5k
        strm->zalloc = PREFIX(zcalloc);
258
36.5k
        strm->opaque = NULL;
259
36.5k
    }
260
36.5k
    if (strm->zfree == NULL)
261
36.5k
        strm->zfree = PREFIX(zcfree);
262
263
36.5k
    if (level == Z_DEFAULT_COMPRESSION)
264
0
        level = 6;
265
266
36.5k
    if (windowBits < 0) { /* suppress zlib wrapper */
267
0
        wrap = 0;
268
0
        if (windowBits < -MAX_WBITS)
269
0
            return Z_STREAM_ERROR;
270
0
        windowBits = -windowBits;
271
0
#ifdef GZIP
272
36.5k
    } else if (windowBits > MAX_WBITS) {
273
0
        wrap = 2;       /* write gzip wrapper instead */
274
0
        windowBits -= 16;
275
0
#endif
276
0
    }
277
36.5k
    if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || windowBits < MIN_WBITS ||
278
36.5k
        windowBits > MAX_WBITS || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED ||
279
36.5k
        (windowBits == 8 && wrap != 1)) {
280
0
        return Z_STREAM_ERROR;
281
0
    }
282
36.5k
    if (windowBits == 8)
283
0
        windowBits = 9;  /* until 256-byte window bug fixed */
284
285
    /* Allocate buffers */
286
36.5k
    int lit_bufsize = 1 << (memLevel + 6);
287
36.5k
    deflate_allocs *alloc_bufs = alloc_deflate(strm, windowBits, lit_bufsize);
288
36.5k
    if (alloc_bufs == NULL)
289
0
        return Z_MEM_ERROR;
290
291
36.5k
    s = alloc_bufs->state;
292
36.5k
    s->alloc_bufs = alloc_bufs;
293
36.5k
    s->window = alloc_bufs->window;
294
36.5k
    s->prev = alloc_bufs->prev;
295
36.5k
    s->head = alloc_bufs->head;
296
36.5k
    s->pending_buf = alloc_bufs->pending_buf;
297
298
36.5k
    strm->state = (struct internal_state *)s;
299
36.5k
    s->strm = strm;
300
36.5k
    s->status = INIT_STATE;     /* to pass state test in deflateReset() */
301
302
36.5k
    s->wrap = wrap;
303
36.5k
    s->gzhead = NULL;
304
36.5k
    s->w_bits = (unsigned int)windowBits;
305
36.5k
    s->w_size = 1 << s->w_bits;
306
36.5k
    s->w_mask = s->w_size - 1;
307
308
36.5k
    s->high_water = 0;      /* nothing written to s->window yet */
309
310
36.5k
    s->lit_bufsize = lit_bufsize; /* 16K elements by default */
311
312
    /* We overlay pending_buf and sym_buf. This works since the average size
313
     * for length/distance pairs over any compressed block is assured to be 31
314
     * bits or less.
315
     *
316
     * Analysis: The longest fixed codes are a length code of 8 bits plus 5
317
     * extra bits, for lengths 131 to 257. The longest fixed distance codes are
318
     * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest
319
     * possible fixed-codes length/distance pair is then 31 bits total.
320
     *
321
     * sym_buf starts one-fourth of the way into pending_buf. So there are
322
     * three bytes in sym_buf for every four bytes in pending_buf. Each symbol
323
     * in sym_buf is three bytes -- two for the distance and one for the
324
     * literal/length. As each symbol is consumed, the pointer to the next
325
     * sym_buf value to read moves forward three bytes. From that symbol, up to
326
     * 31 bits are written to pending_buf. The closest the written pending_buf
327
     * bits gets to the next sym_buf symbol to read is just before the last
328
     * code is written. At that time, 31*(n-2) bits have been written, just
329
     * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at
330
     * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1
331
     * symbols are written.) The closest the writing gets to what is unread is
332
     * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and
333
     * can range from 128 to 32768.
334
     *
335
     * Therefore, at a minimum, there are 142 bits of space between what is
336
     * written and what is read in the overlain buffers, so the symbols cannot
337
     * be overwritten by the compressed data. That space is actually 139 bits,
338
     * due to the three-bit fixed-code block header.
339
     *
340
     * That covers the case where either Z_FIXED is specified, forcing fixed
341
     * codes, or when the use of fixed codes is chosen, because that choice
342
     * results in a smaller compressed block than dynamic codes. That latter
343
     * condition then assures that the above analysis also covers all dynamic
344
     * blocks. A dynamic-code block will only be chosen to be emitted if it has
345
     * fewer bits than a fixed-code block would for the same set of symbols.
346
     * Therefore its average symbol length is assured to be less than 31. So
347
     * the compressed data for a dynamic block also cannot overwrite the
348
     * symbols from which it is being constructed.
349
     */
350
351
36.5k
    s->pending_buf_size = s->lit_bufsize * 4;
352
353
36.5k
#ifdef LIT_MEM
354
36.5k
    s->d_buf = (uint16_t *)(s->pending_buf + (s->lit_bufsize << 1));
355
36.5k
    s->l_buf = s->pending_buf + (s->lit_bufsize << 2);
356
36.5k
    s->sym_end = s->lit_bufsize - 1;
357
#else
358
    s->sym_buf = s->pending_buf + s->lit_bufsize;
359
    s->sym_end = (s->lit_bufsize - 1) * 3;
360
#endif
361
    /* We avoid equality with lit_bufsize*3 because of wraparound at 64K
362
     * on 16 bit machines and because stored blocks are restricted to
363
     * 64K-1 bytes.
364
     */
365
366
36.5k
    s->level = level;
367
36.5k
    s->strategy = strategy;
368
36.5k
    s->block_open = 0;
369
36.5k
    s->reproducible = 0;
370
371
36.5k
    return PREFIX(deflateReset)(strm);
372
36.5k
}
373
374
#ifndef ZLIB_COMPAT
375
36.5k
int32_t Z_EXPORT PREFIX(deflateInit)(PREFIX3(stream) *strm, int32_t level) {
376
36.5k
    return PREFIX(deflateInit2)(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
377
36.5k
}
378
#endif
379
380
/* Function used by zlib.h and zlib-ng version 2.0 macros */
381
0
int32_t Z_EXPORT PREFIX(deflateInit_)(PREFIX3(stream) *strm, int32_t level, const char *version, int32_t stream_size) {
382
0
    if (CHECK_VER_STSIZE(version, stream_size))
383
0
        return Z_VERSION_ERROR;
384
0
    return PREFIX(deflateInit2)(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
385
0
}
386
387
/* Function used by zlib.h and zlib-ng version 2.0 macros */
388
int32_t Z_EXPORT PREFIX(deflateInit2_)(PREFIX3(stream) *strm, int32_t level, int32_t method, int32_t windowBits,
389
0
                           int32_t memLevel, int32_t strategy, const char *version, int32_t stream_size) {
390
0
    if (CHECK_VER_STSIZE(version, stream_size))
391
0
        return Z_VERSION_ERROR;
392
0
    return PREFIX(deflateInit2)(strm, level, method, windowBits, memLevel, strategy);
393
0
}
394
395
/* =========================================================================
396
 * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
397
 */
398
118k
static int deflateStateCheck(PREFIX3(stream) *strm) {
399
118k
    deflate_state *s;
400
118k
    if (strm == NULL || strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
401
0
        return 1;
402
118k
    s = strm->state;
403
118k
    if (s == NULL || s->alloc_bufs == NULL || s->strm != strm || (s->status < INIT_STATE || s->status > MAX_STATE))
404
0
        return 1;
405
118k
    return 0;
406
118k
}
407
408
/* ========================================================================= */
409
0
int32_t Z_EXPORT PREFIX(deflateSetDictionary)(PREFIX3(stream) *strm, const uint8_t *dictionary, uint32_t dictLength) {
410
0
    deflate_state *s;
411
0
    unsigned int str, n;
412
0
    int wrap;
413
0
    uint32_t avail;
414
0
    const unsigned char *next;
415
416
0
    if (deflateStateCheck(strm) || dictionary == NULL)
417
0
        return Z_STREAM_ERROR;
418
0
    s = strm->state;
419
0
    wrap = s->wrap;
420
0
    if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
421
0
        return Z_STREAM_ERROR;
422
423
    /* when using zlib wrappers, compute Adler-32 for provided dictionary */
424
0
    if (wrap == 1)
425
0
        strm->adler = FUNCTABLE_CALL(adler32)(strm->adler, dictionary, dictLength);
426
0
    DEFLATE_SET_DICTIONARY_HOOK(strm, dictionary, dictLength);  /* hook for IBM Z DFLTCC */
427
0
    s->wrap = 0;                    /* avoid computing Adler-32 in read_buf */
428
429
    /* if dictionary would fill window, just replace the history */
430
0
    if (dictLength >= s->w_size) {
431
0
        if (wrap == 0) {            /* already empty otherwise */
432
0
            CLEAR_HASH(s);
433
0
            s->strstart = 0;
434
0
            s->block_start = 0;
435
0
            s->insert = 0;
436
0
        }
437
0
        dictionary += dictLength - s->w_size;  /* use the tail */
438
0
        dictLength = s->w_size;
439
0
    }
440
441
    /* insert dictionary into window and hash */
442
0
    avail = strm->avail_in;
443
0
    next = strm->next_in;
444
0
    strm->avail_in = dictLength;
445
0
    strm->next_in = (z_const unsigned char *)dictionary;
446
0
    PREFIX(fill_window)(s);
447
0
    while (s->lookahead >= STD_MIN_MATCH) {
448
0
        str = s->strstart;
449
0
        n = s->lookahead - (STD_MIN_MATCH - 1);
450
0
        s->insert_string(s, str, n);
451
0
        s->strstart = str + n;
452
0
        s->lookahead = STD_MIN_MATCH - 1;
453
0
        PREFIX(fill_window)(s);
454
0
    }
455
0
    s->strstart += s->lookahead;
456
0
    s->block_start = (int)s->strstart;
457
0
    s->insert = s->lookahead;
458
0
    s->lookahead = 0;
459
0
    s->prev_length = 0;
460
0
    s->match_available = 0;
461
0
    strm->next_in = (z_const unsigned char *)next;
462
0
    strm->avail_in = avail;
463
0
    s->wrap = wrap;
464
0
    return Z_OK;
465
0
}
466
467
/* ========================================================================= */
468
0
int32_t Z_EXPORT PREFIX(deflateGetDictionary)(PREFIX3(stream) *strm, uint8_t *dictionary, uint32_t *dictLength) {
469
0
    deflate_state *s;
470
0
    unsigned int len;
471
472
0
    if (deflateStateCheck(strm))
473
0
        return Z_STREAM_ERROR;
474
0
    DEFLATE_GET_DICTIONARY_HOOK(strm, dictionary, dictLength);  /* hook for IBM Z DFLTCC */
475
0
    s = strm->state;
476
0
    len = s->strstart + s->lookahead;
477
0
    if (len > s->w_size)
478
0
        len = s->w_size;
479
0
    if (dictionary != NULL && len)
480
0
        memcpy(dictionary, s->window + s->strstart + s->lookahead - len, len);
481
0
    if (dictLength != NULL)
482
0
        *dictLength = len;
483
0
    return Z_OK;
484
0
}
485
486
/* ========================================================================= */
487
36.5k
int32_t Z_EXPORT PREFIX(deflateResetKeep)(PREFIX3(stream) *strm) {
488
36.5k
    deflate_state *s;
489
490
36.5k
    if (deflateStateCheck(strm))
491
0
        return Z_STREAM_ERROR;
492
493
36.5k
    strm->total_in = strm->total_out = 0;
494
36.5k
    strm->msg = NULL; /* use zfree if we ever allocate msg dynamically */
495
36.5k
    strm->data_type = Z_UNKNOWN;
496
497
36.5k
    s = (deflate_state *)strm->state;
498
36.5k
    s->pending = 0;
499
36.5k
    s->pending_out = s->pending_buf;
500
501
36.5k
    if (s->wrap < 0)
502
0
        s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
503
504
36.5k
    s->status =
505
36.5k
#ifdef GZIP
506
36.5k
        s->wrap == 2 ? GZIP_STATE :
507
36.5k
#endif
508
36.5k
        INIT_STATE;
509
510
36.5k
#ifdef GZIP
511
36.5k
    if (s->wrap == 2) {
512
0
        strm->adler = FUNCTABLE_CALL(crc32_fold_reset)(&s->crc_fold);
513
0
    } else
514
36.5k
#endif
515
36.5k
        strm->adler = ADLER32_INITIAL_VALUE;
516
36.5k
    s->last_flush = -2;
517
518
36.5k
    zng_tr_init(s);
519
520
36.5k
    DEFLATE_RESET_KEEP_HOOK(strm);  /* hook for IBM Z DFLTCC */
521
522
36.5k
    return Z_OK;
523
36.5k
}
524
525
/* ========================================================================= */
526
36.5k
int32_t Z_EXPORT PREFIX(deflateReset)(PREFIX3(stream) *strm) {
527
36.5k
    int ret = PREFIX(deflateResetKeep)(strm);
528
36.5k
    if (ret == Z_OK)
529
36.5k
        lm_init(strm->state);
530
36.5k
    return ret;
531
36.5k
}
532
533
/* ========================================================================= */
534
0
int32_t Z_EXPORT PREFIX(deflateSetHeader)(PREFIX3(stream) *strm, PREFIX(gz_headerp) head) {
535
0
    if (deflateStateCheck(strm) || strm->state->wrap != 2)
536
0
        return Z_STREAM_ERROR;
537
0
    strm->state->gzhead = head;
538
0
    return Z_OK;
539
0
}
540
541
/* ========================================================================= */
542
0
int32_t Z_EXPORT PREFIX(deflatePending)(PREFIX3(stream) *strm, uint32_t *pending, int32_t *bits) {
543
0
    if (deflateStateCheck(strm))
544
0
        return Z_STREAM_ERROR;
545
0
    if (pending != NULL)
546
0
        *pending = strm->state->pending;
547
0
    if (bits != NULL)
548
0
        *bits = strm->state->bi_valid;
549
0
    return Z_OK;
550
0
}
551
552
/* ========================================================================= */
553
0
int32_t Z_EXPORT PREFIX(deflatePrime)(PREFIX3(stream) *strm, int32_t bits, int32_t value) {
554
0
    deflate_state *s;
555
0
    uint64_t value64 = (uint64_t)value;
556
0
    int32_t put;
557
558
0
    if (deflateStateCheck(strm))
559
0
        return Z_STREAM_ERROR;
560
0
    s = strm->state;
561
562
0
#ifdef LIT_MEM
563
0
    if (bits < 0 || bits > BIT_BUF_SIZE ||
564
0
        (unsigned char *)s->d_buf < s->pending_out + ((BIT_BUF_SIZE + 7) >> 3))
565
0
        return Z_BUF_ERROR;
566
#else
567
    if (bits < 0 || bits > BIT_BUF_SIZE || bits > (int32_t)(sizeof(value) << 3) ||
568
        s->sym_buf < s->pending_out + ((BIT_BUF_SIZE + 7) >> 3))
569
        return Z_BUF_ERROR;
570
#endif
571
572
0
    do {
573
0
        put = BIT_BUF_SIZE - s->bi_valid;
574
0
        put = MIN(put, bits);
575
576
0
        if (s->bi_valid == 0)
577
0
            s->bi_buf = value64;
578
0
        else
579
0
            s->bi_buf |= (value64 & ((UINT64_C(1) << put) - 1)) << s->bi_valid;
580
0
        s->bi_valid += put;
581
0
        zng_tr_flush_bits(s);
582
0
        value64 >>= put;
583
0
        bits -= put;
584
0
    } while (bits);
585
0
    return Z_OK;
586
0
}
587
588
/* ========================================================================= */
589
0
int32_t Z_EXPORT PREFIX(deflateParams)(PREFIX3(stream) *strm, int32_t level, int32_t strategy) {
590
0
    deflate_state *s;
591
0
    compress_func func;
592
0
    int hook_flush = Z_NO_FLUSH;
593
594
0
    if (deflateStateCheck(strm))
595
0
        return Z_STREAM_ERROR;
596
0
    s = strm->state;
597
598
0
    if (level == Z_DEFAULT_COMPRESSION)
599
0
        level = 6;
600
0
    if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED)
601
0
        return Z_STREAM_ERROR;
602
0
    DEFLATE_PARAMS_HOOK(strm, level, strategy, &hook_flush);  /* hook for IBM Z DFLTCC */
603
0
    func = configuration_table[s->level].func;
604
605
0
    if (((strategy != s->strategy || func != configuration_table[level].func) && s->last_flush != -2)
606
0
        || hook_flush != Z_NO_FLUSH) {
607
        /* Flush the last buffer. Use Z_BLOCK mode, unless the hook requests a "stronger" one. */
608
0
        int flush = RANK(hook_flush) > RANK(Z_BLOCK) ? hook_flush : Z_BLOCK;
609
0
        int err = PREFIX(deflate)(strm, flush);
610
0
        if (err == Z_STREAM_ERROR)
611
0
            return err;
612
0
        if (strm->avail_in || ((int)s->strstart - s->block_start) + s->lookahead || !DEFLATE_DONE(strm, flush))
613
0
            return Z_BUF_ERROR;
614
0
    }
615
0
    if (s->level != level) {
616
0
        if (s->level == 0 && s->matches != 0) {
617
0
            if (s->matches == 1) {
618
0
                FUNCTABLE_CALL(slide_hash)(s);
619
0
            } else {
620
0
                CLEAR_HASH(s);
621
0
            }
622
0
            s->matches = 0;
623
0
        }
624
625
0
        lm_set_level(s, level);
626
0
    }
627
0
    s->strategy = strategy;
628
0
    return Z_OK;
629
0
}
630
631
/* ========================================================================= */
632
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) {
633
0
    deflate_state *s;
634
635
0
    if (deflateStateCheck(strm))
636
0
        return Z_STREAM_ERROR;
637
0
    s = strm->state;
638
0
    s->good_match = (unsigned int)good_length;
639
0
    s->max_lazy_match = (unsigned int)max_lazy;
640
0
    s->nice_match = nice_length;
641
0
    s->max_chain_length = (unsigned int)max_chain;
642
0
    return Z_OK;
643
0
}
644
645
/* =========================================================================
646
 * For the default windowBits of 15 and memLevel of 8, this function returns
647
 * a close to exact, as well as small, upper bound on the compressed size.
648
 * They are coded as constants here for a reason--if the #define's are
649
 * changed, then this function needs to be changed as well.  The return
650
 * value for 15 and 8 only works for those exact settings.
651
 *
652
 * For any setting other than those defaults for windowBits and memLevel,
653
 * the value returned is a conservative worst case for the maximum expansion
654
 * resulting from using fixed blocks instead of stored blocks, which deflate
655
 * can emit on compressed data for some combinations of the parameters.
656
 *
657
 * This function could be more sophisticated to provide closer upper bounds for
658
 * every combination of windowBits and memLevel.  But even the conservative
659
 * upper bound of about 14% expansion does not seem onerous for output buffer
660
 * allocation.
661
 */
662
0
unsigned long Z_EXPORT PREFIX(deflateBound)(PREFIX3(stream) *strm, unsigned long sourceLen) {
663
0
    deflate_state *s;
664
0
    unsigned long complen, wraplen;
665
666
    /* conservative upper bound for compressed data */
667
0
    complen = sourceLen + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
668
0
    DEFLATE_BOUND_ADJUST_COMPLEN(strm, complen, sourceLen);  /* hook for IBM Z DFLTCC */
669
670
    /* if can't get parameters, return conservative bound plus zlib wrapper */
671
0
    if (deflateStateCheck(strm))
672
0
        return complen + 6;
673
674
    /* compute wrapper length */
675
0
    s = strm->state;
676
0
    switch (s->wrap) {
677
0
    case 0:                                 /* raw deflate */
678
0
        wraplen = 0;
679
0
        break;
680
0
    case 1:                                 /* zlib wrapper */
681
0
        wraplen = ZLIB_WRAPLEN + (s->strstart ? 4 : 0);
682
0
        break;
683
0
#ifdef GZIP
684
0
    case 2:                                 /* gzip wrapper */
685
0
        wraplen = GZIP_WRAPLEN;
686
0
        if (s->gzhead != NULL) {            /* user-supplied gzip header */
687
0
            unsigned char *str;
688
0
            if (s->gzhead->extra != NULL) {
689
0
                wraplen += 2 + s->gzhead->extra_len;
690
0
            }
691
0
            str = s->gzhead->name;
692
0
            if (str != NULL) {
693
0
                do {
694
0
                    wraplen++;
695
0
                } while (*str++);
696
0
            }
697
0
            str = s->gzhead->comment;
698
0
            if (str != NULL) {
699
0
                do {
700
0
                    wraplen++;
701
0
                } while (*str++);
702
0
            }
703
0
            if (s->gzhead->hcrc)
704
0
                wraplen += 2;
705
0
        }
706
0
        break;
707
0
#endif
708
0
    default:                                /* for compiler happiness */
709
0
        wraplen = ZLIB_WRAPLEN;
710
0
    }
711
712
    /* if not default parameters, return conservative bound */
713
0
    if (DEFLATE_NEED_CONSERVATIVE_BOUND(strm) ||  /* hook for IBM Z DFLTCC */
714
0
            s->w_bits != MAX_WBITS || HASH_BITS < 15) {
715
0
        if (s->level == 0) {
716
            /* upper bound for stored blocks with length 127 (memLevel == 1) --
717
               ~4% overhead plus a small constant */
718
0
            complen = sourceLen + (sourceLen >> 5) + (sourceLen >> 7) + (sourceLen >> 11) + 7;
719
0
        }
720
721
0
        return complen + wraplen;
722
0
    }
723
724
0
#ifndef NO_QUICK_STRATEGY
725
0
    return sourceLen                       /* The source size itself */
726
0
      + (sourceLen == 0 ? 1 : 0)           /* Always at least one byte for any input */
727
0
      + (sourceLen < 9 ? 1 : 0)            /* One extra byte for lengths less than 9 */
728
0
      + DEFLATE_QUICK_OVERHEAD(sourceLen)  /* Source encoding overhead, padded to next full byte */
729
0
      + DEFLATE_BLOCK_OVERHEAD             /* Deflate block overhead bytes */
730
0
      + wraplen;                           /* none, zlib or gzip wrapper */
731
#else
732
    return sourceLen + (sourceLen >> 4) + 7 + wraplen;
733
#endif
734
0
}
735
736
/* =========================================================================
737
 * Flush as much pending output as possible. See flush_pending_inline()
738
 */
739
73.0k
Z_INTERNAL void PREFIX(flush_pending)(PREFIX3(stream) *strm) {
740
73.0k
    flush_pending_inline(strm);
741
73.0k
}
742
743
/* ===========================================================================
744
 * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1].
745
 */
746
#define HCRC_UPDATE(beg) \
747
0
    do { \
748
0
        if (s->gzhead->hcrc && s->pending > (beg)) \
749
0
            strm->adler = PREFIX(crc32)(strm->adler, s->pending_buf + (beg), s->pending - (beg)); \
750
0
    } while (0)
751
752
/* ========================================================================= */
753
45.2k
int32_t Z_EXPORT PREFIX(deflate)(PREFIX3(stream) *strm, int32_t flush) {
754
45.2k
    int32_t old_flush; /* value of flush param for previous deflate call */
755
45.2k
    deflate_state *s;
756
757
45.2k
    if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0)
758
0
        return Z_STREAM_ERROR;
759
45.2k
    s = strm->state;
760
761
45.2k
    if (strm->next_out == NULL || (strm->avail_in != 0 && strm->next_in == NULL)
762
45.2k
        || (s->status == FINISH_STATE && flush != Z_FINISH)) {
763
0
        ERR_RETURN(strm, Z_STREAM_ERROR);
764
0
    }
765
45.2k
    if (strm->avail_out == 0) {
766
8.64k
        ERR_RETURN(strm, Z_BUF_ERROR);
767
8.64k
    }
768
769
36.5k
    old_flush = s->last_flush;
770
36.5k
    s->last_flush = flush;
771
772
    /* Flush as much pending output as possible */
773
36.5k
    if (s->pending != 0) {
774
0
        flush_pending_inline(strm);
775
0
        if (strm->avail_out == 0) {
776
            /* Since avail_out is 0, deflate will be called again with
777
             * more output space, but possibly with both pending and
778
             * avail_in equal to zero. There won't be anything to do,
779
             * but this is not an error situation so make sure we
780
             * return OK instead of BUF_ERROR at next call of deflate:
781
             */
782
0
            s->last_flush = -1;
783
0
            return Z_OK;
784
0
        }
785
786
        /* Make sure there is something to do and avoid duplicate consecutive
787
         * flushes. For repeated and useless calls with Z_FINISH, we keep
788
         * returning Z_STREAM_END instead of Z_BUF_ERROR.
789
         */
790
36.5k
    } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) && flush != Z_FINISH) {
791
0
        ERR_RETURN(strm, Z_BUF_ERROR);
792
0
    }
793
794
    /* User must not provide more input after the first FINISH: */
795
36.5k
    if (s->status == FINISH_STATE && strm->avail_in != 0)   {
796
0
        ERR_RETURN(strm, Z_BUF_ERROR);
797
0
    }
798
799
    /* Write the header */
800
36.5k
    if (s->status == INIT_STATE && s->wrap == 0)
801
0
        s->status = BUSY_STATE;
802
36.5k
    if (s->status == INIT_STATE) {
803
        /* zlib header */
804
36.5k
        unsigned int header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
805
36.5k
        unsigned int level_flags;
806
807
36.5k
        if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
808
4.83k
            level_flags = 0;
809
31.7k
        else if (s->level < 6)
810
14.2k
            level_flags = 1;
811
17.4k
        else if (s->level == 6)
812
3.80k
            level_flags = 2;
813
13.6k
        else
814
13.6k
            level_flags = 3;
815
36.5k
        header |= (level_flags << 6);
816
36.5k
        if (s->strstart != 0)
817
0
            header |= PRESET_DICT;
818
36.5k
        header += 31 - (header % 31);
819
820
36.5k
        put_short_msb(s, (uint16_t)header);
821
822
        /* Save the adler32 of the preset dictionary: */
823
36.5k
        if (s->strstart != 0)
824
0
            put_uint32_msb(s, strm->adler);
825
36.5k
        strm->adler = ADLER32_INITIAL_VALUE;
826
36.5k
        s->status = BUSY_STATE;
827
828
        /* Compression must start with an empty pending buffer */
829
36.5k
        PREFIX(flush_pending)(strm);
830
36.5k
        if (s->pending != 0) {
831
18
            s->last_flush = -1;
832
18
            return Z_OK;
833
18
        }
834
36.5k
    }
835
36.5k
#ifdef GZIP
836
36.5k
    if (s->status == GZIP_STATE) {
837
        /* gzip header */
838
0
        FUNCTABLE_CALL(crc32_fold_reset)(&s->crc_fold);
839
0
        put_byte(s, 31);
840
0
        put_byte(s, 139);
841
0
        put_byte(s, 8);
842
0
        if (s->gzhead == NULL) {
843
0
            put_uint32(s, 0);
844
0
            put_byte(s, 0);
845
0
            put_byte(s, s->level == 9 ? 2 :
846
0
                     (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 4 : 0));
847
0
            put_byte(s, OS_CODE);
848
0
            s->status = BUSY_STATE;
849
850
            /* Compression must start with an empty pending buffer */
851
0
            PREFIX(flush_pending)(strm);
852
0
            if (s->pending != 0) {
853
0
                s->last_flush = -1;
854
0
                return Z_OK;
855
0
            }
856
0
        } else {
857
0
            put_byte(s, (s->gzhead->text ? 1 : 0) +
858
0
                     (s->gzhead->hcrc ? 2 : 0) +
859
0
                     (s->gzhead->extra == NULL ? 0 : 4) +
860
0
                     (s->gzhead->name == NULL ? 0 : 8) +
861
0
                     (s->gzhead->comment == NULL ? 0 : 16)
862
0
                     );
863
0
            put_uint32(s, s->gzhead->time);
864
0
            put_byte(s, s->level == 9 ? 2 : (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? 4 : 0));
865
0
            put_byte(s, s->gzhead->os & 0xff);
866
0
            if (s->gzhead->extra != NULL)
867
0
                put_short(s, (uint16_t)s->gzhead->extra_len);
868
0
            if (s->gzhead->hcrc)
869
0
                strm->adler = PREFIX(crc32)(strm->adler, s->pending_buf, s->pending);
870
0
            s->gzindex = 0;
871
0
            s->status = EXTRA_STATE;
872
0
        }
873
0
    }
874
36.5k
    if (s->status == EXTRA_STATE) {
875
0
        if (s->gzhead->extra != NULL) {
876
0
            uint32_t beg = s->pending;   /* start of bytes to update crc */
877
0
            uint32_t left = (s->gzhead->extra_len & 0xffff) - s->gzindex;
878
879
0
            while (s->pending + left > s->pending_buf_size) {
880
0
                uint32_t copy = s->pending_buf_size - s->pending;
881
0
                memcpy(s->pending_buf + s->pending, s->gzhead->extra + s->gzindex, copy);
882
0
                s->pending = s->pending_buf_size;
883
0
                HCRC_UPDATE(beg);
884
0
                s->gzindex += copy;
885
0
                PREFIX(flush_pending)(strm);
886
0
                if (s->pending != 0) {
887
0
                    s->last_flush = -1;
888
0
                    return Z_OK;
889
0
                }
890
0
                beg = 0;
891
0
                left -= copy;
892
0
            }
893
0
            memcpy(s->pending_buf + s->pending, s->gzhead->extra + s->gzindex, left);
894
0
            s->pending += left;
895
0
            HCRC_UPDATE(beg);
896
0
            s->gzindex = 0;
897
0
        }
898
0
        s->status = NAME_STATE;
899
0
    }
900
36.5k
    if (s->status == NAME_STATE) {
901
0
        if (s->gzhead->name != NULL) {
902
0
            uint32_t beg = s->pending;   /* start of bytes to update crc */
903
0
            unsigned char val;
904
905
0
            do {
906
0
                if (s->pending == s->pending_buf_size) {
907
0
                    HCRC_UPDATE(beg);
908
0
                    PREFIX(flush_pending)(strm);
909
0
                    if (s->pending != 0) {
910
0
                        s->last_flush = -1;
911
0
                        return Z_OK;
912
0
                    }
913
0
                    beg = 0;
914
0
                }
915
0
                val = s->gzhead->name[s->gzindex++];
916
0
                put_byte(s, val);
917
0
            } while (val != 0);
918
0
            HCRC_UPDATE(beg);
919
0
            s->gzindex = 0;
920
0
        }
921
0
        s->status = COMMENT_STATE;
922
0
    }
923
36.5k
    if (s->status == COMMENT_STATE) {
924
0
        if (s->gzhead->comment != NULL) {
925
0
            uint32_t beg = s->pending;  /* start of bytes to update crc */
926
0
            unsigned char val;
927
928
0
            do {
929
0
                if (s->pending == s->pending_buf_size) {
930
0
                    HCRC_UPDATE(beg);
931
0
                    PREFIX(flush_pending)(strm);
932
0
                    if (s->pending != 0) {
933
0
                        s->last_flush = -1;
934
0
                        return Z_OK;
935
0
                    }
936
0
                    beg = 0;
937
0
                }
938
0
                val = s->gzhead->comment[s->gzindex++];
939
0
                put_byte(s, val);
940
0
            } while (val != 0);
941
0
            HCRC_UPDATE(beg);
942
0
        }
943
0
        s->status = HCRC_STATE;
944
0
    }
945
36.5k
    if (s->status == HCRC_STATE) {
946
0
        if (s->gzhead->hcrc) {
947
0
            if (s->pending + 2 > s->pending_buf_size) {
948
0
                PREFIX(flush_pending)(strm);
949
0
                if (s->pending != 0) {
950
0
                    s->last_flush = -1;
951
0
                    return Z_OK;
952
0
                }
953
0
            }
954
0
            put_short(s, (uint16_t)strm->adler);
955
0
            FUNCTABLE_CALL(crc32_fold_reset)(&s->crc_fold);
956
0
        }
957
0
        s->status = BUSY_STATE;
958
959
        /* Compression must start with an empty pending buffer */
960
0
        flush_pending_inline(strm);
961
0
        if (s->pending != 0) {
962
0
            s->last_flush = -1;
963
0
            return Z_OK;
964
0
        }
965
0
    }
966
36.5k
#endif
967
968
    /* Start a new block or continue the current one.
969
     */
970
36.5k
    if (strm->avail_in != 0 || s->lookahead != 0 || (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
971
36.5k
        block_state bstate;
972
973
36.5k
        bstate = DEFLATE_HOOK(strm, flush, &bstate) ? bstate :  /* hook for IBM Z DFLTCC */
974
36.5k
                 s->level == 0 ? deflate_stored(s, flush) :
975
36.5k
                 s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
976
36.5k
                 s->strategy == Z_RLE ? deflate_rle(s, flush) :
977
36.5k
                 (*(configuration_table[s->level].func))(s, flush);
978
979
36.5k
        if (bstate == finish_started || bstate == finish_done) {
980
36.5k
            s->status = FINISH_STATE;
981
36.5k
        }
982
36.5k
        if (bstate == need_more || bstate == finish_started) {
983
7.98k
            if (strm->avail_out == 0) {
984
7.98k
                s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
985
7.98k
            }
986
7.98k
            return Z_OK;
987
            /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
988
             * of deflate should use the same flush parameter to make sure
989
             * that the flush is complete. So we don't have to output an
990
             * empty block here, this will be done at next call. This also
991
             * ensures that for a very small output buffer, we emit at most
992
             * one empty block.
993
             */
994
7.98k
        }
995
28.5k
        if (bstate == block_done) {
996
0
            if (flush == Z_PARTIAL_FLUSH) {
997
0
                zng_tr_align(s);
998
0
            } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
999
0
                zng_tr_stored_block(s, (char*)0, 0L, 0);
1000
                /* For a full flush, this empty block will be recognized
1001
                 * as a special marker by inflate_sync().
1002
                 */
1003
0
                if (flush == Z_FULL_FLUSH) {
1004
0
                    CLEAR_HASH(s);             /* forget history */
1005
0
                    if (s->lookahead == 0) {
1006
0
                        s->strstart = 0;
1007
0
                        s->block_start = 0;
1008
0
                        s->insert = 0;
1009
0
                    }
1010
0
                }
1011
0
            }
1012
0
            PREFIX(flush_pending)(strm);
1013
0
            if (strm->avail_out == 0) {
1014
0
                s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
1015
0
                return Z_OK;
1016
0
            }
1017
0
        }
1018
28.5k
    }
1019
1020
28.5k
    if (flush != Z_FINISH)
1021
0
        return Z_OK;
1022
1023
    /* Write the trailer */
1024
28.5k
#ifdef GZIP
1025
28.5k
    if (s->wrap == 2) {
1026
0
        strm->adler = FUNCTABLE_CALL(crc32_fold_final)(&s->crc_fold);
1027
1028
0
        put_uint32(s, strm->adler);
1029
0
        put_uint32(s, (uint32_t)strm->total_in);
1030
0
    } else
1031
28.5k
#endif
1032
28.5k
    {
1033
28.5k
        if (s->wrap == 1)
1034
28.5k
            put_uint32_msb(s, strm->adler);
1035
28.5k
    }
1036
28.5k
    flush_pending_inline(strm);
1037
    /* If avail_out is zero, the application will call deflate again
1038
     * to flush the rest.
1039
     */
1040
28.5k
    if (s->wrap > 0)
1041
28.5k
        s->wrap = -s->wrap; /* write the trailer only once! */
1042
28.5k
    if (s->pending == 0) {
1043
27.9k
        Assert(s->bi_valid == 0, "bi_buf not flushed");
1044
27.9k
        return Z_STREAM_END;
1045
27.9k
    }
1046
639
    return Z_OK;
1047
28.5k
}
1048
1049
/* ========================================================================= */
1050
36.5k
int32_t Z_EXPORT PREFIX(deflateEnd)(PREFIX3(stream) *strm) {
1051
36.5k
    if (deflateStateCheck(strm))
1052
0
        return Z_STREAM_ERROR;
1053
1054
36.5k
    int32_t status = strm->state->status;
1055
1056
    /* Free allocated buffers */
1057
36.5k
    free_deflate(strm);
1058
1059
36.5k
    return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
1060
36.5k
}
1061
1062
/* =========================================================================
1063
 * Copy the source state to the destination state.
1064
 */
1065
0
int32_t Z_EXPORT PREFIX(deflateCopy)(PREFIX3(stream) *dest, PREFIX3(stream) *source) {
1066
0
    deflate_state *ds;
1067
0
    deflate_state *ss;
1068
1069
0
    if (deflateStateCheck(source) || dest == NULL)
1070
0
        return Z_STREAM_ERROR;
1071
1072
0
    ss = source->state;
1073
1074
0
    memcpy((void *)dest, (void *)source, sizeof(PREFIX3(stream)));
1075
1076
0
    deflate_allocs *alloc_bufs = alloc_deflate(dest, ss->w_bits, ss->lit_bufsize);
1077
0
    if (alloc_bufs == NULL)
1078
0
        return Z_MEM_ERROR;
1079
1080
0
    ds = alloc_bufs->state;
1081
1082
0
    dest->state = (struct internal_state *) ds;
1083
0
    memcpy(ds, ss, sizeof(deflate_state));
1084
0
    ds->strm = dest;
1085
1086
0
    ds->alloc_bufs = alloc_bufs;
1087
0
    ds->window = alloc_bufs->window;
1088
0
    ds->prev = alloc_bufs->prev;
1089
0
    ds->head = alloc_bufs->head;
1090
0
    ds->pending_buf = alloc_bufs->pending_buf;
1091
1092
0
    if (ds->window == NULL || ds->prev == NULL || ds->head == NULL || ds->pending_buf == NULL) {
1093
0
        PREFIX(deflateEnd)(dest);
1094
0
        return Z_MEM_ERROR;
1095
0
    }
1096
1097
0
    memcpy(ds->window, ss->window, DEFLATE_ADJUST_WINDOW_SIZE(ds->w_size * 2 * sizeof(unsigned char)));
1098
0
    memcpy((void *)ds->prev, (void *)ss->prev, ds->w_size * sizeof(Pos));
1099
0
    memcpy((void *)ds->head, (void *)ss->head, HASH_SIZE * sizeof(Pos));
1100
0
    memcpy(ds->pending_buf, ss->pending_buf, ds->lit_bufsize * LIT_BUFS);
1101
1102
0
    ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
1103
0
#ifdef LIT_MEM
1104
0
    ds->d_buf = (uint16_t *)(ds->pending_buf + (ds->lit_bufsize << 1));
1105
0
    ds->l_buf = ds->pending_buf + (ds->lit_bufsize << 2);
1106
#else
1107
    ds->sym_buf = ds->pending_buf + ds->lit_bufsize;
1108
#endif
1109
1110
0
    ds->l_desc.dyn_tree = ds->dyn_ltree;
1111
0
    ds->d_desc.dyn_tree = ds->dyn_dtree;
1112
0
    ds->bl_desc.dyn_tree = ds->bl_tree;
1113
1114
0
    return Z_OK;
1115
0
}
1116
1117
/* ===========================================================================
1118
 * Set longest match variables based on level configuration
1119
 */
1120
36.5k
static void lm_set_level(deflate_state *s, int level) {
1121
36.5k
    s->max_lazy_match   = configuration_table[level].max_lazy;
1122
36.5k
    s->good_match       = configuration_table[level].good_length;
1123
36.5k
    s->nice_match       = configuration_table[level].nice_length;
1124
36.5k
    s->max_chain_length = configuration_table[level].max_chain;
1125
1126
    /* Use rolling hash for deflate_slow algorithm with level 9. It allows us to
1127
     * properly lookup different hash chains to speed up longest_match search. Since hashing
1128
     * method changes depending on the level we cannot put this into functable. */
1129
36.5k
    if (s->max_chain_length > 1024) {
1130
5.60k
        s->update_hash = &update_hash_roll;
1131
5.60k
        s->insert_string = &insert_string_roll;
1132
5.60k
        s->quick_insert_string = &quick_insert_string_roll;
1133
30.9k
    } else {
1134
30.9k
        s->update_hash = update_hash;
1135
30.9k
        s->insert_string = insert_string;
1136
30.9k
        s->quick_insert_string = quick_insert_string;
1137
30.9k
    }
1138
1139
36.5k
    s->level = level;
1140
36.5k
}
1141
1142
/* ===========================================================================
1143
 * Initialize the "longest match" routines for a new zlib stream
1144
 */
1145
36.5k
static void lm_init(deflate_state *s) {
1146
36.5k
    s->window_size = 2 * s->w_size;
1147
1148
36.5k
    CLEAR_HASH(s);
1149
1150
    /* Set the default configuration parameters:
1151
     */
1152
36.5k
    lm_set_level(s, s->level);
1153
1154
36.5k
    s->strstart = 0;
1155
36.5k
    s->block_start = 0;
1156
36.5k
    s->lookahead = 0;
1157
36.5k
    s->insert = 0;
1158
36.5k
    s->prev_length = 0;
1159
36.5k
    s->match_available = 0;
1160
36.5k
    s->match_start = 0;
1161
36.5k
    s->ins_h = 0;
1162
36.5k
}
1163
1164
/* ===========================================================================
1165
 * Fill the window when the lookahead becomes insufficient.
1166
 * Updates strstart and lookahead.
1167
 *
1168
 * IN assertion: lookahead < MIN_LOOKAHEAD
1169
 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1170
 *    At least one byte has been read, or avail_in == 0; reads are
1171
 *    performed for at least two bytes (required for the zip translate_eol
1172
 *    option -- not supported here).
1173
 */
1174
1175
5.03M
void Z_INTERNAL PREFIX(fill_window)(deflate_state *s) {
1176
5.03M
    unsigned n;
1177
5.03M
    unsigned int more;    /* Amount of free space at the end of the window. */
1178
5.03M
    unsigned int wsize = s->w_size;
1179
1180
5.03M
    Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
1181
1182
5.03M
    do {
1183
5.03M
        more = s->window_size - s->lookahead - s->strstart;
1184
1185
        /* If the window is almost full and there is insufficient lookahead,
1186
         * move the upper half to the lower one to make room in the upper half.
1187
         */
1188
5.03M
        if (s->strstart >= wsize+MAX_DIST(s)) {
1189
0
            memcpy(s->window, s->window+wsize, (unsigned)wsize);
1190
0
            if (s->match_start >= wsize) {
1191
0
                s->match_start -= wsize;
1192
0
            } else {
1193
0
                s->match_start = 0;
1194
0
                s->prev_length = 0;
1195
0
            }
1196
0
            s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
1197
0
            s->block_start -= (int)wsize;
1198
0
            if (s->insert > s->strstart)
1199
0
                s->insert = s->strstart;
1200
0
            FUNCTABLE_CALL(slide_hash)(s);
1201
0
            more += wsize;
1202
0
        }
1203
5.03M
        if (s->strm->avail_in == 0)
1204
4.99M
            break;
1205
1206
        /* If there was no sliding:
1207
         *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1208
         *    more == window_size - lookahead - strstart
1209
         * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1210
         * => more >= window_size - 2*WSIZE + 2
1211
         * In the BIG_MEM or MMAP case (not yet supported),
1212
         *   window_size == input_size + MIN_LOOKAHEAD  &&
1213
         *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1214
         * Otherwise, window_size == 2*WSIZE so more >= 2.
1215
         * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1216
         */
1217
36.5k
        Assert(more >= 2, "more < 2");
1218
1219
36.5k
        n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1220
36.5k
        s->lookahead += n;
1221
1222
        /* Initialize the hash value now that we have some input: */
1223
36.5k
        if (s->lookahead + s->insert >= STD_MIN_MATCH) {
1224
36.4k
            unsigned int str = s->strstart - s->insert;
1225
36.4k
            if (UNLIKELY(s->max_chain_length > 1024)) {
1226
5.58k
                s->ins_h = s->update_hash(s->window[str], s->window[str+1]);
1227
30.8k
            } else if (str >= 1) {
1228
0
                s->quick_insert_string(s, str + 2 - STD_MIN_MATCH);
1229
0
            }
1230
36.4k
            unsigned int count = s->insert;
1231
36.4k
            if (UNLIKELY(s->lookahead == 1)) {
1232
0
                count -= 1;
1233
0
            }
1234
36.4k
            if (count > 0) {
1235
0
                s->insert_string(s, str, count);
1236
0
                s->insert -= count;
1237
0
            }
1238
36.4k
        }
1239
        /* If the whole input has less than STD_MIN_MATCH bytes, ins_h is garbage,
1240
         * but this is not important since only literal bytes will be emitted.
1241
         */
1242
36.5k
    } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1243
1244
    /* If the WIN_INIT bytes after the end of the current data have never been
1245
     * written, then zero those bytes in order to avoid memory check reports of
1246
     * the use of uninitialized (or uninitialised as Julian writes) bytes by
1247
     * the longest match routines.  Update the high water mark for the next
1248
     * time through here.  WIN_INIT is set to STD_MAX_MATCH since the longest match
1249
     * routines allow scanning to strstart + STD_MAX_MATCH, ignoring lookahead.
1250
     */
1251
5.03M
    if (s->high_water < s->window_size) {
1252
5.03M
        unsigned int curr = s->strstart + s->lookahead;
1253
5.03M
        unsigned int init;
1254
1255
5.03M
        if (s->high_water < curr) {
1256
            /* Previous high water mark below current data -- zero WIN_INIT
1257
             * bytes or up to end of window, whichever is less.
1258
             */
1259
36.5k
            init = s->window_size - curr;
1260
36.5k
            if (init > WIN_INIT)
1261
36.5k
                init = WIN_INIT;
1262
36.5k
            memset(s->window + curr, 0, init);
1263
36.5k
            s->high_water = curr + init;
1264
4.99M
        } else if (s->high_water < curr + WIN_INIT) {
1265
            /* High water mark at or above current data, but below current data
1266
             * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
1267
             * to end of window, whichever is less.
1268
             */
1269
0
            init = curr + WIN_INIT - s->high_water;
1270
0
            if (init > s->window_size - s->high_water)
1271
0
                init = s->window_size - s->high_water;
1272
0
            memset(s->window + s->high_water, 0, init);
1273
0
            s->high_water += init;
1274
0
        }
1275
5.03M
    }
1276
1277
5.03M
    Assert((unsigned long)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1278
5.03M
           "not enough room for search");
1279
5.03M
}
1280
1281
#ifndef ZLIB_COMPAT
1282
/* =========================================================================
1283
 * Checks whether buffer size is sufficient and whether this parameter is a duplicate.
1284
 */
1285
0
static int32_t deflateSetParamPre(zng_deflate_param_value **out, size_t min_size, zng_deflate_param_value *param) {
1286
0
    int32_t buf_error = param->size < min_size;
1287
1288
0
    if (*out != NULL) {
1289
0
        (*out)->status = Z_BUF_ERROR;
1290
0
        buf_error = 1;
1291
0
    }
1292
0
    *out = param;
1293
0
    return buf_error;
1294
0
}
1295
1296
/* ========================================================================= */
1297
0
int32_t Z_EXPORT zng_deflateSetParams(zng_stream *strm, zng_deflate_param_value *params, size_t count) {
1298
0
    size_t i;
1299
0
    deflate_state *s;
1300
0
    zng_deflate_param_value *new_level = NULL;
1301
0
    zng_deflate_param_value *new_strategy = NULL;
1302
0
    zng_deflate_param_value *new_reproducible = NULL;
1303
0
    int param_buf_error;
1304
0
    int version_error = 0;
1305
0
    int buf_error = 0;
1306
0
    int stream_error = 0;
1307
1308
    /* Initialize the statuses. */
1309
0
    for (i = 0; i < count; i++)
1310
0
        params[i].status = Z_OK;
1311
1312
    /* Check whether the stream state is consistent. */
1313
0
    if (deflateStateCheck(strm))
1314
0
        return Z_STREAM_ERROR;
1315
0
    s = strm->state;
1316
1317
    /* Check buffer sizes and detect duplicates. */
1318
0
    for (i = 0; i < count; i++) {
1319
0
        switch (params[i].param) {
1320
0
            case Z_DEFLATE_LEVEL:
1321
0
                param_buf_error = deflateSetParamPre(&new_level, sizeof(int), &params[i]);
1322
0
                break;
1323
0
            case Z_DEFLATE_STRATEGY:
1324
0
                param_buf_error = deflateSetParamPre(&new_strategy, sizeof(int), &params[i]);
1325
0
                break;
1326
0
            case Z_DEFLATE_REPRODUCIBLE:
1327
0
                param_buf_error = deflateSetParamPre(&new_reproducible, sizeof(int), &params[i]);
1328
0
                break;
1329
0
            default:
1330
0
                params[i].status = Z_VERSION_ERROR;
1331
0
                version_error = 1;
1332
0
                param_buf_error = 0;
1333
0
                break;
1334
0
        }
1335
0
        if (param_buf_error) {
1336
0
            params[i].status = Z_BUF_ERROR;
1337
0
            buf_error = 1;
1338
0
        }
1339
0
    }
1340
    /* Exit early if small buffers or duplicates are detected. */
1341
0
    if (buf_error)
1342
0
        return Z_BUF_ERROR;
1343
1344
    /* Apply changes, remember if there were errors. */
1345
0
    if (new_level != NULL || new_strategy != NULL) {
1346
0
        int ret = PREFIX(deflateParams)(strm, new_level == NULL ? s->level : *(int *)new_level->buf,
1347
0
                                        new_strategy == NULL ? s->strategy : *(int *)new_strategy->buf);
1348
0
        if (ret != Z_OK) {
1349
0
            if (new_level != NULL)
1350
0
                new_level->status = Z_STREAM_ERROR;
1351
0
            if (new_strategy != NULL)
1352
0
                new_strategy->status = Z_STREAM_ERROR;
1353
0
            stream_error = 1;
1354
0
        }
1355
0
    }
1356
0
    if (new_reproducible != NULL) {
1357
0
        int val = *(int *)new_reproducible->buf;
1358
0
        if (DEFLATE_CAN_SET_REPRODUCIBLE(strm, val)) {
1359
0
            s->reproducible = val;
1360
0
        } else {
1361
0
            new_reproducible->status = Z_STREAM_ERROR;
1362
0
            stream_error = 1;
1363
0
        }
1364
0
    }
1365
1366
    /* Report version errors only if there are no real errors. */
1367
0
    return stream_error ? Z_STREAM_ERROR : (version_error ? Z_VERSION_ERROR : Z_OK);
1368
0
}
1369
1370
/* ========================================================================= */
1371
0
int32_t Z_EXPORT zng_deflateGetParams(zng_stream *strm, zng_deflate_param_value *params, size_t count) {
1372
0
    deflate_state *s;
1373
0
    size_t i;
1374
0
    int32_t buf_error = 0;
1375
0
    int32_t version_error = 0;
1376
1377
    /* Initialize the statuses. */
1378
0
    for (i = 0; i < count; i++)
1379
0
        params[i].status = Z_OK;
1380
1381
    /* Check whether the stream state is consistent. */
1382
0
    if (deflateStateCheck(strm))
1383
0
        return Z_STREAM_ERROR;
1384
0
    s = strm->state;
1385
1386
0
    for (i = 0; i < count; i++) {
1387
0
        switch (params[i].param) {
1388
0
            case Z_DEFLATE_LEVEL:
1389
0
                if (params[i].size < sizeof(int))
1390
0
                    params[i].status = Z_BUF_ERROR;
1391
0
                else
1392
0
                    *(int *)params[i].buf = s->level;
1393
0
                break;
1394
0
            case Z_DEFLATE_STRATEGY:
1395
0
                if (params[i].size < sizeof(int))
1396
0
                    params[i].status = Z_BUF_ERROR;
1397
0
                else
1398
0
                    *(int *)params[i].buf = s->strategy;
1399
0
                break;
1400
0
            case Z_DEFLATE_REPRODUCIBLE:
1401
0
                if (params[i].size < sizeof(int))
1402
0
                    params[i].status = Z_BUF_ERROR;
1403
0
                else
1404
0
                    *(int *)params[i].buf = s->reproducible;
1405
0
                break;
1406
0
            default:
1407
0
                params[i].status = Z_VERSION_ERROR;
1408
0
                version_error = 1;
1409
0
                break;
1410
0
        }
1411
0
        if (params[i].status == Z_BUF_ERROR)
1412
0
            buf_error = 1;
1413
0
    }
1414
0
    return buf_error ? Z_BUF_ERROR : (version_error ? Z_VERSION_ERROR : Z_OK);
1415
0
}
1416
#endif