xref: /illumos-gate/usr/src/contrib/zlib/trees.c (revision 148fd93e)
1b8382935SToomas Soome /* trees.c -- output deflated data using Huffman coding
2*148fd93eSToomas Soome  * Copyright (C) 1995-2021 Jean-loup Gailly
3b8382935SToomas Soome  * detect_data_type() function provided freely by Cosmin Truta, 2006
4b8382935SToomas Soome  * For conditions of distribution and use, see copyright notice in zlib.h
5b8382935SToomas Soome  */
6b8382935SToomas Soome 
7b8382935SToomas Soome /*
8b8382935SToomas Soome  *  ALGORITHM
9b8382935SToomas Soome  *
10b8382935SToomas Soome  *      The "deflation" process uses several Huffman trees. The more
11b8382935SToomas Soome  *      common source values are represented by shorter bit sequences.
12b8382935SToomas Soome  *
13b8382935SToomas Soome  *      Each code tree is stored in a compressed form which is itself
14b8382935SToomas Soome  * a Huffman encoding of the lengths of all the code strings (in
15b8382935SToomas Soome  * ascending order by source values).  The actual code strings are
16b8382935SToomas Soome  * reconstructed from the lengths in the inflate process, as described
17b8382935SToomas Soome  * in the deflate specification.
18b8382935SToomas Soome  *
19b8382935SToomas Soome  *  REFERENCES
20b8382935SToomas Soome  *
21b8382935SToomas Soome  *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
22b8382935SToomas Soome  *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
23b8382935SToomas Soome  *
24b8382935SToomas Soome  *      Storer, James A.
25b8382935SToomas Soome  *          Data Compression:  Methods and Theory, pp. 49-50.
26b8382935SToomas Soome  *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
27b8382935SToomas Soome  *
28b8382935SToomas Soome  *      Sedgewick, R.
29b8382935SToomas Soome  *          Algorithms, p290.
30b8382935SToomas Soome  *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
31b8382935SToomas Soome  */
32b8382935SToomas Soome 
33b8382935SToomas Soome /* @(#) $Id$ */
34b8382935SToomas Soome 
35b8382935SToomas Soome /* #define GEN_TREES_H */
36b8382935SToomas Soome 
37b8382935SToomas Soome #include "deflate.h"
38b8382935SToomas Soome 
39b8382935SToomas Soome #ifdef ZLIB_DEBUG
40b8382935SToomas Soome #  include <ctype.h>
41b8382935SToomas Soome #endif
42b8382935SToomas Soome 
43b8382935SToomas Soome /* ===========================================================================
44b8382935SToomas Soome  * Constants
45b8382935SToomas Soome  */
46b8382935SToomas Soome 
47b8382935SToomas Soome #define MAX_BL_BITS 7
48b8382935SToomas Soome /* Bit length codes must not exceed MAX_BL_BITS bits */
49b8382935SToomas Soome 
50b8382935SToomas Soome #define END_BLOCK 256
51b8382935SToomas Soome /* end of block literal code */
52b8382935SToomas Soome 
53b8382935SToomas Soome #define REP_3_6      16
54b8382935SToomas Soome /* repeat previous bit length 3-6 times (2 bits of repeat count) */
55b8382935SToomas Soome 
56b8382935SToomas Soome #define REPZ_3_10    17
57b8382935SToomas Soome /* repeat a zero length 3-10 times  (3 bits of repeat count) */
58b8382935SToomas Soome 
59b8382935SToomas Soome #define REPZ_11_138  18
60b8382935SToomas Soome /* repeat a zero length 11-138 times  (7 bits of repeat count) */
61b8382935SToomas Soome 
62b8382935SToomas Soome local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
63b8382935SToomas Soome    = {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};
64b8382935SToomas Soome 
65b8382935SToomas Soome local const int extra_dbits[D_CODES] /* extra bits for each distance code */
66b8382935SToomas Soome    = {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};
67b8382935SToomas Soome 
68b8382935SToomas Soome local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
69b8382935SToomas Soome    = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
70b8382935SToomas Soome 
71b8382935SToomas Soome local const uch bl_order[BL_CODES]
72b8382935SToomas Soome    = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
73b8382935SToomas Soome /* The lengths of the bit length codes are sent in order of decreasing
74b8382935SToomas Soome  * probability, to avoid transmitting the lengths for unused bit length codes.
75b8382935SToomas Soome  */
76b8382935SToomas Soome 
77b8382935SToomas Soome /* ===========================================================================
78b8382935SToomas Soome  * Local data. These are initialized only once.
79b8382935SToomas Soome  */
80b8382935SToomas Soome 
81b8382935SToomas Soome #define DIST_CODE_LEN  512 /* see definition of array dist_code below */
82b8382935SToomas Soome 
83b8382935SToomas Soome #if defined(GEN_TREES_H) || !defined(STDC)
84b8382935SToomas Soome /* non ANSI compilers may not accept trees.h */
85b8382935SToomas Soome 
86b8382935SToomas Soome local ct_data static_ltree[L_CODES+2];
87b8382935SToomas Soome /* The static literal tree. Since the bit lengths are imposed, there is no
88b8382935SToomas Soome  * need for the L_CODES extra codes used during heap construction. However
89b8382935SToomas Soome  * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
90b8382935SToomas Soome  * below).
91b8382935SToomas Soome  */
92b8382935SToomas Soome 
93b8382935SToomas Soome local ct_data static_dtree[D_CODES];
94b8382935SToomas Soome /* The static distance tree. (Actually a trivial tree since all codes use
95b8382935SToomas Soome  * 5 bits.)
96b8382935SToomas Soome  */
97b8382935SToomas Soome 
98b8382935SToomas Soome uch _dist_code[DIST_CODE_LEN];
99b8382935SToomas Soome /* Distance codes. The first 256 values correspond to the distances
100b8382935SToomas Soome  * 3 .. 258, the last 256 values correspond to the top 8 bits of
101b8382935SToomas Soome  * the 15 bit distances.
102b8382935SToomas Soome  */
103b8382935SToomas Soome 
104b8382935SToomas Soome uch _length_code[MAX_MATCH-MIN_MATCH+1];
105b8382935SToomas Soome /* length code for each normalized match length (0 == MIN_MATCH) */
106b8382935SToomas Soome 
107b8382935SToomas Soome local int base_length[LENGTH_CODES];
108b8382935SToomas Soome /* First normalized length for each code (0 = MIN_MATCH) */
109b8382935SToomas Soome 
110b8382935SToomas Soome local int base_dist[D_CODES];
111b8382935SToomas Soome /* First normalized distance for each code (0 = distance of 1) */
112b8382935SToomas Soome 
113b8382935SToomas Soome #else
114b8382935SToomas Soome #  include "trees.h"
115b8382935SToomas Soome #endif /* GEN_TREES_H */
116b8382935SToomas Soome 
117b8382935SToomas Soome struct static_tree_desc_s {
118b8382935SToomas Soome     const ct_data *static_tree;  /* static tree or NULL */
119b8382935SToomas Soome     const intf *extra_bits;      /* extra bits for each code or NULL */
120b8382935SToomas Soome     int     extra_base;          /* base index for extra_bits */
121b8382935SToomas Soome     int     elems;               /* max number of elements in the tree */
122b8382935SToomas Soome     int     max_length;          /* max bit length for the codes */
123b8382935SToomas Soome };
124b8382935SToomas Soome 
125b8382935SToomas Soome local const static_tree_desc  static_l_desc =
126b8382935SToomas Soome {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
127b8382935SToomas Soome 
128b8382935SToomas Soome local const static_tree_desc  static_d_desc =
129b8382935SToomas Soome {static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
130b8382935SToomas Soome 
131b8382935SToomas Soome local const static_tree_desc  static_bl_desc =
132b8382935SToomas Soome {(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
133b8382935SToomas Soome 
134b8382935SToomas Soome /* ===========================================================================
135b8382935SToomas Soome  * Local (static) routines in this file.
136b8382935SToomas Soome  */
137b8382935SToomas Soome 
138b8382935SToomas Soome local void tr_static_init OF((void));
139b8382935SToomas Soome local void init_block     OF((deflate_state *s));
140b8382935SToomas Soome local void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));
141b8382935SToomas Soome local void gen_bitlen     OF((deflate_state *s, tree_desc *desc));
142b8382935SToomas Soome local void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));
143b8382935SToomas Soome local void build_tree     OF((deflate_state *s, tree_desc *desc));
144b8382935SToomas Soome local void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));
145b8382935SToomas Soome local void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));
146b8382935SToomas Soome local int  build_bl_tree  OF((deflate_state *s));
147b8382935SToomas Soome local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
148b8382935SToomas Soome                               int blcodes));
149b8382935SToomas Soome local void compress_block OF((deflate_state *s, const ct_data *ltree,
150b8382935SToomas Soome                               const ct_data *dtree));
151b8382935SToomas Soome local int  detect_data_type OF((deflate_state *s));
152*148fd93eSToomas Soome local unsigned bi_reverse OF((unsigned code, int len));
153b8382935SToomas Soome local void bi_windup      OF((deflate_state *s));
154b8382935SToomas Soome local void bi_flush       OF((deflate_state *s));
155b8382935SToomas Soome 
156b8382935SToomas Soome #ifdef GEN_TREES_H
157b8382935SToomas Soome local void gen_trees_header OF((void));
158b8382935SToomas Soome #endif
159b8382935SToomas Soome 
160b8382935SToomas Soome #ifndef ZLIB_DEBUG
161b8382935SToomas Soome #  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
162b8382935SToomas Soome    /* Send a code of the given tree. c and tree must not have side effects */
163b8382935SToomas Soome 
164b8382935SToomas Soome #else /* !ZLIB_DEBUG */
165b8382935SToomas Soome #  define send_code(s, c, tree) \
166b8382935SToomas Soome      { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
167b8382935SToomas Soome        send_bits(s, tree[c].Code, tree[c].Len); }
168b8382935SToomas Soome #endif
169b8382935SToomas Soome 
170b8382935SToomas Soome /* ===========================================================================
171b8382935SToomas Soome  * Output a short LSB first on the stream.
172b8382935SToomas Soome  * IN assertion: there is enough room in pendingBuf.
173b8382935SToomas Soome  */
174b8382935SToomas Soome #define put_short(s, w) { \
175b8382935SToomas Soome     put_byte(s, (uch)((w) & 0xff)); \
176b8382935SToomas Soome     put_byte(s, (uch)((ush)(w) >> 8)); \
177b8382935SToomas Soome }
178b8382935SToomas Soome 
179b8382935SToomas Soome /* ===========================================================================
180b8382935SToomas Soome  * Send a value on a given number of bits.
181b8382935SToomas Soome  * IN assertion: length <= 16 and value fits in length bits.
182b8382935SToomas Soome  */
183b8382935SToomas Soome #ifdef ZLIB_DEBUG
184b8382935SToomas Soome local void send_bits      OF((deflate_state *s, int value, int length));
185b8382935SToomas Soome 
send_bits(s,value,length)186b8382935SToomas Soome local void send_bits(s, value, length)
187b8382935SToomas Soome     deflate_state *s;
188b8382935SToomas Soome     int value;  /* value to send */
189b8382935SToomas Soome     int length; /* number of bits */
190b8382935SToomas Soome {
191b8382935SToomas Soome     Tracevv((stderr," l %2d v %4x ", length, value));
192b8382935SToomas Soome     Assert(length > 0 && length <= 15, "invalid length");
193b8382935SToomas Soome     s->bits_sent += (ulg)length;
194b8382935SToomas Soome 
195b8382935SToomas Soome     /* If not enough room in bi_buf, use (valid) bits from bi_buf and
196b8382935SToomas Soome      * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
197b8382935SToomas Soome      * unused bits in value.
198b8382935SToomas Soome      */
199b8382935SToomas Soome     if (s->bi_valid > (int)Buf_size - length) {
200b8382935SToomas Soome         s->bi_buf |= (ush)value << s->bi_valid;
201b8382935SToomas Soome         put_short(s, s->bi_buf);
202b8382935SToomas Soome         s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
203b8382935SToomas Soome         s->bi_valid += length - Buf_size;
204b8382935SToomas Soome     } else {
205b8382935SToomas Soome         s->bi_buf |= (ush)value << s->bi_valid;
206b8382935SToomas Soome         s->bi_valid += length;
207b8382935SToomas Soome     }
208b8382935SToomas Soome }
209b8382935SToomas Soome #else /* !ZLIB_DEBUG */
210b8382935SToomas Soome 
211b8382935SToomas Soome #define send_bits(s, value, length) \
212b8382935SToomas Soome { int len = length;\
213b8382935SToomas Soome   if (s->bi_valid > (int)Buf_size - len) {\
214b8382935SToomas Soome     int val = (int)value;\
215b8382935SToomas Soome     s->bi_buf |= (ush)val << s->bi_valid;\
216b8382935SToomas Soome     put_short(s, s->bi_buf);\
217b8382935SToomas Soome     s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
218b8382935SToomas Soome     s->bi_valid += len - Buf_size;\
219b8382935SToomas Soome   } else {\
220b8382935SToomas Soome     s->bi_buf |= (ush)(value) << s->bi_valid;\
221b8382935SToomas Soome     s->bi_valid += len;\
222b8382935SToomas Soome   }\
223b8382935SToomas Soome }
224b8382935SToomas Soome #endif /* ZLIB_DEBUG */
225b8382935SToomas Soome 
226b8382935SToomas Soome 
227b8382935SToomas Soome /* the arguments must not have side effects */
228b8382935SToomas Soome 
229b8382935SToomas Soome /* ===========================================================================
230b8382935SToomas Soome  * Initialize the various 'constant' tables.
231b8382935SToomas Soome  */
tr_static_init()232b8382935SToomas Soome local void tr_static_init()
233b8382935SToomas Soome {
234b8382935SToomas Soome #if defined(GEN_TREES_H) || !defined(STDC)
235b8382935SToomas Soome     static int static_init_done = 0;
236b8382935SToomas Soome     int n;        /* iterates over tree elements */
237b8382935SToomas Soome     int bits;     /* bit counter */
238b8382935SToomas Soome     int length;   /* length value */
239b8382935SToomas Soome     int code;     /* code value */
240b8382935SToomas Soome     int dist;     /* distance index */
241b8382935SToomas Soome     ush bl_count[MAX_BITS+1];
242b8382935SToomas Soome     /* number of codes at each bit length for an optimal tree */
243b8382935SToomas Soome 
244b8382935SToomas Soome     if (static_init_done) return;
245b8382935SToomas Soome 
246b8382935SToomas Soome     /* For some embedded targets, global variables are not initialized: */
247b8382935SToomas Soome #ifdef NO_INIT_GLOBAL_POINTERS
248b8382935SToomas Soome     static_l_desc.static_tree = static_ltree;
249b8382935SToomas Soome     static_l_desc.extra_bits = extra_lbits;
250b8382935SToomas Soome     static_d_desc.static_tree = static_dtree;
251b8382935SToomas Soome     static_d_desc.extra_bits = extra_dbits;
252b8382935SToomas Soome     static_bl_desc.extra_bits = extra_blbits;
253b8382935SToomas Soome #endif
254b8382935SToomas Soome 
255b8382935SToomas Soome     /* Initialize the mapping length (0..255) -> length code (0..28) */
256b8382935SToomas Soome     length = 0;
257b8382935SToomas Soome     for (code = 0; code < LENGTH_CODES-1; code++) {
258b8382935SToomas Soome         base_length[code] = length;
259b8382935SToomas Soome         for (n = 0; n < (1<<extra_lbits[code]); n++) {
260b8382935SToomas Soome             _length_code[length++] = (uch)code;
261b8382935SToomas Soome         }
262b8382935SToomas Soome     }
263b8382935SToomas Soome     Assert (length == 256, "tr_static_init: length != 256");
264b8382935SToomas Soome     /* Note that the length 255 (match length 258) can be represented
265b8382935SToomas Soome      * in two different ways: code 284 + 5 bits or code 285, so we
266b8382935SToomas Soome      * overwrite length_code[255] to use the best encoding:
267b8382935SToomas Soome      */
268b8382935SToomas Soome     _length_code[length-1] = (uch)code;
269b8382935SToomas Soome 
270b8382935SToomas Soome     /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
271b8382935SToomas Soome     dist = 0;
272b8382935SToomas Soome     for (code = 0 ; code < 16; code++) {
273b8382935SToomas Soome         base_dist[code] = dist;
274b8382935SToomas Soome         for (n = 0; n < (1<<extra_dbits[code]); n++) {
275b8382935SToomas Soome             _dist_code[dist++] = (uch)code;
276b8382935SToomas Soome         }
277b8382935SToomas Soome     }
278b8382935SToomas Soome     Assert (dist == 256, "tr_static_init: dist != 256");
279b8382935SToomas Soome     dist >>= 7; /* from now on, all distances are divided by 128 */
280b8382935SToomas Soome     for ( ; code < D_CODES; code++) {
281b8382935SToomas Soome         base_dist[code] = dist << 7;
282b8382935SToomas Soome         for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
283b8382935SToomas Soome             _dist_code[256 + dist++] = (uch)code;
284b8382935SToomas Soome         }
285b8382935SToomas Soome     }
286b8382935SToomas Soome     Assert (dist == 256, "tr_static_init: 256+dist != 512");
287b8382935SToomas Soome 
288b8382935SToomas Soome     /* Construct the codes of the static literal tree */
289b8382935SToomas Soome     for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
290b8382935SToomas Soome     n = 0;
291b8382935SToomas Soome     while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
292b8382935SToomas Soome     while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
293b8382935SToomas Soome     while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
294b8382935SToomas Soome     while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
295b8382935SToomas Soome     /* Codes 286 and 287 do not exist, but we must include them in the
296b8382935SToomas Soome      * tree construction to get a canonical Huffman tree (longest code
297b8382935SToomas Soome      * all ones)
298b8382935SToomas Soome      */
299b8382935SToomas Soome     gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
300b8382935SToomas Soome 
301b8382935SToomas Soome     /* The static distance tree is trivial: */
302b8382935SToomas Soome     for (n = 0; n < D_CODES; n++) {
303b8382935SToomas Soome         static_dtree[n].Len = 5;
304b8382935SToomas Soome         static_dtree[n].Code = bi_reverse((unsigned)n, 5);
305b8382935SToomas Soome     }
306b8382935SToomas Soome     static_init_done = 1;
307b8382935SToomas Soome 
308b8382935SToomas Soome #  ifdef GEN_TREES_H
309b8382935SToomas Soome     gen_trees_header();
310b8382935SToomas Soome #  endif
311b8382935SToomas Soome #endif /* defined(GEN_TREES_H) || !defined(STDC) */
312b8382935SToomas Soome }
313b8382935SToomas Soome 
314b8382935SToomas Soome /* ===========================================================================
315b8382935SToomas Soome  * Genererate the file trees.h describing the static trees.
316b8382935SToomas Soome  */
317b8382935SToomas Soome #ifdef GEN_TREES_H
318b8382935SToomas Soome #  ifndef ZLIB_DEBUG
319b8382935SToomas Soome #    include <stdio.h>
320b8382935SToomas Soome #  endif
321b8382935SToomas Soome 
322b8382935SToomas Soome #  define SEPARATOR(i, last, width) \
323b8382935SToomas Soome       ((i) == (last)? "\n};\n\n" :    \
324b8382935SToomas Soome        ((i) % (width) == (width)-1 ? ",\n" : ", "))
325b8382935SToomas Soome 
gen_trees_header()326b8382935SToomas Soome void gen_trees_header()
327b8382935SToomas Soome {
328b8382935SToomas Soome     FILE *header = fopen("trees.h", "w");
329b8382935SToomas Soome     int i;
330b8382935SToomas Soome 
331b8382935SToomas Soome     Assert (header != NULL, "Can't open trees.h");
332b8382935SToomas Soome     fprintf(header,
333b8382935SToomas Soome             "/* header created automatically with -DGEN_TREES_H */\n\n");
334b8382935SToomas Soome 
335b8382935SToomas Soome     fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
336b8382935SToomas Soome     for (i = 0; i < L_CODES+2; i++) {
337b8382935SToomas Soome         fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
338b8382935SToomas Soome                 static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
339b8382935SToomas Soome     }
340b8382935SToomas Soome 
341b8382935SToomas Soome     fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
342b8382935SToomas Soome     for (i = 0; i < D_CODES; i++) {
343b8382935SToomas Soome         fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
344b8382935SToomas Soome                 static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
345b8382935SToomas Soome     }
346b8382935SToomas Soome 
347b8382935SToomas Soome     fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
348b8382935SToomas Soome     for (i = 0; i < DIST_CODE_LEN; i++) {
349b8382935SToomas Soome         fprintf(header, "%2u%s", _dist_code[i],
350b8382935SToomas Soome                 SEPARATOR(i, DIST_CODE_LEN-1, 20));
351b8382935SToomas Soome     }
352b8382935SToomas Soome 
353b8382935SToomas Soome     fprintf(header,
354b8382935SToomas Soome         "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
355b8382935SToomas Soome     for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
356b8382935SToomas Soome         fprintf(header, "%2u%s", _length_code[i],
357b8382935SToomas Soome                 SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
358b8382935SToomas Soome     }
359b8382935SToomas Soome 
360b8382935SToomas Soome     fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
361b8382935SToomas Soome     for (i = 0; i < LENGTH_CODES; i++) {
362b8382935SToomas Soome         fprintf(header, "%1u%s", base_length[i],
363b8382935SToomas Soome                 SEPARATOR(i, LENGTH_CODES-1, 20));
364b8382935SToomas Soome     }
365b8382935SToomas Soome 
366b8382935SToomas Soome     fprintf(header, "local const int base_dist[D_CODES] = {\n");
367b8382935SToomas Soome     for (i = 0; i < D_CODES; i++) {
368b8382935SToomas Soome         fprintf(header, "%5u%s", base_dist[i],
369b8382935SToomas Soome                 SEPARATOR(i, D_CODES-1, 10));
370b8382935SToomas Soome     }
371b8382935SToomas Soome 
372b8382935SToomas Soome     fclose(header);
373b8382935SToomas Soome }
374b8382935SToomas Soome #endif /* GEN_TREES_H */
375b8382935SToomas Soome 
376b8382935SToomas Soome /* ===========================================================================
377b8382935SToomas Soome  * Initialize the tree data structures for a new zlib stream.
378b8382935SToomas Soome  */
_tr_init(s)379b8382935SToomas Soome void ZLIB_INTERNAL _tr_init(s)
380b8382935SToomas Soome     deflate_state *s;
381b8382935SToomas Soome {
382b8382935SToomas Soome     tr_static_init();
383b8382935SToomas Soome 
384b8382935SToomas Soome     s->l_desc.dyn_tree = s->dyn_ltree;
385b8382935SToomas Soome     s->l_desc.stat_desc = &static_l_desc;
386b8382935SToomas Soome 
387b8382935SToomas Soome     s->d_desc.dyn_tree = s->dyn_dtree;
388b8382935SToomas Soome     s->d_desc.stat_desc = &static_d_desc;
389b8382935SToomas Soome 
390b8382935SToomas Soome     s->bl_desc.dyn_tree = s->bl_tree;
391b8382935SToomas Soome     s->bl_desc.stat_desc = &static_bl_desc;
392b8382935SToomas Soome 
393b8382935SToomas Soome     s->bi_buf = 0;
394b8382935SToomas Soome     s->bi_valid = 0;
395b8382935SToomas Soome #ifdef ZLIB_DEBUG
396b8382935SToomas Soome     s->compressed_len = 0L;
397b8382935SToomas Soome     s->bits_sent = 0L;
398b8382935SToomas Soome #endif
399b8382935SToomas Soome 
400b8382935SToomas Soome     /* Initialize the first block of the first file: */
401b8382935SToomas Soome     init_block(s);
402b8382935SToomas Soome }
403b8382935SToomas Soome 
404b8382935SToomas Soome /* ===========================================================================
405b8382935SToomas Soome  * Initialize a new block.
406b8382935SToomas Soome  */
init_block(s)407b8382935SToomas Soome local void init_block(s)
408b8382935SToomas Soome     deflate_state *s;
409b8382935SToomas Soome {
410b8382935SToomas Soome     int n; /* iterates over tree elements */
411b8382935SToomas Soome 
412b8382935SToomas Soome     /* Initialize the trees. */
413b8382935SToomas Soome     for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
414b8382935SToomas Soome     for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
415b8382935SToomas Soome     for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
416b8382935SToomas Soome 
417b8382935SToomas Soome     s->dyn_ltree[END_BLOCK].Freq = 1;
418b8382935SToomas Soome     s->opt_len = s->static_len = 0L;
419*148fd93eSToomas Soome     s->sym_next = s->matches = 0;
420b8382935SToomas Soome }
421b8382935SToomas Soome 
422b8382935SToomas Soome #define SMALLEST 1
423b8382935SToomas Soome /* Index within the heap array of least frequent node in the Huffman tree */
424b8382935SToomas Soome 
425b8382935SToomas Soome 
426b8382935SToomas Soome /* ===========================================================================
427b8382935SToomas Soome  * Remove the smallest element from the heap and recreate the heap with
428b8382935SToomas Soome  * one less element. Updates heap and heap_len.
429b8382935SToomas Soome  */
430b8382935SToomas Soome #define pqremove(s, tree, top) \
431b8382935SToomas Soome {\
432b8382935SToomas Soome     top = s->heap[SMALLEST]; \
433b8382935SToomas Soome     s->heap[SMALLEST] = s->heap[s->heap_len--]; \
434b8382935SToomas Soome     pqdownheap(s, tree, SMALLEST); \
435b8382935SToomas Soome }
436b8382935SToomas Soome 
437b8382935SToomas Soome /* ===========================================================================
438b8382935SToomas Soome  * Compares to subtrees, using the tree depth as tie breaker when
439b8382935SToomas Soome  * the subtrees have equal frequency. This minimizes the worst case length.
440b8382935SToomas Soome  */
441b8382935SToomas Soome #define smaller(tree, n, m, depth) \
442b8382935SToomas Soome    (tree[n].Freq < tree[m].Freq || \
443b8382935SToomas Soome    (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
444b8382935SToomas Soome 
445b8382935SToomas Soome /* ===========================================================================
446b8382935SToomas Soome  * Restore the heap property by moving down the tree starting at node k,
447b8382935SToomas Soome  * exchanging a node with the smallest of its two sons if necessary, stopping
448b8382935SToomas Soome  * when the heap property is re-established (each father smaller than its
449b8382935SToomas Soome  * two sons).
450b8382935SToomas Soome  */
pqdownheap(s,tree,k)451b8382935SToomas Soome local void pqdownheap(s, tree, k)
452b8382935SToomas Soome     deflate_state *s;
453b8382935SToomas Soome     ct_data *tree;  /* the tree to restore */
454b8382935SToomas Soome     int k;               /* node to move down */
455b8382935SToomas Soome {
456b8382935SToomas Soome     int v = s->heap[k];
457b8382935SToomas Soome     int j = k << 1;  /* left son of k */
458b8382935SToomas Soome     while (j <= s->heap_len) {
459b8382935SToomas Soome         /* Set j to the smallest of the two sons: */
460b8382935SToomas Soome         if (j < s->heap_len &&
461b8382935SToomas Soome             smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
462b8382935SToomas Soome             j++;
463b8382935SToomas Soome         }
464b8382935SToomas Soome         /* Exit if v is smaller than both sons */
465b8382935SToomas Soome         if (smaller(tree, v, s->heap[j], s->depth)) break;
466b8382935SToomas Soome 
467b8382935SToomas Soome         /* Exchange v with the smallest son */
468b8382935SToomas Soome         s->heap[k] = s->heap[j];  k = j;
469b8382935SToomas Soome 
470b8382935SToomas Soome         /* And continue down the tree, setting j to the left son of k */
471b8382935SToomas Soome         j <<= 1;
472b8382935SToomas Soome     }
473b8382935SToomas Soome     s->heap[k] = v;
474b8382935SToomas Soome }
475b8382935SToomas Soome 
476b8382935SToomas Soome /* ===========================================================================
477b8382935SToomas Soome  * Compute the optimal bit lengths for a tree and update the total bit length
478b8382935SToomas Soome  * for the current block.
479b8382935SToomas Soome  * IN assertion: the fields freq and dad are set, heap[heap_max] and
480b8382935SToomas Soome  *    above are the tree nodes sorted by increasing frequency.
481b8382935SToomas Soome  * OUT assertions: the field len is set to the optimal bit length, the
482b8382935SToomas Soome  *     array bl_count contains the frequencies for each bit length.
483b8382935SToomas Soome  *     The length opt_len is updated; static_len is also updated if stree is
484b8382935SToomas Soome  *     not null.
485b8382935SToomas Soome  */
gen_bitlen(s,desc)486b8382935SToomas Soome local void gen_bitlen(s, desc)
487b8382935SToomas Soome     deflate_state *s;
488b8382935SToomas Soome     tree_desc *desc;    /* the tree descriptor */
489b8382935SToomas Soome {
490b8382935SToomas Soome     ct_data *tree        = desc->dyn_tree;
491b8382935SToomas Soome     int max_code         = desc->max_code;
492b8382935SToomas Soome     const ct_data *stree = desc->stat_desc->static_tree;
493b8382935SToomas Soome     const intf *extra    = desc->stat_desc->extra_bits;
494b8382935SToomas Soome     int base             = desc->stat_desc->extra_base;
495b8382935SToomas Soome     int max_length       = desc->stat_desc->max_length;
496b8382935SToomas Soome     int h;              /* heap index */
497b8382935SToomas Soome     int n, m;           /* iterate over the tree elements */
498b8382935SToomas Soome     int bits;           /* bit length */
499b8382935SToomas Soome     int xbits;          /* extra bits */
500b8382935SToomas Soome     ush f;              /* frequency */
501b8382935SToomas Soome     int overflow = 0;   /* number of elements with bit length too large */
502b8382935SToomas Soome 
503b8382935SToomas Soome     for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
504b8382935SToomas Soome 
505b8382935SToomas Soome     /* In a first pass, compute the optimal bit lengths (which may
506b8382935SToomas Soome      * overflow in the case of the bit length tree).
507b8382935SToomas Soome      */
508b8382935SToomas Soome     tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
509b8382935SToomas Soome 
510b8382935SToomas Soome     for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
511b8382935SToomas Soome         n = s->heap[h];
512b8382935SToomas Soome         bits = tree[tree[n].Dad].Len + 1;
513b8382935SToomas Soome         if (bits > max_length) bits = max_length, overflow++;
514b8382935SToomas Soome         tree[n].Len = (ush)bits;
515b8382935SToomas Soome         /* We overwrite tree[n].Dad which is no longer needed */
516b8382935SToomas Soome 
517b8382935SToomas Soome         if (n > max_code) continue; /* not a leaf node */
518b8382935SToomas Soome 
519b8382935SToomas Soome         s->bl_count[bits]++;
520b8382935SToomas Soome         xbits = 0;
521b8382935SToomas Soome         if (n >= base) xbits = extra[n-base];
522b8382935SToomas Soome         f = tree[n].Freq;
523b8382935SToomas Soome         s->opt_len += (ulg)f * (unsigned)(bits + xbits);
524b8382935SToomas Soome         if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits);
525b8382935SToomas Soome     }
526b8382935SToomas Soome     if (overflow == 0) return;
527b8382935SToomas Soome 
528b8382935SToomas Soome     Tracev((stderr,"\nbit length overflow\n"));
529b8382935SToomas Soome     /* This happens for example on obj2 and pic of the Calgary corpus */
530b8382935SToomas Soome 
531b8382935SToomas Soome     /* Find the first bit length which could increase: */
532b8382935SToomas Soome     do {
533b8382935SToomas Soome         bits = max_length-1;
534b8382935SToomas Soome         while (s->bl_count[bits] == 0) bits--;
535b8382935SToomas Soome         s->bl_count[bits]--;      /* move one leaf down the tree */
536b8382935SToomas Soome         s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
537b8382935SToomas Soome         s->bl_count[max_length]--;
538b8382935SToomas Soome         /* The brother of the overflow item also moves one step up,
539b8382935SToomas Soome          * but this does not affect bl_count[max_length]
540b8382935SToomas Soome          */
541b8382935SToomas Soome         overflow -= 2;
542b8382935SToomas Soome     } while (overflow > 0);
543b8382935SToomas Soome 
544b8382935SToomas Soome     /* Now recompute all bit lengths, scanning in increasing frequency.
545b8382935SToomas Soome      * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
546b8382935SToomas Soome      * lengths instead of fixing only the wrong ones. This idea is taken
547b8382935SToomas Soome      * from 'ar' written by Haruhiko Okumura.)
548b8382935SToomas Soome      */
549b8382935SToomas Soome     for (bits = max_length; bits != 0; bits--) {
550b8382935SToomas Soome         n = s->bl_count[bits];
551b8382935SToomas Soome         while (n != 0) {
552b8382935SToomas Soome             m = s->heap[--h];
553b8382935SToomas Soome             if (m > max_code) continue;
554b8382935SToomas Soome             if ((unsigned) tree[m].Len != (unsigned) bits) {
555b8382935SToomas Soome                 Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
556b8382935SToomas Soome                 s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq;
557b8382935SToomas Soome                 tree[m].Len = (ush)bits;
558b8382935SToomas Soome             }
559b8382935SToomas Soome             n--;
560b8382935SToomas Soome         }
561b8382935SToomas Soome     }
562b8382935SToomas Soome }
563b8382935SToomas Soome 
564b8382935SToomas Soome /* ===========================================================================
565b8382935SToomas Soome  * Generate the codes for a given tree and bit counts (which need not be
566b8382935SToomas Soome  * optimal).
567b8382935SToomas Soome  * IN assertion: the array bl_count contains the bit length statistics for
568b8382935SToomas Soome  * the given tree and the field len is set for all tree elements.
569b8382935SToomas Soome  * OUT assertion: the field code is set for all tree elements of non
570b8382935SToomas Soome  *     zero code length.
571b8382935SToomas Soome  */
gen_codes(tree,max_code,bl_count)572b8382935SToomas Soome local void gen_codes (tree, max_code, bl_count)
573b8382935SToomas Soome     ct_data *tree;             /* the tree to decorate */
574b8382935SToomas Soome     int max_code;              /* largest code with non zero frequency */
575b8382935SToomas Soome     ushf *bl_count;            /* number of codes at each bit length */
576b8382935SToomas Soome {
577b8382935SToomas Soome     ush next_code[MAX_BITS+1]; /* next code value for each bit length */
578b8382935SToomas Soome     unsigned code = 0;         /* running code value */
579b8382935SToomas Soome     int bits;                  /* bit index */
580b8382935SToomas Soome     int n;                     /* code index */
581b8382935SToomas Soome 
582b8382935SToomas Soome     /* The distribution counts are first used to generate the code values
583b8382935SToomas Soome      * without bit reversal.
584b8382935SToomas Soome      */
585b8382935SToomas Soome     for (bits = 1; bits <= MAX_BITS; bits++) {
586b8382935SToomas Soome         code = (code + bl_count[bits-1]) << 1;
587b8382935SToomas Soome         next_code[bits] = (ush)code;
588b8382935SToomas Soome     }
589b8382935SToomas Soome     /* Check that the bit counts in bl_count are consistent. The last code
590b8382935SToomas Soome      * must be all ones.
591b8382935SToomas Soome      */
592b8382935SToomas Soome     Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
593b8382935SToomas Soome             "inconsistent bit counts");
594b8382935SToomas Soome     Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
595b8382935SToomas Soome 
596b8382935SToomas Soome     for (n = 0;  n <= max_code; n++) {
597b8382935SToomas Soome         int len = tree[n].Len;
598b8382935SToomas Soome         if (len == 0) continue;
599b8382935SToomas Soome         /* Now reverse the bits */
600b8382935SToomas Soome         tree[n].Code = (ush)bi_reverse(next_code[len]++, len);
601b8382935SToomas Soome 
602b8382935SToomas Soome         Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
603b8382935SToomas Soome              n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
604b8382935SToomas Soome     }
605b8382935SToomas Soome }
606b8382935SToomas Soome 
607b8382935SToomas Soome /* ===========================================================================
608b8382935SToomas Soome  * Construct one Huffman tree and assigns the code bit strings and lengths.
609b8382935SToomas Soome  * Update the total bit length for the current block.
610b8382935SToomas Soome  * IN assertion: the field freq is set for all tree elements.
611b8382935SToomas Soome  * OUT assertions: the fields len and code are set to the optimal bit length
612b8382935SToomas Soome  *     and corresponding code. The length opt_len is updated; static_len is
613b8382935SToomas Soome  *     also updated if stree is not null. The field max_code is set.
614b8382935SToomas Soome  */
build_tree(s,desc)615b8382935SToomas Soome local void build_tree(s, desc)
616b8382935SToomas Soome     deflate_state *s;
617b8382935SToomas Soome     tree_desc *desc; /* the tree descriptor */
618b8382935SToomas Soome {
619b8382935SToomas Soome     ct_data *tree         = desc->dyn_tree;
620b8382935SToomas Soome     const ct_data *stree  = desc->stat_desc->static_tree;
621b8382935SToomas Soome     int elems             = desc->stat_desc->elems;
622b8382935SToomas Soome     int n, m;          /* iterate over heap elements */
623b8382935SToomas Soome     int max_code = -1; /* largest code with non zero frequency */
624b8382935SToomas Soome     int node;          /* new node being created */
625b8382935SToomas Soome 
626b8382935SToomas Soome     /* Construct the initial heap, with least frequent element in
627b8382935SToomas Soome      * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
628b8382935SToomas Soome      * heap[0] is not used.
629b8382935SToomas Soome      */
630b8382935SToomas Soome     s->heap_len = 0, s->heap_max = HEAP_SIZE;
631b8382935SToomas Soome 
632b8382935SToomas Soome     for (n = 0; n < elems; n++) {
633b8382935SToomas Soome         if (tree[n].Freq != 0) {
634b8382935SToomas Soome             s->heap[++(s->heap_len)] = max_code = n;
635b8382935SToomas Soome             s->depth[n] = 0;
636b8382935SToomas Soome         } else {
637b8382935SToomas Soome             tree[n].Len = 0;
638b8382935SToomas Soome         }
639b8382935SToomas Soome     }
640b8382935SToomas Soome 
641b8382935SToomas Soome     /* The pkzip format requires that at least one distance code exists,
642b8382935SToomas Soome      * and that at least one bit should be sent even if there is only one
643b8382935SToomas Soome      * possible code. So to avoid special checks later on we force at least
644b8382935SToomas Soome      * two codes of non zero frequency.
645b8382935SToomas Soome      */
646b8382935SToomas Soome     while (s->heap_len < 2) {
647b8382935SToomas Soome         node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
648b8382935SToomas Soome         tree[node].Freq = 1;
649b8382935SToomas Soome         s->depth[node] = 0;
650b8382935SToomas Soome         s->opt_len--; if (stree) s->static_len -= stree[node].Len;
651b8382935SToomas Soome         /* node is 0 or 1 so it does not have extra bits */
652b8382935SToomas Soome     }
653b8382935SToomas Soome     desc->max_code = max_code;
654b8382935SToomas Soome 
655b8382935SToomas Soome     /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
656b8382935SToomas Soome      * establish sub-heaps of increasing lengths:
657b8382935SToomas Soome      */
658b8382935SToomas Soome     for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
659b8382935SToomas Soome 
660b8382935SToomas Soome     /* Construct the Huffman tree by repeatedly combining the least two
661b8382935SToomas Soome      * frequent nodes.
662b8382935SToomas Soome      */
663b8382935SToomas Soome     node = elems;              /* next internal node of the tree */
664b8382935SToomas Soome     do {
665b8382935SToomas Soome         pqremove(s, tree, n);  /* n = node of least frequency */
666b8382935SToomas Soome         m = s->heap[SMALLEST]; /* m = node of next least frequency */
667b8382935SToomas Soome 
668b8382935SToomas Soome         s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
669b8382935SToomas Soome         s->heap[--(s->heap_max)] = m;
670b8382935SToomas Soome 
671b8382935SToomas Soome         /* Create a new node father of n and m */
672b8382935SToomas Soome         tree[node].Freq = tree[n].Freq + tree[m].Freq;
673b8382935SToomas Soome         s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
674b8382935SToomas Soome                                 s->depth[n] : s->depth[m]) + 1);
675b8382935SToomas Soome         tree[n].Dad = tree[m].Dad = (ush)node;
676b8382935SToomas Soome #ifdef DUMP_BL_TREE
677b8382935SToomas Soome         if (tree == s->bl_tree) {
678b8382935SToomas Soome             fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
679b8382935SToomas Soome                     node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
680b8382935SToomas Soome         }
681b8382935SToomas Soome #endif
682b8382935SToomas Soome         /* and insert the new node in the heap */
683b8382935SToomas Soome         s->heap[SMALLEST] = node++;
684b8382935SToomas Soome         pqdownheap(s, tree, SMALLEST);
685b8382935SToomas Soome 
686b8382935SToomas Soome     } while (s->heap_len >= 2);
687b8382935SToomas Soome 
688b8382935SToomas Soome     s->heap[--(s->heap_max)] = s->heap[SMALLEST];
689b8382935SToomas Soome 
690b8382935SToomas Soome     /* At this point, the fields freq and dad are set. We can now
691b8382935SToomas Soome      * generate the bit lengths.
692b8382935SToomas Soome      */
693b8382935SToomas Soome     gen_bitlen(s, (tree_desc *)desc);
694b8382935SToomas Soome 
695b8382935SToomas Soome     /* The field len is now set, we can generate the bit codes */
696b8382935SToomas Soome     gen_codes ((ct_data *)tree, max_code, s->bl_count);
697b8382935SToomas Soome }
698b8382935SToomas Soome 
699b8382935SToomas Soome /* ===========================================================================
700b8382935SToomas Soome  * Scan a literal or distance tree to determine the frequencies of the codes
701b8382935SToomas Soome  * in the bit length tree.
702b8382935SToomas Soome  */
scan_tree(s,tree,max_code)703b8382935SToomas Soome local void scan_tree (s, tree, max_code)
704b8382935SToomas Soome     deflate_state *s;
705b8382935SToomas Soome     ct_data *tree;   /* the tree to be scanned */
706b8382935SToomas Soome     int max_code;    /* and its largest code of non zero frequency */
707b8382935SToomas Soome {
708b8382935SToomas Soome     int n;                     /* iterates over all tree elements */
709b8382935SToomas Soome     int prevlen = -1;          /* last emitted length */
710b8382935SToomas Soome     int curlen;                /* length of current code */
711b8382935SToomas Soome     int nextlen = tree[0].Len; /* length of next code */
712b8382935SToomas Soome     int count = 0;             /* repeat count of the current code */
713b8382935SToomas Soome     int max_count = 7;         /* max repeat count */
714b8382935SToomas Soome     int min_count = 4;         /* min repeat count */
715b8382935SToomas Soome 
716b8382935SToomas Soome     if (nextlen == 0) max_count = 138, min_count = 3;
717b8382935SToomas Soome     tree[max_code+1].Len = (ush)0xffff; /* guard */
718b8382935SToomas Soome 
719b8382935SToomas Soome     for (n = 0; n <= max_code; n++) {
720b8382935SToomas Soome         curlen = nextlen; nextlen = tree[n+1].Len;
721b8382935SToomas Soome         if (++count < max_count && curlen == nextlen) {
722b8382935SToomas Soome             continue;
723b8382935SToomas Soome         } else if (count < min_count) {
724b8382935SToomas Soome             s->bl_tree[curlen].Freq += count;
725b8382935SToomas Soome         } else if (curlen != 0) {
726b8382935SToomas Soome             if (curlen != prevlen) s->bl_tree[curlen].Freq++;
727b8382935SToomas Soome             s->bl_tree[REP_3_6].Freq++;
728b8382935SToomas Soome         } else if (count <= 10) {
729b8382935SToomas Soome             s->bl_tree[REPZ_3_10].Freq++;
730b8382935SToomas Soome         } else {
731b8382935SToomas Soome             s->bl_tree[REPZ_11_138].Freq++;
732b8382935SToomas Soome         }
733b8382935SToomas Soome         count = 0; prevlen = curlen;
734b8382935SToomas Soome         if (nextlen == 0) {
735b8382935SToomas Soome             max_count = 138, min_count = 3;
736b8382935SToomas Soome         } else if (curlen == nextlen) {
737b8382935SToomas Soome             max_count = 6, min_count = 3;
738b8382935SToomas Soome         } else {
739b8382935SToomas Soome             max_count = 7, min_count = 4;
740b8382935SToomas Soome         }
741b8382935SToomas Soome     }
742b8382935SToomas Soome }
743b8382935SToomas Soome 
744b8382935SToomas Soome /* ===========================================================================
745b8382935SToomas Soome  * Send a literal or distance tree in compressed form, using the codes in
746b8382935SToomas Soome  * bl_tree.
747b8382935SToomas Soome  */
send_tree(s,tree,max_code)748b8382935SToomas Soome local void send_tree (s, tree, max_code)
749b8382935SToomas Soome     deflate_state *s;
750b8382935SToomas Soome     ct_data *tree; /* the tree to be scanned */
751b8382935SToomas Soome     int max_code;       /* and its largest code of non zero frequency */
752b8382935SToomas Soome {
753b8382935SToomas Soome     int n;                     /* iterates over all tree elements */
754b8382935SToomas Soome     int prevlen = -1;          /* last emitted length */
755b8382935SToomas Soome     int curlen;                /* length of current code */
756b8382935SToomas Soome     int nextlen = tree[0].Len; /* length of next code */
757b8382935SToomas Soome     int count = 0;             /* repeat count of the current code */
758b8382935SToomas Soome     int max_count = 7;         /* max repeat count */
759b8382935SToomas Soome     int min_count = 4;         /* min repeat count */
760b8382935SToomas Soome 
761b8382935SToomas Soome     /* tree[max_code+1].Len = -1; */  /* guard already set */
762b8382935SToomas Soome     if (nextlen == 0) max_count = 138, min_count = 3;
763b8382935SToomas Soome 
764b8382935SToomas Soome     for (n = 0; n <= max_code; n++) {
765b8382935SToomas Soome         curlen = nextlen; nextlen = tree[n+1].Len;
766b8382935SToomas Soome         if (++count < max_count && curlen == nextlen) {
767b8382935SToomas Soome             continue;
768b8382935SToomas Soome         } else if (count < min_count) {
769b8382935SToomas Soome             do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
770b8382935SToomas Soome 
771b8382935SToomas Soome         } else if (curlen != 0) {
772b8382935SToomas Soome             if (curlen != prevlen) {
773b8382935SToomas Soome                 send_code(s, curlen, s->bl_tree); count--;
774b8382935SToomas Soome             }
775b8382935SToomas Soome             Assert(count >= 3 && count <= 6, " 3_6?");
776b8382935SToomas Soome             send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
777b8382935SToomas Soome 
778b8382935SToomas Soome         } else if (count <= 10) {
779b8382935SToomas Soome             send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
780b8382935SToomas Soome 
781b8382935SToomas Soome         } else {
782b8382935SToomas Soome             send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
783b8382935SToomas Soome         }
784b8382935SToomas Soome         count = 0; prevlen = curlen;
785b8382935SToomas Soome         if (nextlen == 0) {
786b8382935SToomas Soome             max_count = 138, min_count = 3;
787b8382935SToomas Soome         } else if (curlen == nextlen) {
788b8382935SToomas Soome             max_count = 6, min_count = 3;
789b8382935SToomas Soome         } else {
790b8382935SToomas Soome             max_count = 7, min_count = 4;
791b8382935SToomas Soome         }
792b8382935SToomas Soome     }
793b8382935SToomas Soome }
794b8382935SToomas Soome 
795b8382935SToomas Soome /* ===========================================================================
796b8382935SToomas Soome  * Construct the Huffman tree for the bit lengths and return the index in
797b8382935SToomas Soome  * bl_order of the last bit length code to send.
798b8382935SToomas Soome  */
build_bl_tree(s)799b8382935SToomas Soome local int build_bl_tree(s)
800b8382935SToomas Soome     deflate_state *s;
801b8382935SToomas Soome {
802b8382935SToomas Soome     int max_blindex;  /* index of last bit length code of non zero freq */
803b8382935SToomas Soome 
804b8382935SToomas Soome     /* Determine the bit length frequencies for literal and distance trees */
805b8382935SToomas Soome     scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
806b8382935SToomas Soome     scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
807b8382935SToomas Soome 
808b8382935SToomas Soome     /* Build the bit length tree: */
809b8382935SToomas Soome     build_tree(s, (tree_desc *)(&(s->bl_desc)));
810b8382935SToomas Soome     /* opt_len now includes the length of the tree representations, except
811b8382935SToomas Soome      * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
812b8382935SToomas Soome      */
813b8382935SToomas Soome 
814b8382935SToomas Soome     /* Determine the number of bit length codes to send. The pkzip format
815b8382935SToomas Soome      * requires that at least 4 bit length codes be sent. (appnote.txt says
816b8382935SToomas Soome      * 3 but the actual value used is 4.)
817b8382935SToomas Soome      */
818b8382935SToomas Soome     for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
819b8382935SToomas Soome         if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
820b8382935SToomas Soome     }
821b8382935SToomas Soome     /* Update opt_len to include the bit length tree and counts */
822b8382935SToomas Soome     s->opt_len += 3*((ulg)max_blindex+1) + 5+5+4;
823b8382935SToomas Soome     Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
824b8382935SToomas Soome             s->opt_len, s->static_len));
825b8382935SToomas Soome 
826b8382935SToomas Soome     return max_blindex;
827b8382935SToomas Soome }
828b8382935SToomas Soome 
829b8382935SToomas Soome /* ===========================================================================
830b8382935SToomas Soome  * Send the header for a block using dynamic Huffman trees: the counts, the
831b8382935SToomas Soome  * lengths of the bit length codes, the literal tree and the distance tree.
832b8382935SToomas Soome  * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
833b8382935SToomas Soome  */
send_all_trees(s,lcodes,dcodes,blcodes)834b8382935SToomas Soome local void send_all_trees(s, lcodes, dcodes, blcodes)
835b8382935SToomas Soome     deflate_state *s;
836b8382935SToomas Soome     int lcodes, dcodes, blcodes; /* number of codes for each tree */
837b8382935SToomas Soome {
838b8382935SToomas Soome     int rank;                    /* index in bl_order */
839b8382935SToomas Soome 
840b8382935SToomas Soome     Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
841b8382935SToomas Soome     Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
842b8382935SToomas Soome             "too many codes");
843b8382935SToomas Soome     Tracev((stderr, "\nbl counts: "));
844b8382935SToomas Soome     send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
845b8382935SToomas Soome     send_bits(s, dcodes-1,   5);
846b8382935SToomas Soome     send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
847b8382935SToomas Soome     for (rank = 0; rank < blcodes; rank++) {
848b8382935SToomas Soome         Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
849b8382935SToomas Soome         send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
850b8382935SToomas Soome     }
851b8382935SToomas Soome     Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
852b8382935SToomas Soome 
853b8382935SToomas Soome     send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
854b8382935SToomas Soome     Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
855b8382935SToomas Soome 
856b8382935SToomas Soome     send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
857b8382935SToomas Soome     Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
858b8382935SToomas Soome }
859b8382935SToomas Soome 
860b8382935SToomas Soome /* ===========================================================================
861b8382935SToomas Soome  * Send a stored block
862b8382935SToomas Soome  */
_tr_stored_block(s,buf,stored_len,last)863b8382935SToomas Soome void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)
864b8382935SToomas Soome     deflate_state *s;
865b8382935SToomas Soome     charf *buf;       /* input block */
866b8382935SToomas Soome     ulg stored_len;   /* length of input block */
867b8382935SToomas Soome     int last;         /* one if this is the last block for a file */
868b8382935SToomas Soome {
869b8382935SToomas Soome     send_bits(s, (STORED_BLOCK<<1)+last, 3);    /* send block type */
870b8382935SToomas Soome     bi_windup(s);        /* align on byte boundary */
871b8382935SToomas Soome     put_short(s, (ush)stored_len);
872b8382935SToomas Soome     put_short(s, (ush)~stored_len);
873*148fd93eSToomas Soome     if (stored_len)
874*148fd93eSToomas Soome         zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len);
875b8382935SToomas Soome     s->pending += stored_len;
876b8382935SToomas Soome #ifdef ZLIB_DEBUG
877b8382935SToomas Soome     s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
878b8382935SToomas Soome     s->compressed_len += (stored_len + 4) << 3;
879b8382935SToomas Soome     s->bits_sent += 2*16;
880b8382935SToomas Soome     s->bits_sent += stored_len<<3;
881b8382935SToomas Soome #endif
882b8382935SToomas Soome }
883b8382935SToomas Soome 
884b8382935SToomas Soome /* ===========================================================================
885b8382935SToomas Soome  * Flush the bits in the bit buffer to pending output (leaves at most 7 bits)
886b8382935SToomas Soome  */
_tr_flush_bits(s)887b8382935SToomas Soome void ZLIB_INTERNAL _tr_flush_bits(s)
888b8382935SToomas Soome     deflate_state *s;
889b8382935SToomas Soome {
890b8382935SToomas Soome     bi_flush(s);
891b8382935SToomas Soome }
892b8382935SToomas Soome 
893b8382935SToomas Soome /* ===========================================================================
894b8382935SToomas Soome  * Send one empty static block to give enough lookahead for inflate.
895b8382935SToomas Soome  * This takes 10 bits, of which 7 may remain in the bit buffer.
896b8382935SToomas Soome  */
_tr_align(s)897b8382935SToomas Soome void ZLIB_INTERNAL _tr_align(s)
898b8382935SToomas Soome     deflate_state *s;
899b8382935SToomas Soome {
900b8382935SToomas Soome     send_bits(s, STATIC_TREES<<1, 3);
901b8382935SToomas Soome     send_code(s, END_BLOCK, static_ltree);
902b8382935SToomas Soome #ifdef ZLIB_DEBUG
903b8382935SToomas Soome     s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
904b8382935SToomas Soome #endif
905b8382935SToomas Soome     bi_flush(s);
906b8382935SToomas Soome }
907b8382935SToomas Soome 
908b8382935SToomas Soome /* ===========================================================================
909b8382935SToomas Soome  * Determine the best encoding for the current block: dynamic trees, static
910b8382935SToomas Soome  * trees or store, and write out the encoded block.
911b8382935SToomas Soome  */
_tr_flush_block(s,buf,stored_len,last)912b8382935SToomas Soome void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)
913b8382935SToomas Soome     deflate_state *s;
914b8382935SToomas Soome     charf *buf;       /* input block, or NULL if too old */
915b8382935SToomas Soome     ulg stored_len;   /* length of input block */
916b8382935SToomas Soome     int last;         /* one if this is the last block for a file */
917b8382935SToomas Soome {
918b8382935SToomas Soome     ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
919b8382935SToomas Soome     int max_blindex = 0;  /* index of last bit length code of non zero freq */
920b8382935SToomas Soome 
921b8382935SToomas Soome     /* Build the Huffman trees unless a stored block is forced */
922b8382935SToomas Soome     if (s->level > 0) {
923b8382935SToomas Soome 
924b8382935SToomas Soome         /* Check if the file is binary or text */
925b8382935SToomas Soome         if (s->strm->data_type == Z_UNKNOWN)
926b8382935SToomas Soome             s->strm->data_type = detect_data_type(s);
927b8382935SToomas Soome 
928b8382935SToomas Soome         /* Construct the literal and distance trees */
929b8382935SToomas Soome         build_tree(s, (tree_desc *)(&(s->l_desc)));
930b8382935SToomas Soome         Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
931b8382935SToomas Soome                 s->static_len));
932b8382935SToomas Soome 
933b8382935SToomas Soome         build_tree(s, (tree_desc *)(&(s->d_desc)));
934b8382935SToomas Soome         Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
935b8382935SToomas Soome                 s->static_len));
936b8382935SToomas Soome         /* At this point, opt_len and static_len are the total bit lengths of
937b8382935SToomas Soome          * the compressed block data, excluding the tree representations.
938b8382935SToomas Soome          */
939b8382935SToomas Soome 
940b8382935SToomas Soome         /* Build the bit length tree for the above two trees, and get the index
941b8382935SToomas Soome          * in bl_order of the last bit length code to send.
942b8382935SToomas Soome          */
943b8382935SToomas Soome         max_blindex = build_bl_tree(s);
944b8382935SToomas Soome 
945b8382935SToomas Soome         /* Determine the best encoding. Compute the block lengths in bytes. */
946b8382935SToomas Soome         opt_lenb = (s->opt_len+3+7)>>3;
947b8382935SToomas Soome         static_lenb = (s->static_len+3+7)>>3;
948b8382935SToomas Soome 
949b8382935SToomas Soome         Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
950b8382935SToomas Soome                 opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
951*148fd93eSToomas Soome                 s->sym_next / 3));
952b8382935SToomas Soome 
953b8382935SToomas Soome         if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
954b8382935SToomas Soome 
955b8382935SToomas Soome     } else {
956b8382935SToomas Soome         Assert(buf != (char*)0, "lost buf");
957b8382935SToomas Soome         opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
958b8382935SToomas Soome     }
959b8382935SToomas Soome 
960b8382935SToomas Soome #ifdef FORCE_STORED
961b8382935SToomas Soome     if (buf != (char*)0) { /* force stored block */
962b8382935SToomas Soome #else
963b8382935SToomas Soome     if (stored_len+4 <= opt_lenb && buf != (char*)0) {
964b8382935SToomas Soome                        /* 4: two words for the lengths */
965b8382935SToomas Soome #endif
966b8382935SToomas Soome         /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
967b8382935SToomas Soome          * Otherwise we can't have processed more than WSIZE input bytes since
968b8382935SToomas Soome          * the last block flush, because compression would have been
969b8382935SToomas Soome          * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
970b8382935SToomas Soome          * transform a block into a stored block.
971b8382935SToomas Soome          */
972b8382935SToomas Soome         _tr_stored_block(s, buf, stored_len, last);
973b8382935SToomas Soome 
974b8382935SToomas Soome #ifdef FORCE_STATIC
975b8382935SToomas Soome     } else if (static_lenb >= 0) { /* force static trees */
976b8382935SToomas Soome #else
977b8382935SToomas Soome     } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
978b8382935SToomas Soome #endif
979b8382935SToomas Soome         send_bits(s, (STATIC_TREES<<1)+last, 3);
980b8382935SToomas Soome         compress_block(s, (const ct_data *)static_ltree,
981b8382935SToomas Soome                        (const ct_data *)static_dtree);
982b8382935SToomas Soome #ifdef ZLIB_DEBUG
983b8382935SToomas Soome         s->compressed_len += 3 + s->static_len;
984b8382935SToomas Soome #endif
985b8382935SToomas Soome     } else {
986b8382935SToomas Soome         send_bits(s, (DYN_TREES<<1)+last, 3);
987b8382935SToomas Soome         send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
988b8382935SToomas Soome                        max_blindex+1);
989b8382935SToomas Soome         compress_block(s, (const ct_data *)s->dyn_ltree,
990b8382935SToomas Soome                        (const ct_data *)s->dyn_dtree);
991b8382935SToomas Soome #ifdef ZLIB_DEBUG
992b8382935SToomas Soome         s->compressed_len += 3 + s->opt_len;
993b8382935SToomas Soome #endif
994b8382935SToomas Soome     }
995b8382935SToomas Soome     Assert (s->compressed_len == s->bits_sent, "bad compressed size");
996b8382935SToomas Soome     /* The above check is made mod 2^32, for files larger than 512 MB
997b8382935SToomas Soome      * and uLong implemented on 32 bits.
998b8382935SToomas Soome      */
999b8382935SToomas Soome     init_block(s);
1000b8382935SToomas Soome 
1001b8382935SToomas Soome     if (last) {
1002b8382935SToomas Soome         bi_windup(s);
1003b8382935SToomas Soome #ifdef ZLIB_DEBUG
1004b8382935SToomas Soome         s->compressed_len += 7;  /* align on byte boundary */
1005b8382935SToomas Soome #endif
1006b8382935SToomas Soome     }
1007b8382935SToomas Soome     Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
1008b8382935SToomas Soome            s->compressed_len-7*last));
1009b8382935SToomas Soome }
1010b8382935SToomas Soome 
1011b8382935SToomas Soome /* ===========================================================================
1012b8382935SToomas Soome  * Save the match info and tally the frequency counts. Return true if
1013b8382935SToomas Soome  * the current block must be flushed.
1014b8382935SToomas Soome  */
_tr_tally(s,dist,lc)1015b8382935SToomas Soome int ZLIB_INTERNAL _tr_tally (s, dist, lc)
1016b8382935SToomas Soome     deflate_state *s;
1017b8382935SToomas Soome     unsigned dist;  /* distance of matched string */
1018b8382935SToomas Soome     unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
1019b8382935SToomas Soome {
1020*148fd93eSToomas Soome     s->sym_buf[s->sym_next++] = dist;
1021*148fd93eSToomas Soome     s->sym_buf[s->sym_next++] = dist >> 8;
1022*148fd93eSToomas Soome     s->sym_buf[s->sym_next++] = lc;
1023b8382935SToomas Soome     if (dist == 0) {
1024b8382935SToomas Soome         /* lc is the unmatched char */
1025b8382935SToomas Soome         s->dyn_ltree[lc].Freq++;
1026b8382935SToomas Soome     } else {
1027b8382935SToomas Soome         s->matches++;
1028b8382935SToomas Soome         /* Here, lc is the match length - MIN_MATCH */
1029b8382935SToomas Soome         dist--;             /* dist = match distance - 1 */
1030b8382935SToomas Soome         Assert((ush)dist < (ush)MAX_DIST(s) &&
1031b8382935SToomas Soome                (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
1032b8382935SToomas Soome                (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
1033b8382935SToomas Soome 
1034b8382935SToomas Soome         s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
1035b8382935SToomas Soome         s->dyn_dtree[d_code(dist)].Freq++;
1036b8382935SToomas Soome     }
1037*148fd93eSToomas Soome     return (s->sym_next == s->sym_end);
1038b8382935SToomas Soome }
1039b8382935SToomas Soome 
1040b8382935SToomas Soome /* ===========================================================================
1041b8382935SToomas Soome  * Send the block data compressed using the given Huffman trees
1042b8382935SToomas Soome  */
compress_block(s,ltree,dtree)1043b8382935SToomas Soome local void compress_block(s, ltree, dtree)
1044b8382935SToomas Soome     deflate_state *s;
1045b8382935SToomas Soome     const ct_data *ltree; /* literal tree */
1046b8382935SToomas Soome     const ct_data *dtree; /* distance tree */
1047b8382935SToomas Soome {
1048b8382935SToomas Soome     unsigned dist;      /* distance of matched string */
1049b8382935SToomas Soome     int lc;             /* match length or unmatched char (if dist == 0) */
1050*148fd93eSToomas Soome     unsigned sx = 0;    /* running index in sym_buf */
1051b8382935SToomas Soome     unsigned code;      /* the code to send */
1052b8382935SToomas Soome     int extra;          /* number of extra bits to send */
1053b8382935SToomas Soome 
1054*148fd93eSToomas Soome     if (s->sym_next != 0) do {
1055*148fd93eSToomas Soome         dist = s->sym_buf[sx++] & 0xff;
1056*148fd93eSToomas Soome         dist += (unsigned)(s->sym_buf[sx++] & 0xff) << 8;
1057*148fd93eSToomas Soome         lc = s->sym_buf[sx++];
1058b8382935SToomas Soome         if (dist == 0) {
1059b8382935SToomas Soome             send_code(s, lc, ltree); /* send a literal byte */
1060b8382935SToomas Soome             Tracecv(isgraph(lc), (stderr," '%c' ", lc));
1061b8382935SToomas Soome         } else {
1062b8382935SToomas Soome             /* Here, lc is the match length - MIN_MATCH */
1063b8382935SToomas Soome             code = _length_code[lc];
1064b8382935SToomas Soome             send_code(s, code+LITERALS+1, ltree); /* send the length code */
1065b8382935SToomas Soome             extra = extra_lbits[code];
1066b8382935SToomas Soome             if (extra != 0) {
1067b8382935SToomas Soome                 lc -= base_length[code];
1068b8382935SToomas Soome                 send_bits(s, lc, extra);       /* send the extra length bits */
1069b8382935SToomas Soome             }
1070b8382935SToomas Soome             dist--; /* dist is now the match distance - 1 */
1071b8382935SToomas Soome             code = d_code(dist);
1072b8382935SToomas Soome             Assert (code < D_CODES, "bad d_code");
1073b8382935SToomas Soome 
1074b8382935SToomas Soome             send_code(s, code, dtree);       /* send the distance code */
1075b8382935SToomas Soome             extra = extra_dbits[code];
1076b8382935SToomas Soome             if (extra != 0) {
1077b8382935SToomas Soome                 dist -= (unsigned)base_dist[code];
1078b8382935SToomas Soome                 send_bits(s, dist, extra);   /* send the extra distance bits */
1079b8382935SToomas Soome             }
1080b8382935SToomas Soome         } /* literal or match pair ? */
1081b8382935SToomas Soome 
1082*148fd93eSToomas Soome         /* Check that the overlay between pending_buf and sym_buf is ok: */
1083*148fd93eSToomas Soome         Assert(s->pending < s->lit_bufsize + sx, "pendingBuf overflow");
1084b8382935SToomas Soome 
1085*148fd93eSToomas Soome     } while (sx < s->sym_next);
1086b8382935SToomas Soome 
1087b8382935SToomas Soome     send_code(s, END_BLOCK, ltree);
1088b8382935SToomas Soome }
1089b8382935SToomas Soome 
1090b8382935SToomas Soome /* ===========================================================================
1091b8382935SToomas Soome  * Check if the data type is TEXT or BINARY, using the following algorithm:
1092b8382935SToomas Soome  * - TEXT if the two conditions below are satisfied:
1093b8382935SToomas Soome  *    a) There are no non-portable control characters belonging to the
1094*148fd93eSToomas Soome  *       "block list" (0..6, 14..25, 28..31).
1095b8382935SToomas Soome  *    b) There is at least one printable character belonging to the
1096*148fd93eSToomas Soome  *       "allow list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
1097b8382935SToomas Soome  * - BINARY otherwise.
1098b8382935SToomas Soome  * - The following partially-portable control characters form a
1099b8382935SToomas Soome  *   "gray list" that is ignored in this detection algorithm:
1100b8382935SToomas Soome  *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
1101b8382935SToomas Soome  * IN assertion: the fields Freq of dyn_ltree are set.
1102b8382935SToomas Soome  */
detect_data_type(s)1103b8382935SToomas Soome local int detect_data_type(s)
1104b8382935SToomas Soome     deflate_state *s;
1105b8382935SToomas Soome {
1106*148fd93eSToomas Soome     /* block_mask is the bit mask of block-listed bytes
1107b8382935SToomas Soome      * set bits 0..6, 14..25, and 28..31
1108b8382935SToomas Soome      * 0xf3ffc07f = binary 11110011111111111100000001111111
1109b8382935SToomas Soome      */
1110*148fd93eSToomas Soome     unsigned long block_mask = 0xf3ffc07fUL;
1111b8382935SToomas Soome     int n;
1112b8382935SToomas Soome 
1113*148fd93eSToomas Soome     /* Check for non-textual ("block-listed") bytes. */
1114*148fd93eSToomas Soome     for (n = 0; n <= 31; n++, block_mask >>= 1)
1115*148fd93eSToomas Soome         if ((block_mask & 1) && (s->dyn_ltree[n].Freq != 0))
1116b8382935SToomas Soome             return Z_BINARY;
1117b8382935SToomas Soome 
1118*148fd93eSToomas Soome     /* Check for textual ("allow-listed") bytes. */
1119b8382935SToomas Soome     if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
1120b8382935SToomas Soome             || s->dyn_ltree[13].Freq != 0)
1121b8382935SToomas Soome         return Z_TEXT;
1122b8382935SToomas Soome     for (n = 32; n < LITERALS; n++)
1123b8382935SToomas Soome         if (s->dyn_ltree[n].Freq != 0)
1124b8382935SToomas Soome             return Z_TEXT;
1125b8382935SToomas Soome 
1126*148fd93eSToomas Soome     /* There are no "block-listed" or "allow-listed" bytes:
1127b8382935SToomas Soome      * this stream either is empty or has tolerated ("gray-listed") bytes only.
1128b8382935SToomas Soome      */
1129b8382935SToomas Soome     return Z_BINARY;
1130b8382935SToomas Soome }
1131b8382935SToomas Soome 
1132b8382935SToomas Soome /* ===========================================================================
1133b8382935SToomas Soome  * Reverse the first len bits of a code, using straightforward code (a faster
1134b8382935SToomas Soome  * method would use a table)
1135b8382935SToomas Soome  * IN assertion: 1 <= len <= 15
1136b8382935SToomas Soome  */
bi_reverse(code,len)1137b8382935SToomas Soome local unsigned bi_reverse(code, len)
1138b8382935SToomas Soome     unsigned code; /* the value to invert */
1139b8382935SToomas Soome     int len;       /* its bit length */
1140b8382935SToomas Soome {
1141b8382935SToomas Soome     register unsigned res = 0;
1142b8382935SToomas Soome     do {
1143b8382935SToomas Soome         res |= code & 1;
1144b8382935SToomas Soome         code >>= 1, res <<= 1;
1145b8382935SToomas Soome     } while (--len > 0);
1146b8382935SToomas Soome     return res >> 1;
1147b8382935SToomas Soome }
1148b8382935SToomas Soome 
1149b8382935SToomas Soome /* ===========================================================================
1150b8382935SToomas Soome  * Flush the bit buffer, keeping at most 7 bits in it.
1151b8382935SToomas Soome  */
bi_flush(s)1152b8382935SToomas Soome local void bi_flush(s)
1153b8382935SToomas Soome     deflate_state *s;
1154b8382935SToomas Soome {
1155b8382935SToomas Soome     if (s->bi_valid == 16) {
1156b8382935SToomas Soome         put_short(s, s->bi_buf);
1157b8382935SToomas Soome         s->bi_buf = 0;
1158b8382935SToomas Soome         s->bi_valid = 0;
1159b8382935SToomas Soome     } else if (s->bi_valid >= 8) {
1160b8382935SToomas Soome         put_byte(s, (Byte)s->bi_buf);
1161b8382935SToomas Soome         s->bi_buf >>= 8;
1162b8382935SToomas Soome         s->bi_valid -= 8;
1163b8382935SToomas Soome     }
1164b8382935SToomas Soome }
1165b8382935SToomas Soome 
1166b8382935SToomas Soome /* ===========================================================================
1167b8382935SToomas Soome  * Flush the bit buffer and align the output on a byte boundary
1168b8382935SToomas Soome  */
bi_windup(s)1169b8382935SToomas Soome local void bi_windup(s)
1170b8382935SToomas Soome     deflate_state *s;
1171b8382935SToomas Soome {
1172b8382935SToomas Soome     if (s->bi_valid > 8) {
1173b8382935SToomas Soome         put_short(s, s->bi_buf);
1174b8382935SToomas Soome     } else if (s->bi_valid > 0) {
1175b8382935SToomas Soome         put_byte(s, (Byte)s->bi_buf);
1176b8382935SToomas Soome     }
1177b8382935SToomas Soome     s->bi_buf = 0;
1178b8382935SToomas Soome     s->bi_valid = 0;
1179b8382935SToomas Soome #ifdef ZLIB_DEBUG
1180b8382935SToomas Soome     s->bits_sent = (s->bits_sent+7) & ~7;
1181b8382935SToomas Soome #endif
1182b8382935SToomas Soome }
1183