deflate.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268
  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 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 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_deflateInit_(
  147. z_streamp strm,
  148. int level,
  149. const char *version,
  150. int stream_size
  151. )
  152. {
  153. return zlib_deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS,
  154. DEF_MEM_LEVEL,
  155. Z_DEFAULT_STRATEGY, version, stream_size);
  156. /* To do: ignore strm->next_in if we use it as window */
  157. }
  158. /* ========================================================================= */
  159. int zlib_deflateInit2_(
  160. z_streamp strm,
  161. int level,
  162. int method,
  163. int windowBits,
  164. int memLevel,
  165. int strategy,
  166. const char *version,
  167. int stream_size
  168. )
  169. {
  170. deflate_state *s;
  171. int noheader = 0;
  172. static char* my_version = ZLIB_VERSION;
  173. deflate_workspace *mem;
  174. ush *overlay;
  175. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  176. * output size for (length,distance) codes is <= 24 bits.
  177. */
  178. if (version == NULL || version[0] != my_version[0] ||
  179. stream_size != sizeof(z_stream)) {
  180. return Z_VERSION_ERROR;
  181. }
  182. if (strm == NULL) return Z_STREAM_ERROR;
  183. strm->msg = NULL;
  184. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  185. mem = (deflate_workspace *) strm->workspace;
  186. if (windowBits < 0) { /* undocumented feature: suppress zlib header */
  187. noheader = 1;
  188. windowBits = -windowBits;
  189. }
  190. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  191. windowBits < 9 || windowBits > 15 || level < 0 || level > 9 ||
  192. strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
  193. return Z_STREAM_ERROR;
  194. }
  195. s = (deflate_state *) &(mem->deflate_memory);
  196. strm->state = (struct internal_state *)s;
  197. s->strm = strm;
  198. s->noheader = noheader;
  199. s->w_bits = windowBits;
  200. s->w_size = 1 << s->w_bits;
  201. s->w_mask = s->w_size - 1;
  202. s->hash_bits = memLevel + 7;
  203. s->hash_size = 1 << s->hash_bits;
  204. s->hash_mask = s->hash_size - 1;
  205. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  206. s->window = (Byte *) mem->window_memory;
  207. s->prev = (Pos *) mem->prev_memory;
  208. s->head = (Pos *) mem->head_memory;
  209. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  210. overlay = (ush *) mem->overlay_memory;
  211. s->pending_buf = (uch *) overlay;
  212. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  213. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  214. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  215. s->level = level;
  216. s->strategy = strategy;
  217. s->method = (Byte)method;
  218. return zlib_deflateReset(strm);
  219. }
  220. /* ========================================================================= */
  221. int zlib_deflateSetDictionary(
  222. z_streamp strm,
  223. const Byte *dictionary,
  224. uInt dictLength
  225. )
  226. {
  227. deflate_state *s;
  228. uInt length = dictLength;
  229. uInt n;
  230. IPos hash_head = 0;
  231. if (strm == NULL || strm->state == NULL || dictionary == NULL)
  232. return Z_STREAM_ERROR;
  233. s = (deflate_state *) strm->state;
  234. if (s->status != INIT_STATE) return Z_STREAM_ERROR;
  235. strm->adler = zlib_adler32(strm->adler, dictionary, dictLength);
  236. if (length < MIN_MATCH) return Z_OK;
  237. if (length > MAX_DIST(s)) {
  238. length = MAX_DIST(s);
  239. #ifndef USE_DICT_HEAD
  240. dictionary += dictLength - length; /* use the tail of the dictionary */
  241. #endif
  242. }
  243. memcpy((char *)s->window, dictionary, length);
  244. s->strstart = length;
  245. s->block_start = (long)length;
  246. /* Insert all strings in the hash table (except for the last two bytes).
  247. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  248. * call of fill_window.
  249. */
  250. s->ins_h = s->window[0];
  251. UPDATE_HASH(s, s->ins_h, s->window[1]);
  252. for (n = 0; n <= length - MIN_MATCH; n++) {
  253. INSERT_STRING(s, n, hash_head);
  254. }
  255. if (hash_head) hash_head = 0; /* to make compiler happy */
  256. return Z_OK;
  257. }
  258. /* ========================================================================= */
  259. int zlib_deflateReset(
  260. z_streamp strm
  261. )
  262. {
  263. deflate_state *s;
  264. if (strm == NULL || strm->state == NULL)
  265. return Z_STREAM_ERROR;
  266. strm->total_in = strm->total_out = 0;
  267. strm->msg = NULL;
  268. strm->data_type = Z_UNKNOWN;
  269. s = (deflate_state *)strm->state;
  270. s->pending = 0;
  271. s->pending_out = s->pending_buf;
  272. if (s->noheader < 0) {
  273. s->noheader = 0; /* was set to -1 by deflate(..., Z_FINISH); */
  274. }
  275. s->status = s->noheader ? BUSY_STATE : INIT_STATE;
  276. strm->adler = 1;
  277. s->last_flush = Z_NO_FLUSH;
  278. zlib_tr_init(s);
  279. lm_init(s);
  280. return Z_OK;
  281. }
  282. /* ========================================================================= */
  283. int zlib_deflateParams(
  284. z_streamp strm,
  285. int level,
  286. int strategy
  287. )
  288. {
  289. deflate_state *s;
  290. compress_func func;
  291. int err = Z_OK;
  292. if (strm == NULL || strm->state == NULL) return Z_STREAM_ERROR;
  293. s = (deflate_state *) strm->state;
  294. if (level == Z_DEFAULT_COMPRESSION) {
  295. level = 6;
  296. }
  297. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
  298. return Z_STREAM_ERROR;
  299. }
  300. func = configuration_table[s->level].func;
  301. if (func != configuration_table[level].func && strm->total_in != 0) {
  302. /* Flush the last buffer: */
  303. err = zlib_deflate(strm, Z_PARTIAL_FLUSH);
  304. }
  305. if (s->level != level) {
  306. s->level = level;
  307. s->max_lazy_match = configuration_table[level].max_lazy;
  308. s->good_match = configuration_table[level].good_length;
  309. s->nice_match = configuration_table[level].nice_length;
  310. s->max_chain_length = configuration_table[level].max_chain;
  311. }
  312. s->strategy = strategy;
  313. return err;
  314. }
  315. /* =========================================================================
  316. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  317. * IN assertion: the stream state is correct and there is enough room in
  318. * pending_buf.
  319. */
  320. static void putShortMSB(
  321. deflate_state *s,
  322. uInt b
  323. )
  324. {
  325. put_byte(s, (Byte)(b >> 8));
  326. put_byte(s, (Byte)(b & 0xff));
  327. }
  328. /* =========================================================================
  329. * Flush as much pending output as possible. All deflate() output goes
  330. * through this function so some applications may wish to modify it
  331. * to avoid allocating a large strm->next_out buffer and copying into it.
  332. * (See also read_buf()).
  333. */
  334. static void flush_pending(
  335. z_streamp strm
  336. )
  337. {
  338. deflate_state *s = (deflate_state *) strm->state;
  339. unsigned len = s->pending;
  340. if (len > strm->avail_out) len = strm->avail_out;
  341. if (len == 0) return;
  342. if (strm->next_out != NULL) {
  343. memcpy(strm->next_out, s->pending_out, len);
  344. strm->next_out += len;
  345. }
  346. s->pending_out += len;
  347. strm->total_out += len;
  348. strm->avail_out -= len;
  349. s->pending -= len;
  350. if (s->pending == 0) {
  351. s->pending_out = s->pending_buf;
  352. }
  353. }
  354. /* ========================================================================= */
  355. int zlib_deflate(
  356. z_streamp strm,
  357. int flush
  358. )
  359. {
  360. int old_flush; /* value of flush param for previous deflate call */
  361. deflate_state *s;
  362. if (strm == NULL || strm->state == NULL ||
  363. flush > Z_FINISH || flush < 0) {
  364. return Z_STREAM_ERROR;
  365. }
  366. s = (deflate_state *) strm->state;
  367. if ((strm->next_in == NULL && strm->avail_in != 0) ||
  368. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  369. return Z_STREAM_ERROR;
  370. }
  371. if (strm->avail_out == 0) return Z_BUF_ERROR;
  372. s->strm = strm; /* just in case */
  373. old_flush = s->last_flush;
  374. s->last_flush = flush;
  375. /* Write the zlib header */
  376. if (s->status == INIT_STATE) {
  377. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  378. uInt level_flags = (s->level-1) >> 1;
  379. if (level_flags > 3) level_flags = 3;
  380. header |= (level_flags << 6);
  381. if (s->strstart != 0) header |= PRESET_DICT;
  382. header += 31 - (header % 31);
  383. s->status = BUSY_STATE;
  384. putShortMSB(s, header);
  385. /* Save the adler32 of the preset dictionary: */
  386. if (s->strstart != 0) {
  387. putShortMSB(s, (uInt)(strm->adler >> 16));
  388. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  389. }
  390. strm->adler = 1L;
  391. }
  392. /* Flush as much pending output as possible */
  393. if (s->pending != 0) {
  394. flush_pending(strm);
  395. if (strm->avail_out == 0) {
  396. /* Since avail_out is 0, deflate will be called again with
  397. * more output space, but possibly with both pending and
  398. * avail_in equal to zero. There won't be anything to do,
  399. * but this is not an error situation so make sure we
  400. * return OK instead of BUF_ERROR at next call of deflate:
  401. */
  402. s->last_flush = -1;
  403. return Z_OK;
  404. }
  405. /* Make sure there is something to do and avoid duplicate consecutive
  406. * flushes. For repeated and useless calls with Z_FINISH, we keep
  407. * returning Z_STREAM_END instead of Z_BUFF_ERROR.
  408. */
  409. } else if (strm->avail_in == 0 && flush <= old_flush &&
  410. flush != Z_FINISH) {
  411. return Z_BUF_ERROR;
  412. }
  413. /* User must not provide more input after the first FINISH: */
  414. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  415. return Z_BUF_ERROR;
  416. }
  417. /* Start a new block or continue the current one.
  418. */
  419. if (strm->avail_in != 0 || s->lookahead != 0 ||
  420. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  421. block_state bstate;
  422. bstate = (*(configuration_table[s->level].func))(s, flush);
  423. if (bstate == finish_started || bstate == finish_done) {
  424. s->status = FINISH_STATE;
  425. }
  426. if (bstate == need_more || bstate == finish_started) {
  427. if (strm->avail_out == 0) {
  428. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  429. }
  430. return Z_OK;
  431. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  432. * of deflate should use the same flush parameter to make sure
  433. * that the flush is complete. So we don't have to output an
  434. * empty block here, this will be done at next call. This also
  435. * ensures that for a very small output buffer, we emit at most
  436. * one empty block.
  437. */
  438. }
  439. if (bstate == block_done) {
  440. if (flush == Z_PARTIAL_FLUSH) {
  441. zlib_tr_align(s);
  442. } else if (flush == Z_PACKET_FLUSH) {
  443. /* Output just the 3-bit `stored' block type value,
  444. but not a zero length. */
  445. zlib_tr_stored_type_only(s);
  446. } else { /* FULL_FLUSH or SYNC_FLUSH */
  447. zlib_tr_stored_block(s, (char*)0, 0L, 0);
  448. /* For a full flush, this empty block will be recognized
  449. * as a special marker by inflate_sync().
  450. */
  451. if (flush == Z_FULL_FLUSH) {
  452. CLEAR_HASH(s); /* forget history */
  453. }
  454. }
  455. flush_pending(strm);
  456. if (strm->avail_out == 0) {
  457. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  458. return Z_OK;
  459. }
  460. }
  461. }
  462. Assert(strm->avail_out > 0, "bug2");
  463. if (flush != Z_FINISH) return Z_OK;
  464. if (s->noheader) return Z_STREAM_END;
  465. /* Write the zlib trailer (adler32) */
  466. putShortMSB(s, (uInt)(strm->adler >> 16));
  467. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  468. flush_pending(strm);
  469. /* If avail_out is zero, the application will call deflate again
  470. * to flush the rest.
  471. */
  472. s->noheader = -1; /* write the trailer only once! */
  473. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  474. }
  475. /* ========================================================================= */
  476. int zlib_deflateEnd(
  477. z_streamp strm
  478. )
  479. {
  480. int status;
  481. deflate_state *s;
  482. if (strm == NULL || strm->state == NULL) return Z_STREAM_ERROR;
  483. s = (deflate_state *) strm->state;
  484. status = s->status;
  485. if (status != INIT_STATE && status != BUSY_STATE &&
  486. status != FINISH_STATE) {
  487. return Z_STREAM_ERROR;
  488. }
  489. strm->state = NULL;
  490. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  491. }
  492. /* =========================================================================
  493. * Copy the source state to the destination state.
  494. */
  495. int zlib_deflateCopy (
  496. z_streamp dest,
  497. z_streamp source
  498. )
  499. {
  500. #ifdef MAXSEG_64K
  501. return Z_STREAM_ERROR;
  502. #else
  503. deflate_state *ds;
  504. deflate_state *ss;
  505. ush *overlay;
  506. deflate_workspace *mem;
  507. if (source == NULL || dest == NULL || source->state == NULL) {
  508. return Z_STREAM_ERROR;
  509. }
  510. ss = (deflate_state *) source->state;
  511. *dest = *source;
  512. mem = (deflate_workspace *) dest->workspace;
  513. ds = &(mem->deflate_memory);
  514. dest->state = (struct internal_state *) ds;
  515. *ds = *ss;
  516. ds->strm = dest;
  517. ds->window = (Byte *) mem->window_memory;
  518. ds->prev = (Pos *) mem->prev_memory;
  519. ds->head = (Pos *) mem->head_memory;
  520. overlay = (ush *) mem->overlay_memory;
  521. ds->pending_buf = (uch *) overlay;
  522. memcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  523. memcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  524. memcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  525. memcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  526. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  527. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  528. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  529. ds->l_desc.dyn_tree = ds->dyn_ltree;
  530. ds->d_desc.dyn_tree = ds->dyn_dtree;
  531. ds->bl_desc.dyn_tree = ds->bl_tree;
  532. return Z_OK;
  533. #endif
  534. }
  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(void)
  1103. {
  1104. return sizeof(deflate_workspace);
  1105. }