deflate.c 68 KB

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