deflate.c 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832
  1. /* deflate.c -- compress data using the deflation algorithm
  2. * Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler
  3. * For conditions of distribution and use, see copyright notice in zlib.h
  4. */
  5. /*
  6. * ALGORITHM
  7. *
  8. * The "deflation" process depends on being able to identify portions
  9. * of the input text which are identical to earlier input (within a
  10. * sliding window trailing behind the input currently being processed).
  11. *
  12. * The most straightforward technique turns out to be the fastest for
  13. * most input files: try all possible matches and select the longest.
  14. * The key feature of this algorithm is that insertions into the string
  15. * dictionary are very simple and thus fast, and deletions are avoided
  16. * completely. Insertions are performed at each input character, whereas
  17. * string matches are performed only when the previous match ends. So it
  18. * is preferable to spend more time in matches to allow very fast string
  19. * insertions and avoid deletions. The matching algorithm for small
  20. * strings is inspired from that of Rabin & Karp. A brute force approach
  21. * is used to find longer strings when a small match has been found.
  22. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  23. * (by Leonid Broukhis).
  24. * A previous version of this file used a more sophisticated algorithm
  25. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  26. * time, but has a larger average cost, uses more memory and is patented.
  27. * However the F&G algorithm may be faster for some highly redundant
  28. * files if the parameter max_chain_length (described below) is too large.
  29. *
  30. * ACKNOWLEDGEMENTS
  31. *
  32. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  33. * I found it in 'freeze' written by Leonid Broukhis.
  34. * Thanks to many people for bug reports and testing.
  35. *
  36. * REFERENCES
  37. *
  38. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  39. * Available in http://www.ietf.org/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$ */
  49. #include "deflate.h"
  50. const char deflate_copyright[] =
  51. " deflate 1.2.5 Copyright 1995-2010 Jean-loup Gailly and Mark Adler ";
  52. /*
  53. If you use the zlib library in a product, an acknowledgment is welcome
  54. in the documentation of your product. If for some reason you cannot
  55. include such an acknowledgment, I would appreciate that you keep this
  56. copyright string in the executable of your product.
  57. */
  58. /* ===========================================================================
  59. * Function prototypes.
  60. */
  61. typedef enum {
  62. need_more, /* block not completed, need more input or more output */
  63. block_done, /* block flush performed */
  64. finish_started, /* finish started, need only more output at next deflate */
  65. finish_done /* finish done, accept no more input or output */
  66. } block_state;
  67. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  68. /* Compression function. Returns the block state after the call. */
  69. local void fill_window OF((deflate_state *s));
  70. local block_state deflate_stored OF((deflate_state *s, int flush));
  71. local block_state deflate_fast OF((deflate_state *s, int flush));
  72. #ifndef FASTEST
  73. local block_state deflate_slow OF((deflate_state *s, int flush));
  74. #endif
  75. local block_state deflate_rle OF((deflate_state *s, int flush));
  76. local block_state deflate_huff OF((deflate_state *s, int flush));
  77. local void lm_init OF((deflate_state *s));
  78. local void putShortMSB OF((deflate_state *s, uInt b));
  79. local void flush_pending OF((z_streamp strm));
  80. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81. #ifdef ASMV
  82. void match_init OF((void)); /* asm code initialization */
  83. uInt longest_match OF((deflate_state *s, IPos cur_match));
  84. #else
  85. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  86. #endif
  87. #ifdef DEBUG
  88. local void check_match OF((deflate_state *s, IPos start, IPos match,
  89. int length));
  90. #endif
  91. /* ===========================================================================
  92. * Local data
  93. */
  94. #define NIL 0
  95. /* Tail of hash chains */
  96. #ifndef TOO_FAR
  97. # define TOO_FAR 4096
  98. #endif
  99. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  100. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  101. * the desired pack level (0..9). The values given below have been tuned to
  102. * exclude worst case performance for pathological files. Better values may be
  103. * found for specific files.
  104. */
  105. typedef struct config_s {
  106. ush good_length; /* reduce lazy search above this match length */
  107. ush max_lazy; /* do not perform lazy search above this match length */
  108. ush nice_length; /* quit search above this match length */
  109. ush max_chain;
  110. compress_func func;
  111. } config;
  112. #ifdef FASTEST
  113. local const config configuration_table[2] = {
  114. /* good lazy nice chain */
  115. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  116. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  117. #else
  118. local const config configuration_table[10] = {
  119. /* good lazy nice chain */
  120. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  121. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  122. /* 2 */ {4, 5, 16, 8, deflate_fast},
  123. /* 3 */ {4, 6, 32, 32, deflate_fast},
  124. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  125. /* 5 */ {8, 16, 32, 32, deflate_slow},
  126. /* 6 */ {8, 16, 128, 128, deflate_slow},
  127. /* 7 */ {8, 32, 128, 256, deflate_slow},
  128. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  129. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  130. #endif
  131. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  132. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  133. * meaning.
  134. */
  135. #define EQUAL 0
  136. /* result of memcmp for equal strings */
  137. #ifndef NO_DUMMY_DECL
  138. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  139. #endif
  140. /* ===========================================================================
  141. * Update a hash value with the given input byte
  142. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  143. * input characters, so that a running hash key can be computed from the
  144. * previous key instead of complete recalculation each time.
  145. */
  146. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  147. /* ===========================================================================
  148. * Insert string str in the dictionary and set match_head to the previous head
  149. * of the hash chain (the most recent string with same hash key). Return
  150. * the previous length of the hash chain.
  151. * If this file is compiled with -DFASTEST, the compression level is forced
  152. * to 1, and no hash chains are maintained.
  153. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  154. * input characters and the first MIN_MATCH bytes of str are valid
  155. * (except for the last MIN_MATCH-1 bytes of the input file).
  156. */
  157. #ifdef FASTEST
  158. #define INSERT_STRING(s, str, match_head) \
  159. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  160. match_head = s->head[s->ins_h], \
  161. s->head[s->ins_h] = (Pos)(str))
  162. #else
  163. #define INSERT_STRING(s, str, match_head) \
  164. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  165. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  166. s->head[s->ins_h] = (Pos)(str))
  167. #endif
  168. /* ===========================================================================
  169. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  170. * prev[] will be initialized on the fly.
  171. */
  172. #define CLEAR_HASH(s) \
  173. s->head[s->hash_size-1] = NIL; \
  174. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  175. /* ========================================================================= */
  176. int ZEXPORT deflateInit_(strm, level, version, stream_size)
  177. z_streamp strm;
  178. int level;
  179. const char *version;
  180. int stream_size;
  181. {
  182. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  183. Z_DEFAULT_STRATEGY, version, stream_size);
  184. /* To do: ignore strm->next_in if we use it as window */
  185. }
  186. /* ========================================================================= */
  187. int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
  188. version, stream_size)
  189. z_streamp strm;
  190. int level;
  191. int method;
  192. int windowBits;
  193. int memLevel;
  194. int strategy;
  195. const char *version;
  196. int stream_size;
  197. {
  198. deflate_state *s;
  199. int wrap = 1;
  200. static const char my_version[] = ZLIB_VERSION;
  201. ushf *overlay;
  202. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  203. * output size for (length,distance) codes is <= 24 bits.
  204. */
  205. if (version == Z_NULL || version[0] != my_version[0] ||
  206. stream_size != sizeof(z_stream)) {
  207. return Z_VERSION_ERROR;
  208. }
  209. if (strm == Z_NULL) return Z_STREAM_ERROR;
  210. strm->msg = Z_NULL;
  211. if (strm->zalloc == (alloc_func)0) {
  212. strm->zalloc = zcalloc;
  213. strm->opaque = (voidpf)0;
  214. }
  215. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  216. #ifdef FASTEST
  217. if (level != 0) level = 1;
  218. #else
  219. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  220. #endif
  221. if (windowBits < 0) { /* suppress zlib wrapper */
  222. wrap = 0;
  223. windowBits = -windowBits;
  224. }
  225. #ifdef GZIP
  226. else if (windowBits > 15) {
  227. wrap = 2; /* write gzip wrapper instead */
  228. windowBits -= 16;
  229. }
  230. #endif
  231. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  232. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  233. strategy < 0 || strategy > Z_FIXED) {
  234. return Z_STREAM_ERROR;
  235. }
  236. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  237. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  238. if (s == Z_NULL) return Z_MEM_ERROR;
  239. strm->state = (struct internal_state FAR *)s;
  240. s->strm = strm;
  241. s->wrap = wrap;
  242. s->gzhead = Z_NULL;
  243. s->w_bits = windowBits;
  244. s->w_size = 1 << s->w_bits;
  245. s->w_mask = s->w_size - 1;
  246. s->hash_bits = memLevel + 7;
  247. s->hash_size = 1 << s->hash_bits;
  248. s->hash_mask = s->hash_size - 1;
  249. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  250. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  251. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  252. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  253. s->high_water = 0; /* nothing written to s->window yet */
  254. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  255. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  256. s->pending_buf = (uchf *) overlay;
  257. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  258. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  259. s->pending_buf == Z_NULL) {
  260. s->status = FINISH_STATE;
  261. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  262. deflateEnd (strm);
  263. return Z_MEM_ERROR;
  264. }
  265. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  266. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  267. s->level = level;
  268. s->strategy = strategy;
  269. s->method = (Byte)method;
  270. return deflateReset(strm);
  271. }
  272. /* ========================================================================= */
  273. int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
  274. z_streamp strm;
  275. const Bytef *dictionary;
  276. uInt dictLength;
  277. {
  278. deflate_state *s;
  279. uInt length = dictLength;
  280. uInt n;
  281. IPos hash_head = 0;
  282. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  283. strm->state->wrap == 2 ||
  284. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  285. return Z_STREAM_ERROR;
  286. s = strm->state;
  287. if (s->wrap)
  288. strm->adler = adler32(strm->adler, dictionary, dictLength);
  289. if (length < MIN_MATCH) return Z_OK;
  290. if (length > s->w_size) {
  291. length = s->w_size;
  292. dictionary += dictLength - length; /* use the tail of the dictionary */
  293. }
  294. zmemcpy(s->window, dictionary, length);
  295. s->strstart = length;
  296. s->block_start = (long)length;
  297. /* Insert all strings in the hash table (except for the last two bytes).
  298. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  299. * call of fill_window.
  300. */
  301. s->ins_h = s->window[0];
  302. UPDATE_HASH(s, s->ins_h, s->window[1]);
  303. for (n = 0; n <= length - MIN_MATCH; n++) {
  304. INSERT_STRING(s, n, hash_head);
  305. }
  306. if (hash_head) hash_head = 0; /* to make compiler happy */
  307. return Z_OK;
  308. }
  309. /* ========================================================================= */
  310. int ZEXPORT deflateReset (strm)
  311. z_streamp strm;
  312. {
  313. deflate_state *s;
  314. if (strm == Z_NULL || strm->state == Z_NULL ||
  315. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  316. return Z_STREAM_ERROR;
  317. }
  318. strm->total_in = strm->total_out = 0;
  319. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  320. strm->data_type = Z_UNKNOWN;
  321. s = (deflate_state *)strm->state;
  322. s->pending = 0;
  323. s->pending_out = s->pending_buf;
  324. if (s->wrap < 0) {
  325. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  326. }
  327. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  328. strm->adler =
  329. #ifdef GZIP
  330. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  331. #endif
  332. adler32(0L, Z_NULL, 0);
  333. s->last_flush = Z_NO_FLUSH;
  334. _tr_init(s);
  335. lm_init(s);
  336. return Z_OK;
  337. }
  338. /* ========================================================================= */
  339. int ZEXPORT deflateSetHeader (strm, head)
  340. z_streamp strm;
  341. gz_headerp head;
  342. {
  343. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  344. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  345. strm->state->gzhead = head;
  346. return Z_OK;
  347. }
  348. /* ========================================================================= */
  349. int ZEXPORT deflatePrime (strm, bits, value)
  350. z_streamp strm;
  351. int bits;
  352. int value;
  353. {
  354. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  355. strm->state->bi_valid = bits;
  356. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  357. return Z_OK;
  358. }
  359. /* ========================================================================= */
  360. int ZEXPORT deflateParams(strm, level, strategy)
  361. z_streamp strm;
  362. int level;
  363. int strategy;
  364. {
  365. deflate_state *s;
  366. compress_func func;
  367. int err = Z_OK;
  368. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  369. s = strm->state;
  370. #ifdef FASTEST
  371. if (level != 0) level = 1;
  372. #else
  373. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  374. #endif
  375. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  376. return Z_STREAM_ERROR;
  377. }
  378. func = configuration_table[s->level].func;
  379. if ((strategy != s->strategy || func != configuration_table[level].func) &&
  380. strm->total_in != 0) {
  381. /* Flush the last buffer: */
  382. err = deflate(strm, Z_BLOCK);
  383. }
  384. if (s->level != level) {
  385. s->level = level;
  386. s->max_lazy_match = configuration_table[level].max_lazy;
  387. s->good_match = configuration_table[level].good_length;
  388. s->nice_match = configuration_table[level].nice_length;
  389. s->max_chain_length = configuration_table[level].max_chain;
  390. }
  391. s->strategy = strategy;
  392. return err;
  393. }
  394. /* ========================================================================= */
  395. int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
  396. z_streamp strm;
  397. int good_length;
  398. int max_lazy;
  399. int nice_length;
  400. int max_chain;
  401. {
  402. deflate_state *s;
  403. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  404. s = strm->state;
  405. s->good_match = good_length;
  406. s->max_lazy_match = max_lazy;
  407. s->nice_match = nice_length;
  408. s->max_chain_length = max_chain;
  409. return Z_OK;
  410. }
  411. /* =========================================================================
  412. * For the default windowBits of 15 and memLevel of 8, this function returns
  413. * a close to exact, as well as small, upper bound on the compressed size.
  414. * They are coded as constants here for a reason--if the #define's are
  415. * changed, then this function needs to be changed as well. The return
  416. * value for 15 and 8 only works for those exact settings.
  417. *
  418. * For any setting other than those defaults for windowBits and memLevel,
  419. * the value returned is a conservative worst case for the maximum expansion
  420. * resulting from using fixed blocks instead of stored blocks, which deflate
  421. * can emit on compressed data for some combinations of the parameters.
  422. *
  423. * This function could be more sophisticated to provide closer upper bounds for
  424. * every combination of windowBits and memLevel. But even the conservative
  425. * upper bound of about 14% expansion does not seem onerous for output buffer
  426. * allocation.
  427. */
  428. uLong ZEXPORT deflateBound(strm, sourceLen)
  429. z_streamp strm;
  430. uLong sourceLen;
  431. {
  432. deflate_state *s;
  433. uLong complen, wraplen;
  434. Bytef *str;
  435. /* conservative upper bound for compressed data */
  436. complen = sourceLen +
  437. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
  438. /* if can't get parameters, return conservative bound plus zlib wrapper */
  439. if (strm == Z_NULL || strm->state == Z_NULL)
  440. return complen + 6;
  441. /* compute wrapper length */
  442. s = strm->state;
  443. switch (s->wrap) {
  444. case 0: /* raw deflate */
  445. wraplen = 0;
  446. break;
  447. case 1: /* zlib wrapper */
  448. wraplen = 6 + (s->strstart ? 4 : 0);
  449. break;
  450. case 2: /* gzip wrapper */
  451. wraplen = 18;
  452. if (s->gzhead != Z_NULL) { /* user-supplied gzip header */
  453. if (s->gzhead->extra != Z_NULL)
  454. wraplen += 2 + s->gzhead->extra_len;
  455. str = s->gzhead->name;
  456. if (str != Z_NULL)
  457. do {
  458. wraplen++;
  459. } while (*str++);
  460. str = s->gzhead->comment;
  461. if (str != Z_NULL)
  462. do {
  463. wraplen++;
  464. } while (*str++);
  465. if (s->gzhead->hcrc)
  466. wraplen += 2;
  467. }
  468. break;
  469. default: /* for compiler happiness */
  470. wraplen = 6;
  471. }
  472. /* if not default parameters, return conservative bound */
  473. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  474. return complen + wraplen;
  475. /* default settings: return tight bound for that case */
  476. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
  477. (sourceLen >> 25) + 13 - 6 + wraplen;
  478. }
  479. /* =========================================================================
  480. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  481. * IN assertion: the stream state is correct and there is enough room in
  482. * pending_buf.
  483. */
  484. local void putShortMSB (s, b)
  485. deflate_state *s;
  486. uInt b;
  487. {
  488. put_byte(s, (Byte)(b >> 8));
  489. put_byte(s, (Byte)(b & 0xff));
  490. }
  491. /* =========================================================================
  492. * Flush as much pending output as possible. All deflate() output goes
  493. * through this function so some applications may wish to modify it
  494. * to avoid allocating a large strm->next_out buffer and copying into it.
  495. * (See also read_buf()).
  496. */
  497. local void flush_pending(strm)
  498. z_streamp strm;
  499. {
  500. unsigned len = strm->state->pending;
  501. if (len > strm->avail_out) len = strm->avail_out;
  502. if (len == 0) return;
  503. zmemcpy(strm->next_out, strm->state->pending_out, len);
  504. strm->next_out += len;
  505. strm->state->pending_out += len;
  506. strm->total_out += len;
  507. strm->avail_out -= len;
  508. strm->state->pending -= len;
  509. if (strm->state->pending == 0) {
  510. strm->state->pending_out = strm->state->pending_buf;
  511. }
  512. }
  513. /* ========================================================================= */
  514. int ZEXPORT deflate (strm, flush)
  515. z_streamp strm;
  516. int flush;
  517. {
  518. int old_flush; /* value of flush param for previous deflate call */
  519. deflate_state *s;
  520. if (strm == Z_NULL || strm->state == Z_NULL ||
  521. flush > Z_BLOCK || flush < 0) {
  522. return Z_STREAM_ERROR;
  523. }
  524. s = strm->state;
  525. if (s->status == FINISH_STATE && flush != Z_FINISH) {
  526. ERR_RETURN(strm, Z_STREAM_ERROR);
  527. }
  528. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  529. s->strm = strm; /* just in case */
  530. old_flush = s->last_flush;
  531. s->last_flush = flush;
  532. /* Write the header */
  533. if (s->status == INIT_STATE) {
  534. #ifdef GZIP
  535. if (s->wrap == 2) {
  536. strm->adler = crc32(0L, Z_NULL, 0);
  537. put_byte(s, 31);
  538. put_byte(s, 139);
  539. put_byte(s, 8);
  540. if (s->gzhead == Z_NULL) {
  541. put_byte(s, 0);
  542. put_byte(s, 0);
  543. put_byte(s, 0);
  544. put_byte(s, 0);
  545. put_byte(s, 0);
  546. put_byte(s, s->level == 9 ? 2 :
  547. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  548. 4 : 0));
  549. put_byte(s, OS_CODE);
  550. s->status = BUSY_STATE;
  551. }
  552. else {
  553. put_byte(s, (s->gzhead->text ? 1 : 0) +
  554. (s->gzhead->hcrc ? 2 : 0) +
  555. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  556. (s->gzhead->name == Z_NULL ? 0 : 8) +
  557. (s->gzhead->comment == Z_NULL ? 0 : 16)
  558. );
  559. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  560. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  561. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  562. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  563. put_byte(s, s->level == 9 ? 2 :
  564. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  565. 4 : 0));
  566. put_byte(s, s->gzhead->os & 0xff);
  567. if (s->gzhead->extra != Z_NULL) {
  568. put_byte(s, s->gzhead->extra_len & 0xff);
  569. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  570. }
  571. if (s->gzhead->hcrc)
  572. strm->adler = crc32(strm->adler, s->pending_buf,
  573. s->pending);
  574. s->gzindex = 0;
  575. s->status = EXTRA_STATE;
  576. }
  577. }
  578. else
  579. #endif
  580. {
  581. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  582. uInt level_flags;
  583. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  584. level_flags = 0;
  585. else if (s->level < 6)
  586. level_flags = 1;
  587. else if (s->level == 6)
  588. level_flags = 2;
  589. else
  590. level_flags = 3;
  591. header |= (level_flags << 6);
  592. if (s->strstart != 0) header |= PRESET_DICT;
  593. header += 31 - (header % 31);
  594. s->status = BUSY_STATE;
  595. putShortMSB(s, header);
  596. /* Save the adler32 of the preset dictionary: */
  597. if (s->strstart != 0) {
  598. putShortMSB(s, (uInt)(strm->adler >> 16));
  599. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  600. }
  601. strm->adler = adler32(0L, Z_NULL, 0);
  602. }
  603. }
  604. #ifdef GZIP
  605. if (s->status == EXTRA_STATE) {
  606. if (s->gzhead->extra != Z_NULL) {
  607. uInt beg = s->pending; /* start of bytes to update crc */
  608. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  609. if (s->pending == s->pending_buf_size) {
  610. if (s->gzhead->hcrc && s->pending > beg)
  611. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  612. s->pending - beg);
  613. flush_pending(strm);
  614. beg = s->pending;
  615. if (s->pending == s->pending_buf_size)
  616. break;
  617. }
  618. put_byte(s, s->gzhead->extra[s->gzindex]);
  619. s->gzindex++;
  620. }
  621. if (s->gzhead->hcrc && s->pending > beg)
  622. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  623. s->pending - beg);
  624. if (s->gzindex == s->gzhead->extra_len) {
  625. s->gzindex = 0;
  626. s->status = NAME_STATE;
  627. }
  628. }
  629. else
  630. s->status = NAME_STATE;
  631. }
  632. if (s->status == NAME_STATE) {
  633. if (s->gzhead->name != Z_NULL) {
  634. uInt beg = s->pending; /* start of bytes to update crc */
  635. int val;
  636. do {
  637. if (s->pending == s->pending_buf_size) {
  638. if (s->gzhead->hcrc && s->pending > beg)
  639. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  640. s->pending - beg);
  641. flush_pending(strm);
  642. beg = s->pending;
  643. if (s->pending == s->pending_buf_size) {
  644. val = 1;
  645. break;
  646. }
  647. }
  648. val = s->gzhead->name[s->gzindex++];
  649. put_byte(s, val);
  650. } while (val != 0);
  651. if (s->gzhead->hcrc && s->pending > beg)
  652. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  653. s->pending - beg);
  654. if (val == 0) {
  655. s->gzindex = 0;
  656. s->status = COMMENT_STATE;
  657. }
  658. }
  659. else
  660. s->status = COMMENT_STATE;
  661. }
  662. if (s->status == COMMENT_STATE) {
  663. if (s->gzhead->comment != Z_NULL) {
  664. uInt beg = s->pending; /* start of bytes to update crc */
  665. int val;
  666. do {
  667. if (s->pending == s->pending_buf_size) {
  668. if (s->gzhead->hcrc && s->pending > beg)
  669. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  670. s->pending - beg);
  671. flush_pending(strm);
  672. beg = s->pending;
  673. if (s->pending == s->pending_buf_size) {
  674. val = 1;
  675. break;
  676. }
  677. }
  678. val = s->gzhead->comment[s->gzindex++];
  679. put_byte(s, val);
  680. } while (val != 0);
  681. if (s->gzhead->hcrc && s->pending > beg)
  682. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  683. s->pending - beg);
  684. if (val == 0)
  685. s->status = HCRC_STATE;
  686. }
  687. else
  688. s->status = HCRC_STATE;
  689. }
  690. if (s->status == HCRC_STATE) {
  691. if (s->gzhead->hcrc) {
  692. if (s->pending + 2 > s->pending_buf_size)
  693. flush_pending(strm);
  694. if (s->pending + 2 <= s->pending_buf_size) {
  695. put_byte(s, (Byte)(strm->adler & 0xff));
  696. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  697. strm->adler = crc32(0L, Z_NULL, 0);
  698. s->status = BUSY_STATE;
  699. }
  700. }
  701. else
  702. s->status = BUSY_STATE;
  703. }
  704. #endif
  705. /* Flush as much pending output as possible */
  706. if (s->pending != 0) {
  707. flush_pending(strm);
  708. if (strm->avail_out == 0) {
  709. /* Since avail_out is 0, deflate will be called again with
  710. * more output space, but possibly with both pending and
  711. * avail_in equal to zero. There won't be anything to do,
  712. * but this is not an error situation so make sure we
  713. * return OK instead of BUF_ERROR at next call of deflate:
  714. */
  715. s->last_flush = -1;
  716. return Z_OK;
  717. }
  718. /* Make sure there is something to do and avoid duplicate consecutive
  719. * flushes. For repeated and useless calls with Z_FINISH, we keep
  720. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  721. */
  722. } else if (strm->avail_in == 0 && flush <= old_flush &&
  723. flush != Z_FINISH) {
  724. ERR_RETURN(strm, Z_BUF_ERROR);
  725. }
  726. /* User must not provide more input after the first FINISH: */
  727. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  728. ERR_RETURN(strm, Z_BUF_ERROR);
  729. }
  730. /* Start a new block or continue the current one.
  731. */
  732. if (strm->avail_in != 0 || s->lookahead != 0 ||
  733. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  734. block_state bstate;
  735. bstate = s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
  736. (s->strategy == Z_RLE ? deflate_rle(s, flush) :
  737. (*(configuration_table[s->level].func))(s, flush));
  738. if (bstate == finish_started || bstate == finish_done) {
  739. s->status = FINISH_STATE;
  740. }
  741. if (bstate == need_more || bstate == finish_started) {
  742. if (strm->avail_out == 0) {
  743. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  744. }
  745. return Z_OK;
  746. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  747. * of deflate should use the same flush parameter to make sure
  748. * that the flush is complete. So we don't have to output an
  749. * empty block here, this will be done at next call. This also
  750. * ensures that for a very small output buffer, we emit at most
  751. * one empty block.
  752. */
  753. }
  754. if (bstate == block_done) {
  755. if (flush == Z_PARTIAL_FLUSH) {
  756. _tr_align(s);
  757. } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  758. _tr_stored_block(s, (char*)0, 0L, 0);
  759. /* For a full flush, this empty block will be recognized
  760. * as a special marker by inflate_sync().
  761. */
  762. if (flush == Z_FULL_FLUSH) {
  763. CLEAR_HASH(s); /* forget history */
  764. if (s->lookahead == 0) {
  765. s->strstart = 0;
  766. s->block_start = 0L;
  767. }
  768. }
  769. }
  770. flush_pending(strm);
  771. if (strm->avail_out == 0) {
  772. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  773. return Z_OK;
  774. }
  775. }
  776. }
  777. Assert(strm->avail_out > 0, "bug2");
  778. if (flush != Z_FINISH) return Z_OK;
  779. if (s->wrap <= 0) return Z_STREAM_END;
  780. /* Write the trailer */
  781. #ifdef GZIP
  782. if (s->wrap == 2) {
  783. put_byte(s, (Byte)(strm->adler & 0xff));
  784. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  785. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  786. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  787. put_byte(s, (Byte)(strm->total_in & 0xff));
  788. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  789. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  790. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  791. }
  792. else
  793. #endif
  794. {
  795. putShortMSB(s, (uInt)(strm->adler >> 16));
  796. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  797. }
  798. flush_pending(strm);
  799. /* If avail_out is zero, the application will call deflate again
  800. * to flush the rest.
  801. */
  802. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  803. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  804. }
  805. /* ========================================================================= */
  806. int ZEXPORT deflateEnd (strm)
  807. z_streamp strm;
  808. {
  809. int status;
  810. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  811. status = strm->state->status;
  812. if (status != INIT_STATE &&
  813. status != EXTRA_STATE &&
  814. status != NAME_STATE &&
  815. status != COMMENT_STATE &&
  816. status != HCRC_STATE &&
  817. status != BUSY_STATE &&
  818. status != FINISH_STATE) {
  819. return Z_STREAM_ERROR;
  820. }
  821. /* Deallocate in reverse order of allocations: */
  822. TRY_FREE(strm, strm->state->pending_buf);
  823. TRY_FREE(strm, strm->state->head);
  824. TRY_FREE(strm, strm->state->prev);
  825. TRY_FREE(strm, strm->state->window);
  826. ZFREE(strm, strm->state);
  827. strm->state = Z_NULL;
  828. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  829. }
  830. /* =========================================================================
  831. * Copy the source state to the destination state.
  832. * To simplify the source, this is not supported for 16-bit MSDOS (which
  833. * doesn't have enough memory anyway to duplicate compression states).
  834. */
  835. int ZEXPORT deflateCopy (dest, source)
  836. z_streamp dest;
  837. z_streamp source;
  838. {
  839. #ifdef MAXSEG_64K
  840. return Z_STREAM_ERROR;
  841. #else
  842. deflate_state *ds;
  843. deflate_state *ss;
  844. ushf *overlay;
  845. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  846. return Z_STREAM_ERROR;
  847. }
  848. ss = source->state;
  849. zmemcpy(dest, source, sizeof(z_stream));
  850. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  851. if (ds == Z_NULL) return Z_MEM_ERROR;
  852. dest->state = (struct internal_state FAR *) ds;
  853. zmemcpy(ds, ss, sizeof(deflate_state));
  854. ds->strm = dest;
  855. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  856. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  857. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  858. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  859. ds->pending_buf = (uchf *) overlay;
  860. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  861. ds->pending_buf == Z_NULL) {
  862. deflateEnd (dest);
  863. return Z_MEM_ERROR;
  864. }
  865. /* following zmemcpy do not work for 16-bit MSDOS */
  866. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  867. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  868. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  869. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  870. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  871. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  872. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  873. ds->l_desc.dyn_tree = ds->dyn_ltree;
  874. ds->d_desc.dyn_tree = ds->dyn_dtree;
  875. ds->bl_desc.dyn_tree = ds->bl_tree;
  876. return Z_OK;
  877. #endif /* MAXSEG_64K */
  878. }
  879. /* ===========================================================================
  880. * Read a new buffer from the current input stream, update the adler32
  881. * and total number of bytes read. All deflate() input goes through
  882. * this function so some applications may wish to modify it to avoid
  883. * allocating a large strm->next_in buffer and copying from it.
  884. * (See also flush_pending()).
  885. */
  886. local int read_buf(strm, buf, size)
  887. z_streamp strm;
  888. Bytef *buf;
  889. unsigned size;
  890. {
  891. unsigned len = strm->avail_in;
  892. if (len > size) len = size;
  893. if (len == 0) return 0;
  894. strm->avail_in -= len;
  895. if (strm->state->wrap == 1) {
  896. strm->adler = adler32(strm->adler, strm->next_in, len);
  897. }
  898. #ifdef GZIP
  899. else if (strm->state->wrap == 2) {
  900. strm->adler = crc32(strm->adler, strm->next_in, len);
  901. }
  902. #endif
  903. zmemcpy(buf, strm->next_in, len);
  904. strm->next_in += len;
  905. strm->total_in += len;
  906. return (int)len;
  907. }
  908. /* ===========================================================================
  909. * Initialize the "longest match" routines for a new zlib stream
  910. */
  911. local void lm_init (s)
  912. deflate_state *s;
  913. {
  914. s->window_size = (ulg)2L*s->w_size;
  915. CLEAR_HASH(s);
  916. /* Set the default configuration parameters:
  917. */
  918. s->max_lazy_match = configuration_table[s->level].max_lazy;
  919. s->good_match = configuration_table[s->level].good_length;
  920. s->nice_match = configuration_table[s->level].nice_length;
  921. s->max_chain_length = configuration_table[s->level].max_chain;
  922. s->strstart = 0;
  923. s->block_start = 0L;
  924. s->lookahead = 0;
  925. s->match_length = s->prev_length = MIN_MATCH-1;
  926. s->match_available = 0;
  927. s->ins_h = 0;
  928. #ifndef FASTEST
  929. #ifdef ASMV
  930. match_init(); /* initialize the asm code */
  931. #endif
  932. #endif
  933. }
  934. #ifndef FASTEST
  935. /* ===========================================================================
  936. * Set match_start to the longest match starting at the given string and
  937. * return its length. Matches shorter or equal to prev_length are discarded,
  938. * in which case the result is equal to prev_length and match_start is
  939. * garbage.
  940. * IN assertions: cur_match is the head of the hash chain for the current
  941. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  942. * OUT assertion: the match length is not greater than s->lookahead.
  943. */
  944. #ifndef ASMV
  945. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  946. * match.S. The code will be functionally equivalent.
  947. */
  948. local uInt longest_match(s, cur_match)
  949. deflate_state *s;
  950. IPos cur_match; /* current match */
  951. {
  952. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  953. register Bytef *scan = s->window + s->strstart; /* current string */
  954. register Bytef *match; /* matched string */
  955. register int len; /* length of current match */
  956. int best_len = s->prev_length; /* best match length so far */
  957. int nice_match = s->nice_match; /* stop if match long enough */
  958. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  959. s->strstart - (IPos)MAX_DIST(s) : NIL;
  960. /* Stop when cur_match becomes <= limit. To simplify the code,
  961. * we prevent matches with the string of window index 0.
  962. */
  963. Posf *prev = s->prev;
  964. uInt wmask = s->w_mask;
  965. #ifdef UNALIGNED_OK
  966. /* Compare two bytes at a time. Note: this is not always beneficial.
  967. * Try with and without -DUNALIGNED_OK to check.
  968. */
  969. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  970. register ush scan_start = *(ushf*)scan;
  971. register ush scan_end = *(ushf*)(scan+best_len-1);
  972. #else
  973. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  974. register Byte scan_end1 = scan[best_len-1];
  975. register Byte scan_end = scan[best_len];
  976. #endif
  977. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  978. * It is easy to get rid of this optimization if necessary.
  979. */
  980. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  981. /* Do not waste too much time if we already have a good match: */
  982. if (s->prev_length >= s->good_match) {
  983. chain_length >>= 2;
  984. }
  985. /* Do not look for matches beyond the end of the input. This is necessary
  986. * to make deflate deterministic.
  987. */
  988. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  989. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  990. do {
  991. Assert(cur_match < s->strstart, "no future");
  992. match = s->window + cur_match;
  993. /* Skip to next match if the match length cannot increase
  994. * or if the match length is less than 2. Note that the checks below
  995. * for insufficient lookahead only occur occasionally for performance
  996. * reasons. Therefore uninitialized memory will be accessed, and
  997. * conditional jumps will be made that depend on those values.
  998. * However the length of the match is limited to the lookahead, so
  999. * the output of deflate is not affected by the uninitialized values.
  1000. */
  1001. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  1002. /* This code assumes sizeof(unsigned short) == 2. Do not use
  1003. * UNALIGNED_OK if your compiler uses a different size.
  1004. */
  1005. if (*(ushf*)(match+best_len-1) != scan_end ||
  1006. *(ushf*)match != scan_start) continue;
  1007. /* It is not necessary to compare scan[2] and match[2] since they are
  1008. * always equal when the other bytes match, given that the hash keys
  1009. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  1010. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  1011. * lookahead only every 4th comparison; the 128th check will be made
  1012. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  1013. * necessary to put more guard bytes at the end of the window, or
  1014. * to check more often for insufficient lookahead.
  1015. */
  1016. Assert(scan[2] == match[2], "scan[2]?");
  1017. scan++, match++;
  1018. do {
  1019. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  1020. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  1021. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  1022. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  1023. scan < strend);
  1024. /* The funny "do {}" generates better code on most compilers */
  1025. /* Here, scan <= window+strstart+257 */
  1026. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  1027. if (*scan == *match) scan++;
  1028. len = (MAX_MATCH - 1) - (int)(strend-scan);
  1029. scan = strend - (MAX_MATCH-1);
  1030. #else /* UNALIGNED_OK */
  1031. if (match[best_len] != scan_end ||
  1032. match[best_len-1] != scan_end1 ||
  1033. *match != *scan ||
  1034. *++match != scan[1]) continue;
  1035. /* The check at best_len-1 can be removed because it will be made
  1036. * again later. (This heuristic is not always a win.)
  1037. * It is not necessary to compare scan[2] and match[2] since they
  1038. * are always equal when the other bytes match, given that
  1039. * the hash keys are equal and that HASH_BITS >= 8.
  1040. */
  1041. scan += 2, match++;
  1042. Assert(*scan == *match, "match[2]?");
  1043. /* We check for insufficient lookahead only every 8th comparison;
  1044. * the 256th check will be made at strstart+258.
  1045. */
  1046. do {
  1047. } while (*++scan == *++match && *++scan == *++match &&
  1048. *++scan == *++match && *++scan == *++match &&
  1049. *++scan == *++match && *++scan == *++match &&
  1050. *++scan == *++match && *++scan == *++match &&
  1051. scan < strend);
  1052. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  1053. len = MAX_MATCH - (int)(strend - scan);
  1054. scan = strend - MAX_MATCH;
  1055. #endif /* UNALIGNED_OK */
  1056. if (len > best_len) {
  1057. s->match_start = cur_match;
  1058. best_len = len;
  1059. if (len >= nice_match) break;
  1060. #ifdef UNALIGNED_OK
  1061. scan_end = *(ushf*)(scan+best_len-1);
  1062. #else
  1063. scan_end1 = scan[best_len-1];
  1064. scan_end = scan[best_len];
  1065. #endif
  1066. }
  1067. } while ((cur_match = prev[cur_match & wmask]) > limit
  1068. && --chain_length != 0);
  1069. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  1070. return s->lookahead;
  1071. }
  1072. #endif /* ASMV */
  1073. #else /* FASTEST */
  1074. /* ---------------------------------------------------------------------------
  1075. * Optimized version for FASTEST only
  1076. */
  1077. local uInt longest_match(s, cur_match)
  1078. deflate_state *s;
  1079. IPos cur_match; /* current match */
  1080. {
  1081. register Bytef *scan = s->window + s->strstart; /* current string */
  1082. register Bytef *match; /* matched string */
  1083. register int len; /* length of current match */
  1084. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  1085. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  1086. * It is easy to get rid of this optimization if necessary.
  1087. */
  1088. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  1089. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  1090. Assert(cur_match < s->strstart, "no future");
  1091. match = s->window + cur_match;
  1092. /* Return failure if the match length is less than 2:
  1093. */
  1094. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  1095. /* The check at best_len-1 can be removed because it will be made
  1096. * again later. (This heuristic is not always a win.)
  1097. * It is not necessary to compare scan[2] and match[2] since they
  1098. * are always equal when the other bytes match, given that
  1099. * the hash keys are equal and that HASH_BITS >= 8.
  1100. */
  1101. scan += 2, match += 2;
  1102. Assert(*scan == *match, "match[2]?");
  1103. /* We check for insufficient lookahead only every 8th comparison;
  1104. * the 256th check will be made at strstart+258.
  1105. */
  1106. do {
  1107. } while (*++scan == *++match && *++scan == *++match &&
  1108. *++scan == *++match && *++scan == *++match &&
  1109. *++scan == *++match && *++scan == *++match &&
  1110. *++scan == *++match && *++scan == *++match &&
  1111. scan < strend);
  1112. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  1113. len = MAX_MATCH - (int)(strend - scan);
  1114. if (len < MIN_MATCH) return MIN_MATCH - 1;
  1115. s->match_start = cur_match;
  1116. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  1117. }
  1118. #endif /* FASTEST */
  1119. #ifdef DEBUG
  1120. /* ===========================================================================
  1121. * Check that the match at match_start is indeed a match.
  1122. */
  1123. local void check_match(s, start, match, length)
  1124. deflate_state *s;
  1125. IPos start, match;
  1126. int length;
  1127. {
  1128. /* check that the match is indeed a match */
  1129. if (zmemcmp(s->window + match,
  1130. s->window + start, length) != EQUAL) {
  1131. fprintf(stderr, " start %u, match %u, length %d\n",
  1132. start, match, length);
  1133. do {
  1134. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  1135. } while (--length != 0);
  1136. z_error("invalid match");
  1137. }
  1138. if (z_verbose > 1) {
  1139. fprintf(stderr,"\\[%d,%d]", start-match, length);
  1140. do { putc(s->window[start++], stderr); } while (--length != 0);
  1141. }
  1142. }
  1143. #else
  1144. # define check_match(s, start, match, length)
  1145. #endif /* DEBUG */
  1146. /* ===========================================================================
  1147. * Fill the window when the lookahead becomes insufficient.
  1148. * Updates strstart and lookahead.
  1149. *
  1150. * IN assertion: lookahead < MIN_LOOKAHEAD
  1151. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  1152. * At least one byte has been read, or avail_in == 0; reads are
  1153. * performed for at least two bytes (required for the zip translate_eol
  1154. * option -- not supported here).
  1155. */
  1156. local void fill_window(s)
  1157. deflate_state *s;
  1158. {
  1159. register unsigned n, m;
  1160. register Posf *p;
  1161. unsigned more; /* Amount of free space at the end of the window. */
  1162. uInt wsize = s->w_size;
  1163. do {
  1164. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  1165. /* Deal with !@#$% 64K limit: */
  1166. if (sizeof(int) <= 2) {
  1167. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  1168. more = wsize;
  1169. } else if (more == (unsigned)(-1)) {
  1170. /* Very unlikely, but possible on 16 bit machine if
  1171. * strstart == 0 && lookahead == 1 (input done a byte at time)
  1172. */
  1173. more--;
  1174. }
  1175. }
  1176. /* If the window is almost full and there is insufficient lookahead,
  1177. * move the upper half to the lower one to make room in the upper half.
  1178. */
  1179. if (s->strstart >= wsize+MAX_DIST(s)) {
  1180. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  1181. s->match_start -= wsize;
  1182. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  1183. s->block_start -= (long) wsize;
  1184. /* Slide the hash table (could be avoided with 32 bit values
  1185. at the expense of memory usage). We slide even when level == 0
  1186. to keep the hash table consistent if we switch back to level > 0
  1187. later. (Using level 0 permanently is not an optimal usage of
  1188. zlib, so we don't care about this pathological case.)
  1189. */
  1190. n = s->hash_size;
  1191. p = &s->head[n];
  1192. do {
  1193. m = *--p;
  1194. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  1195. } while (--n);
  1196. n = wsize;
  1197. #ifndef FASTEST
  1198. p = &s->prev[n];
  1199. do {
  1200. m = *--p;
  1201. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  1202. /* If n is not on any hash chain, prev[n] is garbage but
  1203. * its value will never be used.
  1204. */
  1205. } while (--n);
  1206. #endif
  1207. more += wsize;
  1208. }
  1209. if (s->strm->avail_in == 0) return;
  1210. /* If there was no sliding:
  1211. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  1212. * more == window_size - lookahead - strstart
  1213. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  1214. * => more >= window_size - 2*WSIZE + 2
  1215. * In the BIG_MEM or MMAP case (not yet supported),
  1216. * window_size == input_size + MIN_LOOKAHEAD &&
  1217. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  1218. * Otherwise, window_size == 2*WSIZE so more >= 2.
  1219. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  1220. */
  1221. Assert(more >= 2, "more < 2");
  1222. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  1223. s->lookahead += n;
  1224. /* Initialize the hash value now that we have some input: */
  1225. if (s->lookahead >= MIN_MATCH) {
  1226. s->ins_h = s->window[s->strstart];
  1227. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  1228. #if MIN_MATCH != 3
  1229. Call UPDATE_HASH() MIN_MATCH-3 more times
  1230. #endif
  1231. }
  1232. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  1233. * but this is not important since only literal bytes will be emitted.
  1234. */
  1235. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  1236. /* If the WIN_INIT bytes after the end of the current data have never been
  1237. * written, then zero those bytes in order to avoid memory check reports of
  1238. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  1239. * the longest match routines. Update the high water mark for the next
  1240. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  1241. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  1242. */
  1243. if (s->high_water < s->window_size) {
  1244. ulg curr = s->strstart + (ulg)(s->lookahead);
  1245. ulg init;
  1246. if (s->high_water < curr) {
  1247. /* Previous high water mark below current data -- zero WIN_INIT
  1248. * bytes or up to end of window, whichever is less.
  1249. */
  1250. init = s->window_size - curr;
  1251. if (init > WIN_INIT)
  1252. init = WIN_INIT;
  1253. zmemzero(s->window + curr, (unsigned)init);
  1254. s->high_water = curr + init;
  1255. }
  1256. else if (s->high_water < (ulg)curr + WIN_INIT) {
  1257. /* High water mark at or above current data, but below current data
  1258. * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  1259. * to end of window, whichever is less.
  1260. */
  1261. init = (ulg)curr + WIN_INIT - s->high_water;
  1262. if (init > s->window_size - s->high_water)
  1263. init = s->window_size - s->high_water;
  1264. zmemzero(s->window + s->high_water, (unsigned)init);
  1265. s->high_water += init;
  1266. }
  1267. }
  1268. }
  1269. /* ===========================================================================
  1270. * Flush the current block, with given end-of-file flag.
  1271. * IN assertion: strstart is set to the end of the current match.
  1272. */
  1273. #define FLUSH_BLOCK_ONLY(s, last) { \
  1274. _tr_flush_block(s, (s->block_start >= 0L ? \
  1275. (charf *)&s->window[(unsigned)s->block_start] : \
  1276. (charf *)Z_NULL), \
  1277. (ulg)((long)s->strstart - s->block_start), \
  1278. (last)); \
  1279. s->block_start = s->strstart; \
  1280. flush_pending(s->strm); \
  1281. Tracev((stderr,"[FLUSH]")); \
  1282. }
  1283. /* Same but force premature exit if necessary. */
  1284. #define FLUSH_BLOCK(s, last) { \
  1285. FLUSH_BLOCK_ONLY(s, last); \
  1286. if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
  1287. }
  1288. /* ===========================================================================
  1289. * Copy without compression as much as possible from the input stream, return
  1290. * the current block state.
  1291. * This function does not insert new strings in the dictionary since
  1292. * uncompressible data is probably not useful. This function is used
  1293. * only for the level=0 compression option.
  1294. * NOTE: this function should be optimized to avoid extra copying from
  1295. * window to pending_buf.
  1296. */
  1297. local block_state deflate_stored(s, flush)
  1298. deflate_state *s;
  1299. int flush;
  1300. {
  1301. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  1302. * to pending_buf_size, and each stored block has a 5 byte header:
  1303. */
  1304. ulg max_block_size = 0xffff;
  1305. ulg max_start;
  1306. if (max_block_size > s->pending_buf_size - 5) {
  1307. max_block_size = s->pending_buf_size - 5;
  1308. }
  1309. /* Copy as much as possible from input to output: */
  1310. for (;;) {
  1311. /* Fill the window as much as possible: */
  1312. if (s->lookahead <= 1) {
  1313. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  1314. s->block_start >= (long)s->w_size, "slide too late");
  1315. fill_window(s);
  1316. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  1317. if (s->lookahead == 0) break; /* flush the current block */
  1318. }
  1319. Assert(s->block_start >= 0L, "block gone");
  1320. s->strstart += s->lookahead;
  1321. s->lookahead = 0;
  1322. /* Emit a stored block if pending_buf will be full: */
  1323. max_start = s->block_start + max_block_size;
  1324. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  1325. /* strstart == 0 is possible when wraparound on 16-bit machine */
  1326. s->lookahead = (uInt)(s->strstart - max_start);
  1327. s->strstart = (uInt)max_start;
  1328. FLUSH_BLOCK(s, 0);
  1329. }
  1330. /* Flush if we may have to slide, otherwise block_start may become
  1331. * negative and the data will be gone:
  1332. */
  1333. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  1334. FLUSH_BLOCK(s, 0);
  1335. }
  1336. }
  1337. FLUSH_BLOCK(s, flush == Z_FINISH);
  1338. return flush == Z_FINISH ? finish_done : block_done;
  1339. }
  1340. /* ===========================================================================
  1341. * Compress as much as possible from the input stream, return the current
  1342. * block state.
  1343. * This function does not perform lazy evaluation of matches and inserts
  1344. * new strings in the dictionary only for unmatched strings or for short
  1345. * matches. It is used only for the fast compression options.
  1346. */
  1347. local block_state deflate_fast(s, flush)
  1348. deflate_state *s;
  1349. int flush;
  1350. {
  1351. IPos hash_head; /* head of the hash chain */
  1352. int bflush; /* set if current block must be flushed */
  1353. for (;;) {
  1354. /* Make sure that we always have enough lookahead, except
  1355. * at the end of the input file. We need MAX_MATCH bytes
  1356. * for the next match, plus MIN_MATCH bytes to insert the
  1357. * string following the next match.
  1358. */
  1359. if (s->lookahead < MIN_LOOKAHEAD) {
  1360. fill_window(s);
  1361. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  1362. return need_more;
  1363. }
  1364. if (s->lookahead == 0) break; /* flush the current block */
  1365. }
  1366. /* Insert the string window[strstart .. strstart+2] in the
  1367. * dictionary, and set hash_head to the head of the hash chain:
  1368. */
  1369. hash_head = NIL;
  1370. if (s->lookahead >= MIN_MATCH) {
  1371. INSERT_STRING(s, s->strstart, hash_head);
  1372. }
  1373. /* Find the longest match, discarding those <= prev_length.
  1374. * At this point we have always match_length < MIN_MATCH
  1375. */
  1376. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  1377. /* To simplify the code, we prevent matches with the string
  1378. * of window index 0 (in particular we have to avoid a match
  1379. * of the string with itself at the start of the input file).
  1380. */
  1381. s->match_length = longest_match (s, hash_head);
  1382. /* longest_match() sets match_start */
  1383. }
  1384. if (s->match_length >= MIN_MATCH) {
  1385. check_match(s, s->strstart, s->match_start, s->match_length);
  1386. _tr_tally_dist(s, s->strstart - s->match_start,
  1387. s->match_length - MIN_MATCH, bflush);
  1388. s->lookahead -= s->match_length;
  1389. /* Insert new strings in the hash table only if the match length
  1390. * is not too large. This saves time but degrades compression.
  1391. */
  1392. #ifndef FASTEST
  1393. if (s->match_length <= s->max_insert_length &&
  1394. s->lookahead >= MIN_MATCH) {
  1395. s->match_length--; /* string at strstart already in table */
  1396. do {
  1397. s->strstart++;
  1398. INSERT_STRING(s, s->strstart, hash_head);
  1399. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  1400. * always MIN_MATCH bytes ahead.
  1401. */
  1402. } while (--s->match_length != 0);
  1403. s->strstart++;
  1404. } else
  1405. #endif
  1406. {
  1407. s->strstart += s->match_length;
  1408. s->match_length = 0;
  1409. s->ins_h = s->window[s->strstart];
  1410. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  1411. #if MIN_MATCH != 3
  1412. Call UPDATE_HASH() MIN_MATCH-3 more times
  1413. #endif
  1414. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  1415. * matter since it will be recomputed at next deflate call.
  1416. */
  1417. }
  1418. } else {
  1419. /* No match, output a literal byte */
  1420. Tracevv((stderr,"%c", s->window[s->strstart]));
  1421. _tr_tally_lit (s, s->window[s->strstart], bflush);
  1422. s->lookahead--;
  1423. s->strstart++;
  1424. }
  1425. if (bflush) FLUSH_BLOCK(s, 0);
  1426. }
  1427. FLUSH_BLOCK(s, flush == Z_FINISH);
  1428. return flush == Z_FINISH ? finish_done : block_done;
  1429. }
  1430. #ifndef FASTEST
  1431. /* ===========================================================================
  1432. * Same as above, but achieves better compression. We use a lazy
  1433. * evaluation for matches: a match is finally adopted only if there is
  1434. * no better match at the next window position.
  1435. */
  1436. local block_state deflate_slow(s, flush)
  1437. deflate_state *s;
  1438. int flush;
  1439. {
  1440. IPos hash_head; /* head of hash chain */
  1441. int bflush; /* set if current block must be flushed */
  1442. /* Process the input block. */
  1443. for (;;) {
  1444. /* Make sure that we always have enough lookahead, except
  1445. * at the end of the input file. We need MAX_MATCH bytes
  1446. * for the next match, plus MIN_MATCH bytes to insert the
  1447. * string following the next match.
  1448. */
  1449. if (s->lookahead < MIN_LOOKAHEAD) {
  1450. fill_window(s);
  1451. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  1452. return need_more;
  1453. }
  1454. if (s->lookahead == 0) break; /* flush the current block */
  1455. }
  1456. /* Insert the string window[strstart .. strstart+2] in the
  1457. * dictionary, and set hash_head to the head of the hash chain:
  1458. */
  1459. hash_head = NIL;
  1460. if (s->lookahead >= MIN_MATCH) {
  1461. INSERT_STRING(s, s->strstart, hash_head);
  1462. }
  1463. /* Find the longest match, discarding those <= prev_length.
  1464. */
  1465. s->prev_length = s->match_length, s->prev_match = s->match_start;
  1466. s->match_length = MIN_MATCH-1;
  1467. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  1468. s->strstart - hash_head <= MAX_DIST(s)) {
  1469. /* To simplify the code, we prevent matches with the string
  1470. * of window index 0 (in particular we have to avoid a match
  1471. * of the string with itself at the start of the input file).
  1472. */
  1473. s->match_length = longest_match (s, hash_head);
  1474. /* longest_match() sets match_start */
  1475. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  1476. #if TOO_FAR <= 32767
  1477. || (s->match_length == MIN_MATCH &&
  1478. s->strstart - s->match_start > TOO_FAR)
  1479. #endif
  1480. )) {
  1481. /* If prev_match is also MIN_MATCH, match_start is garbage
  1482. * but we will ignore the current match anyway.
  1483. */
  1484. s->match_length = MIN_MATCH-1;
  1485. }
  1486. }
  1487. /* If there was a match at the previous step and the current
  1488. * match is not better, output the previous match:
  1489. */
  1490. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  1491. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  1492. /* Do not insert strings in hash table beyond this. */
  1493. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  1494. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  1495. s->prev_length - MIN_MATCH, bflush);
  1496. /* Insert in hash table all strings up to the end of the match.
  1497. * strstart-1 and strstart are already inserted. If there is not
  1498. * enough lookahead, the last two strings are not inserted in
  1499. * the hash table.
  1500. */
  1501. s->lookahead -= s->prev_length-1;
  1502. s->prev_length -= 2;
  1503. do {
  1504. if (++s->strstart <= max_insert) {
  1505. INSERT_STRING(s, s->strstart, hash_head);
  1506. }
  1507. } while (--s->prev_length != 0);
  1508. s->match_available = 0;
  1509. s->match_length = MIN_MATCH-1;
  1510. s->strstart++;
  1511. if (bflush) FLUSH_BLOCK(s, 0);
  1512. } else if (s->match_available) {
  1513. /* If there was no match at the previous position, output a
  1514. * single literal. If there was a match but the current match
  1515. * is longer, truncate the previous match to a single literal.
  1516. */
  1517. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  1518. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  1519. if (bflush) {
  1520. FLUSH_BLOCK_ONLY(s, 0);
  1521. }
  1522. s->strstart++;
  1523. s->lookahead--;
  1524. if (s->strm->avail_out == 0) return need_more;
  1525. } else {
  1526. /* There is no previous match to compare with, wait for
  1527. * the next step to decide.
  1528. */
  1529. s->match_available = 1;
  1530. s->strstart++;
  1531. s->lookahead--;
  1532. }
  1533. }
  1534. Assert (flush != Z_NO_FLUSH, "no flush?");
  1535. if (s->match_available) {
  1536. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  1537. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  1538. s->match_available = 0;
  1539. }
  1540. FLUSH_BLOCK(s, flush == Z_FINISH);
  1541. return flush == Z_FINISH ? finish_done : block_done;
  1542. }
  1543. #endif /* FASTEST */
  1544. /* ===========================================================================
  1545. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  1546. * one. Do not maintain a hash table. (It will be regenerated if this run of
  1547. * deflate switches away from Z_RLE.)
  1548. */
  1549. local block_state deflate_rle(s, flush)
  1550. deflate_state *s;
  1551. int flush;
  1552. {
  1553. int bflush; /* set if current block must be flushed */
  1554. uInt prev; /* byte at distance one to match */
  1555. Bytef *scan, *strend; /* scan goes up to strend for length of run */
  1556. for (;;) {
  1557. /* Make sure that we always have enough lookahead, except
  1558. * at the end of the input file. We need MAX_MATCH bytes
  1559. * for the longest encodable run.
  1560. */
  1561. if (s->lookahead < MAX_MATCH) {
  1562. fill_window(s);
  1563. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  1564. return need_more;
  1565. }
  1566. if (s->lookahead == 0) break; /* flush the current block */
  1567. }
  1568. /* See how many times the previous byte repeats */
  1569. s->match_length = 0;
  1570. if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
  1571. scan = s->window + s->strstart - 1;
  1572. prev = *scan;
  1573. if (prev == *++scan && prev == *++scan && prev == *++scan) {
  1574. strend = s->window + s->strstart + MAX_MATCH;
  1575. do {
  1576. } while (prev == *++scan && prev == *++scan &&
  1577. prev == *++scan && prev == *++scan &&
  1578. prev == *++scan && prev == *++scan &&
  1579. prev == *++scan && prev == *++scan &&
  1580. scan < strend);
  1581. s->match_length = MAX_MATCH - (int)(strend - scan);
  1582. if (s->match_length > s->lookahead)
  1583. s->match_length = s->lookahead;
  1584. }
  1585. }
  1586. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  1587. if (s->match_length >= MIN_MATCH) {
  1588. check_match(s, s->strstart, s->strstart - 1, s->match_length);
  1589. _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
  1590. s->lookahead -= s->match_length;
  1591. s->strstart += s->match_length;
  1592. s->match_length = 0;
  1593. } else {
  1594. /* No match, output a literal byte */
  1595. Tracevv((stderr,"%c", s->window[s->strstart]));
  1596. _tr_tally_lit (s, s->window[s->strstart], bflush);
  1597. s->lookahead--;
  1598. s->strstart++;
  1599. }
  1600. if (bflush) FLUSH_BLOCK(s, 0);
  1601. }
  1602. FLUSH_BLOCK(s, flush == Z_FINISH);
  1603. return flush == Z_FINISH ? finish_done : block_done;
  1604. }
  1605. /* ===========================================================================
  1606. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  1607. * (It will be regenerated if this run of deflate switches away from Huffman.)
  1608. */
  1609. local block_state deflate_huff(s, flush)
  1610. deflate_state *s;
  1611. int flush;
  1612. {
  1613. int bflush; /* set if current block must be flushed */
  1614. for (;;) {
  1615. /* Make sure that we have a literal to write. */
  1616. if (s->lookahead == 0) {
  1617. fill_window(s);
  1618. if (s->lookahead == 0) {
  1619. if (flush == Z_NO_FLUSH)
  1620. return need_more;
  1621. break; /* flush the current block */
  1622. }
  1623. }
  1624. /* Output a literal byte */
  1625. s->match_length = 0;
  1626. Tracevv((stderr,"%c", s->window[s->strstart]));
  1627. _tr_tally_lit (s, s->window[s->strstart], bflush);
  1628. s->lookahead--;
  1629. s->strstart++;
  1630. if (bflush) FLUSH_BLOCK(s, 0);
  1631. }
  1632. FLUSH_BLOCK(s, flush == Z_FINISH);
  1633. return flush == Z_FINISH ? finish_done : block_done;
  1634. }