2 /* deflate.c -- compress data using the deflation algorithm
3 * Copyright (C) 1995-1996 Jean-loup Gailly.
4 * For conditions of distribution and use, see copyright notice in zlib.h
10 * The "deflation" process depends on being able to identify portions
11 * of the input text which are identical to earlier input (within a
12 * sliding window trailing behind the input currently being processed).
14 * The most straightforward technique turns out to be the fastest for
15 * most input files: try all possible matches and select the longest.
16 * The key feature of this algorithm is that insertions into the string
17 * dictionary are very simple and thus fast, and deletions are avoided
18 * completely. Insertions are performed at each input character, whereas
19 * string matches are performed only when the previous match ends. So it
20 * is preferable to spend more time in matches to allow very fast string
21 * insertions and avoid deletions. The matching algorithm for small
22 * strings is inspired from that of Rabin & Karp. A brute force approach
23 * is used to find longer strings when a small match has been found.
24 * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
25 * (by Leonid Broukhis).
26 * A previous version of this file used a more sophisticated algorithm
27 * (by Fiala and Greene) which is guaranteed to run in linear amortized
28 * time, but has a larger average cost, uses more memory and is patented.
29 * However the F&G algorithm may be faster for some highly redundant
30 * files if the parameter max_chain_length (described below) is too large.
34 * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
35 * I found it in 'freeze' written by Leonid Broukhis.
36 * Thanks to many people for bug reports and testing.
40 * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
41 * Available in ftp://ds.internic.net/rfc/rfc1951.txt
43 * A description of the Rabin and Karp algorithm is given in the book
44 * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
46 * Fiala,E.R., and Greene,D.H.
47 * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
51 #include <linux/module.h>
52 #include <linux/zutil.h>
56 /* ===========================================================================
57 * Function prototypes.
60 need_more
, /* block not completed, need more input or more output */
61 block_done
, /* block flush performed */
62 finish_started
, /* finish started, need only more output at next deflate */
63 finish_done
/* finish done, accept no more input or output */
66 typedef block_state (*compress_func
) (deflate_state
*s
, int flush
);
67 /* Compression function. Returns the block state after the call. */
69 static void fill_window (deflate_state
*s
);
70 static block_state
deflate_stored (deflate_state
*s
, int flush
);
71 static block_state
deflate_fast (deflate_state
*s
, int flush
);
72 static block_state
deflate_slow (deflate_state
*s
, int flush
);
73 static void lm_init (deflate_state
*s
);
74 static void putShortMSB (deflate_state
*s
, uInt b
);
75 static void flush_pending (z_streamp strm
);
76 static int read_buf (z_streamp strm
, Byte
*buf
, unsigned size
);
77 static uInt
longest_match (deflate_state
*s
, IPos cur_match
);
80 static void check_match (deflate_state
*s
, IPos start
, IPos match
,
84 /* ===========================================================================
89 /* Tail of hash chains */
94 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
96 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
97 /* Minimum amount of lookahead, except at the end of the input file.
98 * See deflate.c for comments about the MIN_MATCH+1.
101 /* Values for max_lazy_match, good_match and max_chain_length, depending on
102 * the desired pack level (0..9). The values given below have been tuned to
103 * exclude worst case performance for pathological files. Better values may be
104 * found for specific files.
106 typedef struct config_s
{
107 ush good_length
; /* reduce lazy search above this match length */
108 ush max_lazy
; /* do not perform lazy search above this match length */
109 ush nice_length
; /* quit search above this match length */
114 static const config configuration_table
[10] = {
115 /* good lazy nice chain */
116 /* 0 */ {0, 0, 0, 0, deflate_stored
}, /* store only */
117 /* 1 */ {4, 4, 8, 4, deflate_fast
}, /* maximum speed, no lazy matches */
118 /* 2 */ {4, 5, 16, 8, deflate_fast
},
119 /* 3 */ {4, 6, 32, 32, deflate_fast
},
121 /* 4 */ {4, 4, 16, 16, deflate_slow
}, /* lazy matches */
122 /* 5 */ {8, 16, 32, 32, deflate_slow
},
123 /* 6 */ {8, 16, 128, 128, deflate_slow
},
124 /* 7 */ {8, 32, 128, 256, deflate_slow
},
125 /* 8 */ {32, 128, 258, 1024, deflate_slow
},
126 /* 9 */ {32, 258, 258, 4096, deflate_slow
}}; /* maximum compression */
128 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
129 * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
134 /* result of memcmp for equal strings */
136 /* ===========================================================================
137 * Update a hash value with the given input byte
138 * IN assertion: all calls to to UPDATE_HASH are made with consecutive
139 * input characters, so that a running hash key can be computed from the
140 * previous key instead of complete recalculation each time.
142 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
145 /* ===========================================================================
146 * Insert string str in the dictionary and set match_head to the previous head
147 * of the hash chain (the most recent string with same hash key). Return
148 * the previous length of the hash chain.
149 * IN assertion: all calls to to INSERT_STRING are made with consecutive
150 * input characters and the first MIN_MATCH bytes of str are valid
151 * (except for the last MIN_MATCH-1 bytes of the input file).
153 #define INSERT_STRING(s, str, match_head) \
154 (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
155 s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \
156 s->head[s->ins_h] = (Pos)(str))
158 /* ===========================================================================
159 * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
160 * prev[] will be initialized on the fly.
162 #define CLEAR_HASH(s) \
163 s->head[s->hash_size-1] = NIL; \
164 memset((char *)s->head, 0, (unsigned)(s->hash_size-1)*sizeof(*s->head));
166 /* ========================================================================= */
167 int zlib_deflateInit_(
174 return zlib_deflateInit2_(strm
, level
, Z_DEFLATED
, MAX_WBITS
,
176 Z_DEFAULT_STRATEGY
, version
, stream_size
);
177 /* To do: ignore strm->next_in if we use it as window */
180 /* ========================================================================= */
181 int zlib_deflateInit2_(
194 static char* my_version
= ZLIB_VERSION
;
195 deflate_workspace
*mem
;
198 /* We overlay pending_buf and d_buf+l_buf. This works since the average
199 * output size for (length,distance) codes is <= 24 bits.
202 if (version
== NULL
|| version
[0] != my_version
[0] ||
203 stream_size
!= sizeof(z_stream
)) {
204 return Z_VERSION_ERROR
;
206 if (strm
== NULL
) return Z_STREAM_ERROR
;
210 if (level
== Z_DEFAULT_COMPRESSION
) level
= 6;
212 mem
= (deflate_workspace
*) strm
->workspace
;
214 if (windowBits
< 0) { /* undocumented feature: suppress zlib header */
216 windowBits
= -windowBits
;
218 if (memLevel
< 1 || memLevel
> MAX_MEM_LEVEL
|| method
!= Z_DEFLATED
||
219 windowBits
< 9 || windowBits
> 15 || level
< 0 || level
> 9 ||
220 strategy
< 0 || strategy
> Z_HUFFMAN_ONLY
) {
221 return Z_STREAM_ERROR
;
223 s
= (deflate_state
*) &(mem
->deflate_memory
);
224 strm
->state
= (struct internal_state
*)s
;
227 s
->noheader
= noheader
;
228 s
->w_bits
= windowBits
;
229 s
->w_size
= 1 << s
->w_bits
;
230 s
->w_mask
= s
->w_size
- 1;
232 s
->hash_bits
= memLevel
+ 7;
233 s
->hash_size
= 1 << s
->hash_bits
;
234 s
->hash_mask
= s
->hash_size
- 1;
235 s
->hash_shift
= ((s
->hash_bits
+MIN_MATCH
-1)/MIN_MATCH
);
237 s
->window
= (Byte
*) mem
->window_memory
;
238 s
->prev
= (Pos
*) mem
->prev_memory
;
239 s
->head
= (Pos
*) mem
->head_memory
;
241 s
->lit_bufsize
= 1 << (memLevel
+ 6); /* 16K elements by default */
243 overlay
= (ush
*) mem
->overlay_memory
;
244 s
->pending_buf
= (uch
*) overlay
;
245 s
->pending_buf_size
= (ulg
)s
->lit_bufsize
* (sizeof(ush
)+2L);
247 s
->d_buf
= overlay
+ s
->lit_bufsize
/sizeof(ush
);
248 s
->l_buf
= s
->pending_buf
+ (1+sizeof(ush
))*s
->lit_bufsize
;
251 s
->strategy
= strategy
;
252 s
->method
= (Byte
)method
;
254 return zlib_deflateReset(strm
);
257 /* ========================================================================= */
258 int zlib_deflateSetDictionary(
260 const Byte
*dictionary
,
265 uInt length
= dictLength
;
269 if (strm
== NULL
|| strm
->state
== NULL
|| dictionary
== NULL
)
270 return Z_STREAM_ERROR
;
272 s
= (deflate_state
*) strm
->state
;
273 if (s
->status
!= INIT_STATE
) return Z_STREAM_ERROR
;
275 strm
->adler
= zlib_adler32(strm
->adler
, dictionary
, dictLength
);
277 if (length
< MIN_MATCH
) return Z_OK
;
278 if (length
> MAX_DIST(s
)) {
279 length
= MAX_DIST(s
);
280 #ifndef USE_DICT_HEAD
281 dictionary
+= dictLength
- length
; /* use the tail of the dictionary */
284 memcpy((char *)s
->window
, dictionary
, length
);
285 s
->strstart
= length
;
286 s
->block_start
= (long)length
;
288 /* Insert all strings in the hash table (except for the last two bytes).
289 * s->lookahead stays null, so s->ins_h will be recomputed at the next
290 * call of fill_window.
292 s
->ins_h
= s
->window
[0];
293 UPDATE_HASH(s
, s
->ins_h
, s
->window
[1]);
294 for (n
= 0; n
<= length
- MIN_MATCH
; n
++) {
295 INSERT_STRING(s
, n
, hash_head
);
297 if (hash_head
) hash_head
= 0; /* to make compiler happy */
301 /* ========================================================================= */
302 int zlib_deflateReset(
308 if (strm
== NULL
|| strm
->state
== NULL
)
309 return Z_STREAM_ERROR
;
311 strm
->total_in
= strm
->total_out
= 0;
313 strm
->data_type
= Z_UNKNOWN
;
315 s
= (deflate_state
*)strm
->state
;
317 s
->pending_out
= s
->pending_buf
;
319 if (s
->noheader
< 0) {
320 s
->noheader
= 0; /* was set to -1 by deflate(..., Z_FINISH); */
322 s
->status
= s
->noheader
? BUSY_STATE
: INIT_STATE
;
324 s
->last_flush
= Z_NO_FLUSH
;
332 /* ========================================================================= */
333 int zlib_deflateParams(
343 if (strm
== NULL
|| strm
->state
== NULL
) return Z_STREAM_ERROR
;
344 s
= (deflate_state
*) strm
->state
;
346 if (level
== Z_DEFAULT_COMPRESSION
) {
349 if (level
< 0 || level
> 9 || strategy
< 0 || strategy
> Z_HUFFMAN_ONLY
) {
350 return Z_STREAM_ERROR
;
352 func
= configuration_table
[s
->level
].func
;
354 if (func
!= configuration_table
[level
].func
&& strm
->total_in
!= 0) {
355 /* Flush the last buffer: */
356 err
= zlib_deflate(strm
, Z_PARTIAL_FLUSH
);
358 if (s
->level
!= level
) {
360 s
->max_lazy_match
= configuration_table
[level
].max_lazy
;
361 s
->good_match
= configuration_table
[level
].good_length
;
362 s
->nice_match
= configuration_table
[level
].nice_length
;
363 s
->max_chain_length
= configuration_table
[level
].max_chain
;
365 s
->strategy
= strategy
;
369 /* =========================================================================
370 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
371 * IN assertion: the stream state is correct and there is enough room in
374 static void putShortMSB(
379 put_byte(s
, (Byte
)(b
>> 8));
380 put_byte(s
, (Byte
)(b
& 0xff));
383 /* =========================================================================
384 * Flush as much pending output as possible. All deflate() output goes
385 * through this function so some applications may wish to modify it
386 * to avoid allocating a large strm->next_out buffer and copying into it.
387 * (See also read_buf()).
389 static void flush_pending(
393 deflate_state
*s
= (deflate_state
*) strm
->state
;
394 unsigned len
= s
->pending
;
396 if (len
> strm
->avail_out
) len
= strm
->avail_out
;
397 if (len
== 0) return;
399 if (strm
->next_out
!= NULL
) {
400 memcpy(strm
->next_out
, s
->pending_out
, len
);
401 strm
->next_out
+= len
;
403 s
->pending_out
+= len
;
404 strm
->total_out
+= len
;
405 strm
->avail_out
-= len
;
407 if (s
->pending
== 0) {
408 s
->pending_out
= s
->pending_buf
;
412 /* ========================================================================= */
418 int old_flush
; /* value of flush param for previous deflate call */
421 if (strm
== NULL
|| strm
->state
== NULL
||
422 flush
> Z_FINISH
|| flush
< 0) {
423 return Z_STREAM_ERROR
;
425 s
= (deflate_state
*) strm
->state
;
427 if ((strm
->next_in
== NULL
&& strm
->avail_in
!= 0) ||
428 (s
->status
== FINISH_STATE
&& flush
!= Z_FINISH
)) {
429 return Z_STREAM_ERROR
;
431 if (strm
->avail_out
== 0) return Z_BUF_ERROR
;
433 s
->strm
= strm
; /* just in case */
434 old_flush
= s
->last_flush
;
435 s
->last_flush
= flush
;
437 /* Write the zlib header */
438 if (s
->status
== INIT_STATE
) {
440 uInt header
= (Z_DEFLATED
+ ((s
->w_bits
-8)<<4)) << 8;
441 uInt level_flags
= (s
->level
-1) >> 1;
443 if (level_flags
> 3) level_flags
= 3;
444 header
|= (level_flags
<< 6);
445 if (s
->strstart
!= 0) header
|= PRESET_DICT
;
446 header
+= 31 - (header
% 31);
448 s
->status
= BUSY_STATE
;
449 putShortMSB(s
, header
);
451 /* Save the adler32 of the preset dictionary: */
452 if (s
->strstart
!= 0) {
453 putShortMSB(s
, (uInt
)(strm
->adler
>> 16));
454 putShortMSB(s
, (uInt
)(strm
->adler
& 0xffff));
459 /* Flush as much pending output as possible */
460 if (s
->pending
!= 0) {
462 if (strm
->avail_out
== 0) {
463 /* Since avail_out is 0, deflate will be called again with
464 * more output space, but possibly with both pending and
465 * avail_in equal to zero. There won't be anything to do,
466 * but this is not an error situation so make sure we
467 * return OK instead of BUF_ERROR at next call of deflate:
473 /* Make sure there is something to do and avoid duplicate consecutive
474 * flushes. For repeated and useless calls with Z_FINISH, we keep
475 * returning Z_STREAM_END instead of Z_BUFF_ERROR.
477 } else if (strm
->avail_in
== 0 && flush
<= old_flush
&&
482 /* User must not provide more input after the first FINISH: */
483 if (s
->status
== FINISH_STATE
&& strm
->avail_in
!= 0) {
487 /* Start a new block or continue the current one.
489 if (strm
->avail_in
!= 0 || s
->lookahead
!= 0 ||
490 (flush
!= Z_NO_FLUSH
&& s
->status
!= FINISH_STATE
)) {
493 bstate
= (*(configuration_table
[s
->level
].func
))(s
, flush
);
495 if (bstate
== finish_started
|| bstate
== finish_done
) {
496 s
->status
= FINISH_STATE
;
498 if (bstate
== need_more
|| bstate
== finish_started
) {
499 if (strm
->avail_out
== 0) {
500 s
->last_flush
= -1; /* avoid BUF_ERROR next call, see above */
503 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
504 * of deflate should use the same flush parameter to make sure
505 * that the flush is complete. So we don't have to output an
506 * empty block here, this will be done at next call. This also
507 * ensures that for a very small output buffer, we emit at most
511 if (bstate
== block_done
) {
512 if (flush
== Z_PARTIAL_FLUSH
) {
514 } else if (flush
== Z_PACKET_FLUSH
) {
515 /* Output just the 3-bit `stored' block type value,
516 but not a zero length. */
517 zlib_tr_stored_type_only(s
);
518 } else { /* FULL_FLUSH or SYNC_FLUSH */
519 zlib_tr_stored_block(s
, (char*)0, 0L, 0);
520 /* For a full flush, this empty block will be recognized
521 * as a special marker by inflate_sync().
523 if (flush
== Z_FULL_FLUSH
) {
524 CLEAR_HASH(s
); /* forget history */
528 if (strm
->avail_out
== 0) {
529 s
->last_flush
= -1; /* avoid BUF_ERROR at next call, see above */
534 Assert(strm
->avail_out
> 0, "bug2");
536 if (flush
!= Z_FINISH
) return Z_OK
;
537 if (s
->noheader
) return Z_STREAM_END
;
539 /* Write the zlib trailer (adler32) */
540 putShortMSB(s
, (uInt
)(strm
->adler
>> 16));
541 putShortMSB(s
, (uInt
)(strm
->adler
& 0xffff));
543 /* If avail_out is zero, the application will call deflate again
546 s
->noheader
= -1; /* write the trailer only once! */
547 return s
->pending
!= 0 ? Z_OK
: Z_STREAM_END
;
550 /* ========================================================================= */
558 if (strm
== NULL
|| strm
->state
== NULL
) return Z_STREAM_ERROR
;
559 s
= (deflate_state
*) strm
->state
;
562 if (status
!= INIT_STATE
&& status
!= BUSY_STATE
&&
563 status
!= FINISH_STATE
) {
564 return Z_STREAM_ERROR
;
569 return status
== BUSY_STATE
? Z_DATA_ERROR
: Z_OK
;
572 /* =========================================================================
573 * Copy the source state to the destination state.
575 int zlib_deflateCopy (
581 return Z_STREAM_ERROR
;
586 deflate_workspace
*mem
;
589 if (source
== NULL
|| dest
== NULL
|| source
->state
== NULL
) {
590 return Z_STREAM_ERROR
;
593 ss
= (deflate_state
*) source
->state
;
597 mem
= (deflate_workspace
*) dest
->workspace
;
599 ds
= &(mem
->deflate_memory
);
601 dest
->state
= (struct internal_state
*) ds
;
605 ds
->window
= (Byte
*) mem
->window_memory
;
606 ds
->prev
= (Pos
*) mem
->prev_memory
;
607 ds
->head
= (Pos
*) mem
->head_memory
;
608 overlay
= (ush
*) mem
->overlay_memory
;
609 ds
->pending_buf
= (uch
*) overlay
;
611 memcpy(ds
->window
, ss
->window
, ds
->w_size
* 2 * sizeof(Byte
));
612 memcpy(ds
->prev
, ss
->prev
, ds
->w_size
* sizeof(Pos
));
613 memcpy(ds
->head
, ss
->head
, ds
->hash_size
* sizeof(Pos
));
614 memcpy(ds
->pending_buf
, ss
->pending_buf
, (uInt
)ds
->pending_buf_size
);
616 ds
->pending_out
= ds
->pending_buf
+ (ss
->pending_out
- ss
->pending_buf
);
617 ds
->d_buf
= overlay
+ ds
->lit_bufsize
/sizeof(ush
);
618 ds
->l_buf
= ds
->pending_buf
+ (1+sizeof(ush
))*ds
->lit_bufsize
;
620 ds
->l_desc
.dyn_tree
= ds
->dyn_ltree
;
621 ds
->d_desc
.dyn_tree
= ds
->dyn_dtree
;
622 ds
->bl_desc
.dyn_tree
= ds
->bl_tree
;
628 /* ===========================================================================
629 * Read a new buffer from the current input stream, update the adler32
630 * and total number of bytes read. All deflate() input goes through
631 * this function so some applications may wish to modify it to avoid
632 * allocating a large strm->next_in buffer and copying from it.
633 * (See also flush_pending()).
641 unsigned len
= strm
->avail_in
;
643 if (len
> size
) len
= size
;
644 if (len
== 0) return 0;
646 strm
->avail_in
-= len
;
648 if (!((deflate_state
*)(strm
->state
))->noheader
) {
649 strm
->adler
= zlib_adler32(strm
->adler
, strm
->next_in
, len
);
651 memcpy(buf
, strm
->next_in
, len
);
652 strm
->next_in
+= len
;
653 strm
->total_in
+= len
;
658 /* ===========================================================================
659 * Initialize the "longest match" routines for a new zlib stream
665 s
->window_size
= (ulg
)2L*s
->w_size
;
669 /* Set the default configuration parameters:
671 s
->max_lazy_match
= configuration_table
[s
->level
].max_lazy
;
672 s
->good_match
= configuration_table
[s
->level
].good_length
;
673 s
->nice_match
= configuration_table
[s
->level
].nice_length
;
674 s
->max_chain_length
= configuration_table
[s
->level
].max_chain
;
679 s
->match_length
= s
->prev_length
= MIN_MATCH
-1;
680 s
->match_available
= 0;
684 /* ===========================================================================
685 * Set match_start to the longest match starting at the given string and
686 * return its length. Matches shorter or equal to prev_length are discarded,
687 * in which case the result is equal to prev_length and match_start is
689 * IN assertions: cur_match is the head of the hash chain for the current
690 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
691 * OUT assertion: the match length is not greater than s->lookahead.
693 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
694 * match.S. The code will be functionally equivalent.
696 static uInt
longest_match(
698 IPos cur_match
/* current match */
701 unsigned chain_length
= s
->max_chain_length
;/* max hash chain length */
702 register Byte
*scan
= s
->window
+ s
->strstart
; /* current string */
703 register Byte
*match
; /* matched string */
704 register int len
; /* length of current match */
705 int best_len
= s
->prev_length
; /* best match length so far */
706 int nice_match
= s
->nice_match
; /* stop if match long enough */
707 IPos limit
= s
->strstart
> (IPos
)MAX_DIST(s
) ?
708 s
->strstart
- (IPos
)MAX_DIST(s
) : NIL
;
709 /* Stop when cur_match becomes <= limit. To simplify the code,
710 * we prevent matches with the string of window index 0.
713 uInt wmask
= s
->w_mask
;
716 /* Compare two bytes at a time. Note: this is not always beneficial.
717 * Try with and without -DUNALIGNED_OK to check.
719 register Byte
*strend
= s
->window
+ s
->strstart
+ MAX_MATCH
- 1;
720 register ush scan_start
= *(ush
*)scan
;
721 register ush scan_end
= *(ush
*)(scan
+best_len
-1);
723 register Byte
*strend
= s
->window
+ s
->strstart
+ MAX_MATCH
;
724 register Byte scan_end1
= scan
[best_len
-1];
725 register Byte scan_end
= scan
[best_len
];
728 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
729 * It is easy to get rid of this optimization if necessary.
731 Assert(s
->hash_bits
>= 8 && MAX_MATCH
== 258, "Code too clever");
733 /* Do not waste too much time if we already have a good match: */
734 if (s
->prev_length
>= s
->good_match
) {
737 /* Do not look for matches beyond the end of the input. This is necessary
738 * to make deflate deterministic.
740 if ((uInt
)nice_match
> s
->lookahead
) nice_match
= s
->lookahead
;
742 Assert((ulg
)s
->strstart
<= s
->window_size
-MIN_LOOKAHEAD
, "need lookahead");
745 Assert(cur_match
< s
->strstart
, "no future");
746 match
= s
->window
+ cur_match
;
748 /* Skip to next match if the match length cannot increase
749 * or if the match length is less than 2:
751 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
752 /* This code assumes sizeof(unsigned short) == 2. Do not use
753 * UNALIGNED_OK if your compiler uses a different size.
755 if (*(ush
*)(match
+best_len
-1) != scan_end
||
756 *(ush
*)match
!= scan_start
) continue;
758 /* It is not necessary to compare scan[2] and match[2] since they are
759 * always equal when the other bytes match, given that the hash keys
760 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
761 * strstart+3, +5, ... up to strstart+257. We check for insufficient
762 * lookahead only every 4th comparison; the 128th check will be made
763 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
764 * necessary to put more guard bytes at the end of the window, or
765 * to check more often for insufficient lookahead.
767 Assert(scan
[2] == match
[2], "scan[2]?");
770 } while (*(ush
*)(scan
+=2) == *(ush
*)(match
+=2) &&
771 *(ush
*)(scan
+=2) == *(ush
*)(match
+=2) &&
772 *(ush
*)(scan
+=2) == *(ush
*)(match
+=2) &&
773 *(ush
*)(scan
+=2) == *(ush
*)(match
+=2) &&
775 /* The funny "do {}" generates better code on most compilers */
777 /* Here, scan <= window+strstart+257 */
778 Assert(scan
<= s
->window
+(unsigned)(s
->window_size
-1), "wild scan");
779 if (*scan
== *match
) scan
++;
781 len
= (MAX_MATCH
- 1) - (int)(strend
-scan
);
782 scan
= strend
- (MAX_MATCH
-1);
784 #else /* UNALIGNED_OK */
786 if (match
[best_len
] != scan_end
||
787 match
[best_len
-1] != scan_end1
||
789 *++match
!= scan
[1]) continue;
791 /* The check at best_len-1 can be removed because it will be made
792 * again later. (This heuristic is not always a win.)
793 * It is not necessary to compare scan[2] and match[2] since they
794 * are always equal when the other bytes match, given that
795 * the hash keys are equal and that HASH_BITS >= 8.
798 Assert(*scan
== *match
, "match[2]?");
800 /* We check for insufficient lookahead only every 8th comparison;
801 * the 256th check will be made at strstart+258.
804 } while (*++scan
== *++match
&& *++scan
== *++match
&&
805 *++scan
== *++match
&& *++scan
== *++match
&&
806 *++scan
== *++match
&& *++scan
== *++match
&&
807 *++scan
== *++match
&& *++scan
== *++match
&&
810 Assert(scan
<= s
->window
+(unsigned)(s
->window_size
-1), "wild scan");
812 len
= MAX_MATCH
- (int)(strend
- scan
);
813 scan
= strend
- MAX_MATCH
;
815 #endif /* UNALIGNED_OK */
817 if (len
> best_len
) {
818 s
->match_start
= cur_match
;
820 if (len
>= nice_match
) break;
822 scan_end
= *(ush
*)(scan
+best_len
-1);
824 scan_end1
= scan
[best_len
-1];
825 scan_end
= scan
[best_len
];
828 } while ((cur_match
= prev
[cur_match
& wmask
]) > limit
829 && --chain_length
!= 0);
831 if ((uInt
)best_len
<= s
->lookahead
) return best_len
;
836 /* ===========================================================================
837 * Check that the match at match_start is indeed a match.
839 static void check_match(
846 /* check that the match is indeed a match */
847 if (memcmp((char *)s
->window
+ match
,
848 (char *)s
->window
+ start
, length
) != EQUAL
) {
849 fprintf(stderr
, " start %u, match %u, length %d\n",
850 start
, match
, length
);
852 fprintf(stderr
, "%c%c", s
->window
[match
++], s
->window
[start
++]);
853 } while (--length
!= 0);
854 z_error("invalid match");
857 fprintf(stderr
,"\\[%d,%d]", start
-match
, length
);
858 do { putc(s
->window
[start
++], stderr
); } while (--length
!= 0);
862 # define check_match(s, start, match, length)
865 /* ===========================================================================
866 * Fill the window when the lookahead becomes insufficient.
867 * Updates strstart and lookahead.
869 * IN assertion: lookahead < MIN_LOOKAHEAD
870 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
871 * At least one byte has been read, or avail_in == 0; reads are
872 * performed for at least two bytes (required for the zip translate_eol
873 * option -- not supported here).
875 static void fill_window(
879 register unsigned n
, m
;
881 unsigned more
; /* Amount of free space at the end of the window. */
882 uInt wsize
= s
->w_size
;
885 more
= (unsigned)(s
->window_size
-(ulg
)s
->lookahead
-(ulg
)s
->strstart
);
887 /* Deal with !@#$% 64K limit: */
888 if (more
== 0 && s
->strstart
== 0 && s
->lookahead
== 0) {
891 } else if (more
== (unsigned)(-1)) {
892 /* Very unlikely, but possible on 16 bit machine if strstart == 0
893 * and lookahead == 1 (input done one byte at time)
897 /* If the window is almost full and there is insufficient lookahead,
898 * move the upper half to the lower one to make room in the upper half.
900 } else if (s
->strstart
>= wsize
+MAX_DIST(s
)) {
902 memcpy((char *)s
->window
, (char *)s
->window
+wsize
,
904 s
->match_start
-= wsize
;
905 s
->strstart
-= wsize
; /* we now have strstart >= MAX_DIST */
906 s
->block_start
-= (long) wsize
;
908 /* Slide the hash table (could be avoided with 32 bit values
909 at the expense of memory usage). We slide even when level == 0
910 to keep the hash table consistent if we switch back to level > 0
911 later. (Using level 0 permanently is not an optimal usage of
912 zlib, so we don't care about this pathological case.)
918 *p
= (Pos
)(m
>= wsize
? m
-wsize
: NIL
);
925 *p
= (Pos
)(m
>= wsize
? m
-wsize
: NIL
);
926 /* If n is not on any hash chain, prev[n] is garbage but
927 * its value will never be used.
932 if (s
->strm
->avail_in
== 0) return;
934 /* If there was no sliding:
935 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
936 * more == window_size - lookahead - strstart
937 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
938 * => more >= window_size - 2*WSIZE + 2
939 * In the BIG_MEM or MMAP case (not yet supported),
940 * window_size == input_size + MIN_LOOKAHEAD &&
941 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
942 * Otherwise, window_size == 2*WSIZE so more >= 2.
943 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
945 Assert(more
>= 2, "more < 2");
947 n
= read_buf(s
->strm
, s
->window
+ s
->strstart
+ s
->lookahead
, more
);
950 /* Initialize the hash value now that we have some input: */
951 if (s
->lookahead
>= MIN_MATCH
) {
952 s
->ins_h
= s
->window
[s
->strstart
];
953 UPDATE_HASH(s
, s
->ins_h
, s
->window
[s
->strstart
+1]);
955 Call
UPDATE_HASH() MIN_MATCH
-3 more times
958 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
959 * but this is not important since only literal bytes will be emitted.
962 } while (s
->lookahead
< MIN_LOOKAHEAD
&& s
->strm
->avail_in
!= 0);
965 /* ===========================================================================
966 * Flush the current block, with given end-of-file flag.
967 * IN assertion: strstart is set to the end of the current match.
969 #define FLUSH_BLOCK_ONLY(s, eof) { \
970 zlib_tr_flush_block(s, (s->block_start >= 0L ? \
971 (char *)&s->window[(unsigned)s->block_start] : \
973 (ulg)((long)s->strstart - s->block_start), \
975 s->block_start = s->strstart; \
976 flush_pending(s->strm); \
977 Tracev((stderr,"[FLUSH]")); \
980 /* Same but force premature exit if necessary. */
981 #define FLUSH_BLOCK(s, eof) { \
982 FLUSH_BLOCK_ONLY(s, eof); \
983 if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
986 /* ===========================================================================
987 * Copy without compression as much as possible from the input stream, return
988 * the current block state.
989 * This function does not insert new strings in the dictionary since
990 * uncompressible data is probably not useful. This function is used
991 * only for the level=0 compression option.
992 * NOTE: this function should be optimized to avoid extra copying from
993 * window to pending_buf.
995 static block_state
deflate_stored(
1000 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
1001 * to pending_buf_size, and each stored block has a 5 byte header:
1003 ulg max_block_size
= 0xffff;
1006 if (max_block_size
> s
->pending_buf_size
- 5) {
1007 max_block_size
= s
->pending_buf_size
- 5;
1010 /* Copy as much as possible from input to output: */
1012 /* Fill the window as much as possible: */
1013 if (s
->lookahead
<= 1) {
1015 Assert(s
->strstart
< s
->w_size
+MAX_DIST(s
) ||
1016 s
->block_start
>= (long)s
->w_size
, "slide too late");
1019 if (s
->lookahead
== 0 && flush
== Z_NO_FLUSH
) return need_more
;
1021 if (s
->lookahead
== 0) break; /* flush the current block */
1023 Assert(s
->block_start
>= 0L, "block gone");
1025 s
->strstart
+= s
->lookahead
;
1028 /* Emit a stored block if pending_buf will be full: */
1029 max_start
= s
->block_start
+ max_block_size
;
1030 if (s
->strstart
== 0 || (ulg
)s
->strstart
>= max_start
) {
1031 /* strstart == 0 is possible when wraparound on 16-bit machine */
1032 s
->lookahead
= (uInt
)(s
->strstart
- max_start
);
1033 s
->strstart
= (uInt
)max_start
;
1036 /* Flush if we may have to slide, otherwise block_start may become
1037 * negative and the data will be gone:
1039 if (s
->strstart
- (uInt
)s
->block_start
>= MAX_DIST(s
)) {
1043 FLUSH_BLOCK(s
, flush
== Z_FINISH
);
1044 return flush
== Z_FINISH
? finish_done
: block_done
;
1047 /* ===========================================================================
1048 * Compress as much as possible from the input stream, return the current
1050 * This function does not perform lazy evaluation of matches and inserts
1051 * new strings in the dictionary only for unmatched strings or for short
1052 * matches. It is used only for the fast compression options.
1054 static block_state
deflate_fast(
1059 IPos hash_head
= NIL
; /* head of the hash chain */
1060 int bflush
; /* set if current block must be flushed */
1063 /* Make sure that we always have enough lookahead, except
1064 * at the end of the input file. We need MAX_MATCH bytes
1065 * for the next match, plus MIN_MATCH bytes to insert the
1066 * string following the next match.
1068 if (s
->lookahead
< MIN_LOOKAHEAD
) {
1070 if (s
->lookahead
< MIN_LOOKAHEAD
&& flush
== Z_NO_FLUSH
) {
1073 if (s
->lookahead
== 0) break; /* flush the current block */
1076 /* Insert the string window[strstart .. strstart+2] in the
1077 * dictionary, and set hash_head to the head of the hash chain:
1079 if (s
->lookahead
>= MIN_MATCH
) {
1080 INSERT_STRING(s
, s
->strstart
, hash_head
);
1083 /* Find the longest match, discarding those <= prev_length.
1084 * At this point we have always match_length < MIN_MATCH
1086 if (hash_head
!= NIL
&& s
->strstart
- hash_head
<= MAX_DIST(s
)) {
1087 /* To simplify the code, we prevent matches with the string
1088 * of window index 0 (in particular we have to avoid a match
1089 * of the string with itself at the start of the input file).
1091 if (s
->strategy
!= Z_HUFFMAN_ONLY
) {
1092 s
->match_length
= longest_match (s
, hash_head
);
1094 /* longest_match() sets match_start */
1096 if (s
->match_length
>= MIN_MATCH
) {
1097 check_match(s
, s
->strstart
, s
->match_start
, s
->match_length
);
1099 bflush
= zlib_tr_tally(s
, s
->strstart
- s
->match_start
,
1100 s
->match_length
- MIN_MATCH
);
1102 s
->lookahead
-= s
->match_length
;
1104 /* Insert new strings in the hash table only if the match length
1105 * is not too large. This saves time but degrades compression.
1107 if (s
->match_length
<= s
->max_insert_length
&&
1108 s
->lookahead
>= MIN_MATCH
) {
1109 s
->match_length
--; /* string at strstart already in hash table */
1112 INSERT_STRING(s
, s
->strstart
, hash_head
);
1113 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1114 * always MIN_MATCH bytes ahead.
1116 } while (--s
->match_length
!= 0);
1119 s
->strstart
+= s
->match_length
;
1120 s
->match_length
= 0;
1121 s
->ins_h
= s
->window
[s
->strstart
];
1122 UPDATE_HASH(s
, s
->ins_h
, s
->window
[s
->strstart
+1]);
1124 Call
UPDATE_HASH() MIN_MATCH
-3 more times
1126 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
1127 * matter since it will be recomputed at next deflate call.
1131 /* No match, output a literal byte */
1132 Tracevv((stderr
,"%c", s
->window
[s
->strstart
]));
1133 bflush
= zlib_tr_tally (s
, 0, s
->window
[s
->strstart
]);
1137 if (bflush
) FLUSH_BLOCK(s
, 0);
1139 FLUSH_BLOCK(s
, flush
== Z_FINISH
);
1140 return flush
== Z_FINISH
? finish_done
: block_done
;
1143 /* ===========================================================================
1144 * Same as above, but achieves better compression. We use a lazy
1145 * evaluation for matches: a match is finally adopted only if there is
1146 * no better match at the next window position.
1148 static block_state
deflate_slow(
1153 IPos hash_head
= NIL
; /* head of hash chain */
1154 int bflush
; /* set if current block must be flushed */
1156 /* Process the input block. */
1158 /* Make sure that we always have enough lookahead, except
1159 * at the end of the input file. We need MAX_MATCH bytes
1160 * for the next match, plus MIN_MATCH bytes to insert the
1161 * string following the next match.
1163 if (s
->lookahead
< MIN_LOOKAHEAD
) {
1165 if (s
->lookahead
< MIN_LOOKAHEAD
&& flush
== Z_NO_FLUSH
) {
1168 if (s
->lookahead
== 0) break; /* flush the current block */
1171 /* Insert the string window[strstart .. strstart+2] in the
1172 * dictionary, and set hash_head to the head of the hash chain:
1174 if (s
->lookahead
>= MIN_MATCH
) {
1175 INSERT_STRING(s
, s
->strstart
, hash_head
);
1178 /* Find the longest match, discarding those <= prev_length.
1180 s
->prev_length
= s
->match_length
, s
->prev_match
= s
->match_start
;
1181 s
->match_length
= MIN_MATCH
-1;
1183 if (hash_head
!= NIL
&& s
->prev_length
< s
->max_lazy_match
&&
1184 s
->strstart
- hash_head
<= MAX_DIST(s
)) {
1185 /* To simplify the code, we prevent matches with the string
1186 * of window index 0 (in particular we have to avoid a match
1187 * of the string with itself at the start of the input file).
1189 if (s
->strategy
!= Z_HUFFMAN_ONLY
) {
1190 s
->match_length
= longest_match (s
, hash_head
);
1192 /* longest_match() sets match_start */
1194 if (s
->match_length
<= 5 && (s
->strategy
== Z_FILTERED
||
1195 (s
->match_length
== MIN_MATCH
&&
1196 s
->strstart
- s
->match_start
> TOO_FAR
))) {
1198 /* If prev_match is also MIN_MATCH, match_start is garbage
1199 * but we will ignore the current match anyway.
1201 s
->match_length
= MIN_MATCH
-1;
1204 /* If there was a match at the previous step and the current
1205 * match is not better, output the previous match:
1207 if (s
->prev_length
>= MIN_MATCH
&& s
->match_length
<= s
->prev_length
) {
1208 uInt max_insert
= s
->strstart
+ s
->lookahead
- MIN_MATCH
;
1209 /* Do not insert strings in hash table beyond this. */
1211 check_match(s
, s
->strstart
-1, s
->prev_match
, s
->prev_length
);
1213 bflush
= zlib_tr_tally(s
, s
->strstart
-1 - s
->prev_match
,
1214 s
->prev_length
- MIN_MATCH
);
1216 /* Insert in hash table all strings up to the end of the match.
1217 * strstart-1 and strstart are already inserted. If there is not
1218 * enough lookahead, the last two strings are not inserted in
1221 s
->lookahead
-= s
->prev_length
-1;
1222 s
->prev_length
-= 2;
1224 if (++s
->strstart
<= max_insert
) {
1225 INSERT_STRING(s
, s
->strstart
, hash_head
);
1227 } while (--s
->prev_length
!= 0);
1228 s
->match_available
= 0;
1229 s
->match_length
= MIN_MATCH
-1;
1232 if (bflush
) FLUSH_BLOCK(s
, 0);
1234 } else if (s
->match_available
) {
1235 /* If there was no match at the previous position, output a
1236 * single literal. If there was a match but the current match
1237 * is longer, truncate the previous match to a single literal.
1239 Tracevv((stderr
,"%c", s
->window
[s
->strstart
-1]));
1240 if (zlib_tr_tally (s
, 0, s
->window
[s
->strstart
-1])) {
1241 FLUSH_BLOCK_ONLY(s
, 0);
1245 if (s
->strm
->avail_out
== 0) return need_more
;
1247 /* There is no previous match to compare with, wait for
1248 * the next step to decide.
1250 s
->match_available
= 1;
1255 Assert (flush
!= Z_NO_FLUSH
, "no flush?");
1256 if (s
->match_available
) {
1257 Tracevv((stderr
,"%c", s
->window
[s
->strstart
-1]));
1258 zlib_tr_tally (s
, 0, s
->window
[s
->strstart
-1]);
1259 s
->match_available
= 0;
1261 FLUSH_BLOCK(s
, flush
== Z_FINISH
);
1262 return flush
== Z_FINISH
? finish_done
: block_done
;
1265 int zlib_deflate_workspacesize(void)
1267 return sizeof(deflate_workspace
);