zdict.h 18 KB

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