deflate.c 63 KB

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