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