Port lib/legacy/zstd_v01.c (the frozen zstd v0.1 decoder) to
rust/src/legacy/zstd_v01.rs as the first legacy-format port on the new
scaffolding, and reduce the C file to a declaration-only shim that
keeps its header includes for configuration and platform preprocessor
behavior.
Frozen-decoder policy: zstd_v01.c embeds its own v0.1-era FSE and
Huff0 snapshot, distinct from every other release. The Rust port is a
line-by-line translation with the same table layouts (FSE_DTable as a
u32 header word plus packed newState/symbol/nbBits entries, the Huff0
u16 DTable with byte/nbBits pairs), the same arithmetic including
wrap-around and pointer-comparison quirks (e.g. the offset-vs-base
address check in ZSTD_execSequence), the same internal FSE error space
(size_t)-1..-7, and the same public ZSTD error codes. It reuses no
modern Rust entropy module; its only crate dependency is `errors`,
matching the C file's error_private.h include. The 32-bit-only reload
points are kept as compile-time conditions on usize::BITS.
Symbol takeover boundary: all nine ZSTDv01_* entry points from
zstd_v01.h now come from Rust as context-free #[no_mangle] extern "C"
functions (isError, decompress, decompressDCtx,
findFrameSizeInfoLegacy, createDCtx, freeDCtx, resetDCtx,
nextSrcSizeToDecompress, decompressContinue). zstd_legacy.h only uses
the first four for v0.1; streaming for v0.1-v0.3 intentionally returns
version_unsupported there, unchanged. The ZSTDv01_Dctx struct
definition moves entirely into Rust: C code only ever holds an opaque
pointer (zstd_v01.h forward-declares the type), and the context is
malloc/free-allocated exactly like the C version so create/free may
pair across the language boundary.
Byte-identity verification against the pristine pre-migration C build
(f8745da6, pure C, ZSTD_LEGACY_SUPPORT=1):
- Real v0.1 frames were generated by building the v0.1.0 git tag and
compressing text, random, and 426 KB multi-block inputs. A one-shot
ZSTD_decompress harness linked once against the pristine C libzstd.a
and once against the Rust-backed libzstd.a produced bit-identical
outputs for all frames.
- A direct ZSTDv01_* probe (one-shot decode, dst-too-small, truncated
input, bad magic, findFrameSizeInfoLegacy, and the streaming
continue loop) printed identical results, including exact error
codes (-70 dstSize_tooSmall, -72 srcSize_wrong, -10 prefix_unknown)
and identical dBound values.
- zstd -l -v on v0.1 files matches the pristine binary; CLI streaming
decode of v0.1 fails with the same "Version not supported" in both,
by design of zstd_legacy.h.
Unit tests embed three v0.1.0-generated fixtures (entropy-coded,
raw-block, and four-block frames) plus the truncation, bad-magic,
small-destination, and streaming-API cases, all asserting the exact C
error codes above. Note that `make -C tests test-legacy` only covers
v0.4+ frames, so the embedded fixtures and the harness comparison are
the actual v0.1 coverage.
Test plan:
- cd rust && cargo fmt --check && cargo clippy --all-targets
--features legacy-v01 -- -D warnings && cargo test --all-targets
--features legacy-v01 (127 tests, 9 for v0.1)
- cargo clippy/test --no-default-features --features
decompression,legacy-v01 (module builds standalone)
- make -C tests fuzzer && ./tests/fuzzer -i1 --no-big-tests, also with
ZSTD_LEGACY_SUPPORT=1 (mixed Rust v0.1 + C v0.2-0.7 link)
- make -C tests test-rust-lib-smoke && make -C tests test-legacy
- make -C programs zstd (default and ZSTD_LEGACY_SUPPORT=1); nm shows
the nine ZSTDv01_* symbols provided by Rust at level 1
- make -C lib libzstd.a ZSTD_LEGACY_SUPPORT=0 (no legacy symbols) and
meson -Dlegacy_level=1 shared library exporting all nine
Zstandard library files
The lib directory is split into several sub-directories, in order to make it easier to select or exclude features.
Building
Makefile script is provided, supporting Makefile conventions,
including commands variables, staged install, directory variables and standard targets.
make: generates both static and dynamic librariesmake install: install libraries and headers in target system directories
libzstd default scope is pretty large, including compression, decompression, dictionary builder,
and support for decoding legacy formats >= v0.5.0.
The scope can be reduced on demand (see paragraph modular build).
Multithreading support
When building with make, by default the dynamic library is multithreaded and static library is single-threaded (for compatibility reasons).
Enabling multithreading requires 2 conditions :
- set build macro
ZSTD_MULTITHREAD(-DZSTD_MULTITHREADforgcc) - for POSIX systems : compile with pthread (
-pthreadcompilation flag forgcc)
For convenience, we provide a build target to generate multi and single threaded libraries:
- Force enable multithreading on both dynamic and static libraries by appending
-mtto the target, e.g.make lib-mt. Note that the.pcgenerated on callingmake lib-mtwill already include the require Libs and Cflags. - Force disable multithreading on both dynamic and static libraries by appending
-nomtto the target, e.g.make lib-nomt. - By default, as mentioned before, dynamic library is multithreaded, and static library is single-threaded, e.g.
make lib.
When linking a POSIX program with a multithreaded version of libzstd,
note that it's necessary to invoke the -pthread flag during link stage.
The .pc generated from make install or make install-pc always assume a single-threaded static library
is compiled. To correctly generate a .pc for the multi-threaded static library, set MT=1 as ENV variable.
Multithreading capabilities are exposed
via the advanced API defined in lib/zstd.h.
API
Zstandard's stable API is exposed within lib/zstd.h.
Advanced API
Optional advanced features are exposed via :
-
lib/zstd_errors.h: translatessize_tfunction results into aZSTD_ErrorCode, for accurate error handling. -
ZSTD_STATIC_LINKING_ONLY: if this macro is defined before includingzstd.h, it unlocks access to the experimental API, exposed in the second part ofzstd.h. All definitions in the experimental APIs are unstable, they may still change in the future, or even be removed. As a consequence, experimental definitions shall never be used with dynamic library ! Only static linking is allowed.
Modular build
It's possible to compile only a limited set of features within libzstd.
The file structure is designed to make this selection manually achievable for any build system :
-
Directory
lib/commonis always required, for all variants. -
Compression source code lies in
lib/compress -
Decompression source code lies in
lib/decompress -
It's possible to include only
compressor onlydecompress, they don't depend on each other. -
lib/dictBuilder: makes it possible to generate dictionaries from a set of samples. The API is exposed inlib/dictBuilder/zdict.h. This module depends on bothlib/commonandlib/compress. -
lib/legacy: makes it possible to decompress legacy zstd formats, starting fromv0.1.0. This module depends onlib/commonandlib/decompress. To enable this feature, defineZSTD_LEGACY_SUPPORTduring compilation. Specifying a number limits versions supported to that version onward. For example,ZSTD_LEGACY_SUPPORT=2means : "support legacy formats >= v0.2.0". Conversely,ZSTD_LEGACY_SUPPORT=0means "do not support legacy formats". By default, this build macro is set asZSTD_LEGACY_SUPPORT=5. Decoding supported legacy format is a transparent capability triggered within decompression functions. It's also allowed to invoke legacy API directly, exposed inlib/legacy/zstd_legacy.h. Each version does also provide its own set of advanced API. For example, advanced API for versionv0.4is exposed inlib/legacy/zstd_v04.h. -
While invoking
make libzstd, it's possible to define build macrosZSTD_LIB_COMPRESSION,ZSTD_LIB_DECOMPRESSION,ZSTD_LIB_DICTBUILDER, andZSTD_LIB_DEPRECATEDas0to forgo compilation of the corresponding features. This will also disable compilation of all dependencies (e.g.ZSTD_LIB_COMPRESSION=0will also disable dictBuilder). -
There are a number of options that can help minimize the binary size of
libzstd.The first step is to select the components needed (using the above-described
ZSTD_LIB_COMPRESSIONetc.).The next step is to set
ZSTD_LIB_MINIFYto1when invokingmake. This disables various optional components and changes the compilation flags to prioritize space-saving.Detailed options: Zstandard's code and build environment is set up by default to optimize above all else for performance. In pursuit of this goal, Zstandard makes significant trade-offs in code size. For example, Zstandard often has more than one implementation of a particular component, with each implementation optimized for different scenarios. For example, the Huffman decoder has complementary implementations that decode the stream one symbol at a time or two symbols at a time. Zstd normally includes both (and dispatches between them at runtime), but by defining
HUF_FORCE_DECOMPRESS_X1orHUF_FORCE_DECOMPRESS_X2, you can force the use of one or the other, avoiding compilation of the other. Similarly,ZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORTandZSTD_FORCE_DECOMPRESS_SEQUENCES_LONGforce the compilation and use of only one or the other of two decompression implementations. The smallest binary is achieved by usingHUF_FORCE_DECOMPRESS_X1andZSTD_FORCE_DECOMPRESS_SEQUENCES_SHORT(implied byZSTD_LIB_MINIFY).On the compressor side, Zstd's compression levels map to several internal strategies. In environments where the higher compression levels aren't used, it is possible to exclude all but the fastest strategy with
ZSTD_LIB_EXCLUDE_COMPRESSORS_DFAST_AND_UP=1. (Note that this will change the behavior of the default compression level.) Or if you want to retain the default compressor as well, you can setZSTD_LIB_EXCLUDE_COMPRESSORS_GREEDY_AND_UP=1, at the cost of an additional ~20KB or so.For squeezing the last ounce of size out, you can also define
ZSTD_NO_INLINE, which disables inlining, andZSTD_STRIP_ERROR_STRINGS, which removes the error messages that are otherwise returned byZSTD_getErrorName(implied byZSTD_LIB_MINIFY).Finally, when integrating into your application, make sure you're doing link- time optimization and unused symbol garbage collection (via some combination of, e.g.,
-flto,-ffat-lto-objects,-fuse-linker-plugin,-ffunction-sections,-fdata-sections,-fmerge-all-constants,-Wl,--gc-sections,-Wl,-z,norelro, and an archiver that understands the compiler's intermediate representation, e.g.,AR=gcc-ar). Consult your compiler's documentation. -
While invoking
make libzstd, the build macroZSTD_LEGACY_MULTITHREADED_API=1will expose the deprecatedZSTDMTAPI exposed byzstdmt_compress.hin the shared library, which is now hidden by default. -
The build macro
STATIC_BMI2can be set to 1 to force usage ofbmi2instructions. It is generally not necessary to set this build macro, becauseSTATIC_BMI2will be automatically set to 1 on detecting the presence of the corresponding instruction set in the compilation target. It's nonetheless available as an optional manual toggle for better control, and can also be used to forcefully disablebmi2instructions by setting it to 0. -
The build macro
DYNAMIC_BMI2can be set to 1 or 0 in order to generate binaries which can detect at runtime the presence of BMI2 instructions, and use them only if present. These instructions contribute to better performance, notably on the decoder side. By default, this feature is automatically enabled on detecting the right instruction set (x64) and compiler (clang or gcc >= 5). It's obviously disabled for different cpus, or when BMI2 instruction set is required by the compiler command line (in this case, only the BMI2 code path is generated). Setting this macro will either force to generate the BMI2 dispatcher (1) or prevent it (0). It overrides automatic detection. -
The build macro
ZSTD_NO_UNUSED_FUNCTIONScan be defined to hide the definitions of functions that zstd does not use. Not all unused functions are hidden, but they can be if needed. Currently, this macro will hide function definitions in FSE and HUF that use an excessive amount of stack space. -
The build macro
ZSTD_NO_INTRINSICScan be defined to disable all explicit intrinsics. Compiler builtins are still used. -
The build macro
ZSTD_DECODER_INTERNAL_BUFFERcan be set to control the amount of extra memory used during decompression to store literals. This defaults to 64kB. Reducing this value reduces the memory footprint ofZSTD_DCtxdecompression contexts, but might also result in a small decompression speed cost. -
The C compiler macros
ZSTDLIB_VISIBLE,ZSTDERRORLIB_VISIBLEandZDICTLIB_VISIBLEcan be overridden to control the visibility of zstd's API. Additionally,ZSTDLIB_STATIC_APIandZDICTLIB_STATIC_APIcan be overridden to control the visibility of zstd's static API. Specifically, it can be set toZSTDLIB_HIDDENto hide the symbols from the shared library. These macros default toZSTDLIB_VISIBILITY,ZSTDERRORLIB_VSIBILITY, andZDICTLIB_VISIBILITYif unset, for backwards compatibility with the old macro names. -
The C compiler macro
HUF_DISABLE_FAST_DECODEdisables the newer Huffman fast C and assembly decoding loops. You may want to use this macro if these loops are slower on your platform.
Windows : using MinGW+MSYS to create DLL
DLL can be created using MinGW+MSYS with the make libzstd command.
This command creates dll\libzstd.dll and the import library dll\libzstd.lib.
The import library is only required with Visual C++.
The header file zstd.h and the dynamic library dll\libzstd.dll are required to
compile a project using gcc/MinGW.
The dynamic library has to be added to linking options.
It means that if a project that uses ZSTD consists of a single test-dll.c
file it should be linked with dll\libzstd.dll. For example:
gcc $(CFLAGS) -Iinclude/ test-dll.c -o test-dll dll\libzstd.dll
The compiled executable will require ZSTD DLL which is available at dll\libzstd.dll.
Advanced Build options
The build system requires a hash function in order to
separate object files created with different compilation flags.
By default, it tries to use md5sum or equivalent.
The hash function can be manually switched by setting the HASH variable.
For example : make HASH=xxhsum
The hash function needs to generate at least 64-bit using hexadecimal format.
When no hash function is found,
the Makefile just generates all object files into the same default directory,
irrespective of compilation flags.
This functionality only matters if libzstd is compiled multiple times
with different build flags.
The build directory, where object files are stored
can also be manually controlled using variable BUILD_DIR,
for example make BUILD_DIR=objectDir/v1.
In which case, the hash function doesn't matter.
Deprecated API
Obsolete API on their way out are stored in directory lib/deprecated.
At this stage, it contains older streaming prototypes, in lib/deprecated/zbuff.h.
These prototypes will be removed in some future version.
Consider migrating code towards supported streaming API exposed in zstd.h.
Miscellaneous
The other files are not source code. There are :
BUCK: support forbuckbuild system (https://buckbuild.com/)Makefile:makescript to build and install zstd library (static and dynamic)README.md: this filedll/: resources directory for Windows compilationlibzstd.pc.in: script forpkg-config(used inmake install)