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