PageRenderTime 68ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/src/zlib/deflate.c

https://bitbucket.org/cabalistic/ogredeps/
C | 1967 lines | 1317 code | 205 blank | 445 comment | 540 complexity | cd7826278ce9d9d9ed5abdefef50c3e2 MD5 | raw file
Possible License(s): LGPL-3.0, BSD-3-Clause, CPL-1.0, Unlicense, GPL-2.0, GPL-3.0, LGPL-2.0, MPL-2.0-no-copyleft-exception, BSD-2-Clause, LGPL-2.1
  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 == 0 && s->lookahead == 0) {
  1251. more = wsize;
  1252. } else if (more == (unsigned)(-1)) {
  1253. /* Very unlikely, but possible on 16 bit machine if
  1254. * strstart == 0 && lookahead == 1 (input done a byte at time)
  1255. */
  1256. more--;
  1257. }
  1258. }
  1259. /* If the window is almost full and there is insufficient lookahead,
  1260. * move the upper half to the lower one to make room in the upper half.
  1261. */
  1262. if (s->strstart >= wsize+MAX_DIST(s)) {
  1263. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  1264. s->match_start -= wsize;
  1265. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  1266. s->block_start -= (long) wsize;
  1267. /* Slide the hash table (could be avoided with 32 bit values
  1268. at the expense of memory usage). We slide even when level == 0
  1269. to keep the hash table consistent if we switch back to level > 0
  1270. later. (Using level 0 permanently is not an optimal usage of
  1271. zlib, so we don't care about this pathological case.)
  1272. */
  1273. n = s->hash_size;
  1274. p = &s->head[n];
  1275. do {
  1276. m = *--p;
  1277. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  1278. } while (--n);
  1279. n = wsize;
  1280. #ifndef FASTEST
  1281. p = &s->prev[n];
  1282. do {
  1283. m = *--p;
  1284. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  1285. /* If n is not on any hash chain, prev[n] is garbage but
  1286. * its value will never be used.
  1287. */
  1288. } while (--n);
  1289. #endif
  1290. more += wsize;
  1291. }
  1292. if (s->strm->avail_in == 0) break;
  1293. /* If there was no sliding:
  1294. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  1295. * more == window_size - lookahead - strstart
  1296. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  1297. * => more >= window_size - 2*WSIZE + 2
  1298. * In the BIG_MEM or MMAP case (not yet supported),
  1299. * window_size == input_size + MIN_LOOKAHEAD &&
  1300. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  1301. * Otherwise, window_size == 2*WSIZE so more >= 2.
  1302. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  1303. */
  1304. Assert(more >= 2, "more < 2");
  1305. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  1306. s->lookahead += n;
  1307. /* Initialize the hash value now that we have some input: */
  1308. if (s->lookahead + s->insert >= MIN_MATCH) {
  1309. uInt str = s->strstart - s->insert;
  1310. s->ins_h = s->window[str];
  1311. UPDATE_HASH(s, s->ins_h, s->window[str + 1]);
  1312. #if MIN_MATCH != 3
  1313. Call UPDATE_HASH() MIN_MATCH-3 more times
  1314. #endif
  1315. while (s->insert) {
  1316. UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
  1317. #ifndef FASTEST
  1318. s->prev[str & s->w_mask] = s->head[s->ins_h];
  1319. #endif
  1320. s->head[s->ins_h] = (Pos)str;
  1321. str++;
  1322. s->insert--;
  1323. if (s->lookahead + s->insert < MIN_MATCH)
  1324. break;
  1325. }
  1326. }
  1327. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  1328. * but this is not important since only literal bytes will be emitted.
  1329. */
  1330. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  1331. /* If the WIN_INIT bytes after the end of the current data have never been
  1332. * written, then zero those bytes in order to avoid memory check reports of
  1333. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  1334. * the longest match routines. Update the high water mark for the next
  1335. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  1336. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  1337. */
  1338. if (s->high_water < s->window_size) {
  1339. ulg curr = s->strstart + (ulg)(s->lookahead);
  1340. ulg init;
  1341. if (s->high_water < curr) {
  1342. /* Previous high water mark below current data -- zero WIN_INIT
  1343. * bytes or up to end of window, whichever is less.
  1344. */
  1345. init = s->window_size - curr;
  1346. if (init > WIN_INIT)
  1347. init = WIN_INIT;
  1348. zmemzero(s->window + curr, (unsigned)init);
  1349. s->high_water = curr + init;
  1350. }
  1351. else if (s->high_water < (ulg)curr + WIN_INIT) {
  1352. /* High water mark at or above current data, but below current data
  1353. * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  1354. * to end of window, whichever is less.
  1355. */
  1356. init = (ulg)curr + WIN_INIT - s->high_water;
  1357. if (init > s->window_size - s->high_water)
  1358. init = s->window_size - s->high_water;
  1359. zmemzero(s->window + s->high_water, (unsigned)init);
  1360. s->high_water += init;
  1361. }
  1362. }
  1363. Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  1364. "not enough room for search");
  1365. }
  1366. /* ===========================================================================
  1367. * Flush the current block, with given end-of-file flag.
  1368. * IN assertion: strstart is set to the end of the current match.
  1369. */
  1370. #define FLUSH_BLOCK_ONLY(s, last) { \
  1371. _tr_flush_block(s, (s->block_start >= 0L ? \
  1372. (charf *)&s->window[(unsigned)s->block_start] : \
  1373. (charf *)Z_NULL), \
  1374. (ulg)((long)s->strstart - s->block_start), \
  1375. (last)); \
  1376. s->block_start = s->strstart; \
  1377. flush_pending(s->strm); \
  1378. Tracev((stderr,"[FLUSH]")); \
  1379. }
  1380. /* Same but force premature exit if necessary. */
  1381. #define FLUSH_BLOCK(s, last) { \
  1382. FLUSH_BLOCK_ONLY(s, last); \
  1383. if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
  1384. }
  1385. /* ===========================================================================
  1386. * Copy without compression as much as possible from the input stream, return
  1387. * the current block state.
  1388. * This function does not insert new strings in the dictionary since
  1389. * uncompressible data is probably not useful. This function is used
  1390. * only for the level=0 compression option.
  1391. * NOTE: this function should be optimized to avoid extra copying from
  1392. * window to pending_buf.
  1393. */
  1394. local block_state deflate_stored(s, flush)
  1395. deflate_state *s;
  1396. int flush;
  1397. {
  1398. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  1399. * to pending_buf_size, and each stored block has a 5 byte header:
  1400. */
  1401. ulg max_block_size = 0xffff;
  1402. ulg max_start;
  1403. if (max_block_size > s->pending_buf_size - 5) {
  1404. max_block_size = s->pending_buf_size - 5;
  1405. }
  1406. /* Copy as much as possible from input to output: */
  1407. for (;;) {
  1408. /* Fill the window as much as possible: */
  1409. if (s->lookahead <= 1) {
  1410. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  1411. s->block_start >= (long)s->w_size, "slide too late");
  1412. fill_window(s);
  1413. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  1414. if (s->lookahead == 0) break; /* flush the current block */
  1415. }
  1416. Assert(s->block_start >= 0L, "block gone");
  1417. s->strstart += s->lookahead;
  1418. s->lookahead = 0;
  1419. /* Emit a stored block if pending_buf will be full: */
  1420. max_start = s->block_start + max_block_size;
  1421. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  1422. /* strstart == 0 is possible when wraparound on 16-bit machine */
  1423. s->lookahead = (uInt)(s->strstart - max_start);
  1424. s->strstart = (uInt)max_start;
  1425. FLUSH_BLOCK(s, 0);
  1426. }
  1427. /* Flush if we may have to slide, otherwise block_start may become
  1428. * negative and the data will be gone:
  1429. */
  1430. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  1431. FLUSH_BLOCK(s, 0);
  1432. }
  1433. }
  1434. s->insert = 0;
  1435. if (flush == Z_FINISH) {
  1436. FLUSH_BLOCK(s, 1);
  1437. return finish_done;
  1438. }
  1439. if ((long)s->strstart > s->block_start)
  1440. FLUSH_BLOCK(s, 0);
  1441. return block_done;
  1442. }
  1443. /* ===========================================================================
  1444. * Compress as much as possible from the input stream, return the current
  1445. * block state.
  1446. * This function does not perform lazy evaluation of matches and inserts
  1447. * new strings in the dictionary only for unmatched strings or for short
  1448. * matches. It is used only for the fast compression options.
  1449. */
  1450. local block_state deflate_fast(s, flush)
  1451. deflate_state *s;
  1452. int flush;
  1453. {
  1454. IPos hash_head; /* head of the hash chain */
  1455. int bflush; /* set if current block must be flushed */
  1456. for (;;) {
  1457. /* Make sure that we always have enough lookahead, except
  1458. * at the end of the input file. We need MAX_MATCH bytes
  1459. * for the next match, plus MIN_MATCH bytes to insert the
  1460. * string following the next match.
  1461. */
  1462. if (s->lookahead < MIN_LOOKAHEAD) {
  1463. fill_window(s);
  1464. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  1465. return need_more;
  1466. }
  1467. if (s->lookahead == 0) break; /* flush the current block */
  1468. }
  1469. /* Insert the string window[strstart .. strstart+2] in the
  1470. * dictionary, and set hash_head to the head of the hash chain:
  1471. */
  1472. hash_head = NIL;
  1473. if (s->lookahead >= MIN_MATCH) {
  1474. INSERT_STRING(s, s->strstart, hash_head);
  1475. }
  1476. /* Find the longest match, discarding those <= prev_length.
  1477. * At this point we have always match_length < MIN_MATCH
  1478. */
  1479. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  1480. /* To simplify the code, we prevent matches with the string
  1481. * of window index 0 (in particular we have to avoid a match
  1482. * of the string with itself at the start of the input file).
  1483. */
  1484. s->match_length = longest_match (s, hash_head);
  1485. /* longest_match() sets match_start */
  1486. }
  1487. if (s->match_length >= MIN_MATCH) {
  1488. check_match(s, s->strstart, s->match_start, s->match_length);
  1489. _tr_tally_dist(s, s->strstart - s->match_start,
  1490. s->match_length - MIN_MATCH, bflush);
  1491. s->lookahead -= s->match_length;
  1492. /* Insert new strings in the hash table only if the match length
  1493. * is not too large. This saves time but degrades compression.
  1494. */
  1495. #ifndef FASTEST
  1496. if (s->match_length <= s->max_insert_length &&
  1497. s->lookahead >= MIN_MATCH) {
  1498. s->match_length--; /* string at strstart already in table */
  1499. do {
  1500. s->strstart++;
  1501. INSERT_STRING(s, s->strstart, hash_head);
  1502. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  1503. * always MIN_MATCH bytes ahead.
  1504. */
  1505. } while (--s->match_length != 0);
  1506. s->strstart++;
  1507. } else
  1508. #endif
  1509. {
  1510. s->strstart += s->match_length;
  1511. s->match_length = 0;
  1512. s->ins_h = s->window[s->strstart];
  1513. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  1514. #if MIN_MATCH != 3
  1515. Call UPDATE_HASH() MIN_MATCH-3 more times
  1516. #endif
  1517. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  1518. * matter since it will be recomputed at next deflate call.
  1519. */
  1520. }
  1521. } else {
  1522. /* No match, output a literal byte */
  1523. Tracevv((stderr,"%c", s->window[s->strstart]));
  1524. _tr_tally_lit (s, s->window[s->strstart], bflush);
  1525. s->lookahead--;
  1526. s->strstart++;
  1527. }
  1528. if (bflush) FLUSH_BLOCK(s, 0);
  1529. }
  1530. s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
  1531. if (flush == Z_FINISH) {
  1532. FLUSH_BLOCK(s, 1);
  1533. return finish_done;
  1534. }
  1535. if (s->last_lit)
  1536. FLUSH_BLOCK(s, 0);
  1537. return block_done;
  1538. }
  1539. #ifndef FASTEST
  1540. /* ===========================================================================
  1541. * Same as above, but achieves better compression. We use a lazy
  1542. * evaluation for matches: a match is finally adopted only if there is
  1543. * no better match at the next window position.
  1544. */
  1545. local block_state deflate_slow(s, flush)
  1546. deflate_state *s;
  1547. int flush;
  1548. {
  1549. IPos hash_head; /* head of hash chain */
  1550. int bflush; /* set if current block must be flushed */
  1551. /* Process the input block. */
  1552. for (;;) {
  1553. /* Make sure that we always have enough lookahead, except
  1554. * at the end of the input file. We need MAX_MATCH bytes
  1555. * for the next match, plus MIN_MATCH bytes to insert the
  1556. * string following the next match.
  1557. */
  1558. if (s->lookahead < MIN_LOOKAHEAD) {
  1559. fill_window(s);
  1560. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  1561. return need_more;
  1562. }
  1563. if (s->lookahead == 0) break; /* flush the current block */
  1564. }
  1565. /* Insert the string window[strstart .. strstart+2] in the
  1566. * dictionary, and set hash_head to the head of the hash chain:
  1567. */
  1568. hash_head = NIL;
  1569. if (s->lookahead >= MIN_MATCH) {
  1570. INSERT_STRING(s, s->strstart, hash_head);
  1571. }
  1572. /* Find the longest match, discarding those <= prev_length.
  1573. */
  1574. s->prev_length = s->match_length, s->prev_match = s->match_start;
  1575. s->match_length = MIN_MATCH-1;
  1576. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  1577. s->strstart - hash_head <= MAX_DIST(s)) {
  1578. /* To simplify the code, we prevent matches with the string
  1579. * of window index 0 (in particular we have to avoid a match
  1580. * of the string with itself at the start of the input file).
  1581. */
  1582. s->match_length = longest_match (s, hash_head);
  1583. /* longest_match() sets match_start */
  1584. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  1585. #if TOO_FAR <= 32767
  1586. || (s->match_length == MIN_MATCH &&
  1587. s->strstart - s->match_start > TOO_FAR)
  1588. #endif
  1589. )) {
  1590. /* If prev_match is also MIN_MATCH, match_start is garbage
  1591. * but we will ignore the current match anyway.
  1592. */
  1593. s->match_length = MIN_MATCH-1;
  1594. }
  1595. }
  1596. /* If there was a match at the previous step and the current
  1597. * match is not better, output the previous match:
  1598. */
  1599. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  1600. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  1601. /* Do not insert strings in hash table beyond this. */
  1602. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  1603. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  1604. s->prev_length - MIN_MATCH, bflush);
  1605. /* Insert in hash table all strings up to the end of the match.
  1606. * strstart-1 and strstart are already inserted. If there is not
  1607. * enough lookahead, the last two strings are not inserted in
  1608. * the hash table.
  1609. */
  1610. s->lookahead -= s->prev_length-1;
  1611. s->prev_length -= 2;
  1612. do {
  1613. if (++s->strstart <= max_insert) {
  1614. INSERT_STRING(s, s->strstart, hash_head);
  1615. }
  1616. } while (--s->prev_length != 0);
  1617. s->match_available = 0;
  1618. s->match_length = MIN_MATCH-1;
  1619. s->strstart++;
  1620. if (bflush) FLUSH_BLOCK(s, 0);
  1621. } else if (s->match_available) {
  1622. /* If there was no match at the previous position, output a
  1623. * single literal. If there was a match but the current match
  1624. * is longer, truncate the previous match to a single literal.
  1625. */
  1626. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  1627. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  1628. if (bflush) {
  1629. FLUSH_BLOCK_ONLY(s, 0);
  1630. }
  1631. s->strstart++;
  1632. s->lookahead--;
  1633. if (s->strm->avail_out == 0) return need_more;
  1634. } else {
  1635. /* There is no previous match to compare with, wait for
  1636. * the next step to decide.
  1637. */
  1638. s->match_available = 1;
  1639. s->strstart++;
  1640. s->lookahead--;
  1641. }
  1642. }
  1643. Assert (flush != Z_NO_FLUSH, "no flush?");
  1644. if (s->match_available) {
  1645. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  1646. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  1647. s->match_available = 0;
  1648. }
  1649. s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
  1650. if (flush == Z_FINISH) {
  1651. FLUSH_BLOCK(s, 1);
  1652. return finish_done;
  1653. }
  1654. if (s->last_lit)
  1655. FLUSH_BLOCK(s, 0);
  1656. return block_done;
  1657. }
  1658. #endif /* FASTEST */
  1659. /* ===========================================================================
  1660. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  1661. * one. Do not maintain a hash table. (It will be regenerated if this run of
  1662. * deflate switches away from Z_RLE.)
  1663. */
  1664. local block_state deflate_rle(s, flush)
  1665. deflate_state *s;
  1666. int flush;
  1667. {
  1668. int bflush; /* set if current block must be flushed */
  1669. uInt prev; /* byte at distance one to match */
  1670. Bytef *scan, *strend; /* scan goes up to strend for length of run */
  1671. for (;;) {
  1672. /* Make sure that we always have enough lookahead, except
  1673. * at the end of the input file. We need MAX_MATCH bytes
  1674. * for the longest run, plus one for the unrolled loop.
  1675. */
  1676. if (s->lookahead <= MAX_MATCH) {
  1677. fill_window(s);
  1678. if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {
  1679. return need_more;
  1680. }
  1681. if (s->lookahead == 0) break; /* flush the current block */
  1682. }
  1683. /* See how many times the previous byte repeats */
  1684. s->match_length = 0;
  1685. if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
  1686. scan = s->window + s->strstart - 1;
  1687. prev = *scan;
  1688. if (prev == *++scan && prev == *++scan && prev == *++scan) {
  1689. strend = s->window + s->strstart + MAX_MATCH;
  1690. do {
  1691. } while (prev == *++scan && prev == *++scan &&
  1692. prev == *++scan && prev == *++scan &&
  1693. prev == *++scan && prev == *++scan &&
  1694. prev == *++scan && prev == *++scan &&
  1695. scan < strend);
  1696. s->match_length = MAX_MATCH - (int)(strend - scan);
  1697. if (s->match_length > s->lookahead)
  1698. s->match_length = s->lookahead;
  1699. }
  1700. Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  1701. }
  1702. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  1703. if (s->match_length >= MIN_MATCH) {
  1704. check_match(s, s->strstart, s->strstart - 1, s->match_length);
  1705. _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
  1706. s->lookahead -= s->match_length;
  1707. s->strstart += s->match_length;
  1708. s->match_length = 0;
  1709. } else {
  1710. /* No match, output a literal byte */
  1711. Tracevv((stderr,"%c", s->window[s->strstart]));
  1712. _tr_tally_lit (s, s->window[s->strstart], bflush);
  1713. s->lookahead--;
  1714. s->strstart++;
  1715. }
  1716. if (bflush) FLUSH_BLOCK(s, 0);
  1717. }
  1718. s->insert = 0;
  1719. if (flush == Z_FINISH) {
  1720. FLUSH_BLOCK(s, 1);
  1721. return finish_done;
  1722. }
  1723. if (s->last_lit)
  1724. FLUSH_BLOCK(s, 0);
  1725. return block_done;
  1726. }
  1727. /* ===========================================================================
  1728. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  1729. * (It will be regenerated if this run of deflate switches away from Huffman.)
  1730. */
  1731. local block_state deflate_huff(s, flush)
  1732. deflate_state *s;
  1733. int flush;
  1734. {
  1735. int bflush; /* set if current block must be flushed */
  1736. for (;;) {
  1737. /* Make sure that we have a literal to write. */
  1738. if (s->lookahead == 0) {
  1739. fill_window(s);
  1740. if (s->lookahead == 0) {
  1741. if (flush == Z_NO_FLUSH)
  1742. return need_more;
  1743. break; /* flush the current block */
  1744. }
  1745. }
  1746. /* Output a literal byte */
  1747. s->match_length = 0;
  1748. Tracevv((stderr,"%c", s->window[s->strstart]));
  1749. _tr_tally_lit (s, s->window[s->strstart], bflush);
  1750. s->lookahead--;
  1751. s->strstart++;
  1752. if (bflush) FLUSH_BLOCK(s, 0);
  1753. }
  1754. s->insert = 0;
  1755. if (flush == Z_FINISH) {
  1756. FLUSH_BLOCK(s, 1);
  1757. return finish_done;
  1758. }
  1759. if (s->last_lit)
  1760. FLUSH_BLOCK(s, 0);
  1761. return block_done;
  1762. }