/*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#ifndef ZSTD_ZDICT_H11#define ZSTD_ZDICT_H121314/*====== Dependencies ======*/15#include <stddef.h> /* size_t */1617#if defined (__cplusplus)18extern "C" {19#endif2021/* ===== 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, ZDICT_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#if defined (__cplusplus)274}275#endif276277#endif /* ZSTD_ZDICT_H */278279#if defined(ZDICT_STATIC_LINKING_ONLY) && !defined(ZSTD_ZDICT_H_STATIC)280#define ZSTD_ZDICT_H_STATIC281282#if defined (__cplusplus)283extern "C" {284#endif285286/* This can be overridden externally to hide static symbols. */287#ifndef ZDICTLIB_STATIC_API288# if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)289# define ZDICTLIB_STATIC_API __declspec(dllexport) ZDICTLIB_VISIBLE290# elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)291# define ZDICTLIB_STATIC_API __declspec(dllimport) ZDICTLIB_VISIBLE292# else293# define ZDICTLIB_STATIC_API ZDICTLIB_VISIBLE294# endif295#endif296297/* ====================================================================================298* The definitions in this section are considered experimental.299* They should never be used with a dynamic library, as they may change in the future.300* They are provided for advanced usages.301* Use them only in association with static linking.302* ==================================================================================== */303304#define ZDICT_DICTSIZE_MIN 256305/* Deprecated: Remove in v1.6.0 */306#define ZDICT_CONTENTSIZE_MIN 128307308/*! ZDICT_cover_params_t:309* k and d are the only required parameters.310* For others, value 0 means default.311*/312typedef struct {313unsigned k; /* Segment size : constraint: 0 < k : Reasonable range [16, 2048+] */314unsigned d; /* dmer size : constraint: 0 < d <= k : Reasonable range [6, 16] */315unsigned steps; /* Number of steps : Only used for optimization : 0 means default (40) : Higher means more parameters checked */316unsigned nbThreads; /* Number of threads : constraint: 0 < nbThreads : 1 means single-threaded : Only used for optimization : Ignored if ZSTD_MULTITHREAD is not defined */317double 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 */318unsigned 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 */319unsigned shrinkDictMaxRegression; /* Sets shrinkDictMaxRegression so that a smaller dictionary can be at worse shrinkDictMaxRegression% worse than the max dict size dictionary. */320ZDICT_params_t zParams;321} ZDICT_cover_params_t;322323typedef struct {324unsigned k; /* Segment size : constraint: 0 < k : Reasonable range [16, 2048+] */325unsigned d; /* dmer size : constraint: 0 < d <= k : Reasonable range [6, 16] */326unsigned f; /* log of size of frequency array : constraint: 0 < f <= 31 : 1 means default(20)*/327unsigned steps; /* Number of steps : Only used for optimization : 0 means default (40) : Higher means more parameters checked */328unsigned nbThreads; /* Number of threads : constraint: 0 < nbThreads : 1 means single-threaded : Only used for optimization : Ignored if ZSTD_MULTITHREAD is not defined */329double 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 */330unsigned accel; /* Acceleration level: constraint: 0 < accel <= 10, higher means faster and less accurate, 0 means default(1) */331unsigned 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 */332unsigned shrinkDictMaxRegression; /* Sets shrinkDictMaxRegression so that a smaller dictionary can be at worse shrinkDictMaxRegression% worse than the max dict size dictionary. */333334ZDICT_params_t zParams;335} ZDICT_fastCover_params_t;336337/*! ZDICT_trainFromBuffer_cover():338* Train a dictionary from an array of samples using the COVER algorithm.339* Samples must be stored concatenated in a single flat buffer `samplesBuffer`,340* supplied with an array of sizes `samplesSizes`, providing the size of each sample, in order.341* The resulting dictionary will be saved into `dictBuffer`.342* @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)343* or an error code, which can be tested with ZDICT_isError().344* See ZDICT_trainFromBuffer() for details on failure modes.345* Note: ZDICT_trainFromBuffer_cover() requires about 9 bytes of memory for each input byte.346* Tips: In general, a reasonable dictionary has a size of ~ 100 KB.347* It's possible to select smaller or larger size, just by specifying `dictBufferCapacity`.348* In general, it's recommended to provide a few thousands samples, though this can vary a lot.349* It's recommended that total size of all samples be about ~x100 times the target size of dictionary.350*/351ZDICTLIB_STATIC_API size_t ZDICT_trainFromBuffer_cover(352void *dictBuffer, size_t dictBufferCapacity,353const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples,354ZDICT_cover_params_t parameters);355356/*! ZDICT_optimizeTrainFromBuffer_cover():357* The same requirements as above hold for all the parameters except `parameters`.358* This function tries many parameter combinations and picks the best parameters.359* `*parameters` is filled with the best parameters found,360* dictionary constructed with those parameters is stored in `dictBuffer`.361*362* All of the parameters d, k, steps are optional.363* If d is non-zero then we don't check multiple values of d, otherwise we check d = {6, 8}.364* if steps is zero it defaults to its default value.365* If k is non-zero then we don't check multiple values of k, otherwise we check steps values in [50, 2000].366*367* @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)368* or an error code, which can be tested with ZDICT_isError().369* On success `*parameters` contains the parameters selected.370* See ZDICT_trainFromBuffer() for details on failure modes.371* 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.372*/373ZDICTLIB_STATIC_API size_t ZDICT_optimizeTrainFromBuffer_cover(374void* dictBuffer, size_t dictBufferCapacity,375const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,376ZDICT_cover_params_t* parameters);377378/*! ZDICT_trainFromBuffer_fastCover():379* Train a dictionary from an array of samples using a modified version of COVER algorithm.380* Samples must be stored concatenated in a single flat buffer `samplesBuffer`,381* supplied with an array of sizes `samplesSizes`, providing the size of each sample, in order.382* d and k are required.383* All other parameters are optional, will use default values if not provided384* The resulting dictionary will be saved into `dictBuffer`.385* @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)386* or an error code, which can be tested with ZDICT_isError().387* See ZDICT_trainFromBuffer() for details on failure modes.388* Note: ZDICT_trainFromBuffer_fastCover() requires 6 * 2^f bytes of memory.389* Tips: In general, a reasonable dictionary has a size of ~ 100 KB.390* It's possible to select smaller or larger size, just by specifying `dictBufferCapacity`.391* In general, it's recommended to provide a few thousands samples, though this can vary a lot.392* It's recommended that total size of all samples be about ~x100 times the target size of dictionary.393*/394ZDICTLIB_STATIC_API size_t ZDICT_trainFromBuffer_fastCover(void *dictBuffer,395size_t dictBufferCapacity, const void *samplesBuffer,396const size_t *samplesSizes, unsigned nbSamples,397ZDICT_fastCover_params_t parameters);398399/*! ZDICT_optimizeTrainFromBuffer_fastCover():400* The same requirements as above hold for all the parameters except `parameters`.401* This function tries many parameter combinations (specifically, k and d combinations)402* and picks the best parameters. `*parameters` is filled with the best parameters found,403* dictionary constructed with those parameters is stored in `dictBuffer`.404* All of the parameters d, k, steps, f, and accel are optional.405* If d is non-zero then we don't check multiple values of d, otherwise we check d = {6, 8}.406* if steps is zero it defaults to its default value.407* If k is non-zero then we don't check multiple values of k, otherwise we check steps values in [50, 2000].408* If f is zero, default value of 20 is used.409* If accel is zero, default value of 1 is used.410*411* @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)412* or an error code, which can be tested with ZDICT_isError().413* On success `*parameters` contains the parameters selected.414* See ZDICT_trainFromBuffer() for details on failure modes.415* Note: ZDICT_optimizeTrainFromBuffer_fastCover() requires about 6 * 2^f bytes of memory for each thread.416*/417ZDICTLIB_STATIC_API size_t ZDICT_optimizeTrainFromBuffer_fastCover(void* dictBuffer,418size_t dictBufferCapacity, const void* samplesBuffer,419const size_t* samplesSizes, unsigned nbSamples,420ZDICT_fastCover_params_t* parameters);421422typedef struct {423unsigned selectivityLevel; /* 0 means default; larger => select more => larger dictionary */424ZDICT_params_t zParams;425} ZDICT_legacy_params_t;426427/*! ZDICT_trainFromBuffer_legacy():428* Train a dictionary from an array of samples.429* Samples must be stored concatenated in a single flat buffer `samplesBuffer`,430* supplied with an array of sizes `samplesSizes`, providing the size of each sample, in order.431* The resulting dictionary will be saved into `dictBuffer`.432* `parameters` is optional and can be provided with values set to 0 to mean "default".433* @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)434* or an error code, which can be tested with ZDICT_isError().435* See ZDICT_trainFromBuffer() for details on failure modes.436* Tips: In general, a reasonable dictionary has a size of ~ 100 KB.437* It's possible to select smaller or larger size, just by specifying `dictBufferCapacity`.438* In general, it's recommended to provide a few thousands samples, though this can vary a lot.439* It's recommended that total size of all samples be about ~x100 times the target size of dictionary.440* Note: ZDICT_trainFromBuffer_legacy() will send notifications into stderr if instructed to, using notificationLevel>0.441*/442ZDICTLIB_STATIC_API size_t ZDICT_trainFromBuffer_legacy(443void* dictBuffer, size_t dictBufferCapacity,444const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,445ZDICT_legacy_params_t parameters);446447448/* Deprecation warnings */449/* It is generally possible to disable deprecation warnings from compiler,450for example with -Wno-deprecated-declarations for gcc451or _CRT_SECURE_NO_WARNINGS in Visual.452Otherwise, it's also possible to manually define ZDICT_DISABLE_DEPRECATE_WARNINGS */453#ifdef ZDICT_DISABLE_DEPRECATE_WARNINGS454# define ZDICT_DEPRECATED(message) /* disable deprecation warnings */455#else456# define ZDICT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)457# if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */458# define ZDICT_DEPRECATED(message) [[deprecated(message)]]459# elif defined(__clang__) || (ZDICT_GCC_VERSION >= 405)460# define ZDICT_DEPRECATED(message) __attribute__((deprecated(message)))461# elif (ZDICT_GCC_VERSION >= 301)462# define ZDICT_DEPRECATED(message) __attribute__((deprecated))463# elif defined(_MSC_VER)464# define ZDICT_DEPRECATED(message) __declspec(deprecated(message))465# else466# pragma message("WARNING: You need to implement ZDICT_DEPRECATED for this compiler")467# define ZDICT_DEPRECATED(message)468# endif469#endif /* ZDICT_DISABLE_DEPRECATE_WARNINGS */470471ZDICT_DEPRECATED("use ZDICT_finalizeDictionary() instead")472ZDICTLIB_STATIC_API473size_t ZDICT_addEntropyTablesFromBuffer(void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,474const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples);475476#if defined (__cplusplus)477}478#endif479480#endif /* ZSTD_ZDICT_H_STATIC */481482483