You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

deflate.c 48KB

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