blob: 7585bd0650cb8d44ec402542c6f0b45df179aa44 [file] [log] [blame]
initial.commit3d533e02008-07-27 00:38:33 +00001/* deflate.c -- compress data using the deflation algorithm
mark13dc2462017-02-14 22:15:29 -08002 * Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler
initial.commit3d533e02008-07-27 00:38:33 +00003 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5
6/*
7 * ALGORITHM
8 *
9 * The "deflation" process depends on being able to identify portions
10 * of the input text which are identical to earlier input (within a
11 * sliding window trailing behind the input currently being processed).
12 *
13 * The most straightforward technique turns out to be the fastest for
14 * most input files: try all possible matches and select the longest.
15 * The key feature of this algorithm is that insertions into the string
16 * dictionary are very simple and thus fast, and deletions are avoided
17 * completely. Insertions are performed at each input character, whereas
18 * string matches are performed only when the previous match ends. So it
19 * is preferable to spend more time in matches to allow very fast string
20 * insertions and avoid deletions. The matching algorithm for small
21 * strings is inspired from that of Rabin & Karp. A brute force approach
22 * is used to find longer strings when a small match has been found.
23 * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
24 * (by Leonid Broukhis).
25 * A previous version of this file used a more sophisticated algorithm
26 * (by Fiala and Greene) which is guaranteed to run in linear amortized
27 * time, but has a larger average cost, uses more memory and is patented.
28 * However the F&G algorithm may be faster for some highly redundant
29 * files if the parameter max_chain_length (described below) is too large.
30 *
31 * ACKNOWLEDGEMENTS
32 *
33 * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
34 * I found it in 'freeze' written by Leonid Broukhis.
35 * Thanks to many people for bug reports and testing.
36 *
37 * REFERENCES
38 *
39 * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
jiadong.zhu6c142162016-06-22 21:22:18 -070040 * Available in http://tools.ietf.org/html/rfc1951
initial.commit3d533e02008-07-27 00:38:33 +000041 *
42 * A description of the Rabin and Karp algorithm is given in the book
43 * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
44 *
45 * Fiala,E.R., and Greene,D.H.
46 * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
47 *
48 */
49
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +000050/* @(#) $Id$ */
robert.bradford10dd6862014-11-05 06:59:34 -080051#include <assert.h>
initial.commit3d533e02008-07-27 00:38:33 +000052#include "deflate.h"
robert.bradford10dd6862014-11-05 06:59:34 -080053#include "x86.h"
Adenilson Cavalcanti21cc38f2018-08-15 01:06:05 +000054
Adenilson Cavalcantid6d19612018-08-07 16:08:59 +000055#if (defined(__ARM_NEON__) || defined(__ARM_NEON))
56#include "contrib/optimizations/slide_hash_neon.h"
57#endif
Adenilson Cavalcanti21cc38f2018-08-15 01:06:05 +000058/* We need crypto extension crc32 to implement optimized hash in
59 * insert_string.
60 */
61#if defined(CRC32_ARMV8_CRC32)
62#include "arm_features.h"
63#include "crc32_simd.h"
64#endif
initial.commit3d533e02008-07-27 00:38:33 +000065
66const char deflate_copyright[] =
mark13dc2462017-02-14 22:15:29 -080067 " deflate 1.2.11 Copyright 1995-2017 Jean-loup Gailly and Mark Adler ";
initial.commit3d533e02008-07-27 00:38:33 +000068/*
69 If you use the zlib library in a product, an acknowledgment is welcome
70 in the documentation of your product. If for some reason you cannot
71 include such an acknowledgment, I would appreciate that you keep this
72 copyright string in the executable of your product.
73 */
74
75/* ===========================================================================
76 * Function prototypes.
77 */
78typedef enum {
79 need_more, /* block not completed, need more input or more output */
80 block_done, /* block flush performed */
81 finish_started, /* finish started, need only more output at next deflate */
82 finish_done /* finish done, accept no more input or output */
83} block_state;
84
davidben709ed022017-02-02 13:58:58 -080085typedef block_state (*compress_func) OF((deflate_state *s, int flush));
initial.commit3d533e02008-07-27 00:38:33 +000086/* Compression function. Returns the block state after the call. */
87
mark13dc2462017-02-14 22:15:29 -080088local int deflateStateCheck OF((z_streamp strm));
89local void slide_hash OF((deflate_state *s));
initial.commit3d533e02008-07-27 00:38:33 +000090local void fill_window OF((deflate_state *s));
davidben709ed022017-02-02 13:58:58 -080091local block_state deflate_stored OF((deflate_state *s, int flush));
92local block_state deflate_fast OF((deflate_state *s, int flush));
initial.commit3d533e02008-07-27 00:38:33 +000093#ifndef FASTEST
davidben709ed022017-02-02 13:58:58 -080094local block_state deflate_slow OF((deflate_state *s, int flush));
initial.commit3d533e02008-07-27 00:38:33 +000095#endif
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +000096local block_state deflate_rle OF((deflate_state *s, int flush));
97local block_state deflate_huff OF((deflate_state *s, int flush));
initial.commit3d533e02008-07-27 00:38:33 +000098local void lm_init OF((deflate_state *s));
99local void putShortMSB OF((deflate_state *s, uInt b));
100local void flush_pending OF((z_streamp strm));
Daniel Bratell2eb38892018-01-11 01:01:17 +0000101unsigned ZLIB_INTERNAL deflate_read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
initial.commit3d533e02008-07-27 00:38:33 +0000102#ifdef ASMV
mark13dc2462017-02-14 22:15:29 -0800103# pragma message("Assembler code may have bugs -- use at your own risk")
initial.commit3d533e02008-07-27 00:38:33 +0000104 void match_init OF((void)); /* asm code initialization */
davidben709ed022017-02-02 13:58:58 -0800105 uInt longest_match OF((deflate_state *s, IPos cur_match));
initial.commit3d533e02008-07-27 00:38:33 +0000106#else
davidben709ed022017-02-02 13:58:58 -0800107local uInt longest_match OF((deflate_state *s, IPos cur_match));
initial.commit3d533e02008-07-27 00:38:33 +0000108#endif
initial.commit3d533e02008-07-27 00:38:33 +0000109
mark13dc2462017-02-14 22:15:29 -0800110#ifdef ZLIB_DEBUG
initial.commit3d533e02008-07-27 00:38:33 +0000111local void check_match OF((deflate_state *s, IPos start, IPos match,
112 int length));
113#endif
114
robert.bradford10dd6862014-11-05 06:59:34 -0800115/* From crc32.c */
116extern void ZLIB_INTERNAL crc_reset(deflate_state *const s);
117extern void ZLIB_INTERNAL crc_finalize(deflate_state *const s);
118extern void ZLIB_INTERNAL copy_with_crc(z_streamp strm, Bytef *dst, long size);
119
120#ifdef _MSC_VER
121#define INLINE __inline
122#else
123#define INLINE inline
124#endif
125
126/* Inline optimisation */
127local INLINE Pos insert_string_sse(deflate_state *const s, const Pos str);
128
initial.commit3d533e02008-07-27 00:38:33 +0000129/* ===========================================================================
130 * Local data
131 */
132
133#define NIL 0
134/* Tail of hash chains */
135
136#ifndef TOO_FAR
137# define TOO_FAR 4096
138#endif
139/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
140
initial.commit3d533e02008-07-27 00:38:33 +0000141/* Values for max_lazy_match, good_match and max_chain_length, depending on
142 * the desired pack level (0..9). The values given below have been tuned to
143 * exclude worst case performance for pathological files. Better values may be
144 * found for specific files.
145 */
146typedef struct config_s {
147 ush good_length; /* reduce lazy search above this match length */
148 ush max_lazy; /* do not perform lazy search above this match length */
149 ush nice_length; /* quit search above this match length */
150 ush max_chain;
151 compress_func func;
152} config;
153
154#ifdef FASTEST
155local const config configuration_table[2] = {
156/* good lazy nice chain */
157/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
158/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
159#else
160local const config configuration_table[10] = {
161/* good lazy nice chain */
162/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
163/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
164/* 2 */ {4, 5, 16, 8, deflate_fast},
165/* 3 */ {4, 6, 32, 32, deflate_fast},
166
167/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
168/* 5 */ {8, 16, 32, 32, deflate_slow},
169/* 6 */ {8, 16, 128, 128, deflate_slow},
170/* 7 */ {8, 32, 128, 256, deflate_slow},
171/* 8 */ {32, 128, 258, 1024, deflate_slow},
172/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
173#endif
174
175/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
176 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
177 * meaning.
178 */
179
jiadong.zhu6c142162016-06-22 21:22:18 -0700180/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */
mark13dc2462017-02-14 22:15:29 -0800181#define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0))
jiadong.zhu6c142162016-06-22 21:22:18 -0700182
initial.commit3d533e02008-07-27 00:38:33 +0000183/* ===========================================================================
184 * Update a hash value with the given input byte
mark13dc2462017-02-14 22:15:29 -0800185 * IN assertion: all calls to UPDATE_HASH are made with consecutive input
186 * characters, so that a running hash key can be computed from the previous
187 * key instead of complete recalculation each time.
initial.commit3d533e02008-07-27 00:38:33 +0000188 */
189#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
190
initial.commit3d533e02008-07-27 00:38:33 +0000191/* ===========================================================================
192 * Insert string str in the dictionary and set match_head to the previous head
193 * of the hash chain (the most recent string with same hash key). Return
194 * the previous length of the hash chain.
195 * If this file is compiled with -DFASTEST, the compression level is forced
196 * to 1, and no hash chains are maintained.
mark13dc2462017-02-14 22:15:29 -0800197 * IN assertion: all calls to INSERT_STRING are made with consecutive input
198 * characters and the first MIN_MATCH bytes of str are valid (except for
199 * the last MIN_MATCH-1 bytes of the input file).
initial.commit3d533e02008-07-27 00:38:33 +0000200 */
robert.bradford10dd6862014-11-05 06:59:34 -0800201local INLINE Pos insert_string_c(deflate_state *const s, const Pos str)
202{
203 Pos ret;
204
205 UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]);
initial.commit3d533e02008-07-27 00:38:33 +0000206#ifdef FASTEST
robert.bradford10dd6862014-11-05 06:59:34 -0800207 ret = s->head[s->ins_h];
initial.commit3d533e02008-07-27 00:38:33 +0000208#else
robert.bradford10dd6862014-11-05 06:59:34 -0800209 ret = s->prev[str & s->w_mask] = s->head[s->ins_h];
initial.commit3d533e02008-07-27 00:38:33 +0000210#endif
robert.bradford10dd6862014-11-05 06:59:34 -0800211 s->head[s->ins_h] = str;
212
213 return ret;
214}
215
216local INLINE Pos insert_string(deflate_state *const s, const Pos str)
217{
Adenilson Cavalcanti21cc38f2018-08-15 01:06:05 +0000218#if defined(CRC32_ARMV8_CRC32)
219 if (arm_cpu_enable_crc32)
220 return insert_string_arm(s, str);
221#endif
robert.bradford10dd6862014-11-05 06:59:34 -0800222 if (x86_cpu_enable_simd)
223 return insert_string_sse(s, str);
Adenilson Cavalcanti21cc38f2018-08-15 01:06:05 +0000224
robert.bradford10dd6862014-11-05 06:59:34 -0800225 return insert_string_c(s, str);
226}
227
initial.commit3d533e02008-07-27 00:38:33 +0000228/* ===========================================================================
229 * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
230 * prev[] will be initialized on the fly.
231 */
232#define CLEAR_HASH(s) \
233 s->head[s->hash_size-1] = NIL; \
234 zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
235
mark13dc2462017-02-14 22:15:29 -0800236/* ===========================================================================
237 * Slide the hash table when sliding the window down (could be avoided with 32
238 * bit values at the expense of memory usage). We slide even when level == 0 to
239 * keep the hash table consistent if we switch back to level > 0 later.
240 */
241local void slide_hash(s)
242 deflate_state *s;
243{
Adenilson Cavalcantid6d19612018-08-07 16:08:59 +0000244#if (defined(__ARM_NEON__) || defined(__ARM_NEON))
245 /* NEON based hash table rebase. */
246 return neon_slide_hash(s->head, s->prev, s->w_size, s->hash_size);
247#endif
mark13dc2462017-02-14 22:15:29 -0800248 unsigned n, m;
249 Posf *p;
250 uInt wsize = s->w_size;
251
252 n = s->hash_size;
253 p = &s->head[n];
254 do {
255 m = *--p;
256 *p = (Pos)(m >= wsize ? m - wsize : NIL);
257 } while (--n);
258 n = wsize;
259#ifndef FASTEST
260 p = &s->prev[n];
261 do {
262 m = *--p;
263 *p = (Pos)(m >= wsize ? m - wsize : NIL);
264 /* If n is not on any hash chain, prev[n] is garbage but
265 * its value will never be used.
266 */
267 } while (--n);
268#endif
269}
270
initial.commit3d533e02008-07-27 00:38:33 +0000271/* ========================================================================= */
272int ZEXPORT deflateInit_(strm, level, version, stream_size)
273 z_streamp strm;
274 int level;
275 const char *version;
276 int stream_size;
277{
278 return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
279 Z_DEFAULT_STRATEGY, version, stream_size);
280 /* To do: ignore strm->next_in if we use it as window */
281}
282
283/* ========================================================================= */
284int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
285 version, stream_size)
286 z_streamp strm;
287 int level;
288 int method;
289 int windowBits;
290 int memLevel;
291 int strategy;
292 const char *version;
293 int stream_size;
294{
robert.bradford10dd6862014-11-05 06:59:34 -0800295 unsigned window_padding = 8;
initial.commit3d533e02008-07-27 00:38:33 +0000296 deflate_state *s;
297 int wrap = 1;
298 static const char my_version[] = ZLIB_VERSION;
299
300 ushf *overlay;
301 /* We overlay pending_buf and d_buf+l_buf. This works since the average
302 * output size for (length,distance) codes is <= 24 bits.
303 */
304
robert.bradford10dd6862014-11-05 06:59:34 -0800305 x86_check_features();
306
initial.commit3d533e02008-07-27 00:38:33 +0000307 if (version == Z_NULL || version[0] != my_version[0] ||
308 stream_size != sizeof(z_stream)) {
309 return Z_VERSION_ERROR;
310 }
311 if (strm == Z_NULL) return Z_STREAM_ERROR;
312
313 strm->msg = Z_NULL;
314 if (strm->zalloc == (alloc_func)0) {
jiadong.zhu6c142162016-06-22 21:22:18 -0700315#ifdef Z_SOLO
316 return Z_STREAM_ERROR;
317#else
initial.commit3d533e02008-07-27 00:38:33 +0000318 strm->zalloc = zcalloc;
319 strm->opaque = (voidpf)0;
jiadong.zhu6c142162016-06-22 21:22:18 -0700320#endif
initial.commit3d533e02008-07-27 00:38:33 +0000321 }
jiadong.zhu6c142162016-06-22 21:22:18 -0700322 if (strm->zfree == (free_func)0)
323#ifdef Z_SOLO
324 return Z_STREAM_ERROR;
325#else
326 strm->zfree = zcfree;
327#endif
initial.commit3d533e02008-07-27 00:38:33 +0000328
329#ifdef FASTEST
330 if (level != 0) level = 1;
331#else
332 if (level == Z_DEFAULT_COMPRESSION) level = 6;
333#endif
334
335 if (windowBits < 0) { /* suppress zlib wrapper */
336 wrap = 0;
337 windowBits = -windowBits;
338 }
339#ifdef GZIP
340 else if (windowBits > 15) {
341 wrap = 2; /* write gzip wrapper instead */
342 windowBits -= 16;
343 }
344#endif
345 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
346 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
mark13dc2462017-02-14 22:15:29 -0800347 strategy < 0 || strategy > Z_FIXED || (windowBits == 8 && wrap != 1)) {
initial.commit3d533e02008-07-27 00:38:33 +0000348 return Z_STREAM_ERROR;
349 }
350 if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
351 s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
352 if (s == Z_NULL) return Z_MEM_ERROR;
353 strm->state = (struct internal_state FAR *)s;
354 s->strm = strm;
mark13dc2462017-02-14 22:15:29 -0800355 s->status = INIT_STATE; /* to pass state test in deflateReset() */
initial.commit3d533e02008-07-27 00:38:33 +0000356
357 s->wrap = wrap;
358 s->gzhead = Z_NULL;
mark13dc2462017-02-14 22:15:29 -0800359 s->w_bits = (uInt)windowBits;
initial.commit3d533e02008-07-27 00:38:33 +0000360 s->w_size = 1 << s->w_bits;
361 s->w_mask = s->w_size - 1;
362
robert.bradford10dd6862014-11-05 06:59:34 -0800363 if (x86_cpu_enable_simd) {
364 s->hash_bits = 15;
365 } else {
366 s->hash_bits = memLevel + 7;
367 }
368
initial.commit3d533e02008-07-27 00:38:33 +0000369 s->hash_size = 1 << s->hash_bits;
370 s->hash_mask = s->hash_size - 1;
371 s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
372
mark13dc2462017-02-14 22:15:29 -0800373 s->window = (Bytef *) ZALLOC(strm,
374 s->w_size + window_padding,
375 2*sizeof(Byte));
initial.commit3d533e02008-07-27 00:38:33 +0000376 s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
377 s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
378
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +0000379 s->high_water = 0; /* nothing written to s->window yet */
380
initial.commit3d533e02008-07-27 00:38:33 +0000381 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
382
383 overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
384 s->pending_buf = (uchf *) overlay;
385 s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
386
387 if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
388 s->pending_buf == Z_NULL) {
389 s->status = FINISH_STATE;
jiadong.zhu6c142162016-06-22 21:22:18 -0700390 strm->msg = ERR_MSG(Z_MEM_ERROR);
initial.commit3d533e02008-07-27 00:38:33 +0000391 deflateEnd (strm);
392 return Z_MEM_ERROR;
393 }
394 s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
395 s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
396
397 s->level = level;
398 s->strategy = strategy;
399 s->method = (Byte)method;
400
401 return deflateReset(strm);
402}
403
mark13dc2462017-02-14 22:15:29 -0800404/* =========================================================================
405 * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
406 */
407local int deflateStateCheck (strm)
408 z_streamp strm;
409{
410 deflate_state *s;
411 if (strm == Z_NULL ||
412 strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
413 return 1;
414 s = strm->state;
415 if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE &&
416#ifdef GZIP
417 s->status != GZIP_STATE &&
418#endif
419 s->status != EXTRA_STATE &&
420 s->status != NAME_STATE &&
421 s->status != COMMENT_STATE &&
422 s->status != HCRC_STATE &&
423 s->status != BUSY_STATE &&
424 s->status != FINISH_STATE))
425 return 1;
426 return 0;
427}
428
initial.commit3d533e02008-07-27 00:38:33 +0000429/* ========================================================================= */
430int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
431 z_streamp strm;
432 const Bytef *dictionary;
433 uInt dictLength;
434{
435 deflate_state *s;
jiadong.zhu6c142162016-06-22 21:22:18 -0700436 uInt str, n;
437 int wrap;
438 unsigned avail;
439 z_const unsigned char *next;
initial.commit3d533e02008-07-27 00:38:33 +0000440
mark13dc2462017-02-14 22:15:29 -0800441 if (deflateStateCheck(strm) || dictionary == Z_NULL)
jiadong.zhu6c142162016-06-22 21:22:18 -0700442 return Z_STREAM_ERROR;
443 s = strm->state;
444 wrap = s->wrap;
445 if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
jiadong.zhu90f7dad2016-06-20 04:09:43 -0700446 return Z_STREAM_ERROR;
jmadillbf2aebe2016-06-20 06:58:52 -0700447
jiadong.zhu6c142162016-06-22 21:22:18 -0700448 /* when using zlib wrappers, compute Adler-32 for provided dictionary */
449 if (wrap == 1)
initial.commit3d533e02008-07-27 00:38:33 +0000450 strm->adler = adler32(strm->adler, dictionary, dictLength);
Daniel Bratell2eb38892018-01-11 01:01:17 +0000451 s->wrap = 0; /* avoid computing Adler-32 in deflate_read_buf */
initial.commit3d533e02008-07-27 00:38:33 +0000452
jiadong.zhu6c142162016-06-22 21:22:18 -0700453 /* if dictionary would fill window, just replace the history */
454 if (dictLength >= s->w_size) {
455 if (wrap == 0) { /* already empty otherwise */
456 CLEAR_HASH(s);
457 s->strstart = 0;
458 s->block_start = 0L;
459 s->insert = 0;
460 }
461 dictionary += dictLength - s->w_size; /* use the tail */
462 dictLength = s->w_size;
initial.commit3d533e02008-07-27 00:38:33 +0000463 }
initial.commit3d533e02008-07-27 00:38:33 +0000464
jiadong.zhu6c142162016-06-22 21:22:18 -0700465 /* insert dictionary into window and hash */
466 avail = strm->avail_in;
467 next = strm->next_in;
468 strm->avail_in = dictLength;
469 strm->next_in = (z_const Bytef *)dictionary;
470 fill_window(s);
471 while (s->lookahead >= MIN_MATCH) {
472 str = s->strstart;
473 n = s->lookahead - (MIN_MATCH-1);
474 do {
475 insert_string(s, str);
476 str++;
477 } while (--n);
478 s->strstart = str;
479 s->lookahead = MIN_MATCH-1;
480 fill_window(s);
initial.commit3d533e02008-07-27 00:38:33 +0000481 }
jiadong.zhu6c142162016-06-22 21:22:18 -0700482 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;
initial.commit3d533e02008-07-27 00:38:33 +0000491 return Z_OK;
492}
493
494/* ========================================================================= */
mark13dc2462017-02-14 22:15:29 -0800495int 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/* ========================================================================= */
jiadong.zhu6c142162016-06-22 21:22:18 -0700517int ZEXPORT deflateResetKeep (strm)
initial.commit3d533e02008-07-27 00:38:33 +0000518 z_streamp strm;
519{
520 deflate_state *s;
521
mark13dc2462017-02-14 22:15:29 -0800522 if (deflateStateCheck(strm)) {
initial.commit3d533e02008-07-27 00:38:33 +0000523 return Z_STREAM_ERROR;
524 }
525
526 strm->total_in = strm->total_out = 0;
527 strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
528 strm->data_type = Z_UNKNOWN;
529
530 s = (deflate_state *)strm->state;
531 s->pending = 0;
532 s->pending_out = s->pending_buf;
533
534 if (s->wrap < 0) {
535 s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
536 }
mark13dc2462017-02-14 22:15:29 -0800537 s->status =
538#ifdef GZIP
539 s->wrap == 2 ? GZIP_STATE :
540#endif
541 s->wrap ? INIT_STATE : BUSY_STATE;
initial.commit3d533e02008-07-27 00:38:33 +0000542 strm->adler =
543#ifdef GZIP
544 s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
545#endif
546 adler32(0L, Z_NULL, 0);
547 s->last_flush = Z_NO_FLUSH;
548
549 _tr_init(s);
initial.commit3d533e02008-07-27 00:38:33 +0000550
551 return Z_OK;
552}
553
554/* ========================================================================= */
jiadong.zhu6c142162016-06-22 21:22:18 -0700555int ZEXPORT deflateReset (strm)
556 z_streamp strm;
557{
558 int ret;
559
560 ret = deflateResetKeep(strm);
561 if (ret == Z_OK)
562 lm_init(strm->state);
563 return ret;
564}
565
566/* ========================================================================= */
initial.commit3d533e02008-07-27 00:38:33 +0000567int ZEXPORT deflateSetHeader (strm, head)
568 z_streamp strm;
569 gz_headerp head;
570{
mark13dc2462017-02-14 22:15:29 -0800571 if (deflateStateCheck(strm) || strm->state->wrap != 2)
572 return Z_STREAM_ERROR;
initial.commit3d533e02008-07-27 00:38:33 +0000573 strm->state->gzhead = head;
574 return Z_OK;
575}
576
577/* ========================================================================= */
jiadong.zhu6c142162016-06-22 21:22:18 -0700578int ZEXPORT deflatePending (strm, pending, bits)
579 unsigned *pending;
580 int *bits;
581 z_streamp strm;
582{
mark13dc2462017-02-14 22:15:29 -0800583 if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
jiadong.zhu6c142162016-06-22 21:22:18 -0700584 if (pending != Z_NULL)
585 *pending = strm->state->pending;
586 if (bits != Z_NULL)
587 *bits = strm->state->bi_valid;
588 return Z_OK;
589}
590
591/* ========================================================================= */
initial.commit3d533e02008-07-27 00:38:33 +0000592int ZEXPORT deflatePrime (strm, bits, value)
593 z_streamp strm;
594 int bits;
595 int value;
596{
jiadong.zhu6c142162016-06-22 21:22:18 -0700597 deflate_state *s;
598 int put;
599
mark13dc2462017-02-14 22:15:29 -0800600 if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
jiadong.zhu6c142162016-06-22 21:22:18 -0700601 s = strm->state;
602 if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3))
603 return Z_BUF_ERROR;
604 do {
605 put = Buf_size - s->bi_valid;
606 if (put > bits)
607 put = bits;
608 s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);
609 s->bi_valid += put;
610 _tr_flush_bits(s);
611 value >>= put;
612 bits -= put;
613 } while (bits);
initial.commit3d533e02008-07-27 00:38:33 +0000614 return Z_OK;
615}
616
617/* ========================================================================= */
618int ZEXPORT deflateParams(strm, level, strategy)
619 z_streamp strm;
620 int level;
621 int strategy;
622{
623 deflate_state *s;
624 compress_func func;
initial.commit3d533e02008-07-27 00:38:33 +0000625
mark13dc2462017-02-14 22:15:29 -0800626 if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
initial.commit3d533e02008-07-27 00:38:33 +0000627 s = strm->state;
628
629#ifdef FASTEST
630 if (level != 0) level = 1;
631#else
632 if (level == Z_DEFAULT_COMPRESSION) level = 6;
633#endif
634 if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
635 return Z_STREAM_ERROR;
636 }
637 func = configuration_table[s->level].func;
638
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +0000639 if ((strategy != s->strategy || func != configuration_table[level].func) &&
mark13dc2462017-02-14 22:15:29 -0800640 s->high_water) {
initial.commit3d533e02008-07-27 00:38:33 +0000641 /* Flush the last buffer: */
mark13dc2462017-02-14 22:15:29 -0800642 int err = deflate(strm, Z_BLOCK);
643 if (err == Z_STREAM_ERROR)
644 return err;
645 if (strm->avail_out == 0)
646 return Z_BUF_ERROR;
initial.commit3d533e02008-07-27 00:38:33 +0000647 }
648 if (s->level != level) {
mark13dc2462017-02-14 22:15:29 -0800649 if (s->level == 0 && s->matches != 0) {
650 if (s->matches == 1)
651 slide_hash(s);
652 else
653 CLEAR_HASH(s);
654 s->matches = 0;
655 }
initial.commit3d533e02008-07-27 00:38:33 +0000656 s->level = level;
657 s->max_lazy_match = configuration_table[level].max_lazy;
658 s->good_match = configuration_table[level].good_length;
659 s->nice_match = configuration_table[level].nice_length;
660 s->max_chain_length = configuration_table[level].max_chain;
661 }
662 s->strategy = strategy;
mark13dc2462017-02-14 22:15:29 -0800663 return Z_OK;
initial.commit3d533e02008-07-27 00:38:33 +0000664}
665
666/* ========================================================================= */
667int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
668 z_streamp strm;
669 int good_length;
670 int max_lazy;
671 int nice_length;
672 int max_chain;
673{
674 deflate_state *s;
675
mark13dc2462017-02-14 22:15:29 -0800676 if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
initial.commit3d533e02008-07-27 00:38:33 +0000677 s = strm->state;
mark13dc2462017-02-14 22:15:29 -0800678 s->good_match = (uInt)good_length;
679 s->max_lazy_match = (uInt)max_lazy;
initial.commit3d533e02008-07-27 00:38:33 +0000680 s->nice_match = nice_length;
mark13dc2462017-02-14 22:15:29 -0800681 s->max_chain_length = (uInt)max_chain;
initial.commit3d533e02008-07-27 00:38:33 +0000682 return Z_OK;
683}
684
685/* =========================================================================
686 * For the default windowBits of 15 and memLevel of 8, this function returns
687 * a close to exact, as well as small, upper bound on the compressed size.
688 * They are coded as constants here for a reason--if the #define's are
689 * changed, then this function needs to be changed as well. The return
690 * value for 15 and 8 only works for those exact settings.
691 *
692 * For any setting other than those defaults for windowBits and memLevel,
693 * the value returned is a conservative worst case for the maximum expansion
694 * resulting from using fixed blocks instead of stored blocks, which deflate
695 * can emit on compressed data for some combinations of the parameters.
696 *
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +0000697 * This function could be more sophisticated to provide closer upper bounds for
698 * every combination of windowBits and memLevel. But even the conservative
699 * upper bound of about 14% expansion does not seem onerous for output buffer
700 * allocation.
initial.commit3d533e02008-07-27 00:38:33 +0000701 */
702uLong ZEXPORT deflateBound(strm, sourceLen)
703 z_streamp strm;
704 uLong sourceLen;
705{
706 deflate_state *s;
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +0000707 uLong complen, wraplen;
initial.commit3d533e02008-07-27 00:38:33 +0000708
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +0000709 /* conservative upper bound for compressed data */
710 complen = sourceLen +
711 ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
initial.commit3d533e02008-07-27 00:38:33 +0000712
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +0000713 /* if can't get parameters, return conservative bound plus zlib wrapper */
mark13dc2462017-02-14 22:15:29 -0800714 if (deflateStateCheck(strm))
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +0000715 return complen + 6;
716
717 /* compute wrapper length */
718 s = strm->state;
719 switch (s->wrap) {
720 case 0: /* raw deflate */
721 wraplen = 0;
722 break;
723 case 1: /* zlib wrapper */
724 wraplen = 6 + (s->strstart ? 4 : 0);
725 break;
mark13dc2462017-02-14 22:15:29 -0800726#ifdef GZIP
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +0000727 case 2: /* gzip wrapper */
728 wraplen = 18;
729 if (s->gzhead != Z_NULL) { /* user-supplied gzip header */
mark13dc2462017-02-14 22:15:29 -0800730 Bytef *str;
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +0000731 if (s->gzhead->extra != Z_NULL)
732 wraplen += 2 + s->gzhead->extra_len;
733 str = s->gzhead->name;
734 if (str != Z_NULL)
735 do {
736 wraplen++;
737 } while (*str++);
738 str = s->gzhead->comment;
739 if (str != Z_NULL)
740 do {
741 wraplen++;
742 } while (*str++);
743 if (s->gzhead->hcrc)
744 wraplen += 2;
745 }
746 break;
mark13dc2462017-02-14 22:15:29 -0800747#endif
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +0000748 default: /* for compiler happiness */
749 wraplen = 6;
750 }
initial.commit3d533e02008-07-27 00:38:33 +0000751
752 /* if not default parameters, return conservative bound */
initial.commit3d533e02008-07-27 00:38:33 +0000753 if (s->w_bits != 15 || s->hash_bits != 8 + 7)
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +0000754 return complen + wraplen;
initial.commit3d533e02008-07-27 00:38:33 +0000755
756 /* default settings: return tight bound for that case */
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +0000757 return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
758 (sourceLen >> 25) + 13 - 6 + wraplen;
initial.commit3d533e02008-07-27 00:38:33 +0000759}
760
761/* =========================================================================
762 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
763 * IN assertion: the stream state is correct and there is enough room in
764 * pending_buf.
765 */
766local void putShortMSB (s, b)
767 deflate_state *s;
768 uInt b;
769{
770 put_byte(s, (Byte)(b >> 8));
771 put_byte(s, (Byte)(b & 0xff));
772}
773
774/* =========================================================================
mark13dc2462017-02-14 22:15:29 -0800775 * Flush as much pending output as possible. All deflate() output, except for
776 * some deflate_stored() output, goes through this function so some
777 * applications may wish to modify it to avoid allocating a large
Daniel Bratell2eb38892018-01-11 01:01:17 +0000778 * strm->next_out buffer and copying into it. (See also deflate_read_buf()).
initial.commit3d533e02008-07-27 00:38:33 +0000779 */
780local void flush_pending(strm)
781 z_streamp strm;
782{
jiadong.zhu6c142162016-06-22 21:22:18 -0700783 unsigned len;
784 deflate_state *s = strm->state;
initial.commit3d533e02008-07-27 00:38:33 +0000785
jiadong.zhu6c142162016-06-22 21:22:18 -0700786 _tr_flush_bits(s);
787 len = s->pending;
initial.commit3d533e02008-07-27 00:38:33 +0000788 if (len > strm->avail_out) len = strm->avail_out;
789 if (len == 0) return;
790
jiadong.zhu6c142162016-06-22 21:22:18 -0700791 zmemcpy(strm->next_out, s->pending_out, len);
initial.commit3d533e02008-07-27 00:38:33 +0000792 strm->next_out += len;
jiadong.zhu6c142162016-06-22 21:22:18 -0700793 s->pending_out += len;
initial.commit3d533e02008-07-27 00:38:33 +0000794 strm->total_out += len;
mark13dc2462017-02-14 22:15:29 -0800795 strm->avail_out -= len;
796 s->pending -= len;
jiadong.zhu6c142162016-06-22 21:22:18 -0700797 if (s->pending == 0) {
798 s->pending_out = s->pending_buf;
initial.commit3d533e02008-07-27 00:38:33 +0000799 }
800}
801
mark13dc2462017-02-14 22:15:29 -0800802/* ===========================================================================
803 * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1].
804 */
805#define HCRC_UPDATE(beg) \
806 do { \
807 if (s->gzhead->hcrc && s->pending > (beg)) \
808 strm->adler = crc32(strm->adler, s->pending_buf + (beg), \
809 s->pending - (beg)); \
810 } while (0)
811
initial.commit3d533e02008-07-27 00:38:33 +0000812/* ========================================================================= */
813int ZEXPORT deflate (strm, flush)
814 z_streamp strm;
815 int flush;
816{
817 int old_flush; /* value of flush param for previous deflate call */
818 deflate_state *s;
819
mark13dc2462017-02-14 22:15:29 -0800820 if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) {
initial.commit3d533e02008-07-27 00:38:33 +0000821 return Z_STREAM_ERROR;
822 }
823 s = strm->state;
824
825 if (strm->next_out == Z_NULL ||
mark13dc2462017-02-14 22:15:29 -0800826 (strm->avail_in != 0 && strm->next_in == Z_NULL) ||
initial.commit3d533e02008-07-27 00:38:33 +0000827 (s->status == FINISH_STATE && flush != Z_FINISH)) {
828 ERR_RETURN(strm, Z_STREAM_ERROR);
829 }
830 if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
831
initial.commit3d533e02008-07-27 00:38:33 +0000832 old_flush = s->last_flush;
833 s->last_flush = flush;
834
initial.commit3d533e02008-07-27 00:38:33 +0000835 /* Flush as much pending output as possible */
836 if (s->pending != 0) {
837 flush_pending(strm);
838 if (strm->avail_out == 0) {
839 /* Since avail_out is 0, deflate will be called again with
840 * more output space, but possibly with both pending and
841 * avail_in equal to zero. There won't be anything to do,
842 * but this is not an error situation so make sure we
843 * return OK instead of BUF_ERROR at next call of deflate:
844 */
845 s->last_flush = -1;
846 return Z_OK;
847 }
848
849 /* Make sure there is something to do and avoid duplicate consecutive
850 * flushes. For repeated and useless calls with Z_FINISH, we keep
851 * returning Z_STREAM_END instead of Z_BUF_ERROR.
852 */
jiadong.zhu6c142162016-06-22 21:22:18 -0700853 } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&
initial.commit3d533e02008-07-27 00:38:33 +0000854 flush != Z_FINISH) {
855 ERR_RETURN(strm, Z_BUF_ERROR);
856 }
857
858 /* User must not provide more input after the first FINISH: */
859 if (s->status == FINISH_STATE && strm->avail_in != 0) {
860 ERR_RETURN(strm, Z_BUF_ERROR);
861 }
862
mark13dc2462017-02-14 22:15:29 -0800863 /* Write the header */
864 if (s->status == INIT_STATE) {
865 /* zlib header */
866 uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
867 uInt level_flags;
868
869 if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
870 level_flags = 0;
871 else if (s->level < 6)
872 level_flags = 1;
873 else if (s->level == 6)
874 level_flags = 2;
875 else
876 level_flags = 3;
877 header |= (level_flags << 6);
878 if (s->strstart != 0) header |= PRESET_DICT;
879 header += 31 - (header % 31);
880
881 putShortMSB(s, header);
882
883 /* Save the adler32 of the preset dictionary: */
884 if (s->strstart != 0) {
885 putShortMSB(s, (uInt)(strm->adler >> 16));
886 putShortMSB(s, (uInt)(strm->adler & 0xffff));
887 }
888 strm->adler = adler32(0L, Z_NULL, 0);
889 s->status = BUSY_STATE;
890
891 /* Compression must start with an empty pending buffer */
892 flush_pending(strm);
893 if (s->pending != 0) {
894 s->last_flush = -1;
895 return Z_OK;
896 }
897 }
898#ifdef GZIP
899 if (s->status == GZIP_STATE) {
900 /* gzip header */
901 crc_reset(s);
902 put_byte(s, 31);
903 put_byte(s, 139);
904 put_byte(s, 8);
905 if (s->gzhead == Z_NULL) {
906 put_byte(s, 0);
907 put_byte(s, 0);
908 put_byte(s, 0);
909 put_byte(s, 0);
910 put_byte(s, 0);
911 put_byte(s, s->level == 9 ? 2 :
912 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
913 4 : 0));
914 put_byte(s, OS_CODE);
915 s->status = BUSY_STATE;
916
917 /* Compression must start with an empty pending buffer */
918 flush_pending(strm);
919 if (s->pending != 0) {
920 s->last_flush = -1;
921 return Z_OK;
922 }
923 }
924 else {
925 put_byte(s, (s->gzhead->text ? 1 : 0) +
926 (s->gzhead->hcrc ? 2 : 0) +
927 (s->gzhead->extra == Z_NULL ? 0 : 4) +
928 (s->gzhead->name == Z_NULL ? 0 : 8) +
929 (s->gzhead->comment == Z_NULL ? 0 : 16)
930 );
931 put_byte(s, (Byte)(s->gzhead->time & 0xff));
932 put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
933 put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
934 put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
935 put_byte(s, s->level == 9 ? 2 :
936 (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
937 4 : 0));
938 put_byte(s, s->gzhead->os & 0xff);
939 if (s->gzhead->extra != Z_NULL) {
940 put_byte(s, s->gzhead->extra_len & 0xff);
941 put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
942 }
943 if (s->gzhead->hcrc)
944 strm->adler = crc32(strm->adler, s->pending_buf,
945 s->pending);
946 s->gzindex = 0;
947 s->status = EXTRA_STATE;
948 }
949 }
950 if (s->status == EXTRA_STATE) {
951 if (s->gzhead->extra != Z_NULL) {
952 ulg beg = s->pending; /* start of bytes to update crc */
953 uInt left = (s->gzhead->extra_len & 0xffff) - s->gzindex;
954 while (s->pending + left > s->pending_buf_size) {
955 uInt copy = s->pending_buf_size - s->pending;
956 zmemcpy(s->pending_buf + s->pending,
957 s->gzhead->extra + s->gzindex, copy);
958 s->pending = s->pending_buf_size;
959 HCRC_UPDATE(beg);
960 s->gzindex += copy;
961 flush_pending(strm);
962 if (s->pending != 0) {
963 s->last_flush = -1;
964 return Z_OK;
965 }
966 beg = 0;
967 left -= copy;
968 }
969 zmemcpy(s->pending_buf + s->pending,
970 s->gzhead->extra + s->gzindex, left);
971 s->pending += left;
972 HCRC_UPDATE(beg);
973 s->gzindex = 0;
974 }
975 s->status = NAME_STATE;
976 }
977 if (s->status == NAME_STATE) {
978 if (s->gzhead->name != Z_NULL) {
979 ulg beg = s->pending; /* start of bytes to update crc */
980 int val;
981 do {
982 if (s->pending == s->pending_buf_size) {
983 HCRC_UPDATE(beg);
984 flush_pending(strm);
985 if (s->pending != 0) {
986 s->last_flush = -1;
987 return Z_OK;
988 }
989 beg = 0;
990 }
991 val = s->gzhead->name[s->gzindex++];
992 put_byte(s, val);
993 } while (val != 0);
994 HCRC_UPDATE(beg);
995 s->gzindex = 0;
996 }
997 s->status = COMMENT_STATE;
998 }
999 if (s->status == COMMENT_STATE) {
1000 if (s->gzhead->comment != Z_NULL) {
1001 ulg beg = s->pending; /* start of bytes to update crc */
1002 int val;
1003 do {
1004 if (s->pending == s->pending_buf_size) {
1005 HCRC_UPDATE(beg);
1006 flush_pending(strm);
1007 if (s->pending != 0) {
1008 s->last_flush = -1;
1009 return Z_OK;
1010 }
1011 beg = 0;
1012 }
1013 val = s->gzhead->comment[s->gzindex++];
1014 put_byte(s, val);
1015 } while (val != 0);
1016 HCRC_UPDATE(beg);
1017 }
1018 s->status = HCRC_STATE;
1019 }
1020 if (s->status == HCRC_STATE) {
1021 if (s->gzhead->hcrc) {
1022 if (s->pending + 2 > s->pending_buf_size) {
1023 flush_pending(strm);
1024 if (s->pending != 0) {
1025 s->last_flush = -1;
1026 return Z_OK;
1027 }
1028 }
1029 put_byte(s, (Byte)(strm->adler & 0xff));
1030 put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
1031 strm->adler = crc32(0L, Z_NULL, 0);
1032 }
1033 s->status = BUSY_STATE;
1034
1035 /* Compression must start with an empty pending buffer */
1036 flush_pending(strm);
1037 if (s->pending != 0) {
1038 s->last_flush = -1;
1039 return Z_OK;
1040 }
1041 }
1042#endif
1043
initial.commit3d533e02008-07-27 00:38:33 +00001044 /* Start a new block or continue the current one.
1045 */
1046 if (strm->avail_in != 0 || s->lookahead != 0 ||
1047 (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
1048 block_state bstate;
1049
mark13dc2462017-02-14 22:15:29 -08001050 bstate = s->level == 0 ? deflate_stored(s, flush) :
1051 s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
1052 s->strategy == Z_RLE ? deflate_rle(s, flush) :
1053 (*(configuration_table[s->level].func))(s, flush);
initial.commit3d533e02008-07-27 00:38:33 +00001054
1055 if (bstate == finish_started || bstate == finish_done) {
1056 s->status = FINISH_STATE;
1057 }
1058 if (bstate == need_more || bstate == finish_started) {
1059 if (strm->avail_out == 0) {
1060 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
1061 }
1062 return Z_OK;
1063 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
1064 * of deflate should use the same flush parameter to make sure
1065 * that the flush is complete. So we don't have to output an
1066 * empty block here, this will be done at next call. This also
1067 * ensures that for a very small output buffer, we emit at most
1068 * one empty block.
1069 */
1070 }
1071 if (bstate == block_done) {
1072 if (flush == Z_PARTIAL_FLUSH) {
1073 _tr_align(s);
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00001074 } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
initial.commit3d533e02008-07-27 00:38:33 +00001075 _tr_stored_block(s, (char*)0, 0L, 0);
1076 /* For a full flush, this empty block will be recognized
1077 * as a special marker by inflate_sync().
1078 */
1079 if (flush == Z_FULL_FLUSH) {
1080 CLEAR_HASH(s); /* forget history */
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00001081 if (s->lookahead == 0) {
1082 s->strstart = 0;
1083 s->block_start = 0L;
jiadong.zhu6c142162016-06-22 21:22:18 -07001084 s->insert = 0;
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00001085 }
initial.commit3d533e02008-07-27 00:38:33 +00001086 }
1087 }
1088 flush_pending(strm);
1089 if (strm->avail_out == 0) {
1090 s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
1091 return Z_OK;
1092 }
1093 }
1094 }
initial.commit3d533e02008-07-27 00:38:33 +00001095
1096 if (flush != Z_FINISH) return Z_OK;
1097 if (s->wrap <= 0) return Z_STREAM_END;
1098
1099 /* Write the trailer */
1100#ifdef GZIP
1101 if (s->wrap == 2) {
robert.bradford10dd6862014-11-05 06:59:34 -08001102 crc_finalize(s);
initial.commit3d533e02008-07-27 00:38:33 +00001103 put_byte(s, (Byte)(strm->adler & 0xff));
1104 put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
1105 put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
1106 put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
1107 put_byte(s, (Byte)(strm->total_in & 0xff));
1108 put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
1109 put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
1110 put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
1111 }
1112 else
1113#endif
1114 {
1115 putShortMSB(s, (uInt)(strm->adler >> 16));
1116 putShortMSB(s, (uInt)(strm->adler & 0xffff));
1117 }
1118 flush_pending(strm);
1119 /* If avail_out is zero, the application will call deflate again
1120 * to flush the rest.
1121 */
1122 if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
1123 return s->pending != 0 ? Z_OK : Z_STREAM_END;
1124}
1125
1126/* ========================================================================= */
1127int ZEXPORT deflateEnd (strm)
1128 z_streamp strm;
1129{
1130 int status;
1131
mark13dc2462017-02-14 22:15:29 -08001132 if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
initial.commit3d533e02008-07-27 00:38:33 +00001133
1134 status = strm->state->status;
initial.commit3d533e02008-07-27 00:38:33 +00001135
1136 /* Deallocate in reverse order of allocations: */
1137 TRY_FREE(strm, strm->state->pending_buf);
1138 TRY_FREE(strm, strm->state->head);
1139 TRY_FREE(strm, strm->state->prev);
1140 TRY_FREE(strm, strm->state->window);
1141
1142 ZFREE(strm, strm->state);
1143 strm->state = Z_NULL;
1144
1145 return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
1146}
1147
1148/* =========================================================================
1149 * Copy the source state to the destination state.
1150 * To simplify the source, this is not supported for 16-bit MSDOS (which
1151 * doesn't have enough memory anyway to duplicate compression states).
1152 */
1153int ZEXPORT deflateCopy (dest, source)
1154 z_streamp dest;
1155 z_streamp source;
1156{
1157#ifdef MAXSEG_64K
1158 return Z_STREAM_ERROR;
1159#else
1160 deflate_state *ds;
1161 deflate_state *ss;
1162 ushf *overlay;
1163
1164
mark13dc2462017-02-14 22:15:29 -08001165 if (deflateStateCheck(source) || dest == Z_NULL) {
initial.commit3d533e02008-07-27 00:38:33 +00001166 return Z_STREAM_ERROR;
1167 }
1168
1169 ss = source->state;
1170
jiadong.zhu6c142162016-06-22 21:22:18 -07001171 zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
initial.commit3d533e02008-07-27 00:38:33 +00001172
1173 ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
1174 if (ds == Z_NULL) return Z_MEM_ERROR;
1175 dest->state = (struct internal_state FAR *) ds;
jiadong.zhu6c142162016-06-22 21:22:18 -07001176 zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));
initial.commit3d533e02008-07-27 00:38:33 +00001177 ds->strm = dest;
1178
1179 ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
1180 ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
1181 ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
1182 overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
1183 ds->pending_buf = (uchf *) overlay;
1184
1185 if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
1186 ds->pending_buf == Z_NULL) {
1187 deflateEnd (dest);
1188 return Z_MEM_ERROR;
1189 }
1190 /* following zmemcpy do not work for 16-bit MSDOS */
1191 zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
jiadong.zhu6c142162016-06-22 21:22:18 -07001192 zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));
1193 zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));
initial.commit3d533e02008-07-27 00:38:33 +00001194 zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
1195
1196 ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
1197 ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
1198 ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
1199
1200 ds->l_desc.dyn_tree = ds->dyn_ltree;
1201 ds->d_desc.dyn_tree = ds->dyn_dtree;
1202 ds->bl_desc.dyn_tree = ds->bl_tree;
1203
1204 return Z_OK;
1205#endif /* MAXSEG_64K */
1206}
1207
1208/* ===========================================================================
1209 * Read a new buffer from the current input stream, update the adler32
1210 * and total number of bytes read. All deflate() input goes through
1211 * this function so some applications may wish to modify it to avoid
1212 * allocating a large strm->next_in buffer and copying from it.
1213 * (See also flush_pending()).
1214 */
Daniel Bratell2eb38892018-01-11 01:01:17 +00001215ZLIB_INTERNAL unsigned deflate_read_buf(strm, buf, size)
initial.commit3d533e02008-07-27 00:38:33 +00001216 z_streamp strm;
1217 Bytef *buf;
1218 unsigned size;
1219{
1220 unsigned len = strm->avail_in;
1221
1222 if (len > size) len = size;
1223 if (len == 0) return 0;
1224
1225 strm->avail_in -= len;
1226
initial.commit3d533e02008-07-27 00:38:33 +00001227#ifdef GZIP
jiadong.zhu6c142162016-06-22 21:22:18 -07001228 if (strm->state->wrap == 2)
robert.bradford10dd6862014-11-05 06:59:34 -08001229 copy_with_crc(strm, buf, len);
jiadong.zhu6c142162016-06-22 21:22:18 -07001230 else
initial.commit3d533e02008-07-27 00:38:33 +00001231#endif
robert.bradford10dd6862014-11-05 06:59:34 -08001232 {
1233 zmemcpy(buf, strm->next_in, len);
1234 if (strm->state->wrap == 1)
1235 strm->adler = adler32(strm->adler, buf, len);
1236 }
initial.commit3d533e02008-07-27 00:38:33 +00001237 strm->next_in += len;
1238 strm->total_in += len;
1239
mark13dc2462017-02-14 22:15:29 -08001240 return len;
initial.commit3d533e02008-07-27 00:38:33 +00001241}
1242
1243/* ===========================================================================
1244 * Initialize the "longest match" routines for a new zlib stream
1245 */
1246local void lm_init (s)
1247 deflate_state *s;
1248{
1249 s->window_size = (ulg)2L*s->w_size;
1250
1251 CLEAR_HASH(s);
1252
1253 /* Set the default configuration parameters:
1254 */
1255 s->max_lazy_match = configuration_table[s->level].max_lazy;
1256 s->good_match = configuration_table[s->level].good_length;
1257 s->nice_match = configuration_table[s->level].nice_length;
1258 s->max_chain_length = configuration_table[s->level].max_chain;
1259
1260 s->strstart = 0;
1261 s->block_start = 0L;
1262 s->lookahead = 0;
jiadong.zhu6c142162016-06-22 21:22:18 -07001263 s->insert = 0;
initial.commit3d533e02008-07-27 00:38:33 +00001264 s->match_length = s->prev_length = MIN_MATCH-1;
1265 s->match_available = 0;
1266 s->ins_h = 0;
1267#ifndef FASTEST
1268#ifdef ASMV
1269 match_init(); /* initialize the asm code */
1270#endif
1271#endif
1272}
1273
1274#ifndef FASTEST
1275/* ===========================================================================
1276 * Set match_start to the longest match starting at the given string and
1277 * return its length. Matches shorter or equal to prev_length are discarded,
1278 * in which case the result is equal to prev_length and match_start is
1279 * garbage.
1280 * IN assertions: cur_match is the head of the hash chain for the current
1281 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1282 * OUT assertion: the match length is not greater than s->lookahead.
1283 */
1284#ifndef ASMV
1285/* For 80x86 and 680x0, an optimized version will be provided in match.asm or
1286 * match.S. The code will be functionally equivalent.
1287 */
davidben709ed022017-02-02 13:58:58 -08001288local uInt longest_match(s, cur_match)
initial.commit3d533e02008-07-27 00:38:33 +00001289 deflate_state *s;
1290 IPos cur_match; /* current match */
1291{
1292 unsigned chain_length = s->max_chain_length;/* max hash chain length */
1293 register Bytef *scan = s->window + s->strstart; /* current string */
mark13dc2462017-02-14 22:15:29 -08001294 register Bytef *match; /* matched string */
initial.commit3d533e02008-07-27 00:38:33 +00001295 register int len; /* length of current match */
mark13dc2462017-02-14 22:15:29 -08001296 int best_len = (int)s->prev_length; /* best match length so far */
initial.commit3d533e02008-07-27 00:38:33 +00001297 int nice_match = s->nice_match; /* stop if match long enough */
1298 IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
1299 s->strstart - (IPos)MAX_DIST(s) : NIL;
1300 /* Stop when cur_match becomes <= limit. To simplify the code,
1301 * we prevent matches with the string of window index 0.
1302 */
1303 Posf *prev = s->prev;
1304 uInt wmask = s->w_mask;
1305
1306#ifdef UNALIGNED_OK
1307 /* Compare two bytes at a time. Note: this is not always beneficial.
1308 * Try with and without -DUNALIGNED_OK to check.
1309 */
1310 register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
1311 register ush scan_start = *(ushf*)scan;
1312 register ush scan_end = *(ushf*)(scan+best_len-1);
1313#else
1314 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1315 register Byte scan_end1 = scan[best_len-1];
1316 register Byte scan_end = scan[best_len];
1317#endif
1318
1319 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1320 * It is easy to get rid of this optimization if necessary.
1321 */
1322 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1323
1324 /* Do not waste too much time if we already have a good match: */
1325 if (s->prev_length >= s->good_match) {
1326 chain_length >>= 2;
1327 }
1328 /* Do not look for matches beyond the end of the input. This is necessary
1329 * to make deflate deterministic.
1330 */
mark13dc2462017-02-14 22:15:29 -08001331 if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead;
initial.commit3d533e02008-07-27 00:38:33 +00001332
1333 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1334
1335 do {
1336 Assert(cur_match < s->strstart, "no future");
1337 match = s->window + cur_match;
1338
1339 /* Skip to next match if the match length cannot increase
1340 * or if the match length is less than 2. Note that the checks below
1341 * for insufficient lookahead only occur occasionally for performance
1342 * reasons. Therefore uninitialized memory will be accessed, and
1343 * conditional jumps will be made that depend on those values.
1344 * However the length of the match is limited to the lookahead, so
1345 * the output of deflate is not affected by the uninitialized values.
1346 */
1347#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
1348 /* This code assumes sizeof(unsigned short) == 2. Do not use
1349 * UNALIGNED_OK if your compiler uses a different size.
1350 */
1351 if (*(ushf*)(match+best_len-1) != scan_end ||
1352 *(ushf*)match != scan_start) continue;
1353
1354 /* It is not necessary to compare scan[2] and match[2] since they are
1355 * always equal when the other bytes match, given that the hash keys
1356 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
1357 * strstart+3, +5, ... up to strstart+257. We check for insufficient
1358 * lookahead only every 4th comparison; the 128th check will be made
1359 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
1360 * necessary to put more guard bytes at the end of the window, or
1361 * to check more often for insufficient lookahead.
1362 */
1363 Assert(scan[2] == match[2], "scan[2]?");
1364 scan++, match++;
1365 do {
1366 } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1367 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1368 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1369 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
1370 scan < strend);
1371 /* The funny "do {}" generates better code on most compilers */
1372
1373 /* Here, scan <= window+strstart+257 */
1374 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1375 if (*scan == *match) scan++;
1376
1377 len = (MAX_MATCH - 1) - (int)(strend-scan);
1378 scan = strend - (MAX_MATCH-1);
1379
1380#else /* UNALIGNED_OK */
1381
1382 if (match[best_len] != scan_end ||
1383 match[best_len-1] != scan_end1 ||
1384 *match != *scan ||
1385 *++match != scan[1]) continue;
1386
1387 /* The check at best_len-1 can be removed because it will be made
1388 * again later. (This heuristic is not always a win.)
1389 * It is not necessary to compare scan[2] and match[2] since they
1390 * are always equal when the other bytes match, given that
1391 * the hash keys are equal and that HASH_BITS >= 8.
1392 */
1393 scan += 2, match++;
1394 Assert(*scan == *match, "match[2]?");
1395
davidben709ed022017-02-02 13:58:58 -08001396 /* We check for insufficient lookahead only every 8th comparison;
1397 * the 256th check will be made at strstart+258.
1398 */
1399 do {
1400 } while (*++scan == *++match && *++scan == *++match &&
1401 *++scan == *++match && *++scan == *++match &&
1402 *++scan == *++match && *++scan == *++match &&
1403 *++scan == *++match && *++scan == *++match &&
1404 scan < strend);
initial.commit3d533e02008-07-27 00:38:33 +00001405
1406 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1407
1408 len = MAX_MATCH - (int)(strend - scan);
1409 scan = strend - MAX_MATCH;
1410
1411#endif /* UNALIGNED_OK */
1412
1413 if (len > best_len) {
1414 s->match_start = cur_match;
1415 best_len = len;
1416 if (len >= nice_match) break;
1417#ifdef UNALIGNED_OK
1418 scan_end = *(ushf*)(scan+best_len-1);
1419#else
1420 scan_end1 = scan[best_len-1];
1421 scan_end = scan[best_len];
1422#endif
1423 }
1424 } while ((cur_match = prev[cur_match & wmask]) > limit
1425 && --chain_length != 0);
1426
1427 if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
1428 return s->lookahead;
1429}
1430#endif /* ASMV */
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00001431
1432#else /* FASTEST */
initial.commit3d533e02008-07-27 00:38:33 +00001433
1434/* ---------------------------------------------------------------------------
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00001435 * Optimized version for FASTEST only
initial.commit3d533e02008-07-27 00:38:33 +00001436 */
davidben709ed022017-02-02 13:58:58 -08001437local uInt longest_match(s, cur_match)
initial.commit3d533e02008-07-27 00:38:33 +00001438 deflate_state *s;
1439 IPos cur_match; /* current match */
1440{
1441 register Bytef *scan = s->window + s->strstart; /* current string */
1442 register Bytef *match; /* matched string */
1443 register int len; /* length of current match */
1444 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
1445
1446 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1447 * It is easy to get rid of this optimization if necessary.
1448 */
1449 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
1450
1451 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
1452
1453 Assert(cur_match < s->strstart, "no future");
1454
1455 match = s->window + cur_match;
1456
1457 /* Return failure if the match length is less than 2:
1458 */
1459 if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
1460
1461 /* The check at best_len-1 can be removed because it will be made
1462 * again later. (This heuristic is not always a win.)
1463 * It is not necessary to compare scan[2] and match[2] since they
1464 * are always equal when the other bytes match, given that
1465 * the hash keys are equal and that HASH_BITS >= 8.
1466 */
1467 scan += 2, match += 2;
1468 Assert(*scan == *match, "match[2]?");
1469
1470 /* We check for insufficient lookahead only every 8th comparison;
1471 * the 256th check will be made at strstart+258.
1472 */
1473 do {
1474 } while (*++scan == *++match && *++scan == *++match &&
1475 *++scan == *++match && *++scan == *++match &&
1476 *++scan == *++match && *++scan == *++match &&
1477 *++scan == *++match && *++scan == *++match &&
1478 scan < strend);
1479
1480 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
1481
1482 len = MAX_MATCH - (int)(strend - scan);
1483
1484 if (len < MIN_MATCH) return MIN_MATCH - 1;
1485
1486 s->match_start = cur_match;
1487 return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
1488}
1489
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00001490#endif /* FASTEST */
1491
mark13dc2462017-02-14 22:15:29 -08001492#ifdef ZLIB_DEBUG
1493
1494#define EQUAL 0
1495/* result of memcmp for equal strings */
1496
initial.commit3d533e02008-07-27 00:38:33 +00001497/* ===========================================================================
1498 * Check that the match at match_start is indeed a match.
1499 */
1500local void check_match(s, start, match, length)
1501 deflate_state *s;
1502 IPos start, match;
1503 int length;
1504{
1505 /* check that the match is indeed a match */
1506 if (zmemcmp(s->window + match,
1507 s->window + start, length) != EQUAL) {
1508 fprintf(stderr, " start %u, match %u, length %d\n",
1509 start, match, length);
1510 do {
1511 fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
1512 } while (--length != 0);
1513 z_error("invalid match");
1514 }
1515 if (z_verbose > 1) {
1516 fprintf(stderr,"\\[%d,%d]", start-match, length);
1517 do { putc(s->window[start++], stderr); } while (--length != 0);
1518 }
1519}
1520#else
1521# define check_match(s, start, match, length)
mark13dc2462017-02-14 22:15:29 -08001522#endif /* ZLIB_DEBUG */
initial.commit3d533e02008-07-27 00:38:33 +00001523
1524/* ===========================================================================
1525 * Fill the window when the lookahead becomes insufficient.
1526 * Updates strstart and lookahead.
1527 *
1528 * IN assertion: lookahead < MIN_LOOKAHEAD
1529 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
1530 * At least one byte has been read, or avail_in == 0; reads are
1531 * performed for at least two bytes (required for the zip translate_eol
1532 * option -- not supported here).
1533 */
robert.bradford10dd6862014-11-05 06:59:34 -08001534local void fill_window_c(deflate_state *s);
1535
1536local void fill_window(deflate_state *s)
1537{
1538 if (x86_cpu_enable_simd) {
1539 fill_window_sse(s);
1540 return;
1541 }
1542
1543 fill_window_c(s);
1544}
1545
1546local void fill_window_c(s)
initial.commit3d533e02008-07-27 00:38:33 +00001547 deflate_state *s;
1548{
mark13dc2462017-02-14 22:15:29 -08001549 unsigned n;
initial.commit3d533e02008-07-27 00:38:33 +00001550 unsigned more; /* Amount of free space at the end of the window. */
1551 uInt wsize = s->w_size;
1552
jiadong.zhu6c142162016-06-22 21:22:18 -07001553 Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
1554
initial.commit3d533e02008-07-27 00:38:33 +00001555 do {
1556 more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
1557
1558 /* Deal with !@#$% 64K limit: */
1559 if (sizeof(int) <= 2) {
1560 if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
1561 more = wsize;
1562
1563 } else if (more == (unsigned)(-1)) {
1564 /* Very unlikely, but possible on 16 bit machine if
1565 * strstart == 0 && lookahead == 1 (input done a byte at time)
1566 */
1567 more--;
1568 }
1569 }
1570
1571 /* If the window is almost full and there is insufficient lookahead,
1572 * move the upper half to the lower one to make room in the upper half.
1573 */
1574 if (s->strstart >= wsize+MAX_DIST(s)) {
1575
mark13dc2462017-02-14 22:15:29 -08001576 zmemcpy(s->window, s->window+wsize, (unsigned)wsize - more);
initial.commit3d533e02008-07-27 00:38:33 +00001577 s->match_start -= wsize;
1578 s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
1579 s->block_start -= (long) wsize;
mark13dc2462017-02-14 22:15:29 -08001580 slide_hash(s);
initial.commit3d533e02008-07-27 00:38:33 +00001581 more += wsize;
1582 }
jiadong.zhu6c142162016-06-22 21:22:18 -07001583 if (s->strm->avail_in == 0) break;
initial.commit3d533e02008-07-27 00:38:33 +00001584
1585 /* If there was no sliding:
1586 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1587 * more == window_size - lookahead - strstart
1588 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1589 * => more >= window_size - 2*WSIZE + 2
1590 * In the BIG_MEM or MMAP case (not yet supported),
1591 * window_size == input_size + MIN_LOOKAHEAD &&
1592 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1593 * Otherwise, window_size == 2*WSIZE so more >= 2.
1594 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1595 */
1596 Assert(more >= 2, "more < 2");
1597
Daniel Bratell2eb38892018-01-11 01:01:17 +00001598 n = deflate_read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
initial.commit3d533e02008-07-27 00:38:33 +00001599 s->lookahead += n;
1600
1601 /* Initialize the hash value now that we have some input: */
jiadong.zhu6c142162016-06-22 21:22:18 -07001602 if (s->lookahead + s->insert >= MIN_MATCH) {
1603 uInt str = s->strstart - s->insert;
1604 s->ins_h = s->window[str];
1605 UPDATE_HASH(s, s->ins_h, s->window[str + 1]);
initial.commit3d533e02008-07-27 00:38:33 +00001606#if MIN_MATCH != 3
1607 Call UPDATE_HASH() MIN_MATCH-3 more times
1608#endif
jiadong.zhu6c142162016-06-22 21:22:18 -07001609 while (s->insert) {
1610 UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
1611#ifndef FASTEST
1612 s->prev[str & s->w_mask] = s->head[s->ins_h];
1613#endif
1614 s->head[s->ins_h] = (Pos)str;
1615 str++;
1616 s->insert--;
1617 if (s->lookahead + s->insert < MIN_MATCH)
1618 break;
1619 }
initial.commit3d533e02008-07-27 00:38:33 +00001620 }
1621 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1622 * but this is not important since only literal bytes will be emitted.
1623 */
1624
1625 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00001626
1627 /* If the WIN_INIT bytes after the end of the current data have never been
1628 * written, then zero those bytes in order to avoid memory check reports of
1629 * the use of uninitialized (or uninitialised as Julian writes) bytes by
1630 * the longest match routines. Update the high water mark for the next
1631 * time through here. WIN_INIT is set to MAX_MATCH since the longest match
1632 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
1633 */
1634 if (s->high_water < s->window_size) {
1635 ulg curr = s->strstart + (ulg)(s->lookahead);
1636 ulg init;
1637
1638 if (s->high_water < curr) {
1639 /* Previous high water mark below current data -- zero WIN_INIT
1640 * bytes or up to end of window, whichever is less.
1641 */
1642 init = s->window_size - curr;
1643 if (init > WIN_INIT)
1644 init = WIN_INIT;
1645 zmemzero(s->window + curr, (unsigned)init);
1646 s->high_water = curr + init;
1647 }
1648 else if (s->high_water < (ulg)curr + WIN_INIT) {
1649 /* High water mark at or above current data, but below current data
1650 * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
1651 * to end of window, whichever is less.
1652 */
1653 init = (ulg)curr + WIN_INIT - s->high_water;
1654 if (init > s->window_size - s->high_water)
1655 init = s->window_size - s->high_water;
1656 zmemzero(s->window + s->high_water, (unsigned)init);
1657 s->high_water += init;
1658 }
1659 }
jiadong.zhu6c142162016-06-22 21:22:18 -07001660
1661 Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
1662 "not enough room for search");
initial.commit3d533e02008-07-27 00:38:33 +00001663}
1664
1665/* ===========================================================================
1666 * Flush the current block, with given end-of-file flag.
1667 * IN assertion: strstart is set to the end of the current match.
1668 */
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00001669#define FLUSH_BLOCK_ONLY(s, last) { \
initial.commit3d533e02008-07-27 00:38:33 +00001670 _tr_flush_block(s, (s->block_start >= 0L ? \
1671 (charf *)&s->window[(unsigned)s->block_start] : \
1672 (charf *)Z_NULL), \
1673 (ulg)((long)s->strstart - s->block_start), \
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00001674 (last)); \
initial.commit3d533e02008-07-27 00:38:33 +00001675 s->block_start = s->strstart; \
1676 flush_pending(s->strm); \
1677 Tracev((stderr,"[FLUSH]")); \
1678}
1679
1680/* Same but force premature exit if necessary. */
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00001681#define FLUSH_BLOCK(s, last) { \
1682 FLUSH_BLOCK_ONLY(s, last); \
1683 if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
initial.commit3d533e02008-07-27 00:38:33 +00001684}
1685
mark13dc2462017-02-14 22:15:29 -08001686/* Maximum stored block length in deflate format (not including header). */
1687#define MAX_STORED 65535
1688
1689/* Minimum of a and b. */
1690#define MIN(a, b) ((a) > (b) ? (b) : (a))
1691
initial.commit3d533e02008-07-27 00:38:33 +00001692/* ===========================================================================
1693 * Copy without compression as much as possible from the input stream, return
1694 * the current block state.
mark13dc2462017-02-14 22:15:29 -08001695 *
1696 * In case deflateParams() is used to later switch to a non-zero compression
1697 * level, s->matches (otherwise unused when storing) keeps track of the number
1698 * of hash table slides to perform. If s->matches is 1, then one hash table
1699 * slide will be done when switching. If s->matches is 2, the maximum value
1700 * allowed here, then the hash table will be cleared, since two or more slides
1701 * is the same as a clear.
1702 *
1703 * deflate_stored() is written to minimize the number of times an input byte is
1704 * copied. It is most efficient with large input and output buffers, which
1705 * maximizes the opportunites to have a single copy from next_in to next_out.
initial.commit3d533e02008-07-27 00:38:33 +00001706 */
davidben709ed022017-02-02 13:58:58 -08001707local block_state deflate_stored(s, flush)
initial.commit3d533e02008-07-27 00:38:33 +00001708 deflate_state *s;
1709 int flush;
1710{
mark13dc2462017-02-14 22:15:29 -08001711 /* Smallest worthy block size when not flushing or finishing. By default
1712 * this is 32K. This can be as small as 507 bytes for memLevel == 1. For
1713 * large input and output buffers, the stored block size will be larger.
initial.commit3d533e02008-07-27 00:38:33 +00001714 */
mark13dc2462017-02-14 22:15:29 -08001715 unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size);
initial.commit3d533e02008-07-27 00:38:33 +00001716
mark13dc2462017-02-14 22:15:29 -08001717 /* Copy as many min_block or larger stored blocks directly to next_out as
1718 * possible. If flushing, copy the remaining available input to next_out as
1719 * stored blocks, if there is enough space.
1720 */
1721 unsigned len, left, have, last = 0;
1722 unsigned used = s->strm->avail_in;
1723 do {
1724 /* Set len to the maximum size block that we can copy directly with the
1725 * available input data and output space. Set left to how much of that
1726 * would be copied from what's left in the window.
initial.commit3d533e02008-07-27 00:38:33 +00001727 */
mark13dc2462017-02-14 22:15:29 -08001728 len = MAX_STORED; /* maximum deflate stored block length */
1729 have = (s->bi_valid + 42) >> 3; /* number of header bytes */
1730 if (s->strm->avail_out < have) /* need room for header */
1731 break;
1732 /* maximum stored block length that will fit in avail_out: */
1733 have = s->strm->avail_out - have;
1734 left = s->strstart - s->block_start; /* bytes left in window */
1735 if (len > (ulg)left + s->strm->avail_in)
1736 len = left + s->strm->avail_in; /* limit len to the input */
1737 if (len > have)
1738 len = have; /* limit len to the output */
1739
1740 /* If the stored block would be less than min_block in length, or if
1741 * unable to copy all of the available input when flushing, then try
1742 * copying to the window and the pending buffer instead. Also don't
1743 * write an empty block when flushing -- deflate() does that.
1744 */
1745 if (len < min_block && ((len == 0 && flush != Z_FINISH) ||
1746 flush == Z_NO_FLUSH ||
1747 len != left + s->strm->avail_in))
1748 break;
1749
1750 /* Make a dummy stored block in pending to get the header bytes,
1751 * including any pending bits. This also updates the debugging counts.
1752 */
1753 last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0;
1754 _tr_stored_block(s, (char *)0, 0L, last);
1755
1756 /* Replace the lengths in the dummy stored block with len. */
1757 s->pending_buf[s->pending - 4] = len;
1758 s->pending_buf[s->pending - 3] = len >> 8;
1759 s->pending_buf[s->pending - 2] = ~len;
1760 s->pending_buf[s->pending - 1] = ~len >> 8;
1761
1762 /* Write the stored block header bytes. */
1763 flush_pending(s->strm);
1764
1765#ifdef ZLIB_DEBUG
1766 /* Update debugging counts for the data about to be copied. */
1767 s->compressed_len += len << 3;
1768 s->bits_sent += len << 3;
1769#endif
1770
1771 /* Copy uncompressed bytes from the window to next_out. */
1772 if (left) {
1773 if (left > len)
1774 left = len;
1775 zmemcpy(s->strm->next_out, s->window + s->block_start, left);
1776 s->strm->next_out += left;
1777 s->strm->avail_out -= left;
1778 s->strm->total_out += left;
1779 s->block_start += left;
1780 len -= left;
initial.commit3d533e02008-07-27 00:38:33 +00001781 }
mark13dc2462017-02-14 22:15:29 -08001782
1783 /* Copy uncompressed bytes directly from next_in to next_out, updating
1784 * the check value.
1785 */
1786 if (len) {
Daniel Bratell2eb38892018-01-11 01:01:17 +00001787 deflate_read_buf(s->strm, s->strm->next_out, len);
mark13dc2462017-02-14 22:15:29 -08001788 s->strm->next_out += len;
1789 s->strm->avail_out -= len;
1790 s->strm->total_out += len;
1791 }
1792 } while (last == 0);
1793
1794 /* Update the sliding window with the last s->w_size bytes of the copied
1795 * data, or append all of the copied data to the existing window if less
1796 * than s->w_size bytes were copied. Also update the number of bytes to
1797 * insert in the hash tables, in the event that deflateParams() switches to
1798 * a non-zero compression level.
1799 */
1800 used -= s->strm->avail_in; /* number of input bytes directly copied */
1801 if (used) {
1802 /* If any input was used, then no unused input remains in the window,
1803 * therefore s->block_start == s->strstart.
1804 */
1805 if (used >= s->w_size) { /* supplant the previous history */
1806 s->matches = 2; /* clear hash */
1807 zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);
1808 s->strstart = s->w_size;
1809 }
1810 else {
1811 if (s->window_size - s->strstart <= used) {
1812 /* Slide the window down. */
1813 s->strstart -= s->w_size;
1814 zmemcpy(s->window, s->window + s->w_size, s->strstart);
1815 if (s->matches < 2)
1816 s->matches++; /* add a pending slide_hash() */
1817 }
1818 zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);
1819 s->strstart += used;
1820 }
1821 s->block_start = s->strstart;
1822 s->insert += MIN(used, s->w_size - s->insert);
initial.commit3d533e02008-07-27 00:38:33 +00001823 }
mark13dc2462017-02-14 22:15:29 -08001824 if (s->high_water < s->strstart)
1825 s->high_water = s->strstart;
1826
1827 /* If the last block was written to next_out, then done. */
1828 if (last)
jiadong.zhu6c142162016-06-22 21:22:18 -07001829 return finish_done;
mark13dc2462017-02-14 22:15:29 -08001830
1831 /* If flushing and all input has been consumed, then done. */
1832 if (flush != Z_NO_FLUSH && flush != Z_FINISH &&
1833 s->strm->avail_in == 0 && (long)s->strstart == s->block_start)
1834 return block_done;
1835
1836 /* Fill the window with any remaining input. */
1837 have = s->window_size - s->strstart - 1;
1838 if (s->strm->avail_in > have && s->block_start >= (long)s->w_size) {
1839 /* Slide the window down. */
1840 s->block_start -= s->w_size;
1841 s->strstart -= s->w_size;
1842 zmemcpy(s->window, s->window + s->w_size, s->strstart);
1843 if (s->matches < 2)
1844 s->matches++; /* add a pending slide_hash() */
1845 have += s->w_size; /* more space now */
jiadong.zhu6c142162016-06-22 21:22:18 -07001846 }
mark13dc2462017-02-14 22:15:29 -08001847 if (have > s->strm->avail_in)
1848 have = s->strm->avail_in;
1849 if (have) {
Daniel Bratell2eb38892018-01-11 01:01:17 +00001850 deflate_read_buf(s->strm, s->window + s->strstart, have);
mark13dc2462017-02-14 22:15:29 -08001851 s->strstart += have;
1852 }
1853 if (s->high_water < s->strstart)
1854 s->high_water = s->strstart;
1855
1856 /* There was not enough avail_out to write a complete worthy or flushed
1857 * stored block to next_out. Write a stored block to pending instead, if we
1858 * have enough input for a worthy block, or if flushing and there is enough
1859 * room for the remaining input as a stored block in the pending buffer.
1860 */
1861 have = (s->bi_valid + 42) >> 3; /* number of header bytes */
1862 /* maximum stored block length that will fit in pending: */
1863 have = MIN(s->pending_buf_size - have, MAX_STORED);
1864 min_block = MIN(have, s->w_size);
1865 left = s->strstart - s->block_start;
1866 if (left >= min_block ||
1867 ((left || flush == Z_FINISH) && flush != Z_NO_FLUSH &&
1868 s->strm->avail_in == 0 && left <= have)) {
1869 len = MIN(left, have);
1870 last = flush == Z_FINISH && s->strm->avail_in == 0 &&
1871 len == left ? 1 : 0;
1872 _tr_stored_block(s, (charf *)s->window + s->block_start, len, last);
1873 s->block_start += len;
1874 flush_pending(s->strm);
1875 }
1876
1877 /* We've done all we can with the available input and output. */
1878 return last ? finish_started : need_more;
initial.commit3d533e02008-07-27 00:38:33 +00001879}
1880
1881/* ===========================================================================
1882 * Compress as much as possible from the input stream, return the current
1883 * block state.
1884 * This function does not perform lazy evaluation of matches and inserts
1885 * new strings in the dictionary only for unmatched strings or for short
1886 * matches. It is used only for the fast compression options.
1887 */
davidben709ed022017-02-02 13:58:58 -08001888local block_state deflate_fast(s, flush)
initial.commit3d533e02008-07-27 00:38:33 +00001889 deflate_state *s;
1890 int flush;
1891{
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00001892 IPos hash_head; /* head of the hash chain */
initial.commit3d533e02008-07-27 00:38:33 +00001893 int bflush; /* set if current block must be flushed */
1894
1895 for (;;) {
1896 /* Make sure that we always have enough lookahead, except
1897 * at the end of the input file. We need MAX_MATCH bytes
1898 * for the next match, plus MIN_MATCH bytes to insert the
1899 * string following the next match.
1900 */
1901 if (s->lookahead < MIN_LOOKAHEAD) {
1902 fill_window(s);
1903 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1904 return need_more;
1905 }
1906 if (s->lookahead == 0) break; /* flush the current block */
1907 }
1908
1909 /* Insert the string window[strstart .. strstart+2] in the
1910 * dictionary, and set hash_head to the head of the hash chain:
1911 */
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00001912 hash_head = NIL;
initial.commit3d533e02008-07-27 00:38:33 +00001913 if (s->lookahead >= MIN_MATCH) {
robert.bradford10dd6862014-11-05 06:59:34 -08001914 hash_head = insert_string(s, s->strstart);
initial.commit3d533e02008-07-27 00:38:33 +00001915 }
1916
1917 /* Find the longest match, discarding those <= prev_length.
1918 * At this point we have always match_length < MIN_MATCH
1919 */
1920 if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1921 /* To simplify the code, we prevent matches with the string
1922 * of window index 0 (in particular we have to avoid a match
1923 * of the string with itself at the start of the input file).
1924 */
davidben709ed022017-02-02 13:58:58 -08001925 s->match_length = longest_match (s, hash_head);
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00001926 /* longest_match() sets match_start */
initial.commit3d533e02008-07-27 00:38:33 +00001927 }
1928 if (s->match_length >= MIN_MATCH) {
1929 check_match(s, s->strstart, s->match_start, s->match_length);
1930
1931 _tr_tally_dist(s, s->strstart - s->match_start,
1932 s->match_length - MIN_MATCH, bflush);
1933
1934 s->lookahead -= s->match_length;
1935
1936 /* Insert new strings in the hash table only if the match length
1937 * is not too large. This saves time but degrades compression.
1938 */
1939#ifndef FASTEST
1940 if (s->match_length <= s->max_insert_length &&
1941 s->lookahead >= MIN_MATCH) {
1942 s->match_length--; /* string at strstart already in table */
1943 do {
1944 s->strstart++;
robert.bradford10dd6862014-11-05 06:59:34 -08001945 hash_head = insert_string(s, s->strstart);
initial.commit3d533e02008-07-27 00:38:33 +00001946 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1947 * always MIN_MATCH bytes ahead.
1948 */
1949 } while (--s->match_length != 0);
1950 s->strstart++;
1951 } else
1952#endif
1953 {
1954 s->strstart += s->match_length;
1955 s->match_length = 0;
1956 s->ins_h = s->window[s->strstart];
1957 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1958#if MIN_MATCH != 3
1959 Call UPDATE_HASH() MIN_MATCH-3 more times
1960#endif
1961 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1962 * matter since it will be recomputed at next deflate call.
1963 */
1964 }
1965 } else {
1966 /* No match, output a literal byte */
1967 Tracevv((stderr,"%c", s->window[s->strstart]));
1968 _tr_tally_lit (s, s->window[s->strstart], bflush);
1969 s->lookahead--;
1970 s->strstart++;
1971 }
1972 if (bflush) FLUSH_BLOCK(s, 0);
1973 }
jiadong.zhu6c142162016-06-22 21:22:18 -07001974 s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
1975 if (flush == Z_FINISH) {
1976 FLUSH_BLOCK(s, 1);
1977 return finish_done;
1978 }
1979 if (s->last_lit)
1980 FLUSH_BLOCK(s, 0);
1981 return block_done;
initial.commit3d533e02008-07-27 00:38:33 +00001982}
1983
1984#ifndef FASTEST
1985/* ===========================================================================
1986 * Same as above, but achieves better compression. We use a lazy
1987 * evaluation for matches: a match is finally adopted only if there is
1988 * no better match at the next window position.
1989 */
davidben709ed022017-02-02 13:58:58 -08001990local block_state deflate_slow(s, flush)
initial.commit3d533e02008-07-27 00:38:33 +00001991 deflate_state *s;
1992 int flush;
1993{
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00001994 IPos hash_head; /* head of hash chain */
initial.commit3d533e02008-07-27 00:38:33 +00001995 int bflush; /* set if current block must be flushed */
1996
1997 /* Process the input block. */
1998 for (;;) {
1999 /* Make sure that we always have enough lookahead, except
2000 * at the end of the input file. We need MAX_MATCH bytes
2001 * for the next match, plus MIN_MATCH bytes to insert the
2002 * string following the next match.
2003 */
2004 if (s->lookahead < MIN_LOOKAHEAD) {
2005 fill_window(s);
2006 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
2007 return need_more;
2008 }
2009 if (s->lookahead == 0) break; /* flush the current block */
2010 }
2011
2012 /* Insert the string window[strstart .. strstart+2] in the
2013 * dictionary, and set hash_head to the head of the hash chain:
2014 */
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00002015 hash_head = NIL;
initial.commit3d533e02008-07-27 00:38:33 +00002016 if (s->lookahead >= MIN_MATCH) {
robert.bradford10dd6862014-11-05 06:59:34 -08002017 hash_head = insert_string(s, s->strstart);
initial.commit3d533e02008-07-27 00:38:33 +00002018 }
2019
2020 /* Find the longest match, discarding those <= prev_length.
2021 */
2022 s->prev_length = s->match_length, s->prev_match = s->match_start;
2023 s->match_length = MIN_MATCH-1;
2024
davidben709ed022017-02-02 13:58:58 -08002025 if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
2026 s->strstart - hash_head <= MAX_DIST(s)) {
initial.commit3d533e02008-07-27 00:38:33 +00002027 /* To simplify the code, we prevent matches with the string
2028 * of window index 0 (in particular we have to avoid a match
2029 * of the string with itself at the start of the input file).
2030 */
davidben709ed022017-02-02 13:58:58 -08002031 s->match_length = longest_match (s, hash_head);
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00002032 /* longest_match() sets match_start */
initial.commit3d533e02008-07-27 00:38:33 +00002033
2034 if (s->match_length <= 5 && (s->strategy == Z_FILTERED
2035#if TOO_FAR <= 32767
2036 || (s->match_length == MIN_MATCH &&
2037 s->strstart - s->match_start > TOO_FAR)
2038#endif
2039 )) {
2040
2041 /* If prev_match is also MIN_MATCH, match_start is garbage
2042 * but we will ignore the current match anyway.
2043 */
2044 s->match_length = MIN_MATCH-1;
2045 }
2046 }
2047 /* If there was a match at the previous step and the current
2048 * match is not better, output the previous match:
2049 */
davidben709ed022017-02-02 13:58:58 -08002050 if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
initial.commit3d533e02008-07-27 00:38:33 +00002051 uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
2052 /* Do not insert strings in hash table beyond this. */
2053
2054 check_match(s, s->strstart-1, s->prev_match, s->prev_length);
2055
2056 _tr_tally_dist(s, s->strstart -1 - s->prev_match,
2057 s->prev_length - MIN_MATCH, bflush);
2058
2059 /* Insert in hash table all strings up to the end of the match.
2060 * strstart-1 and strstart are already inserted. If there is not
2061 * enough lookahead, the last two strings are not inserted in
2062 * the hash table.
2063 */
2064 s->lookahead -= s->prev_length-1;
2065 s->prev_length -= 2;
2066 do {
2067 if (++s->strstart <= max_insert) {
robert.bradford10dd6862014-11-05 06:59:34 -08002068 hash_head = insert_string(s, s->strstart);
initial.commit3d533e02008-07-27 00:38:33 +00002069 }
2070 } while (--s->prev_length != 0);
2071 s->match_available = 0;
2072 s->match_length = MIN_MATCH-1;
2073 s->strstart++;
2074
2075 if (bflush) FLUSH_BLOCK(s, 0);
2076
2077 } else if (s->match_available) {
2078 /* If there was no match at the previous position, output a
2079 * single literal. If there was a match but the current match
2080 * is longer, truncate the previous match to a single literal.
2081 */
2082 Tracevv((stderr,"%c", s->window[s->strstart-1]));
2083 _tr_tally_lit(s, s->window[s->strstart-1], bflush);
2084 if (bflush) {
2085 FLUSH_BLOCK_ONLY(s, 0);
2086 }
2087 s->strstart++;
2088 s->lookahead--;
2089 if (s->strm->avail_out == 0) return need_more;
2090 } else {
2091 /* There is no previous match to compare with, wait for
2092 * the next step to decide.
2093 */
2094 s->match_available = 1;
2095 s->strstart++;
2096 s->lookahead--;
2097 }
2098 }
2099 Assert (flush != Z_NO_FLUSH, "no flush?");
2100 if (s->match_available) {
2101 Tracevv((stderr,"%c", s->window[s->strstart-1]));
2102 _tr_tally_lit(s, s->window[s->strstart-1], bflush);
2103 s->match_available = 0;
2104 }
jiadong.zhu6c142162016-06-22 21:22:18 -07002105 s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
2106 if (flush == Z_FINISH) {
2107 FLUSH_BLOCK(s, 1);
2108 return finish_done;
2109 }
2110 if (s->last_lit)
2111 FLUSH_BLOCK(s, 0);
2112 return block_done;
initial.commit3d533e02008-07-27 00:38:33 +00002113}
2114#endif /* FASTEST */
2115
initial.commit3d533e02008-07-27 00:38:33 +00002116/* ===========================================================================
2117 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
2118 * one. Do not maintain a hash table. (It will be regenerated if this run of
2119 * deflate switches away from Z_RLE.)
2120 */
2121local block_state deflate_rle(s, flush)
2122 deflate_state *s;
2123 int flush;
2124{
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00002125 int bflush; /* set if current block must be flushed */
2126 uInt prev; /* byte at distance one to match */
2127 Bytef *scan, *strend; /* scan goes up to strend for length of run */
initial.commit3d533e02008-07-27 00:38:33 +00002128
2129 for (;;) {
2130 /* Make sure that we always have enough lookahead, except
2131 * at the end of the input file. We need MAX_MATCH bytes
jiadong.zhu6c142162016-06-22 21:22:18 -07002132 * for the longest run, plus one for the unrolled loop.
initial.commit3d533e02008-07-27 00:38:33 +00002133 */
jiadong.zhu6c142162016-06-22 21:22:18 -07002134 if (s->lookahead <= MAX_MATCH) {
initial.commit3d533e02008-07-27 00:38:33 +00002135 fill_window(s);
jiadong.zhu6c142162016-06-22 21:22:18 -07002136 if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {
initial.commit3d533e02008-07-27 00:38:33 +00002137 return need_more;
2138 }
2139 if (s->lookahead == 0) break; /* flush the current block */
2140 }
2141
2142 /* See how many times the previous byte repeats */
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00002143 s->match_length = 0;
2144 if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
initial.commit3d533e02008-07-27 00:38:33 +00002145 scan = s->window + s->strstart - 1;
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00002146 prev = *scan;
2147 if (prev == *++scan && prev == *++scan && prev == *++scan) {
2148 strend = s->window + s->strstart + MAX_MATCH;
2149 do {
2150 } while (prev == *++scan && prev == *++scan &&
2151 prev == *++scan && prev == *++scan &&
2152 prev == *++scan && prev == *++scan &&
2153 prev == *++scan && prev == *++scan &&
2154 scan < strend);
mark13dc2462017-02-14 22:15:29 -08002155 s->match_length = MAX_MATCH - (uInt)(strend - scan);
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00002156 if (s->match_length > s->lookahead)
2157 s->match_length = s->lookahead;
2158 }
jiadong.zhu6c142162016-06-22 21:22:18 -07002159 Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
initial.commit3d533e02008-07-27 00:38:33 +00002160 }
2161
2162 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00002163 if (s->match_length >= MIN_MATCH) {
2164 check_match(s, s->strstart, s->strstart - 1, s->match_length);
2165
2166 _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
2167
2168 s->lookahead -= s->match_length;
2169 s->strstart += s->match_length;
2170 s->match_length = 0;
initial.commit3d533e02008-07-27 00:38:33 +00002171 } else {
2172 /* No match, output a literal byte */
2173 Tracevv((stderr,"%c", s->window[s->strstart]));
2174 _tr_tally_lit (s, s->window[s->strstart], bflush);
2175 s->lookahead--;
2176 s->strstart++;
2177 }
2178 if (bflush) FLUSH_BLOCK(s, 0);
2179 }
jiadong.zhu6c142162016-06-22 21:22:18 -07002180 s->insert = 0;
2181 if (flush == Z_FINISH) {
2182 FLUSH_BLOCK(s, 1);
2183 return finish_done;
2184 }
2185 if (s->last_lit)
2186 FLUSH_BLOCK(s, 0);
2187 return block_done;
initial.commit3d533e02008-07-27 00:38:33 +00002188}
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00002189
2190/* ===========================================================================
2191 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
2192 * (It will be regenerated if this run of deflate switches away from Huffman.)
2193 */
2194local block_state deflate_huff(s, flush)
2195 deflate_state *s;
2196 int flush;
2197{
2198 int bflush; /* set if current block must be flushed */
2199
2200 for (;;) {
2201 /* Make sure that we have a literal to write. */
2202 if (s->lookahead == 0) {
2203 fill_window(s);
2204 if (s->lookahead == 0) {
2205 if (flush == Z_NO_FLUSH)
2206 return need_more;
2207 break; /* flush the current block */
2208 }
2209 }
2210
2211 /* Output a literal byte */
2212 s->match_length = 0;
2213 Tracevv((stderr,"%c", s->window[s->strstart]));
2214 _tr_tally_lit (s, s->window[s->strstart], bflush);
2215 s->lookahead--;
2216 s->strstart++;
2217 if (bflush) FLUSH_BLOCK(s, 0);
2218 }
jiadong.zhu6c142162016-06-22 21:22:18 -07002219 s->insert = 0;
2220 if (flush == Z_FINISH) {
2221 FLUSH_BLOCK(s, 1);
2222 return finish_done;
2223 }
2224 if (s->last_lit)
2225 FLUSH_BLOCK(s, 0);
2226 return block_done;
hbono@chromium.orgd2dc2092011-12-12 08:48:38 +00002227}
robert.bradford10dd6862014-11-05 06:59:34 -08002228
2229/* Safe to inline this as GCC/clang will use inline asm and Visual Studio will
2230 * use intrinsic without extra params
2231 */
2232local INLINE Pos insert_string_sse(deflate_state *const s, const Pos str)
2233{
2234 Pos ret;
2235 unsigned *ip, val, h = 0;
2236
2237 ip = (unsigned *)&s->window[str];
2238 val = *ip;
2239
2240 if (s->level >= 6)
2241 val &= 0xFFFFFF;
2242
2243/* Windows clang should use inline asm */
2244#if defined(_MSC_VER) && !defined(__clang__)
2245 h = _mm_crc32_u32(h, val);
2246#elif defined(__i386__) || defined(__amd64__)
2247 __asm__ __volatile__ (
2248 "crc32 %1,%0\n\t"
2249 : "+r" (h)
2250 : "r" (val)
2251 );
2252#else
2253 /* This should never happen */
2254 assert(0);
2255#endif
2256
2257 ret = s->head[h & s->hash_mask];
2258 s->head[h & s->hash_mask] = str;
2259 s->prev[str & s->w_mask] = ret;
2260 return ret;
2261}