2
0

deflate.c 76 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(
  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_(
  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_(
  217. z_streamp strm,
  218. int level,
  219. int method,
  220. int windowBits,
  221. int memLevel,
  222. int strategy,
  223. const char *version,
  224. int stream_size)
  225. {
  226. deflate_state *s;
  227. int wrap = 1;
  228. static const char my_version[] = ZLIB_VERSION;
  229. ushf *overlay;
  230. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  231. * output size for (length,distance) codes is <= 24 bits.
  232. */
  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. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  294. s->pending_buf = (uchf *) overlay;
  295. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  296. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  297. s->pending_buf == Z_NULL) {
  298. s->status = FINISH_STATE;
  299. strm->msg = ERR_MSG(Z_MEM_ERROR);
  300. deflateEnd (strm);
  301. return Z_MEM_ERROR;
  302. }
  303. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  304. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  305. s->level = level;
  306. s->strategy = strategy;
  307. s->method = (Byte)method;
  308. return deflateReset(strm);
  309. }
  310. /* =========================================================================
  311. * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
  312. */
  313. local int deflateStateCheck (
  314. z_streamp strm)
  315. {
  316. deflate_state *s;
  317. if (strm == Z_NULL ||
  318. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
  319. return 1;
  320. s = strm->state;
  321. if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE &&
  322. #ifdef GZIP
  323. s->status != GZIP_STATE &&
  324. #endif
  325. s->status != EXTRA_STATE &&
  326. s->status != NAME_STATE &&
  327. s->status != COMMENT_STATE &&
  328. s->status != HCRC_STATE &&
  329. s->status != BUSY_STATE &&
  330. s->status != FINISH_STATE))
  331. return 1;
  332. return 0;
  333. }
  334. /* ========================================================================= */
  335. int ZEXPORT deflateSetDictionary (
  336. z_streamp strm,
  337. const Bytef *dictionary,
  338. uInt dictLength)
  339. {
  340. deflate_state *s;
  341. uInt str, n;
  342. int wrap;
  343. unsigned avail;
  344. z_const unsigned char *next;
  345. if (deflateStateCheck(strm) || dictionary == Z_NULL)
  346. return Z_STREAM_ERROR;
  347. s = strm->state;
  348. wrap = s->wrap;
  349. if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
  350. return Z_STREAM_ERROR;
  351. /* when using zlib wrappers, compute Adler-32 for provided dictionary */
  352. if (wrap == 1)
  353. strm->adler = adler32(strm->adler, dictionary, dictLength);
  354. s->wrap = 0; /* avoid computing Adler-32 in read_buf */
  355. /* if dictionary would fill window, just replace the history */
  356. if (dictLength >= s->w_size) {
  357. if (wrap == 0) { /* already empty otherwise */
  358. CLEAR_HASH(s);
  359. s->strstart = 0;
  360. s->block_start = 0L;
  361. s->insert = 0;
  362. }
  363. dictionary += dictLength - s->w_size; /* use the tail */
  364. dictLength = s->w_size;
  365. }
  366. /* insert dictionary into window and hash */
  367. avail = strm->avail_in;
  368. next = strm->next_in;
  369. strm->avail_in = dictLength;
  370. strm->next_in = (z_const Bytef *)dictionary;
  371. fill_window(s);
  372. while (s->lookahead >= MIN_MATCH) {
  373. str = s->strstart;
  374. n = s->lookahead - (MIN_MATCH-1);
  375. do {
  376. UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
  377. #ifndef FASTEST
  378. s->prev[str & s->w_mask] = s->head[s->ins_h];
  379. #endif
  380. s->head[s->ins_h] = (Pos)str;
  381. str++;
  382. } while (--n);
  383. s->strstart = str;
  384. s->lookahead = MIN_MATCH-1;
  385. fill_window(s);
  386. }
  387. s->strstart += s->lookahead;
  388. s->block_start = (long)s->strstart;
  389. s->insert = s->lookahead;
  390. s->lookahead = 0;
  391. s->match_length = s->prev_length = MIN_MATCH-1;
  392. s->match_available = 0;
  393. strm->next_in = next;
  394. strm->avail_in = avail;
  395. s->wrap = wrap;
  396. return Z_OK;
  397. }
  398. /* ========================================================================= */
  399. int ZEXPORT deflateGetDictionary (
  400. z_streamp strm,
  401. Bytef *dictionary,
  402. uInt *dictLength)
  403. {
  404. deflate_state *s;
  405. uInt len;
  406. if (deflateStateCheck(strm))
  407. return Z_STREAM_ERROR;
  408. s = strm->state;
  409. len = s->strstart + s->lookahead;
  410. if (len > s->w_size)
  411. len = s->w_size;
  412. if (dictionary != Z_NULL && len)
  413. zmemcpy(dictionary, s->window + s->strstart + s->lookahead - len, len);
  414. if (dictLength != Z_NULL)
  415. *dictLength = len;
  416. return Z_OK;
  417. }
  418. /* ========================================================================= */
  419. int ZEXPORT deflateResetKeep (
  420. z_streamp strm)
  421. {
  422. deflate_state *s;
  423. if (deflateStateCheck(strm)) {
  424. return Z_STREAM_ERROR;
  425. }
  426. strm->total_in = strm->total_out = 0;
  427. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  428. strm->data_type = Z_UNKNOWN;
  429. s = (deflate_state *)strm->state;
  430. s->pending = 0;
  431. s->pending_out = s->pending_buf;
  432. if (s->wrap < 0) {
  433. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  434. }
  435. s->status =
  436. #ifdef GZIP
  437. s->wrap == 2 ? GZIP_STATE :
  438. #endif
  439. s->wrap ? INIT_STATE : BUSY_STATE;
  440. strm->adler =
  441. #ifdef GZIP
  442. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  443. #endif
  444. adler32(0L, Z_NULL, 0);
  445. s->last_flush = Z_NO_FLUSH;
  446. _tr_init(s);
  447. return Z_OK;
  448. }
  449. /* ========================================================================= */
  450. int ZEXPORT deflateReset (
  451. z_streamp strm)
  452. {
  453. int ret;
  454. ret = deflateResetKeep(strm);
  455. if (ret == Z_OK)
  456. lm_init(strm->state);
  457. return ret;
  458. }
  459. /* ========================================================================= */
  460. int ZEXPORT deflateSetHeader (
  461. z_streamp strm,
  462. gz_headerp head)
  463. {
  464. if (deflateStateCheck(strm) || strm->state->wrap != 2)
  465. return Z_STREAM_ERROR;
  466. strm->state->gzhead = head;
  467. return Z_OK;
  468. }
  469. /* ========================================================================= */
  470. int ZEXPORT deflatePending (
  471. z_streamp strm,
  472. unsigned *pending,
  473. int *bits)
  474. {
  475. if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
  476. if (pending != Z_NULL)
  477. *pending = strm->state->pending;
  478. if (bits != Z_NULL)
  479. *bits = strm->state->bi_valid;
  480. return Z_OK;
  481. }
  482. /* ========================================================================= */
  483. int ZEXPORT deflatePrime (
  484. z_streamp strm,
  485. int bits,
  486. int value)
  487. {
  488. deflate_state *s;
  489. int put;
  490. if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
  491. s = strm->state;
  492. if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3))
  493. return Z_BUF_ERROR;
  494. do {
  495. put = Buf_size - s->bi_valid;
  496. if (put > bits)
  497. put = bits;
  498. s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);
  499. s->bi_valid += put;
  500. _tr_flush_bits(s);
  501. value >>= put;
  502. bits -= put;
  503. } while (bits);
  504. return Z_OK;
  505. }
  506. /* ========================================================================= */
  507. int ZEXPORT deflateParams(
  508. z_streamp strm,
  509. int level,
  510. int strategy)
  511. {
  512. deflate_state *s;
  513. compress_func func;
  514. if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
  515. s = strm->state;
  516. #ifdef FASTEST
  517. if (level != 0) level = 1;
  518. #else
  519. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  520. #endif
  521. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  522. return Z_STREAM_ERROR;
  523. }
  524. func = configuration_table[s->level].func;
  525. if ((strategy != s->strategy || func != configuration_table[level].func) &&
  526. s->high_water) {
  527. /* Flush the last buffer: */
  528. int err = deflate(strm, Z_BLOCK);
  529. if (err == Z_STREAM_ERROR)
  530. return err;
  531. if (strm->avail_out == 0)
  532. return Z_BUF_ERROR;
  533. }
  534. if (s->level != level) {
  535. if (s->level == 0 && s->matches != 0) {
  536. if (s->matches == 1)
  537. slide_hash(s);
  538. else
  539. CLEAR_HASH(s);
  540. s->matches = 0;
  541. }
  542. s->level = level;
  543. s->max_lazy_match = configuration_table[level].max_lazy;
  544. s->good_match = configuration_table[level].good_length;
  545. s->nice_match = configuration_table[level].nice_length;
  546. s->max_chain_length = configuration_table[level].max_chain;
  547. }
  548. s->strategy = strategy;
  549. return Z_OK;
  550. }
  551. /* ========================================================================= */
  552. int ZEXPORT deflateTune(
  553. z_streamp strm,
  554. int good_length,
  555. int max_lazy,
  556. int nice_length,
  557. int max_chain)
  558. {
  559. deflate_state *s;
  560. if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
  561. s = strm->state;
  562. s->good_match = (uInt)good_length;
  563. s->max_lazy_match = (uInt)max_lazy;
  564. s->nice_match = nice_length;
  565. s->max_chain_length = (uInt)max_chain;
  566. return Z_OK;
  567. }
  568. /* =========================================================================
  569. * For the default windowBits of 15 and memLevel of 8, this function returns
  570. * a close to exact, as well as small, upper bound on the compressed size.
  571. * They are coded as constants here for a reason--if the #define's are
  572. * changed, then this function needs to be changed as well. The return
  573. * value for 15 and 8 only works for those exact settings.
  574. *
  575. * For any setting other than those defaults for windowBits and memLevel,
  576. * the value returned is a conservative worst case for the maximum expansion
  577. * resulting from using fixed blocks instead of stored blocks, which deflate
  578. * can emit on compressed data for some combinations of the parameters.
  579. *
  580. * This function could be more sophisticated to provide closer upper bounds for
  581. * every combination of windowBits and memLevel. But even the conservative
  582. * upper bound of about 14% expansion does not seem onerous for output buffer
  583. * allocation.
  584. */
  585. uLong ZEXPORT deflateBound(
  586. z_streamp strm,
  587. uLong sourceLen)
  588. {
  589. deflate_state *s;
  590. uLong complen, wraplen;
  591. /* conservative upper bound for compressed data */
  592. complen = sourceLen +
  593. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
  594. /* if can't get parameters, return conservative bound plus zlib wrapper */
  595. if (deflateStateCheck(strm))
  596. return complen + 6;
  597. /* compute wrapper length */
  598. s = strm->state;
  599. switch (s->wrap) {
  600. case 0: /* raw deflate */
  601. wraplen = 0;
  602. break;
  603. case 1: /* zlib wrapper */
  604. wraplen = 6 + (s->strstart ? 4 : 0);
  605. break;
  606. #ifdef GZIP
  607. case 2: /* gzip wrapper */
  608. wraplen = 18;
  609. if (s->gzhead != Z_NULL) { /* user-supplied gzip header */
  610. Bytef *str;
  611. if (s->gzhead->extra != Z_NULL)
  612. wraplen += 2 + s->gzhead->extra_len;
  613. str = s->gzhead->name;
  614. if (str != Z_NULL)
  615. do {
  616. wraplen++;
  617. } while (*str++);
  618. str = s->gzhead->comment;
  619. if (str != Z_NULL)
  620. do {
  621. wraplen++;
  622. } while (*str++);
  623. if (s->gzhead->hcrc)
  624. wraplen += 2;
  625. }
  626. break;
  627. #endif
  628. default: /* for compiler happiness */
  629. wraplen = 6;
  630. }
  631. /* if not default parameters, return conservative bound */
  632. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  633. return complen + wraplen;
  634. /* default settings: return tight bound for that case */
  635. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
  636. (sourceLen >> 25) + 13 - 6 + wraplen;
  637. }
  638. /* =========================================================================
  639. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  640. * IN assertion: the stream state is correct and there is enough room in
  641. * pending_buf.
  642. */
  643. local void putShortMSB (
  644. deflate_state *s,
  645. uInt b)
  646. {
  647. put_byte(s, (Byte)(b >> 8));
  648. put_byte(s, (Byte)(b & 0xff));
  649. }
  650. /* =========================================================================
  651. * Flush as much pending output as possible. All deflate() output, except for
  652. * some deflate_stored() output, goes through this function so some
  653. * applications may wish to modify it to avoid allocating a large
  654. * strm->next_out buffer and copying into it. (See also read_buf()).
  655. */
  656. local void flush_pending(
  657. z_streamp strm)
  658. {
  659. unsigned len;
  660. deflate_state *s = strm->state;
  661. _tr_flush_bits(s);
  662. len = s->pending;
  663. if (len > strm->avail_out) len = strm->avail_out;
  664. if (len == 0) return;
  665. zmemcpy(strm->next_out, s->pending_out, len);
  666. strm->next_out += len;
  667. s->pending_out += len;
  668. strm->total_out += len;
  669. strm->avail_out -= len;
  670. s->pending -= len;
  671. if (s->pending == 0) {
  672. s->pending_out = s->pending_buf;
  673. }
  674. }
  675. /* ===========================================================================
  676. * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1].
  677. */
  678. #define HCRC_UPDATE(beg) \
  679. do { \
  680. if (s->gzhead->hcrc && s->pending > (beg)) \
  681. strm->adler = crc32(strm->adler, s->pending_buf + (beg), \
  682. s->pending - (beg)); \
  683. } while (0)
  684. /* ========================================================================= */
  685. int ZEXPORT deflate (
  686. z_streamp strm,
  687. int flush)
  688. {
  689. int old_flush; /* value of flush param for previous deflate call */
  690. deflate_state *s;
  691. if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) {
  692. return Z_STREAM_ERROR;
  693. }
  694. s = strm->state;
  695. if (strm->next_out == Z_NULL ||
  696. (strm->avail_in != 0 && strm->next_in == Z_NULL) ||
  697. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  698. ERR_RETURN(strm, Z_STREAM_ERROR);
  699. }
  700. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  701. old_flush = s->last_flush;
  702. s->last_flush = flush;
  703. /* Flush as much pending output as possible */
  704. if (s->pending != 0) {
  705. flush_pending(strm);
  706. if (strm->avail_out == 0) {
  707. /* Since avail_out is 0, deflate will be called again with
  708. * more output space, but possibly with both pending and
  709. * avail_in equal to zero. There won't be anything to do,
  710. * but this is not an error situation so make sure we
  711. * return OK instead of BUF_ERROR at next call of deflate:
  712. */
  713. s->last_flush = -1;
  714. return Z_OK;
  715. }
  716. /* Make sure there is something to do and avoid duplicate consecutive
  717. * flushes. For repeated and useless calls with Z_FINISH, we keep
  718. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  719. */
  720. } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&
  721. flush != Z_FINISH) {
  722. ERR_RETURN(strm, Z_BUF_ERROR);
  723. }
  724. /* User must not provide more input after the first FINISH: */
  725. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  726. ERR_RETURN(strm, Z_BUF_ERROR);
  727. }
  728. /* Write the header */
  729. if (s->status == INIT_STATE) {
  730. /* zlib header */
  731. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  732. uInt level_flags;
  733. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  734. level_flags = 0;
  735. else if (s->level < 6)
  736. level_flags = 1;
  737. else if (s->level == 6)
  738. level_flags = 2;
  739. else
  740. level_flags = 3;
  741. header |= (level_flags << 6);
  742. if (s->strstart != 0) header |= PRESET_DICT;
  743. header += 31 - (header % 31);
  744. putShortMSB(s, header);
  745. /* Save the adler32 of the preset dictionary: */
  746. if (s->strstart != 0) {
  747. putShortMSB(s, (uInt)(strm->adler >> 16));
  748. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  749. }
  750. strm->adler = adler32(0L, Z_NULL, 0);
  751. s->status = BUSY_STATE;
  752. /* Compression must start with an empty pending buffer */
  753. flush_pending(strm);
  754. if (s->pending != 0) {
  755. s->last_flush = -1;
  756. return Z_OK;
  757. }
  758. }
  759. #ifdef GZIP
  760. if (s->status == GZIP_STATE) {
  761. /* gzip header */
  762. strm->adler = crc32(0L, Z_NULL, 0);
  763. put_byte(s, 31);
  764. put_byte(s, 139);
  765. put_byte(s, 8);
  766. if (s->gzhead == Z_NULL) {
  767. put_byte(s, 0);
  768. put_byte(s, 0);
  769. put_byte(s, 0);
  770. put_byte(s, 0);
  771. put_byte(s, 0);
  772. put_byte(s, s->level == 9 ? 2 :
  773. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  774. 4 : 0));
  775. put_byte(s, OS_CODE);
  776. s->status = BUSY_STATE;
  777. /* Compression must start with an empty pending buffer */
  778. flush_pending(strm);
  779. if (s->pending != 0) {
  780. s->last_flush = -1;
  781. return Z_OK;
  782. }
  783. }
  784. else {
  785. put_byte(s, (s->gzhead->text ? 1 : 0) +
  786. (s->gzhead->hcrc ? 2 : 0) +
  787. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  788. (s->gzhead->name == Z_NULL ? 0 : 8) +
  789. (s->gzhead->comment == Z_NULL ? 0 : 16)
  790. );
  791. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  792. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  793. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  794. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  795. put_byte(s, s->level == 9 ? 2 :
  796. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  797. 4 : 0));
  798. put_byte(s, s->gzhead->os & 0xff);
  799. if (s->gzhead->extra != Z_NULL) {
  800. put_byte(s, s->gzhead->extra_len & 0xff);
  801. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  802. }
  803. if (s->gzhead->hcrc)
  804. strm->adler = crc32(strm->adler, s->pending_buf,
  805. s->pending);
  806. s->gzindex = 0;
  807. s->status = EXTRA_STATE;
  808. }
  809. }
  810. if (s->status == EXTRA_STATE) {
  811. if (s->gzhead->extra != Z_NULL) {
  812. ulg beg = s->pending; /* start of bytes to update crc */
  813. uInt left = (s->gzhead->extra_len & 0xffff) - s->gzindex;
  814. while (s->pending + left > s->pending_buf_size) {
  815. uInt copy = s->pending_buf_size - s->pending;
  816. zmemcpy(s->pending_buf + s->pending,
  817. s->gzhead->extra + s->gzindex, copy);
  818. s->pending = s->pending_buf_size;
  819. HCRC_UPDATE(beg);
  820. s->gzindex += copy;
  821. flush_pending(strm);
  822. if (s->pending != 0) {
  823. s->last_flush = -1;
  824. return Z_OK;
  825. }
  826. beg = 0;
  827. left -= copy;
  828. }
  829. zmemcpy(s->pending_buf + s->pending,
  830. s->gzhead->extra + s->gzindex, left);
  831. s->pending += left;
  832. HCRC_UPDATE(beg);
  833. s->gzindex = 0;
  834. }
  835. s->status = NAME_STATE;
  836. }
  837. if (s->status == NAME_STATE) {
  838. if (s->gzhead->name != Z_NULL) {
  839. ulg beg = s->pending; /* start of bytes to update crc */
  840. int val;
  841. do {
  842. if (s->pending == s->pending_buf_size) {
  843. HCRC_UPDATE(beg);
  844. flush_pending(strm);
  845. if (s->pending != 0) {
  846. s->last_flush = -1;
  847. return Z_OK;
  848. }
  849. beg = 0;
  850. }
  851. val = s->gzhead->name[s->gzindex++];
  852. put_byte(s, val);
  853. } while (val != 0);
  854. HCRC_UPDATE(beg);
  855. s->gzindex = 0;
  856. }
  857. s->status = COMMENT_STATE;
  858. }
  859. if (s->status == COMMENT_STATE) {
  860. if (s->gzhead->comment != Z_NULL) {
  861. ulg beg = s->pending; /* start of bytes to update crc */
  862. int val;
  863. do {
  864. if (s->pending == s->pending_buf_size) {
  865. HCRC_UPDATE(beg);
  866. flush_pending(strm);
  867. if (s->pending != 0) {
  868. s->last_flush = -1;
  869. return Z_OK;
  870. }
  871. beg = 0;
  872. }
  873. val = s->gzhead->comment[s->gzindex++];
  874. put_byte(s, val);
  875. } while (val != 0);
  876. HCRC_UPDATE(beg);
  877. }
  878. s->status = HCRC_STATE;
  879. }
  880. if (s->status == HCRC_STATE) {
  881. if (s->gzhead->hcrc) {
  882. if (s->pending + 2 > s->pending_buf_size) {
  883. flush_pending(strm);
  884. if (s->pending != 0) {
  885. s->last_flush = -1;
  886. return Z_OK;
  887. }
  888. }
  889. put_byte(s, (Byte)(strm->adler & 0xff));
  890. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  891. strm->adler = crc32(0L, Z_NULL, 0);
  892. }
  893. s->status = BUSY_STATE;
  894. /* Compression must start with an empty pending buffer */
  895. flush_pending(strm);
  896. if (s->pending != 0) {
  897. s->last_flush = -1;
  898. return Z_OK;
  899. }
  900. }
  901. #endif
  902. /* Start a new block or continue the current one.
  903. */
  904. if (strm->avail_in != 0 || s->lookahead != 0 ||
  905. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  906. block_state bstate;
  907. bstate = s->level == 0 ? deflate_stored(s, flush) :
  908. s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
  909. s->strategy == Z_RLE ? deflate_rle(s, flush) :
  910. (*(configuration_table[s->level].func))(s, flush);
  911. if (bstate == finish_started || bstate == finish_done) {
  912. s->status = FINISH_STATE;
  913. }
  914. if (bstate == need_more || bstate == finish_started) {
  915. if (strm->avail_out == 0) {
  916. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  917. }
  918. return Z_OK;
  919. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  920. * of deflate should use the same flush parameter to make sure
  921. * that the flush is complete. So we don't have to output an
  922. * empty block here, this will be done at next call. This also
  923. * ensures that for a very small output buffer, we emit at most
  924. * one empty block.
  925. */
  926. }
  927. if (bstate == block_done) {
  928. if (flush == Z_PARTIAL_FLUSH) {
  929. _tr_align(s);
  930. } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  931. _tr_stored_block(s, (char*)0, 0L, 0);
  932. /* For a full flush, this empty block will be recognized
  933. * as a special marker by inflate_sync().
  934. */
  935. if (flush == Z_FULL_FLUSH) {
  936. CLEAR_HASH(s); /* forget history */
  937. if (s->lookahead == 0) {
  938. s->strstart = 0;
  939. s->block_start = 0L;
  940. s->insert = 0;
  941. }
  942. }
  943. }
  944. flush_pending(strm);
  945. if (strm->avail_out == 0) {
  946. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  947. return Z_OK;
  948. }
  949. }
  950. }
  951. if (flush != Z_FINISH) return Z_OK;
  952. if (s->wrap <= 0) return Z_STREAM_END;
  953. /* Write the trailer */
  954. #ifdef GZIP
  955. if (s->wrap == 2) {
  956. put_byte(s, (Byte)(strm->adler & 0xff));
  957. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  958. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  959. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  960. put_byte(s, (Byte)(strm->total_in & 0xff));
  961. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  962. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  963. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  964. }
  965. else
  966. #endif
  967. {
  968. putShortMSB(s, (uInt)(strm->adler >> 16));
  969. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  970. }
  971. flush_pending(strm);
  972. /* If avail_out is zero, the application will call deflate again
  973. * to flush the rest.
  974. */
  975. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  976. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  977. }
  978. /* ========================================================================= */
  979. int ZEXPORT deflateEnd (
  980. z_streamp strm)
  981. {
  982. int status;
  983. if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
  984. status = strm->state->status;
  985. /* Deallocate in reverse order of allocations: */
  986. TRY_FREE(strm, strm->state->pending_buf);
  987. TRY_FREE(strm, strm->state->head);
  988. TRY_FREE(strm, strm->state->prev);
  989. TRY_FREE(strm, strm->state->window);
  990. ZFREE(strm, strm->state);
  991. strm->state = Z_NULL;
  992. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  993. }
  994. /* =========================================================================
  995. * Copy the source state to the destination state.
  996. * To simplify the source, this is not supported for 16-bit MSDOS (which
  997. * doesn't have enough memory anyway to duplicate compression states).
  998. */
  999. int ZEXPORT deflateCopy (
  1000. z_streamp dest,
  1001. z_streamp source)
  1002. {
  1003. #ifdef MAXSEG_64K
  1004. return Z_STREAM_ERROR;
  1005. #else
  1006. deflate_state *ds;
  1007. deflate_state *ss;
  1008. ushf *overlay;
  1009. if (deflateStateCheck(source) || dest == Z_NULL) {
  1010. return Z_STREAM_ERROR;
  1011. }
  1012. ss = source->state;
  1013. zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
  1014. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  1015. if (ds == Z_NULL) return Z_MEM_ERROR;
  1016. dest->state = (struct internal_state FAR *) ds;
  1017. zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));
  1018. ds->strm = dest;
  1019. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  1020. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  1021. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  1022. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  1023. ds->pending_buf = (uchf *) overlay;
  1024. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  1025. ds->pending_buf == Z_NULL) {
  1026. deflateEnd (dest);
  1027. return Z_MEM_ERROR;
  1028. }
  1029. /* following zmemcpy do not work for 16-bit MSDOS */
  1030. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  1031. zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));
  1032. zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));
  1033. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  1034. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  1035. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  1036. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  1037. ds->l_desc.dyn_tree = ds->dyn_ltree;
  1038. ds->d_desc.dyn_tree = ds->dyn_dtree;
  1039. ds->bl_desc.dyn_tree = ds->bl_tree;
  1040. return Z_OK;
  1041. #endif /* MAXSEG_64K */
  1042. }
  1043. /* ===========================================================================
  1044. * Read a new buffer from the current input stream, update the adler32
  1045. * and total number of bytes read. All deflate() input goes through
  1046. * this function so some applications may wish to modify it to avoid
  1047. * allocating a large strm->next_in buffer and copying from it.
  1048. * (See also flush_pending()).
  1049. */
  1050. local unsigned read_buf(
  1051. z_streamp strm,
  1052. Bytef *buf,
  1053. unsigned size)
  1054. {
  1055. unsigned len = strm->avail_in;
  1056. if (len > size) len = size;
  1057. if (len == 0) return 0;
  1058. strm->avail_in -= len;
  1059. zmemcpy(buf, strm->next_in, len);
  1060. if (strm->state->wrap == 1) {
  1061. strm->adler = adler32(strm->adler, buf, len);
  1062. }
  1063. #ifdef GZIP
  1064. else if (strm->state->wrap == 2) {
  1065. strm->adler = crc32(strm->adler, buf, len);
  1066. }
  1067. #endif
  1068. strm->next_in += len;
  1069. strm->total_in += len;
  1070. return len;
  1071. }
  1072. /* ===========================================================================
  1073. * Initialize the "longest match" routines for a new zlib stream
  1074. */
  1075. local void lm_init (
  1076. deflate_state *s)
  1077. {
  1078. s->window_size = (ulg)2L*s->w_size;
  1079. CLEAR_HASH(s);
  1080. /* Set the default configuration parameters:
  1081. */
  1082. s->max_lazy_match = configuration_table[s->level].max_lazy;
  1083. s->good_match = configuration_table[s->level].good_length;
  1084. s->nice_match = configuration_table[s->level].nice_length;
  1085. s->max_chain_length = configuration_table[s->level].max_chain;
  1086. s->strstart = 0;
  1087. s->block_start = 0L;
  1088. s->lookahead = 0;
  1089. s->insert = 0;
  1090. s->match_length = s->prev_length = MIN_MATCH-1;
  1091. s->match_available = 0;
  1092. s->ins_h = 0;
  1093. #ifndef FASTEST
  1094. #ifdef ASMV
  1095. match_init(); /* initialize the asm code */
  1096. #endif
  1097. #endif
  1098. }
  1099. #ifndef FASTEST
  1100. /* ===========================================================================
  1101. * Set match_start to the longest match starting at the given string and
  1102. * return its length. Matches shorter or equal to prev_length are discarded,
  1103. * in which case the result is equal to prev_length and match_start is
  1104. * garbage.
  1105. * IN assertions: cur_match is the head of the hash chain for the current
  1106. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  1107. * OUT assertion: the match length is not greater than s->lookahead.
  1108. */
  1109. #ifndef ASMV
  1110. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  1111. * match.S. The code will be functionally equivalent.
  1112. */
  1113. local uInt longest_match(
  1114. deflate_state *s,
  1115. IPos cur_match)
  1116. {
  1117. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  1118. register Bytef *scan = s->window + s->strstart; /* current string */
  1119. register Bytef *match; /* matched string */
  1120. register int len; /* length of current match */
  1121. int best_len = (int)s->prev_length; /* best match length so far */
  1122. int nice_match = s->nice_match; /* stop if match long enough */
  1123. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  1124. s->strstart - (IPos)MAX_DIST(s) : NIL;
  1125. /* Stop when cur_match becomes <= limit. To simplify the code,
  1126. * we prevent matches with the string of window index 0.
  1127. */
  1128. Posf *prev = s->prev;
  1129. uInt wmask = s->w_mask;
  1130. #ifdef UNALIGNED_OK
  1131. /* Compare two bytes at a time. Note: this is not always beneficial.
  1132. * Try with and without -DUNALIGNED_OK to check.
  1133. */
  1134. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  1135. register ush scan_start = *(ushf*)scan;
  1136. register ush scan_end = *(ushf*)(scan+best_len-1);
  1137. #else
  1138. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  1139. register Byte scan_end1 = scan[best_len-1];
  1140. register Byte scan_end = scan[best_len];
  1141. #endif
  1142. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  1143. * It is easy to get rid of this optimization if necessary.
  1144. */
  1145. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  1146. /* Do not waste too much time if we already have a good match: */
  1147. if (s->prev_length >= s->good_match) {
  1148. chain_length >>= 2;
  1149. }
  1150. /* Do not look for matches beyond the end of the input. This is necessary
  1151. * to make deflate deterministic.
  1152. */
  1153. if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead;
  1154. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  1155. do {
  1156. Assert(cur_match < s->strstart, "no future");
  1157. match = s->window + cur_match;
  1158. /* Skip to next match if the match length cannot increase
  1159. * or if the match length is less than 2. Note that the checks below
  1160. * for insufficient lookahead only occur occasionally for performance
  1161. * reasons. Therefore uninitialized memory will be accessed, and
  1162. * conditional jumps will be made that depend on those values.
  1163. * However the length of the match is limited to the lookahead, so
  1164. * the output of deflate is not affected by the uninitialized values.
  1165. */
  1166. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  1167. /* This code assumes sizeof(unsigned short) == 2. Do not use
  1168. * UNALIGNED_OK if your compiler uses a different size.
  1169. */
  1170. if (*(ushf*)(match+best_len-1) != scan_end ||
  1171. *(ushf*)match != scan_start) continue;
  1172. /* It is not necessary to compare scan[2] and match[2] since they are
  1173. * always equal when the other bytes match, given that the hash keys
  1174. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  1175. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  1176. * lookahead only every 4th comparison; the 128th check will be made
  1177. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  1178. * necessary to put more guard bytes at the end of the window, or
  1179. * to check more often for insufficient lookahead.
  1180. */
  1181. Assert(scan[2] == match[2], "scan[2]?");
  1182. scan++, match++;
  1183. do {
  1184. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  1185. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  1186. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  1187. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  1188. scan < strend);
  1189. /* The funny "do {}" generates better code on most compilers */
  1190. /* Here, scan <= window+strstart+257 */
  1191. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  1192. if (*scan == *match) scan++;
  1193. len = (MAX_MATCH - 1) - (int)(strend-scan);
  1194. scan = strend - (MAX_MATCH-1);
  1195. #else /* UNALIGNED_OK */
  1196. if (match[best_len] != scan_end ||
  1197. match[best_len-1] != scan_end1 ||
  1198. *match != *scan ||
  1199. *++match != scan[1]) continue;
  1200. /* The check at best_len-1 can be removed because it will be made
  1201. * again later. (This heuristic is not always a win.)
  1202. * It is not necessary to compare scan[2] and match[2] since they
  1203. * are always equal when the other bytes match, given that
  1204. * the hash keys are equal and that HASH_BITS >= 8.
  1205. */
  1206. scan += 2, match++;
  1207. Assert(*scan == *match, "match[2]?");
  1208. /* We check for insufficient lookahead only every 8th comparison;
  1209. * the 256th check will be made at strstart+258.
  1210. */
  1211. do {
  1212. } while (*++scan == *++match && *++scan == *++match &&
  1213. *++scan == *++match && *++scan == *++match &&
  1214. *++scan == *++match && *++scan == *++match &&
  1215. *++scan == *++match && *++scan == *++match &&
  1216. scan < strend);
  1217. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  1218. len = MAX_MATCH - (int)(strend - scan);
  1219. scan = strend - MAX_MATCH;
  1220. #endif /* UNALIGNED_OK */
  1221. if (len > best_len) {
  1222. s->match_start = cur_match;
  1223. best_len = len;
  1224. if (len >= nice_match) break;
  1225. #ifdef UNALIGNED_OK
  1226. scan_end = *(ushf*)(scan+best_len-1);
  1227. #else
  1228. scan_end1 = scan[best_len-1];
  1229. scan_end = scan[best_len];
  1230. #endif
  1231. }
  1232. } while ((cur_match = prev[cur_match & wmask]) > limit
  1233. && --chain_length != 0);
  1234. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  1235. return s->lookahead;
  1236. }
  1237. #endif /* ASMV */
  1238. #else /* FASTEST */
  1239. /* ---------------------------------------------------------------------------
  1240. * Optimized version for FASTEST only
  1241. */
  1242. local uInt longest_match(
  1243. deflate_state *s,
  1244. IPos cur_match)
  1245. {
  1246. register Bytef *scan = s->window + s->strstart; /* current string */
  1247. register Bytef *match; /* matched string */
  1248. register int len; /* length of current match */
  1249. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  1250. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  1251. * It is easy to get rid of this optimization if necessary.
  1252. */
  1253. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  1254. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  1255. Assert(cur_match < s->strstart, "no future");
  1256. match = s->window + cur_match;
  1257. /* Return failure if the match length is less than 2:
  1258. */
  1259. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  1260. /* The check at best_len-1 can be removed because it will be made
  1261. * again later. (This heuristic is not always a win.)
  1262. * It is not necessary to compare scan[2] and match[2] since they
  1263. * are always equal when the other bytes match, given that
  1264. * the hash keys are equal and that HASH_BITS >= 8.
  1265. */
  1266. scan += 2, match += 2;
  1267. Assert(*scan == *match, "match[2]?");
  1268. /* We check for insufficient lookahead only every 8th comparison;
  1269. * the 256th check will be made at strstart+258.
  1270. */
  1271. do {
  1272. } while (*++scan == *++match && *++scan == *++match &&
  1273. *++scan == *++match && *++scan == *++match &&
  1274. *++scan == *++match && *++scan == *++match &&
  1275. *++scan == *++match && *++scan == *++match &&
  1276. scan < strend);
  1277. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  1278. len = MAX_MATCH - (int)(strend - scan);
  1279. if (len < MIN_MATCH) return MIN_MATCH - 1;
  1280. s->match_start = cur_match;
  1281. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  1282. }
  1283. #endif /* FASTEST */
  1284. #ifdef ZLIB_DEBUG
  1285. #define EQUAL 0
  1286. /* result of memcmp for equal strings */
  1287. /* ===========================================================================
  1288. * Check that the match at match_start is indeed a match.
  1289. */
  1290. local void check_match(
  1291. deflate_state *s,
  1292. IPos start,
  1293. IPos 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(
  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(
  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(
  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(
  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(
  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(
  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. }