/src/zlib/deflate.c

https://bitbucket.org/cabalistic/ogredeps/ · C · 1967 lines · 1317 code · 205 blank · 445 comment · 540 complexity · cd7826278ce9d9d9ed5abdefef50c3e2 MD5 · raw file

Large files are truncated click here to view the full file

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