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