1 /*
2  * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under both the BSD-style license (found in the
6  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7  * in the COPYING file in the root directory of this source tree).
8  * You may select, at your option, one of the above-listed licenses.
9  */
10 
11 #ifndef DICTBUILDER_H_001
12 #define DICTBUILDER_H_001
13 
14 #if defined (__cplusplus)
15 extern "C" {
16 #endif
17 
18 
19 /*======  Dependencies  ======*/
20 #include <stddef.h>  /* size_t */
21 
22 
23 /* =====   ZDICTLIB_API : control library symbols visibility   ===== */
24 #ifndef ZDICTLIB_VISIBILITY
25 #  if defined(__GNUC__) && (__GNUC__ >= 4)
26 #    define ZDICTLIB_VISIBILITY __attribute__ ((visibility ("default")))
27 #  else
28 #    define ZDICTLIB_VISIBILITY
29 #  endif
30 #endif
31 #if defined(ZSTD_DLL_EXPORT) && (ZSTD_DLL_EXPORT==1)
32 #  define ZDICTLIB_API __declspec(dllexport) ZDICTLIB_VISIBILITY
33 #elif defined(ZSTD_DLL_IMPORT) && (ZSTD_DLL_IMPORT==1)
34 #  define ZDICTLIB_API __declspec(dllimport) ZDICTLIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/
35 #else
36 #  define ZDICTLIB_API ZDICTLIB_VISIBILITY
37 #endif
38 
39 
40 /*! ZDICT_trainFromBuffer():
41  *  Train a dictionary from an array of samples.
42  *  Redirect towards ZDICT_optimizeTrainFromBuffer_fastCover() single-threaded, with d=8, steps=4,
43  *  f=20, and accel=1.
44  *  Samples must be stored concatenated in a single flat buffer `samplesBuffer`,
45  *  supplied with an array of sizes `samplesSizes`, providing the size of each sample, in order.
46  *  The resulting dictionary will be saved into `dictBuffer`.
47  * @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)
48  *          or an error code, which can be tested with ZDICT_isError().
49  *  Note:  Dictionary training will fail if there are not enough samples to construct a
50  *         dictionary, or if most of the samples are too small (< 8 bytes being the lower limit).
51  *         If dictionary training fails, you should use zstd without a dictionary, as the dictionary
52  *         would've been ineffective anyways. If you believe your samples would benefit from a dictionary
53  *         please open an issue with details, and we can look into it.
54  *  Note: ZDICT_trainFromBuffer()'s memory usage is about 6 MB.
55  *  Tips: In general, a reasonable dictionary has a size of ~ 100 KB.
56  *        It's possible to select smaller or larger size, just by specifying `dictBufferCapacity`.
57  *        In general, it's recommended to provide a few thousands samples, though this can vary a lot.
58  *        It's recommended that total size of all samples be about ~x100 times the target size of dictionary.
59  */
60 ZDICTLIB_API size_t ZDICT_trainFromBuffer(void* dictBuffer, size_t dictBufferCapacity,
61                                     const void* samplesBuffer,
62                                     const size_t* samplesSizes, unsigned nbSamples);
63 
64 
65 /*======   Helper functions   ======*/
66 ZDICTLIB_API unsigned ZDICT_getDictID(const void* dictBuffer, size_t dictSize);  /**< extracts dictID; @return zero if error (not a valid dictionary) */
67 ZDICTLIB_API unsigned ZDICT_isError(size_t errorCode);
68 ZDICTLIB_API const char* ZDICT_getErrorName(size_t errorCode);
69 
70 
71 
72 #ifdef ZDICT_STATIC_LINKING_ONLY
73 
74 /* ====================================================================================
75  * The definitions in this section are considered experimental.
76  * They should never be used with a dynamic library, as they may change in the future.
77  * They are provided for advanced usages.
78  * Use them only in association with static linking.
79  * ==================================================================================== */
80 
81 typedef struct {
82     int      compressionLevel;   /* optimize for a specific zstd compression level; 0 means default */
83     unsigned notificationLevel;  /* Write log to stderr; 0 = none (default); 1 = errors; 2 = progression; 3 = details; 4 = debug; */
84     unsigned dictID;             /* force dictID value; 0 means auto mode (32-bits random value) */
85 } ZDICT_params_t;
86 
87 /*! ZDICT_cover_params_t:
88  *  k and d are the only required parameters.
89  *  For others, value 0 means default.
90  */
91 typedef struct {
92     unsigned k;                  /* Segment size : constraint: 0 < k : Reasonable range [16, 2048+] */
93     unsigned d;                  /* dmer size : constraint: 0 < d <= k : Reasonable range [6, 16] */
94     unsigned steps;              /* Number of steps : Only used for optimization : 0 means default (40) : Higher means more parameters checked */
95     unsigned nbThreads;          /* Number of threads : constraint: 0 < nbThreads : 1 means single-threaded : Only used for optimization : Ignored if ZSTD_MULTITHREAD is not defined */
96     double 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 */
97     unsigned 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  */
98     unsigned shrinkDictMaxRegression; /* Sets shrinkDictMaxRegression so that a smaller dictionary can be at worse shrinkDictMaxRegression% worse than the max dict size dictionary. */
99     ZDICT_params_t zParams;
100 } ZDICT_cover_params_t;
101 
102 typedef struct {
103     unsigned k;                  /* Segment size : constraint: 0 < k : Reasonable range [16, 2048+] */
104     unsigned d;                  /* dmer size : constraint: 0 < d <= k : Reasonable range [6, 16] */
105     unsigned f;                  /* log of size of frequency array : constraint: 0 < f <= 31 : 1 means default(20)*/
106     unsigned steps;              /* Number of steps : Only used for optimization : 0 means default (40) : Higher means more parameters checked */
107     unsigned nbThreads;          /* Number of threads : constraint: 0 < nbThreads : 1 means single-threaded : Only used for optimization : Ignored if ZSTD_MULTITHREAD is not defined */
108     double 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 */
109     unsigned accel;              /* Acceleration level: constraint: 0 < accel <= 10, higher means faster and less accurate, 0 means default(1) */
110     unsigned 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  */
111     unsigned shrinkDictMaxRegression; /* Sets shrinkDictMaxRegression so that a smaller dictionary can be at worse shrinkDictMaxRegression% worse than the max dict size dictionary. */
112 
113     ZDICT_params_t zParams;
114 } ZDICT_fastCover_params_t;
115 
116 /*! ZDICT_trainFromBuffer_cover():
117  *  Train a dictionary from an array of samples using the COVER algorithm.
118  *  Samples must be stored concatenated in a single flat buffer `samplesBuffer`,
119  *  supplied with an array of sizes `samplesSizes`, providing the size of each sample, in order.
120  *  The resulting dictionary will be saved into `dictBuffer`.
121  * @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)
122  *          or an error code, which can be tested with ZDICT_isError().
123  *          See ZDICT_trainFromBuffer() for details on failure modes.
124  *  Note: ZDICT_trainFromBuffer_cover() requires about 9 bytes of memory for each input byte.
125  *  Tips: In general, a reasonable dictionary has a size of ~ 100 KB.
126  *        It's possible to select smaller or larger size, just by specifying `dictBufferCapacity`.
127  *        In general, it's recommended to provide a few thousands samples, though this can vary a lot.
128  *        It's recommended that total size of all samples be about ~x100 times the target size of dictionary.
129  */
130 ZDICTLIB_API size_t ZDICT_trainFromBuffer_cover(
131           void *dictBuffer, size_t dictBufferCapacity,
132     const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples,
133           ZDICT_cover_params_t parameters);
134 
135 /*! ZDICT_optimizeTrainFromBuffer_cover():
136  * The same requirements as above hold for all the parameters except `parameters`.
137  * This function tries many parameter combinations and picks the best parameters.
138  * `*parameters` is filled with the best parameters found,
139  * dictionary constructed with those parameters is stored in `dictBuffer`.
140  *
141  * All of the parameters d, k, steps are optional.
142  * If d is non-zero then we don't check multiple values of d, otherwise we check d = {6, 8}.
143  * if steps is zero it defaults to its default value.
144  * If k is non-zero then we don't check multiple values of k, otherwise we check steps values in [50, 2000].
145  *
146  * @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)
147  *          or an error code, which can be tested with ZDICT_isError().
148  *          On success `*parameters` contains the parameters selected.
149  *          See ZDICT_trainFromBuffer() for details on failure modes.
150  * 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.
151  */
152 ZDICTLIB_API size_t ZDICT_optimizeTrainFromBuffer_cover(
153           void* dictBuffer, size_t dictBufferCapacity,
154     const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
155           ZDICT_cover_params_t* parameters);
156 
157 /*! ZDICT_trainFromBuffer_fastCover():
158  *  Train a dictionary from an array of samples using a modified version of COVER algorithm.
159  *  Samples must be stored concatenated in a single flat buffer `samplesBuffer`,
160  *  supplied with an array of sizes `samplesSizes`, providing the size of each sample, in order.
161  *  d and k are required.
162  *  All other parameters are optional, will use default values if not provided
163  *  The resulting dictionary will be saved into `dictBuffer`.
164  * @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)
165  *          or an error code, which can be tested with ZDICT_isError().
166  *          See ZDICT_trainFromBuffer() for details on failure modes.
167  *  Note: ZDICT_trainFromBuffer_fastCover() requires 6 * 2^f bytes of memory.
168  *  Tips: In general, a reasonable dictionary has a size of ~ 100 KB.
169  *        It's possible to select smaller or larger size, just by specifying `dictBufferCapacity`.
170  *        In general, it's recommended to provide a few thousands samples, though this can vary a lot.
171  *        It's recommended that total size of all samples be about ~x100 times the target size of dictionary.
172  */
173 ZDICTLIB_API size_t ZDICT_trainFromBuffer_fastCover(void *dictBuffer,
174                     size_t dictBufferCapacity, const void *samplesBuffer,
175                     const size_t *samplesSizes, unsigned nbSamples,
176                     ZDICT_fastCover_params_t parameters);
177 
178 /*! ZDICT_optimizeTrainFromBuffer_fastCover():
179  * The same requirements as above hold for all the parameters except `parameters`.
180  * This function tries many parameter combinations (specifically, k and d combinations)
181  * and picks the best parameters. `*parameters` is filled with the best parameters found,
182  * dictionary constructed with those parameters is stored in `dictBuffer`.
183  * All of the parameters d, k, steps, f, and accel are optional.
184  * If d is non-zero then we don't check multiple values of d, otherwise we check d = {6, 8}.
185  * if steps is zero it defaults to its default value.
186  * If k is non-zero then we don't check multiple values of k, otherwise we check steps values in [50, 2000].
187  * If f is zero, default value of 20 is used.
188  * If accel is zero, default value of 1 is used.
189  *
190  * @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)
191  *          or an error code, which can be tested with ZDICT_isError().
192  *          On success `*parameters` contains the parameters selected.
193  *          See ZDICT_trainFromBuffer() for details on failure modes.
194  * Note: ZDICT_optimizeTrainFromBuffer_fastCover() requires about 6 * 2^f bytes of memory for each thread.
195  */
196 ZDICTLIB_API size_t ZDICT_optimizeTrainFromBuffer_fastCover(void* dictBuffer,
197                     size_t dictBufferCapacity, const void* samplesBuffer,
198                     const size_t* samplesSizes, unsigned nbSamples,
199                     ZDICT_fastCover_params_t* parameters);
200 
201 /*! ZDICT_finalizeDictionary():
202  * Given a custom content as a basis for dictionary, and a set of samples,
203  * finalize dictionary by adding headers and statistics.
204  *
205  * Samples must be stored concatenated in a flat buffer `samplesBuffer`,
206  * supplied with an array of sizes `samplesSizes`, providing the size of each sample in order.
207  *
208  * dictContentSize must be >= ZDICT_CONTENTSIZE_MIN bytes.
209  * maxDictSize must be >= dictContentSize, and must be >= ZDICT_DICTSIZE_MIN bytes.
210  *
211  * @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`),
212  *          or an error code, which can be tested by ZDICT_isError().
213  * Note: ZDICT_finalizeDictionary() will push notifications into stderr if instructed to, using notificationLevel>0.
214  * Note 2: dictBuffer and dictContent can overlap
215  */
216 #define ZDICT_CONTENTSIZE_MIN 128
217 #define ZDICT_DICTSIZE_MIN    256
218 ZDICTLIB_API size_t ZDICT_finalizeDictionary(void* dictBuffer, size_t dictBufferCapacity,
219                                 const void* dictContent, size_t dictContentSize,
220                                 const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples,
221                                 ZDICT_params_t parameters);
222 
223 typedef struct {
224     unsigned selectivityLevel;   /* 0 means default; larger => select more => larger dictionary */
225     ZDICT_params_t zParams;
226 } ZDICT_legacy_params_t;
227 
228 /*! ZDICT_trainFromBuffer_legacy():
229  *  Train a dictionary from an array of samples.
230  *  Samples must be stored concatenated in a single flat buffer `samplesBuffer`,
231  *  supplied with an array of sizes `samplesSizes`, providing the size of each sample, in order.
232  *  The resulting dictionary will be saved into `dictBuffer`.
233  * `parameters` is optional and can be provided with values set to 0 to mean "default".
234  * @return: size of dictionary stored into `dictBuffer` (<= `dictBufferCapacity`)
235  *          or an error code, which can be tested with ZDICT_isError().
236  *          See ZDICT_trainFromBuffer() for details on failure modes.
237  *  Tips: In general, a reasonable dictionary has a size of ~ 100 KB.
238  *        It's possible to select smaller or larger size, just by specifying `dictBufferCapacity`.
239  *        In general, it's recommended to provide a few thousands samples, though this can vary a lot.
240  *        It's recommended that total size of all samples be about ~x100 times the target size of dictionary.
241  *  Note: ZDICT_trainFromBuffer_legacy() will send notifications into stderr if instructed to, using notificationLevel>0.
242  */
243 ZDICTLIB_API size_t ZDICT_trainFromBuffer_legacy(
244     void *dictBuffer, size_t dictBufferCapacity,
245     const void *samplesBuffer, const size_t *samplesSizes, unsigned nbSamples,
246     ZDICT_legacy_params_t parameters);
247 
248 /* Deprecation warnings */
249 /* It is generally possible to disable deprecation warnings from compiler,
250    for example with -Wno-deprecated-declarations for gcc
251    or _CRT_SECURE_NO_WARNINGS in Visual.
252    Otherwise, it's also possible to manually define ZDICT_DISABLE_DEPRECATE_WARNINGS */
253 #ifdef ZDICT_DISABLE_DEPRECATE_WARNINGS
254 #  define ZDICT_DEPRECATED(message) ZDICTLIB_API   /* disable deprecation warnings */
255 #else
256 #  define ZDICT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
257 #  if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */
258 #    define ZDICT_DEPRECATED(message) [[deprecated(message)]] ZDICTLIB_API
259 #  elif (ZDICT_GCC_VERSION >= 405) || defined(__clang__)
260 #    define ZDICT_DEPRECATED(message) ZDICTLIB_API __attribute__((deprecated(message)))
261 #  elif (ZDICT_GCC_VERSION >= 301)
262 #    define ZDICT_DEPRECATED(message) ZDICTLIB_API __attribute__((deprecated))
263 #  elif defined(_MSC_VER)
264 #    define ZDICT_DEPRECATED(message) ZDICTLIB_API __declspec(deprecated(message))
265 #  else
266 #    pragma message("WARNING: You need to implement ZDICT_DEPRECATED for this compiler")
267 #    define ZDICT_DEPRECATED(message) ZDICTLIB_API
268 #  endif
269 #endif /* ZDICT_DISABLE_DEPRECATE_WARNINGS */
270 
271 ZDICT_DEPRECATED("use ZDICT_finalizeDictionary() instead")
272 size_t ZDICT_addEntropyTablesFromBuffer(void* dictBuffer, size_t dictContentSize, size_t dictBufferCapacity,
273                                   const void* samplesBuffer, const size_t* samplesSizes, unsigned nbSamples);
274 
275 
276 #endif   /* ZDICT_STATIC_LINKING_ONLY */
277 
278 #if defined (__cplusplus)
279 }
280 #endif
281 
282 #endif   /* DICTBUILDER_H_001 */
283