xref: /netbsd-src/external/gpl3/gdb/dist/zlib/trees.c (revision 924795e69c8bb3f17afd8fcbb799710cc1719dc4)
1212397c6Schristos /* trees.c -- output deflated data using Huffman coding
2*924795e6Schristos  * Copyright (C) 1995-2021 Jean-loup Gailly
3212397c6Schristos  * detect_data_type() function provided freely by Cosmin Truta, 2006
4212397c6Schristos  * For conditions of distribution and use, see copyright notice in zlib.h
5212397c6Schristos  */
6212397c6Schristos 
7212397c6Schristos /*
8212397c6Schristos  *  ALGORITHM
9212397c6Schristos  *
10212397c6Schristos  *      The "deflation" process uses several Huffman trees. The more
11212397c6Schristos  *      common source values are represented by shorter bit sequences.
12212397c6Schristos  *
13212397c6Schristos  *      Each code tree is stored in a compressed form which is itself
14212397c6Schristos  * a Huffman encoding of the lengths of all the code strings (in
15212397c6Schristos  * ascending order by source values).  The actual code strings are
16212397c6Schristos  * reconstructed from the lengths in the inflate process, as described
17212397c6Schristos  * in the deflate specification.
18212397c6Schristos  *
19212397c6Schristos  *  REFERENCES
20212397c6Schristos  *
21212397c6Schristos  *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
22212397c6Schristos  *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
23212397c6Schristos  *
24212397c6Schristos  *      Storer, James A.
25212397c6Schristos  *          Data Compression:  Methods and Theory, pp. 49-50.
26212397c6Schristos  *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
27212397c6Schristos  *
28212397c6Schristos  *      Sedgewick, R.
29212397c6Schristos  *          Algorithms, p290.
30212397c6Schristos  *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
31212397c6Schristos  */
32212397c6Schristos 
33*924795e6Schristos /* @(#) Id */
34212397c6Schristos 
35212397c6Schristos /* #define GEN_TREES_H */
36212397c6Schristos 
37212397c6Schristos #include "deflate.h"
38212397c6Schristos 
39796c32c9Schristos #ifdef ZLIB_DEBUG
40212397c6Schristos #  include <ctype.h>
41212397c6Schristos #endif
42212397c6Schristos 
43212397c6Schristos /* ===========================================================================
44212397c6Schristos  * Constants
45212397c6Schristos  */
46212397c6Schristos 
47212397c6Schristos #define MAX_BL_BITS 7
48212397c6Schristos /* Bit length codes must not exceed MAX_BL_BITS bits */
49212397c6Schristos 
50212397c6Schristos #define END_BLOCK 256
51212397c6Schristos /* end of block literal code */
52212397c6Schristos 
53212397c6Schristos #define REP_3_6      16
54212397c6Schristos /* repeat previous bit length 3-6 times (2 bits of repeat count) */
55212397c6Schristos 
56212397c6Schristos #define REPZ_3_10    17
57212397c6Schristos /* repeat a zero length 3-10 times  (3 bits of repeat count) */
58212397c6Schristos 
59212397c6Schristos #define REPZ_11_138  18
60212397c6Schristos /* repeat a zero length 11-138 times  (7 bits of repeat count) */
61212397c6Schristos 
62212397c6Schristos local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
63212397c6Schristos    = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
64212397c6Schristos 
65212397c6Schristos local const int extra_dbits[D_CODES] /* extra bits for each distance code */
66212397c6Schristos    = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
67212397c6Schristos 
68212397c6Schristos local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
69212397c6Schristos    = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
70212397c6Schristos 
71212397c6Schristos local const uch bl_order[BL_CODES]
72212397c6Schristos    = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
73212397c6Schristos /* The lengths of the bit length codes are sent in order of decreasing
74212397c6Schristos  * probability, to avoid transmitting the lengths for unused bit length codes.
75212397c6Schristos  */
76212397c6Schristos 
77212397c6Schristos /* ===========================================================================
78212397c6Schristos  * Local data. These are initialized only once.
79212397c6Schristos  */
80212397c6Schristos 
81212397c6Schristos #define DIST_CODE_LEN  512 /* see definition of array dist_code below */
82212397c6Schristos 
83212397c6Schristos #if defined(GEN_TREES_H) || !defined(STDC)
84212397c6Schristos /* non ANSI compilers may not accept trees.h */
85212397c6Schristos 
86212397c6Schristos local ct_data static_ltree[L_CODES+2];
87212397c6Schristos /* The static literal tree. Since the bit lengths are imposed, there is no
88212397c6Schristos  * need for the L_CODES extra codes used during heap construction. However
89212397c6Schristos  * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
90212397c6Schristos  * below).
91212397c6Schristos  */
92212397c6Schristos 
93212397c6Schristos local ct_data static_dtree[D_CODES];
94212397c6Schristos /* The static distance tree. (Actually a trivial tree since all codes use
95212397c6Schristos  * 5 bits.)
96212397c6Schristos  */
97212397c6Schristos 
98212397c6Schristos uch _dist_code[DIST_CODE_LEN];
99212397c6Schristos /* Distance codes. The first 256 values correspond to the distances
100212397c6Schristos  * 3 .. 258, the last 256 values correspond to the top 8 bits of
101212397c6Schristos  * the 15 bit distances.
102212397c6Schristos  */
103212397c6Schristos 
104212397c6Schristos uch _length_code[MAX_MATCH-MIN_MATCH+1];
105212397c6Schristos /* length code for each normalized match length (0 == MIN_MATCH) */
106212397c6Schristos 
107212397c6Schristos local int base_length[LENGTH_CODES];
108212397c6Schristos /* First normalized length for each code (0 = MIN_MATCH) */
109212397c6Schristos 
110212397c6Schristos local int base_dist[D_CODES];
111212397c6Schristos /* First normalized distance for each code (0 = distance of 1) */
112212397c6Schristos 
113212397c6Schristos #else
114212397c6Schristos #  include "trees.h"
115212397c6Schristos #endif /* GEN_TREES_H */
116212397c6Schristos 
117212397c6Schristos struct static_tree_desc_s {
118212397c6Schristos     const ct_data *static_tree;  /* static tree or NULL */
119212397c6Schristos     const intf *extra_bits;      /* extra bits for each code or NULL */
120212397c6Schristos     int     extra_base;          /* base index for extra_bits */
121212397c6Schristos     int     elems;               /* max number of elements in the tree */
122212397c6Schristos     int     max_length;          /* max bit length for the codes */
123212397c6Schristos };
124212397c6Schristos 
125796c32c9Schristos local const static_tree_desc  static_l_desc =
126212397c6Schristos {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
127212397c6Schristos 
128796c32c9Schristos local const static_tree_desc  static_d_desc =
129212397c6Schristos {static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
130212397c6Schristos 
131796c32c9Schristos local const static_tree_desc  static_bl_desc =
132212397c6Schristos {(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
133212397c6Schristos 
134212397c6Schristos /* ===========================================================================
135212397c6Schristos  * Local (static) routines in this file.
136212397c6Schristos  */
137212397c6Schristos 
138212397c6Schristos local void tr_static_init OF((void));
139212397c6Schristos local void init_block     OF((deflate_state *s));
140212397c6Schristos local void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));
141212397c6Schristos local void gen_bitlen     OF((deflate_state *s, tree_desc *desc));
142212397c6Schristos local void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));
143212397c6Schristos local void build_tree     OF((deflate_state *s, tree_desc *desc));
144212397c6Schristos local void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));
145212397c6Schristos local void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));
146212397c6Schristos local int  build_bl_tree  OF((deflate_state *s));
147212397c6Schristos local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
148212397c6Schristos                               int blcodes));
149ba340e45Schristos local void compress_block OF((deflate_state *s, const ct_data *ltree,
150ba340e45Schristos                               const ct_data *dtree));
151212397c6Schristos local int  detect_data_type OF((deflate_state *s));
152*924795e6Schristos local unsigned bi_reverse OF((unsigned code, int len));
153212397c6Schristos local void bi_windup      OF((deflate_state *s));
154212397c6Schristos local void bi_flush       OF((deflate_state *s));
155212397c6Schristos 
156212397c6Schristos #ifdef GEN_TREES_H
157212397c6Schristos local void gen_trees_header OF((void));
158212397c6Schristos #endif
159212397c6Schristos 
160796c32c9Schristos #ifndef ZLIB_DEBUG
161212397c6Schristos #  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
162212397c6Schristos    /* Send a code of the given tree. c and tree must not have side effects */
163212397c6Schristos 
164796c32c9Schristos #else /* !ZLIB_DEBUG */
165212397c6Schristos #  define send_code(s, c, tree) \
166212397c6Schristos      { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
167212397c6Schristos        send_bits(s, tree[c].Code, tree[c].Len); }
168212397c6Schristos #endif
169212397c6Schristos 
170212397c6Schristos /* ===========================================================================
171212397c6Schristos  * Output a short LSB first on the stream.
172212397c6Schristos  * IN assertion: there is enough room in pendingBuf.
173212397c6Schristos  */
174212397c6Schristos #define put_short(s, w) { \
175212397c6Schristos     put_byte(s, (uch)((w) & 0xff)); \
176212397c6Schristos     put_byte(s, (uch)((ush)(w) >> 8)); \
177212397c6Schristos }
178212397c6Schristos 
179212397c6Schristos /* ===========================================================================
180212397c6Schristos  * Send a value on a given number of bits.
181212397c6Schristos  * IN assertion: length <= 16 and value fits in length bits.
182212397c6Schristos  */
183796c32c9Schristos #ifdef ZLIB_DEBUG
184212397c6Schristos local void send_bits      OF((deflate_state *s, int value, int length));
185212397c6Schristos 
send_bits(s,value,length)186212397c6Schristos local void send_bits(s, value, length)
187212397c6Schristos     deflate_state *s;
188212397c6Schristos     int value;  /* value to send */
189212397c6Schristos     int length; /* number of bits */
190212397c6Schristos {
191212397c6Schristos     Tracevv((stderr," l %2d v %4x ", length, value));
192212397c6Schristos     Assert(length > 0 && length <= 15, "invalid length");
193212397c6Schristos     s->bits_sent += (ulg)length;
194212397c6Schristos 
195212397c6Schristos     /* If not enough room in bi_buf, use (valid) bits from bi_buf and
196212397c6Schristos      * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
197212397c6Schristos      * unused bits in value.
198212397c6Schristos      */
199212397c6Schristos     if (s->bi_valid > (int)Buf_size - length) {
200212397c6Schristos         s->bi_buf |= (ush)value << s->bi_valid;
201212397c6Schristos         put_short(s, s->bi_buf);
202212397c6Schristos         s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
203212397c6Schristos         s->bi_valid += length - Buf_size;
204212397c6Schristos     } else {
205212397c6Schristos         s->bi_buf |= (ush)value << s->bi_valid;
206212397c6Schristos         s->bi_valid += length;
207212397c6Schristos     }
208212397c6Schristos }
209796c32c9Schristos #else /* !ZLIB_DEBUG */
210212397c6Schristos 
211212397c6Schristos #define send_bits(s, value, length) \
212212397c6Schristos { int len = length;\
213212397c6Schristos   if (s->bi_valid > (int)Buf_size - len) {\
214796c32c9Schristos     int val = (int)value;\
215212397c6Schristos     s->bi_buf |= (ush)val << s->bi_valid;\
216212397c6Schristos     put_short(s, s->bi_buf);\
217212397c6Schristos     s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
218212397c6Schristos     s->bi_valid += len - Buf_size;\
219212397c6Schristos   } else {\
220212397c6Schristos     s->bi_buf |= (ush)(value) << s->bi_valid;\
221212397c6Schristos     s->bi_valid += len;\
222212397c6Schristos   }\
223212397c6Schristos }
224796c32c9Schristos #endif /* ZLIB_DEBUG */
225212397c6Schristos 
226212397c6Schristos 
227212397c6Schristos /* the arguments must not have side effects */
228212397c6Schristos 
229212397c6Schristos /* ===========================================================================
230212397c6Schristos  * Initialize the various 'constant' tables.
231212397c6Schristos  */
tr_static_init()232212397c6Schristos local void tr_static_init()
233212397c6Schristos {
234212397c6Schristos #if defined(GEN_TREES_H) || !defined(STDC)
235212397c6Schristos     static int static_init_done = 0;
236212397c6Schristos     int n;        /* iterates over tree elements */
237212397c6Schristos     int bits;     /* bit counter */
238212397c6Schristos     int length;   /* length value */
239212397c6Schristos     int code;     /* code value */
240212397c6Schristos     int dist;     /* distance index */
241212397c6Schristos     ush bl_count[MAX_BITS+1];
242212397c6Schristos     /* number of codes at each bit length for an optimal tree */
243212397c6Schristos 
244212397c6Schristos     if (static_init_done) return;
245212397c6Schristos 
246212397c6Schristos     /* For some embedded targets, global variables are not initialized: */
247212397c6Schristos #ifdef NO_INIT_GLOBAL_POINTERS
248212397c6Schristos     static_l_desc.static_tree = static_ltree;
249212397c6Schristos     static_l_desc.extra_bits = extra_lbits;
250212397c6Schristos     static_d_desc.static_tree = static_dtree;
251212397c6Schristos     static_d_desc.extra_bits = extra_dbits;
252212397c6Schristos     static_bl_desc.extra_bits = extra_blbits;
253212397c6Schristos #endif
254212397c6Schristos 
255212397c6Schristos     /* Initialize the mapping length (0..255) -> length code (0..28) */
256212397c6Schristos     length = 0;
257212397c6Schristos     for (code = 0; code < LENGTH_CODES-1; code++) {
258212397c6Schristos         base_length[code] = length;
259212397c6Schristos         for (n = 0; n < (1<<extra_lbits[code]); n++) {
260212397c6Schristos             _length_code[length++] = (uch)code;
261212397c6Schristos         }
262212397c6Schristos     }
263212397c6Schristos     Assert (length == 256, "tr_static_init: length != 256");
264212397c6Schristos     /* Note that the length 255 (match length 258) can be represented
265212397c6Schristos      * in two different ways: code 284 + 5 bits or code 285, so we
266212397c6Schristos      * overwrite length_code[255] to use the best encoding:
267212397c6Schristos      */
268212397c6Schristos     _length_code[length-1] = (uch)code;
269212397c6Schristos 
270212397c6Schristos     /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
271212397c6Schristos     dist = 0;
272212397c6Schristos     for (code = 0 ; code < 16; code++) {
273212397c6Schristos         base_dist[code] = dist;
274212397c6Schristos         for (n = 0; n < (1<<extra_dbits[code]); n++) {
275212397c6Schristos             _dist_code[dist++] = (uch)code;
276212397c6Schristos         }
277212397c6Schristos     }
278212397c6Schristos     Assert (dist == 256, "tr_static_init: dist != 256");
279212397c6Schristos     dist >>= 7; /* from now on, all distances are divided by 128 */
280212397c6Schristos     for ( ; code < D_CODES; code++) {
281212397c6Schristos         base_dist[code] = dist << 7;
282212397c6Schristos         for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
283212397c6Schristos             _dist_code[256 + dist++] = (uch)code;
284212397c6Schristos         }
285212397c6Schristos     }
286212397c6Schristos     Assert (dist == 256, "tr_static_init: 256+dist != 512");
287212397c6Schristos 
288212397c6Schristos     /* Construct the codes of the static literal tree */
289212397c6Schristos     for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
290212397c6Schristos     n = 0;
291212397c6Schristos     while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
292212397c6Schristos     while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
293212397c6Schristos     while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
294212397c6Schristos     while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
295212397c6Schristos     /* Codes 286 and 287 do not exist, but we must include them in the
296212397c6Schristos      * tree construction to get a canonical Huffman tree (longest code
297212397c6Schristos      * all ones)
298212397c6Schristos      */
299212397c6Schristos     gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
300212397c6Schristos 
301212397c6Schristos     /* The static distance tree is trivial: */
302212397c6Schristos     for (n = 0; n < D_CODES; n++) {
303212397c6Schristos         static_dtree[n].Len = 5;
304212397c6Schristos         static_dtree[n].Code = bi_reverse((unsigned)n, 5);
305212397c6Schristos     }
306212397c6Schristos     static_init_done = 1;
307212397c6Schristos 
308212397c6Schristos #  ifdef GEN_TREES_H
309212397c6Schristos     gen_trees_header();
310212397c6Schristos #  endif
311212397c6Schristos #endif /* defined(GEN_TREES_H) || !defined(STDC) */
312212397c6Schristos }
313212397c6Schristos 
314212397c6Schristos /* ===========================================================================
315212397c6Schristos  * Genererate the file trees.h describing the static trees.
316212397c6Schristos  */
317212397c6Schristos #ifdef GEN_TREES_H
318796c32c9Schristos #  ifndef ZLIB_DEBUG
319212397c6Schristos #    include <stdio.h>
320212397c6Schristos #  endif
321212397c6Schristos 
322212397c6Schristos #  define SEPARATOR(i, last, width) \
323212397c6Schristos       ((i) == (last)? "\n};\n\n" :    \
324212397c6Schristos        ((i) % (width) == (width)-1 ? ",\n" : ", "))
325212397c6Schristos 
gen_trees_header()326212397c6Schristos void gen_trees_header()
327212397c6Schristos {
328212397c6Schristos     FILE *header = fopen("trees.h", "w");
329212397c6Schristos     int i;
330212397c6Schristos 
331212397c6Schristos     Assert (header != NULL, "Can't open trees.h");
332212397c6Schristos     fprintf(header,
333212397c6Schristos             "/* header created automatically with -DGEN_TREES_H */\n\n");
334212397c6Schristos 
335212397c6Schristos     fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
336212397c6Schristos     for (i = 0; i < L_CODES+2; i++) {
337212397c6Schristos         fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
338212397c6Schristos                 static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
339212397c6Schristos     }
340212397c6Schristos 
341212397c6Schristos     fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
342212397c6Schristos     for (i = 0; i < D_CODES; i++) {
343212397c6Schristos         fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
344212397c6Schristos                 static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
345212397c6Schristos     }
346212397c6Schristos 
347212397c6Schristos     fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
348212397c6Schristos     for (i = 0; i < DIST_CODE_LEN; i++) {
349212397c6Schristos         fprintf(header, "%2u%s", _dist_code[i],
350212397c6Schristos                 SEPARATOR(i, DIST_CODE_LEN-1, 20));
351212397c6Schristos     }
352212397c6Schristos 
353212397c6Schristos     fprintf(header,
354212397c6Schristos         "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
355212397c6Schristos     for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
356212397c6Schristos         fprintf(header, "%2u%s", _length_code[i],
357212397c6Schristos                 SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
358212397c6Schristos     }
359212397c6Schristos 
360212397c6Schristos     fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
361212397c6Schristos     for (i = 0; i < LENGTH_CODES; i++) {
362212397c6Schristos         fprintf(header, "%1u%s", base_length[i],
363212397c6Schristos                 SEPARATOR(i, LENGTH_CODES-1, 20));
364212397c6Schristos     }
365212397c6Schristos 
366212397c6Schristos     fprintf(header, "local const int base_dist[D_CODES] = {\n");
367212397c6Schristos     for (i = 0; i < D_CODES; i++) {
368212397c6Schristos         fprintf(header, "%5u%s", base_dist[i],
369212397c6Schristos                 SEPARATOR(i, D_CODES-1, 10));
370212397c6Schristos     }
371212397c6Schristos 
372212397c6Schristos     fclose(header);
373212397c6Schristos }
374212397c6Schristos #endif /* GEN_TREES_H */
375212397c6Schristos 
376212397c6Schristos /* ===========================================================================
377212397c6Schristos  * Initialize the tree data structures for a new zlib stream.
378212397c6Schristos  */
_tr_init(s)379212397c6Schristos void ZLIB_INTERNAL _tr_init(s)
380212397c6Schristos     deflate_state *s;
381212397c6Schristos {
382212397c6Schristos     tr_static_init();
383212397c6Schristos 
384212397c6Schristos     s->l_desc.dyn_tree = s->dyn_ltree;
385212397c6Schristos     s->l_desc.stat_desc = &static_l_desc;
386212397c6Schristos 
387212397c6Schristos     s->d_desc.dyn_tree = s->dyn_dtree;
388212397c6Schristos     s->d_desc.stat_desc = &static_d_desc;
389212397c6Schristos 
390212397c6Schristos     s->bl_desc.dyn_tree = s->bl_tree;
391212397c6Schristos     s->bl_desc.stat_desc = &static_bl_desc;
392212397c6Schristos 
393212397c6Schristos     s->bi_buf = 0;
394212397c6Schristos     s->bi_valid = 0;
395796c32c9Schristos #ifdef ZLIB_DEBUG
396212397c6Schristos     s->compressed_len = 0L;
397212397c6Schristos     s->bits_sent = 0L;
398212397c6Schristos #endif
399212397c6Schristos 
400212397c6Schristos     /* Initialize the first block of the first file: */
401212397c6Schristos     init_block(s);
402212397c6Schristos }
403212397c6Schristos 
404212397c6Schristos /* ===========================================================================
405212397c6Schristos  * Initialize a new block.
406212397c6Schristos  */
init_block(s)407212397c6Schristos local void init_block(s)
408212397c6Schristos     deflate_state *s;
409212397c6Schristos {
410212397c6Schristos     int n; /* iterates over tree elements */
411212397c6Schristos 
412212397c6Schristos     /* Initialize the trees. */
413212397c6Schristos     for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
414212397c6Schristos     for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
415212397c6Schristos     for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
416212397c6Schristos 
417212397c6Schristos     s->dyn_ltree[END_BLOCK].Freq = 1;
418212397c6Schristos     s->opt_len = s->static_len = 0L;
419*924795e6Schristos     s->sym_next = s->matches = 0;
420212397c6Schristos }
421212397c6Schristos 
422212397c6Schristos #define SMALLEST 1
423212397c6Schristos /* Index within the heap array of least frequent node in the Huffman tree */
424212397c6Schristos 
425212397c6Schristos 
426212397c6Schristos /* ===========================================================================
427212397c6Schristos  * Remove the smallest element from the heap and recreate the heap with
428212397c6Schristos  * one less element. Updates heap and heap_len.
429212397c6Schristos  */
430212397c6Schristos #define pqremove(s, tree, top) \
431212397c6Schristos {\
432212397c6Schristos     top = s->heap[SMALLEST]; \
433212397c6Schristos     s->heap[SMALLEST] = s->heap[s->heap_len--]; \
434212397c6Schristos     pqdownheap(s, tree, SMALLEST); \
435212397c6Schristos }
436212397c6Schristos 
437212397c6Schristos /* ===========================================================================
438212397c6Schristos  * Compares to subtrees, using the tree depth as tie breaker when
439212397c6Schristos  * the subtrees have equal frequency. This minimizes the worst case length.
440212397c6Schristos  */
441212397c6Schristos #define smaller(tree, n, m, depth) \
442212397c6Schristos    (tree[n].Freq < tree[m].Freq || \
443212397c6Schristos    (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
444212397c6Schristos 
445212397c6Schristos /* ===========================================================================
446212397c6Schristos  * Restore the heap property by moving down the tree starting at node k,
447212397c6Schristos  * exchanging a node with the smallest of its two sons if necessary, stopping
448212397c6Schristos  * when the heap property is re-established (each father smaller than its
449212397c6Schristos  * two sons).
450212397c6Schristos  */
pqdownheap(s,tree,k)451212397c6Schristos local void pqdownheap(s, tree, k)
452212397c6Schristos     deflate_state *s;
453212397c6Schristos     ct_data *tree;  /* the tree to restore */
454212397c6Schristos     int k;               /* node to move down */
455212397c6Schristos {
456212397c6Schristos     int v = s->heap[k];
457212397c6Schristos     int j = k << 1;  /* left son of k */
458212397c6Schristos     while (j <= s->heap_len) {
459212397c6Schristos         /* Set j to the smallest of the two sons: */
460212397c6Schristos         if (j < s->heap_len &&
461212397c6Schristos             smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
462212397c6Schristos             j++;
463212397c6Schristos         }
464212397c6Schristos         /* Exit if v is smaller than both sons */
465212397c6Schristos         if (smaller(tree, v, s->heap[j], s->depth)) break;
466212397c6Schristos 
467212397c6Schristos         /* Exchange v with the smallest son */
468212397c6Schristos         s->heap[k] = s->heap[j];  k = j;
469212397c6Schristos 
470212397c6Schristos         /* And continue down the tree, setting j to the left son of k */
471212397c6Schristos         j <<= 1;
472212397c6Schristos     }
473212397c6Schristos     s->heap[k] = v;
474212397c6Schristos }
475212397c6Schristos 
476212397c6Schristos /* ===========================================================================
477212397c6Schristos  * Compute the optimal bit lengths for a tree and update the total bit length
478212397c6Schristos  * for the current block.
479212397c6Schristos  * IN assertion: the fields freq and dad are set, heap[heap_max] and
480212397c6Schristos  *    above are the tree nodes sorted by increasing frequency.
481212397c6Schristos  * OUT assertions: the field len is set to the optimal bit length, the
482212397c6Schristos  *     array bl_count contains the frequencies for each bit length.
483212397c6Schristos  *     The length opt_len is updated; static_len is also updated if stree is
484212397c6Schristos  *     not null.
485212397c6Schristos  */
gen_bitlen(s,desc)486212397c6Schristos local void gen_bitlen(s, desc)
487212397c6Schristos     deflate_state *s;
488212397c6Schristos     tree_desc *desc;    /* the tree descriptor */
489212397c6Schristos {
490212397c6Schristos     ct_data *tree        = desc->dyn_tree;
491212397c6Schristos     int max_code         = desc->max_code;
492212397c6Schristos     const ct_data *stree = desc->stat_desc->static_tree;
493212397c6Schristos     const intf *extra    = desc->stat_desc->extra_bits;
494212397c6Schristos     int base             = desc->stat_desc->extra_base;
495212397c6Schristos     int max_length       = desc->stat_desc->max_length;
496212397c6Schristos     int h;              /* heap index */
497212397c6Schristos     int n, m;           /* iterate over the tree elements */
498212397c6Schristos     int bits;           /* bit length */
499212397c6Schristos     int xbits;          /* extra bits */
500212397c6Schristos     ush f;              /* frequency */
501212397c6Schristos     int overflow = 0;   /* number of elements with bit length too large */
502212397c6Schristos 
503212397c6Schristos     for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
504212397c6Schristos 
505212397c6Schristos     /* In a first pass, compute the optimal bit lengths (which may
506212397c6Schristos      * overflow in the case of the bit length tree).
507212397c6Schristos      */
508212397c6Schristos     tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
509212397c6Schristos 
510212397c6Schristos     for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
511212397c6Schristos         n = s->heap[h];
512212397c6Schristos         bits = tree[tree[n].Dad].Len + 1;
513212397c6Schristos         if (bits > max_length) bits = max_length, overflow++;
514212397c6Schristos         tree[n].Len = (ush)bits;
515212397c6Schristos         /* We overwrite tree[n].Dad which is no longer needed */
516212397c6Schristos 
517212397c6Schristos         if (n > max_code) continue; /* not a leaf node */
518212397c6Schristos 
519212397c6Schristos         s->bl_count[bits]++;
520212397c6Schristos         xbits = 0;
521212397c6Schristos         if (n >= base) xbits = extra[n-base];
522212397c6Schristos         f = tree[n].Freq;
523796c32c9Schristos         s->opt_len += (ulg)f * (unsigned)(bits + xbits);
524796c32c9Schristos         if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits);
525212397c6Schristos     }
526212397c6Schristos     if (overflow == 0) return;
527212397c6Schristos 
528796c32c9Schristos     Tracev((stderr,"\nbit length overflow\n"));
529212397c6Schristos     /* This happens for example on obj2 and pic of the Calgary corpus */
530212397c6Schristos 
531212397c6Schristos     /* Find the first bit length which could increase: */
532212397c6Schristos     do {
533212397c6Schristos         bits = max_length-1;
534212397c6Schristos         while (s->bl_count[bits] == 0) bits--;
535212397c6Schristos         s->bl_count[bits]--;      /* move one leaf down the tree */
536212397c6Schristos         s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
537212397c6Schristos         s->bl_count[max_length]--;
538212397c6Schristos         /* The brother of the overflow item also moves one step up,
539212397c6Schristos          * but this does not affect bl_count[max_length]
540212397c6Schristos          */
541212397c6Schristos         overflow -= 2;
542212397c6Schristos     } while (overflow > 0);
543212397c6Schristos 
544212397c6Schristos     /* Now recompute all bit lengths, scanning in increasing frequency.
545212397c6Schristos      * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
546212397c6Schristos      * lengths instead of fixing only the wrong ones. This idea is taken
547212397c6Schristos      * from 'ar' written by Haruhiko Okumura.)
548212397c6Schristos      */
549212397c6Schristos     for (bits = max_length; bits != 0; bits--) {
550212397c6Schristos         n = s->bl_count[bits];
551212397c6Schristos         while (n != 0) {
552212397c6Schristos             m = s->heap[--h];
553212397c6Schristos             if (m > max_code) continue;
554212397c6Schristos             if ((unsigned) tree[m].Len != (unsigned) bits) {
555796c32c9Schristos                 Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
556796c32c9Schristos                 s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq;
557212397c6Schristos                 tree[m].Len = (ush)bits;
558212397c6Schristos             }
559212397c6Schristos             n--;
560212397c6Schristos         }
561212397c6Schristos     }
562212397c6Schristos }
563212397c6Schristos 
564212397c6Schristos /* ===========================================================================
565212397c6Schristos  * Generate the codes for a given tree and bit counts (which need not be
566212397c6Schristos  * optimal).
567212397c6Schristos  * IN assertion: the array bl_count contains the bit length statistics for
568212397c6Schristos  * the given tree and the field len is set for all tree elements.
569212397c6Schristos  * OUT assertion: the field code is set for all tree elements of non
570212397c6Schristos  *     zero code length.
571212397c6Schristos  */
gen_codes(tree,max_code,bl_count)572212397c6Schristos local void gen_codes (tree, max_code, bl_count)
573212397c6Schristos     ct_data *tree;             /* the tree to decorate */
574212397c6Schristos     int max_code;              /* largest code with non zero frequency */
575212397c6Schristos     ushf *bl_count;            /* number of codes at each bit length */
576212397c6Schristos {
577212397c6Schristos     ush next_code[MAX_BITS+1]; /* next code value for each bit length */
578796c32c9Schristos     unsigned code = 0;         /* running code value */
579212397c6Schristos     int bits;                  /* bit index */
580212397c6Schristos     int n;                     /* code index */
581212397c6Schristos 
582212397c6Schristos     /* The distribution counts are first used to generate the code values
583212397c6Schristos      * without bit reversal.
584212397c6Schristos      */
585212397c6Schristos     for (bits = 1; bits <= MAX_BITS; bits++) {
586796c32c9Schristos         code = (code + bl_count[bits-1]) << 1;
587796c32c9Schristos         next_code[bits] = (ush)code;
588212397c6Schristos     }
589212397c6Schristos     /* Check that the bit counts in bl_count are consistent. The last code
590212397c6Schristos      * must be all ones.
591212397c6Schristos      */
592212397c6Schristos     Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
593212397c6Schristos             "inconsistent bit counts");
594212397c6Schristos     Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
595212397c6Schristos 
596212397c6Schristos     for (n = 0;  n <= max_code; n++) {
597212397c6Schristos         int len = tree[n].Len;
598212397c6Schristos         if (len == 0) continue;
599212397c6Schristos         /* Now reverse the bits */
600796c32c9Schristos         tree[n].Code = (ush)bi_reverse(next_code[len]++, len);
601212397c6Schristos 
602212397c6Schristos         Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
603212397c6Schristos              n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
604212397c6Schristos     }
605212397c6Schristos }
606212397c6Schristos 
607212397c6Schristos /* ===========================================================================
608212397c6Schristos  * Construct one Huffman tree and assigns the code bit strings and lengths.
609212397c6Schristos  * Update the total bit length for the current block.
610212397c6Schristos  * IN assertion: the field freq is set for all tree elements.
611212397c6Schristos  * OUT assertions: the fields len and code are set to the optimal bit length
612212397c6Schristos  *     and corresponding code. The length opt_len is updated; static_len is
613212397c6Schristos  *     also updated if stree is not null. The field max_code is set.
614212397c6Schristos  */
build_tree(s,desc)615212397c6Schristos local void build_tree(s, desc)
616212397c6Schristos     deflate_state *s;
617212397c6Schristos     tree_desc *desc; /* the tree descriptor */
618212397c6Schristos {
619212397c6Schristos     ct_data *tree         = desc->dyn_tree;
620212397c6Schristos     const ct_data *stree  = desc->stat_desc->static_tree;
621212397c6Schristos     int elems             = desc->stat_desc->elems;
622212397c6Schristos     int n, m;          /* iterate over heap elements */
623212397c6Schristos     int max_code = -1; /* largest code with non zero frequency */
624212397c6Schristos     int node;          /* new node being created */
625212397c6Schristos 
626212397c6Schristos     /* Construct the initial heap, with least frequent element in
627212397c6Schristos      * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
628212397c6Schristos      * heap[0] is not used.
629212397c6Schristos      */
630212397c6Schristos     s->heap_len = 0, s->heap_max = HEAP_SIZE;
631212397c6Schristos 
632212397c6Schristos     for (n = 0; n < elems; n++) {
633212397c6Schristos         if (tree[n].Freq != 0) {
634212397c6Schristos             s->heap[++(s->heap_len)] = max_code = n;
635212397c6Schristos             s->depth[n] = 0;
636212397c6Schristos         } else {
637212397c6Schristos             tree[n].Len = 0;
638212397c6Schristos         }
639212397c6Schristos     }
640212397c6Schristos 
641212397c6Schristos     /* The pkzip format requires that at least one distance code exists,
642212397c6Schristos      * and that at least one bit should be sent even if there is only one
643212397c6Schristos      * possible code. So to avoid special checks later on we force at least
644212397c6Schristos      * two codes of non zero frequency.
645212397c6Schristos      */
646212397c6Schristos     while (s->heap_len < 2) {
647212397c6Schristos         node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
648212397c6Schristos         tree[node].Freq = 1;
649212397c6Schristos         s->depth[node] = 0;
650212397c6Schristos         s->opt_len--; if (stree) s->static_len -= stree[node].Len;
651212397c6Schristos         /* node is 0 or 1 so it does not have extra bits */
652212397c6Schristos     }
653212397c6Schristos     desc->max_code = max_code;
654212397c6Schristos 
655212397c6Schristos     /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
656212397c6Schristos      * establish sub-heaps of increasing lengths:
657212397c6Schristos      */
658212397c6Schristos     for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
659212397c6Schristos 
660212397c6Schristos     /* Construct the Huffman tree by repeatedly combining the least two
661212397c6Schristos      * frequent nodes.
662212397c6Schristos      */
663212397c6Schristos     node = elems;              /* next internal node of the tree */
664212397c6Schristos     do {
665212397c6Schristos         pqremove(s, tree, n);  /* n = node of least frequency */
666212397c6Schristos         m = s->heap[SMALLEST]; /* m = node of next least frequency */
667212397c6Schristos 
668212397c6Schristos         s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
669212397c6Schristos         s->heap[--(s->heap_max)] = m;
670212397c6Schristos 
671212397c6Schristos         /* Create a new node father of n and m */
672212397c6Schristos         tree[node].Freq = tree[n].Freq + tree[m].Freq;
673212397c6Schristos         s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
674212397c6Schristos                                 s->depth[n] : s->depth[m]) + 1);
675212397c6Schristos         tree[n].Dad = tree[m].Dad = (ush)node;
676212397c6Schristos #ifdef DUMP_BL_TREE
677212397c6Schristos         if (tree == s->bl_tree) {
678212397c6Schristos             fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
679212397c6Schristos                     node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
680212397c6Schristos         }
681212397c6Schristos #endif
682212397c6Schristos         /* and insert the new node in the heap */
683212397c6Schristos         s->heap[SMALLEST] = node++;
684212397c6Schristos         pqdownheap(s, tree, SMALLEST);
685212397c6Schristos 
686212397c6Schristos     } while (s->heap_len >= 2);
687212397c6Schristos 
688212397c6Schristos     s->heap[--(s->heap_max)] = s->heap[SMALLEST];
689212397c6Schristos 
690212397c6Schristos     /* At this point, the fields freq and dad are set. We can now
691212397c6Schristos      * generate the bit lengths.
692212397c6Schristos      */
693212397c6Schristos     gen_bitlen(s, (tree_desc *)desc);
694212397c6Schristos 
695212397c6Schristos     /* The field len is now set, we can generate the bit codes */
696212397c6Schristos     gen_codes ((ct_data *)tree, max_code, s->bl_count);
697212397c6Schristos }
698212397c6Schristos 
699212397c6Schristos /* ===========================================================================
700212397c6Schristos  * Scan a literal or distance tree to determine the frequencies of the codes
701212397c6Schristos  * in the bit length tree.
702212397c6Schristos  */
scan_tree(s,tree,max_code)703212397c6Schristos local void scan_tree (s, tree, max_code)
704212397c6Schristos     deflate_state *s;
705212397c6Schristos     ct_data *tree;   /* the tree to be scanned */
706212397c6Schristos     int max_code;    /* and its largest code of non zero frequency */
707212397c6Schristos {
708212397c6Schristos     int n;                     /* iterates over all tree elements */
709212397c6Schristos     int prevlen = -1;          /* last emitted length */
710212397c6Schristos     int curlen;                /* length of current code */
711212397c6Schristos     int nextlen = tree[0].Len; /* length of next code */
712212397c6Schristos     int count = 0;             /* repeat count of the current code */
713212397c6Schristos     int max_count = 7;         /* max repeat count */
714212397c6Schristos     int min_count = 4;         /* min repeat count */
715212397c6Schristos 
716212397c6Schristos     if (nextlen == 0) max_count = 138, min_count = 3;
717212397c6Schristos     tree[max_code+1].Len = (ush)0xffff; /* guard */
718212397c6Schristos 
719212397c6Schristos     for (n = 0; n <= max_code; n++) {
720212397c6Schristos         curlen = nextlen; nextlen = tree[n+1].Len;
721212397c6Schristos         if (++count < max_count && curlen == nextlen) {
722212397c6Schristos             continue;
723212397c6Schristos         } else if (count < min_count) {
724212397c6Schristos             s->bl_tree[curlen].Freq += count;
725212397c6Schristos         } else if (curlen != 0) {
726212397c6Schristos             if (curlen != prevlen) s->bl_tree[curlen].Freq++;
727212397c6Schristos             s->bl_tree[REP_3_6].Freq++;
728212397c6Schristos         } else if (count <= 10) {
729212397c6Schristos             s->bl_tree[REPZ_3_10].Freq++;
730212397c6Schristos         } else {
731212397c6Schristos             s->bl_tree[REPZ_11_138].Freq++;
732212397c6Schristos         }
733212397c6Schristos         count = 0; prevlen = curlen;
734212397c6Schristos         if (nextlen == 0) {
735212397c6Schristos             max_count = 138, min_count = 3;
736212397c6Schristos         } else if (curlen == nextlen) {
737212397c6Schristos             max_count = 6, min_count = 3;
738212397c6Schristos         } else {
739212397c6Schristos             max_count = 7, min_count = 4;
740212397c6Schristos         }
741212397c6Schristos     }
742212397c6Schristos }
743212397c6Schristos 
744212397c6Schristos /* ===========================================================================
745212397c6Schristos  * Send a literal or distance tree in compressed form, using the codes in
746212397c6Schristos  * bl_tree.
747212397c6Schristos  */
send_tree(s,tree,max_code)748212397c6Schristos local void send_tree (s, tree, max_code)
749212397c6Schristos     deflate_state *s;
750212397c6Schristos     ct_data *tree; /* the tree to be scanned */
751212397c6Schristos     int max_code;       /* and its largest code of non zero frequency */
752212397c6Schristos {
753212397c6Schristos     int n;                     /* iterates over all tree elements */
754212397c6Schristos     int prevlen = -1;          /* last emitted length */
755212397c6Schristos     int curlen;                /* length of current code */
756212397c6Schristos     int nextlen = tree[0].Len; /* length of next code */
757212397c6Schristos     int count = 0;             /* repeat count of the current code */
758212397c6Schristos     int max_count = 7;         /* max repeat count */
759212397c6Schristos     int min_count = 4;         /* min repeat count */
760212397c6Schristos 
761212397c6Schristos     /* tree[max_code+1].Len = -1; */  /* guard already set */
762212397c6Schristos     if (nextlen == 0) max_count = 138, min_count = 3;
763212397c6Schristos 
764212397c6Schristos     for (n = 0; n <= max_code; n++) {
765212397c6Schristos         curlen = nextlen; nextlen = tree[n+1].Len;
766212397c6Schristos         if (++count < max_count && curlen == nextlen) {
767212397c6Schristos             continue;
768212397c6Schristos         } else if (count < min_count) {
769212397c6Schristos             do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
770212397c6Schristos 
771212397c6Schristos         } else if (curlen != 0) {
772212397c6Schristos             if (curlen != prevlen) {
773212397c6Schristos                 send_code(s, curlen, s->bl_tree); count--;
774212397c6Schristos             }
775212397c6Schristos             Assert(count >= 3 && count <= 6, " 3_6?");
776212397c6Schristos             send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
777212397c6Schristos 
778212397c6Schristos         } else if (count <= 10) {
779212397c6Schristos             send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
780212397c6Schristos 
781212397c6Schristos         } else {
782212397c6Schristos             send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
783212397c6Schristos         }
784212397c6Schristos         count = 0; prevlen = curlen;
785212397c6Schristos         if (nextlen == 0) {
786212397c6Schristos             max_count = 138, min_count = 3;
787212397c6Schristos         } else if (curlen == nextlen) {
788212397c6Schristos             max_count = 6, min_count = 3;
789212397c6Schristos         } else {
790212397c6Schristos             max_count = 7, min_count = 4;
791212397c6Schristos         }
792212397c6Schristos     }
793212397c6Schristos }
794212397c6Schristos 
795212397c6Schristos /* ===========================================================================
796212397c6Schristos  * Construct the Huffman tree for the bit lengths and return the index in
797212397c6Schristos  * bl_order of the last bit length code to send.
798212397c6Schristos  */
build_bl_tree(s)799212397c6Schristos local int build_bl_tree(s)
800212397c6Schristos     deflate_state *s;
801212397c6Schristos {
802212397c6Schristos     int max_blindex;  /* index of last bit length code of non zero freq */
803212397c6Schristos 
804212397c6Schristos     /* Determine the bit length frequencies for literal and distance trees */
805212397c6Schristos     scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
806212397c6Schristos     scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
807212397c6Schristos 
808212397c6Schristos     /* Build the bit length tree: */
809212397c6Schristos     build_tree(s, (tree_desc *)(&(s->bl_desc)));
810212397c6Schristos     /* opt_len now includes the length of the tree representations, except
811212397c6Schristos      * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
812212397c6Schristos      */
813212397c6Schristos 
814212397c6Schristos     /* Determine the number of bit length codes to send. The pkzip format
815212397c6Schristos      * requires that at least 4 bit length codes be sent. (appnote.txt says
816212397c6Schristos      * 3 but the actual value used is 4.)
817212397c6Schristos      */
818212397c6Schristos     for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
819212397c6Schristos         if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
820212397c6Schristos     }
821212397c6Schristos     /* Update opt_len to include the bit length tree and counts */
822796c32c9Schristos     s->opt_len += 3*((ulg)max_blindex+1) + 5+5+4;
823212397c6Schristos     Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
824212397c6Schristos             s->opt_len, s->static_len));
825212397c6Schristos 
826212397c6Schristos     return max_blindex;
827212397c6Schristos }
828212397c6Schristos 
829212397c6Schristos /* ===========================================================================
830212397c6Schristos  * Send the header for a block using dynamic Huffman trees: the counts, the
831212397c6Schristos  * lengths of the bit length codes, the literal tree and the distance tree.
832212397c6Schristos  * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
833212397c6Schristos  */
send_all_trees(s,lcodes,dcodes,blcodes)834212397c6Schristos local void send_all_trees(s, lcodes, dcodes, blcodes)
835212397c6Schristos     deflate_state *s;
836212397c6Schristos     int lcodes, dcodes, blcodes; /* number of codes for each tree */
837212397c6Schristos {
838212397c6Schristos     int rank;                    /* index in bl_order */
839212397c6Schristos 
840212397c6Schristos     Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
841212397c6Schristos     Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
842212397c6Schristos             "too many codes");
843212397c6Schristos     Tracev((stderr, "\nbl counts: "));
844212397c6Schristos     send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
845212397c6Schristos     send_bits(s, dcodes-1,   5);
846212397c6Schristos     send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
847212397c6Schristos     for (rank = 0; rank < blcodes; rank++) {
848212397c6Schristos         Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
849212397c6Schristos         send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
850212397c6Schristos     }
851212397c6Schristos     Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
852212397c6Schristos 
853212397c6Schristos     send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
854212397c6Schristos     Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
855212397c6Schristos 
856212397c6Schristos     send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
857212397c6Schristos     Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
858212397c6Schristos }
859212397c6Schristos 
860212397c6Schristos /* ===========================================================================
861212397c6Schristos  * Send a stored block
862212397c6Schristos  */
_tr_stored_block(s,buf,stored_len,last)863212397c6Schristos void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)
864212397c6Schristos     deflate_state *s;
865212397c6Schristos     charf *buf;       /* input block */
866212397c6Schristos     ulg stored_len;   /* length of input block */
867212397c6Schristos     int last;         /* one if this is the last block for a file */
868212397c6Schristos {
869212397c6Schristos     send_bits(s, (STORED_BLOCK<<1)+last, 3);    /* send block type */
870796c32c9Schristos     bi_windup(s);        /* align on byte boundary */
871796c32c9Schristos     put_short(s, (ush)stored_len);
872796c32c9Schristos     put_short(s, (ush)~stored_len);
873*924795e6Schristos     if (stored_len)
874796c32c9Schristos         zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len);
875796c32c9Schristos     s->pending += stored_len;
876796c32c9Schristos #ifdef ZLIB_DEBUG
877212397c6Schristos     s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
878212397c6Schristos     s->compressed_len += (stored_len + 4) << 3;
879796c32c9Schristos     s->bits_sent += 2*16;
880796c32c9Schristos     s->bits_sent += stored_len<<3;
881212397c6Schristos #endif
882212397c6Schristos }
883212397c6Schristos 
884212397c6Schristos /* ===========================================================================
885212397c6Schristos  * Flush the bits in the bit buffer to pending output (leaves at most 7 bits)
886212397c6Schristos  */
_tr_flush_bits(s)887212397c6Schristos void ZLIB_INTERNAL _tr_flush_bits(s)
888212397c6Schristos     deflate_state *s;
889212397c6Schristos {
890212397c6Schristos     bi_flush(s);
891212397c6Schristos }
892212397c6Schristos 
893212397c6Schristos /* ===========================================================================
894212397c6Schristos  * Send one empty static block to give enough lookahead for inflate.
895212397c6Schristos  * This takes 10 bits, of which 7 may remain in the bit buffer.
896212397c6Schristos  */
_tr_align(s)897212397c6Schristos void ZLIB_INTERNAL _tr_align(s)
898212397c6Schristos     deflate_state *s;
899212397c6Schristos {
900212397c6Schristos     send_bits(s, STATIC_TREES<<1, 3);
901212397c6Schristos     send_code(s, END_BLOCK, static_ltree);
902796c32c9Schristos #ifdef ZLIB_DEBUG
903212397c6Schristos     s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
904212397c6Schristos #endif
905212397c6Schristos     bi_flush(s);
906212397c6Schristos }
907212397c6Schristos 
908212397c6Schristos /* ===========================================================================
909212397c6Schristos  * Determine the best encoding for the current block: dynamic trees, static
910796c32c9Schristos  * trees or store, and write out the encoded block.
911212397c6Schristos  */
_tr_flush_block(s,buf,stored_len,last)912212397c6Schristos void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)
913212397c6Schristos     deflate_state *s;
914212397c6Schristos     charf *buf;       /* input block, or NULL if too old */
915212397c6Schristos     ulg stored_len;   /* length of input block */
916212397c6Schristos     int last;         /* one if this is the last block for a file */
917212397c6Schristos {
918212397c6Schristos     ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
919212397c6Schristos     int max_blindex = 0;  /* index of last bit length code of non zero freq */
920212397c6Schristos 
921212397c6Schristos     /* Build the Huffman trees unless a stored block is forced */
922212397c6Schristos     if (s->level > 0) {
923212397c6Schristos 
924212397c6Schristos         /* Check if the file is binary or text */
925212397c6Schristos         if (s->strm->data_type == Z_UNKNOWN)
926212397c6Schristos             s->strm->data_type = detect_data_type(s);
927212397c6Schristos 
928212397c6Schristos         /* Construct the literal and distance trees */
929212397c6Schristos         build_tree(s, (tree_desc *)(&(s->l_desc)));
930212397c6Schristos         Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
931212397c6Schristos                 s->static_len));
932212397c6Schristos 
933212397c6Schristos         build_tree(s, (tree_desc *)(&(s->d_desc)));
934212397c6Schristos         Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
935212397c6Schristos                 s->static_len));
936212397c6Schristos         /* At this point, opt_len and static_len are the total bit lengths of
937212397c6Schristos          * the compressed block data, excluding the tree representations.
938212397c6Schristos          */
939212397c6Schristos 
940212397c6Schristos         /* Build the bit length tree for the above two trees, and get the index
941212397c6Schristos          * in bl_order of the last bit length code to send.
942212397c6Schristos          */
943212397c6Schristos         max_blindex = build_bl_tree(s);
944212397c6Schristos 
945212397c6Schristos         /* Determine the best encoding. Compute the block lengths in bytes. */
946212397c6Schristos         opt_lenb = (s->opt_len+3+7)>>3;
947212397c6Schristos         static_lenb = (s->static_len+3+7)>>3;
948212397c6Schristos 
949212397c6Schristos         Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
950212397c6Schristos                 opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
951*924795e6Schristos                 s->sym_next / 3));
952212397c6Schristos 
953212397c6Schristos         if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
954212397c6Schristos 
955212397c6Schristos     } else {
956212397c6Schristos         Assert(buf != (char*)0, "lost buf");
957212397c6Schristos         opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
958212397c6Schristos     }
959212397c6Schristos 
960212397c6Schristos #ifdef FORCE_STORED
961212397c6Schristos     if (buf != (char*)0) { /* force stored block */
962212397c6Schristos #else
963212397c6Schristos     if (stored_len+4 <= opt_lenb && buf != (char*)0) {
964212397c6Schristos                        /* 4: two words for the lengths */
965212397c6Schristos #endif
966212397c6Schristos         /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
967212397c6Schristos          * Otherwise we can't have processed more than WSIZE input bytes since
968212397c6Schristos          * the last block flush, because compression would have been
969212397c6Schristos          * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
970212397c6Schristos          * transform a block into a stored block.
971212397c6Schristos          */
972212397c6Schristos         _tr_stored_block(s, buf, stored_len, last);
973212397c6Schristos 
974212397c6Schristos #ifdef FORCE_STATIC
975212397c6Schristos     } else if (static_lenb >= 0) { /* force static trees */
976212397c6Schristos #else
977212397c6Schristos     } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
978212397c6Schristos #endif
979212397c6Schristos         send_bits(s, (STATIC_TREES<<1)+last, 3);
980ba340e45Schristos         compress_block(s, (const ct_data *)static_ltree,
981ba340e45Schristos                        (const ct_data *)static_dtree);
982796c32c9Schristos #ifdef ZLIB_DEBUG
983212397c6Schristos         s->compressed_len += 3 + s->static_len;
984212397c6Schristos #endif
985212397c6Schristos     } else {
986212397c6Schristos         send_bits(s, (DYN_TREES<<1)+last, 3);
987212397c6Schristos         send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
988212397c6Schristos                        max_blindex+1);
989ba340e45Schristos         compress_block(s, (const ct_data *)s->dyn_ltree,
990ba340e45Schristos                        (const ct_data *)s->dyn_dtree);
991796c32c9Schristos #ifdef ZLIB_DEBUG
992212397c6Schristos         s->compressed_len += 3 + s->opt_len;
993212397c6Schristos #endif
994212397c6Schristos     }
995212397c6Schristos     Assert (s->compressed_len == s->bits_sent, "bad compressed size");
996212397c6Schristos     /* The above check is made mod 2^32, for files larger than 512 MB
997212397c6Schristos      * and uLong implemented on 32 bits.
998212397c6Schristos      */
999212397c6Schristos     init_block(s);
1000212397c6Schristos 
1001212397c6Schristos     if (last) {
1002212397c6Schristos         bi_windup(s);
1003796c32c9Schristos #ifdef ZLIB_DEBUG
1004212397c6Schristos         s->compressed_len += 7;  /* align on byte boundary */
1005212397c6Schristos #endif
1006212397c6Schristos     }
1007212397c6Schristos     Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
1008212397c6Schristos            s->compressed_len-7*last));
1009212397c6Schristos }
1010212397c6Schristos 
1011212397c6Schristos /* ===========================================================================
1012212397c6Schristos  * Save the match info and tally the frequency counts. Return true if
1013212397c6Schristos  * the current block must be flushed.
1014212397c6Schristos  */
_tr_tally(s,dist,lc)1015212397c6Schristos int ZLIB_INTERNAL _tr_tally (s, dist, lc)
1016212397c6Schristos     deflate_state *s;
1017212397c6Schristos     unsigned dist;  /* distance of matched string */
1018212397c6Schristos     unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
1019212397c6Schristos {
1020*924795e6Schristos     s->sym_buf[s->sym_next++] = dist;
1021*924795e6Schristos     s->sym_buf[s->sym_next++] = dist >> 8;
1022*924795e6Schristos     s->sym_buf[s->sym_next++] = lc;
1023212397c6Schristos     if (dist == 0) {
1024212397c6Schristos         /* lc is the unmatched char */
1025212397c6Schristos         s->dyn_ltree[lc].Freq++;
1026212397c6Schristos     } else {
1027212397c6Schristos         s->matches++;
1028212397c6Schristos         /* Here, lc is the match length - MIN_MATCH */
1029212397c6Schristos         dist--;             /* dist = match distance - 1 */
1030212397c6Schristos         Assert((ush)dist < (ush)MAX_DIST(s) &&
1031212397c6Schristos                (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
1032212397c6Schristos                (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
1033212397c6Schristos 
1034212397c6Schristos         s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
1035212397c6Schristos         s->dyn_dtree[d_code(dist)].Freq++;
1036212397c6Schristos     }
1037*924795e6Schristos     return (s->sym_next == s->sym_end);
1038212397c6Schristos }
1039212397c6Schristos 
1040212397c6Schristos /* ===========================================================================
1041212397c6Schristos  * Send the block data compressed using the given Huffman trees
1042212397c6Schristos  */
compress_block(s,ltree,dtree)1043212397c6Schristos local void compress_block(s, ltree, dtree)
1044212397c6Schristos     deflate_state *s;
1045ba340e45Schristos     const ct_data *ltree; /* literal tree */
1046ba340e45Schristos     const ct_data *dtree; /* distance tree */
1047212397c6Schristos {
1048212397c6Schristos     unsigned dist;      /* distance of matched string */
1049212397c6Schristos     int lc;             /* match length or unmatched char (if dist == 0) */
1050*924795e6Schristos     unsigned sx = 0;    /* running index in sym_buf */
1051212397c6Schristos     unsigned code;      /* the code to send */
1052212397c6Schristos     int extra;          /* number of extra bits to send */
1053212397c6Schristos 
1054*924795e6Schristos     if (s->sym_next != 0) do {
1055*924795e6Schristos         dist = s->sym_buf[sx++] & 0xff;
1056*924795e6Schristos         dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8;
1057*924795e6Schristos         lc = s->sym_buf[sx++];
1058212397c6Schristos         if (dist == 0) {
1059212397c6Schristos             send_code(s, lc, ltree); /* send a literal byte */
1060212397c6Schristos             Tracecv(isgraph(lc), (stderr," '%c' ", lc));
1061212397c6Schristos         } else {
1062212397c6Schristos             /* Here, lc is the match length - MIN_MATCH */
1063212397c6Schristos             code = _length_code[lc];
1064212397c6Schristos             send_code(s, code+LITERALS+1, ltree); /* send the length code */
1065212397c6Schristos             extra = extra_lbits[code];
1066212397c6Schristos             if (extra != 0) {
1067212397c6Schristos                 lc -= base_length[code];
1068212397c6Schristos                 send_bits(s, lc, extra);       /* send the extra length bits */
1069212397c6Schristos             }
1070212397c6Schristos             dist--; /* dist is now the match distance - 1 */
1071212397c6Schristos             code = d_code(dist);
1072212397c6Schristos             Assert (code < D_CODES, "bad d_code");
1073212397c6Schristos 
1074212397c6Schristos             send_code(s, code, dtree);       /* send the distance code */
1075212397c6Schristos             extra = extra_dbits[code];
1076212397c6Schristos             if (extra != 0) {
1077796c32c9Schristos                 dist -= (unsigned)base_dist[code];
1078212397c6Schristos                 send_bits(s, dist, extra);   /* send the extra distance bits */
1079212397c6Schristos             }
1080212397c6Schristos         } /* literal or match pair ? */
1081212397c6Schristos 
1082*924795e6Schristos         /* Check that the overlay between pending_buf and sym_buf is ok: */
1083*924795e6Schristos         Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow");
1084212397c6Schristos 
1085*924795e6Schristos     } while (sx < s->sym_next);
1086212397c6Schristos 
1087212397c6Schristos     send_code(s, END_BLOCK, ltree);
1088212397c6Schristos }
1089212397c6Schristos 
1090212397c6Schristos /* ===========================================================================
1091212397c6Schristos  * Check if the data type is TEXT or BINARY, using the following algorithm:
1092212397c6Schristos  * - TEXT if the two conditions below are satisfied:
1093212397c6Schristos  *    a) There are no non-portable control characters belonging to the
1094*924795e6Schristos  *       "block list" (0..6, 14..25, 28..31).
1095212397c6Schristos  *    b) There is at least one printable character belonging to the
1096*924795e6Schristos  *       "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
1097212397c6Schristos  * - BINARY otherwise.
1098212397c6Schristos  * - The following partially-portable control characters form a
1099212397c6Schristos  *   "gray list" that is ignored in this detection algorithm:
1100212397c6Schristos  *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
1101212397c6Schristos  * IN assertion: the fields Freq of dyn_ltree are set.
1102212397c6Schristos  */
detect_data_type(s)1103212397c6Schristos local int detect_data_type(s)
1104212397c6Schristos     deflate_state *s;
1105212397c6Schristos {
1106*924795e6Schristos     /* block_mask is the bit mask of block-listed bytes
1107212397c6Schristos      * set bits 0..6, 14..25, and 28..31
1108212397c6Schristos      * 0xf3ffc07f = binary 11110011111111111100000001111111
1109212397c6Schristos      */
1110*924795e6Schristos     unsigned long block_mask = 0xf3ffc07fUL;
1111212397c6Schristos     int n;
1112212397c6Schristos 
1113*924795e6Schristos     /* Check for non-textual ("block-listed") bytes. */
1114*924795e6Schristos     for (n = 0; n <= 31; n++, block_mask >>= 1)
1115*924795e6Schristos         if ((block_mask & 1) && (s->dyn_ltree[n].Freq != 0))
1116212397c6Schristos             return Z_BINARY;
1117212397c6Schristos 
1118*924795e6Schristos     /* Check for textual ("allow-listed") bytes. */
1119212397c6Schristos     if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
1120212397c6Schristos             || s->dyn_ltree[13].Freq != 0)
1121212397c6Schristos         return Z_TEXT;
1122212397c6Schristos     for (n = 32; n < LITERALS; n++)
1123212397c6Schristos         if (s->dyn_ltree[n].Freq != 0)
1124212397c6Schristos             return Z_TEXT;
1125212397c6Schristos 
1126*924795e6Schristos     /* There are no "block-listed" or "allow-listed" bytes:
1127212397c6Schristos      * this stream either is empty or has tolerated ("gray-listed") bytes only.
1128212397c6Schristos      */
1129212397c6Schristos     return Z_BINARY;
1130212397c6Schristos }
1131212397c6Schristos 
1132212397c6Schristos /* ===========================================================================
1133212397c6Schristos  * Reverse the first len bits of a code, using straightforward code (a faster
1134212397c6Schristos  * method would use a table)
1135212397c6Schristos  * IN assertion: 1 <= len <= 15
1136212397c6Schristos  */
bi_reverse(code,len)1137212397c6Schristos local unsigned bi_reverse(code, len)
1138212397c6Schristos     unsigned code; /* the value to invert */
1139212397c6Schristos     int len;       /* its bit length */
1140212397c6Schristos {
1141212397c6Schristos     register unsigned res = 0;
1142212397c6Schristos     do {
1143212397c6Schristos         res |= code & 1;
1144212397c6Schristos         code >>= 1, res <<= 1;
1145212397c6Schristos     } while (--len > 0);
1146212397c6Schristos     return res >> 1;
1147212397c6Schristos }
1148212397c6Schristos 
1149212397c6Schristos /* ===========================================================================
1150212397c6Schristos  * Flush the bit buffer, keeping at most 7 bits in it.
1151212397c6Schristos  */
bi_flush(s)1152212397c6Schristos local void bi_flush(s)
1153212397c6Schristos     deflate_state *s;
1154212397c6Schristos {
1155212397c6Schristos     if (s->bi_valid == 16) {
1156212397c6Schristos         put_short(s, s->bi_buf);
1157212397c6Schristos         s->bi_buf = 0;
1158212397c6Schristos         s->bi_valid = 0;
1159212397c6Schristos     } else if (s->bi_valid >= 8) {
1160212397c6Schristos         put_byte(s, (Byte)s->bi_buf);
1161212397c6Schristos         s->bi_buf >>= 8;
1162212397c6Schristos         s->bi_valid -= 8;
1163212397c6Schristos     }
1164212397c6Schristos }
1165212397c6Schristos 
1166212397c6Schristos /* ===========================================================================
1167212397c6Schristos  * Flush the bit buffer and align the output on a byte boundary
1168212397c6Schristos  */
bi_windup(s)1169212397c6Schristos local void bi_windup(s)
1170212397c6Schristos     deflate_state *s;
1171212397c6Schristos {
1172212397c6Schristos     if (s->bi_valid > 8) {
1173212397c6Schristos         put_short(s, s->bi_buf);
1174212397c6Schristos     } else if (s->bi_valid > 0) {
1175212397c6Schristos         put_byte(s, (Byte)s->bi_buf);
1176212397c6Schristos     }
1177212397c6Schristos     s->bi_buf = 0;
1178212397c6Schristos     s->bi_valid = 0;
1179796c32c9Schristos #ifdef ZLIB_DEBUG
1180212397c6Schristos     s->bits_sent = (s->bits_sent+7) & ~7;
1181212397c6Schristos #endif
1182212397c6Schristos }
1183