deflate.cc

Go to the documentation of this file.
00001 /* deflate.c -- compress data using the deflation algorithm
00002  * Copyright (C) 1995-2004 Jean-loup Gailly.
00003  * For conditions of distribution and use, see copyright notice in zlib.h
00004  */
00005 
00006 /*
00007  *  ALGORITHM
00008  *
00009  *      The "deflation" process depends on being able to identify portions
00010  *      of the input text which are identical to earlier input (within a
00011  *      sliding window trailing behind the input currently being processed).
00012  *
00013  *      The most straightforward technique turns out to be the fastest for
00014  *      most input files: try all possible matches and select the longest.
00015  *      The key feature of this algorithm is that insertions into the string
00016  *      dictionary are very simple and thus fast, and deletions are avoided
00017  *      completely. Insertions are performed at each input character, whereas
00018  *      string matches are performed only when the previous match ends. So it
00019  *      is preferable to spend more time in matches to allow very fast string
00020  *      insertions and avoid deletions. The matching algorithm for small
00021  *      strings is inspired from that of Rabin & Karp. A brute force approach
00022  *      is used to find longer strings when a small match has been found.
00023  *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
00024  *      (by Leonid Broukhis).
00025  *         A previous version of this file used a more sophisticated algorithm
00026  *      (by Fiala and Greene) which is guaranteed to run in linear amortized
00027  *      time, but has a larger average cost, uses more memory and is patented.
00028  *      However the F&G algorithm may be faster for some highly redundant
00029  *      files if the parameter max_chain_length (described below) is too large.
00030  *
00031  *  ACKNOWLEDGEMENTS
00032  *
00033  *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
00034  *      I found it in 'freeze' written by Leonid Broukhis.
00035  *      Thanks to many people for bug reports and testing.
00036  *
00037  *  REFERENCES
00038  *
00039  *      Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
00040  *      Available in http://www.ietf.org/rfc/rfc1951.txt
00041  *
00042  *      A description of the Rabin and Karp algorithm is given in the book
00043  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
00044  *
00045  *      Fiala,E.R., and Greene,D.H.
00046  *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
00047  *
00048  */
00049 
00050 /* @(#) $Id: deflate.cc,v 1.1 2005-05-12 21:04:53 duns Exp $ */
00051 
00052 #include "deflate.h"
00053 
00054 const char deflate_copyright[] =
00055    " deflate 1.2.2 Copyright 1995-2004 Jean-loup Gailly ";
00056 /*
00057   If you use the zlib library in a product, an acknowledgment is welcome
00058   in the documentation of your product. If for some reason you cannot
00059   include such an acknowledgment, I would appreciate that you keep this
00060   copyright string in the executable of your product.
00061  */
00062 
00063 /* ===========================================================================
00064  *  Function prototypes.
00065  */
00066 typedef enum {
00067     need_more,      /* block not completed, need more input or more output */
00068     block_done,     /* block flush performed */
00069     finish_started, /* finish started, need only more output at next deflate */
00070     finish_done     /* finish done, accept no more input or output */
00071 } block_state;
00072 
00073 typedef block_state (*compress_func) OF((deflate_state *s, int flush));
00074 /* Compression function. Returns the block state after the call. */
00075 
00076 local void fill_window    OF((deflate_state *s));
00077 local block_state deflate_stored OF((deflate_state *s, int flush));
00078 local block_state deflate_fast   OF((deflate_state *s, int flush));
00079 #ifndef FASTEST
00080 local block_state deflate_slow   OF((deflate_state *s, int flush));
00081 #endif
00082 local void lm_init        OF((deflate_state *s));
00083 local void putShortMSB    OF((deflate_state *s, uInt b));
00084 local void flush_pending  OF((z_streamp strm));
00085 local int read_buf        OF((z_streamp strm, Bytef *buf, unsigned size));
00086 #ifndef FASTEST
00087 #ifdef ASMV
00088       void match_init OF((void)); /* asm code initialization */
00089       uInt longest_match  OF((deflate_state *s, IPos cur_match));
00090 #else
00091 local uInt longest_match  OF((deflate_state *s, IPos cur_match));
00092 #endif
00093 #endif
00094 local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
00095 
00096 #ifdef DEBUG
00097 local  void check_match OF((deflate_state *s, IPos start, IPos match,
00098                             int length));
00099 #endif
00100 
00101 /* ===========================================================================
00102  * Local data
00103  */
00104 
00105 #define NIL 0
00106 /* Tail of hash chains */
00107 
00108 #ifndef TOO_FAR
00109 #  define TOO_FAR 4096
00110 #endif
00111 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
00112 
00113 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
00114 /* Minimum amount of lookahead, except at the end of the input file.
00115  * See deflate.c for comments about the MIN_MATCH+1.
00116  */
00117 
00118 /* Values for max_lazy_match, good_match and max_chain_length, depending on
00119  * the desired pack level (0..9). The values given below have been tuned to
00120  * exclude worst case performance for pathological files. Better values may be
00121  * found for specific files.
00122  */
00123 typedef struct config_s {
00124    ush good_length; /* reduce lazy search above this match length */
00125    ush max_lazy;    /* do not perform lazy search above this match length */
00126    ush nice_length; /* quit search above this match length */
00127    ush max_chain;
00128    compress_func func;
00129 } config;
00130 
00131 #ifdef FASTEST
00132 local const config configuration_table[2] = {
00133 /*      good lazy nice chain */
00134 /* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
00135 /* 1 */ {4,    4,  8,    4, deflate_fast}}; /* max speed, no lazy matches */
00136 #else
00137 local const config configuration_table[10] = {
00138 /*      good lazy nice chain */
00139 /* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
00140 /* 1 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */
00141 /* 2 */ {4,    5, 16,    8, deflate_fast},
00142 /* 3 */ {4,    6, 32,   32, deflate_fast},
00143 
00144 /* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
00145 /* 5 */ {8,   16, 32,   32, deflate_slow},
00146 /* 6 */ {8,   16, 128, 128, deflate_slow},
00147 /* 7 */ {8,   32, 128, 256, deflate_slow},
00148 /* 8 */ {32, 128, 258, 1024, deflate_slow},
00149 /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
00150 #endif
00151 
00152 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
00153  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
00154  * meaning.
00155  */
00156 
00157 #define EQUAL 0
00158 /* result of memcmp for equal strings */
00159 
00160 #ifndef NO_DUMMY_DECL
00161 struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
00162 #endif
00163 
00164 /* ===========================================================================
00165  * Update a hash value with the given input byte
00166  * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
00167  *    input characters, so that a running hash key can be computed from the
00168  *    previous key instead of complete recalculation each time.
00169  */
00170 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
00171 
00172 
00173 /* ===========================================================================
00174  * Insert string str in the dictionary and set match_head to the previous head
00175  * of the hash chain (the most recent string with same hash key). Return
00176  * the previous length of the hash chain.
00177  * If this file is compiled with -DFASTEST, the compression level is forced
00178  * to 1, and no hash chains are maintained.
00179  * IN  assertion: all calls to to INSERT_STRING are made with consecutive
00180  *    input characters and the first MIN_MATCH bytes of str are valid
00181  *    (except for the last MIN_MATCH-1 bytes of the input file).
00182  */
00183 #ifdef FASTEST
00184 #define INSERT_STRING(s, str, match_head) \
00185    (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
00186     match_head = s->head[s->ins_h], \
00187     s->head[s->ins_h] = (Pos)(str))
00188 #else
00189 #define INSERT_STRING(s, str, match_head) \
00190    (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
00191     match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
00192     s->head[s->ins_h] = (Pos)(str))
00193 #endif
00194 
00195 /* ===========================================================================
00196  * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
00197  * prev[] will be initialized on the fly.
00198  */
00199 #define CLEAR_HASH(s) \
00200     s->head[s->hash_size-1] = NIL; \
00201     zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
00202 
00203 /* ========================================================================= */
00204 int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
00205 {
00206     return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
00207                          Z_DEFAULT_STRATEGY, version, stream_size);
00208     /* To do: ignore strm->next_in if we use it as window */
00209 }
00210 
00211 /* ========================================================================= */
00212 int ZEXPORT deflateInit2_(z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy,
00213                   const char *version, int stream_size)
00214 {
00215     deflate_state *s;
00216     int wrap = 1;
00217     static const char my_version[] = ZLIB_VERSION;
00218 
00219     ushf *overlay;
00220     /* We overlay pending_buf and d_buf+l_buf. This works since the average
00221      * output size for (length,distance) codes is <= 24 bits.
00222      */
00223 
00224     if (version == Z_NULL || version[0] != my_version[0] ||
00225         stream_size != sizeof(z_stream)) {
00226         return Z_VERSION_ERROR;
00227     }
00228     if (strm == Z_NULL) return Z_STREAM_ERROR;
00229 
00230     strm->msg = Z_NULL;
00231     if (strm->zalloc == (alloc_func)0) {
00232         strm->zalloc = zcalloc;
00233         strm->opaque = (voidpf)0;
00234     }
00235     if (strm->zfree == (free_func)0) strm->zfree = zcfree;
00236 
00237 #ifdef FASTEST
00238     if (level != 0) level = 1;
00239 #else
00240     if (level == Z_DEFAULT_COMPRESSION) level = 6;
00241 #endif
00242 
00243     if (windowBits < 0) { /* suppress zlib wrapper */
00244         wrap = 0;
00245         windowBits = -windowBits;
00246     }
00247 #ifdef GZIP
00248     else if (windowBits > 15) {
00249         wrap = 2;       /* write gzip wrapper instead */
00250         windowBits -= 16;
00251     }
00252 #endif
00253     if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
00254         windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
00255         strategy < 0 || strategy > Z_RLE) {
00256         return Z_STREAM_ERROR;
00257     }
00258     if (windowBits == 8) windowBits = 9;  /* until 256-byte window bug fixed */
00259     s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
00260     if (s == Z_NULL) return Z_MEM_ERROR;
00261     strm->state = (struct internal_state FAR *)s;
00262     s->strm = strm;
00263 
00264     s->wrap = wrap;
00265     s->w_bits = windowBits;
00266     s->w_size = 1 << s->w_bits;
00267     s->w_mask = s->w_size - 1;
00268 
00269     s->hash_bits = memLevel + 7;
00270     s->hash_size = 1 << s->hash_bits;
00271     s->hash_mask = s->hash_size - 1;
00272     s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
00273 
00274     s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
00275     s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
00276     s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
00277 
00278     s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
00279 
00280     overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
00281     s->pending_buf = (uchf *) overlay;
00282     s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
00283 
00284     if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
00285         s->pending_buf == Z_NULL) {
00286         s->status = FINISH_STATE;
00287         strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
00288         deflateEnd (strm);
00289         return Z_MEM_ERROR;
00290     }
00291     s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
00292     s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
00293 
00294     s->level = level;
00295     s->strategy = strategy;
00296     s->method = (Byte)method;
00297 
00298     return deflateReset(strm);
00299 }
00300 
00301 /* ========================================================================= */
00302 int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
00303 {
00304     deflate_state *s;
00305     uInt length = dictLength;
00306     uInt n;
00307     IPos hash_head = 0;
00308 
00309     if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
00310         strm->state->wrap == 2 ||
00311         (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
00312         return Z_STREAM_ERROR;
00313 
00314     s = strm->state;
00315     if (s->wrap)
00316         strm->adler = adler32(strm->adler, dictionary, dictLength);
00317 
00318     if (length < MIN_MATCH) return Z_OK;
00319     if (length > MAX_DIST(s)) {
00320         length = MAX_DIST(s);
00321 #ifndef USE_DICT_HEAD
00322         dictionary += dictLength - length; /* use the tail of the dictionary */
00323 #endif
00324     }
00325     zmemcpy(s->window, dictionary, length);
00326     s->strstart = length;
00327     s->block_start = (long)length;
00328 
00329     /* Insert all strings in the hash table (except for the last two bytes).
00330      * s->lookahead stays null, so s->ins_h will be recomputed at the next
00331      * call of fill_window.
00332      */
00333     s->ins_h = s->window[0];
00334     UPDATE_HASH(s, s->ins_h, s->window[1]);
00335     for (n = 0; n <= length - MIN_MATCH; n++) {
00336         INSERT_STRING(s, n, hash_head);
00337     }
00338     if (hash_head) hash_head = 0;  /* to make compiler happy */
00339     return Z_OK;
00340 }
00341 
00342 /* ========================================================================= */
00343 int ZEXPORT deflateReset (z_streamp strm)
00344 {
00345     deflate_state *s;
00346 
00347     if (strm == Z_NULL || strm->state == Z_NULL ||
00348         strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
00349         return Z_STREAM_ERROR;
00350     }
00351 
00352     strm->total_in = strm->total_out = 0;
00353     strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
00354     strm->data_type = Z_UNKNOWN;
00355 
00356     s = (deflate_state *)strm->state;
00357     s->pending = 0;
00358     s->pending_out = s->pending_buf;
00359 
00360     if (s->wrap < 0) {
00361         s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
00362     }
00363     s->status = s->wrap ? INIT_STATE : BUSY_STATE;
00364     strm->adler =
00365 #ifdef GZIP
00366         s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
00367 #endif
00368         adler32(0L, Z_NULL, 0);
00369     s->last_flush = Z_NO_FLUSH;
00370 
00371     _tr_init(s);
00372     lm_init(s);
00373 
00374     return Z_OK;
00375 }
00376 
00377 /* ========================================================================= */
00378 int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
00379 {
00380     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
00381     strm->state->bi_valid = bits;
00382     strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
00383     return Z_OK;
00384 }
00385 
00386 /* ========================================================================= */
00387 int ZEXPORT deflateParams(z_streamp strm, int level, int strategy)
00388 {
00389     deflate_state *s;
00390     compress_func func;
00391     int err = Z_OK;
00392 
00393     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
00394     s = strm->state;
00395 
00396 #ifdef FASTEST
00397     if (level != 0) level = 1;
00398 #else
00399     if (level == Z_DEFAULT_COMPRESSION) level = 6;
00400 #endif
00401     if (level < 0 || level > 9 || strategy < 0 || strategy > Z_RLE) {
00402         return Z_STREAM_ERROR;
00403     }
00404     func = configuration_table[s->level].func;
00405 
00406     if (func != configuration_table[level].func && strm->total_in != 0) {
00407         /* Flush the last buffer: */
00408         err = deflate(strm, Z_PARTIAL_FLUSH);
00409     }
00410     if (s->level != level) {
00411         s->level = level;
00412         s->max_lazy_match   = configuration_table[level].max_lazy;
00413         s->good_match       = configuration_table[level].good_length;
00414         s->nice_match       = configuration_table[level].nice_length;
00415         s->max_chain_length = configuration_table[level].max_chain;
00416     }
00417     s->strategy = strategy;
00418     return err;
00419 }
00420 
00421 /* =========================================================================
00422  * For the default windowBits of 15 and memLevel of 8, this function returns
00423  * a close to exact, as well as small, upper bound on the compressed size.
00424  * They are coded as constants here for a reason--if the #define's are
00425  * changed, then this function needs to be changed as well.  The return
00426  * value for 15 and 8 only works for those exact settings.
00427  *
00428  * For any setting other than those defaults for windowBits and memLevel,
00429  * the value returned is a conservative worst case for the maximum expansion
00430  * resulting from using fixed blocks instead of stored blocks, which deflate
00431  * can emit on compressed data for some combinations of the parameters.
00432  *
00433  * This function could be more sophisticated to provide closer upper bounds
00434  * for every combination of windowBits and memLevel, as well as wrap.
00435  * But even the conservative upper bound of about 14% expansion does not
00436  * seem onerous for output buffer allocation.
00437  */
00438 uLong ZEXPORT deflateBound(z_streamp strm, uLong sourceLen)
00439 {
00440     deflate_state *s;
00441     uLong destLen;
00442 
00443     /* conservative upper bound */
00444     destLen = sourceLen +
00445               ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
00446 
00447     /* if can't get parameters, return conservative bound */
00448     if (strm == Z_NULL || strm->state == Z_NULL)
00449         return destLen;
00450 
00451     /* if not default parameters, return conservative bound */
00452     s = strm->state;
00453     if (s->w_bits != 15 || s->hash_bits != 8 + 7)
00454         return destLen;
00455 
00456     /* default settings: return tight bound for that case */
00457     return compressBound(sourceLen);
00458 }
00459 
00460 /* =========================================================================
00461  * Put a short in the pending buffer. The 16-bit value is put in MSB order.
00462  * IN assertion: the stream state is correct and there is enough room in
00463  * pending_buf.
00464  */
00465 local void putShortMSB (deflate_state *s, uInt b)
00466 {
00467     put_byte(s, (Byte)(b >> 8));
00468     put_byte(s, (Byte)(b & 0xff));
00469 }
00470 
00471 /* =========================================================================
00472  * Flush as much pending output as possible. All deflate() output goes
00473  * through this function so some applications may wish to modify it
00474  * to avoid allocating a large strm->next_out buffer and copying into it.
00475  * (See also read_buf()).
00476  */
00477 local void flush_pending(z_streamp strm)
00478 {
00479     unsigned len = strm->state->pending;
00480 
00481     if (len > strm->avail_out) len = strm->avail_out;
00482     if (len == 0) return;
00483 
00484     zmemcpy(strm->next_out, strm->state->pending_out, len);
00485     strm->next_out  += len;
00486     strm->state->pending_out  += len;
00487     strm->total_out += len;
00488     strm->avail_out  -= len;
00489     strm->state->pending -= len;
00490     if (strm->state->pending == 0) {
00491         strm->state->pending_out = strm->state->pending_buf;
00492     }
00493 }
00494 
00495 /* ========================================================================= */
00496 int ZEXPORT deflate (z_streamp strm, int flush)
00497 {
00498     int old_flush; /* value of flush param for previous deflate call */
00499     deflate_state *s;
00500 
00501     if (strm == Z_NULL || strm->state == Z_NULL ||
00502         flush > Z_FINISH || flush < 0) {
00503         return Z_STREAM_ERROR;
00504     }
00505     s = strm->state;
00506 
00507     if (strm->next_out == Z_NULL ||
00508         (strm->next_in == Z_NULL && strm->avail_in != 0) ||
00509         (s->status == FINISH_STATE && flush != Z_FINISH)) {
00510         ERR_RETURN(strm, Z_STREAM_ERROR);
00511     }
00512     if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
00513 
00514     s->strm = strm; /* just in case */
00515     old_flush = s->last_flush;
00516     s->last_flush = flush;
00517 
00518     /* Write the header */
00519     if (s->status == INIT_STATE) {
00520 #ifdef GZIP
00521         if (s->wrap == 2) {
00522             put_byte(s, 31);
00523             put_byte(s, 139);
00524             put_byte(s, 8);
00525             put_byte(s, 0);
00526             put_byte(s, 0);
00527             put_byte(s, 0);
00528             put_byte(s, 0);
00529             put_byte(s, 0);
00530             put_byte(s, s->level == 9 ? 2 :
00531                         (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
00532                          4 : 0));
00533             put_byte(s, 255);
00534             s->status = BUSY_STATE;
00535             strm->adler = crc32(0L, Z_NULL, 0);
00536         }
00537         else
00538 #endif
00539         {
00540             uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
00541             uInt level_flags;
00542 
00543             if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
00544                 level_flags = 0;
00545             else if (s->level < 6)
00546                 level_flags = 1;
00547             else if (s->level == 6)
00548                 level_flags = 2;
00549             else
00550                 level_flags = 3;
00551             header |= (level_flags << 6);
00552             if (s->strstart != 0) header |= PRESET_DICT;
00553             header += 31 - (header % 31);
00554 
00555             s->status = BUSY_STATE;
00556             putShortMSB(s, header);
00557 
00558             /* Save the adler32 of the preset dictionary: */
00559             if (s->strstart != 0) {
00560                 putShortMSB(s, (uInt)(strm->adler >> 16));
00561                 putShortMSB(s, (uInt)(strm->adler & 0xffff));
00562             }
00563             strm->adler = adler32(0L, Z_NULL, 0);
00564         }
00565     }
00566 
00567     /* Flush as much pending output as possible */
00568     if (s->pending != 0) {
00569         flush_pending(strm);
00570         if (strm->avail_out == 0) {
00571             /* Since avail_out is 0, deflate will be called again with
00572              * more output space, but possibly with both pending and
00573              * avail_in equal to zero. There won't be anything to do,
00574              * but this is not an error situation so make sure we
00575              * return OK instead of BUF_ERROR at next call of deflate:
00576              */
00577             s->last_flush = -1;
00578             return Z_OK;
00579         }
00580 
00581     /* Make sure there is something to do and avoid duplicate consecutive
00582      * flushes. For repeated and useless calls with Z_FINISH, we keep
00583      * returning Z_STREAM_END instead of Z_BUF_ERROR.
00584      */
00585     } else if (strm->avail_in == 0 && flush <= old_flush &&
00586                flush != Z_FINISH) {
00587         ERR_RETURN(strm, Z_BUF_ERROR);
00588     }
00589 
00590     /* User must not provide more input after the first FINISH: */
00591     if (s->status == FINISH_STATE && strm->avail_in != 0) {
00592         ERR_RETURN(strm, Z_BUF_ERROR);
00593     }
00594 
00595     /* Start a new block or continue the current one.
00596      */
00597     if (strm->avail_in != 0 || s->lookahead != 0 ||
00598         (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
00599         block_state bstate;
00600 
00601         bstate = (*(configuration_table[s->level].func))(s, flush);
00602 
00603         if (bstate == finish_started || bstate == finish_done) {
00604             s->status = FINISH_STATE;
00605         }
00606         if (bstate == need_more || bstate == finish_started) {
00607             if (strm->avail_out == 0) {
00608                 s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
00609             }
00610             return Z_OK;
00611             /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
00612              * of deflate should use the same flush parameter to make sure
00613              * that the flush is complete. So we don't have to output an
00614              * empty block here, this will be done at next call. This also
00615              * ensures that for a very small output buffer, we emit at most
00616              * one empty block.
00617              */
00618         }
00619         if (bstate == block_done) {
00620             if (flush == Z_PARTIAL_FLUSH) {
00621                 _tr_align(s);
00622             } else { /* FULL_FLUSH or SYNC_FLUSH */
00623                 _tr_stored_block(s, (char*)0, 0L, 0);
00624                 /* For a full flush, this empty block will be recognized
00625                  * as a special marker by inflate_sync().
00626                  */
00627                 if (flush == Z_FULL_FLUSH) {
00628                     CLEAR_HASH(s);             /* forget history */
00629                 }
00630             }
00631             flush_pending(strm);
00632             if (strm->avail_out == 0) {
00633               s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
00634               return Z_OK;
00635             }
00636         }
00637     }
00638     Assert(strm->avail_out > 0, (char*)"bug2");
00639 
00640     if (flush != Z_FINISH) return Z_OK;
00641     if (s->wrap <= 0) return Z_STREAM_END;
00642 
00643     /* Write the trailer */
00644 #ifdef GZIP
00645     if (s->wrap == 2) {
00646         put_byte(s, (Byte)(strm->adler & 0xff));
00647         put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
00648         put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
00649         put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
00650         put_byte(s, (Byte)(strm->total_in & 0xff));
00651         put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
00652         put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
00653         put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
00654     }
00655     else
00656 #endif
00657     {
00658         putShortMSB(s, (uInt)(strm->adler >> 16));
00659         putShortMSB(s, (uInt)(strm->adler & 0xffff));
00660     }
00661     flush_pending(strm);
00662     /* If avail_out is zero, the application will call deflate again
00663      * to flush the rest.
00664      */
00665     if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
00666     return s->pending != 0 ? Z_OK : Z_STREAM_END;
00667 }
00668 
00669 /* ========================================================================= */
00670 int ZEXPORT deflateEnd (z_streamp strm)
00671 {
00672     int status;
00673 
00674     if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
00675 
00676     status = strm->state->status;
00677     if (status != INIT_STATE && status != BUSY_STATE &&
00678         status != FINISH_STATE) {
00679       return Z_STREAM_ERROR;
00680     }
00681 
00682     /* Deallocate in reverse order of allocations: */
00683     TRY_FREE(strm, strm->state->pending_buf);
00684     TRY_FREE(strm, strm->state->head);
00685     TRY_FREE(strm, strm->state->prev);
00686     TRY_FREE(strm, strm->state->window);
00687 
00688     ZFREE(strm, strm->state);
00689     strm->state = Z_NULL;
00690 
00691     return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
00692 }
00693 
00694 /* =========================================================================
00695  * Copy the source state to the destination state.
00696  * To simplify the source, this is not supported for 16-bit MSDOS (which
00697  * doesn't have enough memory anyway to duplicate compression states).
00698  */
00699 int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
00700 {
00701 #ifdef MAXSEG_64K
00702     return Z_STREAM_ERROR;
00703 #else
00704     deflate_state *ds;
00705     deflate_state *ss;
00706     ushf *overlay;
00707 
00708 
00709     if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
00710         return Z_STREAM_ERROR;
00711     }
00712 
00713     ss = source->state;
00714 
00715     *dest = *source;
00716 
00717     ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
00718     if (ds == Z_NULL) return Z_MEM_ERROR;
00719     dest->state = (struct internal_state FAR *) ds;
00720     *ds = *ss;
00721     ds->strm = dest;
00722 
00723     ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
00724     ds->prev   = (Posf *)  ZALLOC(dest, ds->w_size, sizeof(Pos));
00725     ds->head   = (Posf *)  ZALLOC(dest, ds->hash_size, sizeof(Pos));
00726     overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
00727     ds->pending_buf = (uchf *) overlay;
00728 
00729     if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
00730         ds->pending_buf == Z_NULL) {
00731         deflateEnd (dest);
00732         return Z_MEM_ERROR;
00733     }
00734     /* following zmemcpy do not work for 16-bit MSDOS */
00735     zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
00736     zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
00737     zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
00738     zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
00739 
00740     ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
00741     ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
00742     ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
00743 
00744     ds->l_desc.dyn_tree = ds->dyn_ltree;
00745     ds->d_desc.dyn_tree = ds->dyn_dtree;
00746     ds->bl_desc.dyn_tree = ds->bl_tree;
00747 
00748     return Z_OK;
00749 #endif /* MAXSEG_64K */
00750 }
00751 
00752 /* ===========================================================================
00753  * Read a new buffer from the current input stream, update the adler32
00754  * and total number of bytes read.  All deflate() input goes through
00755  * this function so some applications may wish to modify it to avoid
00756  * allocating a large strm->next_in buffer and copying from it.
00757  * (See also flush_pending()).
00758  */
00759 local int read_buf(z_streamp strm, Bytef *buf, unsigned size)
00760 {
00761     unsigned len = strm->avail_in;
00762 
00763     if (len > size) len = size;
00764     if (len == 0) return 0;
00765 
00766     strm->avail_in  -= len;
00767 
00768     if (strm->state->wrap == 1) {
00769         strm->adler = adler32(strm->adler, strm->next_in, len);
00770     }
00771 #ifdef GZIP
00772     else if (strm->state->wrap == 2) {
00773         strm->adler = crc32(strm->adler, strm->next_in, len);
00774     }
00775 #endif
00776     zmemcpy(buf, strm->next_in, len);
00777     strm->next_in  += len;
00778     strm->total_in += len;
00779 
00780     return (int)len;
00781 }
00782 
00783 /* ===========================================================================
00784  * Initialize the "longest match" routines for a new zlib stream
00785  */
00786 local void lm_init (deflate_state *s)
00787 {
00788     s->window_size = (ulg)2L*s->w_size;
00789 
00790     CLEAR_HASH(s);
00791 
00792     /* Set the default configuration parameters:
00793      */
00794     s->max_lazy_match   = configuration_table[s->level].max_lazy;
00795     s->good_match       = configuration_table[s->level].good_length;
00796     s->nice_match       = configuration_table[s->level].nice_length;
00797     s->max_chain_length = configuration_table[s->level].max_chain;
00798 
00799     s->strstart = 0;
00800     s->block_start = 0L;
00801     s->lookahead = 0;
00802     s->match_length = s->prev_length = MIN_MATCH-1;
00803     s->match_available = 0;
00804     s->ins_h = 0;
00805 #ifdef ASMV
00806     match_init(); /* initialize the asm code */
00807 #endif
00808 }
00809 
00810 #ifndef FASTEST
00811 /* ===========================================================================
00812  * Set match_start to the longest match starting at the given string and
00813  * return its length. Matches shorter or equal to prev_length are discarded,
00814  * in which case the result is equal to prev_length and match_start is
00815  * garbage.
00816  * IN assertions: cur_match is the head of the hash chain for the current
00817  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
00818  * OUT assertion: the match length is not greater than s->lookahead.
00819  */
00820 #ifndef ASMV
00821 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
00822  * match.S. The code will be functionally equivalent.
00823  */
00824 local uInt longest_match(deflate_state *s, IPos cur_match)
00825 {
00826     unsigned chain_length = s->max_chain_length;/* max hash chain length */
00827     register Bytef *scan = s->window + s->strstart; /* current string */
00828     register Bytef *match;                       /* matched string */
00829     register int len;                           /* length of current match */
00830     int best_len = s->prev_length;              /* best match length so far */
00831     int nice_match = s->nice_match;             /* stop if match long enough */
00832     IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
00833         s->strstart - (IPos)MAX_DIST(s) : NIL;
00834     /* Stop when cur_match becomes <= limit. To simplify the code,
00835      * we prevent matches with the string of window index 0.
00836      */
00837     Posf *prev = s->prev;
00838     uInt wmask = s->w_mask;
00839 
00840 #ifdef UNALIGNED_OK
00841     /* Compare two bytes at a time. Note: this is not always beneficial.
00842      * Try with and without -DUNALIGNED_OK to check.
00843      */
00844     register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
00845     register ush scan_start = *(ushf*)scan;
00846     register ush scan_end   = *(ushf*)(scan+best_len-1);
00847 #else
00848     register Bytef *strend = s->window + s->strstart + MAX_MATCH;
00849     register Byte scan_end1  = scan[best_len-1];
00850     register Byte scan_end   = scan[best_len];
00851 #endif
00852 
00853     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
00854      * It is easy to get rid of this optimization if necessary.
00855      */
00856     Assert(s->hash_bits >= 8 && MAX_MATCH == 258, (char*)"Code too clever");
00857 
00858     /* Do not waste too much time if we already have a good match: */
00859     if (s->prev_length >= s->good_match) {
00860         chain_length >>= 2;
00861     }
00862     /* Do not look for matches beyond the end of the input. This is necessary
00863      * to make deflate deterministic.
00864      */
00865     if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
00866 
00867     Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, (char*)"need lookahead");
00868 
00869     do {
00870         Assert(cur_match < s->strstart, (char*)"no future");
00871         match = s->window + cur_match;
00872 
00873         /* Skip to next match if the match length cannot increase
00874          * or if the match length is less than 2:
00875          */
00876 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
00877         /* This code assumes sizeof(unsigned short) == 2. Do not use
00878          * UNALIGNED_OK if your compiler uses a different size.
00879          */
00880         if (*(ushf*)(match+best_len-1) != scan_end ||
00881             *(ushf*)match != scan_start) continue;
00882 
00883         /* It is not necessary to compare scan[2] and match[2] since they are
00884          * always equal when the other bytes match, given that the hash keys
00885          * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
00886          * strstart+3, +5, ... up to strstart+257. We check for insufficient
00887          * lookahead only every 4th comparison; the 128th check will be made
00888          * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
00889          * necessary to put more guard bytes at the end of the window, or
00890          * to check more often for insufficient lookahead.
00891          */
00892         Assert(scan[2] == match[2], (char*)"scan[2]?");
00893         scan++, match++;
00894         do {
00895         } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
00896                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
00897                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
00898                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
00899                  scan < strend);
00900         /* The funny "do {}" generates better code on most compilers */
00901 
00902         /* Here, scan <= window+strstart+257 */
00903         Assert(scan <= s->window+(unsigned)(s->window_size-1), (char*)"wild scan");
00904         if (*scan == *match) scan++;
00905 
00906         len = (MAX_MATCH - 1) - (int)(strend-scan);
00907         scan = strend - (MAX_MATCH-1);
00908 
00909 #else /* UNALIGNED_OK */
00910 
00911         if (match[best_len]   != scan_end  ||
00912             match[best_len-1] != scan_end1 ||
00913             *match            != *scan     ||
00914             *++match          != scan[1])      continue;
00915 
00916         /* The check at best_len-1 can be removed because it will be made
00917          * again later. (This heuristic is not always a win.)
00918          * It is not necessary to compare scan[2] and match[2] since they
00919          * are always equal when the other bytes match, given that
00920          * the hash keys are equal and that HASH_BITS >= 8.
00921          */
00922         scan += 2, match++;
00923         Assert(*scan == *match, (char*)"match[2]?");
00924 
00925         /* We check for insufficient lookahead only every 8th comparison;
00926          * the 256th check will be made at strstart+258.
00927          */
00928         do {
00929         } while (*++scan == *++match && *++scan == *++match &&
00930                  *++scan == *++match && *++scan == *++match &&
00931                  *++scan == *++match && *++scan == *++match &&
00932                  *++scan == *++match && *++scan == *++match &&
00933                  scan < strend);
00934 
00935         Assert(scan <= s->window+(unsigned)(s->window_size-1), (char*)"wild scan");
00936 
00937         len = MAX_MATCH - (int)(strend - scan);
00938         scan = strend - MAX_MATCH;
00939 
00940 #endif /* UNALIGNED_OK */
00941 
00942         if (len > best_len) {
00943             s->match_start = cur_match;
00944             best_len = len;
00945             if (len >= nice_match) break;
00946 #ifdef UNALIGNED_OK
00947             scan_end = *(ushf*)(scan+best_len-1);
00948 #else
00949             scan_end1  = scan[best_len-1];
00950             scan_end   = scan[best_len];
00951 #endif
00952         }
00953     } while ((cur_match = prev[cur_match & wmask]) > limit
00954              && --chain_length != 0);
00955 
00956     if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
00957     return s->lookahead;
00958 }
00959 #endif /* ASMV */
00960 #endif /* FASTEST */
00961 
00962 /* ---------------------------------------------------------------------------
00963  * Optimized version for level == 1 or strategy == Z_RLE only
00964  */
00965 local uInt longest_match_fast(deflate_state *s, IPos cur_match)
00966 {
00967     register Bytef *scan = s->window + s->strstart; /* current string */
00968     register Bytef *match;                       /* matched string */
00969     register int len;                           /* length of current match */
00970     register Bytef *strend = s->window + s->strstart + MAX_MATCH;
00971 
00972     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
00973      * It is easy to get rid of this optimization if necessary.
00974      */
00975     Assert(s->hash_bits >= 8 && MAX_MATCH == 258, (char*)"Code too clever");
00976 
00977     Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, (char*)"need lookahead");
00978 
00979     Assert(cur_match < s->strstart, (char*)"no future");
00980 
00981     match = s->window + cur_match;
00982 
00983     /* Return failure if the match length is less than 2:
00984      */
00985     if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
00986 
00987     /* The check at best_len-1 can be removed because it will be made
00988      * again later. (This heuristic is not always a win.)
00989      * It is not necessary to compare scan[2] and match[2] since they
00990      * are always equal when the other bytes match, given that
00991      * the hash keys are equal and that HASH_BITS >= 8.
00992      */
00993     scan += 2, match += 2;
00994     Assert(*scan == *match, (char*)"match[2]?");
00995 
00996     /* We check for insufficient lookahead only every 8th comparison;
00997      * the 256th check will be made at strstart+258.
00998      */
00999     do {
01000     } while (*++scan == *++match && *++scan == *++match &&
01001              *++scan == *++match && *++scan == *++match &&
01002              *++scan == *++match && *++scan == *++match &&
01003              *++scan == *++match && *++scan == *++match &&
01004              scan < strend);
01005 
01006     Assert(scan <= s->window+(unsigned)(s->window_size-1), (char*)"wild scan");
01007 
01008     len = MAX_MATCH - (int)(strend - scan);
01009 
01010     if (len < MIN_MATCH) return MIN_MATCH - 1;
01011 
01012     s->match_start = cur_match;
01013     return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
01014 }
01015 
01016 #ifdef DEBUG
01017 /* ===========================================================================
01018  * Check that the match at match_start is indeed a match.
01019  */
01020 local void check_match(deflate_state *s, IPos start, IPos match, int length)
01021 {
01022     /* check that the match is indeed a match */
01023     if (zmemcmp(s->window + match,
01024                 s->window + start, length) != EQUAL) {
01025         fprintf(stderr, (char*)" start %u, match %u, length %d\n",
01026                 start, match, length);
01027         do {
01028             fprintf(stderr, (char*)"%c%c", s->window[match++], s->window[start++]);
01029         } while (--length != 0);
01030         z_error((char*)"invalid match");
01031     }
01032     if (z_verbose > 1) {
01033         fprintf(stderr,(char*)"\\[%d,%d]", start-match, length);
01034         do { putc(s->window[start++], stderr); } while (--length != 0);
01035     }
01036 }
01037 #else
01038 #  define check_match(s, start, match, length)
01039 #endif /* DEBUG */
01040 
01041 /* ===========================================================================
01042  * Fill the window when the lookahead becomes insufficient.
01043  * Updates strstart and lookahead.
01044  *
01045  * IN assertion: lookahead < MIN_LOOKAHEAD
01046  * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
01047  *    At least one byte has been read, or avail_in == 0; reads are
01048  *    performed for at least two bytes (required for the zip translate_eol
01049  *    option -- not supported here).
01050  */
01051 local void fill_window(deflate_state *s)
01052 {
01053     register unsigned n, m;
01054     register Posf *p;
01055     unsigned more;    /* Amount of free space at the end of the window. */
01056     uInt wsize = s->w_size;
01057 
01058     do {
01059         more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
01060 
01061         /* Deal with !@#$% 64K limit: */
01062         if (sizeof(int) <= 2) {
01063             if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
01064                 more = wsize;
01065 
01066             } else if (more == (unsigned)(-1)) {
01067                 /* Very unlikely, but possible on 16 bit machine if
01068                  * strstart == 0 && lookahead == 1 (input done a byte at time)
01069                  */
01070                 more--;
01071             }
01072         }
01073 
01074         /* If the window is almost full and there is insufficient lookahead,
01075          * move the upper half to the lower one to make room in the upper half.
01076          */
01077         if (s->strstart >= wsize+MAX_DIST(s)) {
01078 
01079             zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
01080             s->match_start -= wsize;
01081             s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
01082             s->block_start -= (long) wsize;
01083 
01084             /* Slide the hash table (could be avoided with 32 bit values
01085                at the expense of memory usage). We slide even when level == 0
01086                to keep the hash table consistent if we switch back to level > 0
01087                later. (Using level 0 permanently is not an optimal usage of
01088                zlib, so we don't care about this pathological case.)
01089              */
01090             n = s->hash_size;
01091             p = &s->head[n];
01092             do {
01093                 m = *--p;
01094                 *p = (Pos)(m >= wsize ? m-wsize : NIL);
01095             } while (--n);
01096 
01097             n = wsize;
01098 #ifndef FASTEST
01099             p = &s->prev[n];
01100             do {
01101                 m = *--p;
01102                 *p = (Pos)(m >= wsize ? m-wsize : NIL);
01103                 /* If n is not on any hash chain, prev[n] is garbage but
01104                  * its value will never be used.
01105                  */
01106             } while (--n);
01107 #endif
01108             more += wsize;
01109         }
01110         if (s->strm->avail_in == 0) return;
01111 
01112         /* If there was no sliding:
01113          *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
01114          *    more == window_size - lookahead - strstart
01115          * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
01116          * => more >= window_size - 2*WSIZE + 2
01117          * In the BIG_MEM or MMAP case (not yet supported),
01118          *   window_size == input_size + MIN_LOOKAHEAD  &&
01119          *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
01120          * Otherwise, window_size == 2*WSIZE so more >= 2.
01121          * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
01122          */
01123         Assert(more >= 2, (char*)"more < 2");
01124 
01125         n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
01126         s->lookahead += n;
01127 
01128         /* Initialize the hash value now that we have some input: */
01129         if (s->lookahead >= MIN_MATCH) {
01130             s->ins_h = s->window[s->strstart];
01131             UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
01132 #if MIN_MATCH != 3
01133             Call UPDATE_HASH() MIN_MATCH-3 more times
01134 #endif
01135         }
01136         /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
01137          * but this is not important since only literal bytes will be emitted.
01138          */
01139 
01140     } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
01141 }
01142 
01143 /* ===========================================================================
01144  * Flush the current block, with given end-of-file flag.
01145  * IN assertion: strstart is set to the end of the current match.
01146  */
01147 #define FLUSH_BLOCK_ONLY(s, eof) { \
01148    _tr_flush_block(s, (s->block_start >= 0L ? \
01149                    (charf *)&s->window[(unsigned)s->block_start] : \
01150                    (charf *)Z_NULL), \
01151                 (ulg)((long)s->strstart - s->block_start), \
01152                 (eof)); \
01153    s->block_start = s->strstart; \
01154    flush_pending(s->strm); \
01155    Tracev((stderr,(char*)"[FLUSH]")); \
01156 }
01157 
01158 /* Same but force premature exit if necessary. */
01159 #define FLUSH_BLOCK(s, eof) { \
01160    FLUSH_BLOCK_ONLY(s, eof); \
01161    if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
01162 }
01163 
01164 /* ===========================================================================
01165  * Copy without compression as much as possible from the input stream, return
01166  * the current block state.
01167  * This function does not insert new strings in the dictionary since
01168  * uncompressible data is probably not useful. This function is used
01169  * only for the level=0 compression option.
01170  * NOTE: this function should be optimized to avoid extra copying from
01171  * window to pending_buf.
01172  */
01173 local block_state deflate_stored(deflate_state *s, int flush)
01174 {
01175     /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
01176      * to pending_buf_size, and each stored block has a 5 byte header:
01177      */
01178     ulg max_block_size = 0xffff;
01179     ulg max_start;
01180 
01181     if (max_block_size > s->pending_buf_size - 5) {
01182         max_block_size = s->pending_buf_size - 5;
01183     }
01184 
01185     /* Copy as much as possible from input to output: */
01186     for (;;) {
01187         /* Fill the window as much as possible: */
01188         if (s->lookahead <= 1) {
01189 
01190             Assert(s->strstart < s->w_size+MAX_DIST(s) ||
01191                    s->block_start >= (long)s->w_size, (char*)"slide too late");
01192 
01193             fill_window(s);
01194             if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
01195 
01196             if (s->lookahead == 0) break; /* flush the current block */
01197         }
01198         Assert(s->block_start >= 0L, (char*)"block gone");
01199 
01200         s->strstart += s->lookahead;
01201         s->lookahead = 0;
01202 
01203         /* Emit a stored block if pending_buf will be full: */
01204         max_start = s->block_start + max_block_size;
01205         if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
01206             /* strstart == 0 is possible when wraparound on 16-bit machine */
01207             s->lookahead = (uInt)(s->strstart - max_start);
01208             s->strstart = (uInt)max_start;
01209             FLUSH_BLOCK(s, 0);
01210         }
01211         /* Flush if we may have to slide, otherwise block_start may become
01212          * negative and the data will be gone:
01213          */
01214         if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
01215             FLUSH_BLOCK(s, 0);
01216         }
01217     }
01218     FLUSH_BLOCK(s, flush == Z_FINISH);
01219     return flush == Z_FINISH ? finish_done : block_done;
01220 }
01221 
01222 /* ===========================================================================
01223  * Compress as much as possible from the input stream, return the current
01224  * block state.
01225  * This function does not perform lazy evaluation of matches and inserts
01226  * new strings in the dictionary only for unmatched strings or for short
01227  * matches. It is used only for the fast compression options.
01228  */
01229 local block_state deflate_fast(deflate_state *s, int flush)
01230 {
01231     IPos hash_head = NIL; /* head of the hash chain */
01232     int bflush;           /* set if current block must be flushed */
01233 
01234     for (;;) {
01235         /* Make sure that we always have enough lookahead, except
01236          * at the end of the input file. We need MAX_MATCH bytes
01237          * for the next match, plus MIN_MATCH bytes to insert the
01238          * string following the next match.
01239          */
01240         if (s->lookahead < MIN_LOOKAHEAD) {
01241             fill_window(s);
01242             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
01243                 return need_more;
01244             }
01245             if (s->lookahead == 0) break; /* flush the current block */
01246         }
01247 
01248         /* Insert the string window[strstart .. strstart+2] in the
01249          * dictionary, and set hash_head to the head of the hash chain:
01250          */
01251         if (s->lookahead >= MIN_MATCH) {
01252             INSERT_STRING(s, s->strstart, hash_head);
01253         }
01254 
01255         /* Find the longest match, discarding those <= prev_length.
01256          * At this point we have always match_length < MIN_MATCH
01257          */
01258         if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
01259             /* To simplify the code, we prevent matches with the string
01260              * of window index 0 (in particular we have to avoid a match
01261              * of the string with itself at the start of the input file).
01262              */
01263 #ifdef FASTEST
01264             if ((s->strategy < Z_HUFFMAN_ONLY) ||
01265                 (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
01266                 s->match_length = longest_match_fast (s, hash_head);
01267             }
01268 #else
01269             if (s->strategy < Z_HUFFMAN_ONLY) {
01270                 s->match_length = longest_match (s, hash_head);
01271             } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
01272                 s->match_length = longest_match_fast (s, hash_head);
01273             }
01274 #endif
01275             /* longest_match() or longest_match_fast() sets match_start */
01276         }
01277         if (s->match_length >= MIN_MATCH) {
01278             check_match(s, s->strstart, s->match_start, s->match_length);
01279 
01280             _tr_tally_dist(s, s->strstart - s->match_start,
01281                            s->match_length - MIN_MATCH, bflush);
01282 
01283             s->lookahead -= s->match_length;
01284 
01285             /* Insert new strings in the hash table only if the match length
01286              * is not too large. This saves time but degrades compression.
01287              */
01288 #ifndef FASTEST
01289             if (s->match_length <= s->max_insert_length &&
01290                 s->lookahead >= MIN_MATCH) {
01291                 s->match_length--; /* string at strstart already in table */
01292                 do {
01293                     s->strstart++;
01294                     INSERT_STRING(s, s->strstart, hash_head);
01295                     /* strstart never exceeds WSIZE-MAX_MATCH, so there are
01296                      * always MIN_MATCH bytes ahead.
01297                      */
01298                 } while (--s->match_length != 0);
01299                 s->strstart++;
01300             } else
01301 #endif
01302             {
01303                 s->strstart += s->match_length;
01304                 s->match_length = 0;
01305                 s->ins_h = s->window[s->strstart];
01306                 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
01307 #if MIN_MATCH != 3
01308                 Call UPDATE_HASH() MIN_MATCH-3 more times
01309 #endif
01310                 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
01311                  * matter since it will be recomputed at next deflate call.
01312                  */
01313             }
01314         } else {
01315             /* No match, output a literal byte */
01316             Tracevv((stderr,"%c", s->window[s->strstart]));
01317             _tr_tally_lit (s, s->window[s->strstart], bflush);
01318             s->lookahead--;
01319             s->strstart++;
01320         }
01321         if (bflush) FLUSH_BLOCK(s, 0);
01322     }
01323     FLUSH_BLOCK(s, flush == Z_FINISH);
01324     return flush == Z_FINISH ? finish_done : block_done;
01325 }
01326 
01327 #ifndef FASTEST
01328 /* ===========================================================================
01329  * Same as above, but achieves better compression. We use a lazy
01330  * evaluation for matches: a match is finally adopted only if there is
01331  * no better match at the next window position.
01332  */
01333 local block_state deflate_slow(deflate_state *s, int flush)
01334 {
01335     IPos hash_head = NIL;    /* head of hash chain */
01336     int bflush;              /* set if current block must be flushed */
01337 
01338     /* Process the input block. */
01339     for (;;) {
01340         /* Make sure that we always have enough lookahead, except
01341          * at the end of the input file. We need MAX_MATCH bytes
01342          * for the next match, plus MIN_MATCH bytes to insert the
01343          * string following the next match.
01344          */
01345         if (s->lookahead < MIN_LOOKAHEAD) {
01346             fill_window(s);
01347             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
01348                 return need_more;
01349             }
01350             if (s->lookahead == 0) break; /* flush the current block */
01351         }
01352 
01353         /* Insert the string window[strstart .. strstart+2] in the
01354          * dictionary, and set hash_head to the head of the hash chain:
01355          */
01356         if (s->lookahead >= MIN_MATCH) {
01357             INSERT_STRING(s, s->strstart, hash_head);
01358         }
01359 
01360         /* Find the longest match, discarding those <= prev_length.
01361          */
01362         s->prev_length = s->match_length, s->prev_match = s->match_start;
01363         s->match_length = MIN_MATCH-1;
01364 
01365         if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
01366             s->strstart - hash_head <= MAX_DIST(s)) {
01367             /* To simplify the code, we prevent matches with the string
01368              * of window index 0 (in particular we have to avoid a match
01369              * of the string with itself at the start of the input file).
01370              */
01371             if (s->strategy < Z_HUFFMAN_ONLY) {
01372                 s->match_length = longest_match (s, hash_head);
01373             } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
01374                 s->match_length = longest_match_fast (s, hash_head);
01375             }
01376             /* longest_match() or longest_match_fast() sets match_start */
01377 
01378             if (s->match_length <= 5 && (s->strategy == Z_FILTERED
01379 #if TOO_FAR <= 32767
01380                 || (s->match_length == MIN_MATCH &&
01381                     s->strstart - s->match_start > TOO_FAR)
01382 #endif
01383                 )) {
01384 
01385                 /* If prev_match is also MIN_MATCH, match_start is garbage
01386                  * but we will ignore the current match anyway.
01387                  */
01388                 s->match_length = MIN_MATCH-1;
01389             }
01390         }
01391         /* If there was a match at the previous step and the current
01392          * match is not better, output the previous match:
01393          */
01394         if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
01395             uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
01396             /* Do not insert strings in hash table beyond this. */
01397 
01398             check_match(s, s->strstart-1, s->prev_match, s->prev_length);
01399 
01400             _tr_tally_dist(s, s->strstart -1 - s->prev_match,
01401                            s->prev_length - MIN_MATCH, bflush);
01402 
01403             /* Insert in hash table all strings up to the end of the match.
01404              * strstart-1 and strstart are already inserted. If there is not
01405              * enough lookahead, the last two strings are not inserted in
01406              * the hash table.
01407              */
01408             s->lookahead -= s->prev_length-1;
01409             s->prev_length -= 2;
01410             do {
01411                 if (++s->strstart <= max_insert) {
01412                     INSERT_STRING(s, s->strstart, hash_head);
01413                 }
01414             } while (--s->prev_length != 0);
01415             s->match_available = 0;
01416             s->match_length = MIN_MATCH-1;
01417             s->strstart++;
01418 
01419             if (bflush) FLUSH_BLOCK(s, 0);
01420 
01421         } else if (s->match_available) {
01422             /* If there was no match at the previous position, output a
01423              * single literal. If there was a match but the current match
01424              * is longer, truncate the previous match to a single literal.
01425              */
01426             Tracevv((stderr,(char*)"%c", s->window[s->strstart-1]));
01427             _tr_tally_lit(s, s->window[s->strstart-1], bflush);
01428             if (bflush) {
01429                 FLUSH_BLOCK_ONLY(s, 0);
01430             }
01431             s->strstart++;
01432             s->lookahead--;
01433             if (s->strm->avail_out == 0) return need_more;
01434         } else {
01435             /* There is no previous match to compare with, wait for
01436              * the next step to decide.
01437              */
01438             s->match_available = 1;
01439             s->strstart++;
01440             s->lookahead--;
01441         }
01442     }
01443     Assert (flush != Z_NO_FLUSH, (char*)"no flush?");
01444     if (s->match_available) {
01445         Tracevv((stderr,(char*)"%c", s->window[s->strstart-1]));
01446         _tr_tally_lit(s, s->window[s->strstart-1], bflush);
01447         s->match_available = 0;
01448     }
01449     FLUSH_BLOCK(s, flush == Z_FINISH);
01450     return flush == Z_FINISH ? finish_done : block_done;
01451 }
01452 #endif /* FASTEST */

Generated on Mon May 27 17:47:34 2013 for Geant4 by  doxygen 1.4.7