Coverage Report

Created: 2026-10-17 07:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/zlib-ng/trees.c
Line
Count
Source
1
/* trees.c -- output deflated data using Huffman coding
2
 * Copyright (C) 1995-2026 Jean-loup Gailly
3
 * detect_data_type() function provided freely by Cosmin Truta, 2006
4
 * For conditions of distribution and use, see copyright notice in zlib.h
5
 */
6
7
/*
8
 *  ALGORITHM
9
 *
10
 *      The "deflation" process uses several Huffman trees. The more
11
 *      common source values are represented by shorter bit sequences.
12
 *
13
 *      Each code tree is stored in a compressed form which is itself
14
 * a Huffman encoding of the lengths of all the code strings (in
15
 * ascending order by source values).  The actual code strings are
16
 * reconstructed from the lengths in the inflate process, as described
17
 * in the deflate specification.
18
 *
19
 *  REFERENCES
20
 *
21
 *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
22
 *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
23
 *
24
 *      Storer, James A.
25
 *          Data Compression:  Methods and Theory, pp. 49-50.
26
 *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
27
 *
28
 *      Sedgewick, R.
29
 *          Algorithms, p290.
30
 *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
31
 */
32
33
#include "zbuild.h"
34
#include "deflate.h"
35
#include "deflate_p.h"
36
#include "trees.h"
37
#include "trees_emit.h"
38
#include "trees_tbl.h"
39
40
/* The lengths of the bit length codes are sent in order of decreasing
41
 * probability, to avoid transmitting the lengths for unused bit length codes.
42
 */
43
44
/* ===========================================================================
45
 * Local data. These are initialized only once.
46
 */
47
48
struct static_tree_desc_s {
49
    const ct_data *static_tree; /* static tree or NULL */
50
    const int     *extra_bits;  /* extra bits for each code or NULL */
51
    int            extra_base;  /* base index for extra_bits */
52
    int            elems;       /* max number of elements in the tree */
53
    unsigned int   max_length;  /* max bit length for the codes */
54
};
55
56
static const static_tree_desc  static_l_desc =
57
{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
58
59
static const static_tree_desc  static_d_desc =
60
{static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
61
62
static const static_tree_desc  static_bl_desc =
63
{(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
64
65
/* ===========================================================================
66
 * Local (static) routines in this file.
67
 */
68
69
static void init_block       (deflate_state *s);
70
static void pq_radix_pass    (const uint32_t *src, uint32_t *dst, int n, int shift, uint16_t *count);
71
static void build_tree       (deflate_state *s, tree_desc *desc);
72
static void gen_bitlen       (deflate_state *s, tree_desc *desc, const uint32_t *sorted, int nleaves, int root);
73
static void scan_tree        (deflate_state *s, ct_data *tree, int max_code);
74
static void send_tree        (deflate_state *s, ct_data *tree, int max_code);
75
static int  build_bl_tree    (deflate_state *s);
76
static void send_all_trees   (deflate_state *s, int lcodes, int dcodes, int blcodes);
77
static void compress_block   (deflate_state *s, const ct_data *ltree, const ct_data *dtree);
78
static int  detect_data_type (deflate_state *s);
79
80
/* ===========================================================================
81
 * Initialize the tree data structures for a new zlib stream.
82
 */
83
11.7k
void Z_INTERNAL zng_tr_init(deflate_state *s) {
84
11.7k
    s->l_desc.dyn_tree = s->dyn_ltree;
85
11.7k
    s->l_desc.stat_desc = &static_l_desc;
86
87
11.7k
    s->d_desc.dyn_tree = s->dyn_dtree;
88
11.7k
    s->d_desc.stat_desc = &static_d_desc;
89
90
11.7k
    s->bl_desc.dyn_tree = s->bl_tree;
91
11.7k
    s->bl_desc.stat_desc = &static_bl_desc;
92
93
11.7k
    s->bi_buf = 0;
94
11.7k
    s->bi_valid = 0;
95
11.7k
    s->bi_used = 0;
96
#ifdef ZLIB_DEBUG
97
    s->compressed_len = 0L;
98
    s->bits_sent = 0L;
99
#endif
100
101
    /* Initialize the first block of the first file: */
102
11.7k
    init_block(s);
103
11.7k
}
104
105
/* ===========================================================================
106
 * Initialize a new block.
107
 */
108
38.5k
static void init_block(deflate_state *s) {
109
38.5k
    int n; /* iterates over tree elements */
110
111
    /* Initialize the trees. */
112
11.0M
    for (n = 0; n < L_CODES;  n++)
113
11.0M
        s->dyn_ltree[n].Freq = 0;
114
1.19M
    for (n = 0; n < D_CODES;  n++)
115
1.15M
        s->dyn_dtree[n].Freq = 0;
116
771k
    for (n = 0; n < BL_CODES; n++)
117
732k
        s->bl_tree[n].Freq = 0;
118
119
38.5k
    s->dyn_ltree[END_BLOCK].Freq = 1;
120
38.5k
    s->opt_len = s->static_len = 0;
121
38.5k
    s->sym_next = 0;
122
38.5k
}
123
124
/* Queue entries pack freq above the node index, so a single 32-bit compare orders nodes by
125
 * frequency, breaking ties by node index: leaves first, then internal nodes in creation order,
126
 * which keeps the worst-case code length small. */
127
29.9M
#define PQ_NODE_BITS 10
128
8.55M
#define pq_pack(freq, node) (((uint32_t)(freq) << PQ_NODE_BITS) | (unsigned)(node))
129
12.8M
#define pq_node(e)  ((int)((e) & ((1u << PQ_NODE_BITS) - 1)))
130
8.47M
#define pq_freq(e)  ((e) >> PQ_NODE_BITS)
131
132
/* ===========================================================================
133
 * One stable counting-sort pass over an 8-bit digit of the packed entries.
134
 * count holds the digit histogram at offset +1, accumulated during the leaf
135
 * scan, and is turned into running start positions here. Used by build_tree().
136
 */
137
73.1k
static void pq_radix_pass(const uint32_t *src, uint32_t *dst, int n, int shift, uint16_t *count) {
138
73.1k
    int i;
139
140
18.8M
    for (i = 1; i <= 256; i++)
141
18.7M
        count[i] = (uint16_t)(count[i] + count[i-1]);
142
6.21M
    for (i = 0; i < n; i++)
143
6.14M
        dst[count[(src[i] >> shift) & 0xFF]++] = src[i];
144
73.1k
}
145
146
/* ===========================================================================
147
 * Take the smaller of the two queue heads: the next unused leaf, or the next
148
 * created internal node. Used by build_tree().
149
 */
150
static inline uint32_t pq_take(const uint32_t *leaves, int *li, int nleaves,
151
8.47M
                               const uint32_t *internals, int *ihead, int itail) {
152
8.47M
    if (*li < nleaves && (*ihead == itail || leaves[*li] < internals[*ihead]))
153
4.31M
        return leaves[(*li)++];
154
4.15M
    return internals[(*ihead)++];
155
8.47M
}
156
157
/* ===========================================================================
158
 * Construct one Huffman tree and assigns the code bit strings and lengths.
159
 * Update the total bit length for the current block.
160
 * IN assertion: the field freq is set for all tree elements.
161
 * OUT assertions: the fields len and code are set to the optimal bit length
162
 *     and corresponding code. The length opt_len is updated; static_len is
163
 *     also updated if stree is not null. The field max_code is set.
164
 */
165
80.3k
static void build_tree(deflate_state *s, tree_desc *desc) {
166
    /* desc: the tree descriptor */
167
80.3k
    ct_data *tree         = desc->dyn_tree;
168
80.3k
    const ct_data *stree  = desc->stat_desc->static_tree;
169
80.3k
    int elems             = desc->stat_desc->elems;
170
80.3k
    int n, m;          /* iterate over heap elements */
171
80.3k
    int max_code = -1; /* largest code with non zero frequency */
172
80.3k
    int node;          /* new node being created */
173
80.3k
    int nleaves = 0;
174
80.3k
    int li = 0, ihead = 0, itail = 0;  /* queue positions for leaves and internal nodes */
175
80.3k
    int merges;
176
80.3k
    uint32_t *leaves = s->pq_leaves;   /* packed leaf entries, sorted by frequency */
177
80.3k
    uint32_t *scratch = s->pq_scratch; /* radix buffer, then FIFO of created internal nodes */
178
80.3k
    uint32_t *sorted = leaves;         /* sorted leaves, in scratch after a single pass */
179
80.3k
    uint32_t *internals = scratch;     /* internal node FIFO, in whichever buffer is free */
180
80.3k
    uint16_t count_lo[257];            /* histogram of the low frequency byte, at offset +1 */
181
80.3k
    uint16_t count_hi[257];            /* histogram of the high frequency byte, at offset +1 */
182
183
80.3k
    memset(count_lo, 0, sizeof(count_lo));
184
80.3k
    memset(count_hi, 0, sizeof(count_hi));
185
9.05M
    for (n = 0; n < elems; n++) {
186
8.97M
        const uint16_t freq = tree[n].Freq;
187
8.97M
        if (freq != 0) {
188
4.28M
            leaves[nleaves++] = pq_pack(freq, n);
189
4.28M
            count_lo[(freq & 0xFF) + 1]++;
190
4.28M
            count_hi[(freq >> 8) + 1]++;
191
4.28M
            max_code = n;
192
4.68M
        } else {
193
4.68M
            tree[n].Len = 0;
194
4.68M
        }
195
8.97M
    }
196
197
    /* The pkzip format requires that at least one distance code exists,
198
     * and that at least one bit should be sent even if there is only one
199
     * possible code. So to avoid special checks later on we force at least
200
     * two codes of non zero frequency.
201
     */
202
107k
    while (nleaves < 2) {
203
26.7k
        node = (max_code < 2 ? ++max_code : 0);
204
26.7k
        leaves[nleaves++] = pq_pack(1, node);
205
26.7k
        tree[node].Freq = 1;
206
26.7k
        s->opt_len--;
207
26.7k
        if (stree)
208
26.7k
            s->static_len -= stree[node].Len;
209
        /* node is 0 or 1 so it does not have extra bits */
210
26.7k
    }
211
80.3k
    desc->max_code = max_code;
212
213
    /* Sort the leaves by packed entry. The scan above appended them in node order, which is
214
     * ascending in the node bits, so two stable passes over the freq bytes finish the sort.
215
     * A forced node can arrive out of node order, but then there are exactly two leaves,
216
     * so the radix path only ever sorts entries the histograms counted. */
217
80.3k
    if (nleaves == 2) {
218
19.4k
        if (leaves[0] > leaves[1]) {
219
6.67k
            const uint32_t t = leaves[0];
220
6.67k
            leaves[0] = leaves[1];
221
6.67k
            leaves[1] = t;
222
6.67k
        }
223
60.8k
    } else if ((int)count_hi[1] == nleaves) {
224
        /* Every frequency fits in one byte, so the first pass already produces the final
225
         * order. The sorted entries then live in scratch, so the internal-node FIFO takes
226
         * over the leaves buffer instead. */
227
48.5k
        pq_radix_pass(leaves, scratch, nleaves, PQ_NODE_BITS, count_lo);
228
48.5k
        sorted = scratch;
229
48.5k
        internals = leaves;
230
48.5k
    } else {
231
        /* Sort by the low then high frequency byte, ending back in leaves. */
232
12.2k
        pq_radix_pass(leaves, scratch, nleaves, PQ_NODE_BITS, count_lo);
233
12.2k
        pq_radix_pass(scratch, leaves, nleaves, PQ_NODE_BITS + 8, count_hi);
234
12.2k
    }
235
236
    /* Construct the Huffman tree by repeatedly combining the least two frequent nodes.
237
     * Sorted leaves and the FIFO of created nodes are each ascending, because merge sums
238
     * never decrease, so the two smallest nodes are always at the queue heads.
239
     */
240
80.3k
    node = elems;              /* next internal node of the tree */
241
4.31M
    for (merges = nleaves - 1; merges > 0; merges--) {
242
        /* en = entry of least frequency, em = entry of next least frequency */
243
4.23M
        const uint32_t en = pq_take(sorted, &li, nleaves, internals, &ihead, itail);
244
4.23M
        const uint32_t em = pq_take(sorted, &li, nleaves, internals, &ihead, itail);
245
4.23M
        n = pq_node(en);
246
4.23M
        m = pq_node(em);
247
248
        /* Create a new node father of n and m. Freq wraps the same way the uint16_t
249
         * state field did. */
250
4.23M
        const uint16_t f = (uint16_t)(pq_freq(en) + pq_freq(em));
251
4.23M
        tree[node].Freq = f;
252
4.23M
        tree[n].Dad = tree[m].Dad = (uint16_t)node;
253
#ifdef DUMP_BL_TREE
254
        if (tree == s->bl_tree) {
255
            fprintf(stderr, "\nnode %d(%d), sons %d(%d) %d(%d)",
256
                    node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
257
        }
258
#endif
259
        /* and append the new node to the internal queue */
260
4.23M
        internals[itail++] = pq_pack(f, node);
261
4.23M
        node++;
262
4.23M
    }
263
264
    /* At this point, the fields freq and dad are set. We can now
265
     * generate the bit lengths.
266
     */
267
80.3k
    gen_bitlen(s, (tree_desc *)desc, sorted, nleaves, node - 1);
268
269
    /* The field len is now set, we can generate the bit codes */
270
80.3k
    gen_codes((ct_data *)tree, max_code, s->bl_count);
271
80.3k
}
272
273
/* ===========================================================================
274
 * Compute the optimal bit lengths for a tree and update the total bit length
275
 * for the current block.
276
 * IN assertion: the fields freq and dad are set, sorted holds the leaves by
277
 *    increasing frequency, and root is the last created node.
278
 * OUT assertions: the field len is set to the optimal bit length, the
279
 *     array bl_count contains the frequencies for each bit length.
280
 *     The length opt_len is updated; static_len is also updated if stree is
281
 *     not null. Used by build_tree().
282
 */
283
80.3k
static void gen_bitlen(deflate_state *s, tree_desc *desc, const uint32_t *sorted, int nleaves, int root) {
284
    /* desc: the tree descriptor */
285
80.3k
    ct_data *tree           = desc->dyn_tree;
286
80.3k
    int elems               = desc->stat_desc->elems;
287
80.3k
    const ct_data *stree    = desc->stat_desc->static_tree;
288
80.3k
    const int *extra        = desc->stat_desc->extra_bits;
289
80.3k
    int base                = desc->stat_desc->extra_base;
290
80.3k
    unsigned int max_length = desc->stat_desc->max_length;
291
80.3k
    int i;              /* index into sorted */
292
80.3k
    int n, m;           /* iterate over the tree elements */
293
80.3k
    unsigned int bits;  /* bit length */
294
80.3k
    int xbits;          /* extra bits */
295
80.3k
    uint16_t f;         /* frequency */
296
80.3k
    int overflow = 0;   /* number of elements with bit length too large */
297
298
1.36M
    for (bits = 0; bits <= MAX_BITS; bits++)
299
1.28M
        s->bl_count[bits] = 0;
300
301
    /* In a first pass, compute the optimal bit lengths (which may
302
     * overflow in the case of the bit length tree).
303
     */
304
80.3k
    tree[root].Len = 0; /* root of the tree */
305
306
    /* Dads are created after their sons, so a descending walk visits each dad first */
307
4.23M
    for (n = root - 1; n >= elems; n--) {
308
4.15M
        bits = tree[tree[n].Dad].Len + 1u;
309
4.15M
        if (bits > max_length){
310
80
            bits = max_length;
311
80
            overflow++;
312
80
        }
313
4.15M
        tree[n].Len = (uint16_t)bits;
314
        /* We overwrite tree[n].Dad which is no longer needed */
315
4.15M
    }
316
317
4.39M
    for (i = 0; i < nleaves; i++) {
318
4.31M
        n = pq_node(sorted[i]);
319
4.31M
        bits = tree[tree[n].Dad].Len + 1u;
320
4.31M
        if (bits > max_length){
321
14.2k
            bits = max_length;
322
14.2k
            overflow++;
323
14.2k
        }
324
4.31M
        tree[n].Len = (uint16_t)bits;
325
326
4.31M
        s->bl_count[bits]++;
327
4.31M
        xbits = 0;
328
4.31M
        if (n >= base)
329
562k
            xbits = extra[n-base];
330
4.31M
        f = tree[n].Freq;
331
4.31M
        s->opt_len += (unsigned int)f * (unsigned int)(bits + xbits);
332
4.31M
        if (stree)
333
4.08M
            s->static_len += (unsigned int)f * (unsigned int)(stree[n].Len + xbits);
334
4.31M
    }
335
80.3k
    if (overflow == 0)
336
78.3k
        return;
337
338
2.06k
    Tracev((stderr, "\nbit length overflow\n"));
339
    /* This happens for example on obj2 and pic of the Calgary corpus */
340
341
    /* Find the first bit length which could increase: */
342
7.15k
    do {
343
7.15k
        bits = max_length - 1;
344
11.5k
        while (s->bl_count[bits] == 0)
345
4.37k
            bits--;
346
7.15k
        s->bl_count[bits]--;       /* move one leaf down the tree */
347
7.15k
        s->bl_count[bits+1] += 2u; /* move one overflow item as its brother */
348
7.15k
        s->bl_count[max_length]--;
349
        /* The brother of the overflow item also moves one step up,
350
         * but this does not affect bl_count[max_length]
351
         */
352
7.15k
        overflow -= 2;
353
7.15k
    } while (overflow > 0);
354
355
    /* Now recompute all bit lengths, scanning in increasing frequency.
356
     * (It is simpler to reconstruct all lengths instead of fixing only
357
     * the wrong ones. This idea is taken from 'ar' written by Haruhiko Okumura.)
358
     */
359
2.06k
    i = 0;
360
19.3k
    for (bits = max_length; bits != 0; bits--) {
361
17.3k
        n = s->bl_count[bits];
362
76.7k
        while (n != 0) {
363
59.4k
            m = pq_node(sorted[i++]);
364
59.4k
            if (tree[m].Len != bits) {
365
4.29k
                Tracev((stderr, "code %d bits %d->%u\n", m, tree[m].Len, bits));
366
4.29k
                s->opt_len += (unsigned int)(bits * tree[m].Freq);
367
4.29k
                s->opt_len -= (unsigned int)(tree[m].Len * tree[m].Freq);
368
4.29k
                tree[m].Len = (uint16_t)bits;
369
4.29k
            }
370
59.4k
            n--;
371
59.4k
        }
372
17.3k
    }
373
2.06k
}
374
375
/* ===========================================================================
376
 * Generate the codes for a given tree and bit counts (which need not be
377
 * optimal).
378
 * IN assertion: the array bl_count contains the bit length statistics for
379
 * the given tree and the field len is set for all tree elements.
380
 * OUT assertion: the field code is set for all tree elements of non
381
 *     zero code length. Used by build_tree().
382
 */
383
80.3k
Z_INTERNAL void gen_codes(ct_data *tree, int max_code, uint16_t *bl_count) {
384
    /* tree: the tree to decorate */
385
    /* max_code: largest code with non zero frequency */
386
    /* bl_count: number of codes at each bit length */
387
80.3k
    uint16_t next_code[MAX_BITS+1];  /* next code value for each bit length */
388
80.3k
    uint16_t code = 0;               /* running code value */
389
80.3k
    int bits;                        /* bit index */
390
80.3k
    int n;                           /* code index */
391
392
    /* The distribution counts are first used to generate the code values
393
     * without bit reversal.
394
     */
395
1.28M
    for (bits = 1; bits <= MAX_BITS; bits++) {
396
1.20M
        code = (code + bl_count[bits-1]) << 1;
397
1.20M
        next_code[bits] = code;
398
1.20M
    }
399
    /* Check that the bit counts in bl_count are consistent. The last code
400
     * must be all ones.
401
     */
402
80.3k
    Assert(code + bl_count[MAX_BITS]-1 == (1 << MAX_BITS)-1, "inconsistent bit counts");
403
80.3k
    Tracev((stderr, "\ngen_codes: max_code %d ", max_code));
404
405
8.05M
    for (n = 0;  n <= max_code; n++) {
406
7.97M
        int len = tree[n].Len;
407
7.97M
        if (len == 0)
408
3.66M
            continue;
409
        /* Now reverse the bits */
410
4.31M
        tree[n].Code = bi_reverse(next_code[len]++, len);
411
412
4.31M
        Tracecv(tree != static_ltree, (stderr, "\nn %3d %c l %2d c %4x (%x) ",
413
4.31M
             n, (isgraph(n & 0xff) ? n : ' '), len, tree[n].Code, next_code[len]-1));
414
4.31M
    }
415
80.3k
}
416
417
/* ===========================================================================
418
 * Scan a literal or distance tree to determine the frequencies of the codes
419
 * in the bit length tree.
420
 */
421
53.5k
static void scan_tree(deflate_state *s, ct_data *tree, int max_code) {
422
    /* tree: the tree to be scanned */
423
    /* max_code: and its largest code of non zero frequency */
424
53.5k
    int n;                     /* iterates over all tree elements */
425
53.5k
    int prevlen = -1;          /* last emitted length */
426
53.5k
    int curlen;                /* length of current code */
427
53.5k
    int nextlen = tree[0].Len; /* length of next code */
428
53.5k
    uint16_t count = 0;        /* repeat count of the current code */
429
53.5k
    uint16_t max_count = 7;    /* max repeat count */
430
53.5k
    uint16_t min_count = 4;    /* min repeat count */
431
432
53.5k
    if (nextlen == 0)
433
6.32k
        max_count = 138, min_count = 3;
434
435
53.5k
    tree[max_code+1].Len = (uint16_t)0xffff; /* guard */
436
437
7.53M
    for (n = 0; n <= max_code; n++) {
438
7.48M
        curlen = nextlen;
439
7.48M
        nextlen = tree[n+1].Len;
440
7.48M
        if (++count < max_count && curlen == nextlen) {
441
5.59M
            continue;
442
5.59M
        } else if (count < min_count) {
443
1.29M
            s->bl_tree[curlen].Freq += count;
444
1.29M
        } else if (curlen != 0) {
445
444k
            if (curlen != prevlen)
446
146k
                s->bl_tree[curlen].Freq++;
447
444k
            s->bl_tree[REP_3_6].Freq++;
448
444k
        } else if (count <= 10) {
449
88.3k
            s->bl_tree[REPZ_3_10].Freq++;
450
88.3k
        } else {
451
59.8k
            s->bl_tree[REPZ_11_138].Freq++;
452
59.8k
        }
453
1.88M
        count = 0;
454
1.88M
        prevlen = curlen;
455
1.88M
        if (nextlen == 0) {
456
285k
            max_count = 138, min_count = 3;
457
1.60M
        } else if (curlen == nextlen) {
458
327k
            max_count = 6, min_count = 3;
459
1.27M
        } else {
460
1.27M
            max_count = 7, min_count = 4;
461
1.27M
        }
462
1.88M
    }
463
53.5k
}
464
465
/* ===========================================================================
466
 * Send a literal or distance tree in compressed form, using the codes in
467
 * bl_tree.
468
 */
469
26.8k
static void send_tree(deflate_state *s, ct_data *tree, int max_code) {
470
    /* tree: the tree to be scanned */
471
    /* max_code and its largest code of non zero frequency */
472
26.8k
    int n;                     /* iterates over all tree elements */
473
26.8k
    int prevlen = -1;          /* last emitted length */
474
26.8k
    int curlen;                /* length of current code */
475
26.8k
    int nextlen = tree[0].Len; /* length of next code */
476
26.8k
    int count = 0;             /* repeat count of the current code */
477
26.8k
    int max_count = 7;         /* max repeat count */
478
26.8k
    int min_count = 4;         /* min repeat count */
479
480
    /* tree[max_code+1].Len = -1; */  /* guard already set */
481
26.8k
    if (nextlen == 0)
482
2.40k
        max_count = 138, min_count = 3;
483
484
    // Temp local variables
485
26.8k
    uint32_t bi_valid = s->bi_valid;
486
26.8k
    uint64_t bi_buf = s->bi_buf;
487
488
3.80M
    for (n = 0; n <= max_code; n++) {
489
3.77M
        curlen = nextlen;
490
3.77M
        nextlen = tree[n+1].Len;
491
3.77M
        if (++count < max_count && curlen == nextlen) {
492
2.50M
            continue;
493
2.50M
        } else if (count < min_count) {
494
1.26M
            do {
495
1.26M
                send_code(s, curlen, s->bl_tree, bi_buf, bi_valid);
496
1.26M
            } while (--count != 0);
497
498
975k
        } else if (curlen != 0) {
499
215k
            if (curlen != prevlen) {
500
104k
                send_code(s, curlen, s->bl_tree, bi_buf, bi_valid);
501
104k
                count--;
502
104k
            }
503
215k
            Assert(count >= 3 && count <= 6, " 3_6?");
504
215k
            send_code(s, REP_3_6, s->bl_tree, bi_buf, bi_valid);
505
215k
            send_bits(s, count-3, 2, bi_buf, bi_valid);
506
507
215k
        } else if (count <= 10) {
508
58.6k
            send_code(s, REPZ_3_10, s->bl_tree, bi_buf, bi_valid);
509
58.6k
            send_bits(s, count-3, 3, bi_buf, bi_valid);
510
511
58.6k
        } else {
512
25.0k
            send_code(s, REPZ_11_138, s->bl_tree, bi_buf, bi_valid);
513
25.0k
            send_bits(s, count-11, 7, bi_buf, bi_valid);
514
25.0k
        }
515
1.27M
        count = 0;
516
1.27M
        prevlen = curlen;
517
1.27M
        if (nextlen == 0) {
518
185k
            max_count = 138, min_count = 3;
519
1.08M
        } else if (curlen == nextlen) {
520
129k
            max_count = 6, min_count = 3;
521
960k
        } else {
522
960k
            max_count = 7, min_count = 4;
523
960k
        }
524
1.27M
    }
525
526
    // Store back temp variables
527
26.8k
    s->bi_buf = bi_buf;
528
26.8k
    s->bi_valid = bi_valid;
529
26.8k
}
530
531
/* ===========================================================================
532
 * Construct the Huffman tree for the bit lengths and return the index in
533
 * bl_order of the last bit length code to send.
534
 */
535
26.7k
static int build_bl_tree(deflate_state *s) {
536
26.7k
    int max_blindex;  /* index of last bit length code of non zero freq */
537
538
    /* Determine the bit length frequencies for literal and distance trees */
539
26.7k
    scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
540
26.7k
    scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
541
542
    /* Build the bit length tree: */
543
26.7k
    build_tree(s, (tree_desc *)(&(s->bl_desc)));
544
    /* opt_len now includes the length of the tree representations, except
545
     * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
546
     */
547
548
    /* Determine the number of bit length codes to send. The pkzip format
549
     * requires that at least 4 bit length codes be sent. (appnote.txt says
550
     * 3 but the actual value used is 4.)
551
     */
552
64.4k
    for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
553
64.4k
        if (s->bl_tree[bl_order[max_blindex]].Len != 0)
554
26.7k
            break;
555
64.4k
    }
556
    /* Update opt_len to include the bit length tree and counts */
557
26.7k
    s->opt_len += 3*((unsigned int)max_blindex+1) + 5+5+4;
558
26.7k
    Tracev((stderr, "\ndyn trees: dyn %u, stat %u", s->opt_len, s->static_len));
559
560
26.7k
    return max_blindex;
561
26.7k
}
562
563
/* ===========================================================================
564
 * Send the header for a block using dynamic Huffman trees: the counts, the
565
 * lengths of the bit length codes, the literal tree and the distance tree.
566
 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
567
 */
568
13.4k
static void send_all_trees(deflate_state *s, int lcodes, int dcodes, int blcodes) {
569
13.4k
    int rank;                    /* index in bl_order */
570
571
13.4k
    Assert(lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
572
13.4k
    Assert(lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, "too many codes");
573
574
    // Temp local variables
575
13.4k
    uint32_t bi_valid = s->bi_valid;
576
13.4k
    uint64_t bi_buf = s->bi_buf;
577
578
13.4k
    Tracev((stderr, "\nbl counts: "));
579
13.4k
    send_bits(s, lcodes-257, 5, bi_buf, bi_valid); /* not +255 as stated in appnote.txt */
580
13.4k
    send_bits(s, dcodes-1,   5, bi_buf, bi_valid);
581
13.4k
    send_bits(s, blcodes-4,  4, bi_buf, bi_valid); /* not -3 as stated in appnote.txt */
582
248k
    for (rank = 0; rank < blcodes; rank++) {
583
235k
        Tracev((stderr, "\nbl code %2u ", bl_order[rank]));
584
235k
        send_bits(s, s->bl_tree[bl_order[rank]].Len, 3, bi_buf, bi_valid);
585
235k
    }
586
13.4k
    Tracev((stderr, "\nbl tree: sent %lu", s->bits_sent));
587
588
    // Store back temp variables
589
13.4k
    s->bi_buf = bi_buf;
590
13.4k
    s->bi_valid = bi_valid;
591
592
13.4k
    send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
593
13.4k
    Tracev((stderr, "\nlit tree: sent %lu", s->bits_sent));
594
595
13.4k
    send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
596
13.4k
    Tracev((stderr, "\ndist tree: sent %lu", s->bits_sent));
597
13.4k
}
598
599
/* ===========================================================================
600
 * Send a stored block
601
 */
602
5.78k
void Z_INTERNAL zng_tr_stored_block(deflate_state *s, unsigned char *buf, uint32_t stored_len, int last) {
603
    /* buf: input block */
604
    /* stored_len: length of input block */
605
    /* last: one if this is the last block for a file */
606
5.78k
    zng_tr_emit_tree(s, STORED_BLOCK, last); /* send block type */
607
5.78k
    zng_tr_emit_align(s);                    /* align on byte boundary */
608
5.78k
    cmpr_bits_align(s);
609
5.78k
    put_short(s, (uint16_t)stored_len);
610
5.78k
    put_short(s, (uint16_t)~stored_len);
611
5.78k
    cmpr_bits_add(s, 32);
612
5.78k
    sent_bits_add(s, 32);
613
5.78k
    if (stored_len) {
614
5.03k
        memcpy(s->pending_buf + s->pending, buf, stored_len);
615
5.03k
        s->pending += stored_len;
616
5.03k
        cmpr_bits_add(s, stored_len << 3);
617
5.03k
        sent_bits_add(s, stored_len << 3);
618
5.03k
    }
619
5.78k
}
620
621
/* ===========================================================================
622
 * Send one empty static block to give enough lookahead for inflate.
623
 * This takes 10 bits, of which 7 may remain in the bit buffer.
624
 */
625
0
void Z_INTERNAL zng_tr_align(deflate_state *s) {
626
0
    zng_tr_emit_tree(s, STATIC_TREES, 0);
627
0
    zng_tr_emit_end_block(s, static_ltree, 0);
628
0
    zng_tr_flush_bits(s);
629
0
}
630
631
/* ===========================================================================
632
 * Determine the best encoding for the current block: dynamic trees, static
633
 * trees or store, and write out the encoded block.
634
 */
635
26.8k
void Z_INTERNAL zng_tr_flush_block(deflate_state *s, unsigned char *buf, uint32_t stored_len, int last) {
636
    /* buf: input block, or NULL if too old */
637
    /* stored_len: length of input block */
638
    /* last: one if this is the last block for a file */
639
26.8k
    unsigned int opt_lenb, static_lenb; /* opt_len and static_len in bytes */
640
26.8k
    int max_blindex = 0;  /* index of last bit length code of non zero freq */
641
642
    /* Build the Huffman trees unless a stored block is forced */
643
26.8k
    if (UNLIKELY(s->sym_next == 0)) {
644
        /* Emit an empty static tree block with no codes */
645
46
        opt_lenb = static_lenb = 0;
646
46
        s->static_len = 7;
647
26.7k
    } else if (s->level > 0) {
648
        /* Check if the file is binary or text */
649
26.7k
        if (s->strm->data_type == Z_UNKNOWN)
650
10.5k
            s->strm->data_type = detect_data_type(s);
651
652
        /* Construct the literal and distance trees */
653
26.7k
        build_tree(s, (tree_desc *)(&(s->l_desc)));
654
26.7k
        Tracev((stderr, "\nlit data: dyn %u, stat %u", s->opt_len, s->static_len));
655
656
26.7k
        build_tree(s, (tree_desc *)(&(s->d_desc)));
657
26.7k
        Tracev((stderr, "\ndist data: dyn %u, stat %u", s->opt_len, s->static_len));
658
        /* At this point, opt_len and static_len are the total bit lengths of
659
         * the compressed block data, excluding the tree representations.
660
         */
661
662
        /* Build the bit length tree for the above two trees, and get the index
663
         * in bl_order of the last bit length code to send.
664
         */
665
26.7k
        max_blindex = build_bl_tree(s);
666
667
        /* Determine the best encoding. Compute the block lengths in bytes. */
668
26.7k
        opt_lenb = (s->opt_len + 3 + 7) >> 3;
669
26.7k
        static_lenb = (s->static_len + 3 + 7) >> 3;
670
671
26.7k
        Tracev((stderr, "\nopt %u(%u) stat %u(%u) stored %u lit %u ",
672
26.7k
                opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
673
26.7k
                s->sym_next / 3));
674
675
26.7k
        if (static_lenb <= opt_lenb || s->strategy == Z_FIXED)
676
9.58k
            opt_lenb = static_lenb;
677
678
26.7k
    } else {
679
0
        Assert(buf != NULL, "lost buf");
680
0
        opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
681
0
    }
682
683
26.8k
    if (stored_len+4 <= opt_lenb && buf != NULL) {
684
        /* 4: two words for the lengths
685
         * The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
686
         * Otherwise we can't have processed more than WSIZE input bytes since
687
         * the last block flush, because compression would have been
688
         * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
689
         * transform a block into a stored block.
690
         */
691
5.00k
        zng_tr_stored_block(s, buf, stored_len, last);
692
693
21.8k
    } else if (static_lenb == opt_lenb) {
694
8.41k
        zng_tr_emit_tree(s, STATIC_TREES, last);
695
8.41k
        compress_block(s, (const ct_data *)static_ltree, (const ct_data *)static_dtree);
696
8.41k
        cmpr_bits_add(s, s->static_len);
697
13.4k
    } else {
698
13.4k
        zng_tr_emit_tree(s, DYN_TREES, last);
699
13.4k
        send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, max_blindex+1);
700
13.4k
        compress_block(s, (const ct_data *)s->dyn_ltree, (const ct_data *)s->dyn_dtree);
701
13.4k
        cmpr_bits_add(s, s->opt_len);
702
13.4k
    }
703
26.8k
    Assert(s->compressed_len == s->bits_sent, "bad compressed size");
704
    /* The above check is made mod 2^32, for files larger than 512 MB
705
     * and unsigned long implemented on 32 bits.
706
     */
707
26.8k
    init_block(s);
708
709
26.8k
    if (last) {
710
10.5k
        zng_tr_emit_align(s);
711
10.5k
    }
712
26.8k
    Tracev((stderr, "\ncomprlen %lu(%lu) ", s->compressed_len>>3, s->compressed_len-7*last));
713
26.8k
}
714
715
/* ===========================================================================
716
 * Send the block data compressed using the given Huffman trees
717
 */
718
#if !defined(LIT_MEM) && OPTIMAL_CMP >= 64
719
/* One 64-bit little-endian load at sx spans the next two symbols' dist fields
720
 * (bits 0..15, 24..39) and literals (bits 16..23, 40..47). The second symbol's dist
721
 * field alone separates a one-literal run from a two-literal one. */
722
61.7M
#define LIT3_DIST1_MASK 0x000000FFFF000000ULL
723
#endif
724
725
21.8k
static void compress_block(deflate_state *s, const ct_data *ltree, const ct_data *dtree) {
726
    /* ltree: literal tree */
727
    /* dtree: distance tree */
728
21.8k
    unsigned dist;      /* distance of matched string */
729
21.8k
    int lc;             /* match length or unmatched char (if dist == 0) */
730
21.8k
    unsigned sx = 0;    /* running index in symbol buffers */
731
732
    /* Local pointers to avoid indirection */
733
21.8k
    const unsigned int sym_next = s->sym_next;
734
#ifdef LIT_MEM
735
    uint16_t *d_buf = s->d_buf;
736
    unsigned char *l_buf = s->l_buf;
737
#else
738
21.8k
    unsigned char *sym_buf = s->sym_buf;
739
21.8k
#endif
740
741
    /* Keep the bit writer state in registers across the entire loop */
742
21.8k
    uint64_t bi_buf = s->bi_buf;
743
21.8k
    uint32_t bi_valid = s->bi_valid;
744
21.8k
    uint32_t pending = s->pending;
745
746
21.8k
    if (sym_next != 0) {
747
80.2M
        do {
748
80.2M
            send_bits_flush(s, bi_buf, bi_valid, pending);
749
#ifdef LIT_MEM
750
            dist = d_buf[sx];
751
            lc = l_buf[sx++];
752
#else
753
80.2M
#  if OPTIMAL_CMP >= 32
754
80.2M
            uint32_t dist_lc = Z_U32_FROM_LE(zng_memread_4(&sym_buf[sx]));
755
80.2M
            dist = dist_lc & 0xffff;
756
80.2M
            lc = (dist_lc >> 16) & 0xff;
757
#  else
758
            dist = sym_buf[sx] + ((unsigned)sym_buf[sx + 1] << 8);
759
            lc = sym_buf[sx + 2];
760
#  endif
761
80.2M
            sx += 3;
762
80.2M
#endif
763
80.2M
            if (dist == 0) {
764
67.0M
                uint64_t bits = 0;
765
67.0M
                uint32_t nbits = 0;
766
767
67.0M
                send_code_merge(s, lc, ltree, bits, nbits);
768
67.0M
#if !defined(LIT_MEM) && OPTIMAL_CMP >= 64
769
                /* Accumulate up to 2 more consecutive literals into the same merge. Their
770
                 * codes are at most 15 bits each, so all three fit alongside the at most
771
                 * 7 bits the flush above leaves behind. */
772
67.0M
                if (sx + 8 <= sym_next) {
773
67.0M
                    uint64_t next_syms = Z_U64_FROM_LE(zng_memread_8(&sym_buf[sx]));
774
775
                    /* A dist field is zero exactly when that symbol is a literal */
776
67.0M
                    if ((uint16_t)next_syms == 0) {
777
61.7M
                        send_code_merge(s, (unsigned)((next_syms >> 16) & 0xff), ltree, bits, nbits);
778
61.7M
                        sx += 3;
779
780
61.7M
                        if ((next_syms & LIT3_DIST1_MASK) == 0) {
781
60.0M
                            send_code_merge(s, (unsigned)((next_syms >> 40) & 0xff), ltree, bits, nbits);
782
60.0M
                            sx += 3;
783
60.0M
                        }
784
61.7M
                    }
785
67.0M
                }
786
67.0M
#endif
787
                /* The codes were traced and counted as they accumulated */
788
67.0M
                Assert(bi_valid + nbits <= 64, "bit buffer overflow");
789
67.0M
                bi_buf |= bits << bi_valid;
790
67.0M
                bi_valid += nbits;
791
67.0M
            } else {
792
13.1M
                uint32_t match_bits_len;
793
13.1M
                uint64_t match_bits = zng_assemble_dist(ltree, dtree, lc, dist, &match_bits_len);
794
795
13.1M
                send_bits_merge(s, match_bits, match_bits_len, bi_buf, bi_valid);
796
13.1M
            } /* literal or match pair ? */
797
798
            /* Check for no overlay of pending_buf on needed symbols */
799
#ifdef LIT_MEM
800
            Assert(pending < 2 * (s->lit_bufsize + sx), "pending_buf overflow");
801
#else
802
80.2M
            Assert(pending < s->lit_bufsize + sx, "pending_buf overflow");
803
80.2M
#endif
804
80.2M
        } while (sx < sym_next);
805
21.7k
    }
806
807
21.8k
    s->pending = pending;
808
21.8k
    zng_emit_end_block(s, ltree, 0, &bi_buf, &bi_valid);
809
810
    /* Write back to state */
811
21.8k
    s->bi_buf = bi_buf;
812
21.8k
    s->bi_valid = bi_valid;
813
21.8k
}
814
815
/* ===========================================================================
816
 * Check if the data type is TEXT or BINARY, using the following algorithm:
817
 * - TEXT if the two conditions below are satisfied:
818
 *    a) There are no non-portable control characters belonging to the
819
 *       "block list" (0..6, 14..25, 28..31).
820
 *    b) There is at least one printable character belonging to the
821
 *       "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
822
 * - BINARY otherwise.
823
 * - The following partially-portable control characters form a
824
 *   "gray list" that is ignored in this detection algorithm:
825
 *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
826
 * IN assertion: the fields Freq of dyn_ltree are set.
827
 */
828
10.5k
static int detect_data_type(deflate_state *s) {
829
    /* block_mask is the bit mask of block-listed bytes
830
     * set bits 0..6, 14..25, and 28..31
831
     * 0xf3ffc07f = binary 11110011111111111100000001111111
832
     */
833
10.5k
    unsigned long block_mask = 0xf3ffc07fUL;
834
10.5k
    int n;
835
836
    /* Check for non-textual ("block-listed") bytes. */
837
89.9k
    for (n = 0; n <= 31; n++, block_mask >>= 1)
838
87.7k
        if ((block_mask & 1) && (s->dyn_ltree[n].Freq != 0))
839
8.33k
            return Z_BINARY;
840
841
    /* Check for textual ("allow-listed") bytes. */
842
2.22k
    if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 || s->dyn_ltree[13].Freq != 0)
843
349
        return Z_TEXT;
844
180k
    for (n = 32; n < LITERALS; n++)
845
180k
        if (s->dyn_ltree[n].Freq != 0)
846
1.87k
            return Z_TEXT;
847
848
    /* There are no "block-listed" or "allow-listed" bytes:
849
     * this stream either is empty or has tolerated ("gray-listed") bytes only.
850
     */
851
3
    return Z_BINARY;
852
1.87k
}
853
854
/* ===========================================================================
855
 * Flush the bit buffer, keeping at most 7 bits in it.
856
 */
857
67.0k
void Z_INTERNAL zng_tr_flush_bits(deflate_state *s) {
858
67.0k
    if (s->bi_valid >= 48) {
859
95
        put_uint32(s, (uint32_t)s->bi_buf);
860
95
        put_short(s, (uint16_t)(s->bi_buf >> 32));
861
95
        s->bi_buf >>= 48;
862
95
        s->bi_valid -= 48;
863
67.0k
    } else if (s->bi_valid >= 32) {
864
653
        put_uint32(s, (uint32_t)s->bi_buf);
865
653
        s->bi_buf >>= 32;
866
653
        s->bi_valid -= 32;
867
653
    }
868
67.0k
    if (s->bi_valid >= 16) {
869
8.76k
        put_short(s, (uint16_t)s->bi_buf);
870
8.76k
        s->bi_buf >>= 16;
871
8.76k
        s->bi_valid -= 16;
872
8.76k
    }
873
67.0k
    if (s->bi_valid >= 8) {
874
5.90k
        put_byte(s, s->bi_buf);
875
5.90k
        s->bi_buf >>= 8;
876
5.90k
        s->bi_valid -= 8;
877
5.90k
    }
878
67.0k
}