deflate.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. /* deflate.c -- compress data using the deflation algorithm
  2. Copyright (C) 1999, 2006, 2012 Free Software Foundation, Inc.
  3. Copyright (C) 1992-1993 Jean-loup Gailly
  4. Copyright (C) 2008 Josh Triplett
  5. This program is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 3, or (at your option)
  8. any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program; if not, write to the Free Software Foundation,
  15. Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
  16. /*
  17. * PURPOSE
  18. *
  19. * Identify new text as repetitions of old text within a fixed-
  20. * length sliding window trailing behind the new text.
  21. *
  22. * DISCUSSION
  23. *
  24. * The "deflation" process depends on being able to identify portions
  25. * of the input text which are identical to earlier input (within a
  26. * sliding window trailing behind the input currently being processed).
  27. *
  28. * The most straightforward technique turns out to be the fastest for
  29. * most input files: try all possible matches and select the longest.
  30. * The key feature of this algorithm is that insertions into the string
  31. * dictionary are very simple and thus fast, and deletions are avoided
  32. * completely. Insertions are performed at each input character, whereas
  33. * string matches are performed only when the previous match ends. So it
  34. * is preferable to spend more time in matches to allow very fast string
  35. * insertions and avoid deletions. The matching algorithm for small
  36. * strings is inspired from that of Rabin & Karp. A brute force approach
  37. * is used to find longer strings when a small match has been found.
  38. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  39. * (by Leonid Broukhis).
  40. * A previous version of this file used a more sophisticated algorithm
  41. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  42. * time, but has a larger average cost, uses more memory and is patented.
  43. * However the F&G algorithm may be faster for some highly redundant
  44. * files if the parameter max_chain_length (described below) is too large.
  45. *
  46. * ACKNOWLEDGEMENTS
  47. *
  48. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  49. * I found it in 'freeze' written by Leonid Broukhis.
  50. * Thanks to many info-zippers for bug reports and testing.
  51. *
  52. * REFERENCES
  53. *
  54. * APPNOTE.TXT documentation file in PKZIP 1.93a distribution.
  55. *
  56. * A description of the Rabin and Karp algorithm is given in the book
  57. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  58. *
  59. * Fiala,E.R., and Greene,D.H.
  60. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  61. *
  62. * INTERFACE
  63. *
  64. * void lm_init (int pack_level, ush *flags)
  65. * Initialize the "longest match" routines for a new file
  66. *
  67. * void deflate (void)
  68. * Processes a new input file. Sets the compressed length, crc,
  69. * deflate flags and internal file attributes.
  70. */
  71. #include <stdio.h>
  72. #include "gzip.h"
  73. /* ===========================================================================
  74. * Configuration parameters
  75. */
  76. #define HASH_BITS 15
  77. #define HASH_SIZE (unsigned)(1<<HASH_BITS)
  78. #define HASH_MASK (HASH_SIZE-1)
  79. #define WMASK (WSIZE-1)
  80. /* HASH_SIZE and WSIZE must be powers of two */
  81. #define NIL 0
  82. /* Tail of hash chains */
  83. #define FAST 4
  84. #define SLOW 2
  85. /* speed options for the general purpose bit flag */
  86. #ifndef TOO_FAR
  87. # define TOO_FAR 4096
  88. #endif
  89. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  90. int RSYNC_WIN = 4096;
  91. /* Size of rsync window, must be < MAX_DIST */
  92. /* Whether to enable compatibility with Debian's old rsyncable patch. */
  93. int debian_rsyncable = 1;
  94. void set_14_rsyncable () {
  95. debian_rsyncable = 0;
  96. RSYNC_WIN = 8192;
  97. }
  98. /* gzip 1.6 uses a different rsyncable that is a hybrid between the
  99. * original and the gzip 1.4 version
  100. */
  101. void set_16_rsyncable () {
  102. debian_rsyncable = 2;
  103. RSYNC_WIN = 8192;
  104. }
  105. #define RSYNC_SUM_MATCH_DEBIAN(sum) ((sum) % RSYNC_WIN == 0)
  106. #define RSYNC_SUM_MATCH(sum) (((sum) & (RSYNC_WIN - 1)) == 0)
  107. /* Whether window sum matches magic value */
  108. /* ===========================================================================
  109. * Local data used by the "longest match" routines.
  110. */
  111. typedef ush Pos;
  112. typedef unsigned IPos;
  113. /* A Pos is an index in the character window. We use short instead of int to
  114. * save space in the various tables. IPos is used only for parameter passing.
  115. */
  116. static uch window[2L*WSIZE];
  117. /* Sliding window. Input bytes are read into the second half of the window,
  118. * and move to the first half later to keep a dictionary of at least WSIZE
  119. * bytes. With this organization, matches are limited to a distance of
  120. * WSIZE-MAX_MATCH bytes, but this ensures that IO is always
  121. * performed with a length multiple of the block size. Also, it limits
  122. * the window size to 64K, which is quite useful on MSDOS.
  123. */
  124. Pos prev[WSIZE];
  125. /* Link to older string with same hash index. To limit the size of this
  126. * array to 64K, this link is maintained only for the last 32K strings.
  127. * An index in this array is thus a window index modulo 32K.
  128. */
  129. Pos head[1<<HASH_BITS];
  130. /* Heads of the hash chains or NIL. */
  131. ulg window_size = (ulg)2*WSIZE;
  132. /* window size, 2*WSIZE except for MMAP or BIG_MEM, where it is the
  133. * input file length plus MIN_LOOKAHEAD.
  134. */
  135. long block_start;
  136. /* window position at the beginning of the current output block. Gets
  137. * negative when the window is moved backwards.
  138. */
  139. static unsigned ins_h; /* hash index of string to be inserted */
  140. #define H_SHIFT ((HASH_BITS+MIN_MATCH-1)/MIN_MATCH)
  141. /* Number of bits by which ins_h and del_h must be shifted at each
  142. * input step. It must be such that after MIN_MATCH steps, the oldest
  143. * byte no longer takes part in the hash key, that is:
  144. * H_SHIFT * MIN_MATCH >= HASH_BITS
  145. */
  146. unsigned int prev_length;
  147. /* Length of the best match at previous step. Matches not greater than this
  148. * are discarded. This is used in the lazy match evaluation.
  149. */
  150. unsigned strstart; /* start of string to insert */
  151. unsigned match_start; /* start of matching string */
  152. static int eofile; /* flag set at end of input file */
  153. static unsigned lookahead; /* number of valid bytes ahead in window */
  154. unsigned max_chain_length;
  155. /* To speed up deflation, hash chains are never searched beyond this length.
  156. * A higher limit improves compression ratio but degrades the speed.
  157. */
  158. static unsigned int max_lazy_match;
  159. /* Attempt to find a better match only when the current match is strictly
  160. * smaller than this value. This mechanism is used only for compression
  161. * levels >= 4.
  162. */
  163. #define max_insert_length max_lazy_match
  164. /* Insert new strings in the hash table only if the match length
  165. * is not greater than this length. This saves time but degrades compression.
  166. * max_insert_length is used only for compression levels <= 3.
  167. */
  168. static unsigned good_match;
  169. /* Use a faster search when the previous match is longer than this */
  170. static ulg rsync_sum; /* rolling sum of rsync window */
  171. static ulg rsync_chunk_end; /* next rsync sequence point */
  172. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  173. * the desired pack level (0..9). The values given below have been tuned to
  174. * exclude worst case performance for pathological files. Better values may be
  175. * found for specific files.
  176. */
  177. typedef struct config {
  178. ush good_length; /* reduce lazy search above this match length */
  179. ush max_lazy; /* do not perform lazy search above this match length */
  180. ush nice_length; /* quit search above this match length */
  181. ush max_chain;
  182. } config;
  183. #ifdef FULL_SEARCH
  184. # define nice_match MAX_MATCH
  185. #else
  186. int nice_match; /* Stop searching when current match exceeds this */
  187. #endif
  188. static config configuration_table[10] = {
  189. /* good lazy nice chain */
  190. /* 0 */ {0, 0, 0, 0}, /* store only */
  191. /* 1 */ {4, 4, 8, 4}, /* maximum speed, no lazy matches */
  192. /* 2 */ {4, 5, 16, 8},
  193. /* 3 */ {4, 6, 32, 32},
  194. /* 4 */ {4, 4, 16, 16}, /* lazy matches */
  195. /* 5 */ {8, 16, 32, 32},
  196. /* 6 */ {8, 16, 128, 128},
  197. /* 7 */ {8, 32, 128, 256},
  198. /* 8 */ {32, 128, 258, 1024},
  199. /* 9 */ {32, 258, 258, 4096}}; /* maximum compression */
  200. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  201. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  202. * meaning.
  203. */
  204. #define EQUAL 0
  205. /* result of memcmp for equal strings */
  206. /* ===========================================================================
  207. * Prototypes for local functions.
  208. */
  209. static void fill_window(void);
  210. int longest_match(IPos cur_match);
  211. /* ===========================================================================
  212. * Update a hash value with the given input byte
  213. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  214. * input characters, so that a running hash key can be computed from the
  215. * previous key instead of complete recalculation each time.
  216. */
  217. #define UPDATE_HASH(h,c) (h = (((h)<<H_SHIFT) ^ (c)) & HASH_MASK)
  218. /* ===========================================================================
  219. * Insert string s in the dictionary and set match_head to the previous head
  220. * of the hash chain (the most recent string with same hash key). Return
  221. * the previous length of the hash chain.
  222. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  223. * input characters and the first MIN_MATCH bytes of s are valid
  224. * (except for the last MIN_MATCH-1 bytes of the input file).
  225. */
  226. #define INSERT_STRING(s, match_head) \
  227. (UPDATE_HASH(ins_h, window[(s) + MIN_MATCH-1]), \
  228. prev[(s) & WMASK] = match_head = head[ins_h], \
  229. head[ins_h] = (s))
  230. /* ===========================================================================
  231. * Initialize the "longest match" routines for a new file
  232. */
  233. void lm_init (int pack_level, /* 1: best speed, 9: best compression */
  234. ush *flags) /* general purpose bit flag */
  235. {
  236. register unsigned j;
  237. if (pack_level < 1 || pack_level > 9) gzip_error ("bad pack level");
  238. /* Initialize the hash table. */
  239. memzero((char*)head, HASH_SIZE*sizeof(*head));
  240. /* prev will be initialized on the fly */
  241. /* rsync params */
  242. rsync_chunk_end = 0xFFFFFFFFUL;
  243. rsync_sum = 0;
  244. /* Set the default configuration parameters:
  245. */
  246. max_lazy_match = configuration_table[pack_level].max_lazy;
  247. good_match = configuration_table[pack_level].good_length;
  248. #ifndef FULL_SEARCH
  249. nice_match = configuration_table[pack_level].nice_length;
  250. #endif
  251. max_chain_length = configuration_table[pack_level].max_chain;
  252. if (pack_level == 1) {
  253. *flags |= FAST;
  254. } else if (pack_level == 9) {
  255. *flags |= SLOW;
  256. }
  257. /* ??? reduce max_chain_length for binary files */
  258. strstart = 0;
  259. block_start = 0L;
  260. lookahead = read_buf((char*)window,
  261. sizeof(int) <= 2 ? (unsigned)WSIZE : 2*WSIZE);
  262. if (lookahead == 0 || lookahead == (unsigned)EOF) {
  263. eofile = 1, lookahead = 0;
  264. return;
  265. }
  266. eofile = 0;
  267. /* Make sure that we always have enough lookahead. This is important
  268. * if input comes from a device such as a tty.
  269. */
  270. while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
  271. ins_h = 0;
  272. for (j=0; j<MIN_MATCH-1; j++) UPDATE_HASH(ins_h, window[j]);
  273. /* If lookahead < MIN_MATCH, ins_h is garbage, but this is
  274. * not important since only literal bytes will be emitted.
  275. */
  276. }
  277. /* ===========================================================================
  278. * Set match_start to the longest match starting at the given string and
  279. * return its length. Matches shorter or equal to prev_length are discarded,
  280. * in which case the result is equal to prev_length and match_start is
  281. * garbage.
  282. * IN assertions: cur_match is the head of the hash chain for the current
  283. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  284. */
  285. int longest_match(IPos cur_match)
  286. {
  287. unsigned chain_length = max_chain_length; /* max hash chain length */
  288. register uch *scan = window + strstart; /* current string */
  289. register uch *match; /* matched string */
  290. register int len; /* length of current match */
  291. int best_len = prev_length; /* best match length so far */
  292. IPos limit = strstart > (IPos)MAX_DIST ? strstart - (IPos)MAX_DIST : NIL;
  293. /* Stop when cur_match becomes <= limit. To simplify the code,
  294. * we prevent matches with the string of window index 0.
  295. */
  296. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  297. * It is easy to get rid of this optimization if necessary.
  298. */
  299. #if HASH_BITS < 8 || MAX_MATCH != 258
  300. error: Code too clever
  301. #endif
  302. #ifdef UNALIGNED_OK
  303. /* Compare two bytes at a time. Note: this is not always beneficial.
  304. * Try with and without -DUNALIGNED_OK to check.
  305. */
  306. register uch *strend = window + strstart + MAX_MATCH - 1;
  307. register ush scan_start = *(ush*)scan;
  308. register ush scan_end = *(ush*)(scan+best_len-1);
  309. #else
  310. register uch *strend = window + strstart + MAX_MATCH;
  311. register uch scan_end1 = scan[best_len-1];
  312. register uch scan_end = scan[best_len];
  313. #endif
  314. /* Do not waste too much time if we already have a good match: */
  315. if (prev_length >= good_match) {
  316. chain_length >>= 2;
  317. }
  318. Assert(strstart <= window_size-MIN_LOOKAHEAD, "insufficient lookahead");
  319. do {
  320. Assert(cur_match < strstart, "no future");
  321. match = window + cur_match;
  322. /* Skip to next match if the match length cannot increase
  323. * or if the match length is less than 2:
  324. */
  325. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  326. /* This code assumes sizeof(unsigned short) == 2. Do not use
  327. * UNALIGNED_OK if your compiler uses a different size.
  328. */
  329. if (*(ush*)(match+best_len-1) != scan_end ||
  330. *(ush*)match != scan_start) continue;
  331. /* It is not necessary to compare scan[2] and match[2] since they are
  332. * always equal when the other bytes match, given that the hash keys
  333. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  334. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  335. * lookahead only every 4th comparison; the 128th check will be made
  336. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  337. * necessary to put more guard bytes at the end of the window, or
  338. * to check more often for insufficient lookahead.
  339. */
  340. scan++, match++;
  341. do {
  342. } while (*(ush*)(scan+=2) == *(ush*)(match+=2) &&
  343. *(ush*)(scan+=2) == *(ush*)(match+=2) &&
  344. *(ush*)(scan+=2) == *(ush*)(match+=2) &&
  345. *(ush*)(scan+=2) == *(ush*)(match+=2) &&
  346. scan < strend);
  347. /* The funny "do {}" generates better code on most compilers */
  348. /* Here, scan <= window+strstart+257 */
  349. Assert(scan <= window+(unsigned)(window_size-1), "wild scan");
  350. if (*scan == *match) scan++;
  351. len = (MAX_MATCH - 1) - (int)(strend-scan);
  352. scan = strend - (MAX_MATCH-1);
  353. #else /* UNALIGNED_OK */
  354. if (match[best_len] != scan_end ||
  355. match[best_len-1] != scan_end1 ||
  356. *match != *scan ||
  357. *++match != scan[1]) continue;
  358. /* The check at best_len-1 can be removed because it will be made
  359. * again later. (This heuristic is not always a win.)
  360. * It is not necessary to compare scan[2] and match[2] since they
  361. * are always equal when the other bytes match, given that
  362. * the hash keys are equal and that HASH_BITS >= 8.
  363. */
  364. scan += 2, match++;
  365. /* We check for insufficient lookahead only every 8th comparison;
  366. * the 256th check will be made at strstart+258.
  367. */
  368. do {
  369. } while (*++scan == *++match && *++scan == *++match &&
  370. *++scan == *++match && *++scan == *++match &&
  371. *++scan == *++match && *++scan == *++match &&
  372. *++scan == *++match && *++scan == *++match &&
  373. scan < strend);
  374. len = MAX_MATCH - (int)(strend - scan);
  375. scan = strend - MAX_MATCH;
  376. #endif /* UNALIGNED_OK */
  377. if (len > best_len) {
  378. match_start = cur_match;
  379. best_len = len;
  380. if (len >= nice_match) break;
  381. #ifdef UNALIGNED_OK
  382. scan_end = *(ush*)(scan+best_len-1);
  383. #else
  384. scan_end1 = scan[best_len-1];
  385. scan_end = scan[best_len];
  386. #endif
  387. }
  388. } while ((cur_match = prev[cur_match & WMASK]) > limit
  389. && --chain_length != 0);
  390. return best_len;
  391. }
  392. /* ===========================================================================
  393. * Fill the window when the lookahead becomes insufficient.
  394. * Updates strstart and lookahead, and sets eofile if end of input file.
  395. * IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0
  396. * OUT assertions: at least one byte has been read, or eofile is set;
  397. * file reads are performed for at least two bytes (required for the
  398. * translate_eol option).
  399. */
  400. static void fill_window(void)
  401. {
  402. register unsigned n, m;
  403. unsigned more = (unsigned)(window_size - (ulg)lookahead - (ulg)strstart);
  404. /* Amount of free space at the end of the window. */
  405. /* If the window is almost full and there is insufficient lookahead,
  406. * move the upper half to the lower one to make room in the upper half.
  407. */
  408. if (more == (unsigned)EOF) {
  409. /* Very unlikely, but possible on 16 bit machine if strstart == 0
  410. * and lookahead == 1 (input done one byte at time)
  411. */
  412. more--;
  413. } else if (strstart >= WSIZE+MAX_DIST) {
  414. /* By the IN assertion, the window is not empty so we can't confuse
  415. * more == 0 with more == 64K on a 16 bit machine.
  416. */
  417. Assert(window_size == (ulg)2*WSIZE, "no sliding with BIG_MEM");
  418. memcpy((char*)window, (char*)window+WSIZE, (unsigned)WSIZE);
  419. match_start -= WSIZE;
  420. strstart -= WSIZE; /* we now have strstart >= MAX_DIST: */
  421. if (rsync_chunk_end != 0xFFFFFFFFUL)
  422. rsync_chunk_end -= WSIZE;
  423. block_start -= (long) WSIZE;
  424. for (n = 0; n < HASH_SIZE; n++) {
  425. m = head[n];
  426. head[n] = (Pos)(m >= WSIZE ? m-WSIZE : NIL);
  427. }
  428. for (n = 0; n < WSIZE; n++) {
  429. m = prev[n];
  430. prev[n] = (Pos)(m >= WSIZE ? m-WSIZE : NIL);
  431. /* If n is not on any hash chain, prev[n] is garbage but
  432. * its value will never be used.
  433. */
  434. }
  435. more += WSIZE;
  436. }
  437. /* At this point, more >= 2 */
  438. if (!eofile) {
  439. n = read_buf((char*)window+strstart+lookahead, more);
  440. if (n == 0 || n == (unsigned)EOF) {
  441. eofile = 1;
  442. /* Don't let garbage pollute the dictionary. */
  443. memzero (window + strstart + lookahead, MIN_MATCH - 1);
  444. } else {
  445. lookahead += n;
  446. }
  447. }
  448. }
  449. static void rsync_roll(unsigned start, unsigned num)
  450. {
  451. unsigned i;
  452. if (start < RSYNC_WIN) {
  453. /* before window fills. */
  454. for (i = start; i < RSYNC_WIN; i++) {
  455. if (i == start + num) return;
  456. rsync_sum += (ulg)window[i];
  457. }
  458. num -= (RSYNC_WIN - start);
  459. start = RSYNC_WIN;
  460. }
  461. /* buffer after window full */
  462. for (i = start; i < start+num; i++) {
  463. /* New character in */
  464. rsync_sum += (ulg)window[i];
  465. /* Old character out */
  466. rsync_sum -= (ulg)window[i - RSYNC_WIN];
  467. if (debian_rsyncable == 1 && rsync_chunk_end == 0xFFFFFFFFUL && RSYNC_SUM_MATCH_DEBIAN(rsync_sum))
  468. rsync_chunk_end = i;
  469. if (debian_rsyncable != 1 && rsync_chunk_end == 0xFFFFFFFFUL && RSYNC_SUM_MATCH(rsync_sum))
  470. rsync_chunk_end = i;
  471. }
  472. }
  473. /* ===========================================================================
  474. * Set rsync_chunk_end if window sum matches magic value.
  475. */
  476. #define RSYNC_ROLL(s, n) \
  477. do { if (rsync) rsync_roll((s), (n)); } while(0)
  478. /* ===========================================================================
  479. * Flush the current block, with given end-of-file flag.
  480. * IN assertion: strstart is set to the end of the current match.
  481. */
  482. #define FLUSH_BLOCK(eof) \
  483. flush_block(block_start >= 0L ? (char*)&window[(unsigned)block_start] : \
  484. (char*)NULL, (long)strstart - block_start, flush-1, (eof))
  485. /* ===========================================================================
  486. * Processes a new input file and return its compressed length. This
  487. * function does not perform lazy evaluationof matches and inserts
  488. * new strings in the dictionary only for unmatched strings or for short
  489. * matches. It is used only for the fast compression options.
  490. */
  491. static void deflate_fast(int pack_level, int rsync)
  492. {
  493. IPos hash_head; /* head of the hash chain */
  494. int flush = 0; /* set if current block must be flushed, 2=>and padded */
  495. unsigned match_length = 0; /* length of best match */
  496. prev_length = MIN_MATCH-1;
  497. while (lookahead != 0) {
  498. /* Insert the string window[strstart .. strstart+2] in the
  499. * dictionary, and set hash_head to the head of the hash chain:
  500. */
  501. INSERT_STRING(strstart, hash_head);
  502. /* Find the longest match, discarding those <= prev_length.
  503. * At this point we have always match_length < MIN_MATCH
  504. */
  505. if (hash_head != NIL && strstart - hash_head <= MAX_DIST
  506. && strstart <= window_size - MIN_LOOKAHEAD) {
  507. /* To simplify the code, we prevent matches with the string
  508. * of window index 0 (in particular we have to avoid a match
  509. * of the string with itself at the start of the input file).
  510. */
  511. match_length = longest_match (hash_head);
  512. /* longest_match() sets match_start */
  513. if (match_length > lookahead) match_length = lookahead;
  514. }
  515. if (match_length >= MIN_MATCH) {
  516. flush = ct_tally(pack_level, strstart-match_start, match_length - MIN_MATCH);
  517. lookahead -= match_length;
  518. RSYNC_ROLL(strstart, match_length);
  519. /* Insert new strings in the hash table only if the match length
  520. * is not too large. This saves time but degrades compression.
  521. */
  522. if (match_length <= max_insert_length) {
  523. match_length--; /* string at strstart already in hash table */
  524. do {
  525. strstart++;
  526. INSERT_STRING(strstart, hash_head);
  527. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  528. * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
  529. * these bytes are garbage, but it does not matter since
  530. * the next lookahead bytes will be emitted as literals.
  531. */
  532. } while (--match_length != 0);
  533. strstart++;
  534. } else {
  535. strstart += match_length;
  536. match_length = 0;
  537. ins_h = window[strstart];
  538. UPDATE_HASH(ins_h, window[strstart+1]);
  539. #if MIN_MATCH != 3
  540. Call UPDATE_HASH() MIN_MATCH-3 more times
  541. #endif
  542. }
  543. } else {
  544. /* No match, output a literal byte */
  545. Tracevv((stderr,"%c",window[strstart]));
  546. flush = ct_tally (pack_level, 0, window[strstart]);
  547. RSYNC_ROLL(strstart, 1);
  548. lookahead--;
  549. strstart++;
  550. }
  551. if (rsync && debian_rsyncable && strstart > rsync_chunk_end) {
  552. rsync_chunk_end = 0xFFFFFFFFUL;
  553. flush = 2;
  554. }
  555. if (rsync && ! debian_rsyncable && strstart > rsync_chunk_end) {
  556. flush = 1;
  557. ct_init();
  558. rsync_chunk_end = 0xFFFFFFFFUL;
  559. }
  560. if (flush) FLUSH_BLOCK(0), block_start = strstart;
  561. /* Make sure that we always have enough lookahead, except
  562. * at the end of the input file. We need MAX_MATCH bytes
  563. * for the next match, plus MIN_MATCH bytes to insert the
  564. * string following the next match.
  565. */
  566. while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
  567. }
  568. FLUSH_BLOCK(1); /* eof */
  569. }
  570. /* ===========================================================================
  571. * Same as above, but achieves better compression. We use a lazy
  572. * evaluation for matches: a match is finally adopted only if there is
  573. * no better match at the next window position.
  574. */
  575. void gnu_deflate(int pack_level, int rsync, int rsync14, int rsync16)
  576. {
  577. IPos hash_head; /* head of hash chain */
  578. IPos prev_match; /* previous match */
  579. int flush = 0; /* set if current block must be flushed */
  580. int match_available = 0; /* set if previous match exists */
  581. register unsigned match_length = MIN_MATCH-1; /* length of best match */
  582. /* The rsync14 mode superscedes Debian's old, somewhat broken
  583. * rsync patch. */
  584. if (rsync14) {
  585. rsync=1;
  586. set_14_rsyncable();
  587. }
  588. /* The rsync16 mode superscedes the others yet again */
  589. if (rsync16) {
  590. rsync=1;
  591. set_16_rsyncable();
  592. }
  593. if (pack_level <= 3) {
  594. deflate_fast(pack_level, rsync); /* optimized for speed */
  595. return;
  596. }
  597. /* Process the input block. */
  598. while (lookahead != 0) {
  599. /* Insert the string window[strstart .. strstart+2] in the
  600. * dictionary, and set hash_head to the head of the hash chain:
  601. */
  602. INSERT_STRING(strstart, hash_head);
  603. /* Find the longest match, discarding those <= prev_length.
  604. */
  605. prev_length = match_length, prev_match = match_start;
  606. match_length = MIN_MATCH-1;
  607. if (hash_head != NIL && prev_length < max_lazy_match &&
  608. strstart - hash_head <= MAX_DIST &&
  609. strstart <= window_size - MIN_LOOKAHEAD) {
  610. /* To simplify the code, we prevent matches with the string
  611. * of window index 0 (in particular we have to avoid a match
  612. * of the string with itself at the start of the input file).
  613. */
  614. match_length = longest_match (hash_head);
  615. /* longest_match() sets match_start */
  616. if (match_length > lookahead) match_length = lookahead;
  617. /* Ignore a length 3 match if it is too distant: */
  618. if (match_length == MIN_MATCH && strstart-match_start > TOO_FAR){
  619. /* If prev_match is also MIN_MATCH, match_start is garbage
  620. * but we will ignore the current match anyway.
  621. */
  622. match_length--;
  623. }
  624. }
  625. /* If there was a match at the previous step and the current
  626. * match is not better, output the previous match:
  627. */
  628. if (prev_length >= MIN_MATCH && match_length <= prev_length) {
  629. flush = ct_tally(pack_level, strstart-1-prev_match, prev_length - MIN_MATCH);
  630. /* Insert in hash table all strings up to the end of the match.
  631. * strstart-1 and strstart are already inserted.
  632. */
  633. lookahead -= prev_length-1;
  634. prev_length -= 2;
  635. RSYNC_ROLL(strstart, prev_length+1);
  636. do {
  637. strstart++;
  638. INSERT_STRING(strstart, hash_head);
  639. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  640. * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
  641. * these bytes are garbage, but it does not matter since the
  642. * next lookahead bytes will always be emitted as literals.
  643. */
  644. } while (--prev_length != 0);
  645. match_available = 0;
  646. match_length = MIN_MATCH-1;
  647. strstart++;
  648. if (rsync && debian_rsyncable && strstart > rsync_chunk_end) {
  649. rsync_chunk_end = 0xFFFFFFFFUL;
  650. flush = 2;
  651. }
  652. if (rsync && ! debian_rsyncable && strstart > rsync_chunk_end) {
  653. ct_init();
  654. rsync_chunk_end = 0xFFFFFFFFUL;
  655. flush = 1;
  656. }
  657. if (flush) FLUSH_BLOCK(0), block_start = strstart;
  658. } else if (match_available) {
  659. /* If there was no match at the previous position, output a
  660. * single literal. If there was a match but the current match
  661. * is longer, truncate the previous match to a single literal.
  662. */
  663. Tracevv((stderr,"%c",window[strstart-1]));
  664. flush = ct_tally (pack_level, 0, window[strstart-1]);
  665. if (rsync && debian_rsyncable && strstart > rsync_chunk_end) {
  666. rsync_chunk_end = 0xFFFFFFFFUL;
  667. flush = 2;
  668. }
  669. if (rsync && ! debian_rsyncable && strstart > rsync_chunk_end) {
  670. ct_init();
  671. rsync_chunk_end = 0xFFFFFFFFUL;
  672. flush = 1;
  673. }
  674. if (flush) FLUSH_BLOCK(0), block_start = strstart;
  675. RSYNC_ROLL(strstart, 1);
  676. strstart++;
  677. lookahead--;
  678. } else {
  679. /* There is no previous match to compare with, wait for
  680. * the next step to decide.
  681. */
  682. if (rsync && debian_rsyncable && strstart > rsync_chunk_end) {
  683. /* Reset huffman tree */
  684. rsync_chunk_end = 0xFFFFFFFFUL;
  685. flush = 2;
  686. FLUSH_BLOCK(0), block_start = strstart;
  687. }
  688. if (rsync && ! debian_rsyncable && strstart > rsync_chunk_end) {
  689. ct_init();
  690. /* Reset huffman tree */
  691. rsync_chunk_end = 0xFFFFFFFFUL;
  692. FLUSH_BLOCK(0), block_start = strstart;
  693. }
  694. match_available = 1;
  695. RSYNC_ROLL(strstart, 1);
  696. strstart++;
  697. lookahead--;
  698. }
  699. /* Assert (strstart <= bytes_in && lookahead <= bytes_in, "a bit too far"); */
  700. /* Make sure that we always have enough lookahead, except
  701. * at the end of the input file. We need MAX_MATCH bytes
  702. * for the next match, plus MIN_MATCH bytes to insert the
  703. * string following the next match.
  704. */
  705. while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
  706. }
  707. if (match_available) ct_tally (pack_level, 0, window[strstart-1]);
  708. FLUSH_BLOCK(1); /* eof */
  709. }