deflate.c 44 KB

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