Path: blob/main/sys/contrib/openzfs/module/zstd/lib/compress/zstd_opt.c
48774 views
// SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0-only1/*2* Copyright (c) 2016-2020, Przemyslaw Skibinski, Yann Collet, Facebook, Inc.3* All rights reserved.4*5* This source code is licensed under both the BSD-style license (found in the6* LICENSE file in the root directory of this source tree) and the GPLv2 (found7* in the COPYING file in the root directory of this source tree).8* You may select, at your option, one of the above-listed licenses.9*/1011#include "zstd_compress_internal.h"12#include "hist.h"13#include "zstd_opt.h"141516#define ZSTD_LITFREQ_ADD 2 /* scaling factor for litFreq, so that frequencies adapt faster to new stats */17#define ZSTD_FREQ_DIV 4 /* log factor when using previous stats to init next stats */18#define ZSTD_MAX_PRICE (1<<30)1920#define ZSTD_PREDEF_THRESHOLD 1024 /* if srcSize < ZSTD_PREDEF_THRESHOLD, symbols' cost is assumed static, directly determined by pre-defined distributions */212223/*-*************************************24* Price functions for optimal parser25***************************************/2627#if 0 /* approximation at bit level */28# define BITCOST_ACCURACY 029# define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)30# define WEIGHT(stat) ((void)opt, ZSTD_bitWeight(stat))31#elif 0 /* fractional bit accuracy */32# define BITCOST_ACCURACY 833# define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)34# define WEIGHT(stat,opt) ((void)opt, ZSTD_fracWeight(stat))35#else /* opt==approx, ultra==accurate */36# define BITCOST_ACCURACY 837# define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)38# define WEIGHT(stat,opt) (opt ? ZSTD_fracWeight(stat) : ZSTD_bitWeight(stat))39#endif4041MEM_STATIC U32 ZSTD_bitWeight(U32 stat)42{43return (ZSTD_highbit32(stat+1) * BITCOST_MULTIPLIER);44}4546MEM_STATIC U32 ZSTD_fracWeight(U32 rawStat)47{48U32 const stat = rawStat + 1;49U32 const hb = ZSTD_highbit32(stat);50U32 const BWeight = hb * BITCOST_MULTIPLIER;51U32 const FWeight = (stat << BITCOST_ACCURACY) >> hb;52U32 const weight = BWeight + FWeight;53assert(hb + BITCOST_ACCURACY < 31);54return weight;55}5657#if (DEBUGLEVEL>=2)58/* debugging function,59* @return price in bytes as fractional value60* for debug messages only */61MEM_STATIC double ZSTD_fCost(U32 price)62{63return (double)price / (BITCOST_MULTIPLIER*8);64}65#endif6667static int ZSTD_compressedLiterals(optState_t const* const optPtr)68{69return optPtr->literalCompressionMode != ZSTD_lcm_uncompressed;70}7172static void ZSTD_setBasePrices(optState_t* optPtr, int optLevel)73{74if (ZSTD_compressedLiterals(optPtr))75optPtr->litSumBasePrice = WEIGHT(optPtr->litSum, optLevel);76optPtr->litLengthSumBasePrice = WEIGHT(optPtr->litLengthSum, optLevel);77optPtr->matchLengthSumBasePrice = WEIGHT(optPtr->matchLengthSum, optLevel);78optPtr->offCodeSumBasePrice = WEIGHT(optPtr->offCodeSum, optLevel);79}808182/* ZSTD_downscaleStat() :83* reduce all elements in table by a factor 2^(ZSTD_FREQ_DIV+malus)84* return the resulting sum of elements */85static U32 ZSTD_downscaleStat(unsigned* table, U32 lastEltIndex, int malus)86{87U32 s, sum=0;88DEBUGLOG(5, "ZSTD_downscaleStat (nbElts=%u)", (unsigned)lastEltIndex+1);89assert(ZSTD_FREQ_DIV+malus > 0 && ZSTD_FREQ_DIV+malus < 31);90for (s=0; s<lastEltIndex+1; s++) {91table[s] = 1 + (table[s] >> (ZSTD_FREQ_DIV+malus));92sum += table[s];93}94return sum;95}9697/* ZSTD_rescaleFreqs() :98* if first block (detected by optPtr->litLengthSum == 0) : init statistics99* take hints from dictionary if there is one100* or init from zero, using src for literals stats, or flat 1 for match symbols101* otherwise downscale existing stats, to be used as seed for next block.102*/103static void104ZSTD_rescaleFreqs(optState_t* const optPtr,105const BYTE* const src, size_t const srcSize,106int const optLevel)107{108int const compressedLiterals = ZSTD_compressedLiterals(optPtr);109DEBUGLOG(5, "ZSTD_rescaleFreqs (srcSize=%u)", (unsigned)srcSize);110optPtr->priceType = zop_dynamic;111112if (optPtr->litLengthSum == 0) { /* first block : init */113if (srcSize <= ZSTD_PREDEF_THRESHOLD) { /* heuristic */114DEBUGLOG(5, "(srcSize <= ZSTD_PREDEF_THRESHOLD) => zop_predef");115optPtr->priceType = zop_predef;116}117118assert(optPtr->symbolCosts != NULL);119if (optPtr->symbolCosts->huf.repeatMode == HUF_repeat_valid) {120/* huffman table presumed generated by dictionary */121optPtr->priceType = zop_dynamic;122123if (compressedLiterals) {124unsigned lit;125assert(optPtr->litFreq != NULL);126optPtr->litSum = 0;127for (lit=0; lit<=MaxLit; lit++) {128U32 const scaleLog = 11; /* scale to 2K */129U32 const bitCost = HUF_getNbBits(optPtr->symbolCosts->huf.CTable, lit);130assert(bitCost <= scaleLog);131optPtr->litFreq[lit] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;132optPtr->litSum += optPtr->litFreq[lit];133} }134135{ unsigned ll;136FSE_CState_t llstate;137FSE_initCState(&llstate, optPtr->symbolCosts->fse.litlengthCTable);138optPtr->litLengthSum = 0;139for (ll=0; ll<=MaxLL; ll++) {140U32 const scaleLog = 10; /* scale to 1K */141U32 const bitCost = FSE_getMaxNbBits(llstate.symbolTT, ll);142assert(bitCost < scaleLog);143optPtr->litLengthFreq[ll] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;144optPtr->litLengthSum += optPtr->litLengthFreq[ll];145} }146147{ unsigned ml;148FSE_CState_t mlstate;149FSE_initCState(&mlstate, optPtr->symbolCosts->fse.matchlengthCTable);150optPtr->matchLengthSum = 0;151for (ml=0; ml<=MaxML; ml++) {152U32 const scaleLog = 10;153U32 const bitCost = FSE_getMaxNbBits(mlstate.symbolTT, ml);154assert(bitCost < scaleLog);155optPtr->matchLengthFreq[ml] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;156optPtr->matchLengthSum += optPtr->matchLengthFreq[ml];157} }158159{ unsigned of;160FSE_CState_t ofstate;161FSE_initCState(&ofstate, optPtr->symbolCosts->fse.offcodeCTable);162optPtr->offCodeSum = 0;163for (of=0; of<=MaxOff; of++) {164U32 const scaleLog = 10;165U32 const bitCost = FSE_getMaxNbBits(ofstate.symbolTT, of);166assert(bitCost < scaleLog);167optPtr->offCodeFreq[of] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;168optPtr->offCodeSum += optPtr->offCodeFreq[of];169} }170171} else { /* not a dictionary */172173assert(optPtr->litFreq != NULL);174if (compressedLiterals) {175unsigned lit = MaxLit;176HIST_count_simple(optPtr->litFreq, &lit, src, srcSize); /* use raw first block to init statistics */177optPtr->litSum = ZSTD_downscaleStat(optPtr->litFreq, MaxLit, 1);178}179180{ unsigned ll;181for (ll=0; ll<=MaxLL; ll++)182optPtr->litLengthFreq[ll] = 1;183}184optPtr->litLengthSum = MaxLL+1;185186{ unsigned ml;187for (ml=0; ml<=MaxML; ml++)188optPtr->matchLengthFreq[ml] = 1;189}190optPtr->matchLengthSum = MaxML+1;191192{ unsigned of;193for (of=0; of<=MaxOff; of++)194optPtr->offCodeFreq[of] = 1;195}196optPtr->offCodeSum = MaxOff+1;197198}199200} else { /* new block : re-use previous statistics, scaled down */201202if (compressedLiterals)203optPtr->litSum = ZSTD_downscaleStat(optPtr->litFreq, MaxLit, 1);204optPtr->litLengthSum = ZSTD_downscaleStat(optPtr->litLengthFreq, MaxLL, 0);205optPtr->matchLengthSum = ZSTD_downscaleStat(optPtr->matchLengthFreq, MaxML, 0);206optPtr->offCodeSum = ZSTD_downscaleStat(optPtr->offCodeFreq, MaxOff, 0);207}208209ZSTD_setBasePrices(optPtr, optLevel);210}211212/* ZSTD_rawLiteralsCost() :213* price of literals (only) in specified segment (which length can be 0).214* does not include price of literalLength symbol */215static U32 ZSTD_rawLiteralsCost(const BYTE* const literals, U32 const litLength,216const optState_t* const optPtr,217int optLevel)218{219if (litLength == 0) return 0;220221if (!ZSTD_compressedLiterals(optPtr))222return (litLength << 3) * BITCOST_MULTIPLIER; /* Uncompressed - 8 bytes per literal. */223224if (optPtr->priceType == zop_predef)225return (litLength*6) * BITCOST_MULTIPLIER; /* 6 bit per literal - no statistic used */226227/* dynamic statistics */228{ U32 price = litLength * optPtr->litSumBasePrice;229U32 u;230for (u=0; u < litLength; u++) {231assert(WEIGHT(optPtr->litFreq[literals[u]], optLevel) <= optPtr->litSumBasePrice); /* literal cost should never be negative */232price -= WEIGHT(optPtr->litFreq[literals[u]], optLevel);233}234return price;235}236}237238/* ZSTD_litLengthPrice() :239* cost of literalLength symbol */240static U32 ZSTD_litLengthPrice(U32 const litLength, const optState_t* const optPtr, int optLevel)241{242if (optPtr->priceType == zop_predef) return WEIGHT(litLength, optLevel);243244/* dynamic statistics */245{ U32 const llCode = ZSTD_LLcode(litLength);246return (LL_bits[llCode] * BITCOST_MULTIPLIER)247+ optPtr->litLengthSumBasePrice248- WEIGHT(optPtr->litLengthFreq[llCode], optLevel);249}250}251252/* ZSTD_getMatchPrice() :253* Provides the cost of the match part (offset + matchLength) of a sequence254* Must be combined with ZSTD_fullLiteralsCost() to get the full cost of a sequence.255* optLevel: when <2, favors small offset for decompression speed (improved cache efficiency) */256FORCE_INLINE_TEMPLATE U32257ZSTD_getMatchPrice(U32 const offset,258U32 const matchLength,259const optState_t* const optPtr,260int const optLevel)261{262U32 price;263U32 const offCode = ZSTD_highbit32(offset+1);264U32 const mlBase = matchLength - MINMATCH;265assert(matchLength >= MINMATCH);266267if (optPtr->priceType == zop_predef) /* fixed scheme, do not use statistics */268return WEIGHT(mlBase, optLevel) + ((16 + offCode) * BITCOST_MULTIPLIER);269270/* dynamic statistics */271price = (offCode * BITCOST_MULTIPLIER) + (optPtr->offCodeSumBasePrice - WEIGHT(optPtr->offCodeFreq[offCode], optLevel));272if ((optLevel<2) /*static*/ && offCode >= 20)273price += (offCode-19)*2 * BITCOST_MULTIPLIER; /* handicap for long distance offsets, favor decompression speed */274275/* match Length */276{ U32 const mlCode = ZSTD_MLcode(mlBase);277price += (ML_bits[mlCode] * BITCOST_MULTIPLIER) + (optPtr->matchLengthSumBasePrice - WEIGHT(optPtr->matchLengthFreq[mlCode], optLevel));278}279280price += BITCOST_MULTIPLIER / 5; /* heuristic : make matches a bit more costly to favor less sequences -> faster decompression speed */281282DEBUGLOG(8, "ZSTD_getMatchPrice(ml:%u) = %u", matchLength, price);283return price;284}285286/* ZSTD_updateStats() :287* assumption : literals + litLengtn <= iend */288static void ZSTD_updateStats(optState_t* const optPtr,289U32 litLength, const BYTE* literals,290U32 offsetCode, U32 matchLength)291{292/* literals */293if (ZSTD_compressedLiterals(optPtr)) {294U32 u;295for (u=0; u < litLength; u++)296optPtr->litFreq[literals[u]] += ZSTD_LITFREQ_ADD;297optPtr->litSum += litLength*ZSTD_LITFREQ_ADD;298}299300/* literal Length */301{ U32 const llCode = ZSTD_LLcode(litLength);302optPtr->litLengthFreq[llCode]++;303optPtr->litLengthSum++;304}305306/* match offset code (0-2=>repCode; 3+=>offset+2) */307{ U32 const offCode = ZSTD_highbit32(offsetCode+1);308assert(offCode <= MaxOff);309optPtr->offCodeFreq[offCode]++;310optPtr->offCodeSum++;311}312313/* match Length */314{ U32 const mlBase = matchLength - MINMATCH;315U32 const mlCode = ZSTD_MLcode(mlBase);316optPtr->matchLengthFreq[mlCode]++;317optPtr->matchLengthSum++;318}319}320321322/* ZSTD_readMINMATCH() :323* function safe only for comparisons324* assumption : memPtr must be at least 4 bytes before end of buffer */325MEM_STATIC U32 ZSTD_readMINMATCH(const void* memPtr, U32 length)326{327switch (length)328{329default :330case 4 : return MEM_read32(memPtr);331case 3 : if (MEM_isLittleEndian())332return MEM_read32(memPtr)<<8;333else334return MEM_read32(memPtr)>>8;335}336}337338339/* Update hashTable3 up to ip (excluded)340Assumption : always within prefix (i.e. not within extDict) */341static U32 ZSTD_insertAndFindFirstIndexHash3 (ZSTD_matchState_t* ms,342U32* nextToUpdate3,343const BYTE* const ip)344{345U32* const hashTable3 = ms->hashTable3;346U32 const hashLog3 = ms->hashLog3;347const BYTE* const base = ms->window.base;348U32 idx = *nextToUpdate3;349U32 const target = (U32)(ip - base);350size_t const hash3 = ZSTD_hash3Ptr(ip, hashLog3);351assert(hashLog3 > 0);352353while(idx < target) {354hashTable3[ZSTD_hash3Ptr(base+idx, hashLog3)] = idx;355idx++;356}357358*nextToUpdate3 = target;359return hashTable3[hash3];360}361362363/*-*************************************364* Binary Tree search365***************************************/366/** ZSTD_insertBt1() : add one or multiple positions to tree.367* ip : assumed <= iend-8 .368* @return : nb of positions added */369static U32 ZSTD_insertBt1(370ZSTD_matchState_t* ms,371const BYTE* const ip, const BYTE* const iend,372U32 const mls, const int extDict)373{374const ZSTD_compressionParameters* const cParams = &ms->cParams;375U32* const hashTable = ms->hashTable;376U32 const hashLog = cParams->hashLog;377size_t const h = ZSTD_hashPtr(ip, hashLog, mls);378U32* const bt = ms->chainTable;379U32 const btLog = cParams->chainLog - 1;380U32 const btMask = (1 << btLog) - 1;381U32 matchIndex = hashTable[h];382size_t commonLengthSmaller=0, commonLengthLarger=0;383const BYTE* const base = ms->window.base;384const BYTE* const dictBase = ms->window.dictBase;385const U32 dictLimit = ms->window.dictLimit;386const BYTE* const dictEnd = dictBase + dictLimit;387const BYTE* const prefixStart = base + dictLimit;388const BYTE* match;389const U32 current = (U32)(ip-base);390const U32 btLow = btMask >= current ? 0 : current - btMask;391U32* smallerPtr = bt + 2*(current&btMask);392U32* largerPtr = smallerPtr + 1;393U32 dummy32; /* to be nullified at the end */394U32 const windowLow = ms->window.lowLimit;395U32 matchEndIdx = current+8+1;396size_t bestLength = 8;397U32 nbCompares = 1U << cParams->searchLog;398#ifdef ZSTD_C_PREDICT399U32 predictedSmall = *(bt + 2*((current-1)&btMask) + 0);400U32 predictedLarge = *(bt + 2*((current-1)&btMask) + 1);401predictedSmall += (predictedSmall>0);402predictedLarge += (predictedLarge>0);403#endif /* ZSTD_C_PREDICT */404405DEBUGLOG(8, "ZSTD_insertBt1 (%u)", current);406407assert(ip <= iend-8); /* required for h calculation */408hashTable[h] = current; /* Update Hash Table */409410assert(windowLow > 0);411while (nbCompares-- && (matchIndex >= windowLow)) {412U32* const nextPtr = bt + 2*(matchIndex & btMask);413size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */414assert(matchIndex < current);415416#ifdef ZSTD_C_PREDICT /* note : can create issues when hlog small <= 11 */417const U32* predictPtr = bt + 2*((matchIndex-1) & btMask); /* written this way, as bt is a roll buffer */418if (matchIndex == predictedSmall) {419/* no need to check length, result known */420*smallerPtr = matchIndex;421if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */422smallerPtr = nextPtr+1; /* new "smaller" => larger of match */423matchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */424predictedSmall = predictPtr[1] + (predictPtr[1]>0);425continue;426}427if (matchIndex == predictedLarge) {428*largerPtr = matchIndex;429if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */430largerPtr = nextPtr;431matchIndex = nextPtr[0];432predictedLarge = predictPtr[0] + (predictPtr[0]>0);433continue;434}435#endif436437if (!extDict || (matchIndex+matchLength >= dictLimit)) {438assert(matchIndex+matchLength >= dictLimit); /* might be wrong if actually extDict */439match = base + matchIndex;440matchLength += ZSTD_count(ip+matchLength, match+matchLength, iend);441} else {442match = dictBase + matchIndex;443matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);444if (matchIndex+matchLength >= dictLimit)445match = base + matchIndex; /* to prepare for next usage of match[matchLength] */446}447448if (matchLength > bestLength) {449bestLength = matchLength;450if (matchLength > matchEndIdx - matchIndex)451matchEndIdx = matchIndex + (U32)matchLength;452}453454if (ip+matchLength == iend) { /* equal : no way to know if inf or sup */455break; /* drop , to guarantee consistency ; miss a bit of compression, but other solutions can corrupt tree */456}457458if (match[matchLength] < ip[matchLength]) { /* necessarily within buffer */459/* match is smaller than current */460*smallerPtr = matchIndex; /* update smaller idx */461commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */462if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop searching */463smallerPtr = nextPtr+1; /* new "candidate" => larger than match, which was smaller than target */464matchIndex = nextPtr[1]; /* new matchIndex, larger than previous and closer to current */465} else {466/* match is larger than current */467*largerPtr = matchIndex;468commonLengthLarger = matchLength;469if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop searching */470largerPtr = nextPtr;471matchIndex = nextPtr[0];472} }473474*smallerPtr = *largerPtr = 0;475{ U32 positions = 0;476if (bestLength > 384) positions = MIN(192, (U32)(bestLength - 384)); /* speed optimization */477assert(matchEndIdx > current + 8);478return MAX(positions, matchEndIdx - (current + 8));479}480}481482FORCE_INLINE_TEMPLATE483void ZSTD_updateTree_internal(484ZSTD_matchState_t* ms,485const BYTE* const ip, const BYTE* const iend,486const U32 mls, const ZSTD_dictMode_e dictMode)487{488const BYTE* const base = ms->window.base;489U32 const target = (U32)(ip - base);490U32 idx = ms->nextToUpdate;491DEBUGLOG(6, "ZSTD_updateTree_internal, from %u to %u (dictMode:%u)",492idx, target, dictMode);493494while(idx < target) {495U32 const forward = ZSTD_insertBt1(ms, base+idx, iend, mls, dictMode == ZSTD_extDict);496assert(idx < (U32)(idx + forward));497idx += forward;498}499assert((size_t)(ip - base) <= (size_t)(U32)(-1));500assert((size_t)(iend - base) <= (size_t)(U32)(-1));501ms->nextToUpdate = target;502}503504void ZSTD_updateTree(ZSTD_matchState_t* ms, const BYTE* ip, const BYTE* iend) {505ZSTD_updateTree_internal(ms, ip, iend, ms->cParams.minMatch, ZSTD_noDict);506}507508FORCE_INLINE_TEMPLATE509U32 ZSTD_insertBtAndGetAllMatches (510ZSTD_match_t* matches, /* store result (found matches) in this table (presumed large enough) */511ZSTD_matchState_t* ms,512U32* nextToUpdate3,513const BYTE* const ip, const BYTE* const iLimit, const ZSTD_dictMode_e dictMode,514const U32 rep[ZSTD_REP_NUM],515U32 const ll0, /* tells if associated literal length is 0 or not. This value must be 0 or 1 */516const U32 lengthToBeat,517U32 const mls /* template */)518{519const ZSTD_compressionParameters* const cParams = &ms->cParams;520U32 const sufficient_len = MIN(cParams->targetLength, ZSTD_OPT_NUM -1);521const BYTE* const base = ms->window.base;522U32 const current = (U32)(ip-base);523U32 const hashLog = cParams->hashLog;524U32 const minMatch = (mls==3) ? 3 : 4;525U32* const hashTable = ms->hashTable;526size_t const h = ZSTD_hashPtr(ip, hashLog, mls);527U32 matchIndex = hashTable[h];528U32* const bt = ms->chainTable;529U32 const btLog = cParams->chainLog - 1;530U32 const btMask= (1U << btLog) - 1;531size_t commonLengthSmaller=0, commonLengthLarger=0;532const BYTE* const dictBase = ms->window.dictBase;533U32 const dictLimit = ms->window.dictLimit;534const BYTE* const dictEnd = dictBase + dictLimit;535const BYTE* const prefixStart = base + dictLimit;536U32 const btLow = (btMask >= current) ? 0 : current - btMask;537U32 const windowLow = ZSTD_getLowestMatchIndex(ms, current, cParams->windowLog);538U32 const matchLow = windowLow ? windowLow : 1;539U32* smallerPtr = bt + 2*(current&btMask);540U32* largerPtr = bt + 2*(current&btMask) + 1;541U32 matchEndIdx = current+8+1; /* farthest referenced position of any match => detects repetitive patterns */542U32 dummy32; /* to be nullified at the end */543U32 mnum = 0;544U32 nbCompares = 1U << cParams->searchLog;545546const ZSTD_matchState_t* dms = dictMode == ZSTD_dictMatchState ? ms->dictMatchState : NULL;547const ZSTD_compressionParameters* const dmsCParams =548dictMode == ZSTD_dictMatchState ? &dms->cParams : NULL;549const BYTE* const dmsBase = dictMode == ZSTD_dictMatchState ? dms->window.base : NULL;550const BYTE* const dmsEnd = dictMode == ZSTD_dictMatchState ? dms->window.nextSrc : NULL;551U32 const dmsHighLimit = dictMode == ZSTD_dictMatchState ? (U32)(dmsEnd - dmsBase) : 0;552U32 const dmsLowLimit = dictMode == ZSTD_dictMatchState ? dms->window.lowLimit : 0;553U32 const dmsIndexDelta = dictMode == ZSTD_dictMatchState ? windowLow - dmsHighLimit : 0;554U32 const dmsHashLog = dictMode == ZSTD_dictMatchState ? dmsCParams->hashLog : hashLog;555U32 const dmsBtLog = dictMode == ZSTD_dictMatchState ? dmsCParams->chainLog - 1 : btLog;556U32 const dmsBtMask = dictMode == ZSTD_dictMatchState ? (1U << dmsBtLog) - 1 : 0;557U32 const dmsBtLow = dictMode == ZSTD_dictMatchState && dmsBtMask < dmsHighLimit - dmsLowLimit ? dmsHighLimit - dmsBtMask : dmsLowLimit;558559size_t bestLength = lengthToBeat-1;560DEBUGLOG(8, "ZSTD_insertBtAndGetAllMatches: current=%u", current);561562/* check repCode */563assert(ll0 <= 1); /* necessarily 1 or 0 */564{ U32 const lastR = ZSTD_REP_NUM + ll0;565U32 repCode;566for (repCode = ll0; repCode < lastR; repCode++) {567U32 const repOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];568U32 const repIndex = current - repOffset;569U32 repLen = 0;570assert(current >= dictLimit);571if (repOffset-1 /* intentional overflow, discards 0 and -1 */ < current-dictLimit) { /* equivalent to `current > repIndex >= dictLimit` */572/* We must validate the repcode offset because when we're using a dictionary the573* valid offset range shrinks when the dictionary goes out of bounds.574*/575if ((repIndex >= windowLow) & (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(ip - repOffset, minMatch))) {576repLen = (U32)ZSTD_count(ip+minMatch, ip+minMatch-repOffset, iLimit) + minMatch;577}578} else { /* repIndex < dictLimit || repIndex >= current */579const BYTE* const repMatch = dictMode == ZSTD_dictMatchState ?580dmsBase + repIndex - dmsIndexDelta :581dictBase + repIndex;582assert(current >= windowLow);583if ( dictMode == ZSTD_extDict584&& ( ((repOffset-1) /*intentional overflow*/ < current - windowLow) /* equivalent to `current > repIndex >= windowLow` */585& (((U32)((dictLimit-1) - repIndex) >= 3) ) /* intentional overflow : do not test positions overlapping 2 memory segments */)586&& (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(repMatch, minMatch)) ) {587repLen = (U32)ZSTD_count_2segments(ip+minMatch, repMatch+minMatch, iLimit, dictEnd, prefixStart) + minMatch;588}589if (dictMode == ZSTD_dictMatchState590&& ( ((repOffset-1) /*intentional overflow*/ < current - (dmsLowLimit + dmsIndexDelta)) /* equivalent to `current > repIndex >= dmsLowLimit` */591& ((U32)((dictLimit-1) - repIndex) >= 3) ) /* intentional overflow : do not test positions overlapping 2 memory segments */592&& (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(repMatch, minMatch)) ) {593repLen = (U32)ZSTD_count_2segments(ip+minMatch, repMatch+minMatch, iLimit, dmsEnd, prefixStart) + minMatch;594} }595/* save longer solution */596if (repLen > bestLength) {597DEBUGLOG(8, "found repCode %u (ll0:%u, offset:%u) of length %u",598repCode, ll0, repOffset, repLen);599bestLength = repLen;600matches[mnum].off = repCode - ll0;601matches[mnum].len = (U32)repLen;602mnum++;603if ( (repLen > sufficient_len)604| (ip+repLen == iLimit) ) { /* best possible */605return mnum;606} } } }607608/* HC3 match finder */609if ((mls == 3) /*static*/ && (bestLength < mls)) {610U32 const matchIndex3 = ZSTD_insertAndFindFirstIndexHash3(ms, nextToUpdate3, ip);611if ((matchIndex3 >= matchLow)612& (current - matchIndex3 < (1<<18)) /*heuristic : longer distance likely too expensive*/ ) {613size_t mlen;614if ((dictMode == ZSTD_noDict) /*static*/ || (dictMode == ZSTD_dictMatchState) /*static*/ || (matchIndex3 >= dictLimit)) {615const BYTE* const match = base + matchIndex3;616mlen = ZSTD_count(ip, match, iLimit);617} else {618const BYTE* const match = dictBase + matchIndex3;619mlen = ZSTD_count_2segments(ip, match, iLimit, dictEnd, prefixStart);620}621622/* save best solution */623if (mlen >= mls /* == 3 > bestLength */) {624DEBUGLOG(8, "found small match with hlog3, of length %u",625(U32)mlen);626bestLength = mlen;627assert(current > matchIndex3);628assert(mnum==0); /* no prior solution */629matches[0].off = (current - matchIndex3) + ZSTD_REP_MOVE;630matches[0].len = (U32)mlen;631mnum = 1;632if ( (mlen > sufficient_len) |633(ip+mlen == iLimit) ) { /* best possible length */634ms->nextToUpdate = current+1; /* skip insertion */635return 1;636} } }637/* no dictMatchState lookup: dicts don't have a populated HC3 table */638}639640hashTable[h] = current; /* Update Hash Table */641642while (nbCompares-- && (matchIndex >= matchLow)) {643U32* const nextPtr = bt + 2*(matchIndex & btMask);644const BYTE* match;645size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */646assert(current > matchIndex);647648if ((dictMode == ZSTD_noDict) || (dictMode == ZSTD_dictMatchState) || (matchIndex+matchLength >= dictLimit)) {649assert(matchIndex+matchLength >= dictLimit); /* ensure the condition is correct when !extDict */650match = base + matchIndex;651if (matchIndex >= dictLimit) assert(memcmp(match, ip, matchLength) == 0); /* ensure early section of match is equal as expected */652matchLength += ZSTD_count(ip+matchLength, match+matchLength, iLimit);653} else {654match = dictBase + matchIndex;655assert(memcmp(match, ip, matchLength) == 0); /* ensure early section of match is equal as expected */656matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iLimit, dictEnd, prefixStart);657if (matchIndex+matchLength >= dictLimit)658match = base + matchIndex; /* prepare for match[matchLength] read */659}660661if (matchLength > bestLength) {662DEBUGLOG(8, "found match of length %u at distance %u (offCode=%u)",663(U32)matchLength, current - matchIndex, current - matchIndex + ZSTD_REP_MOVE);664assert(matchEndIdx > matchIndex);665if (matchLength > matchEndIdx - matchIndex)666matchEndIdx = matchIndex + (U32)matchLength;667bestLength = matchLength;668matches[mnum].off = (current - matchIndex) + ZSTD_REP_MOVE;669matches[mnum].len = (U32)matchLength;670mnum++;671if ( (matchLength > ZSTD_OPT_NUM)672| (ip+matchLength == iLimit) /* equal : no way to know if inf or sup */) {673if (dictMode == ZSTD_dictMatchState) nbCompares = 0; /* break should also skip searching dms */674break; /* drop, to preserve bt consistency (miss a little bit of compression) */675}676}677678if (match[matchLength] < ip[matchLength]) {679/* match smaller than current */680*smallerPtr = matchIndex; /* update smaller idx */681commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */682if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */683smallerPtr = nextPtr+1; /* new candidate => larger than match, which was smaller than current */684matchIndex = nextPtr[1]; /* new matchIndex, larger than previous, closer to current */685} else {686*largerPtr = matchIndex;687commonLengthLarger = matchLength;688if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */689largerPtr = nextPtr;690matchIndex = nextPtr[0];691} }692693*smallerPtr = *largerPtr = 0;694695if (dictMode == ZSTD_dictMatchState && nbCompares) {696size_t const dmsH = ZSTD_hashPtr(ip, dmsHashLog, mls);697U32 dictMatchIndex = dms->hashTable[dmsH];698const U32* const dmsBt = dms->chainTable;699commonLengthSmaller = commonLengthLarger = 0;700while (nbCompares-- && (dictMatchIndex > dmsLowLimit)) {701const U32* const nextPtr = dmsBt + 2*(dictMatchIndex & dmsBtMask);702size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */703const BYTE* match = dmsBase + dictMatchIndex;704matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iLimit, dmsEnd, prefixStart);705if (dictMatchIndex+matchLength >= dmsHighLimit)706match = base + dictMatchIndex + dmsIndexDelta; /* to prepare for next usage of match[matchLength] */707708if (matchLength > bestLength) {709matchIndex = dictMatchIndex + dmsIndexDelta;710DEBUGLOG(8, "found dms match of length %u at distance %u (offCode=%u)",711(U32)matchLength, current - matchIndex, current - matchIndex + ZSTD_REP_MOVE);712if (matchLength > matchEndIdx - matchIndex)713matchEndIdx = matchIndex + (U32)matchLength;714bestLength = matchLength;715matches[mnum].off = (current - matchIndex) + ZSTD_REP_MOVE;716matches[mnum].len = (U32)matchLength;717mnum++;718if ( (matchLength > ZSTD_OPT_NUM)719| (ip+matchLength == iLimit) /* equal : no way to know if inf or sup */) {720break; /* drop, to guarantee consistency (miss a little bit of compression) */721}722}723724if (dictMatchIndex <= dmsBtLow) { break; } /* beyond tree size, stop the search */725if (match[matchLength] < ip[matchLength]) {726commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */727dictMatchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */728} else {729/* match is larger than current */730commonLengthLarger = matchLength;731dictMatchIndex = nextPtr[0];732}733}734}735736assert(matchEndIdx > current+8);737ms->nextToUpdate = matchEndIdx - 8; /* skip repetitive patterns */738return mnum;739}740741742FORCE_INLINE_TEMPLATE U32 ZSTD_BtGetAllMatches (743ZSTD_match_t* matches, /* store result (match found, increasing size) in this table */744ZSTD_matchState_t* ms,745U32* nextToUpdate3,746const BYTE* ip, const BYTE* const iHighLimit, const ZSTD_dictMode_e dictMode,747const U32 rep[ZSTD_REP_NUM],748U32 const ll0,749U32 const lengthToBeat)750{751const ZSTD_compressionParameters* const cParams = &ms->cParams;752U32 const matchLengthSearch = cParams->minMatch;753DEBUGLOG(8, "ZSTD_BtGetAllMatches");754if (ip < ms->window.base + ms->nextToUpdate) return 0; /* skipped area */755ZSTD_updateTree_internal(ms, ip, iHighLimit, matchLengthSearch, dictMode);756switch(matchLengthSearch)757{758case 3 : return ZSTD_insertBtAndGetAllMatches(matches, ms, nextToUpdate3, ip, iHighLimit, dictMode, rep, ll0, lengthToBeat, 3);759default :760case 4 : return ZSTD_insertBtAndGetAllMatches(matches, ms, nextToUpdate3, ip, iHighLimit, dictMode, rep, ll0, lengthToBeat, 4);761case 5 : return ZSTD_insertBtAndGetAllMatches(matches, ms, nextToUpdate3, ip, iHighLimit, dictMode, rep, ll0, lengthToBeat, 5);762case 7 :763case 6 : return ZSTD_insertBtAndGetAllMatches(matches, ms, nextToUpdate3, ip, iHighLimit, dictMode, rep, ll0, lengthToBeat, 6);764}765}766767768/*-*******************************769* Optimal parser770*********************************/771772773static U32 ZSTD_totalLen(ZSTD_optimal_t sol)774{775return sol.litlen + sol.mlen;776}777778#if 0 /* debug */779780static void781listStats(const U32* table, int lastEltID)782{783int const nbElts = lastEltID + 1;784int enb;785for (enb=0; enb < nbElts; enb++) {786(void)table;787/* RAWLOG(2, "%3i:%3i, ", enb, table[enb]); */788RAWLOG(2, "%4i,", table[enb]);789}790RAWLOG(2, " \n");791}792793#endif794795FORCE_INLINE_TEMPLATE size_t796ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,797seqStore_t* seqStore,798U32 rep[ZSTD_REP_NUM],799const void* src, size_t srcSize,800const int optLevel,801const ZSTD_dictMode_e dictMode)802{803optState_t* const optStatePtr = &ms->opt;804const BYTE* const istart = (const BYTE*)src;805const BYTE* ip = istart;806const BYTE* anchor = istart;807const BYTE* const iend = istart + srcSize;808const BYTE* const ilimit = iend - 8;809const BYTE* const base = ms->window.base;810const BYTE* const prefixStart = base + ms->window.dictLimit;811const ZSTD_compressionParameters* const cParams = &ms->cParams;812813U32 const sufficient_len = MIN(cParams->targetLength, ZSTD_OPT_NUM -1);814U32 const minMatch = (cParams->minMatch == 3) ? 3 : 4;815U32 nextToUpdate3 = ms->nextToUpdate;816817ZSTD_optimal_t* const opt = optStatePtr->priceTable;818ZSTD_match_t* const matches = optStatePtr->matchTable;819ZSTD_optimal_t lastSequence;820821/* init */822DEBUGLOG(5, "ZSTD_compressBlock_opt_generic: current=%u, prefix=%u, nextToUpdate=%u",823(U32)(ip - base), ms->window.dictLimit, ms->nextToUpdate);824assert(optLevel <= 2);825ZSTD_rescaleFreqs(optStatePtr, (const BYTE*)src, srcSize, optLevel);826ip += (ip==prefixStart);827828/* Match Loop */829while (ip < ilimit) {830U32 cur, last_pos = 0;831832/* find first match */833{ U32 const litlen = (U32)(ip - anchor);834U32 const ll0 = !litlen;835U32 const nbMatches = ZSTD_BtGetAllMatches(matches, ms, &nextToUpdate3, ip, iend, dictMode, rep, ll0, minMatch);836if (!nbMatches) { ip++; continue; }837838/* initialize opt[0] */839{ U32 i ; for (i=0; i<ZSTD_REP_NUM; i++) opt[0].rep[i] = rep[i]; }840opt[0].mlen = 0; /* means is_a_literal */841opt[0].litlen = litlen;842/* We don't need to include the actual price of the literals because843* it is static for the duration of the forward pass, and is included844* in every price. We include the literal length to avoid negative845* prices when we subtract the previous literal length.846*/847opt[0].price = ZSTD_litLengthPrice(litlen, optStatePtr, optLevel);848849/* large match -> immediate encoding */850{ U32 const maxML = matches[nbMatches-1].len;851U32 const maxOffset = matches[nbMatches-1].off;852DEBUGLOG(6, "found %u matches of maxLength=%u and maxOffCode=%u at cPos=%u => start new series",853nbMatches, maxML, maxOffset, (U32)(ip-prefixStart));854855if (maxML > sufficient_len) {856lastSequence.litlen = litlen;857lastSequence.mlen = maxML;858lastSequence.off = maxOffset;859DEBUGLOG(6, "large match (%u>%u), immediate encoding",860maxML, sufficient_len);861cur = 0;862last_pos = ZSTD_totalLen(lastSequence);863goto _shortestPath;864} }865866/* set prices for first matches starting position == 0 */867{ U32 const literalsPrice = opt[0].price + ZSTD_litLengthPrice(0, optStatePtr, optLevel);868U32 pos;869U32 matchNb;870for (pos = 1; pos < minMatch; pos++) {871opt[pos].price = ZSTD_MAX_PRICE; /* mlen, litlen and price will be fixed during forward scanning */872}873for (matchNb = 0; matchNb < nbMatches; matchNb++) {874U32 const offset = matches[matchNb].off;875U32 const end = matches[matchNb].len;876for ( ; pos <= end ; pos++ ) {877U32 const matchPrice = ZSTD_getMatchPrice(offset, pos, optStatePtr, optLevel);878U32 const sequencePrice = literalsPrice + matchPrice;879DEBUGLOG(7, "rPos:%u => set initial price : %.2f",880pos, ZSTD_fCost(sequencePrice));881opt[pos].mlen = pos;882opt[pos].off = offset;883opt[pos].litlen = litlen;884opt[pos].price = sequencePrice;885} }886last_pos = pos-1;887}888}889890/* check further positions */891for (cur = 1; cur <= last_pos; cur++) {892const BYTE* const inr = ip + cur;893assert(cur < ZSTD_OPT_NUM);894DEBUGLOG(7, "cPos:%zi==rPos:%u", inr-istart, cur)895896/* Fix current position with one literal if cheaper */897{ U32 const litlen = (opt[cur-1].mlen == 0) ? opt[cur-1].litlen + 1 : 1;898int const price = opt[cur-1].price899+ ZSTD_rawLiteralsCost(ip+cur-1, 1, optStatePtr, optLevel)900+ ZSTD_litLengthPrice(litlen, optStatePtr, optLevel)901- ZSTD_litLengthPrice(litlen-1, optStatePtr, optLevel);902assert(price < 1000000000); /* overflow check */903if (price <= opt[cur].price) {904DEBUGLOG(7, "cPos:%zi==rPos:%u : better price (%.2f<=%.2f) using literal (ll==%u) (hist:%u,%u,%u)",905inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price), litlen,906opt[cur-1].rep[0], opt[cur-1].rep[1], opt[cur-1].rep[2]);907opt[cur].mlen = 0;908opt[cur].off = 0;909opt[cur].litlen = litlen;910opt[cur].price = price;911} else {912DEBUGLOG(7, "cPos:%zi==rPos:%u : literal would cost more (%.2f>%.2f) (hist:%u,%u,%u)",913inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price),914opt[cur].rep[0], opt[cur].rep[1], opt[cur].rep[2]);915}916}917918/* Set the repcodes of the current position. We must do it here919* because we rely on the repcodes of the 2nd to last sequence being920* correct to set the next chunks repcodes during the backward921* traversal.922*/923ZSTD_STATIC_ASSERT(sizeof(opt[cur].rep) == sizeof(repcodes_t));924assert(cur >= opt[cur].mlen);925if (opt[cur].mlen != 0) {926U32 const prev = cur - opt[cur].mlen;927repcodes_t newReps = ZSTD_updateRep(opt[prev].rep, opt[cur].off, opt[cur].litlen==0);928memcpy(opt[cur].rep, &newReps, sizeof(repcodes_t));929} else {930memcpy(opt[cur].rep, opt[cur - 1].rep, sizeof(repcodes_t));931}932933/* last match must start at a minimum distance of 8 from oend */934if (inr > ilimit) continue;935936if (cur == last_pos) break;937938if ( (optLevel==0) /*static_test*/939&& (opt[cur+1].price <= opt[cur].price + (BITCOST_MULTIPLIER/2)) ) {940DEBUGLOG(7, "move to next rPos:%u : price is <=", cur+1);941continue; /* skip unpromising positions; about ~+6% speed, -0.01 ratio */942}943944{ U32 const ll0 = (opt[cur].mlen != 0);945U32 const litlen = (opt[cur].mlen == 0) ? opt[cur].litlen : 0;946U32 const previousPrice = opt[cur].price;947U32 const basePrice = previousPrice + ZSTD_litLengthPrice(0, optStatePtr, optLevel);948U32 const nbMatches = ZSTD_BtGetAllMatches(matches, ms, &nextToUpdate3, inr, iend, dictMode, opt[cur].rep, ll0, minMatch);949U32 matchNb;950if (!nbMatches) {951DEBUGLOG(7, "rPos:%u : no match found", cur);952continue;953}954955{ U32 const maxML = matches[nbMatches-1].len;956DEBUGLOG(7, "cPos:%zi==rPos:%u, found %u matches, of maxLength=%u",957inr-istart, cur, nbMatches, maxML);958959if ( (maxML > sufficient_len)960|| (cur + maxML >= ZSTD_OPT_NUM) ) {961lastSequence.mlen = maxML;962lastSequence.off = matches[nbMatches-1].off;963lastSequence.litlen = litlen;964cur -= (opt[cur].mlen==0) ? opt[cur].litlen : 0; /* last sequence is actually only literals, fix cur to last match - note : may underflow, in which case, it's first sequence, and it's okay */965last_pos = cur + ZSTD_totalLen(lastSequence);966if (cur > ZSTD_OPT_NUM) cur = 0; /* underflow => first match */967goto _shortestPath;968} }969970/* set prices using matches found at position == cur */971for (matchNb = 0; matchNb < nbMatches; matchNb++) {972U32 const offset = matches[matchNb].off;973U32 const lastML = matches[matchNb].len;974U32 const startML = (matchNb>0) ? matches[matchNb-1].len+1 : minMatch;975U32 mlen;976977DEBUGLOG(7, "testing match %u => offCode=%4u, mlen=%2u, llen=%2u",978matchNb, matches[matchNb].off, lastML, litlen);979980for (mlen = lastML; mlen >= startML; mlen--) { /* scan downward */981U32 const pos = cur + mlen;982int const price = basePrice + ZSTD_getMatchPrice(offset, mlen, optStatePtr, optLevel);983984if ((pos > last_pos) || (price < opt[pos].price)) {985DEBUGLOG(7, "rPos:%u (ml=%2u) => new better price (%.2f<%.2f)",986pos, mlen, ZSTD_fCost(price), ZSTD_fCost(opt[pos].price));987while (last_pos < pos) { opt[last_pos+1].price = ZSTD_MAX_PRICE; last_pos++; } /* fill empty positions */988opt[pos].mlen = mlen;989opt[pos].off = offset;990opt[pos].litlen = litlen;991opt[pos].price = price;992} else {993DEBUGLOG(7, "rPos:%u (ml=%2u) => new price is worse (%.2f>=%.2f)",994pos, mlen, ZSTD_fCost(price), ZSTD_fCost(opt[pos].price));995if (optLevel==0) break; /* early update abort; gets ~+10% speed for about -0.01 ratio loss */996}997} } }998} /* for (cur = 1; cur <= last_pos; cur++) */9991000lastSequence = opt[last_pos];1001cur = last_pos > ZSTD_totalLen(lastSequence) ? last_pos - ZSTD_totalLen(lastSequence) : 0; /* single sequence, and it starts before `ip` */1002assert(cur < ZSTD_OPT_NUM); /* control overflow*/10031004_shortestPath: /* cur, last_pos, best_mlen, best_off have to be set */1005assert(opt[0].mlen == 0);10061007/* Set the next chunk's repcodes based on the repcodes of the beginning1008* of the last match, and the last sequence. This avoids us having to1009* update them while traversing the sequences.1010*/1011if (lastSequence.mlen != 0) {1012repcodes_t reps = ZSTD_updateRep(opt[cur].rep, lastSequence.off, lastSequence.litlen==0);1013memcpy(rep, &reps, sizeof(reps));1014} else {1015memcpy(rep, opt[cur].rep, sizeof(repcodes_t));1016}10171018{ U32 const storeEnd = cur + 1;1019U32 storeStart = storeEnd;1020U32 seqPos = cur;10211022DEBUGLOG(6, "start reverse traversal (last_pos:%u, cur:%u)",1023last_pos, cur); (void)last_pos;1024assert(storeEnd < ZSTD_OPT_NUM);1025DEBUGLOG(6, "last sequence copied into pos=%u (llen=%u,mlen=%u,ofc=%u)",1026storeEnd, lastSequence.litlen, lastSequence.mlen, lastSequence.off);1027opt[storeEnd] = lastSequence;1028while (seqPos > 0) {1029U32 const backDist = ZSTD_totalLen(opt[seqPos]);1030storeStart--;1031DEBUGLOG(6, "sequence from rPos=%u copied into pos=%u (llen=%u,mlen=%u,ofc=%u)",1032seqPos, storeStart, opt[seqPos].litlen, opt[seqPos].mlen, opt[seqPos].off);1033opt[storeStart] = opt[seqPos];1034seqPos = (seqPos > backDist) ? seqPos - backDist : 0;1035}10361037/* save sequences */1038DEBUGLOG(6, "sending selected sequences into seqStore")1039{ U32 storePos;1040for (storePos=storeStart; storePos <= storeEnd; storePos++) {1041U32 const llen = opt[storePos].litlen;1042U32 const mlen = opt[storePos].mlen;1043U32 const offCode = opt[storePos].off;1044U32 const advance = llen + mlen;1045DEBUGLOG(6, "considering seq starting at %zi, llen=%u, mlen=%u",1046anchor - istart, (unsigned)llen, (unsigned)mlen);10471048if (mlen==0) { /* only literals => must be last "sequence", actually starting a new stream of sequences */1049assert(storePos == storeEnd); /* must be last sequence */1050ip = anchor + llen; /* last "sequence" is a bunch of literals => don't progress anchor */1051continue; /* will finish */1052}10531054assert(anchor + llen <= iend);1055ZSTD_updateStats(optStatePtr, llen, anchor, offCode, mlen);1056ZSTD_storeSeq(seqStore, llen, anchor, iend, offCode, mlen-MINMATCH);1057anchor += advance;1058ip = anchor;1059} }1060ZSTD_setBasePrices(optStatePtr, optLevel);1061}1062} /* while (ip < ilimit) */10631064/* Return the last literals size */1065return (size_t)(iend - anchor);1066}106710681069size_t ZSTD_compressBlock_btopt(1070ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1071const void* src, size_t srcSize)1072{1073DEBUGLOG(5, "ZSTD_compressBlock_btopt");1074return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /*optLevel*/, ZSTD_noDict);1075}107610771078/* used in 2-pass strategy */1079static U32 ZSTD_upscaleStat(unsigned* table, U32 lastEltIndex, int bonus)1080{1081U32 s, sum=0;1082assert(ZSTD_FREQ_DIV+bonus >= 0);1083for (s=0; s<lastEltIndex+1; s++) {1084table[s] <<= ZSTD_FREQ_DIV+bonus;1085table[s]--;1086sum += table[s];1087}1088return sum;1089}10901091/* used in 2-pass strategy */1092MEM_STATIC void ZSTD_upscaleStats(optState_t* optPtr)1093{1094if (ZSTD_compressedLiterals(optPtr))1095optPtr->litSum = ZSTD_upscaleStat(optPtr->litFreq, MaxLit, 0);1096optPtr->litLengthSum = ZSTD_upscaleStat(optPtr->litLengthFreq, MaxLL, 0);1097optPtr->matchLengthSum = ZSTD_upscaleStat(optPtr->matchLengthFreq, MaxML, 0);1098optPtr->offCodeSum = ZSTD_upscaleStat(optPtr->offCodeFreq, MaxOff, 0);1099}11001101/* ZSTD_initStats_ultra():1102* make a first compression pass, just to seed stats with more accurate starting values.1103* only works on first block, with no dictionary and no ldm.1104* this function cannot error, hence its contract must be respected.1105*/1106static void1107ZSTD_initStats_ultra(ZSTD_matchState_t* ms,1108seqStore_t* seqStore,1109U32 rep[ZSTD_REP_NUM],1110const void* src, size_t srcSize)1111{1112U32 tmpRep[ZSTD_REP_NUM]; /* updated rep codes will sink here */1113memcpy(tmpRep, rep, sizeof(tmpRep));11141115DEBUGLOG(4, "ZSTD_initStats_ultra (srcSize=%zu)", srcSize);1116assert(ms->opt.litLengthSum == 0); /* first block */1117assert(seqStore->sequences == seqStore->sequencesStart); /* no ldm */1118assert(ms->window.dictLimit == ms->window.lowLimit); /* no dictionary */1119assert(ms->window.dictLimit - ms->nextToUpdate <= 1); /* no prefix (note: intentional overflow, defined as 2-complement) */11201121ZSTD_compressBlock_opt_generic(ms, seqStore, tmpRep, src, srcSize, 2 /*optLevel*/, ZSTD_noDict); /* generate stats into ms->opt*/11221123/* invalidate first scan from history */1124ZSTD_resetSeqStore(seqStore);1125ms->window.base -= srcSize;1126ms->window.dictLimit += (U32)srcSize;1127ms->window.lowLimit = ms->window.dictLimit;1128ms->nextToUpdate = ms->window.dictLimit;11291130/* re-inforce weight of collected statistics */1131ZSTD_upscaleStats(&ms->opt);1132}11331134size_t ZSTD_compressBlock_btultra(1135ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1136const void* src, size_t srcSize)1137{1138DEBUGLOG(5, "ZSTD_compressBlock_btultra (srcSize=%zu)", srcSize);1139return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /*optLevel*/, ZSTD_noDict);1140}11411142size_t ZSTD_compressBlock_btultra2(1143ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1144const void* src, size_t srcSize)1145{1146U32 const current = (U32)((const BYTE*)src - ms->window.base);1147DEBUGLOG(5, "ZSTD_compressBlock_btultra2 (srcSize=%zu)", srcSize);11481149/* 2-pass strategy:1150* this strategy makes a first pass over first block to collect statistics1151* and seed next round's statistics with it.1152* After 1st pass, function forgets everything, and starts a new block.1153* Consequently, this can only work if no data has been previously loaded in tables,1154* aka, no dictionary, no prefix, no ldm preprocessing.1155* The compression ratio gain is generally small (~0.5% on first block),1156* the cost is 2x cpu time on first block. */1157assert(srcSize <= ZSTD_BLOCKSIZE_MAX);1158if ( (ms->opt.litLengthSum==0) /* first block */1159&& (seqStore->sequences == seqStore->sequencesStart) /* no ldm */1160&& (ms->window.dictLimit == ms->window.lowLimit) /* no dictionary */1161&& (current == ms->window.dictLimit) /* start of frame, nothing already loaded nor skipped */1162&& (srcSize > ZSTD_PREDEF_THRESHOLD)1163) {1164ZSTD_initStats_ultra(ms, seqStore, rep, src, srcSize);1165}11661167return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /*optLevel*/, ZSTD_noDict);1168}11691170size_t ZSTD_compressBlock_btopt_dictMatchState(1171ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1172const void* src, size_t srcSize)1173{1174return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /*optLevel*/, ZSTD_dictMatchState);1175}11761177size_t ZSTD_compressBlock_btultra_dictMatchState(1178ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1179const void* src, size_t srcSize)1180{1181return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /*optLevel*/, ZSTD_dictMatchState);1182}11831184size_t ZSTD_compressBlock_btopt_extDict(1185ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1186const void* src, size_t srcSize)1187{1188return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /*optLevel*/, ZSTD_extDict);1189}11901191size_t ZSTD_compressBlock_btultra_extDict(1192ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1193const void* src, size_t srcSize)1194{1195return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /*optLevel*/, ZSTD_extDict);1196}11971198/* note : no btultra2 variant for extDict nor dictMatchState,1199* because btultra2 is not meant to work with dictionaries1200* and is only specific for the first block (no prefix) */120112021203