You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

huf_compress.c 56KB

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