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