1*01826a49SYabin Cui /* ******************************************************************
2*01826a49SYabin Cui * Huffman encoder, part of New Generation Entropy library
3*01826a49SYabin Cui * Copyright (c) Meta Platforms, Inc. and affiliates.
4*01826a49SYabin Cui *
5*01826a49SYabin Cui * You can contact the author at :
6*01826a49SYabin Cui * - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy
7*01826a49SYabin Cui * - Public forum : https://groups.google.com/forum/#!forum/lz4c
8*01826a49SYabin Cui *
9*01826a49SYabin Cui * This source code is licensed under both the BSD-style license (found in the
10*01826a49SYabin Cui * LICENSE file in the root directory of this source tree) and the GPLv2 (found
11*01826a49SYabin Cui * in the COPYING file in the root directory of this source tree).
12*01826a49SYabin Cui * You may select, at your option, one of the above-listed licenses.
13*01826a49SYabin Cui ****************************************************************** */
14*01826a49SYabin Cui
15*01826a49SYabin Cui /* **************************************************************
16*01826a49SYabin Cui * Compiler specifics
17*01826a49SYabin Cui ****************************************************************/
18*01826a49SYabin Cui #ifdef _MSC_VER /* Visual Studio */
19*01826a49SYabin Cui # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
20*01826a49SYabin Cui #endif
21*01826a49SYabin Cui
22*01826a49SYabin Cui
23*01826a49SYabin Cui /* **************************************************************
24*01826a49SYabin Cui * Includes
25*01826a49SYabin Cui ****************************************************************/
26*01826a49SYabin Cui #include "../common/zstd_deps.h" /* ZSTD_memcpy, ZSTD_memset */
27*01826a49SYabin Cui #include "../common/compiler.h"
28*01826a49SYabin Cui #include "../common/bitstream.h"
29*01826a49SYabin Cui #include "hist.h"
30*01826a49SYabin Cui #define FSE_STATIC_LINKING_ONLY /* FSE_optimalTableLog_internal */
31*01826a49SYabin Cui #include "../common/fse.h" /* header compression */
32*01826a49SYabin Cui #include "../common/huf.h"
33*01826a49SYabin Cui #include "../common/error_private.h"
34*01826a49SYabin Cui #include "../common/bits.h" /* ZSTD_highbit32 */
35*01826a49SYabin Cui
36*01826a49SYabin Cui
37*01826a49SYabin Cui /* **************************************************************
38*01826a49SYabin Cui * Error Management
39*01826a49SYabin Cui ****************************************************************/
40*01826a49SYabin Cui #define HUF_isError ERR_isError
41*01826a49SYabin Cui #define HUF_STATIC_ASSERT(c) DEBUG_STATIC_ASSERT(c) /* use only *after* variable declarations */
42*01826a49SYabin Cui
43*01826a49SYabin Cui
44*01826a49SYabin Cui /* **************************************************************
45*01826a49SYabin Cui * Required declarations
46*01826a49SYabin Cui ****************************************************************/
47*01826a49SYabin Cui typedef struct nodeElt_s {
48*01826a49SYabin Cui U32 count;
49*01826a49SYabin Cui U16 parent;
50*01826a49SYabin Cui BYTE byte;
51*01826a49SYabin Cui BYTE nbBits;
52*01826a49SYabin Cui } nodeElt;
53*01826a49SYabin Cui
54*01826a49SYabin Cui
55*01826a49SYabin Cui /* **************************************************************
56*01826a49SYabin Cui * Debug Traces
57*01826a49SYabin Cui ****************************************************************/
58*01826a49SYabin Cui
59*01826a49SYabin Cui #if DEBUGLEVEL >= 2
60*01826a49SYabin Cui
showU32(const U32 * arr,size_t size)61*01826a49SYabin Cui static size_t showU32(const U32* arr, size_t size)
62*01826a49SYabin Cui {
63*01826a49SYabin Cui size_t u;
64*01826a49SYabin Cui for (u=0; u<size; u++) {
65*01826a49SYabin Cui RAWLOG(6, " %u", arr[u]); (void)arr;
66*01826a49SYabin Cui }
67*01826a49SYabin Cui RAWLOG(6, " \n");
68*01826a49SYabin Cui return size;
69*01826a49SYabin Cui }
70*01826a49SYabin Cui
71*01826a49SYabin Cui static size_t HUF_getNbBits(HUF_CElt elt);
72*01826a49SYabin Cui
showCTableBits(const HUF_CElt * ctable,size_t size)73*01826a49SYabin Cui static size_t showCTableBits(const HUF_CElt* ctable, size_t size)
74*01826a49SYabin Cui {
75*01826a49SYabin Cui size_t u;
76*01826a49SYabin Cui for (u=0; u<size; u++) {
77*01826a49SYabin Cui RAWLOG(6, " %zu", HUF_getNbBits(ctable[u])); (void)ctable;
78*01826a49SYabin Cui }
79*01826a49SYabin Cui RAWLOG(6, " \n");
80*01826a49SYabin Cui return size;
81*01826a49SYabin Cui
82*01826a49SYabin Cui }
83*01826a49SYabin Cui
showHNodeSymbols(const nodeElt * hnode,size_t size)84*01826a49SYabin Cui static size_t showHNodeSymbols(const nodeElt* hnode, size_t size)
85*01826a49SYabin Cui {
86*01826a49SYabin Cui size_t u;
87*01826a49SYabin Cui for (u=0; u<size; u++) {
88*01826a49SYabin Cui RAWLOG(6, " %u", hnode[u].byte); (void)hnode;
89*01826a49SYabin Cui }
90*01826a49SYabin Cui RAWLOG(6, " \n");
91*01826a49SYabin Cui return size;
92*01826a49SYabin Cui }
93*01826a49SYabin Cui
showHNodeBits(const nodeElt * hnode,size_t size)94*01826a49SYabin Cui static size_t showHNodeBits(const nodeElt* hnode, size_t size)
95*01826a49SYabin Cui {
96*01826a49SYabin Cui size_t u;
97*01826a49SYabin Cui for (u=0; u<size; u++) {
98*01826a49SYabin Cui RAWLOG(6, " %u", hnode[u].nbBits); (void)hnode;
99*01826a49SYabin Cui }
100*01826a49SYabin Cui RAWLOG(6, " \n");
101*01826a49SYabin Cui return size;
102*01826a49SYabin Cui }
103*01826a49SYabin Cui
104*01826a49SYabin Cui #endif
105*01826a49SYabin Cui
106*01826a49SYabin Cui
107*01826a49SYabin Cui /* *******************************************************
108*01826a49SYabin Cui * HUF : Huffman block compression
109*01826a49SYabin Cui *********************************************************/
110*01826a49SYabin Cui #define HUF_WORKSPACE_MAX_ALIGNMENT 8
111*01826a49SYabin Cui
HUF_alignUpWorkspace(void * workspace,size_t * workspaceSizePtr,size_t align)112*01826a49SYabin Cui static void* HUF_alignUpWorkspace(void* workspace, size_t* workspaceSizePtr, size_t align)
113*01826a49SYabin Cui {
114*01826a49SYabin Cui size_t const mask = align - 1;
115*01826a49SYabin Cui size_t const rem = (size_t)workspace & mask;
116*01826a49SYabin Cui size_t const add = (align - rem) & mask;
117*01826a49SYabin Cui BYTE* const aligned = (BYTE*)workspace + add;
118*01826a49SYabin Cui assert((align & (align - 1)) == 0); /* pow 2 */
119*01826a49SYabin Cui assert(align <= HUF_WORKSPACE_MAX_ALIGNMENT);
120*01826a49SYabin Cui if (*workspaceSizePtr >= add) {
121*01826a49SYabin Cui assert(add < align);
122*01826a49SYabin Cui assert(((size_t)aligned & mask) == 0);
123*01826a49SYabin Cui *workspaceSizePtr -= add;
124*01826a49SYabin Cui return aligned;
125*01826a49SYabin Cui } else {
126*01826a49SYabin Cui *workspaceSizePtr = 0;
127*01826a49SYabin Cui return NULL;
128*01826a49SYabin Cui }
129*01826a49SYabin Cui }
130*01826a49SYabin Cui
131*01826a49SYabin Cui
132*01826a49SYabin Cui /* HUF_compressWeights() :
133*01826a49SYabin Cui * Same as FSE_compress(), but dedicated to huff0's weights compression.
134*01826a49SYabin Cui * The use case needs much less stack memory.
135*01826a49SYabin Cui * Note : all elements within weightTable are supposed to be <= HUF_TABLELOG_MAX.
136*01826a49SYabin Cui */
137*01826a49SYabin Cui #define MAX_FSE_TABLELOG_FOR_HUFF_HEADER 6
138*01826a49SYabin Cui
139*01826a49SYabin Cui typedef struct {
140*01826a49SYabin Cui FSE_CTable CTable[FSE_CTABLE_SIZE_U32(MAX_FSE_TABLELOG_FOR_HUFF_HEADER, HUF_TABLELOG_MAX)];
141*01826a49SYabin Cui U32 scratchBuffer[FSE_BUILD_CTABLE_WORKSPACE_SIZE_U32(HUF_TABLELOG_MAX, MAX_FSE_TABLELOG_FOR_HUFF_HEADER)];
142*01826a49SYabin Cui unsigned count[HUF_TABLELOG_MAX+1];
143*01826a49SYabin Cui S16 norm[HUF_TABLELOG_MAX+1];
144*01826a49SYabin Cui } HUF_CompressWeightsWksp;
145*01826a49SYabin Cui
146*01826a49SYabin Cui static size_t
HUF_compressWeights(void * dst,size_t dstSize,const void * weightTable,size_t wtSize,void * workspace,size_t workspaceSize)147*01826a49SYabin Cui HUF_compressWeights(void* dst, size_t dstSize,
148*01826a49SYabin Cui const void* weightTable, size_t wtSize,
149*01826a49SYabin Cui void* workspace, size_t workspaceSize)
150*01826a49SYabin Cui {
151*01826a49SYabin Cui BYTE* const ostart = (BYTE*) dst;
152*01826a49SYabin Cui BYTE* op = ostart;
153*01826a49SYabin Cui BYTE* const oend = ostart + dstSize;
154*01826a49SYabin Cui
155*01826a49SYabin Cui unsigned maxSymbolValue = HUF_TABLELOG_MAX;
156*01826a49SYabin Cui U32 tableLog = MAX_FSE_TABLELOG_FOR_HUFF_HEADER;
157*01826a49SYabin Cui HUF_CompressWeightsWksp* wksp = (HUF_CompressWeightsWksp*)HUF_alignUpWorkspace(workspace, &workspaceSize, ZSTD_ALIGNOF(U32));
158*01826a49SYabin Cui
159*01826a49SYabin Cui if (workspaceSize < sizeof(HUF_CompressWeightsWksp)) return ERROR(GENERIC);
160*01826a49SYabin Cui
161*01826a49SYabin Cui /* init conditions */
162*01826a49SYabin Cui if (wtSize <= 1) return 0; /* Not compressible */
163*01826a49SYabin Cui
164*01826a49SYabin Cui /* Scan input and build symbol stats */
165*01826a49SYabin Cui { unsigned const maxCount = HIST_count_simple(wksp->count, &maxSymbolValue, weightTable, wtSize); /* never fails */
166*01826a49SYabin Cui if (maxCount == wtSize) return 1; /* only a single symbol in src : rle */
167*01826a49SYabin Cui if (maxCount == 1) return 0; /* each symbol present maximum once => not compressible */
168*01826a49SYabin Cui }
169*01826a49SYabin Cui
170*01826a49SYabin Cui tableLog = FSE_optimalTableLog(tableLog, wtSize, maxSymbolValue);
171*01826a49SYabin Cui CHECK_F( FSE_normalizeCount(wksp->norm, tableLog, wksp->count, wtSize, maxSymbolValue, /* useLowProbCount */ 0) );
172*01826a49SYabin Cui
173*01826a49SYabin Cui /* Write table description header */
174*01826a49SYabin Cui { CHECK_V_F(hSize, FSE_writeNCount(op, (size_t)(oend-op), wksp->norm, maxSymbolValue, tableLog) );
175*01826a49SYabin Cui op += hSize;
176*01826a49SYabin Cui }
177*01826a49SYabin Cui
178*01826a49SYabin Cui /* Compress */
179*01826a49SYabin Cui CHECK_F( FSE_buildCTable_wksp(wksp->CTable, wksp->norm, maxSymbolValue, tableLog, wksp->scratchBuffer, sizeof(wksp->scratchBuffer)) );
180*01826a49SYabin Cui { CHECK_V_F(cSize, FSE_compress_usingCTable(op, (size_t)(oend - op), weightTable, wtSize, wksp->CTable) );
181*01826a49SYabin Cui if (cSize == 0) return 0; /* not enough space for compressed data */
182*01826a49SYabin Cui op += cSize;
183*01826a49SYabin Cui }
184*01826a49SYabin Cui
185*01826a49SYabin Cui return (size_t)(op-ostart);
186*01826a49SYabin Cui }
187*01826a49SYabin Cui
HUF_getNbBits(HUF_CElt elt)188*01826a49SYabin Cui static size_t HUF_getNbBits(HUF_CElt elt)
189*01826a49SYabin Cui {
190*01826a49SYabin Cui return elt & 0xFF;
191*01826a49SYabin Cui }
192*01826a49SYabin Cui
HUF_getNbBitsFast(HUF_CElt elt)193*01826a49SYabin Cui static size_t HUF_getNbBitsFast(HUF_CElt elt)
194*01826a49SYabin Cui {
195*01826a49SYabin Cui return elt;
196*01826a49SYabin Cui }
197*01826a49SYabin Cui
HUF_getValue(HUF_CElt elt)198*01826a49SYabin Cui static size_t HUF_getValue(HUF_CElt elt)
199*01826a49SYabin Cui {
200*01826a49SYabin Cui return elt & ~(size_t)0xFF;
201*01826a49SYabin Cui }
202*01826a49SYabin Cui
HUF_getValueFast(HUF_CElt elt)203*01826a49SYabin Cui static size_t HUF_getValueFast(HUF_CElt elt)
204*01826a49SYabin Cui {
205*01826a49SYabin Cui return elt;
206*01826a49SYabin Cui }
207*01826a49SYabin Cui
HUF_setNbBits(HUF_CElt * elt,size_t nbBits)208*01826a49SYabin Cui static void HUF_setNbBits(HUF_CElt* elt, size_t nbBits)
209*01826a49SYabin Cui {
210*01826a49SYabin Cui assert(nbBits <= HUF_TABLELOG_ABSOLUTEMAX);
211*01826a49SYabin Cui *elt = nbBits;
212*01826a49SYabin Cui }
213*01826a49SYabin Cui
HUF_setValue(HUF_CElt * elt,size_t value)214*01826a49SYabin Cui static void HUF_setValue(HUF_CElt* elt, size_t value)
215*01826a49SYabin Cui {
216*01826a49SYabin Cui size_t const nbBits = HUF_getNbBits(*elt);
217*01826a49SYabin Cui if (nbBits > 0) {
218*01826a49SYabin Cui assert((value >> nbBits) == 0);
219*01826a49SYabin Cui *elt |= value << (sizeof(HUF_CElt) * 8 - nbBits);
220*01826a49SYabin Cui }
221*01826a49SYabin Cui }
222*01826a49SYabin Cui
HUF_readCTableHeader(HUF_CElt const * ctable)223*01826a49SYabin Cui HUF_CTableHeader HUF_readCTableHeader(HUF_CElt const* ctable)
224*01826a49SYabin Cui {
225*01826a49SYabin Cui HUF_CTableHeader header;
226*01826a49SYabin Cui ZSTD_memcpy(&header, ctable, sizeof(header));
227*01826a49SYabin Cui return header;
228*01826a49SYabin Cui }
229*01826a49SYabin Cui
HUF_writeCTableHeader(HUF_CElt * ctable,U32 tableLog,U32 maxSymbolValue)230*01826a49SYabin Cui static void HUF_writeCTableHeader(HUF_CElt* ctable, U32 tableLog, U32 maxSymbolValue)
231*01826a49SYabin Cui {
232*01826a49SYabin Cui HUF_CTableHeader header;
233*01826a49SYabin Cui HUF_STATIC_ASSERT(sizeof(ctable[0]) == sizeof(header));
234*01826a49SYabin Cui ZSTD_memset(&header, 0, sizeof(header));
235*01826a49SYabin Cui assert(tableLog < 256);
236*01826a49SYabin Cui header.tableLog = (BYTE)tableLog;
237*01826a49SYabin Cui assert(maxSymbolValue < 256);
238*01826a49SYabin Cui header.maxSymbolValue = (BYTE)maxSymbolValue;
239*01826a49SYabin Cui ZSTD_memcpy(ctable, &header, sizeof(header));
240*01826a49SYabin Cui }
241*01826a49SYabin Cui
242*01826a49SYabin Cui typedef struct {
243*01826a49SYabin Cui HUF_CompressWeightsWksp wksp;
244*01826a49SYabin Cui BYTE bitsToWeight[HUF_TABLELOG_MAX + 1]; /* precomputed conversion table */
245*01826a49SYabin Cui BYTE huffWeight[HUF_SYMBOLVALUE_MAX];
246*01826a49SYabin Cui } HUF_WriteCTableWksp;
247*01826a49SYabin Cui
HUF_writeCTable_wksp(void * dst,size_t maxDstSize,const HUF_CElt * CTable,unsigned maxSymbolValue,unsigned huffLog,void * workspace,size_t workspaceSize)248*01826a49SYabin Cui size_t HUF_writeCTable_wksp(void* dst, size_t maxDstSize,
249*01826a49SYabin Cui const HUF_CElt* CTable, unsigned maxSymbolValue, unsigned huffLog,
250*01826a49SYabin Cui void* workspace, size_t workspaceSize)
251*01826a49SYabin Cui {
252*01826a49SYabin Cui HUF_CElt const* const ct = CTable + 1;
253*01826a49SYabin Cui BYTE* op = (BYTE*)dst;
254*01826a49SYabin Cui U32 n;
255*01826a49SYabin Cui HUF_WriteCTableWksp* wksp = (HUF_WriteCTableWksp*)HUF_alignUpWorkspace(workspace, &workspaceSize, ZSTD_ALIGNOF(U32));
256*01826a49SYabin Cui
257*01826a49SYabin Cui HUF_STATIC_ASSERT(HUF_CTABLE_WORKSPACE_SIZE >= sizeof(HUF_WriteCTableWksp));
258*01826a49SYabin Cui
259*01826a49SYabin Cui assert(HUF_readCTableHeader(CTable).maxSymbolValue == maxSymbolValue);
260*01826a49SYabin Cui assert(HUF_readCTableHeader(CTable).tableLog == huffLog);
261*01826a49SYabin Cui
262*01826a49SYabin Cui /* check conditions */
263*01826a49SYabin Cui if (workspaceSize < sizeof(HUF_WriteCTableWksp)) return ERROR(GENERIC);
264*01826a49SYabin Cui if (maxSymbolValue > HUF_SYMBOLVALUE_MAX) return ERROR(maxSymbolValue_tooLarge);
265*01826a49SYabin Cui
266*01826a49SYabin Cui /* convert to weight */
267*01826a49SYabin Cui wksp->bitsToWeight[0] = 0;
268*01826a49SYabin Cui for (n=1; n<huffLog+1; n++)
269*01826a49SYabin Cui wksp->bitsToWeight[n] = (BYTE)(huffLog + 1 - n);
270*01826a49SYabin Cui for (n=0; n<maxSymbolValue; n++)
271*01826a49SYabin Cui wksp->huffWeight[n] = wksp->bitsToWeight[HUF_getNbBits(ct[n])];
272*01826a49SYabin Cui
273*01826a49SYabin Cui /* attempt weights compression by FSE */
274*01826a49SYabin Cui if (maxDstSize < 1) return ERROR(dstSize_tooSmall);
275*01826a49SYabin Cui { CHECK_V_F(hSize, HUF_compressWeights(op+1, maxDstSize-1, wksp->huffWeight, maxSymbolValue, &wksp->wksp, sizeof(wksp->wksp)) );
276*01826a49SYabin Cui if ((hSize>1) & (hSize < maxSymbolValue/2)) { /* FSE compressed */
277*01826a49SYabin Cui op[0] = (BYTE)hSize;
278*01826a49SYabin Cui return hSize+1;
279*01826a49SYabin Cui } }
280*01826a49SYabin Cui
281*01826a49SYabin Cui /* write raw values as 4-bits (max : 15) */
282*01826a49SYabin Cui if (maxSymbolValue > (256-128)) return ERROR(GENERIC); /* should not happen : likely means source cannot be compressed */
283*01826a49SYabin Cui if (((maxSymbolValue+1)/2) + 1 > maxDstSize) return ERROR(dstSize_tooSmall); /* not enough space within dst buffer */
284*01826a49SYabin Cui op[0] = (BYTE)(128 /*special case*/ + (maxSymbolValue-1));
285*01826a49SYabin Cui wksp->huffWeight[maxSymbolValue] = 0; /* to be sure it doesn't cause msan issue in final combination */
286*01826a49SYabin Cui for (n=0; n<maxSymbolValue; n+=2)
287*01826a49SYabin Cui op[(n/2)+1] = (BYTE)((wksp->huffWeight[n] << 4) + wksp->huffWeight[n+1]);
288*01826a49SYabin Cui return ((maxSymbolValue+1)/2) + 1;
289*01826a49SYabin Cui }
290*01826a49SYabin Cui
291*01826a49SYabin Cui
HUF_readCTable(HUF_CElt * CTable,unsigned * maxSymbolValuePtr,const void * src,size_t srcSize,unsigned * hasZeroWeights)292*01826a49SYabin Cui size_t HUF_readCTable (HUF_CElt* CTable, unsigned* maxSymbolValuePtr, const void* src, size_t srcSize, unsigned* hasZeroWeights)
293*01826a49SYabin Cui {
294*01826a49SYabin Cui BYTE huffWeight[HUF_SYMBOLVALUE_MAX + 1]; /* init not required, even though some static analyzer may complain */
295*01826a49SYabin Cui U32 rankVal[HUF_TABLELOG_ABSOLUTEMAX + 1]; /* large enough for values from 0 to 16 */
296*01826a49SYabin Cui U32 tableLog = 0;
297*01826a49SYabin Cui U32 nbSymbols = 0;
298*01826a49SYabin Cui HUF_CElt* const ct = CTable + 1;
299*01826a49SYabin Cui
300*01826a49SYabin Cui /* get symbol weights */
301*01826a49SYabin Cui CHECK_V_F(readSize, HUF_readStats(huffWeight, HUF_SYMBOLVALUE_MAX+1, rankVal, &nbSymbols, &tableLog, src, srcSize));
302*01826a49SYabin Cui *hasZeroWeights = (rankVal[0] > 0);
303*01826a49SYabin Cui
304*01826a49SYabin Cui /* check result */
305*01826a49SYabin Cui if (tableLog > HUF_TABLELOG_MAX) return ERROR(tableLog_tooLarge);
306*01826a49SYabin Cui if (nbSymbols > *maxSymbolValuePtr+1) return ERROR(maxSymbolValue_tooSmall);
307*01826a49SYabin Cui
308*01826a49SYabin Cui *maxSymbolValuePtr = nbSymbols - 1;
309*01826a49SYabin Cui
310*01826a49SYabin Cui HUF_writeCTableHeader(CTable, tableLog, *maxSymbolValuePtr);
311*01826a49SYabin Cui
312*01826a49SYabin Cui /* Prepare base value per rank */
313*01826a49SYabin Cui { U32 n, nextRankStart = 0;
314*01826a49SYabin Cui for (n=1; n<=tableLog; n++) {
315*01826a49SYabin Cui U32 curr = nextRankStart;
316*01826a49SYabin Cui nextRankStart += (rankVal[n] << (n-1));
317*01826a49SYabin Cui rankVal[n] = curr;
318*01826a49SYabin Cui } }
319*01826a49SYabin Cui
320*01826a49SYabin Cui /* fill nbBits */
321*01826a49SYabin Cui { U32 n; for (n=0; n<nbSymbols; n++) {
322*01826a49SYabin Cui const U32 w = huffWeight[n];
323*01826a49SYabin Cui HUF_setNbBits(ct + n, (BYTE)(tableLog + 1 - w) & -(w != 0));
324*01826a49SYabin Cui } }
325*01826a49SYabin Cui
326*01826a49SYabin Cui /* fill val */
327*01826a49SYabin Cui { U16 nbPerRank[HUF_TABLELOG_MAX+2] = {0}; /* support w=0=>n=tableLog+1 */
328*01826a49SYabin Cui U16 valPerRank[HUF_TABLELOG_MAX+2] = {0};
329*01826a49SYabin Cui { U32 n; for (n=0; n<nbSymbols; n++) nbPerRank[HUF_getNbBits(ct[n])]++; }
330*01826a49SYabin Cui /* determine stating value per rank */
331*01826a49SYabin Cui valPerRank[tableLog+1] = 0; /* for w==0 */
332*01826a49SYabin Cui { U16 min = 0;
333*01826a49SYabin Cui U32 n; for (n=tableLog; n>0; n--) { /* start at n=tablelog <-> w=1 */
334*01826a49SYabin Cui valPerRank[n] = min; /* get starting value within each rank */
335*01826a49SYabin Cui min += nbPerRank[n];
336*01826a49SYabin Cui min >>= 1;
337*01826a49SYabin Cui } }
338*01826a49SYabin Cui /* assign value within rank, symbol order */
339*01826a49SYabin Cui { U32 n; for (n=0; n<nbSymbols; n++) HUF_setValue(ct + n, valPerRank[HUF_getNbBits(ct[n])]++); }
340*01826a49SYabin Cui }
341*01826a49SYabin Cui
342*01826a49SYabin Cui return readSize;
343*01826a49SYabin Cui }
344*01826a49SYabin Cui
HUF_getNbBitsFromCTable(HUF_CElt const * CTable,U32 symbolValue)345*01826a49SYabin Cui U32 HUF_getNbBitsFromCTable(HUF_CElt const* CTable, U32 symbolValue)
346*01826a49SYabin Cui {
347*01826a49SYabin Cui const HUF_CElt* const ct = CTable + 1;
348*01826a49SYabin Cui assert(symbolValue <= HUF_SYMBOLVALUE_MAX);
349*01826a49SYabin Cui if (symbolValue > HUF_readCTableHeader(CTable).maxSymbolValue)
350*01826a49SYabin Cui return 0;
351*01826a49SYabin Cui return (U32)HUF_getNbBits(ct[symbolValue]);
352*01826a49SYabin Cui }
353*01826a49SYabin Cui
354*01826a49SYabin Cui
355*01826a49SYabin Cui /**
356*01826a49SYabin Cui * HUF_setMaxHeight():
357*01826a49SYabin Cui * Try to enforce @targetNbBits on the Huffman tree described in @huffNode.
358*01826a49SYabin Cui *
359*01826a49SYabin Cui * It attempts to convert all nodes with nbBits > @targetNbBits
360*01826a49SYabin Cui * to employ @targetNbBits instead. Then it adjusts the tree
361*01826a49SYabin Cui * so that it remains a valid canonical Huffman tree.
362*01826a49SYabin Cui *
363*01826a49SYabin Cui * @pre The sum of the ranks of each symbol == 2^largestBits,
364*01826a49SYabin Cui * where largestBits == huffNode[lastNonNull].nbBits.
365*01826a49SYabin Cui * @post The sum of the ranks of each symbol == 2^largestBits,
366*01826a49SYabin Cui * where largestBits is the return value (expected <= targetNbBits).
367*01826a49SYabin Cui *
368*01826a49SYabin Cui * @param huffNode The Huffman tree modified in place to enforce targetNbBits.
369*01826a49SYabin Cui * It's presumed sorted, from most frequent to rarest symbol.
370*01826a49SYabin Cui * @param lastNonNull The symbol with the lowest count in the Huffman tree.
371*01826a49SYabin Cui * @param targetNbBits The allowed number of bits, which the Huffman tree
372*01826a49SYabin Cui * may not respect. After this function the Huffman tree will
373*01826a49SYabin Cui * respect targetNbBits.
374*01826a49SYabin Cui * @return The maximum number of bits of the Huffman tree after adjustment.
375*01826a49SYabin Cui */
HUF_setMaxHeight(nodeElt * huffNode,U32 lastNonNull,U32 targetNbBits)376*01826a49SYabin Cui static U32 HUF_setMaxHeight(nodeElt* huffNode, U32 lastNonNull, U32 targetNbBits)
377*01826a49SYabin Cui {
378*01826a49SYabin Cui const U32 largestBits = huffNode[lastNonNull].nbBits;
379*01826a49SYabin Cui /* early exit : no elt > targetNbBits, so the tree is already valid. */
380*01826a49SYabin Cui if (largestBits <= targetNbBits) return largestBits;
381*01826a49SYabin Cui
382*01826a49SYabin Cui DEBUGLOG(5, "HUF_setMaxHeight (targetNbBits = %u)", targetNbBits);
383*01826a49SYabin Cui
384*01826a49SYabin Cui /* there are several too large elements (at least >= 2) */
385*01826a49SYabin Cui { int totalCost = 0;
386*01826a49SYabin Cui const U32 baseCost = 1 << (largestBits - targetNbBits);
387*01826a49SYabin Cui int n = (int)lastNonNull;
388*01826a49SYabin Cui
389*01826a49SYabin Cui /* Adjust any ranks > targetNbBits to targetNbBits.
390*01826a49SYabin Cui * Compute totalCost, which is how far the sum of the ranks is
391*01826a49SYabin Cui * we are over 2^largestBits after adjust the offending ranks.
392*01826a49SYabin Cui */
393*01826a49SYabin Cui while (huffNode[n].nbBits > targetNbBits) {
394*01826a49SYabin Cui totalCost += baseCost - (1 << (largestBits - huffNode[n].nbBits));
395*01826a49SYabin Cui huffNode[n].nbBits = (BYTE)targetNbBits;
396*01826a49SYabin Cui n--;
397*01826a49SYabin Cui }
398*01826a49SYabin Cui /* n stops at huffNode[n].nbBits <= targetNbBits */
399*01826a49SYabin Cui assert(huffNode[n].nbBits <= targetNbBits);
400*01826a49SYabin Cui /* n end at index of smallest symbol using < targetNbBits */
401*01826a49SYabin Cui while (huffNode[n].nbBits == targetNbBits) --n;
402*01826a49SYabin Cui
403*01826a49SYabin Cui /* renorm totalCost from 2^largestBits to 2^targetNbBits
404*01826a49SYabin Cui * note : totalCost is necessarily a multiple of baseCost */
405*01826a49SYabin Cui assert(((U32)totalCost & (baseCost - 1)) == 0);
406*01826a49SYabin Cui totalCost >>= (largestBits - targetNbBits);
407*01826a49SYabin Cui assert(totalCost > 0);
408*01826a49SYabin Cui
409*01826a49SYabin Cui /* repay normalized cost */
410*01826a49SYabin Cui { U32 const noSymbol = 0xF0F0F0F0;
411*01826a49SYabin Cui U32 rankLast[HUF_TABLELOG_MAX+2];
412*01826a49SYabin Cui
413*01826a49SYabin Cui /* Get pos of last (smallest = lowest cum. count) symbol per rank */
414*01826a49SYabin Cui ZSTD_memset(rankLast, 0xF0, sizeof(rankLast));
415*01826a49SYabin Cui { U32 currentNbBits = targetNbBits;
416*01826a49SYabin Cui int pos;
417*01826a49SYabin Cui for (pos=n ; pos >= 0; pos--) {
418*01826a49SYabin Cui if (huffNode[pos].nbBits >= currentNbBits) continue;
419*01826a49SYabin Cui currentNbBits = huffNode[pos].nbBits; /* < targetNbBits */
420*01826a49SYabin Cui rankLast[targetNbBits-currentNbBits] = (U32)pos;
421*01826a49SYabin Cui } }
422*01826a49SYabin Cui
423*01826a49SYabin Cui while (totalCost > 0) {
424*01826a49SYabin Cui /* Try to reduce the next power of 2 above totalCost because we
425*01826a49SYabin Cui * gain back half the rank.
426*01826a49SYabin Cui */
427*01826a49SYabin Cui U32 nBitsToDecrease = ZSTD_highbit32((U32)totalCost) + 1;
428*01826a49SYabin Cui for ( ; nBitsToDecrease > 1; nBitsToDecrease--) {
429*01826a49SYabin Cui U32 const highPos = rankLast[nBitsToDecrease];
430*01826a49SYabin Cui U32 const lowPos = rankLast[nBitsToDecrease-1];
431*01826a49SYabin Cui if (highPos == noSymbol) continue;
432*01826a49SYabin Cui /* Decrease highPos if no symbols of lowPos or if it is
433*01826a49SYabin Cui * not cheaper to remove 2 lowPos than highPos.
434*01826a49SYabin Cui */
435*01826a49SYabin Cui if (lowPos == noSymbol) break;
436*01826a49SYabin Cui { U32 const highTotal = huffNode[highPos].count;
437*01826a49SYabin Cui U32 const lowTotal = 2 * huffNode[lowPos].count;
438*01826a49SYabin Cui if (highTotal <= lowTotal) break;
439*01826a49SYabin Cui } }
440*01826a49SYabin Cui /* only triggered when no more rank 1 symbol left => find closest one (note : there is necessarily at least one !) */
441*01826a49SYabin Cui assert(rankLast[nBitsToDecrease] != noSymbol || nBitsToDecrease == 1);
442*01826a49SYabin Cui /* HUF_MAX_TABLELOG test just to please gcc 5+; but it should not be necessary */
443*01826a49SYabin Cui while ((nBitsToDecrease<=HUF_TABLELOG_MAX) && (rankLast[nBitsToDecrease] == noSymbol))
444*01826a49SYabin Cui nBitsToDecrease++;
445*01826a49SYabin Cui assert(rankLast[nBitsToDecrease] != noSymbol);
446*01826a49SYabin Cui /* Increase the number of bits to gain back half the rank cost. */
447*01826a49SYabin Cui totalCost -= 1 << (nBitsToDecrease-1);
448*01826a49SYabin Cui huffNode[rankLast[nBitsToDecrease]].nbBits++;
449*01826a49SYabin Cui
450*01826a49SYabin Cui /* Fix up the new rank.
451*01826a49SYabin Cui * If the new rank was empty, this symbol is now its smallest.
452*01826a49SYabin Cui * Otherwise, this symbol will be the largest in the new rank so no adjustment.
453*01826a49SYabin Cui */
454*01826a49SYabin Cui if (rankLast[nBitsToDecrease-1] == noSymbol)
455*01826a49SYabin Cui rankLast[nBitsToDecrease-1] = rankLast[nBitsToDecrease];
456*01826a49SYabin Cui /* Fix up the old rank.
457*01826a49SYabin Cui * If the symbol was at position 0, meaning it was the highest weight symbol in the tree,
458*01826a49SYabin Cui * it must be the only symbol in its rank, so the old rank now has no symbols.
459*01826a49SYabin Cui * Otherwise, since the Huffman nodes are sorted by count, the previous position is now
460*01826a49SYabin Cui * the smallest node in the rank. If the previous position belongs to a different rank,
461*01826a49SYabin Cui * then the rank is now empty.
462*01826a49SYabin Cui */
463*01826a49SYabin Cui if (rankLast[nBitsToDecrease] == 0) /* special case, reached largest symbol */
464*01826a49SYabin Cui rankLast[nBitsToDecrease] = noSymbol;
465*01826a49SYabin Cui else {
466*01826a49SYabin Cui rankLast[nBitsToDecrease]--;
467*01826a49SYabin Cui if (huffNode[rankLast[nBitsToDecrease]].nbBits != targetNbBits-nBitsToDecrease)
468*01826a49SYabin Cui rankLast[nBitsToDecrease] = noSymbol; /* this rank is now empty */
469*01826a49SYabin Cui }
470*01826a49SYabin Cui } /* while (totalCost > 0) */
471*01826a49SYabin Cui
472*01826a49SYabin Cui /* If we've removed too much weight, then we have to add it back.
473*01826a49SYabin Cui * To avoid overshooting again, we only adjust the smallest rank.
474*01826a49SYabin Cui * We take the largest nodes from the lowest rank 0 and move them
475*01826a49SYabin Cui * to rank 1. There's guaranteed to be enough rank 0 symbols because
476*01826a49SYabin Cui * TODO.
477*01826a49SYabin Cui */
478*01826a49SYabin Cui while (totalCost < 0) { /* Sometimes, cost correction overshoot */
479*01826a49SYabin Cui /* special case : no rank 1 symbol (using targetNbBits-1);
480*01826a49SYabin Cui * let's create one from largest rank 0 (using targetNbBits).
481*01826a49SYabin Cui */
482*01826a49SYabin Cui if (rankLast[1] == noSymbol) {
483*01826a49SYabin Cui while (huffNode[n].nbBits == targetNbBits) n--;
484*01826a49SYabin Cui huffNode[n+1].nbBits--;
485*01826a49SYabin Cui assert(n >= 0);
486*01826a49SYabin Cui rankLast[1] = (U32)(n+1);
487*01826a49SYabin Cui totalCost++;
488*01826a49SYabin Cui continue;
489*01826a49SYabin Cui }
490*01826a49SYabin Cui huffNode[ rankLast[1] + 1 ].nbBits--;
491*01826a49SYabin Cui rankLast[1]++;
492*01826a49SYabin Cui totalCost ++;
493*01826a49SYabin Cui }
494*01826a49SYabin Cui } /* repay normalized cost */
495*01826a49SYabin Cui } /* there are several too large elements (at least >= 2) */
496*01826a49SYabin Cui
497*01826a49SYabin Cui return targetNbBits;
498*01826a49SYabin Cui }
499*01826a49SYabin Cui
500*01826a49SYabin Cui typedef struct {
501*01826a49SYabin Cui U16 base;
502*01826a49SYabin Cui U16 curr;
503*01826a49SYabin Cui } rankPos;
504*01826a49SYabin Cui
505*01826a49SYabin Cui typedef nodeElt huffNodeTable[2 * (HUF_SYMBOLVALUE_MAX + 1)];
506*01826a49SYabin Cui
507*01826a49SYabin Cui /* Number of buckets available for HUF_sort() */
508*01826a49SYabin Cui #define RANK_POSITION_TABLE_SIZE 192
509*01826a49SYabin Cui
510*01826a49SYabin Cui typedef struct {
511*01826a49SYabin Cui huffNodeTable huffNodeTbl;
512*01826a49SYabin Cui rankPos rankPosition[RANK_POSITION_TABLE_SIZE];
513*01826a49SYabin Cui } HUF_buildCTable_wksp_tables;
514*01826a49SYabin Cui
515*01826a49SYabin Cui /* RANK_POSITION_DISTINCT_COUNT_CUTOFF == Cutoff point in HUF_sort() buckets for which we use log2 bucketing.
516*01826a49SYabin Cui * Strategy is to use as many buckets as possible for representing distinct
517*01826a49SYabin Cui * counts while using the remainder to represent all "large" counts.
518*01826a49SYabin Cui *
519*01826a49SYabin Cui * To satisfy this requirement for 192 buckets, we can do the following:
520*01826a49SYabin Cui * Let buckets 0-166 represent distinct counts of [0, 166]
521*01826a49SYabin Cui * Let buckets 166 to 192 represent all remaining counts up to RANK_POSITION_MAX_COUNT_LOG using log2 bucketing.
522*01826a49SYabin Cui */
523*01826a49SYabin Cui #define RANK_POSITION_MAX_COUNT_LOG 32
524*01826a49SYabin Cui #define RANK_POSITION_LOG_BUCKETS_BEGIN ((RANK_POSITION_TABLE_SIZE - 1) - RANK_POSITION_MAX_COUNT_LOG - 1 /* == 158 */)
525*01826a49SYabin Cui #define RANK_POSITION_DISTINCT_COUNT_CUTOFF (RANK_POSITION_LOG_BUCKETS_BEGIN + ZSTD_highbit32(RANK_POSITION_LOG_BUCKETS_BEGIN) /* == 166 */)
526*01826a49SYabin Cui
527*01826a49SYabin Cui /* Return the appropriate bucket index for a given count. See definition of
528*01826a49SYabin Cui * RANK_POSITION_DISTINCT_COUNT_CUTOFF for explanation of bucketing strategy.
529*01826a49SYabin Cui */
HUF_getIndex(U32 const count)530*01826a49SYabin Cui static U32 HUF_getIndex(U32 const count) {
531*01826a49SYabin Cui return (count < RANK_POSITION_DISTINCT_COUNT_CUTOFF)
532*01826a49SYabin Cui ? count
533*01826a49SYabin Cui : ZSTD_highbit32(count) + RANK_POSITION_LOG_BUCKETS_BEGIN;
534*01826a49SYabin Cui }
535*01826a49SYabin Cui
536*01826a49SYabin Cui /* Helper swap function for HUF_quickSortPartition() */
HUF_swapNodes(nodeElt * a,nodeElt * b)537*01826a49SYabin Cui static void HUF_swapNodes(nodeElt* a, nodeElt* b) {
538*01826a49SYabin Cui nodeElt tmp = *a;
539*01826a49SYabin Cui *a = *b;
540*01826a49SYabin Cui *b = tmp;
541*01826a49SYabin Cui }
542*01826a49SYabin Cui
543*01826a49SYabin Cui /* Returns 0 if the huffNode array is not sorted by descending count */
HUF_isSorted(nodeElt huffNode[],U32 const maxSymbolValue1)544*01826a49SYabin Cui MEM_STATIC int HUF_isSorted(nodeElt huffNode[], U32 const maxSymbolValue1) {
545*01826a49SYabin Cui U32 i;
546*01826a49SYabin Cui for (i = 1; i < maxSymbolValue1; ++i) {
547*01826a49SYabin Cui if (huffNode[i].count > huffNode[i-1].count) {
548*01826a49SYabin Cui return 0;
549*01826a49SYabin Cui }
550*01826a49SYabin Cui }
551*01826a49SYabin Cui return 1;
552*01826a49SYabin Cui }
553*01826a49SYabin Cui
554*01826a49SYabin Cui /* Insertion sort by descending order */
HUF_insertionSort(nodeElt huffNode[],int const low,int const high)555*01826a49SYabin Cui HINT_INLINE void HUF_insertionSort(nodeElt huffNode[], int const low, int const high) {
556*01826a49SYabin Cui int i;
557*01826a49SYabin Cui int const size = high-low+1;
558*01826a49SYabin Cui huffNode += low;
559*01826a49SYabin Cui for (i = 1; i < size; ++i) {
560*01826a49SYabin Cui nodeElt const key = huffNode[i];
561*01826a49SYabin Cui int j = i - 1;
562*01826a49SYabin Cui while (j >= 0 && huffNode[j].count < key.count) {
563*01826a49SYabin Cui huffNode[j + 1] = huffNode[j];
564*01826a49SYabin Cui j--;
565*01826a49SYabin Cui }
566*01826a49SYabin Cui huffNode[j + 1] = key;
567*01826a49SYabin Cui }
568*01826a49SYabin Cui }
569*01826a49SYabin Cui
570*01826a49SYabin Cui /* Pivot helper function for quicksort. */
HUF_quickSortPartition(nodeElt arr[],int const low,int const high)571*01826a49SYabin Cui static int HUF_quickSortPartition(nodeElt arr[], int const low, int const high) {
572*01826a49SYabin Cui /* Simply select rightmost element as pivot. "Better" selectors like
573*01826a49SYabin Cui * median-of-three don't experimentally appear to have any benefit.
574*01826a49SYabin Cui */
575*01826a49SYabin Cui U32 const pivot = arr[high].count;
576*01826a49SYabin Cui int i = low - 1;
577*01826a49SYabin Cui int j = low;
578*01826a49SYabin Cui for ( ; j < high; j++) {
579*01826a49SYabin Cui if (arr[j].count > pivot) {
580*01826a49SYabin Cui i++;
581*01826a49SYabin Cui HUF_swapNodes(&arr[i], &arr[j]);
582*01826a49SYabin Cui }
583*01826a49SYabin Cui }
584*01826a49SYabin Cui HUF_swapNodes(&arr[i + 1], &arr[high]);
585*01826a49SYabin Cui return i + 1;
586*01826a49SYabin Cui }
587*01826a49SYabin Cui
588*01826a49SYabin Cui /* Classic quicksort by descending with partially iterative calls
589*01826a49SYabin Cui * to reduce worst case callstack size.
590*01826a49SYabin Cui */
HUF_simpleQuickSort(nodeElt arr[],int low,int high)591*01826a49SYabin Cui static void HUF_simpleQuickSort(nodeElt arr[], int low, int high) {
592*01826a49SYabin Cui int const kInsertionSortThreshold = 8;
593*01826a49SYabin Cui if (high - low < kInsertionSortThreshold) {
594*01826a49SYabin Cui HUF_insertionSort(arr, low, high);
595*01826a49SYabin Cui return;
596*01826a49SYabin Cui }
597*01826a49SYabin Cui while (low < high) {
598*01826a49SYabin Cui int const idx = HUF_quickSortPartition(arr, low, high);
599*01826a49SYabin Cui if (idx - low < high - idx) {
600*01826a49SYabin Cui HUF_simpleQuickSort(arr, low, idx - 1);
601*01826a49SYabin Cui low = idx + 1;
602*01826a49SYabin Cui } else {
603*01826a49SYabin Cui HUF_simpleQuickSort(arr, idx + 1, high);
604*01826a49SYabin Cui high = idx - 1;
605*01826a49SYabin Cui }
606*01826a49SYabin Cui }
607*01826a49SYabin Cui }
608*01826a49SYabin Cui
609*01826a49SYabin Cui /**
610*01826a49SYabin Cui * HUF_sort():
611*01826a49SYabin Cui * Sorts the symbols [0, maxSymbolValue] by count[symbol] in decreasing order.
612*01826a49SYabin Cui * This is a typical bucket sorting strategy that uses either quicksort or insertion sort to sort each bucket.
613*01826a49SYabin Cui *
614*01826a49SYabin Cui * @param[out] huffNode Sorted symbols by decreasing count. Only members `.count` and `.byte` are filled.
615*01826a49SYabin Cui * Must have (maxSymbolValue + 1) entries.
616*01826a49SYabin Cui * @param[in] count Histogram of the symbols.
617*01826a49SYabin Cui * @param[in] maxSymbolValue Maximum symbol value.
618*01826a49SYabin Cui * @param rankPosition This is a scratch workspace. Must have RANK_POSITION_TABLE_SIZE entries.
619*01826a49SYabin Cui */
HUF_sort(nodeElt huffNode[],const unsigned count[],U32 const maxSymbolValue,rankPos rankPosition[])620*01826a49SYabin Cui static void HUF_sort(nodeElt huffNode[], const unsigned count[], U32 const maxSymbolValue, rankPos rankPosition[]) {
621*01826a49SYabin Cui U32 n;
622*01826a49SYabin Cui U32 const maxSymbolValue1 = maxSymbolValue+1;
623*01826a49SYabin Cui
624*01826a49SYabin Cui /* Compute base and set curr to base.
625*01826a49SYabin Cui * For symbol s let lowerRank = HUF_getIndex(count[n]) and rank = lowerRank + 1.
626*01826a49SYabin Cui * See HUF_getIndex to see bucketing strategy.
627*01826a49SYabin Cui * We attribute each symbol to lowerRank's base value, because we want to know where
628*01826a49SYabin Cui * each rank begins in the output, so for rank R we want to count ranks R+1 and above.
629*01826a49SYabin Cui */
630*01826a49SYabin Cui ZSTD_memset(rankPosition, 0, sizeof(*rankPosition) * RANK_POSITION_TABLE_SIZE);
631*01826a49SYabin Cui for (n = 0; n < maxSymbolValue1; ++n) {
632*01826a49SYabin Cui U32 lowerRank = HUF_getIndex(count[n]);
633*01826a49SYabin Cui assert(lowerRank < RANK_POSITION_TABLE_SIZE - 1);
634*01826a49SYabin Cui rankPosition[lowerRank].base++;
635*01826a49SYabin Cui }
636*01826a49SYabin Cui
637*01826a49SYabin Cui assert(rankPosition[RANK_POSITION_TABLE_SIZE - 1].base == 0);
638*01826a49SYabin Cui /* Set up the rankPosition table */
639*01826a49SYabin Cui for (n = RANK_POSITION_TABLE_SIZE - 1; n > 0; --n) {
640*01826a49SYabin Cui rankPosition[n-1].base += rankPosition[n].base;
641*01826a49SYabin Cui rankPosition[n-1].curr = rankPosition[n-1].base;
642*01826a49SYabin Cui }
643*01826a49SYabin Cui
644*01826a49SYabin Cui /* Insert each symbol into their appropriate bucket, setting up rankPosition table. */
645*01826a49SYabin Cui for (n = 0; n < maxSymbolValue1; ++n) {
646*01826a49SYabin Cui U32 const c = count[n];
647*01826a49SYabin Cui U32 const r = HUF_getIndex(c) + 1;
648*01826a49SYabin Cui U32 const pos = rankPosition[r].curr++;
649*01826a49SYabin Cui assert(pos < maxSymbolValue1);
650*01826a49SYabin Cui huffNode[pos].count = c;
651*01826a49SYabin Cui huffNode[pos].byte = (BYTE)n;
652*01826a49SYabin Cui }
653*01826a49SYabin Cui
654*01826a49SYabin Cui /* Sort each bucket. */
655*01826a49SYabin Cui for (n = RANK_POSITION_DISTINCT_COUNT_CUTOFF; n < RANK_POSITION_TABLE_SIZE - 1; ++n) {
656*01826a49SYabin Cui int const bucketSize = rankPosition[n].curr - rankPosition[n].base;
657*01826a49SYabin Cui U32 const bucketStartIdx = rankPosition[n].base;
658*01826a49SYabin Cui if (bucketSize > 1) {
659*01826a49SYabin Cui assert(bucketStartIdx < maxSymbolValue1);
660*01826a49SYabin Cui HUF_simpleQuickSort(huffNode + bucketStartIdx, 0, bucketSize-1);
661*01826a49SYabin Cui }
662*01826a49SYabin Cui }
663*01826a49SYabin Cui
664*01826a49SYabin Cui assert(HUF_isSorted(huffNode, maxSymbolValue1));
665*01826a49SYabin Cui }
666*01826a49SYabin Cui
667*01826a49SYabin Cui
668*01826a49SYabin Cui /** HUF_buildCTable_wksp() :
669*01826a49SYabin Cui * Same as HUF_buildCTable(), but using externally allocated scratch buffer.
670*01826a49SYabin Cui * `workSpace` must be aligned on 4-bytes boundaries, and be at least as large as sizeof(HUF_buildCTable_wksp_tables).
671*01826a49SYabin Cui */
672*01826a49SYabin Cui #define STARTNODE (HUF_SYMBOLVALUE_MAX+1)
673*01826a49SYabin Cui
674*01826a49SYabin Cui /* HUF_buildTree():
675*01826a49SYabin Cui * Takes the huffNode array sorted by HUF_sort() and builds an unlimited-depth Huffman tree.
676*01826a49SYabin Cui *
677*01826a49SYabin Cui * @param huffNode The array sorted by HUF_sort(). Builds the Huffman tree in this array.
678*01826a49SYabin Cui * @param maxSymbolValue The maximum symbol value.
679*01826a49SYabin Cui * @return The smallest node in the Huffman tree (by count).
680*01826a49SYabin Cui */
HUF_buildTree(nodeElt * huffNode,U32 maxSymbolValue)681*01826a49SYabin Cui static int HUF_buildTree(nodeElt* huffNode, U32 maxSymbolValue)
682*01826a49SYabin Cui {
683*01826a49SYabin Cui nodeElt* const huffNode0 = huffNode - 1;
684*01826a49SYabin Cui int nonNullRank;
685*01826a49SYabin Cui int lowS, lowN;
686*01826a49SYabin Cui int nodeNb = STARTNODE;
687*01826a49SYabin Cui int n, nodeRoot;
688*01826a49SYabin Cui DEBUGLOG(5, "HUF_buildTree (alphabet size = %u)", maxSymbolValue + 1);
689*01826a49SYabin Cui /* init for parents */
690*01826a49SYabin Cui nonNullRank = (int)maxSymbolValue;
691*01826a49SYabin Cui while(huffNode[nonNullRank].count == 0) nonNullRank--;
692*01826a49SYabin Cui lowS = nonNullRank; nodeRoot = nodeNb + lowS - 1; lowN = nodeNb;
693*01826a49SYabin Cui huffNode[nodeNb].count = huffNode[lowS].count + huffNode[lowS-1].count;
694*01826a49SYabin Cui huffNode[lowS].parent = huffNode[lowS-1].parent = (U16)nodeNb;
695*01826a49SYabin Cui nodeNb++; lowS-=2;
696*01826a49SYabin Cui for (n=nodeNb; n<=nodeRoot; n++) huffNode[n].count = (U32)(1U<<30);
697*01826a49SYabin Cui huffNode0[0].count = (U32)(1U<<31); /* fake entry, strong barrier */
698*01826a49SYabin Cui
699*01826a49SYabin Cui /* create parents */
700*01826a49SYabin Cui while (nodeNb <= nodeRoot) {
701*01826a49SYabin Cui int const n1 = (huffNode[lowS].count < huffNode[lowN].count) ? lowS-- : lowN++;
702*01826a49SYabin Cui int const n2 = (huffNode[lowS].count < huffNode[lowN].count) ? lowS-- : lowN++;
703*01826a49SYabin Cui huffNode[nodeNb].count = huffNode[n1].count + huffNode[n2].count;
704*01826a49SYabin Cui huffNode[n1].parent = huffNode[n2].parent = (U16)nodeNb;
705*01826a49SYabin Cui nodeNb++;
706*01826a49SYabin Cui }
707*01826a49SYabin Cui
708*01826a49SYabin Cui /* distribute weights (unlimited tree height) */
709*01826a49SYabin Cui huffNode[nodeRoot].nbBits = 0;
710*01826a49SYabin Cui for (n=nodeRoot-1; n>=STARTNODE; n--)
711*01826a49SYabin Cui huffNode[n].nbBits = huffNode[ huffNode[n].parent ].nbBits + 1;
712*01826a49SYabin Cui for (n=0; n<=nonNullRank; n++)
713*01826a49SYabin Cui huffNode[n].nbBits = huffNode[ huffNode[n].parent ].nbBits + 1;
714*01826a49SYabin Cui
715*01826a49SYabin Cui DEBUGLOG(6, "Initial distribution of bits completed (%zu sorted symbols)", showHNodeBits(huffNode, maxSymbolValue+1));
716*01826a49SYabin Cui
717*01826a49SYabin Cui return nonNullRank;
718*01826a49SYabin Cui }
719*01826a49SYabin Cui
720*01826a49SYabin Cui /**
721*01826a49SYabin Cui * HUF_buildCTableFromTree():
722*01826a49SYabin Cui * Build the CTable given the Huffman tree in huffNode.
723*01826a49SYabin Cui *
724*01826a49SYabin Cui * @param[out] CTable The output Huffman CTable.
725*01826a49SYabin Cui * @param huffNode The Huffman tree.
726*01826a49SYabin Cui * @param nonNullRank The last and smallest node in the Huffman tree.
727*01826a49SYabin Cui * @param maxSymbolValue The maximum symbol value.
728*01826a49SYabin Cui * @param maxNbBits The exact maximum number of bits used in the Huffman tree.
729*01826a49SYabin Cui */
HUF_buildCTableFromTree(HUF_CElt * CTable,nodeElt const * huffNode,int nonNullRank,U32 maxSymbolValue,U32 maxNbBits)730*01826a49SYabin Cui static void HUF_buildCTableFromTree(HUF_CElt* CTable, nodeElt const* huffNode, int nonNullRank, U32 maxSymbolValue, U32 maxNbBits)
731*01826a49SYabin Cui {
732*01826a49SYabin Cui HUF_CElt* const ct = CTable + 1;
733*01826a49SYabin Cui /* fill result into ctable (val, nbBits) */
734*01826a49SYabin Cui int n;
735*01826a49SYabin Cui U16 nbPerRank[HUF_TABLELOG_MAX+1] = {0};
736*01826a49SYabin Cui U16 valPerRank[HUF_TABLELOG_MAX+1] = {0};
737*01826a49SYabin Cui int const alphabetSize = (int)(maxSymbolValue + 1);
738*01826a49SYabin Cui for (n=0; n<=nonNullRank; n++)
739*01826a49SYabin Cui nbPerRank[huffNode[n].nbBits]++;
740*01826a49SYabin Cui /* determine starting value per rank */
741*01826a49SYabin Cui { U16 min = 0;
742*01826a49SYabin Cui for (n=(int)maxNbBits; n>0; n--) {
743*01826a49SYabin Cui valPerRank[n] = min; /* get starting value within each rank */
744*01826a49SYabin Cui min += nbPerRank[n];
745*01826a49SYabin Cui min >>= 1;
746*01826a49SYabin Cui } }
747*01826a49SYabin Cui for (n=0; n<alphabetSize; n++)
748*01826a49SYabin Cui HUF_setNbBits(ct + huffNode[n].byte, huffNode[n].nbBits); /* push nbBits per symbol, symbol order */
749*01826a49SYabin Cui for (n=0; n<alphabetSize; n++)
750*01826a49SYabin Cui HUF_setValue(ct + n, valPerRank[HUF_getNbBits(ct[n])]++); /* assign value within rank, symbol order */
751*01826a49SYabin Cui
752*01826a49SYabin Cui HUF_writeCTableHeader(CTable, maxNbBits, maxSymbolValue);
753*01826a49SYabin Cui }
754*01826a49SYabin Cui
755*01826a49SYabin Cui size_t
HUF_buildCTable_wksp(HUF_CElt * CTable,const unsigned * count,U32 maxSymbolValue,U32 maxNbBits,void * workSpace,size_t wkspSize)756*01826a49SYabin Cui HUF_buildCTable_wksp(HUF_CElt* CTable, const unsigned* count, U32 maxSymbolValue, U32 maxNbBits,
757*01826a49SYabin Cui void* workSpace, size_t wkspSize)
758*01826a49SYabin Cui {
759*01826a49SYabin Cui HUF_buildCTable_wksp_tables* const wksp_tables =
760*01826a49SYabin Cui (HUF_buildCTable_wksp_tables*)HUF_alignUpWorkspace(workSpace, &wkspSize, ZSTD_ALIGNOF(U32));
761*01826a49SYabin Cui nodeElt* const huffNode0 = wksp_tables->huffNodeTbl;
762*01826a49SYabin Cui nodeElt* const huffNode = huffNode0+1;
763*01826a49SYabin Cui int nonNullRank;
764*01826a49SYabin Cui
765*01826a49SYabin Cui HUF_STATIC_ASSERT(HUF_CTABLE_WORKSPACE_SIZE == sizeof(HUF_buildCTable_wksp_tables));
766*01826a49SYabin Cui
767*01826a49SYabin Cui DEBUGLOG(5, "HUF_buildCTable_wksp (alphabet size = %u)", maxSymbolValue+1);
768*01826a49SYabin Cui
769*01826a49SYabin Cui /* safety checks */
770*01826a49SYabin Cui if (wkspSize < sizeof(HUF_buildCTable_wksp_tables))
771*01826a49SYabin Cui return ERROR(workSpace_tooSmall);
772*01826a49SYabin Cui if (maxNbBits == 0) maxNbBits = HUF_TABLELOG_DEFAULT;
773*01826a49SYabin Cui if (maxSymbolValue > HUF_SYMBOLVALUE_MAX)
774*01826a49SYabin Cui return ERROR(maxSymbolValue_tooLarge);
775*01826a49SYabin Cui ZSTD_memset(huffNode0, 0, sizeof(huffNodeTable));
776*01826a49SYabin Cui
777*01826a49SYabin Cui /* sort, decreasing order */
778*01826a49SYabin Cui HUF_sort(huffNode, count, maxSymbolValue, wksp_tables->rankPosition);
779*01826a49SYabin Cui DEBUGLOG(6, "sorted symbols completed (%zu symbols)", showHNodeSymbols(huffNode, maxSymbolValue+1));
780*01826a49SYabin Cui
781*01826a49SYabin Cui /* build tree */
782*01826a49SYabin Cui nonNullRank = HUF_buildTree(huffNode, maxSymbolValue);
783*01826a49SYabin Cui
784*01826a49SYabin Cui /* determine and enforce maxTableLog */
785*01826a49SYabin Cui maxNbBits = HUF_setMaxHeight(huffNode, (U32)nonNullRank, maxNbBits);
786*01826a49SYabin Cui if (maxNbBits > HUF_TABLELOG_MAX) return ERROR(GENERIC); /* check fit into table */
787*01826a49SYabin Cui
788*01826a49SYabin Cui HUF_buildCTableFromTree(CTable, huffNode, nonNullRank, maxSymbolValue, maxNbBits);
789*01826a49SYabin Cui
790*01826a49SYabin Cui return maxNbBits;
791*01826a49SYabin Cui }
792*01826a49SYabin Cui
HUF_estimateCompressedSize(const HUF_CElt * CTable,const unsigned * count,unsigned maxSymbolValue)793*01826a49SYabin Cui size_t HUF_estimateCompressedSize(const HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue)
794*01826a49SYabin Cui {
795*01826a49SYabin Cui HUF_CElt const* ct = CTable + 1;
796*01826a49SYabin Cui size_t nbBits = 0;
797*01826a49SYabin Cui int s;
798*01826a49SYabin Cui for (s = 0; s <= (int)maxSymbolValue; ++s) {
799*01826a49SYabin Cui nbBits += HUF_getNbBits(ct[s]) * count[s];
800*01826a49SYabin Cui }
801*01826a49SYabin Cui return nbBits >> 3;
802*01826a49SYabin Cui }
803*01826a49SYabin Cui
HUF_validateCTable(const HUF_CElt * CTable,const unsigned * count,unsigned maxSymbolValue)804*01826a49SYabin Cui int HUF_validateCTable(const HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue) {
805*01826a49SYabin Cui HUF_CTableHeader header = HUF_readCTableHeader(CTable);
806*01826a49SYabin Cui HUF_CElt const* ct = CTable + 1;
807*01826a49SYabin Cui int bad = 0;
808*01826a49SYabin Cui int s;
809*01826a49SYabin Cui
810*01826a49SYabin Cui assert(header.tableLog <= HUF_TABLELOG_ABSOLUTEMAX);
811*01826a49SYabin Cui
812*01826a49SYabin Cui if (header.maxSymbolValue < maxSymbolValue)
813*01826a49SYabin Cui return 0;
814*01826a49SYabin Cui
815*01826a49SYabin Cui for (s = 0; s <= (int)maxSymbolValue; ++s) {
816*01826a49SYabin Cui bad |= (count[s] != 0) & (HUF_getNbBits(ct[s]) == 0);
817*01826a49SYabin Cui }
818*01826a49SYabin Cui return !bad;
819*01826a49SYabin Cui }
820*01826a49SYabin Cui
HUF_compressBound(size_t size)821*01826a49SYabin Cui size_t HUF_compressBound(size_t size) { return HUF_COMPRESSBOUND(size); }
822*01826a49SYabin Cui
823*01826a49SYabin Cui /** HUF_CStream_t:
824*01826a49SYabin Cui * Huffman uses its own BIT_CStream_t implementation.
825*01826a49SYabin Cui * There are three major differences from BIT_CStream_t:
826*01826a49SYabin Cui * 1. HUF_addBits() takes a HUF_CElt (size_t) which is
827*01826a49SYabin Cui * the pair (nbBits, value) in the format:
828*01826a49SYabin Cui * format:
829*01826a49SYabin Cui * - Bits [0, 4) = nbBits
830*01826a49SYabin Cui * - Bits [4, 64 - nbBits) = 0
831*01826a49SYabin Cui * - Bits [64 - nbBits, 64) = value
832*01826a49SYabin Cui * 2. The bitContainer is built from the upper bits and
833*01826a49SYabin Cui * right shifted. E.g. to add a new value of N bits
834*01826a49SYabin Cui * you right shift the bitContainer by N, then or in
835*01826a49SYabin Cui * the new value into the N upper bits.
836*01826a49SYabin Cui * 3. The bitstream has two bit containers. You can add
837*01826a49SYabin Cui * bits to the second container and merge them into
838*01826a49SYabin Cui * the first container.
839*01826a49SYabin Cui */
840*01826a49SYabin Cui
841*01826a49SYabin Cui #define HUF_BITS_IN_CONTAINER (sizeof(size_t) * 8)
842*01826a49SYabin Cui
843*01826a49SYabin Cui typedef struct {
844*01826a49SYabin Cui size_t bitContainer[2];
845*01826a49SYabin Cui size_t bitPos[2];
846*01826a49SYabin Cui
847*01826a49SYabin Cui BYTE* startPtr;
848*01826a49SYabin Cui BYTE* ptr;
849*01826a49SYabin Cui BYTE* endPtr;
850*01826a49SYabin Cui } HUF_CStream_t;
851*01826a49SYabin Cui
852*01826a49SYabin Cui /**! HUF_initCStream():
853*01826a49SYabin Cui * Initializes the bitstream.
854*01826a49SYabin Cui * @returns 0 or an error code.
855*01826a49SYabin Cui */
HUF_initCStream(HUF_CStream_t * bitC,void * startPtr,size_t dstCapacity)856*01826a49SYabin Cui static size_t HUF_initCStream(HUF_CStream_t* bitC,
857*01826a49SYabin Cui void* startPtr, size_t dstCapacity)
858*01826a49SYabin Cui {
859*01826a49SYabin Cui ZSTD_memset(bitC, 0, sizeof(*bitC));
860*01826a49SYabin Cui bitC->startPtr = (BYTE*)startPtr;
861*01826a49SYabin Cui bitC->ptr = bitC->startPtr;
862*01826a49SYabin Cui bitC->endPtr = bitC->startPtr + dstCapacity - sizeof(bitC->bitContainer[0]);
863*01826a49SYabin Cui if (dstCapacity <= sizeof(bitC->bitContainer[0])) return ERROR(dstSize_tooSmall);
864*01826a49SYabin Cui return 0;
865*01826a49SYabin Cui }
866*01826a49SYabin Cui
867*01826a49SYabin Cui /*! HUF_addBits():
868*01826a49SYabin Cui * Adds the symbol stored in HUF_CElt elt to the bitstream.
869*01826a49SYabin Cui *
870*01826a49SYabin Cui * @param elt The element we're adding. This is a (nbBits, value) pair.
871*01826a49SYabin Cui * See the HUF_CStream_t docs for the format.
872*01826a49SYabin Cui * @param idx Insert into the bitstream at this idx.
873*01826a49SYabin Cui * @param kFast This is a template parameter. If the bitstream is guaranteed
874*01826a49SYabin Cui * to have at least 4 unused bits after this call it may be 1,
875*01826a49SYabin Cui * otherwise it must be 0. HUF_addBits() is faster when fast is set.
876*01826a49SYabin Cui */
HUF_addBits(HUF_CStream_t * bitC,HUF_CElt elt,int idx,int kFast)877*01826a49SYabin Cui FORCE_INLINE_TEMPLATE void HUF_addBits(HUF_CStream_t* bitC, HUF_CElt elt, int idx, int kFast)
878*01826a49SYabin Cui {
879*01826a49SYabin Cui assert(idx <= 1);
880*01826a49SYabin Cui assert(HUF_getNbBits(elt) <= HUF_TABLELOG_ABSOLUTEMAX);
881*01826a49SYabin Cui /* This is efficient on x86-64 with BMI2 because shrx
882*01826a49SYabin Cui * only reads the low 6 bits of the register. The compiler
883*01826a49SYabin Cui * knows this and elides the mask. When fast is set,
884*01826a49SYabin Cui * every operation can use the same value loaded from elt.
885*01826a49SYabin Cui */
886*01826a49SYabin Cui bitC->bitContainer[idx] >>= HUF_getNbBits(elt);
887*01826a49SYabin Cui bitC->bitContainer[idx] |= kFast ? HUF_getValueFast(elt) : HUF_getValue(elt);
888*01826a49SYabin Cui /* We only read the low 8 bits of bitC->bitPos[idx] so it
889*01826a49SYabin Cui * doesn't matter that the high bits have noise from the value.
890*01826a49SYabin Cui */
891*01826a49SYabin Cui bitC->bitPos[idx] += HUF_getNbBitsFast(elt);
892*01826a49SYabin Cui assert((bitC->bitPos[idx] & 0xFF) <= HUF_BITS_IN_CONTAINER);
893*01826a49SYabin Cui /* The last 4-bits of elt are dirty if fast is set,
894*01826a49SYabin Cui * so we must not be overwriting bits that have already been
895*01826a49SYabin Cui * inserted into the bit container.
896*01826a49SYabin Cui */
897*01826a49SYabin Cui #if DEBUGLEVEL >= 1
898*01826a49SYabin Cui {
899*01826a49SYabin Cui size_t const nbBits = HUF_getNbBits(elt);
900*01826a49SYabin Cui size_t const dirtyBits = nbBits == 0 ? 0 : ZSTD_highbit32((U32)nbBits) + 1;
901*01826a49SYabin Cui (void)dirtyBits;
902*01826a49SYabin Cui /* Middle bits are 0. */
903*01826a49SYabin Cui assert(((elt >> dirtyBits) << (dirtyBits + nbBits)) == 0);
904*01826a49SYabin Cui /* We didn't overwrite any bits in the bit container. */
905*01826a49SYabin Cui assert(!kFast || (bitC->bitPos[idx] & 0xFF) <= HUF_BITS_IN_CONTAINER);
906*01826a49SYabin Cui (void)dirtyBits;
907*01826a49SYabin Cui }
908*01826a49SYabin Cui #endif
909*01826a49SYabin Cui }
910*01826a49SYabin Cui
HUF_zeroIndex1(HUF_CStream_t * bitC)911*01826a49SYabin Cui FORCE_INLINE_TEMPLATE void HUF_zeroIndex1(HUF_CStream_t* bitC)
912*01826a49SYabin Cui {
913*01826a49SYabin Cui bitC->bitContainer[1] = 0;
914*01826a49SYabin Cui bitC->bitPos[1] = 0;
915*01826a49SYabin Cui }
916*01826a49SYabin Cui
917*01826a49SYabin Cui /*! HUF_mergeIndex1() :
918*01826a49SYabin Cui * Merges the bit container @ index 1 into the bit container @ index 0
919*01826a49SYabin Cui * and zeros the bit container @ index 1.
920*01826a49SYabin Cui */
HUF_mergeIndex1(HUF_CStream_t * bitC)921*01826a49SYabin Cui FORCE_INLINE_TEMPLATE void HUF_mergeIndex1(HUF_CStream_t* bitC)
922*01826a49SYabin Cui {
923*01826a49SYabin Cui assert((bitC->bitPos[1] & 0xFF) < HUF_BITS_IN_CONTAINER);
924*01826a49SYabin Cui bitC->bitContainer[0] >>= (bitC->bitPos[1] & 0xFF);
925*01826a49SYabin Cui bitC->bitContainer[0] |= bitC->bitContainer[1];
926*01826a49SYabin Cui bitC->bitPos[0] += bitC->bitPos[1];
927*01826a49SYabin Cui assert((bitC->bitPos[0] & 0xFF) <= HUF_BITS_IN_CONTAINER);
928*01826a49SYabin Cui }
929*01826a49SYabin Cui
930*01826a49SYabin Cui /*! HUF_flushBits() :
931*01826a49SYabin Cui * Flushes the bits in the bit container @ index 0.
932*01826a49SYabin Cui *
933*01826a49SYabin Cui * @post bitPos will be < 8.
934*01826a49SYabin Cui * @param kFast If kFast is set then we must know a-priori that
935*01826a49SYabin Cui * the bit container will not overflow.
936*01826a49SYabin Cui */
HUF_flushBits(HUF_CStream_t * bitC,int kFast)937*01826a49SYabin Cui FORCE_INLINE_TEMPLATE void HUF_flushBits(HUF_CStream_t* bitC, int kFast)
938*01826a49SYabin Cui {
939*01826a49SYabin Cui /* The upper bits of bitPos are noisy, so we must mask by 0xFF. */
940*01826a49SYabin Cui size_t const nbBits = bitC->bitPos[0] & 0xFF;
941*01826a49SYabin Cui size_t const nbBytes = nbBits >> 3;
942*01826a49SYabin Cui /* The top nbBits bits of bitContainer are the ones we need. */
943*01826a49SYabin Cui size_t const bitContainer = bitC->bitContainer[0] >> (HUF_BITS_IN_CONTAINER - nbBits);
944*01826a49SYabin Cui /* Mask bitPos to account for the bytes we consumed. */
945*01826a49SYabin Cui bitC->bitPos[0] &= 7;
946*01826a49SYabin Cui assert(nbBits > 0);
947*01826a49SYabin Cui assert(nbBits <= sizeof(bitC->bitContainer[0]) * 8);
948*01826a49SYabin Cui assert(bitC->ptr <= bitC->endPtr);
949*01826a49SYabin Cui MEM_writeLEST(bitC->ptr, bitContainer);
950*01826a49SYabin Cui bitC->ptr += nbBytes;
951*01826a49SYabin Cui assert(!kFast || bitC->ptr <= bitC->endPtr);
952*01826a49SYabin Cui if (!kFast && bitC->ptr > bitC->endPtr) bitC->ptr = bitC->endPtr;
953*01826a49SYabin Cui /* bitContainer doesn't need to be modified because the leftover
954*01826a49SYabin Cui * bits are already the top bitPos bits. And we don't care about
955*01826a49SYabin Cui * noise in the lower values.
956*01826a49SYabin Cui */
957*01826a49SYabin Cui }
958*01826a49SYabin Cui
959*01826a49SYabin Cui /*! HUF_endMark()
960*01826a49SYabin Cui * @returns The Huffman stream end mark: A 1-bit value = 1.
961*01826a49SYabin Cui */
HUF_endMark(void)962*01826a49SYabin Cui static HUF_CElt HUF_endMark(void)
963*01826a49SYabin Cui {
964*01826a49SYabin Cui HUF_CElt endMark;
965*01826a49SYabin Cui HUF_setNbBits(&endMark, 1);
966*01826a49SYabin Cui HUF_setValue(&endMark, 1);
967*01826a49SYabin Cui return endMark;
968*01826a49SYabin Cui }
969*01826a49SYabin Cui
970*01826a49SYabin Cui /*! HUF_closeCStream() :
971*01826a49SYabin Cui * @return Size of CStream, in bytes,
972*01826a49SYabin Cui * or 0 if it could not fit into dstBuffer */
HUF_closeCStream(HUF_CStream_t * bitC)973*01826a49SYabin Cui static size_t HUF_closeCStream(HUF_CStream_t* bitC)
974*01826a49SYabin Cui {
975*01826a49SYabin Cui HUF_addBits(bitC, HUF_endMark(), /* idx */ 0, /* kFast */ 0);
976*01826a49SYabin Cui HUF_flushBits(bitC, /* kFast */ 0);
977*01826a49SYabin Cui {
978*01826a49SYabin Cui size_t const nbBits = bitC->bitPos[0] & 0xFF;
979*01826a49SYabin Cui if (bitC->ptr >= bitC->endPtr) return 0; /* overflow detected */
980*01826a49SYabin Cui return (size_t)(bitC->ptr - bitC->startPtr) + (nbBits > 0);
981*01826a49SYabin Cui }
982*01826a49SYabin Cui }
983*01826a49SYabin Cui
984*01826a49SYabin Cui FORCE_INLINE_TEMPLATE void
HUF_encodeSymbol(HUF_CStream_t * bitCPtr,U32 symbol,const HUF_CElt * CTable,int idx,int fast)985*01826a49SYabin Cui HUF_encodeSymbol(HUF_CStream_t* bitCPtr, U32 symbol, const HUF_CElt* CTable, int idx, int fast)
986*01826a49SYabin Cui {
987*01826a49SYabin Cui HUF_addBits(bitCPtr, CTable[symbol], idx, fast);
988*01826a49SYabin Cui }
989*01826a49SYabin Cui
990*01826a49SYabin Cui FORCE_INLINE_TEMPLATE void
HUF_compress1X_usingCTable_internal_body_loop(HUF_CStream_t * bitC,const BYTE * ip,size_t srcSize,const HUF_CElt * ct,int kUnroll,int kFastFlush,int kLastFast)991*01826a49SYabin Cui HUF_compress1X_usingCTable_internal_body_loop(HUF_CStream_t* bitC,
992*01826a49SYabin Cui const BYTE* ip, size_t srcSize,
993*01826a49SYabin Cui const HUF_CElt* ct,
994*01826a49SYabin Cui int kUnroll, int kFastFlush, int kLastFast)
995*01826a49SYabin Cui {
996*01826a49SYabin Cui /* Join to kUnroll */
997*01826a49SYabin Cui int n = (int)srcSize;
998*01826a49SYabin Cui int rem = n % kUnroll;
999*01826a49SYabin Cui if (rem > 0) {
1000*01826a49SYabin Cui for (; rem > 0; --rem) {
1001*01826a49SYabin Cui HUF_encodeSymbol(bitC, ip[--n], ct, 0, /* fast */ 0);
1002*01826a49SYabin Cui }
1003*01826a49SYabin Cui HUF_flushBits(bitC, kFastFlush);
1004*01826a49SYabin Cui }
1005*01826a49SYabin Cui assert(n % kUnroll == 0);
1006*01826a49SYabin Cui
1007*01826a49SYabin Cui /* Join to 2 * kUnroll */
1008*01826a49SYabin Cui if (n % (2 * kUnroll)) {
1009*01826a49SYabin Cui int u;
1010*01826a49SYabin Cui for (u = 1; u < kUnroll; ++u) {
1011*01826a49SYabin Cui HUF_encodeSymbol(bitC, ip[n - u], ct, 0, 1);
1012*01826a49SYabin Cui }
1013*01826a49SYabin Cui HUF_encodeSymbol(bitC, ip[n - kUnroll], ct, 0, kLastFast);
1014*01826a49SYabin Cui HUF_flushBits(bitC, kFastFlush);
1015*01826a49SYabin Cui n -= kUnroll;
1016*01826a49SYabin Cui }
1017*01826a49SYabin Cui assert(n % (2 * kUnroll) == 0);
1018*01826a49SYabin Cui
1019*01826a49SYabin Cui for (; n>0; n-= 2 * kUnroll) {
1020*01826a49SYabin Cui /* Encode kUnroll symbols into the bitstream @ index 0. */
1021*01826a49SYabin Cui int u;
1022*01826a49SYabin Cui for (u = 1; u < kUnroll; ++u) {
1023*01826a49SYabin Cui HUF_encodeSymbol(bitC, ip[n - u], ct, /* idx */ 0, /* fast */ 1);
1024*01826a49SYabin Cui }
1025*01826a49SYabin Cui HUF_encodeSymbol(bitC, ip[n - kUnroll], ct, /* idx */ 0, /* fast */ kLastFast);
1026*01826a49SYabin Cui HUF_flushBits(bitC, kFastFlush);
1027*01826a49SYabin Cui /* Encode kUnroll symbols into the bitstream @ index 1.
1028*01826a49SYabin Cui * This allows us to start filling the bit container
1029*01826a49SYabin Cui * without any data dependencies.
1030*01826a49SYabin Cui */
1031*01826a49SYabin Cui HUF_zeroIndex1(bitC);
1032*01826a49SYabin Cui for (u = 1; u < kUnroll; ++u) {
1033*01826a49SYabin Cui HUF_encodeSymbol(bitC, ip[n - kUnroll - u], ct, /* idx */ 1, /* fast */ 1);
1034*01826a49SYabin Cui }
1035*01826a49SYabin Cui HUF_encodeSymbol(bitC, ip[n - kUnroll - kUnroll], ct, /* idx */ 1, /* fast */ kLastFast);
1036*01826a49SYabin Cui /* Merge bitstream @ index 1 into the bitstream @ index 0 */
1037*01826a49SYabin Cui HUF_mergeIndex1(bitC);
1038*01826a49SYabin Cui HUF_flushBits(bitC, kFastFlush);
1039*01826a49SYabin Cui }
1040*01826a49SYabin Cui assert(n == 0);
1041*01826a49SYabin Cui
1042*01826a49SYabin Cui }
1043*01826a49SYabin Cui
1044*01826a49SYabin Cui /**
1045*01826a49SYabin Cui * Returns a tight upper bound on the output space needed by Huffman
1046*01826a49SYabin Cui * with 8 bytes buffer to handle over-writes. If the output is at least
1047*01826a49SYabin Cui * this large we don't need to do bounds checks during Huffman encoding.
1048*01826a49SYabin Cui */
HUF_tightCompressBound(size_t srcSize,size_t tableLog)1049*01826a49SYabin Cui static size_t HUF_tightCompressBound(size_t srcSize, size_t tableLog)
1050*01826a49SYabin Cui {
1051*01826a49SYabin Cui return ((srcSize * tableLog) >> 3) + 8;
1052*01826a49SYabin Cui }
1053*01826a49SYabin Cui
1054*01826a49SYabin Cui
1055*01826a49SYabin Cui FORCE_INLINE_TEMPLATE size_t
HUF_compress1X_usingCTable_internal_body(void * dst,size_t dstSize,const void * src,size_t srcSize,const HUF_CElt * CTable)1056*01826a49SYabin Cui HUF_compress1X_usingCTable_internal_body(void* dst, size_t dstSize,
1057*01826a49SYabin Cui const void* src, size_t srcSize,
1058*01826a49SYabin Cui const HUF_CElt* CTable)
1059*01826a49SYabin Cui {
1060*01826a49SYabin Cui U32 const tableLog = HUF_readCTableHeader(CTable).tableLog;
1061*01826a49SYabin Cui HUF_CElt const* ct = CTable + 1;
1062*01826a49SYabin Cui const BYTE* ip = (const BYTE*) src;
1063*01826a49SYabin Cui BYTE* const ostart = (BYTE*)dst;
1064*01826a49SYabin Cui BYTE* const oend = ostart + dstSize;
1065*01826a49SYabin Cui HUF_CStream_t bitC;
1066*01826a49SYabin Cui
1067*01826a49SYabin Cui /* init */
1068*01826a49SYabin Cui if (dstSize < 8) return 0; /* not enough space to compress */
1069*01826a49SYabin Cui { BYTE* op = ostart;
1070*01826a49SYabin Cui size_t const initErr = HUF_initCStream(&bitC, op, (size_t)(oend-op));
1071*01826a49SYabin Cui if (HUF_isError(initErr)) return 0; }
1072*01826a49SYabin Cui
1073*01826a49SYabin Cui if (dstSize < HUF_tightCompressBound(srcSize, (size_t)tableLog) || tableLog > 11)
1074*01826a49SYabin Cui HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ MEM_32bits() ? 2 : 4, /* kFast */ 0, /* kLastFast */ 0);
1075*01826a49SYabin Cui else {
1076*01826a49SYabin Cui if (MEM_32bits()) {
1077*01826a49SYabin Cui switch (tableLog) {
1078*01826a49SYabin Cui case 11:
1079*01826a49SYabin Cui HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 2, /* kFastFlush */ 1, /* kLastFast */ 0);
1080*01826a49SYabin Cui break;
1081*01826a49SYabin Cui case 10: ZSTD_FALLTHROUGH;
1082*01826a49SYabin Cui case 9: ZSTD_FALLTHROUGH;
1083*01826a49SYabin Cui case 8:
1084*01826a49SYabin Cui HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 2, /* kFastFlush */ 1, /* kLastFast */ 1);
1085*01826a49SYabin Cui break;
1086*01826a49SYabin Cui case 7: ZSTD_FALLTHROUGH;
1087*01826a49SYabin Cui default:
1088*01826a49SYabin Cui HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 3, /* kFastFlush */ 1, /* kLastFast */ 1);
1089*01826a49SYabin Cui break;
1090*01826a49SYabin Cui }
1091*01826a49SYabin Cui } else {
1092*01826a49SYabin Cui switch (tableLog) {
1093*01826a49SYabin Cui case 11:
1094*01826a49SYabin Cui HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 5, /* kFastFlush */ 1, /* kLastFast */ 0);
1095*01826a49SYabin Cui break;
1096*01826a49SYabin Cui case 10:
1097*01826a49SYabin Cui HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 5, /* kFastFlush */ 1, /* kLastFast */ 1);
1098*01826a49SYabin Cui break;
1099*01826a49SYabin Cui case 9:
1100*01826a49SYabin Cui HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 6, /* kFastFlush */ 1, /* kLastFast */ 0);
1101*01826a49SYabin Cui break;
1102*01826a49SYabin Cui case 8:
1103*01826a49SYabin Cui HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 7, /* kFastFlush */ 1, /* kLastFast */ 0);
1104*01826a49SYabin Cui break;
1105*01826a49SYabin Cui case 7:
1106*01826a49SYabin Cui HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 8, /* kFastFlush */ 1, /* kLastFast */ 0);
1107*01826a49SYabin Cui break;
1108*01826a49SYabin Cui case 6: ZSTD_FALLTHROUGH;
1109*01826a49SYabin Cui default:
1110*01826a49SYabin Cui HUF_compress1X_usingCTable_internal_body_loop(&bitC, ip, srcSize, ct, /* kUnroll */ 9, /* kFastFlush */ 1, /* kLastFast */ 1);
1111*01826a49SYabin Cui break;
1112*01826a49SYabin Cui }
1113*01826a49SYabin Cui }
1114*01826a49SYabin Cui }
1115*01826a49SYabin Cui assert(bitC.ptr <= bitC.endPtr);
1116*01826a49SYabin Cui
1117*01826a49SYabin Cui return HUF_closeCStream(&bitC);
1118*01826a49SYabin Cui }
1119*01826a49SYabin Cui
1120*01826a49SYabin Cui #if DYNAMIC_BMI2
1121*01826a49SYabin Cui
1122*01826a49SYabin Cui static BMI2_TARGET_ATTRIBUTE size_t
HUF_compress1X_usingCTable_internal_bmi2(void * dst,size_t dstSize,const void * src,size_t srcSize,const HUF_CElt * CTable)1123*01826a49SYabin Cui HUF_compress1X_usingCTable_internal_bmi2(void* dst, size_t dstSize,
1124*01826a49SYabin Cui const void* src, size_t srcSize,
1125*01826a49SYabin Cui const HUF_CElt* CTable)
1126*01826a49SYabin Cui {
1127*01826a49SYabin Cui return HUF_compress1X_usingCTable_internal_body(dst, dstSize, src, srcSize, CTable);
1128*01826a49SYabin Cui }
1129*01826a49SYabin Cui
1130*01826a49SYabin Cui static size_t
HUF_compress1X_usingCTable_internal_default(void * dst,size_t dstSize,const void * src,size_t srcSize,const HUF_CElt * CTable)1131*01826a49SYabin Cui HUF_compress1X_usingCTable_internal_default(void* dst, size_t dstSize,
1132*01826a49SYabin Cui const void* src, size_t srcSize,
1133*01826a49SYabin Cui const HUF_CElt* CTable)
1134*01826a49SYabin Cui {
1135*01826a49SYabin Cui return HUF_compress1X_usingCTable_internal_body(dst, dstSize, src, srcSize, CTable);
1136*01826a49SYabin Cui }
1137*01826a49SYabin Cui
1138*01826a49SYabin Cui static size_t
HUF_compress1X_usingCTable_internal(void * dst,size_t dstSize,const void * src,size_t srcSize,const HUF_CElt * CTable,const int flags)1139*01826a49SYabin Cui HUF_compress1X_usingCTable_internal(void* dst, size_t dstSize,
1140*01826a49SYabin Cui const void* src, size_t srcSize,
1141*01826a49SYabin Cui const HUF_CElt* CTable, const int flags)
1142*01826a49SYabin Cui {
1143*01826a49SYabin Cui if (flags & HUF_flags_bmi2) {
1144*01826a49SYabin Cui return HUF_compress1X_usingCTable_internal_bmi2(dst, dstSize, src, srcSize, CTable);
1145*01826a49SYabin Cui }
1146*01826a49SYabin Cui return HUF_compress1X_usingCTable_internal_default(dst, dstSize, src, srcSize, CTable);
1147*01826a49SYabin Cui }
1148*01826a49SYabin Cui
1149*01826a49SYabin Cui #else
1150*01826a49SYabin Cui
1151*01826a49SYabin Cui static size_t
HUF_compress1X_usingCTable_internal(void * dst,size_t dstSize,const void * src,size_t srcSize,const HUF_CElt * CTable,const int flags)1152*01826a49SYabin Cui HUF_compress1X_usingCTable_internal(void* dst, size_t dstSize,
1153*01826a49SYabin Cui const void* src, size_t srcSize,
1154*01826a49SYabin Cui const HUF_CElt* CTable, const int flags)
1155*01826a49SYabin Cui {
1156*01826a49SYabin Cui (void)flags;
1157*01826a49SYabin Cui return HUF_compress1X_usingCTable_internal_body(dst, dstSize, src, srcSize, CTable);
1158*01826a49SYabin Cui }
1159*01826a49SYabin Cui
1160*01826a49SYabin Cui #endif
1161*01826a49SYabin Cui
HUF_compress1X_usingCTable(void * dst,size_t dstSize,const void * src,size_t srcSize,const HUF_CElt * CTable,int flags)1162*01826a49SYabin Cui size_t HUF_compress1X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable, int flags)
1163*01826a49SYabin Cui {
1164*01826a49SYabin Cui return HUF_compress1X_usingCTable_internal(dst, dstSize, src, srcSize, CTable, flags);
1165*01826a49SYabin Cui }
1166*01826a49SYabin Cui
1167*01826a49SYabin Cui static size_t
HUF_compress4X_usingCTable_internal(void * dst,size_t dstSize,const void * src,size_t srcSize,const HUF_CElt * CTable,int flags)1168*01826a49SYabin Cui HUF_compress4X_usingCTable_internal(void* dst, size_t dstSize,
1169*01826a49SYabin Cui const void* src, size_t srcSize,
1170*01826a49SYabin Cui const HUF_CElt* CTable, int flags)
1171*01826a49SYabin Cui {
1172*01826a49SYabin Cui size_t const segmentSize = (srcSize+3)/4; /* first 3 segments */
1173*01826a49SYabin Cui const BYTE* ip = (const BYTE*) src;
1174*01826a49SYabin Cui const BYTE* const iend = ip + srcSize;
1175*01826a49SYabin Cui BYTE* const ostart = (BYTE*) dst;
1176*01826a49SYabin Cui BYTE* const oend = ostart + dstSize;
1177*01826a49SYabin Cui BYTE* op = ostart;
1178*01826a49SYabin Cui
1179*01826a49SYabin Cui if (dstSize < 6 + 1 + 1 + 1 + 8) return 0; /* minimum space to compress successfully */
1180*01826a49SYabin Cui if (srcSize < 12) return 0; /* no saving possible : too small input */
1181*01826a49SYabin Cui op += 6; /* jumpTable */
1182*01826a49SYabin Cui
1183*01826a49SYabin Cui assert(op <= oend);
1184*01826a49SYabin Cui { CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, (size_t)(oend-op), ip, segmentSize, CTable, flags) );
1185*01826a49SYabin Cui if (cSize == 0 || cSize > 65535) return 0;
1186*01826a49SYabin Cui MEM_writeLE16(ostart, (U16)cSize);
1187*01826a49SYabin Cui op += cSize;
1188*01826a49SYabin Cui }
1189*01826a49SYabin Cui
1190*01826a49SYabin Cui ip += segmentSize;
1191*01826a49SYabin Cui assert(op <= oend);
1192*01826a49SYabin Cui { CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, (size_t)(oend-op), ip, segmentSize, CTable, flags) );
1193*01826a49SYabin Cui if (cSize == 0 || cSize > 65535) return 0;
1194*01826a49SYabin Cui MEM_writeLE16(ostart+2, (U16)cSize);
1195*01826a49SYabin Cui op += cSize;
1196*01826a49SYabin Cui }
1197*01826a49SYabin Cui
1198*01826a49SYabin Cui ip += segmentSize;
1199*01826a49SYabin Cui assert(op <= oend);
1200*01826a49SYabin Cui { CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, (size_t)(oend-op), ip, segmentSize, CTable, flags) );
1201*01826a49SYabin Cui if (cSize == 0 || cSize > 65535) return 0;
1202*01826a49SYabin Cui MEM_writeLE16(ostart+4, (U16)cSize);
1203*01826a49SYabin Cui op += cSize;
1204*01826a49SYabin Cui }
1205*01826a49SYabin Cui
1206*01826a49SYabin Cui ip += segmentSize;
1207*01826a49SYabin Cui assert(op <= oend);
1208*01826a49SYabin Cui assert(ip <= iend);
1209*01826a49SYabin Cui { CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, (size_t)(oend-op), ip, (size_t)(iend-ip), CTable, flags) );
1210*01826a49SYabin Cui if (cSize == 0 || cSize > 65535) return 0;
1211*01826a49SYabin Cui op += cSize;
1212*01826a49SYabin Cui }
1213*01826a49SYabin Cui
1214*01826a49SYabin Cui return (size_t)(op-ostart);
1215*01826a49SYabin Cui }
1216*01826a49SYabin Cui
HUF_compress4X_usingCTable(void * dst,size_t dstSize,const void * src,size_t srcSize,const HUF_CElt * CTable,int flags)1217*01826a49SYabin Cui size_t HUF_compress4X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable, int flags)
1218*01826a49SYabin Cui {
1219*01826a49SYabin Cui return HUF_compress4X_usingCTable_internal(dst, dstSize, src, srcSize, CTable, flags);
1220*01826a49SYabin Cui }
1221*01826a49SYabin Cui
1222*01826a49SYabin Cui typedef enum { HUF_singleStream, HUF_fourStreams } HUF_nbStreams_e;
1223*01826a49SYabin Cui
HUF_compressCTable_internal(BYTE * const ostart,BYTE * op,BYTE * const oend,const void * src,size_t srcSize,HUF_nbStreams_e nbStreams,const HUF_CElt * CTable,const int flags)1224*01826a49SYabin Cui static size_t HUF_compressCTable_internal(
1225*01826a49SYabin Cui BYTE* const ostart, BYTE* op, BYTE* const oend,
1226*01826a49SYabin Cui const void* src, size_t srcSize,
1227*01826a49SYabin Cui HUF_nbStreams_e nbStreams, const HUF_CElt* CTable, const int flags)
1228*01826a49SYabin Cui {
1229*01826a49SYabin Cui size_t const cSize = (nbStreams==HUF_singleStream) ?
1230*01826a49SYabin Cui HUF_compress1X_usingCTable_internal(op, (size_t)(oend - op), src, srcSize, CTable, flags) :
1231*01826a49SYabin Cui HUF_compress4X_usingCTable_internal(op, (size_t)(oend - op), src, srcSize, CTable, flags);
1232*01826a49SYabin Cui if (HUF_isError(cSize)) { return cSize; }
1233*01826a49SYabin Cui if (cSize==0) { return 0; } /* uncompressible */
1234*01826a49SYabin Cui op += cSize;
1235*01826a49SYabin Cui /* check compressibility */
1236*01826a49SYabin Cui assert(op >= ostart);
1237*01826a49SYabin Cui if ((size_t)(op-ostart) >= srcSize-1) { return 0; }
1238*01826a49SYabin Cui return (size_t)(op-ostart);
1239*01826a49SYabin Cui }
1240*01826a49SYabin Cui
1241*01826a49SYabin Cui typedef struct {
1242*01826a49SYabin Cui unsigned count[HUF_SYMBOLVALUE_MAX + 1];
1243*01826a49SYabin Cui HUF_CElt CTable[HUF_CTABLE_SIZE_ST(HUF_SYMBOLVALUE_MAX)];
1244*01826a49SYabin Cui union {
1245*01826a49SYabin Cui HUF_buildCTable_wksp_tables buildCTable_wksp;
1246*01826a49SYabin Cui HUF_WriteCTableWksp writeCTable_wksp;
1247*01826a49SYabin Cui U32 hist_wksp[HIST_WKSP_SIZE_U32];
1248*01826a49SYabin Cui } wksps;
1249*01826a49SYabin Cui } HUF_compress_tables_t;
1250*01826a49SYabin Cui
1251*01826a49SYabin Cui #define SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE 4096
1252*01826a49SYabin Cui #define SUSPECT_INCOMPRESSIBLE_SAMPLE_RATIO 10 /* Must be >= 2 */
1253*01826a49SYabin Cui
HUF_cardinality(const unsigned * count,unsigned maxSymbolValue)1254*01826a49SYabin Cui unsigned HUF_cardinality(const unsigned* count, unsigned maxSymbolValue)
1255*01826a49SYabin Cui {
1256*01826a49SYabin Cui unsigned cardinality = 0;
1257*01826a49SYabin Cui unsigned i;
1258*01826a49SYabin Cui
1259*01826a49SYabin Cui for (i = 0; i < maxSymbolValue + 1; i++) {
1260*01826a49SYabin Cui if (count[i] != 0) cardinality += 1;
1261*01826a49SYabin Cui }
1262*01826a49SYabin Cui
1263*01826a49SYabin Cui return cardinality;
1264*01826a49SYabin Cui }
1265*01826a49SYabin Cui
HUF_minTableLog(unsigned symbolCardinality)1266*01826a49SYabin Cui unsigned HUF_minTableLog(unsigned symbolCardinality)
1267*01826a49SYabin Cui {
1268*01826a49SYabin Cui U32 minBitsSymbols = ZSTD_highbit32(symbolCardinality) + 1;
1269*01826a49SYabin Cui return minBitsSymbols;
1270*01826a49SYabin Cui }
1271*01826a49SYabin Cui
HUF_optimalTableLog(unsigned maxTableLog,size_t srcSize,unsigned maxSymbolValue,void * workSpace,size_t wkspSize,HUF_CElt * table,const unsigned * count,int flags)1272*01826a49SYabin Cui unsigned HUF_optimalTableLog(
1273*01826a49SYabin Cui unsigned maxTableLog,
1274*01826a49SYabin Cui size_t srcSize,
1275*01826a49SYabin Cui unsigned maxSymbolValue,
1276*01826a49SYabin Cui void* workSpace, size_t wkspSize,
1277*01826a49SYabin Cui HUF_CElt* table,
1278*01826a49SYabin Cui const unsigned* count,
1279*01826a49SYabin Cui int flags)
1280*01826a49SYabin Cui {
1281*01826a49SYabin Cui assert(srcSize > 1); /* Not supported, RLE should be used instead */
1282*01826a49SYabin Cui assert(wkspSize >= sizeof(HUF_buildCTable_wksp_tables));
1283*01826a49SYabin Cui
1284*01826a49SYabin Cui if (!(flags & HUF_flags_optimalDepth)) {
1285*01826a49SYabin Cui /* cheap evaluation, based on FSE */
1286*01826a49SYabin Cui return FSE_optimalTableLog_internal(maxTableLog, srcSize, maxSymbolValue, 1);
1287*01826a49SYabin Cui }
1288*01826a49SYabin Cui
1289*01826a49SYabin Cui { BYTE* dst = (BYTE*)workSpace + sizeof(HUF_WriteCTableWksp);
1290*01826a49SYabin Cui size_t dstSize = wkspSize - sizeof(HUF_WriteCTableWksp);
1291*01826a49SYabin Cui size_t hSize, newSize;
1292*01826a49SYabin Cui const unsigned symbolCardinality = HUF_cardinality(count, maxSymbolValue);
1293*01826a49SYabin Cui const unsigned minTableLog = HUF_minTableLog(symbolCardinality);
1294*01826a49SYabin Cui size_t optSize = ((size_t) ~0) - 1;
1295*01826a49SYabin Cui unsigned optLog = maxTableLog, optLogGuess;
1296*01826a49SYabin Cui
1297*01826a49SYabin Cui DEBUGLOG(6, "HUF_optimalTableLog: probing huf depth (srcSize=%zu)", srcSize);
1298*01826a49SYabin Cui
1299*01826a49SYabin Cui /* Search until size increases */
1300*01826a49SYabin Cui for (optLogGuess = minTableLog; optLogGuess <= maxTableLog; optLogGuess++) {
1301*01826a49SYabin Cui DEBUGLOG(7, "checking for huffLog=%u", optLogGuess);
1302*01826a49SYabin Cui
1303*01826a49SYabin Cui { size_t maxBits = HUF_buildCTable_wksp(table, count, maxSymbolValue, optLogGuess, workSpace, wkspSize);
1304*01826a49SYabin Cui if (ERR_isError(maxBits)) continue;
1305*01826a49SYabin Cui
1306*01826a49SYabin Cui if (maxBits < optLogGuess && optLogGuess > minTableLog) break;
1307*01826a49SYabin Cui
1308*01826a49SYabin Cui hSize = HUF_writeCTable_wksp(dst, dstSize, table, maxSymbolValue, (U32)maxBits, workSpace, wkspSize);
1309*01826a49SYabin Cui }
1310*01826a49SYabin Cui
1311*01826a49SYabin Cui if (ERR_isError(hSize)) continue;
1312*01826a49SYabin Cui
1313*01826a49SYabin Cui newSize = HUF_estimateCompressedSize(table, count, maxSymbolValue) + hSize;
1314*01826a49SYabin Cui
1315*01826a49SYabin Cui if (newSize > optSize + 1) {
1316*01826a49SYabin Cui break;
1317*01826a49SYabin Cui }
1318*01826a49SYabin Cui
1319*01826a49SYabin Cui if (newSize < optSize) {
1320*01826a49SYabin Cui optSize = newSize;
1321*01826a49SYabin Cui optLog = optLogGuess;
1322*01826a49SYabin Cui }
1323*01826a49SYabin Cui }
1324*01826a49SYabin Cui assert(optLog <= HUF_TABLELOG_MAX);
1325*01826a49SYabin Cui return optLog;
1326*01826a49SYabin Cui }
1327*01826a49SYabin Cui }
1328*01826a49SYabin Cui
1329*01826a49SYabin Cui /* HUF_compress_internal() :
1330*01826a49SYabin Cui * `workSpace_align4` must be aligned on 4-bytes boundaries,
1331*01826a49SYabin Cui * and occupies the same space as a table of HUF_WORKSPACE_SIZE_U64 unsigned */
1332*01826a49SYabin Cui static size_t
HUF_compress_internal(void * dst,size_t dstSize,const void * src,size_t srcSize,unsigned maxSymbolValue,unsigned huffLog,HUF_nbStreams_e nbStreams,void * workSpace,size_t wkspSize,HUF_CElt * oldHufTable,HUF_repeat * repeat,int flags)1333*01826a49SYabin Cui HUF_compress_internal (void* dst, size_t dstSize,
1334*01826a49SYabin Cui const void* src, size_t srcSize,
1335*01826a49SYabin Cui unsigned maxSymbolValue, unsigned huffLog,
1336*01826a49SYabin Cui HUF_nbStreams_e nbStreams,
1337*01826a49SYabin Cui void* workSpace, size_t wkspSize,
1338*01826a49SYabin Cui HUF_CElt* oldHufTable, HUF_repeat* repeat, int flags)
1339*01826a49SYabin Cui {
1340*01826a49SYabin Cui HUF_compress_tables_t* const table = (HUF_compress_tables_t*)HUF_alignUpWorkspace(workSpace, &wkspSize, ZSTD_ALIGNOF(size_t));
1341*01826a49SYabin Cui BYTE* const ostart = (BYTE*)dst;
1342*01826a49SYabin Cui BYTE* const oend = ostart + dstSize;
1343*01826a49SYabin Cui BYTE* op = ostart;
1344*01826a49SYabin Cui
1345*01826a49SYabin Cui DEBUGLOG(5, "HUF_compress_internal (srcSize=%zu)", srcSize);
1346*01826a49SYabin Cui HUF_STATIC_ASSERT(sizeof(*table) + HUF_WORKSPACE_MAX_ALIGNMENT <= HUF_WORKSPACE_SIZE);
1347*01826a49SYabin Cui
1348*01826a49SYabin Cui /* checks & inits */
1349*01826a49SYabin Cui if (wkspSize < sizeof(*table)) return ERROR(workSpace_tooSmall);
1350*01826a49SYabin Cui if (!srcSize) return 0; /* Uncompressed */
1351*01826a49SYabin Cui if (!dstSize) return 0; /* cannot fit anything within dst budget */
1352*01826a49SYabin Cui if (srcSize > HUF_BLOCKSIZE_MAX) return ERROR(srcSize_wrong); /* current block size limit */
1353*01826a49SYabin Cui if (huffLog > HUF_TABLELOG_MAX) return ERROR(tableLog_tooLarge);
1354*01826a49SYabin Cui if (maxSymbolValue > HUF_SYMBOLVALUE_MAX) return ERROR(maxSymbolValue_tooLarge);
1355*01826a49SYabin Cui if (!maxSymbolValue) maxSymbolValue = HUF_SYMBOLVALUE_MAX;
1356*01826a49SYabin Cui if (!huffLog) huffLog = HUF_TABLELOG_DEFAULT;
1357*01826a49SYabin Cui
1358*01826a49SYabin Cui /* Heuristic : If old table is valid, use it for small inputs */
1359*01826a49SYabin Cui if ((flags & HUF_flags_preferRepeat) && repeat && *repeat == HUF_repeat_valid) {
1360*01826a49SYabin Cui return HUF_compressCTable_internal(ostart, op, oend,
1361*01826a49SYabin Cui src, srcSize,
1362*01826a49SYabin Cui nbStreams, oldHufTable, flags);
1363*01826a49SYabin Cui }
1364*01826a49SYabin Cui
1365*01826a49SYabin Cui /* If uncompressible data is suspected, do a smaller sampling first */
1366*01826a49SYabin Cui DEBUG_STATIC_ASSERT(SUSPECT_INCOMPRESSIBLE_SAMPLE_RATIO >= 2);
1367*01826a49SYabin Cui if ((flags & HUF_flags_suspectUncompressible) && srcSize >= (SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE * SUSPECT_INCOMPRESSIBLE_SAMPLE_RATIO)) {
1368*01826a49SYabin Cui size_t largestTotal = 0;
1369*01826a49SYabin Cui DEBUGLOG(5, "input suspected incompressible : sampling to check");
1370*01826a49SYabin Cui { unsigned maxSymbolValueBegin = maxSymbolValue;
1371*01826a49SYabin Cui CHECK_V_F(largestBegin, HIST_count_simple (table->count, &maxSymbolValueBegin, (const BYTE*)src, SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE) );
1372*01826a49SYabin Cui largestTotal += largestBegin;
1373*01826a49SYabin Cui }
1374*01826a49SYabin Cui { unsigned maxSymbolValueEnd = maxSymbolValue;
1375*01826a49SYabin Cui CHECK_V_F(largestEnd, HIST_count_simple (table->count, &maxSymbolValueEnd, (const BYTE*)src + srcSize - SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE, SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE) );
1376*01826a49SYabin Cui largestTotal += largestEnd;
1377*01826a49SYabin Cui }
1378*01826a49SYabin Cui if (largestTotal <= ((2 * SUSPECT_INCOMPRESSIBLE_SAMPLE_SIZE) >> 7)+4) return 0; /* heuristic : probably not compressible enough */
1379*01826a49SYabin Cui }
1380*01826a49SYabin Cui
1381*01826a49SYabin Cui /* Scan input and build symbol stats */
1382*01826a49SYabin Cui { CHECK_V_F(largest, HIST_count_wksp (table->count, &maxSymbolValue, (const BYTE*)src, srcSize, table->wksps.hist_wksp, sizeof(table->wksps.hist_wksp)) );
1383*01826a49SYabin Cui if (largest == srcSize) { *ostart = ((const BYTE*)src)[0]; return 1; } /* single symbol, rle */
1384*01826a49SYabin Cui if (largest <= (srcSize >> 7)+4) return 0; /* heuristic : probably not compressible enough */
1385*01826a49SYabin Cui }
1386*01826a49SYabin Cui DEBUGLOG(6, "histogram detail completed (%zu symbols)", showU32(table->count, maxSymbolValue+1));
1387*01826a49SYabin Cui
1388*01826a49SYabin Cui /* Check validity of previous table */
1389*01826a49SYabin Cui if ( repeat
1390*01826a49SYabin Cui && *repeat == HUF_repeat_check
1391*01826a49SYabin Cui && !HUF_validateCTable(oldHufTable, table->count, maxSymbolValue)) {
1392*01826a49SYabin Cui *repeat = HUF_repeat_none;
1393*01826a49SYabin Cui }
1394*01826a49SYabin Cui /* Heuristic : use existing table for small inputs */
1395*01826a49SYabin Cui if ((flags & HUF_flags_preferRepeat) && repeat && *repeat != HUF_repeat_none) {
1396*01826a49SYabin Cui return HUF_compressCTable_internal(ostart, op, oend,
1397*01826a49SYabin Cui src, srcSize,
1398*01826a49SYabin Cui nbStreams, oldHufTable, flags);
1399*01826a49SYabin Cui }
1400*01826a49SYabin Cui
1401*01826a49SYabin Cui /* Build Huffman Tree */
1402*01826a49SYabin Cui huffLog = HUF_optimalTableLog(huffLog, srcSize, maxSymbolValue, &table->wksps, sizeof(table->wksps), table->CTable, table->count, flags);
1403*01826a49SYabin Cui { size_t const maxBits = HUF_buildCTable_wksp(table->CTable, table->count,
1404*01826a49SYabin Cui maxSymbolValue, huffLog,
1405*01826a49SYabin Cui &table->wksps.buildCTable_wksp, sizeof(table->wksps.buildCTable_wksp));
1406*01826a49SYabin Cui CHECK_F(maxBits);
1407*01826a49SYabin Cui huffLog = (U32)maxBits;
1408*01826a49SYabin Cui DEBUGLOG(6, "bit distribution completed (%zu symbols)", showCTableBits(table->CTable + 1, maxSymbolValue+1));
1409*01826a49SYabin Cui }
1410*01826a49SYabin Cui
1411*01826a49SYabin Cui /* Write table description header */
1412*01826a49SYabin Cui { CHECK_V_F(hSize, HUF_writeCTable_wksp(op, dstSize, table->CTable, maxSymbolValue, huffLog,
1413*01826a49SYabin Cui &table->wksps.writeCTable_wksp, sizeof(table->wksps.writeCTable_wksp)) );
1414*01826a49SYabin Cui /* Check if using previous huffman table is beneficial */
1415*01826a49SYabin Cui if (repeat && *repeat != HUF_repeat_none) {
1416*01826a49SYabin Cui size_t const oldSize = HUF_estimateCompressedSize(oldHufTable, table->count, maxSymbolValue);
1417*01826a49SYabin Cui size_t const newSize = HUF_estimateCompressedSize(table->CTable, table->count, maxSymbolValue);
1418*01826a49SYabin Cui if (oldSize <= hSize + newSize || hSize + 12 >= srcSize) {
1419*01826a49SYabin Cui return HUF_compressCTable_internal(ostart, op, oend,
1420*01826a49SYabin Cui src, srcSize,
1421*01826a49SYabin Cui nbStreams, oldHufTable, flags);
1422*01826a49SYabin Cui } }
1423*01826a49SYabin Cui
1424*01826a49SYabin Cui /* Use the new huffman table */
1425*01826a49SYabin Cui if (hSize + 12ul >= srcSize) { return 0; }
1426*01826a49SYabin Cui op += hSize;
1427*01826a49SYabin Cui if (repeat) { *repeat = HUF_repeat_none; }
1428*01826a49SYabin Cui if (oldHufTable)
1429*01826a49SYabin Cui ZSTD_memcpy(oldHufTable, table->CTable, sizeof(table->CTable)); /* Save new table */
1430*01826a49SYabin Cui }
1431*01826a49SYabin Cui return HUF_compressCTable_internal(ostart, op, oend,
1432*01826a49SYabin Cui src, srcSize,
1433*01826a49SYabin Cui nbStreams, table->CTable, flags);
1434*01826a49SYabin Cui }
1435*01826a49SYabin Cui
HUF_compress1X_repeat(void * dst,size_t dstSize,const void * src,size_t srcSize,unsigned maxSymbolValue,unsigned huffLog,void * workSpace,size_t wkspSize,HUF_CElt * hufTable,HUF_repeat * repeat,int flags)1436*01826a49SYabin Cui size_t HUF_compress1X_repeat (void* dst, size_t dstSize,
1437*01826a49SYabin Cui const void* src, size_t srcSize,
1438*01826a49SYabin Cui unsigned maxSymbolValue, unsigned huffLog,
1439*01826a49SYabin Cui void* workSpace, size_t wkspSize,
1440*01826a49SYabin Cui HUF_CElt* hufTable, HUF_repeat* repeat, int flags)
1441*01826a49SYabin Cui {
1442*01826a49SYabin Cui DEBUGLOG(5, "HUF_compress1X_repeat (srcSize = %zu)", srcSize);
1443*01826a49SYabin Cui return HUF_compress_internal(dst, dstSize, src, srcSize,
1444*01826a49SYabin Cui maxSymbolValue, huffLog, HUF_singleStream,
1445*01826a49SYabin Cui workSpace, wkspSize, hufTable,
1446*01826a49SYabin Cui repeat, flags);
1447*01826a49SYabin Cui }
1448*01826a49SYabin Cui
1449*01826a49SYabin Cui /* HUF_compress4X_repeat():
1450*01826a49SYabin Cui * compress input using 4 streams.
1451*01826a49SYabin Cui * consider skipping quickly
1452*01826a49SYabin Cui * reuse an existing huffman compression table */
HUF_compress4X_repeat(void * dst,size_t dstSize,const void * src,size_t srcSize,unsigned maxSymbolValue,unsigned huffLog,void * workSpace,size_t wkspSize,HUF_CElt * hufTable,HUF_repeat * repeat,int flags)1453*01826a49SYabin Cui size_t HUF_compress4X_repeat (void* dst, size_t dstSize,
1454*01826a49SYabin Cui const void* src, size_t srcSize,
1455*01826a49SYabin Cui unsigned maxSymbolValue, unsigned huffLog,
1456*01826a49SYabin Cui void* workSpace, size_t wkspSize,
1457*01826a49SYabin Cui HUF_CElt* hufTable, HUF_repeat* repeat, int flags)
1458*01826a49SYabin Cui {
1459*01826a49SYabin Cui DEBUGLOG(5, "HUF_compress4X_repeat (srcSize = %zu)", srcSize);
1460*01826a49SYabin Cui return HUF_compress_internal(dst, dstSize, src, srcSize,
1461*01826a49SYabin Cui maxSymbolValue, huffLog, HUF_fourStreams,
1462*01826a49SYabin Cui workSpace, wkspSize,
1463*01826a49SYabin Cui hufTable, repeat, flags);
1464*01826a49SYabin Cui }
1465