ยปCore Development>Code coverage>Modules/zlib/deflate.c

Python code coverage for Modules/zlib/deflate.c

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