deflate.c 63 KB

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