huf_compress.c 57 KB

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