1
0

deflate.c 80 KB

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