lz4frame.h 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. /*
  2. LZ4F - LZ4-Frame library
  3. Header File
  4. Copyright (C) 2011-2020, Yann Collet.
  5. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  6. Redistribution and use in source and binary forms, with or without
  7. modification, are permitted provided that the following conditions are
  8. met:
  9. * Redistributions of source code must retain the above copyright
  10. notice, this list of conditions and the following disclaimer.
  11. * Redistributions in binary form must reproduce the above
  12. copyright notice, this list of conditions and the following disclaimer
  13. in the documentation and/or other materials provided with the
  14. distribution.
  15. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  16. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  17. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  18. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  19. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  21. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  22. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  23. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. You can contact the author at :
  27. - LZ4 source repository : https://github.com/lz4/lz4
  28. - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
  29. */
  30. /* LZ4F is a stand-alone API able to create and decode LZ4 frames
  31. * conformant with specification v1.6.1 in doc/lz4_Frame_format.md .
  32. * Generated frames are compatible with `lz4` CLI.
  33. *
  34. * LZ4F also offers streaming capabilities.
  35. *
  36. * lz4.h is not required when using lz4frame.h,
  37. * except to extract common constants such as LZ4_VERSION_NUMBER.
  38. * */
  39. #ifndef LZ4F_H_09782039843
  40. #define LZ4F_H_09782039843
  41. #if defined (__cplusplus)
  42. extern "C" {
  43. #endif
  44. /* --- Dependency --- */
  45. #include <stddef.h> /* size_t */
  46. /**
  47. * Introduction
  48. *
  49. * lz4frame.h implements LZ4 frame specification: see doc/lz4_Frame_format.md .
  50. * LZ4 Frames are compatible with `lz4` CLI,
  51. * and designed to be interoperable with any system.
  52. **/
  53. /*-***************************************************************
  54. * Compiler specifics
  55. *****************************************************************/
  56. /* LZ4_DLL_EXPORT :
  57. * Enable exporting of functions when building a Windows DLL
  58. * LZ4FLIB_VISIBILITY :
  59. * Control library symbols visibility.
  60. */
  61. #ifndef LZ4FLIB_VISIBILITY
  62. # if defined(__GNUC__) && (__GNUC__ >= 4)
  63. # define LZ4FLIB_VISIBILITY __attribute__ ((visibility ("default")))
  64. # else
  65. # define LZ4FLIB_VISIBILITY
  66. # endif
  67. #endif
  68. #if defined(LZ4_DLL_EXPORT) && (LZ4_DLL_EXPORT==1)
  69. # define LZ4FLIB_API __declspec(dllexport) LZ4FLIB_VISIBILITY
  70. #elif defined(LZ4_DLL_IMPORT) && (LZ4_DLL_IMPORT==1)
  71. # define LZ4FLIB_API __declspec(dllimport) LZ4FLIB_VISIBILITY
  72. #else
  73. # define LZ4FLIB_API LZ4FLIB_VISIBILITY
  74. #endif
  75. #ifdef LZ4F_DISABLE_DEPRECATE_WARNINGS
  76. # define LZ4F_DEPRECATE(x) x
  77. #else
  78. # if defined(_MSC_VER)
  79. # define LZ4F_DEPRECATE(x) x /* __declspec(deprecated) x - only works with C++ */
  80. # elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 6))
  81. # define LZ4F_DEPRECATE(x) x __attribute__((deprecated))
  82. # else
  83. # define LZ4F_DEPRECATE(x) x /* no deprecation warning for this compiler */
  84. # endif
  85. #endif
  86. /*-************************************
  87. * Error management
  88. **************************************/
  89. typedef size_t LZ4F_errorCode_t;
  90. LZ4FLIB_API unsigned LZ4F_isError(LZ4F_errorCode_t code); /**< tells when a function result is an error code */
  91. LZ4FLIB_API const char* LZ4F_getErrorName(LZ4F_errorCode_t code); /**< return error code string; for debugging */
  92. /*-************************************
  93. * Frame compression types
  94. ************************************* */
  95. /* #define LZ4F_ENABLE_OBSOLETE_ENUMS // uncomment to enable obsolete enums */
  96. #ifdef LZ4F_ENABLE_OBSOLETE_ENUMS
  97. # define LZ4F_OBSOLETE_ENUM(x) , LZ4F_DEPRECATE(x) = LZ4F_##x
  98. #else
  99. # define LZ4F_OBSOLETE_ENUM(x)
  100. #endif
  101. /* The larger the block size, the (slightly) better the compression ratio,
  102. * though there are diminishing returns.
  103. * Larger blocks also increase memory usage on both compression and decompression sides.
  104. */
  105. typedef enum {
  106. LZ4F_default=0,
  107. LZ4F_max64KB=4,
  108. LZ4F_max256KB=5,
  109. LZ4F_max1MB=6,
  110. LZ4F_max4MB=7
  111. LZ4F_OBSOLETE_ENUM(max64KB)
  112. LZ4F_OBSOLETE_ENUM(max256KB)
  113. LZ4F_OBSOLETE_ENUM(max1MB)
  114. LZ4F_OBSOLETE_ENUM(max4MB)
  115. } LZ4F_blockSizeID_t;
  116. /* Linked blocks sharply reduce inefficiencies when using small blocks,
  117. * they compress better.
  118. * However, some LZ4 decoders are only compatible with independent blocks */
  119. typedef enum {
  120. LZ4F_blockLinked=0,
  121. LZ4F_blockIndependent
  122. LZ4F_OBSOLETE_ENUM(blockLinked)
  123. LZ4F_OBSOLETE_ENUM(blockIndependent)
  124. } LZ4F_blockMode_t;
  125. typedef enum {
  126. LZ4F_noContentChecksum=0,
  127. LZ4F_contentChecksumEnabled
  128. LZ4F_OBSOLETE_ENUM(noContentChecksum)
  129. LZ4F_OBSOLETE_ENUM(contentChecksumEnabled)
  130. } LZ4F_contentChecksum_t;
  131. typedef enum {
  132. LZ4F_noBlockChecksum=0,
  133. LZ4F_blockChecksumEnabled
  134. } LZ4F_blockChecksum_t;
  135. typedef enum {
  136. LZ4F_frame=0,
  137. LZ4F_skippableFrame
  138. LZ4F_OBSOLETE_ENUM(skippableFrame)
  139. } LZ4F_frameType_t;
  140. #ifdef LZ4F_ENABLE_OBSOLETE_ENUMS
  141. typedef LZ4F_blockSizeID_t blockSizeID_t;
  142. typedef LZ4F_blockMode_t blockMode_t;
  143. typedef LZ4F_frameType_t frameType_t;
  144. typedef LZ4F_contentChecksum_t contentChecksum_t;
  145. #endif
  146. /*! LZ4F_frameInfo_t :
  147. * makes it possible to set or read frame parameters.
  148. * Structure must be first init to 0, using memset() or LZ4F_INIT_FRAMEINFO,
  149. * setting all parameters to default.
  150. * It's then possible to update selectively some parameters */
  151. typedef struct {
  152. LZ4F_blockSizeID_t blockSizeID; /* max64KB, max256KB, max1MB, max4MB; 0 == default (LZ4F_max64KB) */
  153. LZ4F_blockMode_t blockMode; /* LZ4F_blockLinked, LZ4F_blockIndependent; 0 == default (LZ4F_blockLinked) */
  154. LZ4F_contentChecksum_t contentChecksumFlag; /* 1: add a 32-bit checksum of frame's decompressed data; 0 == default (disabled) */
  155. LZ4F_frameType_t frameType; /* read-only field : LZ4F_frame or LZ4F_skippableFrame */
  156. unsigned long long contentSize; /* Size of uncompressed content ; 0 == unknown */
  157. unsigned dictID; /* Dictionary ID, sent by compressor to help decoder select correct dictionary; 0 == no dictID provided */
  158. LZ4F_blockChecksum_t blockChecksumFlag; /* 1: each block followed by a checksum of block's compressed data; 0 == default (disabled) */
  159. } LZ4F_frameInfo_t;
  160. #define LZ4F_INIT_FRAMEINFO { LZ4F_max64KB, LZ4F_blockLinked, LZ4F_noContentChecksum, LZ4F_frame, 0ULL, 0U, LZ4F_noBlockChecksum } /* v1.8.3+ */
  161. /*! LZ4F_preferences_t :
  162. * makes it possible to supply advanced compression instructions to streaming interface.
  163. * Structure must be first init to 0, using memset() or LZ4F_INIT_PREFERENCES,
  164. * setting all parameters to default.
  165. * All reserved fields must be set to zero. */
  166. typedef struct {
  167. LZ4F_frameInfo_t frameInfo;
  168. int compressionLevel; /* 0: default (fast mode); values > LZ4HC_CLEVEL_MAX count as LZ4HC_CLEVEL_MAX; values < 0 trigger "fast acceleration" */
  169. unsigned autoFlush; /* 1: always flush; reduces usage of internal buffers */
  170. unsigned favorDecSpeed; /* 1: parser favors decompression speed vs compression ratio. Only works for high compression modes (>= LZ4HC_CLEVEL_OPT_MIN) */ /* v1.8.2+ */
  171. unsigned reserved[3]; /* must be zero for forward compatibility */
  172. } LZ4F_preferences_t;
  173. #define LZ4F_INIT_PREFERENCES { LZ4F_INIT_FRAMEINFO, 0, 0u, 0u, { 0u, 0u, 0u } } /* v1.8.3+ */
  174. /*-*********************************
  175. * Simple compression function
  176. ***********************************/
  177. /*! LZ4F_compressFrame() :
  178. * Compress srcBuffer content into an LZ4-compressed frame.
  179. * It's a one shot operation, all input content is consumed, and all output is generated.
  180. *
  181. * Note : it's a stateless operation (no LZ4F_cctx state needed).
  182. * In order to reduce load on the allocator, LZ4F_compressFrame(), by default,
  183. * uses the stack to allocate space for the compression state and some table.
  184. * If this usage of the stack is too much for your application,
  185. * consider compiling `lz4frame.c` with compile-time macro LZ4F_HEAPMODE set to 1 instead.
  186. * All state allocations will use the Heap.
  187. * It also means each invocation of LZ4F_compressFrame() will trigger several internal alloc/free invocations.
  188. *
  189. * @dstCapacity MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr).
  190. * @preferencesPtr is optional : one can provide NULL, in which case all preferences are set to default.
  191. * @return : number of bytes written into dstBuffer.
  192. * or an error code if it fails (can be tested using LZ4F_isError())
  193. */
  194. LZ4FLIB_API size_t LZ4F_compressFrame(void* dstBuffer, size_t dstCapacity,
  195. const void* srcBuffer, size_t srcSize,
  196. const LZ4F_preferences_t* preferencesPtr);
  197. /*! LZ4F_compressFrameBound() :
  198. * Returns the maximum possible compressed size with LZ4F_compressFrame() given srcSize and preferences.
  199. * `preferencesPtr` is optional. It can be replaced by NULL, in which case, the function will assume default preferences.
  200. * Note : this result is only usable with LZ4F_compressFrame().
  201. * It may also be relevant to LZ4F_compressUpdate() _only if_ no flush() operation is ever performed.
  202. */
  203. LZ4FLIB_API size_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr);
  204. /*! LZ4F_compressionLevel_max() :
  205. * @return maximum allowed compression level (currently: 12)
  206. */
  207. LZ4FLIB_API int LZ4F_compressionLevel_max(void); /* v1.8.0+ */
  208. /*-***********************************
  209. * Advanced compression functions
  210. *************************************/
  211. typedef struct LZ4F_cctx_s LZ4F_cctx; /* incomplete type */
  212. typedef LZ4F_cctx* LZ4F_compressionContext_t; /* for compatibility with older APIs, prefer using LZ4F_cctx */
  213. typedef struct {
  214. unsigned stableSrc; /* 1 == src content will remain present on future calls to LZ4F_compress(); skip copying src content within tmp buffer */
  215. unsigned reserved[3];
  216. } LZ4F_compressOptions_t;
  217. /*--- Resource Management ---*/
  218. #define LZ4F_VERSION 100 /* This number can be used to check for an incompatible API breaking change */
  219. LZ4FLIB_API unsigned LZ4F_getVersion(void);
  220. /*! LZ4F_createCompressionContext() :
  221. * The first thing to do is to create a compressionContext object,
  222. * which will keep track of operation state during streaming compression.
  223. * This is achieved using LZ4F_createCompressionContext(), which takes as argument a version,
  224. * and a pointer to LZ4F_cctx*, to write the resulting pointer into.
  225. * @version provided MUST be LZ4F_VERSION. It is intended to track potential version mismatch, notably when using DLL.
  226. * The function provides a pointer to a fully allocated LZ4F_cctx object.
  227. * @cctxPtr MUST be != NULL.
  228. * If @return != zero, context creation failed.
  229. * A created compression context can be employed multiple times for consecutive streaming operations.
  230. * Once all streaming compression jobs are completed,
  231. * the state object can be released using LZ4F_freeCompressionContext().
  232. * Note1 : LZ4F_freeCompressionContext() is always successful. Its return value can be ignored.
  233. * Note2 : LZ4F_freeCompressionContext() works fine with NULL input pointers (do nothing).
  234. **/
  235. LZ4FLIB_API LZ4F_errorCode_t LZ4F_createCompressionContext(LZ4F_cctx** cctxPtr, unsigned version);
  236. LZ4FLIB_API LZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_cctx* cctx);
  237. /*---- Compression ----*/
  238. #define LZ4F_HEADER_SIZE_MIN 7 /* LZ4 Frame header size can vary, depending on selected parameters */
  239. #define LZ4F_HEADER_SIZE_MAX 19
  240. /* Size in bytes of a block header in little-endian format. Highest bit indicates if block data is uncompressed */
  241. #define LZ4F_BLOCK_HEADER_SIZE 4
  242. /* Size in bytes of a block checksum footer in little-endian format. */
  243. #define LZ4F_BLOCK_CHECKSUM_SIZE 4
  244. /* Size in bytes of the content checksum. */
  245. #define LZ4F_CONTENT_CHECKSUM_SIZE 4
  246. /*! LZ4F_compressBegin() :
  247. * will write the frame header into dstBuffer.
  248. * dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.
  249. * `prefsPtr` is optional : NULL can be provided to set all preferences to default.
  250. * @return : number of bytes written into dstBuffer for the header
  251. * or an error code (which can be tested using LZ4F_isError())
  252. */
  253. LZ4FLIB_API size_t LZ4F_compressBegin(LZ4F_cctx* cctx,
  254. void* dstBuffer, size_t dstCapacity,
  255. const LZ4F_preferences_t* prefsPtr);
  256. /*! LZ4F_compressBound() :
  257. * Provides minimum dstCapacity required to guarantee success of
  258. * LZ4F_compressUpdate(), given a srcSize and preferences, for a worst case scenario.
  259. * When srcSize==0, LZ4F_compressBound() provides an upper bound for LZ4F_flush() and LZ4F_compressEnd() instead.
  260. * Note that the result is only valid for a single invocation of LZ4F_compressUpdate().
  261. * When invoking LZ4F_compressUpdate() multiple times,
  262. * if the output buffer is gradually filled up instead of emptied and re-used from its start,
  263. * one must check if there is enough remaining capacity before each invocation, using LZ4F_compressBound().
  264. * @return is always the same for a srcSize and prefsPtr.
  265. * prefsPtr is optional : when NULL is provided, preferences will be set to cover worst case scenario.
  266. * tech details :
  267. * @return if automatic flushing is not enabled, includes the possibility that internal buffer might already be filled by up to (blockSize-1) bytes.
  268. * It also includes frame footer (ending + checksum), since it might be generated by LZ4F_compressEnd().
  269. * @return doesn't include frame header, as it was already generated by LZ4F_compressBegin().
  270. */
  271. LZ4FLIB_API size_t LZ4F_compressBound(size_t srcSize, const LZ4F_preferences_t* prefsPtr);
  272. /*! LZ4F_compressUpdate() :
  273. * LZ4F_compressUpdate() can be called repetitively to compress as much data as necessary.
  274. * Important rule: dstCapacity MUST be large enough to ensure operation success even in worst case situations.
  275. * This value is provided by LZ4F_compressBound().
  276. * If this condition is not respected, LZ4F_compress() will fail (result is an errorCode).
  277. * After an error, the state is left in a UB state, and must be re-initialized or freed.
  278. * If previously an uncompressed block was written, buffered data is flushed
  279. * before appending compressed data is continued.
  280. * `cOptPtr` is optional : NULL can be provided, in which case all options are set to default.
  281. * @return : number of bytes written into `dstBuffer` (it can be zero, meaning input data was just buffered).
  282. * or an error code if it fails (which can be tested using LZ4F_isError())
  283. */
  284. LZ4FLIB_API size_t LZ4F_compressUpdate(LZ4F_cctx* cctx,
  285. void* dstBuffer, size_t dstCapacity,
  286. const void* srcBuffer, size_t srcSize,
  287. const LZ4F_compressOptions_t* cOptPtr);
  288. /*! LZ4F_flush() :
  289. * When data must be generated and sent immediately, without waiting for a block to be completely filled,
  290. * it's possible to call LZ4_flush(). It will immediately compress any data buffered within cctx.
  291. * `dstCapacity` must be large enough to ensure the operation will be successful.
  292. * `cOptPtr` is optional : it's possible to provide NULL, all options will be set to default.
  293. * @return : nb of bytes written into dstBuffer (can be zero, when there is no data stored within cctx)
  294. * or an error code if it fails (which can be tested using LZ4F_isError())
  295. * Note : LZ4F_flush() is guaranteed to be successful when dstCapacity >= LZ4F_compressBound(0, prefsPtr).
  296. */
  297. LZ4FLIB_API size_t LZ4F_flush(LZ4F_cctx* cctx,
  298. void* dstBuffer, size_t dstCapacity,
  299. const LZ4F_compressOptions_t* cOptPtr);
  300. /*! LZ4F_compressEnd() :
  301. * To properly finish an LZ4 frame, invoke LZ4F_compressEnd().
  302. * It will flush whatever data remained within `cctx` (like LZ4_flush())
  303. * and properly finalize the frame, with an endMark and a checksum.
  304. * `cOptPtr` is optional : NULL can be provided, in which case all options will be set to default.
  305. * @return : nb of bytes written into dstBuffer, necessarily >= 4 (endMark),
  306. * or an error code if it fails (which can be tested using LZ4F_isError())
  307. * Note : LZ4F_compressEnd() is guaranteed to be successful when dstCapacity >= LZ4F_compressBound(0, prefsPtr).
  308. * A successful call to LZ4F_compressEnd() makes `cctx` available again for another compression task.
  309. */
  310. LZ4FLIB_API size_t LZ4F_compressEnd(LZ4F_cctx* cctx,
  311. void* dstBuffer, size_t dstCapacity,
  312. const LZ4F_compressOptions_t* cOptPtr);
  313. /*-*********************************
  314. * Decompression functions
  315. ***********************************/
  316. typedef struct LZ4F_dctx_s LZ4F_dctx; /* incomplete type */
  317. typedef LZ4F_dctx* LZ4F_decompressionContext_t; /* compatibility with previous API versions */
  318. typedef struct {
  319. unsigned stableDst; /* pledges that last 64KB decompressed data is present right before @dstBuffer pointer.
  320. * This optimization skips internal storage operations.
  321. * Once set, this pledge must remain valid up to the end of current frame. */
  322. unsigned skipChecksums; /* disable checksum calculation and verification, even when one is present in frame, to save CPU time.
  323. * Setting this option to 1 once disables all checksums for the rest of the frame. */
  324. unsigned reserved1; /* must be set to zero for forward compatibility */
  325. unsigned reserved0; /* idem */
  326. } LZ4F_decompressOptions_t;
  327. /* Resource management */
  328. /*! LZ4F_createDecompressionContext() :
  329. * Create an LZ4F_dctx object, to track all decompression operations.
  330. * @version provided MUST be LZ4F_VERSION.
  331. * @dctxPtr MUST be valid.
  332. * The function fills @dctxPtr with the value of a pointer to an allocated and initialized LZ4F_dctx object.
  333. * The @return is an errorCode, which can be tested using LZ4F_isError().
  334. * dctx memory can be released using LZ4F_freeDecompressionContext();
  335. * Result of LZ4F_freeDecompressionContext() indicates current state of decompressionContext when being released.
  336. * That is, it should be == 0 if decompression has been completed fully and correctly.
  337. */
  338. LZ4FLIB_API LZ4F_errorCode_t LZ4F_createDecompressionContext(LZ4F_dctx** dctxPtr, unsigned version);
  339. LZ4FLIB_API LZ4F_errorCode_t LZ4F_freeDecompressionContext(LZ4F_dctx* dctx);
  340. /*-***********************************
  341. * Streaming decompression functions
  342. *************************************/
  343. #define LZ4F_MAGICNUMBER 0x184D2204U
  344. #define LZ4F_MAGIC_SKIPPABLE_START 0x184D2A50U
  345. #define LZ4F_MIN_SIZE_TO_KNOW_HEADER_LENGTH 5
  346. /*! LZ4F_headerSize() : v1.9.0+
  347. * Provide the header size of a frame starting at `src`.
  348. * `srcSize` must be >= LZ4F_MIN_SIZE_TO_KNOW_HEADER_LENGTH,
  349. * which is enough to decode the header length.
  350. * @return : size of frame header
  351. * or an error code, which can be tested using LZ4F_isError()
  352. * note : Frame header size is variable, but is guaranteed to be
  353. * >= LZ4F_HEADER_SIZE_MIN bytes, and <= LZ4F_HEADER_SIZE_MAX bytes.
  354. */
  355. LZ4FLIB_API size_t LZ4F_headerSize(const void* src, size_t srcSize);
  356. /*! LZ4F_getFrameInfo() :
  357. * This function extracts frame parameters (max blockSize, dictID, etc.).
  358. * Its usage is optional: user can also invoke LZ4F_decompress() directly.
  359. *
  360. * Extracted information will fill an existing LZ4F_frameInfo_t structure.
  361. * This can be useful for allocation and dictionary identification purposes.
  362. *
  363. * LZ4F_getFrameInfo() can work in the following situations :
  364. *
  365. * 1) At the beginning of a new frame, before any invocation of LZ4F_decompress().
  366. * It will decode header from `srcBuffer`,
  367. * consuming the header and starting the decoding process.
  368. *
  369. * Input size must be large enough to contain the full frame header.
  370. * Frame header size can be known beforehand by LZ4F_headerSize().
  371. * Frame header size is variable, but is guaranteed to be >= LZ4F_HEADER_SIZE_MIN bytes,
  372. * and not more than <= LZ4F_HEADER_SIZE_MAX bytes.
  373. * Hence, blindly providing LZ4F_HEADER_SIZE_MAX bytes or more will always work.
  374. * It's allowed to provide more input data than the header size,
  375. * LZ4F_getFrameInfo() will only consume the header.
  376. *
  377. * If input size is not large enough,
  378. * aka if it's smaller than header size,
  379. * function will fail and return an error code.
  380. *
  381. * 2) After decoding has been started,
  382. * it's possible to invoke LZ4F_getFrameInfo() anytime
  383. * to extract already decoded frame parameters stored within dctx.
  384. *
  385. * Note that, if decoding has barely started,
  386. * and not yet read enough information to decode the header,
  387. * LZ4F_getFrameInfo() will fail.
  388. *
  389. * The number of bytes consumed from srcBuffer will be updated in *srcSizePtr (necessarily <= original value).
  390. * LZ4F_getFrameInfo() only consumes bytes when decoding has not yet started,
  391. * and when decoding the header has been successful.
  392. * Decompression must then resume from (srcBuffer + *srcSizePtr).
  393. *
  394. * @return : a hint about how many srcSize bytes LZ4F_decompress() expects for next call,
  395. * or an error code which can be tested using LZ4F_isError().
  396. * note 1 : in case of error, dctx is not modified. Decoding operation can resume from beginning safely.
  397. * note 2 : frame parameters are *copied into* an already allocated LZ4F_frameInfo_t structure.
  398. */
  399. LZ4FLIB_API size_t
  400. LZ4F_getFrameInfo(LZ4F_dctx* dctx,
  401. LZ4F_frameInfo_t* frameInfoPtr,
  402. const void* srcBuffer, size_t* srcSizePtr);
  403. /*! LZ4F_decompress() :
  404. * Call this function repetitively to regenerate data compressed in `srcBuffer`.
  405. *
  406. * The function requires a valid dctx state.
  407. * It will read up to *srcSizePtr bytes from srcBuffer,
  408. * and decompress data into dstBuffer, of capacity *dstSizePtr.
  409. *
  410. * The nb of bytes consumed from srcBuffer will be written into *srcSizePtr (necessarily <= original value).
  411. * The nb of bytes decompressed into dstBuffer will be written into *dstSizePtr (necessarily <= original value).
  412. *
  413. * The function does not necessarily read all input bytes, so always check value in *srcSizePtr.
  414. * Unconsumed source data must be presented again in subsequent invocations.
  415. *
  416. * `dstBuffer` can freely change between each consecutive function invocation.
  417. * `dstBuffer` content will be overwritten.
  418. *
  419. * Note: if `LZ4F_getFrameInfo()` is called before `LZ4F_decompress()`, srcBuffer must be updated to reflect
  420. * the number of bytes consumed after reading the frame header. Failure to update srcBuffer before calling
  421. * `LZ4F_decompress()` will cause decompression failure or, even worse, successful but incorrect decompression.
  422. * See the `LZ4F_getFrameInfo()` docs for details.
  423. *
  424. * @return : an hint of how many `srcSize` bytes LZ4F_decompress() expects for next call.
  425. * Schematically, it's the size of the current (or remaining) compressed block + header of next block.
  426. * Respecting the hint provides some small speed benefit, because it skips intermediate buffers.
  427. * This is just a hint though, it's always possible to provide any srcSize.
  428. *
  429. * When a frame is fully decoded, @return will be 0 (no more data expected).
  430. * When provided with more bytes than necessary to decode a frame,
  431. * LZ4F_decompress() will stop reading exactly at end of current frame, and @return 0.
  432. *
  433. * If decompression failed, @return is an error code, which can be tested using LZ4F_isError().
  434. * After a decompression error, the `dctx` context is not resumable.
  435. * Use LZ4F_resetDecompressionContext() to return to clean state.
  436. *
  437. * After a frame is fully decoded, dctx can be used again to decompress another frame.
  438. */
  439. LZ4FLIB_API size_t
  440. LZ4F_decompress(LZ4F_dctx* dctx,
  441. void* dstBuffer, size_t* dstSizePtr,
  442. const void* srcBuffer, size_t* srcSizePtr,
  443. const LZ4F_decompressOptions_t* dOptPtr);
  444. /*! LZ4F_resetDecompressionContext() : added in v1.8.0
  445. * In case of an error, the context is left in "undefined" state.
  446. * In which case, it's necessary to reset it, before re-using it.
  447. * This method can also be used to abruptly stop any unfinished decompression,
  448. * and start a new one using same context resources. */
  449. LZ4FLIB_API void LZ4F_resetDecompressionContext(LZ4F_dctx* dctx); /* always successful */
  450. /**********************************
  451. * Dictionary compression API
  452. *********************************/
  453. /* A Dictionary is useful for the compression of small messages (KB range).
  454. * It dramatically improves compression efficiency.
  455. *
  456. * LZ4 can ingest any input as dictionary, though only the last 64 KB are useful.
  457. * Better results are generally achieved by using Zstandard's Dictionary Builder
  458. * to generate a high-quality dictionary from a set of samples.
  459. *
  460. * The same dictionary will have to be used on the decompression side
  461. * for decoding to be successful.
  462. * To help identify the correct dictionary at decoding stage,
  463. * the frame header allows optional embedding of a dictID field.
  464. */
  465. /*! LZ4F_compressBegin_usingDict() : stable since v1.10
  466. * Inits dictionary compression streaming, and writes the frame header into dstBuffer.
  467. * @dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.
  468. * @prefsPtr is optional : one may provide NULL as argument,
  469. * however, it's the only way to provide dictID in the frame header.
  470. * @dictBuffer must outlive the compression session.
  471. * @return : number of bytes written into dstBuffer for the header,
  472. * or an error code (which can be tested using LZ4F_isError())
  473. * NOTE: The LZ4Frame spec allows each independent block to be compressed with the dictionary,
  474. * but this entry supports a more limited scenario, where only the first block uses the dictionary.
  475. * This is still useful for small data, which only need one block anyway.
  476. * For larger inputs, one may be more interested in LZ4F_compressFrame_usingCDict() below.
  477. */
  478. LZ4FLIB_API size_t
  479. LZ4F_compressBegin_usingDict(LZ4F_cctx* cctx,
  480. void* dstBuffer, size_t dstCapacity,
  481. const void* dictBuffer, size_t dictSize,
  482. const LZ4F_preferences_t* prefsPtr);
  483. /*! LZ4F_decompress_usingDict() : stable since v1.10
  484. * Same as LZ4F_decompress(), using a predefined dictionary.
  485. * Dictionary is used "in place", without any preprocessing.
  486. ** It must remain accessible throughout the entire frame decoding. */
  487. LZ4FLIB_API size_t
  488. LZ4F_decompress_usingDict(LZ4F_dctx* dctxPtr,
  489. void* dstBuffer, size_t* dstSizePtr,
  490. const void* srcBuffer, size_t* srcSizePtr,
  491. const void* dict, size_t dictSize,
  492. const LZ4F_decompressOptions_t* decompressOptionsPtr);
  493. /*****************************************
  494. * Bulk processing dictionary compression
  495. *****************************************/
  496. /* Loading a dictionary has a cost, since it involves construction of tables.
  497. * The Bulk processing dictionary API makes it possible to share this cost
  498. * over an arbitrary number of compression jobs, even concurrently,
  499. * markedly improving compression latency for these cases.
  500. *
  501. * Note that there is no corresponding bulk API for the decompression side,
  502. * because dictionary does not carry any initialization cost for decompression.
  503. * Use the regular LZ4F_decompress_usingDict() there.
  504. */
  505. typedef struct LZ4F_CDict_s LZ4F_CDict;
  506. /*! LZ4_createCDict() : stable since v1.10
  507. * When compressing multiple messages / blocks using the same dictionary, it's recommended to initialize it just once.
  508. * LZ4_createCDict() will create a digested dictionary, ready to start future compression operations without startup delay.
  509. * LZ4_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only.
  510. * @dictBuffer can be released after LZ4_CDict creation, since its content is copied within CDict. */
  511. LZ4FLIB_API LZ4F_CDict* LZ4F_createCDict(const void* dictBuffer, size_t dictSize);
  512. LZ4FLIB_API void LZ4F_freeCDict(LZ4F_CDict* CDict);
  513. /*! LZ4_compressFrame_usingCDict() : stable since v1.10
  514. * Compress an entire srcBuffer into a valid LZ4 frame using a digested Dictionary.
  515. * @cctx must point to a context created by LZ4F_createCompressionContext().
  516. * If @cdict==NULL, compress without a dictionary.
  517. * @dstBuffer MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr).
  518. * If this condition is not respected, function will fail (@return an errorCode).
  519. * The LZ4F_preferences_t structure is optional : one may provide NULL as argument,
  520. * but it's not recommended, as it's the only way to provide @dictID in the frame header.
  521. * @return : number of bytes written into dstBuffer.
  522. * or an error code if it fails (can be tested using LZ4F_isError())
  523. * Note: for larger inputs generating multiple independent blocks,
  524. * this entry point uses the dictionary for each block. */
  525. LZ4FLIB_API size_t
  526. LZ4F_compressFrame_usingCDict(LZ4F_cctx* cctx,
  527. void* dst, size_t dstCapacity,
  528. const void* src, size_t srcSize,
  529. const LZ4F_CDict* cdict,
  530. const LZ4F_preferences_t* preferencesPtr);
  531. /*! LZ4F_compressBegin_usingCDict() : stable since v1.10
  532. * Inits streaming dictionary compression, and writes the frame header into dstBuffer.
  533. * @dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.
  534. * @prefsPtr is optional : one may provide NULL as argument,
  535. * note however that it's the only way to insert a @dictID in the frame header.
  536. * @cdict must outlive the compression session.
  537. * @return : number of bytes written into dstBuffer for the header,
  538. * or an error code, which can be tested using LZ4F_isError(). */
  539. LZ4FLIB_API size_t
  540. LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctx,
  541. void* dstBuffer, size_t dstCapacity,
  542. const LZ4F_CDict* cdict,
  543. const LZ4F_preferences_t* prefsPtr);
  544. #if defined (__cplusplus)
  545. }
  546. #endif
  547. #endif /* LZ4F_H_09782039843 */
  548. #if defined(LZ4F_STATIC_LINKING_ONLY) && !defined(LZ4F_H_STATIC_09782039843)
  549. #define LZ4F_H_STATIC_09782039843
  550. /* Note :
  551. * The below declarations are not stable and may change in the future.
  552. * They are therefore only safe to depend on
  553. * when the caller is statically linked against the library.
  554. * To access their declarations, define LZ4F_STATIC_LINKING_ONLY.
  555. *
  556. * By default, these symbols aren't published into shared/dynamic libraries.
  557. * You can override this behavior and force them to be published
  558. * by defining LZ4F_PUBLISH_STATIC_FUNCTIONS.
  559. * Use at your own risk.
  560. */
  561. #if defined (__cplusplus)
  562. extern "C" {
  563. #endif
  564. #ifdef LZ4F_PUBLISH_STATIC_FUNCTIONS
  565. # define LZ4FLIB_STATIC_API LZ4FLIB_API
  566. #else
  567. # define LZ4FLIB_STATIC_API
  568. #endif
  569. /* --- Error List --- */
  570. #define LZ4F_LIST_ERRORS(ITEM) \
  571. ITEM(OK_NoError) \
  572. ITEM(ERROR_GENERIC) \
  573. ITEM(ERROR_maxBlockSize_invalid) \
  574. ITEM(ERROR_blockMode_invalid) \
  575. ITEM(ERROR_parameter_invalid) \
  576. ITEM(ERROR_compressionLevel_invalid) \
  577. ITEM(ERROR_headerVersion_wrong) \
  578. ITEM(ERROR_blockChecksum_invalid) \
  579. ITEM(ERROR_reservedFlag_set) \
  580. ITEM(ERROR_allocation_failed) \
  581. ITEM(ERROR_srcSize_tooLarge) \
  582. ITEM(ERROR_dstMaxSize_tooSmall) \
  583. ITEM(ERROR_frameHeader_incomplete) \
  584. ITEM(ERROR_frameType_unknown) \
  585. ITEM(ERROR_frameSize_wrong) \
  586. ITEM(ERROR_srcPtr_wrong) \
  587. ITEM(ERROR_decompressionFailed) \
  588. ITEM(ERROR_headerChecksum_invalid) \
  589. ITEM(ERROR_contentChecksum_invalid) \
  590. ITEM(ERROR_frameDecoding_alreadyStarted) \
  591. ITEM(ERROR_compressionState_uninitialized) \
  592. ITEM(ERROR_parameter_null) \
  593. ITEM(ERROR_io_write) \
  594. ITEM(ERROR_io_read) \
  595. ITEM(ERROR_maxCode)
  596. #define LZ4F_GENERATE_ENUM(ENUM) LZ4F_##ENUM,
  597. /* enum list is exposed, to handle specific errors */
  598. typedef enum { LZ4F_LIST_ERRORS(LZ4F_GENERATE_ENUM)
  599. _LZ4F_dummy_error_enum_for_c89_never_used } LZ4F_errorCodes;
  600. LZ4FLIB_STATIC_API LZ4F_errorCodes LZ4F_getErrorCode(size_t functionResult);
  601. /**********************************
  602. * Advanced compression operations
  603. *********************************/
  604. /*! LZ4F_getBlockSize() :
  605. * @return, in scalar format (size_t),
  606. * the maximum block size associated with @blockSizeID,
  607. * or an error code (can be tested using LZ4F_isError()) if @blockSizeID is invalid.
  608. **/
  609. LZ4FLIB_STATIC_API size_t LZ4F_getBlockSize(LZ4F_blockSizeID_t blockSizeID);
  610. /*! LZ4F_uncompressedUpdate() :
  611. * LZ4F_uncompressedUpdate() can be called repetitively to add data stored as uncompressed blocks.
  612. * Important rule: dstCapacity MUST be large enough to store the entire source buffer as
  613. * no compression is done for this operation
  614. * If this condition is not respected, LZ4F_uncompressedUpdate() will fail (result is an errorCode).
  615. * After an error, the state is left in a UB state, and must be re-initialized or freed.
  616. * If previously a compressed block was written, buffered data is flushed first,
  617. * before appending uncompressed data is continued.
  618. * This operation is only supported when LZ4F_blockIndependent is used.
  619. * `cOptPtr` is optional : NULL can be provided, in which case all options are set to default.
  620. * @return : number of bytes written into `dstBuffer` (it can be zero, meaning input data was just buffered).
  621. * or an error code if it fails (which can be tested using LZ4F_isError())
  622. */
  623. LZ4FLIB_STATIC_API size_t
  624. LZ4F_uncompressedUpdate(LZ4F_cctx* cctx,
  625. void* dstBuffer, size_t dstCapacity,
  626. const void* srcBuffer, size_t srcSize,
  627. const LZ4F_compressOptions_t* cOptPtr);
  628. /**********************************
  629. * Custom memory allocation
  630. *********************************/
  631. /*! Custom memory allocation : v1.9.4+
  632. * These prototypes make it possible to pass custom allocation/free functions.
  633. * LZ4F_customMem is provided at state creation time, using LZ4F_create*_advanced() listed below.
  634. * All allocation/free operations will be completed using these custom variants instead of regular <stdlib.h> ones.
  635. */
  636. typedef void* (*LZ4F_AllocFunction) (void* opaqueState, size_t size);
  637. typedef void* (*LZ4F_CallocFunction) (void* opaqueState, size_t size);
  638. typedef void (*LZ4F_FreeFunction) (void* opaqueState, void* address);
  639. typedef struct {
  640. LZ4F_AllocFunction customAlloc;
  641. LZ4F_CallocFunction customCalloc; /* optional; when not defined, uses customAlloc + memset */
  642. LZ4F_FreeFunction customFree;
  643. void* opaqueState;
  644. } LZ4F_CustomMem;
  645. static
  646. #ifdef __GNUC__
  647. __attribute__((__unused__))
  648. #endif
  649. LZ4F_CustomMem const LZ4F_defaultCMem = { NULL, NULL, NULL, NULL }; /**< this constant defers to stdlib's functions */
  650. LZ4FLIB_STATIC_API LZ4F_cctx* LZ4F_createCompressionContext_advanced(LZ4F_CustomMem customMem, unsigned version);
  651. LZ4FLIB_STATIC_API LZ4F_dctx* LZ4F_createDecompressionContext_advanced(LZ4F_CustomMem customMem, unsigned version);
  652. LZ4FLIB_STATIC_API LZ4F_CDict* LZ4F_createCDict_advanced(LZ4F_CustomMem customMem, const void* dictBuffer, size_t dictSize);
  653. #if defined (__cplusplus)
  654. }
  655. #endif
  656. #endif /* defined(LZ4F_STATIC_LINKING_ONLY) && !defined(LZ4F_H_STATIC_09782039843) */