Path: blob/main/sys/contrib/zstd/lib/common/entropy_common.c
48378 views
/* ******************************************************************1* Common functions of New Generation Entropy library2* Copyright (c) Yann Collet, Facebook, Inc.3*4* You can contact the author at :5* - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy6* - Public forum : https://groups.google.com/forum/#!forum/lz4c7*8* This source code is licensed under both the BSD-style license (found in the9* LICENSE file in the root directory of this source tree) and the GPLv2 (found10* in the COPYING file in the root directory of this source tree).11* You may select, at your option, one of the above-listed licenses.12****************************************************************** */1314/* *************************************15* Dependencies16***************************************/17#include "mem.h"18#include "error_private.h" /* ERR_*, ERROR */19#define FSE_STATIC_LINKING_ONLY /* FSE_MIN_TABLELOG */20#include "fse.h"21#define HUF_STATIC_LINKING_ONLY /* HUF_TABLELOG_ABSOLUTEMAX */22#include "huf.h"232425/*=== Version ===*/26unsigned FSE_versionNumber(void) { return FSE_VERSION_NUMBER; }272829/*=== Error Management ===*/30unsigned FSE_isError(size_t code) { return ERR_isError(code); }31const char* FSE_getErrorName(size_t code) { return ERR_getErrorName(code); }3233unsigned HUF_isError(size_t code) { return ERR_isError(code); }34const char* HUF_getErrorName(size_t code) { return ERR_getErrorName(code); }353637/*-**************************************************************38* FSE NCount encoding-decoding39****************************************************************/40static U32 FSE_ctz(U32 val)41{42assert(val != 0);43{44# if defined(_MSC_VER) /* Visual */45if (val != 0) {46unsigned long r;47_BitScanForward(&r, val);48return (unsigned)r;49} else {50/* Should not reach this code path */51__assume(0);52}53# elif defined(__GNUC__) && (__GNUC__ >= 3) /* GCC Intrinsic */54return __builtin_ctz(val);55# elif defined(__ICCARM__) /* IAR Intrinsic */56return __CTZ(val);57# else /* Software version */58U32 count = 0;59while ((val & 1) == 0) {60val >>= 1;61++count;62}63return count;64# endif65}66}6768FORCE_INLINE_TEMPLATE69size_t FSE_readNCount_body(short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,70const void* headerBuffer, size_t hbSize)71{72const BYTE* const istart = (const BYTE*) headerBuffer;73const BYTE* const iend = istart + hbSize;74const BYTE* ip = istart;75int nbBits;76int remaining;77int threshold;78U32 bitStream;79int bitCount;80unsigned charnum = 0;81unsigned const maxSV1 = *maxSVPtr + 1;82int previous0 = 0;8384if (hbSize < 8) {85/* This function only works when hbSize >= 8 */86char buffer[8] = {0};87ZSTD_memcpy(buffer, headerBuffer, hbSize);88{ size_t const countSize = FSE_readNCount(normalizedCounter, maxSVPtr, tableLogPtr,89buffer, sizeof(buffer));90if (FSE_isError(countSize)) return countSize;91if (countSize > hbSize) return ERROR(corruption_detected);92return countSize;93} }94assert(hbSize >= 8);9596/* init */97ZSTD_memset(normalizedCounter, 0, (*maxSVPtr+1) * sizeof(normalizedCounter[0])); /* all symbols not present in NCount have a frequency of 0 */98bitStream = MEM_readLE32(ip);99nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG; /* extract tableLog */100if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);101bitStream >>= 4;102bitCount = 4;103*tableLogPtr = nbBits;104remaining = (1<<nbBits)+1;105threshold = 1<<nbBits;106nbBits++;107108for (;;) {109if (previous0) {110/* Count the number of repeats. Each time the111* 2-bit repeat code is 0b11 there is another112* repeat.113* Avoid UB by setting the high bit to 1.114*/115int repeats = FSE_ctz(~bitStream | 0x80000000) >> 1;116while (repeats >= 12) {117charnum += 3 * 12;118if (LIKELY(ip <= iend-7)) {119ip += 3;120} else {121bitCount -= (int)(8 * (iend - 7 - ip));122bitCount &= 31;123ip = iend - 4;124}125bitStream = MEM_readLE32(ip) >> bitCount;126repeats = FSE_ctz(~bitStream | 0x80000000) >> 1;127}128charnum += 3 * repeats;129bitStream >>= 2 * repeats;130bitCount += 2 * repeats;131132/* Add the final repeat which isn't 0b11. */133assert((bitStream & 3) < 3);134charnum += bitStream & 3;135bitCount += 2;136137/* This is an error, but break and return an error138* at the end, because returning out of a loop makes139* it harder for the compiler to optimize.140*/141if (charnum >= maxSV1) break;142143/* We don't need to set the normalized count to 0144* because we already memset the whole buffer to 0.145*/146147if (LIKELY(ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {148assert((bitCount >> 3) <= 3); /* For first condition to work */149ip += bitCount>>3;150bitCount &= 7;151} else {152bitCount -= (int)(8 * (iend - 4 - ip));153bitCount &= 31;154ip = iend - 4;155}156bitStream = MEM_readLE32(ip) >> bitCount;157}158{159int const max = (2*threshold-1) - remaining;160int count;161162if ((bitStream & (threshold-1)) < (U32)max) {163count = bitStream & (threshold-1);164bitCount += nbBits-1;165} else {166count = bitStream & (2*threshold-1);167if (count >= threshold) count -= max;168bitCount += nbBits;169}170171count--; /* extra accuracy */172/* When it matters (small blocks), this is a173* predictable branch, because we don't use -1.174*/175if (count >= 0) {176remaining -= count;177} else {178assert(count == -1);179remaining += count;180}181normalizedCounter[charnum++] = (short)count;182previous0 = !count;183184assert(threshold > 1);185if (remaining < threshold) {186/* This branch can be folded into the187* threshold update condition because we188* know that threshold > 1.189*/190if (remaining <= 1) break;191nbBits = BIT_highbit32(remaining) + 1;192threshold = 1 << (nbBits - 1);193}194if (charnum >= maxSV1) break;195196if (LIKELY(ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {197ip += bitCount>>3;198bitCount &= 7;199} else {200bitCount -= (int)(8 * (iend - 4 - ip));201bitCount &= 31;202ip = iend - 4;203}204bitStream = MEM_readLE32(ip) >> bitCount;205} }206if (remaining != 1) return ERROR(corruption_detected);207/* Only possible when there are too many zeros. */208if (charnum > maxSV1) return ERROR(maxSymbolValue_tooSmall);209if (bitCount > 32) return ERROR(corruption_detected);210*maxSVPtr = charnum-1;211212ip += (bitCount+7)>>3;213return ip-istart;214}215216/* Avoids the FORCE_INLINE of the _body() function. */217static size_t FSE_readNCount_body_default(218short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,219const void* headerBuffer, size_t hbSize)220{221return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);222}223224#if DYNAMIC_BMI2225BMI2_TARGET_ATTRIBUTE static size_t FSE_readNCount_body_bmi2(226short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,227const void* headerBuffer, size_t hbSize)228{229return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);230}231#endif232233size_t FSE_readNCount_bmi2(234short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,235const void* headerBuffer, size_t hbSize, int bmi2)236{237#if DYNAMIC_BMI2238if (bmi2) {239return FSE_readNCount_body_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);240}241#endif242(void)bmi2;243return FSE_readNCount_body_default(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);244}245246size_t FSE_readNCount(247short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,248const void* headerBuffer, size_t hbSize)249{250return FSE_readNCount_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize, /* bmi2 */ 0);251}252253254/*! HUF_readStats() :255Read compact Huffman tree, saved by HUF_writeCTable().256`huffWeight` is destination buffer.257`rankStats` is assumed to be a table of at least HUF_TABLELOG_MAX U32.258@return : size read from `src` , or an error Code .259Note : Needed by HUF_readCTable() and HUF_readDTableX?() .260*/261size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,262U32* nbSymbolsPtr, U32* tableLogPtr,263const void* src, size_t srcSize)264{265U32 wksp[HUF_READ_STATS_WORKSPACE_SIZE_U32];266return HUF_readStats_wksp(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, wksp, sizeof(wksp), /* bmi2 */ 0);267}268269FORCE_INLINE_TEMPLATE size_t270HUF_readStats_body(BYTE* huffWeight, size_t hwSize, U32* rankStats,271U32* nbSymbolsPtr, U32* tableLogPtr,272const void* src, size_t srcSize,273void* workSpace, size_t wkspSize,274int bmi2)275{276U32 weightTotal;277const BYTE* ip = (const BYTE*) src;278size_t iSize;279size_t oSize;280281if (!srcSize) return ERROR(srcSize_wrong);282iSize = ip[0];283/* ZSTD_memset(huffWeight, 0, hwSize); *//* is not necessary, even though some analyzer complain ... */284285if (iSize >= 128) { /* special header */286oSize = iSize - 127;287iSize = ((oSize+1)/2);288if (iSize+1 > srcSize) return ERROR(srcSize_wrong);289if (oSize >= hwSize) return ERROR(corruption_detected);290ip += 1;291{ U32 n;292for (n=0; n<oSize; n+=2) {293huffWeight[n] = ip[n/2] >> 4;294huffWeight[n+1] = ip[n/2] & 15;295} } }296else { /* header compressed with FSE (normal case) */297if (iSize+1 > srcSize) return ERROR(srcSize_wrong);298/* max (hwSize-1) values decoded, as last one is implied */299oSize = FSE_decompress_wksp_bmi2(huffWeight, hwSize-1, ip+1, iSize, 6, workSpace, wkspSize, bmi2);300if (FSE_isError(oSize)) return oSize;301}302303/* collect weight stats */304ZSTD_memset(rankStats, 0, (HUF_TABLELOG_MAX + 1) * sizeof(U32));305weightTotal = 0;306{ U32 n; for (n=0; n<oSize; n++) {307if (huffWeight[n] > HUF_TABLELOG_MAX) return ERROR(corruption_detected);308rankStats[huffWeight[n]]++;309weightTotal += (1 << huffWeight[n]) >> 1;310} }311if (weightTotal == 0) return ERROR(corruption_detected);312313/* get last non-null symbol weight (implied, total must be 2^n) */314{ U32 const tableLog = BIT_highbit32(weightTotal) + 1;315if (tableLog > HUF_TABLELOG_MAX) return ERROR(corruption_detected);316*tableLogPtr = tableLog;317/* determine last weight */318{ U32 const total = 1 << tableLog;319U32 const rest = total - weightTotal;320U32 const verif = 1 << BIT_highbit32(rest);321U32 const lastWeight = BIT_highbit32(rest) + 1;322if (verif != rest) return ERROR(corruption_detected); /* last value must be a clean power of 2 */323huffWeight[oSize] = (BYTE)lastWeight;324rankStats[lastWeight]++;325} }326327/* check tree construction validity */328if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected); /* by construction : at least 2 elts of rank 1, must be even */329330/* results */331*nbSymbolsPtr = (U32)(oSize+1);332return iSize+1;333}334335/* Avoids the FORCE_INLINE of the _body() function. */336static size_t HUF_readStats_body_default(BYTE* huffWeight, size_t hwSize, U32* rankStats,337U32* nbSymbolsPtr, U32* tableLogPtr,338const void* src, size_t srcSize,339void* workSpace, size_t wkspSize)340{341return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 0);342}343344#if DYNAMIC_BMI2345static BMI2_TARGET_ATTRIBUTE size_t HUF_readStats_body_bmi2(BYTE* huffWeight, size_t hwSize, U32* rankStats,346U32* nbSymbolsPtr, U32* tableLogPtr,347const void* src, size_t srcSize,348void* workSpace, size_t wkspSize)349{350return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 1);351}352#endif353354size_t HUF_readStats_wksp(BYTE* huffWeight, size_t hwSize, U32* rankStats,355U32* nbSymbolsPtr, U32* tableLogPtr,356const void* src, size_t srcSize,357void* workSpace, size_t wkspSize,358int bmi2)359{360#if DYNAMIC_BMI2361if (bmi2) {362return HUF_readStats_body_bmi2(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize);363}364#endif365(void)bmi2;366return HUF_readStats_body_default(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize);367}368369370