2 * Copyright (c) Meta Platforms, Inc. and affiliates.
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 #ifndef ZSTDCLI_CLEVEL_DEFAULT
16 # define ZSTDCLI_CLEVEL_DEFAULT 3
19 #ifndef ZSTDCLI_CLEVEL_MAX
20 # define ZSTDCLI_CLEVEL_MAX 19 /* without using --ultra */
23 #ifndef ZSTDCLI_NBTHREADS_DEFAULT
24 # define ZSTDCLI_NBTHREADS_DEFAULT 1
27 /*-************************************
29 **************************************/
30 #include "platform.h" /* PLATFORM_POSIX_VERSION */
31 #include "util.h" /* UTIL_HAS_CREATEFILELIST, UTIL_createFileList, UTIL_isConsole */
32 #include <stdlib.h> /* getenv */
33 #include <string.h> /* strcmp, strlen */
34 #include <stdio.h> /* fprintf(), stdin, stdout, stderr */
35 #include <errno.h> /* errno */
36 #include <assert.h> /* assert */
38 #include "fileio.h" /* stdinmark, stdoutmark, ZSTD_EXTENSION */
40 # include "benchzstd.h" /* BMK_benchFilesAdvanced */
43 # include "dibio.h" /* ZDICT_cover_params_t, DiB_trainFromFiles() */
46 # include "zstdcli_trace.h"
48 #include "../lib/zstd.h" /* ZSTD_VERSION_STRING, ZSTD_minCLevel, ZSTD_maxCLevel */
49 #include "fileio_asyncio.h"
52 /*-************************************
54 **************************************/
55 #define COMPRESSOR_NAME "Zstandard CLI"
57 # define ZSTD_VERSION "v" ZSTD_VERSION_STRING
59 #define AUTHOR "Yann Collet"
60 #define WELCOME_MESSAGE "*** %s (%i-bit) %s, by %s ***\n", COMPRESSOR_NAME, (int)(sizeof(size_t)*8), ZSTD_VERSION, AUTHOR
62 #define ZSTD_ZSTDMT "zstdmt"
63 #define ZSTD_UNZSTD "unzstd"
64 #define ZSTD_CAT "zstdcat"
65 #define ZSTD_ZCAT "zcat"
66 #define ZSTD_GZ "gzip"
67 #define ZSTD_GUNZIP "gunzip"
68 #define ZSTD_GZCAT "gzcat"
69 #define ZSTD_LZMA "lzma"
70 #define ZSTD_UNLZMA "unlzma"
72 #define ZSTD_UNXZ "unxz"
73 #define ZSTD_LZ4 "lz4"
74 #define ZSTD_UNLZ4 "unlz4"
80 #define DISPLAY_LEVEL_DEFAULT 2
82 static const char* g_defaultDictName = "dictionary";
83 static const unsigned g_defaultMaxDictSize = 110 KB;
84 static const int g_defaultDictCLevel = 3;
85 static const unsigned g_defaultSelectivityLevel = 9;
86 static const unsigned g_defaultMaxWindowLog = 27;
87 #define OVERLAP_LOG_DEFAULT 9999
88 #define LDM_PARAM_DEFAULT 9999 /* Default for parameters where 0 is valid */
89 static U32 g_overlapLog = OVERLAP_LOG_DEFAULT;
90 static U32 g_ldmHashLog = 0;
91 static U32 g_ldmMinMatch = 0;
92 static U32 g_ldmHashRateLog = LDM_PARAM_DEFAULT;
93 static U32 g_ldmBucketSizeLog = LDM_PARAM_DEFAULT;
96 #define DEFAULT_ACCEL 1
98 typedef enum { cover, fastCover, legacy } dictType;
100 /*-************************************
102 **************************************/
103 #define DISPLAY_F(f, ...) fprintf((f), __VA_ARGS__)
104 #define DISPLAYOUT(...) DISPLAY_F(stdout, __VA_ARGS__)
105 #define DISPLAY(...) DISPLAY_F(stderr, __VA_ARGS__)
106 #define DISPLAYLEVEL(l, ...) { if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); } }
107 static int g_displayLevel = DISPLAY_LEVEL_DEFAULT; /* 0 : no display, 1: errors, 2 : + result + interaction + warnings, 3 : + progression, 4 : + information */
110 /*-************************************
111 * Check Version (when CLI linked to dynamic library)
112 **************************************/
114 /* Due to usage of experimental symbols and capabilities by the CLI,
115 * the CLI must be linked against a dynamic library of same version */
116 static void checkLibVersion(void)
118 if (strcmp(ZSTD_VERSION_STRING, ZSTD_versionString())) {
119 DISPLAYLEVEL(1, "Error : incorrect library version (expecting : %s ; actual : %s ) \n",
120 ZSTD_VERSION_STRING, ZSTD_versionString());
121 DISPLAYLEVEL(1, "Please update library to version %s, or use stand-alone zstd binary \n",
122 ZSTD_VERSION_STRING);
129 @return : a non-zero value if exeName matches test, excluding the extension
131 static int exeNameMatch(const char* exeName, const char* test)
133 return !strncmp(exeName, test, strlen(test)) &&
134 (exeName[strlen(test)] == '\0' || exeName[strlen(test)] == '.');
137 /*-************************************
139 **************************************/
140 /* print help either in `stderr` or `stdout` depending on originating request
141 * error (badUsage) => stderr
142 * help (usageAdvanced) => stdout
144 static void usage(FILE* f, const char* programName)
146 DISPLAY_F(f, "Compress or decompress the INPUT file(s); reads from STDIN if INPUT is `-` or not provided.\n\n");
147 DISPLAY_F(f, "Usage: %s [OPTIONS...] [INPUT... | -] [-o OUTPUT]\n\n", programName);
148 DISPLAY_F(f, "Options:\n");
149 DISPLAY_F(f, " -o OUTPUT Write output to a single file, OUTPUT.\n");
150 DISPLAY_F(f, " -k, --keep Preserve INPUT file(s). [Default] \n");
151 DISPLAY_F(f, " --rm Remove INPUT file(s) after successful (de)compression.\n");
152 #ifdef ZSTD_GZCOMPRESS
153 if (exeNameMatch(programName, ZSTD_GZ)) { /* behave like gzip */
154 DISPLAY_F(f, " -n, --no-name Do not store original filename when compressing.\n\n");
158 #ifndef ZSTD_NOCOMPRESS
159 DISPLAY_F(f, " -# Desired compression level, where `#` is a number between 1 and %d;\n", ZSTDCLI_CLEVEL_MAX);
160 DISPLAY_F(f, " lower numbers provide faster compression, higher numbers yield\n");
161 DISPLAY_F(f, " better compression ratios. [Default: %d]\n\n", ZSTDCLI_CLEVEL_DEFAULT);
163 #ifndef ZSTD_NODECOMPRESS
164 DISPLAY_F(f, " -d, --decompress Perform decompression.\n");
166 DISPLAY_F(f, " -D DICT Use DICT as the dictionary for compression or decompression.\n\n");
167 DISPLAY_F(f, " -f, --force Disable input and output checks. Allows overwriting existing files,\n");
168 DISPLAY_F(f, " receiving input from the console, printing output to STDOUT, and\n");
169 DISPLAY_F(f, " operating on links, block devices, etc. Unrecognized formats will be\n");
170 DISPLAY_F(f, " passed-through through as-is.\n\n");
172 DISPLAY_F(f, " -h Display short usage and exit.\n");
173 DISPLAY_F(f, " -H, --help Display full help and exit.\n");
174 DISPLAY_F(f, " -V, --version Display the program version and exit.\n");
178 static void usageAdvanced(const char* programName)
180 DISPLAYOUT(WELCOME_MESSAGE);
182 usage(stdout, programName);
183 DISPLAYOUT("Advanced options:\n");
184 DISPLAYOUT(" -c, --stdout Write to STDOUT (even if it is a console) and keep the INPUT file(s).\n\n");
186 DISPLAYOUT(" -v, --verbose Enable verbose output; pass multiple times to increase verbosity.\n");
187 DISPLAYOUT(" -q, --quiet Suppress warnings; pass twice to suppress errors.\n");
189 DISPLAYOUT(" --trace LOG Log tracing information to LOG.\n");
192 DISPLAYOUT(" --[no-]progress Forcibly show/hide the progress counter. NOTE: Any (de)compressed\n");
193 DISPLAYOUT(" output to terminal will mix with progress counter text.\n\n");
195 #ifdef UTIL_HAS_CREATEFILELIST
196 DISPLAYOUT(" -r Operate recursively on directories.\n");
197 DISPLAYOUT(" --filelist LIST Read a list of files to operate on from LIST.\n");
198 DISPLAYOUT(" --output-dir-flat DIR Store processed files in DIR.\n");
201 #ifdef UTIL_HAS_MIRRORFILELIST
202 DISPLAYOUT(" --output-dir-mirror DIR Store processed files in DIR, respecting original directory structure.\n");
205 DISPLAYOUT(" --[no-]asyncio Use asynchronous IO. [Default: Enabled]\n");
208 #ifndef ZSTD_NOCOMPRESS
209 DISPLAYOUT(" --[no-]check Add XXH64 integrity checksums during compression. [Default: Add, Validate]\n");
210 #ifndef ZSTD_NODECOMPRESS
211 DISPLAYOUT(" If `-d` is present, ignore/validate checksums during decompression.\n");
214 #ifdef ZSTD_NOCOMPRESS
215 DISPLAYOUT(" --[no-]check Ignore/validate checksums during decompression. [Default: Validate]");
217 #endif /* ZSTD_NOCOMPRESS */
220 DISPLAYOUT(" -- Treat remaining arguments after `--` as files.\n");
222 #ifndef ZSTD_NOCOMPRESS
224 DISPLAYOUT("Advanced compression options:\n");
225 DISPLAYOUT(" --ultra Enable levels beyond %i, up to %i; requires more memory.\n", ZSTDCLI_CLEVEL_MAX, ZSTD_maxCLevel());
226 DISPLAYOUT(" --fast[=#] Use to very fast compression levels. [Default: %u]\n", 1);
227 #ifdef ZSTD_GZCOMPRESS
228 if (exeNameMatch(programName, ZSTD_GZ)) { /* behave like gzip */
229 DISPLAYOUT(" --best Compatibility alias for `-9`.\n");
232 DISPLAYOUT(" --adapt Dynamically adapt compression level to I/O conditions.\n");
233 DISPLAYOUT(" --long[=#] Enable long distance matching with window log #. [Default: %u]\n", g_defaultMaxWindowLog);
234 DISPLAYOUT(" --patch-from=REF Use REF as the reference point for Zstandard's diff engine. \n\n");
235 # ifdef ZSTD_MULTITHREAD
236 DISPLAYOUT(" -T# Spawn # compression threads. [Default: 1; pass 0 for core count.]\n");
237 DISPLAYOUT(" --single-thread Share a single thread for I/O and compression (slightly different than `-T1`).\n");
238 DISPLAYOUT(" --auto-threads={physical|logical}\n");
239 DISPLAYOUT(" Use physical/logical cores when using `-T0`. [Default: Physical]\n\n");
240 DISPLAYOUT(" -B# Set job size to #. [Default: 0 (automatic)]\n");
241 DISPLAYOUT(" --rsyncable Compress using a rsync-friendly method (`-B` sets block size). \n");
244 DISPLAYOUT(" --exclude-compressed Only compress files that are not already compressed.\n\n");
246 DISPLAYOUT(" --stream-size=# Specify size of streaming input from STDIN.\n");
247 DISPLAYOUT(" --size-hint=# Optimize compression parameters for streaming input of approximately size #.\n");
248 DISPLAYOUT(" --target-compressed-block-size=#\n");
249 DISPLAYOUT(" Generate compressed blocks of approximately # size.\n\n");
250 DISPLAYOUT(" --no-dictID Don't write `dictID` into the header (dictionary compression only).\n");
251 DISPLAYOUT(" --[no-]compress-literals Force (un)compressed literals.\n");
252 DISPLAYOUT(" --[no-]row-match-finder Explicitly enable/disable the fast, row-based matchfinder for\n");
253 DISPLAYOUT(" the 'greedy', 'lazy', and 'lazy2' strategies.\n");
256 DISPLAYOUT(" --format=zstd Compress files to the `.zst` format. [Default]\n");
257 DISPLAYOUT(" --[no-]mmap-dict Memory-map dictionary file rather than mallocing and loading all at once\n");
258 #ifdef ZSTD_GZCOMPRESS
259 DISPLAYOUT(" --format=gzip Compress files to the `.gz` format.\n");
261 #ifdef ZSTD_LZMACOMPRESS
262 DISPLAYOUT(" --format=xz Compress files to the `.xz` format.\n");
263 DISPLAYOUT(" --format=lzma Compress files to the `.lzma` format.\n");
265 #ifdef ZSTD_LZ4COMPRESS
266 DISPLAYOUT( " --format=lz4 Compress files to the `.lz4` format.\n");
268 #endif /* !ZSTD_NOCOMPRESS */
270 #ifndef ZSTD_NODECOMPRESS
272 DISPLAYOUT("Advanced decompression options:\n");
273 DISPLAYOUT(" -l Print information about Zstandard-compressed files.\n");
274 DISPLAYOUT(" --test Test compressed file integrity.\n");
275 DISPLAYOUT(" -M# Set the memory usage limit to # megabytes.\n");
276 # if ZSTD_SPARSE_DEFAULT
277 DISPLAYOUT(" --[no-]sparse Enable sparse mode. [Default: Enabled for files, disabled for STDOUT.]\n");
279 DISPLAYOUT(" --[no-]sparse Enable sparse mode. [Default: Disabled]\n");
282 char const* passThroughDefault = "Disabled";
283 if (exeNameMatch(programName, ZSTD_CAT) ||
284 exeNameMatch(programName, ZSTD_ZCAT) ||
285 exeNameMatch(programName, ZSTD_GZCAT)) {
286 passThroughDefault = "Enabled";
288 DISPLAYOUT(" --[no-]pass-through Pass through uncompressed files as-is. [Default: %s]\n", passThroughDefault);
290 #endif /* ZSTD_NODECOMPRESS */
294 DISPLAYOUT("Dictionary builder:\n");
295 DISPLAYOUT(" --train Create a dictionary from a training set of files.\n\n");
296 DISPLAYOUT(" --train-cover[=k=#,d=#,steps=#,split=#,shrink[=#]]\n");
297 DISPLAYOUT(" Use the cover algorithm (with optional arguments).\n");
298 DISPLAYOUT(" --train-fastcover[=k=#,d=#,f=#,steps=#,split=#,accel=#,shrink[=#]]\n");
299 DISPLAYOUT(" Use the fast cover algorithm (with optional arguments).\n\n");
300 DISPLAYOUT(" --train-legacy[=s=#] Use the legacy algorithm with selectivity #. [Default: %u]\n", g_defaultSelectivityLevel);
301 DISPLAYOUT(" -o NAME Use NAME as dictionary name. [Default: %s]\n", g_defaultDictName);
302 DISPLAYOUT(" --maxdict=# Limit dictionary to specified size #. [Default: %u]\n", g_defaultMaxDictSize);
303 DISPLAYOUT(" --dictID=# Force dictionary ID to #. [Default: Random]\n");
308 DISPLAYOUT("Benchmark options:\n");
309 DISPLAYOUT(" -b# Perform benchmarking with compression level #. [Default: %d]\n", ZSTDCLI_CLEVEL_DEFAULT);
310 DISPLAYOUT(" -e# Test all compression levels up to #; starting level is `-b#`. [Default: 1]\n");
311 DISPLAYOUT(" -i# Set the minimum evaluation to time # seconds. [Default: 3]\n");
312 DISPLAYOUT(" -B# Cut file into independent chunks of size #. [Default: No chunking]\n");
313 DISPLAYOUT(" -S Output one benchmark result per input file. [Default: Consolidated result]\n");
314 DISPLAYOUT(" --priority=rt Set process priority to real-time.\n");
319 static void badUsage(const char* programName, const char* parameter)
321 DISPLAYLEVEL(1, "Incorrect parameter: %s \n", parameter);
322 if (g_displayLevel >= 2) usage(stderr, programName);
325 static void waitEnter(void)
328 DISPLAY("Press enter to continue... \n");
333 static const char* lastNameFromPath(const char* path)
335 const char* name = path;
336 if (strrchr(name, '/')) name = strrchr(name, '/') + 1;
337 if (strrchr(name, '\\')) name = strrchr(name, '\\') + 1; /* windows */
341 static void errorOut(const char* msg)
343 DISPLAYLEVEL(1, "%s \n", msg); exit(1);
346 /*! readU32FromCharChecked() :
347 * @return 0 if success, and store the result in *value.
348 * allows and interprets K, KB, KiB, M, MB and MiB suffix.
349 * Will also modify `*stringPtr`, advancing it to position where it stopped reading.
350 * @return 1 if an overflow error occurs */
351 static int readU32FromCharChecked(const char** stringPtr, unsigned* value)
354 while ((**stringPtr >='0') && (**stringPtr <='9')) {
355 unsigned const max = ((unsigned)(-1)) / 10;
356 unsigned last = result;
357 if (result > max) return 1; /* overflow error */
359 result += (unsigned)(**stringPtr - '0');
360 if (result < last) return 1; /* overflow error */
363 if ((**stringPtr=='K') || (**stringPtr=='M')) {
364 unsigned const maxK = ((unsigned)(-1)) >> 10;
365 if (result > maxK) return 1; /* overflow error */
367 if (**stringPtr=='M') {
368 if (result > maxK) return 1; /* overflow error */
371 (*stringPtr)++; /* skip `K` or `M` */
372 if (**stringPtr=='i') (*stringPtr)++;
373 if (**stringPtr=='B') (*stringPtr)++;
379 /*! readU32FromChar() :
380 * @return : unsigned integer value read from input in `char` format.
381 * allows and interprets K, KB, KiB, M, MB and MiB suffix.
382 * Will also modify `*stringPtr`, advancing it to position where it stopped reading.
383 * Note : function will exit() program if digit sequence overflows */
384 static unsigned readU32FromChar(const char** stringPtr) {
385 static const char errorMsg[] = "error: numeric value overflows 32-bit unsigned int";
387 if (readU32FromCharChecked(stringPtr, &result)) { errorOut(errorMsg); }
391 /*! readIntFromChar() :
392 * @return : signed integer value read from input in `char` format.
393 * allows and interprets K, KB, KiB, M, MB and MiB suffix.
394 * Will also modify `*stringPtr`, advancing it to position where it stopped reading.
395 * Note : function will exit() program if digit sequence overflows */
396 static int readIntFromChar(const char** stringPtr) {
397 static const char errorMsg[] = "error: numeric value overflows 32-bit int";
400 if (**stringPtr=='-') {
404 if (readU32FromCharChecked(stringPtr, &result)) { errorOut(errorMsg); }
405 return (int) result * sign;
408 /*! readSizeTFromCharChecked() :
409 * @return 0 if success, and store the result in *value.
410 * allows and interprets K, KB, KiB, M, MB and MiB suffix.
411 * Will also modify `*stringPtr`, advancing it to position where it stopped reading.
412 * @return 1 if an overflow error occurs */
413 static int readSizeTFromCharChecked(const char** stringPtr, size_t* value)
416 while ((**stringPtr >='0') && (**stringPtr <='9')) {
417 size_t const max = ((size_t)(-1)) / 10;
418 size_t last = result;
419 if (result > max) return 1; /* overflow error */
421 result += (size_t)(**stringPtr - '0');
422 if (result < last) return 1; /* overflow error */
425 if ((**stringPtr=='K') || (**stringPtr=='M')) {
426 size_t const maxK = ((size_t)(-1)) >> 10;
427 if (result > maxK) return 1; /* overflow error */
429 if (**stringPtr=='M') {
430 if (result > maxK) return 1; /* overflow error */
433 (*stringPtr)++; /* skip `K` or `M` */
434 if (**stringPtr=='i') (*stringPtr)++;
435 if (**stringPtr=='B') (*stringPtr)++;
441 /*! readSizeTFromChar() :
442 * @return : size_t value read from input in `char` format.
443 * allows and interprets K, KB, KiB, M, MB and MiB suffix.
444 * Will also modify `*stringPtr`, advancing it to position where it stopped reading.
445 * Note : function will exit() program if digit sequence overflows */
446 static size_t readSizeTFromChar(const char** stringPtr) {
447 static const char errorMsg[] = "error: numeric value overflows size_t";
449 if (readSizeTFromCharChecked(stringPtr, &result)) { errorOut(errorMsg); }
453 /** longCommandWArg() :
454 * check if *stringPtr is the same as longCommand.
455 * If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
456 * @return 0 and doesn't modify *stringPtr otherwise.
458 static int longCommandWArg(const char** stringPtr, const char* longCommand)
460 size_t const comSize = strlen(longCommand);
461 int const result = !strncmp(*stringPtr, longCommand, comSize);
462 if (result) *stringPtr += comSize;
469 static const unsigned kDefaultRegression = 1;
471 * parseCoverParameters() :
472 * reads cover parameters from *stringPtr (e.g. "--train-cover=k=48,d=8,steps=32") into *params
473 * @return 1 means that cover parameters were correct
474 * @return 0 in case of malformed parameters
476 static unsigned parseCoverParameters(const char* stringPtr, ZDICT_cover_params_t* params)
478 memset(params, 0, sizeof(*params));
480 if (longCommandWArg(&stringPtr, "k=")) { params->k = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
481 if (longCommandWArg(&stringPtr, "d=")) { params->d = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
482 if (longCommandWArg(&stringPtr, "steps=")) { params->steps = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
483 if (longCommandWArg(&stringPtr, "split=")) {
484 unsigned splitPercentage = readU32FromChar(&stringPtr);
485 params->splitPoint = (double)splitPercentage / 100.0;
486 if (stringPtr[0]==',') { stringPtr++; continue; } else break;
488 if (longCommandWArg(&stringPtr, "shrink")) {
489 params->shrinkDictMaxRegression = kDefaultRegression;
490 params->shrinkDict = 1;
491 if (stringPtr[0]=='=') {
493 params->shrinkDictMaxRegression = readU32FromChar(&stringPtr);
495 if (stringPtr[0]==',') {
503 if (stringPtr[0] != 0) return 0;
504 DISPLAYLEVEL(4, "cover: k=%u\nd=%u\nsteps=%u\nsplit=%u\nshrink%u\n", params->k, params->d, params->steps, (unsigned)(params->splitPoint * 100), params->shrinkDictMaxRegression);
509 * parseFastCoverParameters() :
510 * reads fastcover parameters from *stringPtr (e.g. "--train-fastcover=k=48,d=8,f=20,steps=32,accel=2") into *params
511 * @return 1 means that fastcover parameters were correct
512 * @return 0 in case of malformed parameters
514 static unsigned parseFastCoverParameters(const char* stringPtr, ZDICT_fastCover_params_t* params)
516 memset(params, 0, sizeof(*params));
518 if (longCommandWArg(&stringPtr, "k=")) { params->k = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
519 if (longCommandWArg(&stringPtr, "d=")) { params->d = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
520 if (longCommandWArg(&stringPtr, "f=")) { params->f = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
521 if (longCommandWArg(&stringPtr, "steps=")) { params->steps = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
522 if (longCommandWArg(&stringPtr, "accel=")) { params->accel = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
523 if (longCommandWArg(&stringPtr, "split=")) {
524 unsigned splitPercentage = readU32FromChar(&stringPtr);
525 params->splitPoint = (double)splitPercentage / 100.0;
526 if (stringPtr[0]==',') { stringPtr++; continue; } else break;
528 if (longCommandWArg(&stringPtr, "shrink")) {
529 params->shrinkDictMaxRegression = kDefaultRegression;
530 params->shrinkDict = 1;
531 if (stringPtr[0]=='=') {
533 params->shrinkDictMaxRegression = readU32FromChar(&stringPtr);
535 if (stringPtr[0]==',') {
543 if (stringPtr[0] != 0) return 0;
544 DISPLAYLEVEL(4, "cover: k=%u\nd=%u\nf=%u\nsteps=%u\nsplit=%u\naccel=%u\nshrink=%u\n", params->k, params->d, params->f, params->steps, (unsigned)(params->splitPoint * 100), params->accel, params->shrinkDictMaxRegression);
549 * parseLegacyParameters() :
550 * reads legacy dictionary builder parameters from *stringPtr (e.g. "--train-legacy=selectivity=8") into *selectivity
551 * @return 1 means that legacy dictionary builder parameters were correct
552 * @return 0 in case of malformed parameters
554 static unsigned parseLegacyParameters(const char* stringPtr, unsigned* selectivity)
556 if (!longCommandWArg(&stringPtr, "s=") && !longCommandWArg(&stringPtr, "selectivity=")) { return 0; }
557 *selectivity = readU32FromChar(&stringPtr);
558 if (stringPtr[0] != 0) return 0;
559 DISPLAYLEVEL(4, "legacy: selectivity=%u\n", *selectivity);
563 static ZDICT_cover_params_t defaultCoverParams(void)
565 ZDICT_cover_params_t params;
566 memset(¶ms, 0, sizeof(params));
569 params.splitPoint = 1.0;
570 params.shrinkDict = 0;
571 params.shrinkDictMaxRegression = kDefaultRegression;
575 static ZDICT_fastCover_params_t defaultFastCoverParams(void)
577 ZDICT_fastCover_params_t params;
578 memset(¶ms, 0, sizeof(params));
582 params.splitPoint = 0.75; /* different from default splitPoint of cover */
583 params.accel = DEFAULT_ACCEL;
584 params.shrinkDict = 0;
585 params.shrinkDictMaxRegression = kDefaultRegression;
591 /** parseAdaptParameters() :
592 * reads adapt parameters from *stringPtr (e.g. "--adapt=min=1,max=19) and store them into adaptMinPtr and adaptMaxPtr.
593 * Both adaptMinPtr and adaptMaxPtr must be already allocated and correctly initialized.
594 * There is no guarantee that any of these values will be updated.
595 * @return 1 means that parsing was successful,
596 * @return 0 in case of malformed parameters
598 static unsigned parseAdaptParameters(const char* stringPtr, int* adaptMinPtr, int* adaptMaxPtr)
601 if (longCommandWArg(&stringPtr, "min=")) { *adaptMinPtr = readIntFromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
602 if (longCommandWArg(&stringPtr, "max=")) { *adaptMaxPtr = readIntFromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
603 DISPLAYLEVEL(4, "invalid compression parameter \n");
606 if (stringPtr[0] != 0) return 0; /* check the end of string */
607 if (*adaptMinPtr > *adaptMaxPtr) {
608 DISPLAYLEVEL(4, "incoherent adaptation limits \n");
615 /** parseCompressionParameters() :
616 * reads compression parameters from *stringPtr (e.g. "--zstd=wlog=23,clog=23,hlog=22,slog=6,mml=3,tlen=48,strat=6") into *params
617 * @return 1 means that compression parameters were correct
618 * @return 0 in case of malformed parameters
620 static unsigned parseCompressionParameters(const char* stringPtr, ZSTD_compressionParameters* params)
623 if (longCommandWArg(&stringPtr, "windowLog=") || longCommandWArg(&stringPtr, "wlog=")) { params->windowLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
624 if (longCommandWArg(&stringPtr, "chainLog=") || longCommandWArg(&stringPtr, "clog=")) { params->chainLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
625 if (longCommandWArg(&stringPtr, "hashLog=") || longCommandWArg(&stringPtr, "hlog=")) { params->hashLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
626 if (longCommandWArg(&stringPtr, "searchLog=") || longCommandWArg(&stringPtr, "slog=")) { params->searchLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
627 if (longCommandWArg(&stringPtr, "minMatch=") || longCommandWArg(&stringPtr, "mml=")) { params->minMatch = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
628 if (longCommandWArg(&stringPtr, "targetLength=") || longCommandWArg(&stringPtr, "tlen=")) { params->targetLength = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
629 if (longCommandWArg(&stringPtr, "strategy=") || longCommandWArg(&stringPtr, "strat=")) { params->strategy = (ZSTD_strategy)(readU32FromChar(&stringPtr)); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
630 if (longCommandWArg(&stringPtr, "overlapLog=") || longCommandWArg(&stringPtr, "ovlog=")) { g_overlapLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
631 if (longCommandWArg(&stringPtr, "ldmHashLog=") || longCommandWArg(&stringPtr, "lhlog=")) { g_ldmHashLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
632 if (longCommandWArg(&stringPtr, "ldmMinMatch=") || longCommandWArg(&stringPtr, "lmml=")) { g_ldmMinMatch = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
633 if (longCommandWArg(&stringPtr, "ldmBucketSizeLog=") || longCommandWArg(&stringPtr, "lblog=")) { g_ldmBucketSizeLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
634 if (longCommandWArg(&stringPtr, "ldmHashRateLog=") || longCommandWArg(&stringPtr, "lhrlog=")) { g_ldmHashRateLog = readU32FromChar(&stringPtr); if (stringPtr[0]==',') { stringPtr++; continue; } else break; }
635 DISPLAYLEVEL(4, "invalid compression parameter \n");
639 DISPLAYLEVEL(4, "windowLog=%d, chainLog=%d, hashLog=%d, searchLog=%d \n", params->windowLog, params->chainLog, params->hashLog, params->searchLog);
640 DISPLAYLEVEL(4, "minMatch=%d, targetLength=%d, strategy=%d \n", params->minMatch, params->targetLength, params->strategy);
641 if (stringPtr[0] != 0) return 0; /* check the end of string */
645 static void printVersion(void)
647 if (g_displayLevel < DISPLAY_LEVEL_DEFAULT) {
648 DISPLAYOUT("%s\n", ZSTD_VERSION_STRING);
652 DISPLAYOUT(WELCOME_MESSAGE);
653 if (g_displayLevel >= 3) {
655 DISPLAYOUT("*** supports: zstd");
656 #if defined(ZSTD_LEGACY_SUPPORT) && (ZSTD_LEGACY_SUPPORT>0) && (ZSTD_LEGACY_SUPPORT<8)
657 DISPLAYOUT(", zstd legacy v0.%d+", ZSTD_LEGACY_SUPPORT);
659 #ifdef ZSTD_GZCOMPRESS
660 DISPLAYOUT(", gzip");
662 #ifdef ZSTD_LZ4COMPRESS
665 #ifdef ZSTD_LZMACOMPRESS
666 DISPLAYOUT(", lzma, xz ");
669 if (g_displayLevel >= 4) {
670 /* library versions */
671 DISPLAYOUT("zlib version %s\n", FIO_zlibVersion());
672 DISPLAYOUT("lz4 version %s\n", FIO_lz4Version());
673 DISPLAYOUT("lzma version %s\n", FIO_lzmaVersion());
676 #ifdef _POSIX_C_SOURCE
677 DISPLAYOUT("_POSIX_C_SOURCE defined: %ldL\n", (long) _POSIX_C_SOURCE);
679 #ifdef _POSIX_VERSION
680 DISPLAYOUT("_POSIX_VERSION defined: %ldL \n", (long) _POSIX_VERSION);
682 #ifdef PLATFORM_POSIX_VERSION
683 DISPLAYOUT("PLATFORM_POSIX_VERSION defined: %ldL\n", (long) PLATFORM_POSIX_VERSION);
688 #define ZSTD_NB_STRATEGIES 9
689 static const char* ZSTD_strategyMap[ZSTD_NB_STRATEGIES + 1] = { "", "ZSTD_fast",
690 "ZSTD_dfast", "ZSTD_greedy", "ZSTD_lazy", "ZSTD_lazy2", "ZSTD_btlazy2",
691 "ZSTD_btopt", "ZSTD_btultra", "ZSTD_btultra2"};
693 #ifndef ZSTD_NOCOMPRESS
695 static void printDefaultCParams(const char* filename, const char* dictFileName, int cLevel) {
696 unsigned long long fileSize = UTIL_getFileSize(filename);
697 const size_t dictSize = dictFileName != NULL ? (size_t)UTIL_getFileSize(dictFileName) : 0;
698 const ZSTD_compressionParameters cParams = ZSTD_getCParams(cLevel, fileSize, dictSize);
699 if (fileSize != UTIL_FILESIZE_UNKNOWN) DISPLAY("%s (%u bytes)\n", filename, (unsigned)fileSize);
700 else DISPLAY("%s (src size unknown)\n", filename);
701 DISPLAY(" - windowLog : %u\n", cParams.windowLog);
702 DISPLAY(" - chainLog : %u\n", cParams.chainLog);
703 DISPLAY(" - hashLog : %u\n", cParams.hashLog);
704 DISPLAY(" - searchLog : %u\n", cParams.searchLog);
705 DISPLAY(" - minMatch : %u\n", cParams.minMatch);
706 DISPLAY(" - targetLength : %u\n", cParams.targetLength);
707 assert(cParams.strategy < ZSTD_NB_STRATEGIES + 1);
708 DISPLAY(" - strategy : %s (%u)\n", ZSTD_strategyMap[(int)cParams.strategy], (unsigned)cParams.strategy);
711 static void printActualCParams(const char* filename, const char* dictFileName, int cLevel, const ZSTD_compressionParameters* cParams) {
712 unsigned long long fileSize = UTIL_getFileSize(filename);
713 const size_t dictSize = dictFileName != NULL ? (size_t)UTIL_getFileSize(dictFileName) : 0;
714 ZSTD_compressionParameters actualCParams = ZSTD_getCParams(cLevel, fileSize, dictSize);
715 assert(g_displayLevel >= 4);
716 actualCParams.windowLog = cParams->windowLog == 0 ? actualCParams.windowLog : cParams->windowLog;
717 actualCParams.chainLog = cParams->chainLog == 0 ? actualCParams.chainLog : cParams->chainLog;
718 actualCParams.hashLog = cParams->hashLog == 0 ? actualCParams.hashLog : cParams->hashLog;
719 actualCParams.searchLog = cParams->searchLog == 0 ? actualCParams.searchLog : cParams->searchLog;
720 actualCParams.minMatch = cParams->minMatch == 0 ? actualCParams.minMatch : cParams->minMatch;
721 actualCParams.targetLength = cParams->targetLength == 0 ? actualCParams.targetLength : cParams->targetLength;
722 actualCParams.strategy = cParams->strategy == 0 ? actualCParams.strategy : cParams->strategy;
723 DISPLAY("--zstd=wlog=%d,clog=%d,hlog=%d,slog=%d,mml=%d,tlen=%d,strat=%d\n",
724 actualCParams.windowLog, actualCParams.chainLog, actualCParams.hashLog, actualCParams.searchLog,
725 actualCParams.minMatch, actualCParams.targetLength, actualCParams.strategy);
730 /* Environment variables for parameter setting */
731 #define ENV_CLEVEL "ZSTD_CLEVEL"
732 #define ENV_NBTHREADS "ZSTD_NBTHREADS" /* takes lower precedence than directly specifying -T# in the CLI */
734 /* pick up environment variable */
735 static int init_cLevel(void) {
736 const char* const env = getenv(ENV_CLEVEL);
738 const char* ptr = env;
743 } else if (*ptr == '+') {
747 if ((*ptr>='0') && (*ptr<='9')) {
749 if (readU32FromCharChecked(&ptr, &absLevel)) {
750 DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: numeric value too large \n", ENV_CLEVEL, env);
751 return ZSTDCLI_CLEVEL_DEFAULT;
752 } else if (*ptr == 0) {
753 return sign * (int)absLevel;
756 DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: not a valid integer value \n", ENV_CLEVEL, env);
759 return ZSTDCLI_CLEVEL_DEFAULT;
762 #ifdef ZSTD_MULTITHREAD
763 static unsigned init_nbThreads(void) {
764 const char* const env = getenv(ENV_NBTHREADS);
766 const char* ptr = env;
767 if ((*ptr>='0') && (*ptr<='9')) {
769 if (readU32FromCharChecked(&ptr, &nbThreads)) {
770 DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: numeric value too large \n", ENV_NBTHREADS, env);
771 return ZSTDCLI_NBTHREADS_DEFAULT;
772 } else if (*ptr == 0) {
776 DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: not a valid unsigned value \n", ENV_NBTHREADS, env);
779 return ZSTDCLI_NBTHREADS_DEFAULT;
783 #define NEXT_FIELD(ptr) { \
784 if (*argument == '=') { \
786 argument += strlen(ptr); \
789 if (argNb >= argCount) { \
790 DISPLAYLEVEL(1, "error: missing command argument \n"); \
794 assert(ptr != NULL); \
796 DISPLAYLEVEL(1, "error: command cannot be separated from its argument by another command \n"); \
800 #define NEXT_UINT32(val32) { \
803 val32 = readU32FromChar(&__nb); \
805 errorOut("error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed"); \
809 #define NEXT_TSIZE(valTsize) { \
812 valTsize = readSizeTFromChar(&__nb); \
814 errorOut("error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed"); \
818 typedef enum { zom_compress, zom_decompress, zom_test, zom_bench, zom_train, zom_list } zstd_operation_mode;
820 #define CLEAN_RETURN(i) { operationResult = (i); goto _end; }
822 #ifdef ZSTD_NOCOMPRESS
823 /* symbols from compression library are not defined and should not be invoked */
824 # define MINCLEVEL -99
825 # define MAXCLEVEL 22
827 # define MINCLEVEL ZSTD_minCLevel()
828 # define MAXCLEVEL ZSTD_maxCLevel()
831 int main(int argCount, const char* argv[])
835 allowBlockDevices = 0,
842 adaptMin = MINCLEVEL,
843 adaptMax = MAXCLEVEL,
845 nextArgumentsAreFiles = 0,
850 defaultLogicalCores = 0,
851 showDefaultCParams = 0,
855 ZSTD_paramSwitch_e mmapDict=ZSTD_ps_auto;
856 ZSTD_paramSwitch_e useRowMatchFinder = ZSTD_ps_auto;
857 FIO_compressionType_t cType = FIO_zstdCompression;
858 unsigned nbWorkers = 0;
859 double compressibility = -1.0; /* lorem ipsum generator */
860 unsigned bench_nbSeconds = 3; /* would be better if this value was synchronized from bench */
861 size_t blockSize = 0;
863 FIO_prefs_t* const prefs = FIO_createPreferences();
864 FIO_ctx_t* const fCtx = FIO_createContext();
865 FIO_progressSetting_e progress = FIO_ps_auto;
866 zstd_operation_mode operation = zom_compress;
867 ZSTD_compressionParameters compressionParams;
868 int cLevel = init_cLevel();
869 int cLevelLast = MINCLEVEL - 1; /* lower than minimum */
870 unsigned recursive = 0;
871 unsigned memLimit = 0;
872 FileNamesTable* filenames = UTIL_allocateFileNamesTable((size_t)argCount); /* argCount >= 1 */
873 FileNamesTable* file_of_names = UTIL_allocateFileNamesTable((size_t)argCount); /* argCount >= 1 */
874 const char* programName = argv[0];
875 const char* outFileName = NULL;
876 const char* outDirName = NULL;
877 const char* outMirroredDirName = NULL;
878 const char* dictFileName = NULL;
879 const char* patchFromDictFileName = NULL;
880 const char* suffix = ZSTD_EXTENSION;
881 unsigned maxDictSize = g_defaultMaxDictSize;
883 size_t streamSrcSize = 0;
884 size_t targetCBlockSize = 0;
885 size_t srcSizeHint = 0;
886 size_t nbInputFileNames = 0;
887 int dictCLevel = g_defaultDictCLevel;
888 unsigned dictSelect = g_defaultSelectivityLevel;
890 ZDICT_cover_params_t coverParams = defaultCoverParams();
891 ZDICT_fastCover_params_t fastCoverParams = defaultFastCoverParams();
892 dictType dict = fastCover;
895 BMK_advancedParams_t benchParams = BMK_initAdvancedParams();
897 ZSTD_paramSwitch_e literalCompressionMode = ZSTD_ps_auto;
902 (void)recursive; (void)cLevelLast; /* not used when ZSTD_NOBENCH set */
904 assert(argCount >= 1);
905 if ((filenames==NULL) || (file_of_names==NULL)) { DISPLAYLEVEL(1, "zstd: allocation error \n"); exit(1); }
906 programName = lastNameFromPath(programName);
907 #ifdef ZSTD_MULTITHREAD
908 nbWorkers = init_nbThreads();
911 /* preset behaviors */
912 if (exeNameMatch(programName, ZSTD_ZSTDMT)) nbWorkers=0, singleThread=0;
913 if (exeNameMatch(programName, ZSTD_UNZSTD)) operation=zom_decompress;
914 if (exeNameMatch(programName, ZSTD_CAT)) { operation=zom_decompress; FIO_overwriteMode(prefs); forceStdout=1; followLinks=1; FIO_setPassThroughFlag(prefs, 1); outFileName=stdoutmark; g_displayLevel=1; } /* supports multiple formats */
915 if (exeNameMatch(programName, ZSTD_ZCAT)) { operation=zom_decompress; FIO_overwriteMode(prefs); forceStdout=1; followLinks=1; FIO_setPassThroughFlag(prefs, 1); outFileName=stdoutmark; g_displayLevel=1; } /* behave like zcat, also supports multiple formats */
916 if (exeNameMatch(programName, ZSTD_GZ)) { /* behave like gzip */
917 suffix = GZ_EXTENSION; cType = FIO_gzipCompression; removeSrcFile=1;
918 dictCLevel = cLevel = 6; /* gzip default is -6 */
920 if (exeNameMatch(programName, ZSTD_GUNZIP)) { operation=zom_decompress; removeSrcFile=1; } /* behave like gunzip, also supports multiple formats */
921 if (exeNameMatch(programName, ZSTD_GZCAT)) { operation=zom_decompress; FIO_overwriteMode(prefs); forceStdout=1; followLinks=1; FIO_setPassThroughFlag(prefs, 1); outFileName=stdoutmark; g_displayLevel=1; } /* behave like gzcat, also supports multiple formats */
922 if (exeNameMatch(programName, ZSTD_LZMA)) { suffix = LZMA_EXTENSION; cType = FIO_lzmaCompression; removeSrcFile=1; } /* behave like lzma */
923 if (exeNameMatch(programName, ZSTD_UNLZMA)) { operation=zom_decompress; cType = FIO_lzmaCompression; removeSrcFile=1; } /* behave like unlzma, also supports multiple formats */
924 if (exeNameMatch(programName, ZSTD_XZ)) { suffix = XZ_EXTENSION; cType = FIO_xzCompression; removeSrcFile=1; } /* behave like xz */
925 if (exeNameMatch(programName, ZSTD_UNXZ)) { operation=zom_decompress; cType = FIO_xzCompression; removeSrcFile=1; } /* behave like unxz, also supports multiple formats */
926 if (exeNameMatch(programName, ZSTD_LZ4)) { suffix = LZ4_EXTENSION; cType = FIO_lz4Compression; } /* behave like lz4 */
927 if (exeNameMatch(programName, ZSTD_UNLZ4)) { operation=zom_decompress; cType = FIO_lz4Compression; } /* behave like unlz4, also supports multiple formats */
928 memset(&compressionParams, 0, sizeof(compressionParams));
930 /* init crash handler */
931 FIO_addAbortHandler();
933 /* command switches */
934 for (argNb=1; argNb<argCount; argNb++) {
935 const char* argument = argv[argNb];
936 const char* const originalArgument = argument;
937 if (!argument) continue; /* Protection if argument empty */
939 if (nextArgumentsAreFiles) {
940 UTIL_refFilename(filenames, argument);
944 /* "-" means stdin/stdout */
945 if (!strcmp(argument, "-")){
946 UTIL_refFilename(filenames, stdinmark);
950 /* Decode commands (note : aggregated commands are allowed) */
951 if (argument[0]=='-') {
953 if (argument[1]=='-') {
954 /* long commands (--long-word) */
955 if (!strcmp(argument, "--")) { nextArgumentsAreFiles=1; continue; } /* only file names allowed from now on */
956 if (!strcmp(argument, "--list")) { operation=zom_list; continue; }
957 if (!strcmp(argument, "--compress")) { operation=zom_compress; continue; }
958 if (!strcmp(argument, "--decompress")) { operation=zom_decompress; continue; }
959 if (!strcmp(argument, "--uncompress")) { operation=zom_decompress; continue; }
960 if (!strcmp(argument, "--force")) { FIO_overwriteMode(prefs); forceStdin=1; forceStdout=1; followLinks=1; allowBlockDevices=1; continue; }
961 if (!strcmp(argument, "--version")) { printVersion(); CLEAN_RETURN(0); }
962 if (!strcmp(argument, "--help")) { usageAdvanced(programName); CLEAN_RETURN(0); }
963 if (!strcmp(argument, "--verbose")) { g_displayLevel++; continue; }
964 if (!strcmp(argument, "--quiet")) { g_displayLevel--; continue; }
965 if (!strcmp(argument, "--stdout")) { forceStdout=1; outFileName=stdoutmark; continue; }
966 if (!strcmp(argument, "--ultra")) { ultra=1; continue; }
967 if (!strcmp(argument, "--check")) { FIO_setChecksumFlag(prefs, 2); continue; }
968 if (!strcmp(argument, "--no-check")) { FIO_setChecksumFlag(prefs, 0); continue; }
969 if (!strcmp(argument, "--sparse")) { FIO_setSparseWrite(prefs, 2); continue; }
970 if (!strcmp(argument, "--no-sparse")) { FIO_setSparseWrite(prefs, 0); continue; }
971 if (!strcmp(argument, "--pass-through")) { FIO_setPassThroughFlag(prefs, 1); continue; }
972 if (!strcmp(argument, "--no-pass-through")) { FIO_setPassThroughFlag(prefs, 0); continue; }
973 if (!strcmp(argument, "--test")) { operation=zom_test; continue; }
974 if (!strcmp(argument, "--asyncio")) { FIO_setAsyncIOFlag(prefs, 1); continue;}
975 if (!strcmp(argument, "--no-asyncio")) { FIO_setAsyncIOFlag(prefs, 0); continue;}
976 if (!strcmp(argument, "--train")) { operation=zom_train; if (outFileName==NULL) outFileName=g_defaultDictName; continue; }
977 if (!strcmp(argument, "--no-dictID")) { FIO_setDictIDFlag(prefs, 0); continue; }
978 if (!strcmp(argument, "--keep")) { removeSrcFile=0; continue; }
979 if (!strcmp(argument, "--rm")) { removeSrcFile=1; continue; }
980 if (!strcmp(argument, "--priority=rt")) { setRealTimePrio = 1; continue; }
981 if (!strcmp(argument, "--show-default-cparams")) { showDefaultCParams = 1; continue; }
982 if (!strcmp(argument, "--content-size")) { contentSize = 1; continue; }
983 if (!strcmp(argument, "--no-content-size")) { contentSize = 0; continue; }
984 if (!strcmp(argument, "--adapt")) { adapt = 1; continue; }
985 if (!strcmp(argument, "--no-row-match-finder")) { useRowMatchFinder = ZSTD_ps_disable; continue; }
986 if (!strcmp(argument, "--row-match-finder")) { useRowMatchFinder = ZSTD_ps_enable; continue; }
987 if (longCommandWArg(&argument, "--adapt=")) { adapt = 1; if (!parseAdaptParameters(argument, &adaptMin, &adaptMax)) { badUsage(programName, originalArgument); CLEAN_RETURN(1); } continue; }
988 if (!strcmp(argument, "--single-thread")) { nbWorkers = 0; singleThread = 1; continue; }
989 if (!strcmp(argument, "--format=zstd")) { suffix = ZSTD_EXTENSION; cType = FIO_zstdCompression; continue; }
990 if (!strcmp(argument, "--mmap-dict")) { mmapDict = ZSTD_ps_enable; continue; }
991 if (!strcmp(argument, "--no-mmap-dict")) { mmapDict = ZSTD_ps_disable; continue; }
992 #ifdef ZSTD_GZCOMPRESS
993 if (!strcmp(argument, "--format=gzip")) { suffix = GZ_EXTENSION; cType = FIO_gzipCompression; continue; }
994 if (exeNameMatch(programName, ZSTD_GZ)) { /* behave like gzip */
995 if (!strcmp(argument, "--best")) { dictCLevel = cLevel = 9; continue; }
996 if (!strcmp(argument, "--no-name")) { /* ignore for now */; continue; }
999 #ifdef ZSTD_LZMACOMPRESS
1000 if (!strcmp(argument, "--format=lzma")) { suffix = LZMA_EXTENSION; cType = FIO_lzmaCompression; continue; }
1001 if (!strcmp(argument, "--format=xz")) { suffix = XZ_EXTENSION; cType = FIO_xzCompression; continue; }
1003 #ifdef ZSTD_LZ4COMPRESS
1004 if (!strcmp(argument, "--format=lz4")) { suffix = LZ4_EXTENSION; cType = FIO_lz4Compression; continue; }
1006 if (!strcmp(argument, "--rsyncable")) { rsyncable = 1; continue; }
1007 if (!strcmp(argument, "--compress-literals")) { literalCompressionMode = ZSTD_ps_enable; continue; }
1008 if (!strcmp(argument, "--no-compress-literals")) { literalCompressionMode = ZSTD_ps_disable; continue; }
1009 if (!strcmp(argument, "--no-progress")) { progress = FIO_ps_never; continue; }
1010 if (!strcmp(argument, "--progress")) { progress = FIO_ps_always; continue; }
1011 if (!strcmp(argument, "--exclude-compressed")) { FIO_setExcludeCompressedFile(prefs, 1); continue; }
1012 if (!strcmp(argument, "--fake-stdin-is-console")) { UTIL_fakeStdinIsConsole(); continue; }
1013 if (!strcmp(argument, "--fake-stdout-is-console")) { UTIL_fakeStdoutIsConsole(); continue; }
1014 if (!strcmp(argument, "--fake-stderr-is-console")) { UTIL_fakeStderrIsConsole(); continue; }
1015 if (!strcmp(argument, "--trace-file-stat")) { UTIL_traceFileStat(); continue; }
1017 /* long commands with arguments */
1019 if (longCommandWArg(&argument, "--train-cover")) {
1020 operation = zom_train;
1021 if (outFileName == NULL)
1022 outFileName = g_defaultDictName;
1024 /* Allow optional arguments following an = */
1025 if (*argument == 0) { memset(&coverParams, 0, sizeof(coverParams)); }
1026 else if (*argument++ != '=') { badUsage(programName, originalArgument); CLEAN_RETURN(1); }
1027 else if (!parseCoverParameters(argument, &coverParams)) { badUsage(programName, originalArgument); CLEAN_RETURN(1); }
1030 if (longCommandWArg(&argument, "--train-fastcover")) {
1031 operation = zom_train;
1032 if (outFileName == NULL)
1033 outFileName = g_defaultDictName;
1035 /* Allow optional arguments following an = */
1036 if (*argument == 0) { memset(&fastCoverParams, 0, sizeof(fastCoverParams)); }
1037 else if (*argument++ != '=') { badUsage(programName, originalArgument); CLEAN_RETURN(1); }
1038 else if (!parseFastCoverParameters(argument, &fastCoverParams)) { badUsage(programName, originalArgument); CLEAN_RETURN(1); }
1041 if (longCommandWArg(&argument, "--train-legacy")) {
1042 operation = zom_train;
1043 if (outFileName == NULL)
1044 outFileName = g_defaultDictName;
1046 /* Allow optional arguments following an = */
1047 if (*argument == 0) { continue; }
1048 else if (*argument++ != '=') { badUsage(programName, originalArgument); CLEAN_RETURN(1); }
1049 else if (!parseLegacyParameters(argument, &dictSelect)) { badUsage(programName, originalArgument); CLEAN_RETURN(1); }
1053 if (longCommandWArg(&argument, "--threads")) { NEXT_UINT32(nbWorkers); continue; }
1054 if (longCommandWArg(&argument, "--memlimit")) { NEXT_UINT32(memLimit); continue; }
1055 if (longCommandWArg(&argument, "--memory")) { NEXT_UINT32(memLimit); continue; }
1056 if (longCommandWArg(&argument, "--memlimit-decompress")) { NEXT_UINT32(memLimit); continue; }
1057 if (longCommandWArg(&argument, "--block-size")) { NEXT_TSIZE(blockSize); continue; }
1058 if (longCommandWArg(&argument, "--maxdict")) { NEXT_UINT32(maxDictSize); continue; }
1059 if (longCommandWArg(&argument, "--dictID")) { NEXT_UINT32(dictID); continue; }
1060 if (longCommandWArg(&argument, "--zstd=")) { if (!parseCompressionParameters(argument, &compressionParams)) { badUsage(programName, originalArgument); CLEAN_RETURN(1); } ; cType = FIO_zstdCompression; continue; }
1061 if (longCommandWArg(&argument, "--stream-size")) { NEXT_TSIZE(streamSrcSize); continue; }
1062 if (longCommandWArg(&argument, "--target-compressed-block-size")) { NEXT_TSIZE(targetCBlockSize); continue; }
1063 if (longCommandWArg(&argument, "--size-hint")) { NEXT_TSIZE(srcSizeHint); continue; }
1064 if (longCommandWArg(&argument, "--output-dir-flat")) {
1065 NEXT_FIELD(outDirName);
1066 if (strlen(outDirName) == 0) {
1067 DISPLAYLEVEL(1, "error: output dir cannot be empty string (did you mean to pass '.' instead?)\n");
1072 if (longCommandWArg(&argument, "--auto-threads")) {
1073 const char* threadDefault = NULL;
1074 NEXT_FIELD(threadDefault);
1075 if (strcmp(threadDefault, "logical") == 0)
1076 defaultLogicalCores = 1;
1079 #ifdef UTIL_HAS_MIRRORFILELIST
1080 if (longCommandWArg(&argument, "--output-dir-mirror")) {
1081 NEXT_FIELD(outMirroredDirName);
1082 if (strlen(outMirroredDirName) == 0) {
1083 DISPLAYLEVEL(1, "error: output dir cannot be empty string (did you mean to pass '.' instead?)\n");
1089 #ifndef ZSTD_NOTRACE
1090 if (longCommandWArg(&argument, "--trace")) { char const* traceFile; NEXT_FIELD(traceFile); TRACE_enable(traceFile); continue; }
1092 if (longCommandWArg(&argument, "--patch-from")) { NEXT_FIELD(patchFromDictFileName); continue; }
1093 if (longCommandWArg(&argument, "--long")) {
1094 unsigned ldmWindowLog = 0;
1096 /* Parse optional window log */
1097 if (*argument == '=') {
1099 ldmWindowLog = readU32FromChar(&argument);
1100 } else if (*argument != 0) {
1101 /* Invalid character following --long */
1102 badUsage(programName, originalArgument);
1105 ldmWindowLog = g_defaultMaxWindowLog;
1107 /* Only set windowLog if not already set by --zstd */
1108 if (compressionParams.windowLog == 0)
1109 compressionParams.windowLog = ldmWindowLog;
1112 #ifndef ZSTD_NOCOMPRESS /* linking ZSTD_minCLevel() requires compression support */
1113 if (longCommandWArg(&argument, "--fast")) {
1114 /* Parse optional acceleration factor */
1115 if (*argument == '=') {
1116 U32 const maxFast = (U32)-ZSTD_minCLevel();
1119 fastLevel = readU32FromChar(&argument);
1120 if (fastLevel > maxFast) fastLevel = maxFast;
1122 dictCLevel = cLevel = -(int)fastLevel;
1124 badUsage(programName, originalArgument);
1127 } else if (*argument != 0) {
1128 /* Invalid character following --fast */
1129 badUsage(programName, originalArgument);
1132 cLevel = -1; /* default for --fast */
1138 if (longCommandWArg(&argument, "--filelist")) {
1139 const char* listName;
1140 NEXT_FIELD(listName);
1141 UTIL_refFilename(file_of_names, listName);
1145 badUsage(programName, originalArgument);
1150 while (argument[0]!=0) {
1152 #ifndef ZSTD_NOCOMPRESS
1153 /* compression Level */
1154 if ((*argument>='0') && (*argument<='9')) {
1155 dictCLevel = cLevel = (int)readU32FromChar(&argument);
1163 case 'V': printVersion(); CLEAN_RETURN(0); /* Version Only */
1164 case 'H': usageAdvanced(programName); CLEAN_RETURN(0);
1165 case 'h': usage(stdout, programName); CLEAN_RETURN(0);
1168 case 'z': operation=zom_compress; argument++; break;
1172 #ifndef ZSTD_NOBENCH
1173 benchParams.mode = BMK_decodeOnly;
1174 if (operation==zom_bench) { argument++; break; } /* benchmark decode (hidden option) */
1176 operation=zom_decompress; argument++; break;
1178 /* Force stdout, even if stdout==console */
1179 case 'c': forceStdout=1; outFileName=stdoutmark; argument++; break;
1181 /* destination file name */
1182 case 'o': argument++; NEXT_FIELD(outFileName); break;
1184 /* do not store filename - gzip compatibility - nothing to do */
1185 case 'n': argument++; break;
1187 /* Use file content as dictionary */
1188 case 'D': argument++; NEXT_FIELD(dictFileName); break;
1191 case 'f': FIO_overwriteMode(prefs); forceStdin=1; forceStdout=1; followLinks=1; allowBlockDevices=1; argument++; break;
1194 case 'v': g_displayLevel++; argument++; break;
1197 case 'q': g_displayLevel--; argument++; break;
1199 /* keep source file (default) */
1200 case 'k': removeSrcFile=0; argument++; break;
1203 case 'C': FIO_setChecksumFlag(prefs, 2); argument++; break;
1205 /* test compressed file */
1206 case 't': operation=zom_test; argument++; break;
1211 memLimit = readU32FromChar(&argument);
1213 case 'l': operation=zom_list; argument++; break;
1214 #ifdef UTIL_HAS_CREATEFILELIST
1216 case 'r': recursive=1; argument++; break;
1219 #ifndef ZSTD_NOBENCH
1222 operation=zom_bench;
1226 /* range bench (benchmark only) */
1228 /* compression Level */
1230 cLevelLast = (int)readU32FromChar(&argument);
1233 /* Modify Nb Iterations (benchmark only) */
1236 bench_nbSeconds = readU32FromChar(&argument);
1239 /* cut input into blocks (benchmark only) */
1242 blockSize = readU32FromChar(&argument);
1245 /* benchmark files separately (hidden option) */
1251 #endif /* ZSTD_NOBENCH */
1253 /* nb of threads (hidden option) */
1256 nbWorkers = readU32FromChar(&argument);
1259 /* Dictionary Selection level */
1262 dictSelect = readU32FromChar(&argument);
1265 /* Pause at the end (-p) or set an additional param (-p#) (hidden option) */
1266 case 'p': argument++;
1267 #ifndef ZSTD_NOBENCH
1268 if ((*argument>='0') && (*argument<='9')) {
1269 benchParams.additionalParam = (int)readU32FromChar(&argument);
1275 /* Select compressibility of synthetic sample */
1278 compressibility = (double)readU32FromChar(&argument) / 100;
1281 /* unknown command */
1283 { char shortArgument[3] = {'-', 0, 0};
1284 shortArgument[1] = argument[0];
1285 badUsage(programName, shortArgument);
1291 } /* if (argument[0]=='-') */
1293 /* none of the above : add filename to list */
1294 UTIL_refFilename(filenames, argument);
1297 /* Welcome message (if verbose) */
1298 DISPLAYLEVEL(3, WELCOME_MESSAGE);
1300 #ifdef ZSTD_MULTITHREAD
1301 if ((operation==zom_decompress) && (!singleThread) && (nbWorkers > 1)) {
1302 DISPLAYLEVEL(2, "Warning : decompression does not support multi-threading\n");
1304 if ((nbWorkers==0) && (!singleThread)) {
1305 /* automatically set # workers based on # of reported cpus */
1306 if (defaultLogicalCores) {
1307 nbWorkers = (unsigned)UTIL_countLogicalCores();
1308 DISPLAYLEVEL(3, "Note: %d logical core(s) detected \n", nbWorkers);
1310 nbWorkers = (unsigned)UTIL_countPhysicalCores();
1311 DISPLAYLEVEL(3, "Note: %d physical core(s) detected \n", nbWorkers);
1315 (void)singleThread; (void)nbWorkers; (void)defaultLogicalCores;
1318 g_utilDisplayLevel = g_displayLevel;
1320 #ifdef UTIL_HAS_CREATEFILELIST
1322 unsigned u, fileNamesNb;
1323 unsigned const nbFilenames = (unsigned)filenames->tableSize;
1324 for (u=0, fileNamesNb=0; u<nbFilenames; u++) {
1325 if ( UTIL_isLink(filenames->fileNames[u])
1326 && !UTIL_isFIFO(filenames->fileNames[u])
1328 DISPLAYLEVEL(2, "Warning : %s is a symbolic link, ignoring \n", filenames->fileNames[u]);
1330 filenames->fileNames[fileNamesNb++] = filenames->fileNames[u];
1332 if (fileNamesNb == 0 && nbFilenames > 0) /* all names are eliminated */
1334 filenames->tableSize = fileNamesNb;
1335 } /* if (!followLinks) */
1337 /* read names from a file */
1338 if (file_of_names->tableSize) {
1339 size_t const nbFileLists = file_of_names->tableSize;
1341 for (flNb=0; flNb < nbFileLists; flNb++) {
1342 FileNamesTable* const fnt = UTIL_createFileNamesTable_fromFileName(file_of_names->fileNames[flNb]);
1344 DISPLAYLEVEL(1, "zstd: error reading %s \n", file_of_names->fileNames[flNb]);
1347 filenames = UTIL_mergeFileNamesTable(filenames, fnt);
1351 nbInputFileNames = filenames->tableSize; /* saving number of input files */
1353 if (recursive) { /* at this stage, filenameTable is a list of paths, which can contain both files and directories */
1354 UTIL_expandFNT(&filenames, followLinks);
1360 if (operation == zom_list) {
1361 #ifndef ZSTD_NODECOMPRESS
1362 int const ret = FIO_listMultipleFiles((unsigned)filenames->tableSize, filenames->fileNames, g_displayLevel);
1365 DISPLAYLEVEL(1, "file information is not supported \n");
1370 /* Check if benchmark is selected */
1371 if (operation==zom_bench) {
1372 #ifndef ZSTD_NOBENCH
1373 if (cType != FIO_zstdCompression) {
1374 DISPLAYLEVEL(1, "benchmark mode is only compatible with zstd format \n");
1377 benchParams.blockSize = blockSize;
1378 benchParams.targetCBlockSize = targetCBlockSize;
1379 benchParams.nbWorkers = (int)nbWorkers;
1380 benchParams.realTime = (unsigned)setRealTimePrio;
1381 benchParams.nbSeconds = bench_nbSeconds;
1382 benchParams.ldmFlag = ldmFlag;
1383 benchParams.ldmMinMatch = (int)g_ldmMinMatch;
1384 benchParams.ldmHashLog = (int)g_ldmHashLog;
1385 benchParams.useRowMatchFinder = (int)useRowMatchFinder;
1386 if (g_ldmBucketSizeLog != LDM_PARAM_DEFAULT) {
1387 benchParams.ldmBucketSizeLog = (int)g_ldmBucketSizeLog;
1389 if (g_ldmHashRateLog != LDM_PARAM_DEFAULT) {
1390 benchParams.ldmHashRateLog = (int)g_ldmHashRateLog;
1392 benchParams.literalCompressionMode = literalCompressionMode;
1394 if (cLevel > ZSTD_maxCLevel()) cLevel = ZSTD_maxCLevel();
1395 if (cLevelLast > ZSTD_maxCLevel()) cLevelLast = ZSTD_maxCLevel();
1396 if (cLevelLast < cLevel) cLevelLast = cLevel;
1397 if (cLevelLast > cLevel)
1398 DISPLAYLEVEL(3, "Benchmarking levels from %d to %d\n", cLevel, cLevelLast);
1399 if (filenames->tableSize > 0) {
1402 for(i = 0; i < filenames->tableSize; i++) {
1404 DISPLAYLEVEL(3, "Benchmarking %s \n", filenames->fileNames[i]);
1405 for(c = cLevel; c <= cLevelLast; c++) {
1406 operationResult = BMK_benchFilesAdvanced(&filenames->fileNames[i], 1, dictFileName, c, &compressionParams, g_displayLevel, &benchParams);
1409 for(; cLevel <= cLevelLast; cLevel++) {
1410 operationResult = BMK_benchFilesAdvanced(filenames->fileNames, (unsigned)filenames->tableSize, dictFileName, cLevel, &compressionParams, g_displayLevel, &benchParams);
1413 for(; cLevel <= cLevelLast; cLevel++) {
1414 operationResult = BMK_syntheticTest(cLevel, compressibility, &compressionParams, g_displayLevel, &benchParams);
1418 (void)bench_nbSeconds; (void)blockSize; (void)setRealTimePrio; (void)separateFiles; (void)compressibility;
1423 /* Check if dictionary builder is selected */
1424 if (operation==zom_train) {
1426 ZDICT_params_t zParams;
1427 zParams.compressionLevel = dictCLevel;
1428 zParams.notificationLevel = (unsigned)g_displayLevel;
1429 zParams.dictID = dictID;
1430 if (dict == cover) {
1431 int const optimize = !coverParams.k || !coverParams.d;
1432 coverParams.nbThreads = (unsigned)nbWorkers;
1433 coverParams.zParams = zParams;
1434 operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (int)filenames->tableSize, blockSize, NULL, &coverParams, NULL, optimize, memLimit);
1435 } else if (dict == fastCover) {
1436 int const optimize = !fastCoverParams.k || !fastCoverParams.d;
1437 fastCoverParams.nbThreads = (unsigned)nbWorkers;
1438 fastCoverParams.zParams = zParams;
1439 operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (int)filenames->tableSize, blockSize, NULL, NULL, &fastCoverParams, optimize, memLimit);
1441 ZDICT_legacy_params_t dictParams;
1442 memset(&dictParams, 0, sizeof(dictParams));
1443 dictParams.selectivityLevel = dictSelect;
1444 dictParams.zParams = zParams;
1445 operationResult = DiB_trainFromFiles(outFileName, maxDictSize, filenames->fileNames, (int)filenames->tableSize, blockSize, &dictParams, NULL, NULL, 0, memLimit);
1448 (void)dictCLevel; (void)dictSelect; (void)dictID; (void)maxDictSize; /* not used when ZSTD_NODICT set */
1449 DISPLAYLEVEL(1, "training mode not available \n");
1450 operationResult = 1;
1455 #ifndef ZSTD_NODECOMPRESS
1456 if (operation==zom_test) { FIO_setTestMode(prefs, 1); outFileName=nulmark; removeSrcFile=0; } /* test mode */
1459 /* No input filename ==> use stdin and stdout */
1460 if (filenames->tableSize == 0) {
1461 /* It is possible that the input
1462 was a number of empty directories. In this case
1463 stdin and stdout should not be used */
1464 if (nbInputFileNames > 0 ){
1465 DISPLAYLEVEL(1, "please provide correct input file(s) or non-empty directories -- ignored \n");
1468 UTIL_refFilename(filenames, stdinmark);
1471 if (filenames->tableSize == 1 && !strcmp(filenames->fileNames[0], stdinmark) && !outFileName)
1472 outFileName = stdoutmark; /* when input is stdin, default output is stdout */
1474 /* Check if input/output defined as console; trigger an error in this case */
1476 && (UTIL_searchFileNamesTable(filenames, stdinmark) != -1)
1477 && UTIL_isConsole(stdin) ) {
1478 DISPLAYLEVEL(1, "stdin is a console, aborting\n");
1481 if ( (!outFileName || !strcmp(outFileName, stdoutmark))
1482 && UTIL_isConsole(stdout)
1483 && (UTIL_searchFileNamesTable(filenames, stdinmark) != -1)
1485 && operation!=zom_decompress ) {
1486 DISPLAYLEVEL(1, "stdout is a console, aborting\n");
1490 #ifndef ZSTD_NOCOMPRESS
1491 /* check compression level limits */
1492 { int const maxCLevel = ultra ? ZSTD_maxCLevel() : ZSTDCLI_CLEVEL_MAX;
1493 if (cLevel > maxCLevel) {
1494 DISPLAYLEVEL(2, "Warning : compression level higher than max, reduced to %i \n", maxCLevel);
1499 if (showDefaultCParams) {
1500 if (operation == zom_decompress) {
1501 DISPLAYLEVEL(1, "error : can't use --show-default-cparams in decompression mode \n");
1506 if (dictFileName != NULL && patchFromDictFileName != NULL) {
1507 DISPLAYLEVEL(1, "error : can't use -D and --patch-from=# at the same time \n");
1511 if (patchFromDictFileName != NULL && filenames->tableSize > 1) {
1512 DISPLAYLEVEL(1, "error : can't use --patch-from=# on multiple files \n");
1516 /* No status message by default when output is stdout */
1517 hasStdout = outFileName && !strcmp(outFileName,stdoutmark);
1518 if (hasStdout && (g_displayLevel==2)) g_displayLevel=1;
1520 /* when stderr is not the console, do not pollute it with progress updates (unless requested) */
1521 if (!UTIL_isConsole(stderr) && (progress!=FIO_ps_always)) progress=FIO_ps_never;
1522 FIO_setProgressSetting(progress);
1524 /* don't remove source files when output is stdout */;
1525 if (hasStdout && removeSrcFile) {
1526 DISPLAYLEVEL(3, "Note: src files are not removed when output is stdout \n");
1529 FIO_setRemoveSrcFile(prefs, removeSrcFile);
1531 /* IO Stream/File */
1532 FIO_setHasStdoutOutput(fCtx, hasStdout);
1533 FIO_setNbFilesTotal(fCtx, (int)filenames->tableSize);
1534 FIO_determineHasStdinInput(fCtx, filenames);
1535 FIO_setNotificationLevel(g_displayLevel);
1536 FIO_setAllowBlockDevices(prefs, allowBlockDevices);
1537 FIO_setPatchFromMode(prefs, patchFromDictFileName != NULL);
1538 FIO_setMMapDict(prefs, mmapDict);
1539 if (memLimit == 0) {
1540 if (compressionParams.windowLog == 0) {
1541 memLimit = (U32)1 << g_defaultMaxWindowLog;
1543 memLimit = (U32)1 << (compressionParams.windowLog & 31);
1545 if (patchFromDictFileName != NULL)
1546 dictFileName = patchFromDictFileName;
1547 FIO_setMemLimit(prefs, memLimit);
1548 if (operation==zom_compress) {
1549 #ifndef ZSTD_NOCOMPRESS
1550 FIO_setCompressionType(prefs, cType);
1551 FIO_setContentSize(prefs, contentSize);
1552 FIO_setNbWorkers(prefs, (int)nbWorkers);
1553 FIO_setBlockSize(prefs, (int)blockSize);
1554 if (g_overlapLog!=OVERLAP_LOG_DEFAULT) FIO_setOverlapLog(prefs, (int)g_overlapLog);
1555 FIO_setLdmFlag(prefs, (unsigned)ldmFlag);
1556 FIO_setLdmHashLog(prefs, (int)g_ldmHashLog);
1557 FIO_setLdmMinMatch(prefs, (int)g_ldmMinMatch);
1558 if (g_ldmBucketSizeLog != LDM_PARAM_DEFAULT) FIO_setLdmBucketSizeLog(prefs, (int)g_ldmBucketSizeLog);
1559 if (g_ldmHashRateLog != LDM_PARAM_DEFAULT) FIO_setLdmHashRateLog(prefs, (int)g_ldmHashRateLog);
1560 FIO_setAdaptiveMode(prefs, adapt);
1561 FIO_setUseRowMatchFinder(prefs, (int)useRowMatchFinder);
1562 FIO_setAdaptMin(prefs, adaptMin);
1563 FIO_setAdaptMax(prefs, adaptMax);
1564 FIO_setRsyncable(prefs, rsyncable);
1565 FIO_setStreamSrcSize(prefs, streamSrcSize);
1566 FIO_setTargetCBlockSize(prefs, targetCBlockSize);
1567 FIO_setSrcSizeHint(prefs, srcSizeHint);
1568 FIO_setLiteralCompressionMode(prefs, literalCompressionMode);
1569 FIO_setSparseWrite(prefs, 0);
1570 if (adaptMin > cLevel) cLevel = adaptMin;
1571 if (adaptMax < cLevel) cLevel = adaptMax;
1573 /* Compare strategies constant with the ground truth */
1574 { ZSTD_bounds strategyBounds = ZSTD_cParam_getBounds(ZSTD_c_strategy);
1575 assert(ZSTD_NB_STRATEGIES == strategyBounds.upperBound);
1576 (void)strategyBounds; }
1578 if (showDefaultCParams || g_displayLevel >= 4) {
1580 for (fileNb = 0; fileNb < (size_t)filenames->tableSize; fileNb++) {
1581 if (showDefaultCParams)
1582 printDefaultCParams(filenames->fileNames[fileNb], dictFileName, cLevel);
1583 if (g_displayLevel >= 4)
1584 printActualCParams(filenames->fileNames[fileNb], dictFileName, cLevel, &compressionParams);
1588 if (g_displayLevel >= 4)
1589 FIO_displayCompressionParameters(prefs);
1590 if ((filenames->tableSize==1) && outFileName)
1591 operationResult = FIO_compressFilename(fCtx, prefs, outFileName, filenames->fileNames[0], dictFileName, cLevel, compressionParams);
1593 operationResult = FIO_compressMultipleFilenames(fCtx, prefs, filenames->fileNames, outMirroredDirName, outDirName, outFileName, suffix, dictFileName, cLevel, compressionParams);
1595 /* these variables are only used when compression mode is enabled */
1596 (void)contentSize; (void)suffix; (void)adapt; (void)rsyncable;
1597 (void)ultra; (void)cLevel; (void)ldmFlag; (void)literalCompressionMode;
1598 (void)targetCBlockSize; (void)streamSrcSize; (void)srcSizeHint;
1599 (void)ZSTD_strategyMap; (void)useRowMatchFinder; (void)cType;
1600 DISPLAYLEVEL(1, "Compression not supported \n");
1602 } else { /* decompression or test */
1603 #ifndef ZSTD_NODECOMPRESS
1604 if (filenames->tableSize == 1 && outFileName) {
1605 operationResult = FIO_decompressFilename(fCtx, prefs, outFileName, filenames->fileNames[0], dictFileName);
1607 operationResult = FIO_decompressMultipleFilenames(fCtx, prefs, filenames->fileNames, outMirroredDirName, outDirName, outFileName, dictFileName);
1610 DISPLAYLEVEL(1, "Decompression not supported \n");
1615 FIO_freePreferences(prefs);
1616 FIO_freeContext(fCtx);
1617 if (main_pause) waitEnter();
1618 UTIL_freeFileNamesTable(filenames);
1619 UTIL_freeFileNamesTable(file_of_names);
1620 #ifndef ZSTD_NOTRACE
1624 return operationResult;