2 * Copyright (c) 2016-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).
11 /*-************************************
13 **************************************/
14 #ifdef _MSC_VER /* Visual Studio */
15 # define _CRT_SECURE_NO_WARNINGS /* fgets */
16 # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
17 # pragma warning(disable : 4204) /* disable: C4204: non-constant aggregate initializer */
21 /*-************************************
23 **************************************/
24 #include <stdlib.h> /* free */
25 #include <stdio.h> /* fgets, sscanf */
26 #include <string.h> /* strcmp */
27 #include <time.h> /* clock_t */
28 #define ZSTD_STATIC_LINKING_ONLY /* ZSTD_compressContinue, ZSTD_compressBlock */
29 #include "zstd.h" /* ZSTD_VERSION_STRING */
30 #include "zstd_errors.h" /* ZSTD_getErrorCode */
31 #include "zstdmt_compress.h"
32 #define ZDICT_STATIC_LINKING_ONLY
33 #include "zdict.h" /* ZDICT_trainFromBuffer */
34 #include "datagen.h" /* RDG_genBuffer */
36 #define XXH_STATIC_LINKING_ONLY
37 #include "xxhash.h" /* XXH64 */
40 /*-************************************
42 **************************************/
47 static const U32 FUZ_compressibility_default = 50;
48 static const U32 nbTestsDefault = 30000;
51 /*-************************************
53 **************************************/
54 #define DISPLAY(...) fprintf(stdout, __VA_ARGS__)
55 #define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
56 static U32 g_displayLevel = 2;
58 #define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \
59 if ((FUZ_clockSpan(g_displayClock) > g_refreshRate) || (g_displayLevel>=4)) \
60 { g_displayClock = clock(); DISPLAY(__VA_ARGS__); \
61 if (g_displayLevel>=4) fflush(stdout); } }
62 static const clock_t g_refreshRate = CLOCKS_PER_SEC / 6;
63 static clock_t g_displayClock = 0;
66 /*-*******************************************************
68 *********************************************************/
69 #define MIN(a,b) ((a)<(b)?(a):(b))
70 #define MAX(a,b) ((a)>(b)?(a):(b))
72 static clock_t FUZ_clockSpan(clock_t cStart)
74 return clock() - cStart; /* works even when overflow; max span ~ 30mn */
77 #define FUZ_rotl32(x,r) ((x << r) | (x >> (32 - r)))
78 static unsigned FUZ_rand(unsigned* src)
80 static const U32 prime1 = 2654435761U;
81 static const U32 prime2 = 2246822519U;
85 rand32 = FUZ_rotl32(rand32, 13);
90 static unsigned FUZ_highbit32(U32 v32)
94 while (v32) v32 >>= 1, nbBits++;
99 /*=============================================
101 =============================================*/
102 #if defined(__APPLE__) && defined(__MACH__)
104 #include <malloc/malloc.h> /* malloc_size */
107 unsigned long long totalMalloc;
108 size_t currentMalloc;
114 static const mallocCounter_t INIT_MALLOC_COUNTER = { 0, 0, 0, 0, 0 };
116 static void* FUZ_mallocDebug(void* counter, size_t size)
118 mallocCounter_t* const mcPtr = (mallocCounter_t*)counter;
119 void* const ptr = malloc(size);
120 if (ptr==NULL) return NULL;
121 DISPLAYLEVEL(4, "allocating %u KB => effectively %u KB \n",
122 (U32)(size >> 10), (U32)(malloc_size(ptr) >> 10)); /* OS-X specific */
123 mcPtr->totalMalloc += size;
124 mcPtr->currentMalloc += size;
125 if (mcPtr->currentMalloc > mcPtr->peakMalloc)
126 mcPtr->peakMalloc = mcPtr->currentMalloc;
127 mcPtr->nbMalloc += 1;
131 static void FUZ_freeDebug(void* counter, void* address)
133 mallocCounter_t* const mcPtr = (mallocCounter_t*)counter;
134 DISPLAYLEVEL(4, "freeing %u KB \n", (U32)(malloc_size(address) >> 10));
136 mcPtr->currentMalloc -= malloc_size(address); /* OS-X specific */
140 static void FUZ_displayMallocStats(mallocCounter_t count)
142 DISPLAYLEVEL(3, "peak:%6u KB, nbMallocs:%2u, total:%6u KB \n",
143 (U32)(count.peakMalloc >> 10),
145 (U32)(count.totalMalloc >> 10));
148 #define CHECK_Z(f) { \
149 size_t const err = f; \
150 if (ZSTD_isError(err)) { \
151 DISPLAY("Error => %s : %s ", \
152 #f, ZSTD_getErrorName(err)); \
156 static int FUZ_mallocTests(unsigned seed, double compressibility, unsigned part)
158 size_t const inSize = 64 MB + 16 MB + 4 MB + 1 MB + 256 KB + 64 KB; /* 85.3 MB */
159 size_t const outSize = ZSTD_compressBound(inSize);
160 void* const inBuffer = malloc(inSize);
161 void* const outBuffer = malloc(outSize);
163 /* test only played in verbose mode, as they are long */
164 if (g_displayLevel<3) return 0;
166 /* Create compressible noise */
167 if (!inBuffer || !outBuffer) {
168 DISPLAY("Not enough memory, aborting\n");
171 RDG_genBuffer(inBuffer, inSize, compressibility, 0. /*auto*/, seed);
173 /* simple compression tests */
175 { int compressionLevel;
176 for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
177 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
178 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
179 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
180 CHECK_Z( ZSTD_compressCCtx(cctx, outBuffer, outSize, inBuffer, inSize, compressionLevel) );
182 DISPLAYLEVEL(3, "compressCCtx level %i : ", compressionLevel);
183 FUZ_displayMallocStats(malcount);
186 /* streaming compression tests */
188 { int compressionLevel;
189 for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
190 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
191 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
192 ZSTD_CCtx* const cstream = ZSTD_createCStream_advanced(cMem);
193 ZSTD_outBuffer out = { outBuffer, outSize, 0 };
194 ZSTD_inBuffer in = { inBuffer, inSize, 0 };
195 CHECK_Z( ZSTD_initCStream(cstream, compressionLevel) );
196 CHECK_Z( ZSTD_compressStream(cstream, &out, &in) );
197 CHECK_Z( ZSTD_endStream(cstream, &out) );
198 ZSTD_freeCStream(cstream);
199 DISPLAYLEVEL(3, "compressStream level %i : ", compressionLevel);
200 FUZ_displayMallocStats(malcount);
203 /* advanced MT API test */
206 for (nbThreads=1; nbThreads<=4; nbThreads++) {
207 int compressionLevel;
208 for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
209 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
210 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
211 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
212 ZSTD_outBuffer out = { outBuffer, outSize, 0 };
213 ZSTD_inBuffer in = { inBuffer, inSize, 0 };
214 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_compressionLevel, (U32)compressionLevel) );
215 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_nbThreads, nbThreads) );
216 while ( ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end) ) {}
218 DISPLAYLEVEL(3, "compress_generic,-T%u,end level %i : ",
219 nbThreads, compressionLevel);
220 FUZ_displayMallocStats(malcount);
223 /* advanced MT streaming API test */
226 for (nbThreads=1; nbThreads<=4; nbThreads++) {
227 int compressionLevel;
228 for (compressionLevel=1; compressionLevel<=6; compressionLevel++) {
229 mallocCounter_t malcount = INIT_MALLOC_COUNTER;
230 ZSTD_customMem const cMem = { FUZ_mallocDebug, FUZ_freeDebug, &malcount };
231 ZSTD_CCtx* const cctx = ZSTD_createCCtx_advanced(cMem);
232 ZSTD_outBuffer out = { outBuffer, outSize, 0 };
233 ZSTD_inBuffer in = { inBuffer, inSize, 0 };
234 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_compressionLevel, (U32)compressionLevel) );
235 CHECK_Z( ZSTD_CCtx_setParameter(cctx, ZSTD_p_nbThreads, nbThreads) );
236 CHECK_Z( ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_continue) );
237 while ( ZSTD_compress_generic(cctx, &out, &in, ZSTD_e_end) ) {}
239 DISPLAYLEVEL(3, "compress_generic,-T%u,continue level %i : ",
240 nbThreads, compressionLevel);
241 FUZ_displayMallocStats(malcount);
249 static int FUZ_mallocTests(unsigned seed, double compressibility, unsigned part)
251 (void)seed; (void)compressibility; (void)part;
257 /*=============================================
259 =============================================*/
261 #define CHECK_V(var, fn) size_t const var = fn; if (ZSTD_isError(var)) goto _output_error
262 #define CHECK(fn) { CHECK_V(err, fn); }
263 #define CHECKPLUS(var, fn, more) { CHECK_V(var, fn); more; }
265 static int basicUnitTests(U32 seed, double compressibility)
267 size_t const CNBuffSize = 5 MB;
268 void* const CNBuffer = malloc(CNBuffSize);
269 size_t const compressedBufferSize = ZSTD_compressBound(CNBuffSize);
270 void* const compressedBuffer = malloc(compressedBufferSize);
271 void* const decodedBuffer = malloc(CNBuffSize);
272 ZSTD_DCtx* dctx = ZSTD_createDCtx();
277 /* Create compressible noise */
278 if (!CNBuffer || !compressedBuffer || !decodedBuffer) {
279 DISPLAY("Not enough memory, aborting\n");
283 RDG_genBuffer(CNBuffer, CNBuffSize, compressibility, 0., seed);
286 DISPLAYLEVEL(4, "test%3i : ZSTD_getErrorName : ", testNb++);
287 { const char* errorString = ZSTD_getErrorName(0);
288 DISPLAYLEVEL(4, "OK : %s \n", errorString);
291 DISPLAYLEVEL(4, "test%3i : ZSTD_getErrorName with wrong value : ", testNb++);
292 { const char* errorString = ZSTD_getErrorName(499);
293 DISPLAYLEVEL(4, "OK : %s \n", errorString);
297 DISPLAYLEVEL(4, "test%3i : compress %u bytes : ", testNb++, (U32)CNBuffSize);
298 { ZSTD_CCtx* cctx = ZSTD_createCCtx();
299 if (cctx==NULL) goto _output_error;
300 CHECKPLUS(r, ZSTD_compressCCtx(cctx,
301 compressedBuffer, compressedBufferSize,
302 CNBuffer, CNBuffSize, 1),
304 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
306 DISPLAYLEVEL(4, "test%3i : size of cctx for level 1 : ", testNb++);
307 { size_t const cctxSize = ZSTD_sizeof_CCtx(cctx);
308 DISPLAYLEVEL(4, "%u bytes \n", (U32)cctxSize);
314 DISPLAYLEVEL(4, "test%3i : ZSTD_getFrameContentSize test : ", testNb++);
315 { unsigned long long const rSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
316 if (rSize != CNBuffSize) goto _output_error;
318 DISPLAYLEVEL(4, "OK \n");
320 DISPLAYLEVEL(4, "test%3i : ZSTD_findDecompressedSize test : ", testNb++);
321 { unsigned long long const rSize = ZSTD_findDecompressedSize(compressedBuffer, cSize);
322 if (rSize != CNBuffSize) goto _output_error;
324 DISPLAYLEVEL(4, "OK \n");
326 DISPLAYLEVEL(4, "test%3i : decompress %u bytes : ", testNb++, (U32)CNBuffSize);
327 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
328 if (r != CNBuffSize) goto _output_error; }
329 DISPLAYLEVEL(4, "OK \n");
331 DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
333 for (u=0; u<CNBuffSize; u++) {
334 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u]) goto _output_error;;
336 DISPLAYLEVEL(4, "OK \n");
339 DISPLAYLEVEL(4, "test%3i : decompress with null dict : ", testNb++);
340 { size_t const r = ZSTD_decompress_usingDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, NULL, 0);
341 if (r != CNBuffSize) goto _output_error; }
342 DISPLAYLEVEL(4, "OK \n");
344 DISPLAYLEVEL(4, "test%3i : decompress with null DDict : ", testNb++);
345 { size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, NULL);
346 if (r != CNBuffSize) goto _output_error; }
347 DISPLAYLEVEL(4, "OK \n");
349 DISPLAYLEVEL(4, "test%3i : decompress with 1 missing byte : ", testNb++);
350 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize-1);
351 if (!ZSTD_isError(r)) goto _output_error;
352 if (ZSTD_getErrorCode((size_t)r) != ZSTD_error_srcSize_wrong) goto _output_error; }
353 DISPLAYLEVEL(4, "OK \n");
355 DISPLAYLEVEL(4, "test%3i : decompress with 1 too much byte : ", testNb++);
356 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize+1);
357 if (!ZSTD_isError(r)) goto _output_error;
358 if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
359 DISPLAYLEVEL(4, "OK \n");
362 /* Static CCtx tests */
363 #define STATIC_CCTX_LEVEL 3
364 DISPLAYLEVEL(4, "test%3i : create static CCtx for level %u :", testNb++, STATIC_CCTX_LEVEL);
365 { size_t const staticCCtxSize = ZSTD_estimateCStreamSize(STATIC_CCTX_LEVEL);
366 void* const staticCCtxBuffer = malloc(staticCCtxSize);
367 size_t const staticDCtxSize = ZSTD_estimateDCtxSize();
368 void* const staticDCtxBuffer = malloc(staticDCtxSize);
369 if (staticCCtxBuffer==NULL || staticDCtxBuffer==NULL) {
370 free(staticCCtxBuffer);
371 free(staticDCtxBuffer);
372 DISPLAY("Not enough memory, aborting\n");
376 { ZSTD_CCtx* staticCCtx = ZSTD_initStaticCCtx(staticCCtxBuffer, staticCCtxSize);
377 ZSTD_DCtx* staticDCtx = ZSTD_initStaticDCtx(staticDCtxBuffer, staticDCtxSize);
378 if ((staticCCtx==NULL) || (staticDCtx==NULL)) goto _output_error;
379 DISPLAYLEVEL(4, "OK \n");
381 DISPLAYLEVEL(4, "test%3i : init CCtx for level %u : ", testNb++, STATIC_CCTX_LEVEL);
382 { size_t const r = ZSTD_compressBegin(staticCCtx, STATIC_CCTX_LEVEL);
383 if (ZSTD_isError(r)) goto _output_error; }
384 DISPLAYLEVEL(4, "OK \n");
386 DISPLAYLEVEL(4, "test%3i : simple compression test with static CCtx : ", testNb++);
387 CHECKPLUS(r, ZSTD_compressCCtx(staticCCtx,
388 compressedBuffer, compressedBufferSize,
389 CNBuffer, CNBuffSize, STATIC_CCTX_LEVEL),
391 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n",
392 (U32)cSize, (double)cSize/CNBuffSize*100);
394 DISPLAYLEVEL(4, "test%3i : simple decompression test with static DCtx : ", testNb++);
395 { size_t const r = ZSTD_decompressDCtx(staticDCtx,
396 decodedBuffer, CNBuffSize,
397 compressedBuffer, cSize);
398 if (r != CNBuffSize) goto _output_error; }
399 DISPLAYLEVEL(4, "OK \n");
401 DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
403 for (u=0; u<CNBuffSize; u++) {
404 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u])
407 DISPLAYLEVEL(4, "OK \n");
409 DISPLAYLEVEL(4, "test%3i : init CCtx for too large level (must fail) : ", testNb++);
410 { size_t const r = ZSTD_compressBegin(staticCCtx, ZSTD_maxCLevel());
411 if (!ZSTD_isError(r)) goto _output_error; }
412 DISPLAYLEVEL(4, "OK \n");
414 DISPLAYLEVEL(4, "test%3i : init CCtx for small level %u (should work again) : ", testNb++, 1);
415 { size_t const r = ZSTD_compressBegin(staticCCtx, 1);
416 if (ZSTD_isError(r)) goto _output_error; }
417 DISPLAYLEVEL(4, "OK \n");
419 DISPLAYLEVEL(4, "test%3i : init CStream for small level %u : ", testNb++, 1);
420 { size_t const r = ZSTD_initCStream(staticCCtx, 1);
421 if (ZSTD_isError(r)) goto _output_error; }
422 DISPLAYLEVEL(4, "OK \n");
424 DISPLAYLEVEL(4, "test%3i : init CStream with dictionary (should fail) : ", testNb++);
425 { size_t const r = ZSTD_initCStream_usingDict(staticCCtx, CNBuffer, 64 KB, 1);
426 if (!ZSTD_isError(r)) goto _output_error; }
427 DISPLAYLEVEL(4, "OK \n");
429 DISPLAYLEVEL(4, "test%3i : init DStream (should fail) : ", testNb++);
430 { size_t const r = ZSTD_initDStream(staticDCtx);
431 if (ZSTD_isError(r)) goto _output_error; }
432 { ZSTD_outBuffer output = { decodedBuffer, CNBuffSize, 0 };
433 ZSTD_inBuffer input = { compressedBuffer, ZSTD_FRAMEHEADERSIZE_MAX+1, 0 };
434 size_t const r = ZSTD_decompressStream(staticDCtx, &output, &input);
435 if (!ZSTD_isError(r)) goto _output_error;
437 DISPLAYLEVEL(4, "OK \n");
439 free(staticCCtxBuffer);
440 free(staticDCtxBuffer);
445 /* ZSTDMT simple MT compression test */
446 DISPLAYLEVEL(4, "test%3i : create ZSTDMT CCtx : ", testNb++);
447 { ZSTDMT_CCtx* mtctx = ZSTDMT_createCCtx(2);
449 DISPLAY("mtctx : mot enough memory, aborting \n");
453 DISPLAYLEVEL(4, "OK \n");
455 DISPLAYLEVEL(4, "test%3i : compress %u bytes with 2 threads : ", testNb++, (U32)CNBuffSize);
456 CHECKPLUS(r, ZSTDMT_compressCCtx(mtctx,
457 compressedBuffer, compressedBufferSize,
458 CNBuffer, CNBuffSize,
461 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
463 DISPLAYLEVEL(4, "test%3i : decompressed size test : ", testNb++);
464 { unsigned long long const rSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
465 if (rSize != CNBuffSize) {
466 DISPLAY("ZSTD_getFrameContentSize incorrect : %u != %u \n", (U32)rSize, (U32)CNBuffSize);
469 DISPLAYLEVEL(4, "OK \n");
471 DISPLAYLEVEL(4, "test%3i : decompress %u bytes : ", testNb++, (U32)CNBuffSize);
472 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
473 if (r != CNBuffSize) goto _output_error; }
474 DISPLAYLEVEL(4, "OK \n");
476 DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
478 for (u=0; u<CNBuffSize; u++) {
479 if (((BYTE*)decodedBuffer)[u] != ((BYTE*)CNBuffer)[u]) goto _output_error;;
481 DISPLAYLEVEL(4, "OK \n");
483 DISPLAYLEVEL(4, "test%3i : compress -T2 with checksum : ", testNb++);
484 { ZSTD_parameters params = ZSTD_getParams(1, CNBuffSize, 0);
485 params.fParams.checksumFlag = 1;
486 params.fParams.contentSizeFlag = 1;
487 CHECKPLUS(r, ZSTDMT_compress_advanced(mtctx,
488 compressedBuffer, compressedBufferSize,
489 CNBuffer, CNBuffSize,
490 NULL, params, 3 /*overlapRLog*/),
493 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
495 DISPLAYLEVEL(4, "test%3i : decompress %u bytes : ", testNb++, (U32)CNBuffSize);
496 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize);
497 if (r != CNBuffSize) goto _output_error; }
498 DISPLAYLEVEL(4, "OK \n");
500 ZSTDMT_freeCCtx(mtctx);
504 /* Simple API multiframe test */
505 DISPLAYLEVEL(4, "test%3i : compress multiple frames : ", testNb++);
509 /* only use the first half so we don't push against size limit of compressedBuffer */
510 size_t const segSize = (CNBuffSize / 2) / segs;
511 for (i = 0; i < segs; i++) {
514 (BYTE *)compressedBuffer + off, CNBuffSize - off,
515 (BYTE *)CNBuffer + segSize * i,
519 /* insert skippable frame */
520 const U32 skipLen = 128 KB;
521 MEM_writeLE32((BYTE*)compressedBuffer + off, ZSTD_MAGIC_SKIPPABLE_START);
522 MEM_writeLE32((BYTE*)compressedBuffer + off + 4, skipLen);
523 off += skipLen + ZSTD_skippableHeaderSize;
528 DISPLAYLEVEL(4, "OK \n");
530 DISPLAYLEVEL(4, "test%3i : get decompressed size of multiple frames : ", testNb++);
531 { unsigned long long const r = ZSTD_findDecompressedSize(compressedBuffer, cSize);
532 if (r != CNBuffSize / 2) goto _output_error; }
533 DISPLAYLEVEL(4, "OK \n");
535 DISPLAYLEVEL(4, "test%3i : decompress multiple frames : ", testNb++);
536 { CHECK_V(r, ZSTD_decompress(decodedBuffer, CNBuffSize, compressedBuffer, cSize));
537 if (r != CNBuffSize / 2) goto _output_error; }
538 DISPLAYLEVEL(4, "OK \n");
540 DISPLAYLEVEL(4, "test%3i : check decompressed result : ", testNb++);
541 if (memcmp(decodedBuffer, CNBuffer, CNBuffSize / 2) != 0) goto _output_error;
542 DISPLAYLEVEL(4, "OK \n");
544 /* Dictionary and CCtx Duplication tests */
545 { ZSTD_CCtx* const ctxOrig = ZSTD_createCCtx();
546 ZSTD_CCtx* const ctxDuplicated = ZSTD_createCCtx();
547 static const size_t dictSize = 551;
549 DISPLAYLEVEL(4, "test%3i : copy context too soon : ", testNb++);
550 { size_t const copyResult = ZSTD_copyCCtx(ctxDuplicated, ctxOrig, 0);
551 if (!ZSTD_isError(copyResult)) goto _output_error; } /* error must be detected */
552 DISPLAYLEVEL(4, "OK \n");
554 DISPLAYLEVEL(4, "test%3i : load dictionary into context : ", testNb++);
555 CHECK( ZSTD_compressBegin_usingDict(ctxOrig, CNBuffer, dictSize, 2) );
556 CHECK( ZSTD_copyCCtx(ctxDuplicated, ctxOrig, 0) ); /* Begin_usingDict implies unknown srcSize, so match that */
557 DISPLAYLEVEL(4, "OK \n");
559 DISPLAYLEVEL(4, "test%3i : compress with flat dictionary : ", testNb++);
561 CHECKPLUS(r, ZSTD_compressEnd(ctxOrig, compressedBuffer, compressedBufferSize,
562 (const char*)CNBuffer + dictSize, CNBuffSize - dictSize),
564 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
566 DISPLAYLEVEL(4, "test%3i : frame built with flat dictionary should be decompressible : ", testNb++);
567 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
568 decodedBuffer, CNBuffSize,
569 compressedBuffer, cSize,
571 if (r != CNBuffSize - dictSize) goto _output_error);
572 DISPLAYLEVEL(4, "OK \n");
574 DISPLAYLEVEL(4, "test%3i : compress with duplicated context : ", testNb++);
575 { size_t const cSizeOrig = cSize;
577 CHECKPLUS(r, ZSTD_compressEnd(ctxDuplicated, compressedBuffer, compressedBufferSize,
578 (const char*)CNBuffer + dictSize, CNBuffSize - dictSize),
580 if (cSize != cSizeOrig) goto _output_error; /* should be identical ==> same size */
582 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
584 DISPLAYLEVEL(4, "test%3i : frame built with duplicated context should be decompressible : ", testNb++);
585 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
586 decodedBuffer, CNBuffSize,
587 compressedBuffer, cSize,
589 if (r != CNBuffSize - dictSize) goto _output_error);
590 DISPLAYLEVEL(4, "OK \n");
592 DISPLAYLEVEL(4, "test%3i : decompress with DDict : ", testNb++);
593 { ZSTD_DDict* const ddict = ZSTD_createDDict(CNBuffer, dictSize);
594 size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, ddict);
595 if (r != CNBuffSize - dictSize) goto _output_error;
596 DISPLAYLEVEL(4, "OK (size of DDict : %u) \n", (U32)ZSTD_sizeof_DDict(ddict));
597 ZSTD_freeDDict(ddict);
600 DISPLAYLEVEL(4, "test%3i : decompress with static DDict : ", testNb++);
601 { size_t const ddictBufferSize = ZSTD_estimateDDictSize(dictSize, 0);
602 void* ddictBuffer = malloc(ddictBufferSize);
603 if (ddictBuffer == NULL) goto _output_error;
604 { ZSTD_DDict* const ddict = ZSTD_initStaticDDict(ddictBuffer, ddictBufferSize, CNBuffer, dictSize, 0);
605 size_t const r = ZSTD_decompress_usingDDict(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize, ddict);
606 if (r != CNBuffSize - dictSize) goto _output_error;
609 DISPLAYLEVEL(4, "OK (size of static DDict : %u) \n", (U32)ddictBufferSize);
612 DISPLAYLEVEL(4, "test%3i : check content size on duplicated context : ", testNb++);
613 { size_t const testSize = CNBuffSize / 3;
614 { ZSTD_parameters p = ZSTD_getParams(2, testSize, dictSize);
615 p.fParams.contentSizeFlag = 1;
616 CHECK( ZSTD_compressBegin_advanced(ctxOrig, CNBuffer, dictSize, p, testSize-1) );
618 CHECK( ZSTD_copyCCtx(ctxDuplicated, ctxOrig, testSize) );
620 CHECKPLUS(r, ZSTD_compressEnd(ctxDuplicated, compressedBuffer, ZSTD_compressBound(testSize),
621 (const char*)CNBuffer + dictSize, testSize),
623 { ZSTD_frameHeader zfh;
624 if (ZSTD_getFrameHeader(&zfh, compressedBuffer, cSize)) goto _output_error;
625 if ((zfh.frameContentSize != testSize) && (zfh.frameContentSize != 0)) goto _output_error;
627 DISPLAYLEVEL(4, "OK \n");
629 ZSTD_freeCCtx(ctxOrig);
630 ZSTD_freeCCtx(ctxDuplicated);
633 /* Dictionary and dictBuilder tests */
634 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
635 size_t dictSize = 16 KB;
636 void* dictBuffer = malloc(dictSize);
637 size_t const totalSampleSize = 1 MB;
638 size_t const sampleUnitSize = 8 KB;
639 U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
640 size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
643 if (dictBuffer==NULL || samplesSizes==NULL) {
649 DISPLAYLEVEL(4, "test%3i : dictBuilder : ", testNb++);
650 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
651 dictSize = ZDICT_trainFromBuffer(dictBuffer, dictSize,
652 CNBuffer, samplesSizes, nbSamples);
653 if (ZDICT_isError(dictSize)) goto _output_error;
654 DISPLAYLEVEL(4, "OK, created dictionary of size %u \n", (U32)dictSize);
656 DISPLAYLEVEL(4, "test%3i : check dictID : ", testNb++);
657 dictID = ZDICT_getDictID(dictBuffer, dictSize);
658 if (dictID==0) goto _output_error;
659 DISPLAYLEVEL(4, "OK : %u \n", dictID);
661 DISPLAYLEVEL(4, "test%3i : compress with dictionary : ", testNb++);
662 cSize = ZSTD_compress_usingDict(cctx, compressedBuffer, compressedBufferSize,
663 CNBuffer, CNBuffSize,
664 dictBuffer, dictSize, 4);
665 if (ZSTD_isError(cSize)) goto _output_error;
666 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
668 DISPLAYLEVEL(4, "test%3i : retrieve dictID from dictionary : ", testNb++);
669 { U32 const did = ZSTD_getDictID_fromDict(dictBuffer, dictSize);
670 if (did != dictID) goto _output_error; /* non-conformant (content-only) dictionary */
672 DISPLAYLEVEL(4, "OK \n");
674 DISPLAYLEVEL(4, "test%3i : retrieve dictID from frame : ", testNb++);
675 { U32 const did = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
676 if (did != dictID) goto _output_error; /* non-conformant (content-only) dictionary */
678 DISPLAYLEVEL(4, "OK \n");
680 DISPLAYLEVEL(4, "test%3i : frame built with dictionary should be decompressible : ", testNb++);
681 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
682 decodedBuffer, CNBuffSize,
683 compressedBuffer, cSize,
684 dictBuffer, dictSize),
685 if (r != CNBuffSize) goto _output_error);
686 DISPLAYLEVEL(4, "OK \n");
688 DISPLAYLEVEL(4, "test%3i : estimate CDict size : ", testNb++);
689 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
690 size_t const estimatedSize = ZSTD_estimateCDictSize_advanced(dictSize, cParams, 1 /*byReference*/);
691 DISPLAYLEVEL(4, "OK : %u \n", (U32)estimatedSize);
694 DISPLAYLEVEL(4, "test%3i : compress with CDict ", testNb++);
695 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
696 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize,
697 1 /* byReference */, ZSTD_dm_auto,
698 cParams, ZSTD_defaultCMem);
699 DISPLAYLEVEL(4, "(size : %u) : ", (U32)ZSTD_sizeof_CDict(cdict));
700 cSize = ZSTD_compress_usingCDict(cctx, compressedBuffer, compressedBufferSize,
701 CNBuffer, CNBuffSize, cdict);
702 ZSTD_freeCDict(cdict);
703 if (ZSTD_isError(cSize)) goto _output_error;
705 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
707 DISPLAYLEVEL(4, "test%3i : retrieve dictID from frame : ", testNb++);
708 { U32 const did = ZSTD_getDictID_fromFrame(compressedBuffer, cSize);
709 if (did != dictID) goto _output_error; /* non-conformant (content-only) dictionary */
711 DISPLAYLEVEL(4, "OK \n");
713 DISPLAYLEVEL(4, "test%3i : frame built with dictionary should be decompressible : ", testNb++);
714 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
715 decodedBuffer, CNBuffSize,
716 compressedBuffer, cSize,
717 dictBuffer, dictSize),
718 if (r != CNBuffSize) goto _output_error);
719 DISPLAYLEVEL(4, "OK \n");
721 DISPLAYLEVEL(4, "test%3i : compress with static CDict : ", testNb++);
722 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
723 size_t const cdictSize = ZSTD_estimateCDictSize_advanced(dictSize, cParams, 0);
724 void* const cdictBuffer = malloc(cdictSize);
725 if (cdictBuffer==NULL) goto _output_error;
726 { ZSTD_CDict* const cdict = ZSTD_initStaticCDict(cdictBuffer, cdictSize,
727 dictBuffer, dictSize,
728 0 /* by Reference */, ZSTD_dm_auto,
731 DISPLAY("ZSTD_initStaticCDict failed ");
734 cSize = ZSTD_compress_usingCDict(cctx,
735 compressedBuffer, compressedBufferSize,
736 CNBuffer, CNBuffSize, cdict);
737 if (ZSTD_isError(cSize)) {
738 DISPLAY("ZSTD_compress_usingCDict failed ");
743 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
745 DISPLAYLEVEL(4, "test%3i : ZSTD_compress_usingCDict_advanced, no contentSize, no dictID : ", testNb++);
746 { ZSTD_frameParameters const fParams = { 0 /* frameSize */, 1 /* checksum */, 1 /* noDictID*/ };
747 ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
748 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize, 1 /*byRef*/, ZSTD_dm_auto, cParams, ZSTD_defaultCMem);
749 cSize = ZSTD_compress_usingCDict_advanced(cctx, compressedBuffer, compressedBufferSize,
750 CNBuffer, CNBuffSize, cdict, fParams);
751 ZSTD_freeCDict(cdict);
752 if (ZSTD_isError(cSize)) goto _output_error;
754 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
756 DISPLAYLEVEL(4, "test%3i : try retrieving contentSize from frame : ", testNb++);
757 { U64 const contentSize = ZSTD_getFrameContentSize(compressedBuffer, cSize);
758 if (contentSize != ZSTD_CONTENTSIZE_UNKNOWN) goto _output_error;
760 DISPLAYLEVEL(4, "OK (unknown)\n");
762 DISPLAYLEVEL(4, "test%3i : frame built without dictID should be decompressible : ", testNb++);
763 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
764 decodedBuffer, CNBuffSize,
765 compressedBuffer, cSize,
766 dictBuffer, dictSize),
767 if (r != CNBuffSize) goto _output_error);
768 DISPLAYLEVEL(4, "OK \n");
770 DISPLAYLEVEL(4, "test%3i : ZSTD_compress_advanced, no dictID : ", testNb++);
771 { ZSTD_parameters p = ZSTD_getParams(3, CNBuffSize, dictSize);
772 p.fParams.noDictIDFlag = 1;
773 cSize = ZSTD_compress_advanced(cctx, compressedBuffer, compressedBufferSize,
774 CNBuffer, CNBuffSize,
775 dictBuffer, dictSize, p);
776 if (ZSTD_isError(cSize)) goto _output_error;
778 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/CNBuffSize*100);
780 DISPLAYLEVEL(4, "test%3i : frame built without dictID should be decompressible : ", testNb++);
781 CHECKPLUS(r, ZSTD_decompress_usingDict(dctx,
782 decodedBuffer, CNBuffSize,
783 compressedBuffer, cSize,
784 dictBuffer, dictSize),
785 if (r != CNBuffSize) goto _output_error);
786 DISPLAYLEVEL(4, "OK \n");
788 DISPLAYLEVEL(4, "test%3i : dictionary containing only header should return error : ", testNb++);
790 const size_t ret = ZSTD_decompress_usingDict(
791 dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize,
792 "\x37\xa4\x30\xec\x11\x22\x33\x44", 8);
793 if (ZSTD_getErrorCode(ret) != ZSTD_error_dictionary_corrupted) goto _output_error;
795 DISPLAYLEVEL(4, "OK \n");
797 DISPLAYLEVEL(4, "test%3i : Building cdict w/ ZSTD_dm_fullDict on a good dictionary : ", testNb++);
798 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
799 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced(dictBuffer, dictSize, 1 /*byRef*/, ZSTD_dm_fullDict, cParams, ZSTD_defaultCMem);
800 if (cdict==NULL) goto _output_error;
801 ZSTD_freeCDict(cdict);
803 DISPLAYLEVEL(4, "OK \n");
805 DISPLAYLEVEL(4, "test%3i : Building cdict w/ ZSTD_dm_fullDict on a rawContent (must fail) : ", testNb++);
806 { ZSTD_compressionParameters const cParams = ZSTD_getCParams(1, CNBuffSize, dictSize);
807 ZSTD_CDict* const cdict = ZSTD_createCDict_advanced((const char*)dictBuffer+1, dictSize-1, 1 /*byRef*/, ZSTD_dm_fullDict, cParams, ZSTD_defaultCMem);
808 if (cdict!=NULL) goto _output_error;
809 ZSTD_freeCDict(cdict);
811 DISPLAYLEVEL(4, "OK \n");
818 /* COVER dictionary builder tests */
819 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
820 size_t dictSize = 16 KB;
821 size_t optDictSize = dictSize;
822 void* dictBuffer = malloc(dictSize);
823 size_t const totalSampleSize = 1 MB;
824 size_t const sampleUnitSize = 8 KB;
825 U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
826 size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
827 ZDICT_cover_params_t params;
830 if (dictBuffer==NULL || samplesSizes==NULL) {
836 DISPLAYLEVEL(4, "test%3i : ZDICT_trainFromBuffer_cover : ", testNb++);
837 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
838 memset(¶ms, 0, sizeof(params));
839 params.d = 1 + (FUZ_rand(&seed) % 16);
840 params.k = params.d + (FUZ_rand(&seed) % 256);
841 dictSize = ZDICT_trainFromBuffer_cover(dictBuffer, dictSize,
842 CNBuffer, samplesSizes, nbSamples,
844 if (ZDICT_isError(dictSize)) goto _output_error;
845 DISPLAYLEVEL(4, "OK, created dictionary of size %u \n", (U32)dictSize);
847 DISPLAYLEVEL(4, "test%3i : check dictID : ", testNb++);
848 dictID = ZDICT_getDictID(dictBuffer, dictSize);
849 if (dictID==0) goto _output_error;
850 DISPLAYLEVEL(4, "OK : %u \n", dictID);
852 DISPLAYLEVEL(4, "test%3i : ZDICT_optimizeTrainFromBuffer_cover : ", testNb++);
853 memset(¶ms, 0, sizeof(params));
855 optDictSize = ZDICT_optimizeTrainFromBuffer_cover(dictBuffer, optDictSize,
856 CNBuffer, samplesSizes,
857 nbSamples / 4, ¶ms);
858 if (ZDICT_isError(optDictSize)) goto _output_error;
859 DISPLAYLEVEL(4, "OK, created dictionary of size %u \n", (U32)optDictSize);
861 DISPLAYLEVEL(4, "test%3i : check dictID : ", testNb++);
862 dictID = ZDICT_getDictID(dictBuffer, optDictSize);
863 if (dictID==0) goto _output_error;
864 DISPLAYLEVEL(4, "OK : %u \n", dictID);
871 /* Decompression defense tests */
872 DISPLAYLEVEL(4, "test%3i : Check input length for magic number : ", testNb++);
873 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, CNBuffer, 3); /* too small input */
874 if (!ZSTD_isError(r)) goto _output_error;
875 if (ZSTD_getErrorCode(r) != ZSTD_error_srcSize_wrong) goto _output_error; }
876 DISPLAYLEVEL(4, "OK \n");
878 DISPLAYLEVEL(4, "test%3i : Check magic Number : ", testNb++);
879 ((char*)(CNBuffer))[0] = 1;
880 { size_t const r = ZSTD_decompress(decodedBuffer, CNBuffSize, CNBuffer, 4);
881 if (!ZSTD_isError(r)) goto _output_error; }
882 DISPLAYLEVEL(4, "OK \n");
884 /* content size verification test */
885 DISPLAYLEVEL(4, "test%3i : Content size verification : ", testNb++);
886 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
887 size_t const srcSize = 5000;
888 size_t const wrongSrcSize = (srcSize + 1000);
889 ZSTD_parameters params = ZSTD_getParams(1, wrongSrcSize, 0);
890 params.fParams.contentSizeFlag = 1;
891 CHECK( ZSTD_compressBegin_advanced(cctx, NULL, 0, params, wrongSrcSize) );
892 { size_t const result = ZSTD_compressEnd(cctx, decodedBuffer, CNBuffSize, CNBuffer, srcSize);
893 if (!ZSTD_isError(result)) goto _output_error;
894 if (ZSTD_getErrorCode(result) != ZSTD_error_srcSize_wrong) goto _output_error;
895 DISPLAYLEVEL(4, "OK : %s \n", ZSTD_getErrorName(result));
900 /* block API tests */
901 { ZSTD_CCtx* const cctx = ZSTD_createCCtx();
902 static const size_t dictSize = 65 KB;
903 static const size_t blockSize = 100 KB; /* won't cause pb with small dict size */
906 /* basic block compression */
907 DISPLAYLEVEL(4, "test%3i : Block compression test : ", testNb++);
908 CHECK( ZSTD_compressBegin(cctx, 5) );
909 CHECK( ZSTD_getBlockSize(cctx) >= blockSize);
910 cSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), CNBuffer, blockSize);
911 if (ZSTD_isError(cSize)) goto _output_error;
912 DISPLAYLEVEL(4, "OK \n");
914 DISPLAYLEVEL(4, "test%3i : Block decompression test : ", testNb++);
915 CHECK( ZSTD_decompressBegin(dctx) );
916 { CHECK_V(r, ZSTD_decompressBlock(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
917 if (r != blockSize) goto _output_error; }
918 DISPLAYLEVEL(4, "OK \n");
920 /* dictionary block compression */
921 DISPLAYLEVEL(4, "test%3i : Dictionary Block compression test : ", testNb++);
922 CHECK( ZSTD_compressBegin_usingDict(cctx, CNBuffer, dictSize, 5) );
923 cSize = ZSTD_compressBlock(cctx, compressedBuffer, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize, blockSize);
924 if (ZSTD_isError(cSize)) goto _output_error;
925 cSize2 = ZSTD_compressBlock(cctx, (char*)compressedBuffer+cSize, ZSTD_compressBound(blockSize), (char*)CNBuffer+dictSize+blockSize, blockSize);
926 if (ZSTD_isError(cSize2)) goto _output_error;
927 memcpy((char*)compressedBuffer+cSize, (char*)CNBuffer+dictSize+blockSize, blockSize); /* fake non-compressed block */
928 cSize2 = ZSTD_compressBlock(cctx, (char*)compressedBuffer+cSize+blockSize, ZSTD_compressBound(blockSize),
929 (char*)CNBuffer+dictSize+2*blockSize, blockSize);
930 if (ZSTD_isError(cSize2)) goto _output_error;
931 DISPLAYLEVEL(4, "OK \n");
933 DISPLAYLEVEL(4, "test%3i : Dictionary Block decompression test : ", testNb++);
934 CHECK( ZSTD_decompressBegin_usingDict(dctx, CNBuffer, dictSize) );
935 { CHECK_V( r, ZSTD_decompressBlock(dctx, decodedBuffer, CNBuffSize, compressedBuffer, cSize) );
936 if (r != blockSize) goto _output_error; }
937 ZSTD_insertBlock(dctx, (char*)decodedBuffer+blockSize, blockSize); /* insert non-compressed block into dctx history */
938 { CHECK_V( r, ZSTD_decompressBlock(dctx, (char*)decodedBuffer+2*blockSize, CNBuffSize, (char*)compressedBuffer+cSize+blockSize, cSize2) );
939 if (r != blockSize) goto _output_error; }
940 DISPLAYLEVEL(4, "OK \n");
947 { size_t sampleSize = 0;
948 DISPLAYLEVEL(4, "test%3i : Long RLE test : ", testNb++);
949 RDG_genBuffer(CNBuffer, sampleSize, compressibility, 0., seed+1);
950 memset((char*)CNBuffer+sampleSize, 'B', 256 KB - 1);
951 sampleSize += 256 KB - 1;
952 RDG_genBuffer((char*)CNBuffer+sampleSize, 96 KB, compressibility, 0., seed+2);
954 cSize = ZSTD_compress(compressedBuffer, ZSTD_compressBound(sampleSize), CNBuffer, sampleSize, 1);
955 if (ZSTD_isError(cSize)) goto _output_error;
956 { CHECK_V(regenSize, ZSTD_decompress(decodedBuffer, sampleSize, compressedBuffer, cSize));
957 if (regenSize!=sampleSize) goto _output_error; }
958 DISPLAYLEVEL(4, "OK \n");
961 /* All zeroes test (test bug #137) */
962 #define ZEROESLENGTH 100
963 DISPLAYLEVEL(4, "test%3i : compress %u zeroes : ", testNb++, ZEROESLENGTH);
964 memset(CNBuffer, 0, ZEROESLENGTH);
965 { CHECK_V(r, ZSTD_compress(compressedBuffer, ZSTD_compressBound(ZEROESLENGTH), CNBuffer, ZEROESLENGTH, 1) );
967 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/ZEROESLENGTH*100);
969 DISPLAYLEVEL(4, "test%3i : decompress %u zeroes : ", testNb++, ZEROESLENGTH);
970 { CHECK_V(r, ZSTD_decompress(decodedBuffer, ZEROESLENGTH, compressedBuffer, cSize) );
971 if (r != ZEROESLENGTH) goto _output_error; }
972 DISPLAYLEVEL(4, "OK \n");
974 /* nbSeq limit test */
975 #define _3BYTESTESTLENGTH 131000
976 #define NB3BYTESSEQLOG 9
977 #define NB3BYTESSEQ (1 << NB3BYTESSEQLOG)
978 #define NB3BYTESSEQMASK (NB3BYTESSEQ-1)
979 /* creates a buffer full of 3-bytes sequences */
980 { BYTE _3BytesSeqs[NB3BYTESSEQ][3];
983 /* create batch of 3-bytes sequences */
985 for (i=0; i < NB3BYTESSEQ; i++) {
986 _3BytesSeqs[i][0] = (BYTE)(FUZ_rand(&rSeed) & 255);
987 _3BytesSeqs[i][1] = (BYTE)(FUZ_rand(&rSeed) & 255);
988 _3BytesSeqs[i][2] = (BYTE)(FUZ_rand(&rSeed) & 255);
991 /* randomly fills CNBuffer with prepared 3-bytes sequences */
993 for (i=0; i < _3BYTESTESTLENGTH; i += 3) { /* note : CNBuffer size > _3BYTESTESTLENGTH+3 */
994 U32 const id = FUZ_rand(&rSeed) & NB3BYTESSEQMASK;
995 ((BYTE*)CNBuffer)[i+0] = _3BytesSeqs[id][0];
996 ((BYTE*)CNBuffer)[i+1] = _3BytesSeqs[id][1];
997 ((BYTE*)CNBuffer)[i+2] = _3BytesSeqs[id][2];
999 DISPLAYLEVEL(4, "test%3i : compress lots 3-bytes sequences : ", testNb++);
1000 { CHECK_V(r, ZSTD_compress(compressedBuffer, ZSTD_compressBound(_3BYTESTESTLENGTH),
1001 CNBuffer, _3BYTESTESTLENGTH, 19) );
1003 DISPLAYLEVEL(4, "OK (%u bytes : %.2f%%)\n", (U32)cSize, (double)cSize/_3BYTESTESTLENGTH*100);
1005 DISPLAYLEVEL(4, "test%3i : decompress lots 3-bytes sequence : ", testNb++);
1006 { CHECK_V(r, ZSTD_decompress(decodedBuffer, _3BYTESTESTLENGTH, compressedBuffer, cSize) );
1007 if (r != _3BYTESTESTLENGTH) goto _output_error; }
1008 DISPLAYLEVEL(4, "OK \n");
1010 DISPLAYLEVEL(4, "test%3i : incompressible data and ill suited dictionary : ", testNb++);
1011 RDG_genBuffer(CNBuffer, CNBuffSize, 0.0, 0.1, seed);
1012 { /* Train a dictionary on low characters */
1013 size_t dictSize = 16 KB;
1014 void* const dictBuffer = malloc(dictSize);
1015 size_t const totalSampleSize = 1 MB;
1016 size_t const sampleUnitSize = 8 KB;
1017 U32 const nbSamples = (U32)(totalSampleSize / sampleUnitSize);
1018 size_t* const samplesSizes = (size_t*) malloc(nbSamples * sizeof(size_t));
1019 if (!dictBuffer || !samplesSizes) goto _output_error;
1020 { U32 u; for (u=0; u<nbSamples; u++) samplesSizes[u] = sampleUnitSize; }
1021 dictSize = ZDICT_trainFromBuffer(dictBuffer, dictSize, CNBuffer, samplesSizes, nbSamples);
1022 if (ZDICT_isError(dictSize)) goto _output_error;
1023 /* Reverse the characters to make the dictionary ill suited */
1025 for (u = 0; u < CNBuffSize; ++u) {
1026 ((BYTE*)CNBuffer)[u] = 255 - ((BYTE*)CNBuffer)[u];
1029 { /* Compress the data */
1030 size_t const inputSize = 500;
1031 size_t const outputSize = ZSTD_compressBound(inputSize);
1032 void* const outputBuffer = malloc(outputSize);
1033 ZSTD_CCtx* const cctx = ZSTD_createCCtx();
1034 if (!outputBuffer || !cctx) goto _output_error;
1035 CHECK(ZSTD_compress_usingDict(cctx, outputBuffer, outputSize, CNBuffer, inputSize, dictBuffer, dictSize, 1));
1037 ZSTD_freeCCtx(cctx);
1043 DISPLAYLEVEL(4, "OK \n");
1046 /* findFrameCompressedSize on skippable frames */
1047 DISPLAYLEVEL(4, "test%3i : frame compressed size of skippable frame : ", testNb++);
1048 { const char* frame = "\x50\x2a\x4d\x18\x05\x0\x0\0abcde";
1049 size_t const frameSrcSize = 13;
1050 if (ZSTD_findFrameCompressedSize(frame, frameSrcSize) != frameSrcSize) goto _output_error; }
1051 DISPLAYLEVEL(4, "OK \n");
1053 /* error string tests */
1054 DISPLAYLEVEL(4, "test%3i : testing ZSTD error code strings : ", testNb++);
1055 if (strcmp("No error detected", ZSTD_getErrorName((ZSTD_ErrorCode)(0-ZSTD_error_no_error))) != 0) goto _output_error;
1056 if (strcmp("No error detected", ZSTD_getErrorString(ZSTD_error_no_error)) != 0) goto _output_error;
1057 if (strcmp("Unspecified error code", ZSTD_getErrorString((ZSTD_ErrorCode)(0-ZSTD_error_GENERIC))) != 0) goto _output_error;
1058 if (strcmp("Error (generic)", ZSTD_getErrorName((size_t)0-ZSTD_error_GENERIC)) != 0) goto _output_error;
1059 if (strcmp("Error (generic)", ZSTD_getErrorString(ZSTD_error_GENERIC)) != 0) goto _output_error;
1060 if (strcmp("No error detected", ZSTD_getErrorName(ZSTD_error_GENERIC)) != 0) goto _output_error;
1061 DISPLAYLEVEL(4, "OK \n");
1065 free(compressedBuffer);
1066 free(decodedBuffer);
1071 DISPLAY("Error detected in Unit tests ! \n");
1076 static size_t findDiff(const void* buf1, const void* buf2, size_t max)
1078 const BYTE* b1 = (const BYTE*)buf1;
1079 const BYTE* b2 = (const BYTE*)buf2;
1081 for (u=0; u<max; u++) {
1082 if (b1[u] != b2[u]) break;
1088 static ZSTD_parameters FUZ_makeParams(ZSTD_compressionParameters cParams, ZSTD_frameParameters fParams)
1090 ZSTD_parameters params;
1091 params.cParams = cParams;
1092 params.fParams = fParams;
1096 static size_t FUZ_rLogLength(U32* seed, U32 logLength)
1098 size_t const lengthMask = ((size_t)1 << logLength) - 1;
1099 return (lengthMask+1) + (FUZ_rand(seed) & lengthMask);
1102 static size_t FUZ_randomLength(U32* seed, U32 maxLog)
1104 U32 const logLength = FUZ_rand(seed) % maxLog;
1105 return FUZ_rLogLength(seed, logLength);
1109 #define CHECK(cond, ...) { \
1111 DISPLAY("Error => "); \
1112 DISPLAY(__VA_ARGS__); \
1113 DISPLAY(" (seed %u, test nb %u) \n", seed, testNb); \
1114 goto _output_error; \
1118 #define CHECK_Z(f) { \
1119 size_t const err = f; \
1120 if (ZSTD_isError(err)) { \
1121 DISPLAY("Error => %s : %s ", \
1122 #f, ZSTD_getErrorName(err)); \
1123 DISPLAY(" (seed %u, test nb %u) \n", seed, testNb); \
1124 goto _output_error; \
1128 static int fuzzerTests(U32 seed, U32 nbTests, unsigned startTest, U32 const maxDurationS, double compressibility, int bigTests)
1130 static const U32 maxSrcLog = 23;
1131 static const U32 maxSampleLog = 22;
1132 size_t const srcBufferSize = (size_t)1<<maxSrcLog;
1133 size_t const dstBufferSize = (size_t)1<<maxSampleLog;
1134 size_t const cBufferSize = ZSTD_compressBound(dstBufferSize);
1135 BYTE* cNoiseBuffer[5];
1136 BYTE* srcBuffer; /* jumping pointer */
1137 BYTE* const cBuffer = (BYTE*) malloc (cBufferSize);
1138 BYTE* const dstBuffer = (BYTE*) malloc (dstBufferSize);
1139 BYTE* const mirrorBuffer = (BYTE*) malloc (dstBufferSize);
1140 ZSTD_CCtx* const refCtx = ZSTD_createCCtx();
1141 ZSTD_CCtx* const ctx = ZSTD_createCCtx();
1142 ZSTD_DCtx* const dctx = ZSTD_createDCtx();
1145 U32 coreSeed = seed, lseed = 0;
1146 clock_t const startClock = clock();
1147 clock_t const maxClockSpan = maxDurationS * CLOCKS_PER_SEC;
1148 int const cLevelLimiter = bigTests ? 3 : 2;
1151 cNoiseBuffer[0] = (BYTE*)malloc (srcBufferSize);
1152 cNoiseBuffer[1] = (BYTE*)malloc (srcBufferSize);
1153 cNoiseBuffer[2] = (BYTE*)malloc (srcBufferSize);
1154 cNoiseBuffer[3] = (BYTE*)malloc (srcBufferSize);
1155 cNoiseBuffer[4] = (BYTE*)malloc (srcBufferSize);
1156 CHECK (!cNoiseBuffer[0] || !cNoiseBuffer[1] || !cNoiseBuffer[2] || !cNoiseBuffer[3] || !cNoiseBuffer[4]
1157 || !dstBuffer || !mirrorBuffer || !cBuffer || !refCtx || !ctx || !dctx,
1158 "Not enough memory, fuzzer tests cancelled");
1160 /* Create initial samples */
1161 RDG_genBuffer(cNoiseBuffer[0], srcBufferSize, 0.00, 0., coreSeed); /* pure noise */
1162 RDG_genBuffer(cNoiseBuffer[1], srcBufferSize, 0.05, 0., coreSeed); /* barely compressible */
1163 RDG_genBuffer(cNoiseBuffer[2], srcBufferSize, compressibility, 0., coreSeed);
1164 RDG_genBuffer(cNoiseBuffer[3], srcBufferSize, 0.95, 0., coreSeed); /* highly compressible */
1165 RDG_genBuffer(cNoiseBuffer[4], srcBufferSize, 1.00, 0., coreSeed); /* sparse content */
1166 srcBuffer = cNoiseBuffer[2];
1168 /* catch up testNb */
1169 for (testNb=1; testNb < startTest; testNb++) FUZ_rand(&coreSeed);
1171 /* main test loop */
1172 for ( ; (testNb <= nbTests) || (FUZ_clockSpan(startClock) < maxClockSpan); testNb++ ) {
1173 size_t sampleSize, maxTestSize, totalTestSize;
1174 size_t cSize, totalCSize, totalGenSize;
1181 if (nbTests >= testNb) { DISPLAYUPDATE(2, "\r%6u/%6u ", testNb, nbTests); }
1182 else { DISPLAYUPDATE(2, "\r%6u ", testNb); }
1184 FUZ_rand(&coreSeed);
1185 { U32 const prime1 = 2654435761U; lseed = coreSeed ^ prime1; }
1187 /* srcBuffer selection [0-4] */
1188 { U32 buffNb = FUZ_rand(&lseed) & 0x7F;
1189 if (buffNb & 7) buffNb=2; /* most common : compressible (P) */
1193 const U32 tnb[2] = { 1, 3 }; /* barely/highly compressible */
1194 buffNb = tnb[buffNb >> 3];
1196 const U32 tnb[2] = { 0, 4 }; /* not compressible / sparse */
1197 buffNb = tnb[buffNb >> 3];
1199 srcBuffer = cNoiseBuffer[buffNb];
1202 /* select src segment */
1203 sampleSize = FUZ_randomLength(&lseed, maxSampleLog);
1205 /* create sample buffer (to catch read error with valgrind & sanitizers) */
1206 sampleBuffer = (BYTE*)malloc(sampleSize);
1207 CHECK(sampleBuffer==NULL, "not enough memory for sample buffer");
1208 { size_t const sampleStart = FUZ_rand(&lseed) % (srcBufferSize - sampleSize);
1209 memcpy(sampleBuffer, srcBuffer + sampleStart, sampleSize); }
1210 crcOrig = XXH64(sampleBuffer, sampleSize, 0);
1212 /* compression tests */
1213 { unsigned const cLevel =
1214 ( FUZ_rand(&lseed) %
1215 (ZSTD_maxCLevel() - (FUZ_highbit32((U32)sampleSize) / cLevelLimiter)) )
1217 cSize = ZSTD_compressCCtx(ctx, cBuffer, cBufferSize, sampleBuffer, sampleSize, cLevel);
1218 CHECK(ZSTD_isError(cSize), "ZSTD_compressCCtx failed : %s", ZSTD_getErrorName(cSize));
1220 /* compression failure test : too small dest buffer */
1222 const size_t missing = (FUZ_rand(&lseed) % (cSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
1223 const size_t tooSmallSize = cSize - missing;
1224 const U32 endMark = 0x4DC2B1A9;
1225 memcpy(dstBuffer+tooSmallSize, &endMark, 4);
1226 { size_t const errorCode = ZSTD_compressCCtx(ctx, dstBuffer, tooSmallSize, sampleBuffer, sampleSize, cLevel);
1227 CHECK(!ZSTD_isError(errorCode), "ZSTD_compressCCtx should have failed ! (buffer too small : %u < %u)", (U32)tooSmallSize, (U32)cSize); }
1228 { U32 endCheck; memcpy(&endCheck, dstBuffer+tooSmallSize, 4);
1229 CHECK(endCheck != endMark, "ZSTD_compressCCtx : dst buffer overflow"); }
1232 /* frame header decompression test */
1233 { ZSTD_frameHeader zfh;
1234 CHECK_Z( ZSTD_getFrameHeader(&zfh, cBuffer, cSize) );
1235 CHECK(zfh.frameContentSize != sampleSize, "Frame content size incorrect");
1238 /* Decompressed size test */
1239 { unsigned long long const rSize = ZSTD_findDecompressedSize(cBuffer, cSize);
1240 CHECK(rSize != sampleSize, "decompressed size incorrect");
1243 /* successful decompression test */
1244 { size_t const margin = (FUZ_rand(&lseed) & 1) ? 0 : (FUZ_rand(&lseed) & 31) + 1;
1245 size_t const dSize = ZSTD_decompress(dstBuffer, sampleSize + margin, cBuffer, cSize);
1246 CHECK(dSize != sampleSize, "ZSTD_decompress failed (%s) (srcSize : %u ; cSize : %u)", ZSTD_getErrorName(dSize), (U32)sampleSize, (U32)cSize);
1247 { U64 const crcDest = XXH64(dstBuffer, sampleSize, 0);
1248 CHECK(crcOrig != crcDest, "decompression result corrupted (pos %u / %u)", (U32)findDiff(sampleBuffer, dstBuffer, sampleSize), (U32)sampleSize);
1251 free(sampleBuffer); /* no longer useful after this point */
1253 /* truncated src decompression test */
1254 { size_t const missing = (FUZ_rand(&lseed) % (cSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
1255 size_t const tooSmallSize = cSize - missing;
1256 void* cBufferTooSmall = malloc(tooSmallSize); /* valgrind will catch read overflows */
1257 CHECK(cBufferTooSmall == NULL, "not enough memory !");
1258 memcpy(cBufferTooSmall, cBuffer, tooSmallSize);
1259 { size_t const errorCode = ZSTD_decompress(dstBuffer, dstBufferSize, cBufferTooSmall, tooSmallSize);
1260 CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed ! (truncated src buffer)"); }
1261 free(cBufferTooSmall);
1264 /* too small dst decompression test */
1265 if (sampleSize > 3) {
1266 size_t const missing = (FUZ_rand(&lseed) % (sampleSize-2)) + 1; /* no problem, as cSize > 4 (frameHeaderSizer) */
1267 size_t const tooSmallSize = sampleSize - missing;
1268 static const BYTE token = 0xA9;
1269 dstBuffer[tooSmallSize] = token;
1270 { size_t const errorCode = ZSTD_decompress(dstBuffer, tooSmallSize, cBuffer, cSize);
1271 CHECK(!ZSTD_isError(errorCode), "ZSTD_decompress should have failed : %u > %u (dst buffer too small)", (U32)errorCode, (U32)tooSmallSize); }
1272 CHECK(dstBuffer[tooSmallSize] != token, "ZSTD_decompress : dst buffer overflow");
1275 /* noisy src decompression test */
1277 /* insert noise into src */
1278 { U32 const maxNbBits = FUZ_highbit32((U32)(cSize-4));
1279 size_t pos = 4; /* preserve magic number (too easy to detect) */
1281 /* keep some original src */
1282 { U32 const nbBits = FUZ_rand(&lseed) % maxNbBits;
1283 size_t const mask = (1<<nbBits) - 1;
1284 size_t const skipLength = FUZ_rand(&lseed) & mask;
1287 if (pos <= cSize) break;
1289 { U32 const nbBitsCodes = FUZ_rand(&lseed) % maxNbBits;
1290 U32 const nbBits = nbBitsCodes ? nbBitsCodes-1 : 0;
1291 size_t const mask = (1<<nbBits) - 1;
1292 size_t const rNoiseLength = (FUZ_rand(&lseed) & mask) + 1;
1293 size_t const noiseLength = MIN(rNoiseLength, cSize-pos);
1294 size_t const noiseStart = FUZ_rand(&lseed) % (srcBufferSize - noiseLength);
1295 memcpy(cBuffer + pos, srcBuffer + noiseStart, noiseLength);
1299 /* decompress noisy source */
1300 { U32 const endMark = 0xA9B1C3D6;
1301 memcpy(dstBuffer+sampleSize, &endMark, 4);
1302 { size_t const decompressResult = ZSTD_decompress(dstBuffer, sampleSize, cBuffer, cSize);
1303 /* result *may* be an unlikely success, but even then, it must strictly respect dst buffer boundaries */
1304 CHECK((!ZSTD_isError(decompressResult)) && (decompressResult>sampleSize),
1305 "ZSTD_decompress on noisy src : result is too large : %u > %u (dst buffer)", (U32)decompressResult, (U32)sampleSize);
1307 { U32 endCheck; memcpy(&endCheck, dstBuffer+sampleSize, 4);
1308 CHECK(endMark!=endCheck, "ZSTD_decompress on noisy src : dst buffer overflow");
1309 } } } /* noisy src decompression test */
1311 /*===== Streaming compression test, scattered segments and dictionary =====*/
1313 { U32 const testLog = FUZ_rand(&lseed) % maxSrcLog;
1314 U32 const dictLog = FUZ_rand(&lseed) % maxSrcLog;
1315 int const cLevel = (FUZ_rand(&lseed) %
1317 (MAX(testLog, dictLog) / cLevelLimiter))) +
1319 maxTestSize = FUZ_rLogLength(&lseed, testLog);
1320 if (maxTestSize >= dstBufferSize) maxTestSize = dstBufferSize-1;
1322 dictSize = FUZ_rLogLength(&lseed, dictLog); /* needed also for decompression */
1323 dict = srcBuffer + (FUZ_rand(&lseed) % (srcBufferSize - dictSize));
1325 if (FUZ_rand(&lseed) & 0xF) {
1326 CHECK_Z ( ZSTD_compressBegin_usingDict(refCtx, dict, dictSize, cLevel) );
1328 ZSTD_compressionParameters const cPar = ZSTD_getCParams(cLevel, 0, dictSize);
1329 ZSTD_frameParameters const fPar = { FUZ_rand(&lseed)&1 /* contentSizeFlag */,
1330 !(FUZ_rand(&lseed)&3) /* contentChecksumFlag*/,
1331 0 /*NodictID*/ }; /* note : since dictionary is fake, dictIDflag has no impact */
1332 ZSTD_parameters const p = FUZ_makeParams(cPar, fPar);
1333 CHECK_Z ( ZSTD_compressBegin_advanced(refCtx, dict, dictSize, p, 0) );
1335 CHECK_Z( ZSTD_copyCCtx(ctx, refCtx, 0) );
1337 ZSTD_setCCtxParameter(ctx, ZSTD_p_forceWindow, FUZ_rand(&lseed) & 1);
1339 { U32 const nbChunks = (FUZ_rand(&lseed) & 127) + 2;
1341 XXH64_state_t xxhState;
1342 XXH64_reset(&xxhState, 0);
1343 for (totalTestSize=0, cSize=0, n=0 ; n<nbChunks ; n++) {
1344 size_t const segmentSize = FUZ_randomLength(&lseed, maxSampleLog);
1345 size_t const segmentStart = FUZ_rand(&lseed) % (srcBufferSize - segmentSize);
1347 if (cBufferSize-cSize < ZSTD_compressBound(segmentSize)) break; /* avoid invalid dstBufferTooSmall */
1348 if (totalTestSize+segmentSize > maxTestSize) break;
1350 { size_t const compressResult = ZSTD_compressContinue(ctx, cBuffer+cSize, cBufferSize-cSize, srcBuffer+segmentStart, segmentSize);
1351 CHECK (ZSTD_isError(compressResult), "multi-segments compression error : %s", ZSTD_getErrorName(compressResult));
1352 cSize += compressResult;
1354 XXH64_update(&xxhState, srcBuffer+segmentStart, segmentSize);
1355 memcpy(mirrorBuffer + totalTestSize, srcBuffer+segmentStart, segmentSize);
1356 totalTestSize += segmentSize;
1359 { size_t const flushResult = ZSTD_compressEnd(ctx, cBuffer+cSize, cBufferSize-cSize, NULL, 0);
1360 CHECK (ZSTD_isError(flushResult), "multi-segments epilogue error : %s", ZSTD_getErrorName(flushResult));
1361 cSize += flushResult;
1363 crcOrig = XXH64_digest(&xxhState);
1366 /* streaming decompression test */
1367 if (dictSize<8) dictSize=0, dict=NULL; /* disable dictionary */
1368 CHECK_Z( ZSTD_decompressBegin_usingDict(dctx, dict, dictSize) );
1371 while (totalCSize < cSize) {
1372 size_t const inSize = ZSTD_nextSrcSizeToDecompress(dctx);
1373 size_t const genSize = ZSTD_decompressContinue(dctx, dstBuffer+totalGenSize, dstBufferSize-totalGenSize, cBuffer+totalCSize, inSize);
1374 CHECK (ZSTD_isError(genSize), "ZSTD_decompressContinue error : %s", ZSTD_getErrorName(genSize));
1375 totalGenSize += genSize;
1376 totalCSize += inSize;
1378 CHECK (ZSTD_nextSrcSizeToDecompress(dctx) != 0, "frame not fully decoded");
1379 CHECK (totalGenSize != totalTestSize, "streaming decompressed data : wrong size")
1380 CHECK (totalCSize != cSize, "compressed data should be fully read")
1381 { U64 const crcDest = XXH64(dstBuffer, totalTestSize, 0);
1382 if (crcDest!=crcOrig) {
1383 size_t const errorPos = findDiff(mirrorBuffer, dstBuffer, totalTestSize);
1384 CHECK (1, "streaming decompressed data corrupted : byte %u / %u (%02X!=%02X)",
1385 (U32)errorPos, (U32)totalTestSize, dstBuffer[errorPos], mirrorBuffer[errorPos]);
1387 } /* for ( ; (testNb <= nbTests) */
1388 DISPLAY("\r%u fuzzer tests completed \n", testNb-1);
1391 ZSTD_freeCCtx(refCtx);
1393 ZSTD_freeDCtx(dctx);
1394 free(cNoiseBuffer[0]);
1395 free(cNoiseBuffer[1]);
1396 free(cNoiseBuffer[2]);
1397 free(cNoiseBuffer[3]);
1398 free(cNoiseBuffer[4]);
1410 /*_*******************************************************
1412 *********************************************************/
1413 static int FUZ_usage(const char* programName)
1415 DISPLAY( "Usage :\n");
1416 DISPLAY( " %s [args]\n", programName);
1418 DISPLAY( "Arguments :\n");
1419 DISPLAY( " -i# : Nb of tests (default:%u) \n", nbTestsDefault);
1420 DISPLAY( " -s# : Select seed (default:prompt user)\n");
1421 DISPLAY( " -t# : Select starting test number (default:0)\n");
1422 DISPLAY( " -P# : Select compressibility in %% (default:%u%%)\n", FUZ_compressibility_default);
1423 DISPLAY( " -v : verbose\n");
1424 DISPLAY( " -p : pause at the end\n");
1425 DISPLAY( " -h : display help and exit\n");
1429 /*! readU32FromChar() :
1430 @return : unsigned integer value read from input in `char` format
1431 allows and interprets K, KB, KiB, M, MB and MiB suffix.
1432 Will also modify `*stringPtr`, advancing it to position where it stopped reading.
1433 Note : function result can overflow if digit string > MAX_UINT */
1434 static unsigned readU32FromChar(const char** stringPtr)
1436 unsigned result = 0;
1437 while ((**stringPtr >='0') && (**stringPtr <='9'))
1438 result *= 10, result += **stringPtr - '0', (*stringPtr)++ ;
1439 if ((**stringPtr=='K') || (**stringPtr=='M')) {
1441 if (**stringPtr=='M') result <<= 10;
1443 if (**stringPtr=='i') (*stringPtr)++;
1444 if (**stringPtr=='B') (*stringPtr)++;
1449 /** longCommandWArg() :
1450 * check if *stringPtr is the same as longCommand.
1451 * If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
1452 * @return 0 and doesn't modify *stringPtr otherwise.
1454 static unsigned longCommandWArg(const char** stringPtr, const char* longCommand)
1456 size_t const comSize = strlen(longCommand);
1457 int const result = !strncmp(*stringPtr, longCommand, comSize);
1458 if (result) *stringPtr += comSize;
1462 int main(int argc, const char** argv)
1467 int nbTests = nbTestsDefault;
1469 U32 proba = FUZ_compressibility_default;
1472 U32 maxDuration = 0;
1474 U32 memTestsOnly = 0;
1475 const char* const programName = argv[0];
1477 /* Check command line */
1478 for (argNb=1; argNb<argc; argNb++) {
1479 const char* argument = argv[argNb];
1480 if(!argument) continue; /* Protection if argument empty */
1482 /* Handle commands. Aggregated commands are allowed */
1483 if (argument[0]=='-') {
1485 if (longCommandWArg(&argument, "--memtest=")) { memTestsOnly = readU32FromChar(&argument); continue; }
1487 if (!strcmp(argument, "--memtest")) { memTestsOnly=1; continue; }
1488 if (!strcmp(argument, "--no-big-tests")) { bigTests=0; continue; }
1491 while (*argument!=0) {
1495 return FUZ_usage(programName);
1507 case 'p': /* pause at the end */
1513 argument++; maxDuration = 0;
1514 nbTests = readU32FromChar(&argument);
1520 maxDuration = readU32FromChar(&argument);
1521 if (*argument=='s') argument++; /* seconds */
1522 if (*argument=='m') maxDuration *= 60, argument++; /* minutes */
1523 if (*argument=='n') argument++;
1529 seed = readU32FromChar(&argument);
1534 testNb = readU32FromChar(&argument);
1537 case 'P': /* compressibility % */
1539 proba = readU32FromChar(&argument);
1540 if (proba>100) proba = 100;
1544 return (FUZ_usage(programName), 1);
1545 } } } } /* for (argNb=1; argNb<argc; argNb++) */
1548 DISPLAY("Starting zstd tester (%i-bits, %s)\n", (int)(sizeof(size_t)*8), ZSTD_VERSION_STRING);
1551 time_t const t = time(NULL);
1552 U32 const h = XXH32(&t, sizeof(t), 1);
1556 DISPLAY("Seed = %u\n", seed);
1557 if (proba!=FUZ_compressibility_default) DISPLAY("Compressibility : %u%%\n", proba);
1560 g_displayLevel = MAX(3, g_displayLevel);
1561 return FUZ_mallocTests(seed, ((double)proba) / 100, memTestsOnly);
1564 if (nbTests < testNb) nbTests = testNb;
1567 result = basicUnitTests(0, ((double)proba) / 100); /* constant seed for predictability */
1569 result = fuzzerTests(seed, nbTests, testNb, maxDuration, ((double)proba) / 100, bigTests);
1572 DISPLAY("Press Enter \n");