1168404Spjd/*
2168404Spjd * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
3168404Spjd * Use is subject to license terms.
4168404Spjd */
5168404Spjd
6168404Spjd/* deflate.c -- compress data using the deflation algorithm
7168404Spjd * Copyright (C) 1995-2005 Jean-loup Gailly.
8168404Spjd * For conditions of distribution and use, see copyright notice in zlib.h
9168404Spjd */
10168404Spjd
11168404Spjd#pragma ident	"%Z%%M%	%I%	%E% SMI"
12168404Spjd
13168404Spjd/*
14168404Spjd *  ALGORITHM
15168404Spjd *
16168404Spjd *      The "deflation" process depends on being able to identify portions
17168404Spjd *      of the input text which are identical to earlier input (within a
18168404Spjd *      sliding window trailing behind the input currently being processed).
19168404Spjd *
20168404Spjd *      The most straightforward technique turns out to be the fastest for
21168404Spjd *      most input files: try all possible matches and select the longest.
22168404Spjd *      The key feature of this algorithm is that insertions into the string
23168404Spjd *      dictionary are very simple and thus fast, and deletions are avoided
24168404Spjd *      completely. Insertions are performed at each input character, whereas
25168404Spjd *      string matches are performed only when the previous match ends. So it
26168404Spjd *      is preferable to spend more time in matches to allow very fast string
27168404Spjd *      insertions and avoid deletions. The matching algorithm for small
28168404Spjd *      strings is inspired from that of Rabin & Karp. A brute force approach
29168404Spjd *      is used to find longer strings when a small match has been found.
30168404Spjd *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
31168404Spjd *      (by Leonid Broukhis).
32168404Spjd *         A previous version of this file used a more sophisticated algorithm
33168404Spjd *      (by Fiala and Greene) which is guaranteed to run in linear amortized
34168404Spjd *      time, but has a larger average cost, uses more memory and is patented.
35168404Spjd *      However the F&G algorithm may be faster for some highly redundant
36168404Spjd *      files if the parameter max_chain_length (described below) is too large.
37168404Spjd *
38168404Spjd *  ACKNOWLEDGEMENTS
39168404Spjd *
40168404Spjd *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
41168404Spjd *      I found it in 'freeze' written by Leonid Broukhis.
42168404Spjd *      Thanks to many people for bug reports and testing.
43168404Spjd *
44168404Spjd *  REFERENCES
45168404Spjd *
46168404Spjd *      Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
47168404Spjd *      Available in http://www.ietf.org/rfc/rfc1951.txt
48168404Spjd *
49168404Spjd *      A description of the Rabin and Karp algorithm is given in the book
50168404Spjd *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
51168404Spjd *
52168404Spjd *      Fiala,E.R., and Greene,D.H.
53168404Spjd *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
54168404Spjd *
55168404Spjd */
56168404Spjd
57168404Spjd#include "deflate.h"
58168404Spjd
59168404Spjdstatic const char deflate_copyright[] =
60168404Spjd   " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
61168404Spjd/*
62168404Spjd  If you use the zlib library in a product, an acknowledgment is welcome
63168404Spjd  in the documentation of your product. If for some reason you cannot
64168404Spjd  include such an acknowledgment, I would appreciate that you keep this
65168404Spjd  copyright string in the executable of your product.
66168404Spjd */
67168404Spjd
68168404Spjd/* ===========================================================================
69168404Spjd *  Function prototypes.
70168404Spjd */
71168404Spjdtypedef enum {
72168404Spjd    need_more,      /* block not completed, need more input or more output */
73168404Spjd    block_done,     /* block flush performed */
74168404Spjd    finish_started, /* finish started, need only more output at next deflate */
75168404Spjd    finish_done     /* finish done, accept no more input or output */
76168404Spjd} block_state;
77168404Spjd
78168404Spjdtypedef block_state (*compress_func) OF((deflate_state *s, int flush));
79168404Spjd/* Compression function. Returns the block state after the call. */
80168404Spjd
81168404Spjdlocal void fill_window    OF((deflate_state *s));
82168404Spjdlocal block_state deflate_stored OF((deflate_state *s, int flush));
83168404Spjdlocal block_state deflate_fast   OF((deflate_state *s, int flush));
84168404Spjd#ifndef FASTEST
85168404Spjdlocal block_state deflate_slow   OF((deflate_state *s, int flush));
86168404Spjd#endif
87168404Spjdlocal void lm_init        OF((deflate_state *s));
88168404Spjdlocal void putShortMSB    OF((deflate_state *s, uInt b));
89168404Spjdlocal void flush_pending  OF((z_streamp strm));
90168404Spjdlocal int read_buf        OF((z_streamp strm, Bytef *buf, unsigned size));
91168404Spjd#ifndef FASTEST
92168404Spjd#ifdef ASMV
93168404Spjd      void match_init OF((void)); /* asm code initialization */
94168404Spjd      uInt longest_match  OF((deflate_state *s, IPos cur_match));
95168404Spjd#else
96168404Spjdlocal uInt longest_match  OF((deflate_state *s, IPos cur_match));
97168404Spjd#endif
98168404Spjd#endif
99168404Spjdlocal uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
100168404Spjd
101168404Spjd#ifdef DEBUG
102168404Spjdlocal  void check_match OF((deflate_state *s, IPos start, IPos match,
103168404Spjd                            int length));
104168404Spjd#endif
105168404Spjd
106168404Spjd/* ===========================================================================
107168404Spjd * Local data
108168404Spjd */
109168404Spjd
110168404Spjd#define NIL 0
111168404Spjd/* Tail of hash chains */
112168404Spjd
113168404Spjd#ifndef TOO_FAR
114168404Spjd#  define TOO_FAR 4096
115168404Spjd#endif
116168404Spjd/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
117168404Spjd
118168404Spjd#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
119168404Spjd/* Minimum amount of lookahead, except at the end of the input file.
120168404Spjd * See deflate.c for comments about the MIN_MATCH+1.
121168404Spjd */
122168404Spjd
123168404Spjd/* Values for max_lazy_match, good_match and max_chain_length, depending on
124168404Spjd * the desired pack level (0..9). The values given below have been tuned to
125168404Spjd * exclude worst case performance for pathological files. Better values may be
126168404Spjd * found for specific files.
127168404Spjd */
128168404Spjdtypedef struct config_s {
129168404Spjd   ush good_length; /* reduce lazy search above this match length */
130168404Spjd   ush max_lazy;    /* do not perform lazy search above this match length */
131168404Spjd   ush nice_length; /* quit search above this match length */
132168404Spjd   ush max_chain;
133168404Spjd   compress_func func;
134168404Spjd} config;
135168404Spjd
136168404Spjd#ifdef FASTEST
137168404Spjdlocal const config configuration_table[2] = {
138168404Spjd/*      good lazy nice chain */
139168404Spjd/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
140168404Spjd/* 1 */ {4,    4,  8,    4, deflate_fast}}; /* max speed, no lazy matches */
141168404Spjd#else
142168404Spjdlocal const config configuration_table[10] = {
143168404Spjd/*      good lazy nice chain */
144168404Spjd/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
145168404Spjd/* 1 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */
146168404Spjd/* 2 */ {4,    5, 16,    8, deflate_fast},
147168404Spjd/* 3 */ {4,    6, 32,   32, deflate_fast},
148168404Spjd
149168404Spjd/* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
150168404Spjd/* 5 */ {8,   16, 32,   32, deflate_slow},
151168404Spjd/* 6 */ {8,   16, 128, 128, deflate_slow},
152168404Spjd/* 7 */ {8,   32, 128, 256, deflate_slow},
153168404Spjd/* 8 */ {32, 128, 258, 1024, deflate_slow},
154168404Spjd/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
155168404Spjd#endif
156168404Spjd
157168404Spjd/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
158168404Spjd * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
159168404Spjd * meaning.
160168404Spjd */
161168404Spjd
162168404Spjd#define EQUAL 0
163168404Spjd/* result of memcmp for equal strings */
164168404Spjd
165168404Spjd#ifndef NO_DUMMY_DECL
166168404Spjdstruct static_tree_desc_s {int dummy;}; /* for buggy compilers */
167168404Spjd#endif
168168404Spjd
169168404Spjd/* ===========================================================================
170168404Spjd * Update a hash value with the given input byte
171168404Spjd * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
172168404Spjd *    input characters, so that a running hash key can be computed from the
173168404Spjd *    previous key instead of complete recalculation each time.
174168404Spjd */
175168404Spjd#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
176168404Spjd
177168404Spjd
178168404Spjd/* ===========================================================================
179168404Spjd * Insert string str in the dictionary and set match_head to the previous head
180168404Spjd * of the hash chain (the most recent string with same hash key). Return
181168404Spjd * the previous length of the hash chain.
182168404Spjd * If this file is compiled with -DFASTEST, the compression level is forced
183168404Spjd * to 1, and no hash chains are maintained.
184168404Spjd * IN  assertion: all calls to to INSERT_STRING are made with consecutive
185168404Spjd *    input characters and the first MIN_MATCH bytes of str are valid
186168404Spjd *    (except for the last MIN_MATCH-1 bytes of the input file).
187168404Spjd */
188168404Spjd#ifdef FASTEST
189168404Spjd#define INSERT_STRING(s, str, match_head) \
190168404Spjd   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
191168404Spjd    match_head = s->head[s->ins_h], \
192168404Spjd    s->head[s->ins_h] = (Pos)(str))
193168404Spjd#else
194168404Spjd#define INSERT_STRING(s, str, match_head) \
195168404Spjd   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
196168404Spjd    match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
197168404Spjd    s->head[s->ins_h] = (Pos)(str))
198168404Spjd#endif
199168404Spjd
200168404Spjd/* ===========================================================================
201168404Spjd * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
202168404Spjd * prev[] will be initialized on the fly.
203168404Spjd */
204168404Spjd#define CLEAR_HASH(s) \
205168404Spjd    s->head[s->hash_size-1] = NIL; \
206168404Spjd    (void) zmemzero((Bytef *)s->head, \
207168404Spjd    (unsigned)(s->hash_size-1)*sizeof(*s->head));
208168404Spjd
209168404Spjd/* ========================================================================= */
210168404Spjdint ZEXPORT deflateInit_(strm, level, version, stream_size)
211168404Spjd    z_streamp strm;
212168404Spjd    int level;
213168404Spjd    const char *version;
214168404Spjd    int stream_size;
215168404Spjd{
216168404Spjd    return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
217168404Spjd                         Z_DEFAULT_STRATEGY, version, stream_size);
218168404Spjd    /* To do: ignore strm->next_in if we use it as window */
219168404Spjd}
220168404Spjd
221168404Spjd/* ========================================================================= */
222168404Spjdint ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
223168404Spjd                  version, stream_size)
224168404Spjd    z_streamp strm;
225168404Spjd    int  level;
226168404Spjd    int  method;
227168404Spjd    int  windowBits;
228168404Spjd    int  memLevel;
229168404Spjd    int  strategy;
230168404Spjd    const char *version;
231168404Spjd    int stream_size;
232168404Spjd{
233168404Spjd    deflate_state *s;
234168404Spjd    int wrap = 1;
235168404Spjd    static const char my_version[] = ZLIB_VERSION;
236168404Spjd
237168404Spjd    ushf *overlay;
238168404Spjd    /* We overlay pending_buf and d_buf+l_buf. This works since the average
239168404Spjd     * output size for (length,distance) codes is <= 24 bits.
240168404Spjd     */
241168404Spjd
242168404Spjd    if (version == Z_NULL || version[0] != my_version[0] ||
243168404Spjd        stream_size != sizeof(z_stream)) {
244168404Spjd        return Z_VERSION_ERROR;
245168404Spjd    }
246168404Spjd    if (strm == Z_NULL) return Z_STREAM_ERROR;
247168404Spjd
248168404Spjd    strm->msg = Z_NULL;
249168404Spjd    if (strm->zalloc == (alloc_func)0) {
250168404Spjd        strm->zalloc = zcalloc;
251168404Spjd        strm->opaque = (voidpf)0;
252168404Spjd    }
253168404Spjd    if (strm->zfree == (free_func)0) strm->zfree = zcfree;
254168404Spjd
255168404Spjd#ifdef FASTEST
256168404Spjd    if (level != 0) level = 1;
257168404Spjd#else
258168404Spjd    if (level == Z_DEFAULT_COMPRESSION) level = 6;
259168404Spjd#endif
260168404Spjd
261168404Spjd    if (windowBits < 0) { /* suppress zlib wrapper */
262168404Spjd        wrap = 0;
263168404Spjd        windowBits = -windowBits;
264168404Spjd    }
265168404Spjd#ifdef GZIP
266168404Spjd    else if (windowBits > 15) {
267168404Spjd        wrap = 2;       /* write gzip wrapper instead */
268168404Spjd        windowBits -= 16;
269168404Spjd    }
270168404Spjd#endif
271168404Spjd    if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
272168404Spjd        windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
273168404Spjd        strategy < 0 || strategy > Z_FIXED) {
274168404Spjd        return Z_STREAM_ERROR;
275168404Spjd    }
276168404Spjd    if (windowBits == 8) windowBits = 9;  /* until 256-byte window bug fixed */
277168404Spjd    s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
278168404Spjd    if (s == Z_NULL) return Z_MEM_ERROR;
279168404Spjd    strm->state = (struct internal_state FAR *)s;
280168404Spjd    s->strm = strm;
281168404Spjd
282168404Spjd    s->wrap = wrap;
283168404Spjd    s->gzhead = Z_NULL;
284168404Spjd    s->w_bits = windowBits;
285168404Spjd    s->w_size = 1 << s->w_bits;
286168404Spjd    s->w_mask = s->w_size - 1;
287168404Spjd
288168404Spjd    s->hash_bits = memLevel + 7;
289168404Spjd    s->hash_size = 1 << s->hash_bits;
290168404Spjd    s->hash_mask = s->hash_size - 1;
291168404Spjd    s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
292168404Spjd
293168404Spjd    s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
294168404Spjd    s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
295168404Spjd    s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
296168404Spjd
297168404Spjd    s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
298168404Spjd
299168404Spjd    overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
300168404Spjd    s->pending_buf = (uchf *) overlay;
301168404Spjd    s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
302168404Spjd
303168404Spjd    if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
304168404Spjd        s->pending_buf == Z_NULL) {
305168404Spjd        s->status = FINISH_STATE;
306168404Spjd        strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
307168404Spjd        (void) deflateEnd (strm);
308168404Spjd        return Z_MEM_ERROR;
309168404Spjd    }
310168404Spjd    s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
311168404Spjd    s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
312168404Spjd
313168404Spjd    s->level = level;
314168404Spjd    s->strategy = strategy;
315168404Spjd    s->method = (Byte)method;
316168404Spjd
317168404Spjd    return deflateReset(strm);
318168404Spjd}
319168404Spjd
320168404Spjd/* ========================================================================= */
321168404Spjdint ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
322168404Spjd    z_streamp strm;
323168404Spjd    const Bytef *dictionary;
324168404Spjd    uInt  dictLength;
325168404Spjd{
326168404Spjd    deflate_state *s;
327168404Spjd    uInt length = dictLength;
328168404Spjd    uInt n;
329168404Spjd    IPos hash_head = 0;
330168404Spjd
331168404Spjd    if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
332168404Spjd        strm->state->wrap == 2 ||
333168404Spjd        (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
334168404Spjd        return Z_STREAM_ERROR;
335168404Spjd
336168404Spjd    s = strm->state;
337168404Spjd    if (s->wrap)
338168404Spjd        strm->adler = adler32(strm->adler, dictionary, dictLength);
339168404Spjd
340168404Spjd    if (length < MIN_MATCH) return Z_OK;
341168404Spjd    if (length > MAX_DIST(s)) {
342168404Spjd        length = MAX_DIST(s);
343168404Spjd        dictionary += dictLength - length; /* use the tail of the dictionary */
344168404Spjd    }
345168404Spjd    (void) zmemcpy(s->window, dictionary, length);
346168404Spjd    s->strstart = length;
347168404Spjd    s->block_start = (long)length;
348168404Spjd
349168404Spjd    /* Insert all strings in the hash table (except for the last two bytes).
350168404Spjd     * s->lookahead stays null, so s->ins_h will be recomputed at the next
351168404Spjd     * call of fill_window.
352168404Spjd     */
353168404Spjd    s->ins_h = s->window[0];
354168404Spjd    UPDATE_HASH(s, s->ins_h, s->window[1]);
355168404Spjd    for (n = 0; n <= length - MIN_MATCH; n++) {
356168404Spjd        INSERT_STRING(s, n, hash_head);
357168404Spjd    }
358168404Spjd    if (hash_head) hash_head = 0;  /* to make compiler happy */
359168404Spjd    return Z_OK;
360168404Spjd}
361168404Spjd
362168404Spjd/* ========================================================================= */
363168404Spjdint ZEXPORT deflateReset (strm)
364168404Spjd    z_streamp strm;
365168404Spjd{
366168404Spjd    deflate_state *s;
367168404Spjd
368168404Spjd    if (strm == Z_NULL || strm->state == Z_NULL ||
369168404Spjd        strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
370168404Spjd        return Z_STREAM_ERROR;
371168404Spjd    }
372168404Spjd
373168404Spjd    strm->total_in = strm->total_out = 0;
374168404Spjd    strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
375168404Spjd    strm->data_type = Z_UNKNOWN;
376168404Spjd
377168404Spjd    s = (deflate_state *)strm->state;
378168404Spjd    s->pending = 0;
379168404Spjd    s->pending_out = s->pending_buf;
380168404Spjd
381168404Spjd    if (s->wrap < 0) {
382168404Spjd        s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
383168404Spjd    }
384168404Spjd    s->status = s->wrap ? INIT_STATE : BUSY_STATE;
385168404Spjd    strm->adler =
386168404Spjd#ifdef GZIP
387168404Spjd        s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
388168404Spjd#endif
389168404Spjd        adler32(0L, Z_NULL, 0);
390168404Spjd    s->last_flush = Z_NO_FLUSH;
391168404Spjd
392168404Spjd    _tr_init(s);
393168404Spjd    lm_init(s);
394168404Spjd
395168404Spjd    return Z_OK;
396168404Spjd}
397168404Spjd
398168404Spjd/* ========================================================================= */
399168404Spjdint ZEXPORT deflateSetHeader (strm, head)
400168404Spjd    z_streamp strm;
401168404Spjd    gz_headerp head;
402168404Spjd{
403168404Spjd    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
404168404Spjd    if (strm->state->wrap != 2) return Z_STREAM_ERROR;
405168404Spjd    strm->state->gzhead = head;
406168404Spjd    return Z_OK;
407168404Spjd}
408168404Spjd
409168404Spjd/* ========================================================================= */
410168404Spjdint ZEXPORT deflatePrime (strm, bits, value)
411168404Spjd    z_streamp strm;
412168404Spjd    int bits;
413168404Spjd    int value;
414168404Spjd{
415168404Spjd    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
416168404Spjd    strm->state->bi_valid = bits;
417168404Spjd    strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
418168404Spjd    return Z_OK;
419168404Spjd}
420168404Spjd
421168404Spjd/* ========================================================================= */
422168404Spjdint ZEXPORT deflateParams(strm, level, strategy)
423168404Spjd    z_streamp strm;
424168404Spjd    int level;
425168404Spjd    int strategy;
426168404Spjd{
427168404Spjd    deflate_state *s;
428168404Spjd    compress_func func;
429168404Spjd    int err = Z_OK;
430168404Spjd
431168404Spjd    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
432168404Spjd    s = strm->state;
433168404Spjd
434168404Spjd#ifdef FASTEST
435168404Spjd    if (level != 0) level = 1;
436168404Spjd#else
437168404Spjd    if (level == Z_DEFAULT_COMPRESSION) level = 6;
438168404Spjd#endif
439168404Spjd    if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
440168404Spjd        return Z_STREAM_ERROR;
441168404Spjd    }
442168404Spjd    func = configuration_table[s->level].func;
443168404Spjd
444168404Spjd    if (func != configuration_table[level].func && strm->total_in != 0) {
445168404Spjd        /* Flush the last buffer: */
446168404Spjd        err = deflate(strm, Z_PARTIAL_FLUSH);
447168404Spjd    }
448168404Spjd    if (s->level != level) {
449168404Spjd        s->level = level;
450168404Spjd        s->max_lazy_match   = configuration_table[level].max_lazy;
451168404Spjd        s->good_match       = configuration_table[level].good_length;
452168404Spjd        s->nice_match       = configuration_table[level].nice_length;
453168404Spjd        s->max_chain_length = configuration_table[level].max_chain;
454168404Spjd    }
455168404Spjd    s->strategy = strategy;
456168404Spjd    return err;
457168404Spjd}
458168404Spjd
459168404Spjd/* ========================================================================= */
460168404Spjdint ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
461168404Spjd    z_streamp strm;
462168404Spjd    int good_length;
463168404Spjd    int max_lazy;
464168404Spjd    int nice_length;
465168404Spjd    int max_chain;
466168404Spjd{
467168404Spjd    deflate_state *s;
468168404Spjd
469168404Spjd    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
470168404Spjd    s = strm->state;
471168404Spjd    s->good_match = good_length;
472168404Spjd    s->max_lazy_match = max_lazy;
473168404Spjd    s->nice_match = nice_length;
474168404Spjd    s->max_chain_length = max_chain;
475168404Spjd    return Z_OK;
476168404Spjd}
477168404Spjd
478168404Spjd/* =========================================================================
479168404Spjd * For the default windowBits of 15 and memLevel of 8, this function returns
480168404Spjd * a close to exact, as well as small, upper bound on the compressed size.
481168404Spjd * They are coded as constants here for a reason--if the #define's are
482168404Spjd * changed, then this function needs to be changed as well.  The return
483168404Spjd * value for 15 and 8 only works for those exact settings.
484168404Spjd *
485168404Spjd * For any setting other than those defaults for windowBits and memLevel,
486168404Spjd * the value returned is a conservative worst case for the maximum expansion
487168404Spjd * resulting from using fixed blocks instead of stored blocks, which deflate
488168404Spjd * can emit on compressed data for some combinations of the parameters.
489168404Spjd *
490168404Spjd * This function could be more sophisticated to provide closer upper bounds
491168404Spjd * for every combination of windowBits and memLevel, as well as wrap.
492168404Spjd * But even the conservative upper bound of about 14% expansion does not
493168404Spjd * seem onerous for output buffer allocation.
494168404Spjd */
495168404SpjduLong ZEXPORT deflateBound(strm, sourceLen)
496168404Spjd    z_streamp strm;
497168404Spjd    uLong sourceLen;
498168404Spjd{
499168404Spjd    deflate_state *s;
500168404Spjd    uLong destLen;
501168404Spjd
502168404Spjd    /* conservative upper bound */
503168404Spjd    destLen = sourceLen +
504168404Spjd              ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
505168404Spjd
506168404Spjd    /* if can't get parameters, return conservative bound */
507168404Spjd    if (strm == Z_NULL || strm->state == Z_NULL)
508168404Spjd        return destLen;
509168404Spjd
510168404Spjd    /* if not default parameters, return conservative bound */
511168404Spjd    s = strm->state;
512168404Spjd    if (s->w_bits != 15 || s->hash_bits != 8 + 7)
513168404Spjd        return destLen;
514168404Spjd
515168404Spjd    /* default settings: return tight bound for that case */
516168404Spjd    return compressBound(sourceLen);
517168404Spjd}
518168404Spjd
519168404Spjd/* =========================================================================
520168404Spjd * Put a short in the pending buffer. The 16-bit value is put in MSB order.
521168404Spjd * IN assertion: the stream state is correct and there is enough room in
522168404Spjd * pending_buf.
523168404Spjd */
524168404Spjdlocal void putShortMSB (s, b)
525168404Spjd    deflate_state *s;
526168404Spjd    uInt b;
527168404Spjd{
528168404Spjd    put_byte(s, (Byte)(b >> 8));
529168404Spjd    put_byte(s, (Byte)(b & 0xff));
530168404Spjd}
531168404Spjd
532168404Spjd/* =========================================================================
533168404Spjd * Flush as much pending output as possible. All deflate() output goes
534168404Spjd * through this function so some applications may wish to modify it
535168404Spjd * to avoid allocating a large strm->next_out buffer and copying into it.
536168404Spjd * (See also read_buf()).
537168404Spjd */
538168404Spjdlocal void flush_pending(strm)
539168404Spjd    z_streamp strm;
540168404Spjd{
541168404Spjd    unsigned len = strm->state->pending;
542168404Spjd
543168404Spjd    if (len > strm->avail_out) len = strm->avail_out;
544168404Spjd    if (len == 0) return;
545168404Spjd
546168404Spjd    zmemcpy(strm->next_out, strm->state->pending_out, len);
547168404Spjd    strm->next_out  += len;
548168404Spjd    strm->state->pending_out  += len;
549168404Spjd    strm->total_out += len;
550168404Spjd    strm->avail_out  -= len;
551168404Spjd    strm->state->pending -= len;
552168404Spjd    if (strm->state->pending == 0) {
553168404Spjd        strm->state->pending_out = strm->state->pending_buf;
554168404Spjd    }
555168404Spjd}
556168404Spjd
557168404Spjd/* ========================================================================= */
558168404Spjdint ZEXPORT deflate (strm, flush)
559168404Spjd    z_streamp strm;
560168404Spjd    int flush;
561168404Spjd{
562168404Spjd    int old_flush; /* value of flush param for previous deflate call */
563168404Spjd    deflate_state *s;
564168404Spjd
565168404Spjd    if (strm == Z_NULL || strm->state == Z_NULL ||
566168404Spjd        flush > Z_FINISH || flush < 0) {
567168404Spjd        return Z_STREAM_ERROR;
568168404Spjd    }
569168404Spjd    s = strm->state;
570168404Spjd
571168404Spjd    if (strm->next_out == Z_NULL ||
572168404Spjd        (strm->next_in == Z_NULL && strm->avail_in != 0) ||
573168404Spjd        (s->status == FINISH_STATE && flush != Z_FINISH)) {
574168404Spjd        ERR_RETURN(strm, Z_STREAM_ERROR);
575168404Spjd    }
576168404Spjd    if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
577168404Spjd
578168404Spjd    s->strm = strm; /* just in case */
579168404Spjd    old_flush = s->last_flush;
580168404Spjd    s->last_flush = flush;
581168404Spjd
582168404Spjd    /* Write the header */
583168404Spjd    if (s->status == INIT_STATE) {
584168404Spjd#ifdef GZIP
585168404Spjd        if (s->wrap == 2) {
586168404Spjd            strm->adler = crc32(0L, Z_NULL, 0);
587168404Spjd            put_byte(s, 31);
588168404Spjd            put_byte(s, 139);
589168404Spjd            put_byte(s, 8);
590168404Spjd            if (s->gzhead == NULL) {
591168404Spjd                put_byte(s, 0);
592168404Spjd                put_byte(s, 0);
593168404Spjd                put_byte(s, 0);
594168404Spjd                put_byte(s, 0);
595168404Spjd                put_byte(s, 0);
596168404Spjd                put_byte(s, s->level == 9 ? 2 :
597168404Spjd                            (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
598168404Spjd                             4 : 0));
599168404Spjd                put_byte(s, OS_CODE);
600168404Spjd                s->status = BUSY_STATE;
601168404Spjd            }
602168404Spjd            else {
603168404Spjd                put_byte(s, (s->gzhead->text ? 1 : 0) +
604168404Spjd                            (s->gzhead->hcrc ? 2 : 0) +
605168404Spjd                            (s->gzhead->extra == Z_NULL ? 0 : 4) +
606168404Spjd                            (s->gzhead->name == Z_NULL ? 0 : 8) +
607168404Spjd                            (s->gzhead->comment == Z_NULL ? 0 : 16)
608168404Spjd                        );
609168404Spjd                put_byte(s, (Byte)(s->gzhead->time & 0xff));
610168404Spjd                put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
611168404Spjd                put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
612168404Spjd                put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
613168404Spjd                put_byte(s, s->level == 9 ? 2 :
614168404Spjd                            (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
615168404Spjd                             4 : 0));
616168404Spjd                put_byte(s, s->gzhead->os & 0xff);
617168404Spjd                if (s->gzhead->extra != NULL) {
618168404Spjd                    put_byte(s, s->gzhead->extra_len & 0xff);
619168404Spjd                    put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
620168404Spjd                }
621168404Spjd                if (s->gzhead->hcrc)
622168404Spjd                    strm->adler = crc32(strm->adler, s->pending_buf,
623168404Spjd                                        s->pending);
624168404Spjd                s->gzindex = 0;
625168404Spjd                s->status = EXTRA_STATE;
626168404Spjd            }
627168404Spjd        }
628168404Spjd        else
629168404Spjd#endif
630168404Spjd        {
631168404Spjd            uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
632168404Spjd            uInt level_flags;
633168404Spjd
634168404Spjd            if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
635168404Spjd                level_flags = 0;
636168404Spjd            else if (s->level < 6)
637168404Spjd                level_flags = 1;
638168404Spjd            else if (s->level == 6)
639168404Spjd                level_flags = 2;
640168404Spjd            else
641168404Spjd                level_flags = 3;
642168404Spjd            header |= (level_flags << 6);
643168404Spjd            if (s->strstart != 0) header |= PRESET_DICT;
644168404Spjd            header += 31 - (header % 31);
645168404Spjd
646168404Spjd            s->status = BUSY_STATE;
647168404Spjd            putShortMSB(s, header);
648168404Spjd
649168404Spjd            /* Save the adler32 of the preset dictionary: */
650168404Spjd            if (s->strstart != 0) {
651168404Spjd                putShortMSB(s, (uInt)(strm->adler >> 16));
652168404Spjd                putShortMSB(s, (uInt)(strm->adler & 0xffff));
653168404Spjd            }
654168404Spjd            strm->adler = adler32(0L, Z_NULL, 0);
655168404Spjd        }
656168404Spjd    }
657168404Spjd#ifdef GZIP
658168404Spjd    if (s->status == EXTRA_STATE) {
659168404Spjd        if (s->gzhead->extra != NULL) {
660168404Spjd            uInt beg = s->pending;  /* start of bytes to update crc */
661168404Spjd
662168404Spjd            while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
663168404Spjd                if (s->pending == s->pending_buf_size) {
664168404Spjd                    if (s->gzhead->hcrc && s->pending > beg)
665168404Spjd                        strm->adler = crc32(strm->adler, s->pending_buf + beg,
666168404Spjd                                            s->pending - beg);
667168404Spjd                    flush_pending(strm);
668168404Spjd                    beg = s->pending;
669168404Spjd                    if (s->pending == s->pending_buf_size)
670168404Spjd                        break;
671168404Spjd                }
672168404Spjd                put_byte(s, s->gzhead->extra[s->gzindex]);
673168404Spjd                s->gzindex++;
674168404Spjd            }
675168404Spjd            if (s->gzhead->hcrc && s->pending > beg)
676168404Spjd                strm->adler = crc32(strm->adler, s->pending_buf + beg,
677168404Spjd                                    s->pending - beg);
678168404Spjd            if (s->gzindex == s->gzhead->extra_len) {
679168404Spjd                s->gzindex = 0;
680168404Spjd                s->status = NAME_STATE;
681168404Spjd            }
682168404Spjd        }
683168404Spjd        else
684168404Spjd            s->status = NAME_STATE;
685168404Spjd    }
686168404Spjd    if (s->status == NAME_STATE) {
687168404Spjd        if (s->gzhead->name != NULL) {
688168404Spjd            uInt beg = s->pending;  /* start of bytes to update crc */
689168404Spjd            int val;
690168404Spjd
691168404Spjd            do {
692168404Spjd                if (s->pending == s->pending_buf_size) {
693168404Spjd                    if (s->gzhead->hcrc && s->pending > beg)
694168404Spjd                        strm->adler = crc32(strm->adler, s->pending_buf + beg,
695168404Spjd                                            s->pending - beg);
696168404Spjd                    flush_pending(strm);
697168404Spjd                    beg = s->pending;
698168404Spjd                    if (s->pending == s->pending_buf_size) {
699168404Spjd                        val = 1;
700168404Spjd                        break;
701168404Spjd                    }
702168404Spjd                }
703168404Spjd                val = s->gzhead->name[s->gzindex++];
704168404Spjd                put_byte(s, val);
705168404Spjd            } while (val != 0);
706168404Spjd            if (s->gzhead->hcrc && s->pending > beg)
707168404Spjd                strm->adler = crc32(strm->adler, s->pending_buf + beg,
708168404Spjd                                    s->pending - beg);
709168404Spjd            if (val == 0) {
710168404Spjd                s->gzindex = 0;
711168404Spjd                s->status = COMMENT_STATE;
712168404Spjd            }
713168404Spjd        }
714168404Spjd        else
715168404Spjd            s->status = COMMENT_STATE;
716168404Spjd    }
717168404Spjd    if (s->status == COMMENT_STATE) {
718168404Spjd        if (s->gzhead->comment != NULL) {
719168404Spjd            uInt beg = s->pending;  /* start of bytes to update crc */
720168404Spjd            int val;
721168404Spjd
722168404Spjd            do {
723168404Spjd                if (s->pending == s->pending_buf_size) {
724168404Spjd                    if (s->gzhead->hcrc && s->pending > beg)
725168404Spjd                        strm->adler = crc32(strm->adler, s->pending_buf + beg,
726168404Spjd                                            s->pending - beg);
727168404Spjd                    flush_pending(strm);
728168404Spjd                    beg = s->pending;
729168404Spjd                    if (s->pending == s->pending_buf_size) {
730168404Spjd                        val = 1;
731168404Spjd                        break;
732168404Spjd                    }
733168404Spjd                }
734168404Spjd                val = s->gzhead->comment[s->gzindex++];
735168404Spjd                put_byte(s, val);
736168404Spjd            } while (val != 0);
737168404Spjd            if (s->gzhead->hcrc && s->pending > beg)
738168404Spjd                strm->adler = crc32(strm->adler, s->pending_buf + beg,
739168404Spjd                                    s->pending - beg);
740168404Spjd            if (val == 0)
741168404Spjd                s->status = HCRC_STATE;
742168404Spjd        }
743168404Spjd        else
744168404Spjd            s->status = HCRC_STATE;
745168404Spjd    }
746168404Spjd    if (s->status == HCRC_STATE) {
747168404Spjd        if (s->gzhead->hcrc) {
748168404Spjd            if (s->pending + 2 > s->pending_buf_size)
749168404Spjd                flush_pending(strm);
750168404Spjd            if (s->pending + 2 <= s->pending_buf_size) {
751168404Spjd                put_byte(s, (Byte)(strm->adler & 0xff));
752168404Spjd                put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
753168404Spjd                strm->adler = crc32(0L, Z_NULL, 0);
754168404Spjd                s->status = BUSY_STATE;
755168404Spjd            }
756168404Spjd        }
757168404Spjd        else
758168404Spjd            s->status = BUSY_STATE;
759168404Spjd    }
760168404Spjd#endif
761168404Spjd
762168404Spjd    /* Flush as much pending output as possible */
763168404Spjd    if (s->pending != 0) {
764168404Spjd        flush_pending(strm);
765168404Spjd        if (strm->avail_out == 0) {
766168404Spjd            /* Since avail_out is 0, deflate will be called again with
767168404Spjd             * more output space, but possibly with both pending and
768168404Spjd             * avail_in equal to zero. There won't be anything to do,
769168404Spjd             * but this is not an error situation so make sure we
770168404Spjd             * return OK instead of BUF_ERROR at next call of deflate:
771168404Spjd             */
772168404Spjd            s->last_flush = -1;
773168404Spjd            return Z_OK;
774168404Spjd        }
775168404Spjd
776168404Spjd    /* Make sure there is something to do and avoid duplicate consecutive
777168404Spjd     * flushes. For repeated and useless calls with Z_FINISH, we keep
778168404Spjd     * returning Z_STREAM_END instead of Z_BUF_ERROR.
779168404Spjd     */
780168404Spjd    } else if (strm->avail_in == 0 && flush <= old_flush &&
781168404Spjd               flush != Z_FINISH) {
782168404Spjd        ERR_RETURN(strm, Z_BUF_ERROR);
783168404Spjd    }
784168404Spjd
785168404Spjd    /* User must not provide more input after the first FINISH: */
786168404Spjd    if (s->status == FINISH_STATE && strm->avail_in != 0) {
787168404Spjd        ERR_RETURN(strm, Z_BUF_ERROR);
788168404Spjd    }
789168404Spjd
790168404Spjd    /* Start a new block or continue the current one.
791168404Spjd     */
792168404Spjd    if (strm->avail_in != 0 || s->lookahead != 0 ||
793168404Spjd        (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
794168404Spjd        block_state bstate;
795168404Spjd
796168404Spjd        bstate = (*(configuration_table[s->level].func))(s, flush);
797168404Spjd
798168404Spjd        if (bstate == finish_started || bstate == finish_done) {
799168404Spjd            s->status = FINISH_STATE;
800168404Spjd        }
801168404Spjd        if (bstate == need_more || bstate == finish_started) {
802168404Spjd            if (strm->avail_out == 0) {
803168404Spjd                s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
804168404Spjd            }
805168404Spjd            return Z_OK;
806168404Spjd            /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
807168404Spjd             * of deflate should use the same flush parameter to make sure
808168404Spjd             * that the flush is complete. So we don't have to output an
809168404Spjd             * empty block here, this will be done at next call. This also
810168404Spjd             * ensures that for a very small output buffer, we emit at most
811168404Spjd             * one empty block.
812168404Spjd             */
813168404Spjd        }
814168404Spjd        if (bstate == block_done) {
815168404Spjd            if (flush == Z_PARTIAL_FLUSH) {
816168404Spjd                _tr_align(s);
817168404Spjd            } else { /* FULL_FLUSH or SYNC_FLUSH */
818168404Spjd                _tr_stored_block(s, (char*)0, 0L, 0);
819168404Spjd                /* For a full flush, this empty block will be recognized
820168404Spjd                 * as a special marker by inflate_sync().
821168404Spjd                 */
822168404Spjd                if (flush == Z_FULL_FLUSH) {
823168404Spjd                    CLEAR_HASH(s);             /* forget history */
824168404Spjd                }
825168404Spjd            }
826168404Spjd            flush_pending(strm);
827168404Spjd            if (strm->avail_out == 0) {
828168404Spjd              s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
829168404Spjd              return Z_OK;
830168404Spjd            }
831168404Spjd        }
832168404Spjd    }
833168404Spjd    Assert(strm->avail_out > 0, "bug2");
834168404Spjd
835168404Spjd    if (flush != Z_FINISH) return Z_OK;
836168404Spjd    if (s->wrap <= 0) return Z_STREAM_END;
837168404Spjd
838168404Spjd    /* Write the trailer */
839168404Spjd#ifdef GZIP
840168404Spjd    if (s->wrap == 2) {
841168404Spjd        put_byte(s, (Byte)(strm->adler & 0xff));
842168404Spjd        put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
843168404Spjd        put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
844168404Spjd        put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
845168404Spjd        put_byte(s, (Byte)(strm->total_in & 0xff));
846168404Spjd        put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
847168404Spjd        put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
848168404Spjd        put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
849168404Spjd    }
850168404Spjd    else
851168404Spjd#endif
852168404Spjd    {
853168404Spjd        putShortMSB(s, (uInt)(strm->adler >> 16));
854168404Spjd        putShortMSB(s, (uInt)(strm->adler & 0xffff));
855168404Spjd    }
856168404Spjd    flush_pending(strm);
857168404Spjd    /* If avail_out is zero, the application will call deflate again
858168404Spjd     * to flush the rest.
859168404Spjd     */
860168404Spjd    if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
861168404Spjd    return s->pending != 0 ? Z_OK : Z_STREAM_END;
862168404Spjd}
863168404Spjd
864168404Spjd/* ========================================================================= */
865168404Spjdint ZEXPORT deflateEnd (strm)
866168404Spjd    z_streamp strm;
867168404Spjd{
868168404Spjd    int status;
869168404Spjd
870168404Spjd    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
871168404Spjd
872168404Spjd    status = strm->state->status;
873168404Spjd    if (status != INIT_STATE &&
874168404Spjd        status != EXTRA_STATE &&
875168404Spjd        status != NAME_STATE &&
876168404Spjd        status != COMMENT_STATE &&
877168404Spjd        status != HCRC_STATE &&
878168404Spjd        status != BUSY_STATE &&
879168404Spjd        status != FINISH_STATE) {
880168404Spjd      return Z_STREAM_ERROR;
881168404Spjd    }
882168404Spjd
883168404Spjd    /* Deallocate in reverse order of allocations: */
884168404Spjd    TRY_FREE(strm, strm->state->pending_buf);
885168404Spjd    TRY_FREE(strm, strm->state->head);
886168404Spjd    TRY_FREE(strm, strm->state->prev);
887168404Spjd    TRY_FREE(strm, strm->state->window);
888168404Spjd
889168404Spjd    ZFREE(strm, strm->state);
890168404Spjd    strm->state = Z_NULL;
891168404Spjd
892168404Spjd    return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
893168404Spjd}
894168404Spjd
895168404Spjd/* =========================================================================
896168404Spjd * Copy the source state to the destination state.
897168404Spjd * To simplify the source, this is not supported for 16-bit MSDOS (which
898168404Spjd * doesn't have enough memory anyway to duplicate compression states).
899168404Spjd */
900168404Spjdint ZEXPORT deflateCopy (dest, source)
901168404Spjd    z_streamp dest;
902168404Spjd    z_streamp source;
903168404Spjd{
904168404Spjd#ifdef MAXSEG_64K
905168404Spjd    return Z_STREAM_ERROR;
906168404Spjd#else
907168404Spjd    deflate_state *ds;
908168404Spjd    deflate_state *ss;
909168404Spjd    ushf *overlay;
910168404Spjd
911168404Spjd
912168404Spjd    if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
913168404Spjd        return Z_STREAM_ERROR;
914168404Spjd    }
915168404Spjd
916168404Spjd    ss = source->state;
917168404Spjd
918168404Spjd    zmemcpy(dest, source, sizeof(z_stream));
919168404Spjd
920168404Spjd    ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
921168404Spjd    if (ds == Z_NULL) return Z_MEM_ERROR;
922168404Spjd    dest->state = (struct internal_state FAR *) ds;
923168404Spjd    zmemcpy(ds, ss, sizeof(deflate_state));
924168404Spjd    ds->strm = dest;
925168404Spjd
926168404Spjd    ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
927168404Spjd    ds->prev   = (Posf *)  ZALLOC(dest, ds->w_size, sizeof(Pos));
928168404Spjd    ds->head   = (Posf *)  ZALLOC(dest, ds->hash_size, sizeof(Pos));
929168404Spjd    overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
930168404Spjd    ds->pending_buf = (uchf *) overlay;
931168404Spjd
932168404Spjd    if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
933168404Spjd        ds->pending_buf == Z_NULL) {
934168404Spjd        deflateEnd (dest);
935168404Spjd        return Z_MEM_ERROR;
936168404Spjd    }
937168404Spjd    /* following zmemcpy do not work for 16-bit MSDOS */
938168404Spjd    zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
939168404Spjd    zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
940168404Spjd    zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
941168404Spjd    zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
942168404Spjd
943168404Spjd    ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
944168404Spjd    ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
945168404Spjd    ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
946168404Spjd
947168404Spjd    ds->l_desc.dyn_tree = ds->dyn_ltree;
948168404Spjd    ds->d_desc.dyn_tree = ds->dyn_dtree;
949168404Spjd    ds->bl_desc.dyn_tree = ds->bl_tree;
950168404Spjd
951168404Spjd    return Z_OK;
952168404Spjd#endif /* MAXSEG_64K */
953168404Spjd}
954168404Spjd
955168404Spjd/* ===========================================================================
956168404Spjd * Read a new buffer from the current input stream, update the adler32
957168404Spjd * and total number of bytes read.  All deflate() input goes through
958168404Spjd * this function so some applications may wish to modify it to avoid
959168404Spjd * allocating a large strm->next_in buffer and copying from it.
960168404Spjd * (See also flush_pending()).
961168404Spjd */
962168404Spjdlocal int read_buf(strm, buf, size)
963168404Spjd    z_streamp strm;
964168404Spjd    Bytef *buf;
965168404Spjd    unsigned size;
966168404Spjd{
967168404Spjd    unsigned len = strm->avail_in;
968168404Spjd
969168404Spjd    if (len > size) len = size;
970168404Spjd    if (len == 0) return 0;
971168404Spjd
972168404Spjd    strm->avail_in  -= len;
973168404Spjd
974168404Spjd    if (strm->state->wrap == 1) {
975168404Spjd        strm->adler = adler32(strm->adler, strm->next_in, len);
976168404Spjd    }
977168404Spjd#ifdef GZIP
978168404Spjd    else if (strm->state->wrap == 2) {
979168404Spjd        strm->adler = crc32(strm->adler, strm->next_in, len);
980168404Spjd    }
981168404Spjd#endif
982168404Spjd    zmemcpy(buf, strm->next_in, len);
983168404Spjd    strm->next_in  += len;
984168404Spjd    strm->total_in += len;
985168404Spjd
986168404Spjd    return (int)len;
987168404Spjd}
988168404Spjd
989168404Spjd/* ===========================================================================
990168404Spjd * Initialize the "longest match" routines for a new zlib stream
991168404Spjd */
992168404Spjdlocal void lm_init (s)
993168404Spjd    deflate_state *s;
994168404Spjd{
995168404Spjd    s->window_size = (ulg)2L*s->w_size;
996168404Spjd
997168404Spjd    CLEAR_HASH(s);
998168404Spjd
999168404Spjd    /* Set the default configuration parameters:
1000168404Spjd     */
1001168404Spjd    s->max_lazy_match   = configuration_table[s->level].max_lazy;
1002168404Spjd    s->good_match       = configuration_table[s->level].good_length;
1003168404Spjd    s->nice_match       = configuration_table[s->level].nice_length;
1004168404Spjd    s->max_chain_length = configuration_table[s->level].max_chain;
1005168404Spjd
1006168404Spjd    s->strstart = 0;
1007168404Spjd    s->block_start = 0L;
1008168404Spjd    s->lookahead = 0;
1009168404Spjd    s->match_length = s->prev_length = MIN_MATCH-1;
1010168404Spjd    s->match_available = 0;
1011168404Spjd    s->ins_h = 0;
1012168404Spjd#ifndef FASTEST
1013168404Spjd#ifdef ASMV
1014168404Spjd    match_init(); /* initialize the asm code */
1015168404Spjd#endif
1016168404Spjd#endif
1017168404Spjd}
1018168404Spjd
1019168404Spjd#ifndef FASTEST
1020168404Spjd/* ===========================================================================
1021168404Spjd * Set match_start to the longest match starting at the given string and
1022168404Spjd * return its length. Matches shorter or equal to prev_length are discarded,
1023168404Spjd * in which case the result is equal to prev_length and match_start is
1024168404Spjd * garbage.
1025168404Spjd * IN assertions: cur_match is the head of the hash chain for the current
1026168404Spjd *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1027168404Spjd * OUT assertion: the match length is not greater than s->lookahead.
1028168404Spjd */
1029168404Spjd#ifndef ASMV
1030168404Spjd/* For 80x86 and 680x0, an optimized version will be provided in match.asm or
1031168404Spjd * match.S. The code will be functionally equivalent.
1032168404Spjd */
1033168404Spjdlocal uInt longest_match(s, cur_match)
1034168404Spjd    deflate_state *s;
1035168404Spjd    IPos cur_match;                             /* current match */
1036168404Spjd{
1037168404Spjd    unsigned chain_length = s->max_chain_length;/* max hash chain length */
1038168404Spjd    register Bytef *scan = s->window + s->strstart; /* current string */
1039168404Spjd    register Bytef *match;                       /* matched string */
1040168404Spjd    register int len;                           /* length of current match */
1041168404Spjd    int best_len = s->prev_length;              /* best match length so far */
1042168404Spjd    int nice_match = s->nice_match;             /* stop if match long enough */
1043168404Spjd    IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
1044168404Spjd        s->strstart - (IPos)MAX_DIST(s) : NIL;
1045168404Spjd    /* Stop when cur_match becomes <= limit. To simplify the code,
1046168404Spjd     * we prevent matches with the string of window index 0.
1047168404Spjd     */
1048168404Spjd    Posf *prev = s->prev;
1049168404Spjd    uInt wmask = s->w_mask;
1050168404Spjd
1051168404Spjd#ifdef UNALIGNED_OK
1052168404Spjd    /* Compare two bytes at a time. Note: this is not always beneficial.
1053168404Spjd     * Try with and without -DUNALIGNED_OK to check.
1054168404Spjd     */
1055168404Spjd    register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
1056168404Spjd    register ush scan_start = *(ushf*)scan;
1057168404Spjd    register ush scan_end   = *(ushf*)(scan+best_len-1);
1058168404Spjd#else
1059168404Spjd    register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1060168404Spjd    register Byte scan_end1  = scan[best_len-1];
1061168404Spjd    register Byte scan_end   = scan[best_len];
1062168404Spjd#endif
1063168404Spjd
1064168404Spjd    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1065168404Spjd     * It is easy to get rid of this optimization if necessary.
1066168404Spjd     */
1067168404Spjd    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1068168404Spjd
1069168404Spjd    /* Do not waste too much time if we already have a good match: */
1070168404Spjd    if (s->prev_length >= s->good_match) {
1071168404Spjd        chain_length >>= 2;
1072168404Spjd    }
1073168404Spjd    /* Do not look for matches beyond the end of the input. This is necessary
1074168404Spjd     * to make deflate deterministic.
1075168404Spjd     */
1076168404Spjd    if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
1077168404Spjd
1078168404Spjd    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1079168404Spjd
1080168404Spjd    do {
1081168404Spjd        Assert(cur_match < s->strstart, "no future");
1082168404Spjd        match = s->window + cur_match;
1083168404Spjd
1084168404Spjd        /* Skip to next match if the match length cannot increase
1085168404Spjd         * or if the match length is less than 2.  Note that the checks below
1086168404Spjd         * for insufficient lookahead only occur occasionally for performance
1087168404Spjd         * reasons.  Therefore uninitialized memory will be accessed, and
1088168404Spjd         * conditional jumps will be made that depend on those values.
1089168404Spjd         * However the length of the match is limited to the lookahead, so
1090168404Spjd         * the output of deflate is not affected by the uninitialized values.
1091168404Spjd         */
1092168404Spjd#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
1093168404Spjd        /* This code assumes sizeof(unsigned short) == 2. Do not use
1094168404Spjd         * UNALIGNED_OK if your compiler uses a different size.
1095168404Spjd         */
1096168404Spjd        if (*(ushf*)(match+best_len-1) != scan_end ||
1097168404Spjd            *(ushf*)match != scan_start) continue;
1098168404Spjd
1099168404Spjd        /* It is not necessary to compare scan[2] and match[2] since they are
1100168404Spjd         * always equal when the other bytes match, given that the hash keys
1101168404Spjd         * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
1102168404Spjd         * strstart+3, +5, ... up to strstart+257. We check for insufficient
1103168404Spjd         * lookahead only every 4th comparison; the 128th check will be made
1104168404Spjd         * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
1105168404Spjd         * necessary to put more guard bytes at the end of the window, or
1106168404Spjd         * to check more often for insufficient lookahead.
1107168404Spjd         */
1108168404Spjd        Assert(scan[2] == match[2], "scan[2]?");
1109168404Spjd        scan++, match++;
1110168404Spjd        do {
1111168404Spjd        } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1112168404Spjd                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1113168404Spjd                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1114168404Spjd                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1115168404Spjd                 scan < strend);
1116168404Spjd        /* The funny "do {}" generates better code on most compilers */
1117168404Spjd
1118168404Spjd        /* Here, scan <= window+strstart+257 */
1119168404Spjd        Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1120168404Spjd        if (*scan == *match) scan++;
1121168404Spjd
1122168404Spjd        len = (MAX_MATCH - 1) - (int)(strend-scan);
1123168404Spjd        scan = strend - (MAX_MATCH-1);
1124168404Spjd
1125168404Spjd#else /* UNALIGNED_OK */
1126168404Spjd
1127168404Spjd        if (match[best_len]   != scan_end  ||
1128168404Spjd            match[best_len-1] != scan_end1 ||
1129168404Spjd            *match            != *scan     ||
1130168404Spjd            *++match          != scan[1])      continue;
1131168404Spjd
1132168404Spjd        /* The check at best_len-1 can be removed because it will be made
1133168404Spjd         * again later. (This heuristic is not always a win.)
1134168404Spjd         * It is not necessary to compare scan[2] and match[2] since they
1135168404Spjd         * are always equal when the other bytes match, given that
1136168404Spjd         * the hash keys are equal and that HASH_BITS >= 8.
1137168404Spjd         */
1138168404Spjd        scan += 2, match++;
1139168404Spjd        Assert(*scan == *match, "match[2]?");
1140168404Spjd
1141168404Spjd        /* We check for insufficient lookahead only every 8th comparison;
1142168404Spjd         * the 256th check will be made at strstart+258.
1143168404Spjd         */
1144168404Spjd        do {
1145168404Spjd        } while (*++scan == *++match && *++scan == *++match &&
1146168404Spjd                 *++scan == *++match && *++scan == *++match &&
1147168404Spjd                 *++scan == *++match && *++scan == *++match &&
1148168404Spjd                 *++scan == *++match && *++scan == *++match &&
1149168404Spjd                 scan < strend);
1150168404Spjd
1151168404Spjd        Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1152168404Spjd
1153168404Spjd        len = MAX_MATCH - (int)(strend - scan);
1154168404Spjd        scan = strend - MAX_MATCH;
1155168404Spjd
1156168404Spjd#endif /* UNALIGNED_OK */
1157168404Spjd
1158168404Spjd        if (len > best_len) {
1159168404Spjd            s->match_start = cur_match;
1160168404Spjd            best_len = len;
1161168404Spjd            if (len >= nice_match) break;
1162168404Spjd#ifdef UNALIGNED_OK
1163168404Spjd            scan_end = *(ushf*)(scan+best_len-1);
1164168404Spjd#else
1165168404Spjd            scan_end1  = scan[best_len-1];
1166168404Spjd            scan_end   = scan[best_len];
1167168404Spjd#endif
1168168404Spjd        }
1169168404Spjd    } while ((cur_match = prev[cur_match & wmask]) > limit
1170168404Spjd             && --chain_length != 0);
1171168404Spjd
1172168404Spjd    if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
1173168404Spjd    return s->lookahead;
1174168404Spjd}
1175168404Spjd#endif /* ASMV */
1176168404Spjd#endif /* FASTEST */
1177168404Spjd
1178168404Spjd/* ---------------------------------------------------------------------------
1179168404Spjd * Optimized version for level == 1 or strategy == Z_RLE only
1180168404Spjd */
1181168404Spjdlocal uInt longest_match_fast(s, cur_match)
1182168404Spjd    deflate_state *s;
1183168404Spjd    IPos cur_match;                             /* current match */
1184168404Spjd{
1185168404Spjd    register Bytef *scan = s->window + s->strstart; /* current string */
1186168404Spjd    register Bytef *match;                       /* matched string */
1187168404Spjd    register int len;                           /* length of current match */
1188168404Spjd    register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1189168404Spjd
1190168404Spjd    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1191168404Spjd     * It is easy to get rid of this optimization if necessary.
1192168404Spjd     */
1193168404Spjd    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1194168404Spjd
1195168404Spjd    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1196168404Spjd
1197168404Spjd    Assert(cur_match < s->strstart, "no future");
1198168404Spjd
1199168404Spjd    match = s->window + cur_match;
1200168404Spjd
1201168404Spjd    /* Return failure if the match length is less than 2:
1202168404Spjd     */
1203168404Spjd    if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
1204168404Spjd
1205168404Spjd    /* The check at best_len-1 can be removed because it will be made
1206168404Spjd     * again later. (This heuristic is not always a win.)
1207168404Spjd     * It is not necessary to compare scan[2] and match[2] since they
1208168404Spjd     * are always equal when the other bytes match, given that
1209168404Spjd     * the hash keys are equal and that HASH_BITS >= 8.
1210168404Spjd     */
1211168404Spjd    scan += 2, match += 2;
1212168404Spjd    Assert(*scan == *match, "match[2]?");
1213168404Spjd
1214168404Spjd    /* We check for insufficient lookahead only every 8th comparison;
1215168404Spjd     * the 256th check will be made at strstart+258.
1216168404Spjd     */
1217168404Spjd    do {
1218168404Spjd    } while (*++scan == *++match && *++scan == *++match &&
1219168404Spjd             *++scan == *++match && *++scan == *++match &&
1220168404Spjd             *++scan == *++match && *++scan == *++match &&
1221168404Spjd             *++scan == *++match && *++scan == *++match &&
1222168404Spjd             scan < strend);
1223168404Spjd
1224168404Spjd    Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1225168404Spjd
1226168404Spjd    len = MAX_MATCH - (int)(strend - scan);
1227168404Spjd
1228168404Spjd    if (len < MIN_MATCH) return MIN_MATCH - 1;
1229168404Spjd
1230168404Spjd    s->match_start = cur_match;
1231168404Spjd    return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
1232168404Spjd}
1233168404Spjd
1234168404Spjd#ifdef DEBUG
1235168404Spjd/* ===========================================================================
1236168404Spjd * Check that the match at match_start is indeed a match.
1237168404Spjd */
1238168404Spjdlocal void check_match(s, start, match, length)
1239168404Spjd    deflate_state *s;
1240168404Spjd    IPos start, match;
1241168404Spjd    int length;
1242168404Spjd{
1243168404Spjd    /* check that the match is indeed a match */
1244168404Spjd    if (zmemcmp(s->window + match,
1245168404Spjd                s->window + start, length) != EQUAL) {
1246168404Spjd        fprintf(stderr, " start %u, match %u, length %d\n",
1247168404Spjd                start, match, length);
1248168404Spjd        do {
1249168404Spjd            fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
1250168404Spjd        } while (--length != 0);
1251168404Spjd        z_error("invalid match");
1252168404Spjd    }
1253168404Spjd    if (z_verbose > 1) {
1254168404Spjd        fprintf(stderr,"\\[%d,%d]", start-match, length);
1255168404Spjd        do { putc(s->window[start++], stderr); } while (--length != 0);
1256168404Spjd    }
1257168404Spjd}
1258168404Spjd#else
1259168404Spjd#  define check_match(s, start, match, length)
1260168404Spjd#endif /* DEBUG */
1261168404Spjd
1262168404Spjd/* ===========================================================================
1263168404Spjd * Fill the window when the lookahead becomes insufficient.
1264168404Spjd * Updates strstart and lookahead.
1265168404Spjd *
1266168404Spjd * IN assertion: lookahead < MIN_LOOKAHEAD
1267168404Spjd * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1268168404Spjd *    At least one byte has been read, or avail_in == 0; reads are
1269168404Spjd *    performed for at least two bytes (required for the zip translate_eol
1270168404Spjd *    option -- not supported here).
1271168404Spjd */
1272168404Spjdlocal void fill_window(s)
1273168404Spjd    deflate_state *s;
1274168404Spjd{
1275168404Spjd    register unsigned n, m;
1276168404Spjd    register Posf *p;
1277168404Spjd    unsigned more;    /* Amount of free space at the end of the window. */
1278168404Spjd    uInt wsize = s->w_size;
1279168404Spjd
1280168404Spjd    do {
1281168404Spjd        more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
1282168404Spjd
1283168404Spjd        /* Deal with !@#$% 64K limit: */
1284168404Spjd        if (sizeof(int) <= 2) {
1285168404Spjd            if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1286168404Spjd                more = wsize;
1287168404Spjd
1288168404Spjd            } else if (more == (unsigned)(-1)) {
1289168404Spjd                /* Very unlikely, but possible on 16 bit machine if
1290168404Spjd                 * strstart == 0 && lookahead == 1 (input done a byte at time)
1291168404Spjd                 */
1292168404Spjd                more--;
1293168404Spjd            }
1294168404Spjd        }
1295168404Spjd
1296168404Spjd        /* If the window is almost full and there is insufficient lookahead,
1297168404Spjd         * move the upper half to the lower one to make room in the upper half.
1298168404Spjd         */
1299168404Spjd        if (s->strstart >= wsize+MAX_DIST(s)) {
1300168404Spjd
1301168404Spjd            zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
1302168404Spjd            s->match_start -= wsize;
1303168404Spjd            s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
1304168404Spjd            s->block_start -= (long) wsize;
1305168404Spjd
1306168404Spjd            /* Slide the hash table (could be avoided with 32 bit values
1307168404Spjd               at the expense of memory usage). We slide even when level == 0
1308168404Spjd               to keep the hash table consistent if we switch back to level > 0
1309168404Spjd               later. (Using level 0 permanently is not an optimal usage of
1310168404Spjd               zlib, so we don't care about this pathological case.)
1311168404Spjd             */
1312168404Spjd            /* %%% avoid this when Z_RLE */
1313168404Spjd            n = s->hash_size;
1314168404Spjd            p = &s->head[n];
1315168404Spjd            do {
1316168404Spjd                m = *--p;
1317168404Spjd                *p = (Pos)(m >= wsize ? m-wsize : NIL);
1318168404Spjd            } while (--n);
1319168404Spjd
1320168404Spjd            n = wsize;
1321168404Spjd#ifndef FASTEST
1322168404Spjd            p = &s->prev[n];
1323168404Spjd            do {
1324168404Spjd                m = *--p;
1325168404Spjd                *p = (Pos)(m >= wsize ? m-wsize : NIL);
1326168404Spjd                /* If n is not on any hash chain, prev[n] is garbage but
1327168404Spjd                 * its value will never be used.
1328168404Spjd                 */
1329168404Spjd            } while (--n);
1330168404Spjd#endif
1331168404Spjd            more += wsize;
1332168404Spjd        }
1333168404Spjd        if (s->strm->avail_in == 0) return;
1334168404Spjd
1335168404Spjd        /* If there was no sliding:
1336168404Spjd         *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1337168404Spjd         *    more == window_size - lookahead - strstart
1338168404Spjd         * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1339168404Spjd         * => more >= window_size - 2*WSIZE + 2
1340168404Spjd         * In the BIG_MEM or MMAP case (not yet supported),
1341168404Spjd         *   window_size == input_size + MIN_LOOKAHEAD  &&
1342168404Spjd         *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1343168404Spjd         * Otherwise, window_size == 2*WSIZE so more >= 2.
1344168404Spjd         * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1345168404Spjd         */
1346168404Spjd        Assert(more >= 2, "more < 2");
1347168404Spjd
1348168404Spjd        n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1349168404Spjd        s->lookahead += n;
1350168404Spjd
1351168404Spjd        /* Initialize the hash value now that we have some input: */
1352168404Spjd        if (s->lookahead >= MIN_MATCH) {
1353168404Spjd            s->ins_h = s->window[s->strstart];
1354168404Spjd            UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1355168404Spjd#if MIN_MATCH != 3
1356168404Spjd            Call UPDATE_HASH() MIN_MATCH-3 more times
1357168404Spjd#endif
1358168404Spjd        }
1359168404Spjd        /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1360168404Spjd         * but this is not important since only literal bytes will be emitted.
1361168404Spjd         */
1362168404Spjd
1363168404Spjd    } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1364168404Spjd}
1365168404Spjd
1366168404Spjd/* ===========================================================================
1367168404Spjd * Flush the current block, with given end-of-file flag.
1368168404Spjd * IN assertion: strstart is set to the end of the current match.
1369168404Spjd */
1370168404Spjd#define FLUSH_BLOCK_ONLY(s, eof) { \
1371168404Spjd   _tr_flush_block(s, (s->block_start >= 0L ? \
1372168404Spjd                   (charf *)&s->window[(unsigned)s->block_start] : \
1373168404Spjd                   (charf *)Z_NULL), \
1374168404Spjd                (ulg)((long)s->strstart - s->block_start), \
1375168404Spjd                (eof)); \
1376168404Spjd   s->block_start = s->strstart; \
1377168404Spjd   flush_pending(s->strm); \
1378168404Spjd   Tracev((stderr,"[FLUSH]")); \
1379168404Spjd}
1380168404Spjd
1381168404Spjd/* Same but force premature exit if necessary. */
1382168404Spjd#define FLUSH_BLOCK(s, eof) { \
1383168404Spjd   FLUSH_BLOCK_ONLY(s, eof); \
1384168404Spjd   if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
1385168404Spjd}
1386168404Spjd
1387168404Spjd/* ===========================================================================
1388168404Spjd * Copy without compression as much as possible from the input stream, return
1389168404Spjd * the current block state.
1390168404Spjd * This function does not insert new strings in the dictionary since
1391168404Spjd * uncompressible data is probably not useful. This function is used
1392168404Spjd * only for the level=0 compression option.
1393168404Spjd * NOTE: this function should be optimized to avoid extra copying from
1394168404Spjd * window to pending_buf.
1395168404Spjd */
1396168404Spjdlocal block_state deflate_stored(s, flush)
1397168404Spjd    deflate_state *s;
1398168404Spjd    int flush;
1399168404Spjd{
1400168404Spjd    /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
1401168404Spjd     * to pending_buf_size, and each stored block has a 5 byte header:
1402168404Spjd     */
1403168404Spjd    ulg max_block_size = 0xffff;
1404168404Spjd    ulg max_start;
1405168404Spjd
1406168404Spjd    if (max_block_size > s->pending_buf_size - 5) {
1407168404Spjd        max_block_size = s->pending_buf_size - 5;
1408168404Spjd    }
1409168404Spjd
1410168404Spjd    /* Copy as much as possible from input to output: */
1411168404Spjd    for (;;) {
1412168404Spjd        /* Fill the window as much as possible: */
1413168404Spjd        if (s->lookahead <= 1) {
1414168404Spjd
1415168404Spjd            Assert(s->strstart < s->w_size+MAX_DIST(s) ||
1416168404Spjd                   s->block_start >= (long)s->w_size, "slide too late");
1417168404Spjd
1418168404Spjd            fill_window(s);
1419168404Spjd            if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
1420168404Spjd
1421168404Spjd            if (s->lookahead == 0) break; /* flush the current block */
1422168404Spjd        }
1423168404Spjd        Assert(s->block_start >= 0L, "block gone");
1424168404Spjd
1425168404Spjd        s->strstart += s->lookahead;
1426168404Spjd        s->lookahead = 0;
1427168404Spjd
1428168404Spjd        /* Emit a stored block if pending_buf will be full: */
1429168404Spjd        max_start = s->block_start + max_block_size;
1430168404Spjd        if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
1431168404Spjd            /* strstart == 0 is possible when wraparound on 16-bit machine */
1432168404Spjd            s->lookahead = (uInt)(s->strstart - max_start);
1433168404Spjd            s->strstart = (uInt)max_start;
1434168404Spjd            FLUSH_BLOCK(s, 0);
1435168404Spjd        }
1436168404Spjd        /* Flush if we may have to slide, otherwise block_start may become
1437168404Spjd         * negative and the data will be gone:
1438168404Spjd         */
1439168404Spjd        if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
1440168404Spjd            FLUSH_BLOCK(s, 0);
1441168404Spjd        }
1442168404Spjd    }
1443168404Spjd    FLUSH_BLOCK(s, flush == Z_FINISH);
1444168404Spjd    return flush == Z_FINISH ? finish_done : block_done;
1445168404Spjd}
1446168404Spjd
1447168404Spjd/* ===========================================================================
1448168404Spjd * Compress as much as possible from the input stream, return the current
1449168404Spjd * block state.
1450168404Spjd * This function does not perform lazy evaluation of matches and inserts
1451168404Spjd * new strings in the dictionary only for unmatched strings or for short
1452168404Spjd * matches. It is used only for the fast compression options.
1453168404Spjd */
1454168404Spjdlocal block_state deflate_fast(s, flush)
1455168404Spjd    deflate_state *s;
1456168404Spjd    int flush;
1457168404Spjd{
1458168404Spjd    IPos hash_head = NIL; /* head of the hash chain */
1459168404Spjd    int bflush;           /* set if current block must be flushed */
1460168404Spjd
1461168404Spjd    for (;;) {
1462168404Spjd        /* Make sure that we always have enough lookahead, except
1463168404Spjd         * at the end of the input file. We need MAX_MATCH bytes
1464168404Spjd         * for the next match, plus MIN_MATCH bytes to insert the
1465168404Spjd         * string following the next match.
1466168404Spjd         */
1467168404Spjd        if (s->lookahead < MIN_LOOKAHEAD) {
1468168404Spjd            fill_window(s);
1469168404Spjd            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1470168404Spjd                return need_more;
1471168404Spjd            }
1472168404Spjd            if (s->lookahead == 0) break; /* flush the current block */
1473168404Spjd        }
1474168404Spjd
1475168404Spjd        /* Insert the string window[strstart .. strstart+2] in the
1476168404Spjd         * dictionary, and set hash_head to the head of the hash chain:
1477168404Spjd         */
1478168404Spjd        if (s->lookahead >= MIN_MATCH) {
1479168404Spjd            INSERT_STRING(s, s->strstart, hash_head);
1480168404Spjd        }
1481168404Spjd
1482168404Spjd        /* Find the longest match, discarding those <= prev_length.
1483168404Spjd         * At this point we have always match_length < MIN_MATCH
1484168404Spjd         */
1485168404Spjd        if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1486168404Spjd            /* To simplify the code, we prevent matches with the string
1487168404Spjd             * of window index 0 (in particular we have to avoid a match
1488168404Spjd             * of the string with itself at the start of the input file).
1489168404Spjd             */
1490168404Spjd#ifdef FASTEST
1491168404Spjd            if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
1492168404Spjd                (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
1493168404Spjd                s->match_length = longest_match_fast (s, hash_head);
1494168404Spjd            }
1495168404Spjd#else
1496168404Spjd            if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
1497168404Spjd                s->match_length = longest_match (s, hash_head);
1498168404Spjd            } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
1499168404Spjd                s->match_length = longest_match_fast (s, hash_head);
1500168404Spjd            }
1501168404Spjd#endif
1502168404Spjd            /* longest_match() or longest_match_fast() sets match_start */
1503168404Spjd        }
1504168404Spjd        if (s->match_length >= MIN_MATCH) {
1505168404Spjd            check_match(s, s->strstart, s->match_start, s->match_length);
1506168404Spjd
1507168404Spjd            _tr_tally_dist(s, s->strstart - s->match_start,
1508168404Spjd                           s->match_length - MIN_MATCH, bflush);
1509168404Spjd
1510168404Spjd            s->lookahead -= s->match_length;
1511168404Spjd
1512168404Spjd            /* Insert new strings in the hash table only if the match length
1513168404Spjd             * is not too large. This saves time but degrades compression.
1514168404Spjd             */
1515168404Spjd#ifndef FASTEST
1516168404Spjd            if (s->match_length <= s->max_insert_length &&
1517168404Spjd                s->lookahead >= MIN_MATCH) {
1518168404Spjd                s->match_length--; /* string at strstart already in table */
1519168404Spjd                do {
1520168404Spjd                    s->strstart++;
1521168404Spjd                    INSERT_STRING(s, s->strstart, hash_head);
1522168404Spjd                    /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1523168404Spjd                     * always MIN_MATCH bytes ahead.
1524168404Spjd                     */
1525168404Spjd                } while (--s->match_length != 0);
1526168404Spjd                s->strstart++;
1527168404Spjd            } else
1528168404Spjd#endif
1529168404Spjd            {
1530168404Spjd                s->strstart += s->match_length;
1531168404Spjd                s->match_length = 0;
1532168404Spjd                s->ins_h = s->window[s->strstart];
1533168404Spjd                UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1534168404Spjd#if MIN_MATCH != 3
1535168404Spjd                Call UPDATE_HASH() MIN_MATCH-3 more times
1536168404Spjd#endif
1537168404Spjd                /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1538168404Spjd                 * matter since it will be recomputed at next deflate call.
1539168404Spjd                 */
1540168404Spjd            }
1541168404Spjd        } else {
1542168404Spjd            /* No match, output a literal byte */
1543168404Spjd            Tracevv((stderr,"%c", s->window[s->strstart]));
1544168404Spjd            _tr_tally_lit (s, s->window[s->strstart], bflush);
1545168404Spjd            s->lookahead--;
1546168404Spjd            s->strstart++;
1547168404Spjd        }
1548168404Spjd        if (bflush) FLUSH_BLOCK(s, 0);
1549168404Spjd    }
1550168404Spjd    FLUSH_BLOCK(s, flush == Z_FINISH);
1551168404Spjd    return flush == Z_FINISH ? finish_done : block_done;
1552168404Spjd}
1553168404Spjd
1554168404Spjd#ifndef FASTEST
1555168404Spjd/* ===========================================================================
1556168404Spjd * Same as above, but achieves better compression. We use a lazy
1557168404Spjd * evaluation for matches: a match is finally adopted only if there is
1558168404Spjd * no better match at the next window position.
1559168404Spjd */
1560168404Spjdlocal block_state deflate_slow(s, flush)
1561168404Spjd    deflate_state *s;
1562168404Spjd    int flush;
1563168404Spjd{
1564168404Spjd    IPos hash_head = NIL;    /* head of hash chain */
1565168404Spjd    int bflush;              /* set if current block must be flushed */
1566168404Spjd
1567168404Spjd    /* Process the input block. */
1568168404Spjd    for (;;) {
1569168404Spjd        /* Make sure that we always have enough lookahead, except
1570168404Spjd         * at the end of the input file. We need MAX_MATCH bytes
1571168404Spjd         * for the next match, plus MIN_MATCH bytes to insert the
1572168404Spjd         * string following the next match.
1573168404Spjd         */
1574168404Spjd        if (s->lookahead < MIN_LOOKAHEAD) {
1575168404Spjd            fill_window(s);
1576168404Spjd            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1577168404Spjd                return need_more;
1578168404Spjd            }
1579168404Spjd            if (s->lookahead == 0) break; /* flush the current block */
1580168404Spjd        }
1581168404Spjd
1582168404Spjd        /* Insert the string window[strstart .. strstart+2] in the
1583168404Spjd         * dictionary, and set hash_head to the head of the hash chain:
1584168404Spjd         */
1585168404Spjd        if (s->lookahead >= MIN_MATCH) {
1586168404Spjd            INSERT_STRING(s, s->strstart, hash_head);
1587168404Spjd        }
1588168404Spjd
1589168404Spjd        /* Find the longest match, discarding those <= prev_length.
1590168404Spjd         */
1591168404Spjd        s->prev_length = s->match_length, s->prev_match = s->match_start;
1592168404Spjd        s->match_length = MIN_MATCH-1;
1593168404Spjd
1594168404Spjd        if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
1595168404Spjd            s->strstart - hash_head <= MAX_DIST(s)) {
1596168404Spjd            /* To simplify the code, we prevent matches with the string
1597168404Spjd             * of window index 0 (in particular we have to avoid a match
1598168404Spjd             * of the string with itself at the start of the input file).
1599168404Spjd             */
1600168404Spjd            if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
1601168404Spjd                s->match_length = longest_match (s, hash_head);
1602168404Spjd            } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
1603168404Spjd                s->match_length = longest_match_fast (s, hash_head);
1604168404Spjd            }
1605168404Spjd            /* longest_match() or longest_match_fast() sets match_start */
1606168404Spjd
1607168404Spjd            if (s->match_length <= 5 && (s->strategy == Z_FILTERED
1608168404Spjd#if TOO_FAR <= 32767
1609168404Spjd                || (s->match_length == MIN_MATCH &&
1610168404Spjd                    s->strstart - s->match_start > TOO_FAR)
1611168404Spjd#endif
1612168404Spjd                )) {
1613168404Spjd
1614168404Spjd                /* If prev_match is also MIN_MATCH, match_start is garbage
1615168404Spjd                 * but we will ignore the current match anyway.
1616168404Spjd                 */
1617168404Spjd                s->match_length = MIN_MATCH-1;
1618168404Spjd            }
1619168404Spjd        }
1620168404Spjd        /* If there was a match at the previous step and the current
1621168404Spjd         * match is not better, output the previous match:
1622168404Spjd         */
1623168404Spjd        if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
1624168404Spjd            uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
1625168404Spjd            /* Do not insert strings in hash table beyond this. */
1626168404Spjd
1627168404Spjd            check_match(s, s->strstart-1, s->prev_match, s->prev_length);
1628168404Spjd
1629168404Spjd            _tr_tally_dist(s, s->strstart -1 - s->prev_match,
1630168404Spjd                           s->prev_length - MIN_MATCH, bflush);
1631168404Spjd
1632168404Spjd            /* Insert in hash table all strings up to the end of the match.
1633168404Spjd             * strstart-1 and strstart are already inserted. If there is not
1634168404Spjd             * enough lookahead, the last two strings are not inserted in
1635168404Spjd             * the hash table.
1636168404Spjd             */
1637168404Spjd            s->lookahead -= s->prev_length-1;
1638168404Spjd            s->prev_length -= 2;
1639168404Spjd            do {
1640168404Spjd                if (++s->strstart <= max_insert) {
1641168404Spjd                    INSERT_STRING(s, s->strstart, hash_head);
1642168404Spjd                }
1643168404Spjd            } while (--s->prev_length != 0);
1644168404Spjd            s->match_available = 0;
1645168404Spjd            s->match_length = MIN_MATCH-1;
1646168404Spjd            s->strstart++;
1647168404Spjd
1648168404Spjd            if (bflush) FLUSH_BLOCK(s, 0);
1649168404Spjd
1650168404Spjd        } else if (s->match_available) {
1651168404Spjd            /* If there was no match at the previous position, output a
1652168404Spjd             * single literal. If there was a match but the current match
1653168404Spjd             * is longer, truncate the previous match to a single literal.
1654168404Spjd             */
1655168404Spjd            Tracevv((stderr,"%c", s->window[s->strstart-1]));
1656168404Spjd            _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1657168404Spjd            if (bflush) {
1658168404Spjd                FLUSH_BLOCK_ONLY(s, 0);
1659168404Spjd            }
1660168404Spjd            s->strstart++;
1661168404Spjd            s->lookahead--;
1662168404Spjd            if (s->strm->avail_out == 0) return need_more;
1663168404Spjd        } else {
1664168404Spjd            /* There is no previous match to compare with, wait for
1665168404Spjd             * the next step to decide.
1666168404Spjd             */
1667168404Spjd            s->match_available = 1;
1668168404Spjd            s->strstart++;
1669168404Spjd            s->lookahead--;
1670168404Spjd        }
1671168404Spjd    }
1672168404Spjd    Assert (flush != Z_NO_FLUSH, "no flush?");
1673168404Spjd    if (s->match_available) {
1674168404Spjd        Tracevv((stderr,"%c", s->window[s->strstart-1]));
1675168404Spjd        _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1676168404Spjd        s->match_available = 0;
1677168404Spjd    }
1678168404Spjd    FLUSH_BLOCK(s, flush == Z_FINISH);
1679168404Spjd    return flush == Z_FINISH ? finish_done : block_done;
1680168404Spjd}
1681168404Spjd#endif /* FASTEST */
1682168404Spjd
1683168404Spjd#if 0
1684168404Spjd/* ===========================================================================
1685168404Spjd * For Z_RLE, simply look for runs of bytes, generate matches only of distance
1686168404Spjd * one.  Do not maintain a hash table.  (It will be regenerated if this run of
1687168404Spjd * deflate switches away from Z_RLE.)
1688168404Spjd */
1689168404Spjdlocal block_state deflate_rle(s, flush)
1690168404Spjd    deflate_state *s;
1691168404Spjd    int flush;
1692168404Spjd{
1693168404Spjd    int bflush;         /* set if current block must be flushed */
1694168404Spjd    uInt run;           /* length of run */
1695168404Spjd    uInt max;           /* maximum length of run */
1696168404Spjd    uInt prev;          /* byte at distance one to match */
1697168404Spjd    Bytef *scan;        /* scan for end of run */
1698168404Spjd
1699168404Spjd    for (;;) {
1700168404Spjd        /* Make sure that we always have enough lookahead, except
1701168404Spjd         * at the end of the input file. We need MAX_MATCH bytes
1702168404Spjd         * for the longest encodable run.
1703168404Spjd         */
1704168404Spjd        if (s->lookahead < MAX_MATCH) {
1705168404Spjd            fill_window(s);
1706168404Spjd            if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
1707168404Spjd                return need_more;
1708168404Spjd            }
1709168404Spjd            if (s->lookahead == 0) break; /* flush the current block */
1710168404Spjd        }
1711168404Spjd
1712168404Spjd        /* See how many times the previous byte repeats */
1713168404Spjd        run = 0;
1714168404Spjd        if (s->strstart > 0) {      /* if there is a previous byte, that is */
1715168404Spjd            max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
1716168404Spjd            scan = s->window + s->strstart - 1;
1717168404Spjd            prev = *scan++;
1718168404Spjd            do {
1719168404Spjd                if (*scan++ != prev)
1720168404Spjd                    break;
1721168404Spjd            } while (++run < max);
1722168404Spjd        }
1723168404Spjd
1724168404Spjd        /* Emit match if have run of MIN_MATCH or longer, else emit literal */
1725168404Spjd        if (run >= MIN_MATCH) {
1726168404Spjd            check_match(s, s->strstart, s->strstart - 1, run);
1727168404Spjd            _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
1728168404Spjd            s->lookahead -= run;
1729168404Spjd            s->strstart += run;
1730168404Spjd        } else {
1731168404Spjd            /* No match, output a literal byte */
1732168404Spjd            Tracevv((stderr,"%c", s->window[s->strstart]));
1733168404Spjd            _tr_tally_lit (s, s->window[s->strstart], bflush);
1734168404Spjd            s->lookahead--;
1735168404Spjd            s->strstart++;
1736168404Spjd        }
1737168404Spjd        if (bflush) FLUSH_BLOCK(s, 0);
1738168404Spjd    }
1739168404Spjd    FLUSH_BLOCK(s, flush == Z_FINISH);
1740168404Spjd    return flush == Z_FINISH ? finish_done : block_done;
1741168404Spjd}
1742168404Spjd#endif
1743