Coverage Report

Created: 2025-12-14 06:55

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