1 /* ******************************************************************
2 * Common functions of New Generation Entropy library
3 * Copyright (c) Yann Collet, Facebook, Inc.
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 */
22 #define HUF_STATIC_LINKING_ONLY /* HUF_TABLELOG_ABSOLUTEMAX */
26 unsigned FSE_versionNumber(void) { return FSE_VERSION_NUMBER; }
28 /*=== Error Management ===*/
29 unsigned FSE_isError(size_t code) { return ERR_isError(code); }
30 const char* FSE_getErrorName(size_t code) { return ERR_getErrorName(code); }
32 unsigned HUF_isError(size_t code) { return ERR_isError(code); }
33 const char* HUF_getErrorName(size_t code) { return ERR_getErrorName(code); }
35 /*-**************************************************************
36 * FSE NCount encoding-decoding
37 ****************************************************************/
38 static U32 FSE_ctz(U32 val)
42 # if (__GNUC__ >= 3) /* GCC Intrinsic */
43 return __builtin_ctz(val);
44 # else /* Software version */
46 while ((val & 1) == 0) {
56 size_t FSE_readNCount_body(short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
57 const void* headerBuffer, size_t hbSize)
59 const BYTE* const istart = (const BYTE*) headerBuffer;
60 const BYTE* const iend = istart + hbSize;
61 const BYTE* ip = istart;
68 unsigned const maxSV1 = *maxSVPtr + 1;
72 /* This function only works when hbSize >= 8 */
74 ZSTD_memcpy(buffer, headerBuffer, hbSize);
75 { size_t const countSize = FSE_readNCount(normalizedCounter, maxSVPtr, tableLogPtr,
76 buffer, sizeof(buffer));
77 if (FSE_isError(countSize)) return countSize;
78 if (countSize > hbSize) return ERROR(corruption_detected);
84 ZSTD_memset(normalizedCounter, 0, (*maxSVPtr+1) * sizeof(normalizedCounter[0])); /* all symbols not present in NCount have a frequency of 0 */
85 bitStream = MEM_readLE32(ip);
86 nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG; /* extract tableLog */
87 if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);
90 *tableLogPtr = nbBits;
91 remaining = (1<<nbBits)+1;
92 threshold = 1<<nbBits;
97 /* Count the number of repeats. Each time the
98 * 2-bit repeat code is 0b11 there is another
100 * Avoid UB by setting the high bit to 1.
102 int repeats = FSE_ctz(~bitStream | 0x80000000) >> 1;
103 while (repeats >= 12) {
105 if (LIKELY(ip <= iend-7)) {
108 bitCount -= (int)(8 * (iend - 7 - ip));
112 bitStream = MEM_readLE32(ip) >> bitCount;
113 repeats = FSE_ctz(~bitStream | 0x80000000) >> 1;
115 charnum += 3 * repeats;
116 bitStream >>= 2 * repeats;
117 bitCount += 2 * repeats;
119 /* Add the final repeat which isn't 0b11. */
120 assert((bitStream & 3) < 3);
121 charnum += bitStream & 3;
124 /* This is an error, but break and return an error
125 * at the end, because returning out of a loop makes
126 * it harder for the compiler to optimize.
128 if (charnum >= maxSV1) break;
130 /* We don't need to set the normalized count to 0
131 * because we already memset the whole buffer to 0.
134 if (LIKELY(ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
135 assert((bitCount >> 3) <= 3); /* For first condition to work */
139 bitCount -= (int)(8 * (iend - 4 - ip));
143 bitStream = MEM_readLE32(ip) >> bitCount;
146 int const max = (2*threshold-1) - remaining;
149 if ((bitStream & (threshold-1)) < (U32)max) {
150 count = bitStream & (threshold-1);
151 bitCount += nbBits-1;
153 count = bitStream & (2*threshold-1);
154 if (count >= threshold) count -= max;
158 count--; /* extra accuracy */
159 /* When it matters (small blocks), this is a
160 * predictable branch, because we don't use -1.
168 normalizedCounter[charnum++] = (short)count;
171 assert(threshold > 1);
172 if (remaining < threshold) {
173 /* This branch can be folded into the
174 * threshold update condition because we
175 * know that threshold > 1.
177 if (remaining <= 1) break;
178 nbBits = BIT_highbit32(remaining) + 1;
179 threshold = 1 << (nbBits - 1);
181 if (charnum >= maxSV1) break;
183 if (LIKELY(ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
187 bitCount -= (int)(8 * (iend - 4 - ip));
191 bitStream = MEM_readLE32(ip) >> bitCount;
193 if (remaining != 1) return ERROR(corruption_detected);
194 /* Only possible when there are too many zeros. */
195 if (charnum > maxSV1) return ERROR(maxSymbolValue_tooSmall);
196 if (bitCount > 32) return ERROR(corruption_detected);
197 *maxSVPtr = charnum-1;
199 ip += (bitCount+7)>>3;
203 /* Avoids the FORCE_INLINE of the _body() function. */
204 static size_t FSE_readNCount_body_default(
205 short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
206 const void* headerBuffer, size_t hbSize)
208 return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
212 BMI2_TARGET_ATTRIBUTE static size_t FSE_readNCount_body_bmi2(
213 short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
214 const void* headerBuffer, size_t hbSize)
216 return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
220 size_t FSE_readNCount_bmi2(
221 short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
222 const void* headerBuffer, size_t hbSize, int bmi2)
226 return FSE_readNCount_body_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
230 return FSE_readNCount_body_default(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
233 size_t FSE_readNCount(
234 short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
235 const void* headerBuffer, size_t hbSize)
237 return FSE_readNCount_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize, /* bmi2 */ 0);
240 /*! HUF_readStats() :
241 Read compact Huffman tree, saved by HUF_writeCTable().
242 `huffWeight` is destination buffer.
243 `rankStats` is assumed to be a table of at least HUF_TABLELOG_MAX U32.
244 @return : size read from `src` , or an error Code .
245 Note : Needed by HUF_readCTable() and HUF_readDTableX?() .
247 size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,
248 U32* nbSymbolsPtr, U32* tableLogPtr,
249 const void* src, size_t srcSize)
251 U32 wksp[HUF_READ_STATS_WORKSPACE_SIZE_U32];
252 return HUF_readStats_wksp(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, wksp, sizeof(wksp), /* bmi2 */ 0);
255 FORCE_INLINE_TEMPLATE size_t
256 HUF_readStats_body(BYTE* huffWeight, size_t hwSize, U32* rankStats,
257 U32* nbSymbolsPtr, U32* tableLogPtr,
258 const void* src, size_t srcSize,
259 void* workSpace, size_t wkspSize,
263 const BYTE* ip = (const BYTE*) src;
267 if (!srcSize) return ERROR(srcSize_wrong);
269 /* ZSTD_memset(huffWeight, 0, hwSize); *//* is not necessary, even though some analyzer complain ... */
271 if (iSize >= 128) { /* special header */
273 iSize = ((oSize+1)/2);
274 if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
275 if (oSize >= hwSize) return ERROR(corruption_detected);
278 for (n=0; n<oSize; n+=2) {
279 huffWeight[n] = ip[n/2] >> 4;
280 huffWeight[n+1] = ip[n/2] & 15;
282 else { /* header compressed with FSE (normal case) */
283 if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
284 /* max (hwSize-1) values decoded, as last one is implied */
285 oSize = FSE_decompress_wksp_bmi2(huffWeight, hwSize-1, ip+1, iSize, 6, workSpace, wkspSize, bmi2);
286 if (FSE_isError(oSize)) return oSize;
289 /* collect weight stats */
290 ZSTD_memset(rankStats, 0, (HUF_TABLELOG_MAX + 1) * sizeof(U32));
292 { U32 n; for (n=0; n<oSize; n++) {
293 if (huffWeight[n] > HUF_TABLELOG_MAX) return ERROR(corruption_detected);
294 rankStats[huffWeight[n]]++;
295 weightTotal += (1 << huffWeight[n]) >> 1;
297 if (weightTotal == 0) return ERROR(corruption_detected);
299 /* get last non-null symbol weight (implied, total must be 2^n) */
300 { U32 const tableLog = BIT_highbit32(weightTotal) + 1;
301 if (tableLog > HUF_TABLELOG_MAX) return ERROR(corruption_detected);
302 *tableLogPtr = tableLog;
303 /* determine last weight */
304 { U32 const total = 1 << tableLog;
305 U32 const rest = total - weightTotal;
306 U32 const verif = 1 << BIT_highbit32(rest);
307 U32 const lastWeight = BIT_highbit32(rest) + 1;
308 if (verif != rest) return ERROR(corruption_detected); /* last value must be a clean power of 2 */
309 huffWeight[oSize] = (BYTE)lastWeight;
310 rankStats[lastWeight]++;
313 /* check tree construction validity */
314 if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected); /* by construction : at least 2 elts of rank 1, must be even */
317 *nbSymbolsPtr = (U32)(oSize+1);
321 /* Avoids the FORCE_INLINE of the _body() function. */
322 static size_t HUF_readStats_body_default(BYTE* huffWeight, size_t hwSize, U32* rankStats,
323 U32* nbSymbolsPtr, U32* tableLogPtr,
324 const void* src, size_t srcSize,
325 void* workSpace, size_t wkspSize)
327 return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 0);
331 static BMI2_TARGET_ATTRIBUTE size_t HUF_readStats_body_bmi2(BYTE* huffWeight, size_t hwSize, U32* rankStats,
332 U32* nbSymbolsPtr, U32* tableLogPtr,
333 const void* src, size_t srcSize,
334 void* workSpace, size_t wkspSize)
336 return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 1);
340 size_t HUF_readStats_wksp(BYTE* huffWeight, size_t hwSize, U32* rankStats,
341 U32* nbSymbolsPtr, U32* tableLogPtr,
342 const void* src, size_t srcSize,
343 void* workSpace, size_t wkspSize,
348 return HUF_readStats_body_bmi2(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize);
352 return HUF_readStats_body_default(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize);