]> git.saurik.com Git - apple/security.git/blob - SecurityServer/MacYarrow/zlib/deflate.c
Security-29.tar.gz
[apple/security.git] / SecurityServer / MacYarrow / zlib / deflate.c
1 /*
2 * Copyright (c) 2000-2001 Apple Computer, Inc. All Rights Reserved.
3 *
4 * The contents of this file constitute Original Code as defined in and are
5 * subject to the Apple Public Source License Version 1.2 (the 'License').
6 * You may not use this file except in compliance with the License. Please obtain
7 * a copy of the License at http://www.apple.com/publicsource and read it before
8 * using this file.
9 *
10 * This Original Code and all software distributed under the License are
11 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS
12 * OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT
13 * LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
14 * PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. Please see the License for the
15 * specific language governing rights and limitations under the License.
16 */
17
18
19 /* deflate.c -- compress data using the deflation algorithm
20 * Copyright (C) 1995-1998 Jean-loup Gailly.
21 * For conditions of distribution and use, see copyright notice in zlib.h
22 */
23
24 /*
25 * ALGORITHM
26 *
27 * The "deflation" process depends on being able to identify portions
28 * of the input text which are identical to earlier input (within a
29 * sliding window trailing behind the input currently being processed).
30 *
31 * The most straightforward technique turns out to be the fastest for
32 * most input files: try all possible matches and select the longest.
33 * The key feature of this algorithm is that insertions into the string
34 * dictionary are very simple and thus fast, and deletions are avoided
35 * completely. Insertions are performed at each input character, whereas
36 * string matches are performed only when the previous match ends. So it
37 * is preferable to spend more time in matches to allow very fast string
38 * insertions and avoid deletions. The matching algorithm for small
39 * strings is inspired from that of Rabin & Karp. A brute force approach
40 * is used to find longer strings when a small match has been found.
41 * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
42 * (by Leonid Broukhis).
43 * A previous version of this file used a more sophisticated algorithm
44 * (by Fiala and Greene) which is guaranteed to run in linear amortized
45 * time, but has a larger average cost, uses more memory and is patented.
46 * However the F&G algorithm may be faster for some highly redundant
47 * files if the parameter max_chain_length (described below) is too large.
48 *
49 * ACKNOWLEDGEMENTS
50 *
51 * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
52 * I found it in 'freeze' written by Leonid Broukhis.
53 * Thanks to many people for bug reports and testing.
54 *
55 * REFERENCES
56 *
57 * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
58 * Available in ftp://ds.internic.net/rfc/rfc1951.txt
59 *
60 * A description of the Rabin and Karp algorithm is given in the book
61 * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
62 *
63 * Fiala,E.R., and Greene,D.H.
64 * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
65 *
66 */
67
68 /* @(#) $Id: deflate.c,v 1.1.1.1 2001/05/18 23:14:03 mb Exp $ */
69
70 #include "deflate.h"
71
72 const char deflate_copyright[] =
73 " deflate 1.1.3 Copyright 1995-1998 Jean-loup Gailly ";
74 /*
75 If you use the zlib library in a product, an acknowledgment is welcome
76 in the documentation of your product. If for some reason you cannot
77 include such an acknowledgment, I would appreciate that you keep this
78 copyright string in the executable of your product.
79 */
80
81 /* ===========================================================================
82 * Function prototypes.
83 */
84 typedef enum {
85 need_more, /* block not completed, need more input or more output */
86 block_done, /* block flush performed */
87 finish_started, /* finish started, need only more output at next deflate */
88 finish_done /* finish done, accept no more input or output */
89 } block_state;
90
91 typedef block_state (*compress_func) OF((deflate_state *s, int flush));
92 /* Compression function. Returns the block state after the call. */
93
94 local void fill_window OF((deflate_state *s));
95 local block_state deflate_stored OF((deflate_state *s, int flush));
96 local block_state deflate_fast OF((deflate_state *s, int flush));
97 local block_state deflate_slow OF((deflate_state *s, int flush));
98 local void lm_init OF((deflate_state *s));
99 local void putShortMSB OF((deflate_state *s, uInt b));
100 local void flush_pending OF((z_streamp strm));
101 local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
102 #ifdef ASMV
103 void match_init OF((void)); /* asm code initialization */
104 uInt longest_match OF((deflate_state *s, IPos cur_match));
105 #else
106 local uInt longest_match OF((deflate_state *s, IPos cur_match));
107 #endif
108
109 #ifdef DEBUG
110 local void check_match OF((deflate_state *s, IPos start, IPos match,
111 int length));
112 #endif
113
114 /* ===========================================================================
115 * Local data
116 */
117
118 #define NIL 0
119 /* Tail of hash chains */
120
121 #ifndef TOO_FAR
122 # define TOO_FAR 4096
123 #endif
124 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
125
126 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
127 /* Minimum amount of lookahead, except at the end of the input file.
128 * See deflate.c for comments about the MIN_MATCH+1.
129 */
130
131 /* Values for max_lazy_match, good_match and max_chain_length, depending on
132 * the desired pack level (0..9). The values given below have been tuned to
133 * exclude worst case performance for pathological files. Better values may be
134 * found for specific files.
135 */
136 typedef struct config_s {
137 ush good_length; /* reduce lazy search above this match length */
138 ush max_lazy; /* do not perform lazy search above this match length */
139 ush nice_length; /* quit search above this match length */
140 ush max_chain;
141 compress_func func;
142 } config;
143
144 local const config configuration_table[10] = {
145 /* good lazy nice chain */
146 /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
147 /* 1 */ {4, 4, 8, 4, deflate_fast}, /* maximum speed, no lazy matches */
148 /* 2 */ {4, 5, 16, 8, deflate_fast},
149 /* 3 */ {4, 6, 32, 32, deflate_fast},
150
151 /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
152 /* 5 */ {8, 16, 32, 32, deflate_slow},
153 /* 6 */ {8, 16, 128, 128, deflate_slow},
154 /* 7 */ {8, 32, 128, 256, deflate_slow},
155 /* 8 */ {32, 128, 258, 1024, deflate_slow},
156 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* maximum compression */
157
158 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
159 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
160 * meaning.
161 */
162
163 #define EQUAL 0
164 /* result of memcmp for equal strings */
165
166 struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
167
168 /* ===========================================================================
169 * Update a hash value with the given input byte
170 * IN assertion: all calls to to UPDATE_HASH are made with consecutive
171 * input characters, so that a running hash key can be computed from the
172 * previous key instead of complete recalculation each time.
173 */
174 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
175
176
177 /* ===========================================================================
178 * Insert string str in the dictionary and set match_head to the previous head
179 * of the hash chain (the most recent string with same hash key). Return
180 * the previous length of the hash chain.
181 * If this file is compiled with -DFASTEST, the compression level is forced
182 * to 1, and no hash chains are maintained.
183 * IN assertion: all calls to to INSERT_STRING are made with consecutive
184 * input characters and the first MIN_MATCH bytes of str are valid
185 * (except for the last MIN_MATCH-1 bytes of the input file).
186 */
187 #ifdef FASTEST
188 #define INSERT_STRING(s, str, match_head) \
189 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
190 match_head = s->head[s->ins_h], \
191 s->head[s->ins_h] = (Pos)(str))
192 #else
193 #define INSERT_STRING(s, str, match_head) \
194 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
195 s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \
196 s->head[s->ins_h] = (Pos)(str))
197 #endif
198
199 /* ===========================================================================
200 * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
201 * prev[] will be initialized on the fly.
202 */
203 #define CLEAR_HASH(s) \
204 s->head[s->hash_size-1] = NIL; \
205 zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
206
207 /* ========================================================================= */
208 int ZEXPORT deflateInit_(strm, level, version, stream_size)
209 z_streamp strm;
210 int level;
211 const char *version;
212 int stream_size;
213 {
214 return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
215 Z_DEFAULT_STRATEGY, version, stream_size);
216 /* To do: ignore strm->next_in if we use it as window */
217 }
218
219 /* ========================================================================= */
220 int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
221 version, stream_size)
222 z_streamp strm;
223 int level;
224 int method;
225 int windowBits;
226 int memLevel;
227 int strategy;
228 const char *version;
229 int stream_size;
230 {
231 deflate_state *s;
232 int noheader = 0;
233 static const char* my_version = ZLIB_VERSION;
234
235 ushf *overlay;
236 /* We overlay pending_buf and d_buf+l_buf. This works since the average
237 * output size for (length,distance) codes is <= 24 bits.
238 */
239
240 if (version == Z_NULL || version[0] != my_version[0] ||
241 stream_size != sizeof(z_stream)) {
242 return Z_VERSION_ERROR;
243 }
244 if (strm == Z_NULL) return Z_STREAM_ERROR;
245
246 strm->msg = Z_NULL;
247 if (strm->zalloc == Z_NULL) {
248 strm->zalloc = zcalloc;
249 strm->opaque = (voidpf)0;
250 }
251 if (strm->zfree == Z_NULL) strm->zfree = zcfree;
252
253 if (level == Z_DEFAULT_COMPRESSION) level = 6;
254 #ifdef FASTEST
255 level = 1;
256 #endif
257
258 if (windowBits < 0) { /* undocumented feature: suppress zlib header */
259 noheader = 1;
260 windowBits = -windowBits;
261 }
262 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
263 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
264 strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
265 return Z_STREAM_ERROR;
266 }
267 s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
268 if (s == Z_NULL) return Z_MEM_ERROR;
269 strm->state = (struct internal_state FAR *)s;
270 s->strm = strm;
271
272 s->noheader = noheader;
273 s->w_bits = windowBits;
274 s->w_size = 1 << s->w_bits;
275 s->w_mask = s->w_size - 1;
276
277 s->hash_bits = memLevel + 7;
278 s->hash_size = 1 << s->hash_bits;
279 s->hash_mask = s->hash_size - 1;
280 s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
281
282 s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
283 s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
284 s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
285
286 s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
287
288 overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
289 s->pending_buf = (uchf *) overlay;
290 s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
291
292 if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
293 s->pending_buf == Z_NULL) {
294 strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
295 deflateEnd (strm);
296 return Z_MEM_ERROR;
297 }
298 s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
299 s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
300
301 s->level = level;
302 s->strategy = strategy;
303 s->method = (Byte)method;
304
305 return deflateReset(strm);
306 }
307
308 /* ========================================================================= */
309 int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
310 z_streamp strm;
311 const Bytef *dictionary;
312 uInt dictLength;
313 {
314 deflate_state *s;
315 uInt length = dictLength;
316 uInt n;
317 IPos hash_head = 0;
318
319 if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
320 strm->state->status != INIT_STATE) return Z_STREAM_ERROR;
321
322 s = strm->state;
323 strm->adler = adler32(strm->adler, dictionary, dictLength);
324
325 if (length < MIN_MATCH) return Z_OK;
326 if (length > MAX_DIST(s)) {
327 length = MAX_DIST(s);
328 #ifndef USE_DICT_HEAD
329 dictionary += dictLength - length; /* use the tail of the dictionary */
330 #endif
331 }
332 zmemcpy(s->window, dictionary, length);
333 s->strstart = length;
334 s->block_start = (long)length;
335
336 /* Insert all strings in the hash table (except for the last two bytes).
337 * s->lookahead stays null, so s->ins_h will be recomputed at the next
338 * call of fill_window.
339 */
340 s->ins_h = s->window[0];
341 UPDATE_HASH(s, s->ins_h, s->window[1]);
342 for (n = 0; n <= length - MIN_MATCH; n++) {
343 INSERT_STRING(s, n, hash_head);
344 }
345 if (hash_head) hash_head = 0; /* to make compiler happy */
346 return Z_OK;
347 }
348
349 /* ========================================================================= */
350 int ZEXPORT deflateReset (strm)
351 z_streamp strm;
352 {
353 deflate_state *s;
354
355 if (strm == Z_NULL || strm->state == Z_NULL ||
356 strm->zalloc == Z_NULL || strm->zfree == Z_NULL) return Z_STREAM_ERROR;
357
358 strm->total_in = strm->total_out = 0;
359 strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
360 strm->data_type = Z_UNKNOWN;
361
362 s = (deflate_state *)strm->state;
363 s->pending = 0;
364 s->pending_out = s->pending_buf;
365
366 if (s->noheader < 0) {
367 s->noheader = 0; /* was set to -1 by deflate(..., Z_FINISH); */
368 }
369 s->status = s->noheader ? BUSY_STATE : INIT_STATE;
370 strm->adler = 1;
371 s->last_flush = Z_NO_FLUSH;
372
373 _tr_init(s);
374 lm_init(s);
375
376 return Z_OK;
377 }
378
379 /* ========================================================================= */
380 int ZEXPORT deflateParams(strm, level, strategy)
381 z_streamp strm;
382 int level;
383 int strategy;
384 {
385 deflate_state *s;
386 compress_func func;
387 int err = Z_OK;
388
389 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
390 s = strm->state;
391
392 if (level == Z_DEFAULT_COMPRESSION) {
393 level = 6;
394 }
395 if (level < 0 || level > 9 || strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
396 return Z_STREAM_ERROR;
397 }
398 func = configuration_table[s->level].func;
399
400 if (func != configuration_table[level].func && strm->total_in != 0) {
401 /* Flush the last buffer: */
402 err = deflate(strm, Z_PARTIAL_FLUSH);
403 }
404 if (s->level != level) {
405 s->level = level;
406 s->max_lazy_match = configuration_table[level].max_lazy;
407 s->good_match = configuration_table[level].good_length;
408 s->nice_match = configuration_table[level].nice_length;
409 s->max_chain_length = configuration_table[level].max_chain;
410 }
411 s->strategy = strategy;
412 return err;
413 }
414
415 /* =========================================================================
416 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
417 * IN assertion: the stream state is correct and there is enough room in
418 * pending_buf.
419 */
420 local void putShortMSB (s, b)
421 deflate_state *s;
422 uInt b;
423 {
424 put_byte(s, (Byte)(b >> 8));
425 put_byte(s, (Byte)(b & 0xff));
426 }
427
428 /* =========================================================================
429 * Flush as much pending output as possible. All deflate() output goes
430 * through this function so some applications may wish to modify it
431 * to avoid allocating a large strm->next_out buffer and copying into it.
432 * (See also read_buf()).
433 */
434 local void flush_pending(strm)
435 z_streamp strm;
436 {
437 unsigned len = strm->state->pending;
438
439 if (len > strm->avail_out) len = strm->avail_out;
440 if (len == 0) return;
441
442 zmemcpy(strm->next_out, strm->state->pending_out, len);
443 strm->next_out += len;
444 strm->state->pending_out += len;
445 strm->total_out += len;
446 strm->avail_out -= len;
447 strm->state->pending -= len;
448 if (strm->state->pending == 0) {
449 strm->state->pending_out = strm->state->pending_buf;
450 }
451 }
452
453 /* ========================================================================= */
454 int ZEXPORT deflate (strm, flush)
455 z_streamp strm;
456 int flush;
457 {
458 int old_flush; /* value of flush param for previous deflate call */
459 deflate_state *s;
460
461 if (strm == Z_NULL || strm->state == Z_NULL ||
462 flush > Z_FINISH || flush < 0) {
463 return Z_STREAM_ERROR;
464 }
465 s = strm->state;
466
467 if (strm->next_out == Z_NULL ||
468 (strm->next_in == Z_NULL && strm->avail_in != 0) ||
469 (s->status == FINISH_STATE && flush != Z_FINISH)) {
470 ERR_RETURN(strm, Z_STREAM_ERROR);
471 }
472 if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
473
474 s->strm = strm; /* just in case */
475 old_flush = s->last_flush;
476 s->last_flush = flush;
477
478 /* Write the zlib header */
479 if (s->status == INIT_STATE) {
480
481 uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
482 uInt level_flags = (s->level-1) >> 1;
483
484 if (level_flags > 3) level_flags = 3;
485 header |= (level_flags << 6);
486 if (s->strstart != 0) header |= PRESET_DICT;
487 header += 31 - (header % 31);
488
489 s->status = BUSY_STATE;
490 putShortMSB(s, header);
491
492 /* Save the adler32 of the preset dictionary: */
493 if (s->strstart != 0) {
494 putShortMSB(s, (uInt)(strm->adler >> 16));
495 putShortMSB(s, (uInt)(strm->adler & 0xffff));
496 }
497 strm->adler = 1L;
498 }
499
500 /* Flush as much pending output as possible */
501 if (s->pending != 0) {
502 flush_pending(strm);
503 if (strm->avail_out == 0) {
504 /* Since avail_out is 0, deflate will be called again with
505 * more output space, but possibly with both pending and
506 * avail_in equal to zero. There won't be anything to do,
507 * but this is not an error situation so make sure we
508 * return OK instead of BUF_ERROR at next call of deflate:
509 */
510 s->last_flush = -1;
511 return Z_OK;
512 }
513
514 /* Make sure there is something to do and avoid duplicate consecutive
515 * flushes. For repeated and useless calls with Z_FINISH, we keep
516 * returning Z_STREAM_END instead of Z_BUFF_ERROR.
517 */
518 } else if (strm->avail_in == 0 && flush <= old_flush &&
519 flush != Z_FINISH) {
520 ERR_RETURN(strm, Z_BUF_ERROR);
521 }
522
523 /* User must not provide more input after the first FINISH: */
524 if (s->status == FINISH_STATE && strm->avail_in != 0) {
525 ERR_RETURN(strm, Z_BUF_ERROR);
526 }
527
528 /* Start a new block or continue the current one.
529 */
530 if (strm->avail_in != 0 || s->lookahead != 0 ||
531 (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
532 block_state bstate;
533
534 bstate = (*(configuration_table[s->level].func))(s, flush);
535
536 if (bstate == finish_started || bstate == finish_done) {
537 s->status = FINISH_STATE;
538 }
539 if (bstate == need_more || bstate == finish_started) {
540 if (strm->avail_out == 0) {
541 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
542 }
543 return Z_OK;
544 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
545 * of deflate should use the same flush parameter to make sure
546 * that the flush is complete. So we don't have to output an
547 * empty block here, this will be done at next call. This also
548 * ensures that for a very small output buffer, we emit at most
549 * one empty block.
550 */
551 }
552 if (bstate == block_done) {
553 if (flush == Z_PARTIAL_FLUSH) {
554 _tr_align(s);
555 } else { /* FULL_FLUSH or SYNC_FLUSH */
556 _tr_stored_block(s, (char*)0, 0L, 0);
557 /* For a full flush, this empty block will be recognized
558 * as a special marker by inflate_sync().
559 */
560 if (flush == Z_FULL_FLUSH) {
561 CLEAR_HASH(s); /* forget history */
562 }
563 }
564 flush_pending(strm);
565 if (strm->avail_out == 0) {
566 s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
567 return Z_OK;
568 }
569 }
570 }
571 Assert(strm->avail_out > 0, "bug2");
572
573 if (flush != Z_FINISH) return Z_OK;
574 if (s->noheader) return Z_STREAM_END;
575
576 /* Write the zlib trailer (adler32) */
577 putShortMSB(s, (uInt)(strm->adler >> 16));
578 putShortMSB(s, (uInt)(strm->adler & 0xffff));
579 flush_pending(strm);
580 /* If avail_out is zero, the application will call deflate again
581 * to flush the rest.
582 */
583 s->noheader = -1; /* write the trailer only once! */
584 return s->pending != 0 ? Z_OK : Z_STREAM_END;
585 }
586
587 /* ========================================================================= */
588 int ZEXPORT deflateEnd (strm)
589 z_streamp strm;
590 {
591 int status;
592
593 if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
594
595 status = strm->state->status;
596 if (status != INIT_STATE && status != BUSY_STATE &&
597 status != FINISH_STATE) {
598 return Z_STREAM_ERROR;
599 }
600
601 /* Deallocate in reverse order of allocations: */
602 TRY_FREE(strm, strm->state->pending_buf);
603 TRY_FREE(strm, strm->state->head);
604 TRY_FREE(strm, strm->state->prev);
605 TRY_FREE(strm, strm->state->window);
606
607 ZFREE(strm, strm->state);
608 strm->state = Z_NULL;
609
610 return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
611 }
612
613 /* =========================================================================
614 * Copy the source state to the destination state.
615 * To simplify the source, this is not supported for 16-bit MSDOS (which
616 * doesn't have enough memory anyway to duplicate compression states).
617 */
618 int ZEXPORT deflateCopy (dest, source)
619 z_streamp dest;
620 z_streamp source;
621 {
622 #ifdef MAXSEG_64K
623 return Z_STREAM_ERROR;
624 #else
625 deflate_state *ds;
626 deflate_state *ss;
627 ushf *overlay;
628
629
630 if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
631 return Z_STREAM_ERROR;
632 }
633
634 ss = source->state;
635
636 *dest = *source;
637
638 ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
639 if (ds == Z_NULL) return Z_MEM_ERROR;
640 dest->state = (struct internal_state FAR *) ds;
641 *ds = *ss;
642 ds->strm = dest;
643
644 ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
645 ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
646 ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
647 overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
648 ds->pending_buf = (uchf *) overlay;
649
650 if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
651 ds->pending_buf == Z_NULL) {
652 deflateEnd (dest);
653 return Z_MEM_ERROR;
654 }
655 /* following zmemcpy do not work for 16-bit MSDOS */
656 zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
657 zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
658 zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
659 zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
660
661 ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
662 ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
663 ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
664
665 ds->l_desc.dyn_tree = ds->dyn_ltree;
666 ds->d_desc.dyn_tree = ds->dyn_dtree;
667 ds->bl_desc.dyn_tree = ds->bl_tree;
668
669 return Z_OK;
670 #endif
671 }
672
673 /* ===========================================================================
674 * Read a new buffer from the current input stream, update the adler32
675 * and total number of bytes read. All deflate() input goes through
676 * this function so some applications may wish to modify it to avoid
677 * allocating a large strm->next_in buffer and copying from it.
678 * (See also flush_pending()).
679 */
680 local int read_buf(strm, buf, size)
681 z_streamp strm;
682 Bytef *buf;
683 unsigned size;
684 {
685 unsigned len = strm->avail_in;
686
687 if (len > size) len = size;
688 if (len == 0) return 0;
689
690 strm->avail_in -= len;
691
692 if (!strm->state->noheader) {
693 strm->adler = adler32(strm->adler, strm->next_in, len);
694 }
695 zmemcpy(buf, strm->next_in, len);
696 strm->next_in += len;
697 strm->total_in += len;
698
699 return (int)len;
700 }
701
702 /* ===========================================================================
703 * Initialize the "longest match" routines for a new zlib stream
704 */
705 local void lm_init (s)
706 deflate_state *s;
707 {
708 s->window_size = (ulg)2L*s->w_size;
709
710 CLEAR_HASH(s);
711
712 /* Set the default configuration parameters:
713 */
714 s->max_lazy_match = configuration_table[s->level].max_lazy;
715 s->good_match = configuration_table[s->level].good_length;
716 s->nice_match = configuration_table[s->level].nice_length;
717 s->max_chain_length = configuration_table[s->level].max_chain;
718
719 s->strstart = 0;
720 s->block_start = 0L;
721 s->lookahead = 0;
722 s->match_length = s->prev_length = MIN_MATCH-1;
723 s->match_available = 0;
724 s->ins_h = 0;
725 #ifdef ASMV
726 match_init(); /* initialize the asm code */
727 #endif
728 }
729
730 /* ===========================================================================
731 * Set match_start to the longest match starting at the given string and
732 * return its length. Matches shorter or equal to prev_length are discarded,
733 * in which case the result is equal to prev_length and match_start is
734 * garbage.
735 * IN assertions: cur_match is the head of the hash chain for the current
736 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
737 * OUT assertion: the match length is not greater than s->lookahead.
738 */
739 #ifndef ASMV
740 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
741 * match.S. The code will be functionally equivalent.
742 */
743 #ifndef FASTEST
744 local uInt longest_match(s, cur_match)
745 deflate_state *s;
746 IPos cur_match; /* current match */
747 {
748 unsigned chain_length = s->max_chain_length;/* max hash chain length */
749 register Bytef *scan = s->window + s->strstart; /* current string */
750 register Bytef *match; /* matched string */
751 register int len; /* length of current match */
752 int best_len = s->prev_length; /* best match length so far */
753 int nice_match = s->nice_match; /* stop if match long enough */
754 IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
755 s->strstart - (IPos)MAX_DIST(s) : NIL;
756 /* Stop when cur_match becomes <= limit. To simplify the code,
757 * we prevent matches with the string of window index 0.
758 */
759 Posf *prev = s->prev;
760 uInt wmask = s->w_mask;
761
762 #ifdef UNALIGNED_OK
763 /* Compare two bytes at a time. Note: this is not always beneficial.
764 * Try with and without -DUNALIGNED_OK to check.
765 */
766 register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
767 register ush scan_start = *(ushf*)scan;
768 register ush scan_end = *(ushf*)(scan+best_len-1);
769 #else
770 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
771 register Byte scan_end1 = scan[best_len-1];
772 register Byte scan_end = scan[best_len];
773 #endif
774
775 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
776 * It is easy to get rid of this optimization if necessary.
777 */
778 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
779
780 /* Do not waste too much time if we already have a good match: */
781 if (s->prev_length >= s->good_match) {
782 chain_length >>= 2;
783 }
784 /* Do not look for matches beyond the end of the input. This is necessary
785 * to make deflate deterministic.
786 */
787 if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
788
789 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
790
791 do {
792 Assert(cur_match < s->strstart, "no future");
793 match = s->window + cur_match;
794
795 /* Skip to next match if the match length cannot increase
796 * or if the match length is less than 2:
797 */
798 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
799 /* This code assumes sizeof(unsigned short) == 2. Do not use
800 * UNALIGNED_OK if your compiler uses a different size.
801 */
802 if (*(ushf*)(match+best_len-1) != scan_end ||
803 *(ushf*)match != scan_start) continue;
804
805 /* It is not necessary to compare scan[2] and match[2] since they are
806 * always equal when the other bytes match, given that the hash keys
807 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
808 * strstart+3, +5, ... up to strstart+257. We check for insufficient
809 * lookahead only every 4th comparison; the 128th check will be made
810 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
811 * necessary to put more guard bytes at the end of the window, or
812 * to check more often for insufficient lookahead.
813 */
814 Assert(scan[2] == match[2], "scan[2]?");
815 scan++, match++;
816 do {
817 } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
818 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
819 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
820 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
821 scan < strend);
822 /* The funny "do {}" generates better code on most compilers */
823
824 /* Here, scan <= window+strstart+257 */
825 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
826 if (*scan == *match) scan++;
827
828 len = (MAX_MATCH - 1) - (int)(strend-scan);
829 scan = strend - (MAX_MATCH-1);
830
831 #else /* UNALIGNED_OK */
832
833 if (match[best_len] != scan_end ||
834 match[best_len-1] != scan_end1 ||
835 *match != *scan ||
836 *++match != scan[1]) continue;
837
838 /* The check at best_len-1 can be removed because it will be made
839 * again later. (This heuristic is not always a win.)
840 * It is not necessary to compare scan[2] and match[2] since they
841 * are always equal when the other bytes match, given that
842 * the hash keys are equal and that HASH_BITS >= 8.
843 */
844 scan += 2, match++;
845 Assert(*scan == *match, "match[2]?");
846
847 /* We check for insufficient lookahead only every 8th comparison;
848 * the 256th check will be made at strstart+258.
849 */
850 do {
851 } while (*++scan == *++match && *++scan == *++match &&
852 *++scan == *++match && *++scan == *++match &&
853 *++scan == *++match && *++scan == *++match &&
854 *++scan == *++match && *++scan == *++match &&
855 scan < strend);
856
857 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
858
859 len = MAX_MATCH - (int)(strend - scan);
860 scan = strend - MAX_MATCH;
861
862 #endif /* UNALIGNED_OK */
863
864 if (len > best_len) {
865 s->match_start = cur_match;
866 best_len = len;
867 if (len >= nice_match) break;
868 #ifdef UNALIGNED_OK
869 scan_end = *(ushf*)(scan+best_len-1);
870 #else
871 scan_end1 = scan[best_len-1];
872 scan_end = scan[best_len];
873 #endif
874 }
875 } while ((cur_match = prev[cur_match & wmask]) > limit
876 && --chain_length != 0);
877
878 if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
879 return s->lookahead;
880 }
881
882 #else /* FASTEST */
883 /* ---------------------------------------------------------------------------
884 * Optimized version for level == 1 only
885 */
886 local uInt longest_match(s, cur_match)
887 deflate_state *s;
888 IPos cur_match; /* current match */
889 {
890 register Bytef *scan = s->window + s->strstart; /* current string */
891 register Bytef *match; /* matched string */
892 register int len; /* length of current match */
893 register Bytef *strend = s->window + s->strstart + MAX_MATCH;
894
895 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
896 * It is easy to get rid of this optimization if necessary.
897 */
898 Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
899
900 Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
901
902 Assert(cur_match < s->strstart, "no future");
903
904 match = s->window + cur_match;
905
906 /* Return failure if the match length is less than 2:
907 */
908 if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
909
910 /* The check at best_len-1 can be removed because it will be made
911 * again later. (This heuristic is not always a win.)
912 * It is not necessary to compare scan[2] and match[2] since they
913 * are always equal when the other bytes match, given that
914 * the hash keys are equal and that HASH_BITS >= 8.
915 */
916 scan += 2, match += 2;
917 Assert(*scan == *match, "match[2]?");
918
919 /* We check for insufficient lookahead only every 8th comparison;
920 * the 256th check will be made at strstart+258.
921 */
922 do {
923 } while (*++scan == *++match && *++scan == *++match &&
924 *++scan == *++match && *++scan == *++match &&
925 *++scan == *++match && *++scan == *++match &&
926 *++scan == *++match && *++scan == *++match &&
927 scan < strend);
928
929 Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
930
931 len = MAX_MATCH - (int)(strend - scan);
932
933 if (len < MIN_MATCH) return MIN_MATCH - 1;
934
935 s->match_start = cur_match;
936 return len <= s->lookahead ? len : s->lookahead;
937 }
938 #endif /* FASTEST */
939 #endif /* ASMV */
940
941 #ifdef DEBUG
942 /* ===========================================================================
943 * Check that the match at match_start is indeed a match.
944 */
945 local void check_match(s, start, match, length)
946 deflate_state *s;
947 IPos start, match;
948 int length;
949 {
950 /* check that the match is indeed a match */
951 if (zmemcmp(s->window + match,
952 s->window + start, length) != EQUAL) {
953 fprintf(stderr, " start %u, match %u, length %d\n",
954 start, match, length);
955 do {
956 fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
957 } while (--length != 0);
958 z_error("invalid match");
959 }
960 if (z_verbose > 1) {
961 fprintf(stderr,"\\[%d,%d]", start-match, length);
962 do { putc(s->window[start++], stderr); } while (--length != 0);
963 }
964 }
965 #else
966 # define check_match(s, start, match, length)
967 #endif
968
969 /* ===========================================================================
970 * Fill the window when the lookahead becomes insufficient.
971 * Updates strstart and lookahead.
972 *
973 * IN assertion: lookahead < MIN_LOOKAHEAD
974 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
975 * At least one byte has been read, or avail_in == 0; reads are
976 * performed for at least two bytes (required for the zip translate_eol
977 * option -- not supported here).
978 */
979 local void fill_window(s)
980 deflate_state *s;
981 {
982 register unsigned n, m;
983 register Posf *p;
984 unsigned more; /* Amount of free space at the end of the window. */
985 uInt wsize = s->w_size;
986
987 do {
988 more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
989
990 /* Deal with !@#$% 64K limit: */
991 if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
992 more = wsize;
993
994 } else if (more == (unsigned)(-1)) {
995 /* Very unlikely, but possible on 16 bit machine if strstart == 0
996 * and lookahead == 1 (input done one byte at time)
997 */
998 more--;
999
1000 /* If the window is almost full and there is insufficient lookahead,
1001 * move the upper half to the lower one to make room in the upper half.
1002 */
1003 } else if (s->strstart >= wsize+MAX_DIST(s)) {
1004
1005 zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
1006 s->match_start -= wsize;
1007 s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
1008 s->block_start -= (long) wsize;
1009
1010 /* Slide the hash table (could be avoided with 32 bit values
1011 at the expense of memory usage). We slide even when level == 0
1012 to keep the hash table consistent if we switch back to level > 0
1013 later. (Using level 0 permanently is not an optimal usage of
1014 zlib, so we don't care about this pathological case.)
1015 */
1016 n = s->hash_size;
1017 p = &s->head[n];
1018 do {
1019 m = *--p;
1020 *p = (Pos)(m >= wsize ? m-wsize : NIL);
1021 } while (--n);
1022
1023 n = wsize;
1024 #ifndef FASTEST
1025 p = &s->prev[n];
1026 do {
1027 m = *--p;
1028 *p = (Pos)(m >= wsize ? m-wsize : NIL);
1029 /* If n is not on any hash chain, prev[n] is garbage but
1030 * its value will never be used.
1031 */
1032 } while (--n);
1033 #endif
1034 more += wsize;
1035 }
1036 if (s->strm->avail_in == 0) return;
1037
1038 /* If there was no sliding:
1039 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
1040 * more == window_size - lookahead - strstart
1041 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
1042 * => more >= window_size - 2*WSIZE + 2
1043 * In the BIG_MEM or MMAP case (not yet supported),
1044 * window_size == input_size + MIN_LOOKAHEAD &&
1045 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
1046 * Otherwise, window_size == 2*WSIZE so more >= 2.
1047 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
1048 */
1049 Assert(more >= 2, "more < 2");
1050
1051 n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
1052 s->lookahead += n;
1053
1054 /* Initialize the hash value now that we have some input: */
1055 if (s->lookahead >= MIN_MATCH) {
1056 s->ins_h = s->window[s->strstart];
1057 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1058 #if MIN_MATCH != 3
1059 Call UPDATE_HASH() MIN_MATCH-3 more times
1060 #endif
1061 }
1062 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
1063 * but this is not important since only literal bytes will be emitted.
1064 */
1065
1066 } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
1067 }
1068
1069 /* ===========================================================================
1070 * Flush the current block, with given end-of-file flag.
1071 * IN assertion: strstart is set to the end of the current match.
1072 */
1073 #define FLUSH_BLOCK_ONLY(s, eof) { \
1074 _tr_flush_block(s, (s->block_start >= 0L ? \
1075 (charf *)&s->window[(unsigned)s->block_start] : \
1076 (charf *)Z_NULL), \
1077 (ulg)((long)s->strstart - s->block_start), \
1078 (eof)); \
1079 s->block_start = s->strstart; \
1080 flush_pending(s->strm); \
1081 Tracev((stderr,"[FLUSH]")); \
1082 }
1083
1084 /* Same but force premature exit if necessary. */
1085 #define FLUSH_BLOCK(s, eof) { \
1086 FLUSH_BLOCK_ONLY(s, eof); \
1087 if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
1088 }
1089
1090 /* ===========================================================================
1091 * Copy without compression as much as possible from the input stream, return
1092 * the current block state.
1093 * This function does not insert new strings in the dictionary since
1094 * uncompressible data is probably not useful. This function is used
1095 * only for the level=0 compression option.
1096 * NOTE: this function should be optimized to avoid extra copying from
1097 * window to pending_buf.
1098 */
1099 local block_state deflate_stored(s, flush)
1100 deflate_state *s;
1101 int flush;
1102 {
1103 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
1104 * to pending_buf_size, and each stored block has a 5 byte header:
1105 */
1106 ulg max_block_size = 0xffff;
1107 ulg max_start;
1108
1109 if (max_block_size > s->pending_buf_size - 5) {
1110 max_block_size = s->pending_buf_size - 5;
1111 }
1112
1113 /* Copy as much as possible from input to output: */
1114 for (;;) {
1115 /* Fill the window as much as possible: */
1116 if (s->lookahead <= 1) {
1117
1118 Assert(s->strstart < s->w_size+MAX_DIST(s) ||
1119 s->block_start >= (long)s->w_size, "slide too late");
1120
1121 fill_window(s);
1122 if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
1123
1124 if (s->lookahead == 0) break; /* flush the current block */
1125 }
1126 Assert(s->block_start >= 0L, "block gone");
1127
1128 s->strstart += s->lookahead;
1129 s->lookahead = 0;
1130
1131 /* Emit a stored block if pending_buf will be full: */
1132 max_start = s->block_start + max_block_size;
1133 if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
1134 /* strstart == 0 is possible when wraparound on 16-bit machine */
1135 s->lookahead = (uInt)(s->strstart - max_start);
1136 s->strstart = (uInt)max_start;
1137 FLUSH_BLOCK(s, 0);
1138 }
1139 /* Flush if we may have to slide, otherwise block_start may become
1140 * negative and the data will be gone:
1141 */
1142 if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
1143 FLUSH_BLOCK(s, 0);
1144 }
1145 }
1146 FLUSH_BLOCK(s, flush == Z_FINISH);
1147 return flush == Z_FINISH ? finish_done : block_done;
1148 }
1149
1150 /* ===========================================================================
1151 * Compress as much as possible from the input stream, return the current
1152 * block state.
1153 * This function does not perform lazy evaluation of matches and inserts
1154 * new strings in the dictionary only for unmatched strings or for short
1155 * matches. It is used only for the fast compression options.
1156 */
1157 local block_state deflate_fast(s, flush)
1158 deflate_state *s;
1159 int flush;
1160 {
1161 IPos hash_head = NIL; /* head of the hash chain */
1162 int bflush; /* set if current block must be flushed */
1163
1164 for (;;) {
1165 /* Make sure that we always have enough lookahead, except
1166 * at the end of the input file. We need MAX_MATCH bytes
1167 * for the next match, plus MIN_MATCH bytes to insert the
1168 * string following the next match.
1169 */
1170 if (s->lookahead < MIN_LOOKAHEAD) {
1171 fill_window(s);
1172 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1173 return need_more;
1174 }
1175 if (s->lookahead == 0) break; /* flush the current block */
1176 }
1177
1178 /* Insert the string window[strstart .. strstart+2] in the
1179 * dictionary, and set hash_head to the head of the hash chain:
1180 */
1181 if (s->lookahead >= MIN_MATCH) {
1182 INSERT_STRING(s, s->strstart, hash_head);
1183 }
1184
1185 /* Find the longest match, discarding those <= prev_length.
1186 * At this point we have always match_length < MIN_MATCH
1187 */
1188 if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
1189 /* To simplify the code, we prevent matches with the string
1190 * of window index 0 (in particular we have to avoid a match
1191 * of the string with itself at the start of the input file).
1192 */
1193 if (s->strategy != Z_HUFFMAN_ONLY) {
1194 s->match_length = longest_match (s, hash_head);
1195 }
1196 /* longest_match() sets match_start */
1197 }
1198 if (s->match_length >= MIN_MATCH) {
1199 check_match(s, s->strstart, s->match_start, s->match_length);
1200
1201 _tr_tally_dist(s, s->strstart - s->match_start,
1202 s->match_length - MIN_MATCH, bflush);
1203
1204 s->lookahead -= s->match_length;
1205
1206 /* Insert new strings in the hash table only if the match length
1207 * is not too large. This saves time but degrades compression.
1208 */
1209 #ifndef FASTEST
1210 if (s->match_length <= s->max_insert_length &&
1211 s->lookahead >= MIN_MATCH) {
1212 s->match_length--; /* string at strstart already in hash table */
1213 do {
1214 s->strstart++;
1215 INSERT_STRING(s, s->strstart, hash_head);
1216 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1217 * always MIN_MATCH bytes ahead.
1218 */
1219 } while (--s->match_length != 0);
1220 s->strstart++;
1221 } else
1222 #endif
1223 {
1224 s->strstart += s->match_length;
1225 s->match_length = 0;
1226 s->ins_h = s->window[s->strstart];
1227 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
1228 #if MIN_MATCH != 3
1229 Call UPDATE_HASH() MIN_MATCH-3 more times
1230 #endif
1231 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1232 * matter since it will be recomputed at next deflate call.
1233 */
1234 }
1235 } else {
1236 /* No match, output a literal byte */
1237 Tracevv((stderr,"%c", s->window[s->strstart]));
1238 _tr_tally_lit (s, s->window[s->strstart], bflush);
1239 s->lookahead--;
1240 s->strstart++;
1241 }
1242 if (bflush) FLUSH_BLOCK(s, 0);
1243 }
1244 FLUSH_BLOCK(s, flush == Z_FINISH);
1245 return flush == Z_FINISH ? finish_done : block_done;
1246 }
1247
1248 /* ===========================================================================
1249 * Same as above, but achieves better compression. We use a lazy
1250 * evaluation for matches: a match is finally adopted only if there is
1251 * no better match at the next window position.
1252 */
1253 local block_state deflate_slow(s, flush)
1254 deflate_state *s;
1255 int flush;
1256 {
1257 IPos hash_head = NIL; /* head of hash chain */
1258 int bflush; /* set if current block must be flushed */
1259
1260 /* Process the input block. */
1261 for (;;) {
1262 /* Make sure that we always have enough lookahead, except
1263 * at the end of the input file. We need MAX_MATCH bytes
1264 * for the next match, plus MIN_MATCH bytes to insert the
1265 * string following the next match.
1266 */
1267 if (s->lookahead < MIN_LOOKAHEAD) {
1268 fill_window(s);
1269 if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
1270 return need_more;
1271 }
1272 if (s->lookahead == 0) break; /* flush the current block */
1273 }
1274
1275 /* Insert the string window[strstart .. strstart+2] in the
1276 * dictionary, and set hash_head to the head of the hash chain:
1277 */
1278 if (s->lookahead >= MIN_MATCH) {
1279 INSERT_STRING(s, s->strstart, hash_head);
1280 }
1281
1282 /* Find the longest match, discarding those <= prev_length.
1283 */
1284 s->prev_length = s->match_length, s->prev_match = s->match_start;
1285 s->match_length = MIN_MATCH-1;
1286
1287 if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
1288 s->strstart - hash_head <= MAX_DIST(s)) {
1289 /* To simplify the code, we prevent matches with the string
1290 * of window index 0 (in particular we have to avoid a match
1291 * of the string with itself at the start of the input file).
1292 */
1293 if (s->strategy != Z_HUFFMAN_ONLY) {
1294 s->match_length = longest_match (s, hash_head);
1295 }
1296 /* longest_match() sets match_start */
1297
1298 if (s->match_length <= 5 && (s->strategy == Z_FILTERED ||
1299 (s->match_length == MIN_MATCH &&
1300 s->strstart - s->match_start > TOO_FAR))) {
1301
1302 /* If prev_match is also MIN_MATCH, match_start is garbage
1303 * but we will ignore the current match anyway.
1304 */
1305 s->match_length = MIN_MATCH-1;
1306 }
1307 }
1308 /* If there was a match at the previous step and the current
1309 * match is not better, output the previous match:
1310 */
1311 if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
1312 uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
1313 /* Do not insert strings in hash table beyond this. */
1314
1315 check_match(s, s->strstart-1, s->prev_match, s->prev_length);
1316
1317 _tr_tally_dist(s, s->strstart -1 - s->prev_match,
1318 s->prev_length - MIN_MATCH, bflush);
1319
1320 /* Insert in hash table all strings up to the end of the match.
1321 * strstart-1 and strstart are already inserted. If there is not
1322 * enough lookahead, the last two strings are not inserted in
1323 * the hash table.
1324 */
1325 s->lookahead -= s->prev_length-1;
1326 s->prev_length -= 2;
1327 do {
1328 if (++s->strstart <= max_insert) {
1329 INSERT_STRING(s, s->strstart, hash_head);
1330 }
1331 } while (--s->prev_length != 0);
1332 s->match_available = 0;
1333 s->match_length = MIN_MATCH-1;
1334 s->strstart++;
1335
1336 if (bflush) FLUSH_BLOCK(s, 0);
1337
1338 } else if (s->match_available) {
1339 /* If there was no match at the previous position, output a
1340 * single literal. If there was a match but the current match
1341 * is longer, truncate the previous match to a single literal.
1342 */
1343 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1344 _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1345 if (bflush) {
1346 FLUSH_BLOCK_ONLY(s, 0);
1347 }
1348 s->strstart++;
1349 s->lookahead--;
1350 if (s->strm->avail_out == 0) return need_more;
1351 } else {
1352 /* There is no previous match to compare with, wait for
1353 * the next step to decide.
1354 */
1355 s->match_available = 1;
1356 s->strstart++;
1357 s->lookahead--;
1358 }
1359 }
1360 Assert (flush != Z_NO_FLUSH, "no flush?");
1361 if (s->match_available) {
1362 Tracevv((stderr,"%c", s->window[s->strstart-1]));
1363 _tr_tally_lit(s, s->window[s->strstart-1], bflush);
1364 s->match_available = 0;
1365 }
1366 FLUSH_BLOCK(s, flush == Z_FINISH);
1367 return flush == Z_FINISH ? finish_done : block_done;
1368 }