/* deflate.c -- compress data using the deflation algorithm1* Copyright (C) 1995-2024 Jean-loup Gailly and Mark Adler2* For conditions of distribution and use, see copyright notice in zlib.h3*/45/*6* ALGORITHM7*8* The "deflation" process depends on being able to identify portions9* of the input text which are identical to earlier input (within a10* sliding window trailing behind the input currently being processed).11*12* The most straightforward technique turns out to be the fastest for13* most input files: try all possible matches and select the longest.14* The key feature of this algorithm is that insertions into the string15* dictionary are very simple and thus fast, and deletions are avoided16* completely. Insertions are performed at each input character, whereas17* string matches are performed only when the previous match ends. So it18* is preferable to spend more time in matches to allow very fast string19* insertions and avoid deletions. The matching algorithm for small20* strings is inspired from that of Rabin & Karp. A brute force approach21* 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 freeze23* (by Leonid Broukhis).24* A previous version of this file used a more sophisticated algorithm25* (by Fiala and Greene) which is guaranteed to run in linear amortized26* 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 redundant28* files if the parameter max_chain_length (described below) is too large.29*30* ACKNOWLEDGEMENTS31*32* The idea of lazy evaluation of matches is due to Jan-Mark Wams, and33* I found it in 'freeze' written by Leonid Broukhis.34* Thanks to many people for bug reports and testing.35*36* REFERENCES37*38* Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".39* Available in http://tools.ietf.org/html/rfc195140*41* A description of the Rabin and Karp algorithm is given in the book42* "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-59546*47*/4849/* @(#) $Id$ */5051#include "deflate.h"5253const char deflate_copyright[] =54" deflate 1.3.1 Copyright 1995-2024 Jean-loup Gailly and Mark Adler ";55/*56If you use the zlib library in a product, an acknowledgment is welcome57in the documentation of your product. If for some reason you cannot58include such an acknowledgment, I would appreciate that you keep this59copyright string in the executable of your product.60*/6162typedef enum {63need_more, /* block not completed, need more input or more output */64block_done, /* block flush performed */65finish_started, /* finish started, need only more output at next deflate */66finish_done /* finish done, accept no more input or output */67} block_state;6869typedef block_state (*compress_func)(deflate_state *s, int flush);70/* Compression function. Returns the block state after the call. */7172local block_state deflate_stored(deflate_state *s, int flush);73local block_state deflate_fast(deflate_state *s, int flush);74#ifndef FASTEST75local block_state deflate_slow(deflate_state *s, int flush);76#endif77local block_state deflate_rle(deflate_state *s, int flush);78local block_state deflate_huff(deflate_state *s, int flush);7980/* ===========================================================================81* Local data82*/8384#define NIL 085/* Tail of hash chains */8687#ifndef TOO_FAR88# define TOO_FAR 409689#endif90/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */9192/* Values for max_lazy_match, good_match and max_chain_length, depending on93* the desired pack level (0..9). The values given below have been tuned to94* exclude worst case performance for pathological files. Better values may be95* found for specific files.96*/97typedef struct config_s {98ush good_length; /* reduce lazy search above this match length */99ush max_lazy; /* do not perform lazy search above this match length */100ush nice_length; /* quit search above this match length */101ush max_chain;102compress_func func;103} config;104105#ifdef FASTEST106local const config configuration_table[2] = {107/* good lazy nice chain */108/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */109/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */110#else111local const config configuration_table[10] = {112/* good lazy nice chain */113/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */114/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */115/* 2 */ {4, 5, 16, 8, deflate_fast},116/* 3 */ {4, 6, 32, 32, deflate_fast},117118/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */119/* 5 */ {8, 16, 32, 32, deflate_slow},120/* 6 */ {8, 16, 128, 128, deflate_slow},121/* 7 */ {8, 32, 128, 256, deflate_slow},122/* 8 */ {32, 128, 258, 1024, deflate_slow},123/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */124#endif125126/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4127* For deflate_fast() (levels <= 3) good is ignored and lazy has a different128* meaning.129*/130131/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */132#define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0))133134/* ===========================================================================135* Update a hash value with the given input byte136* IN assertion: all calls to UPDATE_HASH are made with consecutive input137* characters, so that a running hash key can be computed from the previous138* key instead of complete recalculation each time.139*/140#define UPDATE_HASH(s,h,c) (h = (((h) << s->hash_shift) ^ (c)) & s->hash_mask)141142143/* ===========================================================================144* Insert string str in the dictionary and set match_head to the previous head145* of the hash chain (the most recent string with same hash key). Return146* the previous length of the hash chain.147* If this file is compiled with -DFASTEST, the compression level is forced148* to 1, and no hash chains are maintained.149* IN assertion: all calls to INSERT_STRING are made with consecutive input150* characters and the first MIN_MATCH bytes of str are valid (except for151* the last MIN_MATCH-1 bytes of the input file).152*/153#ifdef FASTEST154#define INSERT_STRING(s, str, match_head) \155(UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \156match_head = s->head[s->ins_h], \157s->head[s->ins_h] = (Pos)(str))158#else159#define INSERT_STRING(s, str, match_head) \160(UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \161match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \162s->head[s->ins_h] = (Pos)(str))163#endif164165/* ===========================================================================166* Initialize the hash table (avoiding 64K overflow for 16 bit systems).167* prev[] will be initialized on the fly.168*/169#define CLEAR_HASH(s) \170do { \171s->head[s->hash_size - 1] = NIL; \172zmemzero((Bytef *)s->head, \173(unsigned)(s->hash_size - 1)*sizeof(*s->head)); \174} while (0)175176/* ===========================================================================177* Slide the hash table when sliding the window down (could be avoided with 32178* bit values at the expense of memory usage). We slide even when level == 0 to179* keep the hash table consistent if we switch back to level > 0 later.180*/181#if defined(__has_feature)182# if __has_feature(memory_sanitizer)183__attribute__((no_sanitize("memory")))184# endif185#endif186local void slide_hash(deflate_state *s) {187unsigned n, m;188Posf *p;189uInt wsize = s->w_size;190191n = s->hash_size;192p = &s->head[n];193do {194m = *--p;195*p = (Pos)(m >= wsize ? m - wsize : NIL);196} while (--n);197n = wsize;198#ifndef FASTEST199p = &s->prev[n];200do {201m = *--p;202*p = (Pos)(m >= wsize ? m - wsize : NIL);203/* If n is not on any hash chain, prev[n] is garbage but204* its value will never be used.205*/206} while (--n);207#endif208}209210/* ===========================================================================211* Read a new buffer from the current input stream, update the adler32212* and total number of bytes read. All deflate() input goes through213* this function so some applications may wish to modify it to avoid214* allocating a large strm->next_in buffer and copying from it.215* (See also flush_pending()).216*/217local unsigned read_buf(z_streamp strm, Bytef *buf, unsigned size) {218unsigned len = strm->avail_in;219220if (len > size) len = size;221if (len == 0) return 0;222223strm->avail_in -= len;224225zmemcpy(buf, strm->next_in, len);226if (strm->state->wrap == 1) {227strm->adler = adler32(strm->adler, buf, len);228}229#ifdef GZIP230else if (strm->state->wrap == 2) {231strm->adler = crc32(strm->adler, buf, len);232}233#endif234strm->next_in += len;235strm->total_in += len;236237return len;238}239240/* ===========================================================================241* Fill the window when the lookahead becomes insufficient.242* Updates strstart and lookahead.243*244* IN assertion: lookahead < MIN_LOOKAHEAD245* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD246* At least one byte has been read, or avail_in == 0; reads are247* performed for at least two bytes (required for the zip translate_eol248* option -- not supported here).249*/250local void fill_window(deflate_state *s) {251unsigned n;252unsigned more; /* Amount of free space at the end of the window. */253uInt wsize = s->w_size;254255Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");256257do {258more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);259260/* Deal with !@#$% 64K limit: */261if (sizeof(int) <= 2) {262if (more == 0 && s->strstart == 0 && s->lookahead == 0) {263more = wsize;264265} else if (more == (unsigned)(-1)) {266/* Very unlikely, but possible on 16 bit machine if267* strstart == 0 && lookahead == 1 (input done a byte at time)268*/269more--;270}271}272273/* If the window is almost full and there is insufficient lookahead,274* move the upper half to the lower one to make room in the upper half.275*/276if (s->strstart >= wsize + MAX_DIST(s)) {277278zmemcpy(s->window, s->window + wsize, (unsigned)wsize - more);279s->match_start -= wsize;280s->strstart -= wsize; /* we now have strstart >= MAX_DIST */281s->block_start -= (long) wsize;282if (s->insert > s->strstart)283s->insert = s->strstart;284slide_hash(s);285more += wsize;286}287if (s->strm->avail_in == 0) break;288289/* If there was no sliding:290* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&291* more == window_size - lookahead - strstart292* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)293* => more >= window_size - 2*WSIZE + 2294* In the BIG_MEM or MMAP case (not yet supported),295* window_size == input_size + MIN_LOOKAHEAD &&296* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.297* Otherwise, window_size == 2*WSIZE so more >= 2.298* If there was sliding, more >= WSIZE. So in all cases, more >= 2.299*/300Assert(more >= 2, "more < 2");301302n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);303s->lookahead += n;304305/* Initialize the hash value now that we have some input: */306if (s->lookahead + s->insert >= MIN_MATCH) {307uInt str = s->strstart - s->insert;308s->ins_h = s->window[str];309UPDATE_HASH(s, s->ins_h, s->window[str + 1]);310#if MIN_MATCH != 3311Call UPDATE_HASH() MIN_MATCH-3 more times312#endif313while (s->insert) {314UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);315#ifndef FASTEST316s->prev[str & s->w_mask] = s->head[s->ins_h];317#endif318s->head[s->ins_h] = (Pos)str;319str++;320s->insert--;321if (s->lookahead + s->insert < MIN_MATCH)322break;323}324}325/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,326* but this is not important since only literal bytes will be emitted.327*/328329} while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);330331/* If the WIN_INIT bytes after the end of the current data have never been332* written, then zero those bytes in order to avoid memory check reports of333* the use of uninitialized (or uninitialised as Julian writes) bytes by334* the longest match routines. Update the high water mark for the next335* time through here. WIN_INIT is set to MAX_MATCH since the longest match336* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.337*/338if (s->high_water < s->window_size) {339ulg curr = s->strstart + (ulg)(s->lookahead);340ulg init;341342if (s->high_water < curr) {343/* Previous high water mark below current data -- zero WIN_INIT344* bytes or up to end of window, whichever is less.345*/346init = s->window_size - curr;347if (init > WIN_INIT)348init = WIN_INIT;349zmemzero(s->window + curr, (unsigned)init);350s->high_water = curr + init;351}352else if (s->high_water < (ulg)curr + WIN_INIT) {353/* High water mark at or above current data, but below current data354* plus WIN_INIT -- zero out to current data plus WIN_INIT, or up355* to end of window, whichever is less.356*/357init = (ulg)curr + WIN_INIT - s->high_water;358if (init > s->window_size - s->high_water)359init = s->window_size - s->high_water;360zmemzero(s->window + s->high_water, (unsigned)init);361s->high_water += init;362}363}364365Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,366"not enough room for search");367}368369/* ========================================================================= */370int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version,371int stream_size) {372return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,373Z_DEFAULT_STRATEGY, version, stream_size);374/* To do: ignore strm->next_in if we use it as window */375}376377/* ========================================================================= */378int ZEXPORT deflateInit2_(z_streamp strm, int level, int method,379int windowBits, int memLevel, int strategy,380const char *version, int stream_size) {381deflate_state *s;382int wrap = 1;383static const char my_version[] = ZLIB_VERSION;384385if (version == Z_NULL || version[0] != my_version[0] ||386stream_size != sizeof(z_stream)) {387return Z_VERSION_ERROR;388}389if (strm == Z_NULL) return Z_STREAM_ERROR;390391strm->msg = Z_NULL;392if (strm->zalloc == (alloc_func)0) {393#ifdef Z_SOLO394return Z_STREAM_ERROR;395#else396strm->zalloc = zcalloc;397strm->opaque = (voidpf)0;398#endif399}400if (strm->zfree == (free_func)0)401#ifdef Z_SOLO402return Z_STREAM_ERROR;403#else404strm->zfree = zcfree;405#endif406407#ifdef FASTEST408if (level != 0) level = 1;409#else410if (level == Z_DEFAULT_COMPRESSION) level = 6;411#endif412413if (windowBits < 0) { /* suppress zlib wrapper */414wrap = 0;415if (windowBits < -15)416return Z_STREAM_ERROR;417windowBits = -windowBits;418}419#ifdef GZIP420else if (windowBits > 15) {421wrap = 2; /* write gzip wrapper instead */422windowBits -= 16;423}424#endif425if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||426windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||427strategy < 0 || strategy > Z_FIXED || (windowBits == 8 && wrap != 1)) {428return Z_STREAM_ERROR;429}430if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */431s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));432if (s == Z_NULL) return Z_MEM_ERROR;433strm->state = (struct internal_state FAR *)s;434s->strm = strm;435s->status = INIT_STATE; /* to pass state test in deflateReset() */436437s->wrap = wrap;438s->gzhead = Z_NULL;439s->w_bits = (uInt)windowBits;440s->w_size = 1 << s->w_bits;441s->w_mask = s->w_size - 1;442443s->hash_bits = (uInt)memLevel + 7;444s->hash_size = 1 << s->hash_bits;445s->hash_mask = s->hash_size - 1;446s->hash_shift = ((s->hash_bits + MIN_MATCH-1) / MIN_MATCH);447448s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));449450/* The following memset eliminates the valgrind uninitialized warning451"swept under the carpet" here:452http://www.zlib.net/zlib_faq.html#faq36 */453454memset(s->window, 0, s->w_size*2*sizeof(Byte));455456s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));457s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));458459s->high_water = 0; /* nothing written to s->window yet */460461s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */462463/* We overlay pending_buf and sym_buf. This works since the average size464* for length/distance pairs over any compressed block is assured to be 31465* bits or less.466*467* Analysis: The longest fixed codes are a length code of 8 bits plus 5468* extra bits, for lengths 131 to 257. The longest fixed distance codes are469* 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest470* possible fixed-codes length/distance pair is then 31 bits total.471*472* sym_buf starts one-fourth of the way into pending_buf. So there are473* three bytes in sym_buf for every four bytes in pending_buf. Each symbol474* in sym_buf is three bytes -- two for the distance and one for the475* literal/length. As each symbol is consumed, the pointer to the next476* sym_buf value to read moves forward three bytes. From that symbol, up to477* 31 bits are written to pending_buf. The closest the written pending_buf478* bits gets to the next sym_buf symbol to read is just before the last479* code is written. At that time, 31*(n - 2) bits have been written, just480* after 24*(n - 2) bits have been consumed from sym_buf. sym_buf starts at481* 8*n bits into pending_buf. (Note that the symbol buffer fills when n - 1482* symbols are written.) The closest the writing gets to what is unread is483* then n + 14 bits. Here n is lit_bufsize, which is 16384 by default, and484* can range from 128 to 32768.485*486* Therefore, at a minimum, there are 142 bits of space between what is487* written and what is read in the overlain buffers, so the symbols cannot488* be overwritten by the compressed data. That space is actually 139 bits,489* due to the three-bit fixed-code block header.490*491* That covers the case where either Z_FIXED is specified, forcing fixed492* codes, or when the use of fixed codes is chosen, because that choice493* results in a smaller compressed block than dynamic codes. That latter494* condition then assures that the above analysis also covers all dynamic495* blocks. A dynamic-code block will only be chosen to be emitted if it has496* fewer bits than a fixed-code block would for the same set of symbols.497* Therefore its average symbol length is assured to be less than 31. So498* the compressed data for a dynamic block also cannot overwrite the499* symbols from which it is being constructed.500*/501502s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, LIT_BUFS);503s->pending_buf_size = (ulg)s->lit_bufsize * 4;504505if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||506s->pending_buf == Z_NULL) {507s->status = FINISH_STATE;508strm->msg = ERR_MSG(Z_MEM_ERROR);509deflateEnd (strm);510return Z_MEM_ERROR;511}512#ifdef LIT_MEM513s->d_buf = (ushf *)(s->pending_buf + (s->lit_bufsize << 1));514s->l_buf = s->pending_buf + (s->lit_bufsize << 2);515s->sym_end = s->lit_bufsize - 1;516#else517s->sym_buf = s->pending_buf + s->lit_bufsize;518s->sym_end = (s->lit_bufsize - 1) * 3;519#endif520/* We avoid equality with lit_bufsize*3 because of wraparound at 64K521* on 16 bit machines and because stored blocks are restricted to522* 64K-1 bytes.523*/524525s->level = level;526s->strategy = strategy;527s->method = (Byte)method;528529return deflateReset(strm);530}531532/* =========================================================================533* Check for a valid deflate stream state. Return 0 if ok, 1 if not.534*/535local int deflateStateCheck(z_streamp strm) {536deflate_state *s;537if (strm == Z_NULL ||538strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)539return 1;540s = strm->state;541if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE &&542#ifdef GZIP543s->status != GZIP_STATE &&544#endif545s->status != EXTRA_STATE &&546s->status != NAME_STATE &&547s->status != COMMENT_STATE &&548s->status != HCRC_STATE &&549s->status != BUSY_STATE &&550s->status != FINISH_STATE))551return 1;552return 0;553}554555/* ========================================================================= */556int ZEXPORT deflateSetDictionary(z_streamp strm, const Bytef *dictionary,557uInt dictLength) {558deflate_state *s;559uInt str, n;560int wrap;561unsigned avail;562z_const unsigned char *next;563564if (deflateStateCheck(strm) || dictionary == Z_NULL)565return Z_STREAM_ERROR;566s = strm->state;567wrap = s->wrap;568if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)569return Z_STREAM_ERROR;570571/* when using zlib wrappers, compute Adler-32 for provided dictionary */572if (wrap == 1)573strm->adler = adler32(strm->adler, dictionary, dictLength);574s->wrap = 0; /* avoid computing Adler-32 in read_buf */575576/* if dictionary would fill window, just replace the history */577if (dictLength >= s->w_size) {578if (wrap == 0) { /* already empty otherwise */579CLEAR_HASH(s);580s->strstart = 0;581s->block_start = 0L;582s->insert = 0;583}584dictionary += dictLength - s->w_size; /* use the tail */585dictLength = s->w_size;586}587588/* insert dictionary into window and hash */589avail = strm->avail_in;590next = strm->next_in;591strm->avail_in = dictLength;592strm->next_in = (z_const Bytef *)dictionary;593fill_window(s);594while (s->lookahead >= MIN_MATCH) {595str = s->strstart;596n = s->lookahead - (MIN_MATCH-1);597do {598UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);599#ifndef FASTEST600s->prev[str & s->w_mask] = s->head[s->ins_h];601#endif602s->head[s->ins_h] = (Pos)str;603str++;604} while (--n);605s->strstart = str;606s->lookahead = MIN_MATCH-1;607fill_window(s);608}609s->strstart += s->lookahead;610s->block_start = (long)s->strstart;611s->insert = s->lookahead;612s->lookahead = 0;613s->match_length = s->prev_length = MIN_MATCH-1;614s->match_available = 0;615strm->next_in = next;616strm->avail_in = avail;617s->wrap = wrap;618return Z_OK;619}620621/* ========================================================================= */622int ZEXPORT deflateGetDictionary(z_streamp strm, Bytef *dictionary,623uInt *dictLength) {624deflate_state *s;625uInt len;626627if (deflateStateCheck(strm))628return Z_STREAM_ERROR;629s = strm->state;630len = s->strstart + s->lookahead;631if (len > s->w_size)632len = s->w_size;633if (dictionary != Z_NULL && len)634zmemcpy(dictionary, s->window + s->strstart + s->lookahead - len, len);635if (dictLength != Z_NULL)636*dictLength = len;637return Z_OK;638}639640/* ========================================================================= */641int ZEXPORT deflateResetKeep(z_streamp strm) {642deflate_state *s;643644if (deflateStateCheck(strm)) {645return Z_STREAM_ERROR;646}647648strm->total_in = strm->total_out = 0;649strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */650strm->data_type = Z_UNKNOWN;651652s = (deflate_state *)strm->state;653s->pending = 0;654s->pending_out = s->pending_buf;655656if (s->wrap < 0) {657s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */658}659s->status =660#ifdef GZIP661s->wrap == 2 ? GZIP_STATE :662#endif663INIT_STATE;664strm->adler =665#ifdef GZIP666s->wrap == 2 ? crc32(0L, Z_NULL, 0) :667#endif668adler32(0L, Z_NULL, 0);669s->last_flush = -2;670671_tr_init(s);672673return Z_OK;674}675676/* ===========================================================================677* Initialize the "longest match" routines for a new zlib stream678*/679local void lm_init(deflate_state *s) {680s->window_size = (ulg)2L*s->w_size;681682CLEAR_HASH(s);683684/* Set the default configuration parameters:685*/686s->max_lazy_match = configuration_table[s->level].max_lazy;687s->good_match = configuration_table[s->level].good_length;688s->nice_match = configuration_table[s->level].nice_length;689s->max_chain_length = configuration_table[s->level].max_chain;690691s->strstart = 0;692s->block_start = 0L;693s->lookahead = 0;694s->insert = 0;695s->match_length = s->prev_length = MIN_MATCH-1;696s->match_available = 0;697s->ins_h = 0;698}699700/* ========================================================================= */701int ZEXPORT deflateReset(z_streamp strm) {702int ret;703704ret = deflateResetKeep(strm);705if (ret == Z_OK)706lm_init(strm->state);707return ret;708}709710/* ========================================================================= */711int ZEXPORT deflateSetHeader(z_streamp strm, gz_headerp head) {712if (deflateStateCheck(strm) || strm->state->wrap != 2)713return Z_STREAM_ERROR;714strm->state->gzhead = head;715return Z_OK;716}717718/* ========================================================================= */719int ZEXPORT deflatePending(z_streamp strm, unsigned *pending, int *bits) {720if (deflateStateCheck(strm)) return Z_STREAM_ERROR;721if (pending != Z_NULL)722*pending = strm->state->pending;723if (bits != Z_NULL)724*bits = strm->state->bi_valid;725return Z_OK;726}727728/* ========================================================================= */729int ZEXPORT deflatePrime(z_streamp strm, int bits, int value) {730deflate_state *s;731int put;732733if (deflateStateCheck(strm)) return Z_STREAM_ERROR;734s = strm->state;735#ifdef LIT_MEM736if (bits < 0 || bits > 16 ||737(uchf *)s->d_buf < s->pending_out + ((Buf_size + 7) >> 3))738return Z_BUF_ERROR;739#else740if (bits < 0 || bits > 16 ||741s->sym_buf < s->pending_out + ((Buf_size + 7) >> 3))742return Z_BUF_ERROR;743#endif744do {745put = Buf_size - s->bi_valid;746if (put > bits)747put = bits;748s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);749s->bi_valid += put;750_tr_flush_bits(s);751value >>= put;752bits -= put;753} while (bits);754return Z_OK;755}756757/* ========================================================================= */758int ZEXPORT deflateParams(z_streamp strm, int level, int strategy) {759deflate_state *s;760compress_func func;761762if (deflateStateCheck(strm)) return Z_STREAM_ERROR;763s = strm->state;764765#ifdef FASTEST766if (level != 0) level = 1;767#else768if (level == Z_DEFAULT_COMPRESSION) level = 6;769#endif770if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {771return Z_STREAM_ERROR;772}773func = configuration_table[s->level].func;774775if ((strategy != s->strategy || func != configuration_table[level].func) &&776s->last_flush != -2) {777/* Flush the last buffer: */778int err = deflate(strm, Z_BLOCK);779if (err == Z_STREAM_ERROR)780return err;781if (strm->avail_in || (s->strstart - s->block_start) + s->lookahead)782return Z_BUF_ERROR;783}784if (s->level != level) {785if (s->level == 0 && s->matches != 0) {786if (s->matches == 1)787slide_hash(s);788else789CLEAR_HASH(s);790s->matches = 0;791}792s->level = level;793s->max_lazy_match = configuration_table[level].max_lazy;794s->good_match = configuration_table[level].good_length;795s->nice_match = configuration_table[level].nice_length;796s->max_chain_length = configuration_table[level].max_chain;797}798s->strategy = strategy;799return Z_OK;800}801802/* ========================================================================= */803int ZEXPORT deflateTune(z_streamp strm, int good_length, int max_lazy,804int nice_length, int max_chain) {805deflate_state *s;806807if (deflateStateCheck(strm)) return Z_STREAM_ERROR;808s = strm->state;809s->good_match = (uInt)good_length;810s->max_lazy_match = (uInt)max_lazy;811s->nice_match = nice_length;812s->max_chain_length = (uInt)max_chain;813return Z_OK;814}815816/* =========================================================================817* For the default windowBits of 15 and memLevel of 8, this function returns a818* close to exact, as well as small, upper bound on the compressed size. This819* is an expansion of ~0.03%, plus a small constant.820*821* For any setting other than those defaults for windowBits and memLevel, one822* of two worst case bounds is returned. This is at most an expansion of ~4% or823* ~13%, plus a small constant.824*825* Both the 0.03% and 4% derive from the overhead of stored blocks. The first826* one is for stored blocks of 16383 bytes (memLevel == 8), whereas the second827* is for stored blocks of 127 bytes (the worst case memLevel == 1). The828* expansion results from five bytes of header for each stored block.829*830* The larger expansion of 13% results from a window size less than or equal to831* the symbols buffer size (windowBits <= memLevel + 7). In that case some of832* the data being compressed may have slid out of the sliding window, impeding833* a stored block from being emitted. Then the only choice is a fixed or834* dynamic block, where a fixed block limits the maximum expansion to 9 bits835* per 8-bit byte, plus 10 bits for every block. The smallest block size for836* which this can occur is 255 (memLevel == 2).837*838* Shifts are used to approximate divisions, for speed.839*/840uLong ZEXPORT deflateBound(z_streamp strm, uLong sourceLen) {841deflate_state *s;842uLong fixedlen, storelen, wraplen;843844/* upper bound for fixed blocks with 9-bit literals and length 255845(memLevel == 2, which is the lowest that may not use stored blocks) --846~13% overhead plus a small constant */847fixedlen = sourceLen + (sourceLen >> 3) + (sourceLen >> 8) +848(sourceLen >> 9) + 4;849850/* upper bound for stored blocks with length 127 (memLevel == 1) --851~4% overhead plus a small constant */852storelen = sourceLen + (sourceLen >> 5) + (sourceLen >> 7) +853(sourceLen >> 11) + 7;854855/* if can't get parameters, return larger bound plus a zlib wrapper */856if (deflateStateCheck(strm))857return (fixedlen > storelen ? fixedlen : storelen) + 6;858859/* compute wrapper length */860s = strm->state;861switch (s->wrap) {862case 0: /* raw deflate */863wraplen = 0;864break;865case 1: /* zlib wrapper */866wraplen = 6 + (s->strstart ? 4 : 0);867break;868#ifdef GZIP869case 2: /* gzip wrapper */870wraplen = 18;871if (s->gzhead != Z_NULL) { /* user-supplied gzip header */872Bytef *str;873if (s->gzhead->extra != Z_NULL)874wraplen += 2 + s->gzhead->extra_len;875str = s->gzhead->name;876if (str != Z_NULL)877do {878wraplen++;879} while (*str++);880str = s->gzhead->comment;881if (str != Z_NULL)882do {883wraplen++;884} while (*str++);885if (s->gzhead->hcrc)886wraplen += 2;887}888break;889#endif890default: /* for compiler happiness */891wraplen = 6;892}893894/* if not default parameters, return one of the conservative bounds */895if (s->w_bits != 15 || s->hash_bits != 8 + 7)896return (s->w_bits <= s->hash_bits && s->level ? fixedlen : storelen) +897wraplen;898899/* default settings: return tight bound for that case -- ~0.03% overhead900plus a small constant */901return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +902(sourceLen >> 25) + 13 - 6 + wraplen;903}904905/* =========================================================================906* Put a short in the pending buffer. The 16-bit value is put in MSB order.907* IN assertion: the stream state is correct and there is enough room in908* pending_buf.909*/910local void putShortMSB(deflate_state *s, uInt b) {911put_byte(s, (Byte)(b >> 8));912put_byte(s, (Byte)(b & 0xff));913}914915/* =========================================================================916* Flush as much pending output as possible. All deflate() output, except for917* some deflate_stored() output, goes through this function so some918* applications may wish to modify it to avoid allocating a large919* strm->next_out buffer and copying into it. (See also read_buf()).920*/921local void flush_pending(z_streamp strm) {922unsigned len;923deflate_state *s = strm->state;924925_tr_flush_bits(s);926len = s->pending;927if (len > strm->avail_out) len = strm->avail_out;928if (len == 0) return;929930zmemcpy(strm->next_out, s->pending_out, len);931strm->next_out += len;932s->pending_out += len;933strm->total_out += len;934strm->avail_out -= len;935s->pending -= len;936if (s->pending == 0) {937s->pending_out = s->pending_buf;938}939}940941/* ===========================================================================942* Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1].943*/944#define HCRC_UPDATE(beg) \945do { \946if (s->gzhead->hcrc && s->pending > (beg)) \947strm->adler = crc32(strm->adler, s->pending_buf + (beg), \948s->pending - (beg)); \949} while (0)950951/* ========================================================================= */952int ZEXPORT deflate(z_streamp strm, int flush) {953int old_flush; /* value of flush param for previous deflate call */954deflate_state *s;955956if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) {957return Z_STREAM_ERROR;958}959s = strm->state;960961if (strm->next_out == Z_NULL ||962(strm->avail_in != 0 && strm->next_in == Z_NULL) ||963(s->status == FINISH_STATE && flush != Z_FINISH)) {964ERR_RETURN(strm, Z_STREAM_ERROR);965}966if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);967968old_flush = s->last_flush;969s->last_flush = flush;970971/* Flush as much pending output as possible */972if (s->pending != 0) {973flush_pending(strm);974if (strm->avail_out == 0) {975/* Since avail_out is 0, deflate will be called again with976* more output space, but possibly with both pending and977* avail_in equal to zero. There won't be anything to do,978* but this is not an error situation so make sure we979* return OK instead of BUF_ERROR at next call of deflate:980*/981s->last_flush = -1;982return Z_OK;983}984985/* Make sure there is something to do and avoid duplicate consecutive986* flushes. For repeated and useless calls with Z_FINISH, we keep987* returning Z_STREAM_END instead of Z_BUF_ERROR.988*/989} else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&990flush != Z_FINISH) {991ERR_RETURN(strm, Z_BUF_ERROR);992}993994/* User must not provide more input after the first FINISH: */995if (s->status == FINISH_STATE && strm->avail_in != 0) {996ERR_RETURN(strm, Z_BUF_ERROR);997}998999/* Write the header */1000if (s->status == INIT_STATE && s->wrap == 0)1001s->status = BUSY_STATE;1002if (s->status == INIT_STATE) {1003/* zlib header */1004uInt header = (Z_DEFLATED + ((s->w_bits - 8) << 4)) << 8;1005uInt level_flags;10061007if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)1008level_flags = 0;1009else if (s->level < 6)1010level_flags = 1;1011else if (s->level == 6)1012level_flags = 2;1013else1014level_flags = 3;1015header |= (level_flags << 6);1016if (s->strstart != 0) header |= PRESET_DICT;1017header += 31 - (header % 31);10181019putShortMSB(s, header);10201021/* Save the adler32 of the preset dictionary: */1022if (s->strstart != 0) {1023putShortMSB(s, (uInt)(strm->adler >> 16));1024putShortMSB(s, (uInt)(strm->adler & 0xffff));1025}1026strm->adler = adler32(0L, Z_NULL, 0);1027s->status = BUSY_STATE;10281029/* Compression must start with an empty pending buffer */1030flush_pending(strm);1031if (s->pending != 0) {1032s->last_flush = -1;1033return Z_OK;1034}1035}1036#ifdef GZIP1037if (s->status == GZIP_STATE) {1038/* gzip header */1039strm->adler = crc32(0L, Z_NULL, 0);1040put_byte(s, 31);1041put_byte(s, 139);1042put_byte(s, 8);1043if (s->gzhead == Z_NULL) {1044put_byte(s, 0);1045put_byte(s, 0);1046put_byte(s, 0);1047put_byte(s, 0);1048put_byte(s, 0);1049put_byte(s, s->level == 9 ? 2 :1050(s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?10514 : 0));1052put_byte(s, OS_CODE);1053s->status = BUSY_STATE;10541055/* Compression must start with an empty pending buffer */1056flush_pending(strm);1057if (s->pending != 0) {1058s->last_flush = -1;1059return Z_OK;1060}1061}1062else {1063put_byte(s, (s->gzhead->text ? 1 : 0) +1064(s->gzhead->hcrc ? 2 : 0) +1065(s->gzhead->extra == Z_NULL ? 0 : 4) +1066(s->gzhead->name == Z_NULL ? 0 : 8) +1067(s->gzhead->comment == Z_NULL ? 0 : 16)1068);1069put_byte(s, (Byte)(s->gzhead->time & 0xff));1070put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));1071put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));1072put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));1073put_byte(s, s->level == 9 ? 2 :1074(s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?10754 : 0));1076put_byte(s, s->gzhead->os & 0xff);1077if (s->gzhead->extra != Z_NULL) {1078put_byte(s, s->gzhead->extra_len & 0xff);1079put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);1080}1081if (s->gzhead->hcrc)1082strm->adler = crc32(strm->adler, s->pending_buf,1083s->pending);1084s->gzindex = 0;1085s->status = EXTRA_STATE;1086}1087}1088if (s->status == EXTRA_STATE) {1089if (s->gzhead->extra != Z_NULL) {1090ulg beg = s->pending; /* start of bytes to update crc */1091uInt left = (s->gzhead->extra_len & 0xffff) - s->gzindex;1092while (s->pending + left > s->pending_buf_size) {1093uInt copy = s->pending_buf_size - s->pending;1094zmemcpy(s->pending_buf + s->pending,1095s->gzhead->extra + s->gzindex, copy);1096s->pending = s->pending_buf_size;1097HCRC_UPDATE(beg);1098s->gzindex += copy;1099flush_pending(strm);1100if (s->pending != 0) {1101s->last_flush = -1;1102return Z_OK;1103}1104beg = 0;1105left -= copy;1106}1107zmemcpy(s->pending_buf + s->pending,1108s->gzhead->extra + s->gzindex, left);1109s->pending += left;1110HCRC_UPDATE(beg);1111s->gzindex = 0;1112}1113s->status = NAME_STATE;1114}1115if (s->status == NAME_STATE) {1116if (s->gzhead->name != Z_NULL) {1117ulg beg = s->pending; /* start of bytes to update crc */1118int val;1119do {1120if (s->pending == s->pending_buf_size) {1121HCRC_UPDATE(beg);1122flush_pending(strm);1123if (s->pending != 0) {1124s->last_flush = -1;1125return Z_OK;1126}1127beg = 0;1128}1129val = s->gzhead->name[s->gzindex++];1130put_byte(s, val);1131} while (val != 0);1132HCRC_UPDATE(beg);1133s->gzindex = 0;1134}1135s->status = COMMENT_STATE;1136}1137if (s->status == COMMENT_STATE) {1138if (s->gzhead->comment != Z_NULL) {1139ulg beg = s->pending; /* start of bytes to update crc */1140int val;1141do {1142if (s->pending == s->pending_buf_size) {1143HCRC_UPDATE(beg);1144flush_pending(strm);1145if (s->pending != 0) {1146s->last_flush = -1;1147return Z_OK;1148}1149beg = 0;1150}1151val = s->gzhead->comment[s->gzindex++];1152put_byte(s, val);1153} while (val != 0);1154HCRC_UPDATE(beg);1155}1156s->status = HCRC_STATE;1157}1158if (s->status == HCRC_STATE) {1159if (s->gzhead->hcrc) {1160if (s->pending + 2 > s->pending_buf_size) {1161flush_pending(strm);1162if (s->pending != 0) {1163s->last_flush = -1;1164return Z_OK;1165}1166}1167put_byte(s, (Byte)(strm->adler & 0xff));1168put_byte(s, (Byte)((strm->adler >> 8) & 0xff));1169strm->adler = crc32(0L, Z_NULL, 0);1170}1171s->status = BUSY_STATE;11721173/* Compression must start with an empty pending buffer */1174flush_pending(strm);1175if (s->pending != 0) {1176s->last_flush = -1;1177return Z_OK;1178}1179}1180#endif11811182/* Start a new block or continue the current one.1183*/1184if (strm->avail_in != 0 || s->lookahead != 0 ||1185(flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {1186block_state bstate;11871188bstate = s->level == 0 ? deflate_stored(s, flush) :1189s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :1190s->strategy == Z_RLE ? deflate_rle(s, flush) :1191(*(configuration_table[s->level].func))(s, flush);11921193if (bstate == finish_started || bstate == finish_done) {1194s->status = FINISH_STATE;1195}1196if (bstate == need_more || bstate == finish_started) {1197if (strm->avail_out == 0) {1198s->last_flush = -1; /* avoid BUF_ERROR next call, see above */1199}1200return Z_OK;1201/* If flush != Z_NO_FLUSH && avail_out == 0, the next call1202* of deflate should use the same flush parameter to make sure1203* that the flush is complete. So we don't have to output an1204* empty block here, this will be done at next call. This also1205* ensures that for a very small output buffer, we emit at most1206* one empty block.1207*/1208}1209if (bstate == block_done) {1210if (flush == Z_PARTIAL_FLUSH) {1211_tr_align(s);1212} else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */1213_tr_stored_block(s, (char*)0, 0L, 0);1214/* For a full flush, this empty block will be recognized1215* as a special marker by inflate_sync().1216*/1217if (flush == Z_FULL_FLUSH) {1218CLEAR_HASH(s); /* forget history */1219if (s->lookahead == 0) {1220s->strstart = 0;1221s->block_start = 0L;1222s->insert = 0;1223}1224}1225}1226flush_pending(strm);1227if (strm->avail_out == 0) {1228s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */1229return Z_OK;1230}1231}1232}12331234if (flush != Z_FINISH) return Z_OK;1235if (s->wrap <= 0) return Z_STREAM_END;12361237/* Write the trailer */1238#ifdef GZIP1239if (s->wrap == 2) {1240put_byte(s, (Byte)(strm->adler & 0xff));1241put_byte(s, (Byte)((strm->adler >> 8) & 0xff));1242put_byte(s, (Byte)((strm->adler >> 16) & 0xff));1243put_byte(s, (Byte)((strm->adler >> 24) & 0xff));1244put_byte(s, (Byte)(strm->total_in & 0xff));1245put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));1246put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));1247put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));1248}1249else1250#endif1251{1252putShortMSB(s, (uInt)(strm->adler >> 16));1253putShortMSB(s, (uInt)(strm->adler & 0xffff));1254}1255flush_pending(strm);1256/* If avail_out is zero, the application will call deflate again1257* to flush the rest.1258*/1259if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */1260return s->pending != 0 ? Z_OK : Z_STREAM_END;1261}12621263/* ========================================================================= */1264int ZEXPORT deflateEnd(z_streamp strm) {1265int status;12661267if (deflateStateCheck(strm)) return Z_STREAM_ERROR;12681269status = strm->state->status;12701271/* Deallocate in reverse order of allocations: */1272TRY_FREE(strm, strm->state->pending_buf);1273TRY_FREE(strm, strm->state->head);1274TRY_FREE(strm, strm->state->prev);1275TRY_FREE(strm, strm->state->window);12761277ZFREE(strm, strm->state);1278strm->state = Z_NULL;12791280return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;1281}12821283/* =========================================================================1284* Copy the source state to the destination state.1285* To simplify the source, this is not supported for 16-bit MSDOS (which1286* doesn't have enough memory anyway to duplicate compression states).1287*/1288int ZEXPORT deflateCopy(z_streamp dest, z_streamp source) {1289#ifdef MAXSEG_64K1290(void)dest;1291(void)source;1292return Z_STREAM_ERROR;1293#else1294deflate_state *ds;1295deflate_state *ss;129612971298if (deflateStateCheck(source) || dest == Z_NULL) {1299return Z_STREAM_ERROR;1300}13011302ss = source->state;13031304zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));13051306ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));1307if (ds == Z_NULL) return Z_MEM_ERROR;1308dest->state = (struct internal_state FAR *) ds;1309zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));1310ds->strm = dest;13111312ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));1313ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));1314ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));1315ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, LIT_BUFS);13161317if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||1318ds->pending_buf == Z_NULL) {1319deflateEnd (dest);1320return Z_MEM_ERROR;1321}1322/* following zmemcpy do not work for 16-bit MSDOS */1323zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));1324zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));1325zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));1326zmemcpy(ds->pending_buf, ss->pending_buf, ds->lit_bufsize * LIT_BUFS);13271328ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);1329#ifdef LIT_MEM1330ds->d_buf = (ushf *)(ds->pending_buf + (ds->lit_bufsize << 1));1331ds->l_buf = ds->pending_buf + (ds->lit_bufsize << 2);1332#else1333ds->sym_buf = ds->pending_buf + ds->lit_bufsize;1334#endif13351336ds->l_desc.dyn_tree = ds->dyn_ltree;1337ds->d_desc.dyn_tree = ds->dyn_dtree;1338ds->bl_desc.dyn_tree = ds->bl_tree;13391340return Z_OK;1341#endif /* MAXSEG_64K */1342}13431344#ifndef FASTEST1345/* ===========================================================================1346* Set match_start to the longest match starting at the given string and1347* return its length. Matches shorter or equal to prev_length are discarded,1348* in which case the result is equal to prev_length and match_start is1349* garbage.1350* IN assertions: cur_match is the head of the hash chain for the current1351* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 11352* OUT assertion: the match length is not greater than s->lookahead.1353*/1354local uInt longest_match(deflate_state *s, IPos cur_match) {1355unsigned chain_length = s->max_chain_length;/* max hash chain length */1356register Bytef *scan = s->window + s->strstart; /* current string */1357register Bytef *match; /* matched string */1358register int len; /* length of current match */1359int best_len = (int)s->prev_length; /* best match length so far */1360int nice_match = s->nice_match; /* stop if match long enough */1361IPos limit = s->strstart > (IPos)MAX_DIST(s) ?1362s->strstart - (IPos)MAX_DIST(s) : NIL;1363/* Stop when cur_match becomes <= limit. To simplify the code,1364* we prevent matches with the string of window index 0.1365*/1366Posf *prev = s->prev;1367uInt wmask = s->w_mask;13681369#ifdef UNALIGNED_OK1370/* Compare two bytes at a time. Note: this is not always beneficial.1371* Try with and without -DUNALIGNED_OK to check.1372*/1373register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;1374register ush scan_start = *(ushf*)scan;1375register ush scan_end = *(ushf*)(scan + best_len - 1);1376#else1377register Bytef *strend = s->window + s->strstart + MAX_MATCH;1378register Byte scan_end1 = scan[best_len - 1];1379register Byte scan_end = scan[best_len];1380#endif13811382/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.1383* It is easy to get rid of this optimization if necessary.1384*/1385Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");13861387/* Do not waste too much time if we already have a good match: */1388if (s->prev_length >= s->good_match) {1389chain_length >>= 2;1390}1391/* Do not look for matches beyond the end of the input. This is necessary1392* to make deflate deterministic.1393*/1394if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead;13951396Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,1397"need lookahead");13981399do {1400Assert(cur_match < s->strstart, "no future");1401match = s->window + cur_match;14021403/* Skip to next match if the match length cannot increase1404* or if the match length is less than 2. Note that the checks below1405* for insufficient lookahead only occur occasionally for performance1406* reasons. Therefore uninitialized memory will be accessed, and1407* conditional jumps will be made that depend on those values.1408* However the length of the match is limited to the lookahead, so1409* the output of deflate is not affected by the uninitialized values.1410*/1411#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)1412/* This code assumes sizeof(unsigned short) == 2. Do not use1413* UNALIGNED_OK if your compiler uses a different size.1414*/1415if (*(ushf*)(match + best_len - 1) != scan_end ||1416*(ushf*)match != scan_start) continue;14171418/* It is not necessary to compare scan[2] and match[2] since they are1419* always equal when the other bytes match, given that the hash keys1420* are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at1421* strstart + 3, + 5, up to strstart + 257. We check for insufficient1422* lookahead only every 4th comparison; the 128th check will be made1423* at strstart + 257. If MAX_MATCH-2 is not a multiple of 8, it is1424* necessary to put more guard bytes at the end of the window, or1425* to check more often for insufficient lookahead.1426*/1427Assert(scan[2] == match[2], "scan[2]?");1428scan++, match++;1429do {1430} while (*(ushf*)(scan += 2) == *(ushf*)(match += 2) &&1431*(ushf*)(scan += 2) == *(ushf*)(match += 2) &&1432*(ushf*)(scan += 2) == *(ushf*)(match += 2) &&1433*(ushf*)(scan += 2) == *(ushf*)(match += 2) &&1434scan < strend);1435/* The funny "do {}" generates better code on most compilers */14361437/* Here, scan <= window + strstart + 257 */1438Assert(scan <= s->window + (unsigned)(s->window_size - 1),1439"wild scan");1440if (*scan == *match) scan++;14411442len = (MAX_MATCH - 1) - (int)(strend - scan);1443scan = strend - (MAX_MATCH-1);14441445#else /* UNALIGNED_OK */14461447if (match[best_len] != scan_end ||1448match[best_len - 1] != scan_end1 ||1449*match != *scan ||1450*++match != scan[1]) continue;14511452/* The check at best_len - 1 can be removed because it will be made1453* again later. (This heuristic is not always a win.)1454* It is not necessary to compare scan[2] and match[2] since they1455* are always equal when the other bytes match, given that1456* the hash keys are equal and that HASH_BITS >= 8.1457*/1458scan += 2, match++;1459Assert(*scan == *match, "match[2]?");14601461/* We check for insufficient lookahead only every 8th comparison;1462* the 256th check will be made at strstart + 258.1463*/1464do {1465} while (*++scan == *++match && *++scan == *++match &&1466*++scan == *++match && *++scan == *++match &&1467*++scan == *++match && *++scan == *++match &&1468*++scan == *++match && *++scan == *++match &&1469scan < strend);14701471Assert(scan <= s->window + (unsigned)(s->window_size - 1),1472"wild scan");14731474len = MAX_MATCH - (int)(strend - scan);1475scan = strend - MAX_MATCH;14761477#endif /* UNALIGNED_OK */14781479if (len > best_len) {1480s->match_start = cur_match;1481best_len = len;1482if (len >= nice_match) break;1483#ifdef UNALIGNED_OK1484scan_end = *(ushf*)(scan + best_len - 1);1485#else1486scan_end1 = scan[best_len - 1];1487scan_end = scan[best_len];1488#endif1489}1490} while ((cur_match = prev[cur_match & wmask]) > limit1491&& --chain_length != 0);14921493if ((uInt)best_len <= s->lookahead) return (uInt)best_len;1494return s->lookahead;1495}14961497#else /* FASTEST */14981499/* ---------------------------------------------------------------------------1500* Optimized version for FASTEST only1501*/1502local uInt longest_match(deflate_state *s, IPos cur_match) {1503register Bytef *scan = s->window + s->strstart; /* current string */1504register Bytef *match; /* matched string */1505register int len; /* length of current match */1506register Bytef *strend = s->window + s->strstart + MAX_MATCH;15071508/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.1509* It is easy to get rid of this optimization if necessary.1510*/1511Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");15121513Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,1514"need lookahead");15151516Assert(cur_match < s->strstart, "no future");15171518match = s->window + cur_match;15191520/* Return failure if the match length is less than 2:1521*/1522if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;15231524/* The check at best_len - 1 can be removed because it will be made1525* again later. (This heuristic is not always a win.)1526* It is not necessary to compare scan[2] and match[2] since they1527* are always equal when the other bytes match, given that1528* the hash keys are equal and that HASH_BITS >= 8.1529*/1530scan += 2, match += 2;1531Assert(*scan == *match, "match[2]?");15321533/* We check for insufficient lookahead only every 8th comparison;1534* the 256th check will be made at strstart + 258.1535*/1536do {1537} while (*++scan == *++match && *++scan == *++match &&1538*++scan == *++match && *++scan == *++match &&1539*++scan == *++match && *++scan == *++match &&1540*++scan == *++match && *++scan == *++match &&1541scan < strend);15421543Assert(scan <= s->window + (unsigned)(s->window_size - 1), "wild scan");15441545len = MAX_MATCH - (int)(strend - scan);15461547if (len < MIN_MATCH) return MIN_MATCH - 1;15481549s->match_start = cur_match;1550return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;1551}15521553#endif /* FASTEST */15541555#ifdef ZLIB_DEBUG15561557#define EQUAL 01558/* result of memcmp for equal strings */15591560/* ===========================================================================1561* Check that the match at match_start is indeed a match.1562*/1563local void check_match(deflate_state *s, IPos start, IPos match, int length) {1564/* check that the match is indeed a match */1565Bytef *back = s->window + (int)match, *here = s->window + start;1566IPos len = length;1567if (match == (IPos)-1) {1568/* match starts one byte before the current window -- just compare the1569subsequent length-1 bytes */1570back++;1571here++;1572len--;1573}1574if (zmemcmp(back, here, len) != EQUAL) {1575fprintf(stderr, " start %u, match %d, length %d\n",1576start, (int)match, length);1577do {1578fprintf(stderr, "(%02x %02x)", *back++, *here++);1579} while (--len != 0);1580z_error("invalid match");1581}1582if (z_verbose > 1) {1583fprintf(stderr,"\\[%d,%d]", start - match, length);1584do { putc(s->window[start++], stderr); } while (--length != 0);1585}1586}1587#else1588# define check_match(s, start, match, length)1589#endif /* ZLIB_DEBUG */15901591/* ===========================================================================1592* Flush the current block, with given end-of-file flag.1593* IN assertion: strstart is set to the end of the current match.1594*/1595#define FLUSH_BLOCK_ONLY(s, last) { \1596_tr_flush_block(s, (s->block_start >= 0L ? \1597(charf *)&s->window[(unsigned)s->block_start] : \1598(charf *)Z_NULL), \1599(ulg)((long)s->strstart - s->block_start), \1600(last)); \1601s->block_start = s->strstart; \1602flush_pending(s->strm); \1603Tracev((stderr,"[FLUSH]")); \1604}16051606/* Same but force premature exit if necessary. */1607#define FLUSH_BLOCK(s, last) { \1608FLUSH_BLOCK_ONLY(s, last); \1609if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \1610}16111612/* Maximum stored block length in deflate format (not including header). */1613#define MAX_STORED 6553516141615/* Minimum of a and b. */1616#define MIN(a, b) ((a) > (b) ? (b) : (a))16171618/* ===========================================================================1619* Copy without compression as much as possible from the input stream, return1620* the current block state.1621*1622* In case deflateParams() is used to later switch to a non-zero compression1623* level, s->matches (otherwise unused when storing) keeps track of the number1624* of hash table slides to perform. If s->matches is 1, then one hash table1625* slide will be done when switching. If s->matches is 2, the maximum value1626* allowed here, then the hash table will be cleared, since two or more slides1627* is the same as a clear.1628*1629* deflate_stored() is written to minimize the number of times an input byte is1630* copied. It is most efficient with large input and output buffers, which1631* maximizes the opportunities to have a single copy from next_in to next_out.1632*/1633local block_state deflate_stored(deflate_state *s, int flush) {1634/* Smallest worthy block size when not flushing or finishing. By default1635* this is 32K. This can be as small as 507 bytes for memLevel == 1. For1636* large input and output buffers, the stored block size will be larger.1637*/1638unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size);16391640/* Copy as many min_block or larger stored blocks directly to next_out as1641* possible. If flushing, copy the remaining available input to next_out as1642* stored blocks, if there is enough space.1643*/1644unsigned len, left, have, last = 0;1645unsigned used = s->strm->avail_in;1646do {1647/* Set len to the maximum size block that we can copy directly with the1648* available input data and output space. Set left to how much of that1649* would be copied from what's left in the window.1650*/1651len = MAX_STORED; /* maximum deflate stored block length */1652have = (s->bi_valid + 42) >> 3; /* number of header bytes */1653if (s->strm->avail_out < have) /* need room for header */1654break;1655/* maximum stored block length that will fit in avail_out: */1656have = s->strm->avail_out - have;1657left = s->strstart - s->block_start; /* bytes left in window */1658if (len > (ulg)left + s->strm->avail_in)1659len = left + s->strm->avail_in; /* limit len to the input */1660if (len > have)1661len = have; /* limit len to the output */16621663/* If the stored block would be less than min_block in length, or if1664* unable to copy all of the available input when flushing, then try1665* copying to the window and the pending buffer instead. Also don't1666* write an empty block when flushing -- deflate() does that.1667*/1668if (len < min_block && ((len == 0 && flush != Z_FINISH) ||1669flush == Z_NO_FLUSH ||1670len != left + s->strm->avail_in))1671break;16721673/* Make a dummy stored block in pending to get the header bytes,1674* including any pending bits. This also updates the debugging counts.1675*/1676last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0;1677_tr_stored_block(s, (char *)0, 0L, last);16781679/* Replace the lengths in the dummy stored block with len. */1680s->pending_buf[s->pending - 4] = len;1681s->pending_buf[s->pending - 3] = len >> 8;1682s->pending_buf[s->pending - 2] = ~len;1683s->pending_buf[s->pending - 1] = ~len >> 8;16841685/* Write the stored block header bytes. */1686flush_pending(s->strm);16871688#ifdef ZLIB_DEBUG1689/* Update debugging counts for the data about to be copied. */1690s->compressed_len += len << 3;1691s->bits_sent += len << 3;1692#endif16931694/* Copy uncompressed bytes from the window to next_out. */1695if (left) {1696if (left > len)1697left = len;1698zmemcpy(s->strm->next_out, s->window + s->block_start, left);1699s->strm->next_out += left;1700s->strm->avail_out -= left;1701s->strm->total_out += left;1702s->block_start += left;1703len -= left;1704}17051706/* Copy uncompressed bytes directly from next_in to next_out, updating1707* the check value.1708*/1709if (len) {1710read_buf(s->strm, s->strm->next_out, len);1711s->strm->next_out += len;1712s->strm->avail_out -= len;1713s->strm->total_out += len;1714}1715} while (last == 0);17161717/* Update the sliding window with the last s->w_size bytes of the copied1718* data, or append all of the copied data to the existing window if less1719* than s->w_size bytes were copied. Also update the number of bytes to1720* insert in the hash tables, in the event that deflateParams() switches to1721* a non-zero compression level.1722*/1723used -= s->strm->avail_in; /* number of input bytes directly copied */1724if (used) {1725/* If any input was used, then no unused input remains in the window,1726* therefore s->block_start == s->strstart.1727*/1728if (used >= s->w_size) { /* supplant the previous history */1729s->matches = 2; /* clear hash */1730zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);1731s->strstart = s->w_size;1732s->insert = s->strstart;1733}1734else {1735if (s->window_size - s->strstart <= used) {1736/* Slide the window down. */1737s->strstart -= s->w_size;1738zmemcpy(s->window, s->window + s->w_size, s->strstart);1739if (s->matches < 2)1740s->matches++; /* add a pending slide_hash() */1741if (s->insert > s->strstart)1742s->insert = s->strstart;1743}1744zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);1745s->strstart += used;1746s->insert += MIN(used, s->w_size - s->insert);1747}1748s->block_start = s->strstart;1749}1750if (s->high_water < s->strstart)1751s->high_water = s->strstart;17521753/* If the last block was written to next_out, then done. */1754if (last)1755return finish_done;17561757/* If flushing and all input has been consumed, then done. */1758if (flush != Z_NO_FLUSH && flush != Z_FINISH &&1759s->strm->avail_in == 0 && (long)s->strstart == s->block_start)1760return block_done;17611762/* Fill the window with any remaining input. */1763have = s->window_size - s->strstart;1764if (s->strm->avail_in > have && s->block_start >= (long)s->w_size) {1765/* Slide the window down. */1766s->block_start -= s->w_size;1767s->strstart -= s->w_size;1768zmemcpy(s->window, s->window + s->w_size, s->strstart);1769if (s->matches < 2)1770s->matches++; /* add a pending slide_hash() */1771have += s->w_size; /* more space now */1772if (s->insert > s->strstart)1773s->insert = s->strstart;1774}1775if (have > s->strm->avail_in)1776have = s->strm->avail_in;1777if (have) {1778read_buf(s->strm, s->window + s->strstart, have);1779s->strstart += have;1780s->insert += MIN(have, s->w_size - s->insert);1781}1782if (s->high_water < s->strstart)1783s->high_water = s->strstart;17841785/* There was not enough avail_out to write a complete worthy or flushed1786* stored block to next_out. Write a stored block to pending instead, if we1787* have enough input for a worthy block, or if flushing and there is enough1788* room for the remaining input as a stored block in the pending buffer.1789*/1790have = (s->bi_valid + 42) >> 3; /* number of header bytes */1791/* maximum stored block length that will fit in pending: */1792have = MIN(s->pending_buf_size - have, MAX_STORED);1793min_block = MIN(have, s->w_size);1794left = s->strstart - s->block_start;1795if (left >= min_block ||1796((left || flush == Z_FINISH) && flush != Z_NO_FLUSH &&1797s->strm->avail_in == 0 && left <= have)) {1798len = MIN(left, have);1799last = flush == Z_FINISH && s->strm->avail_in == 0 &&1800len == left ? 1 : 0;1801_tr_stored_block(s, (charf *)s->window + s->block_start, len, last);1802s->block_start += len;1803flush_pending(s->strm);1804}18051806/* We've done all we can with the available input and output. */1807return last ? finish_started : need_more;1808}18091810/* ===========================================================================1811* Compress as much as possible from the input stream, return the current1812* block state.1813* This function does not perform lazy evaluation of matches and inserts1814* new strings in the dictionary only for unmatched strings or for short1815* matches. It is used only for the fast compression options.1816*/1817local block_state deflate_fast(deflate_state *s, int flush) {1818IPos hash_head; /* head of the hash chain */1819int bflush; /* set if current block must be flushed */18201821for (;;) {1822/* Make sure that we always have enough lookahead, except1823* at the end of the input file. We need MAX_MATCH bytes1824* for the next match, plus MIN_MATCH bytes to insert the1825* string following the next match.1826*/1827if (s->lookahead < MIN_LOOKAHEAD) {1828fill_window(s);1829if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {1830return need_more;1831}1832if (s->lookahead == 0) break; /* flush the current block */1833}18341835/* Insert the string window[strstart .. strstart + 2] in the1836* dictionary, and set hash_head to the head of the hash chain:1837*/1838hash_head = NIL;1839if (s->lookahead >= MIN_MATCH) {1840INSERT_STRING(s, s->strstart, hash_head);1841}18421843/* Find the longest match, discarding those <= prev_length.1844* At this point we have always match_length < MIN_MATCH1845*/1846if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {1847/* To simplify the code, we prevent matches with the string1848* of window index 0 (in particular we have to avoid a match1849* of the string with itself at the start of the input file).1850*/1851s->match_length = longest_match (s, hash_head);1852/* longest_match() sets match_start */1853}1854if (s->match_length >= MIN_MATCH) {1855check_match(s, s->strstart, s->match_start, s->match_length);18561857_tr_tally_dist(s, s->strstart - s->match_start,1858s->match_length - MIN_MATCH, bflush);18591860s->lookahead -= s->match_length;18611862/* Insert new strings in the hash table only if the match length1863* is not too large. This saves time but degrades compression.1864*/1865#ifndef FASTEST1866if (s->match_length <= s->max_insert_length &&1867s->lookahead >= MIN_MATCH) {1868s->match_length--; /* string at strstart already in table */1869do {1870s->strstart++;1871INSERT_STRING(s, s->strstart, hash_head);1872/* strstart never exceeds WSIZE-MAX_MATCH, so there are1873* always MIN_MATCH bytes ahead.1874*/1875} while (--s->match_length != 0);1876s->strstart++;1877} else1878#endif1879{1880s->strstart += s->match_length;1881s->match_length = 0;1882s->ins_h = s->window[s->strstart];1883UPDATE_HASH(s, s->ins_h, s->window[s->strstart + 1]);1884#if MIN_MATCH != 31885Call UPDATE_HASH() MIN_MATCH-3 more times1886#endif1887/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not1888* matter since it will be recomputed at next deflate call.1889*/1890}1891} else {1892/* No match, output a literal byte */1893Tracevv((stderr,"%c", s->window[s->strstart]));1894_tr_tally_lit(s, s->window[s->strstart], bflush);1895s->lookahead--;1896s->strstart++;1897}1898if (bflush) FLUSH_BLOCK(s, 0);1899}1900s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;1901if (flush == Z_FINISH) {1902FLUSH_BLOCK(s, 1);1903return finish_done;1904}1905if (s->sym_next)1906FLUSH_BLOCK(s, 0);1907return block_done;1908}19091910#ifndef FASTEST1911/* ===========================================================================1912* Same as above, but achieves better compression. We use a lazy1913* evaluation for matches: a match is finally adopted only if there is1914* no better match at the next window position.1915*/1916local block_state deflate_slow(deflate_state *s, int flush) {1917IPos hash_head; /* head of hash chain */1918int bflush; /* set if current block must be flushed */19191920/* Process the input block. */1921for (;;) {1922/* Make sure that we always have enough lookahead, except1923* at the end of the input file. We need MAX_MATCH bytes1924* for the next match, plus MIN_MATCH bytes to insert the1925* string following the next match.1926*/1927if (s->lookahead < MIN_LOOKAHEAD) {1928fill_window(s);1929if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {1930return need_more;1931}1932if (s->lookahead == 0) break; /* flush the current block */1933}19341935/* Insert the string window[strstart .. strstart + 2] in the1936* dictionary, and set hash_head to the head of the hash chain:1937*/1938hash_head = NIL;1939if (s->lookahead >= MIN_MATCH) {1940INSERT_STRING(s, s->strstart, hash_head);1941}19421943/* Find the longest match, discarding those <= prev_length.1944*/1945s->prev_length = s->match_length, s->prev_match = s->match_start;1946s->match_length = MIN_MATCH-1;19471948if (hash_head != NIL && s->prev_length < s->max_lazy_match &&1949s->strstart - hash_head <= MAX_DIST(s)) {1950/* To simplify the code, we prevent matches with the string1951* of window index 0 (in particular we have to avoid a match1952* of the string with itself at the start of the input file).1953*/1954s->match_length = longest_match (s, hash_head);1955/* longest_match() sets match_start */19561957if (s->match_length <= 5 && (s->strategy == Z_FILTERED1958#if TOO_FAR <= 327671959|| (s->match_length == MIN_MATCH &&1960s->strstart - s->match_start > TOO_FAR)1961#endif1962)) {19631964/* If prev_match is also MIN_MATCH, match_start is garbage1965* but we will ignore the current match anyway.1966*/1967s->match_length = MIN_MATCH-1;1968}1969}1970/* If there was a match at the previous step and the current1971* match is not better, output the previous match:1972*/1973if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {1974uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;1975/* Do not insert strings in hash table beyond this. */19761977check_match(s, s->strstart - 1, s->prev_match, s->prev_length);19781979_tr_tally_dist(s, s->strstart - 1 - s->prev_match,1980s->prev_length - MIN_MATCH, bflush);19811982/* Insert in hash table all strings up to the end of the match.1983* strstart - 1 and strstart are already inserted. If there is not1984* enough lookahead, the last two strings are not inserted in1985* the hash table.1986*/1987s->lookahead -= s->prev_length - 1;1988s->prev_length -= 2;1989do {1990if (++s->strstart <= max_insert) {1991INSERT_STRING(s, s->strstart, hash_head);1992}1993} while (--s->prev_length != 0);1994s->match_available = 0;1995s->match_length = MIN_MATCH-1;1996s->strstart++;19971998if (bflush) FLUSH_BLOCK(s, 0);19992000} else if (s->match_available) {2001/* If there was no match at the previous position, output a2002* single literal. If there was a match but the current match2003* is longer, truncate the previous match to a single literal.2004*/2005Tracevv((stderr,"%c", s->window[s->strstart - 1]));2006_tr_tally_lit(s, s->window[s->strstart - 1], bflush);2007if (bflush) {2008FLUSH_BLOCK_ONLY(s, 0);2009}2010s->strstart++;2011s->lookahead--;2012if (s->strm->avail_out == 0) return need_more;2013} else {2014/* There is no previous match to compare with, wait for2015* the next step to decide.2016*/2017s->match_available = 1;2018s->strstart++;2019s->lookahead--;2020}2021}2022Assert (flush != Z_NO_FLUSH, "no flush?");2023if (s->match_available) {2024Tracevv((stderr,"%c", s->window[s->strstart - 1]));2025_tr_tally_lit(s, s->window[s->strstart - 1], bflush);2026s->match_available = 0;2027}2028s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;2029if (flush == Z_FINISH) {2030FLUSH_BLOCK(s, 1);2031return finish_done;2032}2033if (s->sym_next)2034FLUSH_BLOCK(s, 0);2035return block_done;2036}2037#endif /* FASTEST */20382039/* ===========================================================================2040* For Z_RLE, simply look for runs of bytes, generate matches only of distance2041* one. Do not maintain a hash table. (It will be regenerated if this run of2042* deflate switches away from Z_RLE.)2043*/2044local block_state deflate_rle(deflate_state *s, int flush) {2045int bflush; /* set if current block must be flushed */2046uInt prev; /* byte at distance one to match */2047Bytef *scan, *strend; /* scan goes up to strend for length of run */20482049for (;;) {2050/* Make sure that we always have enough lookahead, except2051* at the end of the input file. We need MAX_MATCH bytes2052* for the longest run, plus one for the unrolled loop.2053*/2054if (s->lookahead <= MAX_MATCH) {2055fill_window(s);2056if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {2057return need_more;2058}2059if (s->lookahead == 0) break; /* flush the current block */2060}20612062/* See how many times the previous byte repeats */2063s->match_length = 0;2064if (s->lookahead >= MIN_MATCH && s->strstart > 0) {2065scan = s->window + s->strstart - 1;2066prev = *scan;2067if (prev == *++scan && prev == *++scan && prev == *++scan) {2068strend = s->window + s->strstart + MAX_MATCH;2069do {2070} while (prev == *++scan && prev == *++scan &&2071prev == *++scan && prev == *++scan &&2072prev == *++scan && prev == *++scan &&2073prev == *++scan && prev == *++scan &&2074scan < strend);2075s->match_length = MAX_MATCH - (uInt)(strend - scan);2076if (s->match_length > s->lookahead)2077s->match_length = s->lookahead;2078}2079Assert(scan <= s->window + (uInt)(s->window_size - 1),2080"wild scan");2081}20822083/* Emit match if have run of MIN_MATCH or longer, else emit literal */2084if (s->match_length >= MIN_MATCH) {2085check_match(s, s->strstart, s->strstart - 1, s->match_length);20862087_tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);20882089s->lookahead -= s->match_length;2090s->strstart += s->match_length;2091s->match_length = 0;2092} else {2093/* No match, output a literal byte */2094Tracevv((stderr,"%c", s->window[s->strstart]));2095_tr_tally_lit(s, s->window[s->strstart], bflush);2096s->lookahead--;2097s->strstart++;2098}2099if (bflush) FLUSH_BLOCK(s, 0);2100}2101s->insert = 0;2102if (flush == Z_FINISH) {2103FLUSH_BLOCK(s, 1);2104return finish_done;2105}2106if (s->sym_next)2107FLUSH_BLOCK(s, 0);2108return block_done;2109}21102111/* ===========================================================================2112* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.2113* (It will be regenerated if this run of deflate switches away from Huffman.)2114*/2115local block_state deflate_huff(deflate_state *s, int flush) {2116int bflush; /* set if current block must be flushed */21172118for (;;) {2119/* Make sure that we have a literal to write. */2120if (s->lookahead == 0) {2121fill_window(s);2122if (s->lookahead == 0) {2123if (flush == Z_NO_FLUSH)2124return need_more;2125break; /* flush the current block */2126}2127}21282129/* Output a literal byte */2130s->match_length = 0;2131Tracevv((stderr,"%c", s->window[s->strstart]));2132_tr_tally_lit(s, s->window[s->strstart], bflush);2133s->lookahead--;2134s->strstart++;2135if (bflush) FLUSH_BLOCK(s, 0);2136}2137s->insert = 0;2138if (flush == Z_FINISH) {2139FLUSH_BLOCK(s, 1);2140return finish_done;2141}2142if (s->sym_next)2143FLUSH_BLOCK(s, 0);2144return block_done;2145}214621472148