deflate.c 69 KB

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