Path: blob/main/sys/contrib/zstd/lib/compress/zstd_opt.c
48378 views
/*1* Copyright (c) Przemyslaw Skibinski, Yann Collet, Facebook, Inc.2* All rights reserved.3*4* This source code is licensed under both the BSD-style license (found in the5* LICENSE file in the root directory of this source tree) and the GPLv2 (found6* in the COPYING file in the root directory of this source tree).7* You may select, at your option, one of the above-listed licenses.8*/910#include "zstd_compress_internal.h"11#include "hist.h"12#include "zstd_opt.h"131415#define ZSTD_LITFREQ_ADD 2 /* scaling factor for litFreq, so that frequencies adapt faster to new stats */16#define ZSTD_MAX_PRICE (1<<30)1718#define ZSTD_PREDEF_THRESHOLD 1024 /* if srcSize < ZSTD_PREDEF_THRESHOLD, symbols' cost is assumed static, directly determined by pre-defined distributions */192021/*-*************************************22* Price functions for optimal parser23***************************************/2425#if 0 /* approximation at bit level (for tests) */26# define BITCOST_ACCURACY 027# define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)28# define WEIGHT(stat, opt) ((void)opt, ZSTD_bitWeight(stat))29#elif 0 /* fractional bit accuracy (for tests) */30# define BITCOST_ACCURACY 831# define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)32# define WEIGHT(stat,opt) ((void)opt, ZSTD_fracWeight(stat))33#else /* opt==approx, ultra==accurate */34# define BITCOST_ACCURACY 835# define BITCOST_MULTIPLIER (1 << BITCOST_ACCURACY)36# define WEIGHT(stat,opt) (opt ? ZSTD_fracWeight(stat) : ZSTD_bitWeight(stat))37#endif3839MEM_STATIC U32 ZSTD_bitWeight(U32 stat)40{41return (ZSTD_highbit32(stat+1) * BITCOST_MULTIPLIER);42}4344MEM_STATIC U32 ZSTD_fracWeight(U32 rawStat)45{46U32 const stat = rawStat + 1;47U32 const hb = ZSTD_highbit32(stat);48U32 const BWeight = hb * BITCOST_MULTIPLIER;49U32 const FWeight = (stat << BITCOST_ACCURACY) >> hb;50U32 const weight = BWeight + FWeight;51assert(hb + BITCOST_ACCURACY < 31);52return weight;53}5455#if (DEBUGLEVEL>=2)56/* debugging function,57* @return price in bytes as fractional value58* for debug messages only */59MEM_STATIC double ZSTD_fCost(U32 price)60{61return (double)price / (BITCOST_MULTIPLIER*8);62}63#endif6465static int ZSTD_compressedLiterals(optState_t const* const optPtr)66{67return optPtr->literalCompressionMode != ZSTD_ps_disable;68}6970static void ZSTD_setBasePrices(optState_t* optPtr, int optLevel)71{72if (ZSTD_compressedLiterals(optPtr))73optPtr->litSumBasePrice = WEIGHT(optPtr->litSum, optLevel);74optPtr->litLengthSumBasePrice = WEIGHT(optPtr->litLengthSum, optLevel);75optPtr->matchLengthSumBasePrice = WEIGHT(optPtr->matchLengthSum, optLevel);76optPtr->offCodeSumBasePrice = WEIGHT(optPtr->offCodeSum, optLevel);77}787980static U32 sum_u32(const unsigned table[], size_t nbElts)81{82size_t n;83U32 total = 0;84for (n=0; n<nbElts; n++) {85total += table[n];86}87return total;88}8990static U32 ZSTD_downscaleStats(unsigned* table, U32 lastEltIndex, U32 shift)91{92U32 s, sum=0;93DEBUGLOG(5, "ZSTD_downscaleStats (nbElts=%u, shift=%u)", (unsigned)lastEltIndex+1, (unsigned)shift);94assert(shift < 30);95for (s=0; s<lastEltIndex+1; s++) {96table[s] = 1 + (table[s] >> shift);97sum += table[s];98}99return sum;100}101102/* ZSTD_scaleStats() :103* reduce all elements in table is sum too large104* return the resulting sum of elements */105static U32 ZSTD_scaleStats(unsigned* table, U32 lastEltIndex, U32 logTarget)106{107U32 const prevsum = sum_u32(table, lastEltIndex+1);108U32 const factor = prevsum >> logTarget;109DEBUGLOG(5, "ZSTD_scaleStats (nbElts=%u, target=%u)", (unsigned)lastEltIndex+1, (unsigned)logTarget);110assert(logTarget < 30);111if (factor <= 1) return prevsum;112return ZSTD_downscaleStats(table, lastEltIndex, ZSTD_highbit32(factor));113}114115/* ZSTD_rescaleFreqs() :116* if first block (detected by optPtr->litLengthSum == 0) : init statistics117* take hints from dictionary if there is one118* and init from zero if there is none,119* using src for literals stats, and baseline stats for sequence symbols120* otherwise downscale existing stats, to be used as seed for next block.121*/122static void123ZSTD_rescaleFreqs(optState_t* const optPtr,124const BYTE* const src, size_t const srcSize,125int const optLevel)126{127int const compressedLiterals = ZSTD_compressedLiterals(optPtr);128DEBUGLOG(5, "ZSTD_rescaleFreqs (srcSize=%u)", (unsigned)srcSize);129optPtr->priceType = zop_dynamic;130131if (optPtr->litLengthSum == 0) { /* first block : init */132if (srcSize <= ZSTD_PREDEF_THRESHOLD) { /* heuristic */133DEBUGLOG(5, "(srcSize <= ZSTD_PREDEF_THRESHOLD) => zop_predef");134optPtr->priceType = zop_predef;135}136137assert(optPtr->symbolCosts != NULL);138if (optPtr->symbolCosts->huf.repeatMode == HUF_repeat_valid) {139/* huffman table presumed generated by dictionary */140optPtr->priceType = zop_dynamic;141142if (compressedLiterals) {143unsigned lit;144assert(optPtr->litFreq != NULL);145optPtr->litSum = 0;146for (lit=0; lit<=MaxLit; lit++) {147U32 const scaleLog = 11; /* scale to 2K */148U32 const bitCost = HUF_getNbBitsFromCTable(optPtr->symbolCosts->huf.CTable, lit);149assert(bitCost <= scaleLog);150optPtr->litFreq[lit] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;151optPtr->litSum += optPtr->litFreq[lit];152} }153154{ unsigned ll;155FSE_CState_t llstate;156FSE_initCState(&llstate, optPtr->symbolCosts->fse.litlengthCTable);157optPtr->litLengthSum = 0;158for (ll=0; ll<=MaxLL; ll++) {159U32 const scaleLog = 10; /* scale to 1K */160U32 const bitCost = FSE_getMaxNbBits(llstate.symbolTT, ll);161assert(bitCost < scaleLog);162optPtr->litLengthFreq[ll] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;163optPtr->litLengthSum += optPtr->litLengthFreq[ll];164} }165166{ unsigned ml;167FSE_CState_t mlstate;168FSE_initCState(&mlstate, optPtr->symbolCosts->fse.matchlengthCTable);169optPtr->matchLengthSum = 0;170for (ml=0; ml<=MaxML; ml++) {171U32 const scaleLog = 10;172U32 const bitCost = FSE_getMaxNbBits(mlstate.symbolTT, ml);173assert(bitCost < scaleLog);174optPtr->matchLengthFreq[ml] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;175optPtr->matchLengthSum += optPtr->matchLengthFreq[ml];176} }177178{ unsigned of;179FSE_CState_t ofstate;180FSE_initCState(&ofstate, optPtr->symbolCosts->fse.offcodeCTable);181optPtr->offCodeSum = 0;182for (of=0; of<=MaxOff; of++) {183U32 const scaleLog = 10;184U32 const bitCost = FSE_getMaxNbBits(ofstate.symbolTT, of);185assert(bitCost < scaleLog);186optPtr->offCodeFreq[of] = bitCost ? 1 << (scaleLog-bitCost) : 1 /*minimum to calculate cost*/;187optPtr->offCodeSum += optPtr->offCodeFreq[of];188} }189190} else { /* not a dictionary */191192assert(optPtr->litFreq != NULL);193if (compressedLiterals) {194unsigned lit = MaxLit;195HIST_count_simple(optPtr->litFreq, &lit, src, srcSize); /* use raw first block to init statistics */196optPtr->litSum = ZSTD_downscaleStats(optPtr->litFreq, MaxLit, 8);197}198199{ unsigned const baseLLfreqs[MaxLL+1] = {2004, 2, 1, 1, 1, 1, 1, 1,2011, 1, 1, 1, 1, 1, 1, 1,2021, 1, 1, 1, 1, 1, 1, 1,2031, 1, 1, 1, 1, 1, 1, 1,2041, 1, 1, 1205};206ZSTD_memcpy(optPtr->litLengthFreq, baseLLfreqs, sizeof(baseLLfreqs));207optPtr->litLengthSum = sum_u32(baseLLfreqs, MaxLL+1);208}209210{ unsigned ml;211for (ml=0; ml<=MaxML; ml++)212optPtr->matchLengthFreq[ml] = 1;213}214optPtr->matchLengthSum = MaxML+1;215216{ unsigned const baseOFCfreqs[MaxOff+1] = {2176, 2, 1, 1, 2, 3, 4, 4,2184, 3, 2, 1, 1, 1, 1, 1,2191, 1, 1, 1, 1, 1, 1, 1,2201, 1, 1, 1, 1, 1, 1, 1221};222ZSTD_memcpy(optPtr->offCodeFreq, baseOFCfreqs, sizeof(baseOFCfreqs));223optPtr->offCodeSum = sum_u32(baseOFCfreqs, MaxOff+1);224}225226227}228229} else { /* new block : re-use previous statistics, scaled down */230231if (compressedLiterals)232optPtr->litSum = ZSTD_scaleStats(optPtr->litFreq, MaxLit, 12);233optPtr->litLengthSum = ZSTD_scaleStats(optPtr->litLengthFreq, MaxLL, 11);234optPtr->matchLengthSum = ZSTD_scaleStats(optPtr->matchLengthFreq, MaxML, 11);235optPtr->offCodeSum = ZSTD_scaleStats(optPtr->offCodeFreq, MaxOff, 11);236}237238ZSTD_setBasePrices(optPtr, optLevel);239}240241/* ZSTD_rawLiteralsCost() :242* price of literals (only) in specified segment (which length can be 0).243* does not include price of literalLength symbol */244static U32 ZSTD_rawLiteralsCost(const BYTE* const literals, U32 const litLength,245const optState_t* const optPtr,246int optLevel)247{248if (litLength == 0) return 0;249250if (!ZSTD_compressedLiterals(optPtr))251return (litLength << 3) * BITCOST_MULTIPLIER; /* Uncompressed - 8 bytes per literal. */252253if (optPtr->priceType == zop_predef)254return (litLength*6) * BITCOST_MULTIPLIER; /* 6 bit per literal - no statistic used */255256/* dynamic statistics */257{ U32 price = litLength * optPtr->litSumBasePrice;258U32 u;259for (u=0; u < litLength; u++) {260assert(WEIGHT(optPtr->litFreq[literals[u]], optLevel) <= optPtr->litSumBasePrice); /* literal cost should never be negative */261price -= WEIGHT(optPtr->litFreq[literals[u]], optLevel);262}263return price;264}265}266267/* ZSTD_litLengthPrice() :268* cost of literalLength symbol */269static U32 ZSTD_litLengthPrice(U32 const litLength, const optState_t* const optPtr, int optLevel)270{271assert(litLength <= ZSTD_BLOCKSIZE_MAX);272if (optPtr->priceType == zop_predef)273return WEIGHT(litLength, optLevel);274/* We can't compute the litLength price for sizes >= ZSTD_BLOCKSIZE_MAX275* because it isn't representable in the zstd format. So instead just276* call it 1 bit more than ZSTD_BLOCKSIZE_MAX - 1. In this case the block277* would be all literals.278*/279if (litLength == ZSTD_BLOCKSIZE_MAX)280return BITCOST_MULTIPLIER + ZSTD_litLengthPrice(ZSTD_BLOCKSIZE_MAX - 1, optPtr, optLevel);281282/* dynamic statistics */283{ U32 const llCode = ZSTD_LLcode(litLength);284return (LL_bits[llCode] * BITCOST_MULTIPLIER)285+ optPtr->litLengthSumBasePrice286- WEIGHT(optPtr->litLengthFreq[llCode], optLevel);287}288}289290/* ZSTD_getMatchPrice() :291* Provides the cost of the match part (offset + matchLength) of a sequence292* Must be combined with ZSTD_fullLiteralsCost() to get the full cost of a sequence.293* @offcode : expects a scale where 0,1,2 are repcodes 1-3, and 3+ are real_offsets+2294* @optLevel: when <2, favors small offset for decompression speed (improved cache efficiency)295*/296FORCE_INLINE_TEMPLATE U32297ZSTD_getMatchPrice(U32 const offcode,298U32 const matchLength,299const optState_t* const optPtr,300int const optLevel)301{302U32 price;303U32 const offCode = ZSTD_highbit32(STORED_TO_OFFBASE(offcode));304U32 const mlBase = matchLength - MINMATCH;305assert(matchLength >= MINMATCH);306307if (optPtr->priceType == zop_predef) /* fixed scheme, do not use statistics */308return WEIGHT(mlBase, optLevel) + ((16 + offCode) * BITCOST_MULTIPLIER);309310/* dynamic statistics */311price = (offCode * BITCOST_MULTIPLIER) + (optPtr->offCodeSumBasePrice - WEIGHT(optPtr->offCodeFreq[offCode], optLevel));312if ((optLevel<2) /*static*/ && offCode >= 20)313price += (offCode-19)*2 * BITCOST_MULTIPLIER; /* handicap for long distance offsets, favor decompression speed */314315/* match Length */316{ U32 const mlCode = ZSTD_MLcode(mlBase);317price += (ML_bits[mlCode] * BITCOST_MULTIPLIER) + (optPtr->matchLengthSumBasePrice - WEIGHT(optPtr->matchLengthFreq[mlCode], optLevel));318}319320price += BITCOST_MULTIPLIER / 5; /* heuristic : make matches a bit more costly to favor less sequences -> faster decompression speed */321322DEBUGLOG(8, "ZSTD_getMatchPrice(ml:%u) = %u", matchLength, price);323return price;324}325326/* ZSTD_updateStats() :327* assumption : literals + litLengtn <= iend */328static void ZSTD_updateStats(optState_t* const optPtr,329U32 litLength, const BYTE* literals,330U32 offsetCode, U32 matchLength)331{332/* literals */333if (ZSTD_compressedLiterals(optPtr)) {334U32 u;335for (u=0; u < litLength; u++)336optPtr->litFreq[literals[u]] += ZSTD_LITFREQ_ADD;337optPtr->litSum += litLength*ZSTD_LITFREQ_ADD;338}339340/* literal Length */341{ U32 const llCode = ZSTD_LLcode(litLength);342optPtr->litLengthFreq[llCode]++;343optPtr->litLengthSum++;344}345346/* offset code : expected to follow storeSeq() numeric representation */347{ U32 const offCode = ZSTD_highbit32(STORED_TO_OFFBASE(offsetCode));348assert(offCode <= MaxOff);349optPtr->offCodeFreq[offCode]++;350optPtr->offCodeSum++;351}352353/* match Length */354{ U32 const mlBase = matchLength - MINMATCH;355U32 const mlCode = ZSTD_MLcode(mlBase);356optPtr->matchLengthFreq[mlCode]++;357optPtr->matchLengthSum++;358}359}360361362/* ZSTD_readMINMATCH() :363* function safe only for comparisons364* assumption : memPtr must be at least 4 bytes before end of buffer */365MEM_STATIC U32 ZSTD_readMINMATCH(const void* memPtr, U32 length)366{367switch (length)368{369default :370case 4 : return MEM_read32(memPtr);371case 3 : if (MEM_isLittleEndian())372return MEM_read32(memPtr)<<8;373else374return MEM_read32(memPtr)>>8;375}376}377378379/* Update hashTable3 up to ip (excluded)380Assumption : always within prefix (i.e. not within extDict) */381static U32 ZSTD_insertAndFindFirstIndexHash3 (const ZSTD_matchState_t* ms,382U32* nextToUpdate3,383const BYTE* const ip)384{385U32* const hashTable3 = ms->hashTable3;386U32 const hashLog3 = ms->hashLog3;387const BYTE* const base = ms->window.base;388U32 idx = *nextToUpdate3;389U32 const target = (U32)(ip - base);390size_t const hash3 = ZSTD_hash3Ptr(ip, hashLog3);391assert(hashLog3 > 0);392393while(idx < target) {394hashTable3[ZSTD_hash3Ptr(base+idx, hashLog3)] = idx;395idx++;396}397398*nextToUpdate3 = target;399return hashTable3[hash3];400}401402403/*-*************************************404* Binary Tree search405***************************************/406/** ZSTD_insertBt1() : add one or multiple positions to tree.407* @param ip assumed <= iend-8 .408* @param target The target of ZSTD_updateTree_internal() - we are filling to this position409* @return : nb of positions added */410static U32 ZSTD_insertBt1(411const ZSTD_matchState_t* ms,412const BYTE* const ip, const BYTE* const iend,413U32 const target,414U32 const mls, const int extDict)415{416const ZSTD_compressionParameters* const cParams = &ms->cParams;417U32* const hashTable = ms->hashTable;418U32 const hashLog = cParams->hashLog;419size_t const h = ZSTD_hashPtr(ip, hashLog, mls);420U32* const bt = ms->chainTable;421U32 const btLog = cParams->chainLog - 1;422U32 const btMask = (1 << btLog) - 1;423U32 matchIndex = hashTable[h];424size_t commonLengthSmaller=0, commonLengthLarger=0;425const BYTE* const base = ms->window.base;426const BYTE* const dictBase = ms->window.dictBase;427const U32 dictLimit = ms->window.dictLimit;428const BYTE* const dictEnd = dictBase + dictLimit;429const BYTE* const prefixStart = base + dictLimit;430const BYTE* match;431const U32 curr = (U32)(ip-base);432const U32 btLow = btMask >= curr ? 0 : curr - btMask;433U32* smallerPtr = bt + 2*(curr&btMask);434U32* largerPtr = smallerPtr + 1;435U32 dummy32; /* to be nullified at the end */436/* windowLow is based on target because437* we only need positions that will be in the window at the end of the tree update.438*/439U32 const windowLow = ZSTD_getLowestMatchIndex(ms, target, cParams->windowLog);440U32 matchEndIdx = curr+8+1;441size_t bestLength = 8;442U32 nbCompares = 1U << cParams->searchLog;443#ifdef ZSTD_C_PREDICT444U32 predictedSmall = *(bt + 2*((curr-1)&btMask) + 0);445U32 predictedLarge = *(bt + 2*((curr-1)&btMask) + 1);446predictedSmall += (predictedSmall>0);447predictedLarge += (predictedLarge>0);448#endif /* ZSTD_C_PREDICT */449450DEBUGLOG(8, "ZSTD_insertBt1 (%u)", curr);451452assert(curr <= target);453assert(ip <= iend-8); /* required for h calculation */454hashTable[h] = curr; /* Update Hash Table */455456assert(windowLow > 0);457for (; nbCompares && (matchIndex >= windowLow); --nbCompares) {458U32* const nextPtr = bt + 2*(matchIndex & btMask);459size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */460assert(matchIndex < curr);461462#ifdef ZSTD_C_PREDICT /* note : can create issues when hlog small <= 11 */463const U32* predictPtr = bt + 2*((matchIndex-1) & btMask); /* written this way, as bt is a roll buffer */464if (matchIndex == predictedSmall) {465/* no need to check length, result known */466*smallerPtr = matchIndex;467if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */468smallerPtr = nextPtr+1; /* new "smaller" => larger of match */469matchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */470predictedSmall = predictPtr[1] + (predictPtr[1]>0);471continue;472}473if (matchIndex == predictedLarge) {474*largerPtr = matchIndex;475if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */476largerPtr = nextPtr;477matchIndex = nextPtr[0];478predictedLarge = predictPtr[0] + (predictPtr[0]>0);479continue;480}481#endif482483if (!extDict || (matchIndex+matchLength >= dictLimit)) {484assert(matchIndex+matchLength >= dictLimit); /* might be wrong if actually extDict */485match = base + matchIndex;486matchLength += ZSTD_count(ip+matchLength, match+matchLength, iend);487} else {488match = dictBase + matchIndex;489matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iend, dictEnd, prefixStart);490if (matchIndex+matchLength >= dictLimit)491match = base + matchIndex; /* to prepare for next usage of match[matchLength] */492}493494if (matchLength > bestLength) {495bestLength = matchLength;496if (matchLength > matchEndIdx - matchIndex)497matchEndIdx = matchIndex + (U32)matchLength;498}499500if (ip+matchLength == iend) { /* equal : no way to know if inf or sup */501break; /* drop , to guarantee consistency ; miss a bit of compression, but other solutions can corrupt tree */502}503504if (match[matchLength] < ip[matchLength]) { /* necessarily within buffer */505/* match is smaller than current */506*smallerPtr = matchIndex; /* update smaller idx */507commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */508if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop searching */509smallerPtr = nextPtr+1; /* new "candidate" => larger than match, which was smaller than target */510matchIndex = nextPtr[1]; /* new matchIndex, larger than previous and closer to current */511} else {512/* match is larger than current */513*largerPtr = matchIndex;514commonLengthLarger = matchLength;515if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop searching */516largerPtr = nextPtr;517matchIndex = nextPtr[0];518} }519520*smallerPtr = *largerPtr = 0;521{ U32 positions = 0;522if (bestLength > 384) positions = MIN(192, (U32)(bestLength - 384)); /* speed optimization */523assert(matchEndIdx > curr + 8);524return MAX(positions, matchEndIdx - (curr + 8));525}526}527528FORCE_INLINE_TEMPLATE529void ZSTD_updateTree_internal(530ZSTD_matchState_t* ms,531const BYTE* const ip, const BYTE* const iend,532const U32 mls, const ZSTD_dictMode_e dictMode)533{534const BYTE* const base = ms->window.base;535U32 const target = (U32)(ip - base);536U32 idx = ms->nextToUpdate;537DEBUGLOG(6, "ZSTD_updateTree_internal, from %u to %u (dictMode:%u)",538idx, target, dictMode);539540while(idx < target) {541U32 const forward = ZSTD_insertBt1(ms, base+idx, iend, target, mls, dictMode == ZSTD_extDict);542assert(idx < (U32)(idx + forward));543idx += forward;544}545assert((size_t)(ip - base) <= (size_t)(U32)(-1));546assert((size_t)(iend - base) <= (size_t)(U32)(-1));547ms->nextToUpdate = target;548}549550void ZSTD_updateTree(ZSTD_matchState_t* ms, const BYTE* ip, const BYTE* iend) {551ZSTD_updateTree_internal(ms, ip, iend, ms->cParams.minMatch, ZSTD_noDict);552}553554FORCE_INLINE_TEMPLATE555U32 ZSTD_insertBtAndGetAllMatches (556ZSTD_match_t* matches, /* store result (found matches) in this table (presumed large enough) */557ZSTD_matchState_t* ms,558U32* nextToUpdate3,559const BYTE* const ip, const BYTE* const iLimit, const ZSTD_dictMode_e dictMode,560const U32 rep[ZSTD_REP_NUM],561U32 const ll0, /* tells if associated literal length is 0 or not. This value must be 0 or 1 */562const U32 lengthToBeat,563U32 const mls /* template */)564{565const ZSTD_compressionParameters* const cParams = &ms->cParams;566U32 const sufficient_len = MIN(cParams->targetLength, ZSTD_OPT_NUM -1);567const BYTE* const base = ms->window.base;568U32 const curr = (U32)(ip-base);569U32 const hashLog = cParams->hashLog;570U32 const minMatch = (mls==3) ? 3 : 4;571U32* const hashTable = ms->hashTable;572size_t const h = ZSTD_hashPtr(ip, hashLog, mls);573U32 matchIndex = hashTable[h];574U32* const bt = ms->chainTable;575U32 const btLog = cParams->chainLog - 1;576U32 const btMask= (1U << btLog) - 1;577size_t commonLengthSmaller=0, commonLengthLarger=0;578const BYTE* const dictBase = ms->window.dictBase;579U32 const dictLimit = ms->window.dictLimit;580const BYTE* const dictEnd = dictBase + dictLimit;581const BYTE* const prefixStart = base + dictLimit;582U32 const btLow = (btMask >= curr) ? 0 : curr - btMask;583U32 const windowLow = ZSTD_getLowestMatchIndex(ms, curr, cParams->windowLog);584U32 const matchLow = windowLow ? windowLow : 1;585U32* smallerPtr = bt + 2*(curr&btMask);586U32* largerPtr = bt + 2*(curr&btMask) + 1;587U32 matchEndIdx = curr+8+1; /* farthest referenced position of any match => detects repetitive patterns */588U32 dummy32; /* to be nullified at the end */589U32 mnum = 0;590U32 nbCompares = 1U << cParams->searchLog;591592const ZSTD_matchState_t* dms = dictMode == ZSTD_dictMatchState ? ms->dictMatchState : NULL;593const ZSTD_compressionParameters* const dmsCParams =594dictMode == ZSTD_dictMatchState ? &dms->cParams : NULL;595const BYTE* const dmsBase = dictMode == ZSTD_dictMatchState ? dms->window.base : NULL;596const BYTE* const dmsEnd = dictMode == ZSTD_dictMatchState ? dms->window.nextSrc : NULL;597U32 const dmsHighLimit = dictMode == ZSTD_dictMatchState ? (U32)(dmsEnd - dmsBase) : 0;598U32 const dmsLowLimit = dictMode == ZSTD_dictMatchState ? dms->window.lowLimit : 0;599U32 const dmsIndexDelta = dictMode == ZSTD_dictMatchState ? windowLow - dmsHighLimit : 0;600U32 const dmsHashLog = dictMode == ZSTD_dictMatchState ? dmsCParams->hashLog : hashLog;601U32 const dmsBtLog = dictMode == ZSTD_dictMatchState ? dmsCParams->chainLog - 1 : btLog;602U32 const dmsBtMask = dictMode == ZSTD_dictMatchState ? (1U << dmsBtLog) - 1 : 0;603U32 const dmsBtLow = dictMode == ZSTD_dictMatchState && dmsBtMask < dmsHighLimit - dmsLowLimit ? dmsHighLimit - dmsBtMask : dmsLowLimit;604605size_t bestLength = lengthToBeat-1;606DEBUGLOG(8, "ZSTD_insertBtAndGetAllMatches: current=%u", curr);607608/* check repCode */609assert(ll0 <= 1); /* necessarily 1 or 0 */610{ U32 const lastR = ZSTD_REP_NUM + ll0;611U32 repCode;612for (repCode = ll0; repCode < lastR; repCode++) {613U32 const repOffset = (repCode==ZSTD_REP_NUM) ? (rep[0] - 1) : rep[repCode];614U32 const repIndex = curr - repOffset;615U32 repLen = 0;616assert(curr >= dictLimit);617if (repOffset-1 /* intentional overflow, discards 0 and -1 */ < curr-dictLimit) { /* equivalent to `curr > repIndex >= dictLimit` */618/* We must validate the repcode offset because when we're using a dictionary the619* valid offset range shrinks when the dictionary goes out of bounds.620*/621if ((repIndex >= windowLow) & (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(ip - repOffset, minMatch))) {622repLen = (U32)ZSTD_count(ip+minMatch, ip+minMatch-repOffset, iLimit) + minMatch;623}624} else { /* repIndex < dictLimit || repIndex >= curr */625const BYTE* const repMatch = dictMode == ZSTD_dictMatchState ?626dmsBase + repIndex - dmsIndexDelta :627dictBase + repIndex;628assert(curr >= windowLow);629if ( dictMode == ZSTD_extDict630&& ( ((repOffset-1) /*intentional overflow*/ < curr - windowLow) /* equivalent to `curr > repIndex >= windowLow` */631& (((U32)((dictLimit-1) - repIndex) >= 3) ) /* intentional overflow : do not test positions overlapping 2 memory segments */)632&& (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(repMatch, minMatch)) ) {633repLen = (U32)ZSTD_count_2segments(ip+minMatch, repMatch+minMatch, iLimit, dictEnd, prefixStart) + minMatch;634}635if (dictMode == ZSTD_dictMatchState636&& ( ((repOffset-1) /*intentional overflow*/ < curr - (dmsLowLimit + dmsIndexDelta)) /* equivalent to `curr > repIndex >= dmsLowLimit` */637& ((U32)((dictLimit-1) - repIndex) >= 3) ) /* intentional overflow : do not test positions overlapping 2 memory segments */638&& (ZSTD_readMINMATCH(ip, minMatch) == ZSTD_readMINMATCH(repMatch, minMatch)) ) {639repLen = (U32)ZSTD_count_2segments(ip+minMatch, repMatch+minMatch, iLimit, dmsEnd, prefixStart) + minMatch;640} }641/* save longer solution */642if (repLen > bestLength) {643DEBUGLOG(8, "found repCode %u (ll0:%u, offset:%u) of length %u",644repCode, ll0, repOffset, repLen);645bestLength = repLen;646matches[mnum].off = STORE_REPCODE(repCode - ll0 + 1); /* expect value between 1 and 3 */647matches[mnum].len = (U32)repLen;648mnum++;649if ( (repLen > sufficient_len)650| (ip+repLen == iLimit) ) { /* best possible */651return mnum;652} } } }653654/* HC3 match finder */655if ((mls == 3) /*static*/ && (bestLength < mls)) {656U32 const matchIndex3 = ZSTD_insertAndFindFirstIndexHash3(ms, nextToUpdate3, ip);657if ((matchIndex3 >= matchLow)658& (curr - matchIndex3 < (1<<18)) /*heuristic : longer distance likely too expensive*/ ) {659size_t mlen;660if ((dictMode == ZSTD_noDict) /*static*/ || (dictMode == ZSTD_dictMatchState) /*static*/ || (matchIndex3 >= dictLimit)) {661const BYTE* const match = base + matchIndex3;662mlen = ZSTD_count(ip, match, iLimit);663} else {664const BYTE* const match = dictBase + matchIndex3;665mlen = ZSTD_count_2segments(ip, match, iLimit, dictEnd, prefixStart);666}667668/* save best solution */669if (mlen >= mls /* == 3 > bestLength */) {670DEBUGLOG(8, "found small match with hlog3, of length %u",671(U32)mlen);672bestLength = mlen;673assert(curr > matchIndex3);674assert(mnum==0); /* no prior solution */675matches[0].off = STORE_OFFSET(curr - matchIndex3);676matches[0].len = (U32)mlen;677mnum = 1;678if ( (mlen > sufficient_len) |679(ip+mlen == iLimit) ) { /* best possible length */680ms->nextToUpdate = curr+1; /* skip insertion */681return 1;682} } }683/* no dictMatchState lookup: dicts don't have a populated HC3 table */684} /* if (mls == 3) */685686hashTable[h] = curr; /* Update Hash Table */687688for (; nbCompares && (matchIndex >= matchLow); --nbCompares) {689U32* const nextPtr = bt + 2*(matchIndex & btMask);690const BYTE* match;691size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */692assert(curr > matchIndex);693694if ((dictMode == ZSTD_noDict) || (dictMode == ZSTD_dictMatchState) || (matchIndex+matchLength >= dictLimit)) {695assert(matchIndex+matchLength >= dictLimit); /* ensure the condition is correct when !extDict */696match = base + matchIndex;697if (matchIndex >= dictLimit) assert(memcmp(match, ip, matchLength) == 0); /* ensure early section of match is equal as expected */698matchLength += ZSTD_count(ip+matchLength, match+matchLength, iLimit);699} else {700match = dictBase + matchIndex;701assert(memcmp(match, ip, matchLength) == 0); /* ensure early section of match is equal as expected */702matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iLimit, dictEnd, prefixStart);703if (matchIndex+matchLength >= dictLimit)704match = base + matchIndex; /* prepare for match[matchLength] read */705}706707if (matchLength > bestLength) {708DEBUGLOG(8, "found match of length %u at distance %u (offCode=%u)",709(U32)matchLength, curr - matchIndex, STORE_OFFSET(curr - matchIndex));710assert(matchEndIdx > matchIndex);711if (matchLength > matchEndIdx - matchIndex)712matchEndIdx = matchIndex + (U32)matchLength;713bestLength = matchLength;714matches[mnum].off = STORE_OFFSET(curr - matchIndex);715matches[mnum].len = (U32)matchLength;716mnum++;717if ( (matchLength > ZSTD_OPT_NUM)718| (ip+matchLength == iLimit) /* equal : no way to know if inf or sup */) {719if (dictMode == ZSTD_dictMatchState) nbCompares = 0; /* break should also skip searching dms */720break; /* drop, to preserve bt consistency (miss a little bit of compression) */721} }722723if (match[matchLength] < ip[matchLength]) {724/* match smaller than current */725*smallerPtr = matchIndex; /* update smaller idx */726commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */727if (matchIndex <= btLow) { smallerPtr=&dummy32; break; } /* beyond tree size, stop the search */728smallerPtr = nextPtr+1; /* new candidate => larger than match, which was smaller than current */729matchIndex = nextPtr[1]; /* new matchIndex, larger than previous, closer to current */730} else {731*largerPtr = matchIndex;732commonLengthLarger = matchLength;733if (matchIndex <= btLow) { largerPtr=&dummy32; break; } /* beyond tree size, stop the search */734largerPtr = nextPtr;735matchIndex = nextPtr[0];736} }737738*smallerPtr = *largerPtr = 0;739740assert(nbCompares <= (1U << ZSTD_SEARCHLOG_MAX)); /* Check we haven't underflowed. */741if (dictMode == ZSTD_dictMatchState && nbCompares) {742size_t const dmsH = ZSTD_hashPtr(ip, dmsHashLog, mls);743U32 dictMatchIndex = dms->hashTable[dmsH];744const U32* const dmsBt = dms->chainTable;745commonLengthSmaller = commonLengthLarger = 0;746for (; nbCompares && (dictMatchIndex > dmsLowLimit); --nbCompares) {747const U32* const nextPtr = dmsBt + 2*(dictMatchIndex & dmsBtMask);748size_t matchLength = MIN(commonLengthSmaller, commonLengthLarger); /* guaranteed minimum nb of common bytes */749const BYTE* match = dmsBase + dictMatchIndex;750matchLength += ZSTD_count_2segments(ip+matchLength, match+matchLength, iLimit, dmsEnd, prefixStart);751if (dictMatchIndex+matchLength >= dmsHighLimit)752match = base + dictMatchIndex + dmsIndexDelta; /* to prepare for next usage of match[matchLength] */753754if (matchLength > bestLength) {755matchIndex = dictMatchIndex + dmsIndexDelta;756DEBUGLOG(8, "found dms match of length %u at distance %u (offCode=%u)",757(U32)matchLength, curr - matchIndex, STORE_OFFSET(curr - matchIndex));758if (matchLength > matchEndIdx - matchIndex)759matchEndIdx = matchIndex + (U32)matchLength;760bestLength = matchLength;761matches[mnum].off = STORE_OFFSET(curr - matchIndex);762matches[mnum].len = (U32)matchLength;763mnum++;764if ( (matchLength > ZSTD_OPT_NUM)765| (ip+matchLength == iLimit) /* equal : no way to know if inf or sup */) {766break; /* drop, to guarantee consistency (miss a little bit of compression) */767} }768769if (dictMatchIndex <= dmsBtLow) { break; } /* beyond tree size, stop the search */770if (match[matchLength] < ip[matchLength]) {771commonLengthSmaller = matchLength; /* all smaller will now have at least this guaranteed common length */772dictMatchIndex = nextPtr[1]; /* new matchIndex larger than previous (closer to current) */773} else {774/* match is larger than current */775commonLengthLarger = matchLength;776dictMatchIndex = nextPtr[0];777} } } /* if (dictMode == ZSTD_dictMatchState) */778779assert(matchEndIdx > curr+8);780ms->nextToUpdate = matchEndIdx - 8; /* skip repetitive patterns */781return mnum;782}783784typedef U32 (*ZSTD_getAllMatchesFn)(785ZSTD_match_t*,786ZSTD_matchState_t*,787U32*,788const BYTE*,789const BYTE*,790const U32 rep[ZSTD_REP_NUM],791U32 const ll0,792U32 const lengthToBeat);793794FORCE_INLINE_TEMPLATE U32 ZSTD_btGetAllMatches_internal(795ZSTD_match_t* matches,796ZSTD_matchState_t* ms,797U32* nextToUpdate3,798const BYTE* ip,799const BYTE* const iHighLimit,800const U32 rep[ZSTD_REP_NUM],801U32 const ll0,802U32 const lengthToBeat,803const ZSTD_dictMode_e dictMode,804const U32 mls)805{806assert(BOUNDED(3, ms->cParams.minMatch, 6) == mls);807DEBUGLOG(8, "ZSTD_BtGetAllMatches(dictMode=%d, mls=%u)", (int)dictMode, mls);808if (ip < ms->window.base + ms->nextToUpdate)809return 0; /* skipped area */810ZSTD_updateTree_internal(ms, ip, iHighLimit, mls, dictMode);811return ZSTD_insertBtAndGetAllMatches(matches, ms, nextToUpdate3, ip, iHighLimit, dictMode, rep, ll0, lengthToBeat, mls);812}813814#define ZSTD_BT_GET_ALL_MATCHES_FN(dictMode, mls) ZSTD_btGetAllMatches_##dictMode##_##mls815816#define GEN_ZSTD_BT_GET_ALL_MATCHES_(dictMode, mls) \817static U32 ZSTD_BT_GET_ALL_MATCHES_FN(dictMode, mls)( \818ZSTD_match_t* matches, \819ZSTD_matchState_t* ms, \820U32* nextToUpdate3, \821const BYTE* ip, \822const BYTE* const iHighLimit, \823const U32 rep[ZSTD_REP_NUM], \824U32 const ll0, \825U32 const lengthToBeat) \826{ \827return ZSTD_btGetAllMatches_internal( \828matches, ms, nextToUpdate3, ip, iHighLimit, \829rep, ll0, lengthToBeat, ZSTD_##dictMode, mls); \830}831832#define GEN_ZSTD_BT_GET_ALL_MATCHES(dictMode) \833GEN_ZSTD_BT_GET_ALL_MATCHES_(dictMode, 3) \834GEN_ZSTD_BT_GET_ALL_MATCHES_(dictMode, 4) \835GEN_ZSTD_BT_GET_ALL_MATCHES_(dictMode, 5) \836GEN_ZSTD_BT_GET_ALL_MATCHES_(dictMode, 6)837838GEN_ZSTD_BT_GET_ALL_MATCHES(noDict)839GEN_ZSTD_BT_GET_ALL_MATCHES(extDict)840GEN_ZSTD_BT_GET_ALL_MATCHES(dictMatchState)841842#define ZSTD_BT_GET_ALL_MATCHES_ARRAY(dictMode) \843{ \844ZSTD_BT_GET_ALL_MATCHES_FN(dictMode, 3), \845ZSTD_BT_GET_ALL_MATCHES_FN(dictMode, 4), \846ZSTD_BT_GET_ALL_MATCHES_FN(dictMode, 5), \847ZSTD_BT_GET_ALL_MATCHES_FN(dictMode, 6) \848}849850static ZSTD_getAllMatchesFn851ZSTD_selectBtGetAllMatches(ZSTD_matchState_t const* ms, ZSTD_dictMode_e const dictMode)852{853ZSTD_getAllMatchesFn const getAllMatchesFns[3][4] = {854ZSTD_BT_GET_ALL_MATCHES_ARRAY(noDict),855ZSTD_BT_GET_ALL_MATCHES_ARRAY(extDict),856ZSTD_BT_GET_ALL_MATCHES_ARRAY(dictMatchState)857};858U32 const mls = BOUNDED(3, ms->cParams.minMatch, 6);859assert((U32)dictMode < 3);860assert(mls - 3 < 4);861return getAllMatchesFns[(int)dictMode][mls - 3];862}863864/*************************865* LDM helper functions *866*************************/867868/* Struct containing info needed to make decision about ldm inclusion */869typedef struct {870rawSeqStore_t seqStore; /* External match candidates store for this block */871U32 startPosInBlock; /* Start position of the current match candidate */872U32 endPosInBlock; /* End position of the current match candidate */873U32 offset; /* Offset of the match candidate */874} ZSTD_optLdm_t;875876/* ZSTD_optLdm_skipRawSeqStoreBytes():877* Moves forward in @rawSeqStore by @nbBytes,878* which will update the fields 'pos' and 'posInSequence'.879*/880static void ZSTD_optLdm_skipRawSeqStoreBytes(rawSeqStore_t* rawSeqStore, size_t nbBytes)881{882U32 currPos = (U32)(rawSeqStore->posInSequence + nbBytes);883while (currPos && rawSeqStore->pos < rawSeqStore->size) {884rawSeq currSeq = rawSeqStore->seq[rawSeqStore->pos];885if (currPos >= currSeq.litLength + currSeq.matchLength) {886currPos -= currSeq.litLength + currSeq.matchLength;887rawSeqStore->pos++;888} else {889rawSeqStore->posInSequence = currPos;890break;891}892}893if (currPos == 0 || rawSeqStore->pos == rawSeqStore->size) {894rawSeqStore->posInSequence = 0;895}896}897898/* ZSTD_opt_getNextMatchAndUpdateSeqStore():899* Calculates the beginning and end of the next match in the current block.900* Updates 'pos' and 'posInSequence' of the ldmSeqStore.901*/902static void903ZSTD_opt_getNextMatchAndUpdateSeqStore(ZSTD_optLdm_t* optLdm, U32 currPosInBlock,904U32 blockBytesRemaining)905{906rawSeq currSeq;907U32 currBlockEndPos;908U32 literalsBytesRemaining;909U32 matchBytesRemaining;910911/* Setting match end position to MAX to ensure we never use an LDM during this block */912if (optLdm->seqStore.size == 0 || optLdm->seqStore.pos >= optLdm->seqStore.size) {913optLdm->startPosInBlock = UINT_MAX;914optLdm->endPosInBlock = UINT_MAX;915return;916}917/* Calculate appropriate bytes left in matchLength and litLength918* after adjusting based on ldmSeqStore->posInSequence */919currSeq = optLdm->seqStore.seq[optLdm->seqStore.pos];920assert(optLdm->seqStore.posInSequence <= currSeq.litLength + currSeq.matchLength);921currBlockEndPos = currPosInBlock + blockBytesRemaining;922literalsBytesRemaining = (optLdm->seqStore.posInSequence < currSeq.litLength) ?923currSeq.litLength - (U32)optLdm->seqStore.posInSequence :9240;925matchBytesRemaining = (literalsBytesRemaining == 0) ?926currSeq.matchLength - ((U32)optLdm->seqStore.posInSequence - currSeq.litLength) :927currSeq.matchLength;928929/* If there are more literal bytes than bytes remaining in block, no ldm is possible */930if (literalsBytesRemaining >= blockBytesRemaining) {931optLdm->startPosInBlock = UINT_MAX;932optLdm->endPosInBlock = UINT_MAX;933ZSTD_optLdm_skipRawSeqStoreBytes(&optLdm->seqStore, blockBytesRemaining);934return;935}936937/* Matches may be < MINMATCH by this process. In that case, we will reject them938when we are deciding whether or not to add the ldm */939optLdm->startPosInBlock = currPosInBlock + literalsBytesRemaining;940optLdm->endPosInBlock = optLdm->startPosInBlock + matchBytesRemaining;941optLdm->offset = currSeq.offset;942943if (optLdm->endPosInBlock > currBlockEndPos) {944/* Match ends after the block ends, we can't use the whole match */945optLdm->endPosInBlock = currBlockEndPos;946ZSTD_optLdm_skipRawSeqStoreBytes(&optLdm->seqStore, currBlockEndPos - currPosInBlock);947} else {948/* Consume nb of bytes equal to size of sequence left */949ZSTD_optLdm_skipRawSeqStoreBytes(&optLdm->seqStore, literalsBytesRemaining + matchBytesRemaining);950}951}952953/* ZSTD_optLdm_maybeAddMatch():954* Adds a match if it's long enough,955* based on it's 'matchStartPosInBlock' and 'matchEndPosInBlock',956* into 'matches'. Maintains the correct ordering of 'matches'.957*/958static void ZSTD_optLdm_maybeAddMatch(ZSTD_match_t* matches, U32* nbMatches,959const ZSTD_optLdm_t* optLdm, U32 currPosInBlock)960{961U32 const posDiff = currPosInBlock - optLdm->startPosInBlock;962/* Note: ZSTD_match_t actually contains offCode and matchLength (before subtracting MINMATCH) */963U32 const candidateMatchLength = optLdm->endPosInBlock - optLdm->startPosInBlock - posDiff;964965/* Ensure that current block position is not outside of the match */966if (currPosInBlock < optLdm->startPosInBlock967|| currPosInBlock >= optLdm->endPosInBlock968|| candidateMatchLength < MINMATCH) {969return;970}971972if (*nbMatches == 0 || ((candidateMatchLength > matches[*nbMatches-1].len) && *nbMatches < ZSTD_OPT_NUM)) {973U32 const candidateOffCode = STORE_OFFSET(optLdm->offset);974DEBUGLOG(6, "ZSTD_optLdm_maybeAddMatch(): Adding ldm candidate match (offCode: %u matchLength %u) at block position=%u",975candidateOffCode, candidateMatchLength, currPosInBlock);976matches[*nbMatches].len = candidateMatchLength;977matches[*nbMatches].off = candidateOffCode;978(*nbMatches)++;979}980}981982/* ZSTD_optLdm_processMatchCandidate():983* Wrapper function to update ldm seq store and call ldm functions as necessary.984*/985static void986ZSTD_optLdm_processMatchCandidate(ZSTD_optLdm_t* optLdm,987ZSTD_match_t* matches, U32* nbMatches,988U32 currPosInBlock, U32 remainingBytes)989{990if (optLdm->seqStore.size == 0 || optLdm->seqStore.pos >= optLdm->seqStore.size) {991return;992}993994if (currPosInBlock >= optLdm->endPosInBlock) {995if (currPosInBlock > optLdm->endPosInBlock) {996/* The position at which ZSTD_optLdm_processMatchCandidate() is called is not necessarily997* at the end of a match from the ldm seq store, and will often be some bytes998* over beyond matchEndPosInBlock. As such, we need to correct for these "overshoots"999*/1000U32 const posOvershoot = currPosInBlock - optLdm->endPosInBlock;1001ZSTD_optLdm_skipRawSeqStoreBytes(&optLdm->seqStore, posOvershoot);1002}1003ZSTD_opt_getNextMatchAndUpdateSeqStore(optLdm, currPosInBlock, remainingBytes);1004}1005ZSTD_optLdm_maybeAddMatch(matches, nbMatches, optLdm, currPosInBlock);1006}100710081009/*-*******************************1010* Optimal parser1011*********************************/10121013static U32 ZSTD_totalLen(ZSTD_optimal_t sol)1014{1015return sol.litlen + sol.mlen;1016}10171018#if 0 /* debug */10191020static void1021listStats(const U32* table, int lastEltID)1022{1023int const nbElts = lastEltID + 1;1024int enb;1025for (enb=0; enb < nbElts; enb++) {1026(void)table;1027/* RAWLOG(2, "%3i:%3i, ", enb, table[enb]); */1028RAWLOG(2, "%4i,", table[enb]);1029}1030RAWLOG(2, " \n");1031}10321033#endif10341035FORCE_INLINE_TEMPLATE size_t1036ZSTD_compressBlock_opt_generic(ZSTD_matchState_t* ms,1037seqStore_t* seqStore,1038U32 rep[ZSTD_REP_NUM],1039const void* src, size_t srcSize,1040const int optLevel,1041const ZSTD_dictMode_e dictMode)1042{1043optState_t* const optStatePtr = &ms->opt;1044const BYTE* const istart = (const BYTE*)src;1045const BYTE* ip = istart;1046const BYTE* anchor = istart;1047const BYTE* const iend = istart + srcSize;1048const BYTE* const ilimit = iend - 8;1049const BYTE* const base = ms->window.base;1050const BYTE* const prefixStart = base + ms->window.dictLimit;1051const ZSTD_compressionParameters* const cParams = &ms->cParams;10521053ZSTD_getAllMatchesFn getAllMatches = ZSTD_selectBtGetAllMatches(ms, dictMode);10541055U32 const sufficient_len = MIN(cParams->targetLength, ZSTD_OPT_NUM -1);1056U32 const minMatch = (cParams->minMatch == 3) ? 3 : 4;1057U32 nextToUpdate3 = ms->nextToUpdate;10581059ZSTD_optimal_t* const opt = optStatePtr->priceTable;1060ZSTD_match_t* const matches = optStatePtr->matchTable;1061ZSTD_optimal_t lastSequence;1062ZSTD_optLdm_t optLdm;10631064optLdm.seqStore = ms->ldmSeqStore ? *ms->ldmSeqStore : kNullRawSeqStore;1065optLdm.endPosInBlock = optLdm.startPosInBlock = optLdm.offset = 0;1066ZSTD_opt_getNextMatchAndUpdateSeqStore(&optLdm, (U32)(ip-istart), (U32)(iend-ip));10671068/* init */1069DEBUGLOG(5, "ZSTD_compressBlock_opt_generic: current=%u, prefix=%u, nextToUpdate=%u",1070(U32)(ip - base), ms->window.dictLimit, ms->nextToUpdate);1071assert(optLevel <= 2);1072ZSTD_rescaleFreqs(optStatePtr, (const BYTE*)src, srcSize, optLevel);1073ip += (ip==prefixStart);10741075/* Match Loop */1076while (ip < ilimit) {1077U32 cur, last_pos = 0;10781079/* find first match */1080{ U32 const litlen = (U32)(ip - anchor);1081U32 const ll0 = !litlen;1082U32 nbMatches = getAllMatches(matches, ms, &nextToUpdate3, ip, iend, rep, ll0, minMatch);1083ZSTD_optLdm_processMatchCandidate(&optLdm, matches, &nbMatches,1084(U32)(ip-istart), (U32)(iend - ip));1085if (!nbMatches) { ip++; continue; }10861087/* initialize opt[0] */1088{ U32 i ; for (i=0; i<ZSTD_REP_NUM; i++) opt[0].rep[i] = rep[i]; }1089opt[0].mlen = 0; /* means is_a_literal */1090opt[0].litlen = litlen;1091/* We don't need to include the actual price of the literals because1092* it is static for the duration of the forward pass, and is included1093* in every price. We include the literal length to avoid negative1094* prices when we subtract the previous literal length.1095*/1096opt[0].price = (int)ZSTD_litLengthPrice(litlen, optStatePtr, optLevel);10971098/* large match -> immediate encoding */1099{ U32 const maxML = matches[nbMatches-1].len;1100U32 const maxOffcode = matches[nbMatches-1].off;1101DEBUGLOG(6, "found %u matches of maxLength=%u and maxOffCode=%u at cPos=%u => start new series",1102nbMatches, maxML, maxOffcode, (U32)(ip-prefixStart));11031104if (maxML > sufficient_len) {1105lastSequence.litlen = litlen;1106lastSequence.mlen = maxML;1107lastSequence.off = maxOffcode;1108DEBUGLOG(6, "large match (%u>%u), immediate encoding",1109maxML, sufficient_len);1110cur = 0;1111last_pos = ZSTD_totalLen(lastSequence);1112goto _shortestPath;1113} }11141115/* set prices for first matches starting position == 0 */1116assert(opt[0].price >= 0);1117{ U32 const literalsPrice = (U32)opt[0].price + ZSTD_litLengthPrice(0, optStatePtr, optLevel);1118U32 pos;1119U32 matchNb;1120for (pos = 1; pos < minMatch; pos++) {1121opt[pos].price = ZSTD_MAX_PRICE; /* mlen, litlen and price will be fixed during forward scanning */1122}1123for (matchNb = 0; matchNb < nbMatches; matchNb++) {1124U32 const offcode = matches[matchNb].off;1125U32 const end = matches[matchNb].len;1126for ( ; pos <= end ; pos++ ) {1127U32 const matchPrice = ZSTD_getMatchPrice(offcode, pos, optStatePtr, optLevel);1128U32 const sequencePrice = literalsPrice + matchPrice;1129DEBUGLOG(7, "rPos:%u => set initial price : %.2f",1130pos, ZSTD_fCost(sequencePrice));1131opt[pos].mlen = pos;1132opt[pos].off = offcode;1133opt[pos].litlen = litlen;1134opt[pos].price = (int)sequencePrice;1135} }1136last_pos = pos-1;1137}1138}11391140/* check further positions */1141for (cur = 1; cur <= last_pos; cur++) {1142const BYTE* const inr = ip + cur;1143assert(cur < ZSTD_OPT_NUM);1144DEBUGLOG(7, "cPos:%zi==rPos:%u", inr-istart, cur)11451146/* Fix current position with one literal if cheaper */1147{ U32 const litlen = (opt[cur-1].mlen == 0) ? opt[cur-1].litlen + 1 : 1;1148int const price = opt[cur-1].price1149+ (int)ZSTD_rawLiteralsCost(ip+cur-1, 1, optStatePtr, optLevel)1150+ (int)ZSTD_litLengthPrice(litlen, optStatePtr, optLevel)1151- (int)ZSTD_litLengthPrice(litlen-1, optStatePtr, optLevel);1152assert(price < 1000000000); /* overflow check */1153if (price <= opt[cur].price) {1154DEBUGLOG(7, "cPos:%zi==rPos:%u : better price (%.2f<=%.2f) using literal (ll==%u) (hist:%u,%u,%u)",1155inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price), litlen,1156opt[cur-1].rep[0], opt[cur-1].rep[1], opt[cur-1].rep[2]);1157opt[cur].mlen = 0;1158opt[cur].off = 0;1159opt[cur].litlen = litlen;1160opt[cur].price = price;1161} else {1162DEBUGLOG(7, "cPos:%zi==rPos:%u : literal would cost more (%.2f>%.2f) (hist:%u,%u,%u)",1163inr-istart, cur, ZSTD_fCost(price), ZSTD_fCost(opt[cur].price),1164opt[cur].rep[0], opt[cur].rep[1], opt[cur].rep[2]);1165}1166}11671168/* Set the repcodes of the current position. We must do it here1169* because we rely on the repcodes of the 2nd to last sequence being1170* correct to set the next chunks repcodes during the backward1171* traversal.1172*/1173ZSTD_STATIC_ASSERT(sizeof(opt[cur].rep) == sizeof(repcodes_t));1174assert(cur >= opt[cur].mlen);1175if (opt[cur].mlen != 0) {1176U32 const prev = cur - opt[cur].mlen;1177repcodes_t const newReps = ZSTD_newRep(opt[prev].rep, opt[cur].off, opt[cur].litlen==0);1178ZSTD_memcpy(opt[cur].rep, &newReps, sizeof(repcodes_t));1179} else {1180ZSTD_memcpy(opt[cur].rep, opt[cur - 1].rep, sizeof(repcodes_t));1181}11821183/* last match must start at a minimum distance of 8 from oend */1184if (inr > ilimit) continue;11851186if (cur == last_pos) break;11871188if ( (optLevel==0) /*static_test*/1189&& (opt[cur+1].price <= opt[cur].price + (BITCOST_MULTIPLIER/2)) ) {1190DEBUGLOG(7, "move to next rPos:%u : price is <=", cur+1);1191continue; /* skip unpromising positions; about ~+6% speed, -0.01 ratio */1192}11931194assert(opt[cur].price >= 0);1195{ U32 const ll0 = (opt[cur].mlen != 0);1196U32 const litlen = (opt[cur].mlen == 0) ? opt[cur].litlen : 0;1197U32 const previousPrice = (U32)opt[cur].price;1198U32 const basePrice = previousPrice + ZSTD_litLengthPrice(0, optStatePtr, optLevel);1199U32 nbMatches = getAllMatches(matches, ms, &nextToUpdate3, inr, iend, opt[cur].rep, ll0, minMatch);1200U32 matchNb;12011202ZSTD_optLdm_processMatchCandidate(&optLdm, matches, &nbMatches,1203(U32)(inr-istart), (U32)(iend-inr));12041205if (!nbMatches) {1206DEBUGLOG(7, "rPos:%u : no match found", cur);1207continue;1208}12091210{ U32 const maxML = matches[nbMatches-1].len;1211DEBUGLOG(7, "cPos:%zi==rPos:%u, found %u matches, of maxLength=%u",1212inr-istart, cur, nbMatches, maxML);12131214if ( (maxML > sufficient_len)1215|| (cur + maxML >= ZSTD_OPT_NUM) ) {1216lastSequence.mlen = maxML;1217lastSequence.off = matches[nbMatches-1].off;1218lastSequence.litlen = litlen;1219cur -= (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 */1220last_pos = cur + ZSTD_totalLen(lastSequence);1221if (cur > ZSTD_OPT_NUM) cur = 0; /* underflow => first match */1222goto _shortestPath;1223} }12241225/* set prices using matches found at position == cur */1226for (matchNb = 0; matchNb < nbMatches; matchNb++) {1227U32 const offset = matches[matchNb].off;1228U32 const lastML = matches[matchNb].len;1229U32 const startML = (matchNb>0) ? matches[matchNb-1].len+1 : minMatch;1230U32 mlen;12311232DEBUGLOG(7, "testing match %u => offCode=%4u, mlen=%2u, llen=%2u",1233matchNb, matches[matchNb].off, lastML, litlen);12341235for (mlen = lastML; mlen >= startML; mlen--) { /* scan downward */1236U32 const pos = cur + mlen;1237int const price = (int)basePrice + (int)ZSTD_getMatchPrice(offset, mlen, optStatePtr, optLevel);12381239if ((pos > last_pos) || (price < opt[pos].price)) {1240DEBUGLOG(7, "rPos:%u (ml=%2u) => new better price (%.2f<%.2f)",1241pos, mlen, ZSTD_fCost(price), ZSTD_fCost(opt[pos].price));1242while (last_pos < pos) { opt[last_pos+1].price = ZSTD_MAX_PRICE; last_pos++; } /* fill empty positions */1243opt[pos].mlen = mlen;1244opt[pos].off = offset;1245opt[pos].litlen = litlen;1246opt[pos].price = price;1247} else {1248DEBUGLOG(7, "rPos:%u (ml=%2u) => new price is worse (%.2f>=%.2f)",1249pos, mlen, ZSTD_fCost(price), ZSTD_fCost(opt[pos].price));1250if (optLevel==0) break; /* early update abort; gets ~+10% speed for about -0.01 ratio loss */1251}1252} } }1253} /* for (cur = 1; cur <= last_pos; cur++) */12541255lastSequence = opt[last_pos];1256cur = last_pos > ZSTD_totalLen(lastSequence) ? last_pos - ZSTD_totalLen(lastSequence) : 0; /* single sequence, and it starts before `ip` */1257assert(cur < ZSTD_OPT_NUM); /* control overflow*/12581259_shortestPath: /* cur, last_pos, best_mlen, best_off have to be set */1260assert(opt[0].mlen == 0);12611262/* Set the next chunk's repcodes based on the repcodes of the beginning1263* of the last match, and the last sequence. This avoids us having to1264* update them while traversing the sequences.1265*/1266if (lastSequence.mlen != 0) {1267repcodes_t const reps = ZSTD_newRep(opt[cur].rep, lastSequence.off, lastSequence.litlen==0);1268ZSTD_memcpy(rep, &reps, sizeof(reps));1269} else {1270ZSTD_memcpy(rep, opt[cur].rep, sizeof(repcodes_t));1271}12721273{ U32 const storeEnd = cur + 1;1274U32 storeStart = storeEnd;1275U32 seqPos = cur;12761277DEBUGLOG(6, "start reverse traversal (last_pos:%u, cur:%u)",1278last_pos, cur); (void)last_pos;1279assert(storeEnd < ZSTD_OPT_NUM);1280DEBUGLOG(6, "last sequence copied into pos=%u (llen=%u,mlen=%u,ofc=%u)",1281storeEnd, lastSequence.litlen, lastSequence.mlen, lastSequence.off);1282opt[storeEnd] = lastSequence;1283while (seqPos > 0) {1284U32 const backDist = ZSTD_totalLen(opt[seqPos]);1285storeStart--;1286DEBUGLOG(6, "sequence from rPos=%u copied into pos=%u (llen=%u,mlen=%u,ofc=%u)",1287seqPos, storeStart, opt[seqPos].litlen, opt[seqPos].mlen, opt[seqPos].off);1288opt[storeStart] = opt[seqPos];1289seqPos = (seqPos > backDist) ? seqPos - backDist : 0;1290}12911292/* save sequences */1293DEBUGLOG(6, "sending selected sequences into seqStore")1294{ U32 storePos;1295for (storePos=storeStart; storePos <= storeEnd; storePos++) {1296U32 const llen = opt[storePos].litlen;1297U32 const mlen = opt[storePos].mlen;1298U32 const offCode = opt[storePos].off;1299U32 const advance = llen + mlen;1300DEBUGLOG(6, "considering seq starting at %zi, llen=%u, mlen=%u",1301anchor - istart, (unsigned)llen, (unsigned)mlen);13021303if (mlen==0) { /* only literals => must be last "sequence", actually starting a new stream of sequences */1304assert(storePos == storeEnd); /* must be last sequence */1305ip = anchor + llen; /* last "sequence" is a bunch of literals => don't progress anchor */1306continue; /* will finish */1307}13081309assert(anchor + llen <= iend);1310ZSTD_updateStats(optStatePtr, llen, anchor, offCode, mlen);1311ZSTD_storeSeq(seqStore, llen, anchor, iend, offCode, mlen);1312anchor += advance;1313ip = anchor;1314} }1315ZSTD_setBasePrices(optStatePtr, optLevel);1316}1317} /* while (ip < ilimit) */13181319/* Return the last literals size */1320return (size_t)(iend - anchor);1321}13221323static size_t ZSTD_compressBlock_opt0(1324ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1325const void* src, size_t srcSize, const ZSTD_dictMode_e dictMode)1326{1327return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 0 /* optLevel */, dictMode);1328}13291330static size_t ZSTD_compressBlock_opt2(1331ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1332const void* src, size_t srcSize, const ZSTD_dictMode_e dictMode)1333{1334return ZSTD_compressBlock_opt_generic(ms, seqStore, rep, src, srcSize, 2 /* optLevel */, dictMode);1335}13361337size_t ZSTD_compressBlock_btopt(1338ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1339const void* src, size_t srcSize)1340{1341DEBUGLOG(5, "ZSTD_compressBlock_btopt");1342return ZSTD_compressBlock_opt0(ms, seqStore, rep, src, srcSize, ZSTD_noDict);1343}13441345134613471348/* ZSTD_initStats_ultra():1349* make a first compression pass, just to seed stats with more accurate starting values.1350* only works on first block, with no dictionary and no ldm.1351* this function cannot error, hence its contract must be respected.1352*/1353static void1354ZSTD_initStats_ultra(ZSTD_matchState_t* ms,1355seqStore_t* seqStore,1356U32 rep[ZSTD_REP_NUM],1357const void* src, size_t srcSize)1358{1359U32 tmpRep[ZSTD_REP_NUM]; /* updated rep codes will sink here */1360ZSTD_memcpy(tmpRep, rep, sizeof(tmpRep));13611362DEBUGLOG(4, "ZSTD_initStats_ultra (srcSize=%zu)", srcSize);1363assert(ms->opt.litLengthSum == 0); /* first block */1364assert(seqStore->sequences == seqStore->sequencesStart); /* no ldm */1365assert(ms->window.dictLimit == ms->window.lowLimit); /* no dictionary */1366assert(ms->window.dictLimit - ms->nextToUpdate <= 1); /* no prefix (note: intentional overflow, defined as 2-complement) */13671368ZSTD_compressBlock_opt2(ms, seqStore, tmpRep, src, srcSize, ZSTD_noDict); /* generate stats into ms->opt*/13691370/* invalidate first scan from history */1371ZSTD_resetSeqStore(seqStore);1372ms->window.base -= srcSize;1373ms->window.dictLimit += (U32)srcSize;1374ms->window.lowLimit = ms->window.dictLimit;1375ms->nextToUpdate = ms->window.dictLimit;13761377}13781379size_t ZSTD_compressBlock_btultra(1380ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1381const void* src, size_t srcSize)1382{1383DEBUGLOG(5, "ZSTD_compressBlock_btultra (srcSize=%zu)", srcSize);1384return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_noDict);1385}13861387size_t ZSTD_compressBlock_btultra2(1388ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1389const void* src, size_t srcSize)1390{1391U32 const curr = (U32)((const BYTE*)src - ms->window.base);1392DEBUGLOG(5, "ZSTD_compressBlock_btultra2 (srcSize=%zu)", srcSize);13931394/* 2-pass strategy:1395* this strategy makes a first pass over first block to collect statistics1396* and seed next round's statistics with it.1397* After 1st pass, function forgets everything, and starts a new block.1398* Consequently, this can only work if no data has been previously loaded in tables,1399* aka, no dictionary, no prefix, no ldm preprocessing.1400* The compression ratio gain is generally small (~0.5% on first block),1401* the cost is 2x cpu time on first block. */1402assert(srcSize <= ZSTD_BLOCKSIZE_MAX);1403if ( (ms->opt.litLengthSum==0) /* first block */1404&& (seqStore->sequences == seqStore->sequencesStart) /* no ldm */1405&& (ms->window.dictLimit == ms->window.lowLimit) /* no dictionary */1406&& (curr == ms->window.dictLimit) /* start of frame, nothing already loaded nor skipped */1407&& (srcSize > ZSTD_PREDEF_THRESHOLD)1408) {1409ZSTD_initStats_ultra(ms, seqStore, rep, src, srcSize);1410}14111412return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_noDict);1413}14141415size_t ZSTD_compressBlock_btopt_dictMatchState(1416ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1417const void* src, size_t srcSize)1418{1419return ZSTD_compressBlock_opt0(ms, seqStore, rep, src, srcSize, ZSTD_dictMatchState);1420}14211422size_t ZSTD_compressBlock_btultra_dictMatchState(1423ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1424const void* src, size_t srcSize)1425{1426return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_dictMatchState);1427}14281429size_t ZSTD_compressBlock_btopt_extDict(1430ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1431const void* src, size_t srcSize)1432{1433return ZSTD_compressBlock_opt0(ms, seqStore, rep, src, srcSize, ZSTD_extDict);1434}14351436size_t ZSTD_compressBlock_btultra_extDict(1437ZSTD_matchState_t* ms, seqStore_t* seqStore, U32 rep[ZSTD_REP_NUM],1438const void* src, size_t srcSize)1439{1440return ZSTD_compressBlock_opt2(ms, seqStore, rep, src, srcSize, ZSTD_extDict);1441}14421443/* note : no btultra2 variant for extDict nor dictMatchState,1444* because btultra2 is not meant to work with dictionaries1445* and is only specific for the first block (no prefix) */144614471448