deflate.c 77 KB

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