summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorYann Collet <yann.collet.73@gmail.com>2014-09-23 09:00:55 (GMT)
committerYann Collet <yann.collet.73@gmail.com>2014-09-23 09:00:55 (GMT)
commitdc245be066cddb816a913289bfea2ab899b065ad (patch)
treeed96414c79da5f3f6985dc03b3bbc2c0a560e0da
parent6e9183ba44a6863f99023c82e8d9752a8a0a92a6 (diff)
parent8c1ae998379bce4a0e719aaac43a777713ab5c00 (diff)
downloadlz4-dc245be066cddb816a913289bfea2ab899b065ad.zip
lz4-dc245be066cddb816a913289bfea2ab899b065ad.tar.gz
lz4-dc245be066cddb816a913289bfea2ab899b065ad.tar.bz2
Merge pull request #27 from Cyan4973/dev
lz4frame
-rw-r--r--Makefile2
-rw-r--r--NEWS5
-rw-r--r--examples/blockStreaming_doubleBuffer.c6
-rw-r--r--examples/blockStreaming_lineByLine.c6
-rw-r--r--examples/blockStreaming_ringBuffer.c6
-rw-r--r--lz4.c32
-rw-r--r--lz4.h27
-rw-r--r--lz4frame.c1274
-rw-r--r--lz4frame.h261
-rw-r--r--lz4hc.c3
-rw-r--r--programs/Makefile32
-rw-r--r--programs/frametest.c668
-rw-r--r--programs/fullbench.c124
-rw-r--r--programs/fuzzer.c72
-rw-r--r--programs/lz4cli.c8
-rw-r--r--programs/lz4io.c2
-rw-r--r--xxhash.c (renamed from programs/xxhash.c)0
-rw-r--r--xxhash.h (renamed from programs/xxhash.h)0
18 files changed, 2394 insertions, 134 deletions
diff --git a/Makefile b/Makefile
index 30ecbb7..b21ae2f 100644
--- a/Makefile
+++ b/Makefile
@@ -31,7 +31,7 @@
# ################################################################
# Version numbers
-VERSION=122
+VERSION=123
export RELEASE=r$(VERSION)
LIBVER_MAJOR=`sed -n '/define LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < lz4.h`
LIBVER_MINOR=`sed -n '/define LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < lz4.h`
diff --git a/NEWS b/NEWS
index 69e5c4e..41d5762 100644
--- a/NEWS
+++ b/NEWS
@@ -1,3 +1,8 @@
+r123:
+Added : experimental lz4frame API, thanks to Takayuki Matsuoka and Christopher Jackson for testings
+Fix : s390x support, thanks to Nobuhiro Iwamatsu
+Fix : test mode (-t) no longer requires confirmation, thanks to Thary Nguyen
+
r122:
Fix : AIX & AIX64 support (SamG)
Fix : mips 64-bits support (lew van)
diff --git a/examples/blockStreaming_doubleBuffer.c b/examples/blockStreaming_doubleBuffer.c
index bd87e77..0adf6ae 100644
--- a/examples/blockStreaming_doubleBuffer.c
+++ b/examples/blockStreaming_doubleBuffer.c
@@ -140,9 +140,9 @@ int main(int argc, char* argv[])
return 0;
}
- sprintf(inpFilename, "%s", argv[1]);
- sprintf(lz4Filename, "%s.lz4s-%d", argv[1], BLOCK_BYTES);
- sprintf(decFilename, "%s.lz4s-%d.dec", argv[1], BLOCK_BYTES);
+ snprintf(inpFilename, 256, "%s", argv[1]);
+ snprintf(lz4Filename, 256, "%s.lz4s-%d", argv[1], BLOCK_BYTES);
+ snprintf(decFilename, 256, "%s.lz4s-%d.dec", argv[1], BLOCK_BYTES);
printf("inp = [%s]\n", inpFilename);
printf("lz4 = [%s]\n", lz4Filename);
diff --git a/examples/blockStreaming_lineByLine.c b/examples/blockStreaming_lineByLine.c
index e236a44..6d14801 100644
--- a/examples/blockStreaming_lineByLine.c
+++ b/examples/blockStreaming_lineByLine.c
@@ -158,9 +158,9 @@ int main(int argc, char* argv[])
return 0;
}
- sprintf(inpFilename, "%s", argv[1]);
- sprintf(lz4Filename, "%s.lz4s", argv[1]);
- sprintf(decFilename, "%s.lz4s.dec", argv[1]);
+ snprintf(inpFilename, 256, "%s", argv[1]);
+ snprintf(lz4Filename, 256, "%s.lz4s", argv[1]);
+ snprintf(decFilename, 256, "%s.lz4s.dec", argv[1]);
printf("inp = [%s]\n", inpFilename);
printf("lz4 = [%s]\n", lz4Filename);
diff --git a/examples/blockStreaming_ringBuffer.c b/examples/blockStreaming_ringBuffer.c
index 725e375..bfdbed1 100644
--- a/examples/blockStreaming_ringBuffer.c
+++ b/examples/blockStreaming_ringBuffer.c
@@ -136,9 +136,9 @@ int main(int argc, char** argv)
return 0;
}
- sprintf(inpFilename, "%s", argv[1]);
- sprintf(lz4Filename, "%s.lz4s-%d", argv[1], 0);
- sprintf(decFilename, "%s.lz4s-%d.dec", argv[1], 0);
+ snprintf(inpFilename, 256, "%s", argv[1]);
+ snprintf(lz4Filename, 256, "%s.lz4s-%d", argv[1], 0);
+ snprintf(decFilename, 256, "%s.lz4s-%d.dec", argv[1], 0);
printf("inp = [%s]\n", inpFilename);
printf("lz4 = [%s]\n", lz4Filename);
diff --git a/lz4.c b/lz4.c
index 435f1ea..39f176f 100644
--- a/lz4.c
+++ b/lz4.c
@@ -51,7 +51,8 @@
|| defined(__powerpc64__) || defined(__powerpc64le__) \
|| defined(__ppc64__) || defined(__ppc64le__) \
|| defined(__PPC64__) || defined(__PPC64LE__) \
- || defined(__ia64) || defined(__itanium__) || defined(_M_IA64) ) /* Detects 64 bits mode */
+ || defined(__ia64) || defined(__itanium__) || defined(_M_IA64) \
+ || defined(__s390x__) ) /* Detects 64 bits mode */
# define LZ4_ARCH64 1
#else
# define LZ4_ARCH64 0
@@ -855,12 +856,12 @@ int LZ4_saveDict (LZ4_stream_t* LZ4_dict, char* safeBuffer, int dictSize)
if ((U32)dictSize > 64 KB) dictSize = 64 KB; /* useless to define a dictionary > 64 KB */
if ((U32)dictSize > dict->dictSize) dictSize = dict->dictSize;
- memcpy(safeBuffer, previousDictEnd - dictSize, dictSize);
+ memmove(safeBuffer, previousDictEnd - dictSize, dictSize);
dict->dictionary = (const BYTE*)safeBuffer;
dict->dictSize = (U32)dictSize;
- return 1;
+ return dictSize;
}
@@ -870,9 +871,9 @@ int LZ4_saveDict (LZ4_stream_t* LZ4_dict, char* safeBuffer, int dictSize)
****************************/
/*
* This generic decompression function cover all use cases.
- * It shall be instanciated several times, using different sets of directives
+ * It shall be instantiated several times, using different sets of directives
* Note that it is essential this generic function is really inlined,
- * in order to remove useless branches during compilation optimisation.
+ * in order to remove useless branches during compilation optimization.
*/
FORCE_INLINE int LZ4_decompress_generic(
const char* source,
@@ -1153,14 +1154,31 @@ Advanced decoding functions :
the dictionary must be explicitly provided within parameters
*/
+FORCE_INLINE int LZ4_decompress_usingDict_generic(const char* source, char* dest, int compressedSize, int maxOutputSize, int safe, const char* dictStart, int dictSize)
+{
+ if (dictSize==0)
+ return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, noDict, NULL, 64 KB);
+ if ((dictStart+dictSize == dest) && (dictSize >= (int)(64 KB - 1)))
+ return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, withPrefix64k, NULL, 64 KB);
+ return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, usingExtDict, dictStart, dictSize);
+}
+
int LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize)
{
- return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, usingExtDict, dictStart, dictSize);
+ //return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, usingExtDict, dictStart, dictSize);
+ return LZ4_decompress_usingDict_generic(source, dest, compressedSize, maxOutputSize, 1, dictStart, dictSize);
}
int LZ4_decompress_fast_usingDict(const char* source, char* dest, int originalSize, const char* dictStart, int dictSize)
{
- return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, full, 0, usingExtDict, dictStart, dictSize);
+ //return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, full, 0, usingExtDict, dictStart, dictSize);
+ return LZ4_decompress_usingDict_generic(source, dest, 0, originalSize, 0, dictStart, dictSize);
+}
+
+/* debug function */
+int LZ4_decompress_safe_forceExtDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize)
+{
+ return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, usingExtDict, dictStart, dictSize);
}
diff --git a/lz4.h b/lz4.h
index 377e075..44ada14 100644
--- a/lz4.h
+++ b/lz4.h
@@ -37,13 +37,18 @@
extern "C" {
#endif
+/*
+ * lz4.h provides raw compression format functions, for optimal performance and integration into programs.
+ * If you need to generate data using an inter-operable format (respecting the framing specification),
+ * please use lz4frame.h instead.
+*/
/**************************************
Version
**************************************/
#define LZ4_VERSION_MAJOR 1 /* for major interface/format changes */
#define LZ4_VERSION_MINOR 3 /* for minor interface/format changes */
-#define LZ4_VERSION_RELEASE 0 /* for tweaks, bug-fixes, or development */
+#define LZ4_VERSION_RELEASE 1 /* for tweaks, bug-fixes, or development */
#define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE)
int LZ4_versionNumber (void);
@@ -142,7 +147,7 @@ LZ4_decompress_fast() :
Destination buffer must be already allocated. Its size must be a minimum of 'originalSize' bytes.
note : This function fully respect memory boundaries for properly formed compressed data.
It is a bit faster than LZ4_decompress_safe().
- However, it does not provide any protection against intentionnally modified data stream (malicious input).
+ However, it does not provide any protection against intentionally modified data stream (malicious input).
Use this function in trusted environment only (data to decode comes from a trusted source).
*/
int LZ4_decompress_fast (const char* source, char* dest, int originalSize);
@@ -178,10 +183,9 @@ typedef struct { unsigned int table[LZ4_STREAMSIZE_U32]; } LZ4_stream_t;
/*
* LZ4_resetStream
- * Use this function to init a newly allocated LZ4_stream_t structure
- * You can also reset an existing LZ4_stream_t structure
+ * Use this function to init an allocated LZ4_stream_t structure
*/
-void LZ4_resetStream (LZ4_stream_t* LZ4_stream);
+void LZ4_resetStream (LZ4_stream_t* LZ4_streamPtr);
/*
* If you prefer dynamic allocation methods,
@@ -217,10 +221,10 @@ int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* s
/*
* LZ4_saveDict
* If previously compressed data block is not guaranteed to remain available at its memory location
- * save it into a safe place (char* safeBuffer)
+ * save it into a safer place (char* safeBuffer)
* Note : you don't need to call LZ4_loadDict() afterwards,
* dictionary is immediately usable, you can therefore call again LZ4_compress_continue()
- * Return : 1 if OK, 0 if error
+ * Return : dictionary size in bytes, or 0 if error
* Note : any dictSize > 64 KB will be interpreted as 64KB.
*/
int LZ4_saveDict (LZ4_stream_t* LZ4_stream, char* safeBuffer, int dictSize);
@@ -262,9 +266,9 @@ int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream);
These decoding functions allow decompression of multiple blocks in "streaming" mode.
Previously decoded blocks must still be available at the memory position where they were decoded.
If it's not possible, save the relevant part of decoded data into a safe buffer,
- and indicate where its new address using LZ4_setDictDecode()
+ and indicate where its new address using LZ4_setStreamDecode()
*/
-int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxOutputSize);
+int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxDecompressedSize);
int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize);
@@ -273,10 +277,9 @@ Advanced decoding functions :
*_usingDict() :
These decoding functions work the same as
a combination of LZ4_setDictDecode() followed by LZ4_decompress_x_continue()
- all together into a single function call.
- It doesn't use nor update an LZ4_streamDecode_t structure.
+ They don't use nor update an LZ4_streamDecode_t structure.
*/
-int LZ4_decompress_safe_usingDict (const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize);
+int LZ4_decompress_safe_usingDict (const char* source, char* dest, int compressedSize, int maxDecompressedSize, const char* dictStart, int dictSize);
int LZ4_decompress_fast_usingDict (const char* source, char* dest, int originalSize, const char* dictStart, int dictSize);
diff --git a/lz4frame.c b/lz4frame.c
new file mode 100644
index 0000000..3a750c0
--- /dev/null
+++ b/lz4frame.c
@@ -0,0 +1,1274 @@
+/*
+ LZ4 auto-framing library
+ Copyright (C) 2011-2014, Yann Collet.
+ BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following disclaimer
+ in the documentation and/or other materials provided with the
+ distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ You can contact the author at :
+ - LZ4 source repository : http://code.google.com/p/lz4/
+ - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
+*/
+
+/* LZ4F is a stand-alone API to create LZ4-compressed frames
+ * fully conformant to specification v1.4.1.
+ * All related operations, including memory management, are handled by the library.
+ * You don't need lz4.h when using lz4frame.h.
+ * */
+
+
+/**************************************
+ Compiler Options
+**************************************/
+#ifdef _MSC_VER /* Visual Studio */
+# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
+#endif
+
+#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
+#ifdef __GNUC__
+# pragma GCC diagnostic ignored "-Wmissing-braces" /* GCC bug 53119 : doesn't accept { 0 } as initializer (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53119) */
+# pragma GCC diagnostic ignored "-Wmissing-field-initializers" /* GCC bug 53119 : doesn't accept { 0 } as initializer (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53119) */
+#endif
+
+
+/**************************************
+ Memory routines
+**************************************/
+#include <stdlib.h> /* malloc, calloc, free */
+#define ALLOCATOR(s) calloc(1,s)
+#define FREEMEM free
+#include <string.h> /* memset, memcpy, memmove */
+#define MEM_INIT memset
+
+
+/**************************************
+ Includes
+**************************************/
+#include "lz4frame.h"
+#include "lz4.h"
+#include "lz4hc.h"
+#include "xxhash.h"
+
+
+/**************************************
+ Basic Types
+**************************************/
+#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */
+# include <stdint.h>
+typedef uint8_t BYTE;
+typedef uint16_t U16;
+typedef uint32_t U32;
+typedef int32_t S32;
+typedef uint64_t U64;
+#else
+typedef unsigned char BYTE;
+typedef unsigned short U16;
+typedef unsigned int U32;
+typedef signed int S32;
+typedef unsigned long long U64;
+#endif
+
+
+/**************************************
+ Constants
+**************************************/
+#define KB *(1<<10)
+#define MB *(1<<20)
+#define GB *(1<<30)
+
+#define _1BIT 0x01
+#define _2BITS 0x03
+#define _3BITS 0x07
+#define _4BITS 0x0F
+#define _8BITS 0xFF
+
+#define LZ4F_MAGICNUMBER 0x184D2204U
+#define LZ4F_BLOCKUNCOMPRESSED_FLAG 0x80000000U
+#define LZ4F_MAXHEADERFRAME_SIZE 7
+#define LZ4F_BLOCKSIZEID_DEFAULT 4
+
+
+/**************************************
+ Structures and local types
+**************************************/
+typedef struct
+{
+ LZ4F_preferences_t prefs;
+ unsigned version;
+ unsigned cStage;
+ size_t maxBlockSize;
+ size_t maxBufferSize;
+ BYTE* tmpBuff;
+ BYTE* tmpIn;
+ size_t tmpInSize;
+ XXH32_stateSpace_t xxh;
+ LZ4_stream_t lz4ctx;
+} LZ4F_cctx_internal_t;
+
+typedef struct
+{
+ LZ4F_frameInfo_t frameInfo;
+ unsigned version;
+ unsigned dStage;
+ size_t maxBlockSize;
+ size_t maxBufferSize;
+ const BYTE* srcExpect;
+ BYTE* tmpIn;
+ size_t tmpInSize;
+ size_t tmpInTarget;
+ BYTE* tmpOutBuffer;
+ BYTE* dict;
+ size_t dictSize;
+ BYTE* tmpOut;
+ size_t tmpOutSize;
+ size_t tmpOutStart;
+ XXH32_stateSpace_t xxh;
+ BYTE header[8];
+} LZ4F_dctx_internal_t;
+
+
+/**************************************
+ Macros
+**************************************/
+
+
+/**************************************
+ Error management
+**************************************/
+#define LZ4F_GENERATE_STRING(STRING) #STRING,
+static const char* LZ4F_errorStrings[] = { LZ4F_LIST_ERRORS(LZ4F_GENERATE_STRING) };
+
+/*
+typedef enum { OK_NoError=0, ERROR_GENERIC = 1,
+ ERROR_maxBlockSize_invalid, ERROR_blockMode_invalid, ERROR_contentChecksumFlag_invalid,
+ ERROR_compressionLevel_invalid,
+ ERROR_allocation_failed,
+ ERROR_srcSize_tooLarge, ERROR_dstMaxSize_tooSmall,
+ ERROR_decompressionFailed,
+ ERROR_checksum_invalid,
+ ERROR_maxCode
+ } LZ4F_errorCodes; error codes are negative unsigned values.
+ Compare function result to (-specificCode) */
+
+int LZ4F_isError(LZ4F_errorCode_t code)
+{
+ return (code > (LZ4F_errorCode_t)(-ERROR_maxCode));
+}
+
+const char* LZ4F_getErrorName(LZ4F_errorCode_t code)
+{
+ static const char* codeError = "Unspecified error code";
+ if (LZ4F_isError(code)) return LZ4F_errorStrings[-(int)(code)];
+ return codeError;
+}
+
+
+/**************************************
+ Private functions
+**************************************/
+static size_t LZ4F_getBlockSize(unsigned blockSizeID)
+{
+ static const size_t blockSizes[4] = { 64 KB, 256 KB, 1 MB, 4 MB };
+
+ if (blockSizeID == 0) blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT;
+ blockSizeID -= 4;
+ if (blockSizeID > 3) return (size_t)-ERROR_maxBlockSize_invalid;
+ return blockSizes[blockSizeID];
+}
+
+
+/* unoptimized version; solves endianess & alignment issues */
+static void LZ4F_writeLE32 (BYTE* dstPtr, U32 value32)
+{
+ dstPtr[0] = (BYTE)value32;
+ dstPtr[1] = (BYTE)(value32 >> 8);
+ dstPtr[2] = (BYTE)(value32 >> 16);
+ dstPtr[3] = (BYTE)(value32 >> 24);
+}
+
+static U32 LZ4F_readLE32 (const BYTE* srcPtr)
+{
+ U32 value32 = srcPtr[0];
+ value32 += (srcPtr[1]<<8);
+ value32 += (srcPtr[2]<<16);
+ value32 += (srcPtr[3]<<24);
+ return value32;
+}
+
+
+static BYTE LZ4F_headerChecksum (const BYTE* header, size_t length)
+{
+ U32 xxh = XXH32(header, (U32)length, 0);
+ return (BYTE)(xxh >> 8);
+}
+
+
+/**************************************
+ Simple compression functions
+**************************************/
+size_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr)
+{
+ LZ4F_preferences_t prefs = { 0 };
+ size_t headerSize;
+ size_t streamSize;
+
+ if (preferencesPtr!=NULL) prefs = *preferencesPtr;
+ prefs.autoFlush = 1;
+
+ headerSize = 7; /* basic header size (no option) including magic number */
+ streamSize = LZ4F_compressBound(srcSize, &prefs);
+
+ return headerSize + streamSize;
+}
+
+
+/* LZ4F_compressFrame()
+ * Compress an entire srcBuffer into a valid LZ4 frame, as defined by specification v1.4.1, in a single step.
+ * The most important rule is that dstBuffer MUST be large enough (dstMaxSize) to ensure compression completion even in worst case.
+ * You can get the minimum value of dstMaxSize by using LZ4F_compressFrameBound()
+ * If this condition is not respected, LZ4F_compressFrame() will fail (result is an errorCode)
+ * The LZ4F_preferences_t structure is optional : you can provide NULL as argument. All preferences will be set to default.
+ * The result of the function is the number of bytes written into dstBuffer.
+ * The function outputs an error code if it fails (can be tested using LZ4F_isError())
+ */
+size_t LZ4F_compressFrame(void* dstBuffer, size_t dstMaxSize, const void* srcBuffer, size_t srcSize, const LZ4F_preferences_t* preferencesPtr)
+{
+ LZ4F_cctx_internal_t cctxI = { 0 }; /* works because no allocation */
+ LZ4F_preferences_t prefs = { 0 };
+ LZ4F_compressOptions_t options = { 0 };
+ LZ4F_errorCode_t errorCode;
+ BYTE* const dstStart = (BYTE*) dstBuffer;
+ BYTE* dstPtr = dstStart;
+ BYTE* const dstEnd = dstStart + dstMaxSize;
+
+
+ cctxI.version = LZ4F_VERSION;
+ cctxI.maxBufferSize = 5 MB; /* mess with real buffer size to prevent allocation; works because autoflush==1 & stableSrc==1 */
+
+ if (preferencesPtr!=NULL) prefs = *preferencesPtr;
+ {
+ blockSizeID_t proposedBSID = max64KB;
+ size_t maxBlockSize = 64 KB;
+ while (prefs.frameInfo.blockSizeID > proposedBSID)
+ {
+ if (srcSize <= maxBlockSize)
+ {
+ prefs.frameInfo.blockSizeID = proposedBSID;
+ break;
+ }
+ proposedBSID++;
+ maxBlockSize <<= 2;
+ }
+ }
+ prefs.autoFlush = 1;
+ if (srcSize <= LZ4F_getBlockSize(prefs.frameInfo.blockSizeID))
+ prefs.frameInfo.blockMode = blockIndependent; /* no need for linked blocks */
+
+ options.stableSrc = 1;
+
+ if (dstMaxSize < LZ4F_compressFrameBound(srcSize, &prefs))
+ return (size_t)-ERROR_dstMaxSize_tooSmall;
+
+ errorCode = LZ4F_compressBegin(&cctxI, dstBuffer, dstMaxSize, &prefs); /* write header */
+ if (LZ4F_isError(errorCode)) return errorCode;
+ dstPtr += errorCode; /* header size */
+
+ dstMaxSize -= errorCode;
+ errorCode = LZ4F_compressUpdate(&cctxI, dstPtr, dstMaxSize, srcBuffer, srcSize, &options);
+ if (LZ4F_isError(errorCode)) return errorCode;
+ dstPtr += errorCode;
+
+ errorCode = LZ4F_compressEnd(&cctxI, dstPtr, dstEnd-dstPtr, &options); /* flush last block, and generate suffix */
+ if (LZ4F_isError(errorCode)) return errorCode;
+ dstPtr += errorCode;
+
+ return (dstPtr - dstStart);
+}
+
+
+/***********************************
+ * Advanced compression functions
+ * *********************************/
+
+/* LZ4F_createCompressionContext() :
+ * The first thing to do is to create a compressionContext object, which will be used in all compression operations.
+ * This is achieved using LZ4F_createCompressionContext(), which takes as argument a version and an LZ4F_preferences_t structure.
+ * The version provided MUST be LZ4F_VERSION. It is intended to track potential version differences between different binaries.
+ * The function will provide a pointer to an allocated LZ4F_compressionContext_t object.
+ * If the result LZ4F_errorCode_t is not OK_NoError, there was an error during context creation.
+ * Object can release its memory using LZ4F_freeCompressionContext();
+ */
+LZ4F_errorCode_t LZ4F_createCompressionContext(LZ4F_compressionContext_t* LZ4F_compressionContextPtr, unsigned version)
+{
+ LZ4F_cctx_internal_t* cctxPtr;
+
+ cctxPtr = ALLOCATOR(sizeof(LZ4F_cctx_internal_t));
+ if (cctxPtr==NULL) return (LZ4F_errorCode_t)-ERROR_allocation_failed;
+
+ cctxPtr->version = version;
+ cctxPtr->cStage = 0; /* Next stage : write header */
+
+ *LZ4F_compressionContextPtr = (LZ4F_compressionContext_t)cctxPtr;
+
+ return OK_NoError;
+}
+
+
+LZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_compressionContext_t LZ4F_compressionContext)
+{
+ LZ4F_cctx_internal_t* cctxPtr = (LZ4F_cctx_internal_t*)LZ4F_compressionContext;
+
+ FREEMEM(cctxPtr->tmpBuff);
+ FREEMEM(LZ4F_compressionContext);
+
+ return OK_NoError;
+}
+
+
+/* LZ4F_compressBegin() :
+ * will write the frame header into dstBuffer.
+ * dstBuffer must be large enough to accommodate a header (dstMaxSize). Maximum header size is LZ4F_MAXHEADERFRAME_SIZE bytes.
+ * The result of the function is the number of bytes written into dstBuffer for the header
+ * or an error code (can be tested using LZ4F_isError())
+ */
+size_t LZ4F_compressBegin(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const LZ4F_preferences_t* preferencesPtr)
+{
+ LZ4F_preferences_t prefNull = { 0 };
+ LZ4F_cctx_internal_t* cctxPtr = (LZ4F_cctx_internal_t*)compressionContext;
+ BYTE* const dstStart = (BYTE*)dstBuffer;
+ BYTE* dstPtr = dstStart;
+ BYTE* headerStart;
+ size_t requiredBuffSize;
+
+ if (dstMaxSize < LZ4F_MAXHEADERFRAME_SIZE) return (size_t)-ERROR_dstMaxSize_tooSmall;
+ if (cctxPtr->cStage != 0) return (size_t)-ERROR_GENERIC;
+ if (preferencesPtr == NULL) preferencesPtr = &prefNull;
+
+ /* Buffer Management */
+ cctxPtr->prefs = *preferencesPtr;
+ if (cctxPtr->prefs.frameInfo.blockSizeID == 0) cctxPtr->prefs.frameInfo.blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT;
+ cctxPtr->maxBlockSize = LZ4F_getBlockSize(cctxPtr->prefs.frameInfo.blockSizeID);
+
+ requiredBuffSize = cctxPtr->maxBlockSize + ((cctxPtr->prefs.frameInfo.blockMode == blockLinked) * 128 KB);
+ if (preferencesPtr->autoFlush)
+ requiredBuffSize = (cctxPtr->prefs.frameInfo.blockMode == blockLinked) * 64 KB; /* just needs dict */
+
+ if (cctxPtr->maxBufferSize < requiredBuffSize)
+ {
+ cctxPtr->maxBufferSize = requiredBuffSize;
+ FREEMEM(cctxPtr->tmpBuff);
+ cctxPtr->tmpBuff = ALLOCATOR(requiredBuffSize);
+ if (cctxPtr->tmpBuff == NULL) return (size_t)-ERROR_allocation_failed;
+ }
+ cctxPtr->tmpIn = cctxPtr->tmpBuff;
+ cctxPtr->tmpInSize = 0;
+ XXH32_resetState(&(cctxPtr->xxh), 0);
+ LZ4_resetStream(&(cctxPtr->lz4ctx));
+
+ /* Magic Number */
+ LZ4F_writeLE32(dstPtr, LZ4F_MAGICNUMBER);
+ dstPtr += 4;
+ headerStart = dstPtr;
+
+ /* FLG Byte */
+ //cctxPtr->prefs.frameInfo.blockMode = 1; // <============ debug
+ *dstPtr++ = ((1 & _2BITS) << 6) /* Version('01') */
+ + ((cctxPtr->prefs.frameInfo.blockMode & _1BIT ) << 5) /* Block mode */
+ + (char)((cctxPtr->prefs.frameInfo.contentChecksumFlag & _1BIT ) << 2); /* Stream checksum */
+ /* BD Byte */
+ *dstPtr++ = (char)((cctxPtr->prefs.frameInfo.blockSizeID & _3BITS) << 4);
+ /* CRC Byte */
+ *dstPtr++ = LZ4F_headerChecksum(headerStart, 2);
+
+ cctxPtr->cStage = 1; /* header written, wait for data block */
+
+ return (dstPtr - dstStart);
+}
+
+
+/* LZ4F_compressBound() : gives the size of Dst buffer given a srcSize to handle worst case situations.
+ * The LZ4F_frameInfo_t structure is optional :
+ * you can provide NULL as argument, all preferences will then be set to default.
+ * */
+size_t LZ4F_compressBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr)
+{
+ LZ4F_frameInfo_t* frameInfoPtr = (LZ4F_frameInfo_t*)preferencesPtr; /* works because prefs starts with frameInfo */
+ blockSizeID_t bid = (frameInfoPtr==NULL) ? LZ4F_BLOCKSIZEID_DEFAULT : frameInfoPtr->blockSizeID;
+ size_t blockSize = LZ4F_getBlockSize(bid);
+ unsigned nbBlocks = (unsigned)(srcSize / blockSize) + 1;
+ size_t lastBlockSize = preferencesPtr->autoFlush ? srcSize % blockSize : blockSize;
+ size_t blockInfo = 4; /* default, without block CRC option */
+ size_t frameEnd = 4 + (frameInfoPtr->contentChecksumFlag*4);
+ size_t result = (blockInfo * nbBlocks) + (blockSize * (nbBlocks-1)) + lastBlockSize + frameEnd;
+
+ return result;
+}
+
+
+typedef int (*compressFunc_t)(void*, const char*, char*, int, int);
+
+static size_t LZ4F_compressBlock(void* dst, const void* src, size_t srcSize, compressFunc_t compress, void* lz4ctx)
+{
+ /* compress one block */
+ BYTE* cSizePtr = (BYTE*)dst;
+ U32 cSize;
+ cSize = (U32)compress(lz4ctx, (const char*)src, (char*)(cSizePtr+4), (int)(srcSize), (int)(srcSize-1));
+ LZ4F_writeLE32(cSizePtr, cSize);
+ if (cSize == 0) /* compression failed */
+ {
+ cSize = (U32)srcSize;
+ LZ4F_writeLE32(cSizePtr, cSize + LZ4F_BLOCKUNCOMPRESSED_FLAG);
+ memcpy(cSizePtr+4, src, srcSize);
+ }
+ return cSize + 4;
+}
+
+
+typedef enum { notDone, fromTmpBuffer, fromSrcBuffer } LZ4F_lastBlockStatus;
+
+/* LZ4F_compressUpdate()
+ * LZ4F_compressUpdate() can be called repetitively to compress as much data as necessary.
+ * The most important rule is that dstBuffer MUST be large enough (dstMaxSize) to ensure compression completion even in worst case.
+ * If this condition is not respected, LZ4F_compress() will fail (result is an errorCode)
+ * You can get the minimum value of dstMaxSize by using LZ4F_compressBound()
+ * The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.
+ * The result of the function is the number of bytes written into dstBuffer : it can be zero, meaning input data was just buffered.
+ * The function outputs an error code if it fails (can be tested using LZ4F_isError())
+ */
+size_t LZ4F_compressUpdate(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const void* srcBuffer, size_t srcSize, const LZ4F_compressOptions_t* compressOptionsPtr)
+{
+ LZ4F_compressOptions_t cOptionsNull = { 0 };
+ LZ4F_cctx_internal_t* cctxPtr = (LZ4F_cctx_internal_t*)compressionContext;
+ size_t blockSize = cctxPtr->maxBlockSize;
+ const BYTE* srcPtr = (const BYTE*)srcBuffer;
+ const BYTE* const srcEnd = srcPtr + srcSize;
+ BYTE* const dstStart = (BYTE*)dstBuffer;
+ BYTE* dstPtr = dstStart;
+ LZ4F_lastBlockStatus lastBlockCompressed = notDone;
+ compressFunc_t compress;
+
+
+ if (cctxPtr->cStage != 1) return (size_t)-ERROR_GENERIC;
+ if (dstMaxSize < LZ4F_compressBound(srcSize, &(cctxPtr->prefs))) return (size_t)-ERROR_dstMaxSize_tooSmall;
+ if (compressOptionsPtr == NULL) compressOptionsPtr = &cOptionsNull;
+
+ /* select compression function */
+ compress = (cctxPtr->prefs.frameInfo.blockMode == blockLinked) ?
+ (int(*)(void*,const char*,char*,int,int))LZ4_compress_limitedOutput_continue :
+ LZ4_compress_limitedOutput_withState;
+
+ /* complete tmp buffer */
+ if (cctxPtr->tmpInSize > 0) /* some data already within tmp buffer */
+ {
+ size_t sizeToCopy = blockSize - cctxPtr->tmpInSize;
+ if (sizeToCopy > srcSize)
+ {
+ /* add src to tmpIn buffer */
+ memcpy(cctxPtr->tmpIn + cctxPtr->tmpInSize, srcBuffer, srcSize);
+ srcPtr = srcEnd;
+ cctxPtr->tmpInSize += srcSize;
+ /* still needs some CRC */
+ }
+ else
+ {
+ /* complete tmpIn block and then compress it */
+ lastBlockCompressed = fromTmpBuffer;
+ memcpy(cctxPtr->tmpIn + cctxPtr->tmpInSize, srcBuffer, sizeToCopy);
+ srcPtr += sizeToCopy;
+
+ dstPtr += LZ4F_compressBlock(dstPtr, cctxPtr->tmpIn, blockSize, compress, &(cctxPtr->lz4ctx));
+
+ if (cctxPtr->prefs.frameInfo.blockMode==blockLinked) cctxPtr->tmpIn += blockSize;
+ cctxPtr->tmpInSize = 0;
+ }
+ }
+
+ while ((size_t)(srcEnd - srcPtr) >= blockSize)
+ {
+ /* compress full block */
+ lastBlockCompressed = fromSrcBuffer;
+ dstPtr += LZ4F_compressBlock(dstPtr, srcPtr, blockSize, compress, &(cctxPtr->lz4ctx));
+ srcPtr += blockSize;
+ }
+
+ if ((cctxPtr->prefs.autoFlush) && (srcPtr < srcEnd))
+ {
+ /* compress remaining input < blockSize */
+ lastBlockCompressed = fromSrcBuffer;
+ dstPtr += LZ4F_compressBlock(dstPtr, srcPtr, srcEnd - srcPtr, compress, &(cctxPtr->lz4ctx));
+ srcPtr = srcEnd;
+ }
+
+ /* preserve dictionary if necessary */
+ if ((cctxPtr->prefs.frameInfo.blockMode==blockLinked) && (lastBlockCompressed==fromSrcBuffer))
+ {
+ if (compressOptionsPtr->stableSrc)
+ {
+ cctxPtr->tmpIn = cctxPtr->tmpBuff;
+ }
+ else
+ {
+ int realDictSize;
+ realDictSize = LZ4_saveDict (&(cctxPtr->lz4ctx), (char*)(cctxPtr->tmpBuff), 64 KB);
+ if (realDictSize==0) return (size_t)-ERROR_GENERIC;
+ cctxPtr->tmpIn = cctxPtr->tmpBuff + realDictSize;
+ }
+ }
+
+ /* keep tmpIn within limits */
+ if ((cctxPtr->tmpIn + blockSize) > (cctxPtr->tmpBuff + cctxPtr->maxBufferSize)) /* necessarily blockLinked && lastBlockCompressed==fromTmpBuffer */
+ {
+ LZ4_saveDict (&(cctxPtr->lz4ctx), (char*)(cctxPtr->tmpBuff), 64 KB);
+ cctxPtr->tmpIn = cctxPtr->tmpBuff + 64 KB;
+ }
+
+ /* some input data left, necessarily < blockSize */
+ if (srcPtr < srcEnd)
+ {
+ /* fill tmp buffer */
+ size_t sizeToCopy = srcEnd - srcPtr;
+ memcpy(cctxPtr->tmpIn, srcPtr, sizeToCopy);
+ cctxPtr->tmpInSize = sizeToCopy;
+ }
+
+ if (cctxPtr->prefs.frameInfo.contentChecksumFlag == contentChecksumEnabled)
+ XXH32_update(&(cctxPtr->xxh), srcBuffer, (unsigned)srcSize);
+
+ return dstPtr - dstStart;
+}
+
+
+/* LZ4F_flush()
+ * Should you need to create compressed data immediately, without waiting for a block to be filled,
+ * you can call LZ4_flush(), which will immediately compress any remaining data stored within compressionContext.
+ * The result of the function is the number of bytes written into dstBuffer
+ * (it can be zero, this means there was no data left within compressionContext)
+ * The function outputs an error code if it fails (can be tested using LZ4F_isError())
+ * The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.
+ */
+size_t LZ4F_flush(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const LZ4F_compressOptions_t* compressOptionsPtr)
+{
+ LZ4F_compressOptions_t cOptionsNull = { 0 };
+ LZ4F_cctx_internal_t* cctxPtr = (LZ4F_cctx_internal_t*)compressionContext;
+ BYTE* const dstStart = (BYTE*)dstBuffer;
+ BYTE* dstPtr = dstStart;
+ int (*compress)(void*, const char*, char*, int, int);
+
+
+ if (cctxPtr->tmpInSize == 0) return 0; /* nothing to flush */
+ if (cctxPtr->cStage != 1) return (size_t)-ERROR_GENERIC;
+ if (dstMaxSize < (cctxPtr->tmpInSize + 16)) return (size_t)-ERROR_dstMaxSize_tooSmall;
+ if (compressOptionsPtr == NULL) compressOptionsPtr = &cOptionsNull;
+ (void)compressOptionsPtr; /* not yet useful */
+
+ /* select compression function */
+ compress = (cctxPtr->prefs.frameInfo.blockMode == blockLinked) ?
+ (int(*)(void*,const char*,char*,int,int))LZ4_compress_limitedOutput_continue :
+ LZ4_compress_limitedOutput_withState;
+
+ /* compress tmp buffer */
+ dstPtr += LZ4F_compressBlock(dstPtr, cctxPtr->tmpIn, cctxPtr->tmpInSize, compress, &(cctxPtr->lz4ctx));
+ if (cctxPtr->prefs.frameInfo.blockMode==blockLinked) cctxPtr->tmpIn += cctxPtr->tmpInSize;
+ cctxPtr->tmpInSize = 0;
+
+ /* keep tmpIn within limits */
+ if ((cctxPtr->tmpIn + cctxPtr->maxBlockSize) > (cctxPtr->tmpBuff + cctxPtr->maxBufferSize)) /* necessarily blockLinked */
+ {
+ LZ4_saveDict (&(cctxPtr->lz4ctx), (char*)(cctxPtr->tmpBuff), 64 KB);
+ cctxPtr->tmpIn = cctxPtr->tmpBuff + 64 KB;
+ }
+
+ return dstPtr - dstStart;
+}
+
+
+/* LZ4F_compressEnd()
+ * When you want to properly finish the compressed frame, just call LZ4F_compressEnd().
+ * It will flush whatever data remained within compressionContext (like LZ4_flush())
+ * but also properly finalize the frame, with an endMark and a checksum.
+ * The result of the function is the number of bytes written into dstBuffer (necessarily >= 4 (endMark size))
+ * The function outputs an error code if it fails (can be tested using LZ4F_isError())
+ * The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.
+ * compressionContext can then be used again, starting with LZ4F_compressBegin(). The preferences will remain the same.
+ */
+size_t LZ4F_compressEnd(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const LZ4F_compressOptions_t* compressOptionsPtr)
+{
+ LZ4F_cctx_internal_t* cctxPtr = (LZ4F_cctx_internal_t*)compressionContext;
+ BYTE* const dstStart = (BYTE*)dstBuffer;
+ BYTE* dstPtr = dstStart;
+ size_t errorCode;
+
+ errorCode = LZ4F_flush(compressionContext, dstBuffer, dstMaxSize, compressOptionsPtr);
+ if (LZ4F_isError(errorCode)) return errorCode;
+ dstPtr += errorCode;
+
+ LZ4F_writeLE32(dstPtr, 0);
+ dstPtr+=4; /* endMark */
+
+ if (cctxPtr->prefs.frameInfo.contentChecksumFlag == contentChecksumEnabled)
+ {
+ U32 xxh = XXH32_intermediateDigest(&(cctxPtr->xxh));
+ LZ4F_writeLE32(dstPtr, xxh);
+ dstPtr+=4; /* content Checksum */
+ }
+
+ cctxPtr->cStage = 0; /* state is now re-usable (with identical preferences) */
+
+ return dstPtr - dstStart;
+}
+
+
+/***********************************
+ * Decompression functions
+ * *********************************/
+
+/* Resource management */
+
+/* LZ4F_createDecompressionContext() :
+ * The first thing to do is to create a decompressionContext object, which will be used in all decompression operations.
+ * This is achieved using LZ4F_createDecompressionContext().
+ * The function will provide a pointer to a fully allocated and initialized LZ4F_decompressionContext object.
+ * If the result LZ4F_errorCode_t is not zero, there was an error during context creation.
+ * Object can release its memory using LZ4F_freeDecompressionContext();
+ */
+LZ4F_errorCode_t LZ4F_createDecompressionContext(LZ4F_compressionContext_t* LZ4F_decompressionContextPtr, unsigned versionNumber)
+{
+ LZ4F_dctx_internal_t* dctxPtr;
+
+ dctxPtr = ALLOCATOR(sizeof(LZ4F_dctx_internal_t));
+ if (dctxPtr==NULL) return (LZ4F_errorCode_t)-ERROR_GENERIC;
+
+ dctxPtr->version = versionNumber;
+ *LZ4F_decompressionContextPtr = (LZ4F_compressionContext_t)dctxPtr;
+ return OK_NoError;
+}
+
+LZ4F_errorCode_t LZ4F_freeDecompressionContext(LZ4F_compressionContext_t LZ4F_decompressionContext)
+{
+ LZ4F_dctx_internal_t* dctxPtr = (LZ4F_dctx_internal_t*)LZ4F_decompressionContext;
+ FREEMEM(dctxPtr->tmpIn);
+ FREEMEM(dctxPtr->tmpOutBuffer);
+ FREEMEM(dctxPtr);
+ return OK_NoError;
+}
+
+
+/* Decompression */
+
+static size_t LZ4F_decodeHeader(LZ4F_dctx_internal_t* dctxPtr, const BYTE* srcPtr, size_t srcSize)
+{
+ BYTE FLG, BD, HC;
+ unsigned version, blockMode, blockChecksumFlag, contentSizeFlag, contentChecksumFlag, dictFlag, blockSizeID;
+ size_t bufferNeeded;
+
+ /* need to decode header to get frameInfo */
+ if (srcSize < 7) return (size_t)-ERROR_GENERIC; /* minimal header size */
+
+ /* control magic number */
+ if (LZ4F_readLE32(srcPtr) != LZ4F_MAGICNUMBER) return (size_t)-ERROR_GENERIC;
+ srcPtr += 4;
+
+ /* Flags */
+ FLG = srcPtr[0];
+ version = (FLG>>6)&_2BITS;
+ blockMode = (FLG>>5) & _1BIT;
+ blockChecksumFlag = (FLG>>4) & _1BIT;
+ contentSizeFlag = (FLG>>3) & _1BIT;
+ contentChecksumFlag = (FLG>>2) & _1BIT;
+ dictFlag = (FLG>>0) & _1BIT;
+ BD = srcPtr[1];
+ blockSizeID = (BD>>4) & _3BITS;
+
+ /* check */
+ HC = LZ4F_headerChecksum(srcPtr, 2);
+ if (HC != srcPtr[2]) return (size_t)-ERROR_GENERIC; /* Bad header checksum error */
+
+ /* validate */
+ if (version != 1) return (size_t)-ERROR_GENERIC; /* Version Number, only supported value */
+ if (blockChecksumFlag != 0) return (size_t)-ERROR_GENERIC; /* Only supported value for the time being */
+ if (contentSizeFlag != 0) return (size_t)-ERROR_GENERIC; /* Only supported value for the time being */
+ if (((FLG>>1)&_1BIT) != 0) return (size_t)-ERROR_GENERIC; /* Reserved bit */
+ if (dictFlag != 0) return (size_t)-ERROR_GENERIC; /* Only supported value for the time being */
+ if (((BD>>7)&_1BIT) != 0) return (size_t)-ERROR_GENERIC; /* Reserved bit */
+ if (blockSizeID < 4) return (size_t)-ERROR_GENERIC; /* Only supported values for the time being */
+ if (((BD>>0)&_4BITS) != 0) return (size_t)-ERROR_GENERIC; /* Reserved bits */
+
+ /* save */
+ dctxPtr->frameInfo.blockMode = blockMode;
+ dctxPtr->frameInfo.contentChecksumFlag = contentChecksumFlag;
+ dctxPtr->frameInfo.blockSizeID = blockSizeID;
+ dctxPtr->maxBlockSize = LZ4F_getBlockSize(blockSizeID);
+
+ /* init */
+ if (contentChecksumFlag) XXH32_resetState(&(dctxPtr->xxh), 0);
+
+ /* alloc */
+ bufferNeeded = dctxPtr->maxBlockSize + ((dctxPtr->frameInfo.blockMode==blockLinked) * 128 KB);
+ if (bufferNeeded > dctxPtr->maxBufferSize) /* tmp buffers too small */
+ {
+ FREEMEM(dctxPtr->tmpIn);
+ FREEMEM(dctxPtr->tmpOutBuffer);
+ dctxPtr->maxBufferSize = bufferNeeded;
+ dctxPtr->tmpIn = ALLOCATOR(dctxPtr->maxBlockSize);
+ if (dctxPtr->tmpIn == NULL) return (size_t)-ERROR_GENERIC;
+ dctxPtr->tmpOutBuffer= ALLOCATOR(dctxPtr->maxBufferSize);
+ if (dctxPtr->tmpOutBuffer== NULL) return (size_t)-ERROR_GENERIC;
+ }
+ dctxPtr->tmpInSize = 0;
+ dctxPtr->tmpInTarget = 0;
+ dctxPtr->dict = dctxPtr->tmpOutBuffer;
+ dctxPtr->dictSize = 0;
+ dctxPtr->tmpOut = dctxPtr->tmpOutBuffer;
+ dctxPtr->tmpOutStart = 0;
+ dctxPtr->tmpOutSize = 0;
+
+ return 7;
+}
+
+
+typedef enum { dstage_getHeader=0, dstage_storeHeader, dstage_decodeHeader,
+ dstage_getCBlockSize, dstage_storeCBlockSize, dstage_decodeCBlockSize,
+ dstage_copyDirect,
+ dstage_getCBlock, dstage_storeCBlock, dstage_decodeCBlock,
+ dstage_decodeCBlock_intoDst, dstage_decodeCBlock_intoTmp, dstage_flushOut,
+ dstage_getSuffix, dstage_storeSuffix, dstage_checkSuffix
+ } dStage_t;
+
+
+/* LZ4F_getFrameInfo()
+ * This function decodes frame header information, such as blockSize.
+ * It is optional : you could start by calling directly LZ4F_decompress() instead.
+ * The objective is to extract header information without starting decompression, typically for allocation purposes.
+ * LZ4F_getFrameInfo() can also be used *after* starting decompression, on a valid LZ4F_decompressionContext_t.
+ * The number of bytes read from srcBuffer will be provided within *srcSizePtr (necessarily <= original value).
+ * You are expected to resume decompression from where it stopped (srcBuffer + *srcSizePtr)
+ * The function result is an hint of the better srcSize to use for next call to LZ4F_decompress,
+ * or an error code which can be tested using LZ4F_isError().
+ */
+LZ4F_errorCode_t LZ4F_getFrameInfo(LZ4F_decompressionContext_t decompressionContext, LZ4F_frameInfo_t* frameInfoPtr, const void* srcBuffer, size_t* srcSizePtr)
+{
+ LZ4F_dctx_internal_t* dctxPtr = (LZ4F_dctx_internal_t*)decompressionContext;
+
+ if (dctxPtr->dStage == dstage_getHeader)
+ {
+ LZ4F_errorCode_t errorCode = LZ4F_decodeHeader(dctxPtr, srcBuffer, *srcSizePtr);
+ if (LZ4F_isError(errorCode)) return errorCode;
+ *srcSizePtr = errorCode;
+ *frameInfoPtr = dctxPtr->frameInfo;
+ dctxPtr->srcExpect = NULL;
+ dctxPtr->dStage = dstage_getCBlockSize;
+ return 4;
+ }
+
+ /* frameInfo already decoded */
+ *srcSizePtr = 0;
+ *frameInfoPtr = dctxPtr->frameInfo;
+ return 0;
+}
+
+
+static int LZ4F_decompress_safe (const char* source, char* dest, int compressedSize, int maxDecompressedSize, const char* dictStart, int dictSize)
+{
+ (void)dictStart;
+ (void)dictSize;
+ return LZ4_decompress_safe (source, dest, compressedSize, maxDecompressedSize);
+}
+
+
+
+static void LZ4F_updateDict(LZ4F_dctx_internal_t* dctxPtr, const BYTE* dstPtr, size_t dstSize, const BYTE* dstPtr0, unsigned withinTmp)
+{
+ if (dctxPtr->dictSize==0)
+ dctxPtr->dict = (BYTE*)dstPtr; /* priority to dictionary continuity */
+
+ if (dctxPtr->dict + dctxPtr->dictSize == dstPtr) /* dictionary continuity */
+ {
+ dctxPtr->dictSize += dstSize;
+ return;
+ }
+
+ if (dstPtr - dstPtr0 + dstSize >= 64 KB) /* dstBuffer large enough to become dictionary */
+ {
+ dctxPtr->dict = (BYTE*)dstPtr0;
+ dctxPtr->dictSize = dstPtr - dstPtr0 + dstSize;
+ return;
+ }
+
+ if ((withinTmp) && (dctxPtr->dict == dctxPtr->tmpOutBuffer))
+ {
+ /* assumption : dctxPtr->dict + dctxPtr->dictSize == dctxPtr->tmpOut + dctxPtr->tmpOutStart */
+ dctxPtr->dictSize += dstSize;
+ return;
+ }
+
+ if (withinTmp) /* copy relevant dict portion in front of tmpOut within tmpOutBuffer */
+ {
+#if 0
+ size_t savedDictSize = dctxPtr->tmpOut - dctxPtr->tmpOutBuffer;
+ memcpy(dctxPtr->tmpOutBuffer, dctxPtr->dict + dctxPtr->dictSize - dctxPtr->tmpOutStart- savedDictSize, savedDictSize);
+ dctxPtr->dict = dctxPtr->tmpOutBuffer;
+ dctxPtr->dictSize = savedDictSize + dctxPtr->tmpOutStart + dstSize;
+ return;
+
+#else
+
+ size_t preserveSize = dctxPtr->tmpOut - dctxPtr->tmpOutBuffer;
+ size_t copySize = 64 KB - dctxPtr->tmpOutSize;
+ BYTE* oldDictEnd = dctxPtr->dict + dctxPtr->dictSize - dctxPtr->tmpOutStart;
+ if (dctxPtr->tmpOutSize > 64 KB) copySize = 0;
+ if (copySize > preserveSize) copySize = preserveSize;
+
+ memcpy(dctxPtr->tmpOutBuffer + preserveSize - copySize, oldDictEnd - copySize, copySize);
+
+ dctxPtr->dict = dctxPtr->tmpOutBuffer;
+ dctxPtr->dictSize = preserveSize + dctxPtr->tmpOutStart + dstSize;
+ return;
+#endif
+ }
+
+ if (dctxPtr->dict == dctxPtr->tmpOutBuffer) /* copy dst into tmp to complete dict */
+ {
+ if (dctxPtr->dictSize + dstSize > dctxPtr->maxBufferSize) /* tmp buffer not large enough */
+ {
+ size_t preserveSize = 64 KB - dstSize; /* note : dstSize < 64 KB */
+ memcpy(dctxPtr->dict, dctxPtr->dict + dctxPtr->dictSize - preserveSize, preserveSize);
+ dctxPtr->dictSize = preserveSize;
+ }
+ memcpy(dctxPtr->dict + dctxPtr->dictSize, dstPtr, dstSize);
+ dctxPtr->dictSize += dstSize;
+ return;
+ }
+
+ /* join dict & dest into tmp */
+ {
+ size_t preserveSize = 64 KB - dstSize; /* note : dstSize < 64 KB */
+ if (preserveSize > dctxPtr->dictSize) preserveSize = dctxPtr->dictSize;
+ memcpy(dctxPtr->tmpOutBuffer, dctxPtr->dict + dctxPtr->dictSize - preserveSize, preserveSize);
+ memcpy(dctxPtr->tmpOutBuffer + preserveSize, dstPtr, dstSize);
+ dctxPtr->dict = dctxPtr->tmpOutBuffer;
+ dctxPtr->dictSize = preserveSize + dstSize;
+ }
+}
+
+
+
+/* LZ4F_decompress()
+ * Call this function repetitively to regenerate data compressed within srcBuffer.
+ * The function will attempt to decode *srcSizePtr from srcBuffer, into dstBuffer of maximum size *dstSizePtr.
+ *
+ * The number of bytes regenerated into dstBuffer will be provided within *dstSizePtr (necessarily <= original value).
+ *
+ * The number of bytes effectively read from srcBuffer will be provided within *srcSizePtr (necessarily <= original value).
+ * If the number of bytes read is < number of bytes provided, then the decompression operation is not complete.
+ * You will have to call it again, continuing from where it stopped.
+ *
+ * The function result is an hint of the better srcSize to use for next call to LZ4F_decompress.
+ * Basically, it's the size of the current (or remaining) compressed block + header of next block.
+ * Respecting the hint provides some boost to performance, since it allows less buffer shuffling.
+ * Note that this is just a hint, you can always provide any srcSize you want.
+ * When a frame is fully decoded, the function result will be 0.
+ * If decompression failed, function result is an error code which can be tested using LZ4F_isError().
+ */
+size_t LZ4F_decompress(LZ4F_decompressionContext_t decompressionContext,
+ void* dstBuffer, size_t* dstSizePtr,
+ const void* srcBuffer, size_t* srcSizePtr,
+ const LZ4F_decompressOptions_t* decompressOptionsPtr)
+{
+ LZ4F_dctx_internal_t* dctxPtr = (LZ4F_dctx_internal_t*)decompressionContext;
+ static const LZ4F_decompressOptions_t optionsNull = { 0 };
+ const BYTE* const srcStart = (const BYTE*)srcBuffer;
+ const BYTE* const srcEnd = srcStart + *srcSizePtr;
+ const BYTE* srcPtr = srcStart;
+ BYTE* const dstStart = (BYTE*)dstBuffer;
+ BYTE* const dstEnd = dstStart + *dstSizePtr;
+ BYTE* dstPtr = dstStart;
+ const BYTE* selectedIn=NULL;
+ unsigned doAnotherStage = 1;
+ size_t nextSrcSizeHint = 1;
+
+
+ if (decompressOptionsPtr==NULL) decompressOptionsPtr = &optionsNull;
+ *srcSizePtr = 0;
+ *dstSizePtr = 0;
+
+ /* expect to continue decoding src buffer where it left previously */
+ if (dctxPtr->srcExpect != NULL)
+ {
+ if (srcStart != dctxPtr->srcExpect) return (size_t)-ERROR_GENERIC;
+ }
+
+ /* programmed as a state machine */
+
+ while (doAnotherStage)
+ {
+
+ switch(dctxPtr->dStage)
+ {
+
+ case dstage_getHeader:
+ {
+ if (srcEnd-srcPtr >= 7)
+ {
+ selectedIn = srcPtr;
+ srcPtr += 7;
+ dctxPtr->dStage = dstage_decodeHeader;
+ break;
+ }
+ dctxPtr->tmpInSize = 0;
+ dctxPtr->dStage = dstage_storeHeader;
+ break;
+ }
+
+ case dstage_storeHeader:
+ {
+ size_t sizeToCopy = 7 - dctxPtr->tmpInSize;
+ if (sizeToCopy > (size_t)(srcEnd - srcPtr)) sizeToCopy = srcEnd - srcPtr;
+ memcpy(dctxPtr->header + dctxPtr->tmpInSize, srcPtr, sizeToCopy);
+ dctxPtr->tmpInSize += sizeToCopy;
+ srcPtr += sizeToCopy;
+ if (dctxPtr->tmpInSize < 7)
+ {
+ nextSrcSizeHint = (7 - dctxPtr->tmpInSize) + 4;
+ doAnotherStage = 0; /* no enough src, wait to get some more */
+ break;
+ }
+ selectedIn = dctxPtr->header;
+ dctxPtr->dStage = dstage_decodeHeader;
+ break;
+ }
+
+ case dstage_decodeHeader:
+ {
+ LZ4F_errorCode_t errorCode = LZ4F_decodeHeader(dctxPtr, selectedIn, 7);
+ if (LZ4F_isError(errorCode)) return errorCode;
+ dctxPtr->dStage = dstage_getCBlockSize;
+ break;
+ }
+
+ case dstage_getCBlockSize:
+ {
+ if ((srcEnd - srcPtr) >= 4)
+ {
+ selectedIn = srcPtr;
+ srcPtr += 4;
+ dctxPtr->dStage = dstage_decodeCBlockSize;
+ break;
+ }
+ /* not enough input to read cBlockSize field */
+ dctxPtr->tmpInSize = 0;
+ dctxPtr->dStage = dstage_storeCBlockSize;
+ break;
+ }
+
+ case dstage_storeCBlockSize:
+ {
+ size_t sizeToCopy = 4 - dctxPtr->tmpInSize;
+ if (sizeToCopy > (size_t)(srcEnd - srcPtr)) sizeToCopy = srcEnd - srcPtr;
+ memcpy(dctxPtr->tmpIn + dctxPtr->tmpInSize, srcPtr, sizeToCopy);
+ srcPtr += sizeToCopy;
+ dctxPtr->tmpInSize += sizeToCopy;
+ if (dctxPtr->tmpInSize < 4) /* not enough input to get full cBlockSize; wait for more */
+ {
+ nextSrcSizeHint = 4 - dctxPtr->tmpInSize;
+ doAnotherStage=0;
+ break;
+ }
+ selectedIn = dctxPtr->tmpIn;
+ dctxPtr->dStage = dstage_decodeCBlockSize;
+ break;
+ }
+
+ case dstage_decodeCBlockSize:
+ {
+ size_t nextCBlockSize = LZ4F_readLE32(selectedIn) & 0x7FFFFFFFU;
+ if (nextCBlockSize==0) /* frameEnd signal, no more CBlock */
+ {
+ dctxPtr->dStage = dstage_getSuffix;
+ break;
+ }
+ if (nextCBlockSize > dctxPtr->maxBlockSize) return (size_t)-ERROR_GENERIC; /* invalid cBlockSize */
+ dctxPtr->tmpInTarget = nextCBlockSize;
+ if (LZ4F_readLE32(selectedIn) & LZ4F_BLOCKUNCOMPRESSED_FLAG)
+ {
+ dctxPtr->dStage = dstage_copyDirect;
+ break;
+ }
+ dctxPtr->dStage = dstage_getCBlock;
+ if (dstPtr==dstEnd)
+ {
+ nextSrcSizeHint = nextCBlockSize + 4;
+ doAnotherStage = 0;
+ }
+ break;
+ }
+
+ case dstage_copyDirect: /* uncompressed block */
+ {
+ size_t sizeToCopy = dctxPtr->tmpInTarget;
+ if ((size_t)(srcEnd-srcPtr) < sizeToCopy) sizeToCopy = srcEnd - srcPtr; /* not enough input to read full block */
+ if ((size_t)(dstEnd-dstPtr) < sizeToCopy) sizeToCopy = dstEnd - dstPtr;
+ memcpy(dstPtr, srcPtr, sizeToCopy);
+ if (dctxPtr->frameInfo.contentChecksumFlag) XXH32_update(&(dctxPtr->xxh), srcPtr, (U32)sizeToCopy);
+
+ /* dictionary management */
+ if (dctxPtr->frameInfo.blockMode==blockLinked)
+ LZ4F_updateDict(dctxPtr, dstPtr, sizeToCopy, dstStart, 0);
+
+ srcPtr += sizeToCopy;
+ dstPtr += sizeToCopy;
+ if (sizeToCopy == dctxPtr->tmpInTarget) /* all copied */
+ {
+ dctxPtr->dStage = dstage_getCBlockSize;
+ break;
+ }
+ dctxPtr->tmpInTarget -= sizeToCopy; /* still need to copy more */
+ nextSrcSizeHint = dctxPtr->tmpInTarget + 4;
+ doAnotherStage = 0;
+ break;
+ }
+
+ case dstage_getCBlock: /* entry from dstage_decodeCBlockSize */
+ {
+ if ((size_t)(srcEnd-srcPtr) < dctxPtr->tmpInTarget)
+ {
+ dctxPtr->tmpInSize = 0;
+ dctxPtr->dStage = dstage_storeCBlock;
+ break;
+ }
+ selectedIn = srcPtr;
+ srcPtr += dctxPtr->tmpInTarget;
+ dctxPtr->dStage = dstage_decodeCBlock;
+ break;
+ }
+
+ case dstage_storeCBlock:
+ {
+ size_t sizeToCopy = dctxPtr->tmpInTarget - dctxPtr->tmpInSize;
+ if (sizeToCopy > (size_t)(srcEnd-srcPtr)) sizeToCopy = srcEnd-srcPtr;
+ memcpy(dctxPtr->tmpIn + dctxPtr->tmpInSize, srcPtr, sizeToCopy);
+ dctxPtr->tmpInSize += sizeToCopy;
+ srcPtr += sizeToCopy;
+ if (dctxPtr->tmpInSize < dctxPtr->tmpInTarget) /* need more input */
+ {
+ nextSrcSizeHint = (dctxPtr->tmpInTarget - dctxPtr->tmpInSize) + 4;
+ doAnotherStage=0;
+ break;
+ }
+ selectedIn = dctxPtr->tmpIn;
+ dctxPtr->dStage = dstage_decodeCBlock;
+ break;
+ }
+
+ case dstage_decodeCBlock:
+ {
+ if ((size_t)(dstEnd-dstPtr) < dctxPtr->maxBlockSize) /* not enough place into dst : decode into tmpOut */
+ dctxPtr->dStage = dstage_decodeCBlock_intoTmp;
+ else
+ dctxPtr->dStage = dstage_decodeCBlock_intoDst;
+ break;
+ }
+
+ case dstage_decodeCBlock_intoDst:
+ {
+ int (*decoder)(const char*, char*, int, int, const char*, int);
+ int decodedSize;
+
+ if (dctxPtr->frameInfo.blockMode == blockLinked)
+ decoder = LZ4_decompress_safe_usingDict;
+ else
+ decoder = LZ4F_decompress_safe;
+
+ decodedSize = decoder((const char*)selectedIn, (char*)dstPtr, (int)dctxPtr->tmpInTarget, (int)dctxPtr->maxBlockSize, (const char*)dctxPtr->dict, (int)dctxPtr->dictSize);
+ if (decodedSize < 0) return (size_t)-ERROR_GENERIC; /* decompression failed */
+ if (dctxPtr->frameInfo.contentChecksumFlag) XXH32_update(&(dctxPtr->xxh), dstPtr, decodedSize);
+
+ /* dictionary management */
+ if (dctxPtr->frameInfo.blockMode==blockLinked)
+ LZ4F_updateDict(dctxPtr, dstPtr, decodedSize, dstStart, 0);
+
+ dstPtr += decodedSize;
+ dctxPtr->dStage = dstage_getCBlockSize;
+ break;
+ }
+
+ case dstage_decodeCBlock_intoTmp:
+ {
+ /* not enough place into dst : decode into tmpOut */
+ int (*decoder)(const char*, char*, int, int, const char*, int);
+ int decodedSize;
+
+ if (dctxPtr->frameInfo.blockMode == blockLinked)
+ decoder = LZ4_decompress_safe_usingDict;
+ else
+ decoder = LZ4F_decompress_safe;
+
+ /* ensure enough place for tmpOut */
+ if (dctxPtr->frameInfo.blockMode == blockLinked)
+ {
+ if (dctxPtr->dict == dctxPtr->tmpOutBuffer)
+ {
+ if (dctxPtr->dictSize > 128 KB)
+ {
+ memcpy(dctxPtr->dict, dctxPtr->dict + dctxPtr->dictSize - 64 KB, 64 KB);
+ dctxPtr->dictSize = 64 KB;
+ }
+ dctxPtr->tmpOut = dctxPtr->dict + dctxPtr->dictSize;
+ }
+ else /* dict not within tmp */
+ {
+ size_t reservedDictSpace = dctxPtr->dictSize;
+ if (reservedDictSpace > 64 KB) reservedDictSpace = 64 KB;
+ dctxPtr->tmpOut = dctxPtr->tmpOutBuffer + reservedDictSpace;
+ }
+ }
+
+ /* Decode */
+ decodedSize = decoder((const char*)selectedIn, (char*)dctxPtr->tmpOut, (int)dctxPtr->tmpInTarget, (int)dctxPtr->maxBlockSize, (const char*)dctxPtr->dict, (int)dctxPtr->dictSize);
+ if (decodedSize < 0) return (size_t)-ERROR_decompressionFailed; /* decompression failed */
+ if (dctxPtr->frameInfo.contentChecksumFlag) XXH32_update(&(dctxPtr->xxh), dctxPtr->tmpOut, decodedSize);
+ dctxPtr->tmpOutSize = decodedSize;
+ dctxPtr->tmpOutStart = 0;
+ dctxPtr->dStage = dstage_flushOut;
+ break;
+ }
+
+ case dstage_flushOut: /* flush decoded data from tmpOut to dstBuffer */
+ {
+ size_t sizeToCopy = dctxPtr->tmpOutSize - dctxPtr->tmpOutStart;
+ if (sizeToCopy > (size_t)(dstEnd-dstPtr)) sizeToCopy = dstEnd-dstPtr;
+ memcpy(dstPtr, dctxPtr->tmpOut + dctxPtr->tmpOutStart, sizeToCopy);
+
+ /* dictionary management */
+ if (dctxPtr->frameInfo.blockMode==blockLinked)
+ LZ4F_updateDict(dctxPtr, dstPtr, sizeToCopy, dstStart, 1);
+
+ dctxPtr->tmpOutStart += sizeToCopy;
+ dstPtr += sizeToCopy;
+
+ /* end of flush ? */
+ if (dctxPtr->tmpOutStart == dctxPtr->tmpOutSize)
+ {
+ dctxPtr->dStage = dstage_getCBlockSize;
+ break;
+ }
+ nextSrcSizeHint = 4;
+ doAnotherStage = 0; /* still some data to flush */
+ break;
+ }
+
+ case dstage_getSuffix:
+ {
+ size_t suffixSize = dctxPtr->frameInfo.contentChecksumFlag * 4;
+ if (suffixSize == 0) /* frame completed */
+ {
+ nextSrcSizeHint = 0;
+ dctxPtr->dStage = dstage_getHeader;
+ doAnotherStage = 0;
+ break;
+ }
+ if ((srcEnd - srcPtr) >= 4) /* CRC present */
+ {
+ selectedIn = srcPtr;
+ srcPtr += 4;
+ dctxPtr->dStage = dstage_checkSuffix;
+ break;
+ }
+ dctxPtr->tmpInSize = 0;
+ dctxPtr->dStage = dstage_storeSuffix;
+ break;
+ }
+
+ case dstage_storeSuffix:
+ {
+ size_t sizeToCopy = 4 - dctxPtr->tmpInSize;
+ if (sizeToCopy > (size_t)(srcEnd - srcPtr)) sizeToCopy = srcEnd - srcPtr;
+ memcpy(dctxPtr->tmpIn + dctxPtr->tmpInSize, srcPtr, sizeToCopy);
+ srcPtr += sizeToCopy;
+ dctxPtr->tmpInSize += sizeToCopy;
+ if (dctxPtr->tmpInSize < 4) /* not enough input to read complete suffix */
+ {
+ nextSrcSizeHint = 4 - dctxPtr->tmpInSize;
+ doAnotherStage=0;
+ break;
+ }
+ selectedIn = dctxPtr->tmpIn;
+ dctxPtr->dStage = dstage_checkSuffix;
+ break;
+ }
+
+ case dstage_checkSuffix:
+ {
+ U32 readCRC = LZ4F_readLE32(selectedIn);
+ U32 resultCRC = XXH32_intermediateDigest(&(dctxPtr->xxh));
+ if (readCRC != resultCRC) return (size_t)-ERROR_checksum_invalid;
+ nextSrcSizeHint = 0;
+ dctxPtr->dStage = dstage_getHeader;
+ doAnotherStage = 0;
+ break;
+ }
+ }
+ }
+
+ /* preserve dictionary within tmp if necessary */
+ if ( (dctxPtr->frameInfo.blockMode==blockLinked)
+ &&(dctxPtr->dict != dctxPtr->tmpOutBuffer)
+ &&(!decompressOptionsPtr->stableDst)
+ &&((unsigned)(dctxPtr->dStage-1) < (unsigned)(dstage_getSuffix-1))
+ )
+ {
+ if (dctxPtr->dStage == dstage_flushOut)
+ {
+ size_t preserveSize = dctxPtr->tmpOut - dctxPtr->tmpOutBuffer;
+ size_t copySize = 64 KB - dctxPtr->tmpOutSize;
+ BYTE* oldDictEnd = dctxPtr->dict + dctxPtr->dictSize - dctxPtr->tmpOutStart;
+ if (dctxPtr->tmpOutSize > 64 KB) copySize = 0;
+ if (copySize > preserveSize) copySize = preserveSize;
+
+ memcpy(dctxPtr->tmpOutBuffer + preserveSize - copySize, oldDictEnd - copySize, copySize);
+
+ dctxPtr->dict = dctxPtr->tmpOutBuffer;
+ dctxPtr->dictSize = preserveSize + dctxPtr->tmpOutStart;
+ }
+ else
+ {
+ size_t newDictSize = dctxPtr->dictSize;
+ BYTE* oldDictEnd = dctxPtr->dict + dctxPtr->dictSize;
+ if ((newDictSize) > 64 KB) newDictSize = 64 KB;
+
+ memcpy(dctxPtr->tmpOutBuffer, oldDictEnd - newDictSize, newDictSize);
+
+ dctxPtr->dict = dctxPtr->tmpOutBuffer;
+ dctxPtr->dictSize = newDictSize;
+ dctxPtr->tmpOut = dctxPtr->tmpOutBuffer + newDictSize;
+ }
+ }
+
+ if (srcPtr<srcEnd) /* function must be called again with following source data */
+ dctxPtr->srcExpect = srcPtr;
+ else
+ dctxPtr->srcExpect = NULL;
+ *srcSizePtr = (srcPtr - srcStart);
+ *dstSizePtr = (dstPtr - dstStart);
+ return nextSrcSizeHint;
+}
diff --git a/lz4frame.h b/lz4frame.h
new file mode 100644
index 0000000..d24a824
--- /dev/null
+++ b/lz4frame.h
@@ -0,0 +1,261 @@
+/*
+ LZ4 auto-framing library
+ Header File
+ Copyright (C) 2011-2014, Yann Collet.
+ BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following disclaimer
+ in the documentation and/or other materials provided with the
+ distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ You can contact the author at :
+ - LZ4 source repository : http://code.google.com/p/lz4/
+ - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
+*/
+
+/* LZ4F is a stand-alone API to create LZ4-compressed frames
+ * fully conformant to specification v1.4.1.
+ * All related operations, including memory management, are handled by the library.
+ * You don't need lz4.h when using lz4frame.h.
+ * */
+
+#pragma once
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+/****************************************
+ Note : experimental API.
+ Not yet integrated within lz4 library.
+****************************************/
+
+/**************************************
+ Includes
+**************************************/
+#include <stddef.h> /* size_t */
+
+
+/**************************************
+ Error management
+**************************************/
+typedef size_t LZ4F_errorCode_t;
+#define LZ4F_LIST_ERRORS(ITEM) \
+ ITEM(OK_NoError) ITEM(ERROR_GENERIC) \
+ ITEM(ERROR_maxBlockSize_invalid) ITEM(ERROR_blockMode_invalid) ITEM(ERROR_contentChecksumFlag_invalid) \
+ ITEM(ERROR_compressionLevel_invalid) \
+ ITEM(ERROR_allocation_failed) \
+ ITEM(ERROR_srcSize_tooLarge) ITEM(ERROR_dstMaxSize_tooSmall) \
+ ITEM(ERROR_decompressionFailed) \
+ ITEM(ERROR_checksum_invalid) \
+ ITEM(ERROR_maxCode)
+
+#define LZ4F_GENERATE_ENUM(ENUM) ENUM,
+typedef enum { LZ4F_LIST_ERRORS(LZ4F_GENERATE_ENUM) } LZ4F_errorCodes; /* enum is exposed, to let programmer detect & handle specific errors */
+
+int LZ4F_isError(LZ4F_errorCode_t code); /* Basically : code > -ERROR_maxCode */
+const char* LZ4F_getErrorName(LZ4F_errorCode_t code); /* return enum as string */
+
+
+/**************************************
+ Framing compression functions
+**************************************/
+
+typedef enum { LZ4F_default=0, max64KB=4, max256KB=5, max1MB=6, max4MB=7} blockSizeID_t;
+typedef enum { blockLinked=0, blockIndependent} blockMode_t;
+typedef enum { noContentChecksum=0, contentChecksumEnabled } contentChecksum_t;
+
+typedef struct {
+ blockSizeID_t blockSizeID; /* max64KB, max256KB, max1MB, max4MB ; 0 == default */
+ blockMode_t blockMode; /* blockLinked, blockIndependent ; 0 == default */
+ contentChecksum_t contentChecksumFlag; /* noContentChecksum, contentChecksumEnabled ; 0 == default */
+ unsigned reserved[5];
+} LZ4F_frameInfo_t;
+
+typedef struct {
+ LZ4F_frameInfo_t frameInfo;
+ unsigned compressionLevel; /* from 0 to 16 */
+ unsigned autoFlush; /* 1 == always flush; reduce need for tmp buffer */
+ unsigned reserved[4];
+} LZ4F_preferences_t;
+
+
+
+/***********************************
+ * Simple compression function
+ * *********************************/
+size_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr);
+
+size_t LZ4F_compressFrame(void* dstBuffer, size_t dstMaxSize, const void* srcBuffer, size_t srcSize, const LZ4F_preferences_t* preferencesPtr);
+/* LZ4F_compressFrame()
+ * Compress an entire srcBuffer into a valid LZ4 frame, as defined by specification v1.4.1, in a single step.
+ * The most important rule is that dstBuffer MUST be large enough (dstMaxSize) to ensure compression completion even in worst case.
+ * You can get the minimum value of dstMaxSize by using LZ4F_compressFrameBound()
+ * If this condition is not respected, LZ4F_compressFrame() will fail (result is an errorCode)
+ * The LZ4F_preferences_t structure is optional : you can provide NULL as argument. All preferences will be set to default.
+ * The result of the function is the number of bytes written into dstBuffer.
+ * The function outputs an error code if it fails (can be tested using LZ4F_isError())
+ */
+
+
+
+/**********************************
+ * Advanced compression functions
+ * *********************************/
+
+typedef void* LZ4F_compressionContext_t;
+
+typedef struct {
+ unsigned stableSrc; /* 1 == src content will remain available on future calls to LZ4F_compress(); avoid saving src content within tmp buffer as future dictionary */
+ unsigned reserved[3];
+} LZ4F_compressOptions_t;
+
+/* Resource Management */
+
+#define LZ4F_VERSION 100
+LZ4F_errorCode_t LZ4F_createCompressionContext(LZ4F_compressionContext_t* LZ4F_compressionContextPtr, unsigned version);
+LZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_compressionContext_t LZ4F_compressionContext);
+/* LZ4F_createCompressionContext() :
+ * The first thing to do is to create a compressionContext object, which will be used in all compression operations.
+ * This is achieved using LZ4F_createCompressionContext(), which takes as argument a version and an LZ4F_preferences_t structure.
+ * The version provided MUST be LZ4F_VERSION. It is intended to track potential version differences between different binaries.
+ * The function will provide a pointer to a fully allocated LZ4F_compressionContext_t object.
+ * If the result LZ4F_errorCode_t is not zero, there was an error during context creation.
+ * Object can release its memory using LZ4F_freeCompressionContext();
+ */
+
+
+/* Compression */
+
+size_t LZ4F_compressBegin(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const LZ4F_preferences_t* preferencesPtr);
+/* LZ4F_compressBegin() :
+ * will write the frame header into dstBuffer.
+ * dstBuffer must be large enough to accommodate a header (dstMaxSize). Maximum header size is 19 bytes.
+ * The LZ4F_preferences_t structure is optional : you can provide NULL as argument, all preferences will then be set to default.
+ * The result of the function is the number of bytes written into dstBuffer for the header
+ * or an error code (can be tested using LZ4F_isError())
+ */
+
+size_t LZ4F_compressBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr);
+/* LZ4F_compressBound() :
+ * Provides the minimum size of Dst buffer given srcSize to handle worst case situations.
+ * preferencesPtr is optional : you can provide NULL as argument, all preferences will then be set to default.
+ */
+
+size_t LZ4F_compressUpdate(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const void* srcBuffer, size_t srcSize, const LZ4F_compressOptions_t* compressOptionsPtr);
+/* LZ4F_compressUpdate()
+ * LZ4F_compressUpdate() can be called repetitively to compress as much data as necessary.
+ * The most important rule is that dstBuffer MUST be large enough (dstMaxSize) to ensure compression completion even in worst case.
+ * If this condition is not respected, LZ4F_compress() will fail (result is an errorCode)
+ * You can get the minimum value of dstMaxSize by using LZ4F_compressBound()
+ * The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.
+ * The result of the function is the number of bytes written into dstBuffer : it can be zero, meaning input data was just buffered.
+ * The function outputs an error code if it fails (can be tested using LZ4F_isError())
+ */
+
+size_t LZ4F_flush(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const LZ4F_compressOptions_t* compressOptionsPtr);
+/* LZ4F_flush()
+ * Should you need to create compressed data immediately, without waiting for a block to be filled,
+ * you can call LZ4_flush(), which will immediately compress any remaining data buffered within compressionContext.
+ * The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.
+ * The result of the function is the number of bytes written into dstBuffer
+ * (it can be zero, this means there was no data left within compressionContext)
+ * The function outputs an error code if it fails (can be tested using LZ4F_isError())
+ */
+
+size_t LZ4F_compressEnd(LZ4F_compressionContext_t compressionContext, void* dstBuffer, size_t dstMaxSize, const LZ4F_compressOptions_t* compressOptionsPtr);
+/* LZ4F_compressEnd()
+ * When you want to properly finish the compressed frame, just call LZ4F_compressEnd().
+ * It will flush whatever data remained within compressionContext (like LZ4_flush())
+ * but also properly finalize the frame, with an endMark and a checksum.
+ * The result of the function is the number of bytes written into dstBuffer (necessarily >= 4 (endMark size))
+ * The function outputs an error code if it fails (can be tested using LZ4F_isError())
+ * The LZ4F_compressOptions_t structure is optional : you can provide NULL as argument.
+ * compressionContext can then be used again, starting with LZ4F_compressBegin().
+ */
+
+
+/***********************************
+ * Decompression functions
+ * *********************************/
+
+typedef void* LZ4F_decompressionContext_t;
+
+typedef struct {
+ unsigned stableDst; /* unused for the time being, must be 0 */
+ unsigned reserved[3];
+} LZ4F_decompressOptions_t;
+
+/* Resource management */
+
+LZ4F_errorCode_t LZ4F_createDecompressionContext(LZ4F_compressionContext_t* LZ4F_decompressionContextPtr, unsigned version);
+LZ4F_errorCode_t LZ4F_freeDecompressionContext(LZ4F_compressionContext_t LZ4F_decompressionContext);
+/* LZ4F_createDecompressionContext() :
+ * The first thing to do is to create a decompressionContext object, which will be used in all decompression operations.
+ * This is achieved using LZ4F_createDecompressionContext().
+ * The function will provide a pointer to a fully allocated and initialized LZ4F_decompressionContext object.
+ * If the result LZ4F_errorCode_t is not OK_NoError, there was an error during context creation.
+ * Object can release its memory using LZ4F_freeDecompressionContext();
+ */
+
+/* Decompression */
+
+size_t LZ4F_getFrameInfo(LZ4F_decompressionContext_t decompressionContext, LZ4F_frameInfo_t* frameInfoPtr, const void* srcBuffer, size_t* srcSizePtr);
+/* LZ4F_getFrameInfo()
+ * This function decodes frame header information, such as blockSize.
+ * It is optional : you could start by calling directly LZ4F_decompress() instead.
+ * The objective is to extract header information without starting decompression, typically for allocation purposes.
+ * LZ4F_getFrameInfo() can also be used *after* starting decompression, on a valid LZ4F_decompressionContext_t.
+ * The number of bytes read from srcBuffer will be provided within *srcSizePtr (necessarily <= original value).
+ * You are expected to resume decompression from where it stopped (srcBuffer + *srcSizePtr)
+ * The function result is an hint of the better srcSize to use for next call to LZ4F_decompress,
+ * or an error code which can be tested using LZ4F_isError().
+ */
+
+size_t LZ4F_decompress(LZ4F_decompressionContext_t decompressionContext, void* dstBuffer, size_t* dstSizePtr, const void* srcBuffer, size_t* srcSizePtr, const LZ4F_decompressOptions_t* decompressOptionsPtr);
+/* LZ4F_decompress()
+ * Call this function repetitively to regenerate data compressed within srcBuffer.
+ * The function will attempt to decode *srcSizePtr bytes from srcBuffer, into dstBuffer of maximum size *dstSizePtr.
+ *
+ * The number of bytes regenerated into dstBuffer will be provided within *dstSizePtr (necessarily <= original value).
+ *
+ * The number of bytes effectively used from srcBuffer will be provided within *srcSizePtr (necessarily <= original value).
+ * If the number of bytes read is < number of bytes provided, then the decompression operation is not complete.
+ * This typically happens when dstBuffer is not large enough to contain all decoded data.
+ * LZ4F_decompress() will have to be called again, starting from where it stopped (srcBuffer + *srcSizePtr)
+ * The function will check this condition, and refuse to continue if it is not respected.
+ * dstBuffer is supposed to be flushed between calls to the function, since its content will be rewritten.
+ * Different dst arguments can be used between each calls.
+ *
+ * The function result is an hint of the better srcSize to use for next call to LZ4F_decompress.
+ * Basically, it's the size of the current (or remaining) compressed block + header of next block.
+ * Respecting the hint provides some boost to performance, since it allows less buffer shuffling.
+ * Note that this is just a hint, you can always provide any srcSize you want.
+ * When a frame is fully decoded, the function result will be 0.
+ * If decompression failed, function result is an error code which can be tested using LZ4F_isError().
+ */
+
+
+
+#if defined (__cplusplus)
+}
+#endif
diff --git a/lz4hc.c b/lz4hc.c
index 441a1d6..34a6173 100644
--- a/lz4hc.c
+++ b/lz4hc.c
@@ -58,7 +58,8 @@
|| defined(__powerpc64__) || defined(__powerpc64le__) \
|| defined(__ppc64__) || defined(__ppc64le__) \
|| defined(__PPC64__) || defined(__PPC64LE__) \
- || defined(__ia64) || defined(__itanium__) || defined(_M_IA64) ) /* Detects 64 bits mode */
+ || defined(__ia64) || defined(__itanium__) || defined(_M_IA64) \
+ || defined(__s390x__) ) /* Detects 64 bits mode */
# define LZ4_ARCH64 1
#else
# define LZ4_ARCH64 0
diff --git a/programs/Makefile b/programs/Makefile
index a04c323..c653ec6 100644
--- a/programs/Makefile
+++ b/programs/Makefile
@@ -30,7 +30,7 @@
# fullbench32: Same as fullbench, but forced to compile in 32-bits mode
# ##########################################################################
-RELEASE=r122
+RELEASE=r123
DESTDIR?=
PREFIX ?= /usr
@@ -68,29 +68,32 @@ endif
default: lz4 lz4c
-all: lz4 lz4c lz4c32 fullbench fullbench32 fuzzer fuzzer32 datagen
+all: lz4 lz4c lz4c32 fullbench fullbench32 fuzzer fuzzer32 frametest datagen
-lz4: $(LZ4DIR)/lz4.c $(LZ4DIR)/lz4hc.c bench.c xxhash.c lz4io.c lz4cli.c
+lz4: $(LZ4DIR)/lz4.c $(LZ4DIR)/lz4hc.c $(LZ4DIR)/xxhash.c bench.c lz4io.c lz4cli.c
$(CC) $(FLAGS) -DDISABLE_LZ4C_LEGACY_OPTIONS $^ -o $@$(EXT)
-lz4c : $(LZ4DIR)/lz4.c $(LZ4DIR)/lz4hc.c bench.c xxhash.c lz4io.c lz4cli.c
+lz4c : $(LZ4DIR)/lz4.c $(LZ4DIR)/lz4hc.c $(LZ4DIR)/xxhash.c bench.c lz4io.c lz4cli.c
$(CC) $(FLAGS) $^ -o $@$(EXT)
-lz4c32: $(LZ4DIR)/lz4.c $(LZ4DIR)/lz4hc.c bench.c xxhash.c lz4io.c lz4cli.c
+lz4c32: $(LZ4DIR)/lz4.c $(LZ4DIR)/lz4hc.c $(LZ4DIR)/xxhash.c bench.c lz4io.c lz4cli.c
$(CC) -m32 $(FLAGS) $^ -o $@$(EXT)
-fullbench : $(LZ4DIR)/lz4.c $(LZ4DIR)/lz4hc.c xxhash.c fullbench.c
+fullbench : $(LZ4DIR)/lz4.c $(LZ4DIR)/lz4hc.c $(LZ4DIR)/lz4frame.c $(LZ4DIR)/xxhash.c fullbench.c
$(CC) $(FLAGS) $^ -o $@$(EXT)
-fullbench32: $(LZ4DIR)/lz4.c $(LZ4DIR)/lz4hc.c xxhash.c fullbench.c
+fullbench32: $(LZ4DIR)/lz4.c $(LZ4DIR)/lz4hc.c $(LZ4DIR)/lz4frame.c $(LZ4DIR)/xxhash.c fullbench.c
$(CC) -m32 $(FLAGS) $^ -o $@$(EXT)
-fuzzer : $(LZ4DIR)/lz4.c $(LZ4DIR)/lz4hc.c xxhash.c fuzzer.c
+fuzzer : $(LZ4DIR)/lz4.c $(LZ4DIR)/lz4hc.c $(LZ4DIR)/xxhash.c fuzzer.c
$(CC) $(FLAGS) $^ -o $@$(EXT)
-fuzzer32: $(LZ4DIR)/lz4.c $(LZ4DIR)/lz4hc.c xxhash.c fuzzer.c
+fuzzer32: $(LZ4DIR)/lz4.c $(LZ4DIR)/lz4hc.c $(LZ4DIR)/xxhash.c fuzzer.c
$(CC) -m32 $(FLAGS) $^ -o $@$(EXT)
+frametest: $(LZ4DIR)/lz4frame.c $(LZ4DIR)/lz4.c $(LZ4DIR)/lz4hc.c $(LZ4DIR)/xxhash.c frametest.c
+ $(CC) $(FLAGS) $^ -o $@$(EXT)
+
datagen : datagen.c
$(CC) $(FLAGS) $^ -o $@$(EXT)
@@ -99,7 +102,8 @@ clean:
@rm -f core *.o \
lz4$(EXT) lz4c$(EXT) lz4c32$(EXT) \
fullbench$(EXT) fullbench32$(EXT) \
- fuzzer$(EXT) fuzzer32$(EXT) datagen$(EXT)
+ fuzzer$(EXT) fuzzer32$(EXT) \
+ frametest$(EXT) datagen$(EXT)
@echo Cleaning completed
@@ -128,7 +132,7 @@ uninstall:
[ -f $(DESTDIR)$(MANDIR)/lz4cat.1 ] && rm -f $(DESTDIR)$(MANDIR)/lz4cat.1
@echo lz4 successfully uninstalled
-test-native: test-lz4 test-lz4c test-fullbench test-fuzzer test-mem
+test-native: test-lz4 test-lz4c test-frame test-fullbench test-fuzzer test-mem
test-force32: test-lz4c32 test-fullbench32 test-fuzzer32 test-mem32
@@ -165,7 +169,10 @@ test-fuzzer: fuzzer
test-fuzzer32: fuzzer32
./fuzzer32 --no-prompt
-test-mem: lz4 datagen
+test-frame: frametest
+ ./frametest
+
+test-mem: lz4 datagen frametest
./datagen -g16KB > tmp
valgrind ./lz4 -9 -BD -f tmp /dev/null
./datagen -g16MB > tmp
@@ -173,6 +180,7 @@ test-mem: lz4 datagen
./datagen -g256MB > tmp
valgrind ./lz4 -B4D -f tmp /dev/null
rm tmp
+ valgrind ./frametest -i100
test-mem32: lz4c32 datagen
# unfortunately, valgrind doesn't seem to work with non-native binary. If someone knows how to do a valgrind-test on a 32-bits exe with a 64-bits system...
diff --git a/programs/frametest.c b/programs/frametest.c
new file mode 100644
index 0000000..3d19ef4
--- /dev/null
+++ b/programs/frametest.c
@@ -0,0 +1,668 @@
+/*
+ frameTest - test tool for lz4frame
+ Copyright (C) Yann Collet 2014
+ GPL v2 License
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along
+ with this program; if not, write to the Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+ You can contact the author at :
+ - LZ4 source repository : http://code.google.com/p/lz4/
+ - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
+*/
+
+/**************************************
+ Compiler specific
+**************************************/
+#define _CRT_SECURE_NO_WARNINGS // fgets
+#ifdef _MSC_VER /* Visual Studio */
+# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
+# pragma warning(disable : 4146) /* disable: C4146: minus unsigned expression */
+#endif
+#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
+#ifdef __GNUC__
+# pragma GCC diagnostic ignored "-Wmissing-braces" /* GCC bug 53119 : doesn't accept { 0 } as initializer (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53119) */
+# pragma GCC diagnostic ignored "-Wmissing-field-initializers" /* GCC bug 53119 : doesn't accept { 0 } as initializer (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53119) */
+#endif
+
+
+/**************************************
+ Includes
+**************************************/
+#include <stdlib.h>
+#include <stdio.h> // fgets, sscanf
+#include <sys/timeb.h> // timeb
+#include <string.h> // strcmp
+#include "lz4frame.h"
+#include "xxhash.h" // XXH64
+
+
+/**************************************
+ Basic Types
+**************************************/
+#if defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */
+# include <stdint.h>
+typedef uint8_t BYTE;
+typedef uint16_t U16;
+typedef uint32_t U32;
+typedef int32_t S32;
+typedef uint64_t U64;
+#else
+typedef unsigned char BYTE;
+typedef unsigned short U16;
+typedef unsigned int U32;
+typedef signed int S32;
+typedef unsigned long long U64;
+#endif
+
+
+/**************************************
+ Constants
+**************************************/
+#ifndef LZ4_VERSION
+# define LZ4_VERSION ""
+#endif
+
+#define KB *(1U<<10)
+#define MB *(1U<<20)
+#define GB *(1U<<30)
+
+static const U32 nbTestsDefault = 128 KB;
+#define COMPRESSIBLE_NOISE_LENGTH (2 MB)
+#define FUZ_COMPRESSIBILITY_DEFAULT 50
+static const U32 prime1 = 2654435761U;
+static const U32 prime2 = 2246822519U;
+
+
+
+/**************************************
+ Macros
+**************************************/
+#define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
+#define DISPLAYLEVEL(l, ...) if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }
+#define DISPLAYUPDATE(l, ...) if (displayLevel>=l) { \
+ if ((FUZ_GetMilliSpan(g_time) > refreshRate) || (displayLevel>=4)) \
+ { g_time = FUZ_GetMilliStart(); DISPLAY(__VA_ARGS__); \
+ if (displayLevel>=4) fflush(stdout); } }
+static const U32 refreshRate = 150;
+static U32 g_time = 0;
+
+
+/*****************************************
+ Local Parameters
+*****************************************/
+static U32 no_prompt = 0;
+static char* programName;
+static U32 displayLevel = 2;
+static U32 pause = 0;
+
+
+/*********************************************************
+ Fuzzer functions
+*********************************************************/
+static U32 FUZ_GetMilliStart(void)
+{
+ struct timeb tb;
+ U32 nCount;
+ ftime( &tb );
+ nCount = (U32) (((tb.time & 0xFFFFF) * 1000) + tb.millitm);
+ return nCount;
+}
+
+
+static U32 FUZ_GetMilliSpan(U32 nTimeStart)
+{
+ U32 nCurrent = FUZ_GetMilliStart();
+ U32 nSpan = nCurrent - nTimeStart;
+ if (nTimeStart > nCurrent)
+ nSpan += 0x100000 * 1000;
+ return nSpan;
+}
+
+
+
+# define FUZ_rotl32(x,r) ((x << r) | (x >> (32 - r)))
+unsigned int FUZ_rand(unsigned int* src)
+{
+ U32 rand32 = *src;
+ rand32 *= prime1;
+ rand32 += prime2;
+ rand32 = FUZ_rotl32(rand32, 13);
+ *src = rand32;
+ return rand32 >> 5;
+}
+
+
+#define FUZ_RAND15BITS (FUZ_rand(seed) & 0x7FFF)
+#define FUZ_RANDLENGTH ( (FUZ_rand(seed) & 3) ? (FUZ_rand(seed) % 15) : (FUZ_rand(seed) % 510) + 15)
+static void FUZ_fillCompressibleNoiseBuffer(void* buffer, unsigned bufferSize, double proba, U32* seed)
+{
+ BYTE* BBuffer = (BYTE*)buffer;
+ unsigned pos = 0;
+ U32 P32 = (U32)(32768 * proba);
+
+ // First Byte
+ BBuffer[pos++] = (BYTE)(FUZ_rand(seed));
+
+ while (pos < bufferSize)
+ {
+ // Select : Literal (noise) or copy (within 64K)
+ if (FUZ_RAND15BITS < P32)
+ {
+ // Copy (within 64K)
+ unsigned match, end;
+ unsigned length = FUZ_RANDLENGTH + 4;
+ unsigned offset = FUZ_RAND15BITS + 1;
+ if (offset > pos) offset = pos;
+ if (pos + length > bufferSize) length = bufferSize - pos;
+ match = pos - offset;
+ end = pos + length;
+ while (pos < end) BBuffer[pos++] = BBuffer[match++];
+ }
+ else
+ {
+ // Literal (noise)
+ unsigned end;
+ unsigned length = FUZ_RANDLENGTH;
+ if (pos + length > bufferSize) length = bufferSize - pos;
+ end = pos + length;
+ while (pos < end) BBuffer[pos++] = (BYTE)(FUZ_rand(seed) >> 5);
+ }
+ }
+}
+
+
+static unsigned FUZ_highbit(U32 v32)
+{
+ unsigned nbBits = 0;
+ if (v32==0) return 0;
+ while (v32)
+ {
+ v32 >>= 1;
+ nbBits ++;
+ }
+ return nbBits;
+}
+
+
+int basicTests(U32 seed, double compressibility)
+{
+ int testResult = 0;
+ void* CNBuffer;
+ void* compressedBuffer;
+ void* decodedBuffer;
+ U32 randState = seed;
+ size_t cSize, testSize;
+ LZ4F_preferences_t prefs = { 0 };
+ LZ4F_decompressionContext_t dCtx;
+ U64 crcOrig;
+
+ // Create compressible test buffer
+ CNBuffer = malloc(COMPRESSIBLE_NOISE_LENGTH);
+ compressedBuffer = malloc(LZ4F_compressFrameBound(COMPRESSIBLE_NOISE_LENGTH, NULL));
+ decodedBuffer = malloc(COMPRESSIBLE_NOISE_LENGTH);
+ FUZ_fillCompressibleNoiseBuffer(CNBuffer, COMPRESSIBLE_NOISE_LENGTH, compressibility, &randState);
+ crcOrig = XXH64(CNBuffer, COMPRESSIBLE_NOISE_LENGTH, 1);
+
+ // Trivial tests : one-step frame
+ testSize = COMPRESSIBLE_NOISE_LENGTH;
+ DISPLAYLEVEL(3, "Using NULL preferences : \n");
+ cSize = LZ4F_compressFrame(compressedBuffer, LZ4F_compressFrameBound(testSize, NULL), CNBuffer, testSize, NULL);
+ if (LZ4F_isError(cSize)) goto _output_error;
+ DISPLAYLEVEL(3, "Compressed %i bytes into a %i bytes frame \n", (int)testSize, (int)cSize);
+
+ DISPLAYLEVEL(3, "Decompression test : \n");
+ {
+ size_t decodedBufferSize = COMPRESSIBLE_NOISE_LENGTH;
+ size_t compressedBufferSize = cSize;
+ BYTE* op = (BYTE*)decodedBuffer;
+ BYTE* const oend = (BYTE*)decodedBuffer + COMPRESSIBLE_NOISE_LENGTH;
+ BYTE* ip = (BYTE*)compressedBuffer;
+ BYTE* const iend = (BYTE*)compressedBuffer + cSize;
+ U64 crcDest;
+
+ LZ4F_errorCode_t errorCode = LZ4F_createDecompressionContext(&dCtx, LZ4F_VERSION);
+ if (LZ4F_isError(errorCode)) goto _output_error;
+
+ DISPLAYLEVEL(3, "Single Block : \n");
+ errorCode = LZ4F_decompress(dCtx, decodedBuffer, &decodedBufferSize, compressedBuffer, &compressedBufferSize, NULL);
+ crcDest = XXH64(decodedBuffer, COMPRESSIBLE_NOISE_LENGTH, 1);
+ if (crcDest != crcOrig) goto _output_error;
+ DISPLAYLEVEL(3, "Regenerated %i bytes \n", (int)decodedBufferSize);
+
+ DISPLAYLEVEL(3, "Byte after byte : \n");
+ while (ip < iend)
+ {
+ size_t oSize = oend-op;
+ size_t iSize = 1;
+ //DISPLAY("%7i \n", (int)(ip-(BYTE*)compressedBuffer));
+ errorCode = LZ4F_decompress(dCtx, op, &oSize, ip, &iSize, NULL);
+ if (LZ4F_isError(errorCode)) goto _output_error;
+ op += oSize;
+ ip += iSize;
+ }
+ crcDest = XXH64(decodedBuffer, COMPRESSIBLE_NOISE_LENGTH, 1);
+ if (crcDest != crcOrig) goto _output_error;
+ DISPLAYLEVEL(3, "Regenerated %i bytes \n", (int)decodedBufferSize);
+
+ errorCode = LZ4F_freeDecompressionContext(dCtx);
+ if (LZ4F_isError(errorCode)) goto _output_error;
+ }
+
+ DISPLAYLEVEL(3, "Using 64 KB block : \n");
+ prefs.frameInfo.blockSizeID = max64KB;
+ prefs.frameInfo.contentChecksumFlag = contentChecksumEnabled;
+ cSize = LZ4F_compressFrame(compressedBuffer, LZ4F_compressFrameBound(testSize, &prefs), CNBuffer, testSize, &prefs);
+ if (LZ4F_isError(cSize)) goto _output_error;
+ DISPLAYLEVEL(3, "Compressed %i bytes into a %i bytes frame \n", (int)testSize, (int)cSize);
+
+ DISPLAYLEVEL(3, "without checksum : \n");
+ prefs.frameInfo.contentChecksumFlag = noContentChecksum;
+ cSize = LZ4F_compressFrame(compressedBuffer, LZ4F_compressFrameBound(testSize, &prefs), CNBuffer, testSize, &prefs);
+ if (LZ4F_isError(cSize)) goto _output_error;
+ DISPLAYLEVEL(3, "Compressed %i bytes into a %i bytes frame \n", (int)testSize, (int)cSize);
+
+ DISPLAYLEVEL(3, "Using 256 KB block : \n");
+ prefs.frameInfo.blockSizeID = max256KB;
+ prefs.frameInfo.contentChecksumFlag = contentChecksumEnabled;
+ cSize = LZ4F_compressFrame(compressedBuffer, LZ4F_compressFrameBound(testSize, &prefs), CNBuffer, testSize, &prefs);
+ if (LZ4F_isError(cSize)) goto _output_error;
+ DISPLAYLEVEL(3, "Compressed %i bytes into a %i bytes frame \n", (int)testSize, (int)cSize);
+
+ DISPLAYLEVEL(3, "Decompression test : \n");
+ {
+ size_t decodedBufferSize = COMPRESSIBLE_NOISE_LENGTH;
+ unsigned maxBits = FUZ_highbit((U32)decodedBufferSize);
+ BYTE* op = (BYTE*)decodedBuffer;
+ BYTE* const oend = (BYTE*)decodedBuffer + COMPRESSIBLE_NOISE_LENGTH;
+ BYTE* ip = (BYTE*)compressedBuffer;
+ BYTE* const iend = (BYTE*)compressedBuffer + cSize;
+ U64 crcDest;
+
+ LZ4F_errorCode_t errorCode = LZ4F_createDecompressionContext(&dCtx, LZ4F_VERSION);
+ if (LZ4F_isError(errorCode)) goto _output_error;
+
+ DISPLAYLEVEL(3, "random segment sizes : \n");
+ while (ip < iend)
+ {
+ unsigned nbBits = FUZ_rand(&randState) % maxBits;
+ size_t iSize = (FUZ_rand(&randState) & ((1<<nbBits)-1)) + 1;
+ size_t oSize = oend-op;
+ if (iSize > (size_t)(iend-ip)) iSize = iend-ip;
+ //DISPLAY("%7i : + %6i\n", (int)(ip-(BYTE*)compressedBuffer), (int)iSize);
+ errorCode = LZ4F_decompress(dCtx, op, &oSize, ip, &iSize, NULL);
+ if (LZ4F_isError(errorCode)) goto _output_error;
+ op += oSize;
+ ip += iSize;
+ }
+ crcDest = XXH64(decodedBuffer, COMPRESSIBLE_NOISE_LENGTH, 1);
+ if (crcDest != crcOrig) goto _output_error;
+ DISPLAYLEVEL(3, "Regenerated %i bytes \n", (int)decodedBufferSize);
+
+ errorCode = LZ4F_freeDecompressionContext(dCtx);
+ if (LZ4F_isError(errorCode)) goto _output_error;
+ }
+
+ DISPLAYLEVEL(3, "without checksum : \n");
+ prefs.frameInfo.contentChecksumFlag = noContentChecksum;
+ cSize = LZ4F_compressFrame(compressedBuffer, LZ4F_compressFrameBound(testSize, &prefs), CNBuffer, testSize, &prefs);
+ if (LZ4F_isError(cSize)) goto _output_error;
+ DISPLAYLEVEL(3, "Compressed %i bytes into a %i bytes frame \n", (int)testSize, (int)cSize);
+
+ DISPLAYLEVEL(3, "Using 1 MB block : \n");
+ prefs.frameInfo.blockSizeID = max1MB;
+ prefs.frameInfo.contentChecksumFlag = contentChecksumEnabled;
+ cSize = LZ4F_compressFrame(compressedBuffer, LZ4F_compressFrameBound(testSize, &prefs), CNBuffer, testSize, &prefs);
+ if (LZ4F_isError(cSize)) goto _output_error;
+ DISPLAYLEVEL(3, "Compressed %i bytes into a %i bytes frame \n", (int)testSize, (int)cSize);
+
+ DISPLAYLEVEL(3, "without checksum : \n");
+ prefs.frameInfo.contentChecksumFlag = noContentChecksum;
+ cSize = LZ4F_compressFrame(compressedBuffer, LZ4F_compressFrameBound(testSize, &prefs), CNBuffer, testSize, &prefs);
+ if (LZ4F_isError(cSize)) goto _output_error;
+ DISPLAYLEVEL(3, "Compressed %i bytes into a %i bytes frame \n", (int)testSize, (int)cSize);
+
+ DISPLAYLEVEL(3, "Using 4 MB block : \n");
+ prefs.frameInfo.blockSizeID = max4MB;
+ prefs.frameInfo.contentChecksumFlag = contentChecksumEnabled;
+ cSize = LZ4F_compressFrame(compressedBuffer, LZ4F_compressFrameBound(testSize, &prefs), CNBuffer, testSize, &prefs);
+ if (LZ4F_isError(cSize)) goto _output_error;
+ DISPLAYLEVEL(3, "Compressed %i bytes into a %i bytes frame \n", (int)testSize, (int)cSize);
+
+ DISPLAYLEVEL(3, "without checksum : \n");
+ prefs.frameInfo.contentChecksumFlag = noContentChecksum;
+ cSize = LZ4F_compressFrame(compressedBuffer, LZ4F_compressFrameBound(testSize, &prefs), CNBuffer, testSize, &prefs);
+ if (LZ4F_isError(cSize)) goto _output_error;
+ DISPLAYLEVEL(3, "Compressed %i bytes into a %i bytes frame \n", (int)testSize, (int)cSize);
+
+ DISPLAY("Basic tests completed \n");
+_end:
+ free(CNBuffer);
+ free(compressedBuffer);
+ free(decodedBuffer);
+ return testResult;
+
+_output_error:
+ testResult = 1;
+ DISPLAY("Error detected ! \n");
+ goto _end;
+}
+
+
+static void locateBuffDiff(const void* buff1, const void* buff2, size_t size, unsigned nonContiguous)
+{
+ int p=0;
+ BYTE* b1=(BYTE*)buff1;
+ BYTE* b2=(BYTE*)buff2;
+ if (nonContiguous)
+ {
+ DISPLAY("Non-contiguous output test (%i bytes)\n", (int)size);
+ return;
+ }
+ while (b1[p]==b2[p]) p++;
+ DISPLAY("Error at pos %i/%i : %02X != %02X \n", p, (int)size, b1[p], b2[p]);
+}
+
+
+static const U32 srcDataLength = 9 MB; /* needs to be > 2x4MB to test large blocks */
+
+int fuzzerTests(U32 seed, unsigned nbTests, unsigned startTest, double compressibility)
+{
+ unsigned testResult = 0;
+ unsigned testNb = 0;
+ void* srcBuffer = NULL;
+ void* compressedBuffer = NULL;
+ void* decodedBuffer = NULL;
+ U32 coreRand = seed;
+ LZ4F_decompressionContext_t dCtx = NULL;
+ LZ4F_compressionContext_t cCtx = NULL;
+ size_t result;
+ XXH64_stateSpace_t xxh64;
+# define CHECK(cond, ...) if (cond) { DISPLAY("Error => "); DISPLAY(__VA_ARGS__); \
+ DISPLAY(" (seed %u, test nb %u) \n", seed, testNb); goto _output_error; }
+
+ // Create buffers
+ result = LZ4F_createDecompressionContext(&dCtx, LZ4F_VERSION);
+ CHECK(LZ4F_isError(result), "Allocation failed (error %i)", (int)result);
+ result = LZ4F_createCompressionContext(&cCtx, LZ4F_VERSION);
+ CHECK(LZ4F_isError(result), "Allocation failed (error %i)", (int)result);
+ srcBuffer = malloc(srcDataLength);
+ CHECK(srcBuffer==NULL, "srcBuffer Allocation failed");
+ compressedBuffer = malloc(LZ4F_compressFrameBound(srcDataLength, NULL));
+ CHECK(compressedBuffer==NULL, "compressedBuffer Allocation failed");
+ decodedBuffer = malloc(srcDataLength);
+ CHECK(decodedBuffer==NULL, "decodedBuffer Allocation failed");
+ FUZ_fillCompressibleNoiseBuffer(srcBuffer, srcDataLength, compressibility, &coreRand);
+
+ // jump to requested testNb
+ for (testNb =0; testNb < startTest; testNb++) (void)FUZ_rand(&coreRand); // sync randomizer
+
+ // main fuzzer loop
+ for ( ; testNb < nbTests; testNb++)
+ {
+ U32 randState = coreRand ^ prime1;
+ unsigned BSId = 4 + (FUZ_rand(&randState) & 3);
+ unsigned BMId = FUZ_rand(&randState) & 1;
+ unsigned CCflag = FUZ_rand(&randState) & 1;
+ unsigned autoflush = (FUZ_rand(&randState) & 7) == 2;
+ LZ4F_preferences_t prefs = { 0 };
+ LZ4F_compressOptions_t cOptions = { 0 };
+ LZ4F_decompressOptions_t dOptions = { 0 };
+ unsigned nbBits = (FUZ_rand(&randState) % (FUZ_highbit(srcDataLength-1) - 1)) + 1;
+ size_t srcSize = (FUZ_rand(&randState) & ((1<<nbBits)-1)) + 1;
+ size_t srcStart = FUZ_rand(&randState) % (srcDataLength - srcSize);
+ size_t cSize;
+ U64 crcOrig, crcDecoded;
+
+ (void)FUZ_rand(&coreRand); // update rand seed
+ prefs.frameInfo.blockMode = BMId;
+ prefs.frameInfo.blockSizeID = BSId;
+ prefs.frameInfo.contentChecksumFlag = CCflag;
+ prefs.autoFlush = autoflush;
+
+ DISPLAYUPDATE(2, "\r%5u ", testNb);
+ crcOrig = XXH64((BYTE*)srcBuffer+srcStart, (U32)srcSize, 1);
+
+ if ((FUZ_rand(&randState)&0xF) == 2)
+ {
+ LZ4F_preferences_t* framePrefs = &prefs;
+ if ((FUZ_rand(&randState)&7) == 1) framePrefs = NULL;
+ cSize = LZ4F_compressFrame(compressedBuffer, LZ4F_compressFrameBound(srcSize, framePrefs), (char*)srcBuffer + srcStart, srcSize, framePrefs);
+ CHECK(LZ4F_isError(cSize), "LZ4F_compressFrame failed : error %i (%s)", (int)cSize, LZ4F_getErrorName(cSize));
+ }
+ else
+ {
+ const BYTE* ip = (const BYTE*)srcBuffer + srcStart;
+ const BYTE* const iend = ip + srcSize;
+ BYTE* op = compressedBuffer;
+ BYTE* const oend = op + LZ4F_compressFrameBound(srcDataLength, NULL);
+ unsigned maxBits = FUZ_highbit((U32)srcSize);
+ result = LZ4F_compressBegin(cCtx, op, oend-op, &prefs);
+ CHECK(LZ4F_isError(result), "Compression header failed (error %i)", (int)result);
+ op += result;
+ while (ip < iend)
+ {
+ unsigned nbBitsSeg = FUZ_rand(&randState) % maxBits;
+ size_t iSize = (FUZ_rand(&randState) & ((1<<nbBitsSeg)-1)) + 1;
+ size_t oSize = oend-op;
+ unsigned forceFlush = ((FUZ_rand(&randState) & 3) == 1);
+ if (iSize > (size_t)(iend-ip)) iSize = iend-ip;
+ cOptions.stableSrc = ((FUZ_rand(&randState) & 3) == 1);
+
+ result = LZ4F_compressUpdate(cCtx, op, oSize, ip, iSize, &cOptions);
+ CHECK(LZ4F_isError(result), "Compression failed (error %i)", (int)result);
+ op += result;
+ ip += iSize;
+
+ if (forceFlush)
+ {
+ result = LZ4F_flush(cCtx, op, oend-op, &cOptions);
+ CHECK(LZ4F_isError(result), "Compression failed (error %i)", (int)result);
+ op += result;
+ }
+ }
+ result = LZ4F_compressEnd(cCtx, op, oend-op, &cOptions);
+ CHECK(LZ4F_isError(result), "Compression completion failed (error %i)", (int)result);
+ op += result;
+ cSize = op-(BYTE*)compressedBuffer;
+ }
+
+ {
+ const BYTE* ip = compressedBuffer;
+ const BYTE* const iend = ip + cSize;
+ BYTE* op = decodedBuffer;
+ BYTE* const oend = op + srcDataLength;
+ unsigned maxBits = FUZ_highbit((U32)cSize);
+ unsigned nonContiguousDst = (FUZ_rand(&randState) & 3) == 1;
+ nonContiguousDst += FUZ_rand(&randState) & nonContiguousDst; /* 0=>0; 1=>1,2 */
+ XXH64_resetState(&xxh64, 1);
+ while (ip < iend)
+ {
+ unsigned nbBitsI = (FUZ_rand(&randState) % (maxBits-1)) + 1;
+ unsigned nbBitsO = (FUZ_rand(&randState) % (maxBits)) + 1;
+ size_t iSize = (FUZ_rand(&randState) & ((1<<nbBitsI)-1)) + 1;
+ size_t oSize = (FUZ_rand(&randState) & ((1<<nbBitsO)-1)) + 2;
+ if (iSize > (size_t)(iend-ip)) iSize = iend-ip;
+ if (oSize > (size_t)(oend-op)) oSize = oend-op;
+ dOptions.stableDst = FUZ_rand(&randState) & 1;
+ if (nonContiguousDst==2) dOptions.stableDst = 0;
+ //if (ip == compressedBuffer+62073) DISPLAY("oSize : %i : pos %i \n", (int)oSize, (int)(op-(BYTE*)decodedBuffer));
+ result = LZ4F_decompress(dCtx, op, &oSize, ip, &iSize, &dOptions);
+ //if (op+oSize >= (BYTE*)decodedBuffer+94727) DISPLAY("iSize : %i : pos %i \n", (int)iSize, (int)(ip-(BYTE*)compressedBuffer));
+ //if ((int)result<0) DISPLAY("iSize : %i : pos %i \n", (int)iSize, (int)(ip-(BYTE*)compressedBuffer));
+ if (result == (size_t)-ERROR_checksum_invalid) locateBuffDiff((BYTE*)srcBuffer+srcStart, decodedBuffer, srcSize, nonContiguousDst);
+ CHECK(LZ4F_isError(result), "Decompression failed (error %i:%s)", (int)result, LZ4F_getErrorName((LZ4F_errorCode_t)result));
+ XXH64_update(&xxh64, op, (U32)oSize);
+ op += oSize;
+ ip += iSize;
+ op += nonContiguousDst;
+ if (nonContiguousDst==2) op = decodedBuffer; // overwritten destination
+ }
+ CHECK(result != 0, "Frame decompression failed (error %i)", (int)result);
+ crcDecoded = XXH64_intermediateDigest(&xxh64);
+ if (crcDecoded != crcOrig) locateBuffDiff((BYTE*)srcBuffer+srcStart, decodedBuffer, srcSize, nonContiguousDst);
+ CHECK(crcDecoded != crcOrig, "Decompression corruption");
+ }
+ }
+
+ DISPLAYLEVEL(2, "\rAll tests completed \n");
+
+_end:
+ LZ4F_freeDecompressionContext(dCtx);
+ LZ4F_freeCompressionContext(cCtx);
+ free(srcBuffer);
+ free(compressedBuffer);
+ free(decodedBuffer);
+
+ if (pause)
+ {
+ DISPLAY("press enter to finish \n");
+ getchar();
+ }
+ return testResult;
+
+_output_error:
+ testResult = 1;
+ goto _end;
+}
+
+
+int FUZ_usage(void)
+{
+ DISPLAY( "Usage :\n");
+ DISPLAY( " %s [args]\n", programName);
+ DISPLAY( "\n");
+ DISPLAY( "Arguments :\n");
+ DISPLAY( " -i# : Nb of tests (default:%u) \n", nbTestsDefault);
+ DISPLAY( " -s# : Select seed (default:prompt user)\n");
+ DISPLAY( " -t# : Select starting test number (default:0)\n");
+ DISPLAY( " -p# : Select compressibility in %% (default:%i%%)\n", FUZ_COMPRESSIBILITY_DEFAULT);
+ DISPLAY( " -v : verbose\n");
+ DISPLAY( " -h : display help and exit\n");
+ return 0;
+}
+
+
+int main(int argc, char** argv)
+{
+ U32 seed=0;
+ int seedset=0;
+ int argNb;
+ int nbTests = nbTestsDefault;
+ int testNb = 0;
+ int proba = FUZ_COMPRESSIBILITY_DEFAULT;
+ int result=0;
+
+ // Check command line
+ programName = argv[0];
+ for(argNb=1; argNb<argc; argNb++)
+ {
+ char* argument = argv[argNb];
+
+ if(!argument) continue; // Protection if argument empty
+
+ // Decode command (note : aggregated commands are allowed)
+ if (argument[0]=='-')
+ {
+ if (!strcmp(argument, "--no-prompt"))
+ {
+ no_prompt=1;
+ seedset=1;
+ displayLevel=1;
+ continue;
+ }
+ argument++;
+
+ while (*argument!=0)
+ {
+ switch(*argument)
+ {
+ case 'h':
+ return FUZ_usage();
+ case 'v':
+ argument++;
+ displayLevel=4;
+ break;
+ case 'q':
+ argument++;
+ displayLevel--;
+ break;
+ case 'i':
+ argument++;
+ nbTests=0;
+ while ((*argument>='0') && (*argument<='9'))
+ {
+ nbTests *= 10;
+ nbTests += *argument - '0';
+ argument++;
+ }
+ break;
+ case 's':
+ argument++;
+ seed=0;
+ seedset=1;
+ while ((*argument>='0') && (*argument<='9'))
+ {
+ seed *= 10;
+ seed += *argument - '0';
+ argument++;
+ }
+ break;
+ case 't':
+ argument++;
+ testNb=0;
+ while ((*argument>='0') && (*argument<='9'))
+ {
+ testNb *= 10;
+ testNb += *argument - '0';
+ argument++;
+ }
+ break;
+ case 'p': /* compressibility % */
+ argument++;
+ proba=0;
+ while ((*argument>='0') && (*argument<='9'))
+ {
+ proba *= 10;
+ proba += *argument - '0';
+ argument++;
+ }
+ if (proba<0) proba=0;
+ if (proba>100) proba=100;
+ break;
+ case 'P': /* pause at the end */
+ argument++;
+ pause = 1;
+ break;
+ default:
+ ;
+ return FUZ_usage();
+ }
+ }
+ }
+ }
+
+ // Get Seed
+ printf("Starting lz4frame tester (%i-bits, %s)\n", (int)(sizeof(size_t)*8), LZ4_VERSION);
+
+ if (!seedset) seed = FUZ_GetMilliStart() % 10000;
+ printf("Seed = %u\n", seed);
+ if (proba!=FUZ_COMPRESSIBILITY_DEFAULT) printf("Compressibility : %i%%\n", proba);
+
+ if (nbTests<=0) nbTests=1;
+
+ //if (testNb==0) result = basicTests(seed, ((double)proba) / 100);
+ if (result) return 1;
+ return fuzzerTests(seed, nbTests, testNb, ((double)proba) / 100);
+}
diff --git a/programs/fullbench.c b/programs/fullbench.c
index 3d39458..f34c68c 100644
--- a/programs/fullbench.c
+++ b/programs/fullbench.c
@@ -60,10 +60,8 @@
#endif
#include "lz4.h"
-#define COMPRESSOR0 LZ4_compress
#include "lz4hc.h"
-#define COMPRESSOR1 LZ4_compressHC
-#define DEFAULTCOMPRESSOR COMPRESSOR0
+#include "lz4frame.h"
#include "xxhash.h"
@@ -270,7 +268,7 @@ static int local_LZ4_compress_limitedOutput_withState(const char* in, char* out,
return LZ4_compress_limitedOutput_withState(stateLZ4, in, out, inSize, LZ4_compressBound(inSize));
}
-static void* ctx;
+static LZ4_stream_t* ctx;
static int local_LZ4_compress_continue(const char* in, char* out, int inSize)
{
return LZ4_compress_continue(ctx, in, out, inSize);
@@ -323,6 +321,11 @@ static int local_LZ4_compressHC_limitedOutput_continue(const char* in, char* out
return LZ4_compressHC_limitedOutput_continue(ctx, in, out, inSize, LZ4_compressBound(inSize));
}
+static int local_LZ4F_compressFrame(const char* in, char* out, int inSize)
+{
+ return (int)LZ4F_compressFrame(out, 2*inSize + 16, in, inSize, NULL);
+}
+
static int local_LZ4_decompress_fast(const char* in, char* out, int inSize, int outSize)
{
(void)inSize;
@@ -340,14 +343,23 @@ static int local_LZ4_decompress_fast_withPrefix64k(const char* in, char* out, in
static int local_LZ4_decompress_fast_usingDict(const char* in, char* out, int inSize, int outSize)
{
(void)inSize;
- LZ4_decompress_fast_usingDict(in, out, outSize, in - 65536, 65536);
+ LZ4_decompress_fast_usingDict(in, out, outSize, out - 65536, 65536);
return outSize;
}
static int local_LZ4_decompress_safe_usingDict(const char* in, char* out, int inSize, int outSize)
{
(void)inSize;
- LZ4_decompress_safe_usingDict(in, out, inSize, outSize, in - 65536, 65536);
+ LZ4_decompress_safe_usingDict(in, out, inSize, outSize, out - 65536, 65536);
+ return outSize;
+}
+
+extern int LZ4_decompress_safe_forceExtDict(const char* in, char* out, int inSize, int outSize, const char* dict, int dictSize);
+
+static int local_LZ4_decompress_safe_forceExtDict(const char* in, char* out, int inSize, int outSize)
+{
+ (void)inSize;
+ LZ4_decompress_safe_forceExtDict(in, out, inSize, outSize, out - 65536, 65536);
return outSize;
}
@@ -356,21 +368,37 @@ static int local_LZ4_decompress_safe_partial(const char* in, char* out, int inSi
return LZ4_decompress_safe_partial(in, out, inSize, outSize - 5, outSize);
}
+static LZ4F_decompressionContext_t g_dCtx;
+
+static int local_LZ4F_decompress(const char* in, char* out, int inSize, int outSize)
+{
+ size_t srcSize = inSize;
+ size_t dstSize = outSize;
+ size_t result;
+ result = LZ4F_decompress(g_dCtx, out, &dstSize, in, &srcSize, NULL);
+ if (result!=0) { DISPLAY("Error decompressing frame : unfinished frame\n"); exit(8); }
+ if (srcSize != (size_t)inSize) { DISPLAY("Error decompressing frame : read size incorrect\n"); exit(9); }
+ return (int)dstSize;
+}
+
+
int fullSpeedBench(char** fileNamesTable, int nbFiles)
{
int fileIdx=0;
char* orig_buff;
-# define NB_COMPRESSION_ALGORITHMS 13
-# define MINCOMPRESSIONCHAR '0'
+# define NB_COMPRESSION_ALGORITHMS 14
double totalCTime[NB_COMPRESSION_ALGORITHMS+1] = {0};
double totalCSize[NB_COMPRESSION_ALGORITHMS+1] = {0};
-# define NB_DECOMPRESSION_ALGORITHMS 7
-# define MINDECOMPRESSIONCHAR '0'
-# define MAXDECOMPRESSIONCHAR (MINDECOMPRESSIONCHAR + NB_DECOMPRESSION_ALGORITHMS)
- static char* decompressionNames[] = { "LZ4_decompress_fast", "LZ4_decompress_fast_withPrefix64k", "LZ4_decompress_fast_usingDict",
- "LZ4_decompress_safe", "LZ4_decompress_safe_withPrefix64k", "LZ4_decompress_safe_usingDict", "LZ4_decompress_safe_partial" };
+# define NB_DECOMPRESSION_ALGORITHMS 9
double totalDTime[NB_DECOMPRESSION_ALGORITHMS+1] = {0};
+ size_t errorCode;
+ errorCode = LZ4F_createDecompressionContext(&g_dCtx, LZ4F_VERSION);
+ if (LZ4F_isError(errorCode))
+ {
+ DISPLAY("dctx allocation issue \n");
+ return 10;
+ }
// Loop for each file
while (fileIdx<nbFiles)
@@ -428,22 +456,6 @@ int fullSpeedBench(char** fileNamesTable, int nbFiles)
return 12;
}
- // Init chunks data
- {
- int i;
- size_t remaining = benchedSize;
- char* in = orig_buff;
- char* out = compressed_buff;
- for (i=0; i<nbChunks; i++)
- {
- chunkP[i].id = i;
- chunkP[i].origBuffer = in; in += chunkSize;
- if ((int)remaining > chunkSize) { chunkP[i].origSize = chunkSize; remaining -= chunkSize; } else { chunkP[i].origSize = (int)remaining; remaining = 0; }
- chunkP[i].compressedBuffer = out; out += maxCompressedChunkSize;
- chunkP[i].compressedSize = 0;
- }
- }
-
// Fill input buffer
DISPLAY("Loading %s... \r", inFileName);
readSize = fread(orig_buff, 1, benchedSize, inFile);
@@ -471,10 +483,27 @@ int fullSpeedBench(char** fileNamesTable, int nbFiles)
DISPLAY("\r%79s\r", "");
DISPLAY(" %s : \n", inFileName);
+ // Init chunks data
+ {
+ int i;
+ size_t remaining = benchedSize;
+ char* in = orig_buff;
+ char* out = compressed_buff;
+ nbChunks = (int) ((int)benchedSize / chunkSize) + 1;
+ for (i=0; i<nbChunks; i++)
+ {
+ chunkP[i].id = i;
+ chunkP[i].origBuffer = in; in += chunkSize;
+ if ((int)remaining > chunkSize) { chunkP[i].origSize = chunkSize; remaining -= chunkSize; } else { chunkP[i].origSize = (int)remaining; remaining = 0; }
+ chunkP[i].compressedBuffer = out; out += maxCompressedChunkSize;
+ chunkP[i].compressedSize = 0;
+ }
+ }
+
// Compression Algorithms
for (cAlgNb=1; (cAlgNb <= NB_COMPRESSION_ALGORITHMS) && (compressionTest); cAlgNb++)
{
- char* compressorName;
+ const char* compressorName;
int (*compressionFunction)(const char*, char*, int);
void* (*initFunction)(const char*) = NULL;
double bestTime = 100000000.;
@@ -496,6 +525,9 @@ int fullSpeedBench(char** fileNamesTable, int nbFiles)
case 11: compressionFunction = local_LZ4_compressHC_continue; initFunction = LZ4_createHC; compressorName = "LZ4_compressHC_continue"; break;
case 12: compressionFunction = local_LZ4_compressHC_limitedOutput_continue; initFunction = LZ4_createHC; compressorName = "LZ4_compressHC_limitedOutput_continue"; break;
case 13: compressionFunction = local_LZ4_compress_forceDict; initFunction = local_LZ4_resetDictT; compressorName = "LZ4_compress_forceDict"; break;
+ case 14: compressionFunction = local_LZ4F_compressFrame; compressorName = "LZ4F_compressFrame";
+ chunkP[0].origSize = (int)benchedSize; nbChunks=1;
+ break;
default : DISPLAY("ERROR ! Bad algorithm Id !! \n"); free(chunkP); return 1;
}
@@ -546,29 +578,39 @@ int fullSpeedBench(char** fileNamesTable, int nbFiles)
chunkP[chunkNb].compressedSize = LZ4_compress(chunkP[chunkNb].origBuffer, chunkP[chunkNb].compressedBuffer, chunkP[chunkNb].origSize);
if (chunkP[chunkNb].compressedSize==0) DISPLAY("ERROR ! %s() = 0 !! \n", "LZ4_compress"), exit(1);
}
- { size_t i; for (i=0; i<benchedSize; i++) orig_buff[i]=0; } // zeroing source area, for CRC checking
// Decompression Algorithms
- for (dAlgNb=0; (dAlgNb < NB_DECOMPRESSION_ALGORITHMS) && (decompressionTest); dAlgNb++)
+ for (dAlgNb=1; (dAlgNb <= NB_DECOMPRESSION_ALGORITHMS) && (decompressionTest); dAlgNb++)
{
- char* dName = decompressionNames[dAlgNb];
+ //const char* dName = decompressionNames[dAlgNb];
+ const char* dName;
int (*decompressionFunction)(const char*, char*, int, int);
double bestTime = 100000000.;
- if ((decompressionAlgo != ALL_DECOMPRESSORS) && (decompressionAlgo != dAlgNb+1)) continue;
+ if ((decompressionAlgo != ALL_DECOMPRESSORS) && (decompressionAlgo != dAlgNb)) continue;
switch(dAlgNb)
{
- case 0: decompressionFunction = local_LZ4_decompress_fast; break;
- case 1: decompressionFunction = local_LZ4_decompress_fast_withPrefix64k; break;
- case 2: decompressionFunction = local_LZ4_decompress_fast_usingDict; break;
- case 3: decompressionFunction = LZ4_decompress_safe; break;
- case 4: decompressionFunction = LZ4_decompress_safe_withPrefix64k; break;
- case 5: decompressionFunction = local_LZ4_decompress_safe_usingDict; break;
- case 6: decompressionFunction = local_LZ4_decompress_safe_partial; break;
+ case 1: decompressionFunction = local_LZ4_decompress_fast; dName = "LZ4_decompress_fast"; break;
+ case 2: decompressionFunction = local_LZ4_decompress_fast_withPrefix64k; dName = "LZ4_decompress_fast_withPrefix64k"; break;
+ case 3: decompressionFunction = local_LZ4_decompress_fast_usingDict; dName = "LZ4_decompress_fast_usingDict"; break;
+ case 4: decompressionFunction = LZ4_decompress_safe; dName = "LZ4_decompress_safe"; break;
+ case 5: decompressionFunction = LZ4_decompress_safe_withPrefix64k; dName = "LZ4_decompress_safe_withPrefix64k"; break;
+ case 6: decompressionFunction = local_LZ4_decompress_safe_usingDict; dName = "LZ4_decompress_safe_usingDict"; break;
+ case 7: decompressionFunction = local_LZ4_decompress_safe_partial; dName = "LZ4_decompress_safe_partial"; break;
+ case 8: decompressionFunction = local_LZ4_decompress_safe_forceExtDict; dName = "LZ4_decompress_safe_forceExtDict"; break;
+ case 9: decompressionFunction = local_LZ4F_decompress; dName = "LZ4F_decompress";
+ errorCode = LZ4F_compressFrame(compressed_buff, compressedBuffSize, orig_buff, benchedSize, NULL);
+ if (LZ4F_isError(errorCode)) { DISPLAY("Preparation error compressing frame\n"); return 1; }
+ chunkP[0].origSize = (int)benchedSize;
+ chunkP[0].compressedSize = (int)errorCode;
+ nbChunks = 1;
+ break;
default : DISPLAY("ERROR ! Bad decompression algorithm Id !! \n"); free(chunkP); return 1;
}
+ { size_t i; for (i=0; i<benchedSize; i++) orig_buff[i]=0; } // zeroing source area, for CRC checking
+
for (loopNb = 1; loopNb <= nbIterations; loopNb++)
{
double averageTime;
diff --git a/programs/fuzzer.c b/programs/fuzzer.c
index b302078..c98333d 100644
--- a/programs/fuzzer.c
+++ b/programs/fuzzer.c
@@ -29,6 +29,7 @@
#ifdef _MSC_VER /* Visual Studio */
# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
# pragma warning(disable : 4146) /* disable: C4146: minus unsigned expression */
+# pragma warning(disable : 4310) /* disable: C4310: constant char value > 127 */
#endif
@@ -85,9 +86,9 @@
-//**************************************
-// Macros
-//**************************************
+/*****************************************
+ Macros
+*****************************************/
#define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
#define DISPLAYLEVEL(l, ...) if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }
@@ -135,7 +136,7 @@ unsigned int FUZ_rand(unsigned int* src)
#define FUZ_RAND15BITS ((FUZ_rand(seed) >> 3) & 32767)
-#define FUZ_RANDLENGTH ( ((FUZ_rand(seed) >> 7) & 3) ? (FUZ_rand(seed) % 14) : (FUZ_rand(seed) & 511) + 15)
+#define FUZ_RANDLENGTH ( ((FUZ_rand(seed) >> 7) & 3) ? (FUZ_rand(seed) % 15) : (FUZ_rand(seed) % 510) + 15)
void FUZ_fillCompressibleNoiseBuffer(void* buffer, int bufferSize, double proba, U32* seed)
{
BYTE* BBuffer = (BYTE*)buffer;
@@ -173,33 +174,9 @@ void FUZ_fillCompressibleNoiseBuffer(void* buffer, int bufferSize, double proba,
}
-// No longer useful; included into issue 134
-int FUZ_Issue52(void)
-{
- char* output;
- char* input;
- int i, r;
-
- // Overflow test, by Ludwig Strigeus
- printf("Overflow test (issue 52)...");
- input = (char*) malloc (20<<20);
- output = (char*) malloc (20<<20);
- input[0] = 0x0F;
- input[1] = 0x00;
- input[2] = 0x00;
- for(i = 3; i < 16840000; i++) input[i] = 0xff;
- r = LZ4_decompress_safe(input, output, 20<<20, 20<<20);
-
- free(input);
- free(output);
- printf(" Passed (return = %i < 0)\n",r);
- return 0;
-}
-
-
#define MAX_NB_BUFF_I134 150
#define BLOCKSIZE_I134 (32 MB)
-int FUZ_Issue134(void)
+int FUZ_AddressOverflow(void)
{
char* buffers[MAX_NB_BUFF_I134+1] = {0};
int i, nbBuff=0;
@@ -243,31 +220,31 @@ int FUZ_Issue134(void)
char* input = buffers[nbBuff-1];
char* output = buffers[nbBuff];
int r;
- input[0] = 0xF0; // Literal length overflow
- input[1] = 0xFF;
- input[2] = 0xFF;
- input[3] = 0xFF;
- for(i = 4; i <= nbOf255+4; i++) input[i] = 0xff;
+ input[0] = (char)0xF0; // Literal length overflow
+ input[1] = (char)0xFF;
+ input[2] = (char)0xFF;
+ input[3] = (char)0xFF;
+ for(i = 4; i <= nbOf255+4; i++) input[i] = (char)0xff;
r = LZ4_decompress_safe(input, output, nbOf255+64, BLOCKSIZE_I134);
if (r>0) goto _overflowError;
- input[0] = 0x1F; // Match length overflow
- input[1] = 0x01;
- input[2] = 0x01;
- input[3] = 0x00;
+ input[0] = (char)0x1F; // Match length overflow
+ input[1] = (char)0x01;
+ input[2] = (char)0x01;
+ input[3] = (char)0x00;
r = LZ4_decompress_safe(input, output, nbOf255+64, BLOCKSIZE_I134);
if (r>0) goto _overflowError;
output = buffers[nbBuff-2]; // Reverse in/out pointer order
- input[0] = 0xF0; // Literal length overflow
- input[1] = 0xFF;
- input[2] = 0xFF;
- input[3] = 0xFF;
+ input[0] = (char)0xF0; // Literal length overflow
+ input[1] = (char)0xFF;
+ input[2] = (char)0xFF;
+ input[3] = (char)0xFF;
r = LZ4_decompress_safe(input, output, nbOf255+64, BLOCKSIZE_I134);
if (r>0) goto _overflowError;
- input[0] = 0x1F; // Match length overflow
- input[1] = 0x01;
- input[2] = 0x01;
- input[3] = 0x00;
+ input[0] = (char)0x1F; // Match length overflow
+ input[1] = (char)0x01;
+ input[2] = (char)0x01;
+ input[3] = (char)0x00;
r = LZ4_decompress_safe(input, output, nbOf255+64, BLOCKSIZE_I134);
if (r>0) goto _overflowError;
}
@@ -762,8 +739,7 @@ int main(int argc, char** argv) {
printf("Seed = %u\n", seed);
if (proba!=FUZ_COMPRESSIBILITY_DEFAULT) printf("Compressibility : %i%%\n", proba);
- //FUZ_Issue52();
- FUZ_Issue134();
+ FUZ_AddressOverflow();
if (nbTests<=0) nbTests=1;
diff --git a/programs/lz4cli.c b/programs/lz4cli.c
index 1bbeda0..2d612e7 100644
--- a/programs/lz4cli.c
+++ b/programs/lz4cli.c
@@ -48,6 +48,10 @@
# pragma warning(disable : 4127) // disable: C4127: conditional expression is constant
#endif
+#ifdef __clang__
+# pragma clang diagnostic ignored "-Wunused-const-variable" // const variable one is really used !
+#endif
+
#define _FILE_OFFSET_BITS 64 // Large file support on 32-bits unix
#define _POSIX_SOURCE 1 // for fileno() within <stdio.h> on unix
@@ -91,7 +95,7 @@
#if defined(_MSC_VER) // Visual Studio
# define swap32 _byteswap_ulong
-#elif GCC_VERSION >= 403
+#elif (GCC_VERSION >= 403) || defined(__clang__)
# define swap32 __builtin_bswap32
#else
static inline unsigned int swap32(unsigned int x)
@@ -377,7 +381,7 @@ int main(int argc, char** argv)
case 'c': forceStdout=1; output_filename=stdoutmark; displayLevel=1; break;
// Test
- case 't': decode=1; output_filename=nulmark; break;
+ case 't': decode=1; LZ4IO_setOverwrite(1); output_filename=nulmark; break;
// Overwrite
case 'f': LZ4IO_setOverwrite(1); break;
diff --git a/programs/lz4io.c b/programs/lz4io.c
index 2715972..20520d6 100644
--- a/programs/lz4io.c
+++ b/programs/lz4io.c
@@ -233,7 +233,7 @@ int LZ4IO_setNotificationLevel(int level)
/* ************************************************************************ */
-/* ********************** LZ4 File / Stream compression ******************* */
+/* ********************** LZ4 File / Pipe compression ********************* */
/* ************************************************************************ */
static int LZ4S_GetBlockSize_FromBlockId (int id) { return (1 << (8 + (2 * id))); }
diff --git a/programs/xxhash.c b/xxhash.c
index be48370..be48370 100644
--- a/programs/xxhash.c
+++ b/xxhash.c
diff --git a/programs/xxhash.h b/xxhash.h
index 4311485..4311485 100644
--- a/programs/xxhash.h
+++ b/xxhash.h