home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 9 Archive / 09-Archive.zip / zip201.zip / deflate.c < prev    next >
C/C++ Source or Header  |  1993-09-10  |  31KB  |  832 lines

  1. /*
  2.  
  3.  Copyright (C) 1990-1993 Mark Adler, Richard B. Wales, Jean-loup Gailly,
  4.  Kai Uwe Rommel and Igor Mandrichenko.
  5.  Permission is granted to any individual or institution to use, copy, or
  6.  redistribute this software so long as all of the original files are included,
  7.  that it is not sold for profit, and that this copyright notice is retained.
  8.  
  9. */
  10.  
  11. /*
  12.  *  deflate.c by Jean-loup Gailly.
  13.  *
  14.  *  PURPOSE
  15.  *
  16.  *      Identify new text as repetitions of old text within a fixed-
  17.  *      length sliding window trailing behind the new text.
  18.  *
  19.  *  DISCUSSION
  20.  *
  21.  *      The "deflation" process depends on being able to identify portions
  22.  *      of the input text which are identical to earlier input (within a
  23.  *      sliding window trailing behind the input currently being processed).
  24.  *
  25.  *      The most straightforward technique turns out to be the fastest for
  26.  *      most input files: try all possible matches and select the longest.
  27.  *      The key feature of this algorithm is that insertions into the string
  28.  *      dictionary are very simple and thus fast, and deletions are avoided
  29.  *      completely. Insertions are performed at each input character, whereas
  30.  *      string matches are performed only when the previous match ends. So it
  31.  *      is preferable to spend more time in matches to allow very fast string
  32.  *      insertions and avoid deletions. The matching algorithm for small
  33.  *      strings is inspired from that of Rabin & Karp. A brute force approach
  34.  *      is used to find longer strings when a small match has been found.
  35.  *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  36.  *      (by Leonid Broukhis).
  37.  *         A previous version of this file used a more sophisticated algorithm
  38.  *      (by Fiala and Greene) which is guaranteed to run in linear amortized
  39.  *      time, but has a larger average cost, uses more memory and is patented.
  40.  *      However the F&G algorithm may be faster for some highly redundant
  41.  *      files if the parameter max_chain_length (described below) is too large.
  42.  *
  43.  *  ACKNOWLEDGEMENTS
  44.  *
  45.  *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  46.  *      I found it in 'freeze' written by Leonid Broukhis.
  47.  *      Thanks to many info-zippers for bug reports and testing.
  48.  *
  49.  *  REFERENCES
  50.  *
  51.  *      APPNOTE.TXT documentation file in PKZIP 1.93a distribution.
  52.  *
  53.  *      A description of the Rabin and Karp algorithm is given in the book
  54.  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  55.  *
  56.  *      Fiala,E.R., and Greene,D.H.
  57.  *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  58.  *
  59.  *  INTERFACE
  60.  *
  61.  *      void lm_init (int pack_level, ush *flags)
  62.  *          Initialize the "longest match" routines for a new file
  63.  *
  64.  *      ulg deflate (void)
  65.  *          Processes a new input file and return its compressed length. Sets
  66.  *          the compressed length, crc, deflate flags and internal file
  67.  *          attributes.
  68.  */
  69.  
  70. #include "zip.h"
  71.  
  72. /* ===========================================================================
  73.  * Configuration parameters
  74.  */
  75.  
  76. /* Compile with MEDIUM_MEM to reduce the memory requirements or
  77.  * with SMALL_MEM to use as little memory as possible. Use BIG_MEM if the
  78.  * entire input file can be held in memory (not possible on 16 bit systems).
  79.  * Warning: defining these symbols affects HASH_BITS (see below) and thus
  80.  * affects the compression ratio. The compressed output
  81.  * is still correct, and might even be smaller in some cases.
  82.  */
  83.  
  84. #ifdef SMALL_MEM
  85. #   define HASH_BITS  13  /* Number of bits used to hash strings */
  86. #endif
  87. #ifdef MEDIUM_MEM
  88. #   define HASH_BITS  14
  89. #endif
  90. #ifndef HASH_BITS
  91. #   define HASH_BITS  15
  92.    /* For portability to 16 bit machines, do not use values above 15. */
  93. #endif
  94.  
  95. #define HASH_SIZE (unsigned)(1<<HASH_BITS)
  96. #define HASH_MASK (HASH_SIZE-1)
  97. #define WMASK     (WSIZE-1)
  98. /* HASH_SIZE and WSIZE must be powers of two */
  99.  
  100. #define NIL 0
  101. /* Tail of hash chains */
  102.  
  103. #define FAST 4
  104. #define SLOW 2
  105. /* speed options for the general purpose bit flag */
  106.  
  107. #ifndef TOO_FAR
  108. #  define TOO_FAR 4096
  109. #endif
  110. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  111.  
  112. #ifdef ATARI_ST
  113. #  undef MSDOS /* avoid the processor specific parts */
  114.    /* (but the Atari should never define MSDOS anyway ...) */
  115. #endif
  116. #if defined(MSDOS) && !defined(NO_ASM) && !defined(ASMV)
  117. #  define ASMV
  118. #endif
  119. #if defined(ASMV) && !defined(MSDOS) && defined(DYN_ALLOC)
  120.   error: DYN_ALLOC not yet supported in match.s
  121. #endif
  122. #if defined(MSDOS) && !defined(__32BIT__)
  123. #  define MAXSEG_64K
  124. #endif
  125.  
  126. /* ===========================================================================
  127.  * Local data used by the "longest match" routines.
  128.  */
  129.  
  130. #if defined(BIG_MEM) || defined(MMAP)
  131.   typedef unsigned Pos; /* must be at least 32 bits */
  132. #else
  133.   typedef ush Pos;
  134. #endif
  135. typedef unsigned IPos;
  136. /* A Pos is an index in the character window. We use short instead of int to
  137.  * save space in the various tables. IPos is used only for parameter passing.
  138.  */
  139.  
  140. #ifndef DYN_ALLOC
  141.   uch    window[2L*WSIZE];
  142.   /* Sliding window. Input bytes are read into the second half of the window,
  143.    * and move to the first half later to keep a dictionary of at least WSIZE
  144.    * bytes. With this organization, matches are limited to a distance of
  145.    * WSIZE-MAX_MATCH bytes, but this ensures that IO is always
  146.    * performed with a length multiple of the block size. Also, it limits
  147.    * the window size to 64K, which is quite useful on MSDOS.
  148.    * To do: limit the window size to WSIZE+BSZ if SMALL_MEM (the code would
  149.    * be less efficient since the data would have to be copied WSIZE/BSZ times)
  150.    */
  151.   Pos    prev[WSIZE];
  152.   /* Link to older string with same hash index. To limit the size of this
  153.    * array to 64K, this link is maintained only for the last 32K strings.
  154.    * An index in this array is thus a window index modulo 32K.
  155.    */
  156.   Pos    head[HASH_SIZE];
  157.   /* Heads of the hash chains or NIL. If your compiler thinks that
  158.    * HASH_SIZE is a dynamic value, recompile with -DDYN_ALLOC.
  159.    */
  160. #else
  161.   uch    * near window = NULL;
  162.   Pos    * near prev   = NULL;
  163.   Pos    * near head;
  164. #endif
  165. ulg window_size;
  166. /* window size, 2*WSIZE except for MMAP or BIG_MEM, where it is the
  167.  * input file length plus MIN_LOOKAHEAD.
  168.  */
  169.  
  170. long block_start;
  171. /* window position at the beginning of the current output block. Gets
  172.  * negative when the window is moved backwards.
  173.  */
  174.  
  175. local int sliding;
  176. /* Set to false when the input file is already in memory */
  177.  
  178. local unsigned ins_h;  /* hash index of string to be inserted */
  179.  
  180. #define H_SHIFT  ((HASH_BITS+MIN_MATCH-1)/MIN_MATCH)
  181. /* Number of bits by which ins_h and del_h must be shifted at each
  182.  * input step. It must be such that after MIN_MATCH steps, the oldest
  183.  * byte no longer takes part in the hash key, that is:
  184.  *   H_SHIFT * MIN_MATCH >= HASH_BITS
  185.  */
  186.  
  187. unsigned int near prev_length;
  188. /* Length of the best match at previous step. Matches not greater than this
  189.  * are discarded. This is used in the lazy match evaluation.
  190.  */
  191.  
  192.       unsigned near strstart;      /* start of string to insert */
  193.       unsigned near match_start;   /* start of matching string */
  194. local int           eofile;        /* flag set at end of input file */
  195. local unsigned      lookahead;     /* number of valid bytes ahead in window */
  196.  
  197. unsigned near max_chain_length;
  198. /* To speed up deflation, hash chains are never searched beyond this length.
  199.  * A higher limit improves compression ratio but degrades the speed.
  200.  */
  201.  
  202. local unsigned int max_lazy_match;
  203. /* Attempt to find a better match only when the current match is strictly
  204.  * smaller than this value. This mechanism is used only for compression
  205.  * levels >= 4.
  206.  */
  207. #define max_insert_length  max_lazy_match
  208. /* Insert new strings in the hash table only if the match length
  209.  * is not greater than this length. This saves time but degrades compression.
  210.  * max_insert_length is used only for compression levels <= 3.
  211.  */
  212.  
  213. unsigned near good_match;
  214. /* Use a faster search when the previous match is longer than this */
  215.  
  216.  
  217. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  218.  * the desired pack level (0..9). The values given below have been tuned to
  219.  * exclude worst case performance for pathological files. Better values may be
  220.  * found for specific files.
  221.  */
  222.  
  223. typedef struct config {
  224.    ush good_length; /* reduce lazy search above this match length */
  225.    ush max_lazy;    /* do not perform lazy search above this match length */
  226.    ush nice_length; /* quit search above this match length */
  227.    ush max_chain;
  228. } config;
  229.  
  230. #ifdef  FULL_SEARCH
  231. # define nice_match MAX_MATCH
  232. #else
  233.   int near nice_match; /* Stop searching when current match exceeds this */
  234. #endif
  235.  
  236. local config configuration_table[10] = {
  237. /*      good lazy nice chain */
  238. /* 0 */ {0,    0,  0,    0},  /* store only */
  239. /* 1 */ {4,    4,  8,    4},  /* maximum speed, no lazy matches */
  240. /* 2 */ {4,    5, 16,    8},
  241. /* 3 */ {4,    6, 32,   32},
  242.  
  243. /* 4 */ {4,    4, 16,   16},  /* lazy matches */
  244. /* 5 */ {8,   16, 32,   32},
  245. /* 6 */ {8,   16, 128, 128},
  246. /* 7 */ {8,   32, 128, 256},
  247. /* 8 */ {32, 128, 258, 1024},
  248. /* 9 */ {32, 258, 258, 4096}}; /* maximum compression */
  249.  
  250. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  251.  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  252.  * meaning.
  253.  */
  254.  
  255. #define EQUAL 0
  256. /* result of memcmp for equal strings */
  257.  
  258. /* ===========================================================================
  259.  *  Prototypes for local functions.
  260.  */
  261.  
  262. local void fill_window   OF((void));
  263. local ulg deflate_fast   OF((void));
  264.  
  265.       int  longest_match OF((IPos cur_match));
  266. #ifdef ASMV
  267.       void match_init OF((void)); /* asm code initialization */
  268. #endif
  269.  
  270. #ifdef DEBUG
  271. local  void check_match OF((IPos start, IPos match, int length));
  272. #endif
  273.  
  274. /* ===========================================================================
  275.  * Update a hash value with the given input byte
  276.  * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
  277.  *    input characters, so that a running hash key can be computed from the
  278.  *    previous key instead of complete recalculation each time.
  279.  */
  280. #define UPDATE_HASH(h,c) (h = (((h)<<H_SHIFT) ^ (c)) & HASH_MASK)
  281.  
  282. /* ===========================================================================
  283.  * Insert string s in the dictionary and set match_head to the previous head
  284.  * of the hash chain (the most recent string with same hash key). Return
  285.  * the previous length of the hash chain.
  286.  * IN  assertion: all calls to to INSERT_STRING are made with consecutive
  287.  *    input characters and the first MIN_MATCH bytes of s are valid
  288.  *    (except for the last MIN_MATCH-1 bytes of the input file).
  289.  */
  290. #define INSERT_STRING(s, match_head) \
  291.    (UPDATE_HASH(ins_h, window[(s) + MIN_MATCH-1]), \
  292.     prev[(s) & WMASK] = match_head = head[ins_h], \
  293.     head[ins_h] = (s))
  294.  
  295. /* ===========================================================================
  296.  * Initialize the "longest match" routines for a new file
  297.  *
  298.  * IN assertion: window_size is > 0 if the input file is already read or
  299.  *    mmap'ed in the window[] array, 0 otherwise. In the first case,
  300.  *    window_size is sufficient to contain the whole input file plus
  301.  *    MIN_LOOKAHEAD bytes (to avoid referencing memory beyond the end
  302.  *    of window[] when looking for matches towards the end).
  303.  */
  304. void lm_init (pack_level, flags)
  305.     int pack_level; /* 0: store, 1: best speed, 9: best compression */
  306.     ush *flags;     /* general purpose bit flag */
  307. {
  308.     register unsigned j;
  309.  
  310.     if (pack_level < 1 || pack_level > 9) error("bad pack level");
  311.  
  312.     /* Do not slide the window if the whole input is already in memory
  313.      * (window_size > 0)
  314.      */
  315.     sliding = 0;
  316.     if (window_size == 0L) {
  317.         sliding = 1;
  318.         window_size = (ulg)2L*WSIZE;
  319.     }
  320.  
  321.     /* Use dynamic allocation if compiler does not like big static arrays: */
  322. #ifdef DYN_ALLOC
  323.     if (window == NULL) {
  324.         window = (uch*) fcalloc(WSIZE,   2*sizeof(uch));
  325.         if (window == NULL) err(ZE_MEM, "window allocation");
  326.     }
  327.     if (prev == NULL) {
  328.         prev   = (Pos*) fcalloc(WSIZE,     sizeof(Pos));
  329.         head   = (Pos*) fcalloc(HASH_SIZE, sizeof(Pos));
  330.         if (prev == NULL || head == NULL) {
  331.             err(ZE_MEM, "hash table allocation");
  332.         }
  333.     }
  334. #endif /* DYN_ALLOC */
  335.  
  336.     /* Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  337.      * prev[] will be initialized on the fly.
  338.      */
  339.     head[HASH_SIZE-1] = NIL;
  340.     memset((char*)head, NIL, (unsigned)(HASH_SIZE-1)*sizeof(*head));
  341.  
  342.     /* Set the default configuration parameters:
  343.      */
  344.     max_lazy_match   = configuration_table[pack_level].max_lazy;
  345.     good_match       = configuration_table[pack_level].good_length;
  346. #ifndef FULL_SEARCH
  347.     nice_match       = configuration_table[pack_level].nice_length;
  348. #endif
  349.     max_chain_length = configuration_table[pack_level].max_chain;
  350.     if (pack_level == 1) {
  351.        *flags |= FAST;
  352.     } else if (pack_level == 9) {
  353.        *flags |= SLOW;
  354.     }
  355.     /* ??? reduce max_chain_length for binary files */
  356.  
  357.     strstart = 0;
  358.     block_start = 0L;
  359. #ifdef ASMV
  360.     match_init(); /* initialize the asm code */
  361. #endif
  362.  
  363.     j = WSIZE;
  364. #ifndef MAXSEG_64K
  365.     if (sizeof(int) > 2) j <<= 1; /* Can read 64K in one step */
  366. #endif
  367.     lookahead = (*read_buf)((char*)window, j);
  368.  
  369.     if (lookahead == 0 || lookahead == (unsigned)EOF) {
  370.        eofile = 1, lookahead = 0;
  371.        return;
  372.     }
  373.     eofile = 0;
  374.     /* Make sure that we always have enough lookahead. This is important
  375.      * if input comes from a device such as a tty.
  376.      */
  377.     while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
  378.  
  379.     ins_h = 0;
  380.     for (j=0; j<MIN_MATCH-1; j++) UPDATE_HASH(ins_h, window[j]);
  381.     /* If lookahead < MIN_MATCH, ins_h is garbage, but this is
  382.      * not important since only literal bytes will be emitted.
  383.      */
  384. }
  385.  
  386. /* ===========================================================================
  387.  * Free the window and hash table
  388.  */
  389. void lm_free()
  390. {
  391. #ifdef DYN_ALLOC
  392.     if (window != NULL) {
  393.         fcfree(window);
  394.         window = NULL;
  395.     }
  396.     if (prev != NULL) {
  397.         fcfree(prev);
  398.         fcfree(head);
  399.         prev = head = NULL;
  400.     }
  401. #endif /* DYN_ALLOC */
  402. }
  403.  
  404. /* ===========================================================================
  405.  * Set match_start to the longest match starting at the given string and
  406.  * return its length. Matches shorter or equal to prev_length are discarded,
  407.  * in which case the result is equal to prev_length and match_start is
  408.  * garbage.
  409.  * IN assertions: cur_match is the head of the hash chain for the current
  410.  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  411.  */
  412. #ifndef ASMV
  413. /* For MSDOS, OS/2 and 386 Unix, an optimized version is in match.asm or
  414.  * match.s. The code is functionally equivalent, so you can use the C version
  415.  * if desired.  A 68000 version is in amiga/match_68.a -- this could be used
  416.  * with other 68000 based systems such as Macintosh with a little effort.
  417.  */
  418. int longest_match(cur_match)
  419.     IPos cur_match;                             /* current match */
  420. {
  421.     unsigned chain_length = max_chain_length;   /* max hash chain length */
  422.     register uch *scan = window + strstart;     /* current string */
  423.     register uch *match;                        /* matched string */
  424.     register int len;                           /* length of current match */
  425.     int best_len = prev_length;                 /* best match length so far */
  426.     IPos limit = strstart > (IPos)MAX_DIST ? strstart - (IPos)MAX_DIST : NIL;
  427.     /* Stop when cur_match becomes <= limit. To simplify the code,
  428.      * we prevent matches with the string of window index 0.
  429.      */
  430.  
  431. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  432.  * It is easy to get rid of this optimization if necessary.
  433.  */
  434. #if HASH_BITS < 8 || MAX_MATCH != 258
  435.    error: Code too clever
  436. #endif
  437.  
  438. #ifdef UNALIGNED_OK
  439.     /* Compare two bytes at a time. Note: this is not always beneficial.
  440.      * Try with and without -DUNALIGNED_OK to check.
  441.      */
  442.     register uch *strend = window + strstart + MAX_MATCH - 1;
  443.     register ush scan_start = *(ush*)scan;
  444.     register ush scan_end   = *(ush*)(scan+best_len-1);
  445. #else
  446.     register uch *strend = window + strstart + MAX_MATCH;
  447.     register uch scan_end1  = scan[best_len-1];
  448.     register uch scan_end   = scan[best_len];
  449. #endif
  450.  
  451.     /* Do not waste too much time if we already have a good match: */
  452.     if (prev_length >= good_match) {
  453.         chain_length >>= 2;
  454.     }
  455.     Assert(strstart <= window_size-MIN_LOOKAHEAD, "insufficient lookahead");
  456.  
  457.     do {
  458.         Assert(cur_match < strstart, "no future");
  459.         match = window + cur_match;
  460.  
  461.         /* Skip to next match if the match length cannot increase
  462.          * or if the match length is less than 2:
  463.          */
  464. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  465.         /* This code assumes sizeof(unsigned short) == 2. Do not use
  466.          * UNALIGNED_OK if your compiler uses a different size.
  467.          */
  468.         if (*(ush*)(match+best_len-1) != scan_end ||
  469.             *(ush*)match != scan_start) continue;
  470.  
  471.         /* It is not necessary to compare scan[2] and match[2] since they are
  472.          * always equal when the other bytes match, given that the hash keys
  473.          * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  474.          * strstart+3, +5, ... up to strstart+257. We check for insufficient
  475.          * lookahead only every 4th comparison; the 128th check will be made
  476.          * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  477.          * necessary to put more guard bytes at the end of the window, or
  478.          * to check more often for insufficient lookahead.
  479.          */
  480.         scan++, match++;
  481.         do {
  482.         } while (*(ush*)(scan+=2) == *(ush*)(match+=2) &&
  483.                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
  484.                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
  485.                  *(ush*)(scan+=2) == *(ush*)(match+=2) &&
  486.                  scan < strend);
  487.         /* The funny "do {}" generates better code on most compilers */
  488.  
  489.         /* Here, scan <= window+strstart+257 */
  490.         Assert(scan <= window+(unsigned)(window_size-1), "wild scan");
  491.         if (*scan == *match) scan++;
  492.  
  493.         len = (MAX_MATCH - 1) - (int)(strend-scan);
  494.         scan = strend - (MAX_MATCH-1);
  495.  
  496. #else /* UNALIGNED_OK */
  497.  
  498.         if (match[best_len]   != scan_end  ||
  499.             match[best_len-1] != scan_end1 ||
  500.             *match            != *scan     ||
  501.             *++match          != scan[1])      continue;
  502.  
  503.         /* The check at best_len-1 can be removed because it will be made
  504.          * again later. (This heuristic is not always a win.)
  505.          * It is not necessary to compare scan[2] and match[2] since they
  506.          * are always equal when the other bytes match, given that
  507.          * the hash keys are equal and that HASH_BITS >= 8.
  508.          */
  509.         scan += 2, match++;
  510.  
  511.         /* We check for insufficient lookahead only every 8th comparison;
  512.          * the 256th check will be made at strstart+258.
  513.          */
  514.         do {
  515.         } while (*++scan == *++match && *++scan == *++match &&
  516.                  *++scan == *++match && *++scan == *++match &&
  517.                  *++scan == *++match && *++scan == *++match &&
  518.                  *++scan == *++match && *++scan == *++match &&
  519.                  scan < strend);
  520.  
  521.         len = MAX_MATCH - (int)(strend - scan);
  522.         scan = strend - MAX_MATCH;
  523.  
  524. #endif /* UNALIGNED_OK */
  525.  
  526.         if (len > best_len) {
  527.             match_start = cur_match;
  528.             best_len = len;
  529.             if (len >= nice_match) break;
  530. #ifdef UNALIGNED_OK
  531.             scan_end = *(ush*)(scan+best_len-1);
  532. #else
  533.             scan_end1  = scan[best_len-1];
  534.             scan_end   = scan[best_len];
  535. #endif
  536.         }
  537.     } while ((cur_match = prev[cur_match & WMASK]) > limit
  538.              && --chain_length != 0);
  539.  
  540.     return best_len;
  541. }
  542. #endif /* ASMV */
  543.  
  544. #ifdef DEBUG
  545. /* ===========================================================================
  546.  * Check that the match at match_start is indeed a match.
  547.  */
  548. local void check_match(start, match, length)
  549.     IPos start, match;
  550.     int length;
  551. {
  552.     /* check that the match is indeed a match */
  553.     if (memcmp((char*)window + match,
  554.                 (char*)window + start, length) != EQUAL) {
  555.         fprintf(stderr,
  556.             " start %d, match %d, length %d\n",
  557.             start, match, length);
  558.         error("invalid match");
  559.     }
  560.     if (verbose > 1) {
  561.         fprintf(stderr,"\\[%d,%d]", start-match, length);
  562.         do { putc(window[start++], stderr); } while (--length != 0);
  563.     }
  564. }
  565. #else
  566. #  define check_match(start, match, length)
  567. #endif
  568.  
  569. /* ===========================================================================
  570.  * Fill the window when the lookahead becomes insufficient.
  571.  * Updates strstart and lookahead, and sets eofile if end of input file.
  572.  *
  573.  * IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0
  574.  * OUT assertions: at least one byte has been read, or eofile is set;
  575.  *    file reads are performed for at least two bytes (required for the
  576.  *    translate_eol option).
  577.  */
  578. local void fill_window()
  579. {
  580.     register unsigned n, m;
  581.     unsigned more = (unsigned)(window_size - (ulg)lookahead - (ulg)strstart);
  582.     /* Amount of free space at the end of the window. */
  583.  
  584.     /* If the window is almost full and there is insufficient lookahead,
  585.      * move the upper half to the lower one to make room in the upper half.
  586.      */
  587.     if (more == (unsigned)EOF) {
  588.         /* Very unlikely, but possible on 16 bit machine if strstart == 0
  589.          * and lookahead == 1 (input done one byte at time)
  590.          */
  591.         more--;
  592.  
  593.     /* For MMAP or BIG_MEM, the whole input file is already in memory
  594.      * so we must not perform sliding. We must however call file_read
  595.      * in order to compute the crc, update lookahead and possibly set eofile.
  596.      */
  597.     } else if (strstart >= WSIZE+MAX_DIST && sliding) {
  598.  
  599.         /* By the IN assertion, the window is not empty so we can't confuse
  600.          * more == 0 with more == 64K on a 16 bit machine.
  601.          */
  602.         memcpy((char*)window, (char*)window+WSIZE, (unsigned)WSIZE);
  603.         match_start -= WSIZE;
  604.         strstart    -= WSIZE; /* we now have strstart >= MAX_DIST: */
  605.  
  606.         block_start -= (long) WSIZE;
  607.  
  608.         for (n = 0; n < HASH_SIZE; n++) {
  609.             m = head[n];
  610.             head[n] = (Pos)(m >= WSIZE ? m-WSIZE : NIL);
  611.         }
  612.         for (n = 0; n < WSIZE; n++) {
  613.             m = prev[n];
  614.             prev[n] = (Pos)(m >= WSIZE ? m-WSIZE : NIL);
  615.             /* If n is not on any hash chain, prev[n] is garbage but
  616.              * its value will never be used.
  617.              */
  618.         }
  619.         more += WSIZE;
  620.         if (verbose) putc('.', stderr);
  621.     }
  622.     /* At this point, more >= 2 */
  623.     if (!eofile) {
  624.         n = (*read_buf)((char*)window+strstart+lookahead, more);
  625.         if (n == 0 || n == (unsigned)EOF) {
  626.             eofile = 1;
  627.         } else {
  628.             lookahead += n;
  629.         }
  630.     }
  631. }
  632.  
  633. /* ===========================================================================
  634.  * Flush the current block, with given end-of-file flag.
  635.  * IN assertion: strstart is set to the end of the current match.
  636.  */
  637. #define FLUSH_BLOCK(eof) \
  638.    flush_block(block_start >= 0L ? (char*)&window[(unsigned)block_start] : \
  639.                 (char*)NULL, (long)strstart - block_start, (eof))
  640.  
  641. /* ===========================================================================
  642.  * Processes a new input file and return its compressed length. This
  643.  * function does not perform lazy evaluationof matches and inserts
  644.  * new strings in the dictionary only for unmatched strings or for short
  645.  * matches. It is used only for the fast compression options.
  646.  */
  647. local ulg deflate_fast()
  648. {
  649.     IPos hash_head; /* head of the hash chain */
  650.     int flush;      /* set if current block must be flushed */
  651.     unsigned match_length = 0;  /* length of best match */
  652.  
  653.     prev_length = MIN_MATCH-1;
  654.     while (lookahead != 0) {
  655.         /* Insert the string window[strstart .. strstart+2] in the
  656.          * dictionary, and set hash_head to the head of the hash chain:
  657.          */
  658.         INSERT_STRING(strstart, hash_head);
  659.  
  660.         /* Find the longest match, discarding those <= prev_length.
  661.          * At this point we have always match_length < MIN_MATCH
  662.          */
  663.         if (hash_head != NIL && strstart - hash_head <= MAX_DIST) {
  664.             /* To simplify the code, we prevent matches with the string
  665.              * of window index 0 (in particular we have to avoid a match
  666.              * of the string with itself at the start of the input file).
  667.              */
  668.             match_length = longest_match (hash_head);
  669.             /* longest_match() sets match_start */
  670.             if (match_length > lookahead) match_length = lookahead;
  671.         }
  672.         if (match_length >= MIN_MATCH) {
  673.             check_match(strstart, match_start, match_length);
  674.  
  675.             flush = ct_tally(strstart-match_start, match_length - MIN_MATCH);
  676.  
  677.             lookahead -= match_length;
  678.  
  679.             /* Insert new strings in the hash table only if the match length
  680.              * is not too large. This saves time but degrades compression.
  681.              */
  682.             if (match_length <= max_insert_length) {
  683.                 match_length--; /* string at strstart already in hash table */
  684.                 do {
  685.                     strstart++;
  686.                     INSERT_STRING(strstart, hash_head);
  687.                     /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  688.                      * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
  689.                      * these bytes are garbage, but it does not matter since
  690.                      * the next lookahead bytes will be emitted as literals.
  691.                      */
  692.                 } while (--match_length != 0);
  693.                 strstart++; 
  694.             } else {
  695.                 strstart += match_length;
  696.                 match_length = 0;
  697.                 ins_h = window[strstart];
  698.                 UPDATE_HASH(ins_h, window[strstart+1]);
  699. #if MIN_MATCH != 3
  700.                 Call UPDATE_HASH() MIN_MATCH-3 more times
  701. #endif
  702.             }
  703.         } else {
  704.             /* No match, output a literal byte */
  705.             Tracevv((stderr,"%c",window[strstart]));
  706.             flush = ct_tally (0, window[strstart]);
  707.             lookahead--;
  708.             strstart++; 
  709.         }
  710.         if (flush) FLUSH_BLOCK(0), block_start = strstart;
  711.  
  712.         /* Make sure that we always have enough lookahead, except
  713.          * at the end of the input file. We need MAX_MATCH bytes
  714.          * for the next match, plus MIN_MATCH bytes to insert the
  715.          * string following the next match.
  716.          */
  717.         while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
  718.  
  719.     }
  720.     return FLUSH_BLOCK(1); /* eof */
  721. }
  722.  
  723. /* ===========================================================================
  724.  * Same as above, but achieves better compression. We use a lazy
  725.  * evaluation for matches: a match is finally adopted only if there is
  726.  * no better match at the next window position.
  727.  */
  728. ulg deflate()
  729. {
  730.     IPos hash_head;          /* head of hash chain */
  731.     IPos prev_match;         /* previous match */
  732.     int flush;               /* set if current block must be flushed */
  733.     int match_available = 0; /* set if previous match exists */
  734.     register unsigned match_length = MIN_MATCH-1; /* length of best match */
  735. #ifdef DEBUG
  736.     extern ulg isize;        /* byte length of input file, for debug only */
  737. #endif
  738.  
  739.     if (level <= 3) return deflate_fast(); /* optimized for speed */
  740.  
  741.     /* Process the input block. */
  742.     while (lookahead != 0) {
  743.         /* Insert the string window[strstart .. strstart+2] in the
  744.          * dictionary, and set hash_head to the head of the hash chain:
  745.          */
  746.         INSERT_STRING(strstart, hash_head);
  747.  
  748.         /* Find the longest match, discarding those <= prev_length.
  749.          */
  750.         prev_length = match_length, prev_match = match_start;
  751.         match_length = MIN_MATCH-1;
  752.  
  753.         if (hash_head != NIL && prev_length < max_lazy_match &&
  754.             strstart - hash_head <= MAX_DIST) {
  755.             /* To simplify the code, we prevent matches with the string
  756.              * of window index 0 (in particular we have to avoid a match
  757.              * of the string with itself at the start of the input file).
  758.              */
  759.             match_length = longest_match (hash_head);
  760.             /* longest_match() sets match_start */
  761.             if (match_length > lookahead) match_length = lookahead;
  762.  
  763.             /* Ignore a length 3 match if it is too distant: */
  764.             if (match_length == MIN_MATCH && strstart-match_start > TOO_FAR){
  765.                 /* If prev_match is also MIN_MATCH, match_start is garbage
  766.                  * but we will ignore the current match anyway.
  767.                  */
  768.                 match_length--;
  769.             }
  770.         }
  771.         /* If there was a match at the previous step and the current
  772.          * match is not better, output the previous match:
  773.          */
  774.         if (prev_length >= MIN_MATCH && match_length <= prev_length) {
  775.  
  776.             check_match(strstart-1, prev_match, prev_length);
  777.  
  778.             flush = ct_tally(strstart-1-prev_match, prev_length - MIN_MATCH);
  779.  
  780.             /* Insert in hash table all strings up to the end of the match.
  781.              * strstart-1 and strstart are already inserted.
  782.              */
  783.             lookahead -= prev_length-1;
  784.             prev_length -= 2;
  785.             do {
  786.                 strstart++;
  787.                 INSERT_STRING(strstart, hash_head);
  788.                 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  789.                  * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
  790.                  * these bytes are garbage, but it does not matter since the
  791.                  * next lookahead bytes will always be emitted as literals.
  792.                  */
  793.             } while (--prev_length != 0);
  794.             match_available = 0;
  795.             match_length = MIN_MATCH-1;
  796.             strstart++;
  797.             if (flush) FLUSH_BLOCK(0), block_start = strstart;
  798.  
  799.         } else if (match_available) {
  800.             /* If there was no match at the previous position, output a
  801.              * single literal. If there was a match but the current match
  802.              * is longer, truncate the previous match to a single literal.
  803.              */
  804.             Tracevv((stderr,"%c",window[strstart-1]));
  805.             if (ct_tally (0, window[strstart-1])) {
  806.                 FLUSH_BLOCK(0), block_start = strstart;
  807.             }
  808.             strstart++;
  809.             lookahead--;
  810.         } else {
  811.             /* There is no previous match to compare with, wait for
  812.              * the next step to decide.
  813.              */
  814.             match_available = 1;
  815.             strstart++;
  816.             lookahead--;
  817.         }
  818.         Assert (strstart <= isize && lookahead <= isize, "a bit too far");
  819.  
  820.         /* Make sure that we always have enough lookahead, except
  821.          * at the end of the input file. We need MAX_MATCH bytes
  822.          * for the next match, plus MIN_MATCH bytes to insert the
  823.          * string following the next match.
  824.          */
  825.         while (lookahead < MIN_LOOKAHEAD && !eofile) fill_window();
  826.     }
  827.     if (match_available) ct_tally (0, window[strstart-1]);
  828.  
  829.     return FLUSH_BLOCK(1); /* eof */
  830. }
  831.  
  832.