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