1 /* ******************************************************************
2  * Huffman encoder, part of New Generation Entropy library
3  * Copyright (c) Yann Collet, Facebook, Inc.
4  *
5  *  You can contact the author at :
6  *  - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy
7  *  - Public forum : https://groups.google.com/forum/#!forum/lz4c
8  *
9  * This source code is licensed under both the BSD-style license (found in the
10  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
11  * in the COPYING file in the root directory of this source tree).
12  * You may select, at your option, one of the above-listed licenses.
13 ****************************************************************** */
14 
15 /* **************************************************************
16 *  Compiler specifics
17 ****************************************************************/
18 #ifdef _MSC_VER    /* Visual Studio */
19 #  pragma warning(disable : 4127)        /* disable: C4127: conditional expression is constant */
20 #endif
21 
22 
23 /* **************************************************************
24 *  Includes
25 ****************************************************************/
26 #include "../common/zstd_deps.h"     /* ZSTD_memcpy, ZSTD_memset */
27 #include "../common/compiler.h"
28 #include "../common/bitstream.h"
29 #include "hist.h"
30 #define FSE_STATIC_LINKING_ONLY   /* FSE_optimalTableLog_internal */
31 #include "../common/fse.h"        /* header compression */
32 #define HUF_STATIC_LINKING_ONLY
33 #include "../common/huf.h"
34 #include "../common/error_private.h"
35 
36 
37 /* **************************************************************
38 *  Error Management
39 ****************************************************************/
40 #define HUF_isError ERR_isError
41 #define HUF_STATIC_ASSERT(c) DEBUG_STATIC_ASSERT(c)   /* use only *after* variable declarations */
42 
43 
44 /* **************************************************************
45 *  Utils
46 ****************************************************************/
HUF_optimalTableLog(unsigned maxTableLog,size_t srcSize,unsigned maxSymbolValue)47 unsigned HUF_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue)
48 {
49     return FSE_optimalTableLog_internal(maxTableLog, srcSize, maxSymbolValue, 1);
50 }
51 
52 
53 /* *******************************************************
54 *  HUF : Huffman block compression
55 *********************************************************/
56 /* HUF_compressWeights() :
57  * Same as FSE_compress(), but dedicated to huff0's weights compression.
58  * The use case needs much less stack memory.
59  * Note : all elements within weightTable are supposed to be <= HUF_TABLELOG_MAX.
60  */
61 #define MAX_FSE_TABLELOG_FOR_HUFF_HEADER 6
62 
63 typedef struct {
64     FSE_CTable CTable[FSE_CTABLE_SIZE_U32(MAX_FSE_TABLELOG_FOR_HUFF_HEADER, HUF_TABLELOG_MAX)];
65     U32 scratchBuffer[FSE_BUILD_CTABLE_WORKSPACE_SIZE_U32(HUF_TABLELOG_MAX, MAX_FSE_TABLELOG_FOR_HUFF_HEADER)];
66     unsigned count[HUF_TABLELOG_MAX+1];
67     S16 norm[HUF_TABLELOG_MAX+1];
68 } HUF_CompressWeightsWksp;
69 
HUF_compressWeights(void * dst,size_t dstSize,const void * weightTable,size_t wtSize,void * workspace,size_t workspaceSize)70 static size_t HUF_compressWeights(void* dst, size_t dstSize, const void* weightTable, size_t wtSize, void* workspace, size_t workspaceSize)
71 {
72     BYTE* const ostart = (BYTE*) dst;
73     BYTE* op = ostart;
74     BYTE* const oend = ostart + dstSize;
75 
76     unsigned maxSymbolValue = HUF_TABLELOG_MAX;
77     U32 tableLog = MAX_FSE_TABLELOG_FOR_HUFF_HEADER;
78     HUF_CompressWeightsWksp* wksp = (HUF_CompressWeightsWksp*)workspace;
79 
80     if (workspaceSize < sizeof(HUF_CompressWeightsWksp)) return ERROR(GENERIC);
81 
82     /* init conditions */
83     if (wtSize <= 1) return 0;  /* Not compressible */
84 
85     /* Scan input and build symbol stats */
86     {   unsigned const maxCount = HIST_count_simple(wksp->count, &maxSymbolValue, weightTable, wtSize);   /* never fails */
87         if (maxCount == wtSize) return 1;   /* only a single symbol in src : rle */
88         if (maxCount == 1) return 0;        /* each symbol present maximum once => not compressible */
89     }
90 
91     tableLog = FSE_optimalTableLog(tableLog, wtSize, maxSymbolValue);
92     CHECK_F( FSE_normalizeCount(wksp->norm, tableLog, wksp->count, wtSize, maxSymbolValue, /* useLowProbCount */ 0) );
93 
94     /* Write table description header */
95     {   CHECK_V_F(hSize, FSE_writeNCount(op, (size_t)(oend-op), wksp->norm, maxSymbolValue, tableLog) );
96         op += hSize;
97     }
98 
99     /* Compress */
100     CHECK_F( FSE_buildCTable_wksp(wksp->CTable, wksp->norm, maxSymbolValue, tableLog, wksp->scratchBuffer, sizeof(wksp->scratchBuffer)) );
101     {   CHECK_V_F(cSize, FSE_compress_usingCTable(op, (size_t)(oend - op), weightTable, wtSize, wksp->CTable) );
102         if (cSize == 0) return 0;   /* not enough space for compressed data */
103         op += cSize;
104     }
105 
106     return (size_t)(op-ostart);
107 }
108 
109 
110 typedef struct {
111     HUF_CompressWeightsWksp wksp;
112     BYTE bitsToWeight[HUF_TABLELOG_MAX + 1];   /* precomputed conversion table */
113     BYTE huffWeight[HUF_SYMBOLVALUE_MAX];
114 } HUF_WriteCTableWksp;
115 
HUF_writeCTable_wksp(void * dst,size_t maxDstSize,const HUF_CElt * CTable,unsigned maxSymbolValue,unsigned huffLog,void * workspace,size_t workspaceSize)116 size_t HUF_writeCTable_wksp(void* dst, size_t maxDstSize,
117                             const HUF_CElt* CTable, unsigned maxSymbolValue, unsigned huffLog,
118                             void* workspace, size_t workspaceSize)
119 {
120     BYTE* op = (BYTE*)dst;
121     U32 n;
122     HUF_WriteCTableWksp* wksp = (HUF_WriteCTableWksp*)workspace;
123 
124     /* check conditions */
125     if (workspaceSize < sizeof(HUF_WriteCTableWksp)) return ERROR(GENERIC);
126     if (maxSymbolValue > HUF_SYMBOLVALUE_MAX) return ERROR(maxSymbolValue_tooLarge);
127 
128     /* convert to weight */
129     wksp->bitsToWeight[0] = 0;
130     for (n=1; n<huffLog+1; n++)
131         wksp->bitsToWeight[n] = (BYTE)(huffLog + 1 - n);
132     for (n=0; n<maxSymbolValue; n++)
133         wksp->huffWeight[n] = wksp->bitsToWeight[CTable[n].nbBits];
134 
135     /* attempt weights compression by FSE */
136     {   CHECK_V_F(hSize, HUF_compressWeights(op+1, maxDstSize-1, wksp->huffWeight, maxSymbolValue, &wksp->wksp, sizeof(wksp->wksp)) );
137         if ((hSize>1) & (hSize < maxSymbolValue/2)) {   /* FSE compressed */
138             op[0] = (BYTE)hSize;
139             return hSize+1;
140     }   }
141 
142     /* write raw values as 4-bits (max : 15) */
143     if (maxSymbolValue > (256-128)) return ERROR(GENERIC);   /* should not happen : likely means source cannot be compressed */
144     if (((maxSymbolValue+1)/2) + 1 > maxDstSize) return ERROR(dstSize_tooSmall);   /* not enough space within dst buffer */
145     op[0] = (BYTE)(128 /*special case*/ + (maxSymbolValue-1));
146     wksp->huffWeight[maxSymbolValue] = 0;   /* to be sure it doesn't cause msan issue in final combination */
147     for (n=0; n<maxSymbolValue; n+=2)
148         op[(n/2)+1] = (BYTE)((wksp->huffWeight[n] << 4) + wksp->huffWeight[n+1]);
149     return ((maxSymbolValue+1)/2) + 1;
150 }
151 
152 /*! HUF_writeCTable() :
153     `CTable` : Huffman tree to save, using huf representation.
154     @return : size of saved CTable */
HUF_writeCTable(void * dst,size_t maxDstSize,const HUF_CElt * CTable,unsigned maxSymbolValue,unsigned huffLog)155 size_t HUF_writeCTable (void* dst, size_t maxDstSize,
156                         const HUF_CElt* CTable, unsigned maxSymbolValue, unsigned huffLog)
157 {
158     HUF_WriteCTableWksp wksp;
159     return HUF_writeCTable_wksp(dst, maxDstSize, CTable, maxSymbolValue, huffLog, &wksp, sizeof(wksp));
160 }
161 
162 
HUF_readCTable(HUF_CElt * CTable,unsigned * maxSymbolValuePtr,const void * src,size_t srcSize,unsigned * hasZeroWeights)163 size_t HUF_readCTable (HUF_CElt* CTable, unsigned* maxSymbolValuePtr, const void* src, size_t srcSize, unsigned* hasZeroWeights)
164 {
165     BYTE huffWeight[HUF_SYMBOLVALUE_MAX + 1];   /* init not required, even though some static analyzer may complain */
166     U32 rankVal[HUF_TABLELOG_ABSOLUTEMAX + 1];   /* large enough for values from 0 to 16 */
167     U32 tableLog = 0;
168     U32 nbSymbols = 0;
169 
170     /* get symbol weights */
171     CHECK_V_F(readSize, HUF_readStats(huffWeight, HUF_SYMBOLVALUE_MAX+1, rankVal, &nbSymbols, &tableLog, src, srcSize));
172     *hasZeroWeights = (rankVal[0] > 0);
173 
174     /* check result */
175     if (tableLog > HUF_TABLELOG_MAX) return ERROR(tableLog_tooLarge);
176     if (nbSymbols > *maxSymbolValuePtr+1) return ERROR(maxSymbolValue_tooSmall);
177 
178     /* Prepare base value per rank */
179     {   U32 n, nextRankStart = 0;
180         for (n=1; n<=tableLog; n++) {
181             U32 curr = nextRankStart;
182             nextRankStart += (rankVal[n] << (n-1));
183             rankVal[n] = curr;
184     }   }
185 
186     /* fill nbBits */
187     {   U32 n; for (n=0; n<nbSymbols; n++) {
188             const U32 w = huffWeight[n];
189             CTable[n].nbBits = (BYTE)(tableLog + 1 - w) & -(w != 0);
190     }   }
191 
192     /* fill val */
193     {   U16 nbPerRank[HUF_TABLELOG_MAX+2]  = {0};  /* support w=0=>n=tableLog+1 */
194         U16 valPerRank[HUF_TABLELOG_MAX+2] = {0};
195         { U32 n; for (n=0; n<nbSymbols; n++) nbPerRank[CTable[n].nbBits]++; }
196         /* determine stating value per rank */
197         valPerRank[tableLog+1] = 0;   /* for w==0 */
198         {   U16 min = 0;
199             U32 n; for (n=tableLog; n>0; n--) {  /* start at n=tablelog <-> w=1 */
200                 valPerRank[n] = min;     /* get starting value within each rank */
201                 min += nbPerRank[n];
202                 min >>= 1;
203         }   }
204         /* assign value within rank, symbol order */
205         { U32 n; for (n=0; n<nbSymbols; n++) CTable[n].val = valPerRank[CTable[n].nbBits]++; }
206     }
207 
208     *maxSymbolValuePtr = nbSymbols - 1;
209     return readSize;
210 }
211 
HUF_getNbBits(const void * symbolTable,U32 symbolValue)212 U32 HUF_getNbBits(const void* symbolTable, U32 symbolValue)
213 {
214     const HUF_CElt* table = (const HUF_CElt*)symbolTable;
215     assert(symbolValue <= HUF_SYMBOLVALUE_MAX);
216     return table[symbolValue].nbBits;
217 }
218 
219 
220 typedef struct nodeElt_s {
221     U32 count;
222     U16 parent;
223     BYTE byte;
224     BYTE nbBits;
225 } nodeElt;
226 
227 /**
228  * HUF_setMaxHeight():
229  * Enforces maxNbBits on the Huffman tree described in huffNode.
230  *
231  * It sets all nodes with nbBits > maxNbBits to be maxNbBits. Then it adjusts
232  * the tree to so that it is a valid canonical Huffman tree.
233  *
234  * @pre               The sum of the ranks of each symbol == 2^largestBits,
235  *                    where largestBits == huffNode[lastNonNull].nbBits.
236  * @post              The sum of the ranks of each symbol == 2^largestBits,
237  *                    where largestBits is the return value <= maxNbBits.
238  *
239  * @param huffNode    The Huffman tree modified in place to enforce maxNbBits.
240  * @param lastNonNull The symbol with the lowest count in the Huffman tree.
241  * @param maxNbBits   The maximum allowed number of bits, which the Huffman tree
242  *                    may not respect. After this function the Huffman tree will
243  *                    respect maxNbBits.
244  * @return            The maximum number of bits of the Huffman tree after adjustment,
245  *                    necessarily no more than maxNbBits.
246  */
HUF_setMaxHeight(nodeElt * huffNode,U32 lastNonNull,U32 maxNbBits)247 static U32 HUF_setMaxHeight(nodeElt* huffNode, U32 lastNonNull, U32 maxNbBits)
248 {
249     const U32 largestBits = huffNode[lastNonNull].nbBits;
250     /* early exit : no elt > maxNbBits, so the tree is already valid. */
251     if (largestBits <= maxNbBits) return largestBits;
252 
253     /* there are several too large elements (at least >= 2) */
254     {   int totalCost = 0;
255         const U32 baseCost = 1 << (largestBits - maxNbBits);
256         int n = (int)lastNonNull;
257 
258         /* Adjust any ranks > maxNbBits to maxNbBits.
259          * Compute totalCost, which is how far the sum of the ranks is
260          * we are over 2^largestBits after adjust the offending ranks.
261          */
262         while (huffNode[n].nbBits > maxNbBits) {
263             totalCost += baseCost - (1 << (largestBits - huffNode[n].nbBits));
264             huffNode[n].nbBits = (BYTE)maxNbBits;
265             n--;
266         }
267         /* n stops at huffNode[n].nbBits <= maxNbBits */
268         assert(huffNode[n].nbBits <= maxNbBits);
269         /* n end at index of smallest symbol using < maxNbBits */
270         while (huffNode[n].nbBits == maxNbBits) --n;
271 
272         /* renorm totalCost from 2^largestBits to 2^maxNbBits
273          * note : totalCost is necessarily a multiple of baseCost */
274         assert((totalCost & (baseCost - 1)) == 0);
275         totalCost >>= (largestBits - maxNbBits);
276         assert(totalCost > 0);
277 
278         /* repay normalized cost */
279         {   U32 const noSymbol = 0xF0F0F0F0;
280             U32 rankLast[HUF_TABLELOG_MAX+2];
281 
282             /* Get pos of last (smallest = lowest cum. count) symbol per rank */
283             ZSTD_memset(rankLast, 0xF0, sizeof(rankLast));
284             {   U32 currentNbBits = maxNbBits;
285                 int pos;
286                 for (pos=n ; pos >= 0; pos--) {
287                     if (huffNode[pos].nbBits >= currentNbBits) continue;
288                     currentNbBits = huffNode[pos].nbBits;   /* < maxNbBits */
289                     rankLast[maxNbBits-currentNbBits] = (U32)pos;
290             }   }
291 
292             while (totalCost > 0) {
293                 /* Try to reduce the next power of 2 above totalCost because we
294                  * gain back half the rank.
295                  */
296                 U32 nBitsToDecrease = BIT_highbit32((U32)totalCost) + 1;
297                 for ( ; nBitsToDecrease > 1; nBitsToDecrease--) {
298                     U32 const highPos = rankLast[nBitsToDecrease];
299                     U32 const lowPos = rankLast[nBitsToDecrease-1];
300                     if (highPos == noSymbol) continue;
301                     /* Decrease highPos if no symbols of lowPos or if it is
302                      * not cheaper to remove 2 lowPos than highPos.
303                      */
304                     if (lowPos == noSymbol) break;
305                     {   U32 const highTotal = huffNode[highPos].count;
306                         U32 const lowTotal = 2 * huffNode[lowPos].count;
307                         if (highTotal <= lowTotal) break;
308                 }   }
309                 /* only triggered when no more rank 1 symbol left => find closest one (note : there is necessarily at least one !) */
310                 assert(rankLast[nBitsToDecrease] != noSymbol || nBitsToDecrease == 1);
311                 /* HUF_MAX_TABLELOG test just to please gcc 5+; but it should not be necessary */
312                 while ((nBitsToDecrease<=HUF_TABLELOG_MAX) && (rankLast[nBitsToDecrease] == noSymbol))
313                     nBitsToDecrease++;
314                 assert(rankLast[nBitsToDecrease] != noSymbol);
315                 /* Increase the number of bits to gain back half the rank cost. */
316                 totalCost -= 1 << (nBitsToDecrease-1);
317                 huffNode[rankLast[nBitsToDecrease]].nbBits++;
318 
319                 /* Fix up the new rank.
320                  * If the new rank was empty, this symbol is now its smallest.
321                  * Otherwise, this symbol will be the largest in the new rank so no adjustment.
322                  */
323                 if (rankLast[nBitsToDecrease-1] == noSymbol)
324                     rankLast[nBitsToDecrease-1] = rankLast[nBitsToDecrease];
325                 /* Fix up the old rank.
326                  * If the symbol was at position 0, meaning it was the highest weight symbol in the tree,
327                  * it must be the only symbol in its rank, so the old rank now has no symbols.
328                  * Otherwise, since the Huffman nodes are sorted by count, the previous position is now
329                  * the smallest node in the rank. If the previous position belongs to a different rank,
330                  * then the rank is now empty.
331                  */
332                 if (rankLast[nBitsToDecrease] == 0)    /* special case, reached largest symbol */
333                     rankLast[nBitsToDecrease] = noSymbol;
334                 else {
335                     rankLast[nBitsToDecrease]--;
336                     if (huffNode[rankLast[nBitsToDecrease]].nbBits != maxNbBits-nBitsToDecrease)
337                         rankLast[nBitsToDecrease] = noSymbol;   /* this rank is now empty */
338                 }
339             }   /* while (totalCost > 0) */
340 
341             /* If we've removed too much weight, then we have to add it back.
342              * To avoid overshooting again, we only adjust the smallest rank.
343              * We take the largest nodes from the lowest rank 0 and move them
344              * to rank 1. There's guaranteed to be enough rank 0 symbols because
345              * TODO.
346              */
347             while (totalCost < 0) {  /* Sometimes, cost correction overshoot */
348                 /* special case : no rank 1 symbol (using maxNbBits-1);
349                  * let's create one from largest rank 0 (using maxNbBits).
350                  */
351                 if (rankLast[1] == noSymbol) {
352                     while (huffNode[n].nbBits == maxNbBits) n--;
353                     huffNode[n+1].nbBits--;
354                     assert(n >= 0);
355                     rankLast[1] = (U32)(n+1);
356                     totalCost++;
357                     continue;
358                 }
359                 huffNode[ rankLast[1] + 1 ].nbBits--;
360                 rankLast[1]++;
361                 totalCost ++;
362             }
363         }   /* repay normalized cost */
364     }   /* there are several too large elements (at least >= 2) */
365 
366     return maxNbBits;
367 }
368 
369 typedef struct {
370     U32 base;
371     U32 curr;
372 } rankPos;
373 
374 typedef nodeElt huffNodeTable[HUF_CTABLE_WORKSPACE_SIZE_U32];
375 
376 #define RANK_POSITION_TABLE_SIZE 32
377 
378 typedef struct {
379   huffNodeTable huffNodeTbl;
380   rankPos rankPosition[RANK_POSITION_TABLE_SIZE];
381 } HUF_buildCTable_wksp_tables;
382 
383 /**
384  * HUF_sort():
385  * Sorts the symbols [0, maxSymbolValue] by count[symbol] in decreasing order.
386  *
387  * @param[out] huffNode       Sorted symbols by decreasing count. Only members `.count` and `.byte` are filled.
388  *                            Must have (maxSymbolValue + 1) entries.
389  * @param[in]  count          Histogram of the symbols.
390  * @param[in]  maxSymbolValue Maximum symbol value.
391  * @param      rankPosition   This is a scratch workspace. Must have RANK_POSITION_TABLE_SIZE entries.
392  */
HUF_sort(nodeElt * huffNode,const unsigned * count,U32 maxSymbolValue,rankPos * rankPosition)393 static void HUF_sort(nodeElt* huffNode, const unsigned* count, U32 maxSymbolValue, rankPos* rankPosition)
394 {
395     int n;
396     int const maxSymbolValue1 = (int)maxSymbolValue + 1;
397 
398     /* Compute base and set curr to base.
399      * For symbol s let lowerRank = BIT_highbit32(count[n]+1) and rank = lowerRank + 1.
400      * Then 2^lowerRank <= count[n]+1 <= 2^rank.
401      * We attribute each symbol to lowerRank's base value, because we want to know where
402      * each rank begins in the output, so for rank R we want to count ranks R+1 and above.
403      */
404     ZSTD_memset(rankPosition, 0, sizeof(*rankPosition) * RANK_POSITION_TABLE_SIZE);
405     for (n = 0; n < maxSymbolValue1; ++n) {
406         U32 lowerRank = BIT_highbit32(count[n] + 1);
407         rankPosition[lowerRank].base++;
408     }
409     assert(rankPosition[RANK_POSITION_TABLE_SIZE - 1].base == 0);
410     for (n = RANK_POSITION_TABLE_SIZE - 1; n > 0; --n) {
411         rankPosition[n-1].base += rankPosition[n].base;
412         rankPosition[n-1].curr = rankPosition[n-1].base;
413     }
414     /* Sort */
415     for (n = 0; n < maxSymbolValue1; ++n) {
416         U32 const c = count[n];
417         U32 const r = BIT_highbit32(c+1) + 1;
418         U32 pos = rankPosition[r].curr++;
419         /* Insert into the correct position in the rank.
420          * We have at most 256 symbols, so this insertion should be fine.
421          */
422         while ((pos > rankPosition[r].base) && (c > huffNode[pos-1].count)) {
423             huffNode[pos] = huffNode[pos-1];
424             pos--;
425         }
426         huffNode[pos].count = c;
427         huffNode[pos].byte  = (BYTE)n;
428     }
429 }
430 
431 
432 /** HUF_buildCTable_wksp() :
433  *  Same as HUF_buildCTable(), but using externally allocated scratch buffer.
434  *  `workSpace` must be aligned on 4-bytes boundaries, and be at least as large as sizeof(HUF_buildCTable_wksp_tables).
435  */
436 #define STARTNODE (HUF_SYMBOLVALUE_MAX+1)
437 
438 /* HUF_buildTree():
439  * Takes the huffNode array sorted by HUF_sort() and builds an unlimited-depth Huffman tree.
440  *
441  * @param huffNode        The array sorted by HUF_sort(). Builds the Huffman tree in this array.
442  * @param maxSymbolValue  The maximum symbol value.
443  * @return                The smallest node in the Huffman tree (by count).
444  */
HUF_buildTree(nodeElt * huffNode,U32 maxSymbolValue)445 static int HUF_buildTree(nodeElt* huffNode, U32 maxSymbolValue)
446 {
447     nodeElt* const huffNode0 = huffNode - 1;
448     int nonNullRank;
449     int lowS, lowN;
450     int nodeNb = STARTNODE;
451     int n, nodeRoot;
452     /* init for parents */
453     nonNullRank = (int)maxSymbolValue;
454     while(huffNode[nonNullRank].count == 0) nonNullRank--;
455     lowS = nonNullRank; nodeRoot = nodeNb + lowS - 1; lowN = nodeNb;
456     huffNode[nodeNb].count = huffNode[lowS].count + huffNode[lowS-1].count;
457     huffNode[lowS].parent = huffNode[lowS-1].parent = (U16)nodeNb;
458     nodeNb++; lowS-=2;
459     for (n=nodeNb; n<=nodeRoot; n++) huffNode[n].count = (U32)(1U<<30);
460     huffNode0[0].count = (U32)(1U<<31);  /* fake entry, strong barrier */
461 
462     /* create parents */
463     while (nodeNb <= nodeRoot) {
464         int const n1 = (huffNode[lowS].count < huffNode[lowN].count) ? lowS-- : lowN++;
465         int const n2 = (huffNode[lowS].count < huffNode[lowN].count) ? lowS-- : lowN++;
466         huffNode[nodeNb].count = huffNode[n1].count + huffNode[n2].count;
467         huffNode[n1].parent = huffNode[n2].parent = (U16)nodeNb;
468         nodeNb++;
469     }
470 
471     /* distribute weights (unlimited tree height) */
472     huffNode[nodeRoot].nbBits = 0;
473     for (n=nodeRoot-1; n>=STARTNODE; n--)
474         huffNode[n].nbBits = huffNode[ huffNode[n].parent ].nbBits + 1;
475     for (n=0; n<=nonNullRank; n++)
476         huffNode[n].nbBits = huffNode[ huffNode[n].parent ].nbBits + 1;
477 
478     return nonNullRank;
479 }
480 
481 /**
482  * HUF_buildCTableFromTree():
483  * Build the CTable given the Huffman tree in huffNode.
484  *
485  * @param[out] CTable         The output Huffman CTable.
486  * @param      huffNode       The Huffman tree.
487  * @param      nonNullRank    The last and smallest node in the Huffman tree.
488  * @param      maxSymbolValue The maximum symbol value.
489  * @param      maxNbBits      The exact maximum number of bits used in the Huffman tree.
490  */
HUF_buildCTableFromTree(HUF_CElt * CTable,nodeElt const * huffNode,int nonNullRank,U32 maxSymbolValue,U32 maxNbBits)491 static void HUF_buildCTableFromTree(HUF_CElt* CTable, nodeElt const* huffNode, int nonNullRank, U32 maxSymbolValue, U32 maxNbBits)
492 {
493     /* fill result into ctable (val, nbBits) */
494     int n;
495     U16 nbPerRank[HUF_TABLELOG_MAX+1] = {0};
496     U16 valPerRank[HUF_TABLELOG_MAX+1] = {0};
497     int const alphabetSize = (int)(maxSymbolValue + 1);
498     for (n=0; n<=nonNullRank; n++)
499         nbPerRank[huffNode[n].nbBits]++;
500     /* determine starting value per rank */
501     {   U16 min = 0;
502         for (n=(int)maxNbBits; n>0; n--) {
503             valPerRank[n] = min;      /* get starting value within each rank */
504             min += nbPerRank[n];
505             min >>= 1;
506     }   }
507     for (n=0; n<alphabetSize; n++)
508         CTable[huffNode[n].byte].nbBits = huffNode[n].nbBits;   /* push nbBits per symbol, symbol order */
509     for (n=0; n<alphabetSize; n++)
510         CTable[n].val = valPerRank[CTable[n].nbBits]++;   /* assign value within rank, symbol order */
511 }
512 
HUF_buildCTable_wksp(HUF_CElt * tree,const unsigned * count,U32 maxSymbolValue,U32 maxNbBits,void * workSpace,size_t wkspSize)513 size_t HUF_buildCTable_wksp (HUF_CElt* tree, const unsigned* count, U32 maxSymbolValue, U32 maxNbBits, void* workSpace, size_t wkspSize)
514 {
515     HUF_buildCTable_wksp_tables* const wksp_tables = (HUF_buildCTable_wksp_tables*)workSpace;
516     nodeElt* const huffNode0 = wksp_tables->huffNodeTbl;
517     nodeElt* const huffNode = huffNode0+1;
518     int nonNullRank;
519 
520     /* safety checks */
521     if (((size_t)workSpace & 3) != 0) return ERROR(GENERIC);  /* must be aligned on 4-bytes boundaries */
522     if (wkspSize < sizeof(HUF_buildCTable_wksp_tables))
523       return ERROR(workSpace_tooSmall);
524     if (maxNbBits == 0) maxNbBits = HUF_TABLELOG_DEFAULT;
525     if (maxSymbolValue > HUF_SYMBOLVALUE_MAX)
526       return ERROR(maxSymbolValue_tooLarge);
527     ZSTD_memset(huffNode0, 0, sizeof(huffNodeTable));
528 
529     /* sort, decreasing order */
530     HUF_sort(huffNode, count, maxSymbolValue, wksp_tables->rankPosition);
531 
532     /* build tree */
533     nonNullRank = HUF_buildTree(huffNode, maxSymbolValue);
534 
535     /* enforce maxTableLog */
536     maxNbBits = HUF_setMaxHeight(huffNode, (U32)nonNullRank, maxNbBits);
537     if (maxNbBits > HUF_TABLELOG_MAX) return ERROR(GENERIC);   /* check fit into table */
538 
539     HUF_buildCTableFromTree(tree, huffNode, nonNullRank, maxSymbolValue, maxNbBits);
540 
541     return maxNbBits;
542 }
543 
HUF_estimateCompressedSize(const HUF_CElt * CTable,const unsigned * count,unsigned maxSymbolValue)544 size_t HUF_estimateCompressedSize(const HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue)
545 {
546     size_t nbBits = 0;
547     int s;
548     for (s = 0; s <= (int)maxSymbolValue; ++s) {
549         nbBits += CTable[s].nbBits * count[s];
550     }
551     return nbBits >> 3;
552 }
553 
HUF_validateCTable(const HUF_CElt * CTable,const unsigned * count,unsigned maxSymbolValue)554 int HUF_validateCTable(const HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue) {
555   int bad = 0;
556   int s;
557   for (s = 0; s <= (int)maxSymbolValue; ++s) {
558     bad |= (count[s] != 0) & (CTable[s].nbBits == 0);
559   }
560   return !bad;
561 }
562 
HUF_compressBound(size_t size)563 size_t HUF_compressBound(size_t size) { return HUF_COMPRESSBOUND(size); }
564 
565 FORCE_INLINE_TEMPLATE void
HUF_encodeSymbol(BIT_CStream_t * bitCPtr,U32 symbol,const HUF_CElt * CTable)566 HUF_encodeSymbol(BIT_CStream_t* bitCPtr, U32 symbol, const HUF_CElt* CTable)
567 {
568     BIT_addBitsFast(bitCPtr, CTable[symbol].val, CTable[symbol].nbBits);
569 }
570 
571 #define HUF_FLUSHBITS(s)  BIT_flushBits(s)
572 
573 #define HUF_FLUSHBITS_1(stream) \
574     if (sizeof((stream)->bitContainer)*8 < HUF_TABLELOG_MAX*2+7) HUF_FLUSHBITS(stream)
575 
576 #define HUF_FLUSHBITS_2(stream) \
577     if (sizeof((stream)->bitContainer)*8 < HUF_TABLELOG_MAX*4+7) HUF_FLUSHBITS(stream)
578 
579 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)580 HUF_compress1X_usingCTable_internal_body(void* dst, size_t dstSize,
581                                    const void* src, size_t srcSize,
582                                    const HUF_CElt* CTable)
583 {
584     const BYTE* ip = (const BYTE*) src;
585     BYTE* const ostart = (BYTE*)dst;
586     BYTE* const oend = ostart + dstSize;
587     BYTE* op = ostart;
588     size_t n;
589     BIT_CStream_t bitC;
590 
591     /* init */
592     if (dstSize < 8) return 0;   /* not enough space to compress */
593     { size_t const initErr = BIT_initCStream(&bitC, op, (size_t)(oend-op));
594       if (HUF_isError(initErr)) return 0; }
595 
596     n = srcSize & ~3;  /* join to mod 4 */
597     switch (srcSize & 3)
598     {
599         case 3 : HUF_encodeSymbol(&bitC, ip[n+ 2], CTable);
600                  HUF_FLUSHBITS_2(&bitC);
601 		 /* fall-through */
602         case 2 : HUF_encodeSymbol(&bitC, ip[n+ 1], CTable);
603                  HUF_FLUSHBITS_1(&bitC);
604 		 /* fall-through */
605         case 1 : HUF_encodeSymbol(&bitC, ip[n+ 0], CTable);
606                  HUF_FLUSHBITS(&bitC);
607 		 /* fall-through */
608         case 0 : /* fall-through */
609         default: break;
610     }
611 
612     for (; n>0; n-=4) {  /* note : n&3==0 at this stage */
613         HUF_encodeSymbol(&bitC, ip[n- 1], CTable);
614         HUF_FLUSHBITS_1(&bitC);
615         HUF_encodeSymbol(&bitC, ip[n- 2], CTable);
616         HUF_FLUSHBITS_2(&bitC);
617         HUF_encodeSymbol(&bitC, ip[n- 3], CTable);
618         HUF_FLUSHBITS_1(&bitC);
619         HUF_encodeSymbol(&bitC, ip[n- 4], CTable);
620         HUF_FLUSHBITS(&bitC);
621     }
622 
623     return BIT_closeCStream(&bitC);
624 }
625 
626 #if DYNAMIC_BMI2
627 
628 static TARGET_ATTRIBUTE("bmi2") size_t
HUF_compress1X_usingCTable_internal_bmi2(void * dst,size_t dstSize,const void * src,size_t srcSize,const HUF_CElt * CTable)629 HUF_compress1X_usingCTable_internal_bmi2(void* dst, size_t dstSize,
630                                    const void* src, size_t srcSize,
631                                    const HUF_CElt* CTable)
632 {
633     return HUF_compress1X_usingCTable_internal_body(dst, dstSize, src, srcSize, CTable);
634 }
635 
636 static size_t
HUF_compress1X_usingCTable_internal_default(void * dst,size_t dstSize,const void * src,size_t srcSize,const HUF_CElt * CTable)637 HUF_compress1X_usingCTable_internal_default(void* dst, size_t dstSize,
638                                       const void* src, size_t srcSize,
639                                       const HUF_CElt* CTable)
640 {
641     return HUF_compress1X_usingCTable_internal_body(dst, dstSize, src, srcSize, CTable);
642 }
643 
644 static size_t
HUF_compress1X_usingCTable_internal(void * dst,size_t dstSize,const void * src,size_t srcSize,const HUF_CElt * CTable,const int bmi2)645 HUF_compress1X_usingCTable_internal(void* dst, size_t dstSize,
646                               const void* src, size_t srcSize,
647                               const HUF_CElt* CTable, const int bmi2)
648 {
649     if (bmi2) {
650         return HUF_compress1X_usingCTable_internal_bmi2(dst, dstSize, src, srcSize, CTable);
651     }
652     return HUF_compress1X_usingCTable_internal_default(dst, dstSize, src, srcSize, CTable);
653 }
654 
655 #else
656 
657 static size_t
HUF_compress1X_usingCTable_internal(void * dst,size_t dstSize,const void * src,size_t srcSize,const HUF_CElt * CTable,const int bmi2)658 HUF_compress1X_usingCTable_internal(void* dst, size_t dstSize,
659                               const void* src, size_t srcSize,
660                               const HUF_CElt* CTable, const int bmi2)
661 {
662     (void)bmi2;
663     return HUF_compress1X_usingCTable_internal_body(dst, dstSize, src, srcSize, CTable);
664 }
665 
666 #endif
667 
HUF_compress1X_usingCTable(void * dst,size_t dstSize,const void * src,size_t srcSize,const HUF_CElt * CTable)668 size_t HUF_compress1X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable)
669 {
670     return HUF_compress1X_usingCTable_internal(dst, dstSize, src, srcSize, CTable, /* bmi2 */ 0);
671 }
672 
673 
674 static size_t
HUF_compress4X_usingCTable_internal(void * dst,size_t dstSize,const void * src,size_t srcSize,const HUF_CElt * CTable,int bmi2)675 HUF_compress4X_usingCTable_internal(void* dst, size_t dstSize,
676                               const void* src, size_t srcSize,
677                               const HUF_CElt* CTable, int bmi2)
678 {
679     size_t const segmentSize = (srcSize+3)/4;   /* first 3 segments */
680     const BYTE* ip = (const BYTE*) src;
681     const BYTE* const iend = ip + srcSize;
682     BYTE* const ostart = (BYTE*) dst;
683     BYTE* const oend = ostart + dstSize;
684     BYTE* op = ostart;
685 
686     if (dstSize < 6 + 1 + 1 + 1 + 8) return 0;   /* minimum space to compress successfully */
687     if (srcSize < 12) return 0;   /* no saving possible : too small input */
688     op += 6;   /* jumpTable */
689 
690     assert(op <= oend);
691     {   CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, (size_t)(oend-op), ip, segmentSize, CTable, bmi2) );
692         if (cSize==0) return 0;
693         assert(cSize <= 65535);
694         MEM_writeLE16(ostart, (U16)cSize);
695         op += cSize;
696     }
697 
698     ip += segmentSize;
699     assert(op <= oend);
700     {   CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, (size_t)(oend-op), ip, segmentSize, CTable, bmi2) );
701         if (cSize==0) return 0;
702         assert(cSize <= 65535);
703         MEM_writeLE16(ostart+2, (U16)cSize);
704         op += cSize;
705     }
706 
707     ip += segmentSize;
708     assert(op <= oend);
709     {   CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, (size_t)(oend-op), ip, segmentSize, CTable, bmi2) );
710         if (cSize==0) return 0;
711         assert(cSize <= 65535);
712         MEM_writeLE16(ostart+4, (U16)cSize);
713         op += cSize;
714     }
715 
716     ip += segmentSize;
717     assert(op <= oend);
718     assert(ip <= iend);
719     {   CHECK_V_F(cSize, HUF_compress1X_usingCTable_internal(op, (size_t)(oend-op), ip, (size_t)(iend-ip), CTable, bmi2) );
720         if (cSize==0) return 0;
721         op += cSize;
722     }
723 
724     return (size_t)(op-ostart);
725 }
726 
HUF_compress4X_usingCTable(void * dst,size_t dstSize,const void * src,size_t srcSize,const HUF_CElt * CTable)727 size_t HUF_compress4X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable)
728 {
729     return HUF_compress4X_usingCTable_internal(dst, dstSize, src, srcSize, CTable, /* bmi2 */ 0);
730 }
731 
732 typedef enum { HUF_singleStream, HUF_fourStreams } HUF_nbStreams_e;
733 
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 bmi2)734 static size_t HUF_compressCTable_internal(
735                 BYTE* const ostart, BYTE* op, BYTE* const oend,
736                 const void* src, size_t srcSize,
737                 HUF_nbStreams_e nbStreams, const HUF_CElt* CTable, const int bmi2)
738 {
739     size_t const cSize = (nbStreams==HUF_singleStream) ?
740                          HUF_compress1X_usingCTable_internal(op, (size_t)(oend - op), src, srcSize, CTable, bmi2) :
741                          HUF_compress4X_usingCTable_internal(op, (size_t)(oend - op), src, srcSize, CTable, bmi2);
742     if (HUF_isError(cSize)) { return cSize; }
743     if (cSize==0) { return 0; }   /* uncompressible */
744     op += cSize;
745     /* check compressibility */
746     assert(op >= ostart);
747     if ((size_t)(op-ostart) >= srcSize-1) { return 0; }
748     return (size_t)(op-ostart);
749 }
750 
751 typedef struct {
752     unsigned count[HUF_SYMBOLVALUE_MAX + 1];
753     HUF_CElt CTable[HUF_SYMBOLVALUE_MAX + 1];
754     union {
755         HUF_buildCTable_wksp_tables buildCTable_wksp;
756         HUF_WriteCTableWksp writeCTable_wksp;
757     } wksps;
758 } HUF_compress_tables_t;
759 
760 /* HUF_compress_internal() :
761  * `workSpace_align4` must be aligned on 4-bytes boundaries,
762  * and occupies the same space as a table of HUF_WORKSPACE_SIZE_U32 unsigned */
763 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_align4,size_t wkspSize,HUF_CElt * oldHufTable,HUF_repeat * repeat,int preferRepeat,const int bmi2)764 HUF_compress_internal (void* dst, size_t dstSize,
765                  const void* src, size_t srcSize,
766                        unsigned maxSymbolValue, unsigned huffLog,
767                        HUF_nbStreams_e nbStreams,
768                        void* workSpace_align4, size_t wkspSize,
769                        HUF_CElt* oldHufTable, HUF_repeat* repeat, int preferRepeat,
770                  const int bmi2)
771 {
772     HUF_compress_tables_t* const table = (HUF_compress_tables_t*)workSpace_align4;
773     BYTE* const ostart = (BYTE*)dst;
774     BYTE* const oend = ostart + dstSize;
775     BYTE* op = ostart;
776 
777     HUF_STATIC_ASSERT(sizeof(*table) <= HUF_WORKSPACE_SIZE);
778     assert(((size_t)workSpace_align4 & 3) == 0);   /* must be aligned on 4-bytes boundaries */
779 
780     /* checks & inits */
781     if (wkspSize < HUF_WORKSPACE_SIZE) return ERROR(workSpace_tooSmall);
782     if (!srcSize) return 0;  /* Uncompressed */
783     if (!dstSize) return 0;  /* cannot fit anything within dst budget */
784     if (srcSize > HUF_BLOCKSIZE_MAX) return ERROR(srcSize_wrong);   /* current block size limit */
785     if (huffLog > HUF_TABLELOG_MAX) return ERROR(tableLog_tooLarge);
786     if (maxSymbolValue > HUF_SYMBOLVALUE_MAX) return ERROR(maxSymbolValue_tooLarge);
787     if (!maxSymbolValue) maxSymbolValue = HUF_SYMBOLVALUE_MAX;
788     if (!huffLog) huffLog = HUF_TABLELOG_DEFAULT;
789 
790     /* Heuristic : If old table is valid, use it for small inputs */
791     if (preferRepeat && repeat && *repeat == HUF_repeat_valid) {
792         return HUF_compressCTable_internal(ostart, op, oend,
793                                            src, srcSize,
794                                            nbStreams, oldHufTable, bmi2);
795     }
796 
797     /* Scan input and build symbol stats */
798     {   CHECK_V_F(largest, HIST_count_wksp (table->count, &maxSymbolValue, (const BYTE*)src, srcSize, workSpace_align4, wkspSize) );
799         if (largest == srcSize) { *ostart = ((const BYTE*)src)[0]; return 1; }   /* single symbol, rle */
800         if (largest <= (srcSize >> 7)+4) return 0;   /* heuristic : probably not compressible enough */
801     }
802 
803     /* Check validity of previous table */
804     if ( repeat
805       && *repeat == HUF_repeat_check
806       && !HUF_validateCTable(oldHufTable, table->count, maxSymbolValue)) {
807         *repeat = HUF_repeat_none;
808     }
809     /* Heuristic : use existing table for small inputs */
810     if (preferRepeat && repeat && *repeat != HUF_repeat_none) {
811         return HUF_compressCTable_internal(ostart, op, oend,
812                                            src, srcSize,
813                                            nbStreams, oldHufTable, bmi2);
814     }
815 
816     /* Build Huffman Tree */
817     huffLog = HUF_optimalTableLog(huffLog, srcSize, maxSymbolValue);
818     {   size_t const maxBits = HUF_buildCTable_wksp(table->CTable, table->count,
819                                             maxSymbolValue, huffLog,
820                                             &table->wksps.buildCTable_wksp, sizeof(table->wksps.buildCTable_wksp));
821         CHECK_F(maxBits);
822         huffLog = (U32)maxBits;
823         /* Zero unused symbols in CTable, so we can check it for validity */
824         ZSTD_memset(table->CTable + (maxSymbolValue + 1), 0,
825                sizeof(table->CTable) - ((maxSymbolValue + 1) * sizeof(HUF_CElt)));
826     }
827 
828     /* Write table description header */
829     {   CHECK_V_F(hSize, HUF_writeCTable_wksp(op, dstSize, table->CTable, maxSymbolValue, huffLog,
830                                               &table->wksps.writeCTable_wksp, sizeof(table->wksps.writeCTable_wksp)) );
831         /* Check if using previous huffman table is beneficial */
832         if (repeat && *repeat != HUF_repeat_none) {
833             size_t const oldSize = HUF_estimateCompressedSize(oldHufTable, table->count, maxSymbolValue);
834             size_t const newSize = HUF_estimateCompressedSize(table->CTable, table->count, maxSymbolValue);
835             if (oldSize <= hSize + newSize || hSize + 12 >= srcSize) {
836                 return HUF_compressCTable_internal(ostart, op, oend,
837                                                    src, srcSize,
838                                                    nbStreams, oldHufTable, bmi2);
839         }   }
840 
841         /* Use the new huffman table */
842         if (hSize + 12ul >= srcSize) { return 0; }
843         op += hSize;
844         if (repeat) { *repeat = HUF_repeat_none; }
845         if (oldHufTable)
846             ZSTD_memcpy(oldHufTable, table->CTable, sizeof(table->CTable));  /* Save new table */
847     }
848     return HUF_compressCTable_internal(ostart, op, oend,
849                                        src, srcSize,
850                                        nbStreams, table->CTable, bmi2);
851 }
852 
853 
HUF_compress1X_wksp(void * dst,size_t dstSize,const void * src,size_t srcSize,unsigned maxSymbolValue,unsigned huffLog,void * workSpace,size_t wkspSize)854 size_t HUF_compress1X_wksp (void* dst, size_t dstSize,
855                       const void* src, size_t srcSize,
856                       unsigned maxSymbolValue, unsigned huffLog,
857                       void* workSpace, size_t wkspSize)
858 {
859     return HUF_compress_internal(dst, dstSize, src, srcSize,
860                                  maxSymbolValue, huffLog, HUF_singleStream,
861                                  workSpace, wkspSize,
862                                  NULL, NULL, 0, 0 /*bmi2*/);
863 }
864 
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 preferRepeat,int bmi2)865 size_t HUF_compress1X_repeat (void* dst, size_t dstSize,
866                       const void* src, size_t srcSize,
867                       unsigned maxSymbolValue, unsigned huffLog,
868                       void* workSpace, size_t wkspSize,
869                       HUF_CElt* hufTable, HUF_repeat* repeat, int preferRepeat, int bmi2)
870 {
871     return HUF_compress_internal(dst, dstSize, src, srcSize,
872                                  maxSymbolValue, huffLog, HUF_singleStream,
873                                  workSpace, wkspSize, hufTable,
874                                  repeat, preferRepeat, bmi2);
875 }
876 
877 /* HUF_compress4X_repeat():
878  * compress input using 4 streams.
879  * provide workspace to generate compression tables */
HUF_compress4X_wksp(void * dst,size_t dstSize,const void * src,size_t srcSize,unsigned maxSymbolValue,unsigned huffLog,void * workSpace,size_t wkspSize)880 size_t HUF_compress4X_wksp (void* dst, size_t dstSize,
881                       const void* src, size_t srcSize,
882                       unsigned maxSymbolValue, unsigned huffLog,
883                       void* workSpace, size_t wkspSize)
884 {
885     return HUF_compress_internal(dst, dstSize, src, srcSize,
886                                  maxSymbolValue, huffLog, HUF_fourStreams,
887                                  workSpace, wkspSize,
888                                  NULL, NULL, 0, 0 /*bmi2*/);
889 }
890 
891 /* HUF_compress4X_repeat():
892  * compress input using 4 streams.
893  * re-use 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 preferRepeat,int bmi2)894 size_t HUF_compress4X_repeat (void* dst, size_t dstSize,
895                       const void* src, size_t srcSize,
896                       unsigned maxSymbolValue, unsigned huffLog,
897                       void* workSpace, size_t wkspSize,
898                       HUF_CElt* hufTable, HUF_repeat* repeat, int preferRepeat, int bmi2)
899 {
900     return HUF_compress_internal(dst, dstSize, src, srcSize,
901                                  maxSymbolValue, huffLog, HUF_fourStreams,
902                                  workSpace, wkspSize,
903                                  hufTable, repeat, preferRepeat, bmi2);
904 }
905 
906 #ifndef ZSTD_NO_UNUSED_FUNCTIONS
907 /** HUF_buildCTable() :
908  * @return : maxNbBits
909  *  Note : count is used before tree is written, so they can safely overlap
910  */
HUF_buildCTable(HUF_CElt * tree,const unsigned * count,unsigned maxSymbolValue,unsigned maxNbBits)911 size_t HUF_buildCTable (HUF_CElt* tree, const unsigned* count, unsigned maxSymbolValue, unsigned maxNbBits)
912 {
913     HUF_buildCTable_wksp_tables workspace;
914     return HUF_buildCTable_wksp(tree, count, maxSymbolValue, maxNbBits, &workspace, sizeof(workspace));
915 }
916 
HUF_compress1X(void * dst,size_t dstSize,const void * src,size_t srcSize,unsigned maxSymbolValue,unsigned huffLog)917 size_t HUF_compress1X (void* dst, size_t dstSize,
918                  const void* src, size_t srcSize,
919                  unsigned maxSymbolValue, unsigned huffLog)
920 {
921     unsigned workSpace[HUF_WORKSPACE_SIZE_U32];
922     return HUF_compress1X_wksp(dst, dstSize, src, srcSize, maxSymbolValue, huffLog, workSpace, sizeof(workSpace));
923 }
924 
HUF_compress2(void * dst,size_t dstSize,const void * src,size_t srcSize,unsigned maxSymbolValue,unsigned huffLog)925 size_t HUF_compress2 (void* dst, size_t dstSize,
926                 const void* src, size_t srcSize,
927                 unsigned maxSymbolValue, unsigned huffLog)
928 {
929     unsigned workSpace[HUF_WORKSPACE_SIZE_U32];
930     return HUF_compress4X_wksp(dst, dstSize, src, srcSize, maxSymbolValue, huffLog, workSpace, sizeof(workSpace));
931 }
932 
HUF_compress(void * dst,size_t maxDstSize,const void * src,size_t srcSize)933 size_t HUF_compress (void* dst, size_t maxDstSize, const void* src, size_t srcSize)
934 {
935     return HUF_compress2(dst, maxDstSize, src, srcSize, 255, HUF_TABLELOG_DEFAULT);
936 }
937 #endif
938