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 */
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 ****************************************************************/
41 static U32 FSE_ctz(U32 val)
45 # if (__GNUC__ >= 3) /* GCC Intrinsic */
46 return __builtin_ctz(val);
47 # else /* Software version */
49 while ((val & 1) == 0) {
59 size_t FSE_readNCount_body(short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
60 const void* headerBuffer, size_t hbSize)
62 const BYTE* const istart = (const BYTE*) headerBuffer;
63 const BYTE* const iend = istart + hbSize;
64 const BYTE* ip = istart;
71 unsigned const maxSV1 = *maxSVPtr + 1;
75 /* This function only works when hbSize >= 8 */
77 ZSTD_memcpy(buffer, headerBuffer, hbSize);
78 { size_t const countSize = FSE_readNCount(normalizedCounter, maxSVPtr, tableLogPtr,
79 buffer, sizeof(buffer));
80 if (FSE_isError(countSize)) return countSize;
81 if (countSize > hbSize) return ERROR(corruption_detected);
87 ZSTD_memset(normalizedCounter, 0, (*maxSVPtr+1) * sizeof(normalizedCounter[0])); /* all symbols not present in NCount have a frequency of 0 */
88 bitStream = MEM_readLE32(ip);
89 nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG; /* extract tableLog */
90 if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);
93 *tableLogPtr = nbBits;
94 remaining = (1<<nbBits)+1;
95 threshold = 1<<nbBits;
100 /* Count the number of repeats. Each time the
101 * 2-bit repeat code is 0b11 there is another
103 * Avoid UB by setting the high bit to 1.
105 int repeats = FSE_ctz(~bitStream | 0x80000000) >> 1;
106 while (repeats >= 12) {
108 if (LIKELY(ip <= iend-7)) {
111 bitCount -= (int)(8 * (iend - 7 - ip));
115 bitStream = MEM_readLE32(ip) >> bitCount;
116 repeats = FSE_ctz(~bitStream | 0x80000000) >> 1;
118 charnum += 3 * repeats;
119 bitStream >>= 2 * repeats;
120 bitCount += 2 * repeats;
122 /* Add the final repeat which isn't 0b11. */
123 assert((bitStream & 3) < 3);
124 charnum += bitStream & 3;
127 /* This is an error, but break and return an error
128 * at the end, because returning out of a loop makes
129 * it harder for the compiler to optimize.
131 if (charnum >= maxSV1) break;
133 /* We don't need to set the normalized count to 0
134 * because we already memset the whole buffer to 0.
137 if (LIKELY(ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
138 assert((bitCount >> 3) <= 3); /* For first condition to work */
142 bitCount -= (int)(8 * (iend - 4 - ip));
146 bitStream = MEM_readLE32(ip) >> bitCount;
149 int const max = (2*threshold-1) - remaining;
152 if ((bitStream & (threshold-1)) < (U32)max) {
153 count = bitStream & (threshold-1);
154 bitCount += nbBits-1;
156 count = bitStream & (2*threshold-1);
157 if (count >= threshold) count -= max;
161 count--; /* extra accuracy */
162 /* When it matters (small blocks), this is a
163 * predictable branch, because we don't use -1.
171 normalizedCounter[charnum++] = (short)count;
174 assert(threshold > 1);
175 if (remaining < threshold) {
176 /* This branch can be folded into the
177 * threshold update condition because we
178 * know that threshold > 1.
180 if (remaining <= 1) break;
181 nbBits = BIT_highbit32(remaining) + 1;
182 threshold = 1 << (nbBits - 1);
184 if (charnum >= maxSV1) break;
186 if (LIKELY(ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
190 bitCount -= (int)(8 * (iend - 4 - ip));
194 bitStream = MEM_readLE32(ip) >> bitCount;
196 if (remaining != 1) return ERROR(corruption_detected);
197 /* Only possible when there are too many zeros. */
198 if (charnum > maxSV1) return ERROR(maxSymbolValue_tooSmall);
199 if (bitCount > 32) return ERROR(corruption_detected);
200 *maxSVPtr = charnum-1;
202 ip += (bitCount+7)>>3;
206 /* Avoids the FORCE_INLINE of the _body() function. */
207 static size_t FSE_readNCount_body_default(
208 short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
209 const void* headerBuffer, size_t hbSize)
211 return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
215 BMI2_TARGET_ATTRIBUTE static size_t FSE_readNCount_body_bmi2(
216 short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
217 const void* headerBuffer, size_t hbSize)
219 return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
223 size_t FSE_readNCount_bmi2(
224 short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
225 const void* headerBuffer, size_t hbSize, int bmi2)
229 return FSE_readNCount_body_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
233 return FSE_readNCount_body_default(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);
236 size_t FSE_readNCount(
237 short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
238 const void* headerBuffer, size_t hbSize)
240 return FSE_readNCount_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize, /* bmi2 */ 0);
244 /*! HUF_readStats() :
245 Read compact Huffman tree, saved by HUF_writeCTable().
246 `huffWeight` is destination buffer.
247 `rankStats` is assumed to be a table of at least HUF_TABLELOG_MAX U32.
248 @return : size read from `src` , or an error Code .
249 Note : Needed by HUF_readCTable() and HUF_readDTableX?() .
251 size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,
252 U32* nbSymbolsPtr, U32* tableLogPtr,
253 const void* src, size_t srcSize)
255 U32 wksp[HUF_READ_STATS_WORKSPACE_SIZE_U32];
256 return HUF_readStats_wksp(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, wksp, sizeof(wksp), /* bmi2 */ 0);
259 FORCE_INLINE_TEMPLATE size_t
260 HUF_readStats_body(BYTE* huffWeight, size_t hwSize, U32* rankStats,
261 U32* nbSymbolsPtr, U32* tableLogPtr,
262 const void* src, size_t srcSize,
263 void* workSpace, size_t wkspSize,
267 const BYTE* ip = (const BYTE*) src;
271 if (!srcSize) return ERROR(srcSize_wrong);
273 /* ZSTD_memset(huffWeight, 0, hwSize); *//* is not necessary, even though some analyzer complain ... */
275 if (iSize >= 128) { /* special header */
277 iSize = ((oSize+1)/2);
278 if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
279 if (oSize >= hwSize) return ERROR(corruption_detected);
282 for (n=0; n<oSize; n+=2) {
283 huffWeight[n] = ip[n/2] >> 4;
284 huffWeight[n+1] = ip[n/2] & 15;
286 else { /* header compressed with FSE (normal case) */
287 if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
288 /* max (hwSize-1) values decoded, as last one is implied */
289 oSize = FSE_decompress_wksp_bmi2(huffWeight, hwSize-1, ip+1, iSize, 6, workSpace, wkspSize, bmi2);
290 if (FSE_isError(oSize)) return oSize;
293 /* collect weight stats */
294 ZSTD_memset(rankStats, 0, (HUF_TABLELOG_MAX + 1) * sizeof(U32));
296 { U32 n; for (n=0; n<oSize; n++) {
297 if (huffWeight[n] > HUF_TABLELOG_MAX) return ERROR(corruption_detected);
298 rankStats[huffWeight[n]]++;
299 weightTotal += (1 << huffWeight[n]) >> 1;
301 if (weightTotal == 0) return ERROR(corruption_detected);
303 /* get last non-null symbol weight (implied, total must be 2^n) */
304 { U32 const tableLog = BIT_highbit32(weightTotal) + 1;
305 if (tableLog > HUF_TABLELOG_MAX) return ERROR(corruption_detected);
306 *tableLogPtr = tableLog;
307 /* determine last weight */
308 { U32 const total = 1 << tableLog;
309 U32 const rest = total - weightTotal;
310 U32 const verif = 1 << BIT_highbit32(rest);
311 U32 const lastWeight = BIT_highbit32(rest) + 1;
312 if (verif != rest) return ERROR(corruption_detected); /* last value must be a clean power of 2 */
313 huffWeight[oSize] = (BYTE)lastWeight;
314 rankStats[lastWeight]++;
317 /* check tree construction validity */
318 if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected); /* by construction : at least 2 elts of rank 1, must be even */
321 *nbSymbolsPtr = (U32)(oSize+1);
325 /* Avoids the FORCE_INLINE of the _body() function. */
326 static size_t HUF_readStats_body_default(BYTE* huffWeight, size_t hwSize, U32* rankStats,
327 U32* nbSymbolsPtr, U32* tableLogPtr,
328 const void* src, size_t srcSize,
329 void* workSpace, size_t wkspSize)
331 return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 0);
335 static BMI2_TARGET_ATTRIBUTE size_t HUF_readStats_body_bmi2(BYTE* huffWeight, size_t hwSize, U32* rankStats,
336 U32* nbSymbolsPtr, U32* tableLogPtr,
337 const void* src, size_t srcSize,
338 void* workSpace, size_t wkspSize)
340 return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 1);
344 size_t HUF_readStats_wksp(BYTE* huffWeight, size_t hwSize, U32* rankStats,
345 U32* nbSymbolsPtr, U32* tableLogPtr,
346 const void* src, size_t srcSize,
347 void* workSpace, size_t wkspSize,
352 return HUF_readStats_body_bmi2(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize);
356 return HUF_readStats_body_default(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize);