/*1* Copyright (c) Meta Platforms, Inc. and affiliates.2* All rights reserved.3*4* This source code is licensed under both the BSD-style license (found in the5* LICENSE file in the root directory of this source tree) and the GPLv2 (found6* in the COPYING file in the root directory of this source tree).7* You may select, at your option, one of the above-listed licenses.8*/910#if defined (__cplusplus)11extern "C" {12#endif1314#ifndef ZSTD_ZDICT_H15#define ZSTD_ZDICT_H1617/*====== Dependencies ======*/18#include <stddef.h> /* size_t */192021/* ===== ZDICTLIB_API : control library symbols visibility ===== */22#ifndef ZDICTLIB_VISIBLE23/* Backwards compatibility with old macro name */24# ifdef ZDICTLIB_VISIBILITY25# define ZDICTLIB_VISIBLE ZDICTLIB_VISIBILITY26# elif defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__)27# define ZDICTLIB_VISIBLE __attribute__ ((visibility ("default")))28# else29# define ZDICTLIB_VISIBLE30# endif31#endif3233#ifndef ZDICTLIB_HIDDEN34# if defined(__GNUC__) && (__GNUC__ >= 4) && !defined(__MINGW32__)35# define ZDICTLIB_HIDDEN __attribute__ ((visibility ("hidden")))36# else37# define ZDICTLIB_HIDDEN38# endif39#endif4041#if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)42# define ZDICTLIB_API __declspec(dllexport) ZDICTLIB_VISIBLE43#elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)44# define ZDICTLIB_API __declspec(dllimport) ZDICTLIB_VISIBLE /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/45#else46# define ZDICTLIB_API ZDICTLIB_VISIBLE47#endif4849/*******************************************************************************50* Zstd dictionary builder51*52* FAQ53* ===54* Why should I use a dictionary?55* ------------------------------56*57* Zstd can use dictionaries to improve compression ratio of small data.58* Traditionally small files don't compress well because there is very little59* repetition in a single sample, since it is small. But, if you are compressing60* many similar files, like a bunch of JSON records that share the same61* structure, you can train a dictionary on ahead of time on some samples of62* these files. Then, zstd can use the dictionary to find repetitions that are63* present across samples. This can vastly improve compression ratio.64*65* When is a dictionary useful?66* ----------------------------67*68* Dictionaries are useful when compressing many small files that are similar.69* The larger a file is, the less benefit a dictionary will have. Generally,70* we don't expect dictionary compression to be effective past 100KB. And the71* smaller a file is, the more we would expect the dictionary to help.72*73* How do I use a dictionary?74* --------------------------75*76* Simply pass the dictionary to the zstd compressor with77* `ZSTD_CCtx_loadDictionary()`. The same dictionary must then be passed to78* the decompressor, using `ZSTD_DCtx_loadDictionary()`. There are other79* more advanced functions that allow selecting some options, see zstd.h for80* complete documentation.81*82* What is a zstd dictionary?83* --------------------------84*85* A zstd dictionary has two pieces: Its header, and its content. The header86* contains a magic number, the dictionary ID, and entropy tables. These87* entropy tables allow zstd to save on header costs in the compressed file,88* which really matters for small data. The content is just bytes, which are89* repeated content that is common across many samples.90*91* What is a raw content dictionary?92* ---------------------------------93*94* A raw content dictionary is just bytes. It doesn't have a zstd dictionary95* header, a dictionary ID, or entropy tables. Any buffer is a valid raw96* content dictionary.97*98* How do I train a dictionary?99* ----------------------------100*101* Gather samples from your use case. These samples should be similar to each102* other. If you have several use cases, you could try to train one dictionary103* per use case.104*105* Pass those samples to `ZDICT_trainFromBuffer()` and that will train your106* dictionary. There are a few advanced versions of this function, but this107* is a great starting point. If you want to further tune your dictionary108* you could try `ZDICT_optimizeTrainFromBuffer_cover()`. If that is too slow109* you can try `ZDICT_optimizeTrainFromBuffer_fastCover()`.110*111* If the dictionary training function fails, that is likely because you112* either passed too few samples, or a dictionary would not be effective113* for your data. Look at the messages that the dictionary trainer printed,114* if it doesn't say too few samples, then a dictionary would not be effective.115*116* How large should my dictionary be?117* ----------------------------------118*119* A reasonable dictionary size, the `dictBufferCapacity`, is about 100KB.120* The zstd CLI defaults to a 110KB dictionary. You likely don't need a121* dictionary larger than that. But, most use cases can get away with a122* smaller dictionary. The advanced dictionary builders can automatically123* shrink the dictionary for you, and select the smallest size that doesn't124* hurt compression ratio too much. See the `shrinkDict` parameter.125* A smaller dictionary can save memory, and potentially speed up126* compression.127*128* How many samples should I provide to the dictionary builder?129* ------------------------------------------------------------130*131* We generally recommend passing ~100x the size of the dictionary132* in samples. A few thousand should suffice. Having too few samples133* can hurt the dictionaries effectiveness. Having more samples will134* only improve the dictionaries effectiveness. But having too many135* samples can slow down the dictionary builder.136*137* How do I determine if a dictionary will be effective?138* -----------------------------------------------------139*140* Simply train a dictionary and try it out. You can use zstd's built in141* benchmarking tool to test the dictionary effectiveness.142*143* # Benchmark levels 1-3 without a dictionary144* zstd -b1e3 -r /path/to/my/files145* # Benchmark levels 1-3 with a dictionary146* zstd -b1e3 -r /path/to/my/files -D /path/to/my/dictionary147*148* When should I retrain a dictionary?149* -----------------------------------150*151* You should retrain a dictionary when its effectiveness drops. Dictionary152* effectiveness drops as the data you are compressing changes. Generally, we do153* expect dictionaries to "decay" over time, as your data changes, but the rate154* at which they decay depends on your use case. Internally, we regularly155* retrain dictionaries, and if the new dictionary performs significantly156* better than the old dictionary, we will ship the new dictionary.157*158* I have a raw content dictionary, how do I turn it into a zstd dictionary?159* -------------------------------------------------------------------------160*161* If you have a raw content dictionary, e.g. by manually constructing it, or162* using a third-party dictionary builder, you can turn it into a zstd163* dictionary by using `ZDICT_finalizeDictionary()`. You'll also have to164* provide some samples of the data. It will add the zstd header to the165* raw content, which contains a dictionary ID and entropy tables, which166* will improve compression ratio, and allow zstd to write the dictionary ID167* into the frame, if you so choose.168*169* Do I have to use zstd's dictionary builder?170* -------------------------------------------171*172* No! You can construct dictionary content however you please, it is just173* bytes. It will always be valid as a raw content dictionary. If you want174* a zstd dictionary, which can improve compression ratio, use175* `ZDICT_finalizeDictionary()`.176*177* What is the attack surface of a zstd dictionary?178* ------------------------------------------------179*180* Zstd is heavily fuzz tested, including loading fuzzed dictionaries, so181* zstd should never crash, or access out-of-bounds memory no matter what182* the dictionary is. However, if an attacker can control the dictionary183* during decompression, they can cause zstd to generate arbitrary bytes,184* just like if they controlled the compressed data.185*186******************************************************************************/187188189/*! ZDICT_trainFromBuffer():190* Train a dictionary from an array of samples.191* Redirect towards ZDICT_optimizeTrainFromBuffer_fastCover() single-threaded, with d=8, steps=4,192* f=20, and accel=1.193* Samples must be stored concatenated in a single flat buffer `samplesBuffer`,194* supplied with an array of sizes `samplesSizes`, providing the size of each sample, in order.195* The resulting dictionary will be saved into `dictBuffer`.196* @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)197* or an error code, which can be tested with ZDICT_isError().198* Note: Dictionary training will fail if there are not enough samples to construct a199* dictionary, or if most of the samples are too small (< 8 bytes being the lower limit).200* If dictionary training fails, you should use zstd without a dictionary, as the dictionary201* would've been ineffective anyways. If you believe your samples would benefit from a dictionary202* please open an issue with details, and we can look into it.203* Note: ZDICT_trainFromBuffer()'s memory usage is about 6 MB.204* Tips: In general, a reasonable dictionary has a size of ~ 100 KB.205* It's possible to select smaller or larger size, just by specifying `dictBufferCapacity`.206* In general, it's recommended to provide a few thousands samples, though this can vary a lot.207* It's recommended that total size of all samples be about ~x100 times the target size of dictionary.208*/209ZDICTLIB_API size_t ZDICT_trainFromBuffer(void* dictBuffer, size_t dictBufferCapacity,210const void* samplesBuffer,211const size_t* samplesSizes, unsigned nbSamples);212213typedef struct {214int compressionLevel; /**< optimize for a specific zstd compression level; 0 means default */215unsigned notificationLevel; /**< Write log to stderr; 0 = none (default); 1 = errors; 2 = progression; 3 = details; 4 = debug; */216unsigned dictID; /**< force dictID value; 0 means auto mode (32-bits random value)217* NOTE: The zstd format reserves some dictionary IDs for future use.218* You may use them in private settings, but be warned that they219* may be used by zstd in a public dictionary registry in the future.220* These dictionary IDs are:221* - low range : <= 32767222* - high range : >= (2^31)223*/224} ZDICT_params_t;225226/*! ZDICT_finalizeDictionary():227* Given a custom content as a basis for dictionary, and a set of samples,228* finalize dictionary by adding headers and statistics according to the zstd229* dictionary format.230*231* Samples must be stored concatenated in a flat buffer `samplesBuffer`,232* supplied with an array of sizes `samplesSizes`, providing the size of each233* sample in order. The samples are used to construct the statistics, so they234* should be representative of what you will compress with this dictionary.235*236* The compression level can be set in `parameters`. You should pass the237* compression level you expect to use in production. The statistics for each238* compression level differ, so tuning the dictionary for the compression level239* can help quite a bit.240*241* You can set an explicit dictionary ID in `parameters`, or allow us to pick242* a random dictionary ID for you, but we can't guarantee no collisions.243*244* The dstDictBuffer and the dictContent may overlap, and the content will be245* appended to the end of the header. If the header + the content doesn't fit in246* maxDictSize the beginning of the content is truncated to make room, since it247* is presumed that the most profitable content is at the end of the dictionary,248* since that is the cheapest to reference.249*250* `maxDictSize` must be >= max(dictContentSize, ZSTD_DICTSIZE_MIN).251*252* @return: size of dictionary stored into `dstDictBuffer` (<= `maxDictSize`),253* or an error code, which can be tested by ZDICT_isError().254* Note: ZDICT_finalizeDictionary() will push notifications into stderr if255* instructed to, using notificationLevel>0.256* NOTE: This function currently may fail in several edge cases including:257* * Not enough samples258* * Samples are uncompressible259* * Samples are all exactly the same260*/261ZDICTLIB_API size_t ZDICT_finalizeDictionary(void* dstDictBuffer, size_t maxDictSize,262const void* dictContent, size_t dictContentSize,263const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,264ZDICT_params_t parameters);265266267/*====== Helper functions ======*/268ZDICTLIB_API unsigned ZDICT_getDictID(const void* dictBuffer, size_t dictSize); /**< extracts dictID; @return zero if error (not a valid dictionary) */269ZDICTLIB_API size_t ZDICT_getDictHeaderSize(const void* dictBuffer, size_t dictSize); /* returns dict header size; returns a ZSTD error code on failure */270ZDICTLIB_API unsigned ZDICT_isError(size_t errorCode);271ZDICTLIB_API const char* ZDICT_getErrorName(size_t errorCode);272273#endif /* ZSTD_ZDICT_H */274275#if defined(ZDICT_STATIC_LINKING_ONLY) && !defined(ZSTD_ZDICT_H_STATIC)276#define ZSTD_ZDICT_H_STATIC277278/* This can be overridden externally to hide static symbols. */279#ifndef ZDICTLIB_STATIC_API280# if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)281# define ZDICTLIB_STATIC_API __declspec(dllexport) ZDICTLIB_VISIBLE282# elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)283# define ZDICTLIB_STATIC_API __declspec(dllimport) ZDICTLIB_VISIBLE284# else285# define ZDICTLIB_STATIC_API ZDICTLIB_VISIBLE286# endif287#endif288289/* ====================================================================================290* The definitions in this section are considered experimental.291* They should never be used with a dynamic library, as they may change in the future.292* They are provided for advanced usages.293* Use them only in association with static linking.294* ==================================================================================== */295296#define ZDICT_DICTSIZE_MIN 256297/* Deprecated: Remove in v1.6.0 */298#define ZDICT_CONTENTSIZE_MIN 128299300/*! ZDICT_cover_params_t:301* k and d are the only required parameters.302* For others, value 0 means default.303*/304typedef struct {305unsigned k; /* Segment size : constraint: 0 < k : Reasonable range [16, 2048+] */306unsigned d; /* dmer size : constraint: 0 < d <= k : Reasonable range [6, 16] */307unsigned steps; /* Number of steps : Only used for optimization : 0 means default (40) : Higher means more parameters checked */308unsigned nbThreads; /* Number of threads : constraint: 0 < nbThreads : 1 means single-threaded : Only used for optimization : Ignored if ZSTD_MULTITHREAD is not defined */309double splitPoint; /* Percentage of samples used for training: Only used for optimization : the first nbSamples * splitPoint samples will be used to training, the last nbSamples * (1 - splitPoint) samples will be used for testing, 0 means default (1.0), 1.0 when all samples are used for both training and testing */310unsigned shrinkDict; /* Train dictionaries to shrink in size starting from the minimum size and selects the smallest dictionary that is shrinkDictMaxRegression% worse than the largest dictionary. 0 means no shrinking and 1 means shrinking */311unsigned shrinkDictMaxRegression; /* Sets shrinkDictMaxRegression so that a smaller dictionary can be at worse shrinkDictMaxRegression% worse than the max dict size dictionary. */312ZDICT_params_t zParams;313} ZDICT_cover_params_t;314315typedef struct {316unsigned k; /* Segment size : constraint: 0 < k : Reasonable range [16, 2048+] */317unsigned d; /* dmer size : constraint: 0 < d <= k : Reasonable range [6, 16] */318unsigned f; /* log of size of frequency array : constraint: 0 < f <= 31 : 1 means default(20)*/319unsigned steps; /* Number of steps : Only used for optimization : 0 means default (40) : Higher means more parameters checked */320unsigned nbThreads; /* Number of threads : constraint: 0 < nbThreads : 1 means single-threaded : Only used for optimization : Ignored if ZSTD_MULTITHREAD is not defined */321double splitPoint; /* Percentage of samples used for training: Only used for optimization : the first nbSamples * splitPoint samples will be used to training, the last nbSamples * (1 - splitPoint) samples will be used for testing, 0 means default (0.75), 1.0 when all samples are used for both training and testing */322unsigned accel; /* Acceleration level: constraint: 0 < accel <= 10, higher means faster and less accurate, 0 means default(1) */323unsigned shrinkDict; /* Train dictionaries to shrink in size starting from the minimum size and selects the smallest dictionary that is shrinkDictMaxRegression% worse than the largest dictionary. 0 means no shrinking and 1 means shrinking */324unsigned shrinkDictMaxRegression; /* Sets shrinkDictMaxRegression so that a smaller dictionary can be at worse shrinkDictMaxRegression% worse than the max dict size dictionary. */325326ZDICT_params_t zParams;327} ZDICT_fastCover_params_t;328329/*! ZDICT_trainFromBuffer_cover():330* Train a dictionary from an array of samples using the COVER algorithm.331* Samples must be stored concatenated in a single flat buffer `samplesBuffer`,332* supplied with an array of sizes `samplesSizes`, providing the size of each sample, in order.333* The resulting dictionary will be saved into `dictBuffer`.334* @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)335* or an error code, which can be tested with ZDICT_isError().336* See ZDICT_trainFromBuffer() for details on failure modes.337* Note: ZDICT_trainFromBuffer_cover() requires about 9 bytes of memory for each input byte.338* Tips: In general, a reasonable dictionary has a size of ~ 100 KB.339* It's possible to select smaller or larger size, just by specifying `dictBufferCapacity`.340* In general, it's recommended to provide a few thousands samples, though this can vary a lot.341* It's recommended that total size of all samples be about ~x100 times the target size of dictionary.342*/343ZDICTLIB_STATIC_API size_t ZDICT_trainFromBuffer_cover(344void *dictBuffer, size_t dictBufferCapacity,345const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples,346ZDICT_cover_params_t parameters);347348/*! ZDICT_optimizeTrainFromBuffer_cover():349* The same requirements as above hold for all the parameters except `parameters`.350* This function tries many parameter combinations and picks the best parameters.351* `*parameters` is filled with the best parameters found,352* dictionary constructed with those parameters is stored in `dictBuffer`.353*354* All of the parameters d, k, steps are optional.355* If d is non-zero then we don't check multiple values of d, otherwise we check d = {6, 8}.356* if steps is zero it defaults to its default value.357* If k is non-zero then we don't check multiple values of k, otherwise we check steps values in [50, 2000].358*359* @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)360* or an error code, which can be tested with ZDICT_isError().361* On success `*parameters` contains the parameters selected.362* See ZDICT_trainFromBuffer() for details on failure modes.363* Note: ZDICT_optimizeTrainFromBuffer_cover() requires about 8 bytes of memory for each input byte and additionally another 5 bytes of memory for each byte of memory for each thread.364*/365ZDICTLIB_STATIC_API size_t ZDICT_optimizeTrainFromBuffer_cover(366void* dictBuffer, size_t dictBufferCapacity,367const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,368ZDICT_cover_params_t* parameters);369370/*! ZDICT_trainFromBuffer_fastCover():371* Train a dictionary from an array of samples using a modified version of COVER algorithm.372* Samples must be stored concatenated in a single flat buffer `samplesBuffer`,373* supplied with an array of sizes `samplesSizes`, providing the size of each sample, in order.374* d and k are required.375* All other parameters are optional, will use default values if not provided376* The resulting dictionary will be saved into `dictBuffer`.377* @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)378* or an error code, which can be tested with ZDICT_isError().379* See ZDICT_trainFromBuffer() for details on failure modes.380* Note: ZDICT_trainFromBuffer_fastCover() requires 6 * 2^f bytes of memory.381* Tips: In general, a reasonable dictionary has a size of ~ 100 KB.382* It's possible to select smaller or larger size, just by specifying `dictBufferCapacity`.383* In general, it's recommended to provide a few thousands samples, though this can vary a lot.384* It's recommended that total size of all samples be about ~x100 times the target size of dictionary.385*/386ZDICTLIB_STATIC_API size_t ZDICT_trainFromBuffer_fastCover(void *dictBuffer,387size_t dictBufferCapacity, const void *samplesBuffer,388const size_t *samplesSizes, unsigned nbSamples,389ZDICT_fastCover_params_t parameters);390391/*! ZDICT_optimizeTrainFromBuffer_fastCover():392* The same requirements as above hold for all the parameters except `parameters`.393* This function tries many parameter combinations (specifically, k and d combinations)394* and picks the best parameters. `*parameters` is filled with the best parameters found,395* dictionary constructed with those parameters is stored in `dictBuffer`.396* All of the parameters d, k, steps, f, and accel are optional.397* If d is non-zero then we don't check multiple values of d, otherwise we check d = {6, 8}.398* if steps is zero it defaults to its default value.399* If k is non-zero then we don't check multiple values of k, otherwise we check steps values in [50, 2000].400* If f is zero, default value of 20 is used.401* If accel is zero, default value of 1 is used.402*403* @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)404* or an error code, which can be tested with ZDICT_isError().405* On success `*parameters` contains the parameters selected.406* See ZDICT_trainFromBuffer() for details on failure modes.407* Note: ZDICT_optimizeTrainFromBuffer_fastCover() requires about 6 * 2^f bytes of memory for each thread.408*/409ZDICTLIB_STATIC_API size_t ZDICT_optimizeTrainFromBuffer_fastCover(void* dictBuffer,410size_t dictBufferCapacity, const void* samplesBuffer,411const size_t* samplesSizes, unsigned nbSamples,412ZDICT_fastCover_params_t* parameters);413414typedef struct {415unsigned selectivityLevel; /* 0 means default; larger => select more => larger dictionary */416ZDICT_params_t zParams;417} ZDICT_legacy_params_t;418419/*! ZDICT_trainFromBuffer_legacy():420* Train a dictionary from an array of samples.421* Samples must be stored concatenated in a single flat buffer `samplesBuffer`,422* supplied with an array of sizes `samplesSizes`, providing the size of each sample, in order.423* The resulting dictionary will be saved into `dictBuffer`.424* `parameters` is optional and can be provided with values set to 0 to mean "default".425* @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)426* or an error code, which can be tested with ZDICT_isError().427* See ZDICT_trainFromBuffer() for details on failure modes.428* Tips: In general, a reasonable dictionary has a size of ~ 100 KB.429* It's possible to select smaller or larger size, just by specifying `dictBufferCapacity`.430* In general, it's recommended to provide a few thousands samples, though this can vary a lot.431* It's recommended that total size of all samples be about ~x100 times the target size of dictionary.432* Note: ZDICT_trainFromBuffer_legacy() will send notifications into stderr if instructed to, using notificationLevel>0.433*/434ZDICTLIB_STATIC_API size_t ZDICT_trainFromBuffer_legacy(435void* dictBuffer, size_t dictBufferCapacity,436const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,437ZDICT_legacy_params_t parameters);438439440/* Deprecation warnings */441/* It is generally possible to disable deprecation warnings from compiler,442for example with -Wno-deprecated-declarations for gcc443or _CRT_SECURE_NO_WARNINGS in Visual.444Otherwise, it's also possible to manually define ZDICT_DISABLE_DEPRECATE_WARNINGS */445#ifdef ZDICT_DISABLE_DEPRECATE_WARNINGS446# define ZDICT_DEPRECATED(message) /* disable deprecation warnings */447#else448# define ZDICT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)449# if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */450# define ZDICT_DEPRECATED(message) [[deprecated(message)]]451# elif defined(__clang__) || (ZDICT_GCC_VERSION >= 405)452# define ZDICT_DEPRECATED(message) __attribute__((deprecated(message)))453# elif (ZDICT_GCC_VERSION >= 301)454# define ZDICT_DEPRECATED(message) __attribute__((deprecated))455# elif defined(_MSC_VER)456# define ZDICT_DEPRECATED(message) __declspec(deprecated(message))457# else458# pragma message("WARNING: You need to implement ZDICT_DEPRECATED for this compiler")459# define ZDICT_DEPRECATED(message)460# endif461#endif /* ZDICT_DISABLE_DEPRECATE_WARNINGS */462463ZDICT_DEPRECATED("use ZDICT_finalizeDictionary() instead")464ZDICTLIB_STATIC_API465size_t ZDICT_addEntropyTablesFromBuffer(void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,466const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples);467468469#endif /* ZSTD_ZDICT_H_STATIC */470471#if defined (__cplusplus)472}473#endif474475476