/* ******************************************************************1* huff0 huffman codec,2* part of Finite State Entropy library3* Copyright (c) Meta Platforms, Inc. and affiliates.4*5* You can contact the author at :6* - Source repository : https://github.com/Cyan4973/FiniteStateEntropy7*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#if defined (__cplusplus)15extern "C" {16#endif1718#ifndef HUF_H_29873423419#define HUF_H_2987342342021/* *** Dependencies *** */22#include "zstd_deps.h" /* size_t */23#include "mem.h" /* U32 */24#define FSE_STATIC_LINKING_ONLY25#include "fse.h"262728/* *** Tool functions *** */29#define HUF_BLOCKSIZE_MAX (128 * 1024) /**< maximum input size for a single block compressed with HUF_compress */30size_t HUF_compressBound(size_t size); /**< maximum compressed size (worst case) */3132/* Error Management */33unsigned HUF_isError(size_t code); /**< tells if a return value is an error code */34const char* HUF_getErrorName(size_t code); /**< provides error code string (useful for debugging) */353637#define HUF_WORKSPACE_SIZE ((8 << 10) + 512 /* sorting scratch space */)38#define HUF_WORKSPACE_SIZE_U64 (HUF_WORKSPACE_SIZE / sizeof(U64))3940/* *** Constants *** */41#define HUF_TABLELOG_MAX 12 /* max runtime value of tableLog (due to static allocation); can be modified up to HUF_TABLELOG_ABSOLUTEMAX */42#define HUF_TABLELOG_DEFAULT 11 /* default tableLog value when none specified */43#define HUF_SYMBOLVALUE_MAX 2554445#define HUF_TABLELOG_ABSOLUTEMAX 12 /* absolute limit of HUF_MAX_TABLELOG. Beyond that value, code does not work */46#if (HUF_TABLELOG_MAX > HUF_TABLELOG_ABSOLUTEMAX)47# error "HUF_TABLELOG_MAX is too large !"48#endif495051/* ****************************************52* Static allocation53******************************************/54/* HUF buffer bounds */55#define HUF_CTABLEBOUND 12956#define HUF_BLOCKBOUND(size) (size + (size>>8) + 8) /* only true when incompressible is pre-filtered with fast heuristic */57#define HUF_COMPRESSBOUND(size) (HUF_CTABLEBOUND + HUF_BLOCKBOUND(size)) /* Macro version, useful for static allocation */5859/* static allocation of HUF's Compression Table */60/* this is a private definition, just exposed for allocation and strict aliasing purpose. never EVER access its members directly */61typedef size_t HUF_CElt; /* consider it an incomplete type */62#define HUF_CTABLE_SIZE_ST(maxSymbolValue) ((maxSymbolValue)+2) /* Use tables of size_t, for proper alignment */63#define HUF_CTABLE_SIZE(maxSymbolValue) (HUF_CTABLE_SIZE_ST(maxSymbolValue) * sizeof(size_t))64#define HUF_CREATE_STATIC_CTABLE(name, maxSymbolValue) \65HUF_CElt name[HUF_CTABLE_SIZE_ST(maxSymbolValue)] /* no final ; */6667/* static allocation of HUF's DTable */68typedef U32 HUF_DTable;69#define HUF_DTABLE_SIZE(maxTableLog) (1 + (1<<(maxTableLog)))70#define HUF_CREATE_STATIC_DTABLEX1(DTable, maxTableLog) \71HUF_DTable DTable[HUF_DTABLE_SIZE((maxTableLog)-1)] = { ((U32)((maxTableLog)-1) * 0x01000001) }72#define HUF_CREATE_STATIC_DTABLEX2(DTable, maxTableLog) \73HUF_DTable DTable[HUF_DTABLE_SIZE(maxTableLog)] = { ((U32)(maxTableLog) * 0x01000001) }747576/* ****************************************77* Advanced decompression functions78******************************************/7980/**81* Huffman flags bitset.82* For all flags, 0 is the default value.83*/84typedef enum {85/**86* If compiled with DYNAMIC_BMI2: Set flag only if the CPU supports BMI2 at runtime.87* Otherwise: Ignored.88*/89HUF_flags_bmi2 = (1 << 0),90/**91* If set: Test possible table depths to find the one that produces the smallest header + encoded size.92* If unset: Use heuristic to find the table depth.93*/94HUF_flags_optimalDepth = (1 << 1),95/**96* If set: If the previous table can encode the input, always reuse the previous table.97* If unset: If the previous table can encode the input, reuse the previous table if it results in a smaller output.98*/99HUF_flags_preferRepeat = (1 << 2),100/**101* If set: Sample the input and check if the sample is uncompressible, if it is then don't attempt to compress.102* If unset: Always histogram the entire input.103*/104HUF_flags_suspectUncompressible = (1 << 3),105/**106* If set: Don't use assembly implementations107* If unset: Allow using assembly implementations108*/109HUF_flags_disableAsm = (1 << 4),110/**111* If set: Don't use the fast decoding loop, always use the fallback decoding loop.112* If unset: Use the fast decoding loop when possible.113*/114HUF_flags_disableFast = (1 << 5)115} HUF_flags_e;116117118/* ****************************************119* HUF detailed API120* ****************************************/121#define HUF_OPTIMAL_DEPTH_THRESHOLD ZSTD_btultra122123/*! HUF_compress() does the following:124* 1. count symbol occurrence from source[] into table count[] using FSE_count() (exposed within "fse.h")125* 2. (optional) refine tableLog using HUF_optimalTableLog()126* 3. build Huffman table from count using HUF_buildCTable()127* 4. save Huffman table to memory buffer using HUF_writeCTable()128* 5. encode the data stream using HUF_compress4X_usingCTable()129*130* The following API allows targeting specific sub-functions for advanced tasks.131* For example, it's possible to compress several blocks using the same 'CTable',132* or to save and regenerate 'CTable' using external methods.133*/134unsigned HUF_minTableLog(unsigned symbolCardinality);135unsigned HUF_cardinality(const unsigned* count, unsigned maxSymbolValue);136unsigned HUF_optimalTableLog(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, void* workSpace,137size_t wkspSize, HUF_CElt* table, const unsigned* count, int flags); /* table is used as scratch space for building and testing tables, not a return value */138size_t HUF_writeCTable_wksp(void* dst, size_t maxDstSize, const HUF_CElt* CTable, unsigned maxSymbolValue, unsigned huffLog, void* workspace, size_t workspaceSize);139size_t HUF_compress4X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable, int flags);140size_t HUF_estimateCompressedSize(const HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue);141int HUF_validateCTable(const HUF_CElt* CTable, const unsigned* count, unsigned maxSymbolValue);142143typedef enum {144HUF_repeat_none, /**< Cannot use the previous table */145HUF_repeat_check, /**< Can use the previous table but it must be checked. Note : The previous table must have been constructed by HUF_compress{1, 4}X_repeat */146HUF_repeat_valid /**< Can use the previous table and it is assumed to be valid */147} HUF_repeat;148149/** HUF_compress4X_repeat() :150* Same as HUF_compress4X_wksp(), but considers using hufTable if *repeat != HUF_repeat_none.151* If it uses hufTable it does not modify hufTable or repeat.152* If it doesn't, it sets *repeat = HUF_repeat_none, and it sets hufTable to the table used.153* If preferRepeat then the old table will always be used if valid.154* If suspectUncompressible then some sampling checks will be run to potentially skip huffman coding */155size_t HUF_compress4X_repeat(void* dst, size_t dstSize,156const void* src, size_t srcSize,157unsigned maxSymbolValue, unsigned tableLog,158void* workSpace, size_t wkspSize, /**< `workSpace` must be aligned on 4-bytes boundaries, `wkspSize` must be >= HUF_WORKSPACE_SIZE */159HUF_CElt* hufTable, HUF_repeat* repeat, int flags);160161/** HUF_buildCTable_wksp() :162* Same as HUF_buildCTable(), but using externally allocated scratch buffer.163* `workSpace` must be aligned on 4-bytes boundaries, and its size must be >= HUF_CTABLE_WORKSPACE_SIZE.164*/165#define HUF_CTABLE_WORKSPACE_SIZE_U32 ((4 * (HUF_SYMBOLVALUE_MAX + 1)) + 192)166#define HUF_CTABLE_WORKSPACE_SIZE (HUF_CTABLE_WORKSPACE_SIZE_U32 * sizeof(unsigned))167size_t HUF_buildCTable_wksp (HUF_CElt* tree,168const unsigned* count, U32 maxSymbolValue, U32 maxNbBits,169void* workSpace, size_t wkspSize);170171/*! HUF_readStats() :172* Read compact Huffman tree, saved by HUF_writeCTable().173* `huffWeight` is destination buffer.174* @return : size read from `src` , or an error Code .175* Note : Needed by HUF_readCTable() and HUF_readDTableXn() . */176size_t HUF_readStats(BYTE* huffWeight, size_t hwSize,177U32* rankStats, U32* nbSymbolsPtr, U32* tableLogPtr,178const void* src, size_t srcSize);179180/*! HUF_readStats_wksp() :181* Same as HUF_readStats() but takes an external workspace which must be182* 4-byte aligned and its size must be >= HUF_READ_STATS_WORKSPACE_SIZE.183* If the CPU has BMI2 support, pass bmi2=1, otherwise pass bmi2=0.184*/185#define HUF_READ_STATS_WORKSPACE_SIZE_U32 FSE_DECOMPRESS_WKSP_SIZE_U32(6, HUF_TABLELOG_MAX-1)186#define HUF_READ_STATS_WORKSPACE_SIZE (HUF_READ_STATS_WORKSPACE_SIZE_U32 * sizeof(unsigned))187size_t HUF_readStats_wksp(BYTE* huffWeight, size_t hwSize,188U32* rankStats, U32* nbSymbolsPtr, U32* tableLogPtr,189const void* src, size_t srcSize,190void* workspace, size_t wkspSize,191int flags);192193/** HUF_readCTable() :194* Loading a CTable saved with HUF_writeCTable() */195size_t HUF_readCTable (HUF_CElt* CTable, unsigned* maxSymbolValuePtr, const void* src, size_t srcSize, unsigned *hasZeroWeights);196197/** HUF_getNbBitsFromCTable() :198* Read nbBits from CTable symbolTable, for symbol `symbolValue` presumed <= HUF_SYMBOLVALUE_MAX199* Note 1 : is not inlined, as HUF_CElt definition is private */200U32 HUF_getNbBitsFromCTable(const HUF_CElt* symbolTable, U32 symbolValue);201202/*203* HUF_decompress() does the following:204* 1. select the decompression algorithm (X1, X2) based on pre-computed heuristics205* 2. build Huffman table from save, using HUF_readDTableX?()206* 3. decode 1 or 4 segments in parallel using HUF_decompress?X?_usingDTable()207*/208209/** HUF_selectDecoder() :210* Tells which decoder is likely to decode faster,211* based on a set of pre-computed metrics.212* @return : 0==HUF_decompress4X1, 1==HUF_decompress4X2 .213* Assumption : 0 < dstSize <= 128 KB */214U32 HUF_selectDecoder (size_t dstSize, size_t cSrcSize);215216/**217* The minimum workspace size for the `workSpace` used in218* HUF_readDTableX1_wksp() and HUF_readDTableX2_wksp().219*220* The space used depends on HUF_TABLELOG_MAX, ranging from ~1500 bytes when221* HUF_TABLE_LOG_MAX=12 to ~1850 bytes when HUF_TABLE_LOG_MAX=15.222* Buffer overflow errors may potentially occur if code modifications result in223* a required workspace size greater than that specified in the following224* macro.225*/226#define HUF_DECOMPRESS_WORKSPACE_SIZE ((2 << 10) + (1 << 9))227#define HUF_DECOMPRESS_WORKSPACE_SIZE_U32 (HUF_DECOMPRESS_WORKSPACE_SIZE / sizeof(U32))228229230/* ====================== */231/* single stream variants */232/* ====================== */233234size_t HUF_compress1X_usingCTable(void* dst, size_t dstSize, const void* src, size_t srcSize, const HUF_CElt* CTable, int flags);235/** HUF_compress1X_repeat() :236* Same as HUF_compress1X_wksp(), but considers using hufTable if *repeat != HUF_repeat_none.237* If it uses hufTable it does not modify hufTable or repeat.238* If it doesn't, it sets *repeat = HUF_repeat_none, and it sets hufTable to the table used.239* If preferRepeat then the old table will always be used if valid.240* If suspectUncompressible then some sampling checks will be run to potentially skip huffman coding */241size_t HUF_compress1X_repeat(void* dst, size_t dstSize,242const void* src, size_t srcSize,243unsigned maxSymbolValue, unsigned tableLog,244void* workSpace, size_t wkspSize, /**< `workSpace` must be aligned on 4-bytes boundaries, `wkspSize` must be >= HUF_WORKSPACE_SIZE */245HUF_CElt* hufTable, HUF_repeat* repeat, int flags);246247size_t HUF_decompress1X_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int flags);248#ifndef HUF_FORCE_DECOMPRESS_X1249size_t HUF_decompress1X2_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int flags); /**< double-symbols decoder */250#endif251252/* BMI2 variants.253* If the CPU has BMI2 support, pass bmi2=1, otherwise pass bmi2=0.254*/255size_t HUF_decompress1X_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int flags);256#ifndef HUF_FORCE_DECOMPRESS_X2257size_t HUF_decompress1X1_DCtx_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int flags);258#endif259size_t HUF_decompress4X_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUF_DTable* DTable, int flags);260size_t HUF_decompress4X_hufOnly_wksp(HUF_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize, void* workSpace, size_t wkspSize, int flags);261#ifndef HUF_FORCE_DECOMPRESS_X2262size_t HUF_readDTableX1_wksp(HUF_DTable* DTable, const void* src, size_t srcSize, void* workSpace, size_t wkspSize, int flags);263#endif264#ifndef HUF_FORCE_DECOMPRESS_X1265size_t HUF_readDTableX2_wksp(HUF_DTable* DTable, const void* src, size_t srcSize, void* workSpace, size_t wkspSize, int flags);266#endif267268#endif /* HUF_H_298734234 */269270#if defined (__cplusplus)271}272#endif273274275