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