1 /* ******************************************************************
2 * Common functions of New Generation Entropy library
3 * Copyright (c) Meta Platforms, Inc. and affiliates.
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
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 ****************************************************************** */
15 /* *************************************
17 ***************************************/
19 #include "error_private.h" /* ERR_*, ERROR */
20 #define FSE_STATIC_LINKING_ONLY /* FSE_MIN_TABLELOG */
23 #include "bits.h" /* ZSDT_highbit32, ZSTD_countTrailingZeros32 */
27 unsigned FSE_versionNumber(void) { return FSE_VERSION_NUMBER; }
30 /*=== Error Management ===*/
31 unsigned FSE_isError(size_t code) { return ERR_isError(code); }
32 const char* FSE_getErrorName(size_t code) { return ERR_getErrorName(code); }
34 unsigned HUF_isError(size_t code) { return ERR_isError(code); }
35 const char* HUF_getErrorName(size_t code) { return ERR_getErrorName(code); }
38 /*-**************************************************************
39 * FSE NCount encoding-decoding
40 ****************************************************************/
42 size_t FSE_readNCount_body(short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
43 const void* headerBuffer, size_t hbSize)
45 const BYTE* const istart = (const BYTE*) headerBuffer;
46 const BYTE* const iend = istart + hbSize;
47 const BYTE* ip = istart;
54 unsigned const maxSV1 = *maxSVPtr + 1;
58 /* This function only works when hbSize >= 8 */
60 ZSTD_memcpy(buffer, headerBuffer, hbSize);
61 { size_t const countSize = FSE_readNCount(normalizedCounter, maxSVPtr, tableLogPtr,
62 buffer, sizeof(buffer));
63 if (FSE_isError(countSize)) return countSize;
64 if (countSize > hbSize) return ERROR(corruption_detected);
70 ZSTD_memset(normalizedCounter, 0, (*maxSVPtr+1) * sizeof(normalizedCounter[0])); /* all symbols not present in NCount have a frequency of 0 */
71 bitStream = MEM_readLE32(ip);
72 nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG; /* extract tableLog */
73 if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);
76 *tableLogPtr = nbBits;
77 remaining = (1<<nbBits)+1;
78 threshold = 1<<nbBits;
83 /* Count the number of repeats. Each time the
84 * 2-bit repeat code is 0b11 there is another
86 * Avoid UB by setting the high bit to 1.
88 int repeats = ZSTD_countTrailingZeros32(~bitStream | 0x80000000) >> 1;
89 while (repeats >= 12) {
91 if (LIKELY(ip <= iend-7)) {
94 bitCount -= (int)(8 * (iend - 7 - ip));
98 bitStream = MEM_readLE32(ip) >> bitCount;
99 repeats = ZSTD_countTrailingZeros32(~bitStream | 0x80000000) >> 1;
101 charnum += 3 * repeats;
102 bitStream >>= 2 * repeats;
103 bitCount += 2 * repeats;
105 /* Add the final repeat which isn't 0b11. */
106 assert((bitStream & 3) < 3);
107 charnum += bitStream & 3;
110 /* This is an error, but break and return an error
111 * at the end, because returning out of a loop makes
112 * it harder for the compiler to optimize.
114 if (charnum >= maxSV1) break;
116 /* We don't need to set the normalized count to 0
117 * because we already memset the whole buffer to 0.
120 if (LIKELY(ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
121 assert((bitCount >> 3) <= 3); /* For first condition to work */
125 bitCount -= (int)(8 * (iend - 4 - ip));
129 bitStream = MEM_readLE32(ip) >> bitCount;
132 int const max = (2*threshold-1) - remaining;
135 if ((bitStream & (threshold-1)) < (U32)max) {
136 count = bitStream & (threshold-1);
137 bitCount += nbBits-1;
139 count = bitStream & (2*threshold-1);
140 if (count >= threshold) count -= max;
144 count--; /* extra accuracy */
145 /* When it matters (small blocks), this is a
146 * predictable branch, because we don't use -1.
154 normalizedCounter[charnum++] = (short)count;
157 assert(threshold > 1);
158 if (remaining < threshold) {
159 /* This branch can be folded into the
160 * threshold update condition because we
161 * know that threshold > 1.
163 if (remaining <= 1) break;
164 nbBits = ZSTD_highbit32(remaining) + 1;
165 threshold = 1 << (nbBits - 1);
167 if (charnum >= maxSV1) break;
169 if (LIKELY(ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
173 bitCount -= (int)(8 * (iend - 4 - ip));
177 bitStream = MEM_readLE32(ip) >> bitCount;
179 if (remaining != 1) return ERROR(corruption_detected);
180 /* Only possible when there are too many zeros. */
181 if (charnum > maxSV1) return ERROR(maxSymbolValue_tooSmall);
182 if (bitCount > 32) return ERROR(corruption_detected);
183 *maxSVPtr = charnum-1;
185 ip += (bitCount+7)>>3;
189 /* Avoids the FORCE_INLINE of the _body() function. */
190 static size_t FSE_readNCount_body_default(
191 short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
192 const void* headerBuffer, size_t hbSize)
194 return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
198 BMI2_TARGET_ATTRIBUTE static size_t FSE_readNCount_body_bmi2(
199 short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
200 const void* headerBuffer, size_t hbSize)
202 return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
206 size_t FSE_readNCount_bmi2(
207 short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
208 const void* headerBuffer, size_t hbSize, int bmi2)
212 return FSE_readNCount_body_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
216 return FSE_readNCount_body_default(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
219 size_t FSE_readNCount(
220 short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
221 const void* headerBuffer, size_t hbSize)
223 return FSE_readNCount_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize, /* bmi2 */ 0);
227 /*! HUF_readStats() :
228 Read compact Huffman tree, saved by HUF_writeCTable().
229 `huffWeight` is destination buffer.
230 `rankStats` is assumed to be a table of at least HUF_TABLELOG_MAX U32.
231 @return : size read from `src` , or an error Code .
232 Note : Needed by HUF_readCTable() and HUF_readDTableX?() .
234 size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,
235 U32* nbSymbolsPtr, U32* tableLogPtr,
236 const void* src, size_t srcSize)
238 U32 wksp[HUF_READ_STATS_WORKSPACE_SIZE_U32];
239 return HUF_readStats_wksp(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, wksp, sizeof(wksp), /* flags */ 0);
242 FORCE_INLINE_TEMPLATE size_t
243 HUF_readStats_body(BYTE* huffWeight, size_t hwSize, U32* rankStats,
244 U32* nbSymbolsPtr, U32* tableLogPtr,
245 const void* src, size_t srcSize,
246 void* workSpace, size_t wkspSize,
250 const BYTE* ip = (const BYTE*) src;
254 if (!srcSize) return ERROR(srcSize_wrong);
256 /* ZSTD_memset(huffWeight, 0, hwSize); *//* is not necessary, even though some analyzer complain ... */
258 if (iSize >= 128) { /* special header */
260 iSize = ((oSize+1)/2);
261 if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
262 if (oSize >= hwSize) return ERROR(corruption_detected);
265 for (n=0; n<oSize; n+=2) {
266 huffWeight[n] = ip[n/2] >> 4;
267 huffWeight[n+1] = ip[n/2] & 15;
269 else { /* header compressed with FSE (normal case) */
270 if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
271 /* max (hwSize-1) values decoded, as last one is implied */
272 oSize = FSE_decompress_wksp_bmi2(huffWeight, hwSize-1, ip+1, iSize, 6, workSpace, wkspSize, bmi2);
273 if (FSE_isError(oSize)) return oSize;
276 /* collect weight stats */
277 ZSTD_memset(rankStats, 0, (HUF_TABLELOG_MAX + 1) * sizeof(U32));
279 { U32 n; for (n=0; n<oSize; n++) {
280 if (huffWeight[n] > HUF_TABLELOG_MAX) return ERROR(corruption_detected);
281 rankStats[huffWeight[n]]++;
282 weightTotal += (1 << huffWeight[n]) >> 1;
284 if (weightTotal == 0) return ERROR(corruption_detected);
286 /* get last non-null symbol weight (implied, total must be 2^n) */
287 { U32 const tableLog = ZSTD_highbit32(weightTotal) + 1;
288 if (tableLog > HUF_TABLELOG_MAX) return ERROR(corruption_detected);
289 *tableLogPtr = tableLog;
290 /* determine last weight */
291 { U32 const total = 1 << tableLog;
292 U32 const rest = total - weightTotal;
293 U32 const verif = 1 << ZSTD_highbit32(rest);
294 U32 const lastWeight = ZSTD_highbit32(rest) + 1;
295 if (verif != rest) return ERROR(corruption_detected); /* last value must be a clean power of 2 */
296 huffWeight[oSize] = (BYTE)lastWeight;
297 rankStats[lastWeight]++;
300 /* check tree construction validity */
301 if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected); /* by construction : at least 2 elts of rank 1, must be even */
304 *nbSymbolsPtr = (U32)(oSize+1);
308 /* Avoids the FORCE_INLINE of the _body() function. */
309 static size_t HUF_readStats_body_default(BYTE* huffWeight, size_t hwSize, U32* rankStats,
310 U32* nbSymbolsPtr, U32* tableLogPtr,
311 const void* src, size_t srcSize,
312 void* workSpace, size_t wkspSize)
314 return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 0);
318 static BMI2_TARGET_ATTRIBUTE size_t HUF_readStats_body_bmi2(BYTE* huffWeight, size_t hwSize, U32* rankStats,
319 U32* nbSymbolsPtr, U32* tableLogPtr,
320 const void* src, size_t srcSize,
321 void* workSpace, size_t wkspSize)
323 return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 1);
327 size_t HUF_readStats_wksp(BYTE* huffWeight, size_t hwSize, U32* rankStats,
328 U32* nbSymbolsPtr, U32* tableLogPtr,
329 const void* src, size_t srcSize,
330 void* workSpace, size_t wkspSize,
334 if (flags & HUF_flags_bmi2) {
335 return HUF_readStats_body_bmi2(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize);
339 return HUF_readStats_body_default(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize);