2 * Copyright (c) 2015-present, Yann Collet, Facebook, Inc.
5 * This source code is licensed under both the BSD-style license (found in the
6 * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7 * in the COPYING file in the root directory of this source tree).
8 * You may select, at your option, one of the above-listed licenses.
12 /*-************************************
14 **************************************/
15 #ifdef _MSC_VER /* Visual Studio */
16 # define _CRT_SECURE_NO_WARNINGS /* fgets */
17 # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
18 # pragma warning(disable : 4204) /* disable: C4204: non-constant aggregate initializer */
22 /*-************************************
24 **************************************/
25 #include <stdlib.h> /* free */
26 #include <stdio.h> /* fgets, sscanf */
27 #include <string.h> /* strcmp */
29 #define ZSTD_STATIC_LINKING_ONLY /* ZSTD_compressContinue, ZSTD_compressBlock */
31 #include "zstd.h" /* ZSTD_VERSION_STRING */
32 #include "zstd_errors.h" /* ZSTD_getErrorCode */
33 #include "zstdmt_compress.h"
34 #define ZDICT_STATIC_LINKING_ONLY
35 #include "zdict.h" /* ZDICT_trainFromBuffer */
36 #include "datagen.h" /* RDG_genBuffer */
38 #define XXH_STATIC_LINKING_ONLY /* XXH64_state_t */
39 #include "xxhash.h" /* XXH64 */
43 /*-************************************
45 **************************************/
50 static const int FUZ_compressibility_default = 50;
51 static const int nbTestsDefault = 30000;
54 /*-************************************
56 **************************************/
57 #define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
58 #define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
59 static U32 g_displayLevel = 2;
61 static const U64 g_refreshRate = SEC_TO_MICRO / 6;
62 static UTIL_time_t g_displayClock = UTIL_TIME_INITIALIZER;
64 #define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \
65 if ((UTIL_clockSpanMicro(g_displayClock) > g_refreshRate) || (g_displayLevel>=4)) \
66 { g_displayClock = UTIL_getTime(); DISPLAY(__VA_ARGS__); \
67 if (g_displayLevel>=4) fflush(stderr); } }
70 /*-*******************************************************
72 *********************************************************/
75 /* Declaring the function is it isn't unused */
76 void FUZ_bug976(void);
78 { /* these constants shall not depend on MIN() macro */
79 assert(ZSTD_HASHLOG_MAX < 31);
80 assert(ZSTD_CHAINLOG_MAX < 31);
84 /*-*******************************************************
86 *********************************************************/
87 #define MIN(a,b) ((a)<(b)?(a):(b))
88 #define MAX(a,b) ((a)>(b)?(a):(b))
90 #define FUZ_rotl32(x,r) ((x << r) | (x >> (32 - r)))
91 static U32 FUZ_rand(U32* src)
93 static const U32 prime1 = 2654435761U;
94 static const U32 prime2 = 2246822519U;
98 rand32 = FUZ_rotl32(rand32, 13);
103 static U32 FUZ_highbit32(U32 v32)
106 if (v32==0) return 0;
107 while (v32) v32 >>= 1, nbBits++;
112 /*=============================================
114 =============================================*/
115 #define CHECK_Z(f) { \
116 size_t const err = f; \
117 if (ZSTD_isError(err)) { \
118 DISPLAY("Error => %s : %s ", \
119 #f, ZSTD_getErrorName(err)); \
123 #define CHECK_V(var, fn) size_t const var = fn; if (ZSTD_isError(var)) goto _output_error
124 #define CHECK(fn) { CHECK_V(err, fn); }
125 #define CHECKPLUS(var, fn, more) { CHECK_V(var, fn); more; }
127 #define CHECK_EQ(lhs, rhs) { \
128 if ((lhs) != (rhs)) { \
129 DISPLAY("Error L%u => %s != %s ", __LINE__, #lhs, #rhs); \
130 goto _output_error; \
135 /*=============================================
137 =============================================*/
138 #if defined(__APPLE__) && defined(__MACH__)
140 #include <malloc/malloc.h> /* malloc_size */
143 unsigned long long totalMalloc;
144 size_t currentMalloc;
150 static const mallocCounter_t INIT_MALLOC_COUNTER = { 0, 0, 0, 0, 0 };
152 static void* FUZ_mallocDebug(void* counter, size_t size)
154 mallocCounter_t* const mcPtr = (mallocCounter_t*)counter;
155 void* const ptr = malloc(size);
156 if (ptr==NULL) return NULL;
157 DISPLAYLEVEL(4, "allocating %u KB => effectively %u KB \n",
158 (unsigned)(size >> 10), (unsigned)(malloc_size(ptr) >> 10)); /* OS-X specific */
159 mcPtr->totalMalloc += size;
160 mcPtr->currentMalloc += size;
161 if (mcPtr->currentMalloc > mcPtr->peakMalloc)
162 mcPtr->peakMalloc = mcPtr->currentMalloc;
163 mcPtr->nbMalloc += 1;
167 static void FUZ_freeDebug(void* counter, void* address)
169 mallocCounter_t* const mcPtr = (mallocCounter_t*)counter;
170 DISPLAYLEVEL(4, "freeing %u KB \n", (unsigned)(malloc_size(address) >> 10));
172 mcPtr->currentMalloc -= malloc_size(address); /* OS-X specific */
176 static void FUZ_displayMallocStats(mallocCounter_t count)
178 DISPLAYLEVEL(3, "peak:%6u KB, nbMallocs:%2u, total:%6u KB \n",
179 (unsigned)(count.peakMalloc >> 10),
181 (unsigned)(count.totalMalloc >> 10));
184 static int FUZ_mallocTests_internal(unsigned seed, double compressibility, unsigned part,
185 void* inBuffer, size_t inSize, void* outBuffer, size_t outSize)
187 /* test only played in verbose mode, as they are long */
188 if (g_displayLevel<3) return 0;
190 /* Create compressible noise */
191 if (!inBuffer || !outBuffer) {
192 DISPLAY("Not enough memory, aborting\n");
195 RDG_genBuffer(inBuffer, inSize, compressibility, 0. /*auto*/, seed);
197 /* simple compression tests */
199 { int compressionLevel;
200 for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
201 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
202 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
203 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
204 CHECK_Z( ZSTD_compressCCtx(cctx, outBuffer, outSize, inBuffer, inSize, compressionLevel) );
206 DISPLAYLEVEL(3, "compressCCtx level %i : ", compressionLevel);
207 FUZ_displayMallocStats(malcount);
210 /* streaming compression tests */
212 { int compressionLevel;
213 for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
214 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
215 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
216 ZSTD_CCtx* const cstream = ZSTD_createCStream_advanced(cMem);
217 ZSTD_outBuffer out = { outBuffer, outSize, 0 };
218 ZSTD_inBuffer in = { inBuffer, inSize, 0 };
219 CHECK_Z( ZSTD_initCStream(cstream, compressionLevel) );
220 CHECK_Z( ZSTD_compressStream(cstream, &out, &in) );
221 CHECK_Z( ZSTD_endStream(cstream, &out) );
222 ZSTD_freeCStream(cstream);
223 DISPLAYLEVEL(3, "compressStream level %i : ", compressionLevel);
224 FUZ_displayMallocStats(malcount);
227 /* advanced MT API test */
229 { unsigned nbThreads;
230 for (nbThreads=1; nbThreads<=4; nbThreads++) {
231 int compressionLevel;
232 for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
233 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
234 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
235 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
236 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, compressionLevel) );
237 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, nbThreads) );
238 CHECK_Z( ZSTD_compress2(cctx, outBuffer, outSize, inBuffer, inSize) );
240 DISPLAYLEVEL(3, "compress_generic,-T%u,end level %i : ",
241 nbThreads, compressionLevel);
242 FUZ_displayMallocStats(malcount);
245 /* advanced MT streaming API test */
247 { unsigned nbThreads;
248 for (nbThreads=1; nbThreads<=4; nbThreads++) {
249 int compressionLevel;
250 for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
251 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
252 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
253 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
254 ZSTD_outBuffer out = { outBuffer, outSize, 0 };
255 ZSTD_inBuffer in = { inBuffer, inSize, 0 };
256 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, compressionLevel) );
257 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, nbThreads) );
258 CHECK_Z( ZSTD_compressStream2(cctx, &out, &in, ZSTD_e_continue) );
259 while ( ZSTD_compressStream2(cctx, &out, &in, ZSTD_e_end) ) {}
261 DISPLAYLEVEL(3, "compress_generic,-T%u,continue level %i : ",
262 nbThreads, compressionLevel);
263 FUZ_displayMallocStats(malcount);
269 static int FUZ_mallocTests(unsigned seed, double compressibility, unsigned part)
271 size_t const inSize = 64 MB + 16 MB + 4 MB + 1 MB + 256 KB + 64 KB; /* 85.3 MB */
272 size_t const outSize = ZSTD_compressBound(inSize);
273 void* const inBuffer = malloc(inSize);
274 void* const outBuffer = malloc(outSize);
277 /* Create compressible noise */
278 if (!inBuffer || !outBuffer) {
279 DISPLAY("Not enough memory, aborting \n");
283 result = FUZ_mallocTests_internal(seed, compressibility, part,
284 inBuffer, inSize, outBuffer, outSize);
293 static int FUZ_mallocTests(unsigned seed, double compressibility, unsigned part)
295 (void)seed; (void)compressibility; (void)part;
301 /*=============================================
303 =============================================*/
305 static int basicUnitTests(U32 seed, double compressibility)
307 size_t const CNBuffSize = 5 MB;
308 void* const CNBuffer = malloc(CNBuffSize);
309 size_t const compressedBufferSize = ZSTD_compressBound(CNBuffSize);
310 void* const compressedBuffer = malloc(compressedBufferSize);
311 void* const decodedBuffer = malloc(CNBuffSize);
316 /* Create compressible noise */
317 if (!CNBuffer || !compressedBuffer || !decodedBuffer) {
318 DISPLAY("Not enough memory, aborting\n");
322 RDG_genBuffer(CNBuffer, CNBuffSize, compressibility, 0., seed);
325 DISPLAYLEVEL(3, "test%3u : ZSTD_getErrorName : ", testNb++);
326 { const char* errorString = ZSTD_getErrorName(0);
327 DISPLAYLEVEL(3, "OK : %s \n", errorString);
330 DISPLAYLEVEL(3, "test%3u : ZSTD_getErrorName with wrong value : ", testNb++);
331 { const char* errorString = ZSTD_getErrorName(499);
332 DISPLAYLEVEL(3, "OK : %s \n", errorString);
335 DISPLAYLEVEL(3, "test%3u : min compression level : ", testNb++);
336 { int const mcl = ZSTD_minCLevel();
337 DISPLAYLEVEL(3, "%i (OK) \n", mcl);
340 DISPLAYLEVEL(3, "test%3u : compress %u bytes : ", testNb++, (unsigned)CNBuffSize);
341 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
342 if (cctx==NULL) goto _output_error;
343 CHECKPLUS(r, ZSTD_compressCCtx(cctx,
344 compressedBuffer, compressedBufferSize,
345 CNBuffer, CNBuffSize, 1),
347 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBuffSize*100);
349 DISPLAYLEVEL(3, "test%3i : size of cctx for level 1 : ", testNb++);
350 { size_t const cctxSize = ZSTD_sizeof_CCtx(cctx);
351 DISPLAYLEVEL(3, "%u bytes \n", (unsigned)cctxSize);
356 DISPLAYLEVEL(3, "test%3i : decompress skippable frame -8 size : ", testNb++);
358 char const skippable8[] = "\x50\x2a\x4d\x18\xf8\xff\xff\xff";
359 size_t const size = ZSTD_decompress(NULL, 0, skippable8, 8);
360 if (!ZSTD_isError(size)) goto _output_error;
362 DISPLAYLEVEL(3, "OK \n");
365 DISPLAYLEVEL(3, "test%3i : ZSTD_getFrameContentSize test : ", testNb++);
366 { unsigned long long const rSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
367 if (rSize != CNBuffSize) goto _output_error;
369 DISPLAYLEVEL(3, "OK \n");
371 DISPLAYLEVEL(3, "test%3i : ZSTD_findDecompressedSize test : ", testNb++);
372 { unsigned long long const rSize = ZSTD_findDecompressedSize(compressedBuffer, cSize);
373 if (rSize != CNBuffSize) goto _output_error;
375 DISPLAYLEVEL(3, "OK \n");
377 DISPLAYLEVEL(3, "test%3i : decompress %u bytes : ", testNb++, (unsigned)CNBuffSize);
378 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
379 if (r != CNBuffSize) goto _output_error; }
380 DISPLAYLEVEL(3, "OK \n");
382 DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
384 for (u=0; u<CNBuffSize; u++) {
385 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u]) goto _output_error;;
387 DISPLAYLEVEL(3, "OK \n");
390 DISPLAYLEVEL(3, "test%3i : decompress with null dict : ", testNb++);
391 { ZSTD_DCtx* const dctx = ZSTD_createDCtx(); assert(dctx != NULL);
392 { size_t const r = ZSTD_decompress_usingDict(dctx,
393 decodedBuffer, CNBuffSize,
394 compressedBuffer, cSize,
396 if (r != CNBuffSize) goto _output_error;
400 DISPLAYLEVEL(3, "OK \n");
402 DISPLAYLEVEL(3, "test%3i : decompress with null DDict : ", testNb++);
403 { ZSTD_DCtx* const dctx = ZSTD_createDCtx(); assert(dctx != NULL);
404 { size_t const r = ZSTD_decompress_usingDDict(dctx,
405 decodedBuffer, CNBuffSize,
406 compressedBuffer, cSize,
408 if (r != CNBuffSize) goto _output_error;
412 DISPLAYLEVEL(3, "OK \n");
414 DISPLAYLEVEL(3, "test%3i : decompress with 1 missing byte : ", testNb++);
415 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize-1);
416 if (!ZSTD_isError(r)) goto _output_error;
417 if (ZSTD_getErrorCode((size_t)r) != ZSTD_error_srcSize_wrong) goto _output_error; }
418 DISPLAYLEVEL(3, "OK \n");
420 DISPLAYLEVEL(3, "test%3i : decompress with 1 too much byte : ", testNb++);
421 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize+1);
422 if (!ZSTD_isError(r)) goto _output_error;
423 if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
424 DISPLAYLEVEL(3, "OK \n");
426 DISPLAYLEVEL(3, "test%3i : decompress too large input : ", testNb++);
427 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, compressedBufferSize);
428 if (!ZSTD_isError(r)) goto _output_error;
429 if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
430 DISPLAYLEVEL(3, "OK \n");
432 DISPLAYLEVEL(3, "test%3d : check CCtx size after compressing empty input : ", testNb++);
433 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
434 size_t const r = ZSTD_compressCCtx(cctx, compressedBuffer, compressedBufferSize, NULL, 0, 19);
435 if (ZSTD_isError(r)) goto _output_error;
436 if (ZSTD_sizeof_CCtx(cctx) > (1U << 20)) goto _output_error;
440 DISPLAYLEVEL(3, "OK \n");
442 DISPLAYLEVEL(3, "test%3d : decompress empty frame into NULL : ", testNb++);
443 { size_t const r = ZSTD_decompress(NULL, 0, compressedBuffer, cSize);
444 if (ZSTD_isError(r)) goto _output_error;
445 if (r != 0) goto _output_error;
447 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
448 ZSTD_outBuffer output;
449 if (cctx==NULL) goto _output_error;
450 output.dst = compressedBuffer;
451 output.size = compressedBufferSize;
453 CHECK_Z( ZSTD_initCStream(cctx, 1) ); /* content size unknown */
454 CHECK_Z( ZSTD_flushStream(cctx, &output) ); /* ensure no possibility to "concatenate" and determine the content size */
455 CHECK_Z( ZSTD_endStream(cctx, &output) );
457 /* single scan decompression */
458 { size_t const r = ZSTD_decompress(NULL, 0, compressedBuffer, output.pos);
459 if (ZSTD_isError(r)) goto _output_error;
460 if (r != 0) goto _output_error;
462 /* streaming decompression */
463 { ZSTD_DCtx* const dstream = ZSTD_createDStream();
464 ZSTD_inBuffer dinput;
465 ZSTD_outBuffer doutput;
467 if (dstream==NULL) goto _output_error;
468 dinput.src = compressedBuffer;
474 CHECK_Z ( ZSTD_initDStream(dstream) );
475 for (ipos=1; ipos<=output.pos; ipos++) {
477 CHECK_Z ( ZSTD_decompressStream(dstream, &doutput, &dinput) );
479 if (doutput.pos != 0) goto _output_error;
480 ZSTD_freeDStream(dstream);
483 DISPLAYLEVEL(3, "OK \n");
485 DISPLAYLEVEL(3, "test%3d : re-use CCtx with expanding block size : ", testNb++);
486 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
487 ZSTD_parameters const params = ZSTD_getParams(1, ZSTD_CONTENTSIZE_UNKNOWN, 0);
488 assert(params.fParams.contentSizeFlag == 1); /* block size will be adapted if pledgedSrcSize is enabled */
489 CHECK_Z( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, 1 /*pledgedSrcSize*/) );
490 CHECK_Z( ZSTD_compressEnd(cctx, compressedBuffer, compressedBufferSize, CNBuffer, 1) ); /* creates a block size of 1 */
492 CHECK_Z( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, ZSTD_CONTENTSIZE_UNKNOWN) ); /* re-use same parameters */
493 { size_t const inSize = 2* 128 KB;
494 size_t const outSize = ZSTD_compressBound(inSize);
495 CHECK_Z( ZSTD_compressEnd(cctx, compressedBuffer, outSize, CNBuffer, inSize) );
496 /* will fail if blockSize is not resized */
500 DISPLAYLEVEL(3, "OK \n");
502 DISPLAYLEVEL(3, "test%3d : re-using a CCtx should compress the same : ", testNb++);
503 { size_t const sampleSize = 30;
506 ((char*)CNBuffer)[i] = (char)i; /* ensure no match during initial section */
507 memcpy((char*)CNBuffer + 20, CNBuffer, 10); /* create one match, starting from beginning of sample, which is the difficult case (see #1241) */
508 for (i=1; i<=19; i++) {
509 ZSTD_CCtx* const cctx = ZSTD_createCCtx();
511 DISPLAYLEVEL(5, "l%i ", i);
512 size1 = ZSTD_compressCCtx(cctx, compressedBuffer, compressedBufferSize, CNBuffer, sampleSize, i);
515 size2 = ZSTD_compressCCtx(cctx, compressedBuffer, compressedBufferSize, CNBuffer, sampleSize, i);
517 CHECK_EQ(size1, size2);
519 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, i) );
520 size2 = ZSTD_compress2(cctx, compressedBuffer, compressedBufferSize, CNBuffer, sampleSize);
522 CHECK_EQ(size1, size2);
524 size2 = ZSTD_compress2(cctx, compressedBuffer, ZSTD_compressBound(sampleSize) - 1, CNBuffer, sampleSize); /* force streaming, as output buffer is not large enough to guarantee success */
526 CHECK_EQ(size1, size2);
532 inb.size = sampleSize;
533 outb.dst = compressedBuffer;
535 outb.size = ZSTD_compressBound(sampleSize) - 1; /* force streaming, as output buffer is not large enough to guarantee success */
536 CHECK_Z( ZSTD_compressStream2(cctx, &outb, &inb, ZSTD_e_end) );
537 assert(inb.pos == inb.size);
538 CHECK_EQ(size1, outb.pos);
544 DISPLAYLEVEL(3, "OK \n");
546 DISPLAYLEVEL(3, "test%3d : btultra2 & 1st block : ", testNb++);
547 { size_t const sampleSize = 1024;
548 ZSTD_CCtx* const cctx = ZSTD_createCCtx();
554 outb.dst = compressedBuffer;
556 outb.size = compressedBufferSize;
557 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, ZSTD_maxCLevel()) );
559 inb.size = sampleSize; /* start with something, so that context is already used */
560 CHECK_Z( ZSTD_compressStream2(cctx, &outb, &inb, ZSTD_e_end) ); /* will break internal assert if stats_init is not disabled */
561 assert(inb.pos == inb.size);
562 outb.pos = 0; /* cancel output */
564 CHECK_Z( ZSTD_CCtx_setPledgedSrcSize(cctx, sampleSize) );
565 inb.size = 4; /* too small size : compression will be skipped */
567 CHECK_Z( ZSTD_compressStream2(cctx, &outb, &inb, ZSTD_e_flush) );
568 assert(inb.pos == inb.size);
570 inb.size += 5; /* too small size : compression will be skipped */
571 CHECK_Z( ZSTD_compressStream2(cctx, &outb, &inb, ZSTD_e_flush) );
572 assert(inb.pos == inb.size);
574 inb.size += 11; /* small enough to attempt compression */
575 CHECK_Z( ZSTD_compressStream2(cctx, &outb, &inb, ZSTD_e_flush) );
576 assert(inb.pos == inb.size);
578 assert(inb.pos < sampleSize);
579 inb.size = sampleSize; /* large enough to trigger stats_init, but no longer at beginning */
580 CHECK_Z( ZSTD_compressStream2(cctx, &outb, &inb, ZSTD_e_end) ); /* will break internal assert if stats_init is not disabled */
581 assert(inb.pos == inb.size);
584 DISPLAYLEVEL(3, "OK \n");
586 DISPLAYLEVEL(3, "test%3d : ZSTD_CCtx_getParameter() : ", testNb++);
587 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
588 ZSTD_outBuffer out = {NULL, 0, 0};
589 ZSTD_inBuffer in = {NULL, 0, 0};
592 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_compressionLevel, &value));
594 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_hashLog, &value));
596 CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_c_hashLog, ZSTD_HASHLOG_MIN));
597 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_compressionLevel, &value));
599 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_hashLog, &value));
600 CHECK_EQ(value, ZSTD_HASHLOG_MIN);
601 CHECK_Z(ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, 7));
602 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_compressionLevel, &value));
604 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_hashLog, &value));
605 CHECK_EQ(value, ZSTD_HASHLOG_MIN);
606 /* Start a compression job */
607 ZSTD_compressStream2(cctx, &out, &in, ZSTD_e_continue);
608 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_compressionLevel, &value));
610 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_hashLog, &value));
611 CHECK_EQ(value, ZSTD_HASHLOG_MIN);
613 ZSTD_CCtx_reset(cctx, ZSTD_reset_session_only);
614 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_compressionLevel, &value));
616 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_hashLog, &value));
617 CHECK_EQ(value, ZSTD_HASHLOG_MIN);
618 /* Reset the parameters */
619 ZSTD_CCtx_reset(cctx, ZSTD_reset_parameters);
620 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_compressionLevel, &value));
622 CHECK_Z(ZSTD_CCtx_getParameter(cctx, ZSTD_c_hashLog, &value));
627 DISPLAYLEVEL(3, "OK \n");
629 /* this test is really too long, and should be made faster */
630 DISPLAYLEVEL(3, "test%3d : overflow protection with large windowLog : ", testNb++);
631 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
632 ZSTD_parameters params = ZSTD_getParams(-999, ZSTD_CONTENTSIZE_UNKNOWN, 0);
633 size_t const nbCompressions = ((1U << 31) / CNBuffSize) + 2; /* ensure U32 overflow protection is triggered */
635 assert(cctx != NULL);
636 params.fParams.contentSizeFlag = 0;
637 params.cParams.windowLog = ZSTD_WINDOWLOG_MAX;
638 for (cnb = 0; cnb < nbCompressions; ++cnb) {
639 DISPLAYLEVEL(6, "run %zu / %zu \n", cnb, nbCompressions);
640 CHECK_Z( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, ZSTD_CONTENTSIZE_UNKNOWN) ); /* re-use same parameters */
641 CHECK_Z( ZSTD_compressEnd(cctx, compressedBuffer, compressedBufferSize, CNBuffer, CNBuffSize) );
645 DISPLAYLEVEL(3, "OK \n");
647 DISPLAYLEVEL(3, "test%3d : size down context : ", testNb++);
648 { ZSTD_CCtx* const largeCCtx = ZSTD_createCCtx();
649 assert(largeCCtx != NULL);
650 CHECK_Z( ZSTD_compressBegin(largeCCtx, 19) ); /* streaming implies ZSTD_CONTENTSIZE_UNKNOWN, which maximizes memory usage */
651 CHECK_Z( ZSTD_compressEnd(largeCCtx, compressedBuffer, compressedBufferSize, CNBuffer, 1) );
652 { size_t const largeCCtxSize = ZSTD_sizeof_CCtx(largeCCtx); /* size of context must be measured after compression */
653 { ZSTD_CCtx* const smallCCtx = ZSTD_createCCtx();
654 assert(smallCCtx != NULL);
655 CHECK_Z(ZSTD_compressCCtx(smallCCtx, compressedBuffer, compressedBufferSize, CNBuffer, 1, 1));
656 { size_t const smallCCtxSize = ZSTD_sizeof_CCtx(smallCCtx);
657 DISPLAYLEVEL(5, "(large) %zuKB > 32*%zuKB (small) : ",
658 largeCCtxSize>>10, smallCCtxSize>>10);
659 assert(largeCCtxSize > 32* smallCCtxSize); /* note : "too large" definition is handled within zstd_compress.c .
660 * make this test case extreme, so that it doesn't depend on a possibly fluctuating definition */
662 ZSTD_freeCCtx(smallCCtx);
664 { U32 const maxNbAttempts = 1100; /* nb of usages before triggering size down is handled within zstd_compress.c.
665 * currently defined as 128x, but could be adjusted in the future.
666 * make this test long enough so that it's not too much tied to the current definition within zstd_compress.c */
668 for (u=0; u<maxNbAttempts; u++) {
669 CHECK_Z(ZSTD_compressCCtx(largeCCtx, compressedBuffer, compressedBufferSize, CNBuffer, 1, 1));
670 if (ZSTD_sizeof_CCtx(largeCCtx) < largeCCtxSize) break; /* sized down */
672 DISPLAYLEVEL(5, "size down after %u attempts : ", u);
673 if (u==maxNbAttempts) goto _output_error; /* no sizedown happened */
676 ZSTD_freeCCtx(largeCCtx);
678 DISPLAYLEVEL(3, "OK \n");
680 /* Static CCtx tests */
681 #define STATIC_CCTX_LEVEL 3
682 DISPLAYLEVEL(3, "test%3i : create static CCtx for level %u :", testNb++, STATIC_CCTX_LEVEL);
683 { size_t const staticCCtxSize = ZSTD_estimateCStreamSize(STATIC_CCTX_LEVEL);
684 void* const staticCCtxBuffer = malloc(staticCCtxSize);
685 size_t const staticDCtxSize = ZSTD_estimateDCtxSize();
686 void* const staticDCtxBuffer = malloc(staticDCtxSize);
687 if (staticCCtxBuffer==NULL || staticDCtxBuffer==NULL) {
688 free(staticCCtxBuffer);
689 free(staticDCtxBuffer);
690 DISPLAY("Not enough memory, aborting\n");
694 { ZSTD_CCtx* staticCCtx = ZSTD_initStaticCCtx(staticCCtxBuffer, staticCCtxSize);
695 ZSTD_DCtx* staticDCtx = ZSTD_initStaticDCtx(staticDCtxBuffer, staticDCtxSize);
696 if ((staticCCtx==NULL) || (staticDCtx==NULL)) goto _output_error;
697 DISPLAYLEVEL(3, "OK \n");
699 DISPLAYLEVEL(3, "test%3i : init CCtx for level %u : ", testNb++, STATIC_CCTX_LEVEL);
700 { size_t const r = ZSTD_compressBegin(staticCCtx, STATIC_CCTX_LEVEL);
701 if (ZSTD_isError(r)) goto _output_error; }
702 DISPLAYLEVEL(3, "OK \n");
704 DISPLAYLEVEL(3, "test%3i : simple compression test with static CCtx : ", testNb++);
705 CHECKPLUS(r, ZSTD_compressCCtx(staticCCtx,
706 compressedBuffer, compressedBufferSize,
707 CNBuffer, CNBuffSize, STATIC_CCTX_LEVEL),
709 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n",
710 (unsigned)cSize, (double)cSize/CNBuffSize*100);
712 DISPLAYLEVEL(3, "test%3i : simple decompression test with static DCtx : ", testNb++);
713 { size_t const r = ZSTD_decompressDCtx(staticDCtx,
714 decodedBuffer, CNBuffSize,
715 compressedBuffer, cSize);
716 if (r != CNBuffSize) goto _output_error; }
717 DISPLAYLEVEL(3, "OK \n");
719 DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
721 for (u=0; u<CNBuffSize; u++) {
722 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u])
725 DISPLAYLEVEL(3, "OK \n");
727 DISPLAYLEVEL(3, "test%3i : init CCtx for too large level (must fail) : ", testNb++);
728 { size_t const r = ZSTD_compressBegin(staticCCtx, ZSTD_maxCLevel());
729 if (!ZSTD_isError(r)) goto _output_error; }
730 DISPLAYLEVEL(3, "OK \n");
732 DISPLAYLEVEL(3, "test%3i : init CCtx for small level %u (should work again) : ", testNb++, 1);
733 { size_t const r = ZSTD_compressBegin(staticCCtx, 1);
734 if (ZSTD_isError(r)) goto _output_error; }
735 DISPLAYLEVEL(3, "OK \n");
737 DISPLAYLEVEL(3, "test%3i : init CStream for small level %u : ", testNb++, 1);
738 { size_t const r = ZSTD_initCStream(staticCCtx, 1);
739 if (ZSTD_isError(r)) goto _output_error; }
740 DISPLAYLEVEL(3, "OK \n");
742 DISPLAYLEVEL(3, "test%3i : init CStream with dictionary (should fail) : ", testNb++);
743 { size_t const r = ZSTD_initCStream_usingDict(staticCCtx, CNBuffer, 64 KB, 1);
744 if (!ZSTD_isError(r)) goto _output_error; }
745 DISPLAYLEVEL(3, "OK \n");
747 DISPLAYLEVEL(3, "test%3i : init DStream (should fail) : ", testNb++);
748 { size_t const r = ZSTD_initDStream(staticDCtx);
749 if (ZSTD_isError(r)) goto _output_error; }
750 { ZSTD_outBuffer output = { decodedBuffer, CNBuffSize, 0 };
751 ZSTD_inBuffer input = { compressedBuffer, ZSTD_FRAMEHEADERSIZE_MAX+1, 0 };
752 size_t const r = ZSTD_decompressStream(staticDCtx, &output, &input);
753 if (!ZSTD_isError(r)) goto _output_error;
755 DISPLAYLEVEL(3, "OK \n");
757 free(staticCCtxBuffer);
758 free(staticDCtxBuffer);
761 DISPLAYLEVEL(3, "test%3i : Static negative levels : ", testNb++);
762 { size_t const cctxSizeN1 = ZSTD_estimateCCtxSize(-1);
763 size_t const cctxSizeP1 = ZSTD_estimateCCtxSize(1);
764 size_t const cstreamSizeN1 = ZSTD_estimateCStreamSize(-1);
765 size_t const cstreamSizeP1 = ZSTD_estimateCStreamSize(1);
767 if (!(0 < cctxSizeN1 && cctxSizeN1 <= cctxSizeP1)) goto _output_error;
768 if (!(0 < cstreamSizeN1 && cstreamSizeN1 <= cstreamSizeP1)) goto _output_error;
770 DISPLAYLEVEL(3, "OK \n");
773 /* ZSTDMT simple MT compression test */
774 DISPLAYLEVEL(3, "test%3i : create ZSTDMT CCtx : ", testNb++);
775 { ZSTDMT_CCtx* mtctx = ZSTDMT_createCCtx(2);
777 DISPLAY("mtctx : mot enough memory, aborting \n");
781 DISPLAYLEVEL(3, "OK \n");
783 DISPLAYLEVEL(3, "test%3u : compress %u bytes with 2 threads : ", testNb++, (unsigned)CNBuffSize);
784 CHECKPLUS(r, ZSTDMT_compressCCtx(mtctx,
785 compressedBuffer, compressedBufferSize,
786 CNBuffer, CNBuffSize,
789 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBuffSize*100);
791 DISPLAYLEVEL(3, "test%3i : decompressed size test : ", testNb++);
792 { unsigned long long const rSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
793 if (rSize != CNBuffSize) {
794 DISPLAY("ZSTD_getFrameContentSize incorrect : %u != %u \n", (unsigned)rSize, (unsigned)CNBuffSize);
797 DISPLAYLEVEL(3, "OK \n");
799 DISPLAYLEVEL(3, "test%3i : decompress %u bytes : ", testNb++, (unsigned)CNBuffSize);
800 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
801 if (r != CNBuffSize) goto _output_error; }
802 DISPLAYLEVEL(3, "OK \n");
804 DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
806 for (u=0; u<CNBuffSize; u++) {
807 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u]) goto _output_error;;
809 DISPLAYLEVEL(3, "OK \n");
811 DISPLAYLEVEL(3, "test%3i : compress -T2 with checksum : ", testNb++);
812 { ZSTD_parameters params = ZSTD_getParams(1, CNBuffSize, 0);
813 params.fParams.checksumFlag = 1;
814 params.fParams.contentSizeFlag = 1;
815 CHECKPLUS(r, ZSTDMT_compress_advanced(mtctx,
816 compressedBuffer, compressedBufferSize,
817 CNBuffer, CNBuffSize,
818 NULL, params, 3 /*overlapRLog*/),
821 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBuffSize*100);
823 DISPLAYLEVEL(3, "test%3i : decompress %u bytes : ", testNb++, (unsigned)CNBuffSize);
824 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
825 if (r != CNBuffSize) goto _output_error; }
826 DISPLAYLEVEL(3, "OK \n");
828 ZSTDMT_freeCCtx(mtctx);
832 /* Simple API multiframe test */
833 DISPLAYLEVEL(3, "test%3i : compress multiple frames : ", testNb++);
837 /* only use the first half so we don't push against size limit of compressedBuffer */
838 size_t const segSize = (CNBuffSize / 2) / segs;
839 for (i = 0; i < segs; i++) {
840 CHECK_V(r, ZSTD_compress(
841 (BYTE *)compressedBuffer + off, CNBuffSize - off,
842 (BYTE *)CNBuffer + segSize * i,
846 /* insert skippable frame */
847 const U32 skipLen = 129 KB;
848 MEM_writeLE32((BYTE*)compressedBuffer + off, ZSTD_MAGIC_SKIPPABLE_START);
849 MEM_writeLE32((BYTE*)compressedBuffer + off + 4, skipLen);
850 off += skipLen + ZSTD_SKIPPABLEHEADERSIZE;
855 DISPLAYLEVEL(3, "OK \n");
857 DISPLAYLEVEL(3, "test%3i : get decompressed size of multiple frames : ", testNb++);
858 { unsigned long long const r = ZSTD_findDecompressedSize(compressedBuffer, cSize);
859 if (r != CNBuffSize / 2) goto _output_error; }
860 DISPLAYLEVEL(3, "OK \n");
862 DISPLAYLEVEL(3, "test%3i : decompress multiple frames : ", testNb++);
863 { CHECK_V(r, ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize));
864 if (r != CNBuffSize / 2) goto _output_error; }
865 DISPLAYLEVEL(3, "OK \n");
867 DISPLAYLEVEL(3, "test%3i : check decompressed result : ", testNb++);
868 if (memcmp(decodedBuffer, CNBuffer, CNBuffSize / 2) != 0) goto _output_error;
869 DISPLAYLEVEL(3, "OK \n");
871 /* Dictionary and CCtx Duplication tests */
872 { ZSTD_CCtx* const ctxOrig = ZSTD_createCCtx();
873 ZSTD_CCtx* const ctxDuplicated = ZSTD_createCCtx();
874 ZSTD_DCtx* const dctx = ZSTD_createDCtx();
875 static const size_t dictSize = 551;
876 assert(dctx != NULL); assert(ctxOrig != NULL); assert(ctxDuplicated != NULL);
878 DISPLAYLEVEL(3, "test%3i : copy context too soon : ", testNb++);
879 { size_t const copyResult = ZSTD_copyCCtx(ctxDuplicated, ctxOrig, 0);
880 if (!ZSTD_isError(copyResult)) goto _output_error; } /* error must be detected */
881 DISPLAYLEVEL(3, "OK \n");
883 DISPLAYLEVEL(3, "test%3i : load dictionary into context : ", testNb++);
884 CHECK( ZSTD_compressBegin_usingDict(ctxOrig, CNBuffer, dictSize, 2) );
885 CHECK( ZSTD_copyCCtx(ctxDuplicated, ctxOrig, 0) ); /* Begin_usingDict implies unknown srcSize, so match that */
886 DISPLAYLEVEL(3, "OK \n");
888 DISPLAYLEVEL(3, "test%3i : compress with flat dictionary : ", testNb++);
890 CHECKPLUS(r, ZSTD_compressEnd(ctxOrig, compressedBuffer, compressedBufferSize,
891 (const char*)CNBuffer + dictSize, CNBuffSize - dictSize),
893 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBuffSize*100);
895 DISPLAYLEVEL(3, "test%3i : frame built with flat dictionary should be decompressible : ", testNb++);
896 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
897 decodedBuffer, CNBuffSize,
898 compressedBuffer, cSize,
900 if (r != CNBuffSize - dictSize) goto _output_error);
901 DISPLAYLEVEL(3, "OK \n");
903 DISPLAYLEVEL(3, "test%3i : compress with duplicated context : ", testNb++);
904 { size_t const cSizeOrig = cSize;
906 CHECKPLUS(r, ZSTD_compressEnd(ctxDuplicated, compressedBuffer, compressedBufferSize,
907 (const char*)CNBuffer + dictSize, CNBuffSize - dictSize),
909 if (cSize != cSizeOrig) goto _output_error; /* should be identical ==> same size */
911 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBuffSize*100);
913 DISPLAYLEVEL(3, "test%3i : frame built with duplicated context should be decompressible : ", testNb++);
914 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
915 decodedBuffer, CNBuffSize,
916 compressedBuffer, cSize,
918 if (r != CNBuffSize - dictSize) goto _output_error);
919 DISPLAYLEVEL(3, "OK \n");
921 DISPLAYLEVEL(3, "test%3i : decompress with DDict : ", testNb++);
922 { ZSTD_DDict* const ddict = ZSTD_createDDict(CNBuffer, dictSize);
923 size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, ddict);
924 if (r != CNBuffSize - dictSize) goto _output_error;
925 DISPLAYLEVEL(3, "OK (size of DDict : %u) \n", (unsigned)ZSTD_sizeof_DDict(ddict));
926 ZSTD_freeDDict(ddict);
929 DISPLAYLEVEL(3, "test%3i : decompress with static DDict : ", testNb++);
930 { size_t const ddictBufferSize = ZSTD_estimateDDictSize(dictSize, ZSTD_dlm_byCopy);
931 void* ddictBuffer = malloc(ddictBufferSize);
932 if (ddictBuffer == NULL) goto _output_error;
933 { const ZSTD_DDict* const ddict = ZSTD_initStaticDDict(ddictBuffer, ddictBufferSize, CNBuffer, dictSize, ZSTD_dlm_byCopy, ZSTD_dct_auto);
934 size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, ddict);
935 if (r != CNBuffSize - dictSize) goto _output_error;
938 DISPLAYLEVEL(3, "OK (size of static DDict : %u) \n", (unsigned)ddictBufferSize);
941 DISPLAYLEVEL(3, "test%3i : check content size on duplicated context : ", testNb++);
942 { size_t const testSize = CNBuffSize / 3;
943 { ZSTD_parameters p = ZSTD_getParams(2, testSize, dictSize);
944 p.fParams.contentSizeFlag = 1;
945 CHECK( ZSTD_compressBegin_advanced(ctxOrig, CNBuffer, dictSize, p, testSize-1) );
947 CHECK( ZSTD_copyCCtx(ctxDuplicated, ctxOrig, testSize) );
949 CHECKPLUS(r, ZSTD_compressEnd(ctxDuplicated, compressedBuffer, ZSTD_compressBound(testSize),
950 (const char*)CNBuffer + dictSize, testSize),
952 { ZSTD_frameHeader zfh;
953 if (ZSTD_getFrameHeader(&zfh, compressedBuffer, cSize)) goto _output_error;
954 if ((zfh.frameContentSize != testSize) && (zfh.frameContentSize != 0)) goto _output_error;
956 DISPLAYLEVEL(3, "OK \n");
958 ZSTD_freeCCtx(ctxOrig);
959 ZSTD_freeCCtx(ctxDuplicated);
963 /* Dictionary and dictBuilder tests */
964 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
965 size_t const dictBufferCapacity = 16 KB;
966 void* dictBuffer = malloc(dictBufferCapacity);
967 size_t const totalSampleSize = 1 MB;
968 size_t const sampleUnitSize = 8 KB;
969 U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
970 size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
974 if (dictBuffer==NULL || samplesSizes==NULL) {
980 DISPLAYLEVEL(3, "test%3i : dictBuilder on cyclic data : ", testNb++);
981 assert(compressedBufferSize >= totalSampleSize);
982 { U32 u; for (u=0; u<totalSampleSize; u++) ((BYTE*)decodedBuffer)[u] = (BYTE)u; }
983 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
984 { size_t const sDictSize = ZDICT_trainFromBuffer(dictBuffer, dictBufferCapacity,
985 decodedBuffer, samplesSizes, nbSamples);
986 if (ZDICT_isError(sDictSize)) goto _output_error;
987 DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (unsigned)sDictSize);
990 DISPLAYLEVEL(3, "test%3i : dictBuilder : ", testNb++);
991 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
992 dictSize = ZDICT_trainFromBuffer(dictBuffer, dictBufferCapacity,
993 CNBuffer, samplesSizes, nbSamples);
994 if (ZDICT_isError(dictSize)) goto _output_error;
995 DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (unsigned)dictSize);
997 DISPLAYLEVEL(3, "test%3i : Multithreaded COVER dictBuilder : ", testNb++);
998 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
999 { ZDICT_cover_params_t coverParams;
1000 memset(&coverParams, 0, sizeof(coverParams));
1001 coverParams.steps = 8;
1002 coverParams.nbThreads = 4;
1003 dictSize = ZDICT_optimizeTrainFromBuffer_cover(
1004 dictBuffer, dictBufferCapacity,
1005 CNBuffer, samplesSizes, nbSamples/8, /* less samples for faster tests */
1007 if (ZDICT_isError(dictSize)) goto _output_error;
1009 DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (unsigned)dictSize);
1011 DISPLAYLEVEL(3, "test%3i : Multithreaded FASTCOVER dictBuilder : ", testNb++);
1012 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
1013 { ZDICT_fastCover_params_t fastCoverParams;
1014 memset(&fastCoverParams, 0, sizeof(fastCoverParams));
1015 fastCoverParams.steps = 8;
1016 fastCoverParams.nbThreads = 4;
1017 dictSize = ZDICT_optimizeTrainFromBuffer_fastCover(
1018 dictBuffer, dictBufferCapacity,
1019 CNBuffer, samplesSizes, nbSamples,
1021 if (ZDICT_isError(dictSize)) goto _output_error;
1023 DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (unsigned)dictSize);
1025 DISPLAYLEVEL(3, "test%3i : check dictID : ", testNb++);
1026 dictID = ZDICT_getDictID(dictBuffer, dictSize);
1027 if (dictID==0) goto _output_error;
1028 DISPLAYLEVEL(3, "OK : %u \n", (unsigned)dictID);
1030 DISPLAYLEVEL(3, "test%3i : compress with dictionary : ", testNb++);
1031 cSize = ZSTD_compress_usingDict(cctx, compressedBuffer, compressedBufferSize,
1032 CNBuffer, CNBuffSize,
1033 dictBuffer, dictSize, 4);
1034 if (ZSTD_isError(cSize)) goto _output_error;
1035 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBuffSize*100);
1037 DISPLAYLEVEL(3, "test%3i : retrieve dictID from dictionary : ", testNb++);
1038 { U32 const did = ZSTD_getDictID_fromDict(dictBuffer, dictSize);
1039 if (did != dictID) goto _output_error; /* non-conformant (content-only) dictionary */
1041 DISPLAYLEVEL(3, "OK \n");
1043 DISPLAYLEVEL(3, "test%3i : retrieve dictID from frame : ", testNb++);
1044 { U32 const did = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
1045 if (did != dictID) goto _output_error; /* non-conformant (content-only) dictionary */
1047 DISPLAYLEVEL(3, "OK \n");
1049 DISPLAYLEVEL(3, "test%3i : frame built with dictionary should be decompressible : ", testNb++);
1050 { ZSTD_DCtx* const dctx = ZSTD_createDCtx(); assert(dctx != NULL);
1051 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
1052 decodedBuffer, CNBuffSize,
1053 compressedBuffer, cSize,
1054 dictBuffer, dictSize),
1055 if (r != CNBuffSize) goto _output_error);
1056 ZSTD_freeDCtx(dctx);
1058 DISPLAYLEVEL(3, "OK \n");
1060 DISPLAYLEVEL(3, "test%3i : estimate CDict size : ", testNb++);
1061 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
1062 size_t const estimatedSize = ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byRef);
1063 DISPLAYLEVEL(3, "OK : %u \n", (unsigned)estimatedSize);
1066 DISPLAYLEVEL(3, "test%3i : compress with CDict ", testNb++);
1067 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
1068 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize,
1069 ZSTD_dlm_byRef, ZSTD_dct_auto,
1070 cParams, ZSTD_defaultCMem);
1071 DISPLAYLEVEL(3, "(size : %u) : ", (unsigned)ZSTD_sizeof_CDict(cdict));
1072 cSize = ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize,
1073 CNBuffer, CNBuffSize, cdict);
1074 ZSTD_freeCDict(cdict);
1075 if (ZSTD_isError(cSize)) goto _output_error;
1077 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBuffSize*100);
1079 DISPLAYLEVEL(3, "test%3i : retrieve dictID from frame : ", testNb++);
1080 { U32 const did = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
1081 if (did != dictID) goto _output_error; /* non-conformant (content-only) dictionary */
1083 DISPLAYLEVEL(3, "OK \n");
1085 DISPLAYLEVEL(3, "test%3i : frame built with dictionary should be decompressible : ", testNb++);
1086 { ZSTD_DCtx* const dctx = ZSTD_createDCtx(); assert(dctx != NULL);
1087 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
1088 decodedBuffer, CNBuffSize,
1089 compressedBuffer, cSize,
1090 dictBuffer, dictSize),
1091 if (r != CNBuffSize) goto _output_error);
1092 ZSTD_freeDCtx(dctx);
1094 DISPLAYLEVEL(3, "OK \n");
1096 DISPLAYLEVEL(3, "test%3i : compress with static CDict : ", testNb++);
1097 { int const maxLevel = ZSTD_maxCLevel();
1099 for (level = 1; level <= maxLevel; ++level) {
1100 ZSTD_compressionParameters const cParams = ZSTD_getCParams(level, CNBuffSize, dictSize);
1101 size_t const cdictSize = ZSTD_estimateCDictSize_advanced(dictSize, cParams, ZSTD_dlm_byCopy);
1102 void* const cdictBuffer = malloc(cdictSize);
1103 if (cdictBuffer==NULL) goto _output_error;
1104 { const ZSTD_CDict* const cdict = ZSTD_initStaticCDict(
1105 cdictBuffer, cdictSize,
1106 dictBuffer, dictSize,
1107 ZSTD_dlm_byCopy, ZSTD_dct_auto,
1109 if (cdict == NULL) {
1110 DISPLAY("ZSTD_initStaticCDict failed ");
1113 cSize = ZSTD_compress_usingCDict(cctx,
1114 compressedBuffer, compressedBufferSize,
1115 CNBuffer, MIN(10 KB, CNBuffSize), cdict);
1116 if (ZSTD_isError(cSize)) {
1117 DISPLAY("ZSTD_compress_usingCDict failed ");
1122 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBuffSize*100);
1124 DISPLAYLEVEL(3, "test%3i : ZSTD_compress_usingCDict_advanced, no contentSize, no dictID : ", testNb++);
1125 { ZSTD_frameParameters const fParams = { 0 /* frameSize */, 1 /* checksum */, 1 /* noDictID*/ };
1126 ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
1127 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize, ZSTD_dlm_byRef, ZSTD_dct_auto, cParams, ZSTD_defaultCMem);
1128 cSize = ZSTD_compress_usingCDict_advanced(cctx, compressedBuffer, compressedBufferSize,
1129 CNBuffer, CNBuffSize, cdict, fParams);
1130 ZSTD_freeCDict(cdict);
1131 if (ZSTD_isError(cSize)) goto _output_error;
1133 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBuffSize*100);
1135 DISPLAYLEVEL(3, "test%3i : try retrieving contentSize from frame : ", testNb++);
1136 { U64 const contentSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
1137 if (contentSize != ZSTD_CONTENTSIZE_UNKNOWN) goto _output_error;
1139 DISPLAYLEVEL(3, "OK (unknown)\n");
1141 DISPLAYLEVEL(3, "test%3i : frame built without dictID should be decompressible : ", testNb++);
1142 { ZSTD_DCtx* const dctx = ZSTD_createDCtx(); assert(dctx != NULL);
1143 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
1144 decodedBuffer, CNBuffSize,
1145 compressedBuffer, cSize,
1146 dictBuffer, dictSize),
1147 if (r != CNBuffSize) goto _output_error);
1148 ZSTD_freeDCtx(dctx);
1150 DISPLAYLEVEL(3, "OK \n");
1152 DISPLAYLEVEL(3, "test%3i : ZSTD_compress_advanced, no dictID : ", testNb++);
1153 { ZSTD_parameters p = ZSTD_getParams(3, CNBuffSize, dictSize);
1154 p.fParams.noDictIDFlag = 1;
1155 cSize = ZSTD_compress_advanced(cctx, compressedBuffer, compressedBufferSize,
1156 CNBuffer, CNBuffSize,
1157 dictBuffer, dictSize, p);
1158 if (ZSTD_isError(cSize)) goto _output_error;
1160 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/CNBuffSize*100);
1162 DISPLAYLEVEL(3, "test%3i : frame built without dictID should be decompressible : ", testNb++);
1163 { ZSTD_DCtx* const dctx = ZSTD_createDCtx(); assert(dctx != NULL);
1164 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
1165 decodedBuffer, CNBuffSize,
1166 compressedBuffer, cSize,
1167 dictBuffer, dictSize),
1168 if (r != CNBuffSize) goto _output_error);
1169 ZSTD_freeDCtx(dctx);
1171 DISPLAYLEVEL(3, "OK \n");
1173 DISPLAYLEVEL(3, "test%3i : dictionary containing only header should return error : ", testNb++);
1174 { ZSTD_DCtx* const dctx = ZSTD_createDCtx();
1175 assert(dctx != NULL);
1176 { const size_t ret = ZSTD_decompress_usingDict(
1177 dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize,
1178 "\x37\xa4\x30\xec\x11\x22\x33\x44", 8);
1179 if (ZSTD_getErrorCode(ret) != ZSTD_error_dictionary_corrupted)
1182 ZSTD_freeDCtx(dctx);
1184 DISPLAYLEVEL(3, "OK \n");
1186 DISPLAYLEVEL(3, "test%3i : Building cdict w/ ZSTD_dm_fullDict on a good dictionary : ", testNb++);
1187 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
1188 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize, ZSTD_dlm_byRef, ZSTD_dct_fullDict, cParams, ZSTD_defaultCMem);
1189 if (cdict==NULL) goto _output_error;
1190 ZSTD_freeCDict(cdict);
1192 DISPLAYLEVEL(3, "OK \n");
1194 DISPLAYLEVEL(3, "test%3i : Building cdict w/ ZSTD_dm_fullDict on a rawContent (must fail) : ", testNb++);
1195 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
1196 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced((const char*)dictBuffer+1, dictSize-1, ZSTD_dlm_byRef, ZSTD_dct_fullDict, cParams, ZSTD_defaultCMem);
1197 if (cdict!=NULL) goto _output_error;
1198 ZSTD_freeCDict(cdict);
1200 DISPLAYLEVEL(3, "OK \n");
1202 DISPLAYLEVEL(3, "test%3i : Loading rawContent starting with dict header w/ ZSTD_dm_auto should fail : ", testNb++);
1205 MEM_writeLE32((char*)dictBuffer+2, ZSTD_MAGIC_DICTIONARY);
1206 ret = ZSTD_CCtx_loadDictionary_advanced(
1207 cctx, (const char*)dictBuffer+2, dictSize-2, ZSTD_dlm_byRef, ZSTD_dct_auto);
1208 if (!ZSTD_isError(ret)) goto _output_error;
1210 DISPLAYLEVEL(3, "OK \n");
1212 DISPLAYLEVEL(3, "test%3i : Loading rawContent starting with dict header w/ ZSTD_dm_rawContent should pass : ", testNb++);
1215 MEM_writeLE32((char*)dictBuffer+2, ZSTD_MAGIC_DICTIONARY);
1216 ret = ZSTD_CCtx_loadDictionary_advanced(
1217 cctx, (const char*)dictBuffer+2, dictSize-2, ZSTD_dlm_byRef, ZSTD_dct_rawContent);
1218 if (ZSTD_isError(ret)) goto _output_error;
1220 DISPLAYLEVEL(3, "OK \n");
1222 DISPLAYLEVEL(3, "test%3i : Dictionary with non-default repcodes : ", testNb++);
1223 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
1224 dictSize = ZDICT_trainFromBuffer(dictBuffer, dictSize,
1225 CNBuffer, samplesSizes, nbSamples);
1226 if (ZDICT_isError(dictSize)) goto _output_error;
1227 /* Set all the repcodes to non-default */
1229 BYTE* dictPtr = (BYTE*)dictBuffer;
1230 BYTE* dictLimit = dictPtr + dictSize - 12;
1231 /* Find the repcodes */
1232 while (dictPtr < dictLimit &&
1233 (MEM_readLE32(dictPtr) != 1 || MEM_readLE32(dictPtr + 4) != 4 ||
1234 MEM_readLE32(dictPtr + 8) != 8)) {
1237 if (dictPtr >= dictLimit) goto _output_error;
1238 MEM_writeLE32(dictPtr + 0, 10);
1239 MEM_writeLE32(dictPtr + 4, 10);
1240 MEM_writeLE32(dictPtr + 8, 10);
1241 /* Set the last 8 bytes to 'x' */
1242 memset((BYTE*)dictBuffer + dictSize - 8, 'x', 8);
1244 /* The optimal parser checks all the repcodes.
1245 * Make sure at least one is a match >= targetLength so that it is
1246 * immediately chosen. This will make sure that the compressor and
1247 * decompressor agree on at least one of the repcodes.
1251 ZSTD_DCtx* const dctx = ZSTD_createDCtx();
1252 ZSTD_compressionParameters const cParams = ZSTD_getCParams(19, CNBuffSize, dictSize);
1253 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize,
1254 ZSTD_dlm_byRef, ZSTD_dct_auto,
1255 cParams, ZSTD_defaultCMem);
1256 assert(dctx != NULL); assert(cdict != NULL);
1257 memset(data, 'x', sizeof(data));
1258 cSize = ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize,
1259 data, sizeof(data), cdict);
1260 ZSTD_freeCDict(cdict);
1261 if (ZSTD_isError(cSize)) { DISPLAYLEVEL(5, "Compression error %s : ", ZSTD_getErrorName(cSize)); goto _output_error; }
1262 dSize = ZSTD_decompress_usingDict(dctx, decodedBuffer, sizeof(data), compressedBuffer, cSize, dictBuffer, dictSize);
1263 if (ZSTD_isError(dSize)) { DISPLAYLEVEL(5, "Decompression error %s : ", ZSTD_getErrorName(dSize)); goto _output_error; }
1264 if (memcmp(data, decodedBuffer, sizeof(data))) { DISPLAYLEVEL(5, "Data corruption : "); goto _output_error; }
1265 ZSTD_freeDCtx(dctx);
1267 DISPLAYLEVEL(3, "OK \n");
1269 ZSTD_freeCCtx(cctx);
1274 /* COVER dictionary builder tests */
1275 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1276 size_t dictSize = 16 KB;
1277 size_t optDictSize = dictSize;
1278 void* dictBuffer = malloc(dictSize);
1279 size_t const totalSampleSize = 1 MB;
1280 size_t const sampleUnitSize = 8 KB;
1281 U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
1282 size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
1283 ZDICT_cover_params_t params;
1286 if (dictBuffer==NULL || samplesSizes==NULL) {
1292 DISPLAYLEVEL(3, "test%3i : ZDICT_trainFromBuffer_cover : ", testNb++);
1293 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
1294 memset(¶ms, 0, sizeof(params));
1295 params.d = 1 + (FUZ_rand(&seed) % 16);
1296 params.k = params.d + (FUZ_rand(&seed) % 256);
1297 dictSize = ZDICT_trainFromBuffer_cover(dictBuffer, dictSize,
1298 CNBuffer, samplesSizes, nbSamples,
1300 if (ZDICT_isError(dictSize)) goto _output_error;
1301 DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (unsigned)dictSize);
1303 DISPLAYLEVEL(3, "test%3i : check dictID : ", testNb++);
1304 dictID = ZDICT_getDictID(dictBuffer, dictSize);
1305 if (dictID==0) goto _output_error;
1306 DISPLAYLEVEL(3, "OK : %u \n", (unsigned)dictID);
1308 DISPLAYLEVEL(3, "test%3i : ZDICT_optimizeTrainFromBuffer_cover : ", testNb++);
1309 memset(¶ms, 0, sizeof(params));
1311 optDictSize = ZDICT_optimizeTrainFromBuffer_cover(dictBuffer, optDictSize,
1312 CNBuffer, samplesSizes,
1313 nbSamples / 4, ¶ms);
1314 if (ZDICT_isError(optDictSize)) goto _output_error;
1315 DISPLAYLEVEL(3, "OK, created dictionary of size %u \n", (unsigned)optDictSize);
1317 DISPLAYLEVEL(3, "test%3i : check dictID : ", testNb++);
1318 dictID = ZDICT_getDictID(dictBuffer, optDictSize);
1319 if (dictID==0) goto _output_error;
1320 DISPLAYLEVEL(3, "OK : %u \n", (unsigned)dictID);
1322 ZSTD_freeCCtx(cctx);
1327 /* Decompression defense tests */
1328 DISPLAYLEVEL(3, "test%3i : Check input length for magic number : ", testNb++);
1329 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, CNBuffer, 3); /* too small input */
1330 if (!ZSTD_isError(r)) goto _output_error;
1331 if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
1332 DISPLAYLEVEL(3, "OK \n");
1334 DISPLAYLEVEL(3, "test%3i : Check magic Number : ", testNb++);
1335 ((char*)(CNBuffer))[0] = 1;
1336 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, CNBuffer, 4);
1337 if (!ZSTD_isError(r)) goto _output_error; }
1338 DISPLAYLEVEL(3, "OK \n");
1340 /* content size verification test */
1341 DISPLAYLEVEL(3, "test%3i : Content size verification : ", testNb++);
1342 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1343 size_t const srcSize = 5000;
1344 size_t const wrongSrcSize = (srcSize + 1000);
1345 ZSTD_parameters params = ZSTD_getParams(1, wrongSrcSize, 0);
1346 params.fParams.contentSizeFlag = 1;
1347 CHECK( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, wrongSrcSize) );
1348 { size_t const result = ZSTD_compressEnd(cctx, decodedBuffer, CNBuffSize, CNBuffer, srcSize);
1349 if (!ZSTD_isError(result)) goto _output_error;
1350 if (ZSTD_getErrorCode(result) != ZSTD_error_srcSize_wrong) goto _output_error;
1351 DISPLAYLEVEL(3, "OK : %s \n", ZSTD_getErrorName(result));
1353 ZSTD_freeCCtx(cctx);
1356 /* negative compression level test : ensure simple API and advanced API produce same result */
1357 DISPLAYLEVEL(3, "test%3i : negative compression level : ", testNb++);
1358 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1359 size_t const srcSize = CNBuffSize / 5;
1360 int const compressionLevel = -1;
1362 assert(cctx != NULL);
1363 { ZSTD_parameters const params = ZSTD_getParams(compressionLevel, srcSize, 0);
1364 size_t const cSize_1pass = ZSTD_compress_advanced(cctx,
1365 compressedBuffer, compressedBufferSize,
1369 if (ZSTD_isError(cSize_1pass)) goto _output_error;
1371 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, compressionLevel) );
1372 { size_t const compressionResult = ZSTD_compress2(cctx,
1373 compressedBuffer, compressedBufferSize,
1375 DISPLAYLEVEL(5, "simple=%zu vs %zu=advanced : ", cSize_1pass, compressionResult);
1376 if (ZSTD_isError(compressionResult)) goto _output_error;
1377 if (compressionResult != cSize_1pass) goto _output_error;
1379 ZSTD_freeCCtx(cctx);
1381 DISPLAYLEVEL(3, "OK \n");
1383 /* parameters order test */
1384 { size_t const inputSize = CNBuffSize / 2;
1387 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1388 DISPLAYLEVEL(3, "test%3i : parameters in order : ", testNb++);
1389 assert(cctx != NULL);
1390 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, 2) );
1391 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_enableLongDistanceMatching, 1) );
1392 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, 18) );
1393 { size_t const compressedSize = ZSTD_compress2(cctx,
1394 compressedBuffer, ZSTD_compressBound(inputSize),
1395 CNBuffer, inputSize);
1396 CHECK(compressedSize);
1397 cSize = compressedSize;
1398 xxh64 = XXH64(compressedBuffer, compressedSize, 0);
1400 DISPLAYLEVEL(3, "OK (compress : %u -> %u bytes)\n", (unsigned)inputSize, (unsigned)cSize);
1401 ZSTD_freeCCtx(cctx);
1404 { ZSTD_CCtx* cctx = ZSTD_createCCtx();
1405 DISPLAYLEVEL(3, "test%3i : parameters disordered : ", testNb++);
1406 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_windowLog, 18) );
1407 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_enableLongDistanceMatching, 1) );
1408 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel, 2) );
1409 { size_t const result = ZSTD_compress2(cctx,
1410 compressedBuffer, ZSTD_compressBound(inputSize),
1411 CNBuffer, inputSize);
1413 if (result != cSize) goto _output_error; /* must result in same compressed result, hence same size */
1414 if (XXH64(compressedBuffer, result, 0) != xxh64) goto _output_error; /* must result in exactly same content, hence same hash */
1415 DISPLAYLEVEL(3, "OK (compress : %u -> %u bytes)\n", (unsigned)inputSize, (unsigned)result);
1417 ZSTD_freeCCtx(cctx);
1421 /* advanced parameters for decompression */
1422 { ZSTD_DCtx* const dctx = ZSTD_createDCtx();
1423 assert(dctx != NULL);
1425 DISPLAYLEVEL(3, "test%3i : get dParameter bounds ", testNb++);
1426 { ZSTD_bounds const bounds = ZSTD_dParam_getBounds(ZSTD_d_windowLogMax);
1427 CHECK(bounds.error);
1429 DISPLAYLEVEL(3, "OK \n");
1431 DISPLAYLEVEL(3, "test%3i : wrong dParameter : ", testNb++);
1432 { size_t const sr = ZSTD_DCtx_setParameter(dctx, (ZSTD_dParameter)999999, 0);
1433 if (!ZSTD_isError(sr)) goto _output_error;
1435 { ZSTD_bounds const bounds = ZSTD_dParam_getBounds((ZSTD_dParameter)999998);
1436 if (!ZSTD_isError(bounds.error)) goto _output_error;
1438 DISPLAYLEVEL(3, "OK \n");
1440 DISPLAYLEVEL(3, "test%3i : out of bound dParameter : ", testNb++);
1441 { size_t const sr = ZSTD_DCtx_setParameter(dctx, ZSTD_d_windowLogMax, 9999);
1442 if (!ZSTD_isError(sr)) goto _output_error;
1444 { size_t const sr = ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, (ZSTD_format_e)888);
1445 if (!ZSTD_isError(sr)) goto _output_error;
1447 DISPLAYLEVEL(3, "OK \n");
1449 ZSTD_freeDCtx(dctx);
1453 /* custom formats tests */
1454 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1455 ZSTD_DCtx* const dctx = ZSTD_createDCtx();
1456 size_t const inputSize = CNBuffSize / 2; /* won't cause pb with small dict size */
1457 assert(dctx != NULL); assert(cctx != NULL);
1459 /* basic block compression */
1460 DISPLAYLEVEL(3, "test%3i : magic-less format test : ", testNb++);
1461 CHECK( ZSTD_CCtx_setParameter(cctx, ZSTD_c_format, ZSTD_f_zstd1_magicless) );
1462 { ZSTD_inBuffer in = { CNBuffer, inputSize, 0 };
1463 ZSTD_outBuffer out = { compressedBuffer, ZSTD_compressBound(inputSize), 0 };
1464 size_t const result = ZSTD_compressStream2(cctx, &out, &in, ZSTD_e_end);
1465 if (result != 0) goto _output_error;
1466 if (in.pos != in.size) goto _output_error;
1469 DISPLAYLEVEL(3, "OK (compress : %u -> %u bytes)\n", (unsigned)inputSize, (unsigned)cSize);
1471 DISPLAYLEVEL(3, "test%3i : decompress normally (should fail) : ", testNb++);
1472 { size_t const decodeResult = ZSTD_decompressDCtx(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize);
1473 if (ZSTD_getErrorCode(decodeResult) != ZSTD_error_prefix_unknown) goto _output_error;
1474 DISPLAYLEVEL(3, "OK : %s \n", ZSTD_getErrorName(decodeResult));
1477 DISPLAYLEVEL(3, "test%3i : decompress of magic-less frame : ", testNb++);
1478 ZSTD_DCtx_reset(dctx, ZSTD_reset_session_and_parameters);
1479 CHECK( ZSTD_DCtx_setParameter(dctx, ZSTD_d_format, ZSTD_f_zstd1_magicless) );
1480 { ZSTD_frameHeader zfh;
1481 size_t const zfhrt = ZSTD_getFrameHeader_advanced(&zfh, compressedBuffer, cSize, ZSTD_f_zstd1_magicless);
1482 if (zfhrt != 0) goto _output_error;
1485 { size_t const result = ZSTD_decompressDCtx(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize);
1486 if (result != inputSize) goto _output_error;
1487 DISPLAYLEVEL(3, "one-shot OK, ");
1490 { ZSTD_inBuffer in = { compressedBuffer, cSize, 0 };
1491 ZSTD_outBuffer out = { decodedBuffer, CNBuffSize, 0 };
1492 size_t const result = ZSTD_decompressStream(dctx, &out, &in);
1493 if (result != 0) goto _output_error;
1494 if (in.pos != in.size) goto _output_error;
1495 if (out.pos != inputSize) goto _output_error;
1496 DISPLAYLEVEL(3, "streaming OK : regenerated %u bytes \n", (unsigned)out.pos);
1499 ZSTD_freeCCtx(cctx);
1500 ZSTD_freeDCtx(dctx);
1503 /* block API tests */
1504 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1505 ZSTD_DCtx* const dctx = ZSTD_createDCtx();
1506 static const size_t dictSize = 65 KB;
1507 static const size_t blockSize = 100 KB; /* won't cause pb with small dict size */
1509 assert(cctx != NULL); assert(dctx != NULL);
1511 /* basic block compression */
1512 DISPLAYLEVEL(3, "test%3i : Block compression test : ", testNb++);
1513 CHECK( ZSTD_compressBegin(cctx, 5) );
1514 CHECK( ZSTD_getBlockSize(cctx) >= blockSize);
1515 cSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), CNBuffer, blockSize);
1516 if (ZSTD_isError(cSize)) goto _output_error;
1517 DISPLAYLEVEL(3, "OK \n");
1519 DISPLAYLEVEL(3, "test%3i : Block decompression test : ", testNb++);
1520 CHECK( ZSTD_decompressBegin(dctx) );
1521 { CHECK_V(r, ZSTD_decompressBlock(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
1522 if (r != blockSize) goto _output_error; }
1523 DISPLAYLEVEL(3, "OK \n");
1525 /* very long stream of block compression */
1526 DISPLAYLEVEL(3, "test%3i : Huge block streaming compression test : ", testNb++);
1527 CHECK( ZSTD_compressBegin(cctx, -199) ); /* we just want to quickly overflow internal U32 index */
1528 CHECK( ZSTD_getBlockSize(cctx) >= blockSize);
1529 { U64 const toCompress = 5000000000ULL; /* > 4 GB */
1531 while (compressed < toCompress) {
1532 size_t const blockCSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), CNBuffer, blockSize);
1533 assert(blockCSize != 0);
1534 if (ZSTD_isError(blockCSize)) goto _output_error;
1535 compressed += blockCSize;
1538 DISPLAYLEVEL(3, "OK \n");
1540 /* dictionary block compression */
1541 DISPLAYLEVEL(3, "test%3i : Dictionary Block compression test : ", testNb++);
1542 CHECK( ZSTD_compressBegin_usingDict(cctx, CNBuffer, dictSize, 5) );
1543 cSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize, blockSize);
1544 if (ZSTD_isError(cSize)) goto _output_error;
1545 cSize2 = ZSTD_compressBlock(cctx, (char*)compressedBuffer+cSize, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize+blockSize, blockSize);
1546 if (ZSTD_isError(cSize2)) goto _output_error;
1547 memcpy((char*)compressedBuffer+cSize, (char*)CNBuffer+dictSize+blockSize, blockSize); /* fake non-compressed block */
1548 cSize2 = ZSTD_compressBlock(cctx, (char*)compressedBuffer+cSize+blockSize, ZSTD_compressBound(blockSize),
1549 (char*)CNBuffer+dictSize+2*blockSize, blockSize);
1550 if (ZSTD_isError(cSize2)) goto _output_error;
1551 DISPLAYLEVEL(3, "OK \n");
1553 DISPLAYLEVEL(3, "test%3i : Dictionary Block decompression test : ", testNb++);
1554 CHECK( ZSTD_decompressBegin_usingDict(dctx, CNBuffer, dictSize) );
1555 { CHECK_V( r, ZSTD_decompressBlock(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
1556 if (r != blockSize) goto _output_error; }
1557 ZSTD_insertBlock(dctx, (char*)decodedBuffer+blockSize, blockSize); /* insert non-compressed block into dctx history */
1558 { CHECK_V( r, ZSTD_decompressBlock(dctx, (char*)decodedBuffer+2*blockSize, CNBuffSize, (char*)compressedBuffer+cSize+blockSize, cSize2) );
1559 if (r != blockSize) goto _output_error; }
1560 DISPLAYLEVEL(3, "OK \n");
1562 DISPLAYLEVEL(3, "test%3i : Block compression with CDict : ", testNb++);
1563 { ZSTD_CDict* const cdict = ZSTD_createCDict(CNBuffer, dictSize, 3);
1564 if (cdict==NULL) goto _output_error;
1565 CHECK( ZSTD_compressBegin_usingCDict(cctx, cdict) );
1566 CHECK( ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize, blockSize) );
1567 ZSTD_freeCDict(cdict);
1569 DISPLAYLEVEL(3, "OK \n");
1571 ZSTD_freeCCtx(cctx);
1572 ZSTD_freeDCtx(dctx);
1576 { size_t sampleSize = 0;
1577 DISPLAYLEVEL(3, "test%3i : Long RLE test : ", testNb++);
1578 RDG_genBuffer(CNBuffer, sampleSize, compressibility, 0., seed+1);
1579 memset((char*)CNBuffer+sampleSize, 'B', 256 KB - 1);
1580 sampleSize += 256 KB - 1;
1581 RDG_genBuffer((char*)CNBuffer+sampleSize, 96 KB, compressibility, 0., seed+2);
1582 sampleSize += 96 KB;
1583 cSize = ZSTD_compress(compressedBuffer, ZSTD_compressBound(sampleSize), CNBuffer, sampleSize, 1);
1584 if (ZSTD_isError(cSize)) goto _output_error;
1585 { CHECK_V(regenSize, ZSTD_decompress(decodedBuffer, sampleSize, compressedBuffer, cSize));
1586 if (regenSize!=sampleSize) goto _output_error; }
1587 DISPLAYLEVEL(3, "OK \n");
1590 /* All zeroes test (test bug #137) */
1591 #define ZEROESLENGTH 100
1592 DISPLAYLEVEL(3, "test%3i : compress %u zeroes : ", testNb++, ZEROESLENGTH);
1593 memset(CNBuffer, 0, ZEROESLENGTH);
1594 { CHECK_V(r, ZSTD_compress(compressedBuffer, ZSTD_compressBound(ZEROESLENGTH), CNBuffer, ZEROESLENGTH, 1) );
1596 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/ZEROESLENGTH*100);
1598 DISPLAYLEVEL(3, "test%3i : decompress %u zeroes : ", testNb++, ZEROESLENGTH);
1599 { CHECK_V(r, ZSTD_decompress(decodedBuffer, ZEROESLENGTH, compressedBuffer, cSize) );
1600 if (r != ZEROESLENGTH) goto _output_error; }
1601 DISPLAYLEVEL(3, "OK \n");
1603 /* nbSeq limit test */
1604 #define _3BYTESTESTLENGTH 131000
1605 #define NB3BYTESSEQLOG 9
1606 #define NB3BYTESSEQ (1 << NB3BYTESSEQLOG)
1607 #define NB3BYTESSEQMASK (NB3BYTESSEQ-1)
1608 /* creates a buffer full of 3-bytes sequences */
1609 { BYTE _3BytesSeqs[NB3BYTESSEQ][3];
1612 /* create batch of 3-bytes sequences */
1614 for (i=0; i < NB3BYTESSEQ; i++) {
1615 _3BytesSeqs[i][0] = (BYTE)(FUZ_rand(&rSeed) & 255);
1616 _3BytesSeqs[i][1] = (BYTE)(FUZ_rand(&rSeed) & 255);
1617 _3BytesSeqs[i][2] = (BYTE)(FUZ_rand(&rSeed) & 255);
1620 /* randomly fills CNBuffer with prepared 3-bytes sequences */
1622 for (i=0; i < _3BYTESTESTLENGTH; i += 3) { /* note : CNBuffer size > _3BYTESTESTLENGTH+3 */
1623 U32 const id = FUZ_rand(&rSeed) & NB3BYTESSEQMASK;
1624 ((BYTE*)CNBuffer)[i+0] = _3BytesSeqs[id][0];
1625 ((BYTE*)CNBuffer)[i+1] = _3BytesSeqs[id][1];
1626 ((BYTE*)CNBuffer)[i+2] = _3BytesSeqs[id][2];
1628 DISPLAYLEVEL(3, "test%3i : growing nbSeq : ", testNb++);
1629 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1630 size_t const maxNbSeq = _3BYTESTESTLENGTH / 3;
1631 size_t const bound = ZSTD_compressBound(_3BYTESTESTLENGTH);
1633 while (nbSeq <= maxNbSeq) {
1634 CHECK(ZSTD_compressCCtx(cctx, compressedBuffer, bound, CNBuffer, nbSeq * 3, 19));
1635 /* Check every sequence for the first 100, then skip more rapidly. */
1639 nbSeq += (nbSeq >> 2);
1642 ZSTD_freeCCtx(cctx);
1644 DISPLAYLEVEL(3, "OK \n");
1646 DISPLAYLEVEL(3, "test%3i : compress lots 3-bytes sequences : ", testNb++);
1647 { CHECK_V(r, ZSTD_compress(compressedBuffer, ZSTD_compressBound(_3BYTESTESTLENGTH),
1648 CNBuffer, _3BYTESTESTLENGTH, 19) );
1650 DISPLAYLEVEL(3, "OK (%u bytes : %.2f%%)\n", (unsigned)cSize, (double)cSize/_3BYTESTESTLENGTH*100);
1652 DISPLAYLEVEL(3, "test%3i : decompress lots 3-bytes sequence : ", testNb++);
1653 { CHECK_V(r, ZSTD_decompress(decodedBuffer, _3BYTESTESTLENGTH, compressedBuffer, cSize) );
1654 if (r != _3BYTESTESTLENGTH) goto _output_error; }
1655 DISPLAYLEVEL(3, "OK \n");
1658 DISPLAYLEVEL(3, "test%3i : growing literals buffer : ", testNb++);
1659 RDG_genBuffer(CNBuffer, CNBuffSize, 0.0, 0.1, seed);
1660 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1661 size_t const bound = ZSTD_compressBound(CNBuffSize);
1663 while (size <= CNBuffSize) {
1664 CHECK(ZSTD_compressCCtx(cctx, compressedBuffer, bound, CNBuffer, size, 3));
1665 /* Check every size for the first 100, then skip more rapidly. */
1669 size += (size >> 2);
1672 ZSTD_freeCCtx(cctx);
1674 DISPLAYLEVEL(3, "OK \n");
1676 DISPLAYLEVEL(3, "test%3i : incompressible data and ill suited dictionary : ", testNb++);
1677 { /* Train a dictionary on low characters */
1678 size_t dictSize = 16 KB;
1679 void* const dictBuffer = malloc(dictSize);
1680 size_t const totalSampleSize = 1 MB;
1681 size_t const sampleUnitSize = 8 KB;
1682 U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
1683 size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
1684 if (!dictBuffer || !samplesSizes) goto _output_error;
1685 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
1686 dictSize = ZDICT_trainFromBuffer(dictBuffer, dictSize, CNBuffer, samplesSizes, nbSamples);
1687 if (ZDICT_isError(dictSize)) goto _output_error;
1688 /* Reverse the characters to make the dictionary ill suited */
1690 for (u = 0; u < CNBuffSize; ++u) {
1691 ((BYTE*)CNBuffer)[u] = 255 - ((BYTE*)CNBuffer)[u];
1694 { /* Compress the data */
1695 size_t const inputSize = 500;
1696 size_t const outputSize = ZSTD_compressBound(inputSize);
1697 void* const outputBuffer = malloc(outputSize);
1698 ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1699 if (!outputBuffer || !cctx) goto _output_error;
1700 CHECK(ZSTD_compress_usingDict(cctx, outputBuffer, outputSize, CNBuffer, inputSize, dictBuffer, dictSize, 1));
1702 ZSTD_freeCCtx(cctx);
1708 DISPLAYLEVEL(3, "OK \n");
1711 /* findFrameCompressedSize on skippable frames */
1712 DISPLAYLEVEL(3, "test%3i : frame compressed size of skippable frame : ", testNb++);
1713 { const char* frame = "\x50\x2a\x4d\x18\x05\x0\x0\0abcde";
1714 size_t const frameSrcSize = 13;
1715 if (ZSTD_findFrameCompressedSize(frame, frameSrcSize) != frameSrcSize) goto _output_error; }
1716 DISPLAYLEVEL(3, "OK \n");
1718 /* error string tests */
1719 DISPLAYLEVEL(3, "test%3i : testing ZSTD error code strings : ", testNb++);
1720 if (strcmp("No error detected", ZSTD_getErrorName((ZSTD_ErrorCode)(0-ZSTD_error_no_error))) != 0) goto _output_error;
1721 if (strcmp("No error detected", ZSTD_getErrorString(ZSTD_error_no_error)) != 0) goto _output_error;
1722 if (strcmp("Unspecified error code", ZSTD_getErrorString((ZSTD_ErrorCode)(0-ZSTD_error_GENERIC))) != 0) goto _output_error;
1723 if (strcmp("Error (generic)", ZSTD_getErrorName((size_t)0-ZSTD_error_GENERIC)) != 0) goto _output_error;
1724 if (strcmp("Error (generic)", ZSTD_getErrorString(ZSTD_error_GENERIC)) != 0) goto _output_error;
1725 if (strcmp("No error detected", ZSTD_getErrorName(ZSTD_error_GENERIC)) != 0) goto _output_error;
1726 DISPLAYLEVEL(3, "OK \n");
1728 DISPLAYLEVEL(3, "test%3i : testing ZSTD dictionary sizes : ", testNb++);
1729 RDG_genBuffer(CNBuffer, CNBuffSize, compressibility, 0., seed);
1731 size_t const size = MIN(128 KB, CNBuffSize);
1732 ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1733 ZSTD_CDict* const lgCDict = ZSTD_createCDict(CNBuffer, size, 1);
1734 ZSTD_CDict* const smCDict = ZSTD_createCDict(CNBuffer, 1 KB, 1);
1735 ZSTD_frameHeader lgHeader;
1736 ZSTD_frameHeader smHeader;
1738 CHECK_Z(ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize, CNBuffer, size, lgCDict));
1739 CHECK_Z(ZSTD_getFrameHeader(&lgHeader, compressedBuffer, compressedBufferSize));
1740 CHECK_Z(ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize, CNBuffer, size, smCDict));
1741 CHECK_Z(ZSTD_getFrameHeader(&smHeader, compressedBuffer, compressedBufferSize));
1743 if (lgHeader.windowSize != smHeader.windowSize) goto _output_error;
1745 ZSTD_freeCDict(smCDict);
1746 ZSTD_freeCDict(lgCDict);
1747 ZSTD_freeCCtx(cctx);
1749 DISPLAYLEVEL(3, "OK \n");
1751 DISPLAYLEVEL(3, "test%3i : testing FSE_normalizeCount() PR#1255: ", testNb++);
1755 unsigned const tableLog = 5;
1756 size_t const nbSeq = 32;
1757 unsigned const maxSymbolValue = 31;
1760 for (i = 0; i < 32; ++i)
1762 /* Calling FSE_normalizeCount() on a uniform distribution should not
1763 * cause a division by zero.
1765 FSE_normalizeCount(norm, tableLog, count, nbSeq, maxSymbolValue);
1767 DISPLAYLEVEL(3, "OK \n");
1771 free(compressedBuffer);
1772 free(decodedBuffer);
1777 DISPLAY("Error detected in Unit tests ! \n");
1782 static size_t findDiff(const void* buf1, const void* buf2, size_t max)
1784 const BYTE* b1 = (const BYTE*)buf1;
1785 const BYTE* b2 = (const BYTE*)buf2;
1787 for (u=0; u<max; u++) {
1788 if (b1[u] != b2[u]) break;
1794 static ZSTD_parameters FUZ_makeParams(ZSTD_compressionParameters cParams, ZSTD_frameParameters fParams)
1796 ZSTD_parameters params;
1797 params.cParams = cParams;
1798 params.fParams = fParams;
1802 static size_t FUZ_rLogLength(U32* seed, U32 logLength)
1804 size_t const lengthMask = ((size_t)1 << logLength) - 1;
1805 return (lengthMask+1) + (FUZ_rand(seed) & lengthMask);
1808 static size_t FUZ_randomLength(U32* seed, U32 maxLog)
1810 U32 const logLength = FUZ_rand(seed) % maxLog;
1811 return FUZ_rLogLength(seed, logLength);
1815 #define CHECK(cond, ...) { \
1817 DISPLAY("Error => "); \
1818 DISPLAY(__VA_ARGS__); \
1819 DISPLAY(" (seed %u, test nb %u) \n", (unsigned)seed, testNb); \
1820 goto _output_error; \
1824 #define CHECK_Z(f) { \
1825 size_t const err = f; \
1826 if (ZSTD_isError(err)) { \
1827 DISPLAY("Error => %s : %s ", \
1828 #f, ZSTD_getErrorName(err)); \
1829 DISPLAY(" (seed %u, test nb %u) \n", (unsigned)seed, testNb); \
1830 goto _output_error; \
1834 static int fuzzerTests(U32 seed, unsigned nbTests, unsigned startTest, U32 const maxDurationS, double compressibility, int bigTests)
1836 static const U32 maxSrcLog = 23;
1837 static const U32 maxSampleLog = 22;
1838 size_t const srcBufferSize = (size_t)1<<maxSrcLog;
1839 size_t const dstBufferSize = (size_t)1<<maxSampleLog;
1840 size_t const cBufferSize = ZSTD_compressBound(dstBufferSize);
1841 BYTE* cNoiseBuffer[5];
1842 BYTE* const cBuffer = (BYTE*) malloc (cBufferSize);
1843 BYTE* const dstBuffer = (BYTE*) malloc (dstBufferSize);
1844 BYTE* const mirrorBuffer = (BYTE*) malloc (dstBufferSize);
1845 ZSTD_CCtx* const refCtx = ZSTD_createCCtx();
1846 ZSTD_CCtx* const ctx = ZSTD_createCCtx();
1847 ZSTD_DCtx* const dctx = ZSTD_createDCtx();
1849 unsigned testNb = 0;
1850 U32 coreSeed = seed;
1851 UTIL_time_t const startClock = UTIL_getTime();
1852 U64 const maxClockSpan = maxDurationS * SEC_TO_MICRO;
1853 int const cLevelLimiter = bigTests ? 3 : 2;
1856 cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
1857 cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
1858 cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
1859 cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
1860 cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
1861 CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4]
1862 || !dstBuffer || !mirrorBuffer || !cBuffer || !refCtx || !ctx || !dctx,
1863 "Not enough memory, fuzzer tests cancelled");
1865 /* Create initial samples */
1866 RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed); /* pure noise */
1867 RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed); /* barely compressible */
1868 RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
1869 RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed); /* highly compressible */
1870 RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed); /* sparse content */
1872 /* catch up testNb */
1873 for (testNb=1; testNb < startTest; testNb++) FUZ_rand(&coreSeed);
1875 /* main test loop */
1876 for ( ; (testNb <= nbTests) || (UTIL_clockSpanMicro(startClock) < maxClockSpan); testNb++ ) {
1877 BYTE* srcBuffer; /* jumping pointer */
1879 size_t sampleSize, maxTestSize, totalTestSize;
1880 size_t cSize, totalCSize, totalGenSize;
1887 if (nbTests >= testNb) { DISPLAYUPDATE(2, "\r%6u/%6u ", testNb, nbTests); }
1888 else { DISPLAYUPDATE(2, "\r%6u ", testNb); }
1890 FUZ_rand(&coreSeed);
1891 { U32 const prime1 = 2654435761U; lseed = coreSeed ^ prime1; }
1893 /* srcBuffer selection [0-4] */
1894 { U32 buffNb = FUZ_rand(&lseed) & 0x7F;
1895 if (buffNb & 7) buffNb=2; /* most common : compressible (P) */
1899 const U32 tnb[2] = { 1, 3 }; /* barely/highly compressible */
1900 buffNb = tnb[buffNb >> 3];
1902 const U32 tnb[2] = { 0, 4 }; /* not compressible / sparse */
1903 buffNb = tnb[buffNb >> 3];
1905 srcBuffer = cNoiseBuffer[buffNb];
1908 /* select src segment */
1909 sampleSize = FUZ_randomLength(&lseed, maxSampleLog);
1911 /* create sample buffer (to catch read error with valgrind & sanitizers) */
1912 sampleBuffer = (BYTE*)malloc(sampleSize);
1913 CHECK(sampleBuffer==NULL, "not enough memory for sample buffer");
1914 { size_t const sampleStart = FUZ_rand(&lseed) % (srcBufferSize - sampleSize);
1915 memcpy(sampleBuffer, srcBuffer + sampleStart, sampleSize); }
1916 crcOrig = XXH64(sampleBuffer, sampleSize, 0);
1918 /* compression tests */
1919 { int const cLevelPositive =
1920 ( FUZ_rand(&lseed) %
1921 (ZSTD_maxCLevel() - (FUZ_highbit32((U32)sampleSize) / cLevelLimiter)) )
1923 int const cLevel = ((FUZ_rand(&lseed) & 15) == 3) ?
1924 - (int)((FUZ_rand(&lseed) & 7) + 1) : /* test negative cLevel */
1926 DISPLAYLEVEL(5, "fuzzer t%u: Simple compression test (level %i) \n", testNb, cLevel);
1927 cSize = ZSTD_compressCCtx(ctx, cBuffer, cBufferSize, sampleBuffer, sampleSize, cLevel);
1928 CHECK(ZSTD_isError(cSize), "ZSTD_compressCCtx failed : %s", ZSTD_getErrorName(cSize));
1930 /* compression failure test : too small dest buffer */
1932 { const size_t missing = (FUZ_rand(&lseed) % (cSize-2)) + 1;
1933 const size_t tooSmallSize = cSize - missing;
1934 const unsigned endMark = 0x4DC2B1A9;
1935 memcpy(dstBuffer+tooSmallSize, &endMark, sizeof(endMark));
1936 DISPLAYLEVEL(5, "fuzzer t%u: compress into too small buffer of size %u (missing %u bytes) \n",
1937 testNb, (unsigned)tooSmallSize, (unsigned)missing);
1938 { size_t const errorCode = ZSTD_compressCCtx(ctx, dstBuffer, tooSmallSize, sampleBuffer, sampleSize, cLevel);
1939 CHECK(!ZSTD_isError(errorCode), "ZSTD_compressCCtx should have failed ! (buffer too small : %u < %u)", (unsigned)tooSmallSize, (unsigned)cSize); }
1940 { unsigned endCheck; memcpy(&endCheck, dstBuffer+tooSmallSize, sizeof(endCheck));
1941 CHECK(endCheck != endMark, "ZSTD_compressCCtx : dst buffer overflow (check.%08X != %08X.mark)", endCheck, endMark); }
1944 /* frame header decompression test */
1945 { ZSTD_frameHeader zfh;
1946 CHECK_Z( ZSTD_getFrameHeader(&zfh, cBuffer, cSize) );
1947 CHECK(zfh.frameContentSize != sampleSize, "Frame content size incorrect");
1950 /* Decompressed size test */
1951 { unsigned long long const rSize = ZSTD_findDecompressedSize(cBuffer, cSize);
1952 CHECK(rSize != sampleSize, "decompressed size incorrect");
1955 /* successful decompression test */
1956 DISPLAYLEVEL(5, "fuzzer t%u: simple decompression test \n", testNb);
1957 { size_t const margin = (FUZ_rand(&lseed) & 1) ? 0 : (FUZ_rand(&lseed) & 31) + 1;
1958 size_t const dSize = ZSTD_decompress(dstBuffer, sampleSize + margin, cBuffer, cSize);
1959 CHECK(dSize != sampleSize, "ZSTD_decompress failed (%s) (srcSize : %u ; cSize : %u)", ZSTD_getErrorName(dSize), (unsigned)sampleSize, (unsigned)cSize);
1960 { U64 const crcDest = XXH64(dstBuffer, sampleSize, 0);
1961 CHECK(crcOrig != crcDest, "decompression result corrupted (pos %u / %u)", (unsigned)findDiff(sampleBuffer, dstBuffer, sampleSize), (unsigned)sampleSize);
1964 free(sampleBuffer); /* no longer useful after this point */
1966 /* truncated src decompression test */
1967 DISPLAYLEVEL(5, "fuzzer t%u: decompression of truncated source \n", testNb);
1968 { size_t const missing = (FUZ_rand(&lseed) % (cSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
1969 size_t const tooSmallSize = cSize - missing;
1970 void* cBufferTooSmall = malloc(tooSmallSize); /* valgrind will catch read overflows */
1971 CHECK(cBufferTooSmall == NULL, "not enough memory !");
1972 memcpy(cBufferTooSmall, cBuffer, tooSmallSize);
1973 { size_t const errorCode = ZSTD_decompress(dstBuffer, dstBufferSize, cBufferTooSmall, tooSmallSize);
1974 CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed ! (truncated src buffer)"); }
1975 free(cBufferTooSmall);
1978 /* too small dst decompression test */
1979 DISPLAYLEVEL(5, "fuzzer t%u: decompress into too small dst buffer \n", testNb);
1980 if (sampleSize > 3) {
1981 size_t const missing = (FUZ_rand(&lseed) % (sampleSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
1982 size_t const tooSmallSize = sampleSize - missing;
1983 static const BYTE token = 0xA9;
1984 dstBuffer[tooSmallSize] = token;
1985 { size_t const errorCode = ZSTD_decompress(dstBuffer, tooSmallSize, cBuffer, cSize);
1986 CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed : %u > %u (dst buffer too small)", (unsigned)errorCode, (unsigned)tooSmallSize); }
1987 CHECK(dstBuffer[tooSmallSize] != token, "ZSTD_decompress : dst buffer overflow");
1990 /* noisy src decompression test */
1992 /* insert noise into src */
1993 { U32 const maxNbBits = FUZ_highbit32((U32)(cSize-4));
1994 size_t pos = 4; /* preserve magic number (too easy to detect) */
1996 /* keep some original src */
1997 { U32 const nbBits = FUZ_rand(&lseed) % maxNbBits;
1998 size_t const mask = (1<<nbBits) - 1;
1999 size_t const skipLength = FUZ_rand(&lseed) & mask;
2002 if (pos >= cSize) break;
2004 { U32 const nbBitsCodes = FUZ_rand(&lseed) % maxNbBits;
2005 U32 const nbBits = nbBitsCodes ? nbBitsCodes-1 : 0;
2006 size_t const mask = (1<<nbBits) - 1;
2007 size_t const rNoiseLength = (FUZ_rand(&lseed) & mask) + 1;
2008 size_t const noiseLength = MIN(rNoiseLength, cSize-pos);
2009 size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseLength);
2010 memcpy(cBuffer + pos, srcBuffer + noiseStart, noiseLength);
2014 /* decompress noisy source */
2015 DISPLAYLEVEL(5, "fuzzer t%u: decompress noisy source \n", testNb);
2016 { U32 const endMark = 0xA9B1C3D6;
2017 memcpy(dstBuffer+sampleSize, &endMark, 4);
2018 { size_t const decompressResult = ZSTD_decompress(dstBuffer, sampleSize, cBuffer, cSize);
2019 /* result *may* be an unlikely success, but even then, it must strictly respect dst buffer boundaries */
2020 CHECK((!ZSTD_isError(decompressResult)) && (decompressResult>sampleSize),
2021 "ZSTD_decompress on noisy src : result is too large : %u > %u (dst buffer)", (unsigned)decompressResult, (unsigned)sampleSize);
2023 { U32 endCheck; memcpy(&endCheck, dstBuffer+sampleSize, 4);
2024 CHECK(endMark!=endCheck, "ZSTD_decompress on noisy src : dst buffer overflow");
2025 } } } /* noisy src decompression test */
2027 /*===== Bufferless streaming compression test, scattered segments and dictionary =====*/
2028 DISPLAYLEVEL(5, "fuzzer t%u: Bufferless streaming compression test \n", testNb);
2029 { U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
2030 U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
2031 int const cLevel = (FUZ_rand(&lseed) %
2033 (MAX(testLog, dictLog) / cLevelLimiter))) +
2035 maxTestSize = FUZ_rLogLength(&lseed, testLog);
2036 if (maxTestSize >= dstBufferSize) maxTestSize = dstBufferSize-1;
2038 dictSize = FUZ_rLogLength(&lseed, dictLog); /* needed also for decompression */
2039 dict = srcBuffer + (FUZ_rand(&lseed) % (srcBufferSize - dictSize));
2041 DISPLAYLEVEL(6, "fuzzer t%u: Compressing up to <=%u bytes at level %i with dictionary size %u \n",
2042 testNb, (unsigned)maxTestSize, cLevel, (unsigned)dictSize);
2044 if (FUZ_rand(&lseed) & 0xF) {
2045 CHECK_Z ( ZSTD_compressBegin_usingDict(refCtx, dict, dictSize, cLevel) );
2047 ZSTD_compressionParameters const cPar = ZSTD_getCParams(cLevel, ZSTD_CONTENTSIZE_UNKNOWN, dictSize);
2048 ZSTD_frameParameters const fPar = { FUZ_rand(&lseed)&1 /* contentSizeFlag */,
2049 !(FUZ_rand(&lseed)&3) /* contentChecksumFlag*/,
2050 0 /*NodictID*/ }; /* note : since dictionary is fake, dictIDflag has no impact */
2051 ZSTD_parameters const p = FUZ_makeParams(cPar, fPar);
2052 CHECK_Z ( ZSTD_compressBegin_advanced(refCtx, dict, dictSize, p, 0) );
2054 CHECK_Z( ZSTD_copyCCtx(ctx, refCtx, 0) );
2057 { U32 const nbChunks = (FUZ_rand(&lseed) & 127) + 2;
2059 XXH64_state_t xxhState;
2060 XXH64_reset(&xxhState, 0);
2061 for (totalTestSize=0, cSize=0, n=0 ; n<nbChunks ; n++) {
2062 size_t const segmentSize = FUZ_randomLength(&lseed, maxSampleLog);
2063 size_t const segmentStart = FUZ_rand(&lseed) % (srcBufferSize - segmentSize);
2065 if (cBufferSize-cSize < ZSTD_compressBound(segmentSize)) break; /* avoid invalid dstBufferTooSmall */
2066 if (totalTestSize+segmentSize > maxTestSize) break;
2068 { size_t const compressResult = ZSTD_compressContinue(ctx, cBuffer+cSize, cBufferSize-cSize, srcBuffer+segmentStart, segmentSize);
2069 CHECK (ZSTD_isError(compressResult), "multi-segments compression error : %s", ZSTD_getErrorName(compressResult));
2070 cSize += compressResult;
2072 XXH64_update(&xxhState, srcBuffer+segmentStart, segmentSize);
2073 memcpy(mirrorBuffer + totalTestSize, srcBuffer+segmentStart, segmentSize);
2074 totalTestSize += segmentSize;
2077 { size_t const flushResult = ZSTD_compressEnd(ctx, cBuffer+cSize, cBufferSize-cSize, NULL, 0);
2078 CHECK (ZSTD_isError(flushResult), "multi-segments epilogue error : %s", ZSTD_getErrorName(flushResult));
2079 cSize += flushResult;
2081 crcOrig = XXH64_digest(&xxhState);
2084 /* streaming decompression test */
2085 DISPLAYLEVEL(5, "fuzzer t%u: Bufferless streaming decompression test \n", testNb);
2086 /* ensure memory requirement is good enough (should always be true) */
2087 { ZSTD_frameHeader zfh;
2088 CHECK( ZSTD_getFrameHeader(&zfh, cBuffer, ZSTD_FRAMEHEADERSIZE_MAX),
2089 "ZSTD_getFrameHeader(): error retrieving frame information");
2090 { size_t const roundBuffSize = ZSTD_decodingBufferSize_min(zfh.windowSize, zfh.frameContentSize);
2091 CHECK_Z(roundBuffSize);
2092 CHECK((roundBuffSize > totalTestSize) && (zfh.frameContentSize!=ZSTD_CONTENTSIZE_UNKNOWN),
2093 "ZSTD_decodingBufferSize_min() requires more memory (%u) than necessary (%u)",
2094 (unsigned)roundBuffSize, (unsigned)totalTestSize );
2096 if (dictSize<8) dictSize=0, dict=NULL; /* disable dictionary */
2097 CHECK_Z( ZSTD_decompressBegin_usingDict(dctx, dict, dictSize) );
2100 while (totalCSize < cSize) {
2101 size_t const inSize = ZSTD_nextSrcSizeToDecompress(dctx);
2102 size_t const genSize = ZSTD_decompressContinue(dctx, dstBuffer+totalGenSize, dstBufferSize-totalGenSize, cBuffer+totalCSize, inSize);
2103 CHECK (ZSTD_isError(genSize), "ZSTD_decompressContinue error : %s", ZSTD_getErrorName(genSize));
2104 totalGenSize += genSize;
2105 totalCSize += inSize;
2107 CHECK (ZSTD_nextSrcSizeToDecompress(dctx) != 0, "frame not fully decoded");
2108 CHECK (totalGenSize != totalTestSize, "streaming decompressed data : wrong size")
2109 CHECK (totalCSize != cSize, "compressed data should be fully read")
2110 { U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
2111 CHECK(crcOrig != crcDest, "streaming decompressed data corrupted (pos %u / %u)",
2112 (unsigned)findDiff(mirrorBuffer, dstBuffer, totalTestSize), (unsigned)totalTestSize);
2114 } /* for ( ; (testNb <= nbTests) */
2115 DISPLAY("\r%u fuzzer tests completed \n", testNb-1);
2118 ZSTD_freeCCtx(refCtx);
2120 ZSTD_freeDCtx(dctx);
2121 free(cNoiseBuffer[0]);
2122 free(cNoiseBuffer[1]);
2123 free(cNoiseBuffer[2]);
2124 free(cNoiseBuffer[3]);
2125 free(cNoiseBuffer[4]);
2137 /*_*******************************************************
2139 *********************************************************/
2140 static int FUZ_usage(const char* programName)
2142 DISPLAY( "Usage :\n");
2143 DISPLAY( " %s [args]\n", programName);
2145 DISPLAY( "Arguments :\n");
2146 DISPLAY( " -i# : Nb of tests (default:%i) \n", nbTestsDefault);
2147 DISPLAY( " -s# : Select seed (default:prompt user)\n");
2148 DISPLAY( " -t# : Select starting test number (default:0)\n");
2149 DISPLAY( " -P# : Select compressibility in %% (default:%i%%)\n", FUZ_compressibility_default);
2150 DISPLAY( " -v : verbose\n");
2151 DISPLAY( " -p : pause at the end\n");
2152 DISPLAY( " -h : display help and exit\n");
2156 /*! readU32FromChar() :
2157 @return : unsigned integer value read from input in `char` format
2158 allows and interprets K, KB, KiB, M, MB and MiB suffix.
2159 Will also modify `*stringPtr`, advancing it to position where it stopped reading.
2160 Note : function result can overflow if digit string > MAX_UINT */
2161 static unsigned readU32FromChar(const char** stringPtr)
2163 unsigned result = 0;
2164 while ((**stringPtr >='0') && (**stringPtr <='9'))
2165 result *= 10, result += **stringPtr - '0', (*stringPtr)++ ;
2166 if ((**stringPtr=='K') || (**stringPtr=='M')) {
2168 if (**stringPtr=='M') result <<= 10;
2170 if (**stringPtr=='i') (*stringPtr)++;
2171 if (**stringPtr=='B') (*stringPtr)++;
2176 /** longCommandWArg() :
2177 * check if *stringPtr is the same as longCommand.
2178 * If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
2179 * @return 0 and doesn't modify *stringPtr otherwise.
2181 static unsigned longCommandWArg(const char** stringPtr, const char* longCommand)
2183 size_t const comSize = strlen(longCommand);
2184 int const result = !strncmp(*stringPtr, longCommand, comSize);
2185 if (result) *stringPtr += comSize;
2189 int main(int argc, const char** argv)
2194 int nbTests = nbTestsDefault;
2196 int proba = FUZ_compressibility_default;
2199 U32 maxDuration = 0;
2201 U32 memTestsOnly = 0;
2202 const char* const programName = argv[0];
2204 /* Check command line */
2205 for (argNb=1; argNb<argc; argNb++) {
2206 const char* argument = argv[argNb];
2207 if(!argument) continue; /* Protection if argument empty */
2209 /* Handle commands. Aggregated commands are allowed */
2210 if (argument[0]=='-') {
2212 if (longCommandWArg(&argument, "--memtest=")) { memTestsOnly = readU32FromChar(&argument); continue; }
2214 if (!strcmp(argument, "--memtest")) { memTestsOnly=1; continue; }
2215 if (!strcmp(argument, "--no-big-tests")) { bigTests=0; continue; }
2218 while (*argument!=0) {
2222 return FUZ_usage(programName);
2234 case 'p': /* pause at the end */
2240 argument++; maxDuration = 0;
2241 nbTests = readU32FromChar(&argument);
2247 maxDuration = readU32FromChar(&argument);
2248 if (*argument=='s') argument++; /* seconds */
2249 if (*argument=='m') maxDuration *= 60, argument++; /* minutes */
2250 if (*argument=='n') argument++;
2256 seed = readU32FromChar(&argument);
2261 testNb = readU32FromChar(&argument);
2264 case 'P': /* compressibility % */
2266 proba = readU32FromChar(&argument);
2267 if (proba>100) proba = 100;
2271 return (FUZ_usage(programName), 1);
2272 } } } } /* for (argNb=1; argNb<argc; argNb++) */
2275 DISPLAY("Starting zstd tester (%i-bits, %s)\n", (int)(sizeof(size_t)*8), ZSTD_VERSION_STRING);
2278 time_t const t = time(NULL);
2279 U32 const h = XXH32(&t, sizeof(t), 1);
2283 DISPLAY("Seed = %u\n", (unsigned)seed);
2284 if (proba!=FUZ_compressibility_default) DISPLAY("Compressibility : %i%%\n", proba);
2287 g_displayLevel = MAX(3, g_displayLevel);
2288 return FUZ_mallocTests(seed, ((double)proba) / 100, memTestsOnly);
2291 if (nbTests < testNb) nbTests = testNb;
2294 result = basicUnitTests(0, ((double)proba) / 100); /* constant seed for predictability */
2296 result = fuzzerTests(seed, nbTests, testNb, maxDuration, ((double)proba) / 100, bigTests);
2299 DISPLAY("Press Enter \n");