#ifndef TOO_FAR # define TOO_FAR 4096 #endif /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) /* Minimum amount of lookahead, except at the end of the input file. *Seedeflate.cforcommentsabouttheMIN_MATCH+1.
*/
/* Workspace to be allocated for deflate processing */ typedefstruct deflate_workspace { /* State memory for the deflator */
deflate_state deflate_memory; #ifdef CONFIG_ZLIB_DFLTCC /* State memory for s390 hardware deflate */ struct dfltcc_deflate_state dfltcc_memory; #endif
Byte *window_memory;
Pos *prev_memory;
Pos *head_memory; char *overlay_memory;
} deflate_workspace;
#ifdef CONFIG_ZLIB_DFLTCC /* dfltcc_state must be doubleword aligned for DFLTCC call */
static_assert(offsetof(struct deflate_workspace, dfltcc_memory) % 8 == 0); #endif
/* Values for max_lazy_match, good_match and max_chain_length, depending on *thedesiredpacklevel(0..9).Thevaluesgivenbelowhavebeentunedto *excludeworstcaseperformanceforpathologicalfiles.Bettervaluesmaybe *foundforspecificfiles.
*/ typedefstruct config_s {
ush good_length; /* reduce lazy search above this match length */
ush max_lazy; /* do not perform lazy search above this match length */
ush nice_length; /* quit search above this match length */
ush max_chain;
compress_func func;
} config;
/* ========================================================================= */ int zlib_deflateInit2(
z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy
)
{
deflate_state *s; int noheader = 0;
deflate_workspace *mem; char *next;
ush *overlay; /* We overlay pending_buf and d_buf+l_buf. This works since the average *outputsizefor(length,distance)codesis<=24bits.
*/
/* ========================================================================= */ int zlib_deflate(
z_streamp strm, int flush
)
{ int old_flush; /* value of flush param for previous deflate call */
deflate_state *s;
/* Save the adler32 of the preset dictionary: */ if (s->strstart != 0) {
putShortMSB(s, (uInt)(strm->adler >> 16));
putShortMSB(s, (uInt)(strm->adler & 0xffff));
}
strm->adler = 1L;
}
/* Flush as much pending output as possible */ if (s->pending != 0) {
flush_pending(strm); if (strm->avail_out == 0) { /* Since avail_out is 0, deflate will be called again with *moreoutputspace,butpossiblywithbothpendingand *avail_inequaltozero.Therewon'tbeanythingtodo, *butthisisnotanerrorsituationsomakesurewe *returnOKinsteadofBUF_ERRORatnextcallofdeflate:
*/
s->last_flush = -1; return Z_OK;
}
/* Make sure there is something to do and avoid duplicate consecutive *flushes.ForrepeatedanduselesscallswithZ_FINISH,wekeep *returningZ_STREAM_ENDinsteadofZ_BUFF_ERROR.
*/
} elseif (strm->avail_in == 0 && flush <= old_flush &&
flush != Z_FINISH) { return Z_BUF_ERROR;
}
/* User must not provide more input after the first FINISH: */ if (s->status == FINISH_STATE && strm->avail_in != 0) { return Z_BUF_ERROR;
}
/* Start a new block or continue the current one.
*/ if (strm->avail_in != 0 || s->lookahead != 0 ||
(flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
block_state bstate;
/* =========================================================================== *Setmatch_starttothelongestmatchstartingatthegivenstringand *returnitslength.Matchesshorterorequaltoprev_lengtharediscarded, *inwhichcasetheresultisequaltoprev_lengthandmatch_startis *garbage. *INassertions:cur_matchistheheadofthehashchainforthecurrent *string(strstart)anditsdistanceis<=MAX_DIST,andprev_length>=1 *OUTassertion:thematchlengthisnotgreaterthans->lookahead.
*/ /* For 80x86 and 680x0, an optimized version will be provided in match.asm or *match.S.Thecodewillbefunctionallyequivalent.
*/ static uInt longest_match(
deflate_state *s,
IPos cur_match /* current match */
)
{ unsigned chain_length = s->max_chain_length;/* max hash chain length */ register Byte *scan = s->window + s->strstart; /* current string */ register Byte *match; /* matched string */ registerint len; /* length of current match */ int best_len = s->prev_length; /* best match length so far */ int nice_match = s->nice_match; /* stop if match long enough */
IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
s->strstart - (IPos)MAX_DIST(s) : NIL; /* Stop when cur_match becomes <= limit. To simplify the code, *wepreventmatcheswiththestringofwindowindex0.
*/
Pos *prev = s->prev;
uInt wmask = s->w_mask;
#ifdef UNALIGNED_OK /* Compare two bytes at a time. Note: this is not always beneficial. *Trywithandwithout-DUNALIGNED_OKtocheck.
*/ register Byte *strend = s->window + s->strstart + MAX_MATCH - 1; register ush scan_start = *(ush*)scan; register ush scan_end = *(ush*)(scan+best_len-1); #else register Byte *strend = s->window + s->strstart + MAX_MATCH; register Byte scan_end1 = scan[best_len-1]; register Byte scan_end = scan[best_len]; #endif
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. *Itiseasytogetridofthisoptimizationifnecessary.
*/
Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
/* Do not waste too much time if we already have a good match: */ if (s->prev_length >= s->good_match) {
chain_length >>= 2;
} /* Do not look for matches beyond the end of the input. This is necessary *tomakedeflatedeterministic.
*/ if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
do {
Assert(cur_match < s->strstart, "no future");
match = s->window + cur_match;
/* Skip to next match if the match length cannot increase *orifthematchlengthislessthan2:
*/ #if (defined(UNALIGNED_OK) && MAX_MATCH == 258) /* This code assumes sizeof(unsigned short) == 2. Do not use *UNALIGNED_OKifyourcompilerusesadifferentsize.
*/ if (*(ush*)(match+best_len-1) != scan_end ||
*(ush*)match != scan_start) continue;
/* It is not necessary to compare scan[2] and match[2] since they are *alwaysequalwhentheotherbytesmatch,giventhatthehashkeys *areequalandthatHASH_BITS>=8.Compare2bytesatatimeat *strstart+3,+5,...uptostrstart+257.Wecheckforinsufficient *lookaheadonlyevery4thcomparison;the128thcheckwillbemade *atstrstart+257.IfMAX_MATCH-2isnotamultipleof8,itis *necessarytoputmoreguardbytesattheendofthewindow,or *tocheckmoreoftenforinsufficientlookahead.
*/
Assert(scan[2] == match[2], "scan[2]?");
scan++, match++; do {
} while (*(ush*)(scan+=2) == *(ush*)(match+=2) &&
*(ush*)(scan+=2) == *(ush*)(match+=2) &&
*(ush*)(scan+=2) == *(ush*)(match+=2) &&
*(ush*)(scan+=2) == *(ush*)(match+=2) &&
scan < strend); /* The funny "do {}" generates better code on most compilers */
/* The check at best_len-1 can be removed because it will be made *againlater.(Thisheuristicisnotalwaysawin.) *Itisnotnecessarytocomparescan[2]andmatch[2]sincethey *arealwaysequalwhentheotherbytesmatch,giventhat *thehashkeysareequalandthatHASH_BITS>=8.
*/
scan += 2, match++;
Assert(*scan == *match, "match[2]?");
/* We check for insufficient lookahead only every 8th comparison; *the256thcheckwillbemadeatstrstart+258.
*/ do {
} while (*++scan == *++match && *++scan == *++match &&
*++scan == *++match && *++scan == *++match &&
*++scan == *++match && *++scan == *++match &&
*++scan == *++match && *++scan == *++match &&
scan < strend);
if ((uInt)best_len <= s->lookahead) return best_len; return s->lookahead;
}
#ifdef DEBUG_ZLIB /* =========================================================================== *Checkthatthematchatmatch_startisindeedamatch.
*/ staticvoid check_match(
deflate_state *s,
IPos start,
IPos match, int length
)
{ /* check that the match is indeed a match */ if (memcmp((char *)s->window + match, (char *)s->window + start, length)) {
fprintf(stderr, " start %u, match %u, length %d\n",
start, match, length); do {
fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
} while (--length != 0);
z_error("invalid match");
} if (z_verbose > 1) {
fprintf(stderr,"\\[%d,%d]", start-match, length); do { putc(s->window[start++], stderr); } while (--length != 0);
}
} #else # define check_match(s, start, match, length) #endif
/* =========================================================================== *Fillthewindowwhenthelookaheadbecomesinsufficient. *Updatesstrstartandlookahead. * *INassertion:lookahead<MIN_LOOKAHEAD *OUTassertions:strstart<=window_size-MIN_LOOKAHEAD *Atleastonebytehasbeenread,oravail_in==0;readsare *performedforatleasttwobytes(requiredfortheziptranslate_eol *option--notsupportedhere).
*/ staticvoid fill_window(
deflate_state *s
)
{ registerunsigned n, m; register Pos *p; unsigned more; /* Amount of free space at the end of the window. */
uInt wsize = s->w_size;
do {
more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
/* Deal with !@#$% 64K limit: */ if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
more = wsize;
} elseif (more == (unsigned)(-1)) { /* Very unlikely, but possible on 16 bit machine if strstart == 0 *andlookahead==1(inputdoneonebyteattime)
*/
more--;
/* If the window is almost full and there is insufficient lookahead, *movetheupperhalftotheloweronetomakeroomintheupperhalf.
*/
} elseif (s->strstart >= wsize+MAX_DIST(s)) {
memcpy((char *)s->window, (char *)s->window+wsize,
(unsigned)wsize);
s->match_start -= wsize;
s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
s->block_start -= (long) wsize;
/* Slide the hash table (could be avoided with 32 bit values attheexpenseofmemoryusage).Weslideevenwhenlevel==0 tokeepthehashtableconsistentifweswitchbacktolevel>0 later.(Usinglevel0permanentlyisnotanoptimalusageof zlib,sowedon'tcareaboutthispathologicalcase.)
*/
n = s->hash_size;
p = &s->head[n]; do {
m = *--p;
*p = (Pos)(m >= wsize ? m-wsize : NIL);
} while (--n);
n = wsize;
p = &s->prev[n]; do {
m = *--p;
*p = (Pos)(m >= wsize ? m-wsize : NIL); /* If n is not on any hash chain, prev[n] is garbage but *itsvaluewillneverbeused.
*/
} while (--n);
more += wsize;
} if (s->strm->avail_in == 0) return;
/* If there was no sliding: *strstart<=WSIZE+MAX_DIST-1&&lookahead<=MIN_LOOKAHEAD-1&& *more==window_size-lookahead-strstart *=>more>=window_size-(MIN_LOOKAHEAD-1+WSIZE+MAX_DIST-1) *=>more>=window_size-2*WSIZE+2 *IntheBIG_MEMorMMAPcase(notyetsupported), *window_size==input_size+MIN_LOOKAHEAD&& *strstart+s->lookahead<=input_size=>more>=MIN_LOOKAHEAD. *Otherwise,window_size==2*WSIZEsomore>=2. *Iftherewassliding,more>=WSIZE.Soinallcases,more>=2.
*/
Assert(more >= 2, "more < 2");
/* Initialize the hash value now that we have some input: */ if (s->lookahead >= MIN_MATCH) {
s->ins_h = s->window[s->strstart];
UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); #if MIN_MATCH != 3
Call UPDATE_HASH() MIN_MATCH-3 more times #endif
} /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, *butthisisnotimportantsinceonlyliteralbyteswillbeemitted.
*/
} while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
}
if (s->lookahead == 0) break; /* flush the current block */
}
Assert(s->block_start >= 0L, "block gone");
s->strstart += s->lookahead;
s->lookahead = 0;
/* Emit a stored block if pending_buf will be full: */
max_start = s->block_start + max_block_size; if (s->strstart == 0 || (ulg)s->strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */
s->lookahead = (uInt)(s->strstart - max_start);
s->strstart = (uInt)max_start;
FLUSH_BLOCK(s, 0);
} /* Flush if we may have to slide, otherwise block_start may become *negativeandthedatawillbegone:
*/ if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
FLUSH_BLOCK(s, 0);
}
}
FLUSH_BLOCK(s, flush == Z_FINISH); return flush == Z_FINISH ? finish_done : block_done;
}
/* =========================================================================== *Compressasmuchaspossiblefromtheinputstream,returnthecurrent *blockstate. *Thisfunctiondoesnotperformlazyevaluationofmatchesandinserts *newstringsinthedictionaryonlyforunmatchedstringsorforshort *matches.Itisusedonlyforthefastcompressionoptions.
*/ static block_state deflate_fast(
deflate_state *s, int flush
)
{
IPos hash_head = NIL; /* head of the hash chain */ int bflush; /* set if current block must be flushed */
for (;;) { /* Make sure that we always have enough lookahead, except *attheendoftheinputfile.WeneedMAX_MATCHbytes *forthenextmatch,plusMIN_MATCHbytestoinsertthe *stringfollowingthenextmatch.
*/ if (s->lookahead < MIN_LOOKAHEAD) {
fill_window(s); if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return need_more;
} if (s->lookahead == 0) break; /* flush the current block */
}
/* Insert the string window[strstart .. strstart+2] in the *dictionary,andsethash_headtotheheadofthehashchain:
*/ if (s->lookahead >= MIN_MATCH) {
INSERT_STRING(s, s->strstart, hash_head);
}
/* Find the longest match, discarding those <= prev_length. *Atthispointwehavealwaysmatch_length<MIN_MATCH
*/ if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { /* To simplify the code, we prevent matches with the string *ofwindowindex0(inparticularwehavetoavoidamatch *ofthestringwithitselfatthestartoftheinputfile).
*/ if (s->strategy != Z_HUFFMAN_ONLY) {
s->match_length = longest_match (s, hash_head);
} /* longest_match() sets match_start */
} if (s->match_length >= MIN_MATCH) {
check_match(s, s->strstart, s->match_start, s->match_length);
/* Insert new strings in the hash table only if the match length *isnottoolarge.Thissavestimebutdegradescompression.
*/ if (s->match_length <= s->max_insert_length &&
s->lookahead >= MIN_MATCH) {
s->match_length--; /* string at strstart already in hash table */ do {
s->strstart++;
INSERT_STRING(s, s->strstart, hash_head); /* strstart never exceeds WSIZE-MAX_MATCH, so there are *alwaysMIN_MATCHbytesahead.
*/
} while (--s->match_length != 0);
s->strstart++;
} else {
s->strstart += s->match_length;
s->match_length = 0;
s->ins_h = s->window[s->strstart];
UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); #if MIN_MATCH != 3
Call UPDATE_HASH() MIN_MATCH-3 more times #endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not *mattersinceitwillberecomputedatnextdeflatecall.
*/
}
} else { /* No match, output a literal byte */
Tracevv((stderr,"%c", s->window[s->strstart]));
bflush = zlib_tr_tally (s, 0, s->window[s->strstart]);
s->lookahead--;
s->strstart++;
} if (bflush) FLUSH_BLOCK(s, 0);
}
FLUSH_BLOCK(s, flush == Z_FINISH); return flush == Z_FINISH ? finish_done : block_done;
}
/* =========================================================================== *Sameasabove,butachievesbettercompression.Weusealazy *evaluationformatches:amatchisfinallyadoptedonlyifthereis *nobettermatchatthenextwindowposition.
*/ static block_state deflate_slow(
deflate_state *s, int flush
)
{
IPos hash_head = NIL; /* head of hash chain */ int bflush; /* set if current block must be flushed */
/* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except *attheendoftheinputfile.WeneedMAX_MATCHbytes *forthenextmatch,plusMIN_MATCHbytestoinsertthe *stringfollowingthenextmatch.
*/ if (s->lookahead < MIN_LOOKAHEAD) {
fill_window(s); if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return need_more;
} if (s->lookahead == 0) break; /* flush the current block */
}
/* Insert the string window[strstart .. strstart+2] in the *dictionary,andsethash_headtotheheadofthehashchain:
*/ if (s->lookahead >= MIN_MATCH) {
INSERT_STRING(s, s->strstart, hash_head);
}
/* Find the longest match, discarding those <= prev_length.
*/
s->prev_length = s->match_length, s->prev_match = s->match_start;
s->match_length = MIN_MATCH-1;
if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
s->strstart - hash_head <= MAX_DIST(s)) { /* To simplify the code, we prevent matches with the string *ofwindowindex0(inparticularwehavetoavoidamatch *ofthestringwithitselfatthestartoftheinputfile).
*/ if (s->strategy != Z_HUFFMAN_ONLY) {
s->match_length = longest_match (s, hash_head);
} /* longest_match() sets match_start */
/* If prev_match is also MIN_MATCH, match_start is garbage *butwewillignorethecurrentmatchanyway.
*/
s->match_length = MIN_MATCH-1;
}
} /* If there was a match at the previous step and the current *matchisnotbetter,outputthepreviousmatch:
*/ if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */
/* Insert in hash table all strings up to the end of the match. *strstart-1andstrstartarealreadyinserted.Ifthereisnot *enoughlookahead,thelasttwostringsarenotinsertedin *thehashtable.
*/
s->lookahead -= s->prev_length-1;
s->prev_length -= 2; do { if (++s->strstart <= max_insert) {
INSERT_STRING(s, s->strstart, hash_head);
}
} while (--s->prev_length != 0);
s->match_available = 0;
s->match_length = MIN_MATCH-1;
s->strstart++;
if (bflush) FLUSH_BLOCK(s, 0);
} elseif (s->match_available) { /* If there was no match at the previous position, output a *singleliteral.Iftherewasamatchbutthecurrentmatch *islonger,truncatethepreviousmatchtoasingleliteral.
*/
Tracevv((stderr,"%c", s->window[s->strstart-1])); if (zlib_tr_tally (s, 0, s->window[s->strstart-1])) {
FLUSH_BLOCK_ONLY(s, 0);
}
s->strstart++;
s->lookahead--; if (s->strm->avail_out == 0) return need_more;
} else { /* There is no previous match to compare with, wait for *thenextsteptodecide.
*/
s->match_available = 1;
s->strstart++;
s->lookahead--;
}
}
Assert (flush != Z_NO_FLUSH, "no flush?"); if (s->match_available) {
Tracevv((stderr,"%c", s->window[s->strstart-1]));
zlib_tr_tally (s, 0, s->window[s->strstart-1]);
s->match_available = 0;
}
FLUSH_BLOCK(s, flush == Z_FINISH); return flush == Z_FINISH ? finish_done : block_done;
}
int zlib_deflate_workspacesize(int windowBits, int memLevel)
{ if (windowBits < 0) /* undocumented feature: suppress zlib header */
windowBits = -windowBits;
/* Since the return value is typically passed to vmalloc() unchecked... */
BUG_ON(memLevel < 1 || memLevel > MAX_MEM_LEVEL || windowBits < 9 ||
windowBits > 15);
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.