/* 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));449s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));450s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));451452s->high_water = 0; /* nothing written to s->window yet */453454s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */455456/* We overlay pending_buf and sym_buf. This works since the average size457* for length/distance pairs over any compressed block is assured to be 31458* bits or less.459*460* Analysis: The longest fixed codes are a length code of 8 bits plus 5461* extra bits, for lengths 131 to 257. The longest fixed distance codes are462* 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest463* possible fixed-codes length/distance pair is then 31 bits total.464*465* sym_buf starts one-fourth of the way into pending_buf. So there are466* three bytes in sym_buf for every four bytes in pending_buf. Each symbol467* in sym_buf is three bytes -- two for the distance and one for the468* literal/length. As each symbol is consumed, the pointer to the next469* sym_buf value to read moves forward three bytes. From that symbol, up to470* 31 bits are written to pending_buf. The closest the written pending_buf471* bits gets to the next sym_buf symbol to read is just before the last472* code is written. At that time, 31*(n - 2) bits have been written, just473* after 24*(n - 2) bits have been consumed from sym_buf. sym_buf starts at474* 8*n bits into pending_buf. (Note that the symbol buffer fills when n - 1475* symbols are written.) The closest the writing gets to what is unread is476* then n + 14 bits. Here n is lit_bufsize, which is 16384 by default, and477* can range from 128 to 32768.478*479* Therefore, at a minimum, there are 142 bits of space between what is480* written and what is read in the overlain buffers, so the symbols cannot481* be overwritten by the compressed data. That space is actually 139 bits,482* due to the three-bit fixed-code block header.483*484* That covers the case where either Z_FIXED is specified, forcing fixed485* codes, or when the use of fixed codes is chosen, because that choice486* results in a smaller compressed block than dynamic codes. That latter487* condition then assures that the above analysis also covers all dynamic488* blocks. A dynamic-code block will only be chosen to be emitted if it has489* fewer bits than a fixed-code block would for the same set of symbols.490* Therefore its average symbol length is assured to be less than 31. So491* the compressed data for a dynamic block also cannot overwrite the492* symbols from which it is being constructed.493*/494495s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, LIT_BUFS);496s->pending_buf_size = (ulg)s->lit_bufsize * 4;497498if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||499s->pending_buf == Z_NULL) {500s->status = FINISH_STATE;501strm->msg = ERR_MSG(Z_MEM_ERROR);502deflateEnd (strm);503return Z_MEM_ERROR;504}505#ifdef LIT_MEM506s->d_buf = (ushf *)(s->pending_buf + (s->lit_bufsize << 1));507s->l_buf = s->pending_buf + (s->lit_bufsize << 2);508s->sym_end = s->lit_bufsize - 1;509#else510s->sym_buf = s->pending_buf + s->lit_bufsize;511s->sym_end = (s->lit_bufsize - 1) * 3;512#endif513/* We avoid equality with lit_bufsize*3 because of wraparound at 64K514* on 16 bit machines and because stored blocks are restricted to515* 64K-1 bytes.516*/517518s->level = level;519s->strategy = strategy;520s->method = (Byte)method;521522return deflateReset(strm);523}524525/* =========================================================================526* Check for a valid deflate stream state. Return 0 if ok, 1 if not.527*/528local int deflateStateCheck(z_streamp strm) {529deflate_state *s;530if (strm == Z_NULL ||531strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)532return 1;533s = strm->state;534if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE &&535#ifdef GZIP536s->status != GZIP_STATE &&537#endif538s->status != EXTRA_STATE &&539s->status != NAME_STATE &&540s->status != COMMENT_STATE &&541s->status != HCRC_STATE &&542s->status != BUSY_STATE &&543s->status != FINISH_STATE))544return 1;545return 0;546}547548/* ========================================================================= */549int ZEXPORT deflateSetDictionary(z_streamp strm, const Bytef *dictionary,550uInt dictLength) {551deflate_state *s;552uInt str, n;553int wrap;554unsigned avail;555z_const unsigned char *next;556557if (deflateStateCheck(strm) || dictionary == Z_NULL)558return Z_STREAM_ERROR;559s = strm->state;560wrap = s->wrap;561if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)562return Z_STREAM_ERROR;563564/* when using zlib wrappers, compute Adler-32 for provided dictionary */565if (wrap == 1)566strm->adler = adler32(strm->adler, dictionary, dictLength);567s->wrap = 0; /* avoid computing Adler-32 in read_buf */568569/* if dictionary would fill window, just replace the history */570if (dictLength >= s->w_size) {571if (wrap == 0) { /* already empty otherwise */572CLEAR_HASH(s);573s->strstart = 0;574s->block_start = 0L;575s->insert = 0;576}577dictionary += dictLength - s->w_size; /* use the tail */578dictLength = s->w_size;579}580581/* insert dictionary into window and hash */582avail = strm->avail_in;583next = strm->next_in;584strm->avail_in = dictLength;585strm->next_in = (z_const Bytef *)dictionary;586fill_window(s);587while (s->lookahead >= MIN_MATCH) {588str = s->strstart;589n = s->lookahead - (MIN_MATCH-1);590do {591UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);592#ifndef FASTEST593s->prev[str & s->w_mask] = s->head[s->ins_h];594#endif595s->head[s->ins_h] = (Pos)str;596str++;597} while (--n);598s->strstart = str;599s->lookahead = MIN_MATCH-1;600fill_window(s);601}602s->strstart += s->lookahead;603s->block_start = (long)s->strstart;604s->insert = s->lookahead;605s->lookahead = 0;606s->match_length = s->prev_length = MIN_MATCH-1;607s->match_available = 0;608strm->next_in = next;609strm->avail_in = avail;610s->wrap = wrap;611return Z_OK;612}613614/* ========================================================================= */615int ZEXPORT deflateGetDictionary(z_streamp strm, Bytef *dictionary,616uInt *dictLength) {617deflate_state *s;618uInt len;619620if (deflateStateCheck(strm))621return Z_STREAM_ERROR;622s = strm->state;623len = s->strstart + s->lookahead;624if (len > s->w_size)625len = s->w_size;626if (dictionary != Z_NULL && len)627zmemcpy(dictionary, s->window + s->strstart + s->lookahead - len, len);628if (dictLength != Z_NULL)629*dictLength = len;630return Z_OK;631}632633/* ========================================================================= */634int ZEXPORT deflateResetKeep(z_streamp strm) {635deflate_state *s;636637if (deflateStateCheck(strm)) {638return Z_STREAM_ERROR;639}640641strm->total_in = strm->total_out = 0;642strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */643strm->data_type = Z_UNKNOWN;644645s = (deflate_state *)strm->state;646s->pending = 0;647s->pending_out = s->pending_buf;648649if (s->wrap < 0) {650s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */651}652s->status =653#ifdef GZIP654s->wrap == 2 ? GZIP_STATE :655#endif656INIT_STATE;657strm->adler =658#ifdef GZIP659s->wrap == 2 ? crc32(0L, Z_NULL, 0) :660#endif661adler32(0L, Z_NULL, 0);662s->last_flush = -2;663664_tr_init(s);665666return Z_OK;667}668669/* ===========================================================================670* Initialize the "longest match" routines for a new zlib stream671*/672local void lm_init(deflate_state *s) {673s->window_size = (ulg)2L*s->w_size;674675CLEAR_HASH(s);676677/* Set the default configuration parameters:678*/679s->max_lazy_match = configuration_table[s->level].max_lazy;680s->good_match = configuration_table[s->level].good_length;681s->nice_match = configuration_table[s->level].nice_length;682s->max_chain_length = configuration_table[s->level].max_chain;683684s->strstart = 0;685s->block_start = 0L;686s->lookahead = 0;687s->insert = 0;688s->match_length = s->prev_length = MIN_MATCH-1;689s->match_available = 0;690s->ins_h = 0;691}692693/* ========================================================================= */694int ZEXPORT deflateReset(z_streamp strm) {695int ret;696697ret = deflateResetKeep(strm);698if (ret == Z_OK)699lm_init(strm->state);700return ret;701}702703/* ========================================================================= */704int ZEXPORT deflateSetHeader(z_streamp strm, gz_headerp head) {705if (deflateStateCheck(strm) || strm->state->wrap != 2)706return Z_STREAM_ERROR;707strm->state->gzhead = head;708return Z_OK;709}710711/* ========================================================================= */712int ZEXPORT deflatePending(z_streamp strm, unsigned *pending, int *bits) {713if (deflateStateCheck(strm)) return Z_STREAM_ERROR;714if (pending != Z_NULL)715*pending = strm->state->pending;716if (bits != Z_NULL)717*bits = strm->state->bi_valid;718return Z_OK;719}720721/* ========================================================================= */722int ZEXPORT deflatePrime(z_streamp strm, int bits, int value) {723deflate_state *s;724int put;725726if (deflateStateCheck(strm)) return Z_STREAM_ERROR;727s = strm->state;728#ifdef LIT_MEM729if (bits < 0 || bits > 16 ||730(uchf *)s->d_buf < s->pending_out + ((Buf_size + 7) >> 3))731return Z_BUF_ERROR;732#else733if (bits < 0 || bits > 16 ||734s->sym_buf < s->pending_out + ((Buf_size + 7) >> 3))735return Z_BUF_ERROR;736#endif737do {738put = Buf_size - s->bi_valid;739if (put > bits)740put = bits;741s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);742s->bi_valid += put;743_tr_flush_bits(s);744value >>= put;745bits -= put;746} while (bits);747return Z_OK;748}749750/* ========================================================================= */751int ZEXPORT deflateParams(z_streamp strm, int level, int strategy) {752deflate_state *s;753compress_func func;754755if (deflateStateCheck(strm)) return Z_STREAM_ERROR;756s = strm->state;757758#ifdef FASTEST759if (level != 0) level = 1;760#else761if (level == Z_DEFAULT_COMPRESSION) level = 6;762#endif763if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {764return Z_STREAM_ERROR;765}766func = configuration_table[s->level].func;767768if ((strategy != s->strategy || func != configuration_table[level].func) &&769s->last_flush != -2) {770/* Flush the last buffer: */771int err = deflate(strm, Z_BLOCK);772if (err == Z_STREAM_ERROR)773return err;774if (strm->avail_in || (s->strstart - s->block_start) + s->lookahead)775return Z_BUF_ERROR;776}777if (s->level != level) {778if (s->level == 0 && s->matches != 0) {779if (s->matches == 1)780slide_hash(s);781else782CLEAR_HASH(s);783s->matches = 0;784}785s->level = level;786s->max_lazy_match = configuration_table[level].max_lazy;787s->good_match = configuration_table[level].good_length;788s->nice_match = configuration_table[level].nice_length;789s->max_chain_length = configuration_table[level].max_chain;790}791s->strategy = strategy;792return Z_OK;793}794795/* ========================================================================= */796int ZEXPORT deflateTune(z_streamp strm, int good_length, int max_lazy,797int nice_length, int max_chain) {798deflate_state *s;799800if (deflateStateCheck(strm)) return Z_STREAM_ERROR;801s = strm->state;802s->good_match = (uInt)good_length;803s->max_lazy_match = (uInt)max_lazy;804s->nice_match = nice_length;805s->max_chain_length = (uInt)max_chain;806return Z_OK;807}808809/* =========================================================================810* For the default windowBits of 15 and memLevel of 8, this function returns a811* close to exact, as well as small, upper bound on the compressed size. This812* is an expansion of ~0.03%, plus a small constant.813*814* For any setting other than those defaults for windowBits and memLevel, one815* of two worst case bounds is returned. This is at most an expansion of ~4% or816* ~13%, plus a small constant.817*818* Both the 0.03% and 4% derive from the overhead of stored blocks. The first819* one is for stored blocks of 16383 bytes (memLevel == 8), whereas the second820* is for stored blocks of 127 bytes (the worst case memLevel == 1). The821* expansion results from five bytes of header for each stored block.822*823* The larger expansion of 13% results from a window size less than or equal to824* the symbols buffer size (windowBits <= memLevel + 7). In that case some of825* the data being compressed may have slid out of the sliding window, impeding826* a stored block from being emitted. Then the only choice is a fixed or827* dynamic block, where a fixed block limits the maximum expansion to 9 bits828* per 8-bit byte, plus 10 bits for every block. The smallest block size for829* which this can occur is 255 (memLevel == 2).830*831* Shifts are used to approximate divisions, for speed.832*/833uLong ZEXPORT deflateBound(z_streamp strm, uLong sourceLen) {834deflate_state *s;835uLong fixedlen, storelen, wraplen;836837/* upper bound for fixed blocks with 9-bit literals and length 255838(memLevel == 2, which is the lowest that may not use stored blocks) --839~13% overhead plus a small constant */840fixedlen = sourceLen + (sourceLen >> 3) + (sourceLen >> 8) +841(sourceLen >> 9) + 4;842843/* upper bound for stored blocks with length 127 (memLevel == 1) --844~4% overhead plus a small constant */845storelen = sourceLen + (sourceLen >> 5) + (sourceLen >> 7) +846(sourceLen >> 11) + 7;847848/* if can't get parameters, return larger bound plus a zlib wrapper */849if (deflateStateCheck(strm))850return (fixedlen > storelen ? fixedlen : storelen) + 6;851852/* compute wrapper length */853s = strm->state;854switch (s->wrap) {855case 0: /* raw deflate */856wraplen = 0;857break;858case 1: /* zlib wrapper */859wraplen = 6 + (s->strstart ? 4 : 0);860break;861#ifdef GZIP862case 2: /* gzip wrapper */863wraplen = 18;864if (s->gzhead != Z_NULL) { /* user-supplied gzip header */865Bytef *str;866if (s->gzhead->extra != Z_NULL)867wraplen += 2 + s->gzhead->extra_len;868str = s->gzhead->name;869if (str != Z_NULL)870do {871wraplen++;872} while (*str++);873str = s->gzhead->comment;874if (str != Z_NULL)875do {876wraplen++;877} while (*str++);878if (s->gzhead->hcrc)879wraplen += 2;880}881break;882#endif883default: /* for compiler happiness */884wraplen = 6;885}886887/* if not default parameters, return one of the conservative bounds */888if (s->w_bits != 15 || s->hash_bits != 8 + 7)889return (s->w_bits <= s->hash_bits && s->level ? fixedlen : storelen) +890wraplen;891892/* default settings: return tight bound for that case -- ~0.03% overhead893plus a small constant */894return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +895(sourceLen >> 25) + 13 - 6 + wraplen;896}897898/* =========================================================================899* Put a short in the pending buffer. The 16-bit value is put in MSB order.900* IN assertion: the stream state is correct and there is enough room in901* pending_buf.902*/903local void putShortMSB(deflate_state *s, uInt b) {904put_byte(s, (Byte)(b >> 8));905put_byte(s, (Byte)(b & 0xff));906}907908/* =========================================================================909* Flush as much pending output as possible. All deflate() output, except for910* some deflate_stored() output, goes through this function so some911* applications may wish to modify it to avoid allocating a large912* strm->next_out buffer and copying into it. (See also read_buf()).913*/914local void flush_pending(z_streamp strm) {915unsigned len;916deflate_state *s = strm->state;917918_tr_flush_bits(s);919len = s->pending;920if (len > strm->avail_out) len = strm->avail_out;921if (len == 0) return;922923zmemcpy(strm->next_out, s->pending_out, len);924strm->next_out += len;925s->pending_out += len;926strm->total_out += len;927strm->avail_out -= len;928s->pending -= len;929if (s->pending == 0) {930s->pending_out = s->pending_buf;931}932}933934/* ===========================================================================935* Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1].936*/937#define HCRC_UPDATE(beg) \938do { \939if (s->gzhead->hcrc && s->pending > (beg)) \940strm->adler = crc32(strm->adler, s->pending_buf + (beg), \941s->pending - (beg)); \942} while (0)943944/* ========================================================================= */945int ZEXPORT deflate(z_streamp strm, int flush) {946int old_flush; /* value of flush param for previous deflate call */947deflate_state *s;948949if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) {950return Z_STREAM_ERROR;951}952s = strm->state;953954if (strm->next_out == Z_NULL ||955(strm->avail_in != 0 && strm->next_in == Z_NULL) ||956(s->status == FINISH_STATE && flush != Z_FINISH)) {957ERR_RETURN(strm, Z_STREAM_ERROR);958}959if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);960961old_flush = s->last_flush;962s->last_flush = flush;963964/* Flush as much pending output as possible */965if (s->pending != 0) {966flush_pending(strm);967if (strm->avail_out == 0) {968/* Since avail_out is 0, deflate will be called again with969* more output space, but possibly with both pending and970* avail_in equal to zero. There won't be anything to do,971* but this is not an error situation so make sure we972* return OK instead of BUF_ERROR at next call of deflate:973*/974s->last_flush = -1;975return Z_OK;976}977978/* Make sure there is something to do and avoid duplicate consecutive979* flushes. For repeated and useless calls with Z_FINISH, we keep980* returning Z_STREAM_END instead of Z_BUF_ERROR.981*/982} else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&983flush != Z_FINISH) {984ERR_RETURN(strm, Z_BUF_ERROR);985}986987/* User must not provide more input after the first FINISH: */988if (s->status == FINISH_STATE && strm->avail_in != 0) {989ERR_RETURN(strm, Z_BUF_ERROR);990}991992/* Write the header */993if (s->status == INIT_STATE && s->wrap == 0)994s->status = BUSY_STATE;995if (s->status == INIT_STATE) {996/* zlib header */997uInt header = (Z_DEFLATED + ((s->w_bits - 8) << 4)) << 8;998uInt level_flags;9991000if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)1001level_flags = 0;1002else if (s->level < 6)1003level_flags = 1;1004else if (s->level == 6)1005level_flags = 2;1006else1007level_flags = 3;1008header |= (level_flags << 6);1009if (s->strstart != 0) header |= PRESET_DICT;1010header += 31 - (header % 31);10111012putShortMSB(s, header);10131014/* Save the adler32 of the preset dictionary: */1015if (s->strstart != 0) {1016putShortMSB(s, (uInt)(strm->adler >> 16));1017putShortMSB(s, (uInt)(strm->adler & 0xffff));1018}1019strm->adler = adler32(0L, Z_NULL, 0);1020s->status = BUSY_STATE;10211022/* Compression must start with an empty pending buffer */1023flush_pending(strm);1024if (s->pending != 0) {1025s->last_flush = -1;1026return Z_OK;1027}1028}1029#ifdef GZIP1030if (s->status == GZIP_STATE) {1031/* gzip header */1032strm->adler = crc32(0L, Z_NULL, 0);1033put_byte(s, 31);1034put_byte(s, 139);1035put_byte(s, 8);1036if (s->gzhead == Z_NULL) {1037put_byte(s, 0);1038put_byte(s, 0);1039put_byte(s, 0);1040put_byte(s, 0);1041put_byte(s, 0);1042put_byte(s, s->level == 9 ? 2 :1043(s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?10444 : 0));1045put_byte(s, OS_CODE);1046s->status = BUSY_STATE;10471048/* Compression must start with an empty pending buffer */1049flush_pending(strm);1050if (s->pending != 0) {1051s->last_flush = -1;1052return Z_OK;1053}1054}1055else {1056put_byte(s, (s->gzhead->text ? 1 : 0) +1057(s->gzhead->hcrc ? 2 : 0) +1058(s->gzhead->extra == Z_NULL ? 0 : 4) +1059(s->gzhead->name == Z_NULL ? 0 : 8) +1060(s->gzhead->comment == Z_NULL ? 0 : 16)1061);1062put_byte(s, (Byte)(s->gzhead->time & 0xff));1063put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));1064put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));1065put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));1066put_byte(s, s->level == 9 ? 2 :1067(s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?10684 : 0));1069put_byte(s, s->gzhead->os & 0xff);1070if (s->gzhead->extra != Z_NULL) {1071put_byte(s, s->gzhead->extra_len & 0xff);1072put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);1073}1074if (s->gzhead->hcrc)1075strm->adler = crc32(strm->adler, s->pending_buf,1076s->pending);1077s->gzindex = 0;1078s->status = EXTRA_STATE;1079}1080}1081if (s->status == EXTRA_STATE) {1082if (s->gzhead->extra != Z_NULL) {1083ulg beg = s->pending; /* start of bytes to update crc */1084uInt left = (s->gzhead->extra_len & 0xffff) - s->gzindex;1085while (s->pending + left > s->pending_buf_size) {1086uInt copy = s->pending_buf_size - s->pending;1087zmemcpy(s->pending_buf + s->pending,1088s->gzhead->extra + s->gzindex, copy);1089s->pending = s->pending_buf_size;1090HCRC_UPDATE(beg);1091s->gzindex += copy;1092flush_pending(strm);1093if (s->pending != 0) {1094s->last_flush = -1;1095return Z_OK;1096}1097beg = 0;1098left -= copy;1099}1100zmemcpy(s->pending_buf + s->pending,1101s->gzhead->extra + s->gzindex, left);1102s->pending += left;1103HCRC_UPDATE(beg);1104s->gzindex = 0;1105}1106s->status = NAME_STATE;1107}1108if (s->status == NAME_STATE) {1109if (s->gzhead->name != Z_NULL) {1110ulg beg = s->pending; /* start of bytes to update crc */1111int val;1112do {1113if (s->pending == s->pending_buf_size) {1114HCRC_UPDATE(beg);1115flush_pending(strm);1116if (s->pending != 0) {1117s->last_flush = -1;1118return Z_OK;1119}1120beg = 0;1121}1122val = s->gzhead->name[s->gzindex++];1123put_byte(s, val);1124} while (val != 0);1125HCRC_UPDATE(beg);1126s->gzindex = 0;1127}1128s->status = COMMENT_STATE;1129}1130if (s->status == COMMENT_STATE) {1131if (s->gzhead->comment != Z_NULL) {1132ulg beg = s->pending; /* start of bytes to update crc */1133int val;1134do {1135if (s->pending == s->pending_buf_size) {1136HCRC_UPDATE(beg);1137flush_pending(strm);1138if (s->pending != 0) {1139s->last_flush = -1;1140return Z_OK;1141}1142beg = 0;1143}1144val = s->gzhead->comment[s->gzindex++];1145put_byte(s, val);1146} while (val != 0);1147HCRC_UPDATE(beg);1148}1149s->status = HCRC_STATE;1150}1151if (s->status == HCRC_STATE) {1152if (s->gzhead->hcrc) {1153if (s->pending + 2 > s->pending_buf_size) {1154flush_pending(strm);1155if (s->pending != 0) {1156s->last_flush = -1;1157return Z_OK;1158}1159}1160put_byte(s, (Byte)(strm->adler & 0xff));1161put_byte(s, (Byte)((strm->adler >> 8) & 0xff));1162strm->adler = crc32(0L, Z_NULL, 0);1163}1164s->status = BUSY_STATE;11651166/* Compression must start with an empty pending buffer */1167flush_pending(strm);1168if (s->pending != 0) {1169s->last_flush = -1;1170return Z_OK;1171}1172}1173#endif11741175/* Start a new block or continue the current one.1176*/1177if (strm->avail_in != 0 || s->lookahead != 0 ||1178(flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {1179block_state bstate;11801181bstate = s->level == 0 ? deflate_stored(s, flush) :1182s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :1183s->strategy == Z_RLE ? deflate_rle(s, flush) :1184(*(configuration_table[s->level].func))(s, flush);11851186if (bstate == finish_started || bstate == finish_done) {1187s->status = FINISH_STATE;1188}1189if (bstate == need_more || bstate == finish_started) {1190if (strm->avail_out == 0) {1191s->last_flush = -1; /* avoid BUF_ERROR next call, see above */1192}1193return Z_OK;1194/* If flush != Z_NO_FLUSH && avail_out == 0, the next call1195* of deflate should use the same flush parameter to make sure1196* that the flush is complete. So we don't have to output an1197* empty block here, this will be done at next call. This also1198* ensures that for a very small output buffer, we emit at most1199* one empty block.1200*/1201}1202if (bstate == block_done) {1203if (flush == Z_PARTIAL_FLUSH) {1204_tr_align(s);1205} else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */1206_tr_stored_block(s, (char*)0, 0L, 0);1207/* For a full flush, this empty block will be recognized1208* as a special marker by inflate_sync().1209*/1210if (flush == Z_FULL_FLUSH) {1211CLEAR_HASH(s); /* forget history */1212if (s->lookahead == 0) {1213s->strstart = 0;1214s->block_start = 0L;1215s->insert = 0;1216}1217}1218}1219flush_pending(strm);1220if (strm->avail_out == 0) {1221s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */1222return Z_OK;1223}1224}1225}12261227if (flush != Z_FINISH) return Z_OK;1228if (s->wrap <= 0) return Z_STREAM_END;12291230/* Write the trailer */1231#ifdef GZIP1232if (s->wrap == 2) {1233put_byte(s, (Byte)(strm->adler & 0xff));1234put_byte(s, (Byte)((strm->adler >> 8) & 0xff));1235put_byte(s, (Byte)((strm->adler >> 16) & 0xff));1236put_byte(s, (Byte)((strm->adler >> 24) & 0xff));1237put_byte(s, (Byte)(strm->total_in & 0xff));1238put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));1239put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));1240put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));1241}1242else1243#endif1244{1245putShortMSB(s, (uInt)(strm->adler >> 16));1246putShortMSB(s, (uInt)(strm->adler & 0xffff));1247}1248flush_pending(strm);1249/* If avail_out is zero, the application will call deflate again1250* to flush the rest.1251*/1252if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */1253return s->pending != 0 ? Z_OK : Z_STREAM_END;1254}12551256/* ========================================================================= */1257int ZEXPORT deflateEnd(z_streamp strm) {1258int status;12591260if (deflateStateCheck(strm)) return Z_STREAM_ERROR;12611262status = strm->state->status;12631264/* Deallocate in reverse order of allocations: */1265TRY_FREE(strm, strm->state->pending_buf);1266TRY_FREE(strm, strm->state->head);1267TRY_FREE(strm, strm->state->prev);1268TRY_FREE(strm, strm->state->window);12691270ZFREE(strm, strm->state);1271strm->state = Z_NULL;12721273return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;1274}12751276/* =========================================================================1277* Copy the source state to the destination state.1278* To simplify the source, this is not supported for 16-bit MSDOS (which1279* doesn't have enough memory anyway to duplicate compression states).1280*/1281int ZEXPORT deflateCopy(z_streamp dest, z_streamp source) {1282#ifdef MAXSEG_64K1283(void)dest;1284(void)source;1285return Z_STREAM_ERROR;1286#else1287deflate_state *ds;1288deflate_state *ss;128912901291if (deflateStateCheck(source) || dest == Z_NULL) {1292return Z_STREAM_ERROR;1293}12941295ss = source->state;12961297zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));12981299ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));1300if (ds == Z_NULL) return Z_MEM_ERROR;1301dest->state = (struct internal_state FAR *) ds;1302zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));1303ds->strm = dest;13041305ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));1306ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));1307ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));1308ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, LIT_BUFS);13091310if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||1311ds->pending_buf == Z_NULL) {1312deflateEnd (dest);1313return Z_MEM_ERROR;1314}1315/* following zmemcpy do not work for 16-bit MSDOS */1316zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));1317zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));1318zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));1319zmemcpy(ds->pending_buf, ss->pending_buf, ds->lit_bufsize * LIT_BUFS);13201321ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);1322#ifdef LIT_MEM1323ds->d_buf = (ushf *)(ds->pending_buf + (ds->lit_bufsize << 1));1324ds->l_buf = ds->pending_buf + (ds->lit_bufsize << 2);1325#else1326ds->sym_buf = ds->pending_buf + ds->lit_bufsize;1327#endif13281329ds->l_desc.dyn_tree = ds->dyn_ltree;1330ds->d_desc.dyn_tree = ds->dyn_dtree;1331ds->bl_desc.dyn_tree = ds->bl_tree;13321333return Z_OK;1334#endif /* MAXSEG_64K */1335}13361337#ifndef FASTEST1338/* ===========================================================================1339* Set match_start to the longest match starting at the given string and1340* return its length. Matches shorter or equal to prev_length are discarded,1341* in which case the result is equal to prev_length and match_start is1342* garbage.1343* IN assertions: cur_match is the head of the hash chain for the current1344* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 11345* OUT assertion: the match length is not greater than s->lookahead.1346*/1347local uInt longest_match(deflate_state *s, IPos cur_match) {1348unsigned chain_length = s->max_chain_length;/* max hash chain length */1349register Bytef *scan = s->window + s->strstart; /* current string */1350register Bytef *match; /* matched string */1351register int len; /* length of current match */1352int best_len = (int)s->prev_length; /* best match length so far */1353int nice_match = s->nice_match; /* stop if match long enough */1354IPos limit = s->strstart > (IPos)MAX_DIST(s) ?1355s->strstart - (IPos)MAX_DIST(s) : NIL;1356/* Stop when cur_match becomes <= limit. To simplify the code,1357* we prevent matches with the string of window index 0.1358*/1359Posf *prev = s->prev;1360uInt wmask = s->w_mask;13611362#ifdef UNALIGNED_OK1363/* Compare two bytes at a time. Note: this is not always beneficial.1364* Try with and without -DUNALIGNED_OK to check.1365*/1366register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;1367register ush scan_start = *(ushf*)scan;1368register ush scan_end = *(ushf*)(scan + best_len - 1);1369#else1370register Bytef *strend = s->window + s->strstart + MAX_MATCH;1371register Byte scan_end1 = scan[best_len - 1];1372register Byte scan_end = scan[best_len];1373#endif13741375/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.1376* It is easy to get rid of this optimization if necessary.1377*/1378Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");13791380/* Do not waste too much time if we already have a good match: */1381if (s->prev_length >= s->good_match) {1382chain_length >>= 2;1383}1384/* Do not look for matches beyond the end of the input. This is necessary1385* to make deflate deterministic.1386*/1387if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead;13881389Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,1390"need lookahead");13911392do {1393Assert(cur_match < s->strstart, "no future");1394match = s->window + cur_match;13951396/* Skip to next match if the match length cannot increase1397* or if the match length is less than 2. Note that the checks below1398* for insufficient lookahead only occur occasionally for performance1399* reasons. Therefore uninitialized memory will be accessed, and1400* conditional jumps will be made that depend on those values.1401* However the length of the match is limited to the lookahead, so1402* the output of deflate is not affected by the uninitialized values.1403*/1404#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)1405/* This code assumes sizeof(unsigned short) == 2. Do not use1406* UNALIGNED_OK if your compiler uses a different size.1407*/1408if (*(ushf*)(match + best_len - 1) != scan_end ||1409*(ushf*)match != scan_start) continue;14101411/* It is not necessary to compare scan[2] and match[2] since they are1412* always equal when the other bytes match, given that the hash keys1413* are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at1414* strstart + 3, + 5, up to strstart + 257. We check for insufficient1415* lookahead only every 4th comparison; the 128th check will be made1416* at strstart + 257. If MAX_MATCH-2 is not a multiple of 8, it is1417* necessary to put more guard bytes at the end of the window, or1418* to check more often for insufficient lookahead.1419*/1420Assert(scan[2] == match[2], "scan[2]?");1421scan++, match++;1422do {1423} while (*(ushf*)(scan += 2) == *(ushf*)(match += 2) &&1424*(ushf*)(scan += 2) == *(ushf*)(match += 2) &&1425*(ushf*)(scan += 2) == *(ushf*)(match += 2) &&1426*(ushf*)(scan += 2) == *(ushf*)(match += 2) &&1427scan < strend);1428/* The funny "do {}" generates better code on most compilers */14291430/* Here, scan <= window + strstart + 257 */1431Assert(scan <= s->window + (unsigned)(s->window_size - 1),1432"wild scan");1433if (*scan == *match) scan++;14341435len = (MAX_MATCH - 1) - (int)(strend - scan);1436scan = strend - (MAX_MATCH-1);14371438#else /* UNALIGNED_OK */14391440if (match[best_len] != scan_end ||1441match[best_len - 1] != scan_end1 ||1442*match != *scan ||1443*++match != scan[1]) continue;14441445/* The check at best_len - 1 can be removed because it will be made1446* again later. (This heuristic is not always a win.)1447* It is not necessary to compare scan[2] and match[2] since they1448* are always equal when the other bytes match, given that1449* the hash keys are equal and that HASH_BITS >= 8.1450*/1451scan += 2, match++;1452Assert(*scan == *match, "match[2]?");14531454/* We check for insufficient lookahead only every 8th comparison;1455* the 256th check will be made at strstart + 258.1456*/1457do {1458} while (*++scan == *++match && *++scan == *++match &&1459*++scan == *++match && *++scan == *++match &&1460*++scan == *++match && *++scan == *++match &&1461*++scan == *++match && *++scan == *++match &&1462scan < strend);14631464Assert(scan <= s->window + (unsigned)(s->window_size - 1),1465"wild scan");14661467len = MAX_MATCH - (int)(strend - scan);1468scan = strend - MAX_MATCH;14691470#endif /* UNALIGNED_OK */14711472if (len > best_len) {1473s->match_start = cur_match;1474best_len = len;1475if (len >= nice_match) break;1476#ifdef UNALIGNED_OK1477scan_end = *(ushf*)(scan + best_len - 1);1478#else1479scan_end1 = scan[best_len - 1];1480scan_end = scan[best_len];1481#endif1482}1483} while ((cur_match = prev[cur_match & wmask]) > limit1484&& --chain_length != 0);14851486if ((uInt)best_len <= s->lookahead) return (uInt)best_len;1487return s->lookahead;1488}14891490#else /* FASTEST */14911492/* ---------------------------------------------------------------------------1493* Optimized version for FASTEST only1494*/1495local uInt longest_match(deflate_state *s, IPos cur_match) {1496register Bytef *scan = s->window + s->strstart; /* current string */1497register Bytef *match; /* matched string */1498register int len; /* length of current match */1499register Bytef *strend = s->window + s->strstart + MAX_MATCH;15001501/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.1502* It is easy to get rid of this optimization if necessary.1503*/1504Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");15051506Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,1507"need lookahead");15081509Assert(cur_match < s->strstart, "no future");15101511match = s->window + cur_match;15121513/* Return failure if the match length is less than 2:1514*/1515if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;15161517/* The check at best_len - 1 can be removed because it will be made1518* again later. (This heuristic is not always a win.)1519* It is not necessary to compare scan[2] and match[2] since they1520* are always equal when the other bytes match, given that1521* the hash keys are equal and that HASH_BITS >= 8.1522*/1523scan += 2, match += 2;1524Assert(*scan == *match, "match[2]?");15251526/* We check for insufficient lookahead only every 8th comparison;1527* the 256th check will be made at strstart + 258.1528*/1529do {1530} while (*++scan == *++match && *++scan == *++match &&1531*++scan == *++match && *++scan == *++match &&1532*++scan == *++match && *++scan == *++match &&1533*++scan == *++match && *++scan == *++match &&1534scan < strend);15351536Assert(scan <= s->window + (unsigned)(s->window_size - 1), "wild scan");15371538len = MAX_MATCH - (int)(strend - scan);15391540if (len < MIN_MATCH) return MIN_MATCH - 1;15411542s->match_start = cur_match;1543return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;1544}15451546#endif /* FASTEST */15471548#ifdef ZLIB_DEBUG15491550#define EQUAL 01551/* result of memcmp for equal strings */15521553/* ===========================================================================1554* Check that the match at match_start is indeed a match.1555*/1556local void check_match(deflate_state *s, IPos start, IPos match, int length) {1557/* check that the match is indeed a match */1558Bytef *back = s->window + (int)match, *here = s->window + start;1559IPos len = length;1560if (match == (IPos)-1) {1561/* match starts one byte before the current window -- just compare the1562subsequent length-1 bytes */1563back++;1564here++;1565len--;1566}1567if (zmemcmp(back, here, len) != EQUAL) {1568fprintf(stderr, " start %u, match %d, length %d\n",1569start, (int)match, length);1570do {1571fprintf(stderr, "(%02x %02x)", *back++, *here++);1572} while (--len != 0);1573z_error("invalid match");1574}1575if (z_verbose > 1) {1576fprintf(stderr,"\\[%d,%d]", start - match, length);1577do { putc(s->window[start++], stderr); } while (--length != 0);1578}1579}1580#else1581# define check_match(s, start, match, length)1582#endif /* ZLIB_DEBUG */15831584/* ===========================================================================1585* Flush the current block, with given end-of-file flag.1586* IN assertion: strstart is set to the end of the current match.1587*/1588#define FLUSH_BLOCK_ONLY(s, last) { \1589_tr_flush_block(s, (s->block_start >= 0L ? \1590(charf *)&s->window[(unsigned)s->block_start] : \1591(charf *)Z_NULL), \1592(ulg)((long)s->strstart - s->block_start), \1593(last)); \1594s->block_start = s->strstart; \1595flush_pending(s->strm); \1596Tracev((stderr,"[FLUSH]")); \1597}15981599/* Same but force premature exit if necessary. */1600#define FLUSH_BLOCK(s, last) { \1601FLUSH_BLOCK_ONLY(s, last); \1602if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \1603}16041605/* Maximum stored block length in deflate format (not including header). */1606#define MAX_STORED 6553516071608/* Minimum of a and b. */1609#define MIN(a, b) ((a) > (b) ? (b) : (a))16101611/* ===========================================================================1612* Copy without compression as much as possible from the input stream, return1613* the current block state.1614*1615* In case deflateParams() is used to later switch to a non-zero compression1616* level, s->matches (otherwise unused when storing) keeps track of the number1617* of hash table slides to perform. If s->matches is 1, then one hash table1618* slide will be done when switching. If s->matches is 2, the maximum value1619* allowed here, then the hash table will be cleared, since two or more slides1620* is the same as a clear.1621*1622* deflate_stored() is written to minimize the number of times an input byte is1623* copied. It is most efficient with large input and output buffers, which1624* maximizes the opportunities to have a single copy from next_in to next_out.1625*/1626local block_state deflate_stored(deflate_state *s, int flush) {1627/* Smallest worthy block size when not flushing or finishing. By default1628* this is 32K. This can be as small as 507 bytes for memLevel == 1. For1629* large input and output buffers, the stored block size will be larger.1630*/1631unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size);16321633/* Copy as many min_block or larger stored blocks directly to next_out as1634* possible. If flushing, copy the remaining available input to next_out as1635* stored blocks, if there is enough space.1636*/1637unsigned len, left, have, last = 0;1638unsigned used = s->strm->avail_in;1639do {1640/* Set len to the maximum size block that we can copy directly with the1641* available input data and output space. Set left to how much of that1642* would be copied from what's left in the window.1643*/1644len = MAX_STORED; /* maximum deflate stored block length */1645have = (s->bi_valid + 42) >> 3; /* number of header bytes */1646if (s->strm->avail_out < have) /* need room for header */1647break;1648/* maximum stored block length that will fit in avail_out: */1649have = s->strm->avail_out - have;1650left = s->strstart - s->block_start; /* bytes left in window */1651if (len > (ulg)left + s->strm->avail_in)1652len = left + s->strm->avail_in; /* limit len to the input */1653if (len > have)1654len = have; /* limit len to the output */16551656/* If the stored block would be less than min_block in length, or if1657* unable to copy all of the available input when flushing, then try1658* copying to the window and the pending buffer instead. Also don't1659* write an empty block when flushing -- deflate() does that.1660*/1661if (len < min_block && ((len == 0 && flush != Z_FINISH) ||1662flush == Z_NO_FLUSH ||1663len != left + s->strm->avail_in))1664break;16651666/* Make a dummy stored block in pending to get the header bytes,1667* including any pending bits. This also updates the debugging counts.1668*/1669last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0;1670_tr_stored_block(s, (char *)0, 0L, last);16711672/* Replace the lengths in the dummy stored block with len. */1673s->pending_buf[s->pending - 4] = len;1674s->pending_buf[s->pending - 3] = len >> 8;1675s->pending_buf[s->pending - 2] = ~len;1676s->pending_buf[s->pending - 1] = ~len >> 8;16771678/* Write the stored block header bytes. */1679flush_pending(s->strm);16801681#ifdef ZLIB_DEBUG1682/* Update debugging counts for the data about to be copied. */1683s->compressed_len += len << 3;1684s->bits_sent += len << 3;1685#endif16861687/* Copy uncompressed bytes from the window to next_out. */1688if (left) {1689if (left > len)1690left = len;1691zmemcpy(s->strm->next_out, s->window + s->block_start, left);1692s->strm->next_out += left;1693s->strm->avail_out -= left;1694s->strm->total_out += left;1695s->block_start += left;1696len -= left;1697}16981699/* Copy uncompressed bytes directly from next_in to next_out, updating1700* the check value.1701*/1702if (len) {1703read_buf(s->strm, s->strm->next_out, len);1704s->strm->next_out += len;1705s->strm->avail_out -= len;1706s->strm->total_out += len;1707}1708} while (last == 0);17091710/* Update the sliding window with the last s->w_size bytes of the copied1711* data, or append all of the copied data to the existing window if less1712* than s->w_size bytes were copied. Also update the number of bytes to1713* insert in the hash tables, in the event that deflateParams() switches to1714* a non-zero compression level.1715*/1716used -= s->strm->avail_in; /* number of input bytes directly copied */1717if (used) {1718/* If any input was used, then no unused input remains in the window,1719* therefore s->block_start == s->strstart.1720*/1721if (used >= s->w_size) { /* supplant the previous history */1722s->matches = 2; /* clear hash */1723zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);1724s->strstart = s->w_size;1725s->insert = s->strstart;1726}1727else {1728if (s->window_size - s->strstart <= used) {1729/* Slide the window down. */1730s->strstart -= s->w_size;1731zmemcpy(s->window, s->window + s->w_size, s->strstart);1732if (s->matches < 2)1733s->matches++; /* add a pending slide_hash() */1734if (s->insert > s->strstart)1735s->insert = s->strstart;1736}1737zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);1738s->strstart += used;1739s->insert += MIN(used, s->w_size - s->insert);1740}1741s->block_start = s->strstart;1742}1743if (s->high_water < s->strstart)1744s->high_water = s->strstart;17451746/* If the last block was written to next_out, then done. */1747if (last)1748return finish_done;17491750/* If flushing and all input has been consumed, then done. */1751if (flush != Z_NO_FLUSH && flush != Z_FINISH &&1752s->strm->avail_in == 0 && (long)s->strstart == s->block_start)1753return block_done;17541755/* Fill the window with any remaining input. */1756have = s->window_size - s->strstart;1757if (s->strm->avail_in > have && s->block_start >= (long)s->w_size) {1758/* Slide the window down. */1759s->block_start -= s->w_size;1760s->strstart -= s->w_size;1761zmemcpy(s->window, s->window + s->w_size, s->strstart);1762if (s->matches < 2)1763s->matches++; /* add a pending slide_hash() */1764have += s->w_size; /* more space now */1765if (s->insert > s->strstart)1766s->insert = s->strstart;1767}1768if (have > s->strm->avail_in)1769have = s->strm->avail_in;1770if (have) {1771read_buf(s->strm, s->window + s->strstart, have);1772s->strstart += have;1773s->insert += MIN(have, s->w_size - s->insert);1774}1775if (s->high_water < s->strstart)1776s->high_water = s->strstart;17771778/* There was not enough avail_out to write a complete worthy or flushed1779* stored block to next_out. Write a stored block to pending instead, if we1780* have enough input for a worthy block, or if flushing and there is enough1781* room for the remaining input as a stored block in the pending buffer.1782*/1783have = (s->bi_valid + 42) >> 3; /* number of header bytes */1784/* maximum stored block length that will fit in pending: */1785have = MIN(s->pending_buf_size - have, MAX_STORED);1786min_block = MIN(have, s->w_size);1787left = s->strstart - s->block_start;1788if (left >= min_block ||1789((left || flush == Z_FINISH) && flush != Z_NO_FLUSH &&1790s->strm->avail_in == 0 && left <= have)) {1791len = MIN(left, have);1792last = flush == Z_FINISH && s->strm->avail_in == 0 &&1793len == left ? 1 : 0;1794_tr_stored_block(s, (charf *)s->window + s->block_start, len, last);1795s->block_start += len;1796flush_pending(s->strm);1797}17981799/* We've done all we can with the available input and output. */1800return last ? finish_started : need_more;1801}18021803/* ===========================================================================1804* Compress as much as possible from the input stream, return the current1805* block state.1806* This function does not perform lazy evaluation of matches and inserts1807* new strings in the dictionary only for unmatched strings or for short1808* matches. It is used only for the fast compression options.1809*/1810local block_state deflate_fast(deflate_state *s, int flush) {1811IPos hash_head; /* head of the hash chain */1812int bflush; /* set if current block must be flushed */18131814for (;;) {1815/* Make sure that we always have enough lookahead, except1816* at the end of the input file. We need MAX_MATCH bytes1817* for the next match, plus MIN_MATCH bytes to insert the1818* string following the next match.1819*/1820if (s->lookahead < MIN_LOOKAHEAD) {1821fill_window(s);1822if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {1823return need_more;1824}1825if (s->lookahead == 0) break; /* flush the current block */1826}18271828/* Insert the string window[strstart .. strstart + 2] in the1829* dictionary, and set hash_head to the head of the hash chain:1830*/1831hash_head = NIL;1832if (s->lookahead >= MIN_MATCH) {1833INSERT_STRING(s, s->strstart, hash_head);1834}18351836/* Find the longest match, discarding those <= prev_length.1837* At this point we have always match_length < MIN_MATCH1838*/1839if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {1840/* To simplify the code, we prevent matches with the string1841* of window index 0 (in particular we have to avoid a match1842* of the string with itself at the start of the input file).1843*/1844s->match_length = longest_match (s, hash_head);1845/* longest_match() sets match_start */1846}1847if (s->match_length >= MIN_MATCH) {1848check_match(s, s->strstart, s->match_start, s->match_length);18491850_tr_tally_dist(s, s->strstart - s->match_start,1851s->match_length - MIN_MATCH, bflush);18521853s->lookahead -= s->match_length;18541855/* Insert new strings in the hash table only if the match length1856* is not too large. This saves time but degrades compression.1857*/1858#ifndef FASTEST1859if (s->match_length <= s->max_insert_length &&1860s->lookahead >= MIN_MATCH) {1861s->match_length--; /* string at strstart already in table */1862do {1863s->strstart++;1864INSERT_STRING(s, s->strstart, hash_head);1865/* strstart never exceeds WSIZE-MAX_MATCH, so there are1866* always MIN_MATCH bytes ahead.1867*/1868} while (--s->match_length != 0);1869s->strstart++;1870} else1871#endif1872{1873s->strstart += s->match_length;1874s->match_length = 0;1875s->ins_h = s->window[s->strstart];1876UPDATE_HASH(s, s->ins_h, s->window[s->strstart + 1]);1877#if MIN_MATCH != 31878Call UPDATE_HASH() MIN_MATCH-3 more times1879#endif1880/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not1881* matter since it will be recomputed at next deflate call.1882*/1883}1884} else {1885/* No match, output a literal byte */1886Tracevv((stderr,"%c", s->window[s->strstart]));1887_tr_tally_lit(s, s->window[s->strstart], bflush);1888s->lookahead--;1889s->strstart++;1890}1891if (bflush) FLUSH_BLOCK(s, 0);1892}1893s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;1894if (flush == Z_FINISH) {1895FLUSH_BLOCK(s, 1);1896return finish_done;1897}1898if (s->sym_next)1899FLUSH_BLOCK(s, 0);1900return block_done;1901}19021903#ifndef FASTEST1904/* ===========================================================================1905* Same as above, but achieves better compression. We use a lazy1906* evaluation for matches: a match is finally adopted only if there is1907* no better match at the next window position.1908*/1909local block_state deflate_slow(deflate_state *s, int flush) {1910IPos hash_head; /* head of hash chain */1911int bflush; /* set if current block must be flushed */19121913/* Process the input block. */1914for (;;) {1915/* Make sure that we always have enough lookahead, except1916* at the end of the input file. We need MAX_MATCH bytes1917* for the next match, plus MIN_MATCH bytes to insert the1918* string following the next match.1919*/1920if (s->lookahead < MIN_LOOKAHEAD) {1921fill_window(s);1922if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {1923return need_more;1924}1925if (s->lookahead == 0) break; /* flush the current block */1926}19271928/* Insert the string window[strstart .. strstart + 2] in the1929* dictionary, and set hash_head to the head of the hash chain:1930*/1931hash_head = NIL;1932if (s->lookahead >= MIN_MATCH) {1933INSERT_STRING(s, s->strstart, hash_head);1934}19351936/* Find the longest match, discarding those <= prev_length.1937*/1938s->prev_length = s->match_length, s->prev_match = s->match_start;1939s->match_length = MIN_MATCH-1;19401941if (hash_head != NIL && s->prev_length < s->max_lazy_match &&1942s->strstart - hash_head <= MAX_DIST(s)) {1943/* To simplify the code, we prevent matches with the string1944* of window index 0 (in particular we have to avoid a match1945* of the string with itself at the start of the input file).1946*/1947s->match_length = longest_match (s, hash_head);1948/* longest_match() sets match_start */19491950if (s->match_length <= 5 && (s->strategy == Z_FILTERED1951#if TOO_FAR <= 327671952|| (s->match_length == MIN_MATCH &&1953s->strstart - s->match_start > TOO_FAR)1954#endif1955)) {19561957/* If prev_match is also MIN_MATCH, match_start is garbage1958* but we will ignore the current match anyway.1959*/1960s->match_length = MIN_MATCH-1;1961}1962}1963/* If there was a match at the previous step and the current1964* match is not better, output the previous match:1965*/1966if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {1967uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;1968/* Do not insert strings in hash table beyond this. */19691970check_match(s, s->strstart - 1, s->prev_match, s->prev_length);19711972_tr_tally_dist(s, s->strstart - 1 - s->prev_match,1973s->prev_length - MIN_MATCH, bflush);19741975/* Insert in hash table all strings up to the end of the match.1976* strstart - 1 and strstart are already inserted. If there is not1977* enough lookahead, the last two strings are not inserted in1978* the hash table.1979*/1980s->lookahead -= s->prev_length - 1;1981s->prev_length -= 2;1982do {1983if (++s->strstart <= max_insert) {1984INSERT_STRING(s, s->strstart, hash_head);1985}1986} while (--s->prev_length != 0);1987s->match_available = 0;1988s->match_length = MIN_MATCH-1;1989s->strstart++;19901991if (bflush) FLUSH_BLOCK(s, 0);19921993} else if (s->match_available) {1994/* If there was no match at the previous position, output a1995* single literal. If there was a match but the current match1996* is longer, truncate the previous match to a single literal.1997*/1998Tracevv((stderr,"%c", s->window[s->strstart - 1]));1999_tr_tally_lit(s, s->window[s->strstart - 1], bflush);2000if (bflush) {2001FLUSH_BLOCK_ONLY(s, 0);2002}2003s->strstart++;2004s->lookahead--;2005if (s->strm->avail_out == 0) return need_more;2006} else {2007/* There is no previous match to compare with, wait for2008* the next step to decide.2009*/2010s->match_available = 1;2011s->strstart++;2012s->lookahead--;2013}2014}2015Assert (flush != Z_NO_FLUSH, "no flush?");2016if (s->match_available) {2017Tracevv((stderr,"%c", s->window[s->strstart - 1]));2018_tr_tally_lit(s, s->window[s->strstart - 1], bflush);2019s->match_available = 0;2020}2021s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;2022if (flush == Z_FINISH) {2023FLUSH_BLOCK(s, 1);2024return finish_done;2025}2026if (s->sym_next)2027FLUSH_BLOCK(s, 0);2028return block_done;2029}2030#endif /* FASTEST */20312032/* ===========================================================================2033* For Z_RLE, simply look for runs of bytes, generate matches only of distance2034* one. Do not maintain a hash table. (It will be regenerated if this run of2035* deflate switches away from Z_RLE.)2036*/2037local block_state deflate_rle(deflate_state *s, int flush) {2038int bflush; /* set if current block must be flushed */2039uInt prev; /* byte at distance one to match */2040Bytef *scan, *strend; /* scan goes up to strend for length of run */20412042for (;;) {2043/* Make sure that we always have enough lookahead, except2044* at the end of the input file. We need MAX_MATCH bytes2045* for the longest run, plus one for the unrolled loop.2046*/2047if (s->lookahead <= MAX_MATCH) {2048fill_window(s);2049if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {2050return need_more;2051}2052if (s->lookahead == 0) break; /* flush the current block */2053}20542055/* See how many times the previous byte repeats */2056s->match_length = 0;2057if (s->lookahead >= MIN_MATCH && s->strstart > 0) {2058scan = s->window + s->strstart - 1;2059prev = *scan;2060if (prev == *++scan && prev == *++scan && prev == *++scan) {2061strend = s->window + s->strstart + MAX_MATCH;2062do {2063} while (prev == *++scan && prev == *++scan &&2064prev == *++scan && prev == *++scan &&2065prev == *++scan && prev == *++scan &&2066prev == *++scan && prev == *++scan &&2067scan < strend);2068s->match_length = MAX_MATCH - (uInt)(strend - scan);2069if (s->match_length > s->lookahead)2070s->match_length = s->lookahead;2071}2072Assert(scan <= s->window + (uInt)(s->window_size - 1),2073"wild scan");2074}20752076/* Emit match if have run of MIN_MATCH or longer, else emit literal */2077if (s->match_length >= MIN_MATCH) {2078check_match(s, s->strstart, s->strstart - 1, s->match_length);20792080_tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);20812082s->lookahead -= s->match_length;2083s->strstart += s->match_length;2084s->match_length = 0;2085} else {2086/* No match, output a literal byte */2087Tracevv((stderr,"%c", s->window[s->strstart]));2088_tr_tally_lit(s, s->window[s->strstart], bflush);2089s->lookahead--;2090s->strstart++;2091}2092if (bflush) FLUSH_BLOCK(s, 0);2093}2094s->insert = 0;2095if (flush == Z_FINISH) {2096FLUSH_BLOCK(s, 1);2097return finish_done;2098}2099if (s->sym_next)2100FLUSH_BLOCK(s, 0);2101return block_done;2102}21032104/* ===========================================================================2105* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.2106* (It will be regenerated if this run of deflate switches away from Huffman.)2107*/2108local block_state deflate_huff(deflate_state *s, int flush) {2109int bflush; /* set if current block must be flushed */21102111for (;;) {2112/* Make sure that we have a literal to write. */2113if (s->lookahead == 0) {2114fill_window(s);2115if (s->lookahead == 0) {2116if (flush == Z_NO_FLUSH)2117return need_more;2118break; /* flush the current block */2119}2120}21212122/* Output a literal byte */2123s->match_length = 0;2124Tracevv((stderr,"%c", s->window[s->strstart]));2125_tr_tally_lit(s, s->window[s->strstart], bflush);2126s->lookahead--;2127s->strstart++;2128if (bflush) FLUSH_BLOCK(s, 0);2129}2130s->insert = 0;2131if (flush == Z_FINISH) {2132FLUSH_BLOCK(s, 1);2133return finish_done;2134}2135if (s->sym_next)2136FLUSH_BLOCK(s, 0);2137return block_done;2138}213921402141