Path: blob/main/sys/contrib/zstd/lib/compress/huf_compress.c
48378 views
/* ******************************************************************1* Huffman encoder, part of New Generation Entropy library2* Copyright (c) Yann Collet, Facebook, Inc.3*4* You can contact the author at :5* - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy6* - Public forum : https://groups.google.com/forum/#!forum/lz4c7*8* This source code is licensed under both the BSD-style license (found in the9* LICENSE file in the root directory of this source tree) and the GPLv2 (found10* in the COPYING file in the root directory of this source tree).11* You may select, at your option, one of the above-listed licenses.12****************************************************************** */1314/* **************************************************************15* Compiler specifics16****************************************************************/17#ifdef _MSC_VER /* Visual Studio */18# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */19#endif202122/* **************************************************************23* Includes24****************************************************************/25#include "../common/zstd_deps.h" /* ZSTD_memcpy, ZSTD_memset */26#include "../common/compiler.h"27#include "../common/bitstream.h"28#include "hist.h"29#define FSE_STATIC_LINKING_ONLY /* FSE_optimalTableLog_internal */30#include "../common/fse.h" /* header compression */31#define HUF_STATIC_LINKING_ONLY32#include "../common/huf.h"33#include "../common/error_private.h"343536/* **************************************************************37* Error Management38****************************************************************/39#define HUF_isError ERR_isError40#define HUF_STATIC_ASSERT(c) DEBUG_STATIC_ASSERT(c) /* use only *after* variable declarations */414243/* **************************************************************44* Utils45****************************************************************/46unsigned HUF_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue)47{48return FSE_optimalTableLog_internal(maxTableLog, srcSize, maxSymbolValue, 1);49}505152/* *******************************************************53* HUF : Huffman block compression54*********************************************************/55#define HUF_WORKSPACE_MAX_ALIGNMENT 85657static void* HUF_alignUpWorkspace(void* workspace, size_t* workspaceSizePtr, size_t align)58{59size_t const mask = align - 1;60size_t const rem = (size_t)workspace & mask;61size_t const add = (align - rem) & mask;62BYTE* const aligned = (BYTE*)workspace + add;63assert((align & (align - 1)) == 0); /* pow 2 */64assert(align <= HUF_WORKSPACE_MAX_ALIGNMENT);65if (*workspaceSizePtr >= add) {66assert(add < align);67assert(((size_t)aligned & mask) == 0);68*workspaceSizePtr -= add;69return aligned;70} else {71*workspaceSizePtr = 0;72return NULL;73}74}757677/* HUF_compressWeights() :78* Same as FSE_compress(), but dedicated to huff0's weights compression.79* The use case needs much less stack memory.80* Note : all elements within weightTable are supposed to be <= HUF_TABLELOG_MAX.81*/82#define MAX_FSE_TABLELOG_FOR_HUFF_HEADER 68384typedef struct {85FSE_CTable CTable[FSE_CTABLE_SIZE_U32(MAX_FSE_TABLELOG_FOR_HUFF_HEADER, HUF_TABLELOG_MAX)];86U32 scratchBuffer[FSE_BUILD_CTABLE_WORKSPACE_SIZE_U32(HUF_TABLELOG_MAX, MAX_FSE_TABLELOG_FOR_HUFF_HEADER)];87unsigned count[HUF_TABLELOG_MAX+1];88S16 norm[HUF_TABLELOG_MAX+1];89} HUF_CompressWeightsWksp;9091static size_t HUF_compressWeights(void* dst, size_t dstSize, const void* weightTable, size_t wtSize, void* workspace, size_t workspaceSize)92{93BYTE* const ostart = (BYTE*) dst;94BYTE* op = ostart;95BYTE* const oend = ostart + dstSize;9697unsigned maxSymbolValue = HUF_TABLELOG_MAX;98U32 tableLog = MAX_FSE_TABLELOG_FOR_HUFF_HEADER;99HUF_CompressWeightsWksp* wksp = (HUF_CompressWeightsWksp*)HUF_alignUpWorkspace(workspace, &workspaceSize, ZSTD_ALIGNOF(U32));100101if (workspaceSize < sizeof(HUF_CompressWeightsWksp)) return ERROR(GENERIC);102103/* init conditions */104if (wtSize <= 1) return 0; /* Not compressible */105106/* Scan input and build symbol stats */107{ unsigned const maxCount = HIST_count_simple(wksp->count, &maxSymbolValue, weightTable, wtSize); /* never fails */108if (maxCount == wtSize) return 1; /* only a single symbol in src : rle */109if (maxCount == 1) return 0; /* each symbol present maximum once => not compressible */110}111112tableLog = FSE_optimalTableLog(tableLog, wtSize, maxSymbolValue);113CHECK_F( FSE_normalizeCount(wksp->norm, tableLog, wksp->count, wtSize, maxSymbolValue, /* useLowProbCount */ 0) );114115/* Write table description header */116{ CHECK_V_F(hSize, FSE_writeNCount(op, (size_t)(oend-op), wksp->norm, maxSymbolValue, tableLog) );117op += hSize;118}119120/* Compress */121CHECK_F( FSE_buildCTable_wksp(wksp->CTable, wksp->norm, maxSymbolValue, tableLog, wksp->scratchBuffer, sizeof(wksp->scratchBuffer)) );122{ CHECK_V_F(cSize, FSE_compress_usingCTable(op, (size_t)(oend - op), weightTable, wtSize, wksp->CTable) );123if (cSize == 0) return 0; /* not enough space for compressed data */124op += cSize;125}126127return (size_t)(op-ostart);128}129130static size_t HUF_getNbBits(HUF_CElt elt)131{132return elt & 0xFF;133}134135static size_t HUF_getNbBitsFast(HUF_CElt elt)136{137return elt;138}139140static size_t HUF_getValue(HUF_CElt elt)141{142return elt & ~0xFF;143}144145static size_t HUF_getValueFast(HUF_CElt elt)146{147return elt;148}149150static void HUF_setNbBits(HUF_CElt* elt, size_t nbBits)151{152assert(nbBits <= HUF_TABLELOG_ABSOLUTEMAX);153*elt = nbBits;154}155156static void HUF_setValue(HUF_CElt* elt, size_t value)157{158size_t const nbBits = HUF_getNbBits(*elt);159if (nbBits > 0) {160assert((value >> nbBits) == 0);161*elt |= value << (sizeof(HUF_CElt) * 8 - nbBits);162}163}164165typedef struct {166HUF_CompressWeightsWksp wksp;167BYTE bitsToWeight[HUF_TABLELOG_MAX + 1]; /* precomputed conversion table */168BYTE huffWeight[HUF_SYMBOLVALUE_MAX];169} HUF_WriteCTableWksp;170171size_t HUF_writeCTable_wksp(void* dst, size_t maxDstSize,172const HUF_CElt* CTable, unsigned maxSymbolValue, unsigned huffLog,173void* workspace, size_t workspaceSize)174{175HUF_CElt const* const ct = CTable + 1;176BYTE* op = (BYTE*)dst;177U32 n;178HUF_WriteCTableWksp* wksp = (HUF_WriteCTableWksp*)HUF_alignUpWorkspace(workspace, &workspaceSize, ZSTD_ALIGNOF(U32));179180/* check conditions */181if (workspaceSize < sizeof(HUF_WriteCTableWksp)) return ERROR(GENERIC);182if (maxSymbolValue > HUF_SYMBOLVALUE_MAX) return ERROR(maxSymbolValue_tooLarge);183184/* convert to weight */185wksp->bitsToWeight[0] = 0;186for (n=1; n<huffLog+1; n++)187wksp->bitsToWeight[n] = (BYTE)(huffLog + 1 - n);188for (n=0; n<maxSymbolValue; n++)189wksp->huffWeight[n] = wksp->bitsToWeight[HUF_getNbBits(ct[n])];190191/* attempt weights compression by FSE */192if (maxDstSize < 1) return ERROR(dstSize_tooSmall);193{ CHECK_V_F(hSize, HUF_compressWeights(op+1, maxDstSize-1, wksp->huffWeight, maxSymbolValue, &wksp->wksp, sizeof(wksp->wksp)) );194if ((hSize>1) & (hSize < maxSymbolValue/2)) { /* FSE compressed */195op[0] = (BYTE)hSize;196return hSize+1;197} }198199/* write raw values as 4-bits (max : 15) */200if (maxSymbolValue > (256-128)) return ERROR(GENERIC); /* should not happen : likely means source cannot be compressed */201if (((maxSymbolValue+1)/2) + 1 > maxDstSize) return ERROR(dstSize_tooSmall); /* not enough space within dst buffer */202op[0] = (BYTE)(128 /*special case*/ + (maxSymbolValue-1));203wksp->huffWeight[maxSymbolValue] = 0; /* to be sure it doesn't cause msan issue in final combination */204for (n=0; n<maxSymbolValue; n+=2)205op[(n/2)+1] = (BYTE)((wksp->huffWeight[n] << 4) + wksp->huffWeight[n+1]);206return ((maxSymbolValue+1)/2) + 1;207}208209/*! HUF_writeCTable() :210`CTable` : Huffman tree to save, using huf representation.211@return : size of saved CTable */212size_t HUF_writeCTable (void* dst, size_t maxDstSize,213const HUF_CElt* CTable, unsigned maxSymbolValue, unsigned huffLog)214{215HUF_WriteCTableWksp wksp;216return HUF_writeCTable_wksp(dst, maxDstSize, CTable, maxSymbolValue, huffLog, &wksp, sizeof(wksp));217}218219220size_t HUF_readCTable (HUF_CElt* CTable, unsigned* maxSymbolValuePtr, const void* src, size_t srcSize, unsigned* hasZeroWeights)221{222BYTE huffWeight[HUF_SYMBOLVALUE_MAX + 1]; /* init not required, even though some static analyzer may complain */223U32 rankVal[HUF_TABLELOG_ABSOLUTEMAX + 1]; /* large enough for values from 0 to 16 */224U32 tableLog = 0;225U32 nbSymbols = 0;226HUF_CElt* const ct = CTable + 1;227228/* get symbol weights */229CHECK_V_F(readSize, HUF_readStats(huffWeight, HUF_SYMBOLVALUE_MAX+1, rankVal, &nbSymbols, &tableLog, src, srcSize));230*hasZeroWeights = (rankVal[0] > 0);231232/* check result */233if (tableLog > HUF_TABLELOG_MAX) return ERROR(tableLog_tooLarge);234if (nbSymbols > *maxSymbolValuePtr+1) return ERROR(maxSymbolValue_tooSmall);235236CTable[0] = tableLog;237238/* Prepare base value per rank */239{ U32 n, nextRankStart = 0;240for (n=1; n<=tableLog; n++) {241U32 curr = nextRankStart;242nextRankStart += (rankVal[n] << (n-1));243rankVal[n] = curr;244} }245246/* fill nbBits */247{ U32 n; for (n=0; n<nbSymbols; n++) {248const U32 w = huffWeight[n];249HUF_setNbBits(ct + n, (BYTE)(tableLog + 1 - w) & -(w != 0));250} }251252/* fill val */253{ U16 nbPerRank[HUF_TABLELOG_MAX+2] = {0}; /* support w=0=>n=tableLog+1 */254U16 valPerRank[HUF_TABLELOG_MAX+2] = {0};255{ U32 n; for (n=0; n<nbSymbols; n++) nbPerRank[HUF_getNbBits(ct[n])]++; }256/* determine stating value per rank */257valPerRank[tableLog+1] = 0; /* for w==0 */258{ U16 min = 0;259U32 n; for (n=tableLog; n>0; n--) { /* start at n=tablelog <-> w=1 */260valPerRank[n] = min; /* get starting value within each rank */261min += nbPerRank[n];262min >>= 1;263} }264/* assign value within rank, symbol order */265{ U32 n; for (n=0; n<nbSymbols; n++) HUF_setValue(ct + n, valPerRank[HUF_getNbBits(ct[n])]++); }266}267268*maxSymbolValuePtr = nbSymbols - 1;269return readSize;270}271272U32 HUF_getNbBitsFromCTable(HUF_CElt const* CTable, U32 symbolValue)273{274const HUF_CElt* ct = CTable + 1;275assert(symbolValue <= HUF_SYMBOLVALUE_MAX);276return (U32)HUF_getNbBits(ct[symbolValue]);277}278279280typedef struct nodeElt_s {281U32 count;282U16 parent;283BYTE byte;284BYTE nbBits;285} nodeElt;286287/**288* HUF_setMaxHeight():289* Enforces maxNbBits on the Huffman tree described in huffNode.290*291* It sets all nodes with nbBits > maxNbBits to be maxNbBits. Then it adjusts292* the tree to so that it is a valid canonical Huffman tree.293*294* @pre The sum of the ranks of each symbol == 2^largestBits,295* where largestBits == huffNode[lastNonNull].nbBits.296* @post The sum of the ranks of each symbol == 2^largestBits,297* where largestBits is the return value <= maxNbBits.298*299* @param huffNode The Huffman tree modified in place to enforce maxNbBits.300* @param lastNonNull The symbol with the lowest count in the Huffman tree.301* @param maxNbBits The maximum allowed number of bits, which the Huffman tree302* may not respect. After this function the Huffman tree will303* respect maxNbBits.304* @return The maximum number of bits of the Huffman tree after adjustment,305* necessarily no more than maxNbBits.306*/307static U32 HUF_setMaxHeight(nodeElt* huffNode, U32 lastNonNull, U32 maxNbBits)308{309const U32 largestBits = huffNode[lastNonNull].nbBits;310/* early exit : no elt > maxNbBits, so the tree is already valid. */311if (largestBits <= maxNbBits) return largestBits;312313/* there are several too large elements (at least >= 2) */314{ int totalCost = 0;315const U32 baseCost = 1 << (largestBits - maxNbBits);316int n = (int)lastNonNull;317318/* Adjust any ranks > maxNbBits to maxNbBits.319* Compute totalCost, which is how far the sum of the ranks is320* we are over 2^largestBits after adjust the offending ranks.321*/322while (huffNode[n].nbBits > maxNbBits) {323totalCost += baseCost - (1 << (largestBits - huffNode[n].nbBits));324huffNode[n].nbBits = (BYTE)maxNbBits;325n--;326}327/* n stops at huffNode[n].nbBits <= maxNbBits */328assert(huffNode[n].nbBits <= maxNbBits);329/* n end at index of smallest symbol using < maxNbBits */330while (huffNode[n].nbBits == maxNbBits) --n;331332/* renorm totalCost from 2^largestBits to 2^maxNbBits333* note : totalCost is necessarily a multiple of baseCost */334assert((totalCost & (baseCost - 1)) == 0);335totalCost >>= (largestBits - maxNbBits);336assert(totalCost > 0);337338/* repay normalized cost */339{ U32 const noSymbol = 0xF0F0F0F0;340U32 rankLast[HUF_TABLELOG_MAX+2];341342/* Get pos of last (smallest = lowest cum. count) symbol per rank */343ZSTD_memset(rankLast, 0xF0, sizeof(rankLast));344{ U32 currentNbBits = maxNbBits;345int pos;346for (pos=n ; pos >= 0; pos--) {347if (huffNode[pos].nbBits >= currentNbBits) continue;348currentNbBits = huffNode[pos].nbBits; /* < maxNbBits */349rankLast[maxNbBits-currentNbBits] = (U32)pos;350} }351352while (totalCost > 0) {353/* Try to reduce the next power of 2 above totalCost because we354* gain back half the rank.355*/356U32 nBitsToDecrease = BIT_highbit32((U32)totalCost) + 1;357for ( ; nBitsToDecrease > 1; nBitsToDecrease--) {358U32 const highPos = rankLast[nBitsToDecrease];359U32 const lowPos = rankLast[nBitsToDecrease-1];360if (highPos == noSymbol) continue;361/* Decrease highPos if no symbols of lowPos or if it is362* not cheaper to remove 2 lowPos than highPos.363*/364if (lowPos == noSymbol) break;365{ U32 const highTotal = huffNode[highPos].count;366U32 const lowTotal = 2 * huffNode[lowPos].count;367if (highTotal <= lowTotal) break;368} }369/* only triggered when no more rank 1 symbol left => find closest one (note : there is necessarily at least one !) */370assert(rankLast[nBitsToDecrease] != noSymbol || nBitsToDecrease == 1);371/* HUF_MAX_TABLELOG test just to please gcc 5+; but it should not be necessary */372while ((nBitsToDecrease<=HUF_TABLELOG_MAX) && (rankLast[nBitsToDecrease] == noSymbol))373nBitsToDecrease++;374assert(rankLast[nBitsToDecrease] != noSymbol);375/* Increase the number of bits to gain back half the rank cost. */376totalCost -= 1 << (nBitsToDecrease-1);377huffNode[rankLast[nBitsToDecrease]].nbBits++;378379/* Fix up the new rank.380* If the new rank was empty, this symbol is now its smallest.381* Otherwise, this symbol will be the largest in the new rank so no adjustment.382*/383if (rankLast[nBitsToDecrease-1] == noSymbol)384rankLast[nBitsToDecrease-1] = rankLast[nBitsToDecrease];385/* Fix up the old rank.386* If the symbol was at position 0, meaning it was the highest weight symbol in the tree,387* it must be the only symbol in its rank, so the old rank now has no symbols.388* Otherwise, since the Huffman nodes are sorted by count, the previous position is now389* the smallest node in the rank. If the previous position belongs to a different rank,390* then the rank is now empty.391*/392if (rankLast[nBitsToDecrease] == 0) /* special case, reached largest symbol */393rankLast[nBitsToDecrease] = noSymbol;394else {395rankLast[nBitsToDecrease]--;396if (huffNode[rankLast[nBitsToDecrease]].nbBits != maxNbBits-nBitsToDecrease)397rankLast[nBitsToDecrease] = noSymbol; /* this rank is now empty */398}399} /* while (totalCost > 0) */400401/* If we've removed too much weight, then we have to add it back.402* To avoid overshooting again, we only adjust the smallest rank.403* We take the largest nodes from the lowest rank 0 and move them404* to rank 1. There's guaranteed to be enough rank 0 symbols because405* TODO.406*/407while (totalCost < 0) { /* Sometimes, cost correction overshoot */408/* special case : no rank 1 symbol (using maxNbBits-1);409* let's create one from largest rank 0 (using maxNbBits).410*/411if (rankLast[1] == noSymbol) {412while (huffNode[n].nbBits == maxNbBits) n--;413huffNode[n+1].nbBits--;414assert(n >= 0);415rankLast[1] = (U32)(n+1);416totalCost++;417continue;418}419huffNode[ rankLast[1] + 1 ].nbBits--;420rankLast[1]++;421totalCost ++;422}423} /* repay normalized cost */424} /* there are several too large elements (at least >= 2) */425426return maxNbBits;427}428429typedef struct {430U16 base;431U16 curr;432} rankPos;433434typedef nodeElt huffNodeTable[HUF_CTABLE_WORKSPACE_SIZE_U32];435436/* Number of buckets available for HUF_sort() */437#define RANK_POSITION_TABLE_SIZE 192438439typedef struct {440huffNodeTable huffNodeTbl;441rankPos rankPosition[RANK_POSITION_TABLE_SIZE];442} HUF_buildCTable_wksp_tables;443444/* RANK_POSITION_DISTINCT_COUNT_CUTOFF == Cutoff point in HUF_sort() buckets for which we use log2 bucketing.445* Strategy is to use as many buckets as possible for representing distinct446* counts while using the remainder to represent all "large" counts.447*448* To satisfy this requirement for 192 buckets, we can do the following:449* Let buckets 0-166 represent distinct counts of [0, 166]450* Let buckets 166 to 192 represent all remaining counts up to RANK_POSITION_MAX_COUNT_LOG using log2 bucketing.451*/452#define RANK_POSITION_MAX_COUNT_LOG 32453#define RANK_POSITION_LOG_BUCKETS_BEGIN (RANK_POSITION_TABLE_SIZE - 1) - RANK_POSITION_MAX_COUNT_LOG - 1 /* == 158 */454#define RANK_POSITION_DISTINCT_COUNT_CUTOFF RANK_POSITION_LOG_BUCKETS_BEGIN + BIT_highbit32(RANK_POSITION_LOG_BUCKETS_BEGIN) /* == 166 */455456/* Return the appropriate bucket index for a given count. See definition of457* RANK_POSITION_DISTINCT_COUNT_CUTOFF for explanation of bucketing strategy.458*/459static U32 HUF_getIndex(U32 const count) {460return (count < RANK_POSITION_DISTINCT_COUNT_CUTOFF)461? count462: BIT_highbit32(count) + RANK_POSITION_LOG_BUCKETS_BEGIN;463}464465/* Helper swap function for HUF_quickSortPartition() */466static void HUF_swapNodes(nodeElt* a, nodeElt* b) {467nodeElt tmp = *a;468*a = *b;469*b = tmp;470}471472/* Returns 0 if the huffNode array is not sorted by descending count */473MEM_STATIC int HUF_isSorted(nodeElt huffNode[], U32 const maxSymbolValue1) {474U32 i;475for (i = 1; i < maxSymbolValue1; ++i) {476if (huffNode[i].count > huffNode[i-1].count) {477return 0;478}479}480return 1;481}482483/* Insertion sort by descending order */484HINT_INLINE void HUF_insertionSort(nodeElt huffNode[], int const low, int const high) {485int i;486int const size = high-low+1;487huffNode += low;488for (i = 1; i < size; ++i) {489nodeElt const key = huffNode[i];490int j = i - 1;491while (j >= 0 && huffNode[j].count < key.count) {492huffNode[j + 1] = huffNode[j];493j--;494}495huffNode[j + 1] = key;496}497}498499/* Pivot helper function for quicksort. */500static int HUF_quickSortPartition(nodeElt arr[], int const low, int const high) {501/* Simply select rightmost element as pivot. "Better" selectors like502* median-of-three don't experimentally appear to have any benefit.503*/504U32 const pivot = arr[high].count;505int i = low - 1;506int j = low;507for ( ; j < high; j++) {508if (arr[j].count > pivot) {509i++;510HUF_swapNodes(&arr[i], &arr[j]);511}512}513HUF_swapNodes(&arr[i + 1], &arr[high]);514return i + 1;515}516517/* Classic quicksort by descending with partially iterative calls518* to reduce worst case callstack size.519*/520static void HUF_simpleQuickSort(nodeElt arr[], int low, int high) {521int const kInsertionSortThreshold = 8;522if (high - low < kInsertionSortThreshold) {523HUF_insertionSort(arr, low, high);524return;525}526while (low < high) {527int const idx = HUF_quickSortPartition(arr, low, high);528if (idx - low < high - idx) {529HUF_simpleQuickSort(arr, low, idx - 1);530low = idx + 1;531} else {532HUF_simpleQuickSort(arr, idx + 1, high);533high = idx - 1;534}535}536}537538/**539* HUF_sort():540* Sorts the symbols [0, maxSymbolValue] by count[symbol] in decreasing order.541* This is a typical bucket sorting strategy that uses either quicksort or insertion sort to sort each bucket.542*543* @param[out] huffNode Sorted symbols by decreasing count. Only members `.count` and `.byte` are filled.544* Must have (maxSymbolValue + 1) entries.545* @param[in] count Histogram of the symbols.546* @param[in] maxSymbolValue Maximum symbol value.547* @param rankPosition This is a scratch workspace. Must have RANK_POSITION_TABLE_SIZE entries.548*/549static void HUF_sort(nodeElt huffNode[], const unsigned count[], U32 const maxSymbolValue, rankPos rankPosition[]) {550U32 n;551U32 const maxSymbolValue1 = maxSymbolValue+1;552553/* Compute base and set curr to base.554* For symbol s let lowerRank = HUF_getIndex(count[n]) and rank = lowerRank + 1.555* See HUF_getIndex to see bucketing strategy.556* We attribute each symbol to lowerRank's base value, because we want to know where557* each rank begins in the output, so for rank R we want to count ranks R+1 and above.558*/559ZSTD_memset(rankPosition, 0, sizeof(*rankPosition) * RANK_POSITION_TABLE_SIZE);560for (n = 0; n < maxSymbolValue1; ++n) {561U32 lowerRank = HUF_getIndex(count[n]);562assert(lowerRank < RANK_POSITION_TABLE_SIZE - 1);563rankPosition[lowerRank].base++;564}565566assert(rankPosition[RANK_POSITION_TABLE_SIZE - 1].base == 0);567/* Set up the rankPosition table */568for (n = RANK_POSITION_TABLE_SIZE - 1; n > 0; --n) {569rankPosition[n-1].base += rankPosition[n].base;570rankPosition[n-1].curr = rankPosition[n-1].base;571}572573/* Insert each symbol into their appropriate bucket, setting up rankPosition table. */574for (n = 0; n < maxSymbolValue1; ++n) {575U32 const c = count[n];576U32 const r = HUF_getIndex(c) + 1;577U32 const pos = rankPosition[r].curr++;578assert(pos < maxSymbolValue1);579huffNode[pos].count = c;580huffNode[pos].byte = (BYTE)n;581}582583/* Sort each bucket. */584for (n = RANK_POSITION_DISTINCT_COUNT_CUTOFF; n < RANK_POSITION_TABLE_SIZE - 1; ++n) {585U32 const bucketSize = rankPosition[n].curr-rankPosition[n].base;586U32 const bucketStartIdx = rankPosition[n].base;587if (bucketSize > 1) {588assert(bucketStartIdx < maxSymbolValue1);589HUF_simpleQuickSort(huffNode + bucketStartIdx, 0, bucketSize-1);590}591}592593assert(HUF_isSorted(huffNode, maxSymbolValue1));594}595596/** HUF_buildCTable_wksp() :597* Same as HUF_buildCTable(), but using externally allocated scratch buffer.598* `workSpace` must be aligned on 4-bytes boundaries, and be at least as large as sizeof(HUF_buildCTable_wksp_tables).599*/600#define STARTNODE (HUF_SYMBOLVALUE_MAX+1)601602/* HUF_buildTree():603* Takes the huffNode array sorted by HUF_sort() and builds an unlimited-depth Huffman tree.604*605* @param huffNode The array sorted by HUF_sort(). Builds the Huffman tree in this array.606* @param maxSymbolValue The maximum symbol value.607* @return The smallest node in the Huffman tree (by count).608*/609static int HUF_buildTree(nodeElt* huffNode, U32 maxSymbolValue)610{611nodeElt* const huffNode0 = huffNode - 1;612int nonNullRank;613int lowS, lowN;614int nodeNb = STARTNODE;615int n, nodeRoot;616/* init for parents */617nonNullRank = (int)maxSymbolValue;618while(huffNode[nonNullRank].count == 0) nonNullRank--;619lowS = nonNullRank; nodeRoot = nodeNb + lowS - 1; lowN = nodeNb;620huffNode[nodeNb].count = huffNode[lowS].count + huffNode[lowS-1].count;621huffNode[lowS].parent = huffNode[lowS-1].parent = (U16)nodeNb;622nodeNb++; lowS-=2;623for (n=nodeNb; n<=nodeRoot; n++) huffNode[n].count = (U32)(1U<<30);624huffNode0[0].count = (U32)(1U<<31); /* fake entry, strong barrier */625626/* create parents */627while (nodeNb <= nodeRoot) {628int const n1 = (huffNode[lowS].count < huffNode[lowN].count) ? lowS-- : lowN++;629int const n2 = (huffNode[lowS].count < huffNode[lowN].count) ? lowS-- : lowN++;630huffNode[nodeNb].count = huffNode[n1].count + huffNode[n2].count;631huffNode[n1].parent = huffNode[n2].parent = (U16)nodeNb;632nodeNb++;633}634635/* distribute weights (unlimited tree height) */636huffNode[nodeRoot].nbBits = 0;637for (n=nodeRoot-1; n>=STARTNODE; n--)638huffNode[n].nbBits = huffNode[ huffNode[n].parent ].nbBits + 1;639for (n=0; n<=nonNullRank; n++)640huffNode[n].nbBits = huffNode[ huffNode[n].parent ].nbBits + 1;641642return nonNullRank;643}644645/**646* HUF_buildCTableFromTree():647* Build the CTable given the Huffman tree in huffNode.648*649* @param[out] CTable The output Huffman CTable.650* @param huffNode The Huffman tree.651* @param nonNullRank The last and smallest node in the Huffman tree.652* @param maxSymbolValue The maximum symbol value.653* @param maxNbBits The exact maximum number of bits used in the Huffman tree.654*/655static void HUF_buildCTableFromTree(HUF_CElt* CTable, nodeElt const* huffNode, int nonNullRank, U32 maxSymbolValue, U32 maxNbBits)656{657HUF_CElt* const ct = CTable + 1;658/* fill result into ctable (val, nbBits) */659int n;660U16 nbPerRank[HUF_TABLELOG_MAX+1] = {0};661U16 valPerRank[HUF_TABLELOG_MAX+1] = {0};662int const alphabetSize = (int)(maxSymbolValue + 1);663for (n=0; n<=nonNullRank; n++)664nbPerRank[huffNode[n].nbBits]++;665/* determine starting value per rank */666{ U16 min = 0;667for (n=(int)maxNbBits; n>0; n--) {668valPerRank[n] = min; /* get starting value within each rank */669min += nbPerRank[n];670min >>= 1;671} }672for (n=0; n<alphabetSize; n++)673HUF_setNbBits(ct + huffNode[n].byte, huffNode[n].nbBits); /* push nbBits per symbol, symbol order */674for (n=0; n<alphabetSize; n++)675HUF_setValue(ct + n, valPerRank[HUF_getNbBits(ct[n])]++); /* assign value within rank, symbol order */676CTable[0] = maxNbBits;677}678679size_t HUF_buildCTable_wksp (HUF_CElt* CTable, const unsigned* count, U32 maxSymbolValue, U32 maxNbBits, void* workSpace, size_t wkspSize)680{681HUF_buildCTable_wksp_tables* const wksp_tables = (HUF_buildCTable_wksp_tables*)HUF_alignUpWorkspace(workSpace, &wkspSize, ZSTD_ALIGNOF(U32));682nodeElt* const huffNode0 = wksp_tables->huffNodeTbl;683nodeElt* const huffNode = huffNode0+1;684int nonNullRank;685686/* safety checks */687if (wkspSize < sizeof(HUF_buildCTable_wksp_tables))688return ERROR(workSpace_tooSmall);689if (maxNbBits == 0) maxNbBits = HUF_TABLELOG_DEFAULT;690if (maxSymbolValue > HUF_SYMBOLVALUE_MAX)691return ERROR(maxSymbolValue_tooLarge);692ZSTD_memset(huffNode0, 0, sizeof(huffNodeTable));693694/* sort, decreasing order */695HUF_sort(huffNode, count, maxSymbolValue, wksp_tables->rankPosition);696697/* build tree */698nonNullRank = HUF_buildTree(huffNode, maxSymbolValue);699700/* enforce maxTableLog */701maxNbBits = HUF_setMaxHeight(huffNode, (U32)nonNullRank, maxNbBits);702if (maxNbBits > HUF_TABLELOG_MAX) return ERROR(GENERIC); /* check fit into table */703704HUF_buildCTableFromTree(CTable, huffNode, nonNullRank, maxSymbolValue, maxNbBits);705706return maxNbBits;707}708709size_t HUF_estimateCompressedSize(const HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue)710{711HUF_CElt const* ct = CTable + 1;712size_t nbBits = 0;713int s;714for (s = 0; s <= (int)maxSymbolValue; ++s) {715nbBits += HUF_getNbBits(ct[s]) * count[s];716}717return nbBits >> 3;718}719720int HUF_validateCTable(const HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue) {721HUF_CElt const* ct = CTable + 1;722int bad = 0;723int s;724for (s = 0; s <= (int)maxSymbolValue; ++s) {725bad |= (count[s] != 0) & (HUF_getNbBits(ct[s]) == 0);726}727return !bad;728}729730size_t HUF_compressBound(size_t size) { return HUF_COMPRESSBOUND(size); }731732/** HUF_CStream_t:733* Huffman uses its own BIT_CStream_t implementation.734* There are three major differences from BIT_CStream_t:735* 1. HUF_addBits() takes a HUF_CElt (size_t) which is736* the pair (nbBits, value) in the format:737* format:738* - Bits [0, 4) = nbBits739* - Bits [4, 64 - nbBits) = 0740* - Bits [64 - nbBits, 64) = value741* 2. The bitContainer is built from the upper bits and742* right shifted. E.g. to add a new value of N bits743* you right shift the bitContainer by N, then or in744* the new value into the N upper bits.745* 3. The bitstream has two bit containers. You can add746* bits to the second container and merge them into747* the first container.748*/749750#define HUF_BITS_IN_CONTAINER (sizeof(size_t) * 8)751752typedef struct {753size_t bitContainer[2];754size_t bitPos[2];755756BYTE* startPtr;757BYTE* ptr;758BYTE* endPtr;759} HUF_CStream_t;760761/**! HUF_initCStream():762* Initializes the bitstream.763* @returns 0 or an error code.764*/765static size_t HUF_initCStream(HUF_CStream_t* bitC,766void* startPtr, size_t dstCapacity)767{768ZSTD_memset(bitC, 0, sizeof(*bitC));769bitC->startPtr = (BYTE*)startPtr;770bitC->ptr = bitC->startPtr;771bitC->endPtr = bitC->startPtr + dstCapacity - sizeof(bitC->bitContainer[0]);772if (dstCapacity <= sizeof(bitC->bitContainer[0])) return ERROR(dstSize_tooSmall);773return 0;774}775776/*! HUF_addBits():777* Adds the symbol stored in HUF_CElt elt to the bitstream.778*779* @param elt The element we're adding. This is a (nbBits, value) pair.780* See the HUF_CStream_t docs for the format.781* @param idx Insert into the bitstream at this idx.782* @param kFast This is a template parameter. If the bitstream is guaranteed783* to have at least 4 unused bits after this call it may be 1,784* otherwise it must be 0. HUF_addBits() is faster when fast is set.785*/786FORCE_INLINE_TEMPLATE void HUF_addBits(HUF_CStream_t* bitC, HUF_CElt elt, int idx, int kFast)787{788assert(idx <= 1);789assert(HUF_getNbBits(elt) <= HUF_TABLELOG_ABSOLUTEMAX);790/* This is efficient on x86-64 with BMI2 because shrx791* only reads the low 6 bits of the register. The compiler792* knows this and elides the mask. When fast is set,793* every operation can use the same value loaded from elt.794*/795bitC->bitContainer[idx] >>= HUF_getNbBits(elt);796bitC->bitContainer[idx] |= kFast ? HUF_getValueFast(elt) : HUF_getValue(elt);797/* We only read the low 8 bits of bitC->bitPos[idx] so it798* doesn't matter that the high bits have noise from the value.799*/800bitC->bitPos[idx] += HUF_getNbBitsFast(elt);801assert((bitC->bitPos[idx] & 0xFF) <= HUF_BITS_IN_CONTAINER);802/* The last 4-bits of elt are dirty if fast is set,803* so we must not be overwriting bits that have already been804* inserted into the bit container.805*/806#if DEBUGLEVEL >= 1807{808size_t const nbBits = HUF_getNbBits(elt);809size_t const dirtyBits = nbBits == 0 ? 0 : BIT_highbit32((U32)nbBits) + 1;810(void)dirtyBits;811/* Middle bits are 0. */812assert(((elt >> dirtyBits) << (dirtyBits + nbBits)) == 0);813/* We didn't overwrite any bits in the bit container. */814assert(!kFast || (bitC->bitPos[idx] & 0xFF) <= HUF_BITS_IN_CONTAINER);815(void)dirtyBits;816}817#endif818}819820FORCE_INLINE_TEMPLATE void HUF_zeroIndex1(HUF_CStream_t* bitC)821{822bitC->bitContainer[1] = 0;823bitC->bitPos[1] = 0;824}825826/*! HUF_mergeIndex1() :827* Merges the bit container @ index 1 into the bit container @ index 0828* and zeros the bit container @ index 1.829*/830FORCE_INLINE_TEMPLATE void HUF_mergeIndex1(HUF_CStream_t* bitC)831{832assert((bitC->bitPos[1] & 0xFF) < HUF_BITS_IN_CONTAINER);833bitC->bitContainer[0] >>= (bitC->bitPos[1] & 0xFF);834bitC->bitContainer[0] |= bitC->bitContainer[1];835bitC->bitPos[0] += bitC->bitPos[1];836assert((bitC->bitPos[0] & 0xFF) <= HUF_BITS_IN_CONTAINER);837}838839/*! HUF_flushBits() :840* Flushes the bits in the bit container @ index 0.841*842* @post bitPos will be < 8.843* @param kFast If kFast is set then we must know a-priori that844* the bit container will not overflow.845*/846FORCE_INLINE_TEMPLATE void HUF_flushBits(HUF_CStream_t* bitC, int kFast)847{848/* The upper bits of bitPos are noisy, so we must mask by 0xFF. */849size_t const nbBits = bitC->bitPos[0] & 0xFF;850size_t const nbBytes = nbBits >> 3;851/* The top nbBits bits of bitContainer are the ones we need. */852size_t const bitContainer = bitC->bitContainer[0] >> (HUF_BITS_IN_CONTAINER - nbBits);853/* Mask bitPos to account for the bytes we consumed. */854bitC->bitPos[0] &= 7;855assert(nbBits > 0);856assert(nbBits <= sizeof(bitC->bitContainer[0]) * 8);857assert(bitC->ptr <= bitC->endPtr);858MEM_writeLEST(bitC->ptr, bitContainer);859bitC->ptr += nbBytes;860assert(!kFast || bitC->ptr <= bitC->endPtr);861if (!kFast && bitC->ptr > bitC->endPtr) bitC->ptr = bitC->endPtr;862/* bitContainer doesn't need to be modified because the leftover863* bits are already the top bitPos bits. And we don't care about864* noise in the lower values.865*/866}867868/*! HUF_endMark()869* @returns The Huffman stream end mark: A 1-bit value = 1.870*/871static HUF_CElt HUF_endMark(void)872{873HUF_CElt endMark;874HUF_setNbBits(&endMark, 1);875HUF_setValue(&endMark, 1);876return endMark;877}878879/*! HUF_closeCStream() :880* @return Size of CStream, in bytes,881* or 0 if it could not fit into dstBuffer */882static size_t HUF_closeCStream(HUF_CStream_t* bitC)883{884HUF_addBits(bitC, HUF_endMark(), /* idx */ 0, /* kFast */ 0);885HUF_flushBits(bitC, /* kFast */ 0);886{887size_t const nbBits = bitC->bitPos[0] & 0xFF;888if (bitC->ptr >= bitC->endPtr) return 0; /* overflow detected */889return (bitC->ptr - bitC->startPtr) + (nbBits > 0);890}891}892893FORCE_INLINE_TEMPLATE void894HUF_encodeSymbol(HUF_CStream_t* bitCPtr, U32 symbol, const HUF_CElt* CTable, int idx, int fast)895{896HUF_addBits(bitCPtr, CTable[symbol], idx, fast);897}898899FORCE_INLINE_TEMPLATE void900HUF_compress1X_usingCTable_internal_body_loop(HUF_CStream_t* bitC,901const BYTE* ip, size_t srcSize,902const HUF_CElt* ct,903int kUnroll, int kFastFlush, int kLastFast)904{905/* Join to kUnroll */906int n = (int)srcSize;907int rem = n % kUnroll;908if (rem > 0) {909for (; rem > 0; --rem) {910HUF_encodeSymbol(bitC, ip[--n], ct, 0, /* fast */ 0);911}912HUF_flushBits(bitC, kFastFlush);913}914assert(n % kUnroll == 0);915916/* Join to 2 * kUnroll */917if (n % (2 * kUnroll)) {918int u;919for (u = 1; u < kUnroll; ++u) {920HUF_encodeSymbol(bitC, ip[n - u], ct, 0, 1);921}922HUF_encodeSymbol(bitC, ip[n - kUnroll], ct, 0, kLastFast);923HUF_flushBits(bitC, kFastFlush);924n -= kUnroll;925}926assert(n % (2 * kUnroll) == 0);927928for (; n>0; n-= 2 * kUnroll) {929/* Encode kUnroll symbols into the bitstream @ index 0. */930int u;931for (u = 1; u < kUnroll; ++u) {932HUF_encodeSymbol(bitC, ip[n - u], ct, /* idx */ 0, /* fast */ 1);933}934HUF_encodeSymbol(bitC, ip[n - kUnroll], ct, /* idx */ 0, /* fast */ kLastFast);935HUF_flushBits(bitC, kFastFlush);936/* Encode kUnroll symbols into the bitstream @ index 1.937* This allows us to start filling the bit container938* without any data dependencies.939*/940HUF_zeroIndex1(bitC);941for (u = 1; u < kUnroll; ++u) {942HUF_encodeSymbol(bitC, ip[n - kUnroll - u], ct, /* idx */ 1, /* fast */ 1);943}944HUF_encodeSymbol(bitC, ip[n - kUnroll - kUnroll], ct, /* idx */ 1, /* fast */ kLastFast);945/* Merge bitstream @ index 1 into the bitstream @ index 0 */946HUF_mergeIndex1(bitC);947HUF_flushBits(bitC, kFastFlush);948}949assert(n == 0);950951}952953/**954* Returns a tight upper bound on the output space needed by Huffman955* with 8 bytes buffer to handle over-writes. If the output is at least956* this large we don't need to do bounds checks during Huffman encoding.957*/958static size_t HUF_tightCompressBound(size_t srcSize, size_t tableLog)959{960return ((srcSize * tableLog) >> 3) + 8;961}962963964FORCE_INLINE_TEMPLATE size_t965HUF_compress1X_usingCTable_internal_body(void* dst, size_t dstSize,966const void* src, size_t srcSize,967const HUF_CElt* CTable)968{969U32 const tableLog = (U32)CTable[0];970HUF_CElt const* ct = CTable + 1;971const BYTE* ip = (const BYTE*) src;972BYTE* const ostart = (BYTE*)dst;973BYTE* const oend = ostart + dstSize;974BYTE* op = ostart;975HUF_CStream_t bitC;976977/* init */978if (dstSize < 8) return 0; /* not enough space to compress */979{ size_t const initErr = HUF_initCStream(&bitC, op, (size_t)(oend-op));980if (HUF_isError(initErr)) return 0; }981982if (dstSize < HUF_tightCompressBound(srcSize, (size_t)tableLog) || tableLog > 11)983HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ MEM_32bits() ? 2 : 4, /* kFast */ 0, /* kLastFast */ 0);984else {985if (MEM_32bits()) {986switch (tableLog) {987case 11:988HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 2, /* kFastFlush */ 1, /* kLastFast */ 0);989break;990case 10: ZSTD_FALLTHROUGH;991case 9: ZSTD_FALLTHROUGH;992case 8:993HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 2, /* kFastFlush */ 1, /* kLastFast */ 1);994break;995case 7: ZSTD_FALLTHROUGH;996default:997HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 3, /* kFastFlush */ 1, /* kLastFast */ 1);998break;999}1000} else {1001switch (tableLog) {1002case 11:1003HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 5, /* kFastFlush */ 1, /* kLastFast */ 0);1004break;1005case 10:1006HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 5, /* kFastFlush */ 1, /* kLastFast */ 1);1007break;1008case 9:1009HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 6, /* kFastFlush */ 1, /* kLastFast */ 0);1010break;1011case 8:1012HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 7, /* kFastFlush */ 1, /* kLastFast */ 0);1013break;1014case 7:1015HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 8, /* kFastFlush */ 1, /* kLastFast */ 0);1016break;1017case 6: ZSTD_FALLTHROUGH;1018default:1019HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 9, /* kFastFlush */ 1, /* kLastFast */ 1);1020break;1021}1022}1023}1024assert(bitC.ptr <= bitC.endPtr);10251026return HUF_closeCStream(&bitC);1027}10281029#if DYNAMIC_BMI210301031static BMI2_TARGET_ATTRIBUTE size_t1032HUF_compress1X_usingCTable_internal_bmi2(void* dst, size_t dstSize,1033const void* src, size_t srcSize,1034const HUF_CElt* CTable)1035{1036return HUF_compress1X_usingCTable_internal_body(dst, dstSize, src, srcSize, CTable);1037}10381039static size_t1040HUF_compress1X_usingCTable_internal_default(void* dst, size_t dstSize,1041const void* src, size_t srcSize,1042const HUF_CElt* CTable)1043{1044return HUF_compress1X_usingCTable_internal_body(dst, dstSize, src, srcSize, CTable);1045}10461047static size_t1048HUF_compress1X_usingCTable_internal(void* dst, size_t dstSize,1049const void* src, size_t srcSize,1050const HUF_CElt* CTable, const int bmi2)1051{1052if (bmi2) {1053return HUF_compress1X_usingCTable_internal_bmi2(dst, dstSize, src, srcSize, CTable);1054}1055return HUF_compress1X_usingCTable_internal_default(dst, dstSize, src, srcSize, CTable);1056}10571058#else10591060static size_t1061HUF_compress1X_usingCTable_internal(void* dst, size_t dstSize,1062const void* src, size_t srcSize,1063const HUF_CElt* CTable, const int bmi2)1064{1065(void)bmi2;1066return HUF_compress1X_usingCTable_internal_body(dst, dstSize, src, srcSize, CTable);1067}10681069#endif10701071size_t HUF_compress1X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable)1072{1073return HUF_compress1X_usingCTable_bmi2(dst, dstSize, src, srcSize, CTable, /* bmi2 */ 0);1074}10751076size_t HUF_compress1X_usingCTable_bmi2(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable, int bmi2)1077{1078return HUF_compress1X_usingCTable_internal(dst, dstSize, src, srcSize, CTable, bmi2);1079}10801081static size_t1082HUF_compress4X_usingCTable_internal(void* dst, size_t dstSize,1083const void* src, size_t srcSize,1084const HUF_CElt* CTable, int bmi2)1085{1086size_t const segmentSize = (srcSize+3)/4; /* first 3 segments */1087const BYTE* ip = (const BYTE*) src;1088const BYTE* const iend = ip + srcSize;1089BYTE* const ostart = (BYTE*) dst;1090BYTE* const oend = ostart + dstSize;1091BYTE* op = ostart;10921093if (dstSize < 6 + 1 + 1 + 1 + 8) return 0; /* minimum space to compress successfully */1094if (srcSize < 12) return 0; /* no saving possible : too small input */1095op += 6; /* jumpTable */10961097assert(op <= oend);1098{ CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, (size_t)(oend-op), ip, segmentSize, CTable, bmi2) );1099if (cSize == 0 || cSize > 65535) return 0;1100MEM_writeLE16(ostart, (U16)cSize);1101op += cSize;1102}11031104ip += segmentSize;1105assert(op <= oend);1106{ CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, (size_t)(oend-op), ip, segmentSize, CTable, bmi2) );1107if (cSize == 0 || cSize > 65535) return 0;1108MEM_writeLE16(ostart+2, (U16)cSize);1109op += cSize;1110}11111112ip += segmentSize;1113assert(op <= oend);1114{ CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, (size_t)(oend-op), ip, segmentSize, CTable, bmi2) );1115if (cSize == 0 || cSize > 65535) return 0;1116MEM_writeLE16(ostart+4, (U16)cSize);1117op += cSize;1118}11191120ip += segmentSize;1121assert(op <= oend);1122assert(ip <= iend);1123{ CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, (size_t)(oend-op), ip, (size_t)(iend-ip), CTable, bmi2) );1124if (cSize == 0 || cSize > 65535) return 0;1125op += cSize;1126}11271128return (size_t)(op-ostart);1129}11301131size_t HUF_compress4X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable)1132{1133return HUF_compress4X_usingCTable_bmi2(dst, dstSize, src, srcSize, CTable, /* bmi2 */ 0);1134}11351136size_t HUF_compress4X_usingCTable_bmi2(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable, int bmi2)1137{1138return HUF_compress4X_usingCTable_internal(dst, dstSize, src, srcSize, CTable, bmi2);1139}11401141typedef enum { HUF_singleStream, HUF_fourStreams } HUF_nbStreams_e;11421143static size_t HUF_compressCTable_internal(1144BYTE* const ostart, BYTE* op, BYTE* const oend,1145const void* src, size_t srcSize,1146HUF_nbStreams_e nbStreams, const HUF_CElt* CTable, const int bmi2)1147{1148size_t const cSize = (nbStreams==HUF_singleStream) ?1149HUF_compress1X_usingCTable_internal(op, (size_t)(oend - op), src, srcSize, CTable, bmi2) :1150HUF_compress4X_usingCTable_internal(op, (size_t)(oend - op), src, srcSize, CTable, bmi2);1151if (HUF_isError(cSize)) { return cSize; }1152if (cSize==0) { return 0; } /* uncompressible */1153op += cSize;1154/* check compressibility */1155assert(op >= ostart);1156if ((size_t)(op-ostart) >= srcSize-1) { return 0; }1157return (size_t)(op-ostart);1158}11591160typedef struct {1161unsigned count[HUF_SYMBOLVALUE_MAX + 1];1162HUF_CElt CTable[HUF_CTABLE_SIZE_ST(HUF_SYMBOLVALUE_MAX)];1163union {1164HUF_buildCTable_wksp_tables buildCTable_wksp;1165HUF_WriteCTableWksp writeCTable_wksp;1166U32 hist_wksp[HIST_WKSP_SIZE_U32];1167} wksps;1168} HUF_compress_tables_t;11691170#define SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE 40961171#define SUSPECT_INCOMPRESSIBLE_SAMPLE_RATIO 10 /* Must be >= 2 */11721173/* HUF_compress_internal() :1174* `workSpace_align4` must be aligned on 4-bytes boundaries,1175* and occupies the same space as a table of HUF_WORKSPACE_SIZE_U64 unsigned */1176static size_t1177HUF_compress_internal (void* dst, size_t dstSize,1178const void* src, size_t srcSize,1179unsigned maxSymbolValue, unsigned huffLog,1180HUF_nbStreams_e nbStreams,1181void* workSpace, size_t wkspSize,1182HUF_CElt* oldHufTable, HUF_repeat* repeat, int preferRepeat,1183const int bmi2, unsigned suspectUncompressible)1184{1185HUF_compress_tables_t* const table = (HUF_compress_tables_t*)HUF_alignUpWorkspace(workSpace, &wkspSize, ZSTD_ALIGNOF(size_t));1186BYTE* const ostart = (BYTE*)dst;1187BYTE* const oend = ostart + dstSize;1188BYTE* op = ostart;11891190HUF_STATIC_ASSERT(sizeof(*table) + HUF_WORKSPACE_MAX_ALIGNMENT <= HUF_WORKSPACE_SIZE);11911192/* checks & inits */1193if (wkspSize < sizeof(*table)) return ERROR(workSpace_tooSmall);1194if (!srcSize) return 0; /* Uncompressed */1195if (!dstSize) return 0; /* cannot fit anything within dst budget */1196if (srcSize > HUF_BLOCKSIZE_MAX) return ERROR(srcSize_wrong); /* current block size limit */1197if (huffLog > HUF_TABLELOG_MAX) return ERROR(tableLog_tooLarge);1198if (maxSymbolValue > HUF_SYMBOLVALUE_MAX) return ERROR(maxSymbolValue_tooLarge);1199if (!maxSymbolValue) maxSymbolValue = HUF_SYMBOLVALUE_MAX;1200if (!huffLog) huffLog = HUF_TABLELOG_DEFAULT;12011202/* Heuristic : If old table is valid, use it for small inputs */1203if (preferRepeat && repeat && *repeat == HUF_repeat_valid) {1204return HUF_compressCTable_internal(ostart, op, oend,1205src, srcSize,1206nbStreams, oldHufTable, bmi2);1207}12081209/* If uncompressible data is suspected, do a smaller sampling first */1210DEBUG_STATIC_ASSERT(SUSPECT_INCOMPRESSIBLE_SAMPLE_RATIO >= 2);1211if (suspectUncompressible && srcSize >= (SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE * SUSPECT_INCOMPRESSIBLE_SAMPLE_RATIO)) {1212size_t largestTotal = 0;1213{ unsigned maxSymbolValueBegin = maxSymbolValue;1214CHECK_V_F(largestBegin, HIST_count_simple (table->count, &maxSymbolValueBegin, (const BYTE*)src, SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE) );1215largestTotal += largestBegin;1216}1217{ unsigned maxSymbolValueEnd = maxSymbolValue;1218CHECK_V_F(largestEnd, HIST_count_simple (table->count, &maxSymbolValueEnd, (const BYTE*)src + srcSize - SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE, SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE) );1219largestTotal += largestEnd;1220}1221if (largestTotal <= ((2 * SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE) >> 7)+4) return 0; /* heuristic : probably not compressible enough */1222}12231224/* Scan input and build symbol stats */1225{ CHECK_V_F(largest, HIST_count_wksp (table->count, &maxSymbolValue, (const BYTE*)src, srcSize, table->wksps.hist_wksp, sizeof(table->wksps.hist_wksp)) );1226if (largest == srcSize) { *ostart = ((const BYTE*)src)[0]; return 1; } /* single symbol, rle */1227if (largest <= (srcSize >> 7)+4) return 0; /* heuristic : probably not compressible enough */1228}12291230/* Check validity of previous table */1231if ( repeat1232&& *repeat == HUF_repeat_check1233&& !HUF_validateCTable(oldHufTable, table->count, maxSymbolValue)) {1234*repeat = HUF_repeat_none;1235}1236/* Heuristic : use existing table for small inputs */1237if (preferRepeat && repeat && *repeat != HUF_repeat_none) {1238return HUF_compressCTable_internal(ostart, op, oend,1239src, srcSize,1240nbStreams, oldHufTable, bmi2);1241}12421243/* Build Huffman Tree */1244huffLog = HUF_optimalTableLog(huffLog, srcSize, maxSymbolValue);1245{ size_t const maxBits = HUF_buildCTable_wksp(table->CTable, table->count,1246maxSymbolValue, huffLog,1247&table->wksps.buildCTable_wksp, sizeof(table->wksps.buildCTable_wksp));1248CHECK_F(maxBits);1249huffLog = (U32)maxBits;1250}1251/* Zero unused symbols in CTable, so we can check it for validity */1252{1253size_t const ctableSize = HUF_CTABLE_SIZE_ST(maxSymbolValue);1254size_t const unusedSize = sizeof(table->CTable) - ctableSize * sizeof(HUF_CElt);1255ZSTD_memset(table->CTable + ctableSize, 0, unusedSize);1256}12571258/* Write table description header */1259{ CHECK_V_F(hSize, HUF_writeCTable_wksp(op, dstSize, table->CTable, maxSymbolValue, huffLog,1260&table->wksps.writeCTable_wksp, sizeof(table->wksps.writeCTable_wksp)) );1261/* Check if using previous huffman table is beneficial */1262if (repeat && *repeat != HUF_repeat_none) {1263size_t const oldSize = HUF_estimateCompressedSize(oldHufTable, table->count, maxSymbolValue);1264size_t const newSize = HUF_estimateCompressedSize(table->CTable, table->count, maxSymbolValue);1265if (oldSize <= hSize + newSize || hSize + 12 >= srcSize) {1266return HUF_compressCTable_internal(ostart, op, oend,1267src, srcSize,1268nbStreams, oldHufTable, bmi2);1269} }12701271/* Use the new huffman table */1272if (hSize + 12ul >= srcSize) { return 0; }1273op += hSize;1274if (repeat) { *repeat = HUF_repeat_none; }1275if (oldHufTable)1276ZSTD_memcpy(oldHufTable, table->CTable, sizeof(table->CTable)); /* Save new table */1277}1278return HUF_compressCTable_internal(ostart, op, oend,1279src, srcSize,1280nbStreams, table->CTable, bmi2);1281}128212831284size_t HUF_compress1X_wksp (void* dst, size_t dstSize,1285const void* src, size_t srcSize,1286unsigned maxSymbolValue, unsigned huffLog,1287void* workSpace, size_t wkspSize)1288{1289return HUF_compress_internal(dst, dstSize, src, srcSize,1290maxSymbolValue, huffLog, HUF_singleStream,1291workSpace, wkspSize,1292NULL, NULL, 0, 0 /*bmi2*/, 0);1293}12941295size_t HUF_compress1X_repeat (void* dst, size_t dstSize,1296const void* src, size_t srcSize,1297unsigned maxSymbolValue, unsigned huffLog,1298void* workSpace, size_t wkspSize,1299HUF_CElt* hufTable, HUF_repeat* repeat, int preferRepeat,1300int bmi2, unsigned suspectUncompressible)1301{1302return HUF_compress_internal(dst, dstSize, src, srcSize,1303maxSymbolValue, huffLog, HUF_singleStream,1304workSpace, wkspSize, hufTable,1305repeat, preferRepeat, bmi2, suspectUncompressible);1306}13071308/* HUF_compress4X_repeat():1309* compress input using 4 streams.1310* provide workspace to generate compression tables */1311size_t HUF_compress4X_wksp (void* dst, size_t dstSize,1312const void* src, size_t srcSize,1313unsigned maxSymbolValue, unsigned huffLog,1314void* workSpace, size_t wkspSize)1315{1316return HUF_compress_internal(dst, dstSize, src, srcSize,1317maxSymbolValue, huffLog, HUF_fourStreams,1318workSpace, wkspSize,1319NULL, NULL, 0, 0 /*bmi2*/, 0);1320}13211322/* HUF_compress4X_repeat():1323* compress input using 4 streams.1324* consider skipping quickly1325* re-use an existing huffman compression table */1326size_t HUF_compress4X_repeat (void* dst, size_t dstSize,1327const void* src, size_t srcSize,1328unsigned maxSymbolValue, unsigned huffLog,1329void* workSpace, size_t wkspSize,1330HUF_CElt* hufTable, HUF_repeat* repeat, int preferRepeat, int bmi2, unsigned suspectUncompressible)1331{1332return HUF_compress_internal(dst, dstSize, src, srcSize,1333maxSymbolValue, huffLog, HUF_fourStreams,1334workSpace, wkspSize,1335hufTable, repeat, preferRepeat, bmi2, suspectUncompressible);1336}13371338#ifndef ZSTD_NO_UNUSED_FUNCTIONS1339/** HUF_buildCTable() :1340* @return : maxNbBits1341* Note : count is used before tree is written, so they can safely overlap1342*/1343size_t HUF_buildCTable (HUF_CElt* tree, const unsigned* count, unsigned maxSymbolValue, unsigned maxNbBits)1344{1345HUF_buildCTable_wksp_tables workspace;1346return HUF_buildCTable_wksp(tree, count, maxSymbolValue, maxNbBits, &workspace, sizeof(workspace));1347}13481349size_t HUF_compress1X (void* dst, size_t dstSize,1350const void* src, size_t srcSize,1351unsigned maxSymbolValue, unsigned huffLog)1352{1353U64 workSpace[HUF_WORKSPACE_SIZE_U64];1354return HUF_compress1X_wksp(dst, dstSize, src, srcSize, maxSymbolValue, huffLog, workSpace, sizeof(workSpace));1355}13561357size_t HUF_compress2 (void* dst, size_t dstSize,1358const void* src, size_t srcSize,1359unsigned maxSymbolValue, unsigned huffLog)1360{1361U64 workSpace[HUF_WORKSPACE_SIZE_U64];1362return HUF_compress4X_wksp(dst, dstSize, src, srcSize, maxSymbolValue, huffLog, workSpace, sizeof(workSpace));1363}13641365size_t HUF_compress (void* dst, size_t maxDstSize, const void* src, size_t srcSize)1366{1367return HUF_compress2(dst, maxDstSize, src, srcSize, 255, HUF_TABLELOG_DEFAULT);1368}1369#endif137013711372