1/* deflate.c -- compress data using the deflation algorithm
2 * Copyright (C) 1995-2002 Jean-loup Gailly.
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/*
7 *  ALGORITHM
8 *
9 *      The "deflation" process depends on being able to identify portions
10 *      of the input text which are identical to earlier input (within a
11 *      sliding window trailing behind the input currently being processed).
12 *
13 *      The most straightforward technique turns out to be the fastest for
14 *      most input files: try all possible matches and select the longest.
15 *      The key feature of this algorithm is that insertions into the string
16 *      dictionary are very simple and thus fast, and deletions are avoided
17 *      completely. Insertions are performed at each input character, whereas
18 *      string matches are performed only when the previous match ends. So it
19 *      is preferable to spend more time in matches to allow very fast string
20 *      insertions and avoid deletions. The matching algorithm for small
21 *      strings is inspired from that of Rabin & Karp. A brute force approach
22 *      is used to find longer strings when a small match has been found.
23 *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
24 *      (by Leonid Broukhis).
25 *         A previous version of this file used a more sophisticated algorithm
26 *      (by Fiala and Greene) which is guaranteed to run in linear amortized
27 *      time, but has a larger average cost, uses more memory and is patented.
28 *      However the F&G algorithm may be faster for some highly redundant
29 *      files if the parameter max_chain_length (described below) is too large.
30 *
31 *  ACKNOWLEDGEMENTS
32 *
33 *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
34 *      I found it in 'freeze' written by Leonid Broukhis.
35 *      Thanks to many people for bug reports and testing.
36 *
37 *  REFERENCES
38 *
39 *      Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
40 *      Available in ftp://ds.internic.net/rfc/rfc1951.txt
41 *
42 *      A description of the Rabin and Karp algorithm is given in the book
43 *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
44 *
45 *      Fiala,E.R., and Greene,D.H.
46 *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
47 *
48 */
49
50/* $Id: deflate.c 14574 2005-10-29 16:27:43Z bonefish $ */
51/* @(#) $Id: deflate.c 14574 2005-10-29 16:27:43Z bonefish $ */
52
53#include "deflate.h"
54
55const char deflate_copyright[] =
56   " deflate 1.1.4 Copyright 1995-2002 Jean-loup Gailly ";
57/*
58  If you use the zlib library in a product, an acknowledgment is welcome
59  in the documentation of your product. If for some reason you cannot
60  include such an acknowledgment, I would appreciate that you keep this
61  copyright string in the executable of your product.
62 */
63
64/* ===========================================================================
65 *  Function prototypes.
66 */
67typedef enum {
68    need_more,      /* block not completed, need more input or more output */
69    block_done,     /* block flush performed */
70    finish_started, /* finish started, need only more output at next deflate */
71    finish_done     /* finish done, accept no more input or output */
72} block_state;
73
74typedef block_state (*compress_func) OF((deflate_state *s, int flush));
75/* Compression function. Returns the block state after the call. */
76
77local void fill_window    OF((deflate_state *s));
78local block_state deflate_stored OF((deflate_state *s, int flush));
79local block_state deflate_fast   OF((deflate_state *s, int flush));
80local block_state deflate_slow   OF((deflate_state *s, int flush));
81local void lm_init        OF((deflate_state *s));
82local void putShortMSB    OF((deflate_state *s, uInt b));
83local void flush_pending  OF((z_streamp strm));
84local int read_buf        OF((z_streamp strm, Bytef *buf, unsigned size));
85#ifdef ASMV
86      void match_init OF((void)); /* asm code initialization */
87      uInt longest_match  OF((deflate_state *s, IPos cur_match));
88#else
89local uInt longest_match  OF((deflate_state *s, IPos cur_match));
90#endif
91
92#ifdef DEBUG
93local  void check_match OF((deflate_state *s, IPos start, IPos match,
94                            int length));
95#endif
96
97/* ===========================================================================
98 * Local data
99 */
100
101#define NIL 0
102/* Tail of hash chains */
103
104#ifndef TOO_FAR
105#  define TOO_FAR 4096
106#endif
107/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
108
109#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
110/* Minimum amount of lookahead, except at the end of the input file.
111 * See deflate.c for comments about the MIN_MATCH+1.
112 */
113
114/* Values for max_lazy_match, good_match and max_chain_length, depending on
115 * the desired pack level (0..9). The values given below have been tuned to
116 * exclude worst case performance for pathological files. Better values may be
117 * found for specific files.
118 */
119typedef struct config_s {
120   ush good_length; /* reduce lazy search above this match length */
121   ush max_lazy;    /* do not perform lazy search above this match length */
122   ush nice_length; /* quit search above this match length */
123   ush max_chain;
124   compress_func func;
125} config;
126
127local const config configuration_table[10] = {
128/*      good lazy nice chain */
129/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
130/* 1 */ {4,    4,  8,    4, deflate_fast}, /* maximum speed, no lazy matches */
131/* 2 */ {4,    5, 16,    8, deflate_fast},
132/* 3 */ {4,    6, 32,   32, deflate_fast},
133
134/* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
135/* 5 */ {8,   16, 32,   32, deflate_slow},
136/* 6 */ {8,   16, 128, 128, deflate_slow},
137/* 7 */ {8,   32, 128, 256, deflate_slow},
138/* 8 */ {32, 128, 258, 1024, deflate_slow},
139/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* maximum compression */
140
141/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
142 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
143 * meaning.
144 */
145
146#define EQUAL 0
147/* result of memcmp for equal strings */
148
149/* PDFlib GmbH: conflicts with Visual Studio.NET
150struct static_tree_desc_s {int dummy;}; */ /* for buggy compilers */
151
152/* ===========================================================================
153 * Update a hash value with the given input byte
154 * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
155 *    input characters, so that a running hash key can be computed from the
156 *    previous key instead of complete recalculation each time.
157 */
158#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
159
160
161/* ===========================================================================
162 * Insert string str in the dictionary and set match_head to the previous head
163 * of the hash chain (the most recent string with same hash key). Return
164 * the previous length of the hash chain.
165 * If this file is compiled with -DFASTEST, the compression level is forced
166 * to 1, and no hash chains are maintained.
167 * IN  assertion: all calls to to INSERT_STRING are made with consecutive
168 *    input characters and the first MIN_MATCH bytes of str are valid
169 *    (except for the last MIN_MATCH-1 bytes of the input file).
170 */
171#ifdef FASTEST
172#define INSERT_STRING(s, str, match_head) \
173   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
174    match_head = s->head[s->ins_h], \
175    s->head[s->ins_h] = (Pos)(str))
176#else
177#define INSERT_STRING(s, str, match_head) \
178   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
179    s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \
180    s->head[s->ins_h] = (Pos)(str))
181#endif
182
183/* ===========================================================================
184 * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
185 * prev[] will be initialized on the fly.
186 */
187#define CLEAR_HASH(s) \
188    s->head[s->hash_size-1] = NIL; \
189    zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
190
191/* ========================================================================= */
192int ZEXPORT deflateInit_(
193    z_streamp strm,
194    int level,
195    const char *version,
196    int stream_size)
197{
198    return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
199			 Z_DEFAULT_STRATEGY, version, stream_size);
200    /* To do: ignore strm->next_in if we use it as window */
201}
202
203/* ========================================================================= */
204int ZEXPORT deflateInit2_(
205    z_streamp strm,
206    int  level,
207    int  method,
208    int  windowBits,
209    int  memLevel,
210    int  strategy,
211    const char *version,
212    int stream_size)
213{
214    deflate_state *s;
215    int noheader = 0;
216    static const char* my_version = ZLIB_VERSION;
217
218    ushf *overlay;
219    /* We overlay pending_buf and d_buf+l_buf. This works since the average
220     * output size for (length,distance) codes is <= 24 bits.
221     */
222
223    if (version == Z_NULL || version[0] != my_version[0] ||
224        stream_size != sizeof(z_stream)) {
225	return Z_VERSION_ERROR;
226    }
227    if (strm == Z_NULL) return Z_STREAM_ERROR;
228
229    strm->msg = Z_NULL;
230    if (strm->zalloc == Z_NULL) {
231	strm->zalloc = zcalloc;
232	strm->opaque = (voidpf)0;
233    }
234    if (strm->zfree == Z_NULL) strm->zfree = zcfree;
235
236    if (level == Z_DEFAULT_COMPRESSION) level = 6;
237#ifdef FASTEST
238    level = 1;
239#endif
240
241    if (windowBits < 0) { /* undocumented feature: suppress zlib header */
242        noheader = 1;
243        windowBits = -windowBits;
244    }
245    if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
246        windowBits < 9 || windowBits > 15 || level < 0 || level > 9 ||
247	strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
248        return Z_STREAM_ERROR;
249    }
250    s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
251    if (s == Z_NULL) return Z_MEM_ERROR;
252    strm->state = (struct internal_state FAR *)s;
253    s->data_type = Z_UNKNOWN;
254    s->strm = strm;
255
256    s->noheader = noheader;
257    s->w_bits = windowBits;
258    s->w_size = 1 << s->w_bits;
259    s->w_mask = s->w_size - 1;
260
261    s->hash_bits = memLevel + 7;
262    s->hash_size = 1 << s->hash_bits;
263    s->hash_mask = s->hash_size - 1;
264    s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
265
266    s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
267    /* we don't use calloc -> to satisfy purify
268     * at least here memset is needed */
269    memset((void *)s->window, 0, (size_t) s->w_size * 2*sizeof(Byte));
270
271    s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
272    s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
273
274    s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
275
276    overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
277    s->pending_buf = (uchf *) overlay;
278    s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
279
280    if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
281        s->pending_buf == Z_NULL) {
282        strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
283        deflateEnd (strm);
284        return Z_MEM_ERROR;
285    }
286    s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
287    s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
288
289    s->level = level;
290    s->strategy = strategy;
291    s->method = (Byte)method;
292
293    return deflateReset(strm);
294}
295
296/* ========================================================================= */
297int ZEXPORT deflateSetDictionary (
298    z_streamp strm,
299    const Bytef *dictionary,
300    uInt  dictLength)
301{
302    deflate_state *s;
303    uInt length = dictLength;
304    uInt n;
305    IPos hash_head = 0;
306
307    if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
308        strm->state->status != INIT_STATE) return Z_STREAM_ERROR;
309
310    s = strm->state;
311    strm->adler = adler32(strm->adler, dictionary, dictLength);
312
313    if (length < MIN_MATCH) return Z_OK;
314    if (length > MAX_DIST(s)) {
315	length = MAX_DIST(s);
316#ifndef USE_DICT_HEAD
317	dictionary += dictLength - length; /* use the tail of the dictionary */
318#endif
319    }
320    zmemcpy(s->window, dictionary, length);
321    s->strstart = length;
322    s->block_start = (long)length;
323
324    /* Insert all strings in the hash table (except for the last two bytes).
325     * s->lookahead stays null, so s->ins_h will be recomputed at the next
326     * call of fill_window.
327     */
328    s->ins_h = s->window[0];
329    UPDATE_HASH(s, s->ins_h, s->window[1]);
330    for (n = 0; n <= length - MIN_MATCH; n++) {
331	INSERT_STRING(s, n, hash_head);
332    }
333    if (hash_head) hash_head = 0;  /* to make compiler happy */
334    return Z_OK;
335}
336
337/* ========================================================================= */
338int ZEXPORT deflateReset (
339    z_streamp strm)
340{
341    deflate_state *s;
342
343    if (strm == Z_NULL || strm->state == Z_NULL ||
344        strm->zalloc == Z_NULL || strm->zfree == Z_NULL) return Z_STREAM_ERROR;
345
346    strm->total_in = strm->total_out = 0;
347    strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
348    strm->data_type = Z_UNKNOWN;
349
350    s = (deflate_state *)strm->state;
351    s->pending = 0;
352    s->pending_out = s->pending_buf;
353
354    if (s->noheader < 0) {
355        s->noheader = 0; /* was set to -1 by deflate(..., Z_FINISH); */
356    }
357    s->status = s->noheader ? BUSY_STATE : INIT_STATE;
358    strm->adler = 1;
359    s->last_flush = Z_NO_FLUSH;
360
361    _tr_init(s);
362    lm_init(s);
363
364    return Z_OK;
365}
366
367/* ========================================================================= */
368int ZEXPORT deflateParams(
369    z_streamp strm,
370    int level,
371    int strategy)
372{
373    deflate_state *s;
374    compress_func func;
375    int err = Z_OK;
376
377    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
378    s = strm->state;
379
380    if (level == Z_DEFAULT_COMPRESSION) {
381	level = 6;
382    }
383    if (level < 0 || level > 9 || strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
384	return Z_STREAM_ERROR;
385    }
386    func = configuration_table[s->level].func;
387
388    if (func != configuration_table[level].func && strm->total_in != 0) {
389	/* Flush the last buffer: */
390	err = deflate(strm, Z_PARTIAL_FLUSH);
391    }
392    if (s->level != level) {
393	s->level = level;
394	s->max_lazy_match   = configuration_table[level].max_lazy;
395	s->good_match       = configuration_table[level].good_length;
396	s->nice_match       = configuration_table[level].nice_length;
397	s->max_chain_length = configuration_table[level].max_chain;
398    }
399    s->strategy = strategy;
400    return err;
401}
402
403/* =========================================================================
404 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
405 * IN assertion: the stream state is correct and there is enough room in
406 * pending_buf.
407 */
408local void putShortMSB (
409    deflate_state *s,
410    uInt b)
411{
412    put_byte(s, (Byte)(b >> 8));
413    put_byte(s, (Byte)(b & 0xff));
414}
415
416/* =========================================================================
417 * Flush as much pending output as possible. All deflate() output goes
418 * through this function so some applications may wish to modify it
419 * to avoid allocating a large strm->next_out buffer and copying into it.
420 * (See also read_buf()).
421 */
422local void flush_pending(
423    z_streamp strm)
424{
425    unsigned len = strm->state->pending;
426
427    if (len > strm->avail_out) len = strm->avail_out;
428    if (len == 0) return;
429
430    zmemcpy(strm->next_out, strm->state->pending_out, len);
431    strm->next_out  += len;
432    strm->state->pending_out  += len;
433    strm->total_out += len;
434    strm->avail_out  -= len;
435    strm->state->pending -= len;
436    if (strm->state->pending == 0) {
437        strm->state->pending_out = strm->state->pending_buf;
438    }
439}
440
441/* ========================================================================= */
442int ZEXPORT deflate (
443    z_streamp strm,
444    int flush)
445{
446    int old_flush; /* value of flush param for previous deflate call */
447    deflate_state *s;
448
449    if (strm == Z_NULL || strm->state == Z_NULL ||
450	flush > Z_FINISH || flush < 0) {
451        return Z_STREAM_ERROR;
452    }
453    s = strm->state;
454
455    if (strm->next_out == Z_NULL ||
456        (strm->next_in == Z_NULL && strm->avail_in != 0) ||
457	(s->status == FINISH_STATE && flush != Z_FINISH)) {
458        ERR_RETURN(strm, Z_STREAM_ERROR);
459    }
460    if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
461
462    s->strm = strm; /* just in case */
463    old_flush = s->last_flush;
464    s->last_flush = flush;
465
466    /* Write the zlib header */
467    if (s->status == INIT_STATE) {
468
469        uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
470        uInt level_flags = (s->level-1) >> 1;
471
472        if (level_flags > 3) level_flags = 3;
473        header |= (level_flags << 6);
474	if (s->strstart != 0) header |= PRESET_DICT;
475        header += 31 - (header % 31);
476
477        s->status = BUSY_STATE;
478        putShortMSB(s, header);
479
480	/* Save the adler32 of the preset dictionary: */
481	if (s->strstart != 0) {
482	    putShortMSB(s, (uInt)(strm->adler >> 16));
483	    putShortMSB(s, (uInt)(strm->adler & 0xffff));
484	}
485	strm->adler = 1L;
486    }
487
488    /* Flush as much pending output as possible */
489    if (s->pending != 0) {
490        flush_pending(strm);
491        if (strm->avail_out == 0) {
492	    /* Since avail_out is 0, deflate will be called again with
493	     * more output space, but possibly with both pending and
494	     * avail_in equal to zero. There won't be anything to do,
495	     * but this is not an error situation so make sure we
496	     * return OK instead of BUF_ERROR at next call of deflate:
497             */
498	    s->last_flush = -1;
499	    return Z_OK;
500	}
501
502    /* Make sure there is something to do and avoid duplicate consecutive
503     * flushes. For repeated and useless calls with Z_FINISH, we keep
504     * returning Z_STREAM_END instead of Z_BUFF_ERROR.
505     */
506    } else if (strm->avail_in == 0 && flush <= old_flush &&
507	       flush != Z_FINISH) {
508        ERR_RETURN(strm, Z_BUF_ERROR);
509    }
510
511    /* User must not provide more input after the first FINISH: */
512    if (s->status == FINISH_STATE && strm->avail_in != 0) {
513        ERR_RETURN(strm, Z_BUF_ERROR);
514    }
515
516    /* Start a new block or continue the current one.
517     */
518    if (strm->avail_in != 0 || s->lookahead != 0 ||
519        (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
520        block_state bstate;
521
522	bstate = (*(configuration_table[s->level].func))(s, flush);
523
524        if (bstate == finish_started || bstate == finish_done) {
525            s->status = FINISH_STATE;
526        }
527        if (bstate == need_more || bstate == finish_started) {
528	    if (strm->avail_out == 0) {
529	        s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
530	    }
531	    return Z_OK;
532	    /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
533	     * of deflate should use the same flush parameter to make sure
534	     * that the flush is complete. So we don't have to output an
535	     * empty block here, this will be done at next call. This also
536	     * ensures that for a very small output buffer, we emit at most
537	     * one empty block.
538	     */
539	}
540        if (bstate == block_done) {
541            if (flush == Z_PARTIAL_FLUSH) {
542                _tr_align(s);
543            } else { /* FULL_FLUSH or SYNC_FLUSH */
544                _tr_stored_block(s, (char*)0, 0L, 0);
545                /* For a full flush, this empty block will be recognized
546                 * as a special marker by inflate_sync().
547                 */
548                if (flush == Z_FULL_FLUSH) {
549                    CLEAR_HASH(s);             /* forget history */
550                }
551            }
552            flush_pending(strm);
553	    if (strm->avail_out == 0) {
554	      s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
555	      return Z_OK;
556	    }
557        }
558    }
559    Assert(strm->avail_out > 0, "bug2");
560
561    if (flush != Z_FINISH) return Z_OK;
562    if (s->noheader) return Z_STREAM_END;
563
564    /* Write the zlib trailer (adler32) */
565    putShortMSB(s, (uInt)(strm->adler >> 16));
566    putShortMSB(s, (uInt)(strm->adler & 0xffff));
567    flush_pending(strm);
568    /* If avail_out is zero, the application will call deflate again
569     * to flush the rest.
570     */
571    s->noheader = -1; /* write the trailer only once! */
572    return s->pending != 0 ? Z_OK : Z_STREAM_END;
573}
574
575/* ========================================================================= */
576int ZEXPORT deflateEnd (
577    z_streamp strm)
578{
579    int status;
580
581    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
582
583    status = strm->state->status;
584    if (status != INIT_STATE && status != BUSY_STATE &&
585	status != FINISH_STATE) {
586      return Z_STREAM_ERROR;
587    }
588
589    /* Deallocate in reverse order of allocations: */
590    TRY_FREE(strm, strm->state->pending_buf);
591    TRY_FREE(strm, strm->state->head);
592    TRY_FREE(strm, strm->state->prev);
593    TRY_FREE(strm, strm->state->window);
594
595    ZFREE(strm, strm->state);
596    strm->state = Z_NULL;
597
598    return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
599}
600
601/* =========================================================================
602 * Copy the source state to the destination state.
603 * To simplify the source, this is not supported for 16-bit MSDOS (which
604 * doesn't have enough memory anyway to duplicate compression states).
605 */
606int ZEXPORT deflateCopy (
607    z_streamp dest,
608    z_streamp source)
609{
610#ifdef MAXSEG_64K
611    return Z_STREAM_ERROR;
612#else
613    deflate_state *ds;
614    deflate_state *ss;
615    ushf *overlay;
616
617
618    if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
619        return Z_STREAM_ERROR;
620    }
621
622    ss = source->state;
623
624    *dest = *source;
625
626    ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
627    if (ds == Z_NULL) return Z_MEM_ERROR;
628    dest->state = (struct internal_state FAR *) ds;
629    *ds = *ss;
630    ds->strm = dest;
631
632    ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
633    ds->prev   = (Posf *)  ZALLOC(dest, ds->w_size, sizeof(Pos));
634    ds->head   = (Posf *)  ZALLOC(dest, ds->hash_size, sizeof(Pos));
635    overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
636    ds->pending_buf = (uchf *) overlay;
637
638    if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
639        ds->pending_buf == Z_NULL) {
640        deflateEnd (dest);
641        return Z_MEM_ERROR;
642    }
643    /* following zmemcpy do not work for 16-bit MSDOS */
644    zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
645    zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
646    zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
647    zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
648
649    ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
650    ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
651    ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
652
653    ds->l_desc.dyn_tree = ds->dyn_ltree;
654    ds->d_desc.dyn_tree = ds->dyn_dtree;
655    ds->bl_desc.dyn_tree = ds->bl_tree;
656
657    return Z_OK;
658#endif
659}
660
661/* ===========================================================================
662 * Read a new buffer from the current input stream, update the adler32
663 * and total number of bytes read.  All deflate() input goes through
664 * this function so some applications may wish to modify it to avoid
665 * allocating a large strm->next_in buffer and copying from it.
666 * (See also flush_pending()).
667 */
668local int read_buf(
669    z_streamp strm,
670    Bytef *buf,
671    unsigned size)
672{
673    unsigned len = strm->avail_in;
674
675    if (len > size) len = size;
676    if (len == 0) return 0;
677
678    strm->avail_in  -= len;
679
680    if (!strm->state->noheader) {
681        strm->adler = adler32(strm->adler, strm->next_in, len);
682    }
683    zmemcpy(buf, strm->next_in, len);
684    strm->next_in  += len;
685    strm->total_in += len;
686
687    return (int)len;
688}
689
690/* ===========================================================================
691 * Initialize the "longest match" routines for a new zlib stream
692 */
693local void lm_init (
694    deflate_state *s)
695{
696    s->window_size = (ulg)2L*s->w_size;
697
698    CLEAR_HASH(s);
699
700    /* Set the default configuration parameters:
701     */
702    s->max_lazy_match   = configuration_table[s->level].max_lazy;
703    s->good_match       = configuration_table[s->level].good_length;
704    s->nice_match       = configuration_table[s->level].nice_length;
705    s->max_chain_length = configuration_table[s->level].max_chain;
706
707    s->strstart = 0;
708    s->block_start = 0L;
709    s->lookahead = 0;
710    s->match_length = s->prev_length = MIN_MATCH-1;
711    s->match_available = 0;
712    s->ins_h = 0;
713#ifdef ASMV
714    match_init(); /* initialize the asm code */
715#endif
716}
717
718/* ===========================================================================
719 * Set match_start to the longest match starting at the given string and
720 * return its length. Matches shorter or equal to prev_length are discarded,
721 * in which case the result is equal to prev_length and match_start is
722 * garbage.
723 * IN assertions: cur_match is the head of the hash chain for the current
724 *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
725 * OUT assertion: the match length is not greater than s->lookahead.
726 */
727#ifndef ASMV
728/* For 80x86 and 680x0, an optimized version will be provided in match.asm or
729 * match.S. The code will be functionally equivalent.
730 */
731#ifndef FASTEST
732local uInt longest_match(
733    deflate_state *s,
734    IPos cur_match)                             /* current match */
735{
736    unsigned chain_length = s->max_chain_length;/* max hash chain length */
737    register Bytef *scan = s->window + s->strstart; /* current string */
738    register Bytef *match;                       /* matched string */
739    register int len;                           /* length of current match */
740    int best_len = s->prev_length;              /* best match length so far */
741    int nice_match = s->nice_match;             /* stop if match long enough */
742    IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
743        s->strstart - (IPos)MAX_DIST(s) : NIL;
744    /* Stop when cur_match becomes <= limit. To simplify the code,
745     * we prevent matches with the string of window index 0.
746     */
747    Posf *prev = s->prev;
748    uInt wmask = s->w_mask;
749
750#ifdef UNALIGNED_OK
751    /* Compare two bytes at a time. Note: this is not always beneficial.
752     * Try with and without -DUNALIGNED_OK to check.
753     */
754    register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
755    register ush scan_start = *(ushf*)scan;
756    register ush scan_end   = *(ushf*)(scan+best_len-1);
757#else
758    register Bytef *strend = s->window + s->strstart + MAX_MATCH;
759    register Byte scan_end1  = scan[best_len-1];
760    register Byte scan_end   = scan[best_len];
761#endif
762
763    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
764     * It is easy to get rid of this optimization if necessary.
765     */
766    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
767
768    /* Do not waste too much time if we already have a good match: */
769    if (s->prev_length >= s->good_match) {
770        chain_length >>= 2;
771    }
772    /* Do not look for matches beyond the end of the input. This is necessary
773     * to make deflate deterministic.
774     */
775    if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
776
777    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
778
779    do {
780        Assert(cur_match < s->strstart, "no future");
781        match = s->window + cur_match;
782
783        /* Skip to next match if the match length cannot increase
784         * or if the match length is less than 2:
785         */
786#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
787        /* This code assumes sizeof(unsigned short) == 2. Do not use
788         * UNALIGNED_OK if your compiler uses a different size.
789         */
790        if (*(ushf*)(match+best_len-1) != scan_end ||
791            *(ushf*)match != scan_start) continue;
792
793        /* It is not necessary to compare scan[2] and match[2] since they are
794         * always equal when the other bytes match, given that the hash keys
795         * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
796         * strstart+3, +5, ... up to strstart+257. We check for insufficient
797         * lookahead only every 4th comparison; the 128th check will be made
798         * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
799         * necessary to put more guard bytes at the end of the window, or
800         * to check more often for insufficient lookahead.
801         */
802        Assert(scan[2] == match[2], "scan[2]?");
803        scan++, match++;
804        do {
805        } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
806                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
807                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
808                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
809                 scan < strend);
810        /* The funny "do {}" generates better code on most compilers */
811
812        /* Here, scan <= window+strstart+257 */
813        Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
814        if (*scan == *match) scan++;
815
816        len = (MAX_MATCH - 1) - (int)(strend-scan);
817        scan = strend - (MAX_MATCH-1);
818
819#else /* UNALIGNED_OK */
820
821        if (match[best_len]   != scan_end  ||
822            match[best_len-1] != scan_end1 ||
823            *match            != *scan     ||
824            *++match          != scan[1])      continue;
825
826        /* The check at best_len-1 can be removed because it will be made
827         * again later. (This heuristic is not always a win.)
828         * It is not necessary to compare scan[2] and match[2] since they
829         * are always equal when the other bytes match, given that
830         * the hash keys are equal and that HASH_BITS >= 8.
831         */
832        scan += 2, match++;
833        Assert(*scan == *match, "match[2]?");
834
835        /* We check for insufficient lookahead only every 8th comparison;
836         * the 256th check will be made at strstart+258.
837         */
838        do {
839        } while (*++scan == *++match && *++scan == *++match &&
840                 *++scan == *++match && *++scan == *++match &&
841                 *++scan == *++match && *++scan == *++match &&
842                 *++scan == *++match && *++scan == *++match &&
843                 scan < strend);
844
845        Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
846
847        len = MAX_MATCH - (int)(strend - scan);
848        scan = strend - MAX_MATCH;
849
850#endif /* UNALIGNED_OK */
851
852        if (len > best_len) {
853            s->match_start = cur_match;
854            best_len = len;
855            if (len >= nice_match) break;
856#ifdef UNALIGNED_OK
857            scan_end = *(ushf*)(scan+best_len-1);
858#else
859            scan_end1  = scan[best_len-1];
860            scan_end   = scan[best_len];
861#endif
862        }
863    } while ((cur_match = prev[cur_match & wmask]) > limit
864             && --chain_length != 0);
865
866    if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
867    return s->lookahead;
868}
869
870#else /* FASTEST */
871/* ---------------------------------------------------------------------------
872 * Optimized version for level == 1 only
873 */
874local uInt longest_match(
875    deflate_state *s,
876    IPos cur_match)                             /* current match */
877{
878    register Bytef *scan = s->window + s->strstart; /* current string */
879    register Bytef *match;                       /* matched string */
880    register int len;                           /* length of current match */
881    register Bytef *strend = s->window + s->strstart + MAX_MATCH;
882
883    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
884     * It is easy to get rid of this optimization if necessary.
885     */
886    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
887
888    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
889
890    Assert(cur_match < s->strstart, "no future");
891
892    match = s->window + cur_match;
893
894    /* Return failure if the match length is less than 2:
895     */
896    if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
897
898    /* The check at best_len-1 can be removed because it will be made
899     * again later. (This heuristic is not always a win.)
900     * It is not necessary to compare scan[2] and match[2] since they
901     * are always equal when the other bytes match, given that
902     * the hash keys are equal and that HASH_BITS >= 8.
903     */
904    scan += 2, match += 2;
905    Assert(*scan == *match, "match[2]?");
906
907    /* We check for insufficient lookahead only every 8th comparison;
908     * the 256th check will be made at strstart+258.
909     */
910    do {
911    } while (*++scan == *++match && *++scan == *++match &&
912	     *++scan == *++match && *++scan == *++match &&
913	     *++scan == *++match && *++scan == *++match &&
914	     *++scan == *++match && *++scan == *++match &&
915	     scan < strend);
916
917    Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
918
919    len = MAX_MATCH - (int)(strend - scan);
920
921    if (len < MIN_MATCH) return MIN_MATCH - 1;
922
923    s->match_start = cur_match;
924    return len <= s->lookahead ? len : s->lookahead;
925}
926#endif /* FASTEST */
927#endif /* ASMV */
928
929#ifdef DEBUG
930/* ===========================================================================
931 * Check that the match at match_start is indeed a match.
932 */
933local void check_match(
934    deflate_state *s,
935    IPos start, IPos match,
936    int length)
937{
938    /* check that the match is indeed a match */
939    if (zmemcmp(s->window + match,
940                s->window + start, length) != EQUAL) {
941        fprintf(stderr, " start %u, match %u, length %d\n",
942		start, match, length);
943        do {
944	    fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
945	} while (--length != 0);
946        z_error("invalid match");
947    }
948    if (z_verbose > 1) {
949        fprintf(stderr,"\\[%d,%d]", start-match, length);
950        do { putc(s->window[start++], stderr); } while (--length != 0);
951    }
952}
953#else
954#  define check_match(s, start, match, length)
955#endif
956
957/* ===========================================================================
958 * Fill the window when the lookahead becomes insufficient.
959 * Updates strstart and lookahead.
960 *
961 * IN assertion: lookahead < MIN_LOOKAHEAD
962 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
963 *    At least one byte has been read, or avail_in == 0; reads are
964 *    performed for at least two bytes (required for the zip translate_eol
965 *    option -- not supported here).
966 */
967local void fill_window(
968    deflate_state *s)
969{
970    register unsigned n, m;
971    register Posf *p;
972    unsigned more;    /* Amount of free space at the end of the window. */
973    uInt wsize = s->w_size;
974
975    do {
976        more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
977
978        /* Deal with !@#$% 64K limit: */
979        if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
980            more = wsize;
981
982        } else if (more == (unsigned)(-1)) {
983            /* Very unlikely, but possible on 16 bit machine if strstart == 0
984             * and lookahead == 1 (input done one byte at time)
985             */
986            more--;
987
988        /* If the window is almost full and there is insufficient lookahead,
989         * move the upper half to the lower one to make room in the upper half.
990         */
991        } else if (s->strstart >= wsize+MAX_DIST(s)) {
992
993            zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
994            s->match_start -= wsize;
995            s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
996            s->block_start -= (long) wsize;
997
998            /* Slide the hash table (could be avoided with 32 bit values
999               at the expense of memory usage). We slide even when level == 0
1000               to keep the hash table consistent if we switch back to level > 0
1001               later. (Using level 0 permanently is not an optimal usage of
1002               zlib, so we don't care about this pathological case.)
1003             */
1004	    n = s->hash_size;
1005	    p = &s->head[n];
1006	    do {
1007		m = *--p;
1008		*p = (Pos)(m >= wsize ? m-wsize : NIL);
1009	    } while (--n);
1010
1011	    n = wsize;
1012#ifndef FASTEST
1013	    p = &s->prev[n];
1014	    do {
1015		m = *--p;
1016		*p = (Pos)(m >= wsize ? m-wsize : NIL);
1017		/* If n is not on any hash chain, prev[n] is garbage but
1018		 * its value will never be used.
1019		 */
1020	    } while (--n);
1021#endif
1022            more += wsize;
1023        }
1024        if (s->strm->avail_in == 0) return;
1025
1026        /* If there was no sliding:
1027         *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1028         *    more == window_size - lookahead - strstart
1029         * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1030         * => more >= window_size - 2*WSIZE + 2
1031         * In the BIG_MEM or MMAP case (not yet supported),
1032         *   window_size == input_size + MIN_LOOKAHEAD  &&
1033         *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1034         * Otherwise, window_size == 2*WSIZE so more >= 2.
1035         * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1036         */
1037        Assert(more >= 2, "more < 2");
1038
1039        n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1040        s->lookahead += n;
1041
1042        /* Initialize the hash value now that we have some input: */
1043        if (s->lookahead >= MIN_MATCH) {
1044            s->ins_h = s->window[s->strstart];
1045            UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1046#if MIN_MATCH != 3
1047            Call UPDATE_HASH() MIN_MATCH-3 more times
1048#endif
1049        }
1050        /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1051         * but this is not important since only literal bytes will be emitted.
1052         */
1053
1054    } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1055}
1056
1057/* ===========================================================================
1058 * Flush the current block, with given end-of-file flag.
1059 * IN assertion: strstart is set to the end of the current match.
1060 */
1061#define FLUSH_BLOCK_ONLY(s, eof) { \
1062   _tr_flush_block(s, (s->block_start >= 0L ? \
1063                   (charf *)&s->window[(unsigned)s->block_start] : \
1064                   (charf *)Z_NULL), \
1065		(ulg)((long)s->strstart - s->block_start), \
1066		(eof)); \
1067   s->block_start = s->strstart; \
1068   flush_pending(s->strm); \
1069   Tracev((stderr,"[FLUSH]")); \
1070}
1071
1072/* Same but force premature exit if necessary. */
1073#define FLUSH_BLOCK(s, eof) { \
1074   FLUSH_BLOCK_ONLY(s, eof); \
1075   if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
1076}
1077
1078/* ===========================================================================
1079 * Copy without compression as much as possible from the input stream, return
1080 * the current block state.
1081 * This function does not insert new strings in the dictionary since
1082 * uncompressible data is probably not useful. This function is used
1083 * only for the level=0 compression option.
1084 * NOTE: this function should be optimized to avoid extra copying from
1085 * window to pending_buf.
1086 */
1087local block_state deflate_stored(
1088    deflate_state *s,
1089    int flush)
1090{
1091    /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
1092     * to pending_buf_size, and each stored block has a 5 byte header:
1093     */
1094    ulg max_block_size = 0xffff;
1095    ulg max_start;
1096
1097    if (max_block_size > s->pending_buf_size - 5) {
1098        max_block_size = s->pending_buf_size - 5;
1099    }
1100
1101    /* Copy as much as possible from input to output: */
1102    for (;;) {
1103        /* Fill the window as much as possible: */
1104        if (s->lookahead <= 1) {
1105
1106            Assert(s->strstart < s->w_size+MAX_DIST(s) ||
1107		   s->block_start >= (long)s->w_size, "slide too late");
1108
1109            fill_window(s);
1110            if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
1111
1112            if (s->lookahead == 0) break; /* flush the current block */
1113        }
1114	Assert(s->block_start >= 0L, "block gone");
1115
1116	s->strstart += s->lookahead;
1117	s->lookahead = 0;
1118
1119	/* Emit a stored block if pending_buf will be full: */
1120 	max_start = s->block_start + max_block_size;
1121        if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
1122	    /* strstart == 0 is possible when wraparound on 16-bit machine */
1123	    s->lookahead = (uInt)(s->strstart - max_start);
1124	    s->strstart = (uInt)max_start;
1125            FLUSH_BLOCK(s, 0);
1126	}
1127	/* Flush if we may have to slide, otherwise block_start may become
1128         * negative and the data will be gone:
1129         */
1130        if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
1131            FLUSH_BLOCK(s, 0);
1132	}
1133    }
1134    FLUSH_BLOCK(s, flush == Z_FINISH);
1135    return flush == Z_FINISH ? finish_done : block_done;
1136}
1137
1138/* ===========================================================================
1139 * Compress as much as possible from the input stream, return the current
1140 * block state.
1141 * This function does not perform lazy evaluation of matches and inserts
1142 * new strings in the dictionary only for unmatched strings or for short
1143 * matches. It is used only for the fast compression options.
1144 */
1145local block_state deflate_fast(
1146    deflate_state *s,
1147    int flush)
1148{
1149    IPos hash_head = NIL; /* head of the hash chain */
1150    int bflush;           /* set if current block must be flushed */
1151
1152    for (;;) {
1153        /* Make sure that we always have enough lookahead, except
1154         * at the end of the input file. We need MAX_MATCH bytes
1155         * for the next match, plus MIN_MATCH bytes to insert the
1156         * string following the next match.
1157         */
1158        if (s->lookahead < MIN_LOOKAHEAD) {
1159            fill_window(s);
1160            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1161	        return need_more;
1162	    }
1163            if (s->lookahead == 0) break; /* flush the current block */
1164        }
1165
1166        /* Insert the string window[strstart .. strstart+2] in the
1167         * dictionary, and set hash_head to the head of the hash chain:
1168         */
1169        if (s->lookahead >= MIN_MATCH) {
1170            INSERT_STRING(s, s->strstart, hash_head);
1171        }
1172
1173        /* Find the longest match, discarding those <= prev_length.
1174         * At this point we have always match_length < MIN_MATCH
1175         */
1176        if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1177            /* To simplify the code, we prevent matches with the string
1178             * of window index 0 (in particular we have to avoid a match
1179             * of the string with itself at the start of the input file).
1180             */
1181            if (s->strategy != Z_HUFFMAN_ONLY) {
1182                s->match_length = longest_match (s, hash_head);
1183            }
1184            /* longest_match() sets match_start */
1185        }
1186        if (s->match_length >= MIN_MATCH) {
1187            check_match(s, s->strstart, s->match_start, s->match_length);
1188
1189            _tr_tally_dist(s, s->strstart - s->match_start,
1190                           s->match_length - MIN_MATCH, bflush);
1191
1192            s->lookahead -= s->match_length;
1193
1194            /* Insert new strings in the hash table only if the match length
1195             * is not too large. This saves time but degrades compression.
1196             */
1197#ifndef FASTEST
1198            if (s->match_length <= s->max_insert_length &&
1199                s->lookahead >= MIN_MATCH) {
1200                s->match_length--;/* string at strstart already in hash table */
1201                do {
1202                    s->strstart++;
1203                    INSERT_STRING(s, s->strstart, hash_head);
1204                    /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1205                     * always MIN_MATCH bytes ahead.
1206                     */
1207                } while (--s->match_length != 0);
1208                s->strstart++;
1209            } else
1210#endif
1211	    {
1212                s->strstart += s->match_length;
1213                s->match_length = 0;
1214                s->ins_h = s->window[s->strstart];
1215                UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1216#if MIN_MATCH != 3
1217                Call UPDATE_HASH() MIN_MATCH-3 more times
1218#endif
1219                /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1220                 * matter since it will be recomputed at next deflate call.
1221                 */
1222            }
1223        } else {
1224            /* No match, output a literal byte */
1225            Tracevv((stderr,"%c", s->window[s->strstart]));
1226            _tr_tally_lit (s, s->window[s->strstart], bflush);
1227            s->lookahead--;
1228            s->strstart++;
1229        }
1230        if (bflush) FLUSH_BLOCK(s, 0);
1231    }
1232    FLUSH_BLOCK(s, flush == Z_FINISH);
1233    return flush == Z_FINISH ? finish_done : block_done;
1234}
1235
1236/* ===========================================================================
1237 * Same as above, but achieves better compression. We use a lazy
1238 * evaluation for matches: a match is finally adopted only if there is
1239 * no better match at the next window position.
1240 */
1241local block_state deflate_slow(
1242    deflate_state *s,
1243    int flush)
1244{
1245    IPos hash_head = NIL;    /* head of hash chain */
1246    int bflush;              /* set if current block must be flushed */
1247
1248    /* Process the input block. */
1249    for (;;) {
1250        /* Make sure that we always have enough lookahead, except
1251         * at the end of the input file. We need MAX_MATCH bytes
1252         * for the next match, plus MIN_MATCH bytes to insert the
1253         * string following the next match.
1254         */
1255        if (s->lookahead < MIN_LOOKAHEAD) {
1256            fill_window(s);
1257            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1258	        return need_more;
1259	    }
1260            if (s->lookahead == 0) break; /* flush the current block */
1261        }
1262
1263        /* Insert the string window[strstart .. strstart+2] in the
1264         * dictionary, and set hash_head to the head of the hash chain:
1265         */
1266        if (s->lookahead >= MIN_MATCH) {
1267            INSERT_STRING(s, s->strstart, hash_head);
1268        }
1269
1270        /* Find the longest match, discarding those <= prev_length.
1271         */
1272        s->prev_length = s->match_length, s->prev_match = s->match_start;
1273        s->match_length = MIN_MATCH-1;
1274
1275        if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
1276            s->strstart - hash_head <= MAX_DIST(s)) {
1277            /* To simplify the code, we prevent matches with the string
1278             * of window index 0 (in particular we have to avoid a match
1279             * of the string with itself at the start of the input file).
1280             */
1281            if (s->strategy != Z_HUFFMAN_ONLY) {
1282                s->match_length = longest_match (s, hash_head);
1283            }
1284            /* longest_match() sets match_start */
1285
1286            if (s->match_length <= 5 && (s->strategy == Z_FILTERED ||
1287                 (s->match_length == MIN_MATCH &&
1288                  s->strstart - s->match_start > TOO_FAR))) {
1289
1290                /* If prev_match is also MIN_MATCH, match_start is garbage
1291                 * but we will ignore the current match anyway.
1292                 */
1293                s->match_length = MIN_MATCH-1;
1294            }
1295        }
1296        /* If there was a match at the previous step and the current
1297         * match is not better, output the previous match:
1298         */
1299        if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
1300            uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
1301            /* Do not insert strings in hash table beyond this. */
1302
1303            check_match(s, s->strstart-1, s->prev_match, s->prev_length);
1304
1305            _tr_tally_dist(s, s->strstart -1 - s->prev_match,
1306			   s->prev_length - MIN_MATCH, bflush);
1307
1308            /* Insert in hash table all strings up to the end of the match.
1309             * strstart-1 and strstart are already inserted. If there is not
1310             * enough lookahead, the last two strings are not inserted in
1311             * the hash table.
1312             */
1313            s->lookahead -= s->prev_length-1;
1314            s->prev_length -= 2;
1315            do {
1316                if (++s->strstart <= max_insert) {
1317                    INSERT_STRING(s, s->strstart, hash_head);
1318                }
1319            } while (--s->prev_length != 0);
1320            s->match_available = 0;
1321            s->match_length = MIN_MATCH-1;
1322            s->strstart++;
1323
1324            if (bflush) FLUSH_BLOCK(s, 0);
1325
1326        } else if (s->match_available) {
1327            /* If there was no match at the previous position, output a
1328             * single literal. If there was a match but the current match
1329             * is longer, truncate the previous match to a single literal.
1330             */
1331            Tracevv((stderr,"%c", s->window[s->strstart-1]));
1332	    _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1333	    if (bflush) {
1334                FLUSH_BLOCK_ONLY(s, 0);
1335            }
1336            s->strstart++;
1337            s->lookahead--;
1338            if (s->strm->avail_out == 0) return need_more;
1339        } else {
1340            /* There is no previous match to compare with, wait for
1341             * the next step to decide.
1342             */
1343            s->match_available = 1;
1344            s->strstart++;
1345            s->lookahead--;
1346        }
1347    }
1348    Assert (flush != Z_NO_FLUSH, "no flush?");
1349    if (s->match_available) {
1350        Tracevv((stderr,"%c", s->window[s->strstart-1]));
1351        _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1352        s->match_available = 0;
1353    }
1354    FLUSH_BLOCK(s, flush == Z_FINISH);
1355    return flush == Z_FINISH ? finish_done : block_done;
1356}
1357