Path: blob/master/Utilities/cmzstd/lib/common/entropy_common.c
3158 views
/* ******************************************************************1* Common functions of New Generation Entropy library2* Copyright (c) Meta Platforms, Inc. and affiliates.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#include "huf.h"22#include "bits.h" /* ZSDT_highbit32, ZSTD_countTrailingZeros32 */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****************************************************************/40FORCE_INLINE_TEMPLATE41size_t FSE_readNCount_body(short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,42const void* headerBuffer, size_t hbSize)43{44const BYTE* const istart = (const BYTE*) headerBuffer;45const BYTE* const iend = istart + hbSize;46const BYTE* ip = istart;47int nbBits;48int remaining;49int threshold;50U32 bitStream;51int bitCount;52unsigned charnum = 0;53unsigned const maxSV1 = *maxSVPtr + 1;54int previous0 = 0;5556if (hbSize < 8) {57/* This function only works when hbSize >= 8 */58char buffer[8] = {0};59ZSTD_memcpy(buffer, headerBuffer, hbSize);60{ size_t const countSize = FSE_readNCount(normalizedCounter, maxSVPtr, tableLogPtr,61buffer, sizeof(buffer));62if (FSE_isError(countSize)) return countSize;63if (countSize > hbSize) return ERROR(corruption_detected);64return countSize;65} }66assert(hbSize >= 8);6768/* init */69ZSTD_memset(normalizedCounter, 0, (*maxSVPtr+1) * sizeof(normalizedCounter[0])); /* all symbols not present in NCount have a frequency of 0 */70bitStream = MEM_readLE32(ip);71nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG; /* extract tableLog */72if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);73bitStream >>= 4;74bitCount = 4;75*tableLogPtr = nbBits;76remaining = (1<<nbBits)+1;77threshold = 1<<nbBits;78nbBits++;7980for (;;) {81if (previous0) {82/* Count the number of repeats. Each time the83* 2-bit repeat code is 0b11 there is another84* repeat.85* Avoid UB by setting the high bit to 1.86*/87int repeats = ZSTD_countTrailingZeros32(~bitStream | 0x80000000) >> 1;88while (repeats >= 12) {89charnum += 3 * 12;90if (LIKELY(ip <= iend-7)) {91ip += 3;92} else {93bitCount -= (int)(8 * (iend - 7 - ip));94bitCount &= 31;95ip = iend - 4;96}97bitStream = MEM_readLE32(ip) >> bitCount;98repeats = ZSTD_countTrailingZeros32(~bitStream | 0x80000000) >> 1;99}100charnum += 3 * repeats;101bitStream >>= 2 * repeats;102bitCount += 2 * repeats;103104/* Add the final repeat which isn't 0b11. */105assert((bitStream & 3) < 3);106charnum += bitStream & 3;107bitCount += 2;108109/* This is an error, but break and return an error110* at the end, because returning out of a loop makes111* it harder for the compiler to optimize.112*/113if (charnum >= maxSV1) break;114115/* We don't need to set the normalized count to 0116* because we already memset the whole buffer to 0.117*/118119if (LIKELY(ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {120assert((bitCount >> 3) <= 3); /* For first condition to work */121ip += bitCount>>3;122bitCount &= 7;123} else {124bitCount -= (int)(8 * (iend - 4 - ip));125bitCount &= 31;126ip = iend - 4;127}128bitStream = MEM_readLE32(ip) >> bitCount;129}130{131int const max = (2*threshold-1) - remaining;132int count;133134if ((bitStream & (threshold-1)) < (U32)max) {135count = bitStream & (threshold-1);136bitCount += nbBits-1;137} else {138count = bitStream & (2*threshold-1);139if (count >= threshold) count -= max;140bitCount += nbBits;141}142143count--; /* extra accuracy */144/* When it matters (small blocks), this is a145* predictable branch, because we don't use -1.146*/147if (count >= 0) {148remaining -= count;149} else {150assert(count == -1);151remaining += count;152}153normalizedCounter[charnum++] = (short)count;154previous0 = !count;155156assert(threshold > 1);157if (remaining < threshold) {158/* This branch can be folded into the159* threshold update condition because we160* know that threshold > 1.161*/162if (remaining <= 1) break;163nbBits = ZSTD_highbit32(remaining) + 1;164threshold = 1 << (nbBits - 1);165}166if (charnum >= maxSV1) break;167168if (LIKELY(ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {169ip += bitCount>>3;170bitCount &= 7;171} else {172bitCount -= (int)(8 * (iend - 4 - ip));173bitCount &= 31;174ip = iend - 4;175}176bitStream = MEM_readLE32(ip) >> bitCount;177} }178if (remaining != 1) return ERROR(corruption_detected);179/* Only possible when there are too many zeros. */180if (charnum > maxSV1) return ERROR(maxSymbolValue_tooSmall);181if (bitCount > 32) return ERROR(corruption_detected);182*maxSVPtr = charnum-1;183184ip += (bitCount+7)>>3;185return ip-istart;186}187188/* Avoids the FORCE_INLINE of the _body() function. */189static size_t FSE_readNCount_body_default(190short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,191const void* headerBuffer, size_t hbSize)192{193return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);194}195196#if DYNAMIC_BMI2197BMI2_TARGET_ATTRIBUTE static size_t FSE_readNCount_body_bmi2(198short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,199const void* headerBuffer, size_t hbSize)200{201return FSE_readNCount_body(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);202}203#endif204205size_t FSE_readNCount_bmi2(206short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,207const void* headerBuffer, size_t hbSize, int bmi2)208{209#if DYNAMIC_BMI2210if (bmi2) {211return FSE_readNCount_body_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);212}213#endif214(void)bmi2;215return FSE_readNCount_body_default(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize);216}217218size_t FSE_readNCount(219short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,220const void* headerBuffer, size_t hbSize)221{222return FSE_readNCount_bmi2(normalizedCounter, maxSVPtr, tableLogPtr, headerBuffer, hbSize, /* bmi2 */ 0);223}224225226/*! HUF_readStats() :227Read compact Huffman tree, saved by HUF_writeCTable().228`huffWeight` is destination buffer.229`rankStats` is assumed to be a table of at least HUF_TABLELOG_MAX U32.230@return : size read from `src` , or an error Code .231Note : Needed by HUF_readCTable() and HUF_readDTableX?() .232*/233size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,234U32* nbSymbolsPtr, U32* tableLogPtr,235const void* src, size_t srcSize)236{237U32 wksp[HUF_READ_STATS_WORKSPACE_SIZE_U32];238return HUF_readStats_wksp(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, wksp, sizeof(wksp), /* flags */ 0);239}240241FORCE_INLINE_TEMPLATE size_t242HUF_readStats_body(BYTE* huffWeight, size_t hwSize, U32* rankStats,243U32* nbSymbolsPtr, U32* tableLogPtr,244const void* src, size_t srcSize,245void* workSpace, size_t wkspSize,246int bmi2)247{248U32 weightTotal;249const BYTE* ip = (const BYTE*) src;250size_t iSize;251size_t oSize;252253if (!srcSize) return ERROR(srcSize_wrong);254iSize = ip[0];255/* ZSTD_memset(huffWeight, 0, hwSize); *//* is not necessary, even though some analyzer complain ... */256257if (iSize >= 128) { /* special header */258oSize = iSize - 127;259iSize = ((oSize+1)/2);260if (iSize+1 > srcSize) return ERROR(srcSize_wrong);261if (oSize >= hwSize) return ERROR(corruption_detected);262ip += 1;263{ U32 n;264for (n=0; n<oSize; n+=2) {265huffWeight[n] = ip[n/2] >> 4;266huffWeight[n+1] = ip[n/2] & 15;267} } }268else { /* header compressed with FSE (normal case) */269if (iSize+1 > srcSize) return ERROR(srcSize_wrong);270/* max (hwSize-1) values decoded, as last one is implied */271oSize = FSE_decompress_wksp_bmi2(huffWeight, hwSize-1, ip+1, iSize, 6, workSpace, wkspSize, bmi2);272if (FSE_isError(oSize)) return oSize;273}274275/* collect weight stats */276ZSTD_memset(rankStats, 0, (HUF_TABLELOG_MAX + 1) * sizeof(U32));277weightTotal = 0;278{ U32 n; for (n=0; n<oSize; n++) {279if (huffWeight[n] > HUF_TABLELOG_MAX) return ERROR(corruption_detected);280rankStats[huffWeight[n]]++;281weightTotal += (1 << huffWeight[n]) >> 1;282} }283if (weightTotal == 0) return ERROR(corruption_detected);284285/* get last non-null symbol weight (implied, total must be 2^n) */286{ U32 const tableLog = ZSTD_highbit32(weightTotal) + 1;287if (tableLog > HUF_TABLELOG_MAX) return ERROR(corruption_detected);288*tableLogPtr = tableLog;289/* determine last weight */290{ U32 const total = 1 << tableLog;291U32 const rest = total - weightTotal;292U32 const verif = 1 << ZSTD_highbit32(rest);293U32 const lastWeight = ZSTD_highbit32(rest) + 1;294if (verif != rest) return ERROR(corruption_detected); /* last value must be a clean power of 2 */295huffWeight[oSize] = (BYTE)lastWeight;296rankStats[lastWeight]++;297} }298299/* check tree construction validity */300if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected); /* by construction : at least 2 elts of rank 1, must be even */301302/* results */303*nbSymbolsPtr = (U32)(oSize+1);304return iSize+1;305}306307/* Avoids the FORCE_INLINE of the _body() function. */308static size_t HUF_readStats_body_default(BYTE* huffWeight, size_t hwSize, U32* rankStats,309U32* nbSymbolsPtr, U32* tableLogPtr,310const void* src, size_t srcSize,311void* workSpace, size_t wkspSize)312{313return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 0);314}315316#if DYNAMIC_BMI2317static BMI2_TARGET_ATTRIBUTE size_t HUF_readStats_body_bmi2(BYTE* huffWeight, size_t hwSize, U32* rankStats,318U32* nbSymbolsPtr, U32* tableLogPtr,319const void* src, size_t srcSize,320void* workSpace, size_t wkspSize)321{322return HUF_readStats_body(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize, 1);323}324#endif325326size_t HUF_readStats_wksp(BYTE* huffWeight, size_t hwSize, U32* rankStats,327U32* nbSymbolsPtr, U32* tableLogPtr,328const void* src, size_t srcSize,329void* workSpace, size_t wkspSize,330int flags)331{332#if DYNAMIC_BMI2333if (flags & HUF_flags_bmi2) {334return HUF_readStats_body_bmi2(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize);335}336#endif337(void)flags;338return HUF_readStats_body_default(huffWeight, hwSize, rankStats, nbSymbolsPtr, tableLogPtr, src, srcSize, workSpace, wkspSize);339}340341342