xref: /illumos-gate/usr/src/contrib/zlib/deflate.c (revision 148fd93e)
1b8382935SToomas Soome /* deflate.c -- compress data using the deflation algorithm
2*148fd93eSToomas Soome  * Copyright (C) 1995-2022 Jean-loup Gailly and Mark Adler
3b8382935SToomas Soome  * For conditions of distribution and use, see copyright notice in zlib.h
4b8382935SToomas Soome  */
5b8382935SToomas Soome 
6b8382935SToomas Soome /*
7b8382935SToomas Soome  *  ALGORITHM
8b8382935SToomas Soome  *
9b8382935SToomas Soome  *      The "deflation" process depends on being able to identify portions
10b8382935SToomas Soome  *      of the input text which are identical to earlier input (within a
11b8382935SToomas Soome  *      sliding window trailing behind the input currently being processed).
12b8382935SToomas Soome  *
13b8382935SToomas Soome  *      The most straightforward technique turns out to be the fastest for
14b8382935SToomas Soome  *      most input files: try all possible matches and select the longest.
15b8382935SToomas Soome  *      The key feature of this algorithm is that insertions into the string
16b8382935SToomas Soome  *      dictionary are very simple and thus fast, and deletions are avoided
17b8382935SToomas Soome  *      completely. Insertions are performed at each input character, whereas
18b8382935SToomas Soome  *      string matches are performed only when the previous match ends. So it
19b8382935SToomas Soome  *      is preferable to spend more time in matches to allow very fast string
20b8382935SToomas Soome  *      insertions and avoid deletions. The matching algorithm for small
21b8382935SToomas Soome  *      strings is inspired from that of Rabin & Karp. A brute force approach
22b8382935SToomas Soome  *      is used to find longer strings when a small match has been found.
23b8382935SToomas Soome  *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
24b8382935SToomas Soome  *      (by Leonid Broukhis).
25b8382935SToomas Soome  *         A previous version of this file used a more sophisticated algorithm
26b8382935SToomas Soome  *      (by Fiala and Greene) which is guaranteed to run in linear amortized
27b8382935SToomas Soome  *      time, but has a larger average cost, uses more memory and is patented.
28b8382935SToomas Soome  *      However the F&G algorithm may be faster for some highly redundant
29b8382935SToomas Soome  *      files if the parameter max_chain_length (described below) is too large.
30b8382935SToomas Soome  *
31b8382935SToomas Soome  *  ACKNOWLEDGEMENTS
32b8382935SToomas Soome  *
33b8382935SToomas Soome  *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
34b8382935SToomas Soome  *      I found it in 'freeze' written by Leonid Broukhis.
35b8382935SToomas Soome  *      Thanks to many people for bug reports and testing.
36b8382935SToomas Soome  *
37b8382935SToomas Soome  *  REFERENCES
38b8382935SToomas Soome  *
39b8382935SToomas Soome  *      Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
40b8382935SToomas Soome  *      Available in http://tools.ietf.org/html/rfc1951
41b8382935SToomas Soome  *
42b8382935SToomas Soome  *      A description of the Rabin and Karp algorithm is given in the book
43b8382935SToomas Soome  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
44b8382935SToomas Soome  *
45b8382935SToomas Soome  *      Fiala,E.R., and Greene,D.H.
46b8382935SToomas Soome  *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
47b8382935SToomas Soome  *
48b8382935SToomas Soome  */
49b8382935SToomas Soome 
50b8382935SToomas Soome #include "deflate.h"
51b8382935SToomas Soome 
52b8382935SToomas Soome const char deflate_copyright[] =
53*148fd93eSToomas Soome    " deflate 1.2.12 Copyright 1995-2022 Jean-loup Gailly and Mark Adler ";
54b8382935SToomas Soome /*
55b8382935SToomas Soome   If you use the zlib library in a product, an acknowledgment is welcome
56b8382935SToomas Soome   in the documentation of your product. If for some reason you cannot
57b8382935SToomas Soome   include such an acknowledgment, I would appreciate that you keep this
58b8382935SToomas Soome   copyright string in the executable of your product.
59b8382935SToomas Soome  */
60b8382935SToomas Soome 
61b8382935SToomas Soome /* ===========================================================================
62b8382935SToomas Soome  *  Function prototypes.
63b8382935SToomas Soome  */
64b8382935SToomas Soome typedef enum {
65b8382935SToomas Soome     need_more,      /* block not completed, need more input or more output */
66b8382935SToomas Soome     block_done,     /* block flush performed */
67b8382935SToomas Soome     finish_started, /* finish started, need only more output at next deflate */
68b8382935SToomas Soome     finish_done     /* finish done, accept no more input or output */
69b8382935SToomas Soome } block_state;
70b8382935SToomas Soome 
71b8382935SToomas Soome typedef block_state (*compress_func) OF((deflate_state *s, int flush));
72b8382935SToomas Soome /* Compression function. Returns the block state after the call. */
73b8382935SToomas Soome 
74b8382935SToomas Soome local int deflateStateCheck      OF((z_streamp strm));
75b8382935SToomas Soome local void slide_hash     OF((deflate_state *s));
76b8382935SToomas Soome local void fill_window    OF((deflate_state *s));
77b8382935SToomas Soome local block_state deflate_stored OF((deflate_state *s, int flush));
78b8382935SToomas Soome local block_state deflate_fast   OF((deflate_state *s, int flush));
79b8382935SToomas Soome #ifndef FASTEST
80b8382935SToomas Soome local block_state deflate_slow   OF((deflate_state *s, int flush));
81b8382935SToomas Soome #endif
82b8382935SToomas Soome local block_state deflate_rle    OF((deflate_state *s, int flush));
83b8382935SToomas Soome local block_state deflate_huff   OF((deflate_state *s, int flush));
84b8382935SToomas Soome local void lm_init        OF((deflate_state *s));
85b8382935SToomas Soome local void putShortMSB    OF((deflate_state *s, uInt b));
86b8382935SToomas Soome local void flush_pending  OF((z_streamp strm));
87b8382935SToomas Soome local unsigned read_buf   OF((z_streamp strm, Bytef *buf, unsigned size));
88b8382935SToomas Soome #ifdef ASMV
89b8382935SToomas Soome #  pragma message("Assembler code may have bugs -- use at your own risk")
90b8382935SToomas Soome       void match_init OF((void)); /* asm code initialization */
91b8382935SToomas Soome       uInt longest_match  OF((deflate_state *s, IPos cur_match));
92b8382935SToomas Soome #else
93b8382935SToomas Soome local uInt longest_match  OF((deflate_state *s, IPos cur_match));
94b8382935SToomas Soome #endif
95b8382935SToomas Soome 
96b8382935SToomas Soome #ifdef ZLIB_DEBUG
97b8382935SToomas Soome local  void check_match OF((deflate_state *s, IPos start, IPos match,
98b8382935SToomas Soome                             int length));
99b8382935SToomas Soome #endif
100b8382935SToomas Soome 
101b8382935SToomas Soome /* ===========================================================================
102b8382935SToomas Soome  * Local data
103b8382935SToomas Soome  */
104b8382935SToomas Soome 
105b8382935SToomas Soome #define NIL 0
106b8382935SToomas Soome /* Tail of hash chains */
107b8382935SToomas Soome 
108b8382935SToomas Soome #ifndef TOO_FAR
109b8382935SToomas Soome #  define TOO_FAR 4096
110b8382935SToomas Soome #endif
111b8382935SToomas Soome /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
112b8382935SToomas Soome 
113b8382935SToomas Soome /* Values for max_lazy_match, good_match and max_chain_length, depending on
114b8382935SToomas Soome  * the desired pack level (0..9). The values given below have been tuned to
115b8382935SToomas Soome  * exclude worst case performance for pathological files. Better values may be
116b8382935SToomas Soome  * found for specific files.
117b8382935SToomas Soome  */
118b8382935SToomas Soome typedef struct config_s {
119b8382935SToomas Soome    ush good_length; /* reduce lazy search above this match length */
120b8382935SToomas Soome    ush max_lazy;    /* do not perform lazy search above this match length */
121b8382935SToomas Soome    ush nice_length; /* quit search above this match length */
122b8382935SToomas Soome    ush max_chain;
123b8382935SToomas Soome    compress_func func;
124b8382935SToomas Soome } config;
125b8382935SToomas Soome 
126b8382935SToomas Soome #ifdef FASTEST
127b8382935SToomas Soome local const config configuration_table[2] = {
128b8382935SToomas Soome /*      good lazy nice chain */
129b8382935SToomas Soome /* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
130b8382935SToomas Soome /* 1 */ {4,    4,  8,    4, deflate_fast}}; /* max speed, no lazy matches */
131b8382935SToomas Soome #else
132b8382935SToomas Soome local const config configuration_table[10] = {
133b8382935SToomas Soome /*      good lazy nice chain */
134b8382935SToomas Soome /* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
135b8382935SToomas Soome /* 1 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */
136b8382935SToomas Soome /* 2 */ {4,    5, 16,    8, deflate_fast},
137b8382935SToomas Soome /* 3 */ {4,    6, 32,   32, deflate_fast},
138b8382935SToomas Soome 
139b8382935SToomas Soome /* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
140b8382935SToomas Soome /* 5 */ {8,   16, 32,   32, deflate_slow},
141b8382935SToomas Soome /* 6 */ {8,   16, 128, 128, deflate_slow},
142b8382935SToomas Soome /* 7 */ {8,   32, 128, 256, deflate_slow},
143b8382935SToomas Soome /* 8 */ {32, 128, 258, 1024, deflate_slow},
144b8382935SToomas Soome /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
145b8382935SToomas Soome #endif
146b8382935SToomas Soome 
147b8382935SToomas Soome /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
148b8382935SToomas Soome  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
149b8382935SToomas Soome  * meaning.
150b8382935SToomas Soome  */
151b8382935SToomas Soome 
152b8382935SToomas Soome /* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */
153b8382935SToomas Soome #define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0))
154b8382935SToomas Soome 
155b8382935SToomas Soome /* ===========================================================================
156b8382935SToomas Soome  * Update a hash value with the given input byte
157b8382935SToomas Soome  * IN  assertion: all calls to UPDATE_HASH are made with consecutive input
158b8382935SToomas Soome  *    characters, so that a running hash key can be computed from the previous
159b8382935SToomas Soome  *    key instead of complete recalculation each time.
160b8382935SToomas Soome  */
161b8382935SToomas Soome #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
162b8382935SToomas Soome 
163b8382935SToomas Soome 
164b8382935SToomas Soome /* ===========================================================================
165b8382935SToomas Soome  * Insert string str in the dictionary and set match_head to the previous head
166b8382935SToomas Soome  * of the hash chain (the most recent string with same hash key). Return
167b8382935SToomas Soome  * the previous length of the hash chain.
168b8382935SToomas Soome  * If this file is compiled with -DFASTEST, the compression level is forced
169b8382935SToomas Soome  * to 1, and no hash chains are maintained.
170b8382935SToomas Soome  * IN  assertion: all calls to INSERT_STRING are made with consecutive input
171b8382935SToomas Soome  *    characters and the first MIN_MATCH bytes of str are valid (except for
172b8382935SToomas Soome  *    the last MIN_MATCH-1 bytes of the input file).
173b8382935SToomas Soome  */
174b8382935SToomas Soome #ifdef FASTEST
175b8382935SToomas Soome #define INSERT_STRING(s, str, match_head) \
176b8382935SToomas Soome    (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
177b8382935SToomas Soome     match_head = s->head[s->ins_h], \
178b8382935SToomas Soome     s->head[s->ins_h] = (Pos)(str))
179b8382935SToomas Soome #else
180b8382935SToomas Soome #define INSERT_STRING(s, str, match_head) \
181b8382935SToomas Soome    (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
182b8382935SToomas Soome     match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
183b8382935SToomas Soome     s->head[s->ins_h] = (Pos)(str))
184b8382935SToomas Soome #endif
185b8382935SToomas Soome 
186b8382935SToomas Soome /* ===========================================================================
187b8382935SToomas Soome  * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
188b8382935SToomas Soome  * prev[] will be initialized on the fly.
189b8382935SToomas Soome  */
190b8382935SToomas Soome #define CLEAR_HASH(s) \
1910ab6f519SMark Adler     do { \
1920ab6f519SMark Adler         s->head[s->hash_size-1] = NIL; \
1930ab6f519SMark Adler         zmemzero((Bytef *)s->head, \
194*148fd93eSToomas Soome                  (unsigned)(s->hash_size-1)*sizeof(*s->head)); \
1950ab6f519SMark Adler     } while (0)
196b8382935SToomas Soome 
197b8382935SToomas Soome /* ===========================================================================
198b8382935SToomas Soome  * Slide the hash table when sliding the window down (could be avoided with 32
199b8382935SToomas Soome  * bit values at the expense of memory usage). We slide even when level == 0 to
200b8382935SToomas Soome  * keep the hash table consistent if we switch back to level > 0 later.
201b8382935SToomas Soome  */
slide_hash(s)202b8382935SToomas Soome local void slide_hash(s)
203b8382935SToomas Soome     deflate_state *s;
204b8382935SToomas Soome {
205b8382935SToomas Soome     unsigned n, m;
206b8382935SToomas Soome     Posf *p;
207b8382935SToomas Soome     uInt wsize = s->w_size;
208b8382935SToomas Soome 
209b8382935SToomas Soome     n = s->hash_size;
210b8382935SToomas Soome     p = &s->head[n];
211b8382935SToomas Soome     do {
212b8382935SToomas Soome         m = *--p;
213b8382935SToomas Soome         *p = (Pos)(m >= wsize ? m - wsize : NIL);
214b8382935SToomas Soome     } while (--n);
215b8382935SToomas Soome     n = wsize;
216b8382935SToomas Soome #ifndef FASTEST
217b8382935SToomas Soome     p = &s->prev[n];
218b8382935SToomas Soome     do {
219b8382935SToomas Soome         m = *--p;
220b8382935SToomas Soome         *p = (Pos)(m >= wsize ? m - wsize : NIL);
221b8382935SToomas Soome         /* If n is not on any hash chain, prev[n] is garbage but
222b8382935SToomas Soome          * its value will never be used.
223b8382935SToomas Soome          */
224b8382935SToomas Soome     } while (--n);
225b8382935SToomas Soome #endif
226b8382935SToomas Soome }
227b8382935SToomas Soome 
228b8382935SToomas Soome /* ========================================================================= */
deflateInit_(strm,level,version,stream_size)229b8382935SToomas Soome int ZEXPORT deflateInit_(strm, level, version, stream_size)
230b8382935SToomas Soome     z_streamp strm;
231b8382935SToomas Soome     int level;
232b8382935SToomas Soome     const char *version;
233b8382935SToomas Soome     int stream_size;
234b8382935SToomas Soome {
235b8382935SToomas Soome     return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
236b8382935SToomas Soome                          Z_DEFAULT_STRATEGY, version, stream_size);
237b8382935SToomas Soome     /* To do: ignore strm->next_in if we use it as window */
238b8382935SToomas Soome }
239b8382935SToomas Soome 
240b8382935SToomas Soome /* ========================================================================= */
deflateInit2_(strm,level,method,windowBits,memLevel,strategy,version,stream_size)241b8382935SToomas Soome int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
242b8382935SToomas Soome                   version, stream_size)
243b8382935SToomas Soome     z_streamp strm;
244b8382935SToomas Soome     int  level;
245b8382935SToomas Soome     int  method;
246b8382935SToomas Soome     int  windowBits;
247b8382935SToomas Soome     int  memLevel;
248b8382935SToomas Soome     int  strategy;
249b8382935SToomas Soome     const char *version;
250b8382935SToomas Soome     int stream_size;
251b8382935SToomas Soome {
252b8382935SToomas Soome     deflate_state *s;
253b8382935SToomas Soome     int wrap = 1;
254b8382935SToomas Soome     static const char my_version[] = ZLIB_VERSION;
255b8382935SToomas Soome 
256b8382935SToomas Soome     if (version == Z_NULL || version[0] != my_version[0] ||
257b8382935SToomas Soome         stream_size != sizeof(z_stream)) {
258b8382935SToomas Soome         return Z_VERSION_ERROR;
259b8382935SToomas Soome     }
260b8382935SToomas Soome     if (strm == Z_NULL) return Z_STREAM_ERROR;
261b8382935SToomas Soome 
262b8382935SToomas Soome     strm->msg = Z_NULL;
263b8382935SToomas Soome     if (strm->zalloc == (alloc_func)0) {
264b8382935SToomas Soome #ifdef Z_SOLO
265b8382935SToomas Soome         return Z_STREAM_ERROR;
266b8382935SToomas Soome #else
267b8382935SToomas Soome         strm->zalloc = zcalloc;
268b8382935SToomas Soome         strm->opaque = (voidpf)0;
269b8382935SToomas Soome #endif
270b8382935SToomas Soome     }
271b8382935SToomas Soome     if (strm->zfree == (free_func)0)
272b8382935SToomas Soome #ifdef Z_SOLO
273b8382935SToomas Soome         return Z_STREAM_ERROR;
274b8382935SToomas Soome #else
275b8382935SToomas Soome         strm->zfree = zcfree;
276b8382935SToomas Soome #endif
277b8382935SToomas Soome 
278b8382935SToomas Soome #ifdef FASTEST
279b8382935SToomas Soome     if (level != 0) level = 1;
280b8382935SToomas Soome #else
281b8382935SToomas Soome     if (level == Z_DEFAULT_COMPRESSION) level = 6;
282b8382935SToomas Soome #endif
283b8382935SToomas Soome 
284b8382935SToomas Soome     if (windowBits < 0) { /* suppress zlib wrapper */
285b8382935SToomas Soome         wrap = 0;
286b8382935SToomas Soome         windowBits = -windowBits;
287b8382935SToomas Soome     }
288b8382935SToomas Soome #ifdef GZIP
289b8382935SToomas Soome     else if (windowBits > 15) {
290b8382935SToomas Soome         wrap = 2;       /* write gzip wrapper instead */
291b8382935SToomas Soome         windowBits -= 16;
292b8382935SToomas Soome     }
293b8382935SToomas Soome #endif
294b8382935SToomas Soome     if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
295b8382935SToomas Soome         windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
296b8382935SToomas Soome         strategy < 0 || strategy > Z_FIXED || (windowBits == 8 && wrap != 1)) {
297b8382935SToomas Soome         return Z_STREAM_ERROR;
298b8382935SToomas Soome     }
299b8382935SToomas Soome     if (windowBits == 8) windowBits = 9;  /* until 256-byte window bug fixed */
300b8382935SToomas Soome     s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
301b8382935SToomas Soome     if (s == Z_NULL) return Z_MEM_ERROR;
302b8382935SToomas Soome     strm->state = (struct internal_state FAR *)s;
303b8382935SToomas Soome     s->strm = strm;
304b8382935SToomas Soome     s->status = INIT_STATE;     /* to pass state test in deflateReset() */
305b8382935SToomas Soome 
306b8382935SToomas Soome     s->wrap = wrap;
307b8382935SToomas Soome     s->gzhead = Z_NULL;
308b8382935SToomas Soome     s->w_bits = (uInt)windowBits;
309b8382935SToomas Soome     s->w_size = 1 << s->w_bits;
310b8382935SToomas Soome     s->w_mask = s->w_size - 1;
311b8382935SToomas Soome 
312b8382935SToomas Soome     s->hash_bits = (uInt)memLevel + 7;
313b8382935SToomas Soome     s->hash_size = 1 << s->hash_bits;
314b8382935SToomas Soome     s->hash_mask = s->hash_size - 1;
315b8382935SToomas Soome     s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
316b8382935SToomas Soome 
317b8382935SToomas Soome     s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
318b8382935SToomas Soome     s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
319b8382935SToomas Soome     s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
320b8382935SToomas Soome 
321b8382935SToomas Soome     s->high_water = 0;      /* nothing written to s->window yet */
322b8382935SToomas Soome 
323b8382935SToomas Soome     s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
324b8382935SToomas Soome 
325*148fd93eSToomas Soome     /* We overlay pending_buf and sym_buf. This works since the average size
326*148fd93eSToomas Soome      * for length/distance pairs over any compressed block is assured to be 31
327*148fd93eSToomas Soome      * bits or less.
328*148fd93eSToomas Soome      *
329*148fd93eSToomas Soome      * Analysis: The longest fixed codes are a length code of 8 bits plus 5
330*148fd93eSToomas Soome      * extra bits, for lengths 131 to 257. The longest fixed distance codes are
331*148fd93eSToomas Soome      * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest
332*148fd93eSToomas Soome      * possible fixed-codes length/distance pair is then 31 bits total.
333*148fd93eSToomas Soome      *
334*148fd93eSToomas Soome      * sym_buf starts one-fourth of the way into pending_buf. So there are
335*148fd93eSToomas Soome      * three bytes in sym_buf for every four bytes in pending_buf. Each symbol
336*148fd93eSToomas Soome      * in sym_buf is three bytes -- two for the distance and one for the
337*148fd93eSToomas Soome      * literal/length. As each symbol is consumed, the pointer to the next
338*148fd93eSToomas Soome      * sym_buf value to read moves forward three bytes. From that symbol, up to
339*148fd93eSToomas Soome      * 31 bits are written to pending_buf. The closest the written pending_buf
340*148fd93eSToomas Soome      * bits gets to the next sym_buf symbol to read is just before the last
341*148fd93eSToomas Soome      * code is written. At that time, 31*(n-2) bits have been written, just
342*148fd93eSToomas Soome      * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at
343*148fd93eSToomas Soome      * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1
344*148fd93eSToomas Soome      * symbols are written.) The closest the writing gets to what is unread is
345*148fd93eSToomas Soome      * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and
346*148fd93eSToomas Soome      * can range from 128 to 32768.
347*148fd93eSToomas Soome      *
348*148fd93eSToomas Soome      * Therefore, at a minimum, there are 142 bits of space between what is
349*148fd93eSToomas Soome      * written and what is read in the overlain buffers, so the symbols cannot
350*148fd93eSToomas Soome      * be overwritten by the compressed data. That space is actually 139 bits,
351*148fd93eSToomas Soome      * due to the three-bit fixed-code block header.
352*148fd93eSToomas Soome      *
353*148fd93eSToomas Soome      * That covers the case where either Z_FIXED is specified, forcing fixed
354*148fd93eSToomas Soome      * codes, or when the use of fixed codes is chosen, because that choice
355*148fd93eSToomas Soome      * results in a smaller compressed block than dynamic codes. That latter
356*148fd93eSToomas Soome      * condition then assures that the above analysis also covers all dynamic
357*148fd93eSToomas Soome      * blocks. A dynamic-code block will only be chosen to be emitted if it has
358*148fd93eSToomas Soome      * fewer bits than a fixed-code block would for the same set of symbols.
359*148fd93eSToomas Soome      * Therefore its average symbol length is assured to be less than 31. So
360*148fd93eSToomas Soome      * the compressed data for a dynamic block also cannot overwrite the
361*148fd93eSToomas Soome      * symbols from which it is being constructed.
362*148fd93eSToomas Soome      */
363*148fd93eSToomas Soome 
364*148fd93eSToomas Soome     s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, 4);
365*148fd93eSToomas Soome     s->pending_buf_size = (ulg)s->lit_bufsize * 4;
366b8382935SToomas Soome 
367b8382935SToomas Soome     if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
368b8382935SToomas Soome         s->pending_buf == Z_NULL) {
369b8382935SToomas Soome         s->status = FINISH_STATE;
370b8382935SToomas Soome         strm->msg = ERR_MSG(Z_MEM_ERROR);
371b8382935SToomas Soome         deflateEnd (strm);
372b8382935SToomas Soome         return Z_MEM_ERROR;
373b8382935SToomas Soome     }
374*148fd93eSToomas Soome     s->sym_buf = s->pending_buf + s->lit_bufsize;
375*148fd93eSToomas Soome     s->sym_end = (s->lit_bufsize - 1) * 3;
376*148fd93eSToomas Soome     /* We avoid equality with lit_bufsize*3 because of wraparound at 64K
377*148fd93eSToomas Soome      * on 16 bit machines and because stored blocks are restricted to
378*148fd93eSToomas Soome      * 64K-1 bytes.
379*148fd93eSToomas Soome      */
380b8382935SToomas Soome 
381b8382935SToomas Soome     s->level = level;
382b8382935SToomas Soome     s->strategy = strategy;
383b8382935SToomas Soome     s->method = (Byte)method;
384b8382935SToomas Soome 
385b8382935SToomas Soome     return deflateReset(strm);
386b8382935SToomas Soome }
387b8382935SToomas Soome 
388b8382935SToomas Soome /* =========================================================================
389b8382935SToomas Soome  * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
390b8382935SToomas Soome  */
deflateStateCheck(strm)391b8382935SToomas Soome local int deflateStateCheck (strm)
392b8382935SToomas Soome     z_streamp strm;
393b8382935SToomas Soome {
394b8382935SToomas Soome     deflate_state *s;
395b8382935SToomas Soome     if (strm == Z_NULL ||
396b8382935SToomas Soome         strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
397b8382935SToomas Soome         return 1;
398b8382935SToomas Soome     s = strm->state;
399b8382935SToomas Soome     if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE &&
400b8382935SToomas Soome #ifdef GZIP
401b8382935SToomas Soome                                            s->status != GZIP_STATE &&
402b8382935SToomas Soome #endif
403b8382935SToomas Soome                                            s->status != EXTRA_STATE &&
404b8382935SToomas Soome                                            s->status != NAME_STATE &&
405b8382935SToomas Soome                                            s->status != COMMENT_STATE &&
406b8382935SToomas Soome                                            s->status != HCRC_STATE &&
407b8382935SToomas Soome                                            s->status != BUSY_STATE &&
408b8382935SToomas Soome                                            s->status != FINISH_STATE))
409b8382935SToomas Soome         return 1;
410b8382935SToomas Soome     return 0;
411b8382935SToomas Soome }
412b8382935SToomas Soome 
413b8382935SToomas Soome /* ========================================================================= */
deflateSetDictionary(strm,dictionary,dictLength)414b8382935SToomas Soome int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
415b8382935SToomas Soome     z_streamp strm;
416b8382935SToomas Soome     const Bytef *dictionary;
417b8382935SToomas Soome     uInt  dictLength;
418b8382935SToomas Soome {
419b8382935SToomas Soome     deflate_state *s;
420b8382935SToomas Soome     uInt str, n;
421b8382935SToomas Soome     int wrap;
422b8382935SToomas Soome     unsigned avail;
423b8382935SToomas Soome     z_const unsigned char *next;
424b8382935SToomas Soome 
425b8382935SToomas Soome     if (deflateStateCheck(strm) || dictionary == Z_NULL)
426b8382935SToomas Soome         return Z_STREAM_ERROR;
427b8382935SToomas Soome     s = strm->state;
428b8382935SToomas Soome     wrap = s->wrap;
429b8382935SToomas Soome     if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
430b8382935SToomas Soome         return Z_STREAM_ERROR;
431b8382935SToomas Soome 
432b8382935SToomas Soome     /* when using zlib wrappers, compute Adler-32 for provided dictionary */
433b8382935SToomas Soome     if (wrap == 1)
434b8382935SToomas Soome         strm->adler = adler32(strm->adler, dictionary, dictLength);
435b8382935SToomas Soome     s->wrap = 0;                    /* avoid computing Adler-32 in read_buf */
436b8382935SToomas Soome 
437b8382935SToomas Soome     /* if dictionary would fill window, just replace the history */
438b8382935SToomas Soome     if (dictLength >= s->w_size) {
439b8382935SToomas Soome         if (wrap == 0) {            /* already empty otherwise */
440b8382935SToomas Soome             CLEAR_HASH(s);
441b8382935SToomas Soome             s->strstart = 0;
442b8382935SToomas Soome             s->block_start = 0L;
443b8382935SToomas Soome             s->insert = 0;
444b8382935SToomas Soome         }
445b8382935SToomas Soome         dictionary += dictLength - s->w_size;  /* use the tail */
446b8382935SToomas Soome         dictLength = s->w_size;
447b8382935SToomas Soome     }
448b8382935SToomas Soome 
449b8382935SToomas Soome     /* insert dictionary into window and hash */
450b8382935SToomas Soome     avail = strm->avail_in;
451b8382935SToomas Soome     next = strm->next_in;
452b8382935SToomas Soome     strm->avail_in = dictLength;
453b8382935SToomas Soome     strm->next_in = (z_const Bytef *)dictionary;
454b8382935SToomas Soome     fill_window(s);
455b8382935SToomas Soome     while (s->lookahead >= MIN_MATCH) {
456b8382935SToomas Soome         str = s->strstart;
457b8382935SToomas Soome         n = s->lookahead - (MIN_MATCH-1);
458b8382935SToomas Soome         do {
459b8382935SToomas Soome             UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
460b8382935SToomas Soome #ifndef FASTEST
461b8382935SToomas Soome             s->prev[str & s->w_mask] = s->head[s->ins_h];
462b8382935SToomas Soome #endif
463b8382935SToomas Soome             s->head[s->ins_h] = (Pos)str;
464b8382935SToomas Soome             str++;
465b8382935SToomas Soome         } while (--n);
466b8382935SToomas Soome         s->strstart = str;
467b8382935SToomas Soome         s->lookahead = MIN_MATCH-1;
468b8382935SToomas Soome         fill_window(s);
469b8382935SToomas Soome     }
470b8382935SToomas Soome     s->strstart += s->lookahead;
471b8382935SToomas Soome     s->block_start = (long)s->strstart;
472b8382935SToomas Soome     s->insert = s->lookahead;
473b8382935SToomas Soome     s->lookahead = 0;
474b8382935SToomas Soome     s->match_length = s->prev_length = MIN_MATCH-1;
475b8382935SToomas Soome     s->match_available = 0;
476b8382935SToomas Soome     strm->next_in = next;
477b8382935SToomas Soome     strm->avail_in = avail;
478b8382935SToomas Soome     s->wrap = wrap;
479b8382935SToomas Soome     return Z_OK;
480b8382935SToomas Soome }
481b8382935SToomas Soome 
482b8382935SToomas Soome /* ========================================================================= */
deflateGetDictionary(strm,dictionary,dictLength)483b8382935SToomas Soome int ZEXPORT deflateGetDictionary (strm, dictionary, dictLength)
484b8382935SToomas Soome     z_streamp strm;
485b8382935SToomas Soome     Bytef *dictionary;
486b8382935SToomas Soome     uInt  *dictLength;
487b8382935SToomas Soome {
488b8382935SToomas Soome     deflate_state *s;
489b8382935SToomas Soome     uInt len;
490b8382935SToomas Soome 
491b8382935SToomas Soome     if (deflateStateCheck(strm))
492b8382935SToomas Soome         return Z_STREAM_ERROR;
493b8382935SToomas Soome     s = strm->state;
494b8382935SToomas Soome     len = s->strstart + s->lookahead;
495b8382935SToomas Soome     if (len > s->w_size)
496b8382935SToomas Soome         len = s->w_size;
497b8382935SToomas Soome     if (dictionary != Z_NULL && len)
498b8382935SToomas Soome         zmemcpy(dictionary, s->window + s->strstart + s->lookahead - len, len);
499b8382935SToomas Soome     if (dictLength != Z_NULL)
500b8382935SToomas Soome         *dictLength = len;
501b8382935SToomas Soome     return Z_OK;
502b8382935SToomas Soome }
503b8382935SToomas Soome 
504b8382935SToomas Soome /* ========================================================================= */
deflateResetKeep(strm)505b8382935SToomas Soome int ZEXPORT deflateResetKeep (strm)
506b8382935SToomas Soome     z_streamp strm;
507b8382935SToomas Soome {
508b8382935SToomas Soome     deflate_state *s;
509b8382935SToomas Soome 
510b8382935SToomas Soome     if (deflateStateCheck(strm)) {
511b8382935SToomas Soome         return Z_STREAM_ERROR;
512b8382935SToomas Soome     }
513b8382935SToomas Soome 
514b8382935SToomas Soome     strm->total_in = strm->total_out = 0;
515b8382935SToomas Soome     strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
516b8382935SToomas Soome     strm->data_type = Z_UNKNOWN;
517b8382935SToomas Soome 
518b8382935SToomas Soome     s = (deflate_state *)strm->state;
519b8382935SToomas Soome     s->pending = 0;
520b8382935SToomas Soome     s->pending_out = s->pending_buf;
521b8382935SToomas Soome 
522b8382935SToomas Soome     if (s->wrap < 0) {
523b8382935SToomas Soome         s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
524b8382935SToomas Soome     }
525b8382935SToomas Soome     s->status =
526b8382935SToomas Soome #ifdef GZIP
527b8382935SToomas Soome         s->wrap == 2 ? GZIP_STATE :
528b8382935SToomas Soome #endif
529*148fd93eSToomas Soome         INIT_STATE;
530b8382935SToomas Soome     strm->adler =
531b8382935SToomas Soome #ifdef GZIP
532b8382935SToomas Soome         s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
533b8382935SToomas Soome #endif
534b8382935SToomas Soome         adler32(0L, Z_NULL, 0);
535*148fd93eSToomas Soome     s->last_flush = -2;
536b8382935SToomas Soome 
537b8382935SToomas Soome     _tr_init(s);
538b8382935SToomas Soome 
539b8382935SToomas Soome     return Z_OK;
540b8382935SToomas Soome }
541b8382935SToomas Soome 
542b8382935SToomas Soome /* ========================================================================= */
deflateReset(strm)543b8382935SToomas Soome int ZEXPORT deflateReset (strm)
544b8382935SToomas Soome     z_streamp strm;
545b8382935SToomas Soome {
546b8382935SToomas Soome     int ret;
547b8382935SToomas Soome 
548b8382935SToomas Soome     ret = deflateResetKeep(strm);
549b8382935SToomas Soome     if (ret == Z_OK)
550b8382935SToomas Soome         lm_init(strm->state);
551b8382935SToomas Soome     return ret;
552b8382935SToomas Soome }
553b8382935SToomas Soome 
554b8382935SToomas Soome /* ========================================================================= */
deflateSetHeader(strm,head)555b8382935SToomas Soome int ZEXPORT deflateSetHeader (strm, head)
556b8382935SToomas Soome     z_streamp strm;
557b8382935SToomas Soome     gz_headerp head;
558b8382935SToomas Soome {
559b8382935SToomas Soome     if (deflateStateCheck(strm) || strm->state->wrap != 2)
560b8382935SToomas Soome         return Z_STREAM_ERROR;
561b8382935SToomas Soome     strm->state->gzhead = head;
562b8382935SToomas Soome     return Z_OK;
563b8382935SToomas Soome }
564b8382935SToomas Soome 
565b8382935SToomas Soome /* ========================================================================= */
deflatePending(strm,pending,bits)566b8382935SToomas Soome int ZEXPORT deflatePending (strm, pending, bits)
567b8382935SToomas Soome     unsigned *pending;
568b8382935SToomas Soome     int *bits;
569b8382935SToomas Soome     z_streamp strm;
570b8382935SToomas Soome {
571b8382935SToomas Soome     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
572b8382935SToomas Soome     if (pending != Z_NULL)
573b8382935SToomas Soome         *pending = strm->state->pending;
574b8382935SToomas Soome     if (bits != Z_NULL)
575b8382935SToomas Soome         *bits = strm->state->bi_valid;
576b8382935SToomas Soome     return Z_OK;
577b8382935SToomas Soome }
578b8382935SToomas Soome 
579b8382935SToomas Soome /* ========================================================================= */
deflatePrime(strm,bits,value)580b8382935SToomas Soome int ZEXPORT deflatePrime (strm, bits, value)
581b8382935SToomas Soome     z_streamp strm;
582b8382935SToomas Soome     int bits;
583b8382935SToomas Soome     int value;
584b8382935SToomas Soome {
585b8382935SToomas Soome     deflate_state *s;
586b8382935SToomas Soome     int put;
587b8382935SToomas Soome 
588b8382935SToomas Soome     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
589b8382935SToomas Soome     s = strm->state;
590*148fd93eSToomas Soome     if (bits < 0 || bits > 16 ||
591*148fd93eSToomas Soome         s->sym_buf < s->pending_out + ((Buf_size + 7) >> 3))
592b8382935SToomas Soome         return Z_BUF_ERROR;
593b8382935SToomas Soome     do {
594b8382935SToomas Soome         put = Buf_size - s->bi_valid;
595b8382935SToomas Soome         if (put > bits)
596b8382935SToomas Soome             put = bits;
597b8382935SToomas Soome         s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);
598b8382935SToomas Soome         s->bi_valid += put;
599b8382935SToomas Soome         _tr_flush_bits(s);
600b8382935SToomas Soome         value >>= put;
601b8382935SToomas Soome         bits -= put;
602b8382935SToomas Soome     } while (bits);
603b8382935SToomas Soome     return Z_OK;
604b8382935SToomas Soome }
605b8382935SToomas Soome 
606b8382935SToomas Soome /* ========================================================================= */
deflateParams(strm,level,strategy)607b8382935SToomas Soome int ZEXPORT deflateParams(strm, level, strategy)
608b8382935SToomas Soome     z_streamp strm;
609b8382935SToomas Soome     int level;
610b8382935SToomas Soome     int strategy;
611b8382935SToomas Soome {
612b8382935SToomas Soome     deflate_state *s;
613b8382935SToomas Soome     compress_func func;
614b8382935SToomas Soome 
615b8382935SToomas Soome     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
616b8382935SToomas Soome     s = strm->state;
617b8382935SToomas Soome 
618b8382935SToomas Soome #ifdef FASTEST
619b8382935SToomas Soome     if (level != 0) level = 1;
620b8382935SToomas Soome #else
621b8382935SToomas Soome     if (level == Z_DEFAULT_COMPRESSION) level = 6;
622b8382935SToomas Soome #endif
623b8382935SToomas Soome     if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
624b8382935SToomas Soome         return Z_STREAM_ERROR;
625b8382935SToomas Soome     }
626b8382935SToomas Soome     func = configuration_table[s->level].func;
627b8382935SToomas Soome 
628b8382935SToomas Soome     if ((strategy != s->strategy || func != configuration_table[level].func) &&
629*148fd93eSToomas Soome         s->last_flush != -2) {
630b8382935SToomas Soome         /* Flush the last buffer: */
631b8382935SToomas Soome         int err = deflate(strm, Z_BLOCK);
632b8382935SToomas Soome         if (err == Z_STREAM_ERROR)
633b8382935SToomas Soome             return err;
634*148fd93eSToomas Soome         if (strm->avail_in || (s->strstart - s->block_start) + s->lookahead)
635b8382935SToomas Soome             return Z_BUF_ERROR;
636b8382935SToomas Soome     }
637b8382935SToomas Soome     if (s->level != level) {
638b8382935SToomas Soome         if (s->level == 0 && s->matches != 0) {
639b8382935SToomas Soome             if (s->matches == 1)
640b8382935SToomas Soome                 slide_hash(s);
641b8382935SToomas Soome             else
642b8382935SToomas Soome                 CLEAR_HASH(s);
643b8382935SToomas Soome             s->matches = 0;
644b8382935SToomas Soome         }
645b8382935SToomas Soome         s->level = level;
646b8382935SToomas Soome         s->max_lazy_match   = configuration_table[level].max_lazy;
647b8382935SToomas Soome         s->good_match       = configuration_table[level].good_length;
648b8382935SToomas Soome         s->nice_match       = configuration_table[level].nice_length;
649b8382935SToomas Soome         s->max_chain_length = configuration_table[level].max_chain;
650b8382935SToomas Soome     }
651b8382935SToomas Soome     s->strategy = strategy;
652b8382935SToomas Soome     return Z_OK;
653b8382935SToomas Soome }
654b8382935SToomas Soome 
655b8382935SToomas Soome /* ========================================================================= */
deflateTune(strm,good_length,max_lazy,nice_length,max_chain)656b8382935SToomas Soome int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
657b8382935SToomas Soome     z_streamp strm;
658b8382935SToomas Soome     int good_length;
659b8382935SToomas Soome     int max_lazy;
660b8382935SToomas Soome     int nice_length;
661b8382935SToomas Soome     int max_chain;
662b8382935SToomas Soome {
663b8382935SToomas Soome     deflate_state *s;
664b8382935SToomas Soome 
665b8382935SToomas Soome     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
666b8382935SToomas Soome     s = strm->state;
667b8382935SToomas Soome     s->good_match = (uInt)good_length;
668b8382935SToomas Soome     s->max_lazy_match = (uInt)max_lazy;
669b8382935SToomas Soome     s->nice_match = nice_length;
670b8382935SToomas Soome     s->max_chain_length = (uInt)max_chain;
671b8382935SToomas Soome     return Z_OK;
672b8382935SToomas Soome }
673b8382935SToomas Soome 
674b8382935SToomas Soome /* =========================================================================
675b8382935SToomas Soome  * For the default windowBits of 15 and memLevel of 8, this function returns
676b8382935SToomas Soome  * a close to exact, as well as small, upper bound on the compressed size.
677b8382935SToomas Soome  * They are coded as constants here for a reason--if the #define's are
678b8382935SToomas Soome  * changed, then this function needs to be changed as well.  The return
679b8382935SToomas Soome  * value for 15 and 8 only works for those exact settings.
680b8382935SToomas Soome  *
681b8382935SToomas Soome  * For any setting other than those defaults for windowBits and memLevel,
682b8382935SToomas Soome  * the value returned is a conservative worst case for the maximum expansion
683b8382935SToomas Soome  * resulting from using fixed blocks instead of stored blocks, which deflate
684b8382935SToomas Soome  * can emit on compressed data for some combinations of the parameters.
685b8382935SToomas Soome  *
686b8382935SToomas Soome  * This function could be more sophisticated to provide closer upper bounds for
687b8382935SToomas Soome  * every combination of windowBits and memLevel.  But even the conservative
688b8382935SToomas Soome  * upper bound of about 14% expansion does not seem onerous for output buffer
689b8382935SToomas Soome  * allocation.
690b8382935SToomas Soome  */
deflateBound(strm,sourceLen)691b8382935SToomas Soome uLong ZEXPORT deflateBound(strm, sourceLen)
692b8382935SToomas Soome     z_streamp strm;
693b8382935SToomas Soome     uLong sourceLen;
694b8382935SToomas Soome {
695b8382935SToomas Soome     deflate_state *s;
696b8382935SToomas Soome     uLong complen, wraplen;
697b8382935SToomas Soome 
698b8382935SToomas Soome     /* conservative upper bound for compressed data */
699b8382935SToomas Soome     complen = sourceLen +
700b8382935SToomas Soome               ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
701b8382935SToomas Soome 
702b8382935SToomas Soome     /* if can't get parameters, return conservative bound plus zlib wrapper */
703b8382935SToomas Soome     if (deflateStateCheck(strm))
704b8382935SToomas Soome         return complen + 6;
705b8382935SToomas Soome 
706b8382935SToomas Soome     /* compute wrapper length */
707b8382935SToomas Soome     s = strm->state;
708b8382935SToomas Soome     switch (s->wrap) {
709b8382935SToomas Soome     case 0:                                 /* raw deflate */
710b8382935SToomas Soome         wraplen = 0;
711b8382935SToomas Soome         break;
712b8382935SToomas Soome     case 1:                                 /* zlib wrapper */
713b8382935SToomas Soome         wraplen = 6 + (s->strstart ? 4 : 0);
714b8382935SToomas Soome         break;
715b8382935SToomas Soome #ifdef GZIP
716b8382935SToomas Soome     case 2:                                 /* gzip wrapper */
717b8382935SToomas Soome         wraplen = 18;
718b8382935SToomas Soome         if (s->gzhead != Z_NULL) {          /* user-supplied gzip header */
719b8382935SToomas Soome             Bytef *str;
720b8382935SToomas Soome             if (s->gzhead->extra != Z_NULL)
721b8382935SToomas Soome                 wraplen += 2 + s->gzhead->extra_len;
722b8382935SToomas Soome             str = s->gzhead->name;
723b8382935SToomas Soome             if (str != Z_NULL)
724b8382935SToomas Soome                 do {
725b8382935SToomas Soome                     wraplen++;
726b8382935SToomas Soome                 } while (*str++);
727b8382935SToomas Soome             str = s->gzhead->comment;
728b8382935SToomas Soome             if (str != Z_NULL)
729b8382935SToomas Soome                 do {
730b8382935SToomas Soome                     wraplen++;
731b8382935SToomas Soome                 } while (*str++);
732b8382935SToomas Soome             if (s->gzhead->hcrc)
733b8382935SToomas Soome                 wraplen += 2;
734b8382935SToomas Soome         }
735b8382935SToomas Soome         break;
736b8382935SToomas Soome #endif
737b8382935SToomas Soome     default:                                /* for compiler happiness */
738b8382935SToomas Soome         wraplen = 6;
739b8382935SToomas Soome     }
740b8382935SToomas Soome 
741b8382935SToomas Soome     /* if not default parameters, return conservative bound */
742b8382935SToomas Soome     if (s->w_bits != 15 || s->hash_bits != 8 + 7)
743b8382935SToomas Soome         return complen + wraplen;
744b8382935SToomas Soome 
745b8382935SToomas Soome     /* default settings: return tight bound for that case */
746b8382935SToomas Soome     return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
747b8382935SToomas Soome            (sourceLen >> 25) + 13 - 6 + wraplen;
748b8382935SToomas Soome }
749b8382935SToomas Soome 
750b8382935SToomas Soome /* =========================================================================
751b8382935SToomas Soome  * Put a short in the pending buffer. The 16-bit value is put in MSB order.
752b8382935SToomas Soome  * IN assertion: the stream state is correct and there is enough room in
753b8382935SToomas Soome  * pending_buf.
754b8382935SToomas Soome  */
putShortMSB(s,b)755b8382935SToomas Soome local void putShortMSB (s, b)
756b8382935SToomas Soome     deflate_state *s;
757b8382935SToomas Soome     uInt b;
758b8382935SToomas Soome {
759b8382935SToomas Soome     put_byte(s, (Byte)(b >> 8));
760b8382935SToomas Soome     put_byte(s, (Byte)(b & 0xff));
761b8382935SToomas Soome }
762b8382935SToomas Soome 
763b8382935SToomas Soome /* =========================================================================
764b8382935SToomas Soome  * Flush as much pending output as possible. All deflate() output, except for
765b8382935SToomas Soome  * some deflate_stored() output, goes through this function so some
766b8382935SToomas Soome  * applications may wish to modify it to avoid allocating a large
767b8382935SToomas Soome  * strm->next_out buffer and copying into it. (See also read_buf()).
768b8382935SToomas Soome  */
flush_pending(strm)769b8382935SToomas Soome local void flush_pending(strm)
770b8382935SToomas Soome     z_streamp strm;
771b8382935SToomas Soome {
772b8382935SToomas Soome     unsigned len;
773b8382935SToomas Soome     deflate_state *s = strm->state;
774b8382935SToomas Soome 
775b8382935SToomas Soome     _tr_flush_bits(s);
776b8382935SToomas Soome     len = s->pending;
777b8382935SToomas Soome     if (len > strm->avail_out) len = strm->avail_out;
778b8382935SToomas Soome     if (len == 0) return;
779b8382935SToomas Soome 
780b8382935SToomas Soome     zmemcpy(strm->next_out, s->pending_out, len);
781b8382935SToomas Soome     strm->next_out  += len;
782b8382935SToomas Soome     s->pending_out  += len;
783b8382935SToomas Soome     strm->total_out += len;
784b8382935SToomas Soome     strm->avail_out -= len;
785b8382935SToomas Soome     s->pending      -= len;
786b8382935SToomas Soome     if (s->pending == 0) {
787b8382935SToomas Soome         s->pending_out = s->pending_buf;
788b8382935SToomas Soome     }
789b8382935SToomas Soome }
790b8382935SToomas Soome 
791b8382935SToomas Soome /* ===========================================================================
792b8382935SToomas Soome  * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1].
793b8382935SToomas Soome  */
794b8382935SToomas Soome #define HCRC_UPDATE(beg) \
795b8382935SToomas Soome     do { \
796b8382935SToomas Soome         if (s->gzhead->hcrc && s->pending > (beg)) \
797b8382935SToomas Soome             strm->adler = crc32(strm->adler, s->pending_buf + (beg), \
798b8382935SToomas Soome                                 s->pending - (beg)); \
799b8382935SToomas Soome     } while (0)
800b8382935SToomas Soome 
801b8382935SToomas Soome /* ========================================================================= */
deflate(strm,flush)802b8382935SToomas Soome int ZEXPORT deflate (strm, flush)
803b8382935SToomas Soome     z_streamp strm;
804b8382935SToomas Soome     int flush;
805b8382935SToomas Soome {
806b8382935SToomas Soome     int old_flush; /* value of flush param for previous deflate call */
807b8382935SToomas Soome     deflate_state *s;
808b8382935SToomas Soome 
809b8382935SToomas Soome     if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) {
810b8382935SToomas Soome         return Z_STREAM_ERROR;
811b8382935SToomas Soome     }
812b8382935SToomas Soome     s = strm->state;
813b8382935SToomas Soome 
814b8382935SToomas Soome     if (strm->next_out == Z_NULL ||
815b8382935SToomas Soome         (strm->avail_in != 0 && strm->next_in == Z_NULL) ||
816b8382935SToomas Soome         (s->status == FINISH_STATE && flush != Z_FINISH)) {
817b8382935SToomas Soome         ERR_RETURN(strm, Z_STREAM_ERROR);
818b8382935SToomas Soome     }
819b8382935SToomas Soome     if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
820b8382935SToomas Soome 
821b8382935SToomas Soome     old_flush = s->last_flush;
822b8382935SToomas Soome     s->last_flush = flush;
823b8382935SToomas Soome 
824b8382935SToomas Soome     /* Flush as much pending output as possible */
825b8382935SToomas Soome     if (s->pending != 0) {
826b8382935SToomas Soome         flush_pending(strm);
827b8382935SToomas Soome         if (strm->avail_out == 0) {
828b8382935SToomas Soome             /* Since avail_out is 0, deflate will be called again with
829b8382935SToomas Soome              * more output space, but possibly with both pending and
830b8382935SToomas Soome              * avail_in equal to zero. There won't be anything to do,
831b8382935SToomas Soome              * but this is not an error situation so make sure we
832b8382935SToomas Soome              * return OK instead of BUF_ERROR at next call of deflate:
833b8382935SToomas Soome              */
834b8382935SToomas Soome             s->last_flush = -1;
835b8382935SToomas Soome             return Z_OK;
836b8382935SToomas Soome         }
837b8382935SToomas Soome 
838b8382935SToomas Soome     /* Make sure there is something to do and avoid duplicate consecutive
839b8382935SToomas Soome      * flushes. For repeated and useless calls with Z_FINISH, we keep
840b8382935SToomas Soome      * returning Z_STREAM_END instead of Z_BUF_ERROR.
841b8382935SToomas Soome      */
842b8382935SToomas Soome     } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&
843b8382935SToomas Soome                flush != Z_FINISH) {
844b8382935SToomas Soome         ERR_RETURN(strm, Z_BUF_ERROR);
845b8382935SToomas Soome     }
846b8382935SToomas Soome 
847b8382935SToomas Soome     /* User must not provide more input after the first FINISH: */
848b8382935SToomas Soome     if (s->status == FINISH_STATE && strm->avail_in != 0) {
849b8382935SToomas Soome         ERR_RETURN(strm, Z_BUF_ERROR);
850b8382935SToomas Soome     }
851b8382935SToomas Soome 
852b8382935SToomas Soome     /* Write the header */
853*148fd93eSToomas Soome     if (s->status == INIT_STATE && s->wrap == 0)
854*148fd93eSToomas Soome         s->status = BUSY_STATE;
855b8382935SToomas Soome     if (s->status == INIT_STATE) {
856b8382935SToomas Soome         /* zlib header */
857b8382935SToomas Soome         uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
858b8382935SToomas Soome         uInt level_flags;
859b8382935SToomas Soome 
860b8382935SToomas Soome         if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
861b8382935SToomas Soome             level_flags = 0;
862b8382935SToomas Soome         else if (s->level < 6)
863b8382935SToomas Soome             level_flags = 1;
864b8382935SToomas Soome         else if (s->level == 6)
865b8382935SToomas Soome             level_flags = 2;
866b8382935SToomas Soome         else
867b8382935SToomas Soome             level_flags = 3;
868b8382935SToomas Soome         header |= (level_flags << 6);
869b8382935SToomas Soome         if (s->strstart != 0) header |= PRESET_DICT;
870b8382935SToomas Soome         header += 31 - (header % 31);
871b8382935SToomas Soome 
872b8382935SToomas Soome         putShortMSB(s, header);
873b8382935SToomas Soome 
874b8382935SToomas Soome         /* Save the adler32 of the preset dictionary: */
875b8382935SToomas Soome         if (s->strstart != 0) {
876b8382935SToomas Soome             putShortMSB(s, (uInt)(strm->adler >> 16));
877b8382935SToomas Soome             putShortMSB(s, (uInt)(strm->adler & 0xffff));
878b8382935SToomas Soome         }
879b8382935SToomas Soome         strm->adler = adler32(0L, Z_NULL, 0);
880b8382935SToomas Soome         s->status = BUSY_STATE;
881b8382935SToomas Soome 
882b8382935SToomas Soome         /* Compression must start with an empty pending buffer */
883b8382935SToomas Soome         flush_pending(strm);
884b8382935SToomas Soome         if (s->pending != 0) {
885b8382935SToomas Soome             s->last_flush = -1;
886b8382935SToomas Soome             return Z_OK;
887b8382935SToomas Soome         }
888b8382935SToomas Soome     }
889b8382935SToomas Soome #ifdef GZIP
890b8382935SToomas Soome     if (s->status == GZIP_STATE) {
891b8382935SToomas Soome         /* gzip header */
892b8382935SToomas Soome         strm->adler = crc32(0L, Z_NULL, 0);
893b8382935SToomas Soome         put_byte(s, 31);
894b8382935SToomas Soome         put_byte(s, 139);
895b8382935SToomas Soome         put_byte(s, 8);
896b8382935SToomas Soome         if (s->gzhead == Z_NULL) {
897b8382935SToomas Soome             put_byte(s, 0);
898b8382935SToomas Soome             put_byte(s, 0);
899b8382935SToomas Soome             put_byte(s, 0);
900b8382935SToomas Soome             put_byte(s, 0);
901b8382935SToomas Soome             put_byte(s, 0);
902b8382935SToomas Soome             put_byte(s, s->level == 9 ? 2 :
903b8382935SToomas Soome                      (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
904b8382935SToomas Soome                       4 : 0));
905b8382935SToomas Soome             put_byte(s, OS_CODE);
906b8382935SToomas Soome             s->status = BUSY_STATE;
907b8382935SToomas Soome 
908b8382935SToomas Soome             /* Compression must start with an empty pending buffer */
909b8382935SToomas Soome             flush_pending(strm);
910b8382935SToomas Soome             if (s->pending != 0) {
911b8382935SToomas Soome                 s->last_flush = -1;
912b8382935SToomas Soome                 return Z_OK;
913b8382935SToomas Soome             }
914b8382935SToomas Soome         }
915b8382935SToomas Soome         else {
916b8382935SToomas Soome             put_byte(s, (s->gzhead->text ? 1 : 0) +
917b8382935SToomas Soome                      (s->gzhead->hcrc ? 2 : 0) +
918b8382935SToomas Soome                      (s->gzhead->extra == Z_NULL ? 0 : 4) +
919b8382935SToomas Soome                      (s->gzhead->name == Z_NULL ? 0 : 8) +
920b8382935SToomas Soome                      (s->gzhead->comment == Z_NULL ? 0 : 16)
921b8382935SToomas Soome                      );
922b8382935SToomas Soome             put_byte(s, (Byte)(s->gzhead->time & 0xff));
923b8382935SToomas Soome             put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
924b8382935SToomas Soome             put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
925b8382935SToomas Soome             put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
926b8382935SToomas Soome             put_byte(s, s->level == 9 ? 2 :
927b8382935SToomas Soome                      (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
928b8382935SToomas Soome                       4 : 0));
929b8382935SToomas Soome             put_byte(s, s->gzhead->os & 0xff);
930b8382935SToomas Soome             if (s->gzhead->extra != Z_NULL) {
931b8382935SToomas Soome                 put_byte(s, s->gzhead->extra_len & 0xff);
932b8382935SToomas Soome                 put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
933b8382935SToomas Soome             }
934b8382935SToomas Soome             if (s->gzhead->hcrc)
935b8382935SToomas Soome                 strm->adler = crc32(strm->adler, s->pending_buf,
936b8382935SToomas Soome                                     s->pending);
937b8382935SToomas Soome             s->gzindex = 0;
938b8382935SToomas Soome             s->status = EXTRA_STATE;
939b8382935SToomas Soome         }
940b8382935SToomas Soome     }
941b8382935SToomas Soome     if (s->status == EXTRA_STATE) {
942b8382935SToomas Soome         if (s->gzhead->extra != Z_NULL) {
943b8382935SToomas Soome             ulg beg = s->pending;   /* start of bytes to update crc */
944b8382935SToomas Soome             uInt left = (s->gzhead->extra_len & 0xffff) - s->gzindex;
945b8382935SToomas Soome             while (s->pending + left > s->pending_buf_size) {
946b8382935SToomas Soome                 uInt copy = s->pending_buf_size - s->pending;
947b8382935SToomas Soome                 zmemcpy(s->pending_buf + s->pending,
948b8382935SToomas Soome                         s->gzhead->extra + s->gzindex, copy);
949b8382935SToomas Soome                 s->pending = s->pending_buf_size;
950b8382935SToomas Soome                 HCRC_UPDATE(beg);
951b8382935SToomas Soome                 s->gzindex += copy;
952b8382935SToomas Soome                 flush_pending(strm);
953b8382935SToomas Soome                 if (s->pending != 0) {
954b8382935SToomas Soome                     s->last_flush = -1;
955b8382935SToomas Soome                     return Z_OK;
956b8382935SToomas Soome                 }
957b8382935SToomas Soome                 beg = 0;
958b8382935SToomas Soome                 left -= copy;
959b8382935SToomas Soome             }
960b8382935SToomas Soome             zmemcpy(s->pending_buf + s->pending,
961b8382935SToomas Soome                     s->gzhead->extra + s->gzindex, left);
962b8382935SToomas Soome             s->pending += left;
963b8382935SToomas Soome             HCRC_UPDATE(beg);
964b8382935SToomas Soome             s->gzindex = 0;
965b8382935SToomas Soome         }
966b8382935SToomas Soome         s->status = NAME_STATE;
967b8382935SToomas Soome     }
968b8382935SToomas Soome     if (s->status == NAME_STATE) {
969b8382935SToomas Soome         if (s->gzhead->name != Z_NULL) {
970b8382935SToomas Soome             ulg beg = s->pending;   /* start of bytes to update crc */
971b8382935SToomas Soome             int val;
972b8382935SToomas Soome             do {
973b8382935SToomas Soome                 if (s->pending == s->pending_buf_size) {
974b8382935SToomas Soome                     HCRC_UPDATE(beg);
975b8382935SToomas Soome                     flush_pending(strm);
976b8382935SToomas Soome                     if (s->pending != 0) {
977b8382935SToomas Soome                         s->last_flush = -1;
978b8382935SToomas Soome                         return Z_OK;
979b8382935SToomas Soome                     }
980b8382935SToomas Soome                     beg = 0;
981b8382935SToomas Soome                 }
982b8382935SToomas Soome                 val = s->gzhead->name[s->gzindex++];
983b8382935SToomas Soome                 put_byte(s, val);
984b8382935SToomas Soome             } while (val != 0);
985b8382935SToomas Soome             HCRC_UPDATE(beg);
986b8382935SToomas Soome             s->gzindex = 0;
987b8382935SToomas Soome         }
988b8382935SToomas Soome         s->status = COMMENT_STATE;
989b8382935SToomas Soome     }
990b8382935SToomas Soome     if (s->status == COMMENT_STATE) {
991b8382935SToomas Soome         if (s->gzhead->comment != Z_NULL) {
992b8382935SToomas Soome             ulg beg = s->pending;   /* start of bytes to update crc */
993b8382935SToomas Soome             int val;
994b8382935SToomas Soome             do {
995b8382935SToomas Soome                 if (s->pending == s->pending_buf_size) {
996b8382935SToomas Soome                     HCRC_UPDATE(beg);
997b8382935SToomas Soome                     flush_pending(strm);
998b8382935SToomas Soome                     if (s->pending != 0) {
999b8382935SToomas Soome                         s->last_flush = -1;
1000b8382935SToomas Soome                         return Z_OK;
1001b8382935SToomas Soome                     }
1002b8382935SToomas Soome                     beg = 0;
1003b8382935SToomas Soome                 }
1004b8382935SToomas Soome                 val = s->gzhead->comment[s->gzindex++];
1005b8382935SToomas Soome                 put_byte(s, val);
1006b8382935SToomas Soome             } while (val != 0);
1007b8382935SToomas Soome             HCRC_UPDATE(beg);
1008b8382935SToomas Soome         }
1009b8382935SToomas Soome         s->status = HCRC_STATE;
1010b8382935SToomas Soome     }
1011b8382935SToomas Soome     if (s->status == HCRC_STATE) {
1012b8382935SToomas Soome         if (s->gzhead->hcrc) {
1013b8382935SToomas Soome             if (s->pending + 2 > s->pending_buf_size) {
1014b8382935SToomas Soome                 flush_pending(strm);
1015b8382935SToomas Soome                 if (s->pending != 0) {
1016b8382935SToomas Soome                     s->last_flush = -1;
1017b8382935SToomas Soome                     return Z_OK;
1018b8382935SToomas Soome                 }
1019b8382935SToomas Soome             }
1020b8382935SToomas Soome             put_byte(s, (Byte)(strm->adler & 0xff));
1021b8382935SToomas Soome             put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
1022b8382935SToomas Soome             strm->adler = crc32(0L, Z_NULL, 0);
1023b8382935SToomas Soome         }
1024b8382935SToomas Soome         s->status = BUSY_STATE;
1025b8382935SToomas Soome 
1026b8382935SToomas Soome         /* Compression must start with an empty pending buffer */
1027b8382935SToomas Soome         flush_pending(strm);
1028b8382935SToomas Soome         if (s->pending != 0) {
1029b8382935SToomas Soome             s->last_flush = -1;
1030b8382935SToomas Soome             return Z_OK;
1031b8382935SToomas Soome         }
1032b8382935SToomas Soome     }
1033b8382935SToomas Soome #endif
1034b8382935SToomas Soome 
1035b8382935SToomas Soome     /* Start a new block or continue the current one.
1036b8382935SToomas Soome      */
1037b8382935SToomas Soome     if (strm->avail_in != 0 || s->lookahead != 0 ||
1038b8382935SToomas Soome         (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
1039b8382935SToomas Soome         block_state bstate;
1040b8382935SToomas Soome 
1041b8382935SToomas Soome         bstate = s->level == 0 ? deflate_stored(s, flush) :
1042b8382935SToomas Soome                  s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
1043b8382935SToomas Soome                  s->strategy == Z_RLE ? deflate_rle(s, flush) :
1044b8382935SToomas Soome                  (*(configuration_table[s->level].func))(s, flush);
1045b8382935SToomas Soome 
1046b8382935SToomas Soome         if (bstate == finish_started || bstate == finish_done) {
1047b8382935SToomas Soome             s->status = FINISH_STATE;
1048b8382935SToomas Soome         }
1049b8382935SToomas Soome         if (bstate == need_more || bstate == finish_started) {
1050b8382935SToomas Soome             if (strm->avail_out == 0) {
1051b8382935SToomas Soome                 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
1052b8382935SToomas Soome             }
1053b8382935SToomas Soome             return Z_OK;
1054b8382935SToomas Soome             /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
1055b8382935SToomas Soome              * of deflate should use the same flush parameter to make sure
1056b8382935SToomas Soome              * that the flush is complete. So we don't have to output an
1057b8382935SToomas Soome              * empty block here, this will be done at next call. This also
1058b8382935SToomas Soome              * ensures that for a very small output buffer, we emit at most
1059b8382935SToomas Soome              * one empty block.
1060b8382935SToomas Soome              */
1061b8382935SToomas Soome         }
1062b8382935SToomas Soome         if (bstate == block_done) {
1063b8382935SToomas Soome             if (flush == Z_PARTIAL_FLUSH) {
1064b8382935SToomas Soome                 _tr_align(s);
1065b8382935SToomas Soome             } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
1066b8382935SToomas Soome                 _tr_stored_block(s, (char*)0, 0L, 0);
1067b8382935SToomas Soome                 /* For a full flush, this empty block will be recognized
1068b8382935SToomas Soome                  * as a special marker by inflate_sync().
1069b8382935SToomas Soome                  */
1070b8382935SToomas Soome                 if (flush == Z_FULL_FLUSH) {
1071b8382935SToomas Soome                     CLEAR_HASH(s);             /* forget history */
1072b8382935SToomas Soome                     if (s->lookahead == 0) {
1073b8382935SToomas Soome                         s->strstart = 0;
1074b8382935SToomas Soome                         s->block_start = 0L;
1075b8382935SToomas Soome                         s->insert = 0;
1076b8382935SToomas Soome                     }
1077b8382935SToomas Soome                 }
1078b8382935SToomas Soome             }
1079b8382935SToomas Soome             flush_pending(strm);
1080b8382935SToomas Soome             if (strm->avail_out == 0) {
1081b8382935SToomas Soome               s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
1082b8382935SToomas Soome               return Z_OK;
1083b8382935SToomas Soome             }
1084b8382935SToomas Soome         }
1085b8382935SToomas Soome     }
1086b8382935SToomas Soome 
1087b8382935SToomas Soome     if (flush != Z_FINISH) return Z_OK;
1088b8382935SToomas Soome     if (s->wrap <= 0) return Z_STREAM_END;
1089b8382935SToomas Soome 
1090b8382935SToomas Soome     /* Write the trailer */
1091b8382935SToomas Soome #ifdef GZIP
1092b8382935SToomas Soome     if (s->wrap == 2) {
1093b8382935SToomas Soome         put_byte(s, (Byte)(strm->adler & 0xff));
1094b8382935SToomas Soome         put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
1095b8382935SToomas Soome         put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
1096b8382935SToomas Soome         put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
1097b8382935SToomas Soome         put_byte(s, (Byte)(strm->total_in & 0xff));
1098b8382935SToomas Soome         put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
1099b8382935SToomas Soome         put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
1100b8382935SToomas Soome         put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
1101b8382935SToomas Soome     }
1102b8382935SToomas Soome     else
1103b8382935SToomas Soome #endif
1104b8382935SToomas Soome     {
1105b8382935SToomas Soome         putShortMSB(s, (uInt)(strm->adler >> 16));
1106b8382935SToomas Soome         putShortMSB(s, (uInt)(strm->adler & 0xffff));
1107b8382935SToomas Soome     }
1108b8382935SToomas Soome     flush_pending(strm);
1109b8382935SToomas Soome     /* If avail_out is zero, the application will call deflate again
1110b8382935SToomas Soome      * to flush the rest.
1111b8382935SToomas Soome      */
1112b8382935SToomas Soome     if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
1113b8382935SToomas Soome     return s->pending != 0 ? Z_OK : Z_STREAM_END;
1114b8382935SToomas Soome }
1115b8382935SToomas Soome 
1116b8382935SToomas Soome /* ========================================================================= */
deflateEnd(strm)1117b8382935SToomas Soome int ZEXPORT deflateEnd (strm)
1118b8382935SToomas Soome     z_streamp strm;
1119b8382935SToomas Soome {
1120b8382935SToomas Soome     int status;
1121b8382935SToomas Soome 
1122b8382935SToomas Soome     if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
1123b8382935SToomas Soome 
1124b8382935SToomas Soome     status = strm->state->status;
1125b8382935SToomas Soome 
1126b8382935SToomas Soome     /* Deallocate in reverse order of allocations: */
1127b8382935SToomas Soome     TRY_FREE(strm, strm->state->pending_buf);
1128b8382935SToomas Soome     TRY_FREE(strm, strm->state->head);
1129b8382935SToomas Soome     TRY_FREE(strm, strm->state->prev);
1130b8382935SToomas Soome     TRY_FREE(strm, strm->state->window);
1131b8382935SToomas Soome 
1132b8382935SToomas Soome     ZFREE(strm, strm->state);
1133b8382935SToomas Soome     strm->state = Z_NULL;
1134b8382935SToomas Soome 
1135b8382935SToomas Soome     return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
1136b8382935SToomas Soome }
1137b8382935SToomas Soome 
1138b8382935SToomas Soome /* =========================================================================
1139b8382935SToomas Soome  * Copy the source state to the destination state.
1140b8382935SToomas Soome  * To simplify the source, this is not supported for 16-bit MSDOS (which
1141b8382935SToomas Soome  * doesn't have enough memory anyway to duplicate compression states).
1142b8382935SToomas Soome  */
deflateCopy(dest,source)1143b8382935SToomas Soome int ZEXPORT deflateCopy (dest, source)
1144b8382935SToomas Soome     z_streamp dest;
1145b8382935SToomas Soome     z_streamp source;
1146b8382935SToomas Soome {
1147b8382935SToomas Soome #ifdef MAXSEG_64K
1148b8382935SToomas Soome     return Z_STREAM_ERROR;
1149b8382935SToomas Soome #else
1150b8382935SToomas Soome     deflate_state *ds;
1151b8382935SToomas Soome     deflate_state *ss;
1152b8382935SToomas Soome 
1153b8382935SToomas Soome 
1154b8382935SToomas Soome     if (deflateStateCheck(source) || dest == Z_NULL) {
1155b8382935SToomas Soome         return Z_STREAM_ERROR;
1156b8382935SToomas Soome     }
1157b8382935SToomas Soome 
1158b8382935SToomas Soome     ss = source->state;
1159b8382935SToomas Soome 
1160b8382935SToomas Soome     zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
1161b8382935SToomas Soome 
1162b8382935SToomas Soome     ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
1163b8382935SToomas Soome     if (ds == Z_NULL) return Z_MEM_ERROR;
1164b8382935SToomas Soome     dest->state = (struct internal_state FAR *) ds;
1165b8382935SToomas Soome     zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));
1166b8382935SToomas Soome     ds->strm = dest;
1167b8382935SToomas Soome 
1168b8382935SToomas Soome     ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
1169b8382935SToomas Soome     ds->prev   = (Posf *)  ZALLOC(dest, ds->w_size, sizeof(Pos));
1170b8382935SToomas Soome     ds->head   = (Posf *)  ZALLOC(dest, ds->hash_size, sizeof(Pos));
1171*148fd93eSToomas Soome     ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, 4);
1172b8382935SToomas Soome 
1173b8382935SToomas Soome     if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
1174b8382935SToomas Soome         ds->pending_buf == Z_NULL) {
1175b8382935SToomas Soome         deflateEnd (dest);
1176b8382935SToomas Soome         return Z_MEM_ERROR;
1177b8382935SToomas Soome     }
1178b8382935SToomas Soome     /* following zmemcpy do not work for 16-bit MSDOS */
1179b8382935SToomas Soome     zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
1180b8382935SToomas Soome     zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));
1181b8382935SToomas Soome     zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));
1182b8382935SToomas Soome     zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
1183b8382935SToomas Soome 
1184b8382935SToomas Soome     ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
1185*148fd93eSToomas Soome     ds->sym_buf = ds->pending_buf + ds->lit_bufsize;
1186b8382935SToomas Soome 
1187b8382935SToomas Soome     ds->l_desc.dyn_tree = ds->dyn_ltree;
1188b8382935SToomas Soome     ds->d_desc.dyn_tree = ds->dyn_dtree;
1189b8382935SToomas Soome     ds->bl_desc.dyn_tree = ds->bl_tree;
1190b8382935SToomas Soome 
1191b8382935SToomas Soome     return Z_OK;
1192b8382935SToomas Soome #endif /* MAXSEG_64K */
1193b8382935SToomas Soome }
1194b8382935SToomas Soome 
1195b8382935SToomas Soome /* ===========================================================================
1196b8382935SToomas Soome  * Read a new buffer from the current input stream, update the adler32
1197b8382935SToomas Soome  * and total number of bytes read.  All deflate() input goes through
1198b8382935SToomas Soome  * this function so some applications may wish to modify it to avoid
1199b8382935SToomas Soome  * allocating a large strm->next_in buffer and copying from it.
1200b8382935SToomas Soome  * (See also flush_pending()).
1201b8382935SToomas Soome  */
read_buf(strm,buf,size)1202b8382935SToomas Soome local unsigned read_buf(strm, buf, size)
1203b8382935SToomas Soome     z_streamp strm;
1204b8382935SToomas Soome     Bytef *buf;
1205b8382935SToomas Soome     unsigned size;
1206b8382935SToomas Soome {
1207b8382935SToomas Soome     unsigned len = strm->avail_in;
1208b8382935SToomas Soome 
1209b8382935SToomas Soome     if (len > size) len = size;
1210b8382935SToomas Soome     if (len == 0) return 0;
1211b8382935SToomas Soome 
1212b8382935SToomas Soome     strm->avail_in  -= len;
1213b8382935SToomas Soome 
1214b8382935SToomas Soome     zmemcpy(buf, strm->next_in, len);
1215b8382935SToomas Soome     if (strm->state->wrap == 1) {
1216b8382935SToomas Soome         strm->adler = adler32(strm->adler, buf, len);
1217b8382935SToomas Soome     }
1218b8382935SToomas Soome #ifdef GZIP
1219b8382935SToomas Soome     else if (strm->state->wrap == 2) {
1220b8382935SToomas Soome         strm->adler = crc32(strm->adler, buf, len);
1221b8382935SToomas Soome     }
1222b8382935SToomas Soome #endif
1223b8382935SToomas Soome     strm->next_in  += len;
1224b8382935SToomas Soome     strm->total_in += len;
1225b8382935SToomas Soome 
1226b8382935SToomas Soome     return len;
1227b8382935SToomas Soome }
1228b8382935SToomas Soome 
1229b8382935SToomas Soome /* ===========================================================================
1230b8382935SToomas Soome  * Initialize the "longest match" routines for a new zlib stream
1231b8382935SToomas Soome  */
lm_init(s)1232b8382935SToomas Soome local void lm_init (s)
1233b8382935SToomas Soome     deflate_state *s;
1234b8382935SToomas Soome {
1235b8382935SToomas Soome     s->window_size = (ulg)2L*s->w_size;
1236b8382935SToomas Soome 
1237b8382935SToomas Soome     CLEAR_HASH(s);
1238b8382935SToomas Soome 
1239b8382935SToomas Soome     /* Set the default configuration parameters:
1240b8382935SToomas Soome      */
1241b8382935SToomas Soome     s->max_lazy_match   = configuration_table[s->level].max_lazy;
1242b8382935SToomas Soome     s->good_match       = configuration_table[s->level].good_length;
1243b8382935SToomas Soome     s->nice_match       = configuration_table[s->level].nice_length;
1244b8382935SToomas Soome     s->max_chain_length = configuration_table[s->level].max_chain;
1245b8382935SToomas Soome 
1246b8382935SToomas Soome     s->strstart = 0;
1247b8382935SToomas Soome     s->block_start = 0L;
1248b8382935SToomas Soome     s->lookahead = 0;
1249b8382935SToomas Soome     s->insert = 0;
1250b8382935SToomas Soome     s->match_length = s->prev_length = MIN_MATCH-1;
1251b8382935SToomas Soome     s->match_available = 0;
1252b8382935SToomas Soome     s->ins_h = 0;
1253b8382935SToomas Soome #ifndef FASTEST
1254b8382935SToomas Soome #ifdef ASMV
1255b8382935SToomas Soome     match_init(); /* initialize the asm code */
1256b8382935SToomas Soome #endif
1257b8382935SToomas Soome #endif
1258b8382935SToomas Soome }
1259b8382935SToomas Soome 
1260b8382935SToomas Soome #ifndef FASTEST
1261b8382935SToomas Soome /* ===========================================================================
1262b8382935SToomas Soome  * Set match_start to the longest match starting at the given string and
1263b8382935SToomas Soome  * return its length. Matches shorter or equal to prev_length are discarded,
1264b8382935SToomas Soome  * in which case the result is equal to prev_length and match_start is
1265b8382935SToomas Soome  * garbage.
1266b8382935SToomas Soome  * IN assertions: cur_match is the head of the hash chain for the current
1267b8382935SToomas Soome  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1268b8382935SToomas Soome  * OUT assertion: the match length is not greater than s->lookahead.
1269b8382935SToomas Soome  */
1270b8382935SToomas Soome #ifndef ASMV
1271b8382935SToomas Soome /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
1272b8382935SToomas Soome  * match.S. The code will be functionally equivalent.
1273b8382935SToomas Soome  */
longest_match(s,cur_match)1274b8382935SToomas Soome local uInt longest_match(s, cur_match)
1275b8382935SToomas Soome     deflate_state *s;
1276b8382935SToomas Soome     IPos cur_match;                             /* current match */
1277b8382935SToomas Soome {
1278b8382935SToomas Soome     unsigned chain_length = s->max_chain_length;/* max hash chain length */
1279b8382935SToomas Soome     register Bytef *scan = s->window + s->strstart; /* current string */
1280b8382935SToomas Soome     register Bytef *match;                      /* matched string */
1281b8382935SToomas Soome     register int len;                           /* length of current match */
1282b8382935SToomas Soome     int best_len = (int)s->prev_length;         /* best match length so far */
1283b8382935SToomas Soome     int nice_match = s->nice_match;             /* stop if match long enough */
1284b8382935SToomas Soome     IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
1285b8382935SToomas Soome         s->strstart - (IPos)MAX_DIST(s) : NIL;
1286b8382935SToomas Soome     /* Stop when cur_match becomes <= limit. To simplify the code,
1287b8382935SToomas Soome      * we prevent matches with the string of window index 0.
1288b8382935SToomas Soome      */
1289b8382935SToomas Soome     Posf *prev = s->prev;
1290b8382935SToomas Soome     uInt wmask = s->w_mask;
1291b8382935SToomas Soome 
1292b8382935SToomas Soome #ifdef UNALIGNED_OK
1293b8382935SToomas Soome     /* Compare two bytes at a time. Note: this is not always beneficial.
1294b8382935SToomas Soome      * Try with and without -DUNALIGNED_OK to check.
1295b8382935SToomas Soome      */
1296b8382935SToomas Soome     register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
1297b8382935SToomas Soome     register ush scan_start = *(ushf*)scan;
1298b8382935SToomas Soome     register ush scan_end   = *(ushf*)(scan+best_len-1);
1299b8382935SToomas Soome #else
1300b8382935SToomas Soome     register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1301b8382935SToomas Soome     register Byte scan_end1  = scan[best_len-1];
1302b8382935SToomas Soome     register Byte scan_end   = scan[best_len];
1303b8382935SToomas Soome #endif
1304b8382935SToomas Soome 
1305b8382935SToomas Soome     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1306b8382935SToomas Soome      * It is easy to get rid of this optimization if necessary.
1307b8382935SToomas Soome      */
1308b8382935SToomas Soome     Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1309b8382935SToomas Soome 
1310b8382935SToomas Soome     /* Do not waste too much time if we already have a good match: */
1311b8382935SToomas Soome     if (s->prev_length >= s->good_match) {
1312b8382935SToomas Soome         chain_length >>= 2;
1313b8382935SToomas Soome     }
1314b8382935SToomas Soome     /* Do not look for matches beyond the end of the input. This is necessary
1315b8382935SToomas Soome      * to make deflate deterministic.
1316b8382935SToomas Soome      */
1317b8382935SToomas Soome     if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead;
1318b8382935SToomas Soome 
1319b8382935SToomas Soome     Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1320b8382935SToomas Soome 
1321b8382935SToomas Soome     do {
1322b8382935SToomas Soome         Assert(cur_match < s->strstart, "no future");
1323b8382935SToomas Soome         match = s->window + cur_match;
1324b8382935SToomas Soome 
1325b8382935SToomas Soome         /* Skip to next match if the match length cannot increase
1326b8382935SToomas Soome          * or if the match length is less than 2.  Note that the checks below
1327b8382935SToomas Soome          * for insufficient lookahead only occur occasionally for performance
1328b8382935SToomas Soome          * reasons.  Therefore uninitialized memory will be accessed, and
1329b8382935SToomas Soome          * conditional jumps will be made that depend on those values.
1330b8382935SToomas Soome          * However the length of the match is limited to the lookahead, so
1331b8382935SToomas Soome          * the output of deflate is not affected by the uninitialized values.
1332b8382935SToomas Soome          */
1333b8382935SToomas Soome #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
1334b8382935SToomas Soome         /* This code assumes sizeof(unsigned short) == 2. Do not use
1335b8382935SToomas Soome          * UNALIGNED_OK if your compiler uses a different size.
1336b8382935SToomas Soome          */
1337b8382935SToomas Soome         if (*(ushf*)(match+best_len-1) != scan_end ||
1338b8382935SToomas Soome             *(ushf*)match != scan_start) continue;
1339b8382935SToomas Soome 
1340b8382935SToomas Soome         /* It is not necessary to compare scan[2] and match[2] since they are
1341b8382935SToomas Soome          * always equal when the other bytes match, given that the hash keys
1342b8382935SToomas Soome          * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
1343b8382935SToomas Soome          * strstart+3, +5, ... up to strstart+257. We check for insufficient
1344b8382935SToomas Soome          * lookahead only every 4th comparison; the 128th check will be made
1345b8382935SToomas Soome          * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
1346b8382935SToomas Soome          * necessary to put more guard bytes at the end of the window, or
1347b8382935SToomas Soome          * to check more often for insufficient lookahead.
1348b8382935SToomas Soome          */
1349b8382935SToomas Soome         Assert(scan[2] == match[2], "scan[2]?");
1350b8382935SToomas Soome         scan++, match++;
1351b8382935SToomas Soome         do {
1352b8382935SToomas Soome         } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1353b8382935SToomas Soome                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1354b8382935SToomas Soome                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1355b8382935SToomas Soome                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1356b8382935SToomas Soome                  scan < strend);
1357b8382935SToomas Soome         /* The funny "do {}" generates better code on most compilers */
1358b8382935SToomas Soome 
1359b8382935SToomas Soome         /* Here, scan <= window+strstart+257 */
1360b8382935SToomas Soome         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1361b8382935SToomas Soome         if (*scan == *match) scan++;
1362b8382935SToomas Soome 
1363b8382935SToomas Soome         len = (MAX_MATCH - 1) - (int)(strend-scan);
1364b8382935SToomas Soome         scan = strend - (MAX_MATCH-1);
1365b8382935SToomas Soome 
1366b8382935SToomas Soome #else /* UNALIGNED_OK */
1367b8382935SToomas Soome 
1368b8382935SToomas Soome         if (match[best_len]   != scan_end  ||
1369b8382935SToomas Soome             match[best_len-1] != scan_end1 ||
1370b8382935SToomas Soome             *match            != *scan     ||
1371b8382935SToomas Soome             *++match          != scan[1])      continue;
1372b8382935SToomas Soome 
1373b8382935SToomas Soome         /* The check at best_len-1 can be removed because it will be made
1374b8382935SToomas Soome          * again later. (This heuristic is not always a win.)
1375b8382935SToomas Soome          * It is not necessary to compare scan[2] and match[2] since they
1376b8382935SToomas Soome          * are always equal when the other bytes match, given that
1377b8382935SToomas Soome          * the hash keys are equal and that HASH_BITS >= 8.
1378b8382935SToomas Soome          */
1379b8382935SToomas Soome         scan += 2, match++;
1380b8382935SToomas Soome         Assert(*scan == *match, "match[2]?");
1381b8382935SToomas Soome 
1382b8382935SToomas Soome         /* We check for insufficient lookahead only every 8th comparison;
1383b8382935SToomas Soome          * the 256th check will be made at strstart+258.
1384b8382935SToomas Soome          */
1385b8382935SToomas Soome         do {
1386b8382935SToomas Soome         } while (*++scan == *++match && *++scan == *++match &&
1387b8382935SToomas Soome                  *++scan == *++match && *++scan == *++match &&
1388b8382935SToomas Soome                  *++scan == *++match && *++scan == *++match &&
1389b8382935SToomas Soome                  *++scan == *++match && *++scan == *++match &&
1390b8382935SToomas Soome                  scan < strend);
1391b8382935SToomas Soome 
1392b8382935SToomas Soome         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1393b8382935SToomas Soome 
1394b8382935SToomas Soome         len = MAX_MATCH - (int)(strend - scan);
1395b8382935SToomas Soome         scan = strend - MAX_MATCH;
1396b8382935SToomas Soome 
1397b8382935SToomas Soome #endif /* UNALIGNED_OK */
1398b8382935SToomas Soome 
1399b8382935SToomas Soome         if (len > best_len) {
1400b8382935SToomas Soome             s->match_start = cur_match;
1401b8382935SToomas Soome             best_len = len;
1402b8382935SToomas Soome             if (len >= nice_match) break;
1403b8382935SToomas Soome #ifdef UNALIGNED_OK
1404b8382935SToomas Soome             scan_end = *(ushf*)(scan+best_len-1);
1405b8382935SToomas Soome #else
1406b8382935SToomas Soome             scan_end1  = scan[best_len-1];
1407b8382935SToomas Soome             scan_end   = scan[best_len];
1408b8382935SToomas Soome #endif
1409b8382935SToomas Soome         }
1410b8382935SToomas Soome     } while ((cur_match = prev[cur_match & wmask]) > limit
1411b8382935SToomas Soome              && --chain_length != 0);
1412b8382935SToomas Soome 
1413b8382935SToomas Soome     if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
1414b8382935SToomas Soome     return s->lookahead;
1415b8382935SToomas Soome }
1416b8382935SToomas Soome #endif /* ASMV */
1417b8382935SToomas Soome 
1418b8382935SToomas Soome #else /* FASTEST */
1419b8382935SToomas Soome 
1420b8382935SToomas Soome /* ---------------------------------------------------------------------------
1421b8382935SToomas Soome  * Optimized version for FASTEST only
1422b8382935SToomas Soome  */
longest_match(s,cur_match)1423b8382935SToomas Soome local uInt longest_match(s, cur_match)
1424b8382935SToomas Soome     deflate_state *s;
1425b8382935SToomas Soome     IPos cur_match;                             /* current match */
1426b8382935SToomas Soome {
1427b8382935SToomas Soome     register Bytef *scan = s->window + s->strstart; /* current string */
1428b8382935SToomas Soome     register Bytef *match;                       /* matched string */
1429b8382935SToomas Soome     register int len;                           /* length of current match */
1430b8382935SToomas Soome     register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1431b8382935SToomas Soome 
1432b8382935SToomas Soome     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1433b8382935SToomas Soome      * It is easy to get rid of this optimization if necessary.
1434b8382935SToomas Soome      */
1435b8382935SToomas Soome     Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1436b8382935SToomas Soome 
1437b8382935SToomas Soome     Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1438b8382935SToomas Soome 
1439b8382935SToomas Soome     Assert(cur_match < s->strstart, "no future");
1440b8382935SToomas Soome 
1441b8382935SToomas Soome     match = s->window + cur_match;
1442b8382935SToomas Soome 
1443b8382935SToomas Soome     /* Return failure if the match length is less than 2:
1444b8382935SToomas Soome      */
1445b8382935SToomas Soome     if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
1446b8382935SToomas Soome 
1447b8382935SToomas Soome     /* The check at best_len-1 can be removed because it will be made
1448b8382935SToomas Soome      * again later. (This heuristic is not always a win.)
1449b8382935SToomas Soome      * It is not necessary to compare scan[2] and match[2] since they
1450b8382935SToomas Soome      * are always equal when the other bytes match, given that
1451b8382935SToomas Soome      * the hash keys are equal and that HASH_BITS >= 8.
1452b8382935SToomas Soome      */
1453b8382935SToomas Soome     scan += 2, match += 2;
1454b8382935SToomas Soome     Assert(*scan == *match, "match[2]?");
1455b8382935SToomas Soome 
1456b8382935SToomas Soome     /* We check for insufficient lookahead only every 8th comparison;
1457b8382935SToomas Soome      * the 256th check will be made at strstart+258.
1458b8382935SToomas Soome      */
1459b8382935SToomas Soome     do {
1460b8382935SToomas Soome     } while (*++scan == *++match && *++scan == *++match &&
1461b8382935SToomas Soome              *++scan == *++match && *++scan == *++match &&
1462b8382935SToomas Soome              *++scan == *++match && *++scan == *++match &&
1463b8382935SToomas Soome              *++scan == *++match && *++scan == *++match &&
1464b8382935SToomas Soome              scan < strend);
1465b8382935SToomas Soome 
1466b8382935SToomas Soome     Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1467b8382935SToomas Soome 
1468b8382935SToomas Soome     len = MAX_MATCH - (int)(strend - scan);
1469b8382935SToomas Soome 
1470b8382935SToomas Soome     if (len < MIN_MATCH) return MIN_MATCH - 1;
1471b8382935SToomas Soome 
1472b8382935SToomas Soome     s->match_start = cur_match;
1473b8382935SToomas Soome     return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
1474b8382935SToomas Soome }
1475b8382935SToomas Soome 
1476b8382935SToomas Soome #endif /* FASTEST */
1477b8382935SToomas Soome 
1478b8382935SToomas Soome #ifdef ZLIB_DEBUG
1479b8382935SToomas Soome 
1480b8382935SToomas Soome #define EQUAL 0
1481b8382935SToomas Soome /* result of memcmp for equal strings */
1482b8382935SToomas Soome 
1483b8382935SToomas Soome /* ===========================================================================
1484b8382935SToomas Soome  * Check that the match at match_start is indeed a match.
1485b8382935SToomas Soome  */
check_match(s,start,match,length)1486b8382935SToomas Soome local void check_match(s, start, match, length)
1487b8382935SToomas Soome     deflate_state *s;
1488b8382935SToomas Soome     IPos start, match;
1489b8382935SToomas Soome     int length;
1490b8382935SToomas Soome {
1491b8382935SToomas Soome     /* check that the match is indeed a match */
1492b8382935SToomas Soome     if (zmemcmp(s->window + match,
1493b8382935SToomas Soome                 s->window + start, length) != EQUAL) {
1494b8382935SToomas Soome         fprintf(stderr, " start %u, match %u, length %d\n",
1495b8382935SToomas Soome                 start, match, length);
1496b8382935SToomas Soome         do {
1497b8382935SToomas Soome             fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
1498b8382935SToomas Soome         } while (--length != 0);
1499b8382935SToomas Soome         z_error("invalid match");
1500b8382935SToomas Soome     }
1501b8382935SToomas Soome     if (z_verbose > 1) {
1502b8382935SToomas Soome         fprintf(stderr,"\\[%d,%d]", start-match, length);
1503b8382935SToomas Soome         do { putc(s->window[start++], stderr); } while (--length != 0);
1504b8382935SToomas Soome     }
1505b8382935SToomas Soome }
1506b8382935SToomas Soome #else
1507b8382935SToomas Soome #  define check_match(s, start, match, length)
1508b8382935SToomas Soome #endif /* ZLIB_DEBUG */
1509b8382935SToomas Soome 
1510b8382935SToomas Soome /* ===========================================================================
1511b8382935SToomas Soome  * Fill the window when the lookahead becomes insufficient.
1512b8382935SToomas Soome  * Updates strstart and lookahead.
1513b8382935SToomas Soome  *
1514b8382935SToomas Soome  * IN assertion: lookahead < MIN_LOOKAHEAD
1515b8382935SToomas Soome  * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1516b8382935SToomas Soome  *    At least one byte has been read, or avail_in == 0; reads are
1517b8382935SToomas Soome  *    performed for at least two bytes (required for the zip translate_eol
1518b8382935SToomas Soome  *    option -- not supported here).
1519b8382935SToomas Soome  */
fill_window(s)1520b8382935SToomas Soome local void fill_window(s)
1521b8382935SToomas Soome     deflate_state *s;
1522b8382935SToomas Soome {
1523b8382935SToomas Soome     unsigned n;
1524b8382935SToomas Soome     unsigned more;    /* Amount of free space at the end of the window. */
1525b8382935SToomas Soome     uInt wsize = s->w_size;
1526b8382935SToomas Soome 
1527b8382935SToomas Soome     Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
1528b8382935SToomas Soome 
1529b8382935SToomas Soome     do {
1530b8382935SToomas Soome         more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
1531b8382935SToomas Soome 
1532b8382935SToomas Soome         /* Deal with !@#$% 64K limit: */
1533b8382935SToomas Soome         if (sizeof(int) <= 2) {
1534b8382935SToomas Soome             if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1535b8382935SToomas Soome                 more = wsize;
1536b8382935SToomas Soome 
1537b8382935SToomas Soome             } else if (more == (unsigned)(-1)) {
1538b8382935SToomas Soome                 /* Very unlikely, but possible on 16 bit machine if
1539b8382935SToomas Soome                  * strstart == 0 && lookahead == 1 (input done a byte at time)
1540b8382935SToomas Soome                  */
1541b8382935SToomas Soome                 more--;
1542b8382935SToomas Soome             }
1543b8382935SToomas Soome         }
1544b8382935SToomas Soome 
1545b8382935SToomas Soome         /* If the window is almost full and there is insufficient lookahead,
1546b8382935SToomas Soome          * move the upper half to the lower one to make room in the upper half.
1547b8382935SToomas Soome          */
1548b8382935SToomas Soome         if (s->strstart >= wsize+MAX_DIST(s)) {
1549b8382935SToomas Soome 
1550b8382935SToomas Soome             zmemcpy(s->window, s->window+wsize, (unsigned)wsize - more);
1551b8382935SToomas Soome             s->match_start -= wsize;
1552b8382935SToomas Soome             s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
1553b8382935SToomas Soome             s->block_start -= (long) wsize;
1554*148fd93eSToomas Soome             if (s->insert > s->strstart)
1555*148fd93eSToomas Soome                 s->insert = s->strstart;
1556b8382935SToomas Soome             slide_hash(s);
1557b8382935SToomas Soome             more += wsize;
1558b8382935SToomas Soome         }
1559b8382935SToomas Soome         if (s->strm->avail_in == 0) break;
1560b8382935SToomas Soome 
1561b8382935SToomas Soome         /* If there was no sliding:
1562b8382935SToomas Soome          *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1563b8382935SToomas Soome          *    more == window_size - lookahead - strstart
1564b8382935SToomas Soome          * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1565b8382935SToomas Soome          * => more >= window_size - 2*WSIZE + 2
1566b8382935SToomas Soome          * In the BIG_MEM or MMAP case (not yet supported),
1567b8382935SToomas Soome          *   window_size == input_size + MIN_LOOKAHEAD  &&
1568b8382935SToomas Soome          *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1569b8382935SToomas Soome          * Otherwise, window_size == 2*WSIZE so more >= 2.
1570b8382935SToomas Soome          * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1571b8382935SToomas Soome          */
1572b8382935SToomas Soome         Assert(more >= 2, "more < 2");
1573b8382935SToomas Soome 
1574b8382935SToomas Soome         n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1575b8382935SToomas Soome         s->lookahead += n;
1576b8382935SToomas Soome 
1577b8382935SToomas Soome         /* Initialize the hash value now that we have some input: */
1578b8382935SToomas Soome         if (s->lookahead + s->insert >= MIN_MATCH) {
1579b8382935SToomas Soome             uInt str = s->strstart - s->insert;
1580b8382935SToomas Soome             s->ins_h = s->window[str];
1581b8382935SToomas Soome             UPDATE_HASH(s, s->ins_h, s->window[str + 1]);
1582b8382935SToomas Soome #if MIN_MATCH != 3
1583b8382935SToomas Soome             Call UPDATE_HASH() MIN_MATCH-3 more times
1584b8382935SToomas Soome #endif
1585b8382935SToomas Soome             while (s->insert) {
1586b8382935SToomas Soome                 UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
1587b8382935SToomas Soome #ifndef FASTEST
1588b8382935SToomas Soome                 s->prev[str & s->w_mask] = s->head[s->ins_h];
1589b8382935SToomas Soome #endif
1590b8382935SToomas Soome                 s->head[s->ins_h] = (Pos)str;
1591b8382935SToomas Soome                 str++;
1592b8382935SToomas Soome                 s->insert--;
1593b8382935SToomas Soome                 if (s->lookahead + s->insert < MIN_MATCH)
1594b8382935SToomas Soome                     break;
1595b8382935SToomas Soome             }
1596b8382935SToomas Soome         }
1597b8382935SToomas Soome         /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1598b8382935SToomas Soome          * but this is not important since only literal bytes will be emitted.
1599b8382935SToomas Soome          */
1600b8382935SToomas Soome 
1601b8382935SToomas Soome     } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1602b8382935SToomas Soome 
1603b8382935SToomas Soome     /* If the WIN_INIT bytes after the end of the current data have never been
1604b8382935SToomas Soome      * written, then zero those bytes in order to avoid memory check reports of
1605b8382935SToomas Soome      * the use of uninitialized (or uninitialised as Julian writes) bytes by
1606b8382935SToomas Soome      * the longest match routines.  Update the high water mark for the next
1607b8382935SToomas Soome      * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
1608b8382935SToomas Soome      * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
1609b8382935SToomas Soome      */
1610b8382935SToomas Soome     if (s->high_water < s->window_size) {
1611b8382935SToomas Soome         ulg curr = s->strstart + (ulg)(s->lookahead);
1612b8382935SToomas Soome         ulg init;
1613b8382935SToomas Soome 
1614b8382935SToomas Soome         if (s->high_water < curr) {
1615b8382935SToomas Soome             /* Previous high water mark below current data -- zero WIN_INIT
1616b8382935SToomas Soome              * bytes or up to end of window, whichever is less.
1617b8382935SToomas Soome              */
1618b8382935SToomas Soome             init = s->window_size - curr;
1619b8382935SToomas Soome             if (init > WIN_INIT)
1620b8382935SToomas Soome                 init = WIN_INIT;
1621b8382935SToomas Soome             zmemzero(s->window + curr, (unsigned)init);
1622b8382935SToomas Soome             s->high_water = curr + init;
1623b8382935SToomas Soome         }
1624b8382935SToomas Soome         else if (s->high_water < (ulg)curr + WIN_INIT) {
1625b8382935SToomas Soome             /* High water mark at or above current data, but below current data
1626b8382935SToomas Soome              * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
1627b8382935SToomas Soome              * to end of window, whichever is less.
1628b8382935SToomas Soome              */
1629b8382935SToomas Soome             init = (ulg)curr + WIN_INIT - s->high_water;
1630b8382935SToomas Soome             if (init > s->window_size - s->high_water)
1631b8382935SToomas Soome                 init = s->window_size - s->high_water;
1632b8382935SToomas Soome             zmemzero(s->window + s->high_water, (unsigned)init);
1633b8382935SToomas Soome             s->high_water += init;
1634b8382935SToomas Soome         }
1635b8382935SToomas Soome     }
1636b8382935SToomas Soome 
1637b8382935SToomas Soome     Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1638b8382935SToomas Soome            "not enough room for search");
1639b8382935SToomas Soome }
1640b8382935SToomas Soome 
1641b8382935SToomas Soome /* ===========================================================================
1642b8382935SToomas Soome  * Flush the current block, with given end-of-file flag.
1643b8382935SToomas Soome  * IN assertion: strstart is set to the end of the current match.
1644b8382935SToomas Soome  */
1645b8382935SToomas Soome #define FLUSH_BLOCK_ONLY(s, last) { \
1646b8382935SToomas Soome    _tr_flush_block(s, (s->block_start >= 0L ? \
1647b8382935SToomas Soome                    (charf *)&s->window[(unsigned)s->block_start] : \
1648b8382935SToomas Soome                    (charf *)Z_NULL), \
1649b8382935SToomas Soome                 (ulg)((long)s->strstart - s->block_start), \
1650b8382935SToomas Soome                 (last)); \
1651b8382935SToomas Soome    s->block_start = s->strstart; \
1652b8382935SToomas Soome    flush_pending(s->strm); \
1653b8382935SToomas Soome    Tracev((stderr,"[FLUSH]")); \
1654b8382935SToomas Soome }
1655b8382935SToomas Soome 
1656b8382935SToomas Soome /* Same but force premature exit if necessary. */
1657b8382935SToomas Soome #define FLUSH_BLOCK(s, last) { \
1658b8382935SToomas Soome    FLUSH_BLOCK_ONLY(s, last); \
1659b8382935SToomas Soome    if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
1660b8382935SToomas Soome }
1661b8382935SToomas Soome 
1662b8382935SToomas Soome /* Maximum stored block length in deflate format (not including header). */
1663b8382935SToomas Soome #define MAX_STORED 65535
1664b8382935SToomas Soome 
1665b8382935SToomas Soome /* Minimum of a and b. */
1666b8382935SToomas Soome #define MIN(a, b) ((a) > (b) ? (b) : (a))
1667b8382935SToomas Soome 
1668b8382935SToomas Soome /* ===========================================================================
1669b8382935SToomas Soome  * Copy without compression as much as possible from the input stream, return
1670b8382935SToomas Soome  * the current block state.
1671b8382935SToomas Soome  *
1672b8382935SToomas Soome  * In case deflateParams() is used to later switch to a non-zero compression
1673b8382935SToomas Soome  * level, s->matches (otherwise unused when storing) keeps track of the number
1674b8382935SToomas Soome  * of hash table slides to perform. If s->matches is 1, then one hash table
1675b8382935SToomas Soome  * slide will be done when switching. If s->matches is 2, the maximum value
1676b8382935SToomas Soome  * allowed here, then the hash table will be cleared, since two or more slides
1677b8382935SToomas Soome  * is the same as a clear.
1678b8382935SToomas Soome  *
1679b8382935SToomas Soome  * deflate_stored() is written to minimize the number of times an input byte is
1680b8382935SToomas Soome  * copied. It is most efficient with large input and output buffers, which
1681b8382935SToomas Soome  * maximizes the opportunites to have a single copy from next_in to next_out.
1682b8382935SToomas Soome  */
deflate_stored(s,flush)1683b8382935SToomas Soome local block_state deflate_stored(s, flush)
1684b8382935SToomas Soome     deflate_state *s;
1685b8382935SToomas Soome     int flush;
1686b8382935SToomas Soome {
1687b8382935SToomas Soome     /* Smallest worthy block size when not flushing or finishing. By default
1688b8382935SToomas Soome      * this is 32K. This can be as small as 507 bytes for memLevel == 1. For
1689b8382935SToomas Soome      * large input and output buffers, the stored block size will be larger.
1690b8382935SToomas Soome      */
1691b8382935SToomas Soome     unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size);
1692b8382935SToomas Soome 
1693b8382935SToomas Soome     /* Copy as many min_block or larger stored blocks directly to next_out as
1694b8382935SToomas Soome      * possible. If flushing, copy the remaining available input to next_out as
1695b8382935SToomas Soome      * stored blocks, if there is enough space.
1696b8382935SToomas Soome      */
1697b8382935SToomas Soome     unsigned len, left, have, last = 0;
1698b8382935SToomas Soome     unsigned used = s->strm->avail_in;
1699b8382935SToomas Soome     do {
1700b8382935SToomas Soome         /* Set len to the maximum size block that we can copy directly with the
1701b8382935SToomas Soome          * available input data and output space. Set left to how much of that
1702b8382935SToomas Soome          * would be copied from what's left in the window.
1703b8382935SToomas Soome          */
1704b8382935SToomas Soome         len = MAX_STORED;       /* maximum deflate stored block length */
1705b8382935SToomas Soome         have = (s->bi_valid + 42) >> 3;         /* number of header bytes */
1706b8382935SToomas Soome         if (s->strm->avail_out < have)          /* need room for header */
1707b8382935SToomas Soome             break;
1708b8382935SToomas Soome             /* maximum stored block length that will fit in avail_out: */
1709b8382935SToomas Soome         have = s->strm->avail_out - have;
1710b8382935SToomas Soome         left = s->strstart - s->block_start;    /* bytes left in window */
1711b8382935SToomas Soome         if (len > (ulg)left + s->strm->avail_in)
1712b8382935SToomas Soome             len = left + s->strm->avail_in;     /* limit len to the input */
1713b8382935SToomas Soome         if (len > have)
1714b8382935SToomas Soome             len = have;                         /* limit len to the output */
1715b8382935SToomas Soome 
1716b8382935SToomas Soome         /* If the stored block would be less than min_block in length, or if
1717b8382935SToomas Soome          * unable to copy all of the available input when flushing, then try
1718b8382935SToomas Soome          * copying to the window and the pending buffer instead. Also don't
1719b8382935SToomas Soome          * write an empty block when flushing -- deflate() does that.
1720b8382935SToomas Soome          */
1721b8382935SToomas Soome         if (len < min_block && ((len == 0 && flush != Z_FINISH) ||
1722b8382935SToomas Soome                                 flush == Z_NO_FLUSH ||
1723b8382935SToomas Soome                                 len != left + s->strm->avail_in))
1724b8382935SToomas Soome             break;
1725b8382935SToomas Soome 
1726b8382935SToomas Soome         /* Make a dummy stored block in pending to get the header bytes,
1727b8382935SToomas Soome          * including any pending bits. This also updates the debugging counts.
1728b8382935SToomas Soome          */
1729b8382935SToomas Soome         last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0;
1730b8382935SToomas Soome         _tr_stored_block(s, (char *)0, 0L, last);
1731b8382935SToomas Soome 
1732b8382935SToomas Soome         /* Replace the lengths in the dummy stored block with len. */
1733b8382935SToomas Soome         s->pending_buf[s->pending - 4] = len;
1734b8382935SToomas Soome         s->pending_buf[s->pending - 3] = len >> 8;
1735b8382935SToomas Soome         s->pending_buf[s->pending - 2] = ~len;
1736b8382935SToomas Soome         s->pending_buf[s->pending - 1] = ~len >> 8;
1737b8382935SToomas Soome 
1738b8382935SToomas Soome         /* Write the stored block header bytes. */
1739b8382935SToomas Soome         flush_pending(s->strm);
1740b8382935SToomas Soome 
1741b8382935SToomas Soome #ifdef ZLIB_DEBUG
1742b8382935SToomas Soome         /* Update debugging counts for the data about to be copied. */
1743b8382935SToomas Soome         s->compressed_len += len << 3;
1744b8382935SToomas Soome         s->bits_sent += len << 3;
1745b8382935SToomas Soome #endif
1746b8382935SToomas Soome 
1747b8382935SToomas Soome         /* Copy uncompressed bytes from the window to next_out. */
1748b8382935SToomas Soome         if (left) {
1749b8382935SToomas Soome             if (left > len)
1750b8382935SToomas Soome                 left = len;
1751b8382935SToomas Soome             zmemcpy(s->strm->next_out, s->window + s->block_start, left);
1752b8382935SToomas Soome             s->strm->next_out += left;
1753b8382935SToomas Soome             s->strm->avail_out -= left;
1754b8382935SToomas Soome             s->strm->total_out += left;
1755b8382935SToomas Soome             s->block_start += left;
1756b8382935SToomas Soome             len -= left;
1757b8382935SToomas Soome         }
1758b8382935SToomas Soome 
1759b8382935SToomas Soome         /* Copy uncompressed bytes directly from next_in to next_out, updating
1760b8382935SToomas Soome          * the check value.
1761b8382935SToomas Soome          */
1762b8382935SToomas Soome         if (len) {
1763b8382935SToomas Soome             read_buf(s->strm, s->strm->next_out, len);
1764b8382935SToomas Soome             s->strm->next_out += len;
1765b8382935SToomas Soome             s->strm->avail_out -= len;
1766b8382935SToomas Soome             s->strm->total_out += len;
1767b8382935SToomas Soome         }
1768b8382935SToomas Soome     } while (last == 0);
1769b8382935SToomas Soome 
1770b8382935SToomas Soome     /* Update the sliding window with the last s->w_size bytes of the copied
1771b8382935SToomas Soome      * data, or append all of the copied data to the existing window if less
1772b8382935SToomas Soome      * than s->w_size bytes were copied. Also update the number of bytes to
1773b8382935SToomas Soome      * insert in the hash tables, in the event that deflateParams() switches to
1774b8382935SToomas Soome      * a non-zero compression level.
1775b8382935SToomas Soome      */
1776b8382935SToomas Soome     used -= s->strm->avail_in;      /* number of input bytes directly copied */
1777b8382935SToomas Soome     if (used) {
1778b8382935SToomas Soome         /* If any input was used, then no unused input remains in the window,
1779b8382935SToomas Soome          * therefore s->block_start == s->strstart.
1780b8382935SToomas Soome          */
1781b8382935SToomas Soome         if (used >= s->w_size) {    /* supplant the previous history */
1782b8382935SToomas Soome             s->matches = 2;         /* clear hash */
1783b8382935SToomas Soome             zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);
1784b8382935SToomas Soome             s->strstart = s->w_size;
1785*148fd93eSToomas Soome             s->insert = s->strstart;
1786b8382935SToomas Soome         }
1787b8382935SToomas Soome         else {
1788b8382935SToomas Soome             if (s->window_size - s->strstart <= used) {
1789b8382935SToomas Soome                 /* Slide the window down. */
1790b8382935SToomas Soome                 s->strstart -= s->w_size;
1791b8382935SToomas Soome                 zmemcpy(s->window, s->window + s->w_size, s->strstart);
1792b8382935SToomas Soome                 if (s->matches < 2)
1793b8382935SToomas Soome                     s->matches++;   /* add a pending slide_hash() */
1794*148fd93eSToomas Soome                 if (s->insert > s->strstart)
1795*148fd93eSToomas Soome                     s->insert = s->strstart;
1796b8382935SToomas Soome             }
1797b8382935SToomas Soome             zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);
1798b8382935SToomas Soome             s->strstart += used;
1799*148fd93eSToomas Soome             s->insert += MIN(used, s->w_size - s->insert);
1800b8382935SToomas Soome         }
1801b8382935SToomas Soome         s->block_start = s->strstart;
1802b8382935SToomas Soome     }
1803b8382935SToomas Soome     if (s->high_water < s->strstart)
1804b8382935SToomas Soome         s->high_water = s->strstart;
1805b8382935SToomas Soome 
1806b8382935SToomas Soome     /* If the last block was written to next_out, then done. */
1807b8382935SToomas Soome     if (last)
1808b8382935SToomas Soome         return finish_done;
1809b8382935SToomas Soome 
1810b8382935SToomas Soome     /* If flushing and all input has been consumed, then done. */
1811b8382935SToomas Soome     if (flush != Z_NO_FLUSH && flush != Z_FINISH &&
1812b8382935SToomas Soome         s->strm->avail_in == 0 && (long)s->strstart == s->block_start)
1813b8382935SToomas Soome         return block_done;
1814b8382935SToomas Soome 
1815b8382935SToomas Soome     /* Fill the window with any remaining input. */
1816*148fd93eSToomas Soome     have = s->window_size - s->strstart;
1817b8382935SToomas Soome     if (s->strm->avail_in > have && s->block_start >= (long)s->w_size) {
1818b8382935SToomas Soome         /* Slide the window down. */
1819b8382935SToomas Soome         s->block_start -= s->w_size;
1820b8382935SToomas Soome         s->strstart -= s->w_size;
1821b8382935SToomas Soome         zmemcpy(s->window, s->window + s->w_size, s->strstart);
1822b8382935SToomas Soome         if (s->matches < 2)
1823b8382935SToomas Soome             s->matches++;           /* add a pending slide_hash() */
1824b8382935SToomas Soome         have += s->w_size;          /* more space now */
1825*148fd93eSToomas Soome         if (s->insert > s->strstart)
1826*148fd93eSToomas Soome             s->insert = s->strstart;
1827b8382935SToomas Soome     }
1828b8382935SToomas Soome     if (have > s->strm->avail_in)
1829b8382935SToomas Soome         have = s->strm->avail_in;
1830b8382935SToomas Soome     if (have) {
1831b8382935SToomas Soome         read_buf(s->strm, s->window + s->strstart, have);
1832b8382935SToomas Soome         s->strstart += have;
1833*148fd93eSToomas Soome         s->insert += MIN(have, s->w_size - s->insert);
1834b8382935SToomas Soome     }
1835b8382935SToomas Soome     if (s->high_water < s->strstart)
1836b8382935SToomas Soome         s->high_water = s->strstart;
1837b8382935SToomas Soome 
1838b8382935SToomas Soome     /* There was not enough avail_out to write a complete worthy or flushed
1839b8382935SToomas Soome      * stored block to next_out. Write a stored block to pending instead, if we
1840b8382935SToomas Soome      * have enough input for a worthy block, or if flushing and there is enough
1841b8382935SToomas Soome      * room for the remaining input as a stored block in the pending buffer.
1842b8382935SToomas Soome      */
1843b8382935SToomas Soome     have = (s->bi_valid + 42) >> 3;         /* number of header bytes */
1844b8382935SToomas Soome         /* maximum stored block length that will fit in pending: */
1845b8382935SToomas Soome     have = MIN(s->pending_buf_size - have, MAX_STORED);
1846b8382935SToomas Soome     min_block = MIN(have, s->w_size);
1847b8382935SToomas Soome     left = s->strstart - s->block_start;
1848b8382935SToomas Soome     if (left >= min_block ||
1849b8382935SToomas Soome         ((left || flush == Z_FINISH) && flush != Z_NO_FLUSH &&
1850b8382935SToomas Soome          s->strm->avail_in == 0 && left <= have)) {
1851b8382935SToomas Soome         len = MIN(left, have);
1852b8382935SToomas Soome         last = flush == Z_FINISH && s->strm->avail_in == 0 &&
1853b8382935SToomas Soome                len == left ? 1 : 0;
1854b8382935SToomas Soome         _tr_stored_block(s, (charf *)s->window + s->block_start, len, last);
1855b8382935SToomas Soome         s->block_start += len;
1856b8382935SToomas Soome         flush_pending(s->strm);
1857b8382935SToomas Soome     }
1858b8382935SToomas Soome 
1859b8382935SToomas Soome     /* We've done all we can with the available input and output. */
1860b8382935SToomas Soome     return last ? finish_started : need_more;
1861b8382935SToomas Soome }
1862b8382935SToomas Soome 
1863b8382935SToomas Soome /* ===========================================================================
1864b8382935SToomas Soome  * Compress as much as possible from the input stream, return the current
1865b8382935SToomas Soome  * block state.
1866b8382935SToomas Soome  * This function does not perform lazy evaluation of matches and inserts
1867b8382935SToomas Soome  * new strings in the dictionary only for unmatched strings or for short
1868b8382935SToomas Soome  * matches. It is used only for the fast compression options.
1869b8382935SToomas Soome  */
deflate_fast(s,flush)1870b8382935SToomas Soome local block_state deflate_fast(s, flush)
1871b8382935SToomas Soome     deflate_state *s;
1872b8382935SToomas Soome     int flush;
1873b8382935SToomas Soome {
1874b8382935SToomas Soome     IPos hash_head;       /* head of the hash chain */
1875b8382935SToomas Soome     int bflush;           /* set if current block must be flushed */
1876b8382935SToomas Soome 
1877b8382935SToomas Soome     for (;;) {
1878b8382935SToomas Soome         /* Make sure that we always have enough lookahead, except
1879b8382935SToomas Soome          * at the end of the input file. We need MAX_MATCH bytes
1880b8382935SToomas Soome          * for the next match, plus MIN_MATCH bytes to insert the
1881b8382935SToomas Soome          * string following the next match.
1882b8382935SToomas Soome          */
1883b8382935SToomas Soome         if (s->lookahead < MIN_LOOKAHEAD) {
1884b8382935SToomas Soome             fill_window(s);
1885b8382935SToomas Soome             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1886b8382935SToomas Soome                 return need_more;
1887b8382935SToomas Soome             }
1888b8382935SToomas Soome             if (s->lookahead == 0) break; /* flush the current block */
1889b8382935SToomas Soome         }
1890b8382935SToomas Soome 
1891b8382935SToomas Soome         /* Insert the string window[strstart .. strstart+2] in the
1892b8382935SToomas Soome          * dictionary, and set hash_head to the head of the hash chain:
1893b8382935SToomas Soome          */
1894b8382935SToomas Soome         hash_head = NIL;
1895b8382935SToomas Soome         if (s->lookahead >= MIN_MATCH) {
1896b8382935SToomas Soome             INSERT_STRING(s, s->strstart, hash_head);
1897b8382935SToomas Soome         }
1898b8382935SToomas Soome 
1899b8382935SToomas Soome         /* Find the longest match, discarding those <= prev_length.
1900b8382935SToomas Soome          * At this point we have always match_length < MIN_MATCH
1901b8382935SToomas Soome          */
1902b8382935SToomas Soome         if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1903b8382935SToomas Soome             /* To simplify the code, we prevent matches with the string
1904b8382935SToomas Soome              * of window index 0 (in particular we have to avoid a match
1905b8382935SToomas Soome              * of the string with itself at the start of the input file).
1906b8382935SToomas Soome              */
1907b8382935SToomas Soome             s->match_length = longest_match (s, hash_head);
1908b8382935SToomas Soome             /* longest_match() sets match_start */
1909b8382935SToomas Soome         }
1910b8382935SToomas Soome         if (s->match_length >= MIN_MATCH) {
1911b8382935SToomas Soome             check_match(s, s->strstart, s->match_start, s->match_length);
1912b8382935SToomas Soome 
1913b8382935SToomas Soome             _tr_tally_dist(s, s->strstart - s->match_start,
1914b8382935SToomas Soome                            s->match_length - MIN_MATCH, bflush);
1915b8382935SToomas Soome 
1916b8382935SToomas Soome             s->lookahead -= s->match_length;
1917b8382935SToomas Soome 
1918b8382935SToomas Soome             /* Insert new strings in the hash table only if the match length
1919b8382935SToomas Soome              * is not too large. This saves time but degrades compression.
1920b8382935SToomas Soome              */
1921b8382935SToomas Soome #ifndef FASTEST
1922b8382935SToomas Soome             if (s->match_length <= s->max_insert_length &&
1923b8382935SToomas Soome                 s->lookahead >= MIN_MATCH) {
1924b8382935SToomas Soome                 s->match_length--; /* string at strstart already in table */
1925b8382935SToomas Soome                 do {
1926b8382935SToomas Soome                     s->strstart++;
1927b8382935SToomas Soome                     INSERT_STRING(s, s->strstart, hash_head);
1928b8382935SToomas Soome                     /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1929b8382935SToomas Soome                      * always MIN_MATCH bytes ahead.
1930b8382935SToomas Soome                      */
1931b8382935SToomas Soome                 } while (--s->match_length != 0);
1932b8382935SToomas Soome                 s->strstart++;
1933b8382935SToomas Soome             } else
1934b8382935SToomas Soome #endif
1935b8382935SToomas Soome             {
1936b8382935SToomas Soome                 s->strstart += s->match_length;
1937b8382935SToomas Soome                 s->match_length = 0;
1938b8382935SToomas Soome                 s->ins_h = s->window[s->strstart];
1939b8382935SToomas Soome                 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1940b8382935SToomas Soome #if MIN_MATCH != 3
1941b8382935SToomas Soome                 Call UPDATE_HASH() MIN_MATCH-3 more times
1942b8382935SToomas Soome #endif
1943b8382935SToomas Soome                 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1944b8382935SToomas Soome                  * matter since it will be recomputed at next deflate call.
1945b8382935SToomas Soome                  */
1946b8382935SToomas Soome             }
1947b8382935SToomas Soome         } else {
1948b8382935SToomas Soome             /* No match, output a literal byte */
1949b8382935SToomas Soome             Tracevv((stderr,"%c", s->window[s->strstart]));
1950b8382935SToomas Soome             _tr_tally_lit (s, s->window[s->strstart], bflush);
1951b8382935SToomas Soome             s->lookahead--;
1952b8382935SToomas Soome             s->strstart++;
1953b8382935SToomas Soome         }
1954b8382935SToomas Soome         if (bflush) FLUSH_BLOCK(s, 0);
1955b8382935SToomas Soome     }
1956b8382935SToomas Soome     s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
1957b8382935SToomas Soome     if (flush == Z_FINISH) {
1958b8382935SToomas Soome         FLUSH_BLOCK(s, 1);
1959b8382935SToomas Soome         return finish_done;
1960b8382935SToomas Soome     }
1961*148fd93eSToomas Soome     if (s->sym_next)
1962b8382935SToomas Soome         FLUSH_BLOCK(s, 0);
1963b8382935SToomas Soome     return block_done;
1964b8382935SToomas Soome }
1965b8382935SToomas Soome 
1966b8382935SToomas Soome #ifndef FASTEST
1967b8382935SToomas Soome /* ===========================================================================
1968b8382935SToomas Soome  * Same as above, but achieves better compression. We use a lazy
1969b8382935SToomas Soome  * evaluation for matches: a match is finally adopted only if there is
1970b8382935SToomas Soome  * no better match at the next window position.
1971b8382935SToomas Soome  */
deflate_slow(s,flush)1972b8382935SToomas Soome local block_state deflate_slow(s, flush)
1973b8382935SToomas Soome     deflate_state *s;
1974b8382935SToomas Soome     int flush;
1975b8382935SToomas Soome {
1976b8382935SToomas Soome     IPos hash_head;          /* head of hash chain */
1977b8382935SToomas Soome     int bflush;              /* set if current block must be flushed */
1978b8382935SToomas Soome 
1979b8382935SToomas Soome     /* Process the input block. */
1980b8382935SToomas Soome     for (;;) {
1981b8382935SToomas Soome         /* Make sure that we always have enough lookahead, except
1982b8382935SToomas Soome          * at the end of the input file. We need MAX_MATCH bytes
1983b8382935SToomas Soome          * for the next match, plus MIN_MATCH bytes to insert the
1984b8382935SToomas Soome          * string following the next match.
1985b8382935SToomas Soome          */
1986b8382935SToomas Soome         if (s->lookahead < MIN_LOOKAHEAD) {
1987b8382935SToomas Soome             fill_window(s);
1988b8382935SToomas Soome             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1989b8382935SToomas Soome                 return need_more;
1990b8382935SToomas Soome             }
1991b8382935SToomas Soome             if (s->lookahead == 0) break; /* flush the current block */
1992b8382935SToomas Soome         }
1993b8382935SToomas Soome 
1994b8382935SToomas Soome         /* Insert the string window[strstart .. strstart+2] in the
1995b8382935SToomas Soome          * dictionary, and set hash_head to the head of the hash chain:
1996b8382935SToomas Soome          */
1997b8382935SToomas Soome         hash_head = NIL;
1998b8382935SToomas Soome         if (s->lookahead >= MIN_MATCH) {
1999b8382935SToomas Soome             INSERT_STRING(s, s->strstart, hash_head);
2000b8382935SToomas Soome         }
2001b8382935SToomas Soome 
2002b8382935SToomas Soome         /* Find the longest match, discarding those <= prev_length.
2003b8382935SToomas Soome          */
2004b8382935SToomas Soome         s->prev_length = s->match_length, s->prev_match = s->match_start;
2005b8382935SToomas Soome         s->match_length = MIN_MATCH-1;
2006b8382935SToomas Soome 
2007b8382935SToomas Soome         if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
2008b8382935SToomas Soome             s->strstart - hash_head <= MAX_DIST(s)) {
2009b8382935SToomas Soome             /* To simplify the code, we prevent matches with the string
2010b8382935SToomas Soome              * of window index 0 (in particular we have to avoid a match
2011b8382935SToomas Soome              * of the string with itself at the start of the input file).
2012b8382935SToomas Soome              */
2013b8382935SToomas Soome             s->match_length = longest_match (s, hash_head);
2014b8382935SToomas Soome             /* longest_match() sets match_start */
2015b8382935SToomas Soome 
2016b8382935SToomas Soome             if (s->match_length <= 5 && (s->strategy == Z_FILTERED
2017b8382935SToomas Soome #if TOO_FAR <= 32767
2018b8382935SToomas Soome                 || (s->match_length == MIN_MATCH &&
2019b8382935SToomas Soome                     s->strstart - s->match_start > TOO_FAR)
2020b8382935SToomas Soome #endif
2021b8382935SToomas Soome                 )) {
2022b8382935SToomas Soome 
2023b8382935SToomas Soome                 /* If prev_match is also MIN_MATCH, match_start is garbage
2024b8382935SToomas Soome                  * but we will ignore the current match anyway.
2025b8382935SToomas Soome                  */
2026b8382935SToomas Soome                 s->match_length = MIN_MATCH-1;
2027b8382935SToomas Soome             }
2028b8382935SToomas Soome         }
2029b8382935SToomas Soome         /* If there was a match at the previous step and the current
2030b8382935SToomas Soome          * match is not better, output the previous match:
2031b8382935SToomas Soome          */
2032b8382935SToomas Soome         if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
2033b8382935SToomas Soome             uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
2034b8382935SToomas Soome             /* Do not insert strings in hash table beyond this. */
2035b8382935SToomas Soome 
2036b8382935SToomas Soome             check_match(s, s->strstart-1, s->prev_match, s->prev_length);
2037b8382935SToomas Soome 
2038b8382935SToomas Soome             _tr_tally_dist(s, s->strstart -1 - s->prev_match,
2039b8382935SToomas Soome                            s->prev_length - MIN_MATCH, bflush);
2040b8382935SToomas Soome 
2041b8382935SToomas Soome             /* Insert in hash table all strings up to the end of the match.
2042b8382935SToomas Soome              * strstart-1 and strstart are already inserted. If there is not
2043b8382935SToomas Soome              * enough lookahead, the last two strings are not inserted in
2044b8382935SToomas Soome              * the hash table.
2045b8382935SToomas Soome              */
2046b8382935SToomas Soome             s->lookahead -= s->prev_length-1;
2047b8382935SToomas Soome             s->prev_length -= 2;
2048b8382935SToomas Soome             do {
2049b8382935SToomas Soome                 if (++s->strstart <= max_insert) {
2050b8382935SToomas Soome                     INSERT_STRING(s, s->strstart, hash_head);
2051b8382935SToomas Soome                 }
2052b8382935SToomas Soome             } while (--s->prev_length != 0);
2053b8382935SToomas Soome             s->match_available = 0;
2054b8382935SToomas Soome             s->match_length = MIN_MATCH-1;
2055b8382935SToomas Soome             s->strstart++;
2056b8382935SToomas Soome 
2057b8382935SToomas Soome             if (bflush) FLUSH_BLOCK(s, 0);
2058b8382935SToomas Soome 
2059b8382935SToomas Soome         } else if (s->match_available) {
2060b8382935SToomas Soome             /* If there was no match at the previous position, output a
2061b8382935SToomas Soome              * single literal. If there was a match but the current match
2062b8382935SToomas Soome              * is longer, truncate the previous match to a single literal.
2063b8382935SToomas Soome              */
2064b8382935SToomas Soome             Tracevv((stderr,"%c", s->window[s->strstart-1]));
2065b8382935SToomas Soome             _tr_tally_lit(s, s->window[s->strstart-1], bflush);
2066b8382935SToomas Soome             if (bflush) {
2067b8382935SToomas Soome                 FLUSH_BLOCK_ONLY(s, 0);
2068b8382935SToomas Soome             }
2069b8382935SToomas Soome             s->strstart++;
2070b8382935SToomas Soome             s->lookahead--;
2071b8382935SToomas Soome             if (s->strm->avail_out == 0) return need_more;
2072b8382935SToomas Soome         } else {
2073b8382935SToomas Soome             /* There is no previous match to compare with, wait for
2074b8382935SToomas Soome              * the next step to decide.
2075b8382935SToomas Soome              */
2076b8382935SToomas Soome             s->match_available = 1;
2077b8382935SToomas Soome             s->strstart++;
2078b8382935SToomas Soome             s->lookahead--;
2079b8382935SToomas Soome         }
2080b8382935SToomas Soome     }
2081b8382935SToomas Soome     Assert (flush != Z_NO_FLUSH, "no flush?");
2082b8382935SToomas Soome     if (s->match_available) {
2083b8382935SToomas Soome         Tracevv((stderr,"%c", s->window[s->strstart-1]));
2084b8382935SToomas Soome         _tr_tally_lit(s, s->window[s->strstart-1], bflush);
2085b8382935SToomas Soome         s->match_available = 0;
2086b8382935SToomas Soome     }
2087b8382935SToomas Soome     s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
2088b8382935SToomas Soome     if (flush == Z_FINISH) {
2089b8382935SToomas Soome         FLUSH_BLOCK(s, 1);
2090b8382935SToomas Soome         return finish_done;
2091b8382935SToomas Soome     }
2092*148fd93eSToomas Soome     if (s->sym_next)
2093b8382935SToomas Soome         FLUSH_BLOCK(s, 0);
2094b8382935SToomas Soome     return block_done;
2095b8382935SToomas Soome }
2096b8382935SToomas Soome #endif /* FASTEST */
2097b8382935SToomas Soome 
2098b8382935SToomas Soome /* ===========================================================================
2099b8382935SToomas Soome  * For Z_RLE, simply look for runs of bytes, generate matches only of distance
2100b8382935SToomas Soome  * one.  Do not maintain a hash table.  (It will be regenerated if this run of
2101b8382935SToomas Soome  * deflate switches away from Z_RLE.)
2102b8382935SToomas Soome  */
deflate_rle(s,flush)2103b8382935SToomas Soome local block_state deflate_rle(s, flush)
2104b8382935SToomas Soome     deflate_state *s;
2105b8382935SToomas Soome     int flush;
2106b8382935SToomas Soome {
2107b8382935SToomas Soome     int bflush;             /* set if current block must be flushed */
2108b8382935SToomas Soome     uInt prev;              /* byte at distance one to match */
2109b8382935SToomas Soome     Bytef *scan, *strend;   /* scan goes up to strend for length of run */
2110b8382935SToomas Soome 
2111b8382935SToomas Soome     for (;;) {
2112b8382935SToomas Soome         /* Make sure that we always have enough lookahead, except
2113b8382935SToomas Soome          * at the end of the input file. We need MAX_MATCH bytes
2114b8382935SToomas Soome          * for the longest run, plus one for the unrolled loop.
2115b8382935SToomas Soome          */
2116b8382935SToomas Soome         if (s->lookahead <= MAX_MATCH) {
2117b8382935SToomas Soome             fill_window(s);
2118b8382935SToomas Soome             if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {
2119b8382935SToomas Soome                 return need_more;
2120b8382935SToomas Soome             }
2121b8382935SToomas Soome             if (s->lookahead == 0) break; /* flush the current block */
2122b8382935SToomas Soome         }
2123b8382935SToomas Soome 
2124b8382935SToomas Soome         /* See how many times the previous byte repeats */
2125b8382935SToomas Soome         s->match_length = 0;
2126b8382935SToomas Soome         if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
2127b8382935SToomas Soome             scan = s->window + s->strstart - 1;
2128b8382935SToomas Soome             prev = *scan;
2129b8382935SToomas Soome             if (prev == *++scan && prev == *++scan && prev == *++scan) {
2130b8382935SToomas Soome                 strend = s->window + s->strstart + MAX_MATCH;
2131b8382935SToomas Soome                 do {
2132b8382935SToomas Soome                 } while (prev == *++scan && prev == *++scan &&
2133b8382935SToomas Soome                          prev == *++scan && prev == *++scan &&
2134b8382935SToomas Soome                          prev == *++scan && prev == *++scan &&
2135b8382935SToomas Soome                          prev == *++scan && prev == *++scan &&
2136b8382935SToomas Soome                          scan < strend);
2137b8382935SToomas Soome                 s->match_length = MAX_MATCH - (uInt)(strend - scan);
2138b8382935SToomas Soome                 if (s->match_length > s->lookahead)
2139b8382935SToomas Soome                     s->match_length = s->lookahead;
2140b8382935SToomas Soome             }
2141b8382935SToomas Soome             Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
2142b8382935SToomas Soome         }
2143b8382935SToomas Soome 
2144b8382935SToomas Soome         /* Emit match if have run of MIN_MATCH or longer, else emit literal */
2145b8382935SToomas Soome         if (s->match_length >= MIN_MATCH) {
2146b8382935SToomas Soome             check_match(s, s->strstart, s->strstart - 1, s->match_length);
2147b8382935SToomas Soome 
2148b8382935SToomas Soome             _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
2149b8382935SToomas Soome 
2150b8382935SToomas Soome             s->lookahead -= s->match_length;
2151b8382935SToomas Soome             s->strstart += s->match_length;
2152b8382935SToomas Soome             s->match_length = 0;
2153b8382935SToomas Soome         } else {
2154b8382935SToomas Soome             /* No match, output a literal byte */
2155b8382935SToomas Soome             Tracevv((stderr,"%c", s->window[s->strstart]));
2156b8382935SToomas Soome             _tr_tally_lit (s, s->window[s->strstart], bflush);
2157b8382935SToomas Soome             s->lookahead--;
2158b8382935SToomas Soome             s->strstart++;
2159b8382935SToomas Soome         }
2160b8382935SToomas Soome         if (bflush) FLUSH_BLOCK(s, 0);
2161b8382935SToomas Soome     }
2162b8382935SToomas Soome     s->insert = 0;
2163b8382935SToomas Soome     if (flush == Z_FINISH) {
2164b8382935SToomas Soome         FLUSH_BLOCK(s, 1);
2165b8382935SToomas Soome         return finish_done;
2166b8382935SToomas Soome     }
2167*148fd93eSToomas Soome     if (s->sym_next)
2168b8382935SToomas Soome         FLUSH_BLOCK(s, 0);
2169b8382935SToomas Soome     return block_done;
2170b8382935SToomas Soome }
2171b8382935SToomas Soome 
2172b8382935SToomas Soome /* ===========================================================================
2173b8382935SToomas Soome  * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
2174b8382935SToomas Soome  * (It will be regenerated if this run of deflate switches away from Huffman.)
2175b8382935SToomas Soome  */
deflate_huff(s,flush)2176b8382935SToomas Soome local block_state deflate_huff(s, flush)
2177b8382935SToomas Soome     deflate_state *s;
2178b8382935SToomas Soome     int flush;
2179b8382935SToomas Soome {
2180b8382935SToomas Soome     int bflush;             /* set if current block must be flushed */
2181b8382935SToomas Soome 
2182b8382935SToomas Soome     for (;;) {
2183b8382935SToomas Soome         /* Make sure that we have a literal to write. */
2184b8382935SToomas Soome         if (s->lookahead == 0) {
2185b8382935SToomas Soome             fill_window(s);
2186b8382935SToomas Soome             if (s->lookahead == 0) {
2187b8382935SToomas Soome                 if (flush == Z_NO_FLUSH)
2188b8382935SToomas Soome                     return need_more;
2189b8382935SToomas Soome                 break;      /* flush the current block */
2190b8382935SToomas Soome             }
2191b8382935SToomas Soome         }
2192b8382935SToomas Soome 
2193b8382935SToomas Soome         /* Output a literal byte */
2194b8382935SToomas Soome         s->match_length = 0;
2195b8382935SToomas Soome         Tracevv((stderr,"%c", s->window[s->strstart]));
2196b8382935SToomas Soome         _tr_tally_lit (s, s->window[s->strstart], bflush);
2197b8382935SToomas Soome         s->lookahead--;
2198b8382935SToomas Soome         s->strstart++;
2199b8382935SToomas Soome         if (bflush) FLUSH_BLOCK(s, 0);
2200b8382935SToomas Soome     }
2201b8382935SToomas Soome     s->insert = 0;
2202b8382935SToomas Soome     if (flush == Z_FINISH) {
2203b8382935SToomas Soome         FLUSH_BLOCK(s, 1);
2204b8382935SToomas Soome         return finish_done;
2205b8382935SToomas Soome     }
2206*148fd93eSToomas Soome     if (s->sym_next)
2207b8382935SToomas Soome         FLUSH_BLOCK(s, 0);
2208b8382935SToomas Soome     return block_done;
2209b8382935SToomas Soome }
2210