deflate.c 77 KB

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