Path: blob/master/src/java.base/share/native/libzip/zlib/deflate.c
67760 views
/*1* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.2*3* This code is free software; you can redistribute it and/or modify it4* under the terms of the GNU General Public License version 2 only, as5* published by the Free Software Foundation. Oracle designates this6* particular file as subject to the "Classpath" exception as provided7* by Oracle in the LICENSE file that accompanied this code.8*9* This code is distributed in the hope that it will be useful, but WITHOUT10* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or11* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License12* version 2 for more details (a copy is included in the LICENSE file that13* accompanied this code).14*15* You should have received a copy of the GNU General Public License version16* 2 along with this work; if not, write to the Free Software Foundation,17* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.18*19* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA20* or visit www.oracle.com if you need additional information or have any21* questions.22*/2324/* deflate.c -- compress data using the deflation algorithm25* Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler26* For conditions of distribution and use, see copyright notice in zlib.h27*/2829/*30* ALGORITHM31*32* The "deflation" process depends on being able to identify portions33* of the input text which are identical to earlier input (within a34* sliding window trailing behind the input currently being processed).35*36* The most straightforward technique turns out to be the fastest for37* most input files: try all possible matches and select the longest.38* The key feature of this algorithm is that insertions into the string39* dictionary are very simple and thus fast, and deletions are avoided40* completely. Insertions are performed at each input character, whereas41* string matches are performed only when the previous match ends. So it42* is preferable to spend more time in matches to allow very fast string43* insertions and avoid deletions. The matching algorithm for small44* strings is inspired from that of Rabin & Karp. A brute force approach45* is used to find longer strings when a small match has been found.46* A similar algorithm is used in comic (by Jan-Mark Wams) and freeze47* (by Leonid Broukhis).48* A previous version of this file used a more sophisticated algorithm49* (by Fiala and Greene) which is guaranteed to run in linear amortized50* time, but has a larger average cost, uses more memory and is patented.51* However the F&G algorithm may be faster for some highly redundant52* files if the parameter max_chain_length (described below) is too large.53*54* ACKNOWLEDGEMENTS55*56* The idea of lazy evaluation of matches is due to Jan-Mark Wams, and57* I found it in 'freeze' written by Leonid Broukhis.58* Thanks to many people for bug reports and testing.59*60* REFERENCES61*62* Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".63* Available in http://tools.ietf.org/html/rfc195164*65* A description of the Rabin and Karp algorithm is given in the book66* "Algorithms" by R. Sedgewick, Addison-Wesley, p252.67*68* Fiala,E.R., and Greene,D.H.69* Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-59570*71*/7273/* @(#) $Id$ */7475#include "deflate.h"7677const char deflate_copyright[] =78" deflate 1.2.11 Copyright 1995-2017 Jean-loup Gailly and Mark Adler ";79/*80If you use the zlib library in a product, an acknowledgment is welcome81in the documentation of your product. If for some reason you cannot82include such an acknowledgment, I would appreciate that you keep this83copyright string in the executable of your product.84*/8586/* ===========================================================================87* Function prototypes.88*/89typedef enum {90need_more, /* block not completed, need more input or more output */91block_done, /* block flush performed */92finish_started, /* finish started, need only more output at next deflate */93finish_done /* finish done, accept no more input or output */94} block_state;9596typedef block_state (*compress_func) OF((deflate_state *s, int flush));97/* Compression function. Returns the block state after the call. */9899local int deflateStateCheck OF((z_streamp strm));100local void slide_hash OF((deflate_state *s));101local void fill_window OF((deflate_state *s));102local block_state deflate_stored OF((deflate_state *s, int flush));103local block_state deflate_fast OF((deflate_state *s, int flush));104#ifndef FASTEST105local block_state deflate_slow OF((deflate_state *s, int flush));106#endif107local block_state deflate_rle OF((deflate_state *s, int flush));108local block_state deflate_huff OF((deflate_state *s, int flush));109local void lm_init OF((deflate_state *s));110local void putShortMSB OF((deflate_state *s, uInt b));111local void flush_pending OF((z_streamp strm));112local unsigned read_buf OF((z_streamp strm, Bytef *buf, unsigned size));113#ifdef ASMV114# pragma message("Assembler code may have bugs -- use at your own risk")115void match_init OF((void)); /* asm code initialization */116uInt longest_match OF((deflate_state *s, IPos cur_match));117#else118local uInt longest_match OF((deflate_state *s, IPos cur_match));119#endif120121#ifdef ZLIB_DEBUG122local void check_match OF((deflate_state *s, IPos start, IPos match,123int length));124#endif125126/* ===========================================================================127* Local data128*/129130#define NIL 0131/* Tail of hash chains */132133#ifndef TOO_FAR134# define TOO_FAR 4096135#endif136/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */137138/* Values for max_lazy_match, good_match and max_chain_length, depending on139* the desired pack level (0..9). The values given below have been tuned to140* exclude worst case performance for pathological files. Better values may be141* found for specific files.142*/143typedef struct config_s {144ush good_length; /* reduce lazy search above this match length */145ush max_lazy; /* do not perform lazy search above this match length */146ush nice_length; /* quit search above this match length */147ush max_chain;148compress_func func;149} config;150151#ifdef FASTEST152local const config configuration_table[2] = {153/* good lazy nice chain */154/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */155/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */156#else157local const config configuration_table[10] = {158/* good lazy nice chain */159/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */160/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */161/* 2 */ {4, 5, 16, 8, deflate_fast},162/* 3 */ {4, 6, 32, 32, deflate_fast},163164/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */165/* 5 */ {8, 16, 32, 32, deflate_slow},166/* 6 */ {8, 16, 128, 128, deflate_slow},167/* 7 */ {8, 32, 128, 256, deflate_slow},168/* 8 */ {32, 128, 258, 1024, deflate_slow},169/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */170#endif171172/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4173* For deflate_fast() (levels <= 3) good is ignored and lazy has a different174* meaning.175*/176177/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */178#define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0))179180/* ===========================================================================181* Update a hash value with the given input byte182* IN assertion: all calls to UPDATE_HASH are made with consecutive input183* characters, so that a running hash key can be computed from the previous184* key instead of complete recalculation each time.185*/186#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)187188189/* ===========================================================================190* Insert string str in the dictionary and set match_head to the previous head191* of the hash chain (the most recent string with same hash key). Return192* the previous length of the hash chain.193* If this file is compiled with -DFASTEST, the compression level is forced194* to 1, and no hash chains are maintained.195* IN assertion: all calls to INSERT_STRING are made with consecutive input196* characters and the first MIN_MATCH bytes of str are valid (except for197* the last MIN_MATCH-1 bytes of the input file).198*/199#ifdef FASTEST200#define INSERT_STRING(s, str, match_head) \201(UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \202match_head = s->head[s->ins_h], \203s->head[s->ins_h] = (Pos)(str))204#else205#define INSERT_STRING(s, str, match_head) \206(UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \207match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \208s->head[s->ins_h] = (Pos)(str))209#endif210211/* ===========================================================================212* Initialize the hash table (avoiding 64K overflow for 16 bit systems).213* prev[] will be initialized on the fly.214*/215#define CLEAR_HASH(s) \216s->head[s->hash_size-1] = NIL; \217zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));218219/* ===========================================================================220* Slide the hash table when sliding the window down (could be avoided with 32221* bit values at the expense of memory usage). We slide even when level == 0 to222* keep the hash table consistent if we switch back to level > 0 later.223*/224local void slide_hash(s)225deflate_state *s;226{227unsigned n, m;228Posf *p;229uInt wsize = s->w_size;230231n = s->hash_size;232p = &s->head[n];233do {234m = *--p;235*p = (Pos)(m >= wsize ? m - wsize : NIL);236} while (--n);237n = wsize;238#ifndef FASTEST239p = &s->prev[n];240do {241m = *--p;242*p = (Pos)(m >= wsize ? m - wsize : NIL);243/* If n is not on any hash chain, prev[n] is garbage but244* its value will never be used.245*/246} while (--n);247#endif248}249250/* ========================================================================= */251int ZEXPORT deflateInit_(strm, level, version, stream_size)252z_streamp strm;253int level;254const char *version;255int stream_size;256{257return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,258Z_DEFAULT_STRATEGY, version, stream_size);259/* To do: ignore strm->next_in if we use it as window */260}261262/* ========================================================================= */263int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,264version, stream_size)265z_streamp strm;266int level;267int method;268int windowBits;269int memLevel;270int strategy;271const char *version;272int stream_size;273{274deflate_state *s;275int wrap = 1;276static const char my_version[] = ZLIB_VERSION;277278if (version == Z_NULL || version[0] != my_version[0] ||279stream_size != sizeof(z_stream)) {280return Z_VERSION_ERROR;281}282if (strm == Z_NULL) return Z_STREAM_ERROR;283284strm->msg = Z_NULL;285if (strm->zalloc == (alloc_func)0) {286#ifdef Z_SOLO287return Z_STREAM_ERROR;288#else289strm->zalloc = zcalloc;290strm->opaque = (voidpf)0;291#endif292}293if (strm->zfree == (free_func)0)294#ifdef Z_SOLO295return Z_STREAM_ERROR;296#else297strm->zfree = zcfree;298#endif299300#ifdef FASTEST301if (level != 0) level = 1;302#else303if (level == Z_DEFAULT_COMPRESSION) level = 6;304#endif305306if (windowBits < 0) { /* suppress zlib wrapper */307wrap = 0;308windowBits = -windowBits;309}310#ifdef GZIP311else if (windowBits > 15) {312wrap = 2; /* write gzip wrapper instead */313windowBits -= 16;314}315#endif316if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||317windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||318strategy < 0 || strategy > Z_FIXED || (windowBits == 8 && wrap != 1)) {319return Z_STREAM_ERROR;320}321if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */322s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));323if (s == Z_NULL) return Z_MEM_ERROR;324strm->state = (struct internal_state FAR *)s;325s->strm = strm;326s->status = INIT_STATE; /* to pass state test in deflateReset() */327328s->wrap = wrap;329s->gzhead = Z_NULL;330s->w_bits = (uInt)windowBits;331s->w_size = 1 << s->w_bits;332s->w_mask = s->w_size - 1;333334s->hash_bits = (uInt)memLevel + 7;335s->hash_size = 1 << s->hash_bits;336s->hash_mask = s->hash_size - 1;337s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);338339s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));340s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));341s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));342343s->high_water = 0; /* nothing written to s->window yet */344345s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */346347/* We overlay pending_buf and sym_buf. This works since the average size348* for length/distance pairs over any compressed block is assured to be 31349* bits or less.350*351* Analysis: The longest fixed codes are a length code of 8 bits plus 5352* extra bits, for lengths 131 to 257. The longest fixed distance codes are353* 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest354* possible fixed-codes length/distance pair is then 31 bits total.355*356* sym_buf starts one-fourth of the way into pending_buf. So there are357* three bytes in sym_buf for every four bytes in pending_buf. Each symbol358* in sym_buf is three bytes -- two for the distance and one for the359* literal/length. As each symbol is consumed, the pointer to the next360* sym_buf value to read moves forward three bytes. From that symbol, up to361* 31 bits are written to pending_buf. The closest the written pending_buf362* bits gets to the next sym_buf symbol to read is just before the last363* code is written. At that time, 31*(n-2) bits have been written, just364* after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at365* 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1366* symbols are written.) The closest the writing gets to what is unread is367* then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and368* can range from 128 to 32768.369*370* Therefore, at a minimum, there are 142 bits of space between what is371* written and what is read in the overlain buffers, so the symbols cannot372* be overwritten by the compressed data. That space is actually 139 bits,373* due to the three-bit fixed-code block header.374*375* That covers the case where either Z_FIXED is specified, forcing fixed376* codes, or when the use of fixed codes is chosen, because that choice377* results in a smaller compressed block than dynamic codes. That latter378* condition then assures that the above analysis also covers all dynamic379* blocks. A dynamic-code block will only be chosen to be emitted if it has380* fewer bits than a fixed-code block would for the same set of symbols.381* Therefore its average symbol length is assured to be less than 31. So382* the compressed data for a dynamic block also cannot overwrite the383* symbols from which it is being constructed.384*/385386s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, 4);387s->pending_buf_size = (ulg)s->lit_bufsize * 4;388389if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||390s->pending_buf == Z_NULL) {391s->status = FINISH_STATE;392strm->msg = ERR_MSG(Z_MEM_ERROR);393deflateEnd (strm);394return Z_MEM_ERROR;395}396s->sym_buf = s->pending_buf + s->lit_bufsize;397s->sym_end = (s->lit_bufsize - 1) * 3;398/* We avoid equality with lit_bufsize*3 because of wraparound at 64K399* on 16 bit machines and because stored blocks are restricted to400* 64K-1 bytes.401*/402403s->level = level;404s->strategy = strategy;405s->method = (Byte)method;406407return deflateReset(strm);408}409410/* =========================================================================411* Check for a valid deflate stream state. Return 0 if ok, 1 if not.412*/413local int deflateStateCheck (strm)414z_streamp strm;415{416deflate_state *s;417if (strm == Z_NULL ||418strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)419return 1;420s = strm->state;421if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE &&422#ifdef GZIP423s->status != GZIP_STATE &&424#endif425s->status != EXTRA_STATE &&426s->status != NAME_STATE &&427s->status != COMMENT_STATE &&428s->status != HCRC_STATE &&429s->status != BUSY_STATE &&430s->status != FINISH_STATE))431return 1;432return 0;433}434435/* ========================================================================= */436int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)437z_streamp strm;438const Bytef *dictionary;439uInt dictLength;440{441deflate_state *s;442uInt str, n;443int wrap;444unsigned avail;445z_const unsigned char *next;446447if (deflateStateCheck(strm) || dictionary == Z_NULL)448return Z_STREAM_ERROR;449s = strm->state;450wrap = s->wrap;451if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)452return Z_STREAM_ERROR;453454/* when using zlib wrappers, compute Adler-32 for provided dictionary */455if (wrap == 1)456strm->adler = adler32(strm->adler, dictionary, dictLength);457s->wrap = 0; /* avoid computing Adler-32 in read_buf */458459/* if dictionary would fill window, just replace the history */460if (dictLength >= s->w_size) {461if (wrap == 0) { /* already empty otherwise */462CLEAR_HASH(s);463s->strstart = 0;464s->block_start = 0L;465s->insert = 0;466}467dictionary += dictLength - s->w_size; /* use the tail */468dictLength = s->w_size;469}470471/* insert dictionary into window and hash */472avail = strm->avail_in;473next = strm->next_in;474strm->avail_in = dictLength;475strm->next_in = (z_const Bytef *)dictionary;476fill_window(s);477while (s->lookahead >= MIN_MATCH) {478str = s->strstart;479n = s->lookahead - (MIN_MATCH-1);480do {481UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);482#ifndef FASTEST483s->prev[str & s->w_mask] = s->head[s->ins_h];484#endif485s->head[s->ins_h] = (Pos)str;486str++;487} while (--n);488s->strstart = str;489s->lookahead = MIN_MATCH-1;490fill_window(s);491}492s->strstart += s->lookahead;493s->block_start = (long)s->strstart;494s->insert = s->lookahead;495s->lookahead = 0;496s->match_length = s->prev_length = MIN_MATCH-1;497s->match_available = 0;498strm->next_in = next;499strm->avail_in = avail;500s->wrap = wrap;501return Z_OK;502}503504/* ========================================================================= */505int ZEXPORT deflateGetDictionary (strm, dictionary, dictLength)506z_streamp strm;507Bytef *dictionary;508uInt *dictLength;509{510deflate_state *s;511uInt len;512513if (deflateStateCheck(strm))514return Z_STREAM_ERROR;515s = strm->state;516len = s->strstart + s->lookahead;517if (len > s->w_size)518len = s->w_size;519if (dictionary != Z_NULL && len)520zmemcpy(dictionary, s->window + s->strstart + s->lookahead - len, len);521if (dictLength != Z_NULL)522*dictLength = len;523return Z_OK;524}525526/* ========================================================================= */527int ZEXPORT deflateResetKeep (strm)528z_streamp strm;529{530deflate_state *s;531532if (deflateStateCheck(strm)) {533return Z_STREAM_ERROR;534}535536strm->total_in = strm->total_out = 0;537strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */538strm->data_type = Z_UNKNOWN;539540s = (deflate_state *)strm->state;541s->pending = 0;542s->pending_out = s->pending_buf;543544if (s->wrap < 0) {545s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */546}547s->status =548#ifdef GZIP549s->wrap == 2 ? GZIP_STATE :550#endif551s->wrap ? INIT_STATE : BUSY_STATE;552strm->adler =553#ifdef GZIP554s->wrap == 2 ? crc32(0L, Z_NULL, 0) :555#endif556adler32(0L, Z_NULL, 0);557s->last_flush = -2;558559_tr_init(s);560561return Z_OK;562}563564/* ========================================================================= */565int ZEXPORT deflateReset (strm)566z_streamp strm;567{568int ret;569570ret = deflateResetKeep(strm);571if (ret == Z_OK)572lm_init(strm->state);573return ret;574}575576/* ========================================================================= */577int ZEXPORT deflateSetHeader (strm, head)578z_streamp strm;579gz_headerp head;580{581if (deflateStateCheck(strm) || strm->state->wrap != 2)582return Z_STREAM_ERROR;583strm->state->gzhead = head;584return Z_OK;585}586587/* ========================================================================= */588int ZEXPORT deflatePending (strm, pending, bits)589unsigned *pending;590int *bits;591z_streamp strm;592{593if (deflateStateCheck(strm)) return Z_STREAM_ERROR;594if (pending != Z_NULL)595*pending = strm->state->pending;596if (bits != Z_NULL)597*bits = strm->state->bi_valid;598return Z_OK;599}600601/* ========================================================================= */602int ZEXPORT deflatePrime (strm, bits, value)603z_streamp strm;604int bits;605int value;606{607deflate_state *s;608int put;609610if (deflateStateCheck(strm)) return Z_STREAM_ERROR;611s = strm->state;612if (bits < 0 || bits > 16 ||613s->sym_buf < s->pending_out + ((Buf_size + 7) >> 3))614return Z_BUF_ERROR;615do {616put = Buf_size - s->bi_valid;617if (put > bits)618put = bits;619s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);620s->bi_valid += put;621_tr_flush_bits(s);622value >>= put;623bits -= put;624} while (bits);625return Z_OK;626}627628/* ========================================================================= */629int ZEXPORT deflateParams(strm, level, strategy)630z_streamp strm;631int level;632int strategy;633{634deflate_state *s;635compress_func func;636637if (deflateStateCheck(strm)) return Z_STREAM_ERROR;638s = strm->state;639640#ifdef FASTEST641if (level != 0) level = 1;642#else643if (level == Z_DEFAULT_COMPRESSION) level = 6;644#endif645if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {646return Z_STREAM_ERROR;647}648func = configuration_table[s->level].func;649650if ((strategy != s->strategy || func != configuration_table[level].func) &&651s->last_flush != -2) {652/* Flush the last buffer: */653int err = deflate(strm, Z_BLOCK);654if (err == Z_STREAM_ERROR)655return err;656if (strm->avail_out == 0)657return Z_BUF_ERROR;658}659if (s->level != level) {660if (s->level == 0 && s->matches != 0) {661if (s->matches == 1)662slide_hash(s);663else664CLEAR_HASH(s);665s->matches = 0;666}667s->level = level;668s->max_lazy_match = configuration_table[level].max_lazy;669s->good_match = configuration_table[level].good_length;670s->nice_match = configuration_table[level].nice_length;671s->max_chain_length = configuration_table[level].max_chain;672}673s->strategy = strategy;674return Z_OK;675}676677/* ========================================================================= */678int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)679z_streamp strm;680int good_length;681int max_lazy;682int nice_length;683int max_chain;684{685deflate_state *s;686687if (deflateStateCheck(strm)) return Z_STREAM_ERROR;688s = strm->state;689s->good_match = (uInt)good_length;690s->max_lazy_match = (uInt)max_lazy;691s->nice_match = nice_length;692s->max_chain_length = (uInt)max_chain;693return Z_OK;694}695696/* =========================================================================697* For the default windowBits of 15 and memLevel of 8, this function returns698* a close to exact, as well as small, upper bound on the compressed size.699* They are coded as constants here for a reason--if the #define's are700* changed, then this function needs to be changed as well. The return701* value for 15 and 8 only works for those exact settings.702*703* For any setting other than those defaults for windowBits and memLevel,704* the value returned is a conservative worst case for the maximum expansion705* resulting from using fixed blocks instead of stored blocks, which deflate706* can emit on compressed data for some combinations of the parameters.707*708* This function could be more sophisticated to provide closer upper bounds for709* every combination of windowBits and memLevel. But even the conservative710* upper bound of about 14% expansion does not seem onerous for output buffer711* allocation.712*/713uLong ZEXPORT deflateBound(strm, sourceLen)714z_streamp strm;715uLong sourceLen;716{717deflate_state *s;718uLong complen, wraplen;719720/* conservative upper bound for compressed data */721complen = sourceLen +722((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;723724/* if can't get parameters, return conservative bound plus zlib wrapper */725if (deflateStateCheck(strm))726return complen + 6;727728/* compute wrapper length */729s = strm->state;730switch (s->wrap) {731case 0: /* raw deflate */732wraplen = 0;733break;734case 1: /* zlib wrapper */735wraplen = 6 + (s->strstart ? 4 : 0);736break;737#ifdef GZIP738case 2: /* gzip wrapper */739wraplen = 18;740if (s->gzhead != Z_NULL) { /* user-supplied gzip header */741Bytef *str;742if (s->gzhead->extra != Z_NULL)743wraplen += 2 + s->gzhead->extra_len;744str = s->gzhead->name;745if (str != Z_NULL)746do {747wraplen++;748} while (*str++);749str = s->gzhead->comment;750if (str != Z_NULL)751do {752wraplen++;753} while (*str++);754if (s->gzhead->hcrc)755wraplen += 2;756}757break;758#endif759default: /* for compiler happiness */760wraplen = 6;761}762763/* if not default parameters, return conservative bound */764if (s->w_bits != 15 || s->hash_bits != 8 + 7)765return complen + wraplen;766767/* default settings: return tight bound for that case */768return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +769(sourceLen >> 25) + 13 - 6 + wraplen;770}771772/* =========================================================================773* Put a short in the pending buffer. The 16-bit value is put in MSB order.774* IN assertion: the stream state is correct and there is enough room in775* pending_buf.776*/777local void putShortMSB (s, b)778deflate_state *s;779uInt b;780{781put_byte(s, (Byte)(b >> 8));782put_byte(s, (Byte)(b & 0xff));783}784785/* =========================================================================786* Flush as much pending output as possible. All deflate() output, except for787* some deflate_stored() output, goes through this function so some788* applications may wish to modify it to avoid allocating a large789* strm->next_out buffer and copying into it. (See also read_buf()).790*/791local void flush_pending(strm)792z_streamp strm;793{794unsigned len;795deflate_state *s = strm->state;796797_tr_flush_bits(s);798len = s->pending;799if (len > strm->avail_out) len = strm->avail_out;800if (len == 0) return;801802zmemcpy(strm->next_out, s->pending_out, len);803strm->next_out += len;804s->pending_out += len;805strm->total_out += len;806strm->avail_out -= len;807s->pending -= len;808if (s->pending == 0) {809s->pending_out = s->pending_buf;810}811}812813/* ===========================================================================814* Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1].815*/816#define HCRC_UPDATE(beg) \817do { \818if (s->gzhead->hcrc && s->pending > (beg)) \819strm->adler = crc32(strm->adler, s->pending_buf + (beg), \820s->pending - (beg)); \821} while (0)822823/* ========================================================================= */824int ZEXPORT deflate (strm, flush)825z_streamp strm;826int flush;827{828int old_flush; /* value of flush param for previous deflate call */829deflate_state *s;830831if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) {832return Z_STREAM_ERROR;833}834s = strm->state;835836if (strm->next_out == Z_NULL ||837(strm->avail_in != 0 && strm->next_in == Z_NULL) ||838(s->status == FINISH_STATE && flush != Z_FINISH)) {839ERR_RETURN(strm, Z_STREAM_ERROR);840}841if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);842843old_flush = s->last_flush;844s->last_flush = flush;845846/* Flush as much pending output as possible */847if (s->pending != 0) {848flush_pending(strm);849if (strm->avail_out == 0) {850/* Since avail_out is 0, deflate will be called again with851* more output space, but possibly with both pending and852* avail_in equal to zero. There won't be anything to do,853* but this is not an error situation so make sure we854* return OK instead of BUF_ERROR at next call of deflate:855*/856s->last_flush = -1;857return Z_OK;858}859860/* Make sure there is something to do and avoid duplicate consecutive861* flushes. For repeated and useless calls with Z_FINISH, we keep862* returning Z_STREAM_END instead of Z_BUF_ERROR.863*/864} else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&865flush != Z_FINISH) {866ERR_RETURN(strm, Z_BUF_ERROR);867}868869/* User must not provide more input after the first FINISH: */870if (s->status == FINISH_STATE && strm->avail_in != 0) {871ERR_RETURN(strm, Z_BUF_ERROR);872}873874/* Write the header */875if (s->status == INIT_STATE) {876/* zlib header */877uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;878uInt level_flags;879880if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)881level_flags = 0;882else if (s->level < 6)883level_flags = 1;884else if (s->level == 6)885level_flags = 2;886else887level_flags = 3;888header |= (level_flags << 6);889if (s->strstart != 0) header |= PRESET_DICT;890header += 31 - (header % 31);891892putShortMSB(s, header);893894/* Save the adler32 of the preset dictionary: */895if (s->strstart != 0) {896putShortMSB(s, (uInt)(strm->adler >> 16));897putShortMSB(s, (uInt)(strm->adler & 0xffff));898}899strm->adler = adler32(0L, Z_NULL, 0);900s->status = BUSY_STATE;901902/* Compression must start with an empty pending buffer */903flush_pending(strm);904if (s->pending != 0) {905s->last_flush = -1;906return Z_OK;907}908}909#ifdef GZIP910if (s->status == GZIP_STATE) {911/* gzip header */912strm->adler = crc32(0L, Z_NULL, 0);913put_byte(s, 31);914put_byte(s, 139);915put_byte(s, 8);916if (s->gzhead == Z_NULL) {917put_byte(s, 0);918put_byte(s, 0);919put_byte(s, 0);920put_byte(s, 0);921put_byte(s, 0);922put_byte(s, s->level == 9 ? 2 :923(s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?9244 : 0));925put_byte(s, OS_CODE);926s->status = BUSY_STATE;927928/* Compression must start with an empty pending buffer */929flush_pending(strm);930if (s->pending != 0) {931s->last_flush = -1;932return Z_OK;933}934}935else {936put_byte(s, (s->gzhead->text ? 1 : 0) +937(s->gzhead->hcrc ? 2 : 0) +938(s->gzhead->extra == Z_NULL ? 0 : 4) +939(s->gzhead->name == Z_NULL ? 0 : 8) +940(s->gzhead->comment == Z_NULL ? 0 : 16)941);942put_byte(s, (Byte)(s->gzhead->time & 0xff));943put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));944put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));945put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));946put_byte(s, s->level == 9 ? 2 :947(s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?9484 : 0));949put_byte(s, s->gzhead->os & 0xff);950if (s->gzhead->extra != Z_NULL) {951put_byte(s, s->gzhead->extra_len & 0xff);952put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);953}954if (s->gzhead->hcrc)955strm->adler = crc32(strm->adler, s->pending_buf,956s->pending);957s->gzindex = 0;958s->status = EXTRA_STATE;959}960}961if (s->status == EXTRA_STATE) {962if (s->gzhead->extra != Z_NULL) {963ulg beg = s->pending; /* start of bytes to update crc */964uInt left = (s->gzhead->extra_len & 0xffff) - s->gzindex;965while (s->pending + left > s->pending_buf_size) {966uInt copy = s->pending_buf_size - s->pending;967zmemcpy(s->pending_buf + s->pending,968s->gzhead->extra + s->gzindex, copy);969s->pending = s->pending_buf_size;970HCRC_UPDATE(beg);971s->gzindex += copy;972flush_pending(strm);973if (s->pending != 0) {974s->last_flush = -1;975return Z_OK;976}977beg = 0;978left -= copy;979}980zmemcpy(s->pending_buf + s->pending,981s->gzhead->extra + s->gzindex, left);982s->pending += left;983HCRC_UPDATE(beg);984s->gzindex = 0;985}986s->status = NAME_STATE;987}988if (s->status == NAME_STATE) {989if (s->gzhead->name != Z_NULL) {990ulg beg = s->pending; /* start of bytes to update crc */991int val;992do {993if (s->pending == s->pending_buf_size) {994HCRC_UPDATE(beg);995flush_pending(strm);996if (s->pending != 0) {997s->last_flush = -1;998return Z_OK;999}1000beg = 0;1001}1002val = s->gzhead->name[s->gzindex++];1003put_byte(s, val);1004} while (val != 0);1005HCRC_UPDATE(beg);1006s->gzindex = 0;1007}1008s->status = COMMENT_STATE;1009}1010if (s->status == COMMENT_STATE) {1011if (s->gzhead->comment != Z_NULL) {1012ulg beg = s->pending; /* start of bytes to update crc */1013int val;1014do {1015if (s->pending == s->pending_buf_size) {1016HCRC_UPDATE(beg);1017flush_pending(strm);1018if (s->pending != 0) {1019s->last_flush = -1;1020return Z_OK;1021}1022beg = 0;1023}1024val = s->gzhead->comment[s->gzindex++];1025put_byte(s, val);1026} while (val != 0);1027HCRC_UPDATE(beg);1028}1029s->status = HCRC_STATE;1030}1031if (s->status == HCRC_STATE) {1032if (s->gzhead->hcrc) {1033if (s->pending + 2 > s->pending_buf_size) {1034flush_pending(strm);1035if (s->pending != 0) {1036s->last_flush = -1;1037return Z_OK;1038}1039}1040put_byte(s, (Byte)(strm->adler & 0xff));1041put_byte(s, (Byte)((strm->adler >> 8) & 0xff));1042strm->adler = crc32(0L, Z_NULL, 0);1043}1044s->status = BUSY_STATE;10451046/* Compression must start with an empty pending buffer */1047flush_pending(strm);1048if (s->pending != 0) {1049s->last_flush = -1;1050return Z_OK;1051}1052}1053#endif10541055/* Start a new block or continue the current one.1056*/1057if (strm->avail_in != 0 || s->lookahead != 0 ||1058(flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {1059block_state bstate;10601061bstate = s->level == 0 ? deflate_stored(s, flush) :1062s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :1063s->strategy == Z_RLE ? deflate_rle(s, flush) :1064(*(configuration_table[s->level].func))(s, flush);10651066if (bstate == finish_started || bstate == finish_done) {1067s->status = FINISH_STATE;1068}1069if (bstate == need_more || bstate == finish_started) {1070if (strm->avail_out == 0) {1071s->last_flush = -1; /* avoid BUF_ERROR next call, see above */1072}1073return Z_OK;1074/* If flush != Z_NO_FLUSH && avail_out == 0, the next call1075* of deflate should use the same flush parameter to make sure1076* that the flush is complete. So we don't have to output an1077* empty block here, this will be done at next call. This also1078* ensures that for a very small output buffer, we emit at most1079* one empty block.1080*/1081}1082if (bstate == block_done) {1083if (flush == Z_PARTIAL_FLUSH) {1084_tr_align(s);1085} else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */1086_tr_stored_block(s, (char*)0, 0L, 0);1087/* For a full flush, this empty block will be recognized1088* as a special marker by inflate_sync().1089*/1090if (flush == Z_FULL_FLUSH) {1091CLEAR_HASH(s); /* forget history */1092if (s->lookahead == 0) {1093s->strstart = 0;1094s->block_start = 0L;1095s->insert = 0;1096}1097}1098}1099flush_pending(strm);1100if (strm->avail_out == 0) {1101s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */1102return Z_OK;1103}1104}1105}11061107if (flush != Z_FINISH) return Z_OK;1108if (s->wrap <= 0) return Z_STREAM_END;11091110/* Write the trailer */1111#ifdef GZIP1112if (s->wrap == 2) {1113put_byte(s, (Byte)(strm->adler & 0xff));1114put_byte(s, (Byte)((strm->adler >> 8) & 0xff));1115put_byte(s, (Byte)((strm->adler >> 16) & 0xff));1116put_byte(s, (Byte)((strm->adler >> 24) & 0xff));1117put_byte(s, (Byte)(strm->total_in & 0xff));1118put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));1119put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));1120put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));1121}1122else1123#endif1124{1125putShortMSB(s, (uInt)(strm->adler >> 16));1126putShortMSB(s, (uInt)(strm->adler & 0xffff));1127}1128flush_pending(strm);1129/* If avail_out is zero, the application will call deflate again1130* to flush the rest.1131*/1132if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */1133return s->pending != 0 ? Z_OK : Z_STREAM_END;1134}11351136/* ========================================================================= */1137int ZEXPORT deflateEnd (strm)1138z_streamp strm;1139{1140int status;11411142if (deflateStateCheck(strm)) return Z_STREAM_ERROR;11431144status = strm->state->status;11451146/* Deallocate in reverse order of allocations: */1147TRY_FREE(strm, strm->state->pending_buf);1148TRY_FREE(strm, strm->state->head);1149TRY_FREE(strm, strm->state->prev);1150TRY_FREE(strm, strm->state->window);11511152ZFREE(strm, strm->state);1153strm->state = Z_NULL;11541155return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;1156}11571158/* =========================================================================1159* Copy the source state to the destination state.1160* To simplify the source, this is not supported for 16-bit MSDOS (which1161* doesn't have enough memory anyway to duplicate compression states).1162*/1163int ZEXPORT deflateCopy (dest, source)1164z_streamp dest;1165z_streamp source;1166{1167#ifdef MAXSEG_64K1168return Z_STREAM_ERROR;1169#else1170deflate_state *ds;1171deflate_state *ss;117211731174if (deflateStateCheck(source) || dest == Z_NULL) {1175return Z_STREAM_ERROR;1176}11771178ss = source->state;11791180zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));11811182ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));1183if (ds == Z_NULL) return Z_MEM_ERROR;1184dest->state = (struct internal_state FAR *) ds;1185zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));1186ds->strm = dest;11871188ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));1189ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));1190ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));1191ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, 4);11921193if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||1194ds->pending_buf == Z_NULL) {1195deflateEnd (dest);1196return Z_MEM_ERROR;1197}1198/* following zmemcpy do not work for 16-bit MSDOS */1199zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));1200zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));1201zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));1202zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);12031204ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);1205ds->sym_buf = ds->pending_buf + ds->lit_bufsize;12061207ds->l_desc.dyn_tree = ds->dyn_ltree;1208ds->d_desc.dyn_tree = ds->dyn_dtree;1209ds->bl_desc.dyn_tree = ds->bl_tree;12101211return Z_OK;1212#endif /* MAXSEG_64K */1213}12141215/* ===========================================================================1216* Read a new buffer from the current input stream, update the adler321217* and total number of bytes read. All deflate() input goes through1218* this function so some applications may wish to modify it to avoid1219* allocating a large strm->next_in buffer and copying from it.1220* (See also flush_pending()).1221*/1222local unsigned read_buf(strm, buf, size)1223z_streamp strm;1224Bytef *buf;1225unsigned size;1226{1227unsigned len = strm->avail_in;12281229if (len > size) len = size;1230if (len == 0) return 0;12311232strm->avail_in -= len;12331234zmemcpy(buf, strm->next_in, len);1235if (strm->state->wrap == 1) {1236strm->adler = adler32(strm->adler, buf, len);1237}1238#ifdef GZIP1239else if (strm->state->wrap == 2) {1240strm->adler = crc32(strm->adler, buf, len);1241}1242#endif1243strm->next_in += len;1244strm->total_in += len;12451246return len;1247}12481249/* ===========================================================================1250* Initialize the "longest match" routines for a new zlib stream1251*/1252local void lm_init (s)1253deflate_state *s;1254{1255s->window_size = (ulg)2L*s->w_size;12561257CLEAR_HASH(s);12581259/* Set the default configuration parameters:1260*/1261s->max_lazy_match = configuration_table[s->level].max_lazy;1262s->good_match = configuration_table[s->level].good_length;1263s->nice_match = configuration_table[s->level].nice_length;1264s->max_chain_length = configuration_table[s->level].max_chain;12651266s->strstart = 0;1267s->block_start = 0L;1268s->lookahead = 0;1269s->insert = 0;1270s->match_length = s->prev_length = MIN_MATCH-1;1271s->match_available = 0;1272s->ins_h = 0;1273#ifndef FASTEST1274#ifdef ASMV1275match_init(); /* initialize the asm code */1276#endif1277#endif1278}12791280#ifndef FASTEST1281/* ===========================================================================1282* Set match_start to the longest match starting at the given string and1283* return its length. Matches shorter or equal to prev_length are discarded,1284* in which case the result is equal to prev_length and match_start is1285* garbage.1286* IN assertions: cur_match is the head of the hash chain for the current1287* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 11288* OUT assertion: the match length is not greater than s->lookahead.1289*/1290#ifndef ASMV1291/* For 80x86 and 680x0, an optimized version will be provided in match.asm or1292* match.S. The code will be functionally equivalent.1293*/1294local uInt longest_match(s, cur_match)1295deflate_state *s;1296IPos cur_match; /* current match */1297{1298unsigned chain_length = s->max_chain_length;/* max hash chain length */1299register Bytef *scan = s->window + s->strstart; /* current string */1300register Bytef *match; /* matched string */1301register int len; /* length of current match */1302int best_len = (int)s->prev_length; /* best match length so far */1303int nice_match = s->nice_match; /* stop if match long enough */1304IPos limit = s->strstart > (IPos)MAX_DIST(s) ?1305s->strstart - (IPos)MAX_DIST(s) : NIL;1306/* Stop when cur_match becomes <= limit. To simplify the code,1307* we prevent matches with the string of window index 0.1308*/1309Posf *prev = s->prev;1310uInt wmask = s->w_mask;13111312#ifdef UNALIGNED_OK1313/* Compare two bytes at a time. Note: this is not always beneficial.1314* Try with and without -DUNALIGNED_OK to check.1315*/1316register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;1317register ush scan_start = *(ushf*)scan;1318register ush scan_end = *(ushf*)(scan+best_len-1);1319#else1320register Bytef *strend = s->window + s->strstart + MAX_MATCH;1321register Byte scan_end1 = scan[best_len-1];1322register Byte scan_end = scan[best_len];1323#endif13241325/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.1326* It is easy to get rid of this optimization if necessary.1327*/1328Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");13291330/* Do not waste too much time if we already have a good match: */1331if (s->prev_length >= s->good_match) {1332chain_length >>= 2;1333}1334/* Do not look for matches beyond the end of the input. This is necessary1335* to make deflate deterministic.1336*/1337if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead;13381339Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");13401341do {1342Assert(cur_match < s->strstart, "no future");1343match = s->window + cur_match;13441345/* Skip to next match if the match length cannot increase1346* or if the match length is less than 2. Note that the checks below1347* for insufficient lookahead only occur occasionally for performance1348* reasons. Therefore uninitialized memory will be accessed, and1349* conditional jumps will be made that depend on those values.1350* However the length of the match is limited to the lookahead, so1351* the output of deflate is not affected by the uninitialized values.1352*/1353#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)1354/* This code assumes sizeof(unsigned short) == 2. Do not use1355* UNALIGNED_OK if your compiler uses a different size.1356*/1357if (*(ushf*)(match+best_len-1) != scan_end ||1358*(ushf*)match != scan_start) continue;13591360/* It is not necessary to compare scan[2] and match[2] since they are1361* always equal when the other bytes match, given that the hash keys1362* are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at1363* strstart+3, +5, ... up to strstart+257. We check for insufficient1364* lookahead only every 4th comparison; the 128th check will be made1365* at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is1366* necessary to put more guard bytes at the end of the window, or1367* to check more often for insufficient lookahead.1368*/1369Assert(scan[2] == match[2], "scan[2]?");1370scan++, match++;1371do {1372} while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&1373*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&1374*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&1375*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&1376scan < strend);1377/* The funny "do {}" generates better code on most compilers */13781379/* Here, scan <= window+strstart+257 */1380Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");1381if (*scan == *match) scan++;13821383len = (MAX_MATCH - 1) - (int)(strend-scan);1384scan = strend - (MAX_MATCH-1);13851386#else /* UNALIGNED_OK */13871388if (match[best_len] != scan_end ||1389match[best_len-1] != scan_end1 ||1390*match != *scan ||1391*++match != scan[1]) continue;13921393/* The check at best_len-1 can be removed because it will be made1394* again later. (This heuristic is not always a win.)1395* It is not necessary to compare scan[2] and match[2] since they1396* are always equal when the other bytes match, given that1397* the hash keys are equal and that HASH_BITS >= 8.1398*/1399scan += 2, match++;1400Assert(*scan == *match, "match[2]?");14011402/* We check for insufficient lookahead only every 8th comparison;1403* the 256th check will be made at strstart+258.1404*/1405do {1406} while (*++scan == *++match && *++scan == *++match &&1407*++scan == *++match && *++scan == *++match &&1408*++scan == *++match && *++scan == *++match &&1409*++scan == *++match && *++scan == *++match &&1410scan < strend);14111412Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");14131414len = MAX_MATCH - (int)(strend - scan);1415scan = strend - MAX_MATCH;14161417#endif /* UNALIGNED_OK */14181419if (len > best_len) {1420s->match_start = cur_match;1421best_len = len;1422if (len >= nice_match) break;1423#ifdef UNALIGNED_OK1424scan_end = *(ushf*)(scan+best_len-1);1425#else1426scan_end1 = scan[best_len-1];1427scan_end = scan[best_len];1428#endif1429}1430} while ((cur_match = prev[cur_match & wmask]) > limit1431&& --chain_length != 0);14321433if ((uInt)best_len <= s->lookahead) return (uInt)best_len;1434return s->lookahead;1435}1436#endif /* ASMV */14371438#else /* FASTEST */14391440/* ---------------------------------------------------------------------------1441* Optimized version for FASTEST only1442*/1443local uInt longest_match(s, cur_match)1444deflate_state *s;1445IPos cur_match; /* current match */1446{1447register Bytef *scan = s->window + s->strstart; /* current string */1448register Bytef *match; /* matched string */1449register int len; /* length of current match */1450register Bytef *strend = s->window + s->strstart + MAX_MATCH;14511452/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.1453* It is easy to get rid of this optimization if necessary.1454*/1455Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");14561457Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");14581459Assert(cur_match < s->strstart, "no future");14601461match = s->window + cur_match;14621463/* Return failure if the match length is less than 2:1464*/1465if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;14661467/* The check at best_len-1 can be removed because it will be made1468* again later. (This heuristic is not always a win.)1469* It is not necessary to compare scan[2] and match[2] since they1470* are always equal when the other bytes match, given that1471* the hash keys are equal and that HASH_BITS >= 8.1472*/1473scan += 2, match += 2;1474Assert(*scan == *match, "match[2]?");14751476/* We check for insufficient lookahead only every 8th comparison;1477* the 256th check will be made at strstart+258.1478*/1479do {1480} while (*++scan == *++match && *++scan == *++match &&1481*++scan == *++match && *++scan == *++match &&1482*++scan == *++match && *++scan == *++match &&1483*++scan == *++match && *++scan == *++match &&1484scan < strend);14851486Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");14871488len = MAX_MATCH - (int)(strend - scan);14891490if (len < MIN_MATCH) return MIN_MATCH - 1;14911492s->match_start = cur_match;1493return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;1494}14951496#endif /* FASTEST */14971498#ifdef ZLIB_DEBUG14991500#define EQUAL 01501/* result of memcmp for equal strings */15021503/* ===========================================================================1504* Check that the match at match_start is indeed a match.1505*/1506local void check_match(s, start, match, length)1507deflate_state *s;1508IPos start, match;1509int length;1510{1511/* check that the match is indeed a match */1512if (zmemcmp(s->window + match,1513s->window + start, length) != EQUAL) {1514fprintf(stderr, " start %u, match %u, length %d\n",1515start, match, length);1516do {1517fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);1518} while (--length != 0);1519z_error("invalid match");1520}1521if (z_verbose > 1) {1522fprintf(stderr,"\\[%d,%d]", start-match, length);1523do { putc(s->window[start++], stderr); } while (--length != 0);1524}1525}1526#else1527# define check_match(s, start, match, length)1528#endif /* ZLIB_DEBUG */15291530/* ===========================================================================1531* Fill the window when the lookahead becomes insufficient.1532* Updates strstart and lookahead.1533*1534* IN assertion: lookahead < MIN_LOOKAHEAD1535* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD1536* At least one byte has been read, or avail_in == 0; reads are1537* performed for at least two bytes (required for the zip translate_eol1538* option -- not supported here).1539*/1540local void fill_window(s)1541deflate_state *s;1542{1543unsigned n;1544unsigned more; /* Amount of free space at the end of the window. */1545uInt wsize = s->w_size;15461547Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");15481549do {1550more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);15511552/* Deal with !@#$% 64K limit: */1553if (sizeof(int) <= 2) {1554if (more == 0 && s->strstart == 0 && s->lookahead == 0) {1555more = wsize;15561557} else if (more == (unsigned)(-1)) {1558/* Very unlikely, but possible on 16 bit machine if1559* strstart == 0 && lookahead == 1 (input done a byte at time)1560*/1561more--;1562}1563}15641565/* If the window is almost full and there is insufficient lookahead,1566* move the upper half to the lower one to make room in the upper half.1567*/1568if (s->strstart >= wsize+MAX_DIST(s)) {15691570zmemcpy(s->window, s->window+wsize, (unsigned)wsize - more);1571s->match_start -= wsize;1572s->strstart -= wsize; /* we now have strstart >= MAX_DIST */1573s->block_start -= (long) wsize;1574slide_hash(s);1575more += wsize;1576}1577if (s->strm->avail_in == 0) break;15781579/* If there was no sliding:1580* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&1581* more == window_size - lookahead - strstart1582* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)1583* => more >= window_size - 2*WSIZE + 21584* In the BIG_MEM or MMAP case (not yet supported),1585* window_size == input_size + MIN_LOOKAHEAD &&1586* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.1587* Otherwise, window_size == 2*WSIZE so more >= 2.1588* If there was sliding, more >= WSIZE. So in all cases, more >= 2.1589*/1590Assert(more >= 2, "more < 2");15911592n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);1593s->lookahead += n;15941595/* Initialize the hash value now that we have some input: */1596if (s->lookahead + s->insert >= MIN_MATCH) {1597uInt str = s->strstart - s->insert;1598s->ins_h = s->window[str];1599UPDATE_HASH(s, s->ins_h, s->window[str + 1]);1600#if MIN_MATCH != 31601Call UPDATE_HASH() MIN_MATCH-3 more times1602#endif1603while (s->insert) {1604UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);1605#ifndef FASTEST1606s->prev[str & s->w_mask] = s->head[s->ins_h];1607#endif1608s->head[s->ins_h] = (Pos)str;1609str++;1610s->insert--;1611if (s->lookahead + s->insert < MIN_MATCH)1612break;1613}1614}1615/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,1616* but this is not important since only literal bytes will be emitted.1617*/16181619} while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);16201621/* If the WIN_INIT bytes after the end of the current data have never been1622* written, then zero those bytes in order to avoid memory check reports of1623* the use of uninitialized (or uninitialised as Julian writes) bytes by1624* the longest match routines. Update the high water mark for the next1625* time through here. WIN_INIT is set to MAX_MATCH since the longest match1626* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.1627*/1628if (s->high_water < s->window_size) {1629ulg curr = s->strstart + (ulg)(s->lookahead);1630ulg init;16311632if (s->high_water < curr) {1633/* Previous high water mark below current data -- zero WIN_INIT1634* bytes or up to end of window, whichever is less.1635*/1636init = s->window_size - curr;1637if (init > WIN_INIT)1638init = WIN_INIT;1639zmemzero(s->window + curr, (unsigned)init);1640s->high_water = curr + init;1641}1642else if (s->high_water < (ulg)curr + WIN_INIT) {1643/* High water mark at or above current data, but below current data1644* plus WIN_INIT -- zero out to current data plus WIN_INIT, or up1645* to end of window, whichever is less.1646*/1647init = (ulg)curr + WIN_INIT - s->high_water;1648if (init > s->window_size - s->high_water)1649init = s->window_size - s->high_water;1650zmemzero(s->window + s->high_water, (unsigned)init);1651s->high_water += init;1652}1653}16541655Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,1656"not enough room for search");1657}16581659/* ===========================================================================1660* Flush the current block, with given end-of-file flag.1661* IN assertion: strstart is set to the end of the current match.1662*/1663#define FLUSH_BLOCK_ONLY(s, last) { \1664_tr_flush_block(s, (s->block_start >= 0L ? \1665(charf *)&s->window[(unsigned)s->block_start] : \1666(charf *)Z_NULL), \1667(ulg)((long)s->strstart - s->block_start), \1668(last)); \1669s->block_start = s->strstart; \1670flush_pending(s->strm); \1671Tracev((stderr,"[FLUSH]")); \1672}16731674/* Same but force premature exit if necessary. */1675#define FLUSH_BLOCK(s, last) { \1676FLUSH_BLOCK_ONLY(s, last); \1677if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \1678}16791680/* Maximum stored block length in deflate format (not including header). */1681#define MAX_STORED 6553516821683/* Minimum of a and b. */1684#define MIN(a, b) ((a) > (b) ? (b) : (a))16851686/* ===========================================================================1687* Copy without compression as much as possible from the input stream, return1688* the current block state.1689*1690* In case deflateParams() is used to later switch to a non-zero compression1691* level, s->matches (otherwise unused when storing) keeps track of the number1692* of hash table slides to perform. If s->matches is 1, then one hash table1693* slide will be done when switching. If s->matches is 2, the maximum value1694* allowed here, then the hash table will be cleared, since two or more slides1695* is the same as a clear.1696*1697* deflate_stored() is written to minimize the number of times an input byte is1698* copied. It is most efficient with large input and output buffers, which1699* maximizes the opportunites to have a single copy from next_in to next_out.1700*/1701local block_state deflate_stored(s, flush)1702deflate_state *s;1703int flush;1704{1705/* Smallest worthy block size when not flushing or finishing. By default1706* this is 32K. This can be as small as 507 bytes for memLevel == 1. For1707* large input and output buffers, the stored block size will be larger.1708*/1709unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size);17101711/* Copy as many min_block or larger stored blocks directly to next_out as1712* possible. If flushing, copy the remaining available input to next_out as1713* stored blocks, if there is enough space.1714*/1715unsigned len, left, have, last = 0;1716unsigned used = s->strm->avail_in;1717do {1718/* Set len to the maximum size block that we can copy directly with the1719* available input data and output space. Set left to how much of that1720* would be copied from what's left in the window.1721*/1722len = MAX_STORED; /* maximum deflate stored block length */1723have = (s->bi_valid + 42) >> 3; /* number of header bytes */1724if (s->strm->avail_out < have) /* need room for header */1725break;1726/* maximum stored block length that will fit in avail_out: */1727have = s->strm->avail_out - have;1728left = s->strstart - s->block_start; /* bytes left in window */1729if (len > (ulg)left + s->strm->avail_in)1730len = left + s->strm->avail_in; /* limit len to the input */1731if (len > have)1732len = have; /* limit len to the output */17331734/* If the stored block would be less than min_block in length, or if1735* unable to copy all of the available input when flushing, then try1736* copying to the window and the pending buffer instead. Also don't1737* write an empty block when flushing -- deflate() does that.1738*/1739if (len < min_block && ((len == 0 && flush != Z_FINISH) ||1740flush == Z_NO_FLUSH ||1741len != left + s->strm->avail_in))1742break;17431744/* Make a dummy stored block in pending to get the header bytes,1745* including any pending bits. This also updates the debugging counts.1746*/1747last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0;1748_tr_stored_block(s, (char *)0, 0L, last);17491750/* Replace the lengths in the dummy stored block with len. */1751s->pending_buf[s->pending - 4] = len;1752s->pending_buf[s->pending - 3] = len >> 8;1753s->pending_buf[s->pending - 2] = ~len;1754s->pending_buf[s->pending - 1] = ~len >> 8;17551756/* Write the stored block header bytes. */1757flush_pending(s->strm);17581759#ifdef ZLIB_DEBUG1760/* Update debugging counts for the data about to be copied. */1761s->compressed_len += len << 3;1762s->bits_sent += len << 3;1763#endif17641765/* Copy uncompressed bytes from the window to next_out. */1766if (left) {1767if (left > len)1768left = len;1769zmemcpy(s->strm->next_out, s->window + s->block_start, left);1770s->strm->next_out += left;1771s->strm->avail_out -= left;1772s->strm->total_out += left;1773s->block_start += left;1774len -= left;1775}17761777/* Copy uncompressed bytes directly from next_in to next_out, updating1778* the check value.1779*/1780if (len) {1781read_buf(s->strm, s->strm->next_out, len);1782s->strm->next_out += len;1783s->strm->avail_out -= len;1784s->strm->total_out += len;1785}1786} while (last == 0);17871788/* Update the sliding window with the last s->w_size bytes of the copied1789* data, or append all of the copied data to the existing window if less1790* than s->w_size bytes were copied. Also update the number of bytes to1791* insert in the hash tables, in the event that deflateParams() switches to1792* a non-zero compression level.1793*/1794used -= s->strm->avail_in; /* number of input bytes directly copied */1795if (used) {1796/* If any input was used, then no unused input remains in the window,1797* therefore s->block_start == s->strstart.1798*/1799if (used >= s->w_size) { /* supplant the previous history */1800s->matches = 2; /* clear hash */1801zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);1802s->strstart = s->w_size;1803}1804else {1805if (s->window_size - s->strstart <= used) {1806/* Slide the window down. */1807s->strstart -= s->w_size;1808zmemcpy(s->window, s->window + s->w_size, s->strstart);1809if (s->matches < 2)1810s->matches++; /* add a pending slide_hash() */1811}1812zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);1813s->strstart += used;1814}1815s->block_start = s->strstart;1816s->insert += MIN(used, s->w_size - s->insert);1817}1818if (s->high_water < s->strstart)1819s->high_water = s->strstart;18201821/* If the last block was written to next_out, then done. */1822if (last)1823return finish_done;18241825/* If flushing and all input has been consumed, then done. */1826if (flush != Z_NO_FLUSH && flush != Z_FINISH &&1827s->strm->avail_in == 0 && (long)s->strstart == s->block_start)1828return block_done;18291830/* Fill the window with any remaining input. */1831have = s->window_size - s->strstart - 1;1832if (s->strm->avail_in > have && s->block_start >= (long)s->w_size) {1833/* Slide the window down. */1834s->block_start -= s->w_size;1835s->strstart -= s->w_size;1836zmemcpy(s->window, s->window + s->w_size, s->strstart);1837if (s->matches < 2)1838s->matches++; /* add a pending slide_hash() */1839have += s->w_size; /* more space now */1840}1841if (have > s->strm->avail_in)1842have = s->strm->avail_in;1843if (have) {1844read_buf(s->strm, s->window + s->strstart, have);1845s->strstart += have;1846}1847if (s->high_water < s->strstart)1848s->high_water = s->strstart;18491850/* There was not enough avail_out to write a complete worthy or flushed1851* stored block to next_out. Write a stored block to pending instead, if we1852* have enough input for a worthy block, or if flushing and there is enough1853* room for the remaining input as a stored block in the pending buffer.1854*/1855have = (s->bi_valid + 42) >> 3; /* number of header bytes */1856/* maximum stored block length that will fit in pending: */1857have = MIN(s->pending_buf_size - have, MAX_STORED);1858min_block = MIN(have, s->w_size);1859left = s->strstart - s->block_start;1860if (left >= min_block ||1861((left || flush == Z_FINISH) && flush != Z_NO_FLUSH &&1862s->strm->avail_in == 0 && left <= have)) {1863len = MIN(left, have);1864last = flush == Z_FINISH && s->strm->avail_in == 0 &&1865len == left ? 1 : 0;1866_tr_stored_block(s, (charf *)s->window + s->block_start, len, last);1867s->block_start += len;1868flush_pending(s->strm);1869}18701871/* We've done all we can with the available input and output. */1872return last ? finish_started : need_more;1873}18741875/* ===========================================================================1876* Compress as much as possible from the input stream, return the current1877* block state.1878* This function does not perform lazy evaluation of matches and inserts1879* new strings in the dictionary only for unmatched strings or for short1880* matches. It is used only for the fast compression options.1881*/1882local block_state deflate_fast(s, flush)1883deflate_state *s;1884int flush;1885{1886IPos hash_head; /* head of the hash chain */1887int bflush; /* set if current block must be flushed */18881889for (;;) {1890/* Make sure that we always have enough lookahead, except1891* at the end of the input file. We need MAX_MATCH bytes1892* for the next match, plus MIN_MATCH bytes to insert the1893* string following the next match.1894*/1895if (s->lookahead < MIN_LOOKAHEAD) {1896fill_window(s);1897if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {1898return need_more;1899}1900if (s->lookahead == 0) break; /* flush the current block */1901}19021903/* Insert the string window[strstart .. strstart+2] in the1904* dictionary, and set hash_head to the head of the hash chain:1905*/1906hash_head = NIL;1907if (s->lookahead >= MIN_MATCH) {1908INSERT_STRING(s, s->strstart, hash_head);1909}19101911/* Find the longest match, discarding those <= prev_length.1912* At this point we have always match_length < MIN_MATCH1913*/1914if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {1915/* To simplify the code, we prevent matches with the string1916* of window index 0 (in particular we have to avoid a match1917* of the string with itself at the start of the input file).1918*/1919s->match_length = longest_match (s, hash_head);1920/* longest_match() sets match_start */1921}1922if (s->match_length >= MIN_MATCH) {1923check_match(s, s->strstart, s->match_start, s->match_length);19241925_tr_tally_dist(s, s->strstart - s->match_start,1926s->match_length - MIN_MATCH, bflush);19271928s->lookahead -= s->match_length;19291930/* Insert new strings in the hash table only if the match length1931* is not too large. This saves time but degrades compression.1932*/1933#ifndef FASTEST1934if (s->match_length <= s->max_insert_length &&1935s->lookahead >= MIN_MATCH) {1936s->match_length--; /* string at strstart already in table */1937do {1938s->strstart++;1939INSERT_STRING(s, s->strstart, hash_head);1940/* strstart never exceeds WSIZE-MAX_MATCH, so there are1941* always MIN_MATCH bytes ahead.1942*/1943} while (--s->match_length != 0);1944s->strstart++;1945} else1946#endif1947{1948s->strstart += s->match_length;1949s->match_length = 0;1950s->ins_h = s->window[s->strstart];1951UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);1952#if MIN_MATCH != 31953Call UPDATE_HASH() MIN_MATCH-3 more times1954#endif1955/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not1956* matter since it will be recomputed at next deflate call.1957*/1958}1959} else {1960/* No match, output a literal byte */1961Tracevv((stderr,"%c", s->window[s->strstart]));1962_tr_tally_lit (s, s->window[s->strstart], bflush);1963s->lookahead--;1964s->strstart++;1965}1966if (bflush) FLUSH_BLOCK(s, 0);1967}1968s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;1969if (flush == Z_FINISH) {1970FLUSH_BLOCK(s, 1);1971return finish_done;1972}1973if (s->sym_next)1974FLUSH_BLOCK(s, 0);1975return block_done;1976}19771978#ifndef FASTEST1979/* ===========================================================================1980* Same as above, but achieves better compression. We use a lazy1981* evaluation for matches: a match is finally adopted only if there is1982* no better match at the next window position.1983*/1984local block_state deflate_slow(s, flush)1985deflate_state *s;1986int flush;1987{1988IPos hash_head; /* head of hash chain */1989int bflush; /* set if current block must be flushed */19901991/* Process the input block. */1992for (;;) {1993/* Make sure that we always have enough lookahead, except1994* at the end of the input file. We need MAX_MATCH bytes1995* for the next match, plus MIN_MATCH bytes to insert the1996* string following the next match.1997*/1998if (s->lookahead < MIN_LOOKAHEAD) {1999fill_window(s);2000if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {2001return need_more;2002}2003if (s->lookahead == 0) break; /* flush the current block */2004}20052006/* Insert the string window[strstart .. strstart+2] in the2007* dictionary, and set hash_head to the head of the hash chain:2008*/2009hash_head = NIL;2010if (s->lookahead >= MIN_MATCH) {2011INSERT_STRING(s, s->strstart, hash_head);2012}20132014/* Find the longest match, discarding those <= prev_length.2015*/2016s->prev_length = s->match_length, s->prev_match = s->match_start;2017s->match_length = MIN_MATCH-1;20182019if (hash_head != NIL && s->prev_length < s->max_lazy_match &&2020s->strstart - hash_head <= MAX_DIST(s)) {2021/* To simplify the code, we prevent matches with the string2022* of window index 0 (in particular we have to avoid a match2023* of the string with itself at the start of the input file).2024*/2025s->match_length = longest_match (s, hash_head);2026/* longest_match() sets match_start */20272028if (s->match_length <= 5 && (s->strategy == Z_FILTERED2029#if TOO_FAR <= 327672030|| (s->match_length == MIN_MATCH &&2031s->strstart - s->match_start > TOO_FAR)2032#endif2033)) {20342035/* If prev_match is also MIN_MATCH, match_start is garbage2036* but we will ignore the current match anyway.2037*/2038s->match_length = MIN_MATCH-1;2039}2040}2041/* If there was a match at the previous step and the current2042* match is not better, output the previous match:2043*/2044if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {2045uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;2046/* Do not insert strings in hash table beyond this. */20472048check_match(s, s->strstart-1, s->prev_match, s->prev_length);20492050_tr_tally_dist(s, s->strstart -1 - s->prev_match,2051s->prev_length - MIN_MATCH, bflush);20522053/* Insert in hash table all strings up to the end of the match.2054* strstart-1 and strstart are already inserted. If there is not2055* enough lookahead, the last two strings are not inserted in2056* the hash table.2057*/2058s->lookahead -= s->prev_length-1;2059s->prev_length -= 2;2060do {2061if (++s->strstart <= max_insert) {2062INSERT_STRING(s, s->strstart, hash_head);2063}2064} while (--s->prev_length != 0);2065s->match_available = 0;2066s->match_length = MIN_MATCH-1;2067s->strstart++;20682069if (bflush) FLUSH_BLOCK(s, 0);20702071} else if (s->match_available) {2072/* If there was no match at the previous position, output a2073* single literal. If there was a match but the current match2074* is longer, truncate the previous match to a single literal.2075*/2076Tracevv((stderr,"%c", s->window[s->strstart-1]));2077_tr_tally_lit(s, s->window[s->strstart-1], bflush);2078if (bflush) {2079FLUSH_BLOCK_ONLY(s, 0);2080}2081s->strstart++;2082s->lookahead--;2083if (s->strm->avail_out == 0) return need_more;2084} else {2085/* There is no previous match to compare with, wait for2086* the next step to decide.2087*/2088s->match_available = 1;2089s->strstart++;2090s->lookahead--;2091}2092}2093Assert (flush != Z_NO_FLUSH, "no flush?");2094if (s->match_available) {2095Tracevv((stderr,"%c", s->window[s->strstart-1]));2096_tr_tally_lit(s, s->window[s->strstart-1], bflush);2097s->match_available = 0;2098}2099s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;2100if (flush == Z_FINISH) {2101FLUSH_BLOCK(s, 1);2102return finish_done;2103}2104if (s->sym_next)2105FLUSH_BLOCK(s, 0);2106return block_done;2107}2108#endif /* FASTEST */21092110/* ===========================================================================2111* For Z_RLE, simply look for runs of bytes, generate matches only of distance2112* one. Do not maintain a hash table. (It will be regenerated if this run of2113* deflate switches away from Z_RLE.)2114*/2115local block_state deflate_rle(s, flush)2116deflate_state *s;2117int flush;2118{2119int bflush; /* set if current block must be flushed */2120uInt prev; /* byte at distance one to match */2121Bytef *scan, *strend; /* scan goes up to strend for length of run */21222123for (;;) {2124/* Make sure that we always have enough lookahead, except2125* at the end of the input file. We need MAX_MATCH bytes2126* for the longest run, plus one for the unrolled loop.2127*/2128if (s->lookahead <= MAX_MATCH) {2129fill_window(s);2130if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {2131return need_more;2132}2133if (s->lookahead == 0) break; /* flush the current block */2134}21352136/* See how many times the previous byte repeats */2137s->match_length = 0;2138if (s->lookahead >= MIN_MATCH && s->strstart > 0) {2139scan = s->window + s->strstart - 1;2140prev = *scan;2141if (prev == *++scan && prev == *++scan && prev == *++scan) {2142strend = s->window + s->strstart + MAX_MATCH;2143do {2144} while (prev == *++scan && prev == *++scan &&2145prev == *++scan && prev == *++scan &&2146prev == *++scan && prev == *++scan &&2147prev == *++scan && prev == *++scan &&2148scan < strend);2149s->match_length = MAX_MATCH - (uInt)(strend - scan);2150if (s->match_length > s->lookahead)2151s->match_length = s->lookahead;2152}2153Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");2154}21552156/* Emit match if have run of MIN_MATCH or longer, else emit literal */2157if (s->match_length >= MIN_MATCH) {2158check_match(s, s->strstart, s->strstart - 1, s->match_length);21592160_tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);21612162s->lookahead -= s->match_length;2163s->strstart += s->match_length;2164s->match_length = 0;2165} else {2166/* No match, output a literal byte */2167Tracevv((stderr,"%c", s->window[s->strstart]));2168_tr_tally_lit (s, s->window[s->strstart], bflush);2169s->lookahead--;2170s->strstart++;2171}2172if (bflush) FLUSH_BLOCK(s, 0);2173}2174s->insert = 0;2175if (flush == Z_FINISH) {2176FLUSH_BLOCK(s, 1);2177return finish_done;2178}2179if (s->sym_next)2180FLUSH_BLOCK(s, 0);2181return block_done;2182}21832184/* ===========================================================================2185* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.2186* (It will be regenerated if this run of deflate switches away from Huffman.)2187*/2188local block_state deflate_huff(s, flush)2189deflate_state *s;2190int flush;2191{2192int bflush; /* set if current block must be flushed */21932194for (;;) {2195/* Make sure that we have a literal to write. */2196if (s->lookahead == 0) {2197fill_window(s);2198if (s->lookahead == 0) {2199if (flush == Z_NO_FLUSH)2200return need_more;2201break; /* flush the current block */2202}2203}22042205/* Output a literal byte */2206s->match_length = 0;2207Tracevv((stderr,"%c", s->window[s->strstart]));2208_tr_tally_lit (s, s->window[s->strstart], bflush);2209s->lookahead--;2210s->strstart++;2211if (bflush) FLUSH_BLOCK(s, 0);2212}2213s->insert = 0;2214if (flush == Z_FINISH) {2215FLUSH_BLOCK(s, 1);2216return finish_done;2217}2218if (s->sym_next)2219FLUSH_BLOCK(s, 0);2220return block_done;2221}222222232224