deflate.c 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174
  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.1 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. do { \
  174. s->head[s->hash_size-1] = NIL; \
  175. zmemzero((Bytef *)s->head, \
  176. (unsigned)(s->hash_size-1)*sizeof(*s->head)); \
  177. } while (0)
  178. /* ===========================================================================
  179. * Slide the hash table when sliding the window down (could be avoided with 32
  180. * bit values at the expense of memory usage). We slide even when level == 0 to
  181. * keep the hash table consistent if we switch back to level > 0 later.
  182. */
  183. local void slide_hash(s)
  184. deflate_state *s;
  185. {
  186. unsigned n, m;
  187. Posf *p;
  188. uInt wsize = s->w_size;
  189. n = s->hash_size;
  190. p = &s->head[n];
  191. do {
  192. m = *--p;
  193. *p = (Pos)(m >= wsize ? m - wsize : NIL);
  194. } while (--n);
  195. n = wsize;
  196. #ifndef FASTEST
  197. p = &s->prev[n];
  198. do {
  199. m = *--p;
  200. *p = (Pos)(m >= wsize ? m - wsize : NIL);
  201. /* If n is not on any hash chain, prev[n] is garbage but
  202. * its value will never be used.
  203. */
  204. } while (--n);
  205. #endif
  206. }
  207. /* ========================================================================= */
  208. int ZEXPORT deflateInit_(strm, level, version, stream_size)
  209. z_streamp strm;
  210. int level;
  211. const char *version;
  212. int stream_size;
  213. {
  214. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  215. Z_DEFAULT_STRATEGY, version, stream_size);
  216. /* To do: ignore strm->next_in if we use it as window */
  217. }
  218. /* ========================================================================= */
  219. int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
  220. version, stream_size)
  221. z_streamp strm;
  222. int level;
  223. int method;
  224. int windowBits;
  225. int memLevel;
  226. int strategy;
  227. const char *version;
  228. int stream_size;
  229. {
  230. deflate_state *s;
  231. int wrap = 1;
  232. static const char my_version[] = ZLIB_VERSION;
  233. ushf *overlay;
  234. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  235. * output size for (length,distance) codes is <= 24 bits.
  236. */
  237. if (version == Z_NULL || version[0] != my_version[0] ||
  238. stream_size != sizeof(z_stream)) {
  239. return Z_VERSION_ERROR;
  240. }
  241. if (strm == Z_NULL) return Z_STREAM_ERROR;
  242. strm->msg = Z_NULL;
  243. if (strm->zalloc == (alloc_func)0) {
  244. #ifdef Z_SOLO
  245. return Z_STREAM_ERROR;
  246. #else
  247. strm->zalloc = zcalloc;
  248. strm->opaque = (voidpf)0;
  249. #endif
  250. }
  251. if (strm->zfree == (free_func)0)
  252. #ifdef Z_SOLO
  253. return Z_STREAM_ERROR;
  254. #else
  255. strm->zfree = zcfree;
  256. #endif
  257. #ifdef FASTEST
  258. if (level != 0) level = 1;
  259. #else
  260. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  261. #endif
  262. if (windowBits < 0) { /* suppress zlib wrapper */
  263. wrap = 0;
  264. windowBits = -windowBits;
  265. }
  266. #ifdef GZIP
  267. else if (windowBits > 15) {
  268. wrap = 2; /* write gzip wrapper instead */
  269. windowBits -= 16;
  270. }
  271. #endif
  272. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  273. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  274. strategy < 0 || strategy > Z_FIXED || (windowBits == 8 && wrap != 1)) {
  275. return Z_STREAM_ERROR;
  276. }
  277. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  278. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  279. if (s == Z_NULL) return Z_MEM_ERROR;
  280. strm->state = (struct internal_state FAR *)s;
  281. s->strm = strm;
  282. s->status = INIT_STATE; /* to pass state test in deflateReset() */
  283. s->wrap = wrap;
  284. s->gzhead = Z_NULL;
  285. s->w_bits = (uInt)windowBits;
  286. s->w_size = 1 << s->w_bits;
  287. s->w_mask = s->w_size - 1;
  288. s->hash_bits = (uInt)memLevel + 7;
  289. s->hash_size = 1 << s->hash_bits;
  290. s->hash_mask = s->hash_size - 1;
  291. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  292. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  293. s->prev = (Posf *) ZALLOC(strm, 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 = -2;
  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->last_flush != -2) {
  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_in || (s->strstart - s->block_start) + s->lookahead)
  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. 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. if (s->insert > s->strstart)
  1356. s->insert = s->strstart;
  1357. slide_hash(s);
  1358. more += wsize;
  1359. }
  1360. if (s->strm->avail_in == 0) break;
  1361. /* If there was no sliding:
  1362. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  1363. * more == window_size - lookahead - strstart
  1364. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  1365. * => more >= window_size - 2*WSIZE + 2
  1366. * In the BIG_MEM or MMAP case (not yet supported),
  1367. * window_size == input_size + MIN_LOOKAHEAD &&
  1368. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  1369. * Otherwise, window_size == 2*WSIZE so more >= 2.
  1370. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  1371. */
  1372. Assert(more >= 2, "more < 2");
  1373. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  1374. s->lookahead += n;
  1375. /* Initialize the hash value now that we have some input: */
  1376. if (s->lookahead + s->insert >= MIN_MATCH) {
  1377. uInt str = s->strstart - s->insert;
  1378. s->ins_h = s->window[str];
  1379. UPDATE_HASH(s, s->ins_h, s->window[str + 1]);
  1380. #if MIN_MATCH != 3
  1381. Call UPDATE_HASH() MIN_MATCH-3 more times
  1382. #endif
  1383. while (s->insert) {
  1384. UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
  1385. #ifndef FASTEST
  1386. s->prev[str & s->w_mask] = s->head[s->ins_h];
  1387. #endif
  1388. s->head[s->ins_h] = (Pos)str;
  1389. str++;
  1390. s->insert--;
  1391. if (s->lookahead + s->insert < MIN_MATCH)
  1392. break;
  1393. }
  1394. }
  1395. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  1396. * but this is not important since only literal bytes will be emitted.
  1397. */
  1398. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  1399. /* If the WIN_INIT bytes after the end of the current data have never been
  1400. * written, then zero those bytes in order to avoid memory check reports of
  1401. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  1402. * the longest match routines. Update the high water mark for the next
  1403. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  1404. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  1405. */
  1406. if (s->high_water < s->window_size) {
  1407. ulg curr = s->strstart + (ulg)(s->lookahead);
  1408. ulg init;
  1409. if (s->high_water < curr) {
  1410. /* Previous high water mark below current data -- zero WIN_INIT
  1411. * bytes or up to end of window, whichever is less.
  1412. */
  1413. init = s->window_size - curr;
  1414. if (init > WIN_INIT)
  1415. init = WIN_INIT;
  1416. zmemzero(s->window + curr, (unsigned)init);
  1417. s->high_water = curr + init;
  1418. }
  1419. else if (s->high_water < (ulg)curr + WIN_INIT) {
  1420. /* High water mark at or above current data, but below current data
  1421. * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  1422. * to end of window, whichever is less.
  1423. */
  1424. init = (ulg)curr + WIN_INIT - s->high_water;
  1425. if (init > s->window_size - s->high_water)
  1426. init = s->window_size - s->high_water;
  1427. zmemzero(s->window + s->high_water, (unsigned)init);
  1428. s->high_water += init;
  1429. }
  1430. }
  1431. Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  1432. "not enough room for search");
  1433. }
  1434. /* ===========================================================================
  1435. * Flush the current block, with given end-of-file flag.
  1436. * IN assertion: strstart is set to the end of the current match.
  1437. */
  1438. #define FLUSH_BLOCK_ONLY(s, last) { \
  1439. _tr_flush_block(s, (s->block_start >= 0L ? \
  1440. (charf *)&s->window[(unsigned)s->block_start] : \
  1441. (charf *)Z_NULL), \
  1442. (ulg)((long)s->strstart - s->block_start), \
  1443. (last)); \
  1444. s->block_start = s->strstart; \
  1445. flush_pending(s->strm); \
  1446. Tracev((stderr,"[FLUSH]")); \
  1447. }
  1448. /* Same but force premature exit if necessary. */
  1449. #define FLUSH_BLOCK(s, last) { \
  1450. FLUSH_BLOCK_ONLY(s, last); \
  1451. if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
  1452. }
  1453. /* Maximum stored block length in deflate format (not including header). */
  1454. #define MAX_STORED 65535
  1455. /* Minimum of a and b. */
  1456. #define MIN(a, b) ((a) > (b) ? (b) : (a))
  1457. /* ===========================================================================
  1458. * Copy without compression as much as possible from the input stream, return
  1459. * the current block state.
  1460. *
  1461. * In case deflateParams() is used to later switch to a non-zero compression
  1462. * level, s->matches (otherwise unused when storing) keeps track of the number
  1463. * of hash table slides to perform. If s->matches is 1, then one hash table
  1464. * slide will be done when switching. If s->matches is 2, the maximum value
  1465. * allowed here, then the hash table will be cleared, since two or more slides
  1466. * is the same as a clear.
  1467. *
  1468. * deflate_stored() is written to minimize the number of times an input byte is
  1469. * copied. It is most efficient with large input and output buffers, which
  1470. * maximizes the opportunites to have a single copy from next_in to next_out.
  1471. */
  1472. local block_state deflate_stored(s, flush)
  1473. deflate_state *s;
  1474. int flush;
  1475. {
  1476. /* Smallest worthy block size when not flushing or finishing. By default
  1477. * this is 32K. This can be as small as 507 bytes for memLevel == 1. For
  1478. * large input and output buffers, the stored block size will be larger.
  1479. */
  1480. unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size);
  1481. /* Copy as many min_block or larger stored blocks directly to next_out as
  1482. * possible. If flushing, copy the remaining available input to next_out as
  1483. * stored blocks, if there is enough space.
  1484. */
  1485. unsigned len, left, have, last = 0;
  1486. unsigned used = s->strm->avail_in;
  1487. do {
  1488. /* Set len to the maximum size block that we can copy directly with the
  1489. * available input data and output space. Set left to how much of that
  1490. * would be copied from what's left in the window.
  1491. */
  1492. len = MAX_STORED; /* maximum deflate stored block length */
  1493. have = (s->bi_valid + 42) >> 3; /* number of header bytes */
  1494. if (s->strm->avail_out < have) /* need room for header */
  1495. break;
  1496. /* maximum stored block length that will fit in avail_out: */
  1497. have = s->strm->avail_out - have;
  1498. left = s->strstart - s->block_start; /* bytes left in window */
  1499. if (len > (ulg)left + s->strm->avail_in)
  1500. len = left + s->strm->avail_in; /* limit len to the input */
  1501. if (len > have)
  1502. len = have; /* limit len to the output */
  1503. /* If the stored block would be less than min_block in length, or if
  1504. * unable to copy all of the available input when flushing, then try
  1505. * copying to the window and the pending buffer instead. Also don't
  1506. * write an empty block when flushing -- deflate() does that.
  1507. */
  1508. if (len < min_block && ((len == 0 && flush != Z_FINISH) ||
  1509. flush == Z_NO_FLUSH ||
  1510. len != left + s->strm->avail_in))
  1511. break;
  1512. /* Make a dummy stored block in pending to get the header bytes,
  1513. * including any pending bits. This also updates the debugging counts.
  1514. */
  1515. last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0;
  1516. _tr_stored_block(s, (char *)0, 0L, last);
  1517. /* Replace the lengths in the dummy stored block with len. */
  1518. s->pending_buf[s->pending - 4] = len;
  1519. s->pending_buf[s->pending - 3] = len >> 8;
  1520. s->pending_buf[s->pending - 2] = ~len;
  1521. s->pending_buf[s->pending - 1] = ~len >> 8;
  1522. /* Write the stored block header bytes. */
  1523. flush_pending(s->strm);
  1524. #ifdef ZLIB_DEBUG
  1525. /* Update debugging counts for the data about to be copied. */
  1526. s->compressed_len += len << 3;
  1527. s->bits_sent += len << 3;
  1528. #endif
  1529. /* Copy uncompressed bytes from the window to next_out. */
  1530. if (left) {
  1531. if (left > len)
  1532. left = len;
  1533. zmemcpy(s->strm->next_out, s->window + s->block_start, left);
  1534. s->strm->next_out += left;
  1535. s->strm->avail_out -= left;
  1536. s->strm->total_out += left;
  1537. s->block_start += left;
  1538. len -= left;
  1539. }
  1540. /* Copy uncompressed bytes directly from next_in to next_out, updating
  1541. * the check value.
  1542. */
  1543. if (len) {
  1544. read_buf(s->strm, s->strm->next_out, len);
  1545. s->strm->next_out += len;
  1546. s->strm->avail_out -= len;
  1547. s->strm->total_out += len;
  1548. }
  1549. } while (last == 0);
  1550. /* Update the sliding window with the last s->w_size bytes of the copied
  1551. * data, or append all of the copied data to the existing window if less
  1552. * than s->w_size bytes were copied. Also update the number of bytes to
  1553. * insert in the hash tables, in the event that deflateParams() switches to
  1554. * a non-zero compression level.
  1555. */
  1556. used -= s->strm->avail_in; /* number of input bytes directly copied */
  1557. if (used) {
  1558. /* If any input was used, then no unused input remains in the window,
  1559. * therefore s->block_start == s->strstart.
  1560. */
  1561. if (used >= s->w_size) { /* supplant the previous history */
  1562. s->matches = 2; /* clear hash */
  1563. zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);
  1564. s->strstart = s->w_size;
  1565. s->insert = s->strstart;
  1566. }
  1567. else {
  1568. if (s->window_size - s->strstart <= used) {
  1569. /* Slide the window down. */
  1570. s->strstart -= s->w_size;
  1571. zmemcpy(s->window, s->window + s->w_size, s->strstart);
  1572. if (s->matches < 2)
  1573. s->matches++; /* add a pending slide_hash() */
  1574. if (s->insert > s->strstart)
  1575. s->insert = s->strstart;
  1576. }
  1577. zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);
  1578. s->strstart += used;
  1579. s->insert += MIN(used, s->w_size - s->insert);
  1580. }
  1581. s->block_start = s->strstart;
  1582. }
  1583. if (s->high_water < s->strstart)
  1584. s->high_water = s->strstart;
  1585. /* If the last block was written to next_out, then done. */
  1586. if (last)
  1587. return finish_done;
  1588. /* If flushing and all input has been consumed, then done. */
  1589. if (flush != Z_NO_FLUSH && flush != Z_FINISH &&
  1590. s->strm->avail_in == 0 && (long)s->strstart == s->block_start)
  1591. return block_done;
  1592. /* Fill the window with any remaining input. */
  1593. have = s->window_size - s->strstart;
  1594. if (s->strm->avail_in > have && s->block_start >= (long)s->w_size) {
  1595. /* Slide the window down. */
  1596. s->block_start -= s->w_size;
  1597. s->strstart -= s->w_size;
  1598. zmemcpy(s->window, s->window + s->w_size, s->strstart);
  1599. if (s->matches < 2)
  1600. s->matches++; /* add a pending slide_hash() */
  1601. have += s->w_size; /* more space now */
  1602. if (s->insert > s->strstart)
  1603. s->insert = s->strstart;
  1604. }
  1605. if (have > s->strm->avail_in)
  1606. have = s->strm->avail_in;
  1607. if (have) {
  1608. read_buf(s->strm, s->window + s->strstart, have);
  1609. s->strstart += have;
  1610. s->insert += MIN(have, s->w_size - s->insert);
  1611. }
  1612. if (s->high_water < s->strstart)
  1613. s->high_water = s->strstart;
  1614. /* There was not enough avail_out to write a complete worthy or flushed
  1615. * stored block to next_out. Write a stored block to pending instead, if we
  1616. * have enough input for a worthy block, or if flushing and there is enough
  1617. * room for the remaining input as a stored block in the pending buffer.
  1618. */
  1619. have = (s->bi_valid + 42) >> 3; /* number of header bytes */
  1620. /* maximum stored block length that will fit in pending: */
  1621. have = MIN(s->pending_buf_size - have, MAX_STORED);
  1622. min_block = MIN(have, s->w_size);
  1623. left = s->strstart - s->block_start;
  1624. if (left >= min_block ||
  1625. ((left || flush == Z_FINISH) && flush != Z_NO_FLUSH &&
  1626. s->strm->avail_in == 0 && left <= have)) {
  1627. len = MIN(left, have);
  1628. last = flush == Z_FINISH && s->strm->avail_in == 0 &&
  1629. len == left ? 1 : 0;
  1630. _tr_stored_block(s, (charf *)s->window + s->block_start, len, last);
  1631. s->block_start += len;
  1632. flush_pending(s->strm);
  1633. }
  1634. /* We've done all we can with the available input and output. */
  1635. return last ? finish_started : need_more;
  1636. }
  1637. /* ===========================================================================
  1638. * Compress as much as possible from the input stream, return the current
  1639. * block state.
  1640. * This function does not perform lazy evaluation of matches and inserts
  1641. * new strings in the dictionary only for unmatched strings or for short
  1642. * matches. It is used only for the fast compression options.
  1643. */
  1644. local block_state deflate_fast(s, flush)
  1645. deflate_state *s;
  1646. int flush;
  1647. {
  1648. IPos hash_head; /* head of the hash chain */
  1649. int bflush; /* set if current block must be flushed */
  1650. for (;;) {
  1651. /* Make sure that we always have enough lookahead, except
  1652. * at the end of the input file. We need MAX_MATCH bytes
  1653. * for the next match, plus MIN_MATCH bytes to insert the
  1654. * string following the next match.
  1655. */
  1656. if (s->lookahead < MIN_LOOKAHEAD) {
  1657. fill_window(s);
  1658. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  1659. return need_more;
  1660. }
  1661. if (s->lookahead == 0) break; /* flush the current block */
  1662. }
  1663. /* Insert the string window[strstart .. strstart+2] in the
  1664. * dictionary, and set hash_head to the head of the hash chain:
  1665. */
  1666. hash_head = NIL;
  1667. if (s->lookahead >= MIN_MATCH) {
  1668. INSERT_STRING(s, s->strstart, hash_head);
  1669. }
  1670. /* Find the longest match, discarding those <= prev_length.
  1671. * At this point we have always match_length < MIN_MATCH
  1672. */
  1673. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  1674. /* To simplify the code, we prevent matches with the string
  1675. * of window index 0 (in particular we have to avoid a match
  1676. * of the string with itself at the start of the input file).
  1677. */
  1678. s->match_length = longest_match (s, hash_head);
  1679. /* longest_match() sets match_start */
  1680. }
  1681. if (s->match_length >= MIN_MATCH) {
  1682. check_match(s, s->strstart, s->match_start, s->match_length);
  1683. _tr_tally_dist(s, s->strstart - s->match_start,
  1684. s->match_length - MIN_MATCH, bflush);
  1685. s->lookahead -= s->match_length;
  1686. /* Insert new strings in the hash table only if the match length
  1687. * is not too large. This saves time but degrades compression.
  1688. */
  1689. #ifndef FASTEST
  1690. if (s->match_length <= s->max_insert_length &&
  1691. s->lookahead >= MIN_MATCH) {
  1692. s->match_length--; /* string at strstart already in table */
  1693. do {
  1694. s->strstart++;
  1695. INSERT_STRING(s, s->strstart, hash_head);
  1696. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  1697. * always MIN_MATCH bytes ahead.
  1698. */
  1699. } while (--s->match_length != 0);
  1700. s->strstart++;
  1701. } else
  1702. #endif
  1703. {
  1704. s->strstart += s->match_length;
  1705. s->match_length = 0;
  1706. s->ins_h = s->window[s->strstart];
  1707. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  1708. #if MIN_MATCH != 3
  1709. Call UPDATE_HASH() MIN_MATCH-3 more times
  1710. #endif
  1711. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  1712. * matter since it will be recomputed at next deflate call.
  1713. */
  1714. }
  1715. } else {
  1716. /* No match, output a literal byte */
  1717. Tracevv((stderr,"%c", s->window[s->strstart]));
  1718. _tr_tally_lit (s, s->window[s->strstart], bflush);
  1719. s->lookahead--;
  1720. s->strstart++;
  1721. }
  1722. if (bflush) FLUSH_BLOCK(s, 0);
  1723. }
  1724. s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
  1725. if (flush == Z_FINISH) {
  1726. FLUSH_BLOCK(s, 1);
  1727. return finish_done;
  1728. }
  1729. if (s->last_lit)
  1730. FLUSH_BLOCK(s, 0);
  1731. return block_done;
  1732. }
  1733. #ifndef FASTEST
  1734. /* ===========================================================================
  1735. * Same as above, but achieves better compression. We use a lazy
  1736. * evaluation for matches: a match is finally adopted only if there is
  1737. * no better match at the next window position.
  1738. */
  1739. local block_state deflate_slow(s, flush)
  1740. deflate_state *s;
  1741. int flush;
  1742. {
  1743. IPos hash_head; /* head of hash chain */
  1744. int bflush; /* set if current block must be flushed */
  1745. /* Process the input block. */
  1746. for (;;) {
  1747. /* Make sure that we always have enough lookahead, except
  1748. * at the end of the input file. We need MAX_MATCH bytes
  1749. * for the next match, plus MIN_MATCH bytes to insert the
  1750. * string following the next match.
  1751. */
  1752. if (s->lookahead < MIN_LOOKAHEAD) {
  1753. fill_window(s);
  1754. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  1755. return need_more;
  1756. }
  1757. if (s->lookahead == 0) break; /* flush the current block */
  1758. }
  1759. /* Insert the string window[strstart .. strstart+2] in the
  1760. * dictionary, and set hash_head to the head of the hash chain:
  1761. */
  1762. hash_head = NIL;
  1763. if (s->lookahead >= MIN_MATCH) {
  1764. INSERT_STRING(s, s->strstart, hash_head);
  1765. }
  1766. /* Find the longest match, discarding those <= prev_length.
  1767. */
  1768. s->prev_length = s->match_length, s->prev_match = s->match_start;
  1769. s->match_length = MIN_MATCH-1;
  1770. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  1771. s->strstart - hash_head <= MAX_DIST(s)) {
  1772. /* To simplify the code, we prevent matches with the string
  1773. * of window index 0 (in particular we have to avoid a match
  1774. * of the string with itself at the start of the input file).
  1775. */
  1776. s->match_length = longest_match (s, hash_head);
  1777. /* longest_match() sets match_start */
  1778. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  1779. #if TOO_FAR <= 32767
  1780. || (s->match_length == MIN_MATCH &&
  1781. s->strstart - s->match_start > TOO_FAR)
  1782. #endif
  1783. )) {
  1784. /* If prev_match is also MIN_MATCH, match_start is garbage
  1785. * but we will ignore the current match anyway.
  1786. */
  1787. s->match_length = MIN_MATCH-1;
  1788. }
  1789. }
  1790. /* If there was a match at the previous step and the current
  1791. * match is not better, output the previous match:
  1792. */
  1793. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  1794. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  1795. /* Do not insert strings in hash table beyond this. */
  1796. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  1797. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  1798. s->prev_length - MIN_MATCH, bflush);
  1799. /* Insert in hash table all strings up to the end of the match.
  1800. * strstart-1 and strstart are already inserted. If there is not
  1801. * enough lookahead, the last two strings are not inserted in
  1802. * the hash table.
  1803. */
  1804. s->lookahead -= s->prev_length-1;
  1805. s->prev_length -= 2;
  1806. do {
  1807. if (++s->strstart <= max_insert) {
  1808. INSERT_STRING(s, s->strstart, hash_head);
  1809. }
  1810. } while (--s->prev_length != 0);
  1811. s->match_available = 0;
  1812. s->match_length = MIN_MATCH-1;
  1813. s->strstart++;
  1814. if (bflush) FLUSH_BLOCK(s, 0);
  1815. } else if (s->match_available) {
  1816. /* If there was no match at the previous position, output a
  1817. * single literal. If there was a match but the current match
  1818. * is longer, truncate the previous match to a single literal.
  1819. */
  1820. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  1821. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  1822. if (bflush) {
  1823. FLUSH_BLOCK_ONLY(s, 0);
  1824. }
  1825. s->strstart++;
  1826. s->lookahead--;
  1827. if (s->strm->avail_out == 0) return need_more;
  1828. } else {
  1829. /* There is no previous match to compare with, wait for
  1830. * the next step to decide.
  1831. */
  1832. s->match_available = 1;
  1833. s->strstart++;
  1834. s->lookahead--;
  1835. }
  1836. }
  1837. Assert (flush != Z_NO_FLUSH, "no flush?");
  1838. if (s->match_available) {
  1839. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  1840. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  1841. s->match_available = 0;
  1842. }
  1843. s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
  1844. if (flush == Z_FINISH) {
  1845. FLUSH_BLOCK(s, 1);
  1846. return finish_done;
  1847. }
  1848. if (s->last_lit)
  1849. FLUSH_BLOCK(s, 0);
  1850. return block_done;
  1851. }
  1852. #endif /* FASTEST */
  1853. /* ===========================================================================
  1854. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  1855. * one. Do not maintain a hash table. (It will be regenerated if this run of
  1856. * deflate switches away from Z_RLE.)
  1857. */
  1858. local block_state deflate_rle(s, flush)
  1859. deflate_state *s;
  1860. int flush;
  1861. {
  1862. int bflush; /* set if current block must be flushed */
  1863. uInt prev; /* byte at distance one to match */
  1864. Bytef *scan, *strend; /* scan goes up to strend for length of run */
  1865. for (;;) {
  1866. /* Make sure that we always have enough lookahead, except
  1867. * at the end of the input file. We need MAX_MATCH bytes
  1868. * for the longest run, plus one for the unrolled loop.
  1869. */
  1870. if (s->lookahead <= MAX_MATCH) {
  1871. fill_window(s);
  1872. if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {
  1873. return need_more;
  1874. }
  1875. if (s->lookahead == 0) break; /* flush the current block */
  1876. }
  1877. /* See how many times the previous byte repeats */
  1878. s->match_length = 0;
  1879. if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
  1880. scan = s->window + s->strstart - 1;
  1881. prev = *scan;
  1882. if (prev == *++scan && prev == *++scan && prev == *++scan) {
  1883. strend = s->window + s->strstart + MAX_MATCH;
  1884. do {
  1885. } while (prev == *++scan && prev == *++scan &&
  1886. prev == *++scan && prev == *++scan &&
  1887. prev == *++scan && prev == *++scan &&
  1888. prev == *++scan && prev == *++scan &&
  1889. scan < strend);
  1890. s->match_length = MAX_MATCH - (uInt)(strend - scan);
  1891. if (s->match_length > s->lookahead)
  1892. s->match_length = s->lookahead;
  1893. }
  1894. Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  1895. }
  1896. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  1897. if (s->match_length >= MIN_MATCH) {
  1898. check_match(s, s->strstart, s->strstart - 1, s->match_length);
  1899. _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
  1900. s->lookahead -= s->match_length;
  1901. s->strstart += s->match_length;
  1902. s->match_length = 0;
  1903. } else {
  1904. /* No match, output a literal byte */
  1905. Tracevv((stderr,"%c", s->window[s->strstart]));
  1906. _tr_tally_lit (s, s->window[s->strstart], bflush);
  1907. s->lookahead--;
  1908. s->strstart++;
  1909. }
  1910. if (bflush) FLUSH_BLOCK(s, 0);
  1911. }
  1912. s->insert = 0;
  1913. if (flush == Z_FINISH) {
  1914. FLUSH_BLOCK(s, 1);
  1915. return finish_done;
  1916. }
  1917. if (s->last_lit)
  1918. FLUSH_BLOCK(s, 0);
  1919. return block_done;
  1920. }
  1921. /* ===========================================================================
  1922. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  1923. * (It will be regenerated if this run of deflate switches away from Huffman.)
  1924. */
  1925. local block_state deflate_huff(s, flush)
  1926. deflate_state *s;
  1927. int flush;
  1928. {
  1929. int bflush; /* set if current block must be flushed */
  1930. for (;;) {
  1931. /* Make sure that we have a literal to write. */
  1932. if (s->lookahead == 0) {
  1933. fill_window(s);
  1934. if (s->lookahead == 0) {
  1935. if (flush == Z_NO_FLUSH)
  1936. return need_more;
  1937. break; /* flush the current block */
  1938. }
  1939. }
  1940. /* Output a literal byte */
  1941. s->match_length = 0;
  1942. Tracevv((stderr,"%c", s->window[s->strstart]));
  1943. _tr_tally_lit (s, s->window[s->strstart], bflush);
  1944. s->lookahead--;
  1945. s->strstart++;
  1946. if (bflush) FLUSH_BLOCK(s, 0);
  1947. }
  1948. s->insert = 0;
  1949. if (flush == Z_FINISH) {
  1950. FLUSH_BLOCK(s, 1);
  1951. return finish_done;
  1952. }
  1953. if (s->last_lit)
  1954. FLUSH_BLOCK(s, 0);
  1955. return block_done;
  1956. }