Coverage Report

Created: 2026-04-12 06:41

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