deflate.c
上传用户:zlh9724
上传日期:2007-01-04
资源大小:1991k
文件大小:36k
源码类别:

浏览器

开发平台:

Unix_Linux

  1. /* deflate.c -- compress data using the deflation algorithm
  2.  * Copyright (C) 1995 Jean-loup Gailly.
  3.  * For conditions of distribution and use, see copyright notice in zlib.h 
  4.  */
  5. /*
  6.  *  ALGORITHM
  7.  *
  8.  *      The "deflation" process depends on being able to identify portions
  9.  *      of the input text which are identical to earlier input (within a
  10.  *      sliding window trailing behind the input currently being processed).
  11.  *
  12.  *      The most straightforward technique turns out to be the fastest for
  13.  *      most input files: try all possible matches and select the longest.
  14.  *      The key feature of this algorithm is that insertions into the string
  15.  *      dictionary are very simple and thus fast, and deletions are avoided
  16.  *      completely. Insertions are performed at each input character, whereas
  17.  *      string matches are performed only when the previous match ends. So it
  18.  *      is preferable to spend more time in matches to allow very fast string
  19.  *      insertions and avoid deletions. The matching algorithm for small
  20.  *      strings is inspired from that of Rabin & Karp. A brute force approach
  21.  *      is used to find longer strings when a small match has been found.
  22.  *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  23.  *      (by Leonid Broukhis).
  24.  *         A previous version of this file used a more sophisticated algorithm
  25.  *      (by Fiala and Greene) which is guaranteed to run in linear amortized
  26.  *      time, but has a larger average cost, uses more memory and is patented.
  27.  *      However the F&G algorithm may be faster for some highly redundant
  28.  *      files if the parameter max_chain_length (described below) is too large.
  29.  *
  30.  *  ACKNOWLEDGEMENTS
  31.  *
  32.  *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  33.  *      I found it in 'freeze' written by Leonid Broukhis.
  34.  *      Thanks to many people for bug reports and testing.
  35.  *
  36.  *  REFERENCES
  37.  *
  38.  *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  39.  *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  40.  *
  41.  *      A description of the Rabin and Karp algorithm is given in the book
  42.  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  43.  *
  44.  *      Fiala,E.R., and Greene,D.H.
  45.  *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  46.  *
  47.  */
  48. /* $Id: deflate.c,v 1.8 1995/05/03 17:27:08 jloup Exp $ */
  49. #include "deflate.h"
  50. char copyright[] = " deflate Copyright 1995 Jean-loup Gailly ";
  51. /*
  52.   If you use the zlib library in a product, an acknowledgment is welcome
  53.   in the documentation of your product. If for some reason you cannot
  54.   include such an acknowledgment, I would appreciate that you keep this
  55.   copyright string in the executable of your product.
  56.  */
  57. #define NIL 0
  58. /* Tail of hash chains */
  59. #ifndef TOO_FAR
  60. #  define TOO_FAR 4096
  61. #endif
  62. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  63. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  64. /* Minimum amount of lookahead, except at the end of the input file.
  65.  * See deflate.c for comments about the MIN_MATCH+1.
  66.  */
  67. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  68.  * the desired pack level (0..9). The values given below have been tuned to
  69.  * exclude worst case performance for pathological files. Better values may be
  70.  * found for specific files.
  71.  */
  72. typedef struct config_s {
  73.    ush good_length; /* reduce lazy search above this match length */
  74.    ush max_lazy;    /* do not perform lazy search above this match length */
  75.    ush nice_length; /* quit search above this match length */
  76.    ush max_chain;
  77. } config;
  78. local config configuration_table[10] = {
  79. /*      good lazy nice chain */
  80. /* 0 */ {0,    0,  0,    0},  /* store only */
  81. /* 1 */ {4,    4,  8,    4},  /* maximum speed, no lazy matches */
  82. /* 2 */ {4,    5, 16,    8},
  83. /* 3 */ {4,    6, 32,   32},
  84. /* 4 */ {4,    4, 16,   16},  /* lazy matches */
  85. /* 5 */ {8,   16, 32,   32},
  86. /* 6 */ {8,   16, 128, 128},
  87. /* 7 */ {8,   32, 128, 256},
  88. /* 8 */ {32, 128, 258, 1024},
  89. /* 9 */ {32, 258, 258, 4096}}; /* maximum compression */
  90. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  91.  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  92.  * meaning.
  93.  */
  94. #define EQUAL 0
  95. /* result of memcmp for equal strings */
  96. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  97. /* ===========================================================================
  98.  *  Prototypes for local functions.
  99.  */
  100. local void fill_window   OF((deflate_state *s));
  101. local int  deflate_fast  OF((deflate_state *s, int flush));
  102. local int  deflate_slow  OF((deflate_state *s, int flush));
  103. local void lm_init       OF((deflate_state *s));
  104. local int longest_match  OF((deflate_state *s, IPos cur_match));
  105. local void putShortMSB   OF((deflate_state *s, uInt b));
  106. local void flush_pending OF((z_stream *strm));
  107. local int read_buf       OF((z_stream *strm, charf *buf, unsigned size));
  108. #ifdef ASMV
  109.       void match_init OF((void)); /* asm code initialization */
  110. #endif
  111. #ifdef DEBUG
  112. local  void check_match OF((deflate_state *s, IPos start, IPos match,
  113.                             int length));
  114. #endif
  115. /* ===========================================================================
  116.  * Update a hash value with the given input byte
  117.  * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
  118.  *    input characters, so that a running hash key can be computed from the
  119.  *    previous key instead of complete recalculation each time.
  120.  */
  121. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  122. /* ===========================================================================
  123.  * Insert string str in the dictionary and set match_head to the previous head
  124.  * of the hash chain (the most recent string with same hash key). Return
  125.  * the previous length of the hash chain.
  126.  * IN  assertion: all calls to to INSERT_STRING are made with consecutive
  127.  *    input characters and the first MIN_MATCH bytes of str are valid
  128.  *    (except for the last MIN_MATCH-1 bytes of the input file).
  129.  */
  130. #define INSERT_STRING(s, str, match_head) 
  131.    (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), 
  132.     s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], 
  133.     s->head[s->ins_h] = (str))
  134. /* ===========================================================================
  135.  * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  136.  * prev[] will be initialized on the fly.
  137.  */
  138. #define CLEAR_HASH(s) 
  139.     s->head[s->hash_size-1] = NIL; 
  140.     zmemzero((charf *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  141. /* ========================================================================= */
  142. int deflateInit (strm, level)
  143.     z_stream *strm;
  144.     int level;
  145. {
  146.     return deflateInit2 (strm, level, DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, 0);
  147.     /* To do: ignore strm->next_in if we use it as window */
  148. }
  149. /* ========================================================================= */
  150. int deflateInit2 (strm, level, method, windowBits, memLevel, strategy)
  151.     z_stream *strm;
  152.     int  level;
  153.     int  method;
  154.     int  windowBits;
  155.     int  memLevel;
  156.     int  strategy;
  157. {
  158.     deflate_state *s;
  159.     int noheader = 0;
  160.     if (strm == Z_NULL) return Z_STREAM_ERROR;
  161.     strm->msg = Z_NULL;
  162.     if (strm->zalloc == Z_NULL) strm->zalloc = zcalloc;
  163.     if (strm->zfree == Z_NULL) strm->zfree = zcfree;
  164.     if (level == Z_DEFAULT_COMPRESSION) level = 6;
  165.     if (windowBits < 0) { /* undocumented feature: suppress zlib header */
  166.         noheader = 1;
  167.         windowBits = -windowBits;
  168.     }
  169.     if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != DEFLATED ||
  170.         windowBits < 8 || windowBits > 15 || level < 1 || level > 9) {
  171.         return Z_STREAM_ERROR;
  172.     }
  173.     s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  174.     if (s == Z_NULL) return Z_MEM_ERROR;
  175.     strm->state = (struct internal_state FAR *)s;
  176.     s->strm = strm;
  177.     s->noheader = noheader;
  178.     s->w_bits = windowBits;
  179.     s->w_size = 1 << s->w_bits;
  180.     s->w_mask = s->w_size - 1;
  181.     s->hash_bits = memLevel + 7;
  182.     s->hash_size = 1 << s->hash_bits;
  183.     s->hash_mask = s->hash_size - 1;
  184.     s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  185.     s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  186.     s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
  187.     s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
  188.     s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  189.     s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, 2*sizeof(ush));
  190.     if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  191.         s->pending_buf == Z_NULL) {
  192.         strm->msg = z_errmsg[1-Z_MEM_ERROR];
  193.         deflateEnd (strm);
  194.         return Z_MEM_ERROR;
  195.     }
  196.     s->d_buf = (ushf *) &(s->pending_buf[s->lit_bufsize]);
  197.     s->l_buf = (uchf *) &(s->pending_buf[3*s->lit_bufsize]);
  198.     /* We overlay pending_buf and d_buf+l_buf. This works since the average
  199.      * output size for (length,distance) codes is <= 32 bits (worst case
  200.      * is 15+15+13=33).
  201.      */
  202.     s->level = level;
  203.     s->strategy = strategy;
  204.     s->method = (Byte)method;
  205.     return deflateReset(strm);
  206. }
  207. /* ========================================================================= */
  208. int deflateReset (strm)
  209.     z_stream *strm;
  210. {
  211.     deflate_state *s;
  212.     
  213.     if (strm == Z_NULL || strm->state == Z_NULL ||
  214.         strm->zalloc == Z_NULL || strm->zfree == Z_NULL) return Z_STREAM_ERROR;
  215.     strm->total_in = strm->total_out = 0;
  216.     strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  217.     strm->data_type = Z_UNKNOWN;
  218.     s = (deflate_state *)strm->state;
  219.     s->pending = 0;
  220.     s->pending_out = s->pending_buf;
  221.     if (s->noheader < 0) {
  222.         s->noheader = 0; /* was set to -1 by deflate(..., Z_FINISH); */
  223.     }
  224.     s->status = s->noheader ? BUSY_STATE : INIT_STATE;
  225.     s->adler = 1;
  226.     ct_init(s);
  227.     lm_init(s);
  228.     return Z_OK;
  229. }
  230. /* =========================================================================
  231.  * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  232.  * IN assertion: the stream state is correct and there is enough room in
  233.  * pending_buf.
  234.  */
  235. local void putShortMSB (s, b)
  236.     deflate_state *s;
  237.     uInt b;
  238. {
  239.     put_byte(s, (Byte)(b >> 8));
  240.     put_byte(s, (Byte)(b & 0xff));
  241. }   
  242. /* =========================================================================
  243.  * Flush as much pending output as possible.
  244.  */
  245. local void flush_pending(strm)
  246.     z_stream *strm;
  247. {
  248.     unsigned len = strm->state->pending;
  249.     if (len > strm->avail_out) len = strm->avail_out;
  250.     if (len == 0) return;
  251.     zmemcpy(strm->next_out, strm->state->pending_out, len);
  252.     strm->next_out  += len;
  253.     strm->state->pending_out  += len;
  254.     strm->total_out += len;
  255.     strm->avail_out  -= len;
  256.     strm->state->pending -= len;
  257.     if (strm->state->pending == 0) {
  258.         strm->state->pending_out = strm->state->pending_buf;
  259.     }
  260. }
  261. /* ========================================================================= */
  262. int deflate (strm, flush)
  263.     z_stream *strm;
  264.     int flush;
  265. {
  266.     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  267.     
  268.     if (strm->next_out == Z_NULL ||
  269.         (strm->next_in == Z_NULL && strm->avail_in != 0)) {
  270.         ERR_RETURN(strm, Z_STREAM_ERROR);
  271.     }
  272.     if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  273.     strm->state->strm = strm; /* just in case */
  274.     /* Write the zlib header */
  275.     if (strm->state->status == INIT_STATE) {
  276.         uInt header = (DEFLATED + ((strm->state->w_bits-8)<<4)) << 8;
  277.         uInt level_flags = (strm->state->level-1) >> 1;
  278.         if (level_flags > 3) level_flags = 3;
  279.         header |= (level_flags << 6);
  280.         header += 31 - (header % 31);
  281.         strm->state->status = BUSY_STATE;
  282.         putShortMSB(strm->state, header);
  283.     }
  284.     /* Flush as much pending output as possible */
  285.     if (strm->state->pending != 0) {
  286.         flush_pending(strm);
  287.         if (strm->avail_out == 0) return Z_OK;
  288.     }
  289.     /* User must not provide more input after the first FINISH: */
  290.     if (strm->state->status == FINISH_STATE && strm->avail_in != 0) {
  291.         ERR_RETURN(strm, Z_BUF_ERROR);
  292.     }
  293.     /* Start a new block or continue the current one.
  294.      */
  295.     if (strm->avail_in != 0 || strm->state->lookahead != 0 ||
  296.         (flush != Z_NO_FLUSH && strm->state->status != FINISH_STATE)) {
  297.         int quit;
  298.         if (flush == Z_FINISH) {
  299.             strm->state->status = FINISH_STATE;
  300.         }
  301.         if (strm->state->level <= 3) {
  302.             quit = deflate_fast(strm->state, flush);
  303.         } else {
  304.             quit = deflate_slow(strm->state, flush);
  305.         }
  306.         if (quit || strm->avail_out == 0) return Z_OK;
  307.         /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  308.          * of deflate should use the same flush parameter to make sure
  309.          * that the flush is complete. So we don't have to output an
  310.          * empty block here, this will be done at next call. This also
  311.          * ensures that for a very small output buffer, we emit at most
  312.          * one empty block.
  313.          */
  314.         if (flush != Z_OK && flush != Z_FINISH) {
  315.             if (flush == Z_PARTIAL_FLUSH) {
  316.                 ct_align(strm->state);
  317.             } else { /* FULL_FLUSH or SYNC_FLUSH */
  318.                 ct_stored_block(strm->state, (char*)0, 0L, 0);
  319.                 /* For a full flush, this empty block will be recognized
  320.                  * as a special marker by inflate_sync().
  321.                  */
  322.                 if (flush == Z_FULL_FLUSH) {
  323.                     CLEAR_HASH(strm->state);             /* forget history */
  324.                 }
  325.             }
  326.             flush_pending(strm);
  327.             if (strm->avail_out == 0) return Z_OK;
  328.         }
  329.     }
  330.     Assert(strm->avail_out > 0, "bug2");
  331.     if (flush != Z_FINISH) return Z_OK;
  332.     if (strm->state->noheader) return Z_STREAM_END;
  333.     /* Write the zlib trailer (adler32) */
  334.     putShortMSB(strm->state, (uInt)(strm->state->adler >> 16));
  335.     putShortMSB(strm->state, (uInt)(strm->state->adler & 0xffff));
  336.     flush_pending(strm);
  337.     /* If avail_out is zero, the application will call deflate again
  338.      * to flush the rest.
  339.      */
  340.     strm->state->noheader = -1; /* write the trailer only once! */
  341.     return strm->state->pending != 0 ? Z_OK : Z_STREAM_END;
  342. }
  343. /* ========================================================================= */
  344. int deflateEnd (strm)
  345.     z_stream *strm;
  346. {
  347.     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  348.     TRY_FREE(strm, strm->state->window);
  349.     TRY_FREE(strm, strm->state->prev);
  350.     TRY_FREE(strm, strm->state->head);
  351.     TRY_FREE(strm, strm->state->pending_buf);
  352.     ZFREE(strm, strm->state);
  353.     strm->state = Z_NULL;
  354.     return Z_OK;
  355. }
  356. /* ========================================================================= */
  357. int deflateCopy (dest, source)
  358.     z_stream *dest;
  359.     z_stream *source;
  360. {
  361.     if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  362.         return Z_STREAM_ERROR;
  363.     }
  364.     *dest = *source;
  365.     return Z_STREAM_ERROR; /* to be implemented */
  366. #if 0
  367.     dest->state = (struct internal_state FAR *)
  368.         (*dest->zalloc)(1, sizeof(deflate_state));
  369.     if (dest->state == Z_NULL) return Z_MEM_ERROR;
  370.     *(dest->state) = *(source->state);
  371.     return Z_OK;
  372. #endif
  373. }
  374. /* ===========================================================================
  375.  * Read a new buffer from the current input stream, update the adler32
  376.  * and total number of bytes read.
  377.  */
  378. local int read_buf(strm, buf, size)
  379.     z_stream *strm;
  380.     charf *buf;
  381.     unsigned size;
  382. {
  383.     unsigned len = strm->avail_in;
  384.     if (len > size) len = size;
  385.     if (len == 0) return 0;
  386.     strm->avail_in  -= len;
  387.     if (!strm->state->noheader) {
  388.         strm->state->adler = adler32(strm->state->adler, strm->next_in, len);
  389.     }
  390.     zmemcpy(buf, strm->next_in, len);
  391.     strm->next_in  += len;
  392.     strm->total_in += len;
  393.     return (int)len;
  394. }
  395. /* ===========================================================================
  396.  * Initialize the "longest match" routines for a new zlib stream
  397.  */
  398. local void lm_init (s)
  399.     deflate_state *s;
  400. {
  401.     s->window_size = (ulg)2L*s->w_size;
  402.     CLEAR_HASH(s);
  403.     /* Set the default configuration parameters:
  404.      */
  405.     s->max_lazy_match   = configuration_table[s->level].max_lazy;
  406.     s->good_match       = configuration_table[s->level].good_length;
  407.     s->nice_match       = configuration_table[s->level].nice_length;
  408.     s->max_chain_length = configuration_table[s->level].max_chain;
  409.     s->strstart = 0;
  410.     s->block_start = 0L;
  411.     s->lookahead = 0;
  412.     s->match_length = MIN_MATCH-1;
  413.     s->match_available = 0;
  414.     s->ins_h = 0;
  415. #ifdef ASMV
  416.     match_init(); /* initialize the asm code */
  417. #endif
  418. }
  419. /* ===========================================================================
  420.  * Set match_start to the longest match starting at the given string and
  421.  * return its length. Matches shorter or equal to prev_length are discarded,
  422.  * in which case the result is equal to prev_length and match_start is
  423.  * garbage.
  424.  * IN assertions: cur_match is the head of the hash chain for the current
  425.  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  426.  */
  427. #ifndef ASMV
  428. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  429.  * match.S. The code will be functionally equivalent.
  430.  */
  431. local int longest_match(s, cur_match)
  432.     deflate_state *s;
  433.     IPos cur_match;                             /* current match */
  434. {
  435.     unsigned chain_length = s->max_chain_length;/* max hash chain length */
  436.     register Bytef *scan = s->window + s->strstart; /* current string */
  437.     register Bytef *match;                       /* matched string */
  438.     register int len;                           /* length of current match */
  439.     int best_len = s->prev_length;              /* best match length so far */
  440.     IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  441.         s->strstart - (IPos)MAX_DIST(s) : NIL;
  442.     /* Stop when cur_match becomes <= limit. To simplify the code,
  443.      * we prevent matches with the string of window index 0.
  444.      */
  445.     Posf *prev = s->prev;
  446.     uInt wmask = s->w_mask;
  447. #ifdef UNALIGNED_OK
  448.     /* Compare two bytes at a time. Note: this is not always beneficial.
  449.      * Try with and without -DUNALIGNED_OK to check.
  450.      */
  451.     register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  452.     register ush scan_start = *(ushf*)scan;
  453.     register ush scan_end   = *(ushf*)(scan+best_len-1);
  454. #else
  455.     register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  456.     register Byte scan_end1  = scan[best_len-1];
  457.     register Byte scan_end   = scan[best_len];
  458. #endif
  459.     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  460.      * It is easy to get rid of this optimization if necessary.
  461.      */
  462.     Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  463.     /* Do not waste too much time if we already have a good match: */
  464.     if (s->prev_length >= s->good_match) {
  465.         chain_length >>= 2;
  466.     }
  467.     Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  468.     do {
  469.         Assert(cur_match < s->strstart, "no future");
  470.         match = s->window + cur_match;
  471.         /* Skip to next match if the match length cannot increase
  472.          * or if the match length is less than 2:
  473.          */
  474. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  475.         /* This code assumes sizeof(unsigned short) == 2. Do not use
  476.          * UNALIGNED_OK if your compiler uses a different size.
  477.          */
  478.         if (*(ushf*)(match+best_len-1) != scan_end ||
  479.             *(ushf*)match != scan_start) continue;
  480.         /* It is not necessary to compare scan[2] and match[2] since they are
  481.          * always equal when the other bytes match, given that the hash keys
  482.          * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  483.          * strstart+3, +5, ... up to strstart+257. We check for insufficient
  484.          * lookahead only every 4th comparison; the 128th check will be made
  485.          * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  486.          * necessary to put more guard bytes at the end of the window, or
  487.          * to check more often for insufficient lookahead.
  488.          */
  489.         Assert(scan[2] == match[2], "scan[2]?");
  490.         scan++, match++;
  491.         do {
  492.         } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  493.                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  494.                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  495.                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  496.                  scan < strend);
  497.         /* The funny "do {}" generates better code on most compilers */
  498.         /* Here, scan <= window+strstart+257 */
  499.         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  500.         if (*scan == *match) scan++;
  501.         len = (MAX_MATCH - 1) - (int)(strend-scan);
  502.         scan = strend - (MAX_MATCH-1);
  503. #else /* UNALIGNED_OK */
  504.         if (match[best_len]   != scan_end  ||
  505.             match[best_len-1] != scan_end1 ||
  506.             *match            != *scan     ||
  507.             *++match          != scan[1])      continue;
  508.         /* The check at best_len-1 can be removed because it will be made
  509.          * again later. (This heuristic is not always a win.)
  510.          * It is not necessary to compare scan[2] and match[2] since they
  511.          * are always equal when the other bytes match, given that
  512.          * the hash keys are equal and that HASH_BITS >= 8.
  513.          */
  514.         scan += 2, match++;
  515.         Assert(*scan == *match, "match[2]?");
  516.         /* We check for insufficient lookahead only every 8th comparison;
  517.          * the 256th check will be made at strstart+258.
  518.          */
  519.         do {
  520.         } while (*++scan == *++match && *++scan == *++match &&
  521.                  *++scan == *++match && *++scan == *++match &&
  522.                  *++scan == *++match && *++scan == *++match &&
  523.                  *++scan == *++match && *++scan == *++match &&
  524.                  scan < strend);
  525.         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  526.         len = MAX_MATCH - (int)(strend - scan);
  527.         scan = strend - MAX_MATCH;
  528. #endif /* UNALIGNED_OK */
  529.         if (len > best_len) {
  530.             s->match_start = cur_match;
  531.             best_len = len;
  532.             if (len >= s->nice_match) break;
  533. #ifdef UNALIGNED_OK
  534.             scan_end = *(ushf*)(scan+best_len-1);
  535. #else
  536.             scan_end1  = scan[best_len-1];
  537.             scan_end   = scan[best_len];
  538. #endif
  539.         }
  540.     } while ((cur_match = prev[cur_match & wmask]) > limit
  541.              && --chain_length != 0);
  542.     return best_len;
  543. }
  544. #endif /* ASMV */
  545. #ifdef DEBUG
  546. /* ===========================================================================
  547.  * Check that the match at match_start is indeed a match.
  548.  */
  549. local void check_match(s, start, match, length)
  550.     deflate_state *s;
  551.     IPos start, match;
  552.     int length;
  553. {
  554.     /* check that the match is indeed a match */
  555.     if (memcmp((charf *)s->window + match,
  556.                 (charf *)s->window + start, length) != EQUAL) {
  557.         fprintf(stderr,
  558.             " start %u, match %u, length %dn",
  559.             start, match, length);
  560.         do { fprintf(stderr, "%c%c", s->window[match++],
  561.                      s->window[start++]); } while (--length != 0);
  562.         z_error("invalid match");
  563.     }
  564.     if (verbose > 1) {
  565.         fprintf(stderr,"\[%d,%d]", start-match, length);
  566.         do { putc(s->window[start++], stderr); } while (--length != 0);
  567.     }
  568. }
  569. #else
  570. #  define check_match(s, start, match, length)
  571. #endif
  572. /* ===========================================================================
  573.  * Fill the window when the lookahead becomes insufficient.
  574.  * Updates strstart and lookahead.
  575.  *
  576.  * IN assertion: lookahead < MIN_LOOKAHEAD
  577.  * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  578.  *    At least one byte has been read, or avail_in == 0; reads are
  579.  *    performed for at least two bytes (required for the zip translate_eol
  580.  *    option -- not supported here).
  581.  */
  582. local void fill_window(s)
  583.     deflate_state *s;
  584. {
  585.     register unsigned n, m;
  586.     register Posf *p;
  587.     unsigned more;    /* Amount of free space at the end of the window. */
  588.     uInt wsize = s->w_size;
  589.     do {
  590.         more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  591.         /* Deal with !@#$% 64K limit: */
  592.         if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  593.             more = wsize;
  594.         } else if (more == (unsigned)(-1)) {
  595.             /* Very unlikely, but possible on 16 bit machine if strstart == 0
  596.              * and lookahead == 1 (input done one byte at time)
  597.              */
  598.             more--;
  599.         /* If the window is almost full and there is insufficient lookahead,
  600.          * move the upper half to the lower one to make room in the upper half.
  601.          */
  602.         } else if (s->strstart >= wsize+MAX_DIST(s)) {
  603.             /* By the IN assertion, the window is not empty so we can't confuse
  604.              * more == 0 with more == 64K on a 16 bit machine.
  605.              */
  606.             zmemcpy((charf *)s->window, (charf *)s->window+wsize,
  607.                    (unsigned)wsize);
  608.             s->match_start -= wsize;
  609.             s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
  610.             s->block_start -= (long) wsize;
  611.             /* Slide the hash table (could be avoided with 32 bit values
  612.                at the expense of memory usage):
  613.              */
  614.             n = s->hash_size;
  615.             p = &s->head[n];
  616.             do {
  617.                 m = *--p;
  618.                 *p = (Pos)(m >= wsize ? m-wsize : NIL);
  619.             } while (--n);
  620.             n = wsize;
  621.             p = &s->prev[n];
  622.             do {
  623.                 m = *--p;
  624.                 *p = (Pos)(m >= wsize ? m-wsize : NIL);
  625.                 /* If n is not on any hash chain, prev[n] is garbage but
  626.                  * its value will never be used.
  627.                  */
  628.             } while (--n);
  629.             more += wsize;
  630.         }
  631.         if (s->strm->avail_in == 0) return;
  632.         /* If there was no sliding:
  633.          *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  634.          *    more == window_size - lookahead - strstart
  635.          * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  636.          * => more >= window_size - 2*WSIZE + 2
  637.          * In the BIG_MEM or MMAP case (not yet supported),
  638.          *   window_size == input_size + MIN_LOOKAHEAD  &&
  639.          *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  640.          * Otherwise, window_size == 2*WSIZE so more >= 2.
  641.          * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  642.          */
  643.         Assert(more >= 2, "more < 2");
  644.         n = read_buf(s->strm, (charf *)s->window + s->strstart + s->lookahead,
  645.                      more);
  646.         s->lookahead += n;
  647.         /* Initialize the hash value now that we have some input: */
  648.         if (s->lookahead >= MIN_MATCH) {
  649.             s->ins_h = s->window[s->strstart];
  650.             UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  651. #if MIN_MATCH != 3
  652.             Call UPDATE_HASH() MIN_MATCH-3 more times
  653. #endif
  654.         }
  655.         /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  656.          * but this is not important since only literal bytes will be emitted.
  657.          */
  658.     } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  659. }
  660. /* ===========================================================================
  661.  * Flush the current block, with given end-of-file flag.
  662.  * IN assertion: strstart is set to the end of the current match.
  663.  */
  664. #define FLUSH_BLOCK_ONLY(s, eof) { 
  665.    ct_flush_block(s, (s->block_start >= 0L ? 
  666.                (charf *)&s->window[(unsigned)s->block_start] : 
  667.                (charf *)Z_NULL), (long)s->strstart - s->block_start, (eof)); 
  668.    s->block_start = s->strstart; 
  669.    flush_pending(s->strm); 
  670.    Tracev((stderr,"[FLUSH]")); 
  671. }
  672. /* Same but force premature exit if necessary. */
  673. #define FLUSH_BLOCK(s, eof) { 
  674.    FLUSH_BLOCK_ONLY(s, eof); 
  675.    if (s->strm->avail_out == 0) return 1; 
  676. }
  677. /* ===========================================================================
  678.  * Compress as much as possible from the input stream, return true if
  679.  * processing was terminated prematurely (no more input or output space).
  680.  * This function does not perform lazy evaluationof matches and inserts
  681.  * new strings in the dictionary only for unmatched strings or for short
  682.  * matches. It is used only for the fast compression options.
  683.  */
  684. local int deflate_fast(s, flush)
  685.     deflate_state *s;
  686.     int flush;
  687. {
  688.     IPos hash_head; /* head of the hash chain */
  689.     int bflush;     /* set if current block must be flushed */
  690.     s->prev_length = MIN_MATCH-1;
  691.     for (;;) {
  692.         /* Make sure that we always have enough lookahead, except
  693.          * at the end of the input file. We need MAX_MATCH bytes
  694.          * for the next match, plus MIN_MATCH bytes to insert the
  695.          * string following the next match.
  696.          */
  697.         if (s->lookahead < MIN_LOOKAHEAD) {
  698.             fill_window(s);
  699.             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) return 1;
  700.             if (s->lookahead == 0) break; /* flush the current block */
  701.         }
  702.         /* Insert the string window[strstart .. strstart+2] in the
  703.          * dictionary, and set hash_head to the head of the hash chain:
  704.          */
  705.         if (s->lookahead >= MIN_MATCH) {
  706.             INSERT_STRING(s, s->strstart, hash_head);
  707.         }
  708.         /* Find the longest match, discarding those <= prev_length.
  709.          * At this point we have always match_length < MIN_MATCH
  710.          */
  711.         if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  712.             /* To simplify the code, we prevent matches with the string
  713.              * of window index 0 (in particular we have to avoid a match
  714.              * of the string with itself at the start of the input file).
  715.              */
  716.             if (s->strategy != Z_HUFFMAN_ONLY) {
  717.                 s->match_length = longest_match (s, hash_head);
  718.             }
  719.             /* longest_match() sets match_start */
  720.             if (s->match_length > s->lookahead) s->match_length = s->lookahead;
  721.         }
  722.         if (s->match_length >= MIN_MATCH) {
  723.             check_match(s, s->strstart, s->match_start, s->match_length);
  724.             bflush = ct_tally(s, s->strstart - s->match_start,
  725.                               s->match_length - MIN_MATCH);
  726.             s->lookahead -= s->match_length;
  727.             /* Insert new strings in the hash table only if the match length
  728.              * is not too large. This saves time but degrades compression.
  729.              */
  730.             if (s->match_length <= s->max_insert_length &&
  731.                 s->lookahead >= MIN_MATCH) {
  732.                 s->match_length--; /* string at strstart already in hash table */
  733.                 do {
  734.                     s->strstart++;
  735.                     INSERT_STRING(s, s->strstart, hash_head);
  736.                     /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  737.                      * always MIN_MATCH bytes ahead.
  738.                      */
  739.                 } while (--s->match_length != 0);
  740.                 s->strstart++; 
  741.             } else {
  742.                 s->strstart += s->match_length;
  743.                 s->match_length = 0;
  744.                 s->ins_h = s->window[s->strstart];
  745.                 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  746. #if MIN_MATCH != 3
  747.                 Call UPDATE_HASH() MIN_MATCH-3 more times
  748. #endif
  749.                 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  750.                  * matter since it will be recomputed at next deflate call.
  751.                  */
  752.             }
  753.         } else {
  754.             /* No match, output a literal byte */
  755.             Tracevv((stderr,"%c", s->window[s->strstart]));
  756.             bflush = ct_tally (s, 0, s->window[s->strstart]);
  757.             s->lookahead--;
  758.             s->strstart++; 
  759.         }
  760.         if (bflush) FLUSH_BLOCK(s, 0);
  761.     }
  762.     FLUSH_BLOCK(s, flush == Z_FINISH);
  763.     return 0; /* normal exit */
  764. }
  765. /* ===========================================================================
  766.  * Same as above, but achieves better compression. We use a lazy
  767.  * evaluation for matches: a match is finally adopted only if there is
  768.  * no better match at the next window position.
  769.  */
  770. local int deflate_slow(s, flush)
  771.     deflate_state *s;
  772.     int flush;
  773. {
  774.     IPos hash_head;          /* head of hash chain */
  775.     int bflush;              /* set if current block must be flushed */
  776.     /* Process the input block. */
  777.     for (;;) {
  778.         /* Make sure that we always have enough lookahead, except
  779.          * at the end of the input file. We need MAX_MATCH bytes
  780.          * for the next match, plus MIN_MATCH bytes to insert the
  781.          * string following the next match.
  782.          */
  783.         if (s->lookahead < MIN_LOOKAHEAD) {
  784.             fill_window(s);
  785.             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) return 1;
  786.             if (s->lookahead == 0) break; /* flush the current block */
  787.         }
  788.         /* Insert the string window[strstart .. strstart+2] in the
  789.          * dictionary, and set hash_head to the head of the hash chain:
  790.          */
  791.         if (s->lookahead >= MIN_MATCH) {
  792.             INSERT_STRING(s, s->strstart, hash_head);
  793.         }
  794.         /* Find the longest match, discarding those <= prev_length.
  795.          */
  796.         s->prev_length = s->match_length, s->prev_match = s->match_start;
  797.         s->match_length = MIN_MATCH-1;
  798.         if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  799.             s->strstart - hash_head <= MAX_DIST(s)) {
  800.             /* To simplify the code, we prevent matches with the string
  801.              * of window index 0 (in particular we have to avoid a match
  802.              * of the string with itself at the start of the input file).
  803.              */
  804.             if (s->strategy != Z_HUFFMAN_ONLY) {
  805.                 s->match_length = longest_match (s, hash_head);
  806.             }
  807.             /* longest_match() sets match_start */
  808.             if (s->match_length > s->lookahead) s->match_length = s->lookahead;
  809.             if (s->match_length <= 5 && (s->strategy == Z_FILTERED ||
  810.                  (s->match_length == MIN_MATCH &&
  811.                   s->strstart - s->match_start > TOO_FAR))) {
  812.                 /* If prev_match is also MIN_MATCH, match_start is garbage
  813.                  * but we will ignore the current match anyway.
  814.                  */
  815.                 s->match_length = MIN_MATCH-1;
  816.             }
  817.         }
  818.         /* If there was a match at the previous step and the current
  819.          * match is not better, output the previous match:
  820.          */
  821.         if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  822.             uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  823.             /* Do not insert strings in hash table beyond this. */
  824.             check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  825.             bflush = ct_tally(s, s->strstart -1 - s->prev_match,
  826.                               s->prev_length - MIN_MATCH);
  827.             /* Insert in hash table all strings up to the end of the match.
  828.              * strstart-1 and strstart are already inserted. If there is not
  829.              * enough lookahead, the last two strings are not inserted in
  830.              * the hash table.
  831.              */
  832.             s->lookahead -= s->prev_length-1;
  833.             s->prev_length -= 2;
  834.             do {
  835.                 if (++s->strstart <= max_insert) {
  836.                     INSERT_STRING(s, s->strstart, hash_head);
  837.                 }
  838.             } while (--s->prev_length != 0);
  839.             s->match_available = 0;
  840.             s->match_length = MIN_MATCH-1;
  841.             s->strstart++;
  842.             if (bflush) FLUSH_BLOCK(s, 0);
  843.         } else if (s->match_available) {
  844.             /* If there was no match at the previous position, output a
  845.              * single literal. If there was a match but the current match
  846.              * is longer, truncate the previous match to a single literal.
  847.              */
  848.             Tracevv((stderr,"%c", s->window[s->strstart-1]));
  849.             if (ct_tally (s, 0, s->window[s->strstart-1])) {
  850.                 FLUSH_BLOCK_ONLY(s, 0);
  851.             }
  852.             s->strstart++;
  853.             s->lookahead--;
  854.             if (s->strm->avail_out == 0) return 1;
  855.         } else {
  856.             /* There is no previous match to compare with, wait for
  857.              * the next step to decide.
  858.              */
  859.             s->match_available = 1;
  860.             s->strstart++;
  861.             s->lookahead--;
  862.         }
  863.     }
  864.     Assert (flush != Z_NO_FLUSH, "no flush?");
  865.     if (s->match_available) {
  866.         Tracevv((stderr,"%c", s->window[s->strstart-1]));
  867.         ct_tally (s, 0, s->window[s->strstart-1]);
  868.         s->match_available = 0;
  869.     }
  870.     FLUSH_BLOCK(s, flush == Z_FINISH);
  871.     return 0;
  872. }