home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 9 Archive / 09-Archive.zip / zip21.zip / deflate.c < prev    next >
C/C++ Source or Header  |  1996-04-01  |  32KB  |  851 lines

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