From f3eca253222900bb7fa1e9a8d6c59e42551e5324 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 22 Oct 2015 15:31:46 +0100 Subject: [PATCH 01/37] quick first zstdhc version --- lib/zstd.c | 215 ++----------------- lib/zstd_static.h | 189 +++++++++++++++++ lib/zstdhc.c | 512 +++++++++++++++++++++++++++++++++++++++++++++ lib/zstdhc.h | 76 +++++++ programs/Makefile | 4 +- programs/bench.c | 90 ++++---- programs/fileio.c | 9 +- programs/fileio.h | 20 +- programs/zstdcli.c | 18 +- 9 files changed, 866 insertions(+), 267 deletions(-) create mode 100644 lib/zstdhc.c create mode 100644 lib/zstdhc.h diff --git a/lib/zstd.c b/lib/zstd.c index 37c67144b..6c3db75b0 100644 --- a/lib/zstd.c +++ b/lib/zstd.c @@ -130,12 +130,6 @@ static const U32 g_searchStrength = 8; #define WORKPLACESIZE (BLOCKSIZE*3) #define MINMATCH 4 -#define MLbits 7 -#define LLbits 6 -#define Offbits 5 -#define MaxML ((1<offset = ssPtr->offsetStart; @@ -205,7 +162,6 @@ void ZSTD_resetSeqStore(seqStore_t* ssPtr) ssPtr->dumps = ssPtr->dumpsStart; } - struct ZSTD_CCtx_s { const BYTE* base; @@ -231,7 +187,7 @@ void ZSTD_resetCCtx(ZSTD_CCtx* ctx) ctx->seqStore.litLengthStart = ctx->seqStore.litStart + BLOCKSIZE; ctx->seqStore.matchLengthStart = ctx->seqStore.litLengthStart + (BLOCKSIZE>>2); ctx->seqStore.dumpsStart = ctx->seqStore.matchLengthStart + (BLOCKSIZE>>2); - memset(ctx->hashTable, 0, HASH_TABLESIZE*4); + memset(ctx->hashTable, 0, sizeof(ctx->hashTable)); } ZSTD_CCtx* ZSTD_createCCtx(void) @@ -289,100 +245,6 @@ static unsigned ZSTD_highbit(U32 val) } -/* ************************************* -* Function body to include -***************************************/ -#include "mem.h" -static size_t ZSTD_read_ARCH(const void* p) { size_t r; memcpy(&r, p, sizeof(r)); return r; } - -MEM_STATIC unsigned ZSTD_NbCommonBytes (register size_t val) -{ - if (MEM_isLittleEndian()) - { - if (MEM_64bits()) - { -# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) - unsigned long r = 0; - _BitScanForward64( &r, (U64)val ); - return (int)(r>>3); -# elif defined(__GNUC__) && (__GNUC__ >= 3) && !defined(LZ4_FORCE_SW_BITCOUNT) - return (__builtin_ctzll((U64)val) >> 3); -# else - static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 }; - return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58]; -# endif - } - else /* 32 bits */ - { -# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) - unsigned long r; - _BitScanForward( &r, (U32)val ); - return (int)(r>>3); -# elif defined(__GNUC__) && (__GNUC__ >= 3) && !defined(LZ4_FORCE_SW_BITCOUNT) - return (__builtin_ctz((U32)val) >> 3); -# else - static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 }; - return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27]; -# endif - } - } - else /* Big Endian CPU */ - { - if (MEM_32bits()) - { -# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) - unsigned long r = 0; - _BitScanReverse64( &r, val ); - return (unsigned)(r>>3); -# elif defined(__GNUC__) && (__GNUC__ >= 3) && !defined(LZ4_FORCE_SW_BITCOUNT) - return (__builtin_clzll(val) >> 3); -# else - unsigned r; - const unsigned n32 = sizeof(size_t)*4; /* calculate this way due to compiler complaining in 32-bits mode */ - if (!(val>>n32)) { r=4; } else { r=0; val>>=n32; } - if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; } - r += (!val); - return r; -# endif - } - else /* 32 bits */ - { -# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) - unsigned long r = 0; - _BitScanReverse( &r, (unsigned long)val ); - return (unsigned)(r>>3); -# elif defined(__GNUC__) && (__GNUC__ >= 3) && !defined(LZ4_FORCE_SW_BITCOUNT) - return (__builtin_clz((U32)val) >> 3); -# else - unsigned r; - if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; } - r += (!val); - return r; -# endif - } - } -} - - -MEM_STATIC size_t ZSTD_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit) -{ - const BYTE* const pStart = pIn; - - while ((pIn> 6) + 1; } static size_t ZSTD_compressLiterals (void* dst, size_t maxDstSize, - const void* src, size_t srcSize) + const void* src, size_t srcSize) { const size_t minGain = ZSTD_minGain(srcSize); BYTE* const ostart = (BYTE*)dst; @@ -461,9 +323,9 @@ static size_t ZSTD_compressLiterals (void* dst, size_t maxDstSize, } -static size_t ZSTD_compressSequences(BYTE* dst, size_t maxDstSize, - const seqStore_t* seqStorePtr, - size_t srcSize) +size_t ZSTD_compressSequences(BYTE* dst, size_t maxDstSize, + const seqStore_t* seqStorePtr, + size_t srcSize) { U32 count[MaxSeq+1]; S16 norm[MaxSeq+1]; @@ -475,7 +337,6 @@ static size_t ZSTD_compressSequences(BYTE* dst, size_t maxDstSize, U32 CTable_MatchLength[FSE_CTABLE_SIZE_U32(MLFSELog, MaxML )]; U32 LLtype, Offtype, MLtype; /* compressed, raw or rle */ const BYTE* const op_lit_start = seqStorePtr->litStart; - const BYTE* op_lit = seqStorePtr->lit; const BYTE* const llTable = seqStorePtr->litLengthStart; const BYTE* const llPtr = seqStorePtr->litLength; const BYTE* const mlTable = seqStorePtr->matchLengthStart; @@ -492,7 +353,7 @@ static size_t ZSTD_compressSequences(BYTE* dst, size_t maxDstSize, /* Compress literals */ { size_t cSize; - size_t litSize = op_lit - op_lit_start; + size_t litSize = seqStorePtr->lit - op_lit_start; if (litSize <= LITERAL_NOENTROPY) cSize = ZSTD_compressRawLiteralsBlock(op, maxDstSize, op_lit_start, litSize); @@ -665,48 +526,6 @@ static size_t ZSTD_compressSequences(BYTE* dst, size_t maxDstSize, } -static void ZSTD_storeSeq(seqStore_t* seqStorePtr, size_t litLength, const BYTE* literals, size_t offset, size_t matchLength) -{ - BYTE* op_lit = seqStorePtr->lit; - BYTE* const l_end = op_lit + litLength; - - /* copy Literals */ - while (op_litlit += litLength; - - /* literal Length */ - if (litLength >= MaxLL) - { - *(seqStorePtr->litLength++) = MaxLL; - if (litLength<255 + MaxLL) - *(seqStorePtr->dumps++) = (BYTE)(litLength - MaxLL); - else - { - *(seqStorePtr->dumps++) = 255; - MEM_writeLE32(seqStorePtr->dumps, (U32)litLength); seqStorePtr->dumps += 3; - } - } - else *(seqStorePtr->litLength++) = (BYTE)litLength; - - /* match offset */ - *(seqStorePtr->offset++) = (U32)offset; - - /* match Length */ - if (matchLength >= MaxML) - { - *(seqStorePtr->matchLength++) = MaxML; - if (matchLength < 255+MaxML) - *(seqStorePtr->dumps++) = (BYTE)(matchLength - MaxML); - else - { - *(seqStorePtr->dumps++) = 255; - MEM_writeLE32(seqStorePtr->dumps, (U32)matchLength); seqStorePtr->dumps+=3; - } - } - else *(seqStorePtr->matchLength++) = (BYTE)matchLength; -} - - //static const U32 hashMask = (1<litSize = litSize; return 4; } + default: + return ERROR(corruption_detected); /* forbidden nominal case */ } } @@ -1343,8 +1163,8 @@ static size_t ZSTD_execSequence(BYTE* op, const BYTE* match = op - sequence.offset; /* check */ - if (sequence.offset > (size_t)op) return ERROR(corruption_detected); /* address space overflow test (this test seems kept by clang optimizer) */ //if (match > op) return ERROR(corruption_detected); /* address space overflow test (is clang optimizer removing this test ?) */ + if (sequence.offset > (size_t)op) return ERROR(corruption_detected); /* address space overflow test (this test seems kept by clang optimizer) */ if (match < base) return ERROR(corruption_detected); /* close range match, overlap */ @@ -1419,9 +1239,10 @@ static size_t ZSTD_decompressSequences( seqState_t seqState; memset(&sequence, 0, sizeof(sequence)); + sequence.offset = 4; seqState.dumps = dumps; seqState.dumpsEnd = dumps + dumpsLength; - seqState.prevOffset = 1; + seqState.prevOffset = 4; errorCode = BIT_initDStream(&(seqState.DStream), ip, iend-ip); if (ERR_isError(errorCode)) return ERROR(corruption_detected); FSE_initDState(&(seqState.stateLL), &(seqState.DStream), DTableLL); @@ -1447,7 +1268,7 @@ static size_t ZSTD_decompressSequences( size_t lastLLSize = litEnd - litPtr; if (litPtr > litEnd) return ERROR(corruption_detected); if (op+lastLLSize > oend) return ERROR(dstSize_tooSmall); - if (op != litPtr) memmove(op, litPtr, lastLLSize); + if (op != litPtr) memcpy(op, litPtr, lastLLSize); op += lastLLSize; } } @@ -1542,9 +1363,9 @@ size_t ZSTD_decompress(void* dst, size_t maxDstSize, const void* src, size_t src } -/******************************* +/* ****************************** * Streaming Decompression API -*******************************/ +********************************/ size_t ZSTD_resetDCtx(ZSTD_DCtx* dctx) { diff --git a/lib/zstd_static.h b/lib/zstd_static.h index dcdabdb25..6eacc5302 100644 --- a/lib/zstd_static.h +++ b/lib/zstd_static.h @@ -82,6 +82,195 @@ size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, co #include "error.h" +/* ************************************* +* Function body to include +***************************************/ +#include "mem.h" +static size_t ZSTD_read_ARCH(const void* p) { size_t r; memcpy(&r, p, sizeof(r)); return r; } + +MEM_STATIC unsigned ZSTD_NbCommonBytes (register size_t val) +{ + if (MEM_isLittleEndian()) + { + if (MEM_64bits()) + { +# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) + unsigned long r = 0; + _BitScanForward64( &r, (U64)val ); + return (int)(r>>3); +# elif defined(__GNUC__) && (__GNUC__ >= 3) && !defined(LZ4_FORCE_SW_BITCOUNT) + return (__builtin_ctzll((U64)val) >> 3); +# else + static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 }; + return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58]; +# endif + } + else /* 32 bits */ + { +# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) + unsigned long r; + _BitScanForward( &r, (U32)val ); + return (int)(r>>3); +# elif defined(__GNUC__) && (__GNUC__ >= 3) && !defined(LZ4_FORCE_SW_BITCOUNT) + return (__builtin_ctz((U32)val) >> 3); +# else + static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 }; + return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27]; +# endif + } + } + else /* Big Endian CPU */ + { + if (MEM_32bits()) + { +# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) + unsigned long r = 0; + _BitScanReverse64( &r, val ); + return (unsigned)(r>>3); +# elif defined(__GNUC__) && (__GNUC__ >= 3) && !defined(LZ4_FORCE_SW_BITCOUNT) + return (__builtin_clzll(val) >> 3); +# else + unsigned r; + const unsigned n32 = sizeof(size_t)*4; /* calculate this way due to compiler complaining in 32-bits mode */ + if (!(val>>n32)) { r=4; } else { r=0; val>>=n32; } + if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; } + r += (!val); + return r; +# endif + } + else /* 32 bits */ + { +# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) + unsigned long r = 0; + _BitScanReverse( &r, (unsigned long)val ); + return (unsigned)(r>>3); +# elif defined(__GNUC__) && (__GNUC__ >= 3) && !defined(LZ4_FORCE_SW_BITCOUNT) + return (__builtin_clz((U32)val) >> 3); +# else + unsigned r; + if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; } + r += (!val); + return r; +# endif + } + } +} + + +MEM_STATIC size_t ZSTD_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit) +{ + const BYTE* const pStart = pIn; + + while ((pInlit, literals, litLength); + seqStorePtr->lit += litLength; + + /* literal Length */ + if (litLength >= MaxLL) + { + *(seqStorePtr->litLength++) = MaxLL; + if (litLength<255 + MaxLL) + *(seqStorePtr->dumps++) = (BYTE)(litLength - MaxLL); + else + { + *(seqStorePtr->dumps++) = 255; + MEM_writeLE32(seqStorePtr->dumps, (U32)litLength); seqStorePtr->dumps += 3; + } + } + else *(seqStorePtr->litLength++) = (BYTE)litLength; + + /* match offset */ + *(seqStorePtr->offset++) = (U32)offsetCode; + + /* match Length */ + if (matchCode >= MaxML) + { + *(seqStorePtr->matchLength++) = MaxML; + if (matchCode < 255+MaxML) + *(seqStorePtr->dumps++) = (BYTE)(matchCode - MaxML); + else + { + *(seqStorePtr->dumps++) = 255; + MEM_writeLE32(seqStorePtr->dumps, (U32)matchCode); seqStorePtr->dumps += 3; + } + } + else *(seqStorePtr->matchLength++) = (BYTE)matchCode; +} + +size_t ZSTD_compressSequences(BYTE* dst, size_t maxDstSize, const seqStore_t* seqStorePtr, size_t srcSize); + #if defined (__cplusplus) } #endif diff --git a/lib/zstdhc.c b/lib/zstdhc.c new file mode 100644 index 000000000..a635e1afc --- /dev/null +++ b/lib/zstdhc.c @@ -0,0 +1,512 @@ +/* + ZSTD HC - High Compression Mode of Zstandard + Copyright (C) 2015, 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 : + - Zstd source repository : https://www.zstd.net +*/ + + +/* ************************************* +* Includes +***************************************/ +#include /* malloc */ +#include /* memset */ +#include "zstdhc.h" +#include "zstd_static.h" +#include "mem.h" + + +/* ************************************* +* Tuning Parameter +***************************************/ +static const U32 ZSTD_HC_compressionLevel_default = 9; + + +/* ************************************* +* Local Constants +***************************************/ +#define MINMATCH 4 +#define MAX_DISTANCE 65535 /* <=== To be changed (dynamic ?) */ + +#define DICTIONARY_LOGSIZE 16 +#define MAXD (1< g_maxCompressionLevel) compressionLevel = g_maxCompressionLevel; + memset(zc->hashTable, 0, sizeof(zc->hashTable)); + memset(zc->chainTable, 0xFF, sizeof(zc->chainTable)); + zc->nextToUpdate = 64 KB; + zc->base = start - 64 KB; + zc->end = start; + zc->dictBase = start - 64 KB; + zc->dictLimit = 64 KB; + zc->lowLimit = 64 KB; + zc->compressionLevel = compressionLevel; + zc->seqStore.buffer = zc->buffer; + zc->seqStore.offsetStart = (U32*) (zc->seqStore.buffer); + zc->seqStore.offCodeStart = (BYTE*) (zc->seqStore.offsetStart + (BLOCKSIZE>>2)); + zc->seqStore.litStart = zc->seqStore.offCodeStart + (BLOCKSIZE>>2); + zc->seqStore.litLengthStart = zc->seqStore.litStart + BLOCKSIZE; + zc->seqStore.matchLengthStart = zc->seqStore.litLengthStart + (BLOCKSIZE>>2); + zc->seqStore.dumpsStart = zc->seqStore.matchLengthStart + (BLOCKSIZE>>2); +} + +/* ************************************* +* Local Macros +***************************************/ +#define HASH_FUNCTION(u) (((u) * 2654435761U) >> ((MINMATCH*8)-HASH_LOG)) +//#define DELTANEXTU16(p) chainTable[(p) & MAXD_MASK] /* flexible, MAXD dependent */ +#define DELTANEXTU16(p) chainTable[(U16)(p)] /* faster */ + +static U32 ZSTD_HC_hashPtr(const void* ptr) { return HASH_FUNCTION(MEM_read32(ptr)); } + + +/* ************************************* +* HC Compression +***************************************/ +/* Update chains up to ip (excluded) */ +static void ZSTD_HC_insert (ZSTD_HC_CCtx* zc, const BYTE* ip) +{ + U16* chainTable = zc->chainTable; + U32* HashTable = zc->hashTable; + const BYTE* const base = zc->base; + const U32 target = (U32)(ip - base); + U32 idx = zc->nextToUpdate; + + while(idx < target) + { + U32 h = ZSTD_HC_hashPtr(base+idx); + size_t delta = idx - HashTable[h]; + if (delta>MAX_DISTANCE) delta = MAX_DISTANCE; + DELTANEXTU16(idx) = (U16)delta; + HashTable[h] = idx; + idx++; + } + + zc->nextToUpdate = target; +} + + +static size_t ZSTD_HC_insertAndFindBestMatch ( + ZSTD_HC_CCtx* zc, /* Index table will be updated */ + const BYTE* ip, const BYTE* const iLimit, + const BYTE** matchpos, + const U32 maxNbAttempts) +{ + U16* const chainTable = zc->chainTable; + U32* const HashTable = zc->hashTable; + const BYTE* const base = zc->base; + const BYTE* const dictBase = zc->dictBase; + const U32 dictLimit = zc->dictLimit; + const U32 lowLimit = (zc->lowLimit + 64 KB > (U32)(ip-base)) ? zc->lowLimit : (U32)(ip - base) - (64 KB - 1); + U32 matchIndex; + const BYTE* match; + int nbAttempts=maxNbAttempts; + size_t ml=0; + + /* HC4 match finder */ + ZSTD_HC_insert(zc, ip); + matchIndex = HashTable[ZSTD_HC_hashPtr(ip)]; + + while ((matchIndex>=lowLimit) && (nbAttempts)) + { + nbAttempts--; + if (matchIndex >= dictLimit) + { + match = base + matchIndex; + if (*(match+ml) == *(ip+ml) + && (MEM_read32(match) == MEM_read32(ip))) + { + const size_t mlt = ZSTD_count(ip+MINMATCH, match+MINMATCH, iLimit) + MINMATCH; + if (mlt > ml) { ml = mlt; *matchpos = match; } + } + } + else + { + match = dictBase + matchIndex; + if (MEM_read32(match) == MEM_read32(ip)) + { + size_t mlt; + const BYTE* vLimit = ip + (dictLimit - matchIndex); + if (vLimit > iLimit) vLimit = iLimit; + mlt = ZSTD_count(ip+MINMATCH, match+MINMATCH, vLimit) + MINMATCH; + if ((ip+mlt == vLimit) && (vLimit < iLimit)) + mlt += ZSTD_count(ip+mlt, base+dictLimit, iLimit); + if (mlt > ml) { ml = mlt; *matchpos = base + matchIndex; } /* virtual matchpos */ + } + } + matchIndex -= DELTANEXTU16(matchIndex); + } + + return ml; +} + + +size_t ZSTD_HC_InsertAndGetWiderMatch ( + ZSTD_HC_CCtx* zc, + const BYTE* const ip, + const BYTE* const iLowLimit, + const BYTE* const iHighLimit, + size_t longest, + const BYTE** matchpos, + const BYTE** startpos, + const int maxNbAttempts) +{ + U16* const chainTable = zc->chainTable; + U32* const HashTable = zc->hashTable; + const BYTE* const base = zc->base; + const U32 dictLimit = zc->dictLimit; + const BYTE* const lowPrefixPtr = base + dictLimit; + const U32 lowLimit = (zc->lowLimit + 64 KB > (U32)(ip-base)) ? zc->lowLimit : (U32)(ip - base) - (64 KB - 1); + const BYTE* const dictBase = zc->dictBase; + U32 matchIndex; + int nbAttempts = maxNbAttempts; + int delta = (int)(ip-iLowLimit); + + + /* First Match */ + ZSTD_HC_insert(zc, ip); + matchIndex = HashTable[ZSTD_HC_hashPtr(ip)]; + + while ((matchIndex>=lowLimit) && (nbAttempts)) + { + nbAttempts--; + if (matchIndex >= dictLimit) + { + const BYTE* matchPtr = base + matchIndex; + if (*(iLowLimit + longest) == *(matchPtr - delta + longest)) + if (MEM_read32(matchPtr) == MEM_read32(ip)) + { + size_t mlt = MINMATCH + ZSTD_count(ip+MINMATCH, matchPtr+MINMATCH, iHighLimit); + int back = 0; + + while ((ip+back>iLowLimit) + && (matchPtr+back > lowPrefixPtr) + && (ip[back-1] == matchPtr[back-1])) + back--; + + mlt -= back; + + if (mlt > longest) + { + longest = mlt; + *matchpos = matchPtr+back; + *startpos = ip+back; + } + } + } + else + { + const BYTE* matchPtr = dictBase + matchIndex; + if (MEM_read32(matchPtr) == MEM_read32(ip)) + { + size_t mlt; + int back=0; + const BYTE* vLimit = ip + (dictLimit - matchIndex); + if (vLimit > iHighLimit) vLimit = iHighLimit; + mlt = ZSTD_count(ip+MINMATCH, matchPtr+MINMATCH, vLimit) + MINMATCH; + if ((ip+mlt == vLimit) && (vLimit < iHighLimit)) + mlt += ZSTD_count(ip+mlt, base+dictLimit, iHighLimit); + while ((ip+back > iLowLimit) && (matchIndex+back > lowLimit) && (ip[back-1] == matchPtr[back-1])) back--; + mlt -= back; + if (mlt > longest) { longest = (int)mlt; *matchpos = base + matchIndex + back; *startpos = ip+back; } + } + } + matchIndex -= DELTANEXTU16(matchIndex); + } + + return longest; +} + + +static size_t ZSTD_HC_compressBlock(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize) +{ + seqStore_t* seqStorePtr = &(ctx->seqStore); + const BYTE* const istart = (const BYTE*)src; + const BYTE* ip = istart + 1; + const BYTE* anchor = istart; + const BYTE* const iend = istart + srcSize; + const BYTE* const ilimit = iend - 8; + + size_t offset_2=4, offset_1=4; + const U32 maxSearches = 1 << ctx->compressionLevel; + + /* init */ + ZSTD_resetSeqStore(seqStorePtr); + + /* Main Search Loop */ + while (ip < ilimit) + { + const BYTE* match; + size_t matchLength = ZSTD_HC_insertAndFindBestMatch(ctx, ip, ilimit, &match, maxSearches); + if (!matchLength) { ip++; continue; } + /* save match */ + { + size_t litLength = ip-anchor; + size_t offset = ip-match; + if (litLength) offset_2 = offset_1; + if (offset == offset_2) offset = 0; + offset_2 = offset_1; + offset_1 = ip-match; + ZSTD_storeSeq(seqStorePtr, litLength, anchor, offset, matchLength-MINMATCH); + ip += matchLength; + anchor = ip; + } + } + + /* Last Literals */ + { + size_t lastLLSize = iend - anchor; + memcpy(seqStorePtr->lit, anchor, lastLLSize); + seqStorePtr->lit += lastLLSize; + } + + /* Finale compression stage */ + return ZSTD_compressSequences((BYTE*)dst, maxDstSize, + seqStorePtr, srcSize); +} + +static size_t ZSTD_HC_compress_generic (ZSTD_HC_CCtx* ctxPtr, + void* dst, size_t maxDstSize, + const void* src, size_t srcSize) +{ + static const size_t blockSize = 128 KB; + size_t remaining = srcSize; + const BYTE* ip = (const BYTE*)src; + BYTE* const ostart = (BYTE*)dst; + BYTE* op = ostart; + BYTE* const oend = op + maxDstSize; + + while (remaining > blockSize) + { + size_t cSize = ZSTD_HC_compressBlock(ctxPtr, op+3, oend-op, ip, blockSize); + + if (cSize == 0) + { + cSize = ZSTD_noCompressBlock(op, maxDstSize, ip, blockSize); /* block is not compressible */ + } + else + { + op[0] = (BYTE)(cSize>>16); + op[1] = (BYTE)(cSize>>8); + op[2] = (BYTE)cSize; + op[0] += (BYTE)(bt_compressed << 6); /* is a compressed block */ + cSize += 3; + } + + remaining -= blockSize; + ip += blockSize; + op += cSize; + if (ZSTD_isError(cSize)) return cSize; + } + + /* last block */ + { + size_t cSize = ZSTD_HC_compressBlock(ctxPtr, op+3, oend-op, ip, remaining); + + if (cSize == 0) + { + cSize = ZSTD_noCompressBlock(op, maxDstSize, ip, remaining); /* block is not compressible */ + } + else + { + op[0] = (BYTE)(cSize>>16); + op[1] = (BYTE)(cSize>>8); + op[2] = (BYTE)cSize; + op[0] += (BYTE)(bt_compressed << 6); /* is a compressed block */ + cSize += 3; + } + + op += cSize; + if (ZSTD_isError(cSize)) return cSize; + } + + return op-ostart; +} + + +size_t ZSTD_HC_loadDict(ZSTD_HC_CCtx* ctx, const void* dictionary, size_t dictSize) +{ + /* TBD */ + (void)ctx; (void)dictionary; (void)dictSize; + return 0; +} + +static void ZSTD_HC_setExternalDict(ZSTD_HC_CCtx* ctxPtr, const void* newBlock) +{ + if (ctxPtr->end >= ctxPtr->base + 4) + ZSTD_HC_insert (ctxPtr, ctxPtr->end-3); /* Referencing remaining dictionary content */ + /* Only one memory segment for extDict, so any previous extDict is lost at this stage */ + ctxPtr->lowLimit = ctxPtr->dictLimit; + ctxPtr->dictLimit = (U32)(ctxPtr->end - ctxPtr->base); + ctxPtr->dictBase = ctxPtr->base; + ctxPtr->base = newBlock - ctxPtr->dictLimit; + ctxPtr->end = newBlock; + ctxPtr->nextToUpdate = ctxPtr->dictLimit; /* match referencing will resume from there */ +} + +size_t ZSTD_HC_compress_continue (ZSTD_HC_CCtx* ctxPtr, + void* dst, size_t dstSize, + const void* src, size_t srcSize) +{ + /* Check overflow */ + if ((size_t)(ctxPtr->end - ctxPtr->base) > 2 GB) + { + size_t dictSize = (size_t)(ctxPtr->end - ctxPtr->base) - ctxPtr->dictLimit; + if (dictSize > 64 KB) dictSize = 64 KB; + + ZSTD_HC_loadDict(ctxPtr, ctxPtr->end - dictSize, dictSize); + } + + /* Check if blocks follow each other */ + if ((const BYTE*)src != ctxPtr->end) + ZSTD_HC_setExternalDict(ctxPtr, (const BYTE*)src); + + /* Check overlapping src/dictionary space (typical of cycling buffers) */ + { + const BYTE* sourceEnd = (const BYTE*) src + srcSize; + const BYTE* dictBegin = ctxPtr->dictBase + ctxPtr->lowLimit; + const BYTE* dictEnd = ctxPtr->dictBase + ctxPtr->dictLimit; + if ((sourceEnd > dictBegin) && ((const BYTE*)src < dictEnd)) + { + if (sourceEnd > dictEnd) sourceEnd = dictEnd; + ctxPtr->lowLimit = (U32)(sourceEnd - ctxPtr->dictBase); + if (ctxPtr->dictLimit - ctxPtr->lowLimit < 4) ctxPtr->lowLimit = ctxPtr->dictLimit; + } + } + + return ZSTD_HC_compress_generic (ctxPtr, dst, dstSize, src, srcSize); +} + + +size_t ZSTD_HC_compressBegin(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, unsigned compressionLevel, const void* src) +{ + /* Sanity check */ + if (maxDstSize < 4) return ERROR(dstSize_tooSmall); + + /* Init */ + ZSTD_HC_resetCCtx(ctx, compressionLevel, src); + + /* Write Header */ + MEM_writeLE32(dst, ZSTD_magicNumber); + + return 4; +} + +size_t ZSTD_HC_compressCCtx (ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize, unsigned compressionLevel) +{ + BYTE* const ostart = (BYTE*)dst; + BYTE* op = ostart; + + /* Header */ + size_t oSize = ZSTD_HC_compressBegin(ctx, dst, maxDstSize, compressionLevel, src); + if(ZSTD_isError(oSize)) return oSize; + op += oSize; + maxDstSize -= oSize; + + /* body (compression) */ + op += ZSTD_HC_compress_generic (ctx, op, maxDstSize, src, srcSize); + if(ZSTD_isError(oSize)) return oSize; + op += oSize; + maxDstSize -= oSize; + + /* Close frame */ + oSize = ZSTD_compressEnd((ZSTD_CCtx*)ctx, op, maxDstSize); + if(ZSTD_isError(oSize)) return oSize; + op += oSize; + + return (op - ostart); +} + +size_t ZSTD_HC_compress(void* dst, size_t maxDstSize, const void* src, size_t srcSize, unsigned compressionLevel) +{ + ZSTD_HC_CCtx ctxBody; + return ZSTD_HC_compressCCtx(&ctxBody, dst, maxDstSize, src, srcSize, compressionLevel); +} + + + +/************************************** +* Streaming Functions +**************************************/ + + + +/* dictionary saving */ + +size_t ZSTD_HC_saveDict (ZSTD_HC_CCtx* ctx, void* safeBuffer, size_t dictSize) +{ + /* TBD */ + (void)ctx; (void)safeBuffer; (void)dictSize; + return 0; +} + diff --git a/lib/zstdhc.h b/lib/zstdhc.h new file mode 100644 index 000000000..e7053a849 --- /dev/null +++ b/lib/zstdhc.h @@ -0,0 +1,76 @@ +/* + zstdhc - high compression variant + Header File + Copyright (C) 2015, 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 : + - zstd source repository : http://www.zstd.net +*/ +#pragma once + +#if defined (__cplusplus) +extern "C" { +#endif + +/* ************************************* +* Includes +***************************************/ +#include /* size_t */ + + +/* ************************************* +* Simple function +***************************************/ +/** +ZSTD_HC_compress() : + Compresses 'srcSize' bytes from buffer 'src' into buffer 'dst', of maximum size 'dstSize'. + Destination buffer must be already allocated. + Compression runs faster if maxDstSize >= ZSTD_compressBound(srcSize). + @return : the number of bytes written into buffer 'dst' + or an error code if it fails (which can be tested using ZSTD_isError()) +*/ +size_t ZSTD_HC_compress(void* dst, size_t maxDstSize, + const void* src, size_t srcSize, + unsigned compressionLevel); + + +/* ************************************* +* Advanced functions +***************************************/ +typedef struct ZSTD_HC_CCtx_s ZSTD_HC_CCtx; /* incomplete type */ +ZSTD_HC_CCtx* ZSTD_HC_createCCtx(void); +size_t ZSTD_HC_freeCCtx(ZSTD_HC_CCtx* cctx); + +/** +ZSTD_HC_compressCCtx() : + Same as ZSTD_compress(), but requires a ZSTD_HC_CCtx working space already allocated +*/ +size_t ZSTD_HC_compressCCtx(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize, unsigned compressionLevel); + + +#if defined (__cplusplus) +} +#endif diff --git a/programs/Makefile b/programs/Makefile index bf7768c7a..7295425bc 100644 --- a/programs/Makefile +++ b/programs/Makefile @@ -30,7 +30,7 @@ # fullbench32: Same as fullbench, but forced to compile in 32-bits mode # ########################################################################## -VERSION?= v0.2.0 +VERSION?= 0.3.0 DESTDIR?= PREFIX ?= /usr/local @@ -58,7 +58,7 @@ default: zstd all: zstd zstd32 fullbench fullbench32 fuzzer fuzzer32 datagen -zstd : $(ZSTDDIR)/zstd.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legacy/zstd_v01.c xxhash.c bench.c fileio.c zstdcli.c +zstd : $(ZSTDDIR)/zstd.c $(ZSTDDIR)/zstdhc.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legacy/zstd_v01.c xxhash.c bench.c fileio.c zstdcli.c $(CC) $(FLAGS) $^ -o $@$(EXT) zstd32: $(ZSTDDIR)/zstd.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legacy/zstd_v01.c xxhash.c bench.c fileio.c zstdcli.c diff --git a/programs/bench.c b/programs/bench.c index 53ff5e9e9..86a536851 100644 --- a/programs/bench.c +++ b/programs/bench.c @@ -23,29 +23,29 @@ - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c */ -/*************************************** +/* ************************************** * Compiler Options -***************************************/ +****************************************/ /* Disable some Visual warning messages */ #define _CRT_SECURE_NO_WARNINGS /* fopen */ -// Unix Large Files support (>4GB) +/* Unix Large Files support (>4GB) */ #define _FILE_OFFSET_BITS 64 -#if (defined(__sun__) && (!defined(__LP64__))) // Sun Solaris 32-bits requires specific definitions +#if (defined(__sun__) && (!defined(__LP64__))) /* Sun Solaris 32-bits requires specific definitions */ # define _LARGEFILE_SOURCE -#elif ! defined(__LP64__) // No point defining Large file for 64 bit +#elif ! defined(__LP64__) /* No point defining Large file for 64 bit */ # define _LARGEFILE64_SOURCE #endif -// S_ISREG & gettimeofday() are not supported by MSVC +/* S_ISREG & gettimeofday() are not supported by MSVC */ #if defined(_MSC_VER) || defined(_WIN32) # define BMK_LEGACY_TIMER 1 #endif -/************************************** +/* ************************************* * Includes -**************************************/ +***************************************/ #include /* malloc, free */ #include /* memset */ #include // fprintf, fopen, ftello64 @@ -59,40 +59,23 @@ # include // gettimeofday #endif +#include "mem.h" #include "zstd.h" +#include "zstdhc.h" #include "xxhash.h" -/************************************** +/* ************************************* * Compiler specifics -**************************************/ +***************************************/ #if !defined(S_ISREG) # define S_ISREG(x) (((x) & S_IFMT) == S_IFREG) #endif -/************************************** -* Basic Types -**************************************/ -#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */ -# include - 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 NBLOOPS 3 #define TIMELOOP 2500 @@ -108,15 +91,15 @@ static U32 prime1 = 2654435761U; static U32 prime2 = 2246822519U; -/************************************** +/* ************************************* * Macros -**************************************/ +***************************************/ #define DISPLAY(...) fprintf(stderr, __VA_ARGS__) -/************************************** +/* ************************************* * Benchmark Parameters -**************************************/ +***************************************/ static int nbIterations = NBLOOPS; static size_t g_blockSize = 0; @@ -133,9 +116,9 @@ void BMK_SetBlockSize(size_t blockSize) } -/********************************************************* +/* ******************************************************** * Private functions -*********************************************************/ +**********************************************************/ #if defined(BMK_LEGACY_TIMER) @@ -176,10 +159,9 @@ static int BMK_GetMilliSpan( int nTimeStart ) } - -/********************************************************* +/* ******************************************************** * Data generator -*********************************************************/ +**********************************************************/ /* will hopefully be converted into ROL instruction by compiler */ static U32 BMK_rotl32(unsigned val32, unsigned nbBits) { return((val32 << nbBits) | (val32 >> (32 - nbBits))); } @@ -234,9 +216,9 @@ static void BMK_datagen(void* buffer, size_t bufferSize, double proba, U32 seed) } -/********************************************************* +/* ******************************************************** * Bench functions -*********************************************************/ +**********************************************************/ typedef struct { char* srcPtr; @@ -249,6 +231,14 @@ typedef struct } blockParam_t; +typedef size_t (*compressor_t) (void* dst, size_t maxDstSize, const void* src, size_t srcSize, unsigned compressionLevel); + +static size_t local_compress_fast (void* dst, size_t maxDstSize, const void* src, size_t srcSize, unsigned compressionLevel) +{ + (void)compressionLevel; + return ZSTD_compress(dst, maxDstSize, src, srcSize); +} + #define MIN(a,b) (a='0') && (*argument<='9')) + { + cLevel = 0; + while ((*argument >= '0') && (*argument <= '9')) + { + cLevel *= 10; + cLevel += *argument - '0'; + argument++; + } + continue; + } + switch(argument[0]) { /* Display help */ @@ -307,7 +321,7 @@ int main(int argc, char** argv) if (!strcmp(inFileName, stdinmark) && IS_CONSOLE(stdin) ) return badusage(programName); /* Check if benchmark is selected */ - if (bench) { BMK_benchFiles(argv+fileNameStart, nbFiles, 0); goto _end; } + if (bench) { BMK_benchFiles(argv+fileNameStart, nbFiles, cLevel); goto _end; } /* No output filename ==> try to select one automatically (when possible) */ while (!outFileName) @@ -351,7 +365,7 @@ int main(int argc, char** argv) if (decode) FIO_decompressFilename(outFileName, inFileName); else - FIO_compressFilename(outFileName, inFileName); + FIO_compressFilename(outFileName, inFileName, cLevel); _end: if (main_pause) waitEnter(); From eeb8ba18d17ad08f28705a45777f002dd9bd518a Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 22 Oct 2015 16:55:40 +0100 Subject: [PATCH 02/37] uncoupled maxdlog and chainlog --- lib/zstdhc.c | 58 +++++++++++++++++++++++------------------------ programs/Makefile | 2 +- programs/bench.c | 24 ++++++++------------ programs/fileio.c | 42 ++++++++++++++++++---------------- 4 files changed, 62 insertions(+), 64 deletions(-) diff --git a/lib/zstdhc.c b/lib/zstdhc.c index a635e1afc..73a22f5cc 100644 --- a/lib/zstdhc.c +++ b/lib/zstdhc.c @@ -52,17 +52,18 @@ static const U32 ZSTD_HC_compressionLevel_default = 9; * Local Constants ***************************************/ #define MINMATCH 4 -#define MAX_DISTANCE 65535 /* <=== To be changed (dynamic ?) */ +#define MAXD_LOG 19 +#define MAX_DISTANCE (1 << MAXD_LOG) /* <=== dynamic ? */ -#define DICTIONARY_LOGSIZE 16 -#define MAXD (1< g_maxCompressionLevel) compressionLevel = g_maxCompressionLevel; memset(zc->hashTable, 0, sizeof(zc->hashTable)); memset(zc->chainTable, 0xFF, sizeof(zc->chainTable)); - zc->nextToUpdate = 64 KB; - zc->base = start - 64 KB; - zc->end = start; - zc->dictBase = start - 64 KB; - zc->dictLimit = 64 KB; - zc->lowLimit = 64 KB; + zc->nextToUpdate = MAX_DISTANCE; + zc->end = (const BYTE*)start; + zc->base = zc->end - MAX_DISTANCE; + zc->dictBase = zc->base; + zc->dictLimit = MAX_DISTANCE; + zc->lowLimit = MAX_DISTANCE; zc->compressionLevel = compressionLevel; zc->seqStore.buffer = zc->buffer; zc->seqStore.offsetStart = (U32*) (zc->seqStore.buffer); @@ -124,8 +124,8 @@ static void ZSTD_HC_resetCCtx (ZSTD_HC_CCtx* zc, U32 compressionLevel, const BYT * Local Macros ***************************************/ #define HASH_FUNCTION(u) (((u) * 2654435761U) >> ((MINMATCH*8)-HASH_LOG)) -//#define DELTANEXTU16(p) chainTable[(p) & MAXD_MASK] /* flexible, MAXD dependent */ -#define DELTANEXTU16(p) chainTable[(U16)(p)] /* faster */ +//#define DELTANEXTU16(d) chainTable[(d) & MAXD_MASK] /* flexible, CHAINSIZE dependent */ +#define DELTANEXTU16(d) chainTable[(U16)(d)] /* faster, specific to CHAINLOG==16 */ static U32 ZSTD_HC_hashPtr(const void* ptr) { return HASH_FUNCTION(MEM_read32(ptr)); } @@ -167,7 +167,7 @@ static size_t ZSTD_HC_insertAndFindBestMatch ( const BYTE* const base = zc->base; const BYTE* const dictBase = zc->dictBase; const U32 dictLimit = zc->dictLimit; - const U32 lowLimit = (zc->lowLimit + 64 KB > (U32)(ip-base)) ? zc->lowLimit : (U32)(ip - base) - (64 KB - 1); + const U32 lowLimit = (zc->lowLimit + MAX_DISTANCE > (U32)(ip-base)) ? zc->lowLimit : (U32)(ip - base) - (MAX_DISTANCE - 1); U32 matchIndex; const BYTE* match; int nbAttempts=maxNbAttempts; @@ -204,6 +204,7 @@ static size_t ZSTD_HC_insertAndFindBestMatch ( if (mlt > ml) { ml = mlt; *matchpos = base + matchIndex; } /* virtual matchpos */ } } + if (base + matchIndex <= ip - CHAIN_SIZE) break; matchIndex -= DELTANEXTU16(matchIndex); } @@ -226,7 +227,7 @@ size_t ZSTD_HC_InsertAndGetWiderMatch ( const BYTE* const base = zc->base; const U32 dictLimit = zc->dictLimit; const BYTE* const lowPrefixPtr = base + dictLimit; - const U32 lowLimit = (zc->lowLimit + 64 KB > (U32)(ip-base)) ? zc->lowLimit : (U32)(ip - base) - (64 KB - 1); + const U32 lowLimit = (zc->lowLimit + MAX_DISTANCE > (U32)(ip-base)) ? zc->lowLimit : (U32)(ip - base) - (MAX_DISTANCE - 1); const BYTE* const dictBase = zc->dictBase; U32 matchIndex; int nbAttempts = maxNbAttempts; @@ -281,6 +282,8 @@ size_t ZSTD_HC_InsertAndGetWiderMatch ( if (mlt > longest) { longest = (int)mlt; *matchpos = base + matchIndex + back; *startpos = ip+back; } } } + if (base + matchIndex <= ip - CHAIN_SIZE) + matchIndex -= MAX_DISTANCE; /* ensures it gets eliminated on next test */ matchIndex -= DELTANEXTU16(matchIndex); } @@ -409,8 +412,8 @@ static void ZSTD_HC_setExternalDict(ZSTD_HC_CCtx* ctxPtr, const void* newBlock) ctxPtr->lowLimit = ctxPtr->dictLimit; ctxPtr->dictLimit = (U32)(ctxPtr->end - ctxPtr->base); ctxPtr->dictBase = ctxPtr->base; - ctxPtr->base = newBlock - ctxPtr->dictLimit; - ctxPtr->end = newBlock; + ctxPtr->base = (const BYTE*)newBlock - ctxPtr->dictLimit; + ctxPtr->end = (const BYTE*)newBlock; ctxPtr->nextToUpdate = ctxPtr->dictLimit; /* match referencing will resume from there */ } @@ -422,7 +425,7 @@ size_t ZSTD_HC_compress_continue (ZSTD_HC_CCtx* ctxPtr, if ((size_t)(ctxPtr->end - ctxPtr->base) > 2 GB) { size_t dictSize = (size_t)(ctxPtr->end - ctxPtr->base) - ctxPtr->dictLimit; - if (dictSize > 64 KB) dictSize = 64 KB; + if (dictSize > MAX_DISTANCE) dictSize = MAX_DISTANCE; ZSTD_HC_loadDict(ctxPtr, ctxPtr->end - dictSize, dictSize); } @@ -498,9 +501,6 @@ size_t ZSTD_HC_compress(void* dst, size_t maxDstSize, const void* src, size_t sr /************************************** * Streaming Functions **************************************/ - - - /* dictionary saving */ size_t ZSTD_HC_saveDict (ZSTD_HC_CCtx* ctx, void* safeBuffer, size_t dictSize) diff --git a/programs/Makefile b/programs/Makefile index 7295425bc..891c55f75 100644 --- a/programs/Makefile +++ b/programs/Makefile @@ -61,7 +61,7 @@ all: zstd zstd32 fullbench fullbench32 fuzzer fuzzer32 datagen zstd : $(ZSTDDIR)/zstd.c $(ZSTDDIR)/zstdhc.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legacy/zstd_v01.c xxhash.c bench.c fileio.c zstdcli.c $(CC) $(FLAGS) $^ -o $@$(EXT) -zstd32: $(ZSTDDIR)/zstd.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legacy/zstd_v01.c xxhash.c bench.c fileio.c zstdcli.c +zstd32: $(ZSTDDIR)/zstd.c $(ZSTDDIR)/zstdhc.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legacy/zstd_v01.c xxhash.c bench.c fileio.c zstdcli.c $(CC) -m32 $(FLAGS) $^ -o $@$(EXT) fullbench : $(ZSTDDIR)/zstd.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legacy/zstd_v01.c datagen.c fullbench.c diff --git a/programs/bench.c b/programs/bench.c index 86a536851..aed0a446d 100644 --- a/programs/bench.c +++ b/programs/bench.c @@ -48,15 +48,15 @@ ***************************************/ #include /* malloc, free */ #include /* memset */ -#include // fprintf, fopen, ftello64 -#include // stat64 -#include // stat64 +#include /* fprintf, fopen, ftello64 */ +#include /* stat64 */ +#include /* stat64 */ -// Use ftime() if gettimeofday() is not available on your target +/* Use ftime() if gettimeofday() is not available */ #if defined(BMK_LEGACY_TIMER) -# include // timeb, ftime +# include /* timeb, ftime */ #else -# include // gettimeofday +# include /* gettimeofday */ #endif #include "mem.h" @@ -249,13 +249,9 @@ static int BMK_benchMem(void* srcBuffer, size_t srcSize, const char* fileName, i const size_t maxCompressedSize = (size_t)nbBlocks * ZSTD_compressBound(blockSize); void* const compressedBuffer = malloc(maxCompressedSize); void* const resultBuffer = malloc(srcSize); - compressor_t compressor; + const compressor_t compressor = (cLevel <= 1) ? local_compress_fast : ZSTD_HC_compress; U64 crcOrig; - /* Init */ - if (cLevel <= 1) compressor = local_compress_fast; - else compressor = ZSTD_HC_compress; - /* Memory allocation & restrictions */ if (!compressedBuffer || !resultBuffer || !blockTable) { @@ -356,7 +352,7 @@ static int BMK_benchMem(void* srcBuffer, size_t srcSize, const char* fileName, i if (crcOrig!=crcCheck) { unsigned u; - unsigned eBlockSize = MIN(65536*2, blockSize); + unsigned eBlockSize = (unsigned)(MIN(65536*2, blockSize)); DISPLAY("\n!!! WARNING !!! %14s : Invalid Checksum : %x != %x\n", fileName, (unsigned)crcOrig, (unsigned)crcCheck); for (u=0; u on unix */ -/************************************** +/* ************************************* * Includes -**************************************/ +***************************************/ #include /* fprintf, fopen, fread, _fileno, stdin, stdout */ #include /* malloc, free */ #include /* strcmp, strlen */ @@ -69,12 +69,12 @@ #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT==1) # include "zstd_v01.h" /* legacy */ -#endif // ZSTD_LEGACY_SUPPORT +#endif -/************************************** +/* ************************************* * OS-specific Includes -**************************************/ +***************************************/ #if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__) # include /* _O_BINARY */ # include /* _setmode, _isatty */ @@ -90,9 +90,9 @@ #endif -/************************************** +/* ************************************* * Constants -**************************************/ +***************************************/ #define KB *(1U<<10) #define MB *(1U<<20) #define GB *(1U<<30) @@ -116,9 +116,9 @@ static const unsigned FIO_blockHeaderSize = 3; #define CACHELINE 64 -/************************************** +/* ************************************* * Macros -**************************************/ +***************************************/ #define DISPLAY(...) fprintf(stderr, __VA_ARGS__) #define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); } static U32 g_displayLevel = 2; /* 0 : no display; 1: errors; 2 : + result + interaction + warnings; 3 : + progression; 4 : + information */ @@ -131,19 +131,21 @@ static const unsigned refreshRate = 150; static clock_t g_time = 0; -/************************************** +/* ************************************* * Local Parameters -**************************************/ +***************************************/ static U32 g_overwrite = 0; void FIO_overwriteMode(void) { g_overwrite=1; } void FIO_setNotificationLevel(unsigned level) { g_displayLevel=level; } -/************************************** +/* ************************************* * Exceptions -**************************************/ -#define DEBUG 0 +***************************************/ +#ifndef DEBUG +# define DEBUG 0 +#endif #define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__); #define EXM_THROW(error, ...) \ { \ @@ -155,9 +157,9 @@ void FIO_setNotificationLevel(unsigned level) { g_displayLevel=level; } } -/************************************** +/* ************************************* * Functions -**************************************/ +***************************************/ static unsigned FIO_GetMilliSpan(clock_t nPrevious) { clock_t nCurrent = clock(); From fc60883d42f7f860d4573e34b466eca632d57966 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 23 Oct 2015 12:45:02 +0100 Subject: [PATCH 03/37] =?UTF-8?q?fixed=20issue=20#49,=20reported=20by=20Ha?= =?UTF-8?q?nno=20B=C3=B6ck=20(@hannob)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/huff0.c | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/huff0.c b/lib/huff0.c index 2200e5017..74c7a7be0 100644 --- a/lib/huff0.c +++ b/lib/huff0.c @@ -602,6 +602,7 @@ static size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats, /* get last non-null symbol weight (implied, total must be 2^n) */ tableLog = BIT_highbit32(weightTotal) + 1; + if (tableLog > HUF_ABSOLUTEMAX_TABLELOG) return ERROR(corruption_detected); { U32 total = 1 << tableLog; U32 rest = total - weightTotal; From 83fae977e6a993d032ad2ea2f821c2911065414b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 23 Oct 2015 15:21:53 +0100 Subject: [PATCH 04/37] Added asan tests --- .travis.yml | 5 +++-- Makefile | 10 ++++++++-- lib/zstd.c | 29 ++++++++++++++++++----------- programs/Makefile | 4 ++-- 4 files changed, 31 insertions(+), 17 deletions(-) diff --git a/.travis.yml b/.travis.yml index 501afe9fe..83a6f23a6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -16,8 +16,9 @@ env: - ZSTD_TRAVIS_CI_ENV=armtest - ZSTD_TRAVIS_CI_ENV=test - ZSTD_TRAVIS_CI_ENV="-C programs test32" - - ZSTD_TRAVIS_CI_ENV=sanitize - - ZSTD_TRAVIS_CI_ENV="-C programs memtest" + - ZSTD_TRAVIS_CI_ENV=usan + - ZSTD_TRAVIS_CI_ENV=asan + - ZSTD_TRAVIS_CI_ENV="-C programs valgrindTest" matrix: fast_finish: true diff --git a/Makefile b/Makefile index a5e6cf8b0..4d837af85 100644 --- a/Makefile +++ b/Makefile @@ -32,7 +32,7 @@ # ################################################################ # Version number -export VERSION := 0.2.0 +export VERSION := 0.3.0 PRGDIR = programs ZSTDDIR = lib @@ -83,7 +83,13 @@ armtest: clean $(MAKE) -C $(ZSTDDIR) -e all CC=arm-linux-gnueabi-gcc MOREFLAGS="-Werror" $(MAKE) -C $(PRGDIR) -e CC=arm-linux-gnueabi-gcc MOREFLAGS="-Werror" -sanitize: clean +usan: clean $(MAKE) test CC=clang MOREFLAGS="-g -fsanitize=undefined" +asan: clean + $(MAKE) test CC=clang MOREFLAGS="-g -fsanitize=address" + +uasan: clean + $(MAKE) test CC=clang MOREFLAGS="-g -fsanitize=address -fsanitize=undefined" + endif diff --git a/lib/zstd.c b/lib/zstd.c index 6c3db75b0..e947fb8f7 100644 --- a/lib/zstd.c +++ b/lib/zstd.c @@ -173,14 +173,14 @@ struct ZSTD_CCtx_s #else U32 hashTable[HASH_TABLESIZE]; #endif - BYTE buffer[WORKPLACESIZE]; + BYTE buffer[WORKPLACESIZE]; }; void ZSTD_resetCCtx(ZSTD_CCtx* ctx) { ctx->base = NULL; - ctx->seqStore.buffer = ctx->buffer; + ctx->seqStore.buffer = ctx->buffer; ctx->seqStore.offsetStart = (U32*) (ctx->seqStore.buffer); ctx->seqStore.offCodeStart = (BYTE*) (ctx->seqStore.offsetStart + (BLOCKSIZE>>2)); ctx->seqStore.litStart = ctx->seqStore.offCodeStart + (BLOCKSIZE>>2); @@ -850,7 +850,7 @@ struct ZSTD_DCtx_s const BYTE* litPtr; size_t litBufSize; size_t litSize; - BYTE litBuffer[BLOCKSIZE]; + BYTE litBuffer[BLOCKSIZE + 8 /* margin for wildcopy */]; }; /* typedef'd to ZSTD_Dctx within "zstd_static.h" */ @@ -916,22 +916,29 @@ size_t ZSTD_decodeLiteralsBlock(void* ctx, { case 0: { - size_t nbLiterals = BLOCKSIZE; - const size_t readSize = ZSTD_decompressLiterals(dctx->litBuffer, &nbLiterals, src, srcSize); + size_t litSize = BLOCKSIZE; + const size_t readSize = ZSTD_decompressLiterals(dctx->litBuffer, &litSize, src, srcSize); dctx->litPtr = dctx->litBuffer; dctx->litBufSize = BLOCKSIZE; - dctx->litSize = nbLiterals; + dctx->litSize = litSize; return readSize; /* works if it's an error too */ } case IS_RAW: { const size_t litSize = (MEM_readLE32(istart) & 0xFFFFFF) >> 2; /* no buffer issue : srcSize >= MIN_CBLOCK_SIZE */ - if (litSize > srcSize-3) return ERROR(corruption_detected); + if (litSize > srcSize-11) /* risk of reading too far with wildcopy */ + { + if (litSize > srcSize-3) return ERROR(corruption_detected); + memcpy(dctx->litBuffer, istart, litSize); + dctx->litBufSize = BLOCKSIZE; + dctx->litSize = litSize; + return litSize+3; + } + /* direct reference into compressed stream */ dctx->litPtr = istart+3; dctx->litBufSize = srcSize-3; dctx->litSize = litSize; - return litSize+3; - } + return litSize+3; } case IS_RLE: { const size_t litSize = (MEM_readLE32(istart) & 0xFFFFFF) >> 2; /* no buffer issue : srcSize >= MIN_CBLOCK_SIZE */ @@ -1151,7 +1158,7 @@ static size_t ZSTD_execSequence(BYTE* op, /* check */ if (oLitEnd > oend_8) return ERROR(dstSize_tooSmall); /* last match must start at a minimum distance of 8 from oend */ if (oMatchEnd > oend) return ERROR(dstSize_tooSmall); /* overwrite beyond dst buffer */ - if (litEnd > litLimit) return ERROR(corruption_detected); /* overRead beyond lit buffer */ + if (litEnd > litLimit-8) return ERROR(corruption_detected); /* overRead beyond lit buffer */ /* copy Literals */ ZSTD_wildcopy(op, *litPtr, sequence.litLength); /* note : oLitEnd <= oend-8 : no risk of overwrite beyond oend */ @@ -1311,7 +1318,7 @@ static size_t ZSTD_decompressDCtx(void* ctx, void* dst, size_t maxDstSize, const magicNumber = MEM_readLE32(src); #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT==1) if (magicNumber == ZSTDv01_magicNumberLE) return ZSTDv01_decompressDCtx(ctx, dst, maxDstSize, src, srcSize); -#endif /* ZSTD_LEGACY_SUPPORT */ +#endif if (magicNumber != ZSTD_magicNumber) return ERROR(prefix_unknown); ip += ZSTD_frameHeaderSize; remainingSize -= ZSTD_frameHeaderSize; diff --git a/programs/Makefile b/programs/Makefile index 891c55f75..be578c053 100644 --- a/programs/Makefile +++ b/programs/Makefile @@ -117,7 +117,7 @@ test: test-zstd test-fullbench test-fuzzer test32: test-zstd32 test-fullbench32 test-fuzzer32 -test-all: test test32 memtest +test-all: test test32 valgrindTest test-zstd: zstd datagen @echo "\n**** frame concatenation **** " @@ -159,7 +159,7 @@ test-fuzzer: fuzzer test-fuzzer32: fuzzer32 ./fuzzer32 -memtest: zstd datagen fuzzer fullbench +valgrindTest: zstd datagen fuzzer fullbench @echo "\n ---- valgrind tests : memory analyzer ----" valgrind --leak-check=yes --error-exitcode=1 ./datagen -g50M > $(VOID) ./datagen -g16KB > tmp From 563c6ba8cc8a982a24baca11f53398d6e2ef58ab Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 23 Oct 2015 17:07:34 +0100 Subject: [PATCH 05/37] reorder --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e04e37168..a9e76dcc4 100644 --- a/README.md +++ b/README.md @@ -18,8 +18,8 @@ For a taste of its performance, here are a few benchmark numbers, completed on a | [LZ4] HC r131 | 2.720 | 25 | 2100 | | QuickLZ 1.5.1b6| 2.237 | 370 | 415 | | LZO 2.06 | 2.106 | 400 | 580 | -| Snappy 1.1.0 | 2.091 | 330 | 1100 | | [LZ4] r131 | 2.101 | 450 | 2100 | +| Snappy 1.1.0 | 2.091 | 330 | 1100 | | LZF 3.6 | 2.077 | 200 | 560 | [zlib 1.2.8]:http://www.zlib.net/ From ed0a781246e35f023554bd980bce70e3e1113ed2 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 23 Oct 2015 19:25:06 +0100 Subject: [PATCH 06/37] repfirst --- lib/zstd.c | 19 ++++++++++--------- lib/zstd_static.h | 1 + lib/zstdhc.c | 44 +++++++++++++++++++++++++++++++------------- 3 files changed, 42 insertions(+), 22 deletions(-) diff --git a/lib/zstd.c b/lib/zstd.c index e947fb8f7..8493b43a7 100644 --- a/lib/zstd.c +++ b/lib/zstd.c @@ -904,22 +904,23 @@ static size_t ZSTD_decompressLiterals(void* dst, size_t* maxDstSizePtr, /** ZSTD_decodeLiteralsBlock @return : nb of bytes read from src (< srcSize )*/ size_t ZSTD_decodeLiteralsBlock(void* ctx, - const void* src, size_t srcSize) + const void* src, size_t srcSize) /* note : srcSize < BLOCKSIZE */ { ZSTD_DCtx* dctx = (ZSTD_DCtx*)ctx; - const BYTE* const istart = (const BYTE* const)src; + const BYTE* const istart = (const BYTE*) src; /* any compressed block with literals segment must be at least this size */ if (srcSize < MIN_CBLOCK_SIZE) return ERROR(corruption_detected); switch(*istart & 3) { + /* compressed */ case 0: { size_t litSize = BLOCKSIZE; const size_t readSize = ZSTD_decompressLiterals(dctx->litBuffer, &litSize, src, srcSize); dctx->litPtr = dctx->litBuffer; - dctx->litBufSize = BLOCKSIZE; + dctx->litBufSize = BLOCKSIZE+8; dctx->litSize = litSize; return readSize; /* works if it's an error too */ } @@ -930,7 +931,7 @@ size_t ZSTD_decodeLiteralsBlock(void* ctx, { if (litSize > srcSize-3) return ERROR(corruption_detected); memcpy(dctx->litBuffer, istart, litSize); - dctx->litBufSize = BLOCKSIZE; + dctx->litBufSize = BLOCKSIZE+8; dctx->litSize = litSize; return litSize+3; } @@ -945,7 +946,7 @@ size_t ZSTD_decodeLiteralsBlock(void* ctx, if (litSize > BLOCKSIZE) return ERROR(corruption_detected); memset(dctx->litBuffer, istart[3], litSize); dctx->litPtr = dctx->litBuffer; - dctx->litBufSize = BLOCKSIZE; + dctx->litBufSize = BLOCKSIZE+8; dctx->litSize = litSize; return 4; } @@ -1144,7 +1145,7 @@ static void ZSTD_decodeSequence(seq_t* seq, seqState_t* seqState) static size_t ZSTD_execSequence(BYTE* op, seq_t sequence, - const BYTE** litPtr, const BYTE* const litLimit, + const BYTE** litPtr, const BYTE* const litLimit_8, BYTE* const base, BYTE* const oend) { static const int dec32table[] = {0, 1, 2, 1, 4, 4, 4, 4}; /* added */ @@ -1158,7 +1159,7 @@ static size_t ZSTD_execSequence(BYTE* op, /* check */ if (oLitEnd > oend_8) return ERROR(dstSize_tooSmall); /* last match must start at a minimum distance of 8 from oend */ if (oMatchEnd > oend) return ERROR(dstSize_tooSmall); /* overwrite beyond dst buffer */ - if (litEnd > litLimit-8) return ERROR(corruption_detected); /* overRead beyond lit buffer */ + if (litEnd > litLimit_8) return ERROR(corruption_detected); /* overRead beyond lit buffer */ /* copy Literals */ ZSTD_wildcopy(op, *litPtr, sequence.litLength); /* note : oLitEnd <= oend-8 : no risk of overwrite beyond oend */ @@ -1224,7 +1225,7 @@ static size_t ZSTD_decompressSequences( BYTE* const oend = ostart + maxDstSize; size_t errorCode, dumpsLength; const BYTE* litPtr = dctx->litPtr; - const BYTE* const litMax = litPtr + dctx->litBufSize; + const BYTE* const litLimit_8 = litPtr + dctx->litBufSize - 8; const BYTE* const litEnd = litPtr + dctx->litSize; int nbSeq; const BYTE* dumps; @@ -1261,7 +1262,7 @@ static size_t ZSTD_decompressSequences( size_t oneSeqSize; nbSeq--; ZSTD_decodeSequence(&sequence, &seqState); - oneSeqSize = ZSTD_execSequence(op, sequence, &litPtr, litMax, base, oend); + oneSeqSize = ZSTD_execSequence(op, sequence, &litPtr, litLimit_8, base, oend); if (ZSTD_isError(oneSeqSize)) return oneSeqSize; op += oneSeqSize; } diff --git a/lib/zstd_static.h b/lib/zstd_static.h index 6eacc5302..d977cc8b0 100644 --- a/lib/zstd_static.h +++ b/lib/zstd_static.h @@ -219,6 +219,7 @@ typedef struct { void ZSTD_resetSeqStore(seqStore_t* ssPtr); +#define REPCODE_STARTVALUE 4 #define MLbits 7 #define LLbits 6 #define Offbits 5 diff --git a/lib/zstdhc.c b/lib/zstdhc.c index 73a22f5cc..ffd0581db 100644 --- a/lib/zstdhc.c +++ b/lib/zstdhc.c @@ -295,34 +295,52 @@ static size_t ZSTD_HC_compressBlock(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstS { seqStore_t* seqStorePtr = &(ctx->seqStore); const BYTE* const istart = (const BYTE*)src; - const BYTE* ip = istart + 1; + const BYTE* ip = istart; const BYTE* anchor = istart; const BYTE* const iend = istart + srcSize; const BYTE* const ilimit = iend - 8; - size_t offset_2=4, offset_1=4; + size_t offset_2=REPCODE_STARTVALUE, offset_1=REPCODE_STARTVALUE; const U32 maxSearches = 1 << ctx->compressionLevel; /* init */ ZSTD_resetSeqStore(seqStorePtr); + if (((ip-ctx->base) - ctx->dictLimit) < REPCODE_STARTVALUE) ip += REPCODE_STARTVALUE; - /* Main Search Loop */ + /* Match Loop */ while (ip < ilimit) { - const BYTE* match; - size_t matchLength = ZSTD_HC_insertAndFindBestMatch(ctx, ip, ilimit, &match, maxSearches); - if (!matchLength) { ip++; continue; } - /* save match */ + /* repcode */ + if (MEM_read32(ip) == MEM_read32(ip - offset_2)) + /* store sequence */ { + size_t matchLength = ZSTD_count(ip+4, ip+4-offset_2, iend); size_t litLength = ip-anchor; - size_t offset = ip-match; - if (litLength) offset_2 = offset_1; - if (offset == offset_2) offset = 0; + size_t offset = offset_2; offset_2 = offset_1; - offset_1 = ip-match; - ZSTD_storeSeq(seqStorePtr, litLength, anchor, offset, matchLength-MINMATCH); - ip += matchLength; + offset_1 = offset; + ZSTD_storeSeq(seqStorePtr, litLength, anchor, 0, matchLength); + ip += matchLength+MINMATCH; anchor = ip; + continue; + } + + /* search */ + { + const BYTE* match; + size_t matchLength = ZSTD_HC_insertAndFindBestMatch(ctx, ip, iend, &match, maxSearches); + if (!matchLength) { ip++; offset_2 = offset_1; continue; } + /* store sequence */ + { + size_t litLength = ip-anchor; + size_t offset = ip-match; + if (offset == offset_2) offset = 0; + offset_2 = offset_1; + offset_1 = ip-match; + ZSTD_storeSeq(seqStorePtr, litLength, anchor, offset, matchLength-MINMATCH); + ip += matchLength; + anchor = ip; + } } } From 53fff6cd9d633adf05e88349a46896c253c3cf9c Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sat, 24 Oct 2015 13:48:37 +0100 Subject: [PATCH 07/37] Individual memlog values --- lib/zstdhc.c | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/lib/zstdhc.c b/lib/zstdhc.c index ffd0581db..419a85dda 100644 --- a/lib/zstdhc.c +++ b/lib/zstdhc.c @@ -52,10 +52,10 @@ static const U32 ZSTD_HC_compressionLevel_default = 9; * Local Constants ***************************************/ #define MINMATCH 4 -#define MAXD_LOG 19 +#define MAXD_LOG 26 #define MAX_DISTANCE (1 << MAXD_LOG) /* <=== dynamic ? */ -#define CHAIN_LOG 16 +#define CHAIN_LOG 18 #define CHAIN_SIZE (1<> ((MINMATCH*8)-HASH_LOG)) -//#define DELTANEXTU16(d) chainTable[(d) & MAXD_MASK] /* flexible, CHAINSIZE dependent */ -#define DELTANEXTU16(d) chainTable[(U16)(d)] /* faster, specific to CHAINLOG==16 */ +//#define DELTANEXTU16(d) chainTable[(U16)(d)] /* faster, specific to CHAINLOG==16 */ +#define DELTANEXT(d) chainTable[(d) & CHAIN_MASK] /* flexible, CHAINSIZE dependent */ static U32 ZSTD_HC_hashPtr(const void* ptr) { return HASH_FUNCTION(MEM_read32(ptr)); } @@ -136,7 +136,7 @@ static U32 ZSTD_HC_hashPtr(const void* ptr) { return HASH_FUNCTION(MEM_read32(pt /* Update chains up to ip (excluded) */ static void ZSTD_HC_insert (ZSTD_HC_CCtx* zc, const BYTE* ip) { - U16* chainTable = zc->chainTable; + U32* chainTable = zc->chainTable; U32* HashTable = zc->hashTable; const BYTE* const base = zc->base; const U32 target = (U32)(ip - base); @@ -147,7 +147,7 @@ static void ZSTD_HC_insert (ZSTD_HC_CCtx* zc, const BYTE* ip) U32 h = ZSTD_HC_hashPtr(base+idx); size_t delta = idx - HashTable[h]; if (delta>MAX_DISTANCE) delta = MAX_DISTANCE; - DELTANEXTU16(idx) = (U16)delta; + DELTANEXT(idx) = (U32)delta; HashTable[h] = idx; idx++; } @@ -162,7 +162,7 @@ static size_t ZSTD_HC_insertAndFindBestMatch ( const BYTE** matchpos, const U32 maxNbAttempts) { - U16* const chainTable = zc->chainTable; + U32* const chainTable = zc->chainTable; U32* const HashTable = zc->hashTable; const BYTE* const base = zc->base; const BYTE* const dictBase = zc->dictBase; @@ -204,8 +204,9 @@ static size_t ZSTD_HC_insertAndFindBestMatch ( if (mlt > ml) { ml = mlt; *matchpos = base + matchIndex; } /* virtual matchpos */ } } + if (base + matchIndex <= ip - CHAIN_SIZE) break; - matchIndex -= DELTANEXTU16(matchIndex); + matchIndex -= DELTANEXT(matchIndex); } return ml; @@ -222,7 +223,7 @@ size_t ZSTD_HC_InsertAndGetWiderMatch ( const BYTE** startpos, const int maxNbAttempts) { - U16* const chainTable = zc->chainTable; + U32* const chainTable = zc->chainTable; U32* const HashTable = zc->hashTable; const BYTE* const base = zc->base; const U32 dictLimit = zc->dictLimit; @@ -284,7 +285,7 @@ size_t ZSTD_HC_InsertAndGetWiderMatch ( } if (base + matchIndex <= ip - CHAIN_SIZE) matchIndex -= MAX_DISTANCE; /* ensures it gets eliminated on next test */ - matchIndex -= DELTANEXTU16(matchIndex); + matchIndex -= DELTANEXT(matchIndex); } return longest; @@ -510,8 +511,10 @@ size_t ZSTD_HC_compressCCtx (ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, co size_t ZSTD_HC_compress(void* dst, size_t maxDstSize, const void* src, size_t srcSize, unsigned compressionLevel) { - ZSTD_HC_CCtx ctxBody; - return ZSTD_HC_compressCCtx(&ctxBody, dst, maxDstSize, src, srcSize, compressionLevel); + ZSTD_HC_CCtx* ctx = ZSTD_HC_createCCtx(); + size_t result = ZSTD_HC_compressCCtx(ctx, dst, maxDstSize, src, srcSize, compressionLevel); + ZSTD_HC_freeCCtx(ctx); + return result; } From 083fcc82fcf3a30ffcadbd90452345d4b0469385 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 25 Oct 2015 14:06:35 +0100 Subject: [PATCH 08/37] HC params --- lib/Makefile | 2 +- lib/zstd.h | 2 +- lib/zstd_static.h | 2 +- lib/zstdhc.c | 246 +++++++++++++++++++++----------------------- lib/zstdhc_static.h | 70 +++++++++++++ 5 files changed, 192 insertions(+), 130 deletions(-) create mode 100644 lib/zstdhc_static.h diff --git a/lib/Makefile b/lib/Makefile index e5afb9742..75d44c4a5 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -32,11 +32,11 @@ # ################################################################ # Version numbers -VERSION?= 0.1.2 LIBVER_MAJOR=`sed -n '/define ZSTD_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < zstd.h` LIBVER_MINOR=`sed -n '/define ZSTD_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < zstd.h` LIBVER_PATCH=`sed -n '/define ZSTD_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < zstd.h` LIBVER = $(LIBVER_MAJOR).$(LIBVER_MINOR).$(LIBVER_PATCH) +VERSION?= $(LIBVER) DESTDIR?= PREFIX ?= /usr/local diff --git a/lib/zstd.h b/lib/zstd.h index 3978776ce..789749b71 100644 --- a/lib/zstd.h +++ b/lib/zstd.h @@ -46,7 +46,7 @@ extern "C" { * Version ***************************************/ #define ZSTD_VERSION_MAJOR 0 /* for breaking interface changes */ -#define ZSTD_VERSION_MINOR 2 /* for new (non-breaking) interface capabilities */ +#define ZSTD_VERSION_MINOR 3 /* for new (non-breaking) interface capabilities */ #define ZSTD_VERSION_RELEASE 0 /* for tweaks, bug-fixes, or development */ #define ZSTD_VERSION_NUMBER (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE) unsigned ZSTD_versionNumber (void); diff --git a/lib/zstd_static.h b/lib/zstd_static.h index d977cc8b0..76315c3a8 100644 --- a/lib/zstd_static.h +++ b/lib/zstd_static.h @@ -73,7 +73,7 @@ size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, co /* ************************************* * Prefix - version detection ***************************************/ -#define ZSTD_magicNumber 0xFD2FB522 /* v0.2 (current)*/ +#define ZSTD_magicNumber 0xFD2FB523 /* v0.3 (current)*/ /* ************************************* diff --git a/lib/zstdhc.c b/lib/zstdhc.c index 419a85dda..3409a17b3 100644 --- a/lib/zstdhc.c +++ b/lib/zstdhc.c @@ -37,7 +37,7 @@ ***************************************/ #include /* malloc */ #include /* memset */ -#include "zstdhc.h" +#include "zstdhc_static.h" #include "zstd_static.h" #include "mem.h" @@ -53,17 +53,6 @@ static const U32 ZSTD_HC_compressionLevel_default = 9; ***************************************/ #define MINMATCH 4 #define MAXD_LOG 26 -#define MAX_DISTANCE (1 << MAXD_LOG) /* <=== dynamic ? */ - -#define CHAIN_LOG 18 -#define CHAIN_SIZE (1<hashTable = NULL; + ctx->chainTable = NULL; + ctx->hashTableLog = 0; + ctx->chainTableLog = 0; + return ctx; } -size_t ZSTD_HC_freeCCtx(ZSTD_HC_CCtx* cctx) { free(cctx); return 0; } - -static void ZSTD_HC_resetCCtx (ZSTD_HC_CCtx* zc, U32 compressionLevel, const void* start) +size_t ZSTD_HC_freeCCtx(ZSTD_HC_CCtx* cctx) { - if (compressionLevel==0) compressionLevel = ZSTD_HC_compressionLevel_default; - if (compressionLevel > g_maxCompressionLevel) compressionLevel = g_maxCompressionLevel; - memset(zc->hashTable, 0, sizeof(zc->hashTable)); - memset(zc->chainTable, 0xFF, sizeof(zc->chainTable)); - zc->nextToUpdate = MAX_DISTANCE; + free(cctx->hashTable); + free(cctx->chainTable); + free(cctx); + return 0; +} + +static void ZSTD_HC_resetCCtx_advanced (ZSTD_HC_CCtx* zc, + const ZSTD_HC_parameters params, const void* start) +{ + size_t maxDistance = ( 1 << params.searchLog) + 1; + + if (zc->hashTableLog < params.hashLog) + { + free(zc->hashTable); + zc->hashTableLog = params.hashLog; + zc->hashTable = (U32*) malloc ( (1 << zc->hashTableLog) * sizeof(U32) ); + } + memset(zc->hashTable, 0, (1 << params.hashLog) * sizeof(U32) ); + + if (zc->chainTableLog < params.chainLog) + { + free(zc->chainTable); + zc->chainTableLog = params.chainLog; + zc->chainTable = (U32*) malloc ( (1 << zc->chainTableLog) * sizeof(U32) ); + } + memset(zc->chainTable, 0, (1 << params.chainLog) * sizeof(U32) ); + + zc->nextToUpdate = maxDistance; zc->end = (const BYTE*)start; - zc->base = zc->end - MAX_DISTANCE; + zc->base = zc->end - maxDistance; zc->dictBase = zc->base; - zc->dictLimit = MAX_DISTANCE; - zc->lowLimit = MAX_DISTANCE; - zc->compressionLevel = compressionLevel; + zc->dictLimit = maxDistance; + zc->lowLimit = maxDistance; + zc->params = params; zc->seqStore.buffer = zc->buffer; zc->seqStore.offsetStart = (U32*) (zc->seqStore.buffer); zc->seqStore.offCodeStart = (BYTE*) (zc->seqStore.offsetStart + (BLOCKSIZE>>2)); @@ -120,14 +162,15 @@ static void ZSTD_HC_resetCCtx (ZSTD_HC_CCtx* zc, U32 compressionLevel, const voi zc->seqStore.dumpsStart = zc->seqStore.matchLengthStart + (BLOCKSIZE>>2); } + /* ************************************* * Local Macros ***************************************/ -#define HASH_FUNCTION(u) (((u) * 2654435761U) >> ((MINMATCH*8)-HASH_LOG)) -//#define DELTANEXTU16(d) chainTable[(U16)(d)] /* faster, specific to CHAINLOG==16 */ -#define DELTANEXT(d) chainTable[(d) & CHAIN_MASK] /* flexible, CHAINSIZE dependent */ +#define KNUTH 2654435761U +static U32 ZSTD_HC_hash(U32 u, U32 h) { return (u * KNUTH) >> (32-h) ; } +#define DELTANEXT(d) chainTable[(d) & chainMask] /* flexible, CHAINSIZE dependent */ -static U32 ZSTD_HC_hashPtr(const void* ptr) { return HASH_FUNCTION(MEM_read32(ptr)); } +static U32 ZSTD_HC_hashPtr(const void* ptr, U32 h) { return ZSTD_HC_hash(MEM_read32(ptr), h); } /* ************************************* @@ -136,19 +179,20 @@ static U32 ZSTD_HC_hashPtr(const void* ptr) { return HASH_FUNCTION(MEM_read32(pt /* Update chains up to ip (excluded) */ static void ZSTD_HC_insert (ZSTD_HC_CCtx* zc, const BYTE* ip) { - U32* chainTable = zc->chainTable; - U32* HashTable = zc->hashTable; + U32* const hashTable = zc->hashTable; + const U32 hashLog = zc->params.hashLog; + U32* const chainTable = zc->chainTable; + const U32 chainMask = (1 << zc->params.chainLog) - 1; const BYTE* const base = zc->base; const U32 target = (U32)(ip - base); U32 idx = zc->nextToUpdate; while(idx < target) { - U32 h = ZSTD_HC_hashPtr(base+idx); - size_t delta = idx - HashTable[h]; - if (delta>MAX_DISTANCE) delta = MAX_DISTANCE; + U32 h = ZSTD_HC_hashPtr(base+idx, hashLog); + size_t delta = idx - hashTable[h]; DELTANEXT(idx) = (U32)delta; - HashTable[h] = idx; + hashTable[h] = idx; idx++; } @@ -162,12 +206,16 @@ static size_t ZSTD_HC_insertAndFindBestMatch ( const BYTE** matchpos, const U32 maxNbAttempts) { + U32* const hashTable = zc->hashTable; + const U32 hashLog = zc->params.hashLog; U32* const chainTable = zc->chainTable; - U32* const HashTable = zc->hashTable; + const U32 chainSize = (1 << zc->params.chainLog); + const U32 chainMask = chainSize-1; const BYTE* const base = zc->base; const BYTE* const dictBase = zc->dictBase; const U32 dictLimit = zc->dictLimit; - const U32 lowLimit = (zc->lowLimit + MAX_DISTANCE > (U32)(ip-base)) ? zc->lowLimit : (U32)(ip - base) - (MAX_DISTANCE - 1); + const U32 maxDistance = (1 << zc->params.windowLog); + const U32 lowLimit = (zc->lowLimit + maxDistance > (U32)(ip-base)) ? zc->lowLimit : (U32)(ip - base) - (maxDistance - 1); U32 matchIndex; const BYTE* match; int nbAttempts=maxNbAttempts; @@ -175,7 +223,7 @@ static size_t ZSTD_HC_insertAndFindBestMatch ( /* HC4 match finder */ ZSTD_HC_insert(zc, ip); - matchIndex = HashTable[ZSTD_HC_hashPtr(ip)]; + matchIndex = hashTable[ZSTD_HC_hashPtr(ip, hashLog)]; while ((matchIndex>=lowLimit) && (nbAttempts)) { @@ -205,7 +253,7 @@ static size_t ZSTD_HC_insertAndFindBestMatch ( } } - if (base + matchIndex <= ip - CHAIN_SIZE) break; + if (base + matchIndex <= ip - chainSize) break; matchIndex -= DELTANEXT(matchIndex); } @@ -213,85 +261,6 @@ static size_t ZSTD_HC_insertAndFindBestMatch ( } -size_t ZSTD_HC_InsertAndGetWiderMatch ( - ZSTD_HC_CCtx* zc, - const BYTE* const ip, - const BYTE* const iLowLimit, - const BYTE* const iHighLimit, - size_t longest, - const BYTE** matchpos, - const BYTE** startpos, - const int maxNbAttempts) -{ - U32* const chainTable = zc->chainTable; - U32* const HashTable = zc->hashTable; - const BYTE* const base = zc->base; - const U32 dictLimit = zc->dictLimit; - const BYTE* const lowPrefixPtr = base + dictLimit; - const U32 lowLimit = (zc->lowLimit + MAX_DISTANCE > (U32)(ip-base)) ? zc->lowLimit : (U32)(ip - base) - (MAX_DISTANCE - 1); - const BYTE* const dictBase = zc->dictBase; - U32 matchIndex; - int nbAttempts = maxNbAttempts; - int delta = (int)(ip-iLowLimit); - - - /* First Match */ - ZSTD_HC_insert(zc, ip); - matchIndex = HashTable[ZSTD_HC_hashPtr(ip)]; - - while ((matchIndex>=lowLimit) && (nbAttempts)) - { - nbAttempts--; - if (matchIndex >= dictLimit) - { - const BYTE* matchPtr = base + matchIndex; - if (*(iLowLimit + longest) == *(matchPtr - delta + longest)) - if (MEM_read32(matchPtr) == MEM_read32(ip)) - { - size_t mlt = MINMATCH + ZSTD_count(ip+MINMATCH, matchPtr+MINMATCH, iHighLimit); - int back = 0; - - while ((ip+back>iLowLimit) - && (matchPtr+back > lowPrefixPtr) - && (ip[back-1] == matchPtr[back-1])) - back--; - - mlt -= back; - - if (mlt > longest) - { - longest = mlt; - *matchpos = matchPtr+back; - *startpos = ip+back; - } - } - } - else - { - const BYTE* matchPtr = dictBase + matchIndex; - if (MEM_read32(matchPtr) == MEM_read32(ip)) - { - size_t mlt; - int back=0; - const BYTE* vLimit = ip + (dictLimit - matchIndex); - if (vLimit > iHighLimit) vLimit = iHighLimit; - mlt = ZSTD_count(ip+MINMATCH, matchPtr+MINMATCH, vLimit) + MINMATCH; - if ((ip+mlt == vLimit) && (vLimit < iHighLimit)) - mlt += ZSTD_count(ip+mlt, base+dictLimit, iHighLimit); - while ((ip+back > iLowLimit) && (matchIndex+back > lowLimit) && (ip[back-1] == matchPtr[back-1])) back--; - mlt -= back; - if (mlt > longest) { longest = (int)mlt; *matchpos = base + matchIndex + back; *startpos = ip+back; } - } - } - if (base + matchIndex <= ip - CHAIN_SIZE) - matchIndex -= MAX_DISTANCE; /* ensures it gets eliminated on next test */ - matchIndex -= DELTANEXT(matchIndex); - } - - return longest; -} - - static size_t ZSTD_HC_compressBlock(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize) { seqStore_t* seqStorePtr = &(ctx->seqStore); @@ -302,7 +271,7 @@ static size_t ZSTD_HC_compressBlock(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstS const BYTE* const ilimit = iend - 8; size_t offset_2=REPCODE_STARTVALUE, offset_1=REPCODE_STARTVALUE; - const U32 maxSearches = 1 << ctx->compressionLevel; + const U32 maxSearches = 1 << ctx->params.searchLog; /* init */ ZSTD_resetSeqStore(seqStorePtr); @@ -440,11 +409,13 @@ size_t ZSTD_HC_compress_continue (ZSTD_HC_CCtx* ctxPtr, void* dst, size_t dstSize, const void* src, size_t srcSize) { + const U32 maxDistance = 1 << ctxPtr->params.windowLog; + /* Check overflow */ if ((size_t)(ctxPtr->end - ctxPtr->base) > 2 GB) { size_t dictSize = (size_t)(ctxPtr->end - ctxPtr->base) - ctxPtr->dictLimit; - if (dictSize > MAX_DISTANCE) dictSize = MAX_DISTANCE; + if (dictSize > maxDistance) dictSize = maxDistance; ZSTD_HC_loadDict(ctxPtr, ctxPtr->end - dictSize, dictSize); } @@ -470,13 +441,15 @@ size_t ZSTD_HC_compress_continue (ZSTD_HC_CCtx* ctxPtr, } -size_t ZSTD_HC_compressBegin(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, unsigned compressionLevel, const void* src) +size_t ZSTD_HC_compressBegin_advanced(ZSTD_HC_CCtx* ctx, + void* dst, size_t maxDstSize, + const ZSTD_HC_parameters params, const void* src) { /* Sanity check */ if (maxDstSize < 4) return ERROR(dstSize_tooSmall); /* Init */ - ZSTD_HC_resetCCtx(ctx, compressionLevel, src); + ZSTD_HC_resetCCtx_advanced(ctx, params, src); /* Write Header */ MEM_writeLE32(dst, ZSTD_magicNumber); @@ -484,13 +457,25 @@ size_t ZSTD_HC_compressBegin(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, un return 4; } -size_t ZSTD_HC_compressCCtx (ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize, unsigned compressionLevel) + +size_t ZSTD_HC_compressBegin(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, unsigned compressionLevel, const void* src) +{ + if (compressionLevel==0) compressionLevel = ZSTD_HC_compressionLevel_default; + if (compressionLevel > MAX_CLEVEL) compressionLevel = MAX_CLEVEL; + return ZSTD_HC_compressBegin_advanced(ctx, dst, maxDstSize, ZSTD_HC_defaultParameters[compressionLevel], src); +} + + +size_t ZSTD_HC_compress_advanced (ZSTD_HC_CCtx* ctx, + void* dst, size_t maxDstSize, + const void* src, size_t srcSize, + ZSTD_HC_parameters params) { BYTE* const ostart = (BYTE*)dst; BYTE* op = ostart; /* Header */ - size_t oSize = ZSTD_HC_compressBegin(ctx, dst, maxDstSize, compressionLevel, src); + size_t oSize = ZSTD_HC_compressBegin_advanced(ctx, dst, maxDstSize, params, src); if(ZSTD_isError(oSize)) return oSize; op += oSize; maxDstSize -= oSize; @@ -509,6 +494,13 @@ size_t ZSTD_HC_compressCCtx (ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, co return (op - ostart); } +size_t ZSTD_HC_compressCCtx (ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize, unsigned compressionLevel) +{ + if (compressionLevel==0) compressionLevel = ZSTD_HC_compressionLevel_default; + if (compressionLevel > MAX_CLEVEL) compressionLevel = MAX_CLEVEL; + return ZSTD_HC_compress_advanced(ctx, dst, maxDstSize, src, srcSize, ZSTD_HC_defaultParameters[compressionLevel]); +} + size_t ZSTD_HC_compress(void* dst, size_t maxDstSize, const void* src, size_t srcSize, unsigned compressionLevel) { ZSTD_HC_CCtx* ctx = ZSTD_HC_createCCtx(); diff --git a/lib/zstdhc_static.h b/lib/zstdhc_static.h new file mode 100644 index 000000000..80935ffcf --- /dev/null +++ b/lib/zstdhc_static.h @@ -0,0 +1,70 @@ +/* + zstdhc - high compression variant + Header File - Experimental API, static linking only + Copyright (C) 2015, 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 : + - zstd source repository : http://www.zstd.net +*/ +#pragma once + +#if defined (__cplusplus) +extern "C" { +#endif + +/* ************************************* +* Includes +***************************************/ +#include "mem.h" +#include "zstdhc.h" + + +/* ************************************* +* Types +***************************************/ +typedef struct +{ + U32 windowLog; /* largest match distance : impact decompression buffer size */ + U32 chainLog; /* full search distance : larger == more compression, slower, more memory*/ + U32 hashLog; /* dispatch table : larger == more memory, faster*/ + U32 searchLog; /* nb of searches : larger == more compression, slower*/ +} ZSTD_HC_parameters; + + +/* ************************************* +* Functions +***************************************/ +/** ZSTD_HC_compress_advanced +* Same as ZSTD_HC_compressCCtx(), but can fine-tune each compression parameter */ +size_t ZSTD_HC_compress_advanced (ZSTD_HC_CCtx* ctx, + void* dst, size_t maxDstSize, + const void* src, size_t srcSize, + ZSTD_HC_parameters params); + + +#if defined (__cplusplus) +} +#endif From 3a787da4198acaa5d2e844b416913b7f82e9e16e Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Sun, 25 Oct 2015 19:42:03 +0100 Subject: [PATCH 09/37] Fixed : minor clang warning --- lib/zstdhc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/zstdhc.c b/lib/zstdhc.c index 3409a17b3..71ff7a160 100644 --- a/lib/zstdhc.c +++ b/lib/zstdhc.c @@ -128,7 +128,7 @@ size_t ZSTD_HC_freeCCtx(ZSTD_HC_CCtx* cctx) static void ZSTD_HC_resetCCtx_advanced (ZSTD_HC_CCtx* zc, const ZSTD_HC_parameters params, const void* start) { - size_t maxDistance = ( 1 << params.searchLog) + 1; + U32 maxDistance = ( 1 << params.searchLog) + 1; if (zc->hashTableLog < params.hashLog) { From fd9d6b8e2fc9ad6f3d9faca986118e1cbec0a035 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 26 Oct 2015 00:06:36 +0100 Subject: [PATCH 10/37] paramgrill --- programs/fullbench.c | 2 +- programs/paramgrill.c | 737 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 738 insertions(+), 1 deletion(-) create mode 100644 programs/paramgrill.c diff --git a/programs/fullbench.c b/programs/fullbench.c index eeec11598..ef532361e 100644 --- a/programs/fullbench.c +++ b/programs/fullbench.c @@ -78,7 +78,7 @@ /************************************** * Constants **************************************/ -#define PROGRAM_DESCRIPTION "zStandard speed analyzer" +#define PROGRAM_DESCRIPTION "Zstandard speed analyzer" #ifndef ZSTD_VERSION # define ZSTD_VERSION "" #endif diff --git a/programs/paramgrill.c b/programs/paramgrill.c new file mode 100644 index 000000000..a02186a52 --- /dev/null +++ b/programs/paramgrill.c @@ -0,0 +1,737 @@ +/* + paramgrill.c - parameter tester for zstd_hc + Copyright (C) Yann Collet 2015 + + 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 : + - zstd source repository : https://github.com/Cyan4973/zstd + - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c +*/ + +/************************************** +* Compiler Options +**************************************/ +/* Disable some Visual warning messages */ +#define _CRT_SECURE_NO_WARNINGS +#define _CRT_SECURE_NO_DEPRECATE /* VS2005 */ + +/* Unix Large Files support (>4GB) */ +#if (defined(__sun__) && (!defined(__LP64__))) /* Sun Solaris 32-bits requires specific definitions */ +# define _LARGEFILE_SOURCE +# define _FILE_OFFSET_BITS 64 +#elif ! defined(__LP64__) /* No point defining Large file for 64 bit */ +# define _LARGEFILE64_SOURCE +#endif + +/* S_ISREG & gettimeofday() are not supported by MSVC */ +#if defined(_MSC_VER) || defined(_WIN32) +# define BMK_LEGACY_TIMER 1 +#endif + + +/************************************** +* Includes +**************************************/ +#include /* malloc */ +#include /* fprintf, fopen, ftello64 */ +#include /* stat64 */ +#include /* stat64 */ +#include /* strcmp */ + +/* Use ftime() if gettimeofday() is not available on your target */ +#if defined(BMK_LEGACY_TIMER) +# include /* timeb, ftime */ +#else +# include /* gettimeofday */ +#endif + +#include "mem.h" +#include "zstdhc_static.h" +#include "zstd.h" +#include "datagen.h" +#include "xxhash.h" + + +/************************************** +* Compiler Options +**************************************/ +/* S_ISREG & gettimeofday() are not supported by MSVC */ +#if !defined(S_ISREG) +# define S_ISREG(x) (((x) & S_IFMT) == S_IFREG) +#endif + + +/************************************** +* Constants +**************************************/ +#define PROGRAM_DESCRIPTION "ZSTD_HC parameters tester" +#ifndef ZSTD_VERSION +# define ZSTD_VERSION "" +#endif +#define AUTHOR "Yann Collet" +#define WELCOME_MESSAGE "*** %s %s %i-bits, by %s (%s) ***\n", PROGRAM_DESCRIPTION, ZSTD_VERSION, (int)(sizeof(void*)*8), AUTHOR, __DATE__ + + +#define KB *(1<<10) +#define MB *(1<<20) + +#define NBLOOPS 3 +#define TIMELOOP 2500 + +#define KNUTH 2654435761U +#define MAX_MEM (1984 MB) +#define DEFAULT_CHUNKSIZE (4<<20) + +#define COMPRESSIBILITY_DEFAULT 0.50 +static const size_t sampleSize = 10000000; + + +/************************************** +* Macros +**************************************/ +#define DISPLAY(...) fprintf(stderr, __VA_ARGS__) + + +/************************************** +* Benchmark Parameters +**************************************/ +static U32 nbIterations = NBLOOPS; +static double g_compressibility = COMPRESSIBILITY_DEFAULT; +static U32 g_blockSize = 0; + +void BMK_SetNbIterations(int nbLoops) +{ + nbIterations = nbLoops; + DISPLAY("- %u iterations -\n", nbIterations); +} + + +/********************************************************* +* Private functions +*********************************************************/ + +#if defined(BMK_LEGACY_TIMER) + +static int BMK_GetMilliStart(void) +{ + /* Based on Legacy ftime() + * Rolls over every ~ 12.1 days (0x100000/24/60/60) + * Use GetMilliSpan to correct for rollover */ + struct timeb tb; + int nCount; + ftime( &tb ); + nCount = (int) (tb.millitm + (tb.time & 0xfffff) * 1000); + return nCount; +} + +#else + +static int BMK_GetMilliStart(void) +{ + /* Based on newer gettimeofday() + * Use GetMilliSpan to correct for rollover */ + struct timeval tv; + int nCount; + gettimeofday(&tv, NULL); + nCount = (int) (tv.tv_usec/1000 + (tv.tv_sec & 0xfffff) * 1000); + return nCount; +} + +#endif + + +static int BMK_GetMilliSpan( int nTimeStart ) +{ + int nSpan = BMK_GetMilliStart() - nTimeStart; + if ( nSpan < 0 ) + nSpan += 0x100000 * 1000; + return nSpan; +} + + +static size_t BMK_findMaxMem(U64 requiredMem) +{ + size_t step = 64 MB; + BYTE* testmem=NULL; + + requiredMem = (((requiredMem >> 26) + 1) << 26); + if (requiredMem > MAX_MEM) requiredMem = MAX_MEM; + + requiredMem += 2*step; + while (!testmem) + { + requiredMem -= step; + testmem = (BYTE*) malloc ((size_t)requiredMem); + } + + free (testmem); + return (size_t) (requiredMem - step); +} + + +static U64 BMK_GetFileSize(char* infilename) +{ + int r; +#if defined(_MSC_VER) + struct _stat64 statbuf; + r = _stat64(infilename, &statbuf); +#else + struct stat statbuf; + r = stat(infilename, &statbuf); +#endif + if (r || !S_ISREG(statbuf.st_mode)) return 0; /* No good... */ + return (U64)statbuf.st_size; +} + +# define FUZ_rotl32(x,r) ((x << r) | (x >> (32 - r))) +U32 FUZ_rand(U32* src) +{ + const U32 prime1 = 2654435761U; + const U32 prime2 = 2246822519U; + U32 rand32 = *src; + rand32 *= prime1; + rand32 += prime2; + rand32 = FUZ_rotl32(rand32, 13); + *src = rand32; + return rand32 >> 5; +} + + +/********************************************************* +* Bench functions +*********************************************************/ +typedef struct { + size_t cSize; + U32 cSpeed; + U32 dSpeed; +} BMK_result_t; + +typedef struct +{ + const char* srcPtr; + size_t srcSize; + char* cPtr; + size_t cRoom; + size_t cSize; + char* resPtr; + size_t resSize; +} blockParam_t; + + +#define MIN(a,b) ( (a) < (b) ? (a) : (b) ) +static size_t BMK_benchParam(BMK_result_t* resultPtr, + const void* srcBuffer, size_t srcSize, + ZSTD_HC_CCtx* ctx, + const ZSTD_HC_parameters params) +{ + const size_t blockSize = g_blockSize ? g_blockSize : srcSize; + const U32 nbBlocks = (U32) ((srcSize + (blockSize-1)) / blockSize); + blockParam_t* const blockTable = (blockParam_t*) malloc(nbBlocks * sizeof(blockParam_t)); + const size_t maxCompressedSize = (size_t)nbBlocks * ZSTD_compressBound(blockSize); + void* const compressedBuffer = malloc(maxCompressedSize); + void* const resultBuffer = malloc(srcSize); + U32 Wlog = params.windowLog; + U32 Clog = params.chainLog; + U32 Hlog = params.hashLog; + U32 Slog = params.searchLog; + U64 crcOrig; + + /* Memory allocation & restrictions */ + if (!compressedBuffer || !resultBuffer || !blockTable) + { + DISPLAY("\nError: not enough memory!\n"); + free(compressedBuffer); + free(resultBuffer); + free(blockTable); + return 12; + } + + /* Calculating input Checksum */ + crcOrig = XXH64(srcBuffer, srcSize, 0); + + /* Init blockTable data */ + { + U32 i; + size_t remaining = srcSize; + const char* srcPtr = (const char*)srcBuffer; + char* cPtr = (char*)compressedBuffer; + char* resPtr = (char*)resultBuffer; + for (i=0; i\r", loopNb, Wlog, Clog, Hlog, Slog, (U32)srcSize); + memset(compressedBuffer, 0xE5, maxCompressedSize); + + nbLoops = 0; + milliTime = BMK_GetMilliStart(); + while (BMK_GetMilliStart() == milliTime); + milliTime = BMK_GetMilliStart(); + while (BMK_GetMilliSpan(milliTime) < TIMELOOP) + { + for (blockNb=0; blockNb", loopNb, Wlog, Clog, Hlog, Slog, (U32)srcSize); + DISPLAY(" %9u (%4.3f),%7.1f MB/s\r", (U32)cSize, ratio, (double)srcSize / fastestC / 1000.); + resultPtr->cSize = cSize; + resultPtr->cSpeed = (U32)((double)srcSize / fastestC); + +#if 1 + /* Decompression */ + memset(resultBuffer, 0xD6, srcSize); + + nbLoops = 0; + milliTime = BMK_GetMilliStart(); + while (BMK_GetMilliStart() == milliTime); + milliTime = BMK_GetMilliStart(); + for ( ; BMK_GetMilliSpan(milliTime) < TIMELOOP; nbLoops++) + { + for (blockNb=0; blockNb ", loopNb, Wlog, Clog, Hlog, Slog, (U32)srcSize); + DISPLAY("%9u (%4.3f),%7.1f MB/s, ", (U32)cSize, ratio, (double)srcSize / fastestC / 1000.); + DISPLAY("%7.1f MB/s\r", (double)srcSize / fastestD / 1000.); + resultPtr->dSpeed = (U32)((double)srcSize / fastestD); + + /* CRC Checking */ + crcCheck = XXH64(resultBuffer, srcSize, 0); + if (crcOrig!=crcCheck) + { + unsigned u; + unsigned eBlockSize = (unsigned)(MIN(65536*2, blockSize)); + DISPLAY("\n!!! WARNING !!! Invalid Checksum : %x != %x\n", (unsigned)crcOrig, (unsigned)crcCheck); + for (u=0; u W%02uC%02uH%02uS%02u \n", + cLevel, (double)srcSize / result.cSize, (double)result.cSpeed / 1000., + params.windowLog, params.chainLog, params.hashLog, params.searchLog); +} + + +#define CLEVEL_MAX 20 +typedef struct { + BMK_result_t result; + ZSTD_HC_parameters params; +} winnerInfo_t; + +static void BMK_printWinners(const winnerInfo_t* winners, size_t srcSize) +{ + int cLevel; + + DISPLAY("\nSelected configurations :\n"); + for (cLevel=0; cLevel < CLEVEL_MAX; cLevel++) + BMK_printWinner(cLevel, winners[cLevel].result, winners[cLevel].params, srcSize); + +} + +#define WINDOWLOG_MAX 26 +#define WINDOWLOG_MIN 17 +#define CHAINLOG_MAX WINDOWLOG_MAX +#define CHAINLOG_MIN 4 +#define HASHLOG_MAX (CHAINLOG_MAX+4) +#define HASHLOG_MIN 4 +#define SEARCHLOG_MAX CHAINLOG_MAX +#define SEARCHLOG_MIN 1 + +U32 g_cSpeedTarget[CLEVEL_MAX] = { 300000, 200000, 150000, 100000, 70000, 50000, 35000, 25000, 15000, 10000, /* 0 - 9 */ + 7000, 5000, 3500, 2500, 1500, 1000, 700, 500, 350, 250 }; /* 10 - 19 */ + +static void playAround(winnerInfo_t* winners, ZSTD_HC_parameters params, + const void* srcBuffer, size_t srcSize, + ZSTD_HC_CCtx* ctx) +{ + BMK_result_t testResult; + int better = 0; + int cLevel; + + BMK_benchParam(&testResult, srcBuffer, srcSize, ctx, params); + + for (cLevel = 0; cLevel < CLEVEL_MAX; cLevel++) + { + if ( (testResult.cSpeed > g_cSpeedTarget[cLevel]) + && ((winners[cLevel].result.cSize==0) || (winners[cLevel].result.cSize > testResult.cSize)) ) + { + better = 1; + winners[cLevel].result = testResult; + winners[cLevel].params = params; + BMK_printWinner(cLevel, testResult, params, srcSize); + } + } + + if (!better) return; + + BMK_printWinners(winners, srcSize); + + if (params.searchLog > SEARCHLOG_MIN) + { + params.searchLog--; + playAround(winners, params, srcBuffer, srcSize, ctx); + params.searchLog++; + } + + if (params.hashLog < HASHLOG_MAX) + { + params.hashLog++; + playAround(winners, params, srcBuffer, srcSize, ctx); + params.hashLog--; + } + + if (params.chainLog > CHAINLOG_MIN) + { + params.chainLog--; + playAround(winners, params, srcBuffer, srcSize, ctx); + params.chainLog++; + } + + if (params.windowLog > params.chainLog) + { + params.windowLog--; + playAround(winners, params, srcBuffer, srcSize, ctx); + params.windowLog++; + } + + if (params.windowLog < WINDOWLOG_MAX) + { + params.windowLog++; + playAround(winners, params, srcBuffer, srcSize, ctx); + params.windowLog--; + } + + if (params.chainLog < params.windowLog) + { + params.chainLog++; + playAround(winners, params, srcBuffer, srcSize, ctx); + params.chainLog--; + } + + if (params.hashLog > HASHLOG_MIN) + { + params.hashLog--; + playAround(winners, params, srcBuffer, srcSize, ctx); + params.hashLog++; + } + + if (params.searchLog < params.chainLog) + { + params.searchLog++; + playAround(winners, params, srcBuffer, srcSize, ctx); + params.searchLog--; + } + +} + +static void BMK_benchMem(void* srcBuffer, size_t srcSize) +{ + ZSTD_HC_CCtx* ctx = ZSTD_HC_createCCtx(); + ZSTD_HC_parameters params; + winnerInfo_t winners[CLEVEL_MAX]; + BMK_result_t testResult; + + /* init */ + memset(winners, 0, sizeof(winners)); + params.windowLog = 19; + params.chainLog = 18; + params.hashLog = 17; + params.searchLog = 9; + + /* set start config for level 9 */ + BMK_benchParam(&testResult, srcBuffer, srcSize, ctx, params); + + { + int i; + g_cSpeedTarget[9] = (testResult.cSpeed * 15) >> 4; + g_cSpeedTarget[1] = g_cSpeedTarget[9] << 4; + g_cSpeedTarget[0] = (g_cSpeedTarget[1] * 181) >> 7; /* sqrt2 */ + for (i=2; i> 8; + } + + /* establish speed objectives (relative to current platform) */ + playAround(winners, params, srcBuffer, srcSize, ctx); + + /* end summary */ + BMK_printWinners(winners, srcSize); + + /* clean up*/ + ZSTD_HC_freeCCtx(ctx); +} + + +static int benchSample(void) +{ + char* origBuff; + size_t benchedSize = sampleSize; + const char* name = "Sample 10MiB"; + + /* Allocation */ + origBuff = (char*) malloc((size_t)benchedSize); + if(!origBuff) + { + DISPLAY("\nError: not enough memory!\n"); + return 12; + } + + /* Fill buffer */ + RDG_genBuffer(origBuff, benchedSize, g_compressibility, 0.0, 0); + + /* bench */ + DISPLAY("\r%79s\r", ""); + DISPLAY("using %s %i%%: \n", name, (int)(g_compressibility*100)); + BMK_benchMem(origBuff, benchedSize); + + free(origBuff); + return 0; +} + + +int benchFiles(char** fileNamesTable, int nbFiles) +{ + int fileIdx=0; + + /* Loop for each file */ + while (fileIdx inFileSize) benchedSize = (size_t)inFileSize; + if (benchedSize < inFileSize) + { + DISPLAY("Not enough memory for '%s' full size; testing %i MB only...\n", inFileName, (int)(benchedSize>>20)); + } + + /* Alloc */ + origBuff = (char*) malloc((size_t)benchedSize); + if(!origBuff) + { + DISPLAY("\nError: not enough memory!\n"); + fclose(inFile); + return 12; + } + + /* Fill input buffer */ + DISPLAY("Loading %s... \r", inFileName); + readSize = fread(origBuff, 1, benchedSize, inFile); + fclose(inFile); + + if(readSize != benchedSize) + { + DISPLAY("\nError: problem reading file '%s' !! \n", inFileName); + free(origBuff); + return 13; + } + + /* bench */ + DISPLAY("\r%79s\r", ""); + DISPLAY("using %s : \n", inFileName); + BMK_benchMem(origBuff, benchedSize); + } + + return 0; +} + + +int usage(char* exename) +{ + DISPLAY( "Usage :\n"); + DISPLAY( " %s [arg] file\n", exename); + DISPLAY( "Arguments :\n"); + DISPLAY( " -H/-h : Help (this text + advanced options)\n"); + return 0; +} + +int usage_advanced(void) +{ + DISPLAY( "\nAdvanced options :\n"); + DISPLAY( " -i# : iteration loops [1-9](default : %i)\n", NBLOOPS); + DISPLAY( " -P# : sample compressibility (default : %.1f%%)\n", COMPRESSIBILITY_DEFAULT * 100); + return 0; +} + +int badusage(char* exename) +{ + DISPLAY("Wrong parameters\n"); + usage(exename); + return 0; +} + +int main(int argc, char** argv) +{ + int i, + filenamesStart=0, + result; + char* exename=argv[0]; + char* input_filename=0; + U32 main_pause = 0; + + /* Welcome message */ + DISPLAY(WELCOME_MESSAGE); + + if (argc<1) { badusage(exename); return 1; } + + for(i=1; i='0') && (argument[1] <='9')) + { + int iters = argument[1] - '0'; + BMK_SetNbIterations(iters); + argument++; + } + break; + + /* Sample compressibility (when no file provided) */ + case 'P': + { + U32 proba32 = 0; + while ((argument[1]>= '0') && (argument[1]<= '9')) + { + proba32 *= 10; + proba32 += argument[1] - '0'; + argument++; + } + g_compressibility = (double)proba32 / 100.; + } + break; + + /* Unknown command */ + default : badusage(exename); return 1; + } + } + continue; + } + + /* first provided filename is input */ + if (!input_filename) { input_filename=argument; filenamesStart=i; continue; } + } + + if (filenamesStart==0) + result = benchSample(); + else result = benchFiles(argv+filenamesStart, argc-filenamesStart); + + if (main_pause) { int unused; printf("press enter...\n"); unused = getchar(); (void)unused; } + + return result; +} + From 78d0f39605940c224e5ee4538e67bf741751812b Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 26 Oct 2015 00:07:32 +0100 Subject: [PATCH 11/37] make paramgrill --- programs/Makefile | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/programs/Makefile b/programs/Makefile index be578c053..94912316d 100644 --- a/programs/Makefile +++ b/programs/Makefile @@ -56,7 +56,7 @@ endif default: zstd -all: zstd zstd32 fullbench fullbench32 fuzzer fuzzer32 datagen +all: zstd zstd32 fullbench fullbench32 fuzzer fuzzer32 paramgrill datagen zstd : $(ZSTDDIR)/zstd.c $(ZSTDDIR)/zstdhc.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legacy/zstd_v01.c xxhash.c bench.c fileio.c zstdcli.c $(CC) $(FLAGS) $^ -o $@$(EXT) @@ -76,6 +76,9 @@ fuzzer : $(ZSTDDIR)/zstd.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legac fuzzer32: $(ZSTDDIR)/zstd.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legacy/zstd_v01.c datagen.c xxhash.c fuzzer.c $(CC) -m32 $(FLAGS) $^ -o $@$(EXT) +paramgrill : $(ZSTDDIR)/zstdhc.c $(ZSTDDIR)/zstd.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legacy/zstd_v01.c datagen.c xxhash.c paramgrill.c + $(CC) $(FLAGS) $^ -o $@$(EXT) + datagen : datagen.c datagencli.c $(CC) $(FLAGS) $^ -o $@$(EXT) From 0b87939dc08fc08c0f591d577958e495aef84f69 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 26 Oct 2015 00:11:16 +0100 Subject: [PATCH 12/37] clean paramgrill --- programs/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/programs/Makefile b/programs/Makefile index 94912316d..27e3e0e6a 100644 --- a/programs/Makefile +++ b/programs/Makefile @@ -87,7 +87,7 @@ clean: zstd$(EXT) zstd32$(EXT) \ fullbench$(EXT) fullbench32$(EXT) \ fuzzer$(EXT) fuzzer32$(EXT) \ - datagen$(EXT) + datagen$(EXT) paramgrill$(EXT) @echo Cleaning completed From b2ad30cea2a208742f1e786eebe084b6eeada762 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 26 Oct 2015 02:45:19 +0100 Subject: [PATCH 13/37] faster scan --- programs/paramgrill.c | 45 +++++++++++++++++++++++++++++++------------ 1 file changed, 33 insertions(+), 12 deletions(-) diff --git a/programs/paramgrill.c b/programs/paramgrill.c index a02186a52..1d221ab12 100644 --- a/programs/paramgrill.c +++ b/programs/paramgrill.c @@ -90,8 +90,8 @@ #define KB *(1<<10) #define MB *(1<<20) -#define NBLOOPS 3 -#define TIMELOOP 2500 +#define NBLOOPS 2 +#define TIMELOOP 2000 #define KNUTH 2654435761U #define MAX_MEM (1984 MB) @@ -392,7 +392,11 @@ static void BMK_printWinner(U32 cLevel, BMK_result_t result, ZSTD_HC_parameters } -#define CLEVEL_MAX 20 +#define CLEVEL_MAX 21 +static U32 g_cSpeedTarget[CLEVEL_MAX] = { 300000, 200000, 150000, 100000, 70000, 50000, 35000, 25000, 15000, 10000, /* 0 - 9 */ + 7000, 5000, 3500, 2500, 1500, 1000, 700, 500, 350, 250, /* 10 - 19 */ + 0 }; /* 20 */ + typedef struct { BMK_result_t result; ZSTD_HC_parameters params; @@ -412,13 +416,12 @@ static void BMK_printWinners(const winnerInfo_t* winners, size_t srcSize) #define WINDOWLOG_MIN 17 #define CHAINLOG_MAX WINDOWLOG_MAX #define CHAINLOG_MIN 4 -#define HASHLOG_MAX (CHAINLOG_MAX+4) +#define HASHLOG_MAX 28 #define HASHLOG_MIN 4 -#define SEARCHLOG_MAX CHAINLOG_MAX +#define SEARCHLOG_MAX (CHAINLOG_MAX-1) #define SEARCHLOG_MIN 1 -U32 g_cSpeedTarget[CLEVEL_MAX] = { 300000, 200000, 150000, 100000, 70000, 50000, 35000, 25000, 15000, 10000, /* 0 - 9 */ - 7000, 5000, 3500, 2500, 1500, 1000, 700, 500, 350, 250 }; /* 10 - 19 */ +#define MAX(a,b) ( (a) > (b) ? (a) : (b) ) static void playAround(winnerInfo_t* winners, ZSTD_HC_parameters params, const void* srcBuffer, size_t srcSize, @@ -428,6 +431,19 @@ static void playAround(winnerInfo_t* winners, ZSTD_HC_parameters params, int better = 0; int cLevel; + static BYTE g_alreadyTested[WINDOWLOG_MAX+1-WINDOWLOG_MIN] + [CHAINLOG_MAX+1-CHAINLOG_MIN] + [HASHLOG_MAX+1-HASHLOG_MIN] + [SEARCHLOG_MAX+1-SEARCHLOG_MIN] = {}; /* init to zero */ + static U32 g_rand = 1; + + /* exclude faster already played params */ + if (FUZ_rand(&g_rand) & ((1 << g_alreadyTested[params.windowLog-WINDOWLOG_MIN] + [params.chainLog-CHAINLOG_MIN] + [params.hashLog-HASHLOG_MIN] + [params.searchLog-SEARCHLOG_MIN]++)-1)) + return; + BMK_benchParam(&testResult, srcBuffer, srcSize, ctx, params); for (cLevel = 0; cLevel < CLEVEL_MAX; cLevel++) @@ -467,7 +483,7 @@ static void playAround(winnerInfo_t* winners, ZSTD_HC_parameters params, params.chainLog++; } - if (params.windowLog > params.chainLog) + if (params.windowLog > MAX(WINDOWLOG_MIN, params.chainLog)) { params.windowLog--; playAround(winners, params, srcBuffer, srcSize, ctx); @@ -513,24 +529,29 @@ static void BMK_benchMem(void* srcBuffer, size_t srcSize) /* init */ memset(winners, 0, sizeof(winners)); + + /* baseline config for level 9 */ params.windowLog = 19; params.chainLog = 18; params.hashLog = 17; params.searchLog = 9; - - /* set start config for level 9 */ BMK_benchParam(&testResult, srcBuffer, srcSize, ctx, params); + /* establish speed objectives (relative to current platform) */ { int i; g_cSpeedTarget[9] = (testResult.cSpeed * 15) >> 4; g_cSpeedTarget[1] = g_cSpeedTarget[9] << 4; g_cSpeedTarget[0] = (g_cSpeedTarget[1] * 181) >> 7; /* sqrt2 */ - for (i=2; i> 8; } - /* establish speed objectives (relative to current platform) */ + /* start from fast conf */ + params.windowLog = WINDOWLOG_MIN; + params.chainLog = CHAINLOG_MIN; + params.hashLog = 12; + params.searchLog = SEARCHLOG_MIN; playAround(winners, params, srcBuffer, srcSize, ctx); /* end summary */ From 786f5b554a7b6d810af800ef640bde11089f6592 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 26 Oct 2015 15:45:58 +0100 Subject: [PATCH 14/37] skip slow conf faster --- lib/zstdhc.c | 31 +---- lib/zstdhc_static.h | 30 +++++ programs/paramgrill.c | 278 +++++++++++++++++++++++++----------------- 3 files changed, 197 insertions(+), 142 deletions(-) diff --git a/lib/zstdhc.c b/lib/zstdhc.c index 71ff7a160..1671f4265 100644 --- a/lib/zstdhc.c +++ b/lib/zstdhc.c @@ -64,31 +64,6 @@ static const U32 ZSTD_HC_compressionLevel_default = 9; #define BLOCKSIZE (128 KB) /* define, for static allocation */ #define WORKPLACESIZE (BLOCKSIZE*3) -#define MAX_CLEVEL 20 -static const ZSTD_HC_parameters ZSTD_HC_defaultParameters[MAX_CLEVEL] = { - /* W, C, H, S */ - { 19, 18, 17 , 1}, - { 19, 18, 17 , 1}, - { 19, 18, 17 , 2}, - { 19, 18, 17 , 3}, - { 19, 18, 17 , 4}, - { 19, 18, 17 , 5}, - { 19, 18, 17 , 6}, - { 19, 18, 17 , 7}, - { 19, 18, 17 , 8}, - { 19, 18, 17 , 9}, - { 19, 18, 17 ,10}, - { 19, 18, 17 ,11}, - { 19, 18, 17 ,12}, - { 19, 18, 17 ,13}, - { 19, 18, 17 ,14}, - { 19, 18, 17 ,15}, - { 19, 18, 17 ,16}, - { 19, 18, 17 ,17}, - { 19, 18, 17 ,18}, - { 19, 18, 17 ,19}, -}; - struct ZSTD_HC_CCtx_s { const BYTE* end; /* next block here to continue on current prefix */ @@ -461,7 +436,7 @@ size_t ZSTD_HC_compressBegin_advanced(ZSTD_HC_CCtx* ctx, size_t ZSTD_HC_compressBegin(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, unsigned compressionLevel, const void* src) { if (compressionLevel==0) compressionLevel = ZSTD_HC_compressionLevel_default; - if (compressionLevel > MAX_CLEVEL) compressionLevel = MAX_CLEVEL; + if (compressionLevel > ZSTD_HC_MAX_CLEVEL) compressionLevel = ZSTD_HC_MAX_CLEVEL; return ZSTD_HC_compressBegin_advanced(ctx, dst, maxDstSize, ZSTD_HC_defaultParameters[compressionLevel], src); } @@ -496,8 +471,8 @@ size_t ZSTD_HC_compress_advanced (ZSTD_HC_CCtx* ctx, size_t ZSTD_HC_compressCCtx (ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize, unsigned compressionLevel) { - if (compressionLevel==0) compressionLevel = ZSTD_HC_compressionLevel_default; - if (compressionLevel > MAX_CLEVEL) compressionLevel = MAX_CLEVEL; + if (compressionLevel==0) return ZSTD_compress(dst, maxDstSize, src, srcSize); /* fast mode */ + if (compressionLevel > ZSTD_HC_MAX_CLEVEL) compressionLevel = ZSTD_HC_MAX_CLEVEL; return ZSTD_HC_compress_advanced(ctx, dst, maxDstSize, src, srcSize, ZSTD_HC_defaultParameters[compressionLevel]); } diff --git a/lib/zstdhc_static.h b/lib/zstdhc_static.h index 80935ffcf..26d910fad 100644 --- a/lib/zstdhc_static.h +++ b/lib/zstdhc_static.h @@ -65,6 +65,36 @@ size_t ZSTD_HC_compress_advanced (ZSTD_HC_CCtx* ctx, ZSTD_HC_parameters params); +/* ************************************* +* Pre-defined compression levels +***************************************/ +#define ZSTD_HC_MAX_CLEVEL 20 +static const ZSTD_HC_parameters ZSTD_HC_defaultParameters[ZSTD_HC_MAX_CLEVEL+1] = { + /* W, C, H, S */ + { 18, 4, 12, 1 }, /* 0 - should never be used */ + { 18, 10, 14, 1 }, /* 1 */ + { 18, 13, 15, 1 }, /* 2 */ + { 20, 18, 19, 2 }, /* 3 */ + { 21, 19, 20, 3 }, /* 4 */ + { 21, 19, 21, 4 }, /* 5 */ + { 21, 19, 21, 5 }, /* 6 */ + { 21, 21, 21, 5 }, /* 7 */ + { 21, 21, 21, 6 }, /* 8 */ + { 21, 21, 21, 7 }, /* 9 */ + { 21, 21, 21, 8 }, /*10 */ + { 21, 21, 21, 9 }, /*11 */ + { 21, 21, 21, 10 }, /*12 */ + { 21, 21, 21, 11 }, /*13 */ + { 21, 21, 21, 13 }, /*14 */ + { 21, 21, 21, 17 }, /*15 */ + { 22, 22, 22, 18 }, /*16 */ + { 23, 23, 23, 19 }, /*17 */ + { 24, 24, 24, 20 }, /*18 */ + { 25, 25, 25, 21 }, /*19 */ + { 26, 26, 26, 25 }, /*20 - ultra-slow */ +}; + + #if defined (__cplusplus) } #endif diff --git a/programs/paramgrill.c b/programs/paramgrill.c index 1d221ab12..24eba9253 100644 --- a/programs/paramgrill.c +++ b/programs/paramgrill.c @@ -100,6 +100,10 @@ #define COMPRESSIBILITY_DEFAULT 0.50 static const size_t sampleSize = 10000000; +static const int g_grillDuration = 30000000; /* about 8.5 hours */ +static const int g_maxParamTime = 15000; /* 15 sec */ +static const int g_maxVariationTime = 60000; /* 60 sec */ +static const int g_maxNbVariations = 32; /************************************** * Macros @@ -113,6 +117,7 @@ static const size_t sampleSize = 10000000; static U32 nbIterations = NBLOOPS; static double g_compressibility = COMPRESSIBILITY_DEFAULT; static U32 g_blockSize = 0; +static U32 g_rand = 1; void BMK_SetNbIterations(int nbLoops) { @@ -296,6 +301,7 @@ static size_t BMK_benchParam(BMK_result_t* resultPtr, double fastestC = 100000000., fastestD = 100000000.; double ratio = 0.; U64 crcCheck = 0; + const int startTime =BMK_GetMilliStart(); DISPLAY("\r%79s\r", ""); for (loopNb = 1; loopNb <= nbIterations; loopNb++) @@ -303,6 +309,10 @@ static size_t BMK_benchParam(BMK_result_t* resultPtr, int nbLoops; int milliTime; U32 blockNb; + const int totalTime = BMK_GetMilliSpan(startTime); + + /* early break (slow params) */ + if (totalTime > g_maxParamTime) break; /* Compression */ DISPLAY("%1u-W%02uC%02uH%02uS%02u : %9u ->\r", loopNb, Wlog, Clog, Hlog, Slog, (U32)srcSize); @@ -316,9 +326,9 @@ static size_t BMK_benchParam(BMK_result_t* resultPtr, { for (blockNb=0; blockNb W%02uC%02uH%02uS%02u \n", + fprintf(f, + "level %2u: R:%5.3f at %5.1f MB/s => W%02uC%02uH%02uS%02u \n", cLevel, (double)srcSize / result.cSize, (double)result.cSpeed / 1000., params.windowLog, params.chainLog, params.hashLog, params.searchLog); + } -#define CLEVEL_MAX 21 -static U32 g_cSpeedTarget[CLEVEL_MAX] = { 300000, 200000, 150000, 100000, 70000, 50000, 35000, 25000, 15000, 10000, /* 0 - 9 */ - 7000, 5000, 3500, 2500, 1500, 1000, 700, 500, 350, 250, /* 10 - 19 */ - 0 }; /* 20 */ +static U32 g_cSpeedTarget[ZSTD_HC_MAX_CLEVEL+1] = { + 300000, 200000, 150000, 100000, 70000, 50000, 35000, 25000, 15000, 10000, /* 0 - 9 */ + 7000, 5000, 3500, 2500, 1500, 1000, 700, 500, 350, 250, /* 10 - 19 */ + 0 }; /* 20 */ typedef struct { BMK_result_t result; ZSTD_HC_parameters params; } winnerInfo_t; -static void BMK_printWinners(const winnerInfo_t* winners, size_t srcSize) +static void BMK_printWinners(FILE* f, const winnerInfo_t* winners, size_t srcSize) { int cLevel; DISPLAY("\nSelected configurations :\n"); - for (cLevel=0; cLevel < CLEVEL_MAX; cLevel++) - BMK_printWinner(cLevel, winners[cLevel].result, winners[cLevel].params, srcSize); + for (cLevel=0; cLevel <= ZSTD_HC_MAX_CLEVEL; cLevel++) + BMK_printWinner(stdout, cLevel, winners[cLevel].result, winners[cLevel].params, srcSize); + fseek(f, 0, SEEK_SET); + for (cLevel=0; cLevel <= ZSTD_HC_MAX_CLEVEL; cLevel++) + BMK_printWinner(f, cLevel, winners[cLevel].result, winners[cLevel].params, srcSize); +} + +static int BMK_seed(winnerInfo_t* winners, ZSTD_HC_parameters params, + const void* srcBuffer, size_t srcSize, + ZSTD_HC_CCtx* ctx) +{ + BMK_result_t testResult; + int better = 0; + int cLevel; + + BMK_benchParam(&testResult, srcBuffer, srcSize, ctx, params); + + for (cLevel = 0; cLevel <= ZSTD_HC_MAX_CLEVEL; cLevel++) + { + if ( (testResult.cSpeed > g_cSpeedTarget[cLevel]) + && ((winners[cLevel].result.cSize==0) || (winners[cLevel].result.cSize > testResult.cSize)) ) + { + better = 1; + winners[cLevel].result = testResult; + winners[cLevel].params = params; + BMK_printWinner(stdout, cLevel, testResult, params, srcSize); + } + } + + return better; } #define WINDOWLOG_MAX 26 @@ -423,141 +463,151 @@ static void BMK_printWinners(const winnerInfo_t* winners, size_t srcSize) #define MAX(a,b) ( (a) > (b) ? (a) : (b) ) -static void playAround(winnerInfo_t* winners, ZSTD_HC_parameters params, +static BYTE g_alreadyTested[WINDOWLOG_MAX+1-WINDOWLOG_MIN] + [CHAINLOG_MAX+1-CHAINLOG_MIN] + [HASHLOG_MAX+1-HASHLOG_MIN] + [SEARCHLOG_MAX+1-SEARCHLOG_MIN] = {}; /* init to zero */ + +#define NB_TESTS_PLAYED(p) \ + g_alreadyTested[p.windowLog-WINDOWLOG_MIN][p.chainLog-CHAINLOG_MIN][p.hashLog-HASHLOG_MIN][p.searchLog-SEARCHLOG_MIN] + + +static void playAround(FILE* f, winnerInfo_t* winners, + ZSTD_HC_parameters params, const void* srcBuffer, size_t srcSize, ZSTD_HC_CCtx* ctx) { - BMK_result_t testResult; - int better = 0; - int cLevel; - - static BYTE g_alreadyTested[WINDOWLOG_MAX+1-WINDOWLOG_MIN] - [CHAINLOG_MAX+1-CHAINLOG_MIN] - [HASHLOG_MAX+1-HASHLOG_MIN] - [SEARCHLOG_MAX+1-SEARCHLOG_MIN] = {}; /* init to zero */ - static U32 g_rand = 1; - - /* exclude faster already played params */ - if (FUZ_rand(&g_rand) & ((1 << g_alreadyTested[params.windowLog-WINDOWLOG_MIN] - [params.chainLog-CHAINLOG_MIN] - [params.hashLog-HASHLOG_MIN] - [params.searchLog-SEARCHLOG_MIN]++)-1)) - return; - - BMK_benchParam(&testResult, srcBuffer, srcSize, ctx, params); - - for (cLevel = 0; cLevel < CLEVEL_MAX; cLevel++) + int nbVariations = 0; + const int startTime = BMK_GetMilliStart(); + while (BMK_GetMilliSpan(startTime) < g_maxVariationTime) { - if ( (testResult.cSpeed > g_cSpeedTarget[cLevel]) - && ((winners[cLevel].result.cSize==0) || (winners[cLevel].result.cSize > testResult.cSize)) ) + ZSTD_HC_parameters p = params; + U32 nbChanges = (FUZ_rand(&g_rand) & 3) + 1; + if (nbVariations++ > g_maxNbVariations) break; + + for (; nbChanges; nbChanges--) { - better = 1; - winners[cLevel].result = testResult; - winners[cLevel].params = params; - BMK_printWinner(cLevel, testResult, params, srcSize); + const U32 changeID = FUZ_rand(&g_rand) & 7; + switch(changeID) + { + case 0: + p.chainLog++; break; + case 1: + p.chainLog--; break; + case 2: + p.hashLog++; break; + case 3: + p.hashLog--; break; + case 4: + p.searchLog++; break; + case 5: + p.searchLog--; break; + case 6: + p.windowLog++; break; + case 7: + p.windowLog--; break; + } } - } - if (!better) return; + /* validate new conf */ + if (p.windowLog > WINDOWLOG_MAX) continue; + if (p.windowLog < MAX(WINDOWLOG_MIN, p.chainLog)) continue; + if (p.chainLog > p.windowLog) continue; + if (p.chainLog < CHAINLOG_MIN) continue; + if (p.hashLog > HASHLOG_MAX) continue; + if (p.hashLog < HASHLOG_MIN) continue; + if (p.searchLog > p.chainLog) continue; + if (p.searchLog < SEARCHLOG_MIN) continue; - BMK_printWinners(winners, srcSize); + /* exclude faster if already played params */ + if (FUZ_rand(&g_rand) & ((1 << NB_TESTS_PLAYED(p))-1)) continue; - if (params.searchLog > SEARCHLOG_MIN) - { - params.searchLog--; - playAround(winners, params, srcBuffer, srcSize, ctx); - params.searchLog++; - } + /* test */ + NB_TESTS_PLAYED(p)++; + if (!BMK_seed(winners, p, srcBuffer, srcSize, ctx)) continue; - if (params.hashLog < HASHLOG_MAX) - { - params.hashLog++; - playAround(winners, params, srcBuffer, srcSize, ctx); - params.hashLog--; - } - - if (params.chainLog > CHAINLOG_MIN) - { - params.chainLog--; - playAround(winners, params, srcBuffer, srcSize, ctx); - params.chainLog++; - } - - if (params.windowLog > MAX(WINDOWLOG_MIN, params.chainLog)) - { - params.windowLog--; - playAround(winners, params, srcBuffer, srcSize, ctx); - params.windowLog++; - } - - if (params.windowLog < WINDOWLOG_MAX) - { - params.windowLog++; - playAround(winners, params, srcBuffer, srcSize, ctx); - params.windowLog--; - } - - if (params.chainLog < params.windowLog) - { - params.chainLog++; - playAround(winners, params, srcBuffer, srcSize, ctx); - params.chainLog--; - } - - if (params.hashLog > HASHLOG_MIN) - { - params.hashLog--; - playAround(winners, params, srcBuffer, srcSize, ctx); - params.hashLog++; - } - - if (params.searchLog < params.chainLog) - { - params.searchLog++; - playAround(winners, params, srcBuffer, srcSize, ctx); - params.searchLog--; + /* improvement found => search more */ + BMK_printWinners(f, winners, srcSize); + playAround(f, winners, p, srcBuffer, srcSize, ctx); } } + +static void BMK_selectRandomStart( + FILE* f, winnerInfo_t* winners, + const void* srcBuffer, size_t srcSize, + ZSTD_HC_CCtx* ctx) +{ + U32 id = FUZ_rand(&g_rand) % (ZSTD_HC_MAX_CLEVEL+1); + if (id==0) + { + /* totally random entry */ + ZSTD_HC_parameters p; + p.chainLog = FUZ_rand(&g_rand) % (CHAINLOG_MAX+1 - CHAINLOG_MIN) + CHAINLOG_MIN; + p.hashLog = FUZ_rand(&g_rand) % (HASHLOG_MAX+1 - HASHLOG_MIN) + HASHLOG_MIN; + p.searchLog = FUZ_rand(&g_rand) % (SEARCHLOG_MAX+1 - SEARCHLOG_MIN) + SEARCHLOG_MIN; + p.windowLog = FUZ_rand(&g_rand) % (WINDOWLOG_MAX+1 - WINDOWLOG_MIN) + WINDOWLOG_MIN; + playAround(f, winners, p, srcBuffer, srcSize, ctx); + } + else + playAround(f, winners, winners[id].params, srcBuffer, srcSize, ctx); +} + + +static const ZSTD_HC_parameters* seedParams = ZSTD_HC_defaultParameters; + static void BMK_benchMem(void* srcBuffer, size_t srcSize) { ZSTD_HC_CCtx* ctx = ZSTD_HC_createCCtx(); ZSTD_HC_parameters params; - winnerInfo_t winners[CLEVEL_MAX]; + winnerInfo_t winners[ZSTD_HC_MAX_CLEVEL+1]; BMK_result_t testResult; + int i; + const char* rfName = "grillResults.txt"; + FILE* f; /* init */ memset(winners, 0, sizeof(winners)); + f = fopen(rfName, "w"); + if (f==NULL) { DISPLAY("error opening %s \n", rfName); exit(1); } /* baseline config for level 9 */ params.windowLog = 19; - params.chainLog = 18; - params.hashLog = 17; + params.chainLog = 19; + params.hashLog = 19; params.searchLog = 9; BMK_benchParam(&testResult, srcBuffer, srcSize, ctx, params); /* establish speed objectives (relative to current platform) */ + g_cSpeedTarget[9] = (testResult.cSpeed * 15) >> 4; + g_cSpeedTarget[1] = g_cSpeedTarget[9] << 4; + g_cSpeedTarget[0] = (g_cSpeedTarget[1] * 181) >> 7; /* sqrt2 */ + for (i=2; i> 8; + + /* populate initial solution */ + BMK_seed(winners, params, srcBuffer, srcSize, ctx); + for (i=1; i<=ZSTD_HC_MAX_CLEVEL; i++) + BMK_seed(winners, seedParams[i], srcBuffer, srcSize, ctx); + BMK_printWinners(f, winners, srcSize); + + /* start tests */ { - int i; - g_cSpeedTarget[9] = (testResult.cSpeed * 15) >> 4; - g_cSpeedTarget[1] = g_cSpeedTarget[9] << 4; - g_cSpeedTarget[0] = (g_cSpeedTarget[1] * 181) >> 7; /* sqrt2 */ - for (i=2; i<(CLEVEL_MAX-1); i++) /* last level : pure compression */ - g_cSpeedTarget[i] = (g_cSpeedTarget[i-1] * 181) >> 8; + const int milliStart = BMK_GetMilliStart(); + int mLength; + do + { + BMK_selectRandomStart(f, winners, srcBuffer, srcSize, ctx); + mLength = BMK_GetMilliSpan(milliStart); + } while (mLength < g_grillDuration); } - /* start from fast conf */ - params.windowLog = WINDOWLOG_MIN; - params.chainLog = CHAINLOG_MIN; - params.hashLog = 12; - params.searchLog = SEARCHLOG_MIN; - playAround(winners, params, srcBuffer, srcSize, ctx); - /* end summary */ - BMK_printWinners(winners, srcSize); + BMK_printWinners(f, winners, srcSize); /* clean up*/ + fclose(f); ZSTD_HC_freeCCtx(ctx); } @@ -612,7 +662,7 @@ int benchFiles(char** fileNamesTable, int nbFiles) return 11; } - // Memory allocation & restrictions + /* Memory allocation & restrictions */ inFileSize = BMK_GetFileSize(inFileName); benchedSize = (size_t) BMK_findMaxMem(inFileSize*3) / 3; if ((U64)benchedSize > inFileSize) benchedSize = (size_t)inFileSize; @@ -696,7 +746,7 @@ int main(int argc, char** argv) if(!argument) continue; // Protection if argument empty - // Decode command (note : aggregated commands are allowed) + /* Decode command (note : aggregated commands are allowed) */ if (argument[0]=='-') { while (argument[1]!=0) From 342892c3ae8390f3e55d3353aefc4be2df7b770e Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Mon, 26 Oct 2015 17:44:04 +0100 Subject: [PATCH 15/37] repcode+1 --- lib/zstdhc.c | 28 +++++++++++++++++++--------- 1 file changed, 19 insertions(+), 9 deletions(-) diff --git a/lib/zstdhc.c b/lib/zstdhc.c index 1671f4265..1440d55ce 100644 --- a/lib/zstdhc.c +++ b/lib/zstdhc.c @@ -103,7 +103,7 @@ size_t ZSTD_HC_freeCCtx(ZSTD_HC_CCtx* cctx) static void ZSTD_HC_resetCCtx_advanced (ZSTD_HC_CCtx* zc, const ZSTD_HC_parameters params, const void* start) { - U32 maxDistance = ( 1 << params.searchLog) + 1; + U32 outOfReach = ( 1 << params.searchLog) + 1; if (zc->hashTableLog < params.hashLog) { @@ -121,12 +121,12 @@ static void ZSTD_HC_resetCCtx_advanced (ZSTD_HC_CCtx* zc, } memset(zc->chainTable, 0, (1 << params.chainLog) * sizeof(U32) ); - zc->nextToUpdate = maxDistance; + zc->nextToUpdate = outOfReach; zc->end = (const BYTE*)start; - zc->base = zc->end - maxDistance; + zc->base = zc->end - outOfReach; zc->dictBase = zc->base; - zc->dictLimit = maxDistance; - zc->lowLimit = maxDistance; + zc->dictLimit = outOfReach; + zc->lowLimit = outOfReach; zc->params = params; zc->seqStore.buffer = zc->buffer; zc->seqStore.offsetStart = (U32*) (zc->seqStore.buffer); @@ -259,7 +259,7 @@ static size_t ZSTD_HC_compressBlock(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstS if (MEM_read32(ip) == MEM_read32(ip - offset_2)) /* store sequence */ { - size_t matchLength = ZSTD_count(ip+4, ip+4-offset_2, iend); + size_t matchLength = ZSTD_count(ip+MINMATCH, ip+MINMATCH-offset_2, iend); size_t litLength = ip-anchor; size_t offset = offset_2; offset_2 = offset_1; @@ -270,6 +270,18 @@ static size_t ZSTD_HC_compressBlock(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstS continue; } + /* repcode at ip+1 */ + if (MEM_read32(ip+1) == MEM_read32(ip+1 - offset_1)) + { + size_t matchLength = ZSTD_count(ip+1+MINMATCH, ip+1+MINMATCH-offset_1, iend); + size_t litLength = ip+1-anchor; + offset_2 = offset_1; + ZSTD_storeSeq(seqStorePtr, litLength, anchor, 0, matchLength); + ip += 1+matchLength+MINMATCH; + anchor = ip; + continue; + } + /* search */ { const BYTE* match; @@ -278,11 +290,9 @@ static size_t ZSTD_HC_compressBlock(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstS /* store sequence */ { size_t litLength = ip-anchor; - size_t offset = ip-match; - if (offset == offset_2) offset = 0; offset_2 = offset_1; offset_1 = ip-match; - ZSTD_storeSeq(seqStorePtr, litLength, anchor, offset, matchLength-MINMATCH); + ZSTD_storeSeq(seqStorePtr, litLength, anchor, offset_1, matchLength-MINMATCH); ip += matchLength; anchor = ip; } From 8b91abec18bdab5878ee45ce0d454ebebf891532 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 27 Oct 2015 02:59:12 +0100 Subject: [PATCH 16/37] can test param conf --- lib/zstdhc_static.h | 40 ++++++++++++------------ programs/paramgrill.c | 72 ++++++++++++++++++++++++++++++++----------- 2 files changed, 74 insertions(+), 38 deletions(-) diff --git a/lib/zstdhc_static.h b/lib/zstdhc_static.h index 26d910fad..06d8c2907 100644 --- a/lib/zstdhc_static.h +++ b/lib/zstdhc_static.h @@ -72,26 +72,26 @@ size_t ZSTD_HC_compress_advanced (ZSTD_HC_CCtx* ctx, static const ZSTD_HC_parameters ZSTD_HC_defaultParameters[ZSTD_HC_MAX_CLEVEL+1] = { /* W, C, H, S */ { 18, 4, 12, 1 }, /* 0 - should never be used */ - { 18, 10, 14, 1 }, /* 1 */ - { 18, 13, 15, 1 }, /* 2 */ - { 20, 18, 19, 2 }, /* 3 */ - { 21, 19, 20, 3 }, /* 4 */ - { 21, 19, 21, 4 }, /* 5 */ - { 21, 19, 21, 5 }, /* 6 */ - { 21, 21, 21, 5 }, /* 7 */ - { 21, 21, 21, 6 }, /* 8 */ - { 21, 21, 21, 7 }, /* 9 */ - { 21, 21, 21, 8 }, /*10 */ - { 21, 21, 21, 9 }, /*11 */ - { 21, 21, 21, 10 }, /*12 */ - { 21, 21, 21, 11 }, /*13 */ - { 21, 21, 21, 13 }, /*14 */ - { 21, 21, 21, 17 }, /*15 */ - { 22, 22, 22, 18 }, /*16 */ - { 23, 23, 23, 19 }, /*17 */ - { 24, 24, 24, 20 }, /*18 */ - { 25, 25, 25, 21 }, /*19 */ - { 26, 26, 26, 25 }, /*20 - ultra-slow */ + { 18, 11, 14, 1 }, /* 1 */ + { 20, 13, 16, 2 }, /* 2 */ + { 20, 19, 20, 2 }, /* 3 */ + { 21, 19, 20, 4 }, /* 4 */ + { 21, 20, 21, 4 }, /* 5 */ + { 21, 20, 22, 5 }, /* 6 */ + { 21, 20, 22, 6 }, /* 7 */ + { 21, 20, 22, 7 }, /* 8 */ + { 21, 21, 23, 7 }, /* 9 */ + { 21, 21, 23, 8 }, /*10 */ + { 21, 21, 23, 9 }, /*11 */ + { 21, 21, 23, 10 }, /*12 */ + { 22, 22, 24, 9 }, /*13 */ + { 22, 22, 24, 10 }, /*14 */ + { 23, 23, 23, 10 }, /*15 */ + { 24, 23, 22, 11 }, /*16 */ + { 24, 24, 23, 11 }, /*17 */ + { 24, 24, 22, 12 }, /*18 */ + { 24, 24, 22, 13 }, /*19 */ + { 25, 25, 25, 22 }, /*20 - ultra-slow */ }; diff --git a/programs/paramgrill.c b/programs/paramgrill.c index 24eba9253..3d030570e 100644 --- a/programs/paramgrill.c +++ b/programs/paramgrill.c @@ -118,6 +118,8 @@ static U32 nbIterations = NBLOOPS; static double g_compressibility = COMPRESSIBILITY_DEFAULT; static U32 g_blockSize = 0; static U32 g_rand = 1; +static U32 g_singleRun = 0; +static ZSTD_HC_parameters g_params = { 0, 0, 0, 0 }; void BMK_SetNbIterations(int nbLoops) { @@ -396,11 +398,10 @@ static size_t BMK_benchParam(BMK_result_t* resultPtr, static void BMK_printWinner(FILE* f, U32 cLevel, BMK_result_t result, ZSTD_HC_parameters params, size_t srcSize) { DISPLAY("\r%79s\r", ""); + fprintf(f," {%3u,%3u,%3u,%3u }, ", params.windowLog, params.chainLog, params.hashLog, params.searchLog); fprintf(f, - "level %2u: R:%5.3f at %5.1f MB/s => W%02uC%02uH%02uS%02u \n", - cLevel, (double)srcSize / result.cSize, (double)result.cSpeed / 1000., - params.windowLog, params.chainLog, params.hashLog, params.searchLog); - + "/* level %2u: R:%5.3f at %5.1f MB/s */ \n", + cLevel, (double)srcSize / result.cSize, (double)result.cSpeed / 1000.); } @@ -414,19 +415,28 @@ typedef struct { ZSTD_HC_parameters params; } winnerInfo_t; -static void BMK_printWinners(FILE* f, const winnerInfo_t* winners, size_t srcSize) +static void BMK_printWinners2(FILE* f, const winnerInfo_t* winners, size_t srcSize) { int cLevel; - DISPLAY("\nSelected configurations :\n"); - for (cLevel=0; cLevel <= ZSTD_HC_MAX_CLEVEL; cLevel++) - BMK_printWinner(stdout, cLevel, winners[cLevel].result, winners[cLevel].params, srcSize); + fprintf(f, "\n /* Selected configurations : */ \n"); + fprintf(f, "#define ZSTD_HC_MAX_CLEVEL 20 \n"); + fprintf(f, "static const ZSTD_HC_parameters ZSTD_HC_defaultParameters[ZSTD_HC_MAX_CLEVEL+1] = {\n"); + fprintf(f, " /* W, C, H, S */ \n"); - fseek(f, 0, SEEK_SET); for (cLevel=0; cLevel <= ZSTD_HC_MAX_CLEVEL; cLevel++) BMK_printWinner(f, cLevel, winners[cLevel].result, winners[cLevel].params, srcSize); } + +static void BMK_printWinners(FILE* f, const winnerInfo_t* winners, size_t srcSize) +{ + fseek(f, 0, SEEK_SET); + BMK_printWinners2(f, winners, srcSize); + BMK_printWinners2(stdout, winners, srcSize); +} + + static int BMK_seed(winnerInfo_t* winners, ZSTD_HC_parameters params, const void* srcBuffer, size_t srcSize, ZSTD_HC_CCtx* ctx) @@ -567,6 +577,13 @@ static void BMK_benchMem(void* srcBuffer, size_t srcSize) const char* rfName = "grillResults.txt"; FILE* f; + if (g_singleRun) + { + BMK_benchParam(&testResult, srcBuffer, srcSize, ctx, g_params); + DISPLAY("\n"); + return; + } + /* init */ memset(winners, 0, sizeof(winners)); f = fopen(rfName, "w"); @@ -723,7 +740,7 @@ int badusage(char* exename) { DISPLAY("Wrong parameters\n"); usage(exename); - return 0; + return 1; } int main(int argc, char** argv) @@ -749,9 +766,10 @@ int main(int argc, char** argv) /* Decode command (note : aggregated commands are allowed) */ if (argument[0]=='-') { - while (argument[1]!=0) + argument++; + + while (argument[0]!=0) { - argument ++; switch(argument[0]) { @@ -760,13 +778,14 @@ int main(int argc, char** argv) case 'H': usage(exename); usage_advanced(); return 0; /* Pause at the end (hidden option) */ - case 'p': main_pause = 1; break; + case 'p': main_pause = 1; argument++; break; /* Modify Nb Iterations */ case 'i': - if ((argument[1] >='0') && (argument[1] <='9')) + argument++; + if ((argument[0] >='0') && (argument[0] <='9')) { - int iters = argument[1] - '0'; + int iters = argument[0] - '0'; BMK_SetNbIterations(iters); argument++; } @@ -774,20 +793,37 @@ int main(int argc, char** argv) /* Sample compressibility (when no file provided) */ case 'P': + argument++; { U32 proba32 = 0; - while ((argument[1]>= '0') && (argument[1]<= '9')) + while ((argument[0]>= '0') && (argument[0]<= '9')) { proba32 *= 10; - proba32 += argument[1] - '0'; + proba32 += argument[0] - '0'; argument++; } g_compressibility = (double)proba32 / 100.; } break; + /* Run Single conf */ + case 'S': + { + if (argument[ 1]!='w') return badusage(exename); + if (argument[ 4]!='c') return badusage(exename); + if (argument[ 7]!='h') return badusage(exename); + if (argument[10]!='s') return badusage(exename); + g_singleRun = 1; + g_params.windowLog = (argument[ 2] - '0') * 10 + (argument[ 3] - '0'); + g_params.chainLog = (argument[ 5] - '0') * 10 + (argument[ 6] - '0'); + g_params.hashLog = (argument[ 8] - '0') * 10 + (argument[ 9] - '0'); + g_params.searchLog = (argument[11] - '0') * 10 + (argument[12] - '0'); + argument += 13; + break; + } + /* Unknown command */ - default : badusage(exename); return 1; + default : return badusage(exename); } } continue; From d55a7e0e4d7ccfcc12812b30b4a337948cb01b78 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 27 Oct 2015 03:06:40 +0100 Subject: [PATCH 17/37] simplified chain --- lib/zstdhc.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/lib/zstdhc.c b/lib/zstdhc.c index 1440d55ce..869e4355f 100644 --- a/lib/zstdhc.c +++ b/lib/zstdhc.c @@ -143,7 +143,7 @@ static void ZSTD_HC_resetCCtx_advanced (ZSTD_HC_CCtx* zc, ***************************************/ #define KNUTH 2654435761U static U32 ZSTD_HC_hash(U32 u, U32 h) { return (u * KNUTH) >> (32-h) ; } -#define DELTANEXT(d) chainTable[(d) & chainMask] /* flexible, CHAINSIZE dependent */ +#define NEXT_IN_CHAIN(d) chainTable[(d) & chainMask] /* flexible, CHAINSIZE dependent */ static U32 ZSTD_HC_hashPtr(const void* ptr, U32 h) { return ZSTD_HC_hash(MEM_read32(ptr), h); } @@ -165,8 +165,7 @@ static void ZSTD_HC_insert (ZSTD_HC_CCtx* zc, const BYTE* ip) while(idx < target) { U32 h = ZSTD_HC_hashPtr(base+idx, hashLog); - size_t delta = idx - hashTable[h]; - DELTANEXT(idx) = (U32)delta; + NEXT_IN_CHAIN(idx) = hashTable[h]; hashTable[h] = idx; idx++; } @@ -229,7 +228,7 @@ static size_t ZSTD_HC_insertAndFindBestMatch ( } if (base + matchIndex <= ip - chainSize) break; - matchIndex -= DELTANEXT(matchIndex); + matchIndex = NEXT_IN_CHAIN(matchIndex); } return ml; From 2c6992e1dc00a0519a6adc8f4b692e0bfa19ca6c Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 27 Oct 2015 12:18:00 +0100 Subject: [PATCH 18/37] blocksize & T --- lib/zstd_static.h | 16 ++++---- lib/zstdhc.c | 2 +- lib/zstdhc_static.h | 10 +++++ programs/bench.c | 6 +-- programs/paramgrill.c | 96 +++++++++++++++++++++++++++---------------- 5 files changed, 82 insertions(+), 48 deletions(-) diff --git a/lib/zstd_static.h b/lib/zstd_static.h index 76315c3a8..147dcd0c6 100644 --- a/lib/zstd_static.h +++ b/lib/zstd_static.h @@ -94,11 +94,11 @@ MEM_STATIC unsigned ZSTD_NbCommonBytes (register size_t val) { if (MEM_64bits()) { -# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) +# if defined(_MSC_VER) && defined(_WIN64) unsigned long r = 0; _BitScanForward64( &r, (U64)val ); return (int)(r>>3); -# elif defined(__GNUC__) && (__GNUC__ >= 3) && !defined(LZ4_FORCE_SW_BITCOUNT) +# elif defined(__GNUC__) && (__GNUC__ >= 3) return (__builtin_ctzll((U64)val) >> 3); # else static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 }; @@ -107,11 +107,11 @@ MEM_STATIC unsigned ZSTD_NbCommonBytes (register size_t val) } else /* 32 bits */ { -# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) +# if defined(_MSC_VER) unsigned long r; _BitScanForward( &r, (U32)val ); return (int)(r>>3); -# elif defined(__GNUC__) && (__GNUC__ >= 3) && !defined(LZ4_FORCE_SW_BITCOUNT) +# elif defined(__GNUC__) && (__GNUC__ >= 3) return (__builtin_ctz((U32)val) >> 3); # else static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 }; @@ -123,11 +123,11 @@ MEM_STATIC unsigned ZSTD_NbCommonBytes (register size_t val) { if (MEM_32bits()) { -# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) +# if defined(_MSC_VER) && defined(_WIN64) unsigned long r = 0; _BitScanReverse64( &r, val ); return (unsigned)(r>>3); -# elif defined(__GNUC__) && (__GNUC__ >= 3) && !defined(LZ4_FORCE_SW_BITCOUNT) +# elif defined(__GNUC__) && (__GNUC__ >= 3) return (__builtin_clzll(val) >> 3); # else unsigned r; @@ -140,11 +140,11 @@ MEM_STATIC unsigned ZSTD_NbCommonBytes (register size_t val) } else /* 32 bits */ { -# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) +# if defined(_MSC_VER) unsigned long r = 0; _BitScanReverse( &r, (unsigned long)val ); return (unsigned)(r>>3); -# elif defined(__GNUC__) && (__GNUC__ >= 3) && !defined(LZ4_FORCE_SW_BITCOUNT) +# elif defined(__GNUC__) && (__GNUC__ >= 3) return (__builtin_clz((U32)val) >> 3); # else unsigned r; diff --git a/lib/zstdhc.c b/lib/zstdhc.c index 869e4355f..5a79b9f8b 100644 --- a/lib/zstdhc.c +++ b/lib/zstdhc.c @@ -305,7 +305,7 @@ static size_t ZSTD_HC_compressBlock(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstS seqStorePtr->lit += lastLLSize; } - /* Finale compression stage */ + /* Final compression stage */ return ZSTD_compressSequences((BYTE*)dst, maxDstSize, seqStorePtr, srcSize); } diff --git a/lib/zstdhc_static.h b/lib/zstdhc_static.h index 06d8c2907..786d61883 100644 --- a/lib/zstdhc_static.h +++ b/lib/zstdhc_static.h @@ -53,6 +53,16 @@ typedef struct U32 searchLog; /* nb of searches : larger == more compression, slower*/ } ZSTD_HC_parameters; +/* parameters boundaries */ +#define ZSTD_HC_WINDOWLOG_MAX 26 +#define ZSTD_HC_WINDOWLOG_MIN 17 +#define ZSTD_HC_CHAINLOG_MAX ZSTD_HC_WINDOWLOG_MAX +#define ZSTD_HC_CHAINLOG_MIN 4 +#define ZSTD_HC_HASHLOG_MAX 28 +#define ZSTD_HC_HASHLOG_MIN 4 +#define ZSTD_HC_SEARCHLOG_MAX (ZSTD_HC_CHAINLOG_MAX-1) +#define ZSTD_HC_SEARCHLOG_MIN 1 + /* ************************************* * Functions diff --git a/programs/bench.c b/programs/bench.c index aed0a446d..f52210b9d 100644 --- a/programs/bench.c +++ b/programs/bench.c @@ -175,7 +175,6 @@ static U32 BMK_rand(U32* src) return rand32 >> 9; } - #define BMK_RAND15BITS ( BMK_rand(&seed) & 0x7FFF) #define BMK_RANDLENGTH ((BMK_rand(&seed) & 3) ? (BMK_rand(&seed) % 15) : (BMK_rand(&seed) % 510) + 15) #define BMK_RANDCHAR (BYTE)((BMK_rand(&seed) & 63) + '0') @@ -230,7 +229,6 @@ typedef struct size_t resSize; } blockParam_t; - typedef size_t (*compressor_t) (void* dst, size_t maxDstSize, const void* src, size_t srcSize, unsigned compressionLevel); static size_t local_compress_fast (void* dst, size_t maxDstSize, const void* src, size_t srcSize, unsigned compressionLevel) @@ -249,7 +247,7 @@ static int BMK_benchMem(void* srcBuffer, size_t srcSize, const char* fileName, i const size_t maxCompressedSize = (size_t)nbBlocks * ZSTD_compressBound(blockSize); void* const compressedBuffer = malloc(maxCompressedSize); void* const resultBuffer = malloc(srcSize); - const compressor_t compressor = (cLevel <= 1) ? local_compress_fast : ZSTD_HC_compress; + const compressor_t compressor = (cLevel == 0) ? local_compress_fast : ZSTD_HC_compress; U64 crcOrig; /* Memory allocation & restrictions */ @@ -328,7 +326,7 @@ static int BMK_benchMem(void* srcBuffer, size_t srcSize, const char* fileName, i ratio = (double)cSize / (double)srcSize*100.; DISPLAY("%1i-%-14.14s : %9i -> %9i (%5.2f%%),%7.1f MB/s\r", loopNb, fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000.); -#if 1 +#if 0 /* Decompression */ memset(resultBuffer, 0xD6, srcSize); diff --git a/programs/paramgrill.c b/programs/paramgrill.c index 3d030570e..93ba0b48b 100644 --- a/programs/paramgrill.c +++ b/programs/paramgrill.c @@ -100,10 +100,10 @@ #define COMPRESSIBILITY_DEFAULT 0.50 static const size_t sampleSize = 10000000; -static const int g_grillDuration = 30000000; /* about 8.5 hours */ +static const int g_grillDuration = 50000000; /* about 13 hours */ static const int g_maxParamTime = 15000; /* 15 sec */ static const int g_maxVariationTime = 60000; /* 60 sec */ -static const int g_maxNbVariations = 32; +static const int g_maxNbVariations = 64; /************************************** * Macros @@ -119,6 +119,7 @@ static double g_compressibility = COMPRESSIBILITY_DEFAULT; static U32 g_blockSize = 0; static U32 g_rand = 1; static U32 g_singleRun = 0; +static U32 g_target = 0; static ZSTD_HC_parameters g_params = { 0, 0, 0, 0 }; void BMK_SetNbIterations(int nbLoops) @@ -462,24 +463,18 @@ static int BMK_seed(winnerInfo_t* winners, ZSTD_HC_parameters params, return better; } -#define WINDOWLOG_MAX 26 -#define WINDOWLOG_MIN 17 -#define CHAINLOG_MAX WINDOWLOG_MAX -#define CHAINLOG_MIN 4 -#define HASHLOG_MAX 28 -#define HASHLOG_MIN 4 -#define SEARCHLOG_MAX (CHAINLOG_MAX-1) -#define SEARCHLOG_MIN 1 - #define MAX(a,b) ( (a) > (b) ? (a) : (b) ) -static BYTE g_alreadyTested[WINDOWLOG_MAX+1-WINDOWLOG_MIN] - [CHAINLOG_MAX+1-CHAINLOG_MIN] - [HASHLOG_MAX+1-HASHLOG_MIN] - [SEARCHLOG_MAX+1-SEARCHLOG_MIN] = {}; /* init to zero */ +static BYTE g_alreadyTested[ZSTD_HC_WINDOWLOG_MAX+1-ZSTD_HC_WINDOWLOG_MIN] + [ZSTD_HC_CHAINLOG_MAX+1-ZSTD_HC_CHAINLOG_MIN] + [ZSTD_HC_HASHLOG_MAX+1-ZSTD_HC_HASHLOG_MIN] + [ZSTD_HC_SEARCHLOG_MAX+1-ZSTD_HC_SEARCHLOG_MIN] = {}; /* init to zero */ #define NB_TESTS_PLAYED(p) \ - g_alreadyTested[p.windowLog-WINDOWLOG_MIN][p.chainLog-CHAINLOG_MIN][p.hashLog-HASHLOG_MIN][p.searchLog-SEARCHLOG_MIN] + g_alreadyTested[p.windowLog-ZSTD_HC_WINDOWLOG_MIN] \ + [p.chainLog-ZSTD_HC_CHAINLOG_MIN] \ + [p.hashLog-ZSTD_HC_HASHLOG_MIN] \ + [p.searchLog-ZSTD_HC_SEARCHLOG_MIN] static void playAround(FILE* f, winnerInfo_t* winners, @@ -520,14 +515,14 @@ static void playAround(FILE* f, winnerInfo_t* winners, } /* validate new conf */ - if (p.windowLog > WINDOWLOG_MAX) continue; - if (p.windowLog < MAX(WINDOWLOG_MIN, p.chainLog)) continue; + if (p.windowLog > ZSTD_HC_WINDOWLOG_MAX) continue; + if (p.windowLog < MAX(ZSTD_HC_WINDOWLOG_MIN, p.chainLog)) continue; if (p.chainLog > p.windowLog) continue; - if (p.chainLog < CHAINLOG_MIN) continue; - if (p.hashLog > HASHLOG_MAX) continue; - if (p.hashLog < HASHLOG_MIN) continue; + if (p.chainLog < ZSTD_HC_CHAINLOG_MIN) continue; + if (p.hashLog > ZSTD_HC_HASHLOG_MAX) continue; + if (p.hashLog < ZSTD_HC_HASHLOG_MIN) continue; if (p.searchLog > p.chainLog) continue; - if (p.searchLog < SEARCHLOG_MIN) continue; + if (p.searchLog < ZSTD_HC_SEARCHLOG_MIN) continue; /* exclude faster if already played params */ if (FUZ_rand(&g_rand) & ((1 << NB_TESTS_PLAYED(p))-1)) continue; @@ -554,10 +549,10 @@ static void BMK_selectRandomStart( { /* totally random entry */ ZSTD_HC_parameters p; - p.chainLog = FUZ_rand(&g_rand) % (CHAINLOG_MAX+1 - CHAINLOG_MIN) + CHAINLOG_MIN; - p.hashLog = FUZ_rand(&g_rand) % (HASHLOG_MAX+1 - HASHLOG_MIN) + HASHLOG_MIN; - p.searchLog = FUZ_rand(&g_rand) % (SEARCHLOG_MAX+1 - SEARCHLOG_MIN) + SEARCHLOG_MIN; - p.windowLog = FUZ_rand(&g_rand) % (WINDOWLOG_MAX+1 - WINDOWLOG_MIN) + WINDOWLOG_MIN; + p.chainLog = FUZ_rand(&g_rand) % (ZSTD_HC_CHAINLOG_MAX+1 - ZSTD_HC_CHAINLOG_MIN) + ZSTD_HC_CHAINLOG_MIN; + p.hashLog = FUZ_rand(&g_rand) % (ZSTD_HC_HASHLOG_MAX+1 - ZSTD_HC_HASHLOG_MIN) + ZSTD_HC_HASHLOG_MIN; + p.searchLog = FUZ_rand(&g_rand) % (ZSTD_HC_SEARCHLOG_MAX+1 - ZSTD_HC_SEARCHLOG_MIN) + ZSTD_HC_SEARCHLOG_MIN; + p.windowLog = FUZ_rand(&g_rand) % (ZSTD_HC_WINDOWLOG_MAX+1 - ZSTD_HC_WINDOWLOG_MIN) + ZSTD_HC_WINDOWLOG_MIN; playAround(f, winners, p, srcBuffer, srcSize, ctx); } else @@ -589,24 +584,29 @@ static void BMK_benchMem(void* srcBuffer, size_t srcSize) f = fopen(rfName, "w"); if (f==NULL) { DISPLAY("error opening %s \n", rfName); exit(1); } - /* baseline config for level 9 */ - params.windowLog = 19; - params.chainLog = 19; - params.hashLog = 19; - params.searchLog = 9; - BMK_benchParam(&testResult, srcBuffer, srcSize, ctx, params); + if (g_target) + g_cSpeedTarget[9] = g_target * 1000; + else + { + /* baseline config for level 9 */ + params.windowLog = 19; + params.chainLog = 19; + params.hashLog = 19; + params.searchLog = 9; + BMK_benchParam(&testResult, srcBuffer, srcSize, ctx, params); + g_cSpeedTarget[9] = (testResult.cSpeed * 15) >> 4; + } - /* establish speed objectives (relative to current platform) */ - g_cSpeedTarget[9] = (testResult.cSpeed * 15) >> 4; + /* establish speed objectives (relative to level9) */ g_cSpeedTarget[1] = g_cSpeedTarget[9] << 4; g_cSpeedTarget[0] = (g_cSpeedTarget[1] * 181) >> 7; /* sqrt2 */ for (i=2; i> 8; /* populate initial solution */ - BMK_seed(winners, params, srcBuffer, srcSize, ctx); for (i=1; i<=ZSTD_HC_MAX_CLEVEL; i++) BMK_seed(winners, seedParams[i], srcBuffer, srcSize, ctx); + BMK_seed(winners, params, srcBuffer, srcSize, ctx); BMK_printWinners(f, winners, srcSize); /* start tests */ @@ -622,6 +622,7 @@ static void BMK_benchMem(void* srcBuffer, size_t srcSize) /* end summary */ BMK_printWinners(f, winners, srcSize); + DISPLAY("grillParams operations completed \n"); /* clean up*/ fclose(f); @@ -822,6 +823,31 @@ int main(int argc, char** argv) break; } + /* target level9 objective, in MB/s */ + case 'T': + argument++; + g_target = 0; + while ((*argument >= '0') && (*argument <= '9')) + { + g_target *= 10; + g_target += *argument - '0'; + argument++; + } + break; + + /* cut input into blocks */ + case 'B': + { + g_blockSize = 0; + argument++; + while ((*argument >='0') && (*argument <='9')) + g_blockSize *= 10, g_blockSize += *argument++ - '0'; + if (*argument=='K') g_blockSize<<=10, argument++; /* allows using KB notation */ + if (*argument=='M') g_blockSize<<=20, argument++; + if (*argument=='B') argument++; + } + break; + /* Unknown command */ default : return badusage(exename); } From b315bc86e109f0716ada602cc7160ebabcd65b16 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Tue, 27 Oct 2015 13:12:25 +0100 Subject: [PATCH 19/37] srcLog --- lib/zstdhc_static.h | 10 ++++---- programs/paramgrill.c | 55 ++++++++++++++++++++++++++++++++++++------- 2 files changed, 52 insertions(+), 13 deletions(-) diff --git a/lib/zstdhc_static.h b/lib/zstdhc_static.h index 786d61883..b1618adad 100644 --- a/lib/zstdhc_static.h +++ b/lib/zstdhc_static.h @@ -94,13 +94,13 @@ static const ZSTD_HC_parameters ZSTD_HC_defaultParameters[ZSTD_HC_MAX_CLEVEL+1] { 21, 21, 23, 8 }, /*10 */ { 21, 21, 23, 9 }, /*11 */ { 21, 21, 23, 10 }, /*12 */ - { 22, 22, 24, 9 }, /*13 */ - { 22, 22, 24, 10 }, /*14 */ + { 22, 22, 23, 9 }, /*13 */ + { 22, 22, 23, 10 }, /*14 */ { 23, 23, 23, 10 }, /*15 */ - { 24, 23, 22, 11 }, /*16 */ + { 24, 23, 23, 11 }, /*16 */ { 24, 24, 23, 11 }, /*17 */ - { 24, 24, 22, 12 }, /*18 */ - { 24, 24, 22, 13 }, /*19 */ + { 24, 24, 23, 12 }, /*18 */ + { 24, 24, 23, 13 }, /*19 */ { 25, 25, 25, 22 }, /*20 - ultra-slow */ }; diff --git a/programs/paramgrill.c b/programs/paramgrill.c index 93ba0b48b..5c5a8264b 100644 --- a/programs/paramgrill.c +++ b/programs/paramgrill.c @@ -120,6 +120,7 @@ static U32 g_blockSize = 0; static U32 g_rand = 1; static U32 g_singleRun = 0; static U32 g_target = 0; +static U32 g_noSeed = 0; static ZSTD_HC_parameters g_params = { 0, 0, 0, 0 }; void BMK_SetNbIterations(int nbLoops) @@ -133,6 +134,28 @@ void BMK_SetNbIterations(int nbLoops) * Private functions *********************************************************/ +static unsigned BMK_highbit(U32 val) +{ +# if defined(_MSC_VER) /* Visual */ + unsigned long r; + _BitScanReverse(&r, val); + return (unsigned)r; +# elif defined(__GNUC__) && (__GNUC__ >= 3) /* GCC Intrinsic */ + return 31 - __builtin_clz(val); +# else /* Software version */ + static const int DeBruijnClz[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 }; + U32 v = val; + int r; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + r = DeBruijnClz[(U32)(v * 0x07C4ACDDU) >> 27]; + return r; +# endif +} + #if defined(BMK_LEGACY_TIMER) static int BMK_GetMilliStart(void) @@ -242,6 +265,7 @@ typedef struct #define MIN(a,b) ( (a) < (b) ? (a) : (b) ) + static size_t BMK_benchParam(BMK_result_t* resultPtr, const void* srcBuffer, size_t srcSize, ZSTD_HC_CCtx* ctx, @@ -482,8 +506,10 @@ static void playAround(FILE* f, winnerInfo_t* winners, const void* srcBuffer, size_t srcSize, ZSTD_HC_CCtx* ctx) { + const U32 srcLog = BMK_highbit((U32)( (g_blockSize ? g_blockSize : srcSize) -1))+1; int nbVariations = 0; const int startTime = BMK_GetMilliStart(); + while (BMK_GetMilliSpan(startTime) < g_maxVariationTime) { ZSTD_HC_parameters p = params; @@ -515,6 +541,7 @@ static void playAround(FILE* f, winnerInfo_t* winners, } /* validate new conf */ + if (p.windowLog > srcLog) continue; if (p.windowLog > ZSTD_HC_WINDOWLOG_MAX) continue; if (p.windowLog < MAX(ZSTD_HC_WINDOWLOG_MIN, p.chainLog)) continue; if (p.chainLog > p.windowLog) continue; @@ -545,7 +572,7 @@ static void BMK_selectRandomStart( ZSTD_HC_CCtx* ctx) { U32 id = FUZ_rand(&g_rand) % (ZSTD_HC_MAX_CLEVEL+1); - if (id==0) + if ((id==0) || (winners[id].params.windowLog==0)) { /* totally random entry */ ZSTD_HC_parameters p; @@ -571,6 +598,7 @@ static void BMK_benchMem(void* srcBuffer, size_t srcSize) int i; const char* rfName = "grillResults.txt"; FILE* f; + const U32 srcLog = BMK_highbit((U32)( (g_blockSize ? g_blockSize : srcSize) -1))+1; if (g_singleRun) { @@ -589,10 +617,10 @@ static void BMK_benchMem(void* srcBuffer, size_t srcSize) else { /* baseline config for level 9 */ - params.windowLog = 19; - params.chainLog = 19; + params.windowLog = MIN(srcLog, 19); + params.chainLog = MIN(params.windowLog, 19); params.hashLog = 19; - params.searchLog = 9; + params.searchLog = MIN(params.chainLog, 9); BMK_benchParam(&testResult, srcBuffer, srcSize, ctx, params); g_cSpeedTarget[9] = (testResult.cSpeed * 15) >> 4; } @@ -604,9 +632,18 @@ static void BMK_benchMem(void* srcBuffer, size_t srcSize) g_cSpeedTarget[i] = (g_cSpeedTarget[i-1] * 181) >> 8; /* populate initial solution */ - for (i=1; i<=ZSTD_HC_MAX_CLEVEL; i++) - BMK_seed(winners, seedParams[i], srcBuffer, srcSize, ctx); - BMK_seed(winners, params, srcBuffer, srcSize, ctx); + { + const int maxSeeds = g_noSeed ? 1 : ZSTD_HC_MAX_CLEVEL; + //BMK_seed(winners, params, srcBuffer, srcSize, ctx); + for (i=1; i<=maxSeeds; i++) + { + params = seedParams[i]; + params.windowLog = MIN(srcLog, params.windowLog); + params.chainLog = MIN(params.windowLog, params.chainLog); + params.searchLog = MIN(params.chainLog, params.searchLog); + BMK_seed(winners, params, srcBuffer, srcSize, ctx); + } + } BMK_printWinners(f, winners, srcSize); /* start tests */ @@ -762,7 +799,9 @@ int main(int argc, char** argv) { char* argument = argv[i]; - if(!argument) continue; // Protection if argument empty + if(!argument) continue; /* Protection if argument empty */ + + if(!strcmp(argument,"--no-seed")) { g_noSeed = 1; continue; } /* Decode command (note : aggregated commands are allowed) */ if (argument[0]=='-') From 1077bb81416088b60455dc15fe6d9362aa9a5194 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 28 Oct 2015 12:32:25 +0100 Subject: [PATCH 20/37] memory notation --- NEWS | 6 +++++ programs/Makefile | 2 +- programs/paramgrill.c | 54 +++++++++++++++++++++++++++++++------------ 3 files changed, 46 insertions(+), 16 deletions(-) diff --git a/NEWS b/NEWS index b09b624f5..8388dfceb 100644 --- a/NEWS +++ b/NEWS @@ -1,3 +1,9 @@ +v0.2.2 +Fix : Visual Studio 2013 & 2015 release compilation, by Christophe Chevalier + +v0.2.2 +Fix : Read errors, advanced fuzzer tests, by Hanno Böck + v0.2.0 **Breaking format change** Faster decompression speed diff --git a/programs/Makefile b/programs/Makefile index 27e3e0e6a..047a0c45c 100644 --- a/programs/Makefile +++ b/programs/Makefile @@ -77,7 +77,7 @@ fuzzer32: $(ZSTDDIR)/zstd.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legac $(CC) -m32 $(FLAGS) $^ -o $@$(EXT) paramgrill : $(ZSTDDIR)/zstdhc.c $(ZSTDDIR)/zstd.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legacy/zstd_v01.c datagen.c xxhash.c paramgrill.c - $(CC) $(FLAGS) $^ -o $@$(EXT) + $(CC) $(FLAGS) $^ -lm -o $@$(EXT) datagen : datagen.c datagencli.c $(CC) $(FLAGS) $^ -o $@$(EXT) diff --git a/programs/paramgrill.c b/programs/paramgrill.c index 5c5a8264b..7e8e24bcf 100644 --- a/programs/paramgrill.c +++ b/programs/paramgrill.c @@ -52,6 +52,7 @@ #include /* stat64 */ #include /* stat64 */ #include /* strcmp */ +#include /* log */ /* Use ftime() if gettimeofday() is not available on your target */ #if defined(BMK_LEGACY_TIMER) @@ -425,7 +426,7 @@ static void BMK_printWinner(FILE* f, U32 cLevel, BMK_result_t result, ZSTD_HC_pa DISPLAY("\r%79s\r", ""); fprintf(f," {%3u,%3u,%3u,%3u }, ", params.windowLog, params.chainLog, params.hashLog, params.searchLog); fprintf(f, - "/* level %2u: R:%5.3f at %5.1f MB/s */ \n", + "/* level %2u */ /* R:%5.3f at %5.1f MB/s */ \n", cLevel, (double)srcSize / result.cSize, (double)result.cSpeed / 1000.); } @@ -451,6 +452,8 @@ static void BMK_printWinners2(FILE* f, const winnerInfo_t* winners, size_t srcSi for (cLevel=0; cLevel <= ZSTD_HC_MAX_CLEVEL; cLevel++) BMK_printWinner(f, cLevel, winners[cLevel].result, winners[cLevel].params, srcSize); + + fflush(f); } @@ -474,10 +477,32 @@ static int BMK_seed(winnerInfo_t* winners, ZSTD_HC_parameters params, for (cLevel = 0; cLevel <= ZSTD_HC_MAX_CLEVEL; cLevel++) { - if ( (testResult.cSpeed > g_cSpeedTarget[cLevel]) - && ((winners[cLevel].result.cSize==0) || (winners[cLevel].result.cSize > testResult.cSize)) ) + if ( (testResult.cSpeed > g_cSpeedTarget[cLevel]) && (winners[cLevel].result.cSize==0) ) + better = 1; /* first solution for this cLevel */ + + if ( (testResult.cSpeed > g_cSpeedTarget[cLevel]) && (testResult.cSize < winners[cLevel].result.cSize )) { + /* Validate solution is "good enough" */ + double W_ratioNote = log ( (double)srcSize / testResult.cSize); + double O_ratioNote = log ( (double)srcSize / winners[cLevel].result.cSize); + size_t W_DMemUsed = (1 << params.windowLog) + (16 KB); + size_t O_DMemUsed = (1 << winners[cLevel].params.windowLog) + (16 KB); + double W_DMemUsed_note = W_ratioNote * ( 18 + 2*cLevel) - log((double)W_DMemUsed); + double O_DMemUsed_note = O_ratioNote * ( 18 + 2*cLevel) - log((double)O_DMemUsed); + + size_t W_CMemUsed = (1 << params.windowLog) + 4 * (1 << params.hashLog) + 4 * (1 << params.chainLog); + size_t O_CMemUsed = (1 << winners[cLevel].params.windowLog) + 4 * (1 << winners[cLevel].params.hashLog) + 4 * (1 << winners[cLevel].params.chainLog); + double W_CMemUsed_note = W_ratioNote * ( 35 + 5*cLevel) - log((double)W_CMemUsed); + double O_CMemUsed_note = O_ratioNote * ( 35 + 5*cLevel) - log((double)O_CMemUsed); + + if (W_DMemUsed_note < O_DMemUsed_note) continue; /* uses too much Decompression memory for too little benefit */ + if (W_CMemUsed_note < O_CMemUsed_note) continue; /* uses too much memory for compression for too little benefit */ + better = 1; + } + + if (better) + { winners[cLevel].result = testResult; winners[cLevel].params = params; BMK_printWinner(stdout, cLevel, testResult, params, srcSize); @@ -594,7 +619,6 @@ static void BMK_benchMem(void* srcBuffer, size_t srcSize) ZSTD_HC_CCtx* ctx = ZSTD_HC_createCCtx(); ZSTD_HC_parameters params; winnerInfo_t winners[ZSTD_HC_MAX_CLEVEL+1]; - BMK_result_t testResult; int i; const char* rfName = "grillResults.txt"; FILE* f; @@ -602,6 +626,7 @@ static void BMK_benchMem(void* srcBuffer, size_t srcSize) if (g_singleRun) { + BMK_result_t testResult; BMK_benchParam(&testResult, srcBuffer, srcSize, ctx, g_params); DISPLAY("\n"); return; @@ -613,23 +638,22 @@ static void BMK_benchMem(void* srcBuffer, size_t srcSize) if (f==NULL) { DISPLAY("error opening %s \n", rfName); exit(1); } if (g_target) - g_cSpeedTarget[9] = g_target * 1000; + g_cSpeedTarget[1] = g_target * 1000; else { - /* baseline config for level 9 */ - params.windowLog = MIN(srcLog, 19); - params.chainLog = MIN(params.windowLog, 19); - params.hashLog = 19; - params.searchLog = MIN(params.chainLog, 9); + /* baseline config for level 1 */ + BMK_result_t testResult; + params = seedParams[1]; + params.windowLog = MIN(srcLog, params.windowLog); + params.chainLog = MIN(params.windowLog, params.chainLog); + params.searchLog = MIN(params.chainLog, params.searchLog); BMK_benchParam(&testResult, srcBuffer, srcSize, ctx, params); - g_cSpeedTarget[9] = (testResult.cSpeed * 15) >> 4; + g_cSpeedTarget[1] = (testResult.cSpeed * 15) >> 4; } - /* establish speed objectives (relative to level9) */ - g_cSpeedTarget[1] = g_cSpeedTarget[9] << 4; - g_cSpeedTarget[0] = (g_cSpeedTarget[1] * 181) >> 7; /* sqrt2 */ + /* establish speed objectives (relative to level 1) */ for (i=2; i> 8; + g_cSpeedTarget[i] = (g_cSpeedTarget[i-1] * 13) >> 4; /* populate initial solution */ { From 10ba1834cc0fc20401870b8dec8738931b7574c2 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 28 Oct 2015 14:05:37 +0100 Subject: [PATCH 21/37] value time --- README.md | 13 +++++-------- programs/paramgrill.c | 18 +++++++++++++----- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index a9e76dcc4..2231d0486 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ - **Zstd**, short for Zstandard, is a new lossless compression algorithm, which provides both good compression ratio _and_ speed for your standard compression needs. "Standard" translates into everyday situations which neither look for highest possible ratio nor extreme speed. + **Zstd**, short for Zstandard, is a fast lossless compression algorithm, targeting real-time compression scenarios, and featuring zlib-level compression ratio. It is provided as a BSD-license package, hosted on Github. @@ -7,15 +7,13 @@ It is provided as a BSD-license package, hosted on Github. |master | [![Build Status](https://travis-ci.org/Cyan4973/zstd.svg?branch=master)](https://travis-ci.org/Cyan4973/zstd) | |dev | [![Build Status](https://travis-ci.org/Cyan4973/zstd.svg?branch=dev)](https://travis-ci.org/Cyan4973/zstd) | -For a taste of its performance, here are a few benchmark numbers, completed on a Core i7-5600U @ 2.6 GHz, using [fsbench 0.14.3](http://encode.ru/threads/1371-Filesystem-benchmark?p=34029&viewfull=1#post34029), an open-source benchmark program by m^2. +For a taste of its performance, here are a few benchmark numbers from a number of compression codecs suitable for real-time. The test was completed on a Core i7-5600U @ 2.6 GHz, using [fsbench 0.14.3](http://encode.ru/threads/1371-Filesystem-benchmark?p=34029&viewfull=1#post34029), an open-source benchmark program by m^2. |Name | Ratio | C.speed | D.speed | |----------------|-------|--------:|--------:| | | | MB/s | MB/s | -| [zlib 1.2.8] -6| 3.099 | 21 | 320 | | **zstd 0.2** |**2.871**|**255**| **670** | | [zlib 1.2.8] -1| 2.730 | 70 | 300 | -| [LZ4] HC r131 | 2.720 | 25 | 2100 | | QuickLZ 1.5.1b6| 2.237 | 370 | 415 | | LZO 2.06 | 2.106 | 400 | 580 | | [LZ4] r131 | 2.101 | 450 | 2100 | @@ -25,10 +23,8 @@ For a taste of its performance, here are a few benchmark numbers, completed on a [zlib 1.2.8]:http://www.zlib.net/ [LZ4]:http://www.lz4.org/ -An interesting feature of zstd is that it can qualify as both a reasonably strong compressor and a fast one. - -Zstd delivers very high decompression speed, at more than >600 MB/s per core. -Obviously, your exact mileage will vary depending on your target system. +Zstd strong feature is its very high decompression speed, at more than >600 MB/s per core. +Obviously, your exact mileage will vary depending on target system. Zstd compression speed will be configurable to fit different situations. The first available version is the fast one, at ~250 MB/s per core, which is suitable for a few real-time scenarios. @@ -42,6 +38,7 @@ Another property zstd is developed for is configurable memory requirement, with Zstd entropy stage is provided by [Huff0 and FSE, from Finite State Entrop library](https://github.com/Cyan4973/FiniteStateEntropy). + Zstd has not yet reached "stable" status. Specifically, it doesn't guarantee yet that its current compressed format will remain stable and supported in future versions. It may still change to adapt further optimizations still being investigated. However, the library starts to be pretty robust, able to withstand hazards situations, including invalid input. The library reliability has been tested using [Fuzz Testing](https://en.wikipedia.org/wiki/Fuzz_testing), using both [internal tools](programs/fuzzer.c) and [external ones](http://lcamtuf.coredump.cx/afl). Therefore, you can now safely test zstd, even within production environments. "Stable Format" is projected sometimes early 2016. diff --git a/programs/paramgrill.c b/programs/paramgrill.c index 7e8e24bcf..afc81d4e1 100644 --- a/programs/paramgrill.c +++ b/programs/paramgrill.c @@ -452,8 +452,6 @@ static void BMK_printWinners2(FILE* f, const winnerInfo_t* winners, size_t srcSi for (cLevel=0; cLevel <= ZSTD_HC_MAX_CLEVEL; cLevel++) BMK_printWinner(f, cLevel, winners[cLevel].result, winners[cLevel].params, srcSize); - - fflush(f); } @@ -461,6 +459,7 @@ static void BMK_printWinners(FILE* f, const winnerInfo_t* winners, size_t srcSiz { fseek(f, 0, SEEK_SET); BMK_printWinners2(f, winners, srcSize); + fflush(f); BMK_printWinners2(stdout, winners, srcSize); } @@ -480,7 +479,7 @@ static int BMK_seed(winnerInfo_t* winners, ZSTD_HC_parameters params, if ( (testResult.cSpeed > g_cSpeedTarget[cLevel]) && (winners[cLevel].result.cSize==0) ) better = 1; /* first solution for this cLevel */ - if ( (testResult.cSpeed > g_cSpeedTarget[cLevel]) && (testResult.cSize < winners[cLevel].result.cSize )) + if ( (testResult.cSpeed > g_cSpeedTarget[cLevel]) && ((double)testResult.cSize <= (double)winners[cLevel].result.cSize * 1.001 )) { /* Validate solution is "good enough" */ double W_ratioNote = log ( (double)srcSize / testResult.cSize); @@ -495,8 +494,17 @@ static int BMK_seed(winnerInfo_t* winners, ZSTD_HC_parameters params, double W_CMemUsed_note = W_ratioNote * ( 35 + 5*cLevel) - log((double)W_CMemUsed); double O_CMemUsed_note = O_ratioNote * ( 35 + 5*cLevel) - log((double)O_CMemUsed); + double W_CSpeed_note = W_ratioNote * ( 20 + 3*cLevel) + log((double)testResult.cSpeed); + double O_CSpeed_note = O_ratioNote * ( 20 + 3*cLevel) + log((double)winners[cLevel].result.cSpeed); + + double W_DSpeed_note = W_ratioNote * ( 10 + cLevel) + log((double)testResult.dSpeed); + double O_DSpeed_note = O_ratioNote * ( 10 + cLevel) + log((double)winners[cLevel].result.dSpeed); + + if (W_DMemUsed_note < O_DMemUsed_note) continue; /* uses too much Decompression memory for too little benefit */ if (W_CMemUsed_note < O_CMemUsed_note) continue; /* uses too much memory for compression for too little benefit */ + if (W_CSpeed_note < O_CSpeed_note ) continue; /* too large compression speed difference for the compression benefit */ + if (W_DSpeed_note < O_DSpeed_note ) continue; /* too large decompression speed difference for the compression benefit */ better = 1; } @@ -652,7 +660,7 @@ static void BMK_benchMem(void* srcBuffer, size_t srcSize) } /* establish speed objectives (relative to level 1) */ - for (i=2; i> 4; /* populate initial solution */ @@ -886,7 +894,7 @@ int main(int argc, char** argv) break; } - /* target level9 objective, in MB/s */ + /* target level1 speed objective, in MB/s */ case 'T': argument++; g_target = 0; From 81e49e6654ee48dd3fbed11f16dcdc72a777c1cb Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 28 Oct 2015 15:56:48 +0100 Subject: [PATCH 22/37] fine tune & messages --- NEWS | 2 +- lib/zstdhc_static.h | 9 +++- programs/paramgrill.c | 97 +++++++++++++++++++++++++++++++------------ 3 files changed, 79 insertions(+), 29 deletions(-) diff --git a/NEWS b/NEWS index 8388dfceb..4c4c30019 100644 --- a/NEWS +++ b/NEWS @@ -1,7 +1,7 @@ v0.2.2 Fix : Visual Studio 2013 & 2015 release compilation, by Christophe Chevalier -v0.2.2 +v0.2.1 Fix : Read errors, advanced fuzzer tests, by Hanno Böck v0.2.0 diff --git a/lib/zstdhc_static.h b/lib/zstdhc_static.h index b1618adad..5bfc408cd 100644 --- a/lib/zstdhc_static.h +++ b/lib/zstdhc_static.h @@ -78,7 +78,7 @@ size_t ZSTD_HC_compress_advanced (ZSTD_HC_CCtx* ctx, /* ************************************* * Pre-defined compression levels ***************************************/ -#define ZSTD_HC_MAX_CLEVEL 20 +#define ZSTD_HC_MAX_CLEVEL 25 static const ZSTD_HC_parameters ZSTD_HC_defaultParameters[ZSTD_HC_MAX_CLEVEL+1] = { /* W, C, H, S */ { 18, 4, 12, 1 }, /* 0 - should never be used */ @@ -101,7 +101,12 @@ static const ZSTD_HC_parameters ZSTD_HC_defaultParameters[ZSTD_HC_MAX_CLEVEL+1] { 24, 24, 23, 11 }, /*17 */ { 24, 24, 23, 12 }, /*18 */ { 24, 24, 23, 13 }, /*19 */ - { 25, 25, 25, 22 }, /*20 - ultra-slow */ + { 24, 24, 23, 13 }, /*20 */ + { 24, 24, 23, 13 }, /*21 */ + { 24, 24, 23, 13 }, /*22 */ + { 24, 24, 23, 13 }, /*23 */ + { 24, 24, 23, 13 }, /*24 */ + { 24, 24, 23, 13 }, /*25 */ }; diff --git a/programs/paramgrill.c b/programs/paramgrill.c index afc81d4e1..8ac9a2c2c 100644 --- a/programs/paramgrill.c +++ b/programs/paramgrill.c @@ -464,7 +464,7 @@ static void BMK_printWinners(FILE* f, const winnerInfo_t* winners, size_t srcSiz } -static int BMK_seed(winnerInfo_t* winners, ZSTD_HC_parameters params, +static int BMK_seed(winnerInfo_t* winners, const ZSTD_HC_parameters params, const void* srcBuffer, size_t srcSize, ZSTD_HC_CCtx* ctx) { @@ -474,47 +474,91 @@ static int BMK_seed(winnerInfo_t* winners, ZSTD_HC_parameters params, BMK_benchParam(&testResult, srcBuffer, srcSize, ctx, params); - for (cLevel = 0; cLevel <= ZSTD_HC_MAX_CLEVEL; cLevel++) + for (cLevel = 1; cLevel <= ZSTD_HC_MAX_CLEVEL; cLevel++) { - if ( (testResult.cSpeed > g_cSpeedTarget[cLevel]) && (winners[cLevel].result.cSize==0) ) - better = 1; /* first solution for this cLevel */ + if (testResult.cSpeed < g_cSpeedTarget[cLevel]) + continue; /* not fast enough for this level */ + if (winners[cLevel].result.cSize==0) + { + /* first solution for this cLevel */ + winners[cLevel].result = testResult; + winners[cLevel].params = params; + BMK_printWinner(stdout, cLevel, testResult, params, srcSize); + better = 1; + continue; + } - if ( (testResult.cSpeed > g_cSpeedTarget[cLevel]) && ((double)testResult.cSize <= (double)winners[cLevel].result.cSize * 1.001 )) + if ((double)testResult.cSize <= ((double)winners[cLevel].result.cSize * (1. + (0.01 / cLevel))) ) { /* Validate solution is "good enough" */ - double W_ratioNote = log ( (double)srcSize / testResult.cSize); - double O_ratioNote = log ( (double)srcSize / winners[cLevel].result.cSize); + double W_ratio = (double)srcSize / testResult.cSize; + double O_ratio = (double)srcSize / winners[cLevel].result.cSize; + double W_ratioNote = log (W_ratio); + double O_ratioNote = log (O_ratio); size_t W_DMemUsed = (1 << params.windowLog) + (16 KB); size_t O_DMemUsed = (1 << winners[cLevel].params.windowLog) + (16 KB); - double W_DMemUsed_note = W_ratioNote * ( 18 + 2*cLevel) - log((double)W_DMemUsed); - double O_DMemUsed_note = O_ratioNote * ( 18 + 2*cLevel) - log((double)O_DMemUsed); + double W_DMemUsed_note = W_ratioNote * ( 25 + 8*cLevel) - log((double)W_DMemUsed); + double O_DMemUsed_note = O_ratioNote * ( 25 + 8*cLevel) - log((double)O_DMemUsed); size_t W_CMemUsed = (1 << params.windowLog) + 4 * (1 << params.hashLog) + 4 * (1 << params.chainLog); size_t O_CMemUsed = (1 << winners[cLevel].params.windowLog) + 4 * (1 << winners[cLevel].params.hashLog) + 4 * (1 << winners[cLevel].params.chainLog); - double W_CMemUsed_note = W_ratioNote * ( 35 + 5*cLevel) - log((double)W_CMemUsed); - double O_CMemUsed_note = O_ratioNote * ( 35 + 5*cLevel) - log((double)O_CMemUsed); + double W_CMemUsed_note = W_ratioNote * ( 50 + 13*cLevel) - log((double)W_CMemUsed); + double O_CMemUsed_note = O_ratioNote * ( 50 + 13*cLevel) - log((double)O_CMemUsed); - double W_CSpeed_note = W_ratioNote * ( 20 + 3*cLevel) + log((double)testResult.cSpeed); - double O_CSpeed_note = O_ratioNote * ( 20 + 3*cLevel) + log((double)winners[cLevel].result.cSpeed); + double W_CSpeed_note = W_ratioNote * ( 30 + 8*cLevel) + log((double)testResult.cSpeed); + double O_CSpeed_note = O_ratioNote * ( 30 + 8*cLevel) + log((double)winners[cLevel].result.cSpeed); - double W_DSpeed_note = W_ratioNote * ( 10 + cLevel) + log((double)testResult.dSpeed); - double O_DSpeed_note = O_ratioNote * ( 10 + cLevel) + log((double)winners[cLevel].result.dSpeed); + double W_DSpeed_note = W_ratioNote * ( 20 + 2*cLevel) + log((double)testResult.dSpeed); + double O_DSpeed_note = O_ratioNote * ( 20 + 2*cLevel) + log((double)winners[cLevel].result.dSpeed); - if (W_DMemUsed_note < O_DMemUsed_note) continue; /* uses too much Decompression memory for too little benefit */ - if (W_CMemUsed_note < O_CMemUsed_note) continue; /* uses too much memory for compression for too little benefit */ - if (W_CSpeed_note < O_CSpeed_note ) continue; /* too large compression speed difference for the compression benefit */ - if (W_DSpeed_note < O_DSpeed_note ) continue; /* too large decompression speed difference for the compression benefit */ + if (W_DMemUsed_note < O_DMemUsed_note) + { + /* uses too much Decompression memory for too little benefit */ + if (W_ratio > O_ratio) + DISPLAY ("Decompression Memory : %5.3f @ %4.1f MB vs %5.3f @ %4.1f MB : not enough for level %i\n", + W_ratio, (double)(W_DMemUsed) / 1024 / 1024, + O_ratio, (double)(O_DMemUsed) / 1024 / 1024, cLevel); + continue; + } + if (W_CMemUsed_note < O_CMemUsed_note) + { + /* uses too much memory for compression for too little benefit */ + if (W_ratio > O_ratio) + DISPLAY ("Compression Memory : %5.3f @ %4.1f MB vs %5.3f @ %4.1f MB : not enough for level %i\n", + W_ratio, (double)(W_CMemUsed) / 1024 / 1024, + O_ratio, (double)(O_CMemUsed) / 1024 / 1024, cLevel); + continue; + } + if (W_CSpeed_note < O_CSpeed_note ) + { + /* too large compression speed difference for the compression benefit */ + if (W_ratio > O_ratio) + DISPLAY ("Compression Speed : %5.3f @ %4.1f MB/s vs %5.3f @ %4.1f MB/s : not enough for level %i\n", + W_ratio, (double)(testResult.cSpeed) / 1000., + O_ratio, (double)(winners[cLevel].result.cSpeed) / 1000., cLevel); + continue; + } + if (W_DSpeed_note < O_DSpeed_note ) + { + /* too large decompression speed difference for the compression benefit */ + if (W_ratio > O_ratio) + DISPLAY ("Decompression Speed : %5.3f @ %4.1f MB/s vs %5.3f @ %4.1f MB/s : not enough for level %i\n", + W_ratio, (double)(testResult.dSpeed) / 1000., + O_ratio, (double)(winners[cLevel].result.dSpeed) / 1000., cLevel); + continue; + } + + if (W_ratio < O_ratio) + DISPLAY("Solution %4.3f selected over %4.3f at level %i, due to better secondary statistics \n", W_ratio, O_ratio, cLevel); + + winners[cLevel].result = testResult; + winners[cLevel].params = params; + BMK_printWinner(stdout, cLevel, testResult, params, srcSize); better = 1; } - if (better) - { - winners[cLevel].result = testResult; - winners[cLevel].params = params; - BMK_printWinner(stdout, cLevel, testResult, params, srcSize); - } } return better; @@ -665,7 +709,8 @@ static void BMK_benchMem(void* srcBuffer, size_t srcSize) /* populate initial solution */ { - const int maxSeeds = g_noSeed ? 1 : ZSTD_HC_MAX_CLEVEL; + const int maxSeeds = g_noSeed ? 1 : 13; + //const int maxSeeds = g_noSeed ? 1 : ZSTD_HC_MAX_CLEVEL; //BMK_seed(winners, params, srcBuffer, srcSize, ctx); for (i=1; i<=maxSeeds; i++) { From 76c5c2a4a00a918a0e9d6a91325ce99147f36a1f Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Wed, 28 Oct 2015 19:07:05 +0100 Subject: [PATCH 23/37] minor tuning --- lib/zstdhc_static.h | 56 ++++++++++++++++++++++--------------------- programs/paramgrill.c | 8 +++---- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/lib/zstdhc_static.h b/lib/zstdhc_static.h index 5bfc408cd..0492d2297 100644 --- a/lib/zstdhc_static.h +++ b/lib/zstdhc_static.h @@ -55,7 +55,7 @@ typedef struct /* parameters boundaries */ #define ZSTD_HC_WINDOWLOG_MAX 26 -#define ZSTD_HC_WINDOWLOG_MIN 17 +#define ZSTD_HC_WINDOWLOG_MIN 18 #define ZSTD_HC_CHAINLOG_MAX ZSTD_HC_WINDOWLOG_MAX #define ZSTD_HC_CHAINLOG_MIN 4 #define ZSTD_HC_HASHLOG_MAX 28 @@ -81,35 +81,37 @@ size_t ZSTD_HC_compress_advanced (ZSTD_HC_CCtx* ctx, #define ZSTD_HC_MAX_CLEVEL 25 static const ZSTD_HC_parameters ZSTD_HC_defaultParameters[ZSTD_HC_MAX_CLEVEL+1] = { /* W, C, H, S */ - { 18, 4, 12, 1 }, /* 0 - should never be used */ - { 18, 11, 14, 1 }, /* 1 */ - { 20, 13, 16, 2 }, /* 2 */ - { 20, 19, 20, 2 }, /* 3 */ - { 21, 19, 20, 4 }, /* 4 */ - { 21, 20, 21, 4 }, /* 5 */ - { 21, 20, 22, 5 }, /* 6 */ - { 21, 20, 22, 6 }, /* 7 */ - { 21, 20, 22, 7 }, /* 8 */ - { 21, 21, 23, 7 }, /* 9 */ - { 21, 21, 23, 8 }, /*10 */ - { 21, 21, 23, 9 }, /*11 */ - { 21, 21, 23, 10 }, /*12 */ - { 22, 22, 23, 9 }, /*13 */ - { 22, 22, 23, 10 }, /*14 */ - { 23, 23, 23, 10 }, /*15 */ - { 24, 23, 23, 11 }, /*16 */ - { 24, 24, 23, 11 }, /*17 */ - { 24, 24, 23, 12 }, /*18 */ - { 24, 24, 23, 13 }, /*19 */ - { 24, 24, 23, 13 }, /*20 */ - { 24, 24, 23, 13 }, /*21 */ - { 24, 24, 23, 13 }, /*22 */ - { 24, 24, 23, 13 }, /*23 */ - { 24, 24, 23, 13 }, /*24 */ - { 24, 24, 23, 13 }, /*25 */ + { 18, 12, 14, 1 }, /* level 0 - never used */ + { 18, 12, 15, 2 }, /* level 1 */ + { 19, 14, 16, 3 }, /* level 2 */ + { 20, 19, 19, 2 }, /* level 3 */ + { 20, 19, 19, 3 }, /* level 4 */ + { 20, 19, 19, 4 }, /* level 5 */ + { 20, 20, 19, 4 }, /* level 6 */ + { 20, 19, 19, 5 }, /* level 7 */ + { 20, 19, 19, 6 }, /* level 8 */ + { 20, 20, 20, 6 }, /* level 9 */ + { 21, 20, 21, 6 }, /* level 10 */ + { 21, 20, 21, 7 }, /* level 11 */ + { 21, 20, 22, 7 }, /* level 12 */ + { 21, 21, 23, 7 }, /* level 13 */ + { 21, 21, 23, 7 }, /* level 14 */ + { 21, 21, 23, 8 }, /* level 15 */ + { 21, 21, 23, 9 }, /* level 16 */ + { 21, 21, 23, 9 }, /* level 17 */ + { 21, 21, 23, 10 }, /* level 18 */ + { 22, 22, 23, 9 }, /* level 19 */ + { 22, 22, 23, 9 }, /* level 20 */ + { 22, 22, 23, 10 }, /* level 21 */ + { 22, 22, 23, 10 }, /* level 22 */ + { 22, 22, 23, 11 }, /* level 23 */ + { 22, 22, 23, 12 }, /* level 24 */ + { 23, 23, 23, 11 }, /* level 25 */ }; + + #if defined (__cplusplus) } #endif diff --git a/programs/paramgrill.c b/programs/paramgrill.c index 8ac9a2c2c..772eaad1f 100644 --- a/programs/paramgrill.c +++ b/programs/paramgrill.c @@ -497,8 +497,8 @@ static int BMK_seed(winnerInfo_t* winners, const ZSTD_HC_parameters params, double O_ratioNote = log (O_ratio); size_t W_DMemUsed = (1 << params.windowLog) + (16 KB); size_t O_DMemUsed = (1 << winners[cLevel].params.windowLog) + (16 KB); - double W_DMemUsed_note = W_ratioNote * ( 25 + 8*cLevel) - log((double)W_DMemUsed); - double O_DMemUsed_note = O_ratioNote * ( 25 + 8*cLevel) - log((double)O_DMemUsed); + double W_DMemUsed_note = W_ratioNote * ( 40 + 9*cLevel) - log((double)W_DMemUsed); + double O_DMemUsed_note = O_ratioNote * ( 40 + 9*cLevel) - log((double)O_DMemUsed); size_t W_CMemUsed = (1 << params.windowLog) + 4 * (1 << params.hashLog) + 4 * (1 << params.chainLog); size_t O_CMemUsed = (1 << winners[cLevel].params.windowLog) + 4 * (1 << winners[cLevel].params.hashLog) + 4 * (1 << winners[cLevel].params.chainLog); @@ -709,9 +709,7 @@ static void BMK_benchMem(void* srcBuffer, size_t srcSize) /* populate initial solution */ { - const int maxSeeds = g_noSeed ? 1 : 13; - //const int maxSeeds = g_noSeed ? 1 : ZSTD_HC_MAX_CLEVEL; - //BMK_seed(winners, params, srcBuffer, srcSize, ctx); + const int maxSeeds = g_noSeed ? 1 : ZSTD_HC_MAX_CLEVEL; for (i=1; i<=maxSeeds; i++) { params = seedParams[i]; From 2acb5d3d48c454a0d35c9b9064864bd5c04f7793 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 29 Oct 2015 16:49:43 +0100 Subject: [PATCH 24/37] HC modes can be selected from command line --- lib/zstd.c | 27 +++-- lib/zstd_Ccommon.h | 243 ++++++++++++++++++++++++++++++++++++++++++ lib/zstd_static.h | 190 --------------------------------- lib/zstdhc.c | 179 +++++++++++++------------------ lib/zstdhc.h | 4 +- lib/zstdhc_static.h | 17 ++- programs/Makefile | 2 +- programs/bench.c | 17 ++- programs/fileio.c | 76 +++++++++++-- programs/fileio.h | 2 +- programs/paramgrill.c | 2 +- programs/zstdcli.c | 2 + 12 files changed, 426 insertions(+), 335 deletions(-) create mode 100644 lib/zstd_Ccommon.h diff --git a/lib/zstd.c b/lib/zstd.c index 8493b43a7..0edde3ac9 100644 --- a/lib/zstd.c +++ b/lib/zstd.c @@ -68,6 +68,7 @@ #include /* debug : printf */ #include "mem.h" /* low level memory routines */ #include "zstd_static.h" +#include "zstd_Ccommon.h" #include "fse_static.h" #include "huff0.h" @@ -527,20 +528,24 @@ size_t ZSTD_compressSequences(BYTE* dst, size_t maxDstSize, //static const U32 hashMask = (1<> (64-HASH_LOG)); } //static U32 ZSTD_hashPtr(const void* p) { return ( (*(U64*)p * prime7bytes) >> (56-HASH_LOG)) & ((1<> (64-HASH_LOG)); } +//static const U64 prime8bytes = 14923729446516375013ULL; //static U32 ZSTD_hashPtr(const void* p) { return ( (*(U64*)p * prime8bytes) >> (64-HASH_LOG)); } + +static const U64 prime7bytes = 58295818150454627ULL; static U32 ZSTD_hashPtr(const void* p) { return ( (MEM_read64(p) * prime7bytes) >> (56-HASH_LOG)) & HASH_MASK; } -//static U32 ZSTD_hashPtr(const void* p) { return ( (*(U64*)p * prime6bytes) >> (48-HASH_LOG)) & HASH_MASK; } + +//static const U64 prime6bytes = 227718039650203ULL; +//static U32 ZSTD_hashPtr(const void* p) { return ( (MEM_read64(p) * prime6bytes) >> (48-HASH_LOG)) & HASH_MASK; } + +//static const U64 prime5bytes = 889523592379ULL; //static U32 ZSTD_hashPtr(const void* p) { return ( (*(U64*)p * prime5bytes) >> (40-HASH_LOG)) & HASH_MASK; } + //static U32 ZSTD_hashPtr(const void* p) { return ( (*(U32*)p * KNUTH) >> (32-HASH_LOG)); } static void ZSTD_addPtr(U32* table, const BYTE* p, const BYTE* start) { table[ZSTD_hashPtr(p)] = (U32)(p-start); } @@ -572,7 +577,7 @@ static size_t ZSTD_compressBlock(ZSTD_CCtx* ctx, void* dst, size_t maxDstSize, c const BYTE* const iend = istart + srcSize; const BYTE* const ilimit = iend - 8; - size_t prevOffset=4, offset=4; + size_t offset_2=4, offset_1=4; /* init */ @@ -591,11 +596,11 @@ static size_t ZSTD_compressBlock(ZSTD_CCtx* ctx, void* dst, size_t maxDstSize, c size_t litLength = ip-anchor; size_t matchLength = ZSTD_count(ip+MINMATCH, match+MINMATCH, iend); size_t offsetCode; - if (litLength) prevOffset = offset; + if (litLength) offset_2 = offset_1; offsetCode = ip-match; - if (offsetCode == prevOffset) offsetCode = 0; - prevOffset = offset; - offset = ip-match; + if (offsetCode == offset_2) offsetCode = 0; + offset_2 = offset_1; + offset_1 = ip-match; ZSTD_storeSeq(seqStorePtr, litLength, anchor, offsetCode, matchLength); /* Fill Table */ @@ -1159,7 +1164,7 @@ static size_t ZSTD_execSequence(BYTE* op, /* check */ if (oLitEnd > oend_8) return ERROR(dstSize_tooSmall); /* last match must start at a minimum distance of 8 from oend */ if (oMatchEnd > oend) return ERROR(dstSize_tooSmall); /* overwrite beyond dst buffer */ - if (litEnd > litLimit_8) return ERROR(corruption_detected); /* overRead beyond lit buffer */ + if (litEnd > litLimit_8) return ERROR(corruption_detected); /* risk read beyond lit buffer */ /* copy Literals */ ZSTD_wildcopy(op, *litPtr, sequence.litLength); /* note : oLitEnd <= oend-8 : no risk of overwrite beyond oend */ diff --git a/lib/zstd_Ccommon.h b/lib/zstd_Ccommon.h new file mode 100644 index 000000000..5cbd70b8b --- /dev/null +++ b/lib/zstd_Ccommon.h @@ -0,0 +1,243 @@ +/* + zstd_CCommon - common functions + Header File for include + Copyright (C) 2014-2015, 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 : + - zstd source repository : https://github.com/Cyan4973/zstd + - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c +*/ +#ifndef ZSTD_CCOMMON_H_MODULE +#define ZSTD_CCOMMON_H_MODULE + +#if defined (__cplusplus) +extern "C" { +#endif + +/* ************************************* +* Includes +***************************************/ +#include "mem.h" +#include "error.h" + + +/* ************************************* +* Function body to include +***************************************/ +static size_t ZSTD_read_ARCH(const void* p) { size_t r; memcpy(&r, p, sizeof(r)); return r; } + +MEM_STATIC unsigned ZSTD_NbCommonBytes (register size_t val) +{ + if (MEM_isLittleEndian()) + { + if (MEM_64bits()) + { +# if defined(_MSC_VER) && defined(_WIN64) + unsigned long r = 0; + _BitScanForward64( &r, (U64)val ); + return (int)(r>>3); +# elif defined(__GNUC__) && (__GNUC__ >= 3) + return (__builtin_ctzll((U64)val) >> 3); +# else + static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 }; + return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58]; +# endif + } + else /* 32 bits */ + { +# if defined(_MSC_VER) + unsigned long r; + _BitScanForward( &r, (U32)val ); + return (int)(r>>3); +# elif defined(__GNUC__) && (__GNUC__ >= 3) + return (__builtin_ctz((U32)val) >> 3); +# else + static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 }; + return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27]; +# endif + } + } + else /* Big Endian CPU */ + { + if (MEM_32bits()) + { +# if defined(_MSC_VER) && defined(_WIN64) + unsigned long r = 0; + _BitScanReverse64( &r, val ); + return (unsigned)(r>>3); +# elif defined(__GNUC__) && (__GNUC__ >= 3) + return (__builtin_clzll(val) >> 3); +# else + unsigned r; + const unsigned n32 = sizeof(size_t)*4; /* calculate this way due to compiler complaining in 32-bits mode */ + if (!(val>>n32)) { r=4; } else { r=0; val>>=n32; } + if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; } + r += (!val); + return r; +# endif + } + else /* 32 bits */ + { +# if defined(_MSC_VER) + unsigned long r = 0; + _BitScanReverse( &r, (unsigned long)val ); + return (unsigned)(r>>3); +# elif defined(__GNUC__) && (__GNUC__ >= 3) + return (__builtin_clz((U32)val) >> 3); +# else + unsigned r; + if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; } + r += (!val); + return r; +# endif + } + } +} + + +MEM_STATIC size_t ZSTD_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit) +{ + const BYTE* const pStart = pIn; + + while ((pInlit, literals, litLength); + seqStorePtr->lit += litLength; + + /* literal Length */ + if (litLength >= MaxLL) + { + *(seqStorePtr->litLength++) = MaxLL; + if (litLength<255 + MaxLL) + *(seqStorePtr->dumps++) = (BYTE)(litLength - MaxLL); + else + { + *(seqStorePtr->dumps++) = 255; + MEM_writeLE32(seqStorePtr->dumps, (U32)litLength); seqStorePtr->dumps += 3; + } + } + else *(seqStorePtr->litLength++) = (BYTE)litLength; + + /* match offset */ + *(seqStorePtr->offset++) = (U32)offsetCode; + + /* match Length */ + if (matchCode >= MaxML) + { + *(seqStorePtr->matchLength++) = MaxML; + if (matchCode < 255+MaxML) + *(seqStorePtr->dumps++) = (BYTE)(matchCode - MaxML); + else + { + *(seqStorePtr->dumps++) = 255; + MEM_writeLE32(seqStorePtr->dumps, (U32)matchCode); seqStorePtr->dumps += 3; + } + } + else *(seqStorePtr->matchLength++) = (BYTE)matchCode; +} + + +/* prototype, body into zstd.c */ +size_t ZSTD_compressSequences(BYTE* dst, size_t maxDstSize, const seqStore_t* seqStorePtr, size_t srcSize); + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_CCOMMON_H_MODULE */ diff --git a/lib/zstd_static.h b/lib/zstd_static.h index 147dcd0c6..498aa81cf 100644 --- a/lib/zstd_static.h +++ b/lib/zstd_static.h @@ -82,196 +82,6 @@ size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, co #include "error.h" -/* ************************************* -* Function body to include -***************************************/ -#include "mem.h" -static size_t ZSTD_read_ARCH(const void* p) { size_t r; memcpy(&r, p, sizeof(r)); return r; } - -MEM_STATIC unsigned ZSTD_NbCommonBytes (register size_t val) -{ - if (MEM_isLittleEndian()) - { - if (MEM_64bits()) - { -# if defined(_MSC_VER) && defined(_WIN64) - unsigned long r = 0; - _BitScanForward64( &r, (U64)val ); - return (int)(r>>3); -# elif defined(__GNUC__) && (__GNUC__ >= 3) - return (__builtin_ctzll((U64)val) >> 3); -# else - static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 }; - return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58]; -# endif - } - else /* 32 bits */ - { -# if defined(_MSC_VER) - unsigned long r; - _BitScanForward( &r, (U32)val ); - return (int)(r>>3); -# elif defined(__GNUC__) && (__GNUC__ >= 3) - return (__builtin_ctz((U32)val) >> 3); -# else - static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 }; - return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27]; -# endif - } - } - else /* Big Endian CPU */ - { - if (MEM_32bits()) - { -# if defined(_MSC_VER) && defined(_WIN64) - unsigned long r = 0; - _BitScanReverse64( &r, val ); - return (unsigned)(r>>3); -# elif defined(__GNUC__) && (__GNUC__ >= 3) - return (__builtin_clzll(val) >> 3); -# else - unsigned r; - const unsigned n32 = sizeof(size_t)*4; /* calculate this way due to compiler complaining in 32-bits mode */ - if (!(val>>n32)) { r=4; } else { r=0; val>>=n32; } - if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; } - r += (!val); - return r; -# endif - } - else /* 32 bits */ - { -# if defined(_MSC_VER) - unsigned long r = 0; - _BitScanReverse( &r, (unsigned long)val ); - return (unsigned)(r>>3); -# elif defined(__GNUC__) && (__GNUC__ >= 3) - return (__builtin_clz((U32)val) >> 3); -# else - unsigned r; - if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; } - r += (!val); - return r; -# endif - } - } -} - - -MEM_STATIC size_t ZSTD_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit) -{ - const BYTE* const pStart = pIn; - - while ((pInlit, literals, litLength); - seqStorePtr->lit += litLength; - - /* literal Length */ - if (litLength >= MaxLL) - { - *(seqStorePtr->litLength++) = MaxLL; - if (litLength<255 + MaxLL) - *(seqStorePtr->dumps++) = (BYTE)(litLength - MaxLL); - else - { - *(seqStorePtr->dumps++) = 255; - MEM_writeLE32(seqStorePtr->dumps, (U32)litLength); seqStorePtr->dumps += 3; - } - } - else *(seqStorePtr->litLength++) = (BYTE)litLength; - - /* match offset */ - *(seqStorePtr->offset++) = (U32)offsetCode; - - /* match Length */ - if (matchCode >= MaxML) - { - *(seqStorePtr->matchLength++) = MaxML; - if (matchCode < 255+MaxML) - *(seqStorePtr->dumps++) = (BYTE)(matchCode - MaxML); - else - { - *(seqStorePtr->dumps++) = 255; - MEM_writeLE32(seqStorePtr->dumps, (U32)matchCode); seqStorePtr->dumps += 3; - } - } - else *(seqStorePtr->matchLength++) = (BYTE)matchCode; -} - -size_t ZSTD_compressSequences(BYTE* dst, size_t maxDstSize, const seqStore_t* seqStorePtr, size_t srcSize); - #if defined (__cplusplus) } #endif diff --git a/lib/zstdhc.c b/lib/zstdhc.c index 5a79b9f8b..b3b711dbc 100644 --- a/lib/zstdhc.c +++ b/lib/zstdhc.c @@ -39,6 +39,7 @@ #include /* memset */ #include "zstdhc_static.h" #include "zstd_static.h" +#include "zstd_Ccommon.h" #include "mem.h" @@ -73,8 +74,7 @@ struct ZSTD_HC_CCtx_s U32 lowLimit; /* below that point, no more data */ U32 nextToUpdate; /* index from which to continue dictionary update */ ZSTD_HC_parameters params; - U32 hashTableLog; - U32 chainTableLog; + size_t tableSpace; U32* hashTable; U32* chainTable; seqStore_t seqStore; /* sequences storage ptrs */ @@ -86,47 +86,49 @@ ZSTD_HC_CCtx* ZSTD_HC_createCCtx(void) { ZSTD_HC_CCtx* ctx = (ZSTD_HC_CCtx*) malloc(sizeof(ZSTD_HC_CCtx)); ctx->hashTable = NULL; - ctx->chainTable = NULL; - ctx->hashTableLog = 0; - ctx->chainTableLog = 0; + ctx->tableSpace = 0; return ctx; } size_t ZSTD_HC_freeCCtx(ZSTD_HC_CCtx* cctx) { free(cctx->hashTable); - free(cctx->chainTable); free(cctx); return 0; } static void ZSTD_HC_resetCCtx_advanced (ZSTD_HC_CCtx* zc, - const ZSTD_HC_parameters params, const void* start) + ZSTD_HC_parameters params) { - U32 outOfReach = ( 1 << params.searchLog) + 1; + /* validate params */ + if (params.windowLog > ZSTD_HC_WINDOWLOG_MAX) params.windowLog = ZSTD_HC_WINDOWLOG_MAX; + if (params.windowLog < ZSTD_HC_WINDOWLOG_MIN) params.windowLog = ZSTD_HC_WINDOWLOG_MIN; + if (params.chainLog > params.windowLog) params.chainLog = params.windowLog; /* <= ZSTD_HC_CHAINLOG_MAX */ + if (params.chainLog < ZSTD_HC_CHAINLOG_MIN) params.chainLog = ZSTD_HC_CHAINLOG_MIN; + if (params.hashLog > ZSTD_HC_HASHLOG_MAX) params.hashLog = ZSTD_HC_HASHLOG_MAX; + if (params.hashLog < ZSTD_HC_HASHLOG_MIN) params.hashLog = ZSTD_HC_HASHLOG_MIN; + if (params.searchLog > ZSTD_HC_SEARCHLOG_MAX) params.searchLog = ZSTD_HC_SEARCHLOG_MAX; + if (params.searchLog < ZSTD_HC_SEARCHLOG_MIN) params.searchLog = ZSTD_HC_SEARCHLOG_MIN; - if (zc->hashTableLog < params.hashLog) + /* reserve table memory */ { - free(zc->hashTable); - zc->hashTableLog = params.hashLog; - zc->hashTable = (U32*) malloc ( (1 << zc->hashTableLog) * sizeof(U32) ); + const size_t neededSpace = ((1 << params.chainLog) + (1 << params.hashLog)) * sizeof(U32); + if (neededSpace > zc->tableSpace) + { + free(zc->hashTable); + zc->tableSpace = neededSpace; + zc->hashTable = (U32*) malloc ( neededSpace ); + } + zc->chainTable = zc->hashTable + (1 << params.hashLog); + memset(zc->hashTable, 0, neededSpace ); } - memset(zc->hashTable, 0, (1 << params.hashLog) * sizeof(U32) ); - if (zc->chainTableLog < params.chainLog) - { - free(zc->chainTable); - zc->chainTableLog = params.chainLog; - zc->chainTable = (U32*) malloc ( (1 << zc->chainTableLog) * sizeof(U32) ); - } - memset(zc->chainTable, 0, (1 << params.chainLog) * sizeof(U32) ); - - zc->nextToUpdate = outOfReach; - zc->end = (const BYTE*)start; - zc->base = zc->end - outOfReach; - zc->dictBase = zc->base; - zc->dictLimit = outOfReach; - zc->lowLimit = outOfReach; + zc->nextToUpdate = 0; + zc->end = NULL; + zc->base = NULL; + zc->dictBase = NULL; + zc->dictLimit = 0; + zc->lowLimit = 0; zc->params = params; zc->seqStore.buffer = zc->buffer; zc->seqStore.offsetStart = (U32*) (zc->seqStore.buffer); @@ -135,17 +137,23 @@ static void ZSTD_HC_resetCCtx_advanced (ZSTD_HC_CCtx* zc, zc->seqStore.litLengthStart = zc->seqStore.litStart + BLOCKSIZE; zc->seqStore.matchLengthStart = zc->seqStore.litLengthStart + (BLOCKSIZE>>2); zc->seqStore.dumpsStart = zc->seqStore.matchLengthStart + (BLOCKSIZE>>2); + } /* ************************************* * Local Macros ***************************************/ + #define KNUTH 2654435761U static U32 ZSTD_HC_hash(U32 u, U32 h) { return (u * KNUTH) >> (32-h) ; } +static U32 ZSTD_HC_hashPtr(const void* ptr, U32 h) { return ZSTD_HC_hash(MEM_read32(ptr), h); } + +//static const U64 prime5bytes = 889523592379ULL; +//static U32 ZSTD_HC_hashPtr(const void* p, U32 h) { return ((MEM_read64(p) * prime5bytes) << (64-40)) >> (64-h); } + #define NEXT_IN_CHAIN(d) chainTable[(d) & chainMask] /* flexible, CHAINSIZE dependent */ -static U32 ZSTD_HC_hashPtr(const void* ptr, U32 h) { return ZSTD_HC_hash(MEM_read32(ptr), h); } /* ************************************* @@ -369,87 +377,60 @@ static size_t ZSTD_HC_compress_generic (ZSTD_HC_CCtx* ctxPtr, } -size_t ZSTD_HC_loadDict(ZSTD_HC_CCtx* ctx, const void* dictionary, size_t dictSize) +size_t ZSTD_HC_compressContinue (ZSTD_HC_CCtx* ctxPtr, + void* dst, size_t dstSize, + const void* src, size_t srcSize) { - /* TBD */ - (void)ctx; (void)dictionary; (void)dictSize; - return 0; -} - -static void ZSTD_HC_setExternalDict(ZSTD_HC_CCtx* ctxPtr, const void* newBlock) -{ - if (ctxPtr->end >= ctxPtr->base + 4) - ZSTD_HC_insert (ctxPtr, ctxPtr->end-3); /* Referencing remaining dictionary content */ - /* Only one memory segment for extDict, so any previous extDict is lost at this stage */ - ctxPtr->lowLimit = ctxPtr->dictLimit; - ctxPtr->dictLimit = (U32)(ctxPtr->end - ctxPtr->base); - ctxPtr->dictBase = ctxPtr->base; - ctxPtr->base = (const BYTE*)newBlock - ctxPtr->dictLimit; - ctxPtr->end = (const BYTE*)newBlock; - ctxPtr->nextToUpdate = ctxPtr->dictLimit; /* match referencing will resume from there */ -} - -size_t ZSTD_HC_compress_continue (ZSTD_HC_CCtx* ctxPtr, - void* dst, size_t dstSize, - const void* src, size_t srcSize) -{ - const U32 maxDistance = 1 << ctxPtr->params.windowLog; - - /* Check overflow */ - if ((size_t)(ctxPtr->end - ctxPtr->base) > 2 GB) - { - size_t dictSize = (size_t)(ctxPtr->end - ctxPtr->base) - ctxPtr->dictLimit; - if (dictSize > maxDistance) dictSize = maxDistance; - - ZSTD_HC_loadDict(ctxPtr, ctxPtr->end - dictSize, dictSize); - } + const BYTE* const ip = (const BYTE*) src; /* Check if blocks follow each other */ - if ((const BYTE*)src != ctxPtr->end) - ZSTD_HC_setExternalDict(ctxPtr, (const BYTE*)src); - - /* Check overlapping src/dictionary space (typical of cycling buffers) */ + if (ip != ctxPtr->end) { - const BYTE* sourceEnd = (const BYTE*) src + srcSize; - const BYTE* dictBegin = ctxPtr->dictBase + ctxPtr->lowLimit; - const BYTE* dictEnd = ctxPtr->dictBase + ctxPtr->dictLimit; - if ((sourceEnd > dictBegin) && ((const BYTE*)src < dictEnd)) - { - if (sourceEnd > dictEnd) sourceEnd = dictEnd; - ctxPtr->lowLimit = (U32)(sourceEnd - ctxPtr->dictBase); - if (ctxPtr->dictLimit - ctxPtr->lowLimit < 4) ctxPtr->lowLimit = ctxPtr->dictLimit; - } + if (ctxPtr->end != NULL) + ZSTD_HC_resetCCtx_advanced(ctxPtr, ctxPtr->params); /* reset */ + ctxPtr->base = ip; } + ctxPtr->end = ip + srcSize; return ZSTD_HC_compress_generic (ctxPtr, dst, dstSize, src, srcSize); } size_t ZSTD_HC_compressBegin_advanced(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, - const ZSTD_HC_parameters params, const void* src) + const ZSTD_HC_parameters params) { - /* Sanity check */ if (maxDstSize < 4) return ERROR(dstSize_tooSmall); - - /* Init */ - ZSTD_HC_resetCCtx_advanced(ctx, params, src); - - /* Write Header */ - MEM_writeLE32(dst, ZSTD_magicNumber); - + ZSTD_HC_resetCCtx_advanced(ctx, params); + MEM_writeLE32(dst, ZSTD_magicNumber); /* Write Header */ return 4; } -size_t ZSTD_HC_compressBegin(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, unsigned compressionLevel, const void* src) +size_t ZSTD_HC_compressBegin(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, int compressionLevel) { - if (compressionLevel==0) compressionLevel = ZSTD_HC_compressionLevel_default; + if (compressionLevel<=0) compressionLevel = 1; if (compressionLevel > ZSTD_HC_MAX_CLEVEL) compressionLevel = ZSTD_HC_MAX_CLEVEL; - return ZSTD_HC_compressBegin_advanced(ctx, dst, maxDstSize, ZSTD_HC_defaultParameters[compressionLevel], src); + return ZSTD_HC_compressBegin_advanced(ctx, dst, maxDstSize, ZSTD_HC_defaultParameters[compressionLevel]); } +size_t ZSTD_HC_compressEnd(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize) +{ + BYTE* op = (BYTE*)dst; + + /* Sanity check */ + (void)ctx; + if (maxDstSize < 3) return ERROR(dstSize_tooSmall); + + /* End of frame */ + op[0] = (BYTE)(bt_end << 6); + op[1] = 0; + op[2] = 0; + + return 3; +} + size_t ZSTD_HC_compress_advanced (ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize, @@ -459,51 +440,37 @@ size_t ZSTD_HC_compress_advanced (ZSTD_HC_CCtx* ctx, BYTE* op = ostart; /* Header */ - size_t oSize = ZSTD_HC_compressBegin_advanced(ctx, dst, maxDstSize, params, src); + size_t oSize = ZSTD_HC_compressBegin_advanced(ctx, dst, maxDstSize, params); if(ZSTD_isError(oSize)) return oSize; op += oSize; maxDstSize -= oSize; /* body (compression) */ + ctx->base = src; op += ZSTD_HC_compress_generic (ctx, op, maxDstSize, src, srcSize); if(ZSTD_isError(oSize)) return oSize; op += oSize; maxDstSize -= oSize; /* Close frame */ - oSize = ZSTD_compressEnd((ZSTD_CCtx*)ctx, op, maxDstSize); + oSize = ZSTD_HC_compressEnd(ctx, op, maxDstSize); if(ZSTD_isError(oSize)) return oSize; op += oSize; return (op - ostart); } -size_t ZSTD_HC_compressCCtx (ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize, unsigned compressionLevel) +size_t ZSTD_HC_compressCCtx (ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize, int compressionLevel) { - if (compressionLevel==0) return ZSTD_compress(dst, maxDstSize, src, srcSize); /* fast mode */ + if (compressionLevel<=1) return ZSTD_compress(dst, maxDstSize, src, srcSize); /* fast mode */ if (compressionLevel > ZSTD_HC_MAX_CLEVEL) compressionLevel = ZSTD_HC_MAX_CLEVEL; return ZSTD_HC_compress_advanced(ctx, dst, maxDstSize, src, srcSize, ZSTD_HC_defaultParameters[compressionLevel]); } -size_t ZSTD_HC_compress(void* dst, size_t maxDstSize, const void* src, size_t srcSize, unsigned compressionLevel) +size_t ZSTD_HC_compress(void* dst, size_t maxDstSize, const void* src, size_t srcSize, int compressionLevel) { ZSTD_HC_CCtx* ctx = ZSTD_HC_createCCtx(); size_t result = ZSTD_HC_compressCCtx(ctx, dst, maxDstSize, src, srcSize, compressionLevel); ZSTD_HC_freeCCtx(ctx); return result; } - - - -/************************************** -* Streaming Functions -**************************************/ -/* dictionary saving */ - -size_t ZSTD_HC_saveDict (ZSTD_HC_CCtx* ctx, void* safeBuffer, size_t dictSize) -{ - /* TBD */ - (void)ctx; (void)safeBuffer; (void)dictSize; - return 0; -} - diff --git a/lib/zstdhc.h b/lib/zstdhc.h index e7053a849..fae9d8524 100644 --- a/lib/zstdhc.h +++ b/lib/zstdhc.h @@ -54,7 +54,7 @@ ZSTD_HC_compress() : */ size_t ZSTD_HC_compress(void* dst, size_t maxDstSize, const void* src, size_t srcSize, - unsigned compressionLevel); + int compressionLevel); /* ************************************* @@ -68,7 +68,7 @@ size_t ZSTD_HC_freeCCtx(ZSTD_HC_CCtx* cctx); ZSTD_HC_compressCCtx() : Same as ZSTD_compress(), but requires a ZSTD_HC_CCtx working space already allocated */ -size_t ZSTD_HC_compressCCtx(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize, unsigned compressionLevel); +size_t ZSTD_HC_compressCCtx(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize, int compressionLevel); #if defined (__cplusplus) diff --git a/lib/zstdhc_static.h b/lib/zstdhc_static.h index 0492d2297..caaea5aff 100644 --- a/lib/zstdhc_static.h +++ b/lib/zstdhc_static.h @@ -65,7 +65,7 @@ typedef struct /* ************************************* -* Functions +* Advanced function ***************************************/ /** ZSTD_HC_compress_advanced * Same as ZSTD_HC_compressCCtx(), but can fine-tune each compression parameter */ @@ -75,16 +75,25 @@ size_t ZSTD_HC_compress_advanced (ZSTD_HC_CCtx* ctx, ZSTD_HC_parameters params); +/* ************************************* +* Streaming functions +***************************************/ +size_t ZSTD_HC_compressBegin(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, int compressionLevel); +size_t ZSTD_HC_compressContinue(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize); +size_t ZSTD_HC_compressEnd(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize); + + /* ************************************* * Pre-defined compression levels ***************************************/ -#define ZSTD_HC_MAX_CLEVEL 25 +#define ZSTD_HC_MAX_CLEVEL 26 static const ZSTD_HC_parameters ZSTD_HC_defaultParameters[ZSTD_HC_MAX_CLEVEL+1] = { /* W, C, H, S */ { 18, 12, 14, 1 }, /* level 0 - never used */ + { 18, 12, 14, 1 }, /* real level 1 - all levels below are +1 */ { 18, 12, 15, 2 }, /* level 1 */ { 19, 14, 16, 3 }, /* level 2 */ - { 20, 19, 19, 2 }, /* level 3 */ + { 20, 18, 18, 3 }, /* level 3 */ { 20, 19, 19, 3 }, /* level 4 */ { 20, 19, 19, 4 }, /* level 5 */ { 20, 20, 19, 4 }, /* level 6 */ @@ -110,8 +119,6 @@ static const ZSTD_HC_parameters ZSTD_HC_defaultParameters[ZSTD_HC_MAX_CLEVEL+1] }; - - #if defined (__cplusplus) } #endif diff --git a/programs/Makefile b/programs/Makefile index 047a0c45c..85584ce03 100644 --- a/programs/Makefile +++ b/programs/Makefile @@ -58,7 +58,7 @@ default: zstd all: zstd zstd32 fullbench fullbench32 fuzzer fuzzer32 paramgrill datagen -zstd : $(ZSTDDIR)/zstd.c $(ZSTDDIR)/zstdhc.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legacy/zstd_v01.c xxhash.c bench.c fileio.c zstdcli.c +zstd: $(ZSTDDIR)/zstd.c $(ZSTDDIR)/zstdhc.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legacy/zstd_v01.c xxhash.c bench.c fileio.c zstdcli.c $(CC) $(FLAGS) $^ -o $@$(EXT) zstd32: $(ZSTDDIR)/zstd.c $(ZSTDDIR)/zstdhc.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legacy/zstd_v01.c xxhash.c bench.c fileio.c zstdcli.c diff --git a/programs/bench.c b/programs/bench.c index f52210b9d..7cffc5eec 100644 --- a/programs/bench.c +++ b/programs/bench.c @@ -229,9 +229,9 @@ typedef struct size_t resSize; } blockParam_t; -typedef size_t (*compressor_t) (void* dst, size_t maxDstSize, const void* src, size_t srcSize, unsigned compressionLevel); +typedef size_t (*compressor_t) (void* dst, size_t maxDstSize, const void* src, size_t srcSize, int compressionLevel); -static size_t local_compress_fast (void* dst, size_t maxDstSize, const void* src, size_t srcSize, unsigned compressionLevel) +static size_t local_compress_fast (void* dst, size_t maxDstSize, const void* src, size_t srcSize, int compressionLevel) { (void)compressionLevel; return ZSTD_compress(dst, maxDstSize, src, srcSize); @@ -323,10 +323,10 @@ static int BMK_benchMem(void* srcBuffer, size_t srcSize, const char* fileName, i for (blockNb=0; blockNb %9i (%5.2f%%),%7.1f MB/s\r", loopNb, fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000.); + ratio = (double)srcSize / (double)cSize; + DISPLAY("%1i-%-14.14s : %9i -> %9i (%5.3f),%7.1f MB/s\r", loopNb, fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000.); -#if 0 +#if 1 /* Decompression */ memset(resultBuffer, 0xD6, srcSize); @@ -343,7 +343,7 @@ static int BMK_benchMem(void* srcBuffer, size_t srcSize, const char* fileName, i milliTime = BMK_GetMilliSpan(milliTime); if ((double)milliTime < fastestD*nbLoops) fastestD = (double)milliTime / nbLoops; - DISPLAY("%1i-%-14.14s : %9i -> %9i (%5.2f%%),%7.1f MB/s ,%7.1f MB/s\r", loopNb, fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000., (double)srcSize / fastestD / 1000.); + DISPLAY("%1i-%-14.14s : %9i -> %9i (%5.3f),%7.1f MB/s ,%7.1f MB/s\r", loopNb, fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000., (double)srcSize / fastestD / 1000.); /* CRC Checking */ crcCheck = XXH64(resultBuffer, srcSize, 0); @@ -367,10 +367,7 @@ static int BMK_benchMem(void* srcBuffer, size_t srcSize, const char* fileName, i if (crcOrig == crcCheck) { - if (ratio<100.) - DISPLAY("%-16.16s : %9i -> %9i (%5.2f%%),%7.1f MB/s ,%7.1f MB/s\n", fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000., (double)srcSize / fastestD / 1000.); - else - DISPLAY("%-16.16s : %9i -> %9i (%5.1f%%),%7.1f MB/s ,%7.1f MB/s \n", fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000., (double)srcSize / fastestD / 1000.); + DISPLAY("%-16.16s : %9i -> %9i (%5.3f),%7.1f MB/s ,%7.1f MB/s \n", fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000., (double)srcSize / fastestD / 1000.); } } diff --git a/programs/fileio.c b/programs/fileio.c index 2c768253e..315a38c37 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -66,6 +66,7 @@ #include "mem.h" #include "fileio.h" #include "zstd_static.h" +#include "zstdhc_static.h" #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT==1) # include "zstd_v01.h" /* legacy */ @@ -213,8 +214,47 @@ static void FIO_getFileHandles(FILE** pfinput, FILE** pfoutput, const char* inpu if ( *pfoutput==0) EXM_THROW(13, "Pb opening dst : %s", output_filename); } +typedef void* (*FIO_createC) (void); +static void* local_ZSTD_createCCtx(void) { return (void*) ZSTD_createCCtx(); } +static void* local_ZSTD_HC_createCCtx(void) { return (void*) ZSTD_HC_createCCtx(); } -unsigned long long FIO_compressFilename(const char* output_filename, const char* input_filename, unsigned cLevel) +typedef size_t (*FIO_initC) (void* ctx, void* dst, size_t maxDstSize, int cLevel); +static size_t local_ZSTD_compressBegin (void* ctx, void* dst, size_t maxDstSize, int cLevel) +{ + (void)cLevel; + return ZSTD_compressBegin((ZSTD_CCtx*)ctx, dst, maxDstSize); +} +static size_t local_ZSTD_HC_compressBegin (void* ctx, void* dst, size_t maxDstSize, int cLevel) +{ + return ZSTD_HC_compressBegin((ZSTD_HC_CCtx*)ctx, dst, maxDstSize, cLevel); +} + +typedef size_t (*FIO_continueC) (void* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize); +static size_t local_ZSTD_compressContinue (void* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize) +{ + return ZSTD_compressContinue((ZSTD_CCtx*)ctx, dst, maxDstSize, src, srcSize); +} +static size_t local_ZSTD_HC_compressContinue (void* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize) +{ + return ZSTD_HC_compressContinue((ZSTD_HC_CCtx*)ctx, dst, maxDstSize, src, srcSize); +} + +typedef size_t (*FIO_endC) (void* ctx, void* dst, size_t maxDstSize); +static size_t local_ZSTD_compressEnd (void* ctx, void* dst, size_t maxDstSize) +{ + return ZSTD_compressEnd((ZSTD_CCtx*)ctx, dst, maxDstSize); +} +static size_t local_ZSTD_HC_compressEnd (void* ctx, void* dst, size_t maxDstSize) +{ + return ZSTD_HC_compressEnd((ZSTD_HC_CCtx*)ctx, dst, maxDstSize); +} + +typedef void (*FIO_freeC) (void* ctx); +static void local_ZSTD_freeCCtx(void* ctx) { ZSTD_freeCCtx((ZSTD_CCtx*)ctx); } +static void local_ZSTD_HC_freeCCtx(void* ctx) { ZSTD_HC_freeCCtx((ZSTD_HC_CCtx*)ctx); } + + +unsigned long long FIO_compressFilename(const char* output_filename, const char* input_filename, int cLevel) { U64 filesize = 0; U64 compressedfilesize = 0; @@ -228,14 +268,34 @@ unsigned long long FIO_compressFilename(const char* output_filename, const char* FILE* finput; FILE* foutput; size_t sizeCheck, cSize; - ZSTD_CCtx* ctx = ZSTD_createCCtx(); - + void* ctx; + FIO_createC createC=NULL; + FIO_initC initC=NULL; + FIO_continueC continueC = NULL; + FIO_endC endC = NULL; + FIO_freeC freeC = NULL; /* Init */ - (void)cLevel; + if (cLevel <= 1) + { + createC = local_ZSTD_createCCtx; + initC = local_ZSTD_compressBegin; + continueC = local_ZSTD_compressContinue; + endC = local_ZSTD_compressEnd; + freeC = local_ZSTD_freeCCtx; + } + else + { + createC = local_ZSTD_HC_createCCtx; + initC = local_ZSTD_HC_compressBegin; + continueC = local_ZSTD_HC_compressContinue; + endC = local_ZSTD_HC_compressEnd; + freeC = local_ZSTD_HC_freeCCtx; + } FIO_getFileHandles(&finput, &foutput, input_filename, output_filename); /* Allocate Memory */ + ctx = createC(); inBuff = (BYTE*)malloc(inBuffSize); outBuff = (BYTE*)malloc(outBuffSize); if (!inBuff || !outBuff || !ctx) EXM_THROW(21, "Allocation error : not enough memory"); @@ -243,7 +303,7 @@ unsigned long long FIO_compressFilename(const char* output_filename, const char* inEnd = inBuff + inBuffSize; /* Write Frame Header */ - cSize = ZSTD_compressBegin(ctx, outBuff, outBuffSize); + cSize = initC(ctx, outBuff, outBuffSize, cLevel); if (ZSTD_isError(cSize)) EXM_THROW(22, "Compression error : cannot create frame header"); sizeCheck = fwrite(outBuff, 1, cSize, foutput); @@ -263,7 +323,7 @@ unsigned long long FIO_compressFilename(const char* output_filename, const char* DISPLAYUPDATE(2, "\rRead : %u MB ", (U32)(filesize>>20)); /* Compress Block */ - cSize = ZSTD_compressContinue(ctx, outBuff, outBuffSize, inSlot, inSize); + cSize = continueC(ctx, outBuff, outBuffSize, inSlot, inSize); if (ZSTD_isError(cSize)) EXM_THROW(24, "Compression error : %s ", ZSTD_getErrorName(cSize)); @@ -277,7 +337,7 @@ unsigned long long FIO_compressFilename(const char* output_filename, const char* } /* End of Frame */ - cSize = ZSTD_compressEnd(ctx, outBuff, outBuffSize); + cSize = endC(ctx, outBuff, outBuffSize); if (ZSTD_isError(cSize)) EXM_THROW(26, "Compression error : cannot create frame end"); sizeCheck = fwrite(outBuff, 1, cSize, foutput); @@ -292,7 +352,7 @@ unsigned long long FIO_compressFilename(const char* output_filename, const char* /* clean */ free(inBuff); free(outBuff); - ZSTD_freeCCtx(ctx); + freeC(ctx); fclose(finput); if (fclose(foutput)) EXM_THROW(28, "Write error : cannot properly close %s", output_filename); diff --git a/programs/fileio.h b/programs/fileio.h index 0e98c5795..037c819ea 100644 --- a/programs/fileio.h +++ b/programs/fileio.h @@ -52,7 +52,7 @@ void FIO_setNotificationLevel(unsigned level); /* ************************************* * Stream/File functions ***************************************/ -unsigned long long FIO_compressFilename (const char* outfilename, const char* infilename, unsigned cLevel); +unsigned long long FIO_compressFilename (const char* outfilename, const char* infilename, int compressionLevel); unsigned long long FIO_decompressFilename (const char* outfilename, const char* infilename); /** FIO_compressFilename : diff --git a/programs/paramgrill.c b/programs/paramgrill.c index 772eaad1f..975f83aeb 100644 --- a/programs/paramgrill.c +++ b/programs/paramgrill.c @@ -446,7 +446,7 @@ static void BMK_printWinners2(FILE* f, const winnerInfo_t* winners, size_t srcSi int cLevel; fprintf(f, "\n /* Selected configurations : */ \n"); - fprintf(f, "#define ZSTD_HC_MAX_CLEVEL 20 \n"); + fprintf(f, "#define ZSTD_HC_MAX_CLEVEL %2u \n", ZSTD_HC_MAX_CLEVEL); fprintf(f, "static const ZSTD_HC_parameters ZSTD_HC_defaultParameters[ZSTD_HC_MAX_CLEVEL+1] = {\n"); fprintf(f, " /* W, C, H, S */ \n"); diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 71d904e79..d71850149 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -118,6 +118,8 @@ static int usage(const char* programName) DISPLAY( "input : a filename\n"); DISPLAY( " with no FILE, or when FILE is - , read standard input\n"); DISPLAY( "Arguments :\n"); + DISPLAY( " -1 : Fast compression (default) \n"); + DISPLAY( " -9 : High compression \n"); DISPLAY( " -d : decompression (default for %s extension)\n", ZSTD_EXTENSION); //DISPLAY( " -z : force compression\n"); DISPLAY( " -f : overwrite output without prompting \n"); From 71bcdb5c1fd8610ea93157e972e97418d1d787c9 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 29 Oct 2015 17:08:03 +0100 Subject: [PATCH 25/37] sync paramgrill with HC starting at level 2 --- lib/zstd.c | 22 ------------------ lib/{zstd_Ccommon.h => zstd_internal.h} | 30 +++++++++++++++++++++---- lib/zstdhc.c | 5 +++++ programs/paramgrill.c | 18 +++++++-------- 4 files changed, 40 insertions(+), 35 deletions(-) rename lib/{zstd_Ccommon.h => zstd_internal.h} (90%) diff --git a/lib/zstd.c b/lib/zstd.c index 0edde3ac9..5d5c8380c 100644 --- a/lib/zstd.c +++ b/lib/zstd.c @@ -223,28 +223,6 @@ const char* ZSTD_getErrorName(size_t code) { return ERR_getErrorName(code); } ***************************************/ unsigned ZSTD_versionNumber (void) { return ZSTD_VERSION_NUMBER; } -static unsigned ZSTD_highbit(U32 val) -{ -# if defined(_MSC_VER) /* Visual */ - unsigned long r; - _BitScanReverse(&r, val); - return (unsigned)r; -# elif defined(__GNUC__) && (GCC_VERSION >= 304) /* GCC Intrinsic */ - return 31 - __builtin_clz(val); -# else /* Software version */ - static const int DeBruijnClz[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 }; - U32 v = val; - int r; - v |= v >> 1; - v |= v >> 2; - v |= v >> 4; - v |= v >> 8; - v |= v >> 16; - r = DeBruijnClz[(U32)(v * 0x07C4ACDDU) >> 27]; - return r; -# endif -} - /* ******************************************************* * Compression diff --git a/lib/zstd_Ccommon.h b/lib/zstd_internal.h similarity index 90% rename from lib/zstd_Ccommon.h rename to lib/zstd_internal.h index 5cbd70b8b..bc03534d3 100644 --- a/lib/zstd_Ccommon.h +++ b/lib/zstd_internal.h @@ -1,5 +1,5 @@ /* - zstd_CCommon - common functions + zstd_internal - common functions to include Header File for include Copyright (C) 2014-2015, Yann Collet. @@ -44,11 +44,33 @@ extern "C" { #include "error.h" -/* ************************************* -* Function body to include -***************************************/ +/* ************************************** +* Function body to include for inlining +****************************************/ static size_t ZSTD_read_ARCH(const void* p) { size_t r; memcpy(&r, p, sizeof(r)); return r; } +static unsigned ZSTD_highbit(U32 val) +{ +# if defined(_MSC_VER) /* Visual */ + unsigned long r; + _BitScanReverse(&r, val); + return (unsigned)r; +# elif defined(__GNUC__) && (__GNUC__ >= 3) /* GCC Intrinsic */ + return 31 - __builtin_clz(val); +# else /* Software version */ + static const int DeBruijnClz[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 }; + U32 v = val; + int r; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + r = DeBruijnClz[(U32)(v * 0x07C4ACDDU) >> 27]; + return r; +# endif +} + MEM_STATIC unsigned ZSTD_NbCommonBytes (register size_t val) { if (MEM_isLittleEndian()) diff --git a/lib/zstdhc.c b/lib/zstdhc.c index b3b711dbc..54d94fa0f 100644 --- a/lib/zstdhc.c +++ b/lib/zstdhc.c @@ -439,6 +439,11 @@ size_t ZSTD_HC_compress_advanced (ZSTD_HC_CCtx* ctx, BYTE* const ostart = (BYTE*)dst; BYTE* op = ostart; + /* correct params, to use less memory */ + U32 srcLog = ZSTD_highbit((U32)srcSize-1) + 1; + if (params.windowLog > srcLog) params.windowLog = srcLog; + if (params.chainLog > srcLog) params.chainLog = srcLog; + /* Header */ size_t oSize = ZSTD_HC_compressBegin_advanced(ctx, dst, maxDstSize, params); if(ZSTD_isError(oSize)) return oSize; diff --git a/programs/paramgrill.c b/programs/paramgrill.c index 975f83aeb..4552129f8 100644 --- a/programs/paramgrill.c +++ b/programs/paramgrill.c @@ -648,8 +648,8 @@ static void BMK_selectRandomStart( const void* srcBuffer, size_t srcSize, ZSTD_HC_CCtx* ctx) { - U32 id = FUZ_rand(&g_rand) % (ZSTD_HC_MAX_CLEVEL+1); - if ((id==0) || (winners[id].params.windowLog==0)) + U32 id = (FUZ_rand(&g_rand) % ZSTD_HC_MAX_CLEVEL) + 1; + if ((id<2) || (winners[id].params.windowLog==0)) { /* totally random entry */ ZSTD_HC_parameters p; @@ -693,24 +693,24 @@ static void BMK_benchMem(void* srcBuffer, size_t srcSize) g_cSpeedTarget[1] = g_target * 1000; else { - /* baseline config for level 1 */ + /* baseline config for level 2 */ BMK_result_t testResult; - params = seedParams[1]; + params = seedParams[2]; params.windowLog = MIN(srcLog, params.windowLog); params.chainLog = MIN(params.windowLog, params.chainLog); params.searchLog = MIN(params.chainLog, params.searchLog); BMK_benchParam(&testResult, srcBuffer, srcSize, ctx, params); - g_cSpeedTarget[1] = (testResult.cSpeed * 15) >> 4; + g_cSpeedTarget[2] = (testResult.cSpeed * 15) >> 4; } - /* establish speed objectives (relative to level 1) */ - for (i=2; i<=ZSTD_HC_MAX_CLEVEL; i++) + /* establish speed objectives (relative to level 2) */ + for (i=3; i<=ZSTD_HC_MAX_CLEVEL; i++) g_cSpeedTarget[i] = (g_cSpeedTarget[i-1] * 13) >> 4; /* populate initial solution */ { - const int maxSeeds = g_noSeed ? 1 : ZSTD_HC_MAX_CLEVEL; - for (i=1; i<=maxSeeds; i++) + const int maxSeeds = g_noSeed ? 2 : ZSTD_HC_MAX_CLEVEL; + for (i=2; i<=maxSeeds; i++) { params = seedParams[i]; params.windowLog = MIN(srcLog, params.windowLog); From 3d9cf7acf29cbe73806738a80b3a56bb00a1fd46 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 29 Oct 2015 17:15:14 +0100 Subject: [PATCH 26/37] fix include --- lib/zstd.c | 2 +- lib/zstdhc.c | 10 ++-------- 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/lib/zstd.c b/lib/zstd.c index 5d5c8380c..7e69169a4 100644 --- a/lib/zstd.c +++ b/lib/zstd.c @@ -68,7 +68,7 @@ #include /* debug : printf */ #include "mem.h" /* low level memory routines */ #include "zstd_static.h" -#include "zstd_Ccommon.h" +#include "zstd_internal.h" #include "fse_static.h" #include "huff0.h" diff --git a/lib/zstdhc.c b/lib/zstdhc.c index 54d94fa0f..f3ad3a5a7 100644 --- a/lib/zstdhc.c +++ b/lib/zstdhc.c @@ -39,16 +39,10 @@ #include /* memset */ #include "zstdhc_static.h" #include "zstd_static.h" -#include "zstd_Ccommon.h" +#include "zstd_internal.h" #include "mem.h" -/* ************************************* -* Tuning Parameter -***************************************/ -static const U32 ZSTD_HC_compressionLevel_default = 9; - - /* ************************************* * Local Constants ***************************************/ @@ -451,7 +445,7 @@ size_t ZSTD_HC_compress_advanced (ZSTD_HC_CCtx* ctx, maxDstSize -= oSize; /* body (compression) */ - ctx->base = src; + ctx->base = (const BYTE*)src; op += ZSTD_HC_compress_generic (ctx, op, maxDstSize, src, srcSize); if(ZSTD_isError(oSize)) return oSize; op += oSize; From 2f648e54ff2866abf2b9f7688636649d8c84b770 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 29 Oct 2015 18:23:38 +0100 Subject: [PATCH 27/37] hc fuzzer tests --- programs/Makefile | 4 ++-- programs/fuzzer.c | 19 ++++++++++++++++--- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/programs/Makefile b/programs/Makefile index 85584ce03..9938bc73a 100644 --- a/programs/Makefile +++ b/programs/Makefile @@ -70,10 +70,10 @@ fullbench : $(ZSTDDIR)/zstd.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/le fullbench32: $(ZSTDDIR)/zstd.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legacy/zstd_v01.c datagen.c fullbench.c $(CC) -m32 $(FLAGS) $^ -o $@$(EXT) -fuzzer : $(ZSTDDIR)/zstd.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legacy/zstd_v01.c datagen.c xxhash.c fuzzer.c +fuzzer : $(ZSTDDIR)/zstd.c $(ZSTDDIR)/zstdhc.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legacy/zstd_v01.c datagen.c xxhash.c fuzzer.c $(CC) $(FLAGS) $^ -o $@$(EXT) -fuzzer32: $(ZSTDDIR)/zstd.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legacy/zstd_v01.c datagen.c xxhash.c fuzzer.c +fuzzer32: $(ZSTDDIR)/zstd.c $(ZSTDDIR)/zstdhc.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legacy/zstd_v01.c datagen.c xxhash.c fuzzer.c $(CC) -m32 $(FLAGS) $^ -o $@$(EXT) paramgrill : $(ZSTDDIR)/zstdhc.c $(ZSTDDIR)/zstd.c $(ZSTDDIR)/fse.c $(ZSTDDIR)/huff0.c $(ZSTDDIR)/legacy/zstd_v01.c datagen.c xxhash.c paramgrill.c diff --git a/programs/fuzzer.c b/programs/fuzzer.c index 6c486eab6..a549d232f 100644 --- a/programs/fuzzer.c +++ b/programs/fuzzer.c @@ -47,6 +47,7 @@ #include /* timeb */ #include /* strcmp */ #include "zstd_static.h" +#include "zstdhc_static.h" #include "datagen.h" /* RDG_genBuffer */ #include "xxhash.h" /* XXH64 */ #include "mem.h" @@ -263,8 +264,12 @@ int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, double compressibilit U32 result = 0; U32 testNb = 0; U32 coreSeed = seed, lseed = 0; + ZSTD_CCtx* ctx; + ZSTD_HC_CCtx* hcctx; /* allocation */ + ctx = ZSTD_createCCtx(); + hcctx = ZSTD_HC_createCCtx(); cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize); cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize); cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize); @@ -272,7 +277,7 @@ int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, double compressibilit cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize); dstBuffer = (BYTE*)malloc (dstBufferSize); cBuffer = (BYTE*)malloc (cBufferSize); - CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !dstBuffer || !cBuffer, + CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !dstBuffer || !cBuffer || !ctx || !hcctx, "Not enough memory, fuzzer tests cancelled"); /* Create initial samples */ @@ -294,6 +299,7 @@ int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, double compressibilit size_t cSize, dSize, dSupSize; U32 sampleSizeLog, buffNb; U64 crcOrig, crcDest; + int cLevel; /* init */ DISPLAYUPDATE(2, "\r%6u/%6u ", testNb, nbTests); @@ -322,8 +328,13 @@ int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, double compressibilit sampleStart = FUZ_rand(&lseed) % (srcBufferSize - sampleSize); crcOrig = XXH64(srcBuffer + sampleStart, sampleSize, 0); + /* HC compression test */ + cLevel = (FUZ_rand(&lseed) & 3) + 2; + cSize = ZSTD_HC_compressCCtx(hcctx, cBuffer, cBufferSize, srcBuffer + sampleStart, sampleSize, cLevel); + CHECK(ZSTD_isError(cSize), "ZSTD_compress failed"); + /* compression test */ - cSize = ZSTD_compress(cBuffer, cBufferSize, srcBuffer + sampleStart, sampleSize); + cSize = ZSTD_compressCCtx(ctx, cBuffer, cBufferSize, srcBuffer + sampleStart, sampleSize); CHECK(ZSTD_isError(cSize), "ZSTD_compress failed"); /* compression failure test : too small dest buffer */ @@ -335,7 +346,7 @@ int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, double compressibilit static const U32 endMark = 0x4DC2B1A9; U32 endCheck; memcpy(dstBuffer+tooSmallSize, &endMark, 4); - errorCode = ZSTD_compress(dstBuffer, tooSmallSize, srcBuffer + sampleStart, sampleSize); + errorCode = ZSTD_compressCCtx(ctx, dstBuffer, tooSmallSize, srcBuffer + sampleStart, sampleSize); CHECK(!ZSTD_isError(errorCode), "ZSTD_compress should have failed ! (buffer too small)"); memcpy(&endCheck, dstBuffer+tooSmallSize, 4); CHECK(endCheck != endMark, "ZSTD_compress : dst buffer overflow"); @@ -424,6 +435,8 @@ int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, double compressibilit DISPLAY("\rAll fuzzer tests completed \n"); _cleanup: + ZSTD_freeCCtx(ctx); + ZSTD_HC_freeCCtx(hcctx); free(cNoiseBuffer[0]); free(cNoiseBuffer[1]); free(cNoiseBuffer[2]); From 712def905bea5b1a77d1698c629e05f8e7b9e308 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 29 Oct 2015 18:41:45 +0100 Subject: [PATCH 28/37] one less hc malloc --- lib/zstdhc.c | 37 ++++++++++++++++++------------------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/lib/zstdhc.c b/lib/zstdhc.c index f3ad3a5a7..e90fd0638 100644 --- a/lib/zstdhc.c +++ b/lib/zstdhc.c @@ -68,25 +68,23 @@ struct ZSTD_HC_CCtx_s U32 lowLimit; /* below that point, no more data */ U32 nextToUpdate; /* index from which to continue dictionary update */ ZSTD_HC_parameters params; - size_t tableSpace; + void* workSpace; + size_t workSpaceSize; + + seqStore_t seqStore; /* sequences storage ptrs */ U32* hashTable; U32* chainTable; - seqStore_t seqStore; /* sequences storage ptrs */ - BYTE buffer[WORKPLACESIZE]; }; ZSTD_HC_CCtx* ZSTD_HC_createCCtx(void) { - ZSTD_HC_CCtx* ctx = (ZSTD_HC_CCtx*) malloc(sizeof(ZSTD_HC_CCtx)); - ctx->hashTable = NULL; - ctx->tableSpace = 0; - return ctx; + return (ZSTD_HC_CCtx*) calloc(1, sizeof(ZSTD_HC_CCtx)); } size_t ZSTD_HC_freeCCtx(ZSTD_HC_CCtx* cctx) { - free(cctx->hashTable); + free(cctx->workSpace); free(cctx); return 0; } @@ -106,15 +104,18 @@ static void ZSTD_HC_resetCCtx_advanced (ZSTD_HC_CCtx* zc, /* reserve table memory */ { - const size_t neededSpace = ((1 << params.chainLog) + (1 << params.hashLog)) * sizeof(U32); - if (neededSpace > zc->tableSpace) + const size_t tableSpace = ((1 << params.chainLog) + (1 << params.hashLog)) * sizeof(U32); + const size_t neededSpace = tableSpace + WORKPLACESIZE; + if (zc->workSpaceSize < neededSpace) { - free(zc->hashTable); - zc->tableSpace = neededSpace; - zc->hashTable = (U32*) malloc ( neededSpace ); + free(zc->workSpace); + zc->workSpaceSize = neededSpace; + zc->workSpace = malloc(neededSpace); } + zc->hashTable = (U32*)zc->workSpace; zc->chainTable = zc->hashTable + (1 << params.hashLog); - memset(zc->hashTable, 0, neededSpace ); + zc->seqStore.buffer = (void*) (zc->chainTable + (1 << params.chainLog)); + memset(zc->hashTable, 0, tableSpace ); } zc->nextToUpdate = 0; @@ -124,7 +125,6 @@ static void ZSTD_HC_resetCCtx_advanced (ZSTD_HC_CCtx* zc, zc->dictLimit = 0; zc->lowLimit = 0; zc->params = params; - zc->seqStore.buffer = zc->buffer; zc->seqStore.offsetStart = (U32*) (zc->seqStore.buffer); zc->seqStore.offCodeStart = (BYTE*) (zc->seqStore.offsetStart + (BLOCKSIZE>>2)); zc->seqStore.litStart = zc->seqStore.offCodeStart + (BLOCKSIZE>>2); @@ -468,8 +468,7 @@ size_t ZSTD_HC_compressCCtx (ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, co size_t ZSTD_HC_compress(void* dst, size_t maxDstSize, const void* src, size_t srcSize, int compressionLevel) { - ZSTD_HC_CCtx* ctx = ZSTD_HC_createCCtx(); - size_t result = ZSTD_HC_compressCCtx(ctx, dst, maxDstSize, src, srcSize, compressionLevel); - ZSTD_HC_freeCCtx(ctx); - return result; + ZSTD_HC_CCtx ctxBody; + memset(&ctxBody, 0, sizeof(ctxBody)); + return ZSTD_HC_compressCCtx(&ctxBody, dst, maxDstSize, src, srcSize, compressionLevel); } From c776c46b46a8e969e4599d843c94273e34bbdb9d Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 29 Oct 2015 19:10:54 +0100 Subject: [PATCH 29/37] range bench --- NEWS | 3 +++ programs/bench.c | 41 ++++++++++++++++++++++++++--------------- programs/paramgrill.c | 4 ++-- programs/zstdcli.c | 17 +++++++++++++---- 4 files changed, 44 insertions(+), 21 deletions(-) diff --git a/NEWS b/NEWS index 4c4c30019..e8d8affa0 100644 --- a/NEWS +++ b/NEWS @@ -1,3 +1,6 @@ +v0.3 +HC mode : compression levels 2-26 + v0.2.2 Fix : Visual Studio 2013 & 2015 release compilation, by Christophe Chevalier diff --git a/programs/bench.c b/programs/bench.c index 7cffc5eec..324f9f282 100644 --- a/programs/bench.c +++ b/programs/bench.c @@ -247,9 +247,13 @@ static int BMK_benchMem(void* srcBuffer, size_t srcSize, const char* fileName, i const size_t maxCompressedSize = (size_t)nbBlocks * ZSTD_compressBound(blockSize); void* const compressedBuffer = malloc(maxCompressedSize); void* const resultBuffer = malloc(srcSize); - const compressor_t compressor = (cLevel == 0) ? local_compress_fast : ZSTD_HC_compress; + const compressor_t compressor = (cLevel <= 1) ? local_compress_fast : ZSTD_HC_compress; U64 crcOrig; + /* init */ + if (strlen(fileName)>16) + fileName += strlen(fileName)-16; + /* Memory allocation & restrictions */ if (!compressedBuffer || !resultBuffer || !blockTable) { @@ -304,7 +308,7 @@ static int BMK_benchMem(void* srcBuffer, size_t srcSize, const char* fileName, i U32 blockNb; /* Compression */ - DISPLAY("%1i-%-14.14s : %9u ->\r", loopNb, fileName, (U32)srcSize); + DISPLAY("%1i-%-16.16s : %9u ->\r", loopNb, fileName, (U32)srcSize); memset(compressedBuffer, 0xE5, maxCompressedSize); nbLoops = 0; @@ -324,7 +328,7 @@ static int BMK_benchMem(void* srcBuffer, size_t srcSize, const char* fileName, i cSize += blockTable[blockNb].cSize; if ((double)milliTime < fastestC*nbLoops) fastestC = (double)milliTime / nbLoops; ratio = (double)srcSize / (double)cSize; - DISPLAY("%1i-%-14.14s : %9i -> %9i (%5.3f),%7.1f MB/s\r", loopNb, fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000.); + DISPLAY("%1i-%-16.16s : %9i -> %9i (%5.3f),%7.1f MB/s\r", loopNb, fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000.); #if 1 /* Decompression */ @@ -343,7 +347,7 @@ static int BMK_benchMem(void* srcBuffer, size_t srcSize, const char* fileName, i milliTime = BMK_GetMilliSpan(milliTime); if ((double)milliTime < fastestD*nbLoops) fastestD = (double)milliTime / nbLoops; - DISPLAY("%1i-%-14.14s : %9i -> %9i (%5.3f),%7.1f MB/s ,%7.1f MB/s\r", loopNb, fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000., (double)srcSize / fastestD / 1000.); + DISPLAY("%1i-%-16.16s : %9i -> %9i (%5.3f),%7.1f MB/s ,%7.1f MB/s\r", loopNb, fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000., (double)srcSize / fastestD / 1000.); /* CRC Checking */ crcCheck = XXH64(resultBuffer, srcSize, 0); @@ -366,9 +370,7 @@ static int BMK_benchMem(void* srcBuffer, size_t srcSize, const char* fileName, i } if (crcOrig == crcCheck) - { - DISPLAY("%-16.16s : %9i -> %9i (%5.3f),%7.1f MB/s ,%7.1f MB/s \n", fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000., (double)srcSize / fastestD / 1000.); - } + DISPLAY("%1i-%-16.16s : %9i -> %9i (%5.3f),%7.1f MB/s ,%7.1f MB/s \n", cLevel, fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000., (double)srcSize / fastestD / 1000.); } /* End cleaning */ @@ -419,9 +421,6 @@ static int BMK_benchOneFile(char* inFileName, int cLevel) void* srcBuffer; int result; - /* Init */ - (void)cLevel; - /* Check file existence */ inFile = fopen(inFileName, "rb"); if (inFile == NULL) @@ -457,7 +456,14 @@ static int BMK_benchOneFile(char* inFileName, int cLevel) } /* Bench */ - result = BMK_benchMem(srcBuffer, benchedSize, inFileName, cLevel); + if (cLevel<0) + { + int l; + for (l=1; l <= -cLevel; l++) + result = BMK_benchMem(srcBuffer, benchedSize, inFileName, l); + } + else + result = BMK_benchMem(srcBuffer, benchedSize, inFileName, cLevel); /* clean up */ free(srcBuffer); @@ -473,9 +479,6 @@ static int BMK_syntheticTest(int cLevel, double compressibility) int result; char name[20] = {0}; - /* Init */ - (void)cLevel; - /* Memory allocation */ if (!srcBuffer) { @@ -493,7 +496,15 @@ static int BMK_syntheticTest(int cLevel, double compressibility) #else snprintf (name, 20, "Synthetic %2u%%", (unsigned)(compressibility*100)); #endif - result = BMK_benchMem(srcBuffer, benchedSize, name, cLevel); + /* Bench */ + if (cLevel<0) + { + int l; + for (l=1; l <= -cLevel; l++) + result = BMK_benchMem(srcBuffer, benchedSize, name, l); + } + else + result = BMK_benchMem(srcBuffer, benchedSize, name, cLevel); /* End */ free(srcBuffer); diff --git a/programs/paramgrill.c b/programs/paramgrill.c index 4552129f8..7b20d9f26 100644 --- a/programs/paramgrill.c +++ b/programs/paramgrill.c @@ -508,8 +508,8 @@ static int BMK_seed(winnerInfo_t* winners, const ZSTD_HC_parameters params, double W_CSpeed_note = W_ratioNote * ( 30 + 8*cLevel) + log((double)testResult.cSpeed); double O_CSpeed_note = O_ratioNote * ( 30 + 8*cLevel) + log((double)winners[cLevel].result.cSpeed); - double W_DSpeed_note = W_ratioNote * ( 20 + 2*cLevel) + log((double)testResult.dSpeed); - double O_DSpeed_note = O_ratioNote * ( 20 + 2*cLevel) + log((double)winners[cLevel].result.dSpeed); + double W_DSpeed_note = W_ratioNote * ( 10 + 2*cLevel) + log((double)testResult.dSpeed); + double O_DSpeed_note = O_ratioNote * ( 10 + 2*cLevel) + log((double)winners[cLevel].result.dSpeed); if (W_DMemUsed_note < O_DMemUsed_note) diff --git a/programs/zstdcli.c b/programs/zstdcli.c index d71850149..837ce6812 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -139,9 +139,10 @@ static int usage_advanced(const char* programName) DISPLAY( " -c : force write to standard output, even if it is the console\n"); //DISPLAY( " -t : test compressed file integrity\n"); DISPLAY( "Benchmark arguments :\n"); - DISPLAY( " -b : benchmark file(s)\n"); + DISPLAY( " -b# : benchmark file(s), using # compression level (default : 1) \n"); DISPLAY( " -B# : cut file into independent blocks of size # (default : no block)\n"); DISPLAY( " -i# : iteration loops [1-9](default : 3)\n"); + DISPLAY( " -r# : test all compression levels from 1 to # (default : disabled)\n"); return 0; } @@ -168,7 +169,8 @@ int main(int argc, char** argv) bench=0, decode=0, forceStdout=0, - main_pause=0; + main_pause=0, + rangeBench = 1; unsigned fileNameStart = 0; unsigned nbFiles = 0; unsigned cLevel = 0; @@ -291,7 +293,14 @@ int main(int argc, char** argv) BMK_SetBlockSize(bSize); } break; - /* Pause at the end (hidden option) */ + + /* range bench (benchmark only) */ + case 'r': + rangeBench = -1; + argument++; + break; + + /* Pause at the end (hidden option) */ case 'p': main_pause=1; argument++; break; /* unknown command */ @@ -323,7 +332,7 @@ int main(int argc, char** argv) if (!strcmp(inFileName, stdinmark) && IS_CONSOLE(stdin) ) return badusage(programName); /* Check if benchmark is selected */ - if (bench) { BMK_benchFiles(argv+fileNameStart, nbFiles, cLevel); goto _end; } + if (bench) { BMK_benchFiles(argv+fileNameStart, nbFiles, cLevel*rangeBench); goto _end; } /* No output filename ==> try to select one automatically (when possible) */ while (!outFileName) From 44fe99116eecea477a904a6ed168c03d42c40bcf Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Thu, 29 Oct 2015 22:02:40 +0100 Subject: [PATCH 30/37] fixed hc alloc --- lib/zstdhc.c | 5 ++++- programs/bench.c | 8 ++++---- programs/zstdcli.c | 2 +- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/lib/zstdhc.c b/lib/zstdhc.c index e90fd0638..e74ab2598 100644 --- a/lib/zstdhc.c +++ b/lib/zstdhc.c @@ -468,7 +468,10 @@ size_t ZSTD_HC_compressCCtx (ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, co size_t ZSTD_HC_compress(void* dst, size_t maxDstSize, const void* src, size_t srcSize, int compressionLevel) { + size_t result; ZSTD_HC_CCtx ctxBody; memset(&ctxBody, 0, sizeof(ctxBody)); - return ZSTD_HC_compressCCtx(&ctxBody, dst, maxDstSize, src, srcSize, compressionLevel); + result = ZSTD_HC_compressCCtx(&ctxBody, dst, maxDstSize, src, srcSize, compressionLevel); + free(ctxBody.workSpace); + return result; } diff --git a/programs/bench.c b/programs/bench.c index 324f9f282..3742655cc 100644 --- a/programs/bench.c +++ b/programs/bench.c @@ -308,7 +308,7 @@ static int BMK_benchMem(void* srcBuffer, size_t srcSize, const char* fileName, i U32 blockNb; /* Compression */ - DISPLAY("%1i-%-16.16s : %9u ->\r", loopNb, fileName, (U32)srcSize); + DISPLAY("%2i-%-17.17s :%10u ->\r", loopNb, fileName, (U32)srcSize); memset(compressedBuffer, 0xE5, maxCompressedSize); nbLoops = 0; @@ -328,7 +328,7 @@ static int BMK_benchMem(void* srcBuffer, size_t srcSize, const char* fileName, i cSize += blockTable[blockNb].cSize; if ((double)milliTime < fastestC*nbLoops) fastestC = (double)milliTime / nbLoops; ratio = (double)srcSize / (double)cSize; - DISPLAY("%1i-%-16.16s : %9i -> %9i (%5.3f),%7.1f MB/s\r", loopNb, fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000.); + DISPLAY("%2i-%-17.17s :%10i ->%10i (%5.3f),%6.1f MB/s\r", loopNb, fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000.); #if 1 /* Decompression */ @@ -347,7 +347,7 @@ static int BMK_benchMem(void* srcBuffer, size_t srcSize, const char* fileName, i milliTime = BMK_GetMilliSpan(milliTime); if ((double)milliTime < fastestD*nbLoops) fastestD = (double)milliTime / nbLoops; - DISPLAY("%1i-%-16.16s : %9i -> %9i (%5.3f),%7.1f MB/s ,%7.1f MB/s\r", loopNb, fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000., (double)srcSize / fastestD / 1000.); + DISPLAY("%2i-%-17.17s :%10i ->%10i (%5.3f),%6.1f MB/s ,%6.1f MB/s\r", loopNb, fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000., (double)srcSize / fastestD / 1000.); /* CRC Checking */ crcCheck = XXH64(resultBuffer, srcSize, 0); @@ -370,7 +370,7 @@ static int BMK_benchMem(void* srcBuffer, size_t srcSize, const char* fileName, i } if (crcOrig == crcCheck) - DISPLAY("%1i-%-16.16s : %9i -> %9i (%5.3f),%7.1f MB/s ,%7.1f MB/s \n", cLevel, fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000., (double)srcSize / fastestD / 1000.); + DISPLAY("%2i-%-17.17s :%10i ->%10i (%5.3f),%6.1f MB/s ,%6.1f MB/s \n", cLevel, fileName, (int)srcSize, (int)cSize, ratio, (double)srcSize / fastestC / 1000., (double)srcSize / fastestD / 1000.); } /* End cleaning */ diff --git a/programs/zstdcli.c b/programs/zstdcli.c index 837ce6812..c6f7b5530 100644 --- a/programs/zstdcli.c +++ b/programs/zstdcli.c @@ -173,7 +173,7 @@ int main(int argc, char** argv) rangeBench = 1; unsigned fileNameStart = 0; unsigned nbFiles = 0; - unsigned cLevel = 0; + unsigned cLevel = 1; const char* programName = argv[0]; const char* inFileName = NULL; const char* outFileName = NULL; From f8eaf0e1589aa972ea4bae2f491911d0da6fa8ba Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 30 Oct 2015 05:59:18 +0100 Subject: [PATCH 31/37] added HC tests --- programs/Makefile | 2 ++ 1 file changed, 2 insertions(+) diff --git a/programs/Makefile b/programs/Makefile index 9938bc73a..0e01ffea5 100644 --- a/programs/Makefile +++ b/programs/Makefile @@ -140,7 +140,9 @@ test-zstd: zstd datagen echo foo | ./zstd | ./zstd -d > /dev/full; if [ $$? -eq 0 ] ; then echo "write error not detected!"; false; fi @echo "**** zstd round-trip tests **** " ./datagen | ./zstd -v | ./zstd -d > $(VOID) + ./datagen | ./zstd -6 -v | ./zstd -d > $(VOID) ./datagen -g256MB | ./zstd -v | ./zstd -d > $(VOID) + ./datagen -g256MB | ./zstd -3 -v | ./zstd -d > $(VOID) ./datagen -g6GB -P99 | ./zstd -vq | ./zstd -d > $(VOID) test-zstd32: zstd32 datagen From 4114f95ce993164dbf59c3b8f9cf7619881dfb28 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 30 Oct 2015 06:40:22 +0100 Subject: [PATCH 32/37] fix Visual Studio projects --- lib/bitstream.h | 2 +- lib/error.h | 1 + lib/zstd.c | 30 ++++++++++++++--------- lib/zstd_internal.h | 4 +-- lib/zstdhc.c | 25 +++++++++++-------- programs/bench.c | 4 +-- programs/fileio.c | 2 +- visual/2012/fuzzer/fuzzer.vcxproj | 4 +++ visual/2012/fuzzer/fuzzer.vcxproj.filters | 12 +++++++++ visual/2012/zstd/zstd.vcxproj | 4 +++ visual/2012/zstd/zstd.vcxproj.filters | 12 +++++++++ 11 files changed, 72 insertions(+), 28 deletions(-) diff --git a/lib/bitstream.h b/lib/bitstream.h index 20e40ec66..e6c2228e9 100644 --- a/lib/bitstream.h +++ b/lib/bitstream.h @@ -150,7 +150,7 @@ MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits); MEM_STATIC unsigned BIT_highbit32 (register U32 val) { # if defined(_MSC_VER) /* Visual */ - unsigned long r; + unsigned long r=0; _BitScanReverse ( &r, val ); return (unsigned) r; # elif defined(__GNUC__) && (__GNUC__ >= 3) /* Use GCC Intrinsic */ diff --git a/lib/error.h b/lib/error.h index a6981dd3b..1e2e06257 100644 --- a/lib/error.h +++ b/lib/error.h @@ -62,6 +62,7 @@ extern "C" { #define ERROR_LIST(ITEM) \ ITEM(PREFIX(No_Error)) ITEM(PREFIX(GENERIC)) \ + ITEM(PREFIX(memory_allocation)) \ ITEM(PREFIX(dstSize_tooSmall)) ITEM(PREFIX(srcSize_wrong)) \ ITEM(PREFIX(prefix_unknown)) ITEM(PREFIX(corruption_detected)) \ ITEM(PREFIX(tableLog_tooLarge)) ITEM(PREFIX(maxSymbolValue_tooLarge)) ITEM(PREFIX(maxSymbolValue_tooSmall)) \ diff --git a/lib/zstd.c b/lib/zstd.c index 7e69169a4..43832f01d 100644 --- a/lib/zstd.c +++ b/lib/zstd.c @@ -39,7 +39,7 @@ * Increasing memory usage improves compression ratio * Reduced memory usage can improve speed, due to cache effect */ -#define ZSTD_MEMORY_USAGE 17 +#define ZSTD_MEMORY_USAGE 16 /*! * HEAPMODE : @@ -533,7 +533,7 @@ static const BYTE* ZSTD_updateMatch(U32* table, const BYTE* p, const BYTE* start U32 h = ZSTD_hashPtr(p); const BYTE* r; r = table[h] + start; - ZSTD_addPtr(table, p, start); + table[h] = (U32)(p-start); return r; } @@ -559,23 +559,29 @@ static size_t ZSTD_compressBlock(ZSTD_CCtx* ctx, void* dst, size_t maxDstSize, c /* init */ + if (ip-base < 4) + { + ZSTD_addPtr(HashTable, ip+0, base); + ZSTD_addPtr(HashTable, ip+1, base); + ZSTD_addPtr(HashTable, ip+2, base); + ZSTD_addPtr(HashTable, ip+3, base); + ip += 4; + } ZSTD_resetSeqStore(seqStorePtr); /* Main Search Loop */ - while (ip < ilimit) + while (ip <= ilimit) { - const BYTE* match = (const BYTE*) ZSTD_updateMatch(HashTable, ip, base); + const BYTE* match = ZSTD_updateMatch(HashTable, ip, base); - if (!ZSTD_checkMatch(match,ip)) { ip += ((ip-anchor) >> g_searchStrength) + 1; continue; } - /* catch up */ - while ((ip>anchor) && (match>base) && (ip[-1] == match[-1])) { ip--; match--; } + if (ZSTD_checkMatch(ip-offset_2,ip)) match = ip-offset_2; + if (!ZSTD_checkMatch(match,ip)) { ip += ((ip-anchor) >> g_searchStrength) + 1; offset_2 = offset_1; continue; } + while ((ip>anchor) && (match>base) && (ip[-1] == match[-1])) { ip--; match--; } /* catch up */ { size_t litLength = ip-anchor; size_t matchLength = ZSTD_count(ip+MINMATCH, match+MINMATCH, iend); - size_t offsetCode; - if (litLength) offset_2 = offset_1; - offsetCode = ip-match; + size_t offsetCode = ip-match; if (offsetCode == offset_2) offsetCode = 0; offset_2 = offset_1; offset_1 = ip-match; @@ -584,8 +590,8 @@ static size_t ZSTD_compressBlock(ZSTD_CCtx* ctx, void* dst, size_t maxDstSize, c /* Fill Table */ ZSTD_addPtr(HashTable, ip+1, base); ip += matchLength + MINMATCH; - if (ip<=iend-8) ZSTD_addPtr(HashTable, ip-2, base); anchor = ip; + if (ip <= ilimit) ZSTD_addPtr(HashTable, ip-2, base); } } @@ -1089,7 +1095,7 @@ static void ZSTD_decodeSequence(seq_t* seq, seqState_t* seqState) /* Offset */ { - static const size_t offsetPrefix[MaxOff+1] = { /* note : size_t faster than U32 */ + static const U32 offsetPrefix[MaxOff+1] = { 1 /*fake*/, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, /*fake*/ 1, 1, 1, 1, 1 }; diff --git a/lib/zstd_internal.h b/lib/zstd_internal.h index bc03534d3..09fa1923e 100644 --- a/lib/zstd_internal.h +++ b/lib/zstd_internal.h @@ -52,7 +52,7 @@ static size_t ZSTD_read_ARCH(const void* p) { size_t r; memcpy(&r, p, sizeof(r)) static unsigned ZSTD_highbit(U32 val) { # if defined(_MSC_VER) /* Visual */ - unsigned long r; + unsigned long r=0; _BitScanReverse(&r, val); return (unsigned)r; # elif defined(__GNUC__) && (__GNUC__ >= 3) /* GCC Intrinsic */ @@ -91,7 +91,7 @@ MEM_STATIC unsigned ZSTD_NbCommonBytes (register size_t val) else /* 32 bits */ { # if defined(_MSC_VER) - unsigned long r; + unsigned long r=0; _BitScanForward( &r, (U32)val ); return (int)(r>>3); # elif defined(__GNUC__) && (__GNUC__ >= 3) diff --git a/lib/zstdhc.c b/lib/zstdhc.c index e74ab2598..9c70d79aa 100644 --- a/lib/zstdhc.c +++ b/lib/zstdhc.c @@ -89,8 +89,8 @@ size_t ZSTD_HC_freeCCtx(ZSTD_HC_CCtx* cctx) return 0; } -static void ZSTD_HC_resetCCtx_advanced (ZSTD_HC_CCtx* zc, - ZSTD_HC_parameters params) +static size_t ZSTD_HC_resetCCtx_advanced (ZSTD_HC_CCtx* zc, + ZSTD_HC_parameters params) { /* validate params */ if (params.windowLog > ZSTD_HC_WINDOWLOG_MAX) params.windowLog = ZSTD_HC_WINDOWLOG_MAX; @@ -111,6 +111,7 @@ static void ZSTD_HC_resetCCtx_advanced (ZSTD_HC_CCtx* zc, free(zc->workSpace); zc->workSpaceSize = neededSpace; zc->workSpace = malloc(neededSpace); + if (zc->workSpace == NULL) return ERROR(memory_allocation); } zc->hashTable = (U32*)zc->workSpace; zc->chainTable = zc->hashTable + (1 << params.hashLog); @@ -132,6 +133,7 @@ static void ZSTD_HC_resetCCtx_advanced (ZSTD_HC_CCtx* zc, zc->seqStore.matchLengthStart = zc->seqStore.litLengthStart + (BLOCKSIZE>>2); zc->seqStore.dumpsStart = zc->seqStore.matchLengthStart + (BLOCKSIZE>>2); + return 0; } @@ -144,7 +146,7 @@ static U32 ZSTD_HC_hash(U32 u, U32 h) { return (u * KNUTH) >> (32-h) ; } static U32 ZSTD_HC_hashPtr(const void* ptr, U32 h) { return ZSTD_HC_hash(MEM_read32(ptr), h); } //static const U64 prime5bytes = 889523592379ULL; -//static U32 ZSTD_HC_hashPtr(const void* p, U32 h) { return ((MEM_read64(p) * prime5bytes) << (64-40)) >> (64-h); } +//static U32 ZSTD_HC_hashPtr(const void* p, U32 h) { return (U32)((MEM_read64(p) * prime5bytes) << (64-40)) >> (64-h); } #define NEXT_IN_CHAIN(d) chainTable[(d) & chainMask] /* flexible, CHAINSIZE dependent */ @@ -258,8 +260,8 @@ static size_t ZSTD_HC_compressBlock(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstS { /* repcode */ if (MEM_read32(ip) == MEM_read32(ip - offset_2)) - /* store sequence */ { + /* store sequence */ size_t matchLength = ZSTD_count(ip+MINMATCH, ip+MINMATCH-offset_2, iend); size_t litLength = ip-anchor; size_t offset = offset_2; @@ -271,12 +273,13 @@ static size_t ZSTD_HC_compressBlock(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstS continue; } + offset_2 = offset_1; /* failed once : necessarily offset_1 now */ + /* repcode at ip+1 */ if (MEM_read32(ip+1) == MEM_read32(ip+1 - offset_1)) { size_t matchLength = ZSTD_count(ip+1+MINMATCH, ip+1+MINMATCH-offset_1, iend); size_t litLength = ip+1-anchor; - offset_2 = offset_1; ZSTD_storeSeq(seqStorePtr, litLength, anchor, 0, matchLength); ip += 1+matchLength+MINMATCH; anchor = ip; @@ -287,11 +290,10 @@ static size_t ZSTD_HC_compressBlock(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstS { const BYTE* match; size_t matchLength = ZSTD_HC_insertAndFindBestMatch(ctx, ip, iend, &match, maxSearches); - if (!matchLength) { ip++; offset_2 = offset_1; continue; } + if (!matchLength) { ip++; continue; } /* store sequence */ { size_t litLength = ip-anchor; - offset_2 = offset_1; offset_1 = ip-match; ZSTD_storeSeq(seqStorePtr, litLength, anchor, offset_1, matchLength-MINMATCH); ip += matchLength; @@ -381,7 +383,7 @@ size_t ZSTD_HC_compressContinue (ZSTD_HC_CCtx* ctxPtr, if (ip != ctxPtr->end) { if (ctxPtr->end != NULL) - ZSTD_HC_resetCCtx_advanced(ctxPtr, ctxPtr->params); /* reset */ + ZSTD_HC_resetCCtx_advanced(ctxPtr, ctxPtr->params); /* just reset, but no need to re-alloc */ ctxPtr->base = ip; } @@ -394,8 +396,10 @@ size_t ZSTD_HC_compressBegin_advanced(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstSize, const ZSTD_HC_parameters params) { + size_t errorCode; if (maxDstSize < 4) return ERROR(dstSize_tooSmall); - ZSTD_HC_resetCCtx_advanced(ctx, params); + errorCode = ZSTD_HC_resetCCtx_advanced(ctx, params); + if (ZSTD_isError(errorCode)) return errorCode; MEM_writeLE32(dst, ZSTD_magicNumber); /* Write Header */ return 4; } @@ -432,6 +436,7 @@ size_t ZSTD_HC_compress_advanced (ZSTD_HC_CCtx* ctx, { BYTE* const ostart = (BYTE*)dst; BYTE* op = ostart; + size_t oSize; /* correct params, to use less memory */ U32 srcLog = ZSTD_highbit((U32)srcSize-1) + 1; @@ -439,7 +444,7 @@ size_t ZSTD_HC_compress_advanced (ZSTD_HC_CCtx* ctx, if (params.chainLog > srcLog) params.chainLog = srcLog; /* Header */ - size_t oSize = ZSTD_HC_compressBegin_advanced(ctx, dst, maxDstSize, params); + oSize = ZSTD_HC_compressBegin_advanced(ctx, dst, maxDstSize, params); if(ZSTD_isError(oSize)) return oSize; op += oSize; maxDstSize -= oSize; diff --git a/programs/bench.c b/programs/bench.c index 3742655cc..5c410f39a 100644 --- a/programs/bench.c +++ b/programs/bench.c @@ -419,7 +419,7 @@ static int BMK_benchOneFile(char* inFileName, int cLevel) U64 inFileSize; size_t benchedSize, readSize; void* srcBuffer; - int result; + int result=0; /* Check file existence */ inFile = fopen(inFileName, "rb"); @@ -476,7 +476,7 @@ static int BMK_syntheticTest(int cLevel, double compressibility) { size_t benchedSize = 10000000; void* srcBuffer = malloc(benchedSize); - int result; + int result=0; char name[20] = {0}; /* Memory allocation */ diff --git a/programs/fileio.c b/programs/fileio.c index 315a38c37..84720330b 100644 --- a/programs/fileio.c +++ b/programs/fileio.c @@ -520,7 +520,7 @@ unsigned long long FIO_decompressFilename(const char* output_filename, const cha ZSTD_resetDCtx(dctx); toRead = ZSTD_nextSrcSizeToDecompress(dctx) - sizeof(ZSTD_magicNumber); if (toRead > MAXHEADERSIZE) EXM_THROW(30, "Not enough memory to read header"); - sizeCheck = fread(header+sizeof(ZSTD_magicNumber), (size_t)1, toRead, finput); + sizeCheck = fread(&header[sizeof(ZSTD_magicNumber)], 1, toRead, finput); if (sizeCheck != toRead) EXM_THROW(31, "Read error : cannot read header"); sizeCheck = ZSTD_decompressContinue(dctx, NULL, 0, header, sizeof(ZSTD_magicNumber)+toRead); // Decode frame header if (ZSTD_isError(sizeCheck)) EXM_THROW(32, "Error decoding header"); diff --git a/visual/2012/fuzzer/fuzzer.vcxproj b/visual/2012/fuzzer/fuzzer.vcxproj index 9cc2a2d44..861012d6b 100644 --- a/visual/2012/fuzzer/fuzzer.vcxproj +++ b/visual/2012/fuzzer/fuzzer.vcxproj @@ -163,6 +163,7 @@ + @@ -174,6 +175,9 @@ + + + diff --git a/visual/2012/fuzzer/fuzzer.vcxproj.filters b/visual/2012/fuzzer/fuzzer.vcxproj.filters index 45e7a6d97..bb412fa7c 100644 --- a/visual/2012/fuzzer/fuzzer.vcxproj.filters +++ b/visual/2012/fuzzer/fuzzer.vcxproj.filters @@ -36,6 +36,9 @@ Fichiers sources + + Fichiers sources + @@ -65,5 +68,14 @@ Fichiers d%27en-tête + + Fichiers d%27en-tête + + + Fichiers d%27en-tête + + + Fichiers d%27en-tête + \ No newline at end of file diff --git a/visual/2012/zstd/zstd.vcxproj b/visual/2012/zstd/zstd.vcxproj index 531c4e8ff..0a35dd902 100644 --- a/visual/2012/zstd/zstd.vcxproj +++ b/visual/2012/zstd/zstd.vcxproj @@ -23,6 +23,7 @@ + @@ -35,6 +36,9 @@ + + + diff --git a/visual/2012/zstd/zstd.vcxproj.filters b/visual/2012/zstd/zstd.vcxproj.filters index cc5950b7e..a9b5393cd 100644 --- a/visual/2012/zstd/zstd.vcxproj.filters +++ b/visual/2012/zstd/zstd.vcxproj.filters @@ -39,6 +39,9 @@ Fichiers sources + + Fichiers sources + @@ -71,5 +74,14 @@ Fichiers d%27en-tête + + Fichiers d%27en-tête + + + Fichiers d%27en-tête + + + Fichiers d%27en-tête + \ No newline at end of file From 8f9d49c092de31059726def93edf43e09caaa9dc Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 30 Oct 2015 07:00:37 +0100 Subject: [PATCH 33/37] fixed asan warning --- lib/zstdhc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/zstdhc.c b/lib/zstdhc.c index 9c70d79aa..cc5a57c24 100644 --- a/lib/zstdhc.c +++ b/lib/zstdhc.c @@ -213,7 +213,7 @@ static size_t ZSTD_HC_insertAndFindBestMatch ( && (MEM_read32(match) == MEM_read32(ip))) { const size_t mlt = ZSTD_count(ip+MINMATCH, match+MINMATCH, iLimit) + MINMATCH; - if (mlt > ml) { ml = mlt; *matchpos = match; } + if (mlt > ml) { ml = mlt; *matchpos = match; if (ip+ml >= iLimit) break; } } } else From fc04bcc6d73d67c1f93c92eeb214db322b303ea5 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 30 Oct 2015 07:11:07 +0100 Subject: [PATCH 34/37] fixed minor gcc warning --- lib/zstdhc.c | 2 +- programs/Makefile | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/zstdhc.c b/lib/zstdhc.c index cc5a57c24..499b63bc0 100644 --- a/lib/zstdhc.c +++ b/lib/zstdhc.c @@ -247,6 +247,7 @@ static size_t ZSTD_HC_compressBlock(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstS const BYTE* anchor = istart; const BYTE* const iend = istart + srcSize; const BYTE* const ilimit = iend - 8; + const BYTE* match = istart; size_t offset_2=REPCODE_STARTVALUE, offset_1=REPCODE_STARTVALUE; const U32 maxSearches = 1 << ctx->params.searchLog; @@ -288,7 +289,6 @@ static size_t ZSTD_HC_compressBlock(ZSTD_HC_CCtx* ctx, void* dst, size_t maxDstS /* search */ { - const BYTE* match; size_t matchLength = ZSTD_HC_insertAndFindBestMatch(ctx, ip, iend, &match, maxSearches); if (!matchLength) { ip++; continue; } /* store sequence */ diff --git a/programs/Makefile b/programs/Makefile index 0e01ffea5..17166013a 100644 --- a/programs/Makefile +++ b/programs/Makefile @@ -169,6 +169,8 @@ valgrindTest: zstd datagen fuzzer fullbench valgrind --leak-check=yes --error-exitcode=1 ./datagen -g50M > $(VOID) ./datagen -g16KB > tmp valgrind --leak-check=yes --error-exitcode=1 ./zstd -vf tmp $(VOID) + ./datagen -g2930KB > tmp + valgrind --leak-check=yes --error-exitcode=1 ./zstd -4 -vf tmp $(VOID) ./datagen -g64MB > tmp valgrind --leak-check=yes --error-exitcode=1 ./zstd -vf tmp $(VOID) @rm tmp From aa074051d6d2c9057897af4ab0b14388aaa93ef2 Mon Sep 17 00:00:00 2001 From: Yann Collet Date: Fri, 30 Oct 2015 11:21:50 +0100 Subject: [PATCH 35/37] decoding support for legacy v0.2 format --- lib/Makefile | 2 +- lib/error.h | 6 + lib/fse.h | 5 +- lib/fse_static.h | 5 +- lib/huff0.c | 20 +- lib/huff0.h | 5 +- lib/huff0_static.h | 5 +- lib/legacy/zstd_legacy.h | 81 + lib/legacy/zstd_v01.c | 2 +- lib/legacy/zstd_v02.c | 3729 +++++++++++++++++++++++++++++++ lib/legacy/zstd_v02.h | 99 + lib/zstd.c | 5 +- lib/zstd.h | 5 +- lib/zstd_static.h | 5 +- programs/Makefile | 30 +- programs/fileio.c | 81 +- programs/legacy/fileio_legacy.c | 284 +++ programs/legacy/fileio_legacy.h | 46 + programs/paramgrill.c | 4 +- 19 files changed, 4317 insertions(+), 102 deletions(-) create mode 100644 lib/legacy/zstd_legacy.h create mode 100644 lib/legacy/zstd_v02.c create mode 100644 lib/legacy/zstd_v02.h create mode 100644 programs/legacy/fileio_legacy.c create mode 100644 programs/legacy/fileio_legacy.h diff --git a/lib/Makefile b/lib/Makefile index 75d44c4a5..7d09111a7 100644 --- a/lib/Makefile +++ b/lib/Makefile @@ -40,7 +40,7 @@ VERSION?= $(LIBVER) DESTDIR?= PREFIX ?= /usr/local -CPPFLAGS= -I./legacy -DZSTD_LEGACY_SUPPORT=1 +CPPFLAGS= -I. -I./legacy -DZSTD_LEGACY_SUPPORT=1 CFLAGS ?= -O3 CFLAGS += -std=c99 -Wall -Wextra -Wundef -Wshadow -Wcast-qual -Wcast-align -Wstrict-prototypes FLAGS = $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $(MOREFLAGS) diff --git a/lib/error.h b/lib/error.h index 1e2e06257..6afa87f18 100644 --- a/lib/error.h +++ b/lib/error.h @@ -39,6 +39,12 @@ extern "C" { #endif +/****************************************** +* Includes +******************************************/ +#include /* size_t, ptrdiff_t */ + + /****************************************** * Compiler-specific ******************************************/ diff --git a/lib/fse.h b/lib/fse.h index 4b1ecb15b..24d1d26d4 100644 --- a/lib/fse.h +++ b/lib/fse.h @@ -32,7 +32,8 @@ - Source repository : https://github.com/Cyan4973/FiniteStateEntropy - Public forum : https://groups.google.com/forum/#!forum/lz4c ****************************************************************** */ -#pragma once +#ifndef FSE_H +#define FSE_H #if defined (__cplusplus) extern "C" { @@ -290,3 +291,5 @@ If there is an error, the function will return an error code, which can be teste #if defined (__cplusplus) } #endif + +#endif /* FSE_H */ diff --git a/lib/fse_static.h b/lib/fse_static.h index e5ad53bb7..01e25669f 100644 --- a/lib/fse_static.h +++ b/lib/fse_static.h @@ -32,7 +32,8 @@ - Source repository : https://github.com/Cyan4973/FiniteStateEntropy - Public forum : https://groups.google.com/forum/#!forum/lz4c ****************************************************************** */ -#pragma once +#ifndef FSE_STATIC_H +#define FSE_STATIC_H #if defined (__cplusplus) extern "C" { @@ -305,3 +306,5 @@ MEM_STATIC unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr) #if defined (__cplusplus) } #endif + +#endif /* FSE_STATIC_H */ diff --git a/lib/huff0.c b/lib/huff0.c index 74c7a7be0..13c41e5fd 100644 --- a/lib/huff0.c +++ b/lib/huff0.c @@ -68,6 +68,18 @@ #include "fse.h" /* header compression */ +/**************************************************************** +* Constants +****************************************************************/ +#define HUF_ABSOLUTEMAX_TABLELOG 16 /* absolute limit of HUF_MAX_TABLELOG. Beyond that value, code does not work */ +#define HUF_MAX_TABLELOG 12 /* max configured tableLog (for static allocation); can be modified up to HUF_ABSOLUTEMAX_TABLELOG */ +#define HUF_DEFAULT_TABLELOG HUF_MAX_TABLELOG /* tableLog by default, when not specified */ +#define HUF_MAX_SYMBOL_VALUE 255 +#if (HUF_MAX_TABLELOG > HUF_ABSOLUTEMAX_TABLELOG) +# error "HUF_MAX_TABLELOG is too large !" +#endif + + /**************************************************************** * Error Management ****************************************************************/ @@ -85,14 +97,6 @@ const char* HUF_getErrorName(size_t code) { return ERR_getErrorName(code); } /********************************************************* * Huff0 : Huffman block compression *********************************************************/ -#define HUF_ABSOLUTEMAX_TABLELOG 16 /* absolute limit of HUF_MAX_TABLELOG. Beyond that value, code does not work */ -#define HUF_MAX_TABLELOG 12 /* max configured tableLog (for static allocation); can be modified up to HUF_ABSOLUTEMAX_TABLELOG */ -#define HUF_DEFAULT_TABLELOG HUF_MAX_TABLELOG /* tableLog by default, when not specified */ -#define HUF_MAX_SYMBOL_VALUE 255 -#if (HUF_MAX_TABLELOG > HUF_ABSOLUTEMAX_TABLELOG) -# error "HUF_MAX_TABLELOG is too large !" -#endif - typedef struct HUF_CElt_s { U16 val; BYTE nbBits; diff --git a/lib/huff0.h b/lib/huff0.h index 91fb00c47..613d9b9cc 100644 --- a/lib/huff0.h +++ b/lib/huff0.h @@ -32,7 +32,8 @@ - Source repository : https://github.com/Cyan4973/FiniteStateEntropy - Public forum : https://groups.google.com/forum/#!forum/lz4c ****************************************************************** */ -#pragma once +#ifndef HUFF0_H +#define HUFF0_H #if defined (__cplusplus) extern "C" { @@ -91,3 +92,5 @@ size_t HUF_compress2 (void* dst, size_t dstSize, const void* src, size_t srcSize #if defined (__cplusplus) } #endif + +#endif /* HUFF0_H */ diff --git a/lib/huff0_static.h b/lib/huff0_static.h index ca4832b34..e8af19ede 100644 --- a/lib/huff0_static.h +++ b/lib/huff0_static.h @@ -32,7 +32,8 @@ - Source repository : https://github.com/Cyan4973/FiniteStateEntropy - Public forum : https://groups.google.com/forum/#!forum/lz4c ****************************************************************** */ -#pragma once +#ifndef HUFF0_STATIC_H +#define HUFF0_STATIC_H #if defined (__cplusplus) extern "C" { @@ -74,3 +75,5 @@ size_t HUF_decompress4X6 (void* dst, size_t dstSize, const void* cSrc, size_t cS #if defined (__cplusplus) } #endif + +#endif /* HUFF0_STATIC_H */ diff --git a/lib/legacy/zstd_legacy.h b/lib/legacy/zstd_legacy.h new file mode 100644 index 000000000..b9ca94199 --- /dev/null +++ b/lib/legacy/zstd_legacy.h @@ -0,0 +1,81 @@ +/* + zstd_v02 - decoder for 0.2 format + Header File + Copyright (C) 2015, 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 : + - zstd source repository : https://github.com/Cyan4973/zstd + - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c +*/ +#ifndef ZSTD_LEGACY_H +#define ZSTD_LEGACY_H + +#if defined (__cplusplus) +extern "C" { +#endif + +/* ************************************* +* Includes +***************************************/ +#include "mem.h" /* MEM_STATIC */ +#include "error.h" /* ERROR */ +#include "zstd_v01.h" +#include "zstd_v02.h" + +MEM_STATIC unsigned ZSTD_isLegacy (U32 magicNumberLE) +{ + switch(magicNumberLE) + { + case ZSTDv01_magicNumberLE : + case ZSTDv02_magicNumber : return 1; + default : return 0; + } +} + + +MEM_STATIC size_t ZSTD_decompressLegacy( + void* dst, size_t maxOriginalSize, + const void* src, size_t compressedSize, + U32 magicNumberLE) +{ + switch(magicNumberLE) + { + case ZSTDv01_magicNumberLE : + return ZSTDv01_decompress(dst, maxOriginalSize, src, compressedSize); + case ZSTDv02_magicNumber : + return ZSTDv02_decompress(dst, maxOriginalSize, src, compressedSize); + default : + return ERROR(prefix_unknown); + } +} + + + +#if defined (__cplusplus) +} +#endif + +#endif /* ZSTD_LEGACY_H */ diff --git a/lib/legacy/zstd_v01.c b/lib/legacy/zstd_v01.c index cb29d1359..ccd57d5b7 100644 --- a/lib/legacy/zstd_v01.c +++ b/lib/legacy/zstd_v01.c @@ -988,7 +988,7 @@ static size_t HUF_readDTable (U16* DTable, const void* src, size_t srcSize) { static int l[14] = { 1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 63, 64, 127, 128 }; oSize = l[iSize-242]; - memset(huffWeight, 1, oSize); + memset(huffWeight, 1, sizeof(huffWeight)); iSize = 0; } else /* Incompressible */ diff --git a/lib/legacy/zstd_v02.c b/lib/legacy/zstd_v02.c new file mode 100644 index 000000000..a52878e29 --- /dev/null +++ b/lib/legacy/zstd_v02.c @@ -0,0 +1,3729 @@ +/* ****************************************************************** + Error codes and messages + Copyright (C) 2013-2015, 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 : + - Source repository : https://github.com/Cyan4973/FiniteStateEntropy + - Public forum : https://groups.google.com/forum/#!forum/lz4c +****************************************************************** */ +#ifndef ERROR_H_MODULE +#define ERROR_H_MODULE + +#if defined (__cplusplus) +extern "C" { +#endif + +#include /* size_t, ptrdiff_t */ +#include "zstd_v02.h" + +/****************************************** +* Compiler-specific +******************************************/ +#if defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) +# define ERR_STATIC static inline +#elif defined(_MSC_VER) +# define ERR_STATIC static __inline +#elif defined(__GNUC__) +# define ERR_STATIC static __attribute__((unused)) +#else +# define ERR_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */ +#endif + + +/****************************************** +* Error Management +******************************************/ +#define PREFIX(name) ZSTD_error_##name + +#define ERROR(name) (size_t)-PREFIX(name) + +#define ERROR_LIST(ITEM) \ + ITEM(PREFIX(No_Error)) ITEM(PREFIX(GENERIC)) \ + ITEM(PREFIX(memory_allocation)) \ + ITEM(PREFIX(dstSize_tooSmall)) ITEM(PREFIX(srcSize_wrong)) \ + ITEM(PREFIX(prefix_unknown)) ITEM(PREFIX(corruption_detected)) \ + ITEM(PREFIX(tableLog_tooLarge)) ITEM(PREFIX(maxSymbolValue_tooLarge)) ITEM(PREFIX(maxSymbolValue_tooSmall)) \ + ITEM(PREFIX(maxCode)) + +#define ERROR_GENERATE_ENUM(ENUM) ENUM, +typedef enum { ERROR_LIST(ERROR_GENERATE_ENUM) } ERR_codes; /* enum is exposed, to detect & handle specific errors; compare function result to -enum value */ + +#define ERROR_CONVERTTOSTRING(STRING) #STRING, +#define ERROR_GENERATE_STRING(EXPR) ERROR_CONVERTTOSTRING(EXPR) + +ERR_STATIC unsigned ERR_isError(size_t code) { return (code > ERROR(maxCode)); } + + +#if defined (__cplusplus) +} +#endif + +#endif /* ERROR_H_MODULE */ + + +/* ****************************************************************** + mem.h + low-level memory access routines + Copyright (C) 2013-2015, 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 : + - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy + - Public forum : https://groups.google.com/forum/#!forum/lz4c +****************************************************************** */ +#ifndef MEM_H_MODULE +#define MEM_H_MODULE + +#if defined (__cplusplus) +extern "C" { +#endif + +/****************************************** +* Includes +******************************************/ +#include /* size_t, ptrdiff_t */ +#include /* memcpy */ + + +/****************************************** +* Compiler-specific +******************************************/ +#if defined(__GNUC__) +# define MEM_STATIC static __attribute__((unused)) +#elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) +# define MEM_STATIC static inline +#elif defined(_MSC_VER) +# define MEM_STATIC static __inline +#else +# define MEM_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */ +#endif + + +/**************************************************************** +* Basic Types +*****************************************************************/ +#if defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) +# include + typedef uint8_t BYTE; + typedef uint16_t U16; + typedef int16_t S16; + typedef uint32_t U32; + typedef int32_t S32; + typedef uint64_t U64; + typedef int64_t S64; +#else + typedef unsigned char BYTE; + typedef unsigned short U16; + typedef signed short S16; + typedef unsigned int U32; + typedef signed int S32; + typedef unsigned long long U64; + typedef signed long long S64; +#endif + + +/**************************************************************** +* Memory I/O +*****************************************************************/ +/* MEM_FORCE_MEMORY_ACCESS + * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable. + * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal. + * The below switch allow to select different access method for improved performance. + * Method 0 (default) : use `memcpy()`. Safe and portable. + * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable). + * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`. + * Method 2 : direct access. This method is portable but violate C standard. + * It can generate buggy code on targets generating assembly depending on alignment. + * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6) + * See http://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details. + * Prefer these methods in priority order (0 > 1 > 2) + */ +#ifndef MEM_FORCE_MEMORY_ACCESS /* can be defined externally, on command line for example */ +# if defined(__GNUC__) && ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) ) +# define MEM_FORCE_MEMORY_ACCESS 2 +# elif defined(__INTEL_COMPILER) || \ + (defined(__GNUC__) && ( defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__) )) +# define MEM_FORCE_MEMORY_ACCESS 1 +# endif +#endif + +MEM_STATIC unsigned MEM_32bits(void) { return sizeof(void*)==4; } +MEM_STATIC unsigned MEM_64bits(void) { return sizeof(void*)==8; } + +MEM_STATIC unsigned MEM_isLittleEndian(void) +{ + const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */ + return one.c[0]; +} + +#if defined(MEM_FORCE_MEMORY_ACCESS) && (MEM_FORCE_MEMORY_ACCESS==2) + +/* violates C standard on structure alignment. +Only use if no other choice to achieve best performance on target platform */ +MEM_STATIC U16 MEM_read16(const void* memPtr) { return *(const U16*) memPtr; } +MEM_STATIC U32 MEM_read32(const void* memPtr) { return *(const U32*) memPtr; } +MEM_STATIC U64 MEM_read64(const void* memPtr) { return *(const U64*) memPtr; } + +MEM_STATIC void MEM_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; } +MEM_STATIC void MEM_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; } +MEM_STATIC void MEM_write64(void* memPtr, U64 value) { *(U64*)memPtr = value; } + +#elif defined(MEM_FORCE_MEMORY_ACCESS) && (MEM_FORCE_MEMORY_ACCESS==1) + +/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */ +/* currently only defined for gcc and icc */ +typedef union { U16 u16; U32 u32; U64 u64; } __attribute__((packed)) unalign; + +MEM_STATIC U16 MEM_read16(const void* ptr) { return ((const unalign*)ptr)->u16; } +MEM_STATIC U32 MEM_read32(const void* ptr) { return ((const unalign*)ptr)->u32; } +MEM_STATIC U64 MEM_read64(const void* ptr) { return ((const unalign*)ptr)->u64; } + +MEM_STATIC void MEM_write16(void* memPtr, U16 value) { ((unalign*)memPtr)->u16 = value; } +MEM_STATIC void MEM_write32(void* memPtr, U32 value) { ((unalign*)memPtr)->u32 = value; } +MEM_STATIC void MEM_write64(void* memPtr, U64 value) { ((unalign*)memPtr)->u64 = value; } + +#else + +/* default method, safe and standard. + can sometimes prove slower */ + +MEM_STATIC U16 MEM_read16(const void* memPtr) +{ + U16 val; memcpy(&val, memPtr, sizeof(val)); return val; +} + +MEM_STATIC U32 MEM_read32(const void* memPtr) +{ + U32 val; memcpy(&val, memPtr, sizeof(val)); return val; +} + +MEM_STATIC U64 MEM_read64(const void* memPtr) +{ + U64 val; memcpy(&val, memPtr, sizeof(val)); return val; +} + +MEM_STATIC void MEM_write16(void* memPtr, U16 value) +{ + memcpy(memPtr, &value, sizeof(value)); +} + +MEM_STATIC void MEM_write32(void* memPtr, U32 value) +{ + memcpy(memPtr, &value, sizeof(value)); +} + +MEM_STATIC void MEM_write64(void* memPtr, U64 value) +{ + memcpy(memPtr, &value, sizeof(value)); +} + +#endif // MEM_FORCE_MEMORY_ACCESS + + +MEM_STATIC U16 MEM_readLE16(const void* memPtr) +{ + if (MEM_isLittleEndian()) + return MEM_read16(memPtr); + else + { + const BYTE* p = (const BYTE*)memPtr; + return (U16)(p[0] + (p[1]<<8)); + } +} + +MEM_STATIC void MEM_writeLE16(void* memPtr, U16 val) +{ + if (MEM_isLittleEndian()) + { + MEM_write16(memPtr, val); + } + else + { + BYTE* p = (BYTE*)memPtr; + p[0] = (BYTE)val; + p[1] = (BYTE)(val>>8); + } +} + +MEM_STATIC U32 MEM_readLE32(const void* memPtr) +{ + if (MEM_isLittleEndian()) + return MEM_read32(memPtr); + else + { + const BYTE* p = (const BYTE*)memPtr; + return (U32)((U32)p[0] + ((U32)p[1]<<8) + ((U32)p[2]<<16) + ((U32)p[3]<<24)); + } +} + +MEM_STATIC void MEM_writeLE32(void* memPtr, U32 val32) +{ + if (MEM_isLittleEndian()) + { + MEM_write32(memPtr, val32); + } + else + { + BYTE* p = (BYTE*)memPtr; + p[0] = (BYTE)val32; + p[1] = (BYTE)(val32>>8); + p[2] = (BYTE)(val32>>16); + p[3] = (BYTE)(val32>>24); + } +} + +MEM_STATIC U64 MEM_readLE64(const void* memPtr) +{ + if (MEM_isLittleEndian()) + return MEM_read64(memPtr); + else + { + const BYTE* p = (const BYTE*)memPtr; + return (U64)((U64)p[0] + ((U64)p[1]<<8) + ((U64)p[2]<<16) + ((U64)p[3]<<24) + + ((U64)p[4]<<32) + ((U64)p[5]<<40) + ((U64)p[6]<<48) + ((U64)p[7]<<56)); + } +} + +MEM_STATIC void MEM_writeLE64(void* memPtr, U64 val64) +{ + if (MEM_isLittleEndian()) + { + MEM_write64(memPtr, val64); + } + else + { + BYTE* p = (BYTE*)memPtr; + p[0] = (BYTE)val64; + p[1] = (BYTE)(val64>>8); + p[2] = (BYTE)(val64>>16); + p[3] = (BYTE)(val64>>24); + p[4] = (BYTE)(val64>>32); + p[5] = (BYTE)(val64>>40); + p[6] = (BYTE)(val64>>48); + p[7] = (BYTE)(val64>>56); + } +} + +MEM_STATIC size_t MEM_readLEST(const void* memPtr) +{ + if (MEM_32bits()) + return (size_t)MEM_readLE32(memPtr); + else + return (size_t)MEM_readLE64(memPtr); +} + +MEM_STATIC void MEM_writeLEST(void* memPtr, size_t val) +{ + if (MEM_32bits()) + MEM_writeLE32(memPtr, (U32)val); + else + MEM_writeLE64(memPtr, (U64)val); +} + +#if defined (__cplusplus) +} +#endif + +#endif /* MEM_H_MODULE */ + + +/* ****************************************************************** + bitstream + Part of NewGen Entropy library + header file (to include) + Copyright (C) 2013-2015, 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 : + - Source repository : https://github.com/Cyan4973/FiniteStateEntropy + - Public forum : https://groups.google.com/forum/#!forum/lz4c +****************************************************************** */ +#ifndef BITSTREAM_H_MODULE +#define BITSTREAM_H_MODULE + +#if defined (__cplusplus) +extern "C" { +#endif + + +/* +* This API consists of small unitary functions, which highly benefit from being inlined. +* Since link-time-optimization is not available for all compilers, +* these functions are defined into a .h to be included. +*/ + + +/********************************************** +* bitStream decompression API (read backward) +**********************************************/ +typedef struct +{ + size_t bitContainer; + unsigned bitsConsumed; + const char* ptr; + const char* start; +} BIT_DStream_t; + +typedef enum { BIT_DStream_unfinished = 0, + BIT_DStream_endOfBuffer = 1, + BIT_DStream_completed = 2, + BIT_DStream_overflow = 3 } BIT_DStream_status; /* result of BIT_reloadDStream() */ + /* 1,2,4,8 would be better for bitmap combinations, but slows down performance a bit ... :( */ + +MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize); +MEM_STATIC size_t BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits); +MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD); +MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* bitD); + + +/* +* Start by invoking BIT_initDStream(). +* A chunk of the bitStream is then stored into a local register. +* Local register size is 64-bits on 64-bits systems, 32-bits on 32-bits systems (size_t). +* You can then retrieve bitFields stored into the local register, **in reverse order**. +* Local register is manually filled from memory by the BIT_reloadDStream() method. +* A reload guarantee a minimum of ((8*sizeof(size_t))-7) bits when its result is BIT_DStream_unfinished. +* Otherwise, it can be less than that, so proceed accordingly. +* Checking if DStream has reached its end can be performed with BIT_endOfDStream() +*/ + + +/****************************************** +* unsafe API +******************************************/ +MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits); +/* faster, but works only if nbBits >= 1 */ + + + +/**************************************************************** +* Helper functions +****************************************************************/ +MEM_STATIC unsigned BIT_highbit32 (register U32 val) +{ +# if defined(_MSC_VER) /* Visual */ + unsigned long r; + _BitScanReverse ( &r, val ); + return (unsigned) r; +# elif defined(__GNUC__) && (__GNUC__ >= 3) /* Use GCC Intrinsic */ + return 31 - __builtin_clz (val); +# else /* Software version */ + static const unsigned DeBruijnClz[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 }; + U32 v = val; + unsigned r; + v |= v >> 1; + v |= v >> 2; + v |= v >> 4; + v |= v >> 8; + v |= v >> 16; + r = DeBruijnClz[ (U32) (v * 0x07C4ACDDU) >> 27]; + return r; +# endif +} + + + +/********************************************************** +* bitStream decoding +**********************************************************/ + +/*!BIT_initDStream +* Initialize a BIT_DStream_t. +* @bitD : a pointer to an already allocated BIT_DStream_t structure +* @srcBuffer must point at the beginning of a bitStream +* @srcSize must be the exact size of the bitStream +* @result : size of stream (== srcSize) or an errorCode if a problem is detected +*/ +MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize) +{ + if (srcSize < 1) { memset(bitD, 0, sizeof(*bitD)); return ERROR(srcSize_wrong); } + + if (srcSize >= sizeof(size_t)) /* normal case */ + { + U32 contain32; + bitD->start = (const char*)srcBuffer; + bitD->ptr = (const char*)srcBuffer + srcSize - sizeof(size_t); + bitD->bitContainer = MEM_readLEST(bitD->ptr); + contain32 = ((const BYTE*)srcBuffer)[srcSize-1]; + if (contain32 == 0) return ERROR(GENERIC); /* endMark not present */ + bitD->bitsConsumed = 8 - BIT_highbit32(contain32); + } + else + { + U32 contain32; + bitD->start = (const char*)srcBuffer; + bitD->ptr = bitD->start; + bitD->bitContainer = *(const BYTE*)(bitD->start); + switch(srcSize) + { + case 7: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[6]) << (sizeof(size_t)*8 - 16); + case 6: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[5]) << (sizeof(size_t)*8 - 24); + case 5: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[4]) << (sizeof(size_t)*8 - 32); + case 4: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[3]) << 24; + case 3: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[2]) << 16; + case 2: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[1]) << 8; + default:; + } + contain32 = ((const BYTE*)srcBuffer)[srcSize-1]; + if (contain32 == 0) return ERROR(GENERIC); /* endMark not present */ + bitD->bitsConsumed = 8 - BIT_highbit32(contain32); + bitD->bitsConsumed += (U32)(sizeof(size_t) - srcSize)*8; + } + + return srcSize; +} + +/*!BIT_lookBits + * Provides next n bits from local register + * local register is not modified (bits are still present for next read/look) + * On 32-bits, maxNbBits==25 + * On 64-bits, maxNbBits==57 + * @return : value extracted + */ +MEM_STATIC size_t BIT_lookBits(BIT_DStream_t* bitD, U32 nbBits) +{ + const U32 bitMask = sizeof(bitD->bitContainer)*8 - 1; + return ((bitD->bitContainer << (bitD->bitsConsumed & bitMask)) >> 1) >> ((bitMask-nbBits) & bitMask); +} + +/*! BIT_lookBitsFast : +* unsafe version; only works only if nbBits >= 1 */ +MEM_STATIC size_t BIT_lookBitsFast(BIT_DStream_t* bitD, U32 nbBits) +{ + const U32 bitMask = sizeof(bitD->bitContainer)*8 - 1; + return (bitD->bitContainer << (bitD->bitsConsumed & bitMask)) >> (((bitMask+1)-nbBits) & bitMask); +} + +MEM_STATIC void BIT_skipBits(BIT_DStream_t* bitD, U32 nbBits) +{ + bitD->bitsConsumed += nbBits; +} + +/*!BIT_readBits + * Read next n bits from local register. + * pay attention to not read more than nbBits contained into local register. + * @return : extracted value. + */ +MEM_STATIC size_t BIT_readBits(BIT_DStream_t* bitD, U32 nbBits) +{ + size_t value = BIT_lookBits(bitD, nbBits); + BIT_skipBits(bitD, nbBits); + return value; +} + +/*!BIT_readBitsFast : +* unsafe version; only works only if nbBits >= 1 */ +MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, U32 nbBits) +{ + size_t value = BIT_lookBitsFast(bitD, nbBits); + BIT_skipBits(bitD, nbBits); + return value; +} + +MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD) +{ + if (bitD->bitsConsumed > (sizeof(bitD->bitContainer)*8)) /* should never happen */ + return BIT_DStream_overflow; + + if (bitD->ptr >= bitD->start + sizeof(bitD->bitContainer)) + { + bitD->ptr -= bitD->bitsConsumed >> 3; + bitD->bitsConsumed &= 7; + bitD->bitContainer = MEM_readLEST(bitD->ptr); + return BIT_DStream_unfinished; + } + if (bitD->ptr == bitD->start) + { + if (bitD->bitsConsumed < sizeof(bitD->bitContainer)*8) return BIT_DStream_endOfBuffer; + return BIT_DStream_completed; + } + { + U32 nbBytes = bitD->bitsConsumed >> 3; + BIT_DStream_status result = BIT_DStream_unfinished; + if (bitD->ptr - nbBytes < bitD->start) + { + nbBytes = (U32)(bitD->ptr - bitD->start); /* ptr > start */ + result = BIT_DStream_endOfBuffer; + } + bitD->ptr -= nbBytes; + bitD->bitsConsumed -= nbBytes*8; + bitD->bitContainer = MEM_readLEST(bitD->ptr); /* reminder : srcSize > sizeof(bitD) */ + return result; + } +} + +/*! BIT_endOfDStream +* @return Tells if DStream has reached its exact end +*/ +MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* DStream) +{ + return ((DStream->ptr == DStream->start) && (DStream->bitsConsumed == sizeof(DStream->bitContainer)*8)); +} + +#if defined (__cplusplus) +} +#endif + +#endif /* BITSTREAM_H_MODULE */ +/* ****************************************************************** + Error codes and messages + Copyright (C) 2013-2015, 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 : + - Source repository : https://github.com/Cyan4973/FiniteStateEntropy + - Public forum : https://groups.google.com/forum/#!forum/lz4c +****************************************************************** */ +#ifndef ERROR_H_MODULE +#define ERROR_H_MODULE + +#if defined (__cplusplus) +extern "C" { +#endif + + +/****************************************** +* Compiler-specific +******************************************/ +#if defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) +# define ERR_STATIC static inline +#elif defined(_MSC_VER) +# define ERR_STATIC static __inline +#elif defined(__GNUC__) +# define ERR_STATIC static __attribute__((unused)) +#else +# define ERR_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */ +#endif + + +/****************************************** +* Error Management +******************************************/ +#define PREFIX(name) ZSTD_error_##name + +#define ERROR(name) (size_t)-PREFIX(name) + +#define ERROR_LIST(ITEM) \ + ITEM(PREFIX(No_Error)) ITEM(PREFIX(GENERIC)) \ + ITEM(PREFIX(dstSize_tooSmall)) ITEM(PREFIX(srcSize_wrong)) \ + ITEM(PREFIX(prefix_unknown)) ITEM(PREFIX(corruption_detected)) \ + ITEM(PREFIX(tableLog_tooLarge)) ITEM(PREFIX(maxSymbolValue_tooLarge)) ITEM(PREFIX(maxSymbolValue_tooSmall)) \ + ITEM(PREFIX(maxCode)) + +#define ERROR_GENERATE_ENUM(ENUM) ENUM, +typedef enum { ERROR_LIST(ERROR_GENERATE_ENUM) } ERR_codes; /* enum is exposed, to detect & handle specific errors; compare function result to -enum value */ + +#define ERROR_CONVERTTOSTRING(STRING) #STRING, +#define ERROR_GENERATE_STRING(EXPR) ERROR_CONVERTTOSTRING(EXPR) +static const char* ERR_strings[] = { ERROR_LIST(ERROR_GENERATE_STRING) }; + +ERR_STATIC unsigned ERR_isError(size_t code) { return (code > ERROR(maxCode)); } + +ERR_STATIC const char* ERR_getErrorName(size_t code) +{ + static const char* codeError = "Unspecified error code"; + if (ERR_isError(code)) return ERR_strings[-(int)(code)]; + return codeError; +} + + +#if defined (__cplusplus) +} +#endif + +#endif /* ERROR_H_MODULE */ +/* +Constructor and Destructor of type FSE_CTable + Note that its size depends on 'tableLog' and 'maxSymbolValue' */ +typedef unsigned FSE_CTable; /* don't allocate that. It's just a way to be more restrictive than void* */ +typedef unsigned FSE_DTable; /* don't allocate that. It's just a way to be more restrictive than void* */ + + +/* ****************************************************************** + FSE : Finite State Entropy coder + header file for static linking (only) + Copyright (C) 2013-2015, 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 : + - Source repository : https://github.com/Cyan4973/FiniteStateEntropy + - Public forum : https://groups.google.com/forum/#!forum/lz4c +****************************************************************** */ +#if defined (__cplusplus) +extern "C" { +#endif + + +/****************************************** +* Static allocation +******************************************/ +/* FSE buffer bounds */ +#define FSE_NCOUNTBOUND 512 +#define FSE_BLOCKBOUND(size) (size + (size>>7)) +#define FSE_COMPRESSBOUND(size) (FSE_NCOUNTBOUND + FSE_BLOCKBOUND(size)) /* Macro version, useful for static allocation */ + +/* You can statically allocate FSE CTable/DTable as a table of unsigned using below macro */ +#define FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue) (1 + (1<<(maxTableLog-1)) + ((maxSymbolValue+1)*2)) +#define FSE_DTABLE_SIZE_U32(maxTableLog) (1 + (1<= BIT_DStream_completed + +When it's done, verify decompression is fully completed, by checking both DStream and the relevant states. +Checking if DStream has reached its end is performed by : + BIT_endOfDStream(&DStream); +Check also the states. There might be some symbols left there, if some high probability ones (>50%) are possible. + FSE_endOfDState(&DState); +*/ + + +/****************************************** +* FSE unsafe API +******************************************/ +static unsigned char FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD); +/* faster, but works only if nbBits is always >= 1 (otherwise, result will be corrupted) */ + + +/****************************************** +* Implementation of inline functions +******************************************/ + +/* decompression */ + +typedef struct { + U16 tableLog; + U16 fastMode; +} FSE_DTableHeader; /* sizeof U32 */ + +typedef struct +{ + unsigned short newState; + unsigned char symbol; + unsigned char nbBits; +} FSE_decode_t; /* size == U32 */ + +MEM_STATIC void FSE_initDState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD, const FSE_DTable* dt) +{ + const FSE_DTableHeader* const DTableH = (const FSE_DTableHeader*)dt; + DStatePtr->state = BIT_readBits(bitD, DTableH->tableLog); + BIT_reloadDStream(bitD); + DStatePtr->table = dt + 1; +} + +MEM_STATIC BYTE FSE_decodeSymbol(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD) +{ + const FSE_decode_t DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state]; + const U32 nbBits = DInfo.nbBits; + BYTE symbol = DInfo.symbol; + size_t lowBits = BIT_readBits(bitD, nbBits); + + DStatePtr->state = DInfo.newState + lowBits; + return symbol; +} + +MEM_STATIC BYTE FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD) +{ + const FSE_decode_t DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state]; + const U32 nbBits = DInfo.nbBits; + BYTE symbol = DInfo.symbol; + size_t lowBits = BIT_readBitsFast(bitD, nbBits); + + DStatePtr->state = DInfo.newState + lowBits; + return symbol; +} + +MEM_STATIC unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr) +{ + return DStatePtr->state == 0; +} + + +#if defined (__cplusplus) +} +#endif +/* ****************************************************************** + Huff0 : Huffman coder, part of New Generation Entropy library + header file for static linking (only) + Copyright (C) 2013-2015, 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 : + - Source repository : https://github.com/Cyan4973/FiniteStateEntropy + - Public forum : https://groups.google.com/forum/#!forum/lz4c +****************************************************************** */ + +#if defined (__cplusplus) +extern "C" { +#endif + +/****************************************** +* Static allocation macros +******************************************/ +/* Huff0 buffer bounds */ +#define HUF_CTABLEBOUND 129 +#define HUF_BLOCKBOUND(size) (size + (size>>8) + 8) /* only true if incompressible pre-filtered with fast heuristic */ +#define HUF_COMPRESSBOUND(size) (HUF_CTABLEBOUND + HUF_BLOCKBOUND(size)) /* Macro version, useful for static allocation */ + +/* static allocation of Huff0's DTable */ +#define HUF_DTABLE_SIZE(maxTableLog) (1 + (1< /* size_t */ + + +/* ************************************* +* Version +***************************************/ +#define ZSTD_VERSION_MAJOR 0 /* for breaking interface changes */ +#define ZSTD_VERSION_MINOR 2 /* for new (non-breaking) interface capabilities */ +#define ZSTD_VERSION_RELEASE 2 /* for tweaks, bug-fixes, or development */ +#define ZSTD_VERSION_NUMBER (ZSTD_VERSION_MAJOR *100*100 + ZSTD_VERSION_MINOR *100 + ZSTD_VERSION_RELEASE) + + +/* ************************************* +* Advanced functions +***************************************/ +typedef struct ZSTD_CCtx_s ZSTD_CCtx; /* incomplete type */ + +#if defined (__cplusplus) +} +#endif +/* + zstd - standard compression library + Header File for static linking only + Copyright (C) 2014-2015, 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 : + - zstd source repository : https://github.com/Cyan4973/zstd + - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c +*/ + +/* The objects defined into this file should be considered experimental. + * They are not labelled stable, as their prototype may change in the future. + * You can use them for tests, provide feedback, or if you can endure risk of future changes. + */ + +#if defined (__cplusplus) +extern "C" { +#endif + +/* ************************************* +* Streaming functions +***************************************/ + +typedef struct ZSTD_DCtx_s ZSTD_DCtx; + +/* + Use above functions alternatively. + ZSTD_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTD_decompressContinue(). + ZSTD_decompressContinue() will use previous data blocks to improve compression if they are located prior to current block. + Result is the number of bytes regenerated within 'dst'. + It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some header. +*/ + +/* ************************************* +* Prefix - version detection +***************************************/ +#define ZSTD_magicNumber 0xFD2FB522 /* v0.2 (current)*/ + + +#if defined (__cplusplus) +} +#endif +/* ****************************************************************** + FSE : Finite State Entropy coder + Copyright (C) 2013-2015, 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 : + - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy + - Public forum : https://groups.google.com/forum/#!forum/lz4c +****************************************************************** */ + +#ifndef FSE_COMMONDEFS_ONLY + +/**************************************************************** +* Tuning parameters +****************************************************************/ +/* MEMORY_USAGE : +* Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) +* Increasing memory usage improves compression ratio +* Reduced memory usage can improve speed, due to cache effect +* Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */ +#define FSE_MAX_MEMORY_USAGE 14 +#define FSE_DEFAULT_MEMORY_USAGE 13 + +/* FSE_MAX_SYMBOL_VALUE : +* Maximum symbol value authorized. +* Required for proper stack allocation */ +#define FSE_MAX_SYMBOL_VALUE 255 + + +/**************************************************************** +* template functions type & suffix +****************************************************************/ +#define FSE_FUNCTION_TYPE BYTE +#define FSE_FUNCTION_EXTENSION + + +/**************************************************************** +* Byte symbol type +****************************************************************/ +#endif /* !FSE_COMMONDEFS_ONLY */ + + +/**************************************************************** +* Compiler specifics +****************************************************************/ +#ifdef _MSC_VER /* Visual Studio */ +# define FORCE_INLINE static __forceinline +# include /* For Visual 2005 */ +# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ +# pragma warning(disable : 4214) /* disable: C4214: non-int bitfields */ +#else +# ifdef __GNUC__ +# define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) +# define FORCE_INLINE static inline __attribute__((always_inline)) +# else +# define FORCE_INLINE static inline +# endif +#endif + + +/**************************************************************** +* Includes +****************************************************************/ +#include /* malloc, free, qsort */ +#include /* memcpy, memset */ +#include /* printf (debug) */ + +/**************************************************************** +* Constants +*****************************************************************/ +#define FSE_MAX_TABLELOG (FSE_MAX_MEMORY_USAGE-2) +#define FSE_MAX_TABLESIZE (1U< FSE_TABLELOG_ABSOLUTE_MAX +#error "FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX is not supported" +#endif + + +/**************************************************************** +* Error Management +****************************************************************/ +#define FSE_STATIC_ASSERT(c) { enum { FSE_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */ + + +/**************************************************************** +* Complex types +****************************************************************/ +typedef U32 DTable_max_t[FSE_DTABLE_SIZE_U32(FSE_MAX_TABLELOG)]; + + +/**************************************************************** +* Templates +****************************************************************/ +/* + designed to be included + for type-specific functions (template emulation in C) + Objective is to write these functions only once, for improved maintenance +*/ + +/* safety checks */ +#ifndef FSE_FUNCTION_EXTENSION +# error "FSE_FUNCTION_EXTENSION must be defined" +#endif +#ifndef FSE_FUNCTION_TYPE +# error "FSE_FUNCTION_TYPE must be defined" +#endif + +/* Function names */ +#define FSE_CAT(X,Y) X##Y +#define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y) +#define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y) + + +/* Function templates */ + +#define FSE_DECODE_TYPE FSE_TYPE_NAME(FSE_decode_t, FSE_FUNCTION_EXTENSION) + +static U32 FSE_tableStep(U32 tableSize) { return (tableSize>>1) + (tableSize>>3) + 3; } + +static size_t FSE_FUNCTION_NAME(FSE_buildDTable, FSE_FUNCTION_EXTENSION) +(FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog) +{ + FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)dt; + FSE_DECODE_TYPE* const tableDecode = (FSE_DECODE_TYPE*) (dt+1); /* because dt is unsigned, 32-bits aligned on 32-bits */ + const U32 tableSize = 1 << tableLog; + const U32 tableMask = tableSize-1; + const U32 step = FSE_tableStep(tableSize); + U16 symbolNext[FSE_MAX_SYMBOL_VALUE+1]; + U32 position = 0; + U32 highThreshold = tableSize-1; + const S16 largeLimit= (S16)(1 << (tableLog-1)); + U32 noLarge = 1; + U32 s; + + /* Sanity Checks */ + if (maxSymbolValue > FSE_MAX_SYMBOL_VALUE) return ERROR(maxSymbolValue_tooLarge); + if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge); + + /* Init, lay down lowprob symbols */ + DTableH[0].tableLog = (U16)tableLog; + for (s=0; s<=maxSymbolValue; s++) + { + if (normalizedCounter[s]==-1) + { + tableDecode[highThreshold--].symbol = (FSE_FUNCTION_TYPE)s; + symbolNext[s] = 1; + } + else + { + if (normalizedCounter[s] >= largeLimit) noLarge=0; + symbolNext[s] = normalizedCounter[s]; + } + } + + /* Spread symbols */ + for (s=0; s<=maxSymbolValue; s++) + { + int i; + for (i=0; i highThreshold) position = (position + step) & tableMask; /* lowprob area */ + } + } + + if (position!=0) return ERROR(GENERIC); /* position must reach all cells once, otherwise normalizedCounter is incorrect */ + + /* Build Decoding table */ + { + U32 i; + for (i=0; ifastMode = (U16)noLarge; + return 0; +} + + +#ifndef FSE_COMMONDEFS_ONLY +/****************************************** +* FSE helper functions +******************************************/ +static unsigned FSE_isError(size_t code) { return ERR_isError(code); } + + +/**************************************************************** +* FSE NCount encoding-decoding +****************************************************************/ +static short FSE_abs(short a) +{ + return a<0 ? -a : a; +} + +static size_t FSE_readNCount (short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr, + const void* headerBuffer, size_t hbSize) +{ + const BYTE* const istart = (const BYTE*) headerBuffer; + const BYTE* const iend = istart + hbSize; + const BYTE* ip = istart; + int nbBits; + int remaining; + int threshold; + U32 bitStream; + int bitCount; + unsigned charnum = 0; + int previous0 = 0; + + if (hbSize < 4) return ERROR(srcSize_wrong); + bitStream = MEM_readLE32(ip); + nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG; /* extract tableLog */ + if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge); + bitStream >>= 4; + bitCount = 4; + *tableLogPtr = nbBits; + remaining = (1<1) && (charnum<=*maxSVPtr)) + { + if (previous0) + { + unsigned n0 = charnum; + while ((bitStream & 0xFFFF) == 0xFFFF) + { + n0+=24; + if (ip < iend-5) + { + ip+=2; + bitStream = MEM_readLE32(ip) >> bitCount; + } + else + { + bitStream >>= 16; + bitCount+=16; + } + } + while ((bitStream & 3) == 3) + { + n0+=3; + bitStream>>=2; + bitCount+=2; + } + n0 += bitStream & 3; + bitCount += 2; + if (n0 > *maxSVPtr) return ERROR(maxSymbolValue_tooSmall); + while (charnum < n0) normalizedCounter[charnum++] = 0; + if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) + { + ip += bitCount>>3; + bitCount &= 7; + bitStream = MEM_readLE32(ip) >> bitCount; + } + else + bitStream >>= 2; + } + { + const short max = (short)((2*threshold-1)-remaining); + short count; + + if ((bitStream & (threshold-1)) < (U32)max) + { + count = (short)(bitStream & (threshold-1)); + bitCount += nbBits-1; + } + else + { + count = (short)(bitStream & (2*threshold-1)); + if (count >= threshold) count -= max; + bitCount += nbBits; + } + + count--; /* extra accuracy */ + remaining -= FSE_abs(count); + normalizedCounter[charnum++] = count; + previous0 = !count; + while (remaining < threshold) + { + nbBits--; + threshold >>= 1; + } + + { + if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) + { + ip += bitCount>>3; + bitCount &= 7; + } + else + { + bitCount -= (int)(8 * (iend - 4 - ip)); + ip = iend - 4; + } + bitStream = MEM_readLE32(ip) >> (bitCount & 31); + } + } + } + if (remaining != 1) return ERROR(GENERIC); + *maxSVPtr = charnum-1; + + ip += (bitCount+7)>>3; + if ((size_t)(ip-istart) > hbSize) return ERROR(srcSize_wrong); + return ip-istart; +} + + +/********************************************************* +* Decompression (Byte symbols) +*********************************************************/ +static size_t FSE_buildDTable_rle (FSE_DTable* dt, BYTE symbolValue) +{ + FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)dt; + FSE_decode_t* const cell = (FSE_decode_t*)(dt + 1); /* because dt is unsigned */ + + DTableH->tableLog = 0; + DTableH->fastMode = 0; + + cell->newState = 0; + cell->symbol = symbolValue; + cell->nbBits = 0; + + return 0; +} + + +static size_t FSE_buildDTable_raw (FSE_DTable* dt, unsigned nbBits) +{ + FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)dt; + FSE_decode_t* const dinfo = (FSE_decode_t*)(dt + 1); /* because dt is unsigned */ + const unsigned tableSize = 1 << nbBits; + const unsigned tableMask = tableSize - 1; + const unsigned maxSymbolValue = tableMask; + unsigned s; + + /* Sanity checks */ + if (nbBits < 1) return ERROR(GENERIC); /* min size */ + + /* Build Decoding Table */ + DTableH->tableLog = (U16)nbBits; + DTableH->fastMode = 1; + for (s=0; s<=maxSymbolValue; s++) + { + dinfo[s].newState = 0; + dinfo[s].symbol = (BYTE)s; + dinfo[s].nbBits = (BYTE)nbBits; + } + + return 0; +} + +FORCE_INLINE size_t FSE_decompress_usingDTable_generic( + void* dst, size_t maxDstSize, + const void* cSrc, size_t cSrcSize, + const FSE_DTable* dt, const unsigned fast) +{ + BYTE* const ostart = (BYTE*) dst; + BYTE* op = ostart; + BYTE* const omax = op + maxDstSize; + BYTE* const olimit = omax-3; + + BIT_DStream_t bitD; + FSE_DState_t state1; + FSE_DState_t state2; + size_t errorCode; + + /* Init */ + errorCode = BIT_initDStream(&bitD, cSrc, cSrcSize); /* replaced last arg by maxCompressed Size */ + if (FSE_isError(errorCode)) return errorCode; + + FSE_initDState(&state1, &bitD, dt); + FSE_initDState(&state2, &bitD, dt); + +#define FSE_GETSYMBOL(statePtr) fast ? FSE_decodeSymbolFast(statePtr, &bitD) : FSE_decodeSymbol(statePtr, &bitD) + + /* 4 symbols per loop */ + for ( ; (BIT_reloadDStream(&bitD)==BIT_DStream_unfinished) && (op sizeof(bitD.bitContainer)*8) /* This test must be static */ + BIT_reloadDStream(&bitD); + + op[1] = FSE_GETSYMBOL(&state2); + + if (FSE_MAX_TABLELOG*4+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */ + { if (BIT_reloadDStream(&bitD) > BIT_DStream_unfinished) { op+=2; break; } } + + op[2] = FSE_GETSYMBOL(&state1); + + if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */ + BIT_reloadDStream(&bitD); + + op[3] = FSE_GETSYMBOL(&state2); + } + + /* tail */ + /* note : BIT_reloadDStream(&bitD) >= FSE_DStream_partiallyFilled; Ends at exactly BIT_DStream_completed */ + while (1) + { + if ( (BIT_reloadDStream(&bitD)>BIT_DStream_completed) || (op==omax) || (BIT_endOfDStream(&bitD) && (fast || FSE_endOfDState(&state1))) ) + break; + + *op++ = FSE_GETSYMBOL(&state1); + + if ( (BIT_reloadDStream(&bitD)>BIT_DStream_completed) || (op==omax) || (BIT_endOfDStream(&bitD) && (fast || FSE_endOfDState(&state2))) ) + break; + + *op++ = FSE_GETSYMBOL(&state2); + } + + /* end ? */ + if (BIT_endOfDStream(&bitD) && FSE_endOfDState(&state1) && FSE_endOfDState(&state2)) + return op-ostart; + + if (op==omax) return ERROR(dstSize_tooSmall); /* dst buffer is full, but cSrc unfinished */ + + return ERROR(corruption_detected); +} + + +static size_t FSE_decompress_usingDTable(void* dst, size_t originalSize, + const void* cSrc, size_t cSrcSize, + const FSE_DTable* dt) +{ + const FSE_DTableHeader* DTableH = (const FSE_DTableHeader*)dt; + const U32 fastMode = DTableH->fastMode; + + /* select fast mode (static) */ + if (fastMode) return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 1); + return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 0); +} + + +static size_t FSE_decompress(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize) +{ + const BYTE* const istart = (const BYTE*)cSrc; + const BYTE* ip = istart; + short counting[FSE_MAX_SYMBOL_VALUE+1]; + DTable_max_t dt; /* Static analyzer seems unable to understand this table will be properly initialized later */ + unsigned tableLog; + unsigned maxSymbolValue = FSE_MAX_SYMBOL_VALUE; + size_t errorCode; + + if (cSrcSize<2) return ERROR(srcSize_wrong); /* too small input size */ + + /* normal FSE decoding mode */ + errorCode = FSE_readNCount (counting, &maxSymbolValue, &tableLog, istart, cSrcSize); + if (FSE_isError(errorCode)) return errorCode; + if (errorCode >= cSrcSize) return ERROR(srcSize_wrong); /* too small input size */ + ip += errorCode; + cSrcSize -= errorCode; + + errorCode = FSE_buildDTable (dt, counting, maxSymbolValue, tableLog); + if (FSE_isError(errorCode)) return errorCode; + + /* always return, even if it is an error code */ + return FSE_decompress_usingDTable (dst, maxDstSize, ip, cSrcSize, dt); +} + + + +#endif /* FSE_COMMONDEFS_ONLY */ +/* ****************************************************************** + Huff0 : Huffman coder, part of New Generation Entropy library + Copyright (C) 2013-2015, 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 : + - FSE+Huff0 source repository : https://github.com/Cyan4973/FiniteStateEntropy + - Public forum : https://groups.google.com/forum/#!forum/lz4c +****************************************************************** */ + +/**************************************************************** +* Compiler specifics +****************************************************************/ +#if defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) +/* inline is defined */ +#elif defined(_MSC_VER) +# define inline __inline +#else +# define inline /* disable inline */ +#endif + + +#ifdef _MSC_VER /* Visual Studio */ +# define FORCE_INLINE static __forceinline +# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ +#else +# ifdef __GNUC__ +# define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) +# define FORCE_INLINE static inline __attribute__((always_inline)) +# else +# define FORCE_INLINE static inline +# endif +#endif + + +/**************************************************************** +* Includes +****************************************************************/ +#include /* malloc, free, qsort */ +#include /* memcpy, memset */ +#include /* printf (debug) */ + +/**************************************************************** +* Error Management +****************************************************************/ +#define HUF_STATIC_ASSERT(c) { enum { HUF_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */ + + +/****************************************** +* Helper functions +******************************************/ +static unsigned HUF_isError(size_t code) { return ERR_isError(code); } + +#define HUF_ABSOLUTEMAX_TABLELOG 16 /* absolute limit of HUF_MAX_TABLELOG. Beyond that value, code does not work */ +#define HUF_MAX_TABLELOG 12 /* max configured tableLog (for static allocation); can be modified up to HUF_ABSOLUTEMAX_TABLELOG */ +#define HUF_DEFAULT_TABLELOG HUF_MAX_TABLELOG /* tableLog by default, when not specified */ +#define HUF_MAX_SYMBOL_VALUE 255 +#if (HUF_MAX_TABLELOG > HUF_ABSOLUTEMAX_TABLELOG) +# error "HUF_MAX_TABLELOG is too large !" +#endif + + + +/********************************************************* +* Huff0 : Huffman block decompression +*********************************************************/ +typedef struct { BYTE byte; BYTE nbBits; } HUF_DEltX2; /* single-symbol decoding */ + +typedef struct { U16 sequence; BYTE nbBits; BYTE length; } HUF_DEltX4; /* double-symbols decoding */ + +typedef struct { BYTE symbol; BYTE weight; } sortedSymbol_t; + +/*! HUF_readStats + Read compact Huffman tree, saved by HUF_writeCTable + @huffWeight : destination buffer + @return : size read from `src` +*/ +static size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats, + U32* nbSymbolsPtr, U32* tableLogPtr, + const void* src, size_t srcSize) +{ + U32 weightTotal; + U32 tableLog; + const BYTE* ip = (const BYTE*) src; + size_t iSize = ip[0]; + size_t oSize; + U32 n; + + //memset(huffWeight, 0, hwSize); /* is not necessary, even though some analyzer complain ... */ + + if (iSize >= 128) /* special header */ + { + if (iSize >= (242)) /* RLE */ + { + static int l[14] = { 1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 63, 64, 127, 128 }; + oSize = l[iSize-242]; + memset(huffWeight, 1, hwSize); + iSize = 0; + } + else /* Incompressible */ + { + oSize = iSize - 127; + iSize = ((oSize+1)/2); + if (iSize+1 > srcSize) return ERROR(srcSize_wrong); + if (oSize >= hwSize) return ERROR(corruption_detected); + ip += 1; + for (n=0; n> 4; + huffWeight[n+1] = ip[n/2] & 15; + } + } + } + else /* header compressed with FSE (normal case) */ + { + if (iSize+1 > srcSize) return ERROR(srcSize_wrong); + oSize = FSE_decompress(huffWeight, hwSize-1, ip+1, iSize); /* max (hwSize-1) values decoded, as last one is implied */ + if (FSE_isError(oSize)) return oSize; + } + + /* collect weight stats */ + memset(rankStats, 0, (HUF_ABSOLUTEMAX_TABLELOG + 1) * sizeof(U32)); + weightTotal = 0; + for (n=0; n= HUF_ABSOLUTEMAX_TABLELOG) return ERROR(corruption_detected); + rankStats[huffWeight[n]]++; + weightTotal += (1 << huffWeight[n]) >> 1; + } + + /* get last non-null symbol weight (implied, total must be 2^n) */ + tableLog = BIT_highbit32(weightTotal) + 1; + if (tableLog > HUF_ABSOLUTEMAX_TABLELOG) return ERROR(corruption_detected); + { + U32 total = 1 << tableLog; + U32 rest = total - weightTotal; + U32 verif = 1 << BIT_highbit32(rest); + U32 lastWeight = BIT_highbit32(rest) + 1; + if (verif != rest) return ERROR(corruption_detected); /* last value must be a clean power of 2 */ + huffWeight[oSize] = (BYTE)lastWeight; + rankStats[lastWeight]++; + } + + /* check tree construction validity */ + if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected); /* by construction : at least 2 elts of rank 1, must be even */ + + /* results */ + *nbSymbolsPtr = (U32)(oSize+1); + *tableLogPtr = tableLog; + return iSize+1; +} + + +/**************************/ +/* single-symbol decoding */ +/**************************/ + +static size_t HUF_readDTableX2 (U16* DTable, const void* src, size_t srcSize) +{ + BYTE huffWeight[HUF_MAX_SYMBOL_VALUE + 1]; + U32 rankVal[HUF_ABSOLUTEMAX_TABLELOG + 1]; /* large enough for values from 0 to 16 */ + U32 tableLog = 0; + const BYTE* ip = (const BYTE*) src; + size_t iSize = ip[0]; + U32 nbSymbols = 0; + U32 n; + U32 nextRankStart; + HUF_DEltX2* const dt = (HUF_DEltX2*)(DTable + 1); + + HUF_STATIC_ASSERT(sizeof(HUF_DEltX2) == sizeof(U16)); /* if compilation fails here, assertion is false */ + //memset(huffWeight, 0, sizeof(huffWeight)); /* is not necessary, even though some analyzer complain ... */ + + iSize = HUF_readStats(huffWeight, HUF_MAX_SYMBOL_VALUE + 1, rankVal, &nbSymbols, &tableLog, src, srcSize); + if (HUF_isError(iSize)) return iSize; + + /* check result */ + if (tableLog > DTable[0]) return ERROR(tableLog_tooLarge); /* DTable is too small */ + DTable[0] = (U16)tableLog; /* maybe should separate sizeof DTable, as allocated, from used size of DTable, in case of DTable re-use */ + + /* Prepare ranks */ + nextRankStart = 0; + for (n=1; n<=tableLog; n++) + { + U32 current = nextRankStart; + nextRankStart += (rankVal[n] << (n-1)); + rankVal[n] = current; + } + + /* fill DTable */ + for (n=0; n> 1; + U32 i; + HUF_DEltX2 D; + D.byte = (BYTE)n; D.nbBits = (BYTE)(tableLog + 1 - w); + for (i = rankVal[w]; i < rankVal[w] + length; i++) + dt[i] = D; + rankVal[w] += length; + } + + return iSize; +} + +static BYTE HUF_decodeSymbolX2(BIT_DStream_t* Dstream, const HUF_DEltX2* dt, const U32 dtLog) +{ + const size_t val = BIT_lookBitsFast(Dstream, dtLog); /* note : dtLog >= 1 */ + const BYTE c = dt[val].byte; + BIT_skipBits(Dstream, dt[val].nbBits); + return c; +} + +#define HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr) \ + *ptr++ = HUF_decodeSymbolX2(DStreamPtr, dt, dtLog) + +#define HUF_DECODE_SYMBOLX2_1(ptr, DStreamPtr) \ + if (MEM_64bits() || (HUF_MAX_TABLELOG<=12)) \ + HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr) + +#define HUF_DECODE_SYMBOLX2_2(ptr, DStreamPtr) \ + if (MEM_64bits()) \ + HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr) + +static inline size_t HUF_decodeStreamX2(BYTE* p, BIT_DStream_t* const bitDPtr, BYTE* const pEnd, const HUF_DEltX2* const dt, const U32 dtLog) +{ + BYTE* const pStart = p; + + /* up to 4 symbols at a time */ + while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p <= pEnd-4)) + { + HUF_DECODE_SYMBOLX2_2(p, bitDPtr); + HUF_DECODE_SYMBOLX2_1(p, bitDPtr); + HUF_DECODE_SYMBOLX2_2(p, bitDPtr); + HUF_DECODE_SYMBOLX2_0(p, bitDPtr); + } + + /* closer to the end */ + while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p < pEnd)) + HUF_DECODE_SYMBOLX2_0(p, bitDPtr); + + /* no more data to retrieve from bitstream, hence no need to reload */ + while (p < pEnd) + HUF_DECODE_SYMBOLX2_0(p, bitDPtr); + + return pEnd-pStart; +} + + +static size_t HUF_decompress4X2_usingDTable( + void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + const U16* DTable) +{ + if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */ + + { + const BYTE* const istart = (const BYTE*) cSrc; + BYTE* const ostart = (BYTE*) dst; + BYTE* const oend = ostart + dstSize; + + const HUF_DEltX2* const dt = ((const HUF_DEltX2*)DTable) +1; + const U32 dtLog = DTable[0]; + size_t errorCode; + + /* Init */ + BIT_DStream_t bitD1; + BIT_DStream_t bitD2; + BIT_DStream_t bitD3; + BIT_DStream_t bitD4; + const size_t length1 = MEM_readLE16(istart); + const size_t length2 = MEM_readLE16(istart+2); + const size_t length3 = MEM_readLE16(istart+4); + size_t length4; + const BYTE* const istart1 = istart + 6; /* jumpTable */ + const BYTE* const istart2 = istart1 + length1; + const BYTE* const istart3 = istart2 + length2; + const BYTE* const istart4 = istart3 + length3; + const size_t segmentSize = (dstSize+3) / 4; + BYTE* const opStart2 = ostart + segmentSize; + BYTE* const opStart3 = opStart2 + segmentSize; + BYTE* const opStart4 = opStart3 + segmentSize; + BYTE* op1 = ostart; + BYTE* op2 = opStart2; + BYTE* op3 = opStart3; + BYTE* op4 = opStart4; + U32 endSignal; + + length4 = cSrcSize - (length1 + length2 + length3 + 6); + if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */ + errorCode = BIT_initDStream(&bitD1, istart1, length1); + if (HUF_isError(errorCode)) return errorCode; + errorCode = BIT_initDStream(&bitD2, istart2, length2); + if (HUF_isError(errorCode)) return errorCode; + errorCode = BIT_initDStream(&bitD3, istart3, length3); + if (HUF_isError(errorCode)) return errorCode; + errorCode = BIT_initDStream(&bitD4, istart4, length4); + if (HUF_isError(errorCode)) return errorCode; + + /* 16-32 symbols per loop (4-8 symbols per stream) */ + endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4); + for ( ; (endSignal==BIT_DStream_unfinished) && (op4<(oend-7)) ; ) + { + HUF_DECODE_SYMBOLX2_2(op1, &bitD1); + HUF_DECODE_SYMBOLX2_2(op2, &bitD2); + HUF_DECODE_SYMBOLX2_2(op3, &bitD3); + HUF_DECODE_SYMBOLX2_2(op4, &bitD4); + HUF_DECODE_SYMBOLX2_1(op1, &bitD1); + HUF_DECODE_SYMBOLX2_1(op2, &bitD2); + HUF_DECODE_SYMBOLX2_1(op3, &bitD3); + HUF_DECODE_SYMBOLX2_1(op4, &bitD4); + HUF_DECODE_SYMBOLX2_2(op1, &bitD1); + HUF_DECODE_SYMBOLX2_2(op2, &bitD2); + HUF_DECODE_SYMBOLX2_2(op3, &bitD3); + HUF_DECODE_SYMBOLX2_2(op4, &bitD4); + HUF_DECODE_SYMBOLX2_0(op1, &bitD1); + HUF_DECODE_SYMBOLX2_0(op2, &bitD2); + HUF_DECODE_SYMBOLX2_0(op3, &bitD3); + HUF_DECODE_SYMBOLX2_0(op4, &bitD4); + + endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4); + } + + /* check corruption */ + if (op1 > opStart2) return ERROR(corruption_detected); + if (op2 > opStart3) return ERROR(corruption_detected); + if (op3 > opStart4) return ERROR(corruption_detected); + /* note : op4 supposed already verified within main loop */ + + /* finish bitStreams one by one */ + HUF_decodeStreamX2(op1, &bitD1, opStart2, dt, dtLog); + HUF_decodeStreamX2(op2, &bitD2, opStart3, dt, dtLog); + HUF_decodeStreamX2(op3, &bitD3, opStart4, dt, dtLog); + HUF_decodeStreamX2(op4, &bitD4, oend, dt, dtLog); + + /* check */ + endSignal = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4); + if (!endSignal) return ERROR(corruption_detected); + + /* decoded size */ + return dstSize; + } +} + + +static size_t HUF_decompress4X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize) +{ + HUF_CREATE_STATIC_DTABLEX2(DTable, HUF_MAX_TABLELOG); + const BYTE* ip = (const BYTE*) cSrc; + size_t errorCode; + + errorCode = HUF_readDTableX2 (DTable, cSrc, cSrcSize); + if (HUF_isError(errorCode)) return errorCode; + if (errorCode >= cSrcSize) return ERROR(srcSize_wrong); + ip += errorCode; + cSrcSize -= errorCode; + + return HUF_decompress4X2_usingDTable (dst, dstSize, ip, cSrcSize, DTable); +} + + +/***************************/ +/* double-symbols decoding */ +/***************************/ + +static void HUF_fillDTableX4Level2(HUF_DEltX4* DTable, U32 sizeLog, const U32 consumed, + const U32* rankValOrigin, const int minWeight, + const sortedSymbol_t* sortedSymbols, const U32 sortedListSize, + U32 nbBitsBaseline, U16 baseSeq) +{ + HUF_DEltX4 DElt; + U32 rankVal[HUF_ABSOLUTEMAX_TABLELOG + 1]; + U32 s; + + /* get pre-calculated rankVal */ + memcpy(rankVal, rankValOrigin, sizeof(rankVal)); + + /* fill skipped values */ + if (minWeight>1) + { + U32 i, skipSize = rankVal[minWeight]; + MEM_writeLE16(&(DElt.sequence), baseSeq); + DElt.nbBits = (BYTE)(consumed); + DElt.length = 1; + for (i = 0; i < skipSize; i++) + DTable[i] = DElt; + } + + /* fill DTable */ + for (s=0; s= 1 */ + + rankVal[weight] += length; + } +} + +typedef U32 rankVal_t[HUF_ABSOLUTEMAX_TABLELOG][HUF_ABSOLUTEMAX_TABLELOG + 1]; + +static void HUF_fillDTableX4(HUF_DEltX4* DTable, const U32 targetLog, + const sortedSymbol_t* sortedList, const U32 sortedListSize, + const U32* rankStart, rankVal_t rankValOrigin, const U32 maxWeight, + const U32 nbBitsBaseline) +{ + U32 rankVal[HUF_ABSOLUTEMAX_TABLELOG + 1]; + const int scaleLog = nbBitsBaseline - targetLog; /* note : targetLog >= srcLog, hence scaleLog <= 1 */ + const U32 minBits = nbBitsBaseline - maxWeight; + U32 s; + + memcpy(rankVal, rankValOrigin, sizeof(rankVal)); + + /* fill DTable */ + for (s=0; s= minBits) /* enough room for a second symbol */ + { + U32 sortedRank; + int minWeight = nbBits + scaleLog; + if (minWeight < 1) minWeight = 1; + sortedRank = rankStart[minWeight]; + HUF_fillDTableX4Level2(DTable+start, targetLog-nbBits, nbBits, + rankValOrigin[nbBits], minWeight, + sortedList+sortedRank, sortedListSize-sortedRank, + nbBitsBaseline, symbol); + } + else + { + U32 i; + const U32 end = start + length; + HUF_DEltX4 DElt; + + MEM_writeLE16(&(DElt.sequence), symbol); + DElt.nbBits = (BYTE)(nbBits); + DElt.length = 1; + for (i = start; i < end; i++) + DTable[i] = DElt; + } + rankVal[weight] += length; + } +} + +static size_t HUF_readDTableX4 (U32* DTable, const void* src, size_t srcSize) +{ + BYTE weightList[HUF_MAX_SYMBOL_VALUE + 1]; + sortedSymbol_t sortedSymbol[HUF_MAX_SYMBOL_VALUE + 1]; + U32 rankStats[HUF_ABSOLUTEMAX_TABLELOG + 1] = { 0 }; + U32 rankStart0[HUF_ABSOLUTEMAX_TABLELOG + 2] = { 0 }; + U32* const rankStart = rankStart0+1; + rankVal_t rankVal; + U32 tableLog, maxW, sizeOfSort, nbSymbols; + const U32 memLog = DTable[0]; + const BYTE* ip = (const BYTE*) src; + size_t iSize = ip[0]; + HUF_DEltX4* const dt = ((HUF_DEltX4*)DTable) + 1; + + HUF_STATIC_ASSERT(sizeof(HUF_DEltX4) == sizeof(U32)); /* if compilation fails here, assertion is false */ + if (memLog > HUF_ABSOLUTEMAX_TABLELOG) return ERROR(tableLog_tooLarge); + //memset(weightList, 0, sizeof(weightList)); /* is not necessary, even though some analyzer complain ... */ + + iSize = HUF_readStats(weightList, HUF_MAX_SYMBOL_VALUE + 1, rankStats, &nbSymbols, &tableLog, src, srcSize); + if (HUF_isError(iSize)) return iSize; + + /* check result */ + if (tableLog > memLog) return ERROR(tableLog_tooLarge); /* DTable can't fit code depth */ + + /* find maxWeight */ + for (maxW = tableLog; rankStats[maxW]==0; maxW--) {} /* necessarily finds a solution before 0 */ + + /* Get start index of each weight */ + { + U32 w, nextRankStart = 0; + for (w=1; w<=maxW; w++) + { + U32 current = nextRankStart; + nextRankStart += rankStats[w]; + rankStart[w] = current; + } + rankStart[0] = nextRankStart; /* put all 0w symbols at the end of sorted list*/ + sizeOfSort = nextRankStart; + } + + /* sort symbols by weight */ + { + U32 s; + for (s=0; s> consumed; + } + } + } + + HUF_fillDTableX4(dt, memLog, + sortedSymbol, sizeOfSort, + rankStart0, rankVal, maxW, + tableLog+1); + + return iSize; +} + + +static U32 HUF_decodeSymbolX4(void* op, BIT_DStream_t* DStream, const HUF_DEltX4* dt, const U32 dtLog) +{ + const size_t val = BIT_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */ + memcpy(op, dt+val, 2); + BIT_skipBits(DStream, dt[val].nbBits); + return dt[val].length; +} + +static U32 HUF_decodeLastSymbolX4(void* op, BIT_DStream_t* DStream, const HUF_DEltX4* dt, const U32 dtLog) +{ + const size_t val = BIT_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */ + memcpy(op, dt+val, 1); + if (dt[val].length==1) BIT_skipBits(DStream, dt[val].nbBits); + else + { + if (DStream->bitsConsumed < (sizeof(DStream->bitContainer)*8)) + { + BIT_skipBits(DStream, dt[val].nbBits); + if (DStream->bitsConsumed > (sizeof(DStream->bitContainer)*8)) + DStream->bitsConsumed = (sizeof(DStream->bitContainer)*8); /* ugly hack; works only because it's the last symbol. Note : can't easily extract nbBits from just this symbol */ + } + } + return 1; +} + + +#define HUF_DECODE_SYMBOLX4_0(ptr, DStreamPtr) \ + ptr += HUF_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog) + +#define HUF_DECODE_SYMBOLX4_1(ptr, DStreamPtr) \ + if (MEM_64bits() || (HUF_MAX_TABLELOG<=12)) \ + ptr += HUF_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog) + +#define HUF_DECODE_SYMBOLX4_2(ptr, DStreamPtr) \ + if (MEM_64bits()) \ + ptr += HUF_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog) + +static inline size_t HUF_decodeStreamX4(BYTE* p, BIT_DStream_t* bitDPtr, BYTE* const pEnd, const HUF_DEltX4* const dt, const U32 dtLog) +{ + BYTE* const pStart = p; + + /* up to 8 symbols at a time */ + while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p < pEnd-7)) + { + HUF_DECODE_SYMBOLX4_2(p, bitDPtr); + HUF_DECODE_SYMBOLX4_1(p, bitDPtr); + HUF_DECODE_SYMBOLX4_2(p, bitDPtr); + HUF_DECODE_SYMBOLX4_0(p, bitDPtr); + } + + /* closer to the end */ + while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p <= pEnd-2)) + HUF_DECODE_SYMBOLX4_0(p, bitDPtr); + + while (p <= pEnd-2) + HUF_DECODE_SYMBOLX4_0(p, bitDPtr); /* no need to reload : reached the end of DStream */ + + if (p < pEnd) + p += HUF_decodeLastSymbolX4(p, bitDPtr, dt, dtLog); + + return p-pStart; +} + + + +static size_t HUF_decompress4X4_usingDTable( + void* dst, size_t dstSize, + const void* cSrc, size_t cSrcSize, + const U32* DTable) +{ + if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */ + + { + const BYTE* const istart = (const BYTE*) cSrc; + BYTE* const ostart = (BYTE*) dst; + BYTE* const oend = ostart + dstSize; + + const HUF_DEltX4* const dt = ((const HUF_DEltX4*)DTable) +1; + const U32 dtLog = DTable[0]; + size_t errorCode; + + /* Init */ + BIT_DStream_t bitD1; + BIT_DStream_t bitD2; + BIT_DStream_t bitD3; + BIT_DStream_t bitD4; + const size_t length1 = MEM_readLE16(istart); + const size_t length2 = MEM_readLE16(istart+2); + const size_t length3 = MEM_readLE16(istart+4); + size_t length4; + const BYTE* const istart1 = istart + 6; /* jumpTable */ + const BYTE* const istart2 = istart1 + length1; + const BYTE* const istart3 = istart2 + length2; + const BYTE* const istart4 = istart3 + length3; + const size_t segmentSize = (dstSize+3) / 4; + BYTE* const opStart2 = ostart + segmentSize; + BYTE* const opStart3 = opStart2 + segmentSize; + BYTE* const opStart4 = opStart3 + segmentSize; + BYTE* op1 = ostart; + BYTE* op2 = opStart2; + BYTE* op3 = opStart3; + BYTE* op4 = opStart4; + U32 endSignal; + + length4 = cSrcSize - (length1 + length2 + length3 + 6); + if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */ + errorCode = BIT_initDStream(&bitD1, istart1, length1); + if (HUF_isError(errorCode)) return errorCode; + errorCode = BIT_initDStream(&bitD2, istart2, length2); + if (HUF_isError(errorCode)) return errorCode; + errorCode = BIT_initDStream(&bitD3, istart3, length3); + if (HUF_isError(errorCode)) return errorCode; + errorCode = BIT_initDStream(&bitD4, istart4, length4); + if (HUF_isError(errorCode)) return errorCode; + + /* 16-32 symbols per loop (4-8 symbols per stream) */ + endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4); + for ( ; (endSignal==BIT_DStream_unfinished) && (op4<(oend-7)) ; ) + { + HUF_DECODE_SYMBOLX4_2(op1, &bitD1); + HUF_DECODE_SYMBOLX4_2(op2, &bitD2); + HUF_DECODE_SYMBOLX4_2(op3, &bitD3); + HUF_DECODE_SYMBOLX4_2(op4, &bitD4); + HUF_DECODE_SYMBOLX4_1(op1, &bitD1); + HUF_DECODE_SYMBOLX4_1(op2, &bitD2); + HUF_DECODE_SYMBOLX4_1(op3, &bitD3); + HUF_DECODE_SYMBOLX4_1(op4, &bitD4); + HUF_DECODE_SYMBOLX4_2(op1, &bitD1); + HUF_DECODE_SYMBOLX4_2(op2, &bitD2); + HUF_DECODE_SYMBOLX4_2(op3, &bitD3); + HUF_DECODE_SYMBOLX4_2(op4, &bitD4); + HUF_DECODE_SYMBOLX4_0(op1, &bitD1); + HUF_DECODE_SYMBOLX4_0(op2, &bitD2); + HUF_DECODE_SYMBOLX4_0(op3, &bitD3); + HUF_DECODE_SYMBOLX4_0(op4, &bitD4); + + endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4); + } + + /* check corruption */ + if (op1 > opStart2) return ERROR(corruption_detected); + if (op2 > opStart3) return ERROR(corruption_detected); + if (op3 > opStart4) return ERROR(corruption_detected); + /* note : op4 supposed already verified within main loop */ + + /* finish bitStreams one by one */ + HUF_decodeStreamX4(op1, &bitD1, opStart2, dt, dtLog); + HUF_decodeStreamX4(op2, &bitD2, opStart3, dt, dtLog); + HUF_decodeStreamX4(op3, &bitD3, opStart4, dt, dtLog); + HUF_decodeStreamX4(op4, &bitD4, oend, dt, dtLog); + + /* check */ + endSignal = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4); + if (!endSignal) return ERROR(corruption_detected); + + /* decoded size */ + return dstSize; + } +} + + +static size_t HUF_decompress4X4 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize) +{ + HUF_CREATE_STATIC_DTABLEX4(DTable, HUF_MAX_TABLELOG); + const BYTE* ip = (const BYTE*) cSrc; + + size_t hSize = HUF_readDTableX4 (DTable, cSrc, cSrcSize); + if (HUF_isError(hSize)) return hSize; + if (hSize >= cSrcSize) return ERROR(srcSize_wrong); + ip += hSize; + cSrcSize -= hSize; + + return HUF_decompress4X4_usingDTable (dst, dstSize, ip, cSrcSize, DTable); +} + + +/**********************************/ +/* quad-symbol decoding */ +/**********************************/ +typedef struct { BYTE nbBits; BYTE nbBytes; } HUF_DDescX6; +typedef union { BYTE byte[4]; U32 sequence; } HUF_DSeqX6; + +/* recursive, up to level 3; may benefit from