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