diff --git a/.circleci/config.yml b/.circleci/config.yml index ae5aa3984f06cbc90f5b6bc347e7e022c2642770..f1ac6c0ffb805c7e3b6b6b011d2aa1d7faba740a 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -43,26 +43,26 @@ jobs: # Test # This would typically be a build job when using workflows, possibly combined with build # This is based on your 1.0 configuration file or project settings - - run: CFLAGS= make clangtest && make clean - - run: g++ -v; make cxxtest && make clean - - run: gcc -v; g++ -v; make ctocpptest && make clean + - run: CC=clang CFLAGS="-Werror -O0" make all && make clean + - run: c++ -v; make cxxtest && make clean + - run: cc -v; c++ -v; make ctocxxtest && make clean - run: gcc-5 -v; CC=gcc-5 CFLAGS="-O2 -Werror" make check && make clean - run: gcc-5 -v; CC=gcc-5 CFLAGS="-O2 -m32 -Werror" CPPFLAGS=-I/usr/include/x86_64-linux-gnu make check && make clean - - run: gcc-6 -v; CC=gcc-6 MOREFLAGS="-O2 -Werror" make check && make clean - - run: make cmake && make clean + - run: gcc-6 -v; CC=gcc-6 CFLAGS="-O2 -Werror" make check && make clean + - run: make cmakebuild && make clean - run: make -C tests test-lz4 - run: make -C tests test-lz4c - run: make -C tests test-frametest - run: make -C tests test-fuzzer && make clean - - run: make -C lib all && make clean - - run: pyenv global 3.4.4; make versionsTest MOREFLAGS=-I/usr/include/x86_64-linux-gnu && make clean - - run: make travis-install && make clean + - run: make -C lib all && make clean + - run: pyenv global 3.4.4; CPPFLAGS=-I/usr/include/x86_64-linux-gnu make versionsTest && make clean + - run: make test-install && make clean - run: gcc -v; CFLAGS="-O2 -m32 -Werror" CPPFLAGS=-I/usr/include/x86_64-linux-gnu make check && make clean - run: clang -v; make staticAnalyze && make clean - - run: make platformTest CC=powerpc-linux-gnu-gcc QEMU_SYS=qemu-ppc-static && make clean - - run: make platformTest CC=powerpc-linux-gnu-gcc QEMU_SYS=qemu-ppc64-static MOREFLAGS=-m64 && make clean - - run: make platformTest CC=arm-linux-gnueabi-gcc QEMU_SYS=qemu-arm-static && make clean - - run: make platformTest CC=aarch64-linux-gnu-gcc QEMU_SYS=qemu-aarch64-static && make clean + - run: make platformTest CC=powerpc-linux-gnu-gcc QEMU_SYS=qemu-ppc-static V=1 && make clean + - run: CFLAGS=-m64 LDFLAGS=-m64 make platformTest CC=powerpc-linux-gnu-gcc QEMU_SYS=qemu-ppc64-static V=1 && make clean + - run: make platformTest CC=arm-linux-gnueabi-gcc QEMU_SYS=qemu-arm-static V=1 && make clean + - run: make platformTest CC=aarch64-linux-gnu-gcc QEMU_SYS=qemu-aarch64-static V=1 && make clean # Teardown # If you break your build into multiple jobs with workflows, you will probably want to do the parts of this that are relevant in each # Save test results diff --git a/.cirrus.yml b/.cirrus.yml index e42353855f1bd5f9e669732f5c245632eeee2b57..d9936c8cc45c0a630ad7f11d619fde34c82b7299 100644 --- a/.cirrus.yml +++ b/.cirrus.yml @@ -1,5 +1,9 @@ -freebsd_instance: - image_family: freebsd-12-2 - task: - script: pkg install -y gmake && gmake test + name: FreeBSD + freebsd_instance: + matrix: + image_family: freebsd-14-0 + install_script: pkg install -y gmake + script: | + cc -v + gmake test diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000000000000000000000000000000000000..bc22ba3f059cece4d97642a4dc5a7642fb61519b --- /dev/null +++ b/.clang-format @@ -0,0 +1,132 @@ +# This is the configuration file for clang-format, an automatic code formatter. +# Introduction: https://clang.llvm.org/docs/ClangFormat.html +# Supported options: https://clang.llvm.org/docs/ClangFormatStyleOptions.html + +Language: Cpp +Standard: Latest + +ColumnLimit: 110 + +UseTab: Never +IndentWidth: 4 +PPIndentWidth: 2 +ContinuationIndentWidth: 4 + +LineEnding: LF +InsertNewlineAtEOF: true +KeepEmptyLinesAtTheStartOfBlocks: false +MaxEmptyLinesToKeep: 1 + +IndentCaseBlocks: false +IndentCaseLabels: false +IndentGotoLabels: false +IndentPPDirectives: AfterHash +IndentWrappedFunctionNames: false + +AlignAfterOpenBracket: Align +AlignArrayOfStructures: Right +AlignEscapedNewlines: Left +AlignOperands: Align +AlignConsecutiveAssignments: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + PadOperators: false +AlignConsecutiveBitFields: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false +AlignConsecutiveDeclarations: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false +AlignConsecutiveMacros: + Enabled: true + AcrossEmptyLines: false + AcrossComments: false +AlignTrailingComments: + Kind: Leave + OverEmptyLines: 0 + +BinPackArguments: true +BinPackParameters: false +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: false + +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortEnumsOnASingleLine: true +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: AllIfsAndElse +AllowShortLoopsOnASingleLine: false + +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +BraceWrapping: + AfterCaseLabel: false + AfterControlStatement: Never + AfterEnum: false + AfterExternBlock: false + AfterFunction: true + AfterStruct: false + AfterUnion: false + BeforeElse: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: false +BreakAfterAttributes: Never +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Custom +BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTernaryOperators: true + +DerivePointerAlignment: false +PointerAlignment: Left + +QualifierAlignment: Custom +QualifierOrder: ["inline", "static", "volatile", "restrict", "const", "type"] + +ReflowComments: false +BreakStringLiterals: false +RemoveSemicolon: true +RemoveParentheses: ReturnStatement +InsertBraces: false +SeparateDefinitionBlocks: Always + +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeParens: ControlStatements +BitFieldColonSpacing: Both +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false +SpacesBeforeTrailingComments: 1 +SpacesInSquareBrackets: false +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 + +SortIncludes: Never +IncludeBlocks: Preserve +IncludeIsMainRegex: "" +IncludeCategories: + - {Regex: "<.*>", Priority: -2, CaseSensitive: true} + - {Regex: "\".*\"", Priority: -1, CaseSensitive: true} + +AttributeMacros: ["__capability"] +StatementAttributeLikeMacros: [] +StatementMacros: [] + +PenaltyBreakAssignment: 200 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakString: 1000 +PenaltyExcessCharacter: 10 +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 60 diff --git a/.gitignore b/.gitignore index ed02057e53ac263b67de31422d39b9dbd2ee609f..cacde293035f1e9ddb29dd817808cd3f8c95be8a 100644 --- a/.gitignore +++ b/.gitignore @@ -21,11 +21,16 @@ lz4 # IDE / editors files .clang_complete +.vscode _codelite/ _codelite_lz4/ bin/ *.zip *.swp +compile_flags.txt +compile_commands.json +.vscode +.cache # analyzers infer-out @@ -41,3 +46,7 @@ ld.exe* # test artifacts *.lz4 tmp* + +# generated Windows resource files +lib/*.rc +programs/*.rc diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 0aeea6ef0acf87fd775e2ddac143a940e070675b..0000000000000000000000000000000000000000 --- a/.travis.yml +++ /dev/null @@ -1,42 +0,0 @@ -language: c - -matrix: - fast_finish: true - include: - - - name: aarch64 real-hw tests - arch: arm64 - script: - - make test - - - name: PPC64LE real-hw tests - arch: ppc64le - script: - - make test - - - name: IBM s390x real-hw tests - arch: s390x - script: - - make test - - # tag-specific test - - name: tag build - if: tag =~ ^v[0-9]\.[0-9] - os: linux - script: - - make -C tests checkTag - - tests/checkTag "$TRAVIS_BRANCH" - - # oss-fuzz compilation test - - name: Compile OSS-Fuzz targets - script: - - ./ossfuzz/travisoss.sh - - # Unicode lint - # See https://github.com/lz4/lz4/issues/1018 - - name: Run Unicode lint - script: - - ./tests/unicode_lint.sh - - allow_failures: - - env: ALLOW_FAILURES=true diff --git a/CODING_STYLE b/CODING_STYLE new file mode 100644 index 0000000000000000000000000000000000000000..0e94f1e92484e73c7355584968d98b739477a078 --- /dev/null +++ b/CODING_STYLE @@ -0,0 +1,57 @@ +LZ4 CODING STYLE +================ + +When contributing code and patches to the `LZ4` project, the following rules are expected to be followed for a successful merge. + + +Library +------- + +The library's source code in `lib/` directory has a BSD 2-clause license. +It's designed to be integrated into 3rd party applications. + +It adheres relatively strictly to vanilla `C90`, with the following exceptions: +- `long long` type is required, in order to support 64-bit values +- Variadic Macros are used for debug mode (but not required in release mode) + +Beyond that, all other rules and limitations of C90 must be respected, including `/* ... */` comment style only, and variable declaration at top of block only. The automated CI test suite will check for these rules. + +The code is allowed to use more modern variants (C99 / C11 / C23) when useful +as long as it provides a clean C90 backup for older compilers. +For example, C99+ compilers will employ the `restrict` keyword, while `C90` ones will ignore it, thanks to conditional macros. +This ensures maximum portability across a wide range of systems. + +Moreover, in the interest of safety, the code has to respect a fairly strigent list of additional restrictions, provided through warning flags, the list of which is maintained within `Makefile`. +Among the less common ones, we want the source to be compatible with `-Wc++-compat`, which ensures that the code can be compiled "as is", with no modification, as C++ code. It makes it possible to copy-paste the code into other C++ source files, or the source files are just dropped into a C++ environment which then compiles them as C++ source files. + + +Command Line Interface +---------------------- + +The CLI executable's source code in `programs/` directory has a GPLv2+ license. +While it's designed to be portable and freely distributable, it's not meant to be integrated into 3rd party applications. +The license difference is meant to reflect that choice. + +Similar to the library, the CLI adheres relatively strictly to vanilla `C90`, and features the same exceptions: +- `long long` requirement for 64-bit values +- Variadic Macros for console messages (now used all the time, not just debug mode) + +The code can also use system-specific libraries and symbols (such as `posix` ones) +as long as it provides a backup for plain `C90` platforms. +It's even allowed to lose capabilities, as long as the CLI can be cleanly compiled on `C90`. +For example, systems without `` support nor Completion Ports will just not feature multi-threading support, and run single threaded. + +In the interest of build familiarity, the CLI source code also respects the same set of advanced warning flags as the library. +That being said, this last part is debatable and could deviate in the future. +For example, there are less reasons to support `-Wc++-compat` on the CLI side, since it's not meant to be integrated into 3rd party applications. + + +Others +------ + +The repository includes other directories with their own set of compilable projects, such as `tests/`, `examples/` and `contrib/`. + +These repositories do not have to respect the same set of restrictions, and can employ a larger array of different languages. +For example, some tests employ `sh`, and others employ `python`. + +These directories may nonetheless include several targets employing the same coding convention as the `lz4` library. This is in a no way a rule, more like a side effect of build familiarity. diff --git a/LICENSE b/LICENSE index 1b84cc30f0361b13d56bf8c2fbe043493c08fbe6..ba8a2900f8b180fefc0c16f8a35076ef290c9492 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ This repository uses 2 different licenses : - all files in the `lib` directory use a BSD 2-Clause license -- all other files use a GPLv2 license, unless explicitly stated otherwise +- all other files use a GPL-2.0-or-later license, unless explicitly stated otherwise Relevant license is reminded at the top of each source file, and with presence of COPYING or LICENSE file in associated directories. diff --git a/Makefile b/Makefile index e70c3dbd334ead295ce05f32170d5364c5b2eba1..dbf4910f9917f06accf4bcd90c51644c7c843328 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # ################################################################ # LZ4 - Makefile -# Copyright (C) Yann Collet 2011-2020 +# Copyright (C) Yann Collet 2011-2023 # All rights reserved. # # BSD license @@ -61,7 +61,8 @@ lz4 : liblz4.a lz4-release : lib-release lz4 lz4-release : $(MAKE) -C $(PRGDIR) $@ - cp $(PRGDIR)/lz4$(EXT) . + $(LN_SF) $(PRGDIR)/lz4$(EXT) . + echo lz4 build completed .PHONY: examples examples: liblz4.a @@ -84,7 +85,7 @@ clean: $(MAKE) -C $(FUZZDIR) $@ > $(VOID) $(MAKE) -C contrib/gen_manual $@ > $(VOID) $(RM) lz4$(EXT) - $(RM) -r $(CMAKE_BUILD_DIR) + $(RM) -r $(CMAKE_BUILD_DIR) $(MESON_BUILD_DIR) @echo Cleaning completed @@ -99,8 +100,8 @@ install uninstall: $(MAKE) -C $(LZ4DIR) $@ $(MAKE) -C $(PRGDIR) $@ -.PHONY: travis-install -travis-install: +.PHONY: test-install +test-install: $(MAKE) -j1 install DESTDIR=~/install_test_dir endif # POSIX_ENV @@ -113,11 +114,18 @@ HOST_OS = MSYS CMAKE_PARAMS = -G"MSYS Makefiles" endif -.PHONY: cmake -cmake: +.PHONY: cmakebuild +cmakebuild: mkdir -p $(CMAKE_BUILD_DIR) cd $(CMAKE_BUILD_DIR); $(CMAKE) $(CMAKE_PARAMS) ..; $(CMAKE) --build . +MESON ?= meson +MESON_BUILD_DIR ?= mesonBuildDir + +.PHONY: mesonbuild +mesonbuild: + $(MESON) setup --fatal-meson-warnings --buildtype=debug -Db_lundef=false -Dauto_features=enabled -Dprograms=true -Dcontrib=true -Dtests=true -Dexamples=true build/meson $(MESON_BUILD_DIR) + $(MESON) test -C $(MESON_BUILD_DIR) #------------------------------------------------------------------------ # make tests validated only for MSYS and Posix environments @@ -137,23 +145,6 @@ test: $(MAKE) -C $(TESTDIR) $@ $(MAKE) -C $(EXDIR) $@ -.PHONY: clangtest -clangtest: CFLAGS += -Werror -Wconversion -Wno-sign-conversion -clangtest: CC = clang -clangtest: clean - $(CC) -v - $(MAKE) -C $(LZ4DIR) all CC=$(CC) - $(MAKE) -C $(PRGDIR) all CC=$(CC) - $(MAKE) -C $(TESTDIR) all CC=$(CC) - -.PHONY: clangtest-native -clangtest-native: CFLAGS = -O3 -Werror -Wconversion -Wno-sign-conversion -clangtest-native: clean - clang -v - $(MAKE) -C $(LZ4DIR) all CC=clang - $(MAKE) -C $(PRGDIR) native CC=clang - $(MAKE) -C $(TESTDIR) native CC=clang - .PHONY: usan usan: CC = clang usan: CFLAGS = -O3 -g -fsanitize=undefined -fno-sanitize-recover=undefined -fsanitize-recover=pointer-overflow @@ -162,10 +153,10 @@ usan: clean CC=$(CC) CFLAGS='$(CFLAGS)' LDFLAGS='$(LDFLAGS)' $(MAKE) test FUZZER_TIME="-T30s" NB_LOOPS=-i1 .PHONY: usan32 -usan32: CFLAGS = -m32 -O3 -g -fsanitize=undefined +usan32: CFLAGS = -m32 -O3 -g -fsanitize=undefined -fno-sanitize-recover=undefined -fsanitize-recover=pointer-overflow usan32: LDFLAGS = $(CFLAGS) usan32: clean - $(MAKE) test FUZZER_TIME="-T30s" NB_LOOPS=-i1 + CFLAGS='$(CFLAGS)' LDFLAGS='$(LDFLAGS)' $(MAKE) V=1 test FUZZER_TIME="-T30s" NB_LOOPS=-i1 SCANBUILD ?= scan-build SCANBUILD_FLAGS += --status-bugs -v --force-analyze-debug-code @@ -181,24 +172,36 @@ cppcheck: platformTest: clean @echo "\n ---- test lz4 with $(CC) compiler ----" $(CC) -v - CFLAGS="-O3 -Werror" $(MAKE) -C $(LZ4DIR) all - CFLAGS="-O3 -Werror -static" $(MAKE) -C $(PRGDIR) all - CFLAGS="-O3 -Werror -static" $(MAKE) -C $(TESTDIR) all + CFLAGS="$(CFLAGS) -O3 -Werror" $(MAKE) -C $(LZ4DIR) all + CFLAGS="$(CFLAGS) -O3 -Werror -static" $(MAKE) -C $(PRGDIR) all + CFLAGS="$(CFLAGS) -O3 -Werror -static" $(MAKE) -C $(TESTDIR) all $(MAKE) -C $(TESTDIR) test-platform .PHONY: versionsTest -versionsTest: clean +versionsTest: + $(MAKE) -C $(TESTDIR) clean $(MAKE) -C $(TESTDIR) $@ .PHONY: test-freestanding test-freestanding: - $(MAKE) -C $(TESTDIR) clean $@ + $(MAKE) -C $(TESTDIR) clean + $(MAKE) -C $(TESTDIR) $@ + +# test linking C libraries from C++ executables +.PHONY: ctocxxtest +ctocxxtest: LIBCC="$(CC)" +ctocxxtest: EXECC="$(CXX) -Wno-deprecated" +ctocxxtest: CFLAGS=-O0 +ctocxxtest: + CC=$(LIBCC) $(MAKE) -C $(LZ4DIR) CFLAGS="$(CFLAGS)" all + CC=$(LIBCC) $(MAKE) -C $(TESTDIR) CFLAGS="$(CFLAGS)" lz4.o lz4hc.o lz4frame.o + CC=$(EXECC) $(MAKE) -C $(TESTDIR) CFLAGS="$(CFLAGS)" all .PHONY: cxxtest cxx32test +cxx32test: CFLAGS += -m32 cxxtest cxx32test: CC := "$(CXX) -Wno-deprecated" cxxtest cxx32test: CFLAGS = -O3 -Wall -Wextra -Wundef -Wshadow -Wcast-align -Werror -cxx32test: CFLAGS += -m32 -cxxtest cxx32test: clean +cxxtest cxx32test: $(CXX) -v CC=$(CC) $(MAKE) -C $(LZ4DIR) all CFLAGS="$(CFLAGS)" CC=$(CC) $(MAKE) -C $(PRGDIR) all CFLAGS="$(CFLAGS)" @@ -206,34 +209,25 @@ cxxtest cxx32test: clean .PHONY: cxx17build cxx17build : CC = "$(CXX) -Wno-deprecated" -cxx17build : CFLAGS = -std=c++17 -Wall -Wextra -Wundef -Wshadow -Wcast-align -Werror -pedantic +cxx17build : CFLAGS = -std=c++17 -Wall -Wextra -Wundef -Wshadow -Wcast-align -Werror -Wpedantic cxx17build : clean $(CXX) -v CC=$(CC) $(MAKE) -C $(LZ4DIR) all CFLAGS="$(CFLAGS)" CC=$(CC) $(MAKE) -C $(PRGDIR) all CFLAGS="$(CFLAGS)" CC=$(CC) $(MAKE) -C $(TESTDIR) all CFLAGS="$(CFLAGS)" -.PHONY: ctocpptest -ctocpptest: LIBCC="$(CC)" -ctocpptest: TESTCC="$(CXX)" -ctocpptest: CFLAGS= -ctocpptest: clean - CC=$(LIBCC) $(MAKE) -C $(LZ4DIR) CFLAGS="$(CFLAGS)" all - CC=$(LIBCC) $(MAKE) -C $(TESTDIR) CFLAGS="$(CFLAGS)" lz4.o lz4hc.o lz4frame.o - CC=$(TESTCC) $(MAKE) -C $(TESTDIR) CFLAGS="$(CFLAGS)" all - .PHONY: c_standards c_standards: clean c_standards_c11 c_standards_c99 c_standards_c90 .PHONY: c_standards_c90 c_standards_c90: clean - $(MAKE) clean; CFLAGS="-std=c90 -Werror -pedantic -Wno-long-long -Wno-variadic-macros" $(MAKE) allmost - $(MAKE) clean; CFLAGS="-std=gnu90 -Werror -pedantic -Wno-long-long -Wno-variadic-macros" $(MAKE) allmost + $(MAKE) clean; CFLAGS="-std=c90 -Werror -Wpedantic -Wno-long-long -Wno-variadic-macros" $(MAKE) allmost + $(MAKE) clean; CFLAGS="-std=gnu90 -Werror -Wpedantic -Wno-long-long -Wno-variadic-macros" $(MAKE) allmost .PHONY: c_standards_c99 c_standards_c99: clean - $(MAKE) clean; CFLAGS="-std=c99 -Werror -pedantic" $(MAKE) all - $(MAKE) clean; CFLAGS="-std=gnu99 -Werror -pedantic" $(MAKE) all + $(MAKE) clean; CFLAGS="-std=c99 -Werror -Wpedantic" $(MAKE) all + $(MAKE) clean; CFLAGS="-std=gnu99 -Werror -Wpedantic" $(MAKE) all .PHONY: c_standards_c11 c_standards_c11: clean @@ -243,7 +237,8 @@ c_standards_c11: clean # are correctly transmitted at compilation stage. # This test is meant to detect issues like https://github.com/lz4/lz4/issues/958 .PHONY: standard_variables -standard_variables: clean +standard_variables: + $(MAKE) clean @echo ================= @echo Check support of Makefile Standard variables through environment @echo note : this test requires V=1 to work properly @@ -259,13 +254,13 @@ standard_variables: clean # supported in some part of the Makefile, and missed in others. # So the test checks if they are present the _right nb of times_. # However, checking static quantities makes this test brittle, - # because quantities (7, 2 and 1) can still evolve in future, + # because quantities (10, 2 and 1) can still evolve in future, # for example when source directories or Makefile evolve. - if [ $$(grep CC_TEST tmpsv | wc -l) -ne 7 ]; then \ + if [ $$(grep CC_TEST tmpsv | wc -l) -ne 10 ]; then \ echo "CC environment variable missed" && False; fi - if [ $$(grep CFLAGS_TEST tmpsv | wc -l) -ne 7 ]; then \ + if [ $$(grep CFLAGS_TEST tmpsv | wc -l) -ne 10 ]; then \ echo "CFLAGS environment variable missed" && False; fi - if [ $$(grep CPPFLAGS_TEST tmpsv | wc -l) -ne 7 ]; then \ + if [ $$(grep CPPFLAGS_TEST tmpsv | wc -l) -ne 10 ]; then \ echo "CPPFLAGS environment variable missed" && False; fi if [ $$(grep LDFLAGS_TEST tmpsv | wc -l) -ne 2 ]; then \ echo "LDFLAGS environment variable missed" && False; fi diff --git a/Makefile.inc b/Makefile.inc index e78298c3204a2b242570bd90ff7adc915a3b3711..0ccc2da66e929810cbbb7700eaa6039686117889 100644 --- a/Makefile.inc +++ b/Makefile.inc @@ -38,26 +38,26 @@ ifeq ($(TARGET_OS),) endif ifneq (,$(filter Windows%,$(TARGET_OS))) -LIBLZ4 = liblz4-$(LIBVER_MAJOR) -LIBLZ4_EXP = liblz4.lib -WINBASED = yes +LIBLZ4_NAME = liblz4-$(LIBVER_MAJOR) +LIBLZ4_EXP = liblz4.lib +WINBASED = yes else -LIBLZ4_EXP = liblz4.dll.a +LIBLZ4_EXP = liblz4.dll.a ifneq (,$(filter MINGW%,$(TARGET_OS))) -LIBLZ4 = liblz4 -WINBASED = yes +LIBLZ4_NAME = liblz4 +WINBASED = yes else ifneq (,$(filter MSYS%,$(TARGET_OS))) -LIBLZ4 = msys-lz4-$(LIBVER_MAJOR) -WINBASED = yes +LIBLZ4_NAME = msys-lz4-$(LIBVER_MAJOR) +WINBASED = yes else ifneq (,$(filter CYGWIN%,$(TARGET_OS))) -LIBLZ4 = cyglz4-$(LIBVER_MAJOR) -WINBASED = yes +LIBLZ4_NAME = cyglz4-$(LIBVER_MAJOR) +WINBASED = yes else -LIBLZ4 = liblz4.$(SHARED_EXT_VER) -WINBASED = no -EXT = +LIBLZ4_NAME = liblz4 +WINBASED = no +EXT = endif endif endif @@ -65,9 +65,11 @@ endif ifeq ($(WINBASED),yes) EXT = .exe -WINDRES = windres +WINDRES ?= windres endif +LIBLZ4 = $(LIBLZ4_NAME).$(SHARED_EXT_VER) + #determine if dev/nul based on host environment ifneq (,$(filter MINGW% MSYS% CYGWIN%,$(shell $(UNAME)))) VOID := /dev/null @@ -108,4 +110,4 @@ endif INSTALL_PROGRAM ?= $(INSTALL) -m 755 INSTALL_DATA ?= $(INSTALL) -m 644 -INSTALL_DIR ?= $(INSTALL) -d -m 755 +MAKE_DIR ?= $(INSTALL) -d -m 755 diff --git a/NEWS b/NEWS index 0a56992128c05f1cc15418d21efde6bab78924dd..b6c5730fa4c8ca89f14d5309953604bd852f8748 100644 --- a/NEWS +++ b/NEWS @@ -1,3 +1,27 @@ +v1.10.0 +cli : multithreading compression support: improves speed by X times threads allocated +cli : overlap decompression with i/o, improving speed by ~+60% +cli : support environment variables LZ4_CLEVEL and LZ4_NBWORKERS +cli : license of CLI more clearly labelled GPL-2.0-or-later +cli : fix: refuse to compress directories +cli : fix dictionary compression benchmark on multiple files +cli : change: no more implicit `stdout` (except when input is `stdin`) +lib : new level 2, offering mid-way performance (speed and compression) +lib : Improved lz4frame compression speed for small data (up to +160% at 1KB) +lib : Slightly faster (+5%) HC compression speed (levels 3-9), by @JunHe77 +lib : dictionary compression support now in stable status +lib : lz4frame states can be safely reset and reused after a processing error (described by @QrczakMK) +lib : `lz4file` API improvements, by @vsolontsov-volant and @t-mat +lib : new experimental symbol `LZ4_compress_destSize_extState()` +build: cmake minimum version raised to 3.5 +build: cmake improvements, by @foxeng, @Ohjurot, @LocalSpook, @teo-tsirpanis, @ur4t and @t-mat +build: meson scripts are now hosted into `build/` directory, by @eli-schwartz +build: meson improvements, by @tristan957 +build: Visual Studio solutions generated by `cmake` via scripts +port : support for loongArch, risc-v, m68k, mips and sparc architectures +port : improved Visual Studio compatibility, by @t-mat +port : freestanding support improvements, by @t-mat + v1.9.4 perf : faster decoding speed (~+20%) on aarch64 platforms perf : faster decoding speed (~+70%) for -BD4 setting in CLI @@ -9,6 +33,7 @@ api : new experimental function `LZ4F_uncompressedUpdate()`, by @alexmohr cli : `--list` works on `stdin` input, by @Low-power cli : `--no-crc` does not produce (compression) nor check (decompression) checksums cli : fix: `--test` and `--list` produce an error code when parsing invalid input +cli : fix: `--test -m` does no longer create decompressed file artifacts cli : fix: support skippable frames when passed via `stdin`, reported by @davidmankin build: fix: Makefile respects CFLAGS directives passed via environment variable build: `LZ4_FREESTANDING`, new build macro for freestanding environments, by @t-mat diff --git a/README.OpenSource b/README.OpenSource index 9cf521e8d7a6372e63df3b2a64dbaa74e1819484..23862abadd2f34b2401bbcc5bb054795ee2a4c84 100755 --- a/README.OpenSource +++ b/README.OpenSource @@ -3,7 +3,7 @@ "Name": "lz4", "License": "BSD 2-Clause License", "License File": "LICENSE", - "Version Number": "1.9.4", + "Version Number": "1.10.0", "Owner": "chennaidong@huawei.com", "Upstream URL": "https://github.com/lz4/lz4", "Description": "This package provides a streaming interface to LZ4 data streams as well as low level compress and uncompress functions for LZ4 data blocks. The implementation is based on the reference C one." diff --git a/README.md b/README.md index b314e69911367d48a0e79b3c0958a7bc0334d242..5ee643fb88ef068481e15c3676188446039c02ab 100644 --- a/README.md +++ b/README.md @@ -26,10 +26,8 @@ LZ4 library is provided as open-source software using BSD 2-Clause license. |Branch |Status | |------------|---------| -|dev | [![Build Status][travisDevBadge]][travisLink] [![Build status][AppveyorDevBadge]][AppveyorLink] | +|dev | [![Build status][AppveyorDevBadge]][AppveyorLink] | -[travisDevBadge]: https://travis-ci.org/lz4/lz4.svg?branch=dev "Continuous Integration test suite" -[travisLink]: https://travis-ci.org/lz4/lz4 [AppveyorDevBadge]: https://ci.appveyor.com/api/projects/status/github/lz4/lz4?branch=dev&svg=true "Windows test suite" [AppveyorLink]: https://ci.appveyor.com/project/YannCollet/lz4-1lndh @@ -62,7 +60,7 @@ in single-thread mode. [zlib]: http://www.zlib.net/ [Zstandard]: http://www.zstd.net/ -LZ4 is also compatible and optimized for x32 mode, +LZ4 is also compatible and optimized for x32 mode (`-mx32`), for which it provides additional speed performance. @@ -91,7 +89,7 @@ You can download and install LZ4 using the [vcpkg](https://github.com/Microsoft/ cd vcpkg ./bootstrap-vcpkg.sh ./vcpkg integrate install - vcpkg install lz4 + ./vcpkg.exe install lz4 The LZ4 port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. @@ -118,3 +116,16 @@ many contributors have created versions of lz4 in multiple languages A list of known source ports is maintained on the [LZ4 Homepage]. [LZ4 Homepage]: http://www.lz4.org + +### Packaging status + +Most distributions are bundled with a package manager +which allows easy installation of both the `liblz4` library +and the `lz4` command line interface. + +[![Packaging status](https://repology.org/badge/vertical-allrepos/lz4.svg)](https://repology.org/project/lz4/versions) + + +### Special Thanks + +- Takayuki Matsuoka, aka @t-mat, for exceptional first-class support throughout the lifetime of this project diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..9be9aeb2c2706e62345dea66f38052826dcfaac7 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,17 @@ +# Security Policy + +If you have discovered a security vulnerability in this project, please report it +privately. **Do not disclose it as a public issue.** This gives me time to work with you +to fix the issue before public exposure, reducing the chance that the exploit will be +used before a patch is released. + +Please submit the report by filling out +[this form](https://github.com/lz4/lz4/security/advisories/new). + +Please provide the following information in your report: + +- A description of the vulnerability and its impact +- How to reproduce the issue + +This project is maintained by a single maintainer on a reasonable-effort basis. As such, +I ask that you give me 90 days to work on a fix before public exposure. diff --git a/appveyor.yml b/appveyor.yml index b4c27ef8240a075a5f81e212fd65047b03e92959..6be66ae1bb44d6eea27f7fb635516c0ebd624de4 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,13 +1,8 @@ version: 1.0.{build} environment: matrix: - - COMPILER: "gcc" - PLATFORM: "mingw64" - COMPILER: "gcc" PLATFORM: "mingw32" - - COMPILER: "visual" - CONFIGURATION: "Debug" - PLATFORM: "x64" - COMPILER: "visual" CONFIGURATION: "Debug" PLATFORM: "Win32" @@ -17,48 +12,53 @@ environment: - COMPILER: "visual" CONFIGURATION: "Release" PLATFORM: "Win32" + - COMPILER: "clang" + PLATFORM: "mingw64" - COMPILER: "gcc" - PLATFORM: "clang" + PLATFORM: "mingw64" install: - ECHO Installing %COMPILER% %PLATFORM% %CONFIGURATION% - MKDIR bin - - if [%COMPILER%]==[gcc] SET PATH_ORIGINAL=%PATH% - - if [%COMPILER%]==[gcc] ( + - if [%COMPILER%]==[visual] ( + if [%PLATFORM%]==[x64] ( + SET ADDITIONALPARAM=/p:LibraryPath="C:\Program Files\Microsoft SDKs\Windows\v7.1\lib\x64;c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib\amd64;C:\Program Files (x86)\Microsoft Visual Studio 10.0\;C:\Program Files (x86)\Microsoft Visual Studio 10.0\lib\amd64;" + ) + ) else ( SET "PATH_MINGW32=c:\MinGW\bin;c:\MinGW\usr\bin" && SET "PATH_MINGW64=c:\msys64\mingw64\bin;c:\msys64\usr\bin" && COPY C:\MinGW\bin\mingw32-make.exe C:\MinGW\bin\make.exe && COPY C:\MinGW\bin\gcc.exe C:\MinGW\bin\cc.exe - ) else ( - IF [%PLATFORM%]==[x64] (SET ADDITIONALPARAM=/p:LibraryPath="C:\Program Files\Microsoft SDKs\Windows\v7.1\lib\x64;c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib\amd64;C:\Program Files (x86)\Microsoft Visual Studio 10.0\;C:\Program Files (x86)\Microsoft Visual Studio 10.0\lib\amd64;") ) build_script: - - if [%PLATFORM%]==[mingw32] SET PATH=%PATH_MINGW32%;%PATH_ORIGINAL% - - if [%PLATFORM%]==[mingw64] SET PATH=%PATH_MINGW64%;%PATH_ORIGINAL% - - if [%PLATFORM%]==[clang] SET PATH=%PATH_MINGW64%;%PATH_ORIGINAL% + - if [%PLATFORM%]==[mingw32] SET PATH=%PATH_MINGW32%;%PATH% + - if [%PLATFORM%]==[mingw64] SET PATH=%PATH_MINGW64%;%PATH% - ECHO *** && ECHO Building %COMPILER% %PLATFORM% %CONFIGURATION% && ECHO *** - - if [%PLATFORM%]==[clang] (clang -v) - - if [%COMPILER%]==[gcc] (gcc -v) - if [%COMPILER%]==[gcc] ( + echo ----- %TIME% && + gcc -v && + make -v && echo ----- && + make -j -C programs lz4 V=1 && + make -j -C tests fullbench V=1 && + make -j -C tests fuzzer V=1 && + make -j -C lib lib V=1 + ) + - if [%COMPILER%]==[clang] ( + echo ----- %TIME% && + clang -v && make -v && echo ----- && - if not [%PLATFORM%]==[clang] ( - make -C programs lz4 && - make -C tests fullbench && - make -C tests fuzzer && - make -C lib lib V=1 - ) ELSE ( - make -C programs lz4 CC=clang MOREFLAGS="--target=x86_64-w64-mingw32 -Werror -Wconversion -Wno-sign-conversion" && - make -C tests fullbench CC=clang MOREFLAGS="--target=x86_64-w64-mingw32 -Werror -Wconversion -Wno-sign-conversion" && - make -C tests fuzzer CC=clang MOREFLAGS="--target=x86_64-w64-mingw32 -Werror -Wconversion -Wno-sign-conversion" && - make -C lib lib CC=clang MOREFLAGS="--target=x86_64-w64-mingw32 -Werror -Wconversion -Wno-sign-conversion" - ) + set CFLAGS="--target=x86_64-w64-mingw32 -Werror -Wconversion -Wno-sign-conversion" && + make -j -C programs lz4 CC=clang V=1 && + make -j -C tests fullbench CC=clang V=1 && + make -j -C tests fuzzer CC=clang V=1 && + make -j -C lib lib CC=clang V=1 ) - - if [%COMPILER%]==[gcc] if not [%PLATFORM%]==[clang] ( + - if [%COMPILER%]==[gcc] ( MKDIR bin\dll bin\static bin\example bin\include && COPY tests\fullbench.c bin\example\ && COPY lib\xxhash.c bin\example\ && @@ -67,7 +67,7 @@ build_script: COPY lib\lz4hc.h bin\include\ && COPY lib\lz4frame.h bin\include\ && COPY lib\liblz4.a bin\static\liblz4_static.lib && - COPY lib\dll\* bin\dll\ && + COPY lib\liblz4.dll* bin\dll\ && COPY lib\dll\example\Makefile bin\example\ && COPY lib\dll\example\fullbench-dll.* bin\example\ && COPY lib\dll\example\README.md bin\ && @@ -81,29 +81,22 @@ build_script: 7z.exe a -bb1 bin\lz4_x86.zip NEWS .\bin\lz4.exe .\bin\README.md .\bin\example .\bin\dll .\bin\static .\bin\include && appveyor PushArtifact bin\lz4_x86.zip ) - - if [%COMPILER%]==[gcc] (COPY tests\*.exe programs\) - if [%COMPILER%]==[visual] ( - ECHO *** && - ECHO *** Building Visual Studio 2010 %PLATFORM%\%CONFIGURATION% && - ECHO *** && - msbuild "build\VS2010\lz4.sln" %ADDITIONALPARAM% /m /verbosity:minimal /property:PlatformToolset=v100 /t:Clean,Build /p:Platform=%PLATFORM% /p:Configuration=%CONFIGURATION% /p:EnableWholeProgramOptimization=true /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" && - ECHO *** && + ECHO *** %TIME% && ECHO *** Building Visual Studio 2012 %PLATFORM%\%CONFIGURATION% && ECHO *** && - msbuild "build\VS2010\lz4.sln" /m /verbosity:minimal /property:PlatformToolset=v110 /t:Clean,Build /p:Platform=%PLATFORM% /p:Configuration=%CONFIGURATION% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" && - ECHO *** && + msbuild "build\VS2022\lz4.sln" /m /verbosity:minimal /property:PlatformToolset=v110 /property:Optimize=false /t:Clean,Build /p:Platform=%PLATFORM% /p:Configuration=%CONFIGURATION% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" && + ECHO *** %TIME% && ECHO *** Building Visual Studio 2013 %PLATFORM%\%CONFIGURATION% && ECHO *** && - msbuild "build\VS2010\lz4.sln" /m /verbosity:minimal /property:PlatformToolset=v120 /t:Clean,Build /p:Platform=%PLATFORM% /p:Configuration=%CONFIGURATION% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" && - ECHO *** && - ECHO *** Building Visual Studio 2015 %PLATFORM%\%CONFIGURATION% && - ECHO *** && - msbuild "build\VS2010\lz4.sln" /m /verbosity:minimal /property:PlatformToolset=v140 /t:Clean,Build /p:Platform=%PLATFORM% /p:Configuration=%CONFIGURATION% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" && - COPY build\VS2010\bin\%PLATFORM%_%CONFIGURATION%\*.exe programs\ + msbuild "build\VS2022\lz4.sln" /m /verbosity:minimal /property:PlatformToolset=v120 /property:Optimize=false /t:Clean,Build /p:Platform=%PLATFORM% /p:Configuration=%CONFIGURATION% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" && + COPY build\VS2022\bin\%PLATFORM%_%CONFIGURATION%\*.exe programs\ + ) else ( + COPY tests\*.exe programs\ ) test_script: - - ECHO *** && + - ECHO *** %TIME% && ECHO Testing %COMPILER% %PLATFORM% %CONFIGURATION% && ECHO *** - if not [%COMPILER%]==[unknown] ( @@ -114,10 +107,11 @@ test_script: lz4 -i1b10 lz4.exe && lz4 -i1b15 lz4.exe && echo ------- lz4 tested ------- && - fullbench.exe -i1 fullbench.exe && - echo trying to launch fuzzer.exe && - fuzzer.exe -v -T30s + fullbench.exe -i0 fullbench.exe && + echo Launching test program fuzzer.exe && + fuzzer.exe -v -T20s ) + - ECHO *** %TIME% artifacts: - path: bin\lz4_x64.zip diff --git a/build/.gitignore b/build/.gitignore index 69e11119e5de0708976f568df1604e06962b280e..f0a2f9da2a4624b06dd166efef0d8c9315611fe0 100644 --- a/build/.gitignore +++ b/build/.gitignore @@ -9,8 +9,10 @@ ver*/ VS2010/bin/ VS2017/bin/ +VS*/bin/ ipch # Fixup for lz4 project directories !VS2010/lz4 !VS2017/lz4 +!VS*/lz4 diff --git a/build/README.md b/build/README.md index d416aeb32fee6639b62f744b7cd6e17eda48146f..d183edbafc9400f1b8269d8dfa50639da9489a67 100644 --- a/build/README.md +++ b/build/README.md @@ -5,23 +5,12 @@ Projects for various integrated development environments (IDE) The following projects are included with the lz4 distribution: - `cmake` - CMake project -- `VS2010` - Visual Studio 2010 project (which also works well with Visual Studio 2012, 2013, 2015) -- `VS2017` - Visual Studio 2017 project +- `meson` - Meson project +- `visual` - scripts to generate Visual Studio solutions from `cmake` script +- `VS2022` - Visual Studio 2022 solution - will soon be deprecated, prefer `visual` generators -#### How to compile lz4 with Visual Studio - -1. Install Visual Studio e.g. VS 2015 Community Edition (it's free). -2. Download the latest version of lz4 from https://github.com/lz4/lz4/releases -3. Decompress ZIP archive. -4. Go to decompressed directory then to `build` then `VS2010` and open `lz4.sln` -5. Visual Studio will ask about converting VS2010 project to VS2015 and you should agree. -6. Change `Debug` to `Release` and if you have 64-bit Windows change also `Win32` to `x64`. -7. Press F7 on keyboard or select `BUILD` from the menu bar and choose `Build Solution`. -8. If compilation will be fine a compiled executable will be in `build\VS2010\bin\x64_Release\lz4.exe` - - -#### Projects available within lz4.sln +#### Projects available within VS2022\lz4.sln The Visual Studio solution file `lz4.sln` contains many projects that will be compiled to the `build\VS2010\bin\$(Platform)_$(Configuration)` directory. For example `lz4` set to `x64` and diff --git a/build/VS2010/datagen/datagen.vcxproj b/build/VS2010/datagen/datagen.vcxproj deleted file mode 100644 index e24f961de4d282c037630b878ec3f28fac29a152..0000000000000000000000000000000000000000 --- a/build/VS2010/datagen/datagen.vcxproj +++ /dev/null @@ -1,169 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {D745AE2F-596A-403A-9B91-81A8C6779243} - Win32Proj - datagen - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - Unicode - true - - - Application - false - Unicode - true - - - - - - - - - - - - - - - - - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - false - MultiThreadedDebug - - - Console - true - - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreadedDebug - - - Console - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - false - MultiThreaded - - - Console - true - true - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreaded - - - Console - true - true - true - - - - - - - - - - - - - diff --git a/build/VS2010/frametest/frametest.vcxproj b/build/VS2010/frametest/frametest.vcxproj deleted file mode 100644 index 3196768729d48eeeaf0c0141754cb017a51518a1..0000000000000000000000000000000000000000 --- a/build/VS2010/frametest/frametest.vcxproj +++ /dev/null @@ -1,176 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7} - Win32Proj - frametest - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - Unicode - true - - - Application - false - Unicode - true - - - - - - - - - - - - - - - - - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - false - MultiThreadedDebug - - - Console - true - - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreadedDebug - - - Console - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - false - MultiThreaded - - - Console - true - true - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreaded - - - Console - true - true - true - - - - - - - - - - - - - - - - - - - - diff --git a/build/VS2010/fullbench-dll/fullbench-dll.vcxproj b/build/VS2010/fullbench-dll/fullbench-dll.vcxproj deleted file mode 100644 index 8f503f565807d6a2818511be78d067153262c7c9..0000000000000000000000000000000000000000 --- a/build/VS2010/fullbench-dll/fullbench-dll.vcxproj +++ /dev/null @@ -1,180 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {13992FD2-077E-4954-B065-A428198201A9} - Win32Proj - fullbench-dll - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - Unicode - true - - - Application - false - Unicode - true - - - - - - - - - - - - - - - - - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions) - true - false - MultiThreadedDebug - - - Console - true - $(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories) - liblz4.lib;%(AdditionalDependencies) - - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreadedDebug - - - Console - true - $(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories) - liblz4.lib;%(AdditionalDependencies) - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions) - false - false - MultiThreaded - - - Console - true - true - true - $(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories) - liblz4.lib;%(AdditionalDependencies) - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreaded - - - Console - true - true - true - $(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories) - liblz4.lib;%(AdditionalDependencies) - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/build/VS2010/fullbench/fullbench.vcxproj b/build/VS2010/fullbench/fullbench.vcxproj deleted file mode 100644 index aa6743152a1ecb5be48563920ceea763749aac1b..0000000000000000000000000000000000000000 --- a/build/VS2010/fullbench/fullbench.vcxproj +++ /dev/null @@ -1,176 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E} - Win32Proj - fullbench - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - Unicode - true - - - Application - false - Unicode - true - - - - - - - - - - - - - - - - - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - false - MultiThreadedDebug - - - Console - true - - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreadedDebug - - - Console - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - false - MultiThreaded - - - Console - true - true - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreaded - - - Console - true - true - true - - - - - - - - - - - - - - - - - - - - diff --git a/build/VS2010/fuzzer/fuzzer.vcxproj b/build/VS2010/fuzzer/fuzzer.vcxproj deleted file mode 100644 index 21cbf5622ec2547371ffae49997e9ece6316c8c5..0000000000000000000000000000000000000000 --- a/build/VS2010/fuzzer/fuzzer.vcxproj +++ /dev/null @@ -1,173 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {18B9F1A7-9C66-4352-898B-30804DADE0FD} - Win32Proj - fuzzer - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - Unicode - true - - - Application - false - Unicode - true - - - - - - - - - - - - - - - - - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - false - MultiThreadedDebug - - - Console - true - - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreadedDebug - - - Console - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - false - MultiThreaded - - - Console - true - true - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreaded - - - Console - true - true - true - - - - - - - - - - - - - - - - - diff --git a/build/VS2010/liblz4-dll/liblz4-dll.rc b/build/VS2010/liblz4-dll/liblz4-dll.rc deleted file mode 100644 index e089c24cd7d427076d59cb65062ff15574cadc6e..0000000000000000000000000000000000000000 --- a/build/VS2010/liblz4-dll/liblz4-dll.rc +++ /dev/null @@ -1,51 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// - -#include "lz4.h" /* LZ4_VERSION_STRING */ -#define APSTUDIO_READONLY_SYMBOLS -#include "verrsrc.h" -#undef APSTUDIO_READONLY_SYMBOLS - - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -LANGUAGE 9, 1 - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION LZ4_VERSION_MAJOR,LZ4_VERSION_MINOR,LZ4_VERSION_RELEASE,0 - PRODUCTVERSION LZ4_VERSION_MAJOR,LZ4_VERSION_MINOR,LZ4_VERSION_RELEASE,0 - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK -#ifdef _DEBUG - FILEFLAGS VS_FF_DEBUG -#else - FILEFLAGS 0x0L -#endif - FILEOS VOS_NT_WINDOWS32 - FILETYPE VFT_DLL - FILESUBTYPE VFT2_UNKNOWN -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904B0" - BEGIN - VALUE "CompanyName", "Yann Collet" - VALUE "FileDescription", "Extremely fast compression" - VALUE "FileVersion", LZ4_VERSION_STRING - VALUE "InternalName", "lz4.dll" - VALUE "LegalCopyright", "Copyright (C) 2013-2020, Yann Collet" - VALUE "OriginalFilename", "lz4.dll" - VALUE "ProductName", "LZ4" - VALUE "ProductVersion", LZ4_VERSION_STRING - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 1200 - END -END - -#endif diff --git a/build/VS2010/liblz4-dll/liblz4-dll.vcxproj b/build/VS2010/liblz4-dll/liblz4-dll.vcxproj deleted file mode 100644 index 56ec3b98120fb8cf7d15d437d2756a7a7cdeeba0..0000000000000000000000000000000000000000 --- a/build/VS2010/liblz4-dll/liblz4-dll.vcxproj +++ /dev/null @@ -1,179 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {9800039D-4AAA-43A4-BB78-FEF6F4836927} - Win32Proj - liblz4-dll - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - liblz4-dll - - - - DynamicLibrary - true - Unicode - - - DynamicLibrary - true - Unicode - - - DynamicLibrary - false - Unicode - true - - - DynamicLibrary - false - Unicode - true - - - - - - - - - - - - - - - - - - - true - liblz4 - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - liblz4 - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - liblz4 - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - liblz4 - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - true - false - MultiThreadedDebug - - - true - - - - - - - Level4 - Disabled - WIN32;_DEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreadedDebug - - - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - false - false - MultiThreaded - - - true - true - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreaded - - - true - true - true - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/build/VS2010/liblz4/liblz4.vcxproj b/build/VS2010/liblz4/liblz4.vcxproj deleted file mode 100644 index 61ea159b412bf8f3996498172aa561ff5ca51e60..0000000000000000000000000000000000000000 --- a/build/VS2010/liblz4/liblz4.vcxproj +++ /dev/null @@ -1,175 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476} - Win32Proj - liblz4 - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - StaticLibrary - true - Unicode - - - StaticLibrary - true - Unicode - - - StaticLibrary - false - Unicode - true - - - StaticLibrary - false - Unicode - true - - - - - - - - - - - - - - - - - - - true - liblz4_static - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - liblz4_static - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - liblz4_static - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - liblz4_static - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - true - false - MultiThreadedDebug - - - true - - - - - - - Level4 - Disabled - WIN32;_DEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreadedDebug - - - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - false - false - MultiThreaded - - - true - true - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreaded - - - true - true - true - - - - - - - - - - - - - - - - - - - diff --git a/build/VS2010/lz4.sln b/build/VS2010/lz4.sln deleted file mode 100644 index 78f223bf48713f4a041e61de11360cf4329432e7..0000000000000000000000000000000000000000 --- a/build/VS2010/lz4.sln +++ /dev/null @@ -1,98 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Express 2012 for Windows Desktop -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lz4", "lz4\lz4.vcxproj", "{E30329AC-0057-4FE0-8FDA-7F650D398C4C}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblz4-dll", "liblz4-dll\liblz4-dll.vcxproj", "{9800039D-4AAA-43A4-BB78-FEF6F4836927}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblz4", "liblz4\liblz4.vcxproj", "{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fuzzer", "fuzzer\fuzzer.vcxproj", "{18B9F1A7-9C66-4352-898B-30804DADE0FD}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fullbench", "fullbench\fullbench.vcxproj", "{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "frametest", "frametest\frametest.vcxproj", "{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "datagen", "datagen\datagen.vcxproj", "{D745AE2F-596A-403A-9B91-81A8C6779243}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fullbench-dll", "fullbench-dll\fullbench-dll.vcxproj", "{13992FD2-077E-4954-B065-A428198201A9}" - ProjectSection(ProjectDependencies) = postProject - {9800039D-4AAA-43A4-BB78-FEF6F4836927} = {9800039D-4AAA-43A4-BB78-FEF6F4836927} - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Debug|Win32.ActiveCfg = Debug|Win32 - {E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Debug|Win32.Build.0 = Debug|Win32 - {E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Debug|x64.ActiveCfg = Debug|x64 - {E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Debug|x64.Build.0 = Debug|x64 - {E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Release|Win32.ActiveCfg = Release|Win32 - {E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Release|Win32.Build.0 = Release|Win32 - {E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Release|x64.ActiveCfg = Release|x64 - {E30329AC-0057-4FE0-8FDA-7F650D398C4C}.Release|x64.Build.0 = Release|x64 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Debug|Win32.ActiveCfg = Debug|Win32 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Debug|Win32.Build.0 = Debug|Win32 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Debug|x64.ActiveCfg = Debug|x64 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Debug|x64.Build.0 = Debug|x64 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Release|Win32.ActiveCfg = Release|Win32 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Release|Win32.Build.0 = Release|Win32 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Release|x64.ActiveCfg = Release|x64 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Release|x64.Build.0 = Release|x64 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Debug|Win32.ActiveCfg = Debug|Win32 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Debug|Win32.Build.0 = Debug|Win32 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Debug|x64.ActiveCfg = Debug|x64 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Debug|x64.Build.0 = Debug|x64 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Release|Win32.ActiveCfg = Release|Win32 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Release|Win32.Build.0 = Release|Win32 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Release|x64.ActiveCfg = Release|x64 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Release|x64.Build.0 = Release|x64 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Debug|Win32.ActiveCfg = Debug|Win32 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Debug|Win32.Build.0 = Debug|Win32 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Debug|x64.ActiveCfg = Debug|x64 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Debug|x64.Build.0 = Debug|x64 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Release|Win32.ActiveCfg = Release|Win32 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Release|Win32.Build.0 = Release|Win32 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Release|x64.ActiveCfg = Release|x64 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Release|x64.Build.0 = Release|x64 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Debug|Win32.ActiveCfg = Debug|Win32 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Debug|Win32.Build.0 = Debug|Win32 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Debug|x64.ActiveCfg = Debug|x64 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Debug|x64.Build.0 = Debug|x64 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Release|Win32.ActiveCfg = Release|Win32 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Release|Win32.Build.0 = Release|Win32 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Release|x64.ActiveCfg = Release|x64 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Release|x64.Build.0 = Release|x64 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Debug|Win32.ActiveCfg = Debug|Win32 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Debug|Win32.Build.0 = Debug|Win32 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Debug|x64.ActiveCfg = Debug|x64 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Debug|x64.Build.0 = Debug|x64 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Release|Win32.ActiveCfg = Release|Win32 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Release|Win32.Build.0 = Release|Win32 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Release|x64.ActiveCfg = Release|x64 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Release|x64.Build.0 = Release|x64 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Debug|Win32.ActiveCfg = Debug|Win32 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Debug|Win32.Build.0 = Debug|Win32 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Debug|x64.ActiveCfg = Debug|x64 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Debug|x64.Build.0 = Debug|x64 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Release|Win32.ActiveCfg = Release|Win32 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Release|Win32.Build.0 = Release|Win32 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Release|x64.ActiveCfg = Release|x64 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Release|x64.Build.0 = Release|x64 - {13992FD2-077E-4954-B065-A428198201A9}.Debug|Win32.ActiveCfg = Debug|Win32 - {13992FD2-077E-4954-B065-A428198201A9}.Debug|Win32.Build.0 = Debug|Win32 - {13992FD2-077E-4954-B065-A428198201A9}.Debug|x64.ActiveCfg = Debug|x64 - {13992FD2-077E-4954-B065-A428198201A9}.Debug|x64.Build.0 = Debug|x64 - {13992FD2-077E-4954-B065-A428198201A9}.Release|Win32.ActiveCfg = Release|Win32 - {13992FD2-077E-4954-B065-A428198201A9}.Release|Win32.Build.0 = Release|Win32 - {13992FD2-077E-4954-B065-A428198201A9}.Release|x64.ActiveCfg = Release|x64 - {13992FD2-077E-4954-B065-A428198201A9}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/build/VS2010/lz4/lz4.vcxproj b/build/VS2010/lz4/lz4.vcxproj deleted file mode 100644 index de7a7143eea78ba8c667164d473db45aaa541ed9..0000000000000000000000000000000000000000 --- a/build/VS2010/lz4/lz4.vcxproj +++ /dev/null @@ -1,189 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {E30329AC-0057-4FE0-8FDA-7F650D398C4C} - Win32Proj - lz4 - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - Application - true - Unicode - - - Application - true - Unicode - - - Application - false - Unicode - true - - - Application - false - Unicode - true - - - - - - - - - - - - - - - - - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - false - MultiThreadedDebug - - - Console - true - setargv.obj;%(AdditionalDependencies) - - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreadedDebug - - - Console - true - setargv.obj;%(AdditionalDependencies) - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - false - MultiThreaded - - - Console - true - true - true - setargv.obj;%(AdditionalDependencies) - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreaded - - - Console - true - true - true - setargv.obj;%(AdditionalDependencies) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/build/VS2017/datagen/datagen.vcxproj b/build/VS2017/datagen/datagen.vcxproj deleted file mode 100644 index 30e159ea5d29df1293fc0ca73ef320128a9126c4..0000000000000000000000000000000000000000 --- a/build/VS2017/datagen/datagen.vcxproj +++ /dev/null @@ -1,173 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {D745AE2F-596A-403A-9B91-81A8C6779243} - Win32Proj - datagen - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - Application - true - Unicode - v141 - - - Application - true - Unicode - v141 - - - Application - false - Unicode - true - v141 - - - Application - false - Unicode - true - v141 - - - - - - - - - - - - - - - - - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\programs;$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - false - MultiThreadedDebug - - - Console - true - - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreadedDebug - - - Console - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - false - MultiThreaded - - - Console - true - true - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreaded - - - Console - true - true - true - - - - - - - - - - - - - \ No newline at end of file diff --git a/build/VS2017/frametest/frametest.vcxproj b/build/VS2017/frametest/frametest.vcxproj deleted file mode 100644 index a3a403d1b1c82ed0d19f2869668403fc237a80d7..0000000000000000000000000000000000000000 --- a/build/VS2017/frametest/frametest.vcxproj +++ /dev/null @@ -1,180 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7} - Win32Proj - frametest - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - Application - true - Unicode - v141 - - - Application - true - Unicode - v141 - - - Application - false - Unicode - true - v141 - - - Application - false - Unicode - true - v141 - - - - - - - - - - - - - - - - - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - false - MultiThreadedDebug - - - Console - true - - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreadedDebug - - - Console - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - false - MultiThreaded - - - Console - true - true - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreaded - - - Console - true - true - true - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/build/VS2017/fullbench-dll/fullbench-dll.vcxproj b/build/VS2017/fullbench-dll/fullbench-dll.vcxproj deleted file mode 100644 index d54a8d7281941b00a7f8e917fed4ace01ed6114a..0000000000000000000000000000000000000000 --- a/build/VS2017/fullbench-dll/fullbench-dll.vcxproj +++ /dev/null @@ -1,184 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {13992FD2-077E-4954-B065-A428198201A9} - Win32Proj - fullbench-dll - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - Application - true - Unicode - v141 - - - Application - true - Unicode - v141 - - - Application - false - Unicode - true - v141 - - - Application - false - Unicode - true - v141 - - - - - - - - - - - - - - - - - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions) - true - false - MultiThreadedDebug - - - Console - true - $(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories) - liblz4.lib;%(AdditionalDependencies) - - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreadedDebug - - - Console - true - $(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories) - liblz4.lib;%(AdditionalDependencies) - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions) - false - false - MultiThreaded - - - Console - true - true - true - $(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories) - liblz4.lib;%(AdditionalDependencies) - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;LZ4_DLL_IMPORT=1;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreaded - - - Console - true - true - true - $(SolutionDir)bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories) - liblz4.lib;%(AdditionalDependencies) - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/build/VS2017/fullbench/fullbench.vcxproj b/build/VS2017/fullbench/fullbench.vcxproj deleted file mode 100644 index 54c97439019c3fb3ed2c9285ddc7891cd9cc9fc1..0000000000000000000000000000000000000000 --- a/build/VS2017/fullbench/fullbench.vcxproj +++ /dev/null @@ -1,180 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E} - Win32Proj - fullbench - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - Application - true - Unicode - v141 - - - Application - true - Unicode - v141 - - - Application - false - Unicode - true - v141 - - - Application - false - Unicode - true - v141 - - - - - - - - - - - - - - - - - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - false - MultiThreadedDebug - - - Console - true - - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreadedDebug - - - Console - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - false - MultiThreaded - - - Console - true - true - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreaded - - - Console - true - true - true - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/build/VS2017/fuzzer/fuzzer.vcxproj b/build/VS2017/fuzzer/fuzzer.vcxproj deleted file mode 100644 index aa6fe42508553a919487a3981318b3f6e828a68b..0000000000000000000000000000000000000000 --- a/build/VS2017/fuzzer/fuzzer.vcxproj +++ /dev/null @@ -1,177 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {18B9F1A7-9C66-4352-898B-30804DADE0FD} - Win32Proj - fuzzer - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - Application - true - Unicode - v141 - - - Application - true - Unicode - v141 - - - Application - false - Unicode - true - v141 - - - Application - false - Unicode - true - v141 - - - - - - - - - - - - - - - - - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(SolutionDir)..\..\programs;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - false - MultiThreadedDebug - - - Console - true - - - - - - - Level4 - Disabled - WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreadedDebug - - - Console - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - false - MultiThreaded - - - Console - true - true - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreaded - - - Console - true - true - true - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/build/VS2017/liblz4-dll/liblz4-dll.rc b/build/VS2017/liblz4-dll/liblz4-dll.rc deleted file mode 100644 index e089c24cd7d427076d59cb65062ff15574cadc6e..0000000000000000000000000000000000000000 --- a/build/VS2017/liblz4-dll/liblz4-dll.rc +++ /dev/null @@ -1,51 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// - -#include "lz4.h" /* LZ4_VERSION_STRING */ -#define APSTUDIO_READONLY_SYMBOLS -#include "verrsrc.h" -#undef APSTUDIO_READONLY_SYMBOLS - - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -LANGUAGE 9, 1 - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION LZ4_VERSION_MAJOR,LZ4_VERSION_MINOR,LZ4_VERSION_RELEASE,0 - PRODUCTVERSION LZ4_VERSION_MAJOR,LZ4_VERSION_MINOR,LZ4_VERSION_RELEASE,0 - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK -#ifdef _DEBUG - FILEFLAGS VS_FF_DEBUG -#else - FILEFLAGS 0x0L -#endif - FILEOS VOS_NT_WINDOWS32 - FILETYPE VFT_DLL - FILESUBTYPE VFT2_UNKNOWN -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904B0" - BEGIN - VALUE "CompanyName", "Yann Collet" - VALUE "FileDescription", "Extremely fast compression" - VALUE "FileVersion", LZ4_VERSION_STRING - VALUE "InternalName", "lz4.dll" - VALUE "LegalCopyright", "Copyright (C) 2013-2020, Yann Collet" - VALUE "OriginalFilename", "lz4.dll" - VALUE "ProductName", "LZ4" - VALUE "ProductVersion", LZ4_VERSION_STRING - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 1200 - END -END - -#endif diff --git a/build/VS2017/liblz4-dll/liblz4-dll.vcxproj b/build/VS2017/liblz4-dll/liblz4-dll.vcxproj deleted file mode 100644 index 8e7ee3b978bb69a50853e9df29a15c5073b0db40..0000000000000000000000000000000000000000 --- a/build/VS2017/liblz4-dll/liblz4-dll.vcxproj +++ /dev/null @@ -1,183 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {9800039D-4AAA-43A4-BB78-FEF6F4836927} - Win32Proj - liblz4-dll - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - liblz4-dll - - - - DynamicLibrary - true - Unicode - v141 - - - DynamicLibrary - true - Unicode - v141 - - - DynamicLibrary - false - Unicode - true - v141 - - - DynamicLibrary - false - Unicode - true - v141 - - - - - - - - - - - - - - - - - - - true - liblz4 - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - liblz4 - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - liblz4 - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - liblz4 - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - true - false - MultiThreadedDebug - - - true - - - - - - - Level4 - Disabled - WIN32;_DEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreadedDebug - - - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - false - false - MultiThreaded - - - true - true - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreaded - - - true - true - true - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/build/VS2017/liblz4/liblz4.vcxproj b/build/VS2017/liblz4/liblz4.vcxproj deleted file mode 100644 index 948f7db377e75aa25e38df87f34842354d843aaf..0000000000000000000000000000000000000000 --- a/build/VS2017/liblz4/liblz4.vcxproj +++ /dev/null @@ -1,179 +0,0 @@ - - - - - Debug - Win32 - - - Debug - x64 - - - Release - Win32 - - - Release - x64 - - - - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476} - Win32Proj - liblz4 - $(SolutionDir)bin\$(Platform)_$(Configuration)\ - $(SolutionDir)bin\obj\$(RootNamespace)_$(Platform)_$(Configuration)\ - - - - StaticLibrary - true - Unicode - v141 - - - StaticLibrary - true - Unicode - v141 - - - StaticLibrary - false - Unicode - true - v141 - - - StaticLibrary - false - Unicode - true - v141 - - - - - - - - - - - - - - - - - - - true - liblz4_static - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - true - liblz4_static - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - false - liblz4_static - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - - - false - liblz4_static - $(IncludePath);$(UniversalCRT_IncludePath);$(SolutionDir)..\..\lib;$(VCInstallDir)include;$(VCInstallDir)atlmfc\include;$(WindowsSDK_IncludePath); - true - - - - - - Level4 - Disabled - WIN32;_DEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - true - false - MultiThreadedDebug - - - true - - - - - - - Level4 - Disabled - WIN32;_DEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - true - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreadedDebug - - - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - false - false - MultiThreaded - - - true - true - true - - - - - Level4 - - - MaxSpeed - true - true - WIN32;NDEBUG;LZ4_DLL_EXPORT=1;%(PreprocessorDefinitions) - false - true - /analyze:stacksize295252 %(AdditionalOptions) - MultiThreaded - - - true - true - true - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/build/VS2017/lz4.sln b/build/VS2017/lz4.sln deleted file mode 100644 index 6a2779f915b8f016c0eb0e23a6f7f7c805f6c529..0000000000000000000000000000000000000000 --- a/build/VS2017/lz4.sln +++ /dev/null @@ -1,103 +0,0 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.28307.271 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblz4-dll", "liblz4-dll\liblz4-dll.vcxproj", "{9800039D-4AAA-43A4-BB78-FEF6F4836927}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblz4", "liblz4\liblz4.vcxproj", "{9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fuzzer", "fuzzer\fuzzer.vcxproj", "{18B9F1A7-9C66-4352-898B-30804DADE0FD}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fullbench", "fullbench\fullbench.vcxproj", "{6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "frametest", "frametest\frametest.vcxproj", "{39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "datagen", "datagen\datagen.vcxproj", "{D745AE2F-596A-403A-9B91-81A8C6779243}" -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fullbench-dll", "fullbench-dll\fullbench-dll.vcxproj", "{13992FD2-077E-4954-B065-A428198201A9}" - ProjectSection(ProjectDependencies) = postProject - {9800039D-4AAA-43A4-BB78-FEF6F4836927} = {9800039D-4AAA-43A4-BB78-FEF6F4836927} - EndProjectSection -EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lz4", "lz4\lz4.vcxproj", "{60A3115E-B988-41EE-8815-F4D4F253D866}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Debug|x64 = Debug|x64 - Release|Win32 = Release|Win32 - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Debug|Win32.ActiveCfg = Debug|Win32 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Debug|Win32.Build.0 = Debug|Win32 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Debug|x64.ActiveCfg = Debug|x64 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Debug|x64.Build.0 = Debug|x64 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Release|Win32.ActiveCfg = Release|Win32 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Release|Win32.Build.0 = Release|Win32 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Release|x64.ActiveCfg = Release|x64 - {9800039D-4AAA-43A4-BB78-FEF6F4836927}.Release|x64.Build.0 = Release|x64 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Debug|Win32.ActiveCfg = Debug|Win32 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Debug|Win32.Build.0 = Debug|Win32 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Debug|x64.ActiveCfg = Debug|x64 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Debug|x64.Build.0 = Debug|x64 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Release|Win32.ActiveCfg = Release|Win32 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Release|Win32.Build.0 = Release|Win32 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Release|x64.ActiveCfg = Release|x64 - {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476}.Release|x64.Build.0 = Release|x64 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Debug|Win32.ActiveCfg = Debug|Win32 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Debug|Win32.Build.0 = Debug|Win32 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Debug|x64.ActiveCfg = Debug|x64 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Debug|x64.Build.0 = Debug|x64 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Release|Win32.ActiveCfg = Release|Win32 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Release|Win32.Build.0 = Release|Win32 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Release|x64.ActiveCfg = Release|x64 - {18B9F1A7-9C66-4352-898B-30804DADE0FD}.Release|x64.Build.0 = Release|x64 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Debug|Win32.ActiveCfg = Debug|Win32 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Debug|Win32.Build.0 = Debug|Win32 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Debug|x64.ActiveCfg = Debug|x64 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Debug|x64.Build.0 = Debug|x64 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Release|Win32.ActiveCfg = Release|Win32 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Release|Win32.Build.0 = Release|Win32 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Release|x64.ActiveCfg = Release|x64 - {6A4DF4EF-C77F-43C6-8901-DDCD20879E4E}.Release|x64.Build.0 = Release|x64 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Debug|Win32.ActiveCfg = Debug|Win32 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Debug|Win32.Build.0 = Debug|Win32 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Debug|x64.ActiveCfg = Debug|x64 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Debug|x64.Build.0 = Debug|x64 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Release|Win32.ActiveCfg = Release|Win32 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Release|Win32.Build.0 = Release|Win32 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Release|x64.ActiveCfg = Release|x64 - {39AD6ECC-8BAD-4368-95E4-A1AA2F077BB7}.Release|x64.Build.0 = Release|x64 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Debug|Win32.ActiveCfg = Debug|Win32 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Debug|Win32.Build.0 = Debug|Win32 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Debug|x64.ActiveCfg = Debug|x64 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Debug|x64.Build.0 = Debug|x64 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Release|Win32.ActiveCfg = Release|Win32 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Release|Win32.Build.0 = Release|Win32 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Release|x64.ActiveCfg = Release|x64 - {D745AE2F-596A-403A-9B91-81A8C6779243}.Release|x64.Build.0 = Release|x64 - {13992FD2-077E-4954-B065-A428198201A9}.Debug|Win32.ActiveCfg = Debug|Win32 - {13992FD2-077E-4954-B065-A428198201A9}.Debug|Win32.Build.0 = Debug|Win32 - {13992FD2-077E-4954-B065-A428198201A9}.Debug|x64.ActiveCfg = Debug|x64 - {13992FD2-077E-4954-B065-A428198201A9}.Debug|x64.Build.0 = Debug|x64 - {13992FD2-077E-4954-B065-A428198201A9}.Release|Win32.ActiveCfg = Release|Win32 - {13992FD2-077E-4954-B065-A428198201A9}.Release|Win32.Build.0 = Release|Win32 - {13992FD2-077E-4954-B065-A428198201A9}.Release|x64.ActiveCfg = Release|x64 - {13992FD2-077E-4954-B065-A428198201A9}.Release|x64.Build.0 = Release|x64 - {60A3115E-B988-41EE-8815-F4D4F253D866}.Debug|Win32.ActiveCfg = Debug|Win32 - {60A3115E-B988-41EE-8815-F4D4F253D866}.Debug|Win32.Build.0 = Debug|Win32 - {60A3115E-B988-41EE-8815-F4D4F253D866}.Debug|x64.ActiveCfg = Debug|x64 - {60A3115E-B988-41EE-8815-F4D4F253D866}.Debug|x64.Build.0 = Debug|x64 - {60A3115E-B988-41EE-8815-F4D4F253D866}.Release|Win32.ActiveCfg = Release|Win32 - {60A3115E-B988-41EE-8815-F4D4F253D866}.Release|Win32.Build.0 = Release|Win32 - {60A3115E-B988-41EE-8815-F4D4F253D866}.Release|x64.ActiveCfg = Release|x64 - {60A3115E-B988-41EE-8815-F4D4F253D866}.Release|x64.Build.0 = Release|x64 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {BBC259B2-BABF-47CD-8A6A-7B8318A803AC} - EndGlobalSection -EndGlobal diff --git a/build/VS2017/lz4/lz4.rc b/build/VS2017/lz4/lz4.rc deleted file mode 100644 index 5eec36bfc4a6dc69317bdeeaa6f7723100c81f6b..0000000000000000000000000000000000000000 --- a/build/VS2017/lz4/lz4.rc +++ /dev/null @@ -1,51 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// - -#include "lz4.h" /* LZ4_VERSION_STRING */ -#define APSTUDIO_READONLY_SYMBOLS -#include "verrsrc.h" -#undef APSTUDIO_READONLY_SYMBOLS - - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -LANGUAGE 9, 1 - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION LZ4_VERSION_MAJOR,LZ4_VERSION_MINOR,LZ4_VERSION_RELEASE,0 - PRODUCTVERSION LZ4_VERSION_MAJOR,LZ4_VERSION_MINOR,LZ4_VERSION_RELEASE,0 - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK -#ifdef _DEBUG - FILEFLAGS VS_FF_DEBUG -#else - FILEFLAGS 0x0L -#endif - FILEOS VOS_NT_WINDOWS32 - FILETYPE VFT_DLL - FILESUBTYPE VFT2_UNKNOWN -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904B0" - BEGIN - VALUE "CompanyName", "Yann Collet" - VALUE "FileDescription", "Extremely fast compression" - VALUE "FileVersion", LZ4_VERSION_STRING - VALUE "InternalName", "lz4.exe" - VALUE "LegalCopyright", "Copyright (C) 2013-2020, Yann Collet" - VALUE "OriginalFilename", "lz4.exe" - VALUE "ProductName", "LZ4" - VALUE "ProductVersion", LZ4_VERSION_STRING - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x0409, 1200 - END -END - -#endif diff --git a/build/VS2022/_build.bat b/build/VS2022/_build.bat new file mode 100644 index 0000000000000000000000000000000000000000..2c2eb57d6292c062fc33db46e70fd548b2d22af4 --- /dev/null +++ b/build/VS2022/_build.bat @@ -0,0 +1,39 @@ +set /a errorno=1 +for /F "delims=#" %%E in ('"prompt #$E# & for %%E in (1) do rem"') do set "esc=%%E" + +rem https://docs.microsoft.com/visualstudio/msbuild/msbuild-command-line-reference + +set "sln=lz4.sln" + +@rem set "Configuration=Debug" +@rem set "Platform=Win32" + +set "BIN=.\bin\!Platform!_!Configuration!" +rmdir /S /Q "!BIN!" 2>nul +echo msbuild "%sln%" /p:Configuration=!Configuration! /p:Platform=!Platform! +msbuild "%sln%" ^ + /nologo ^ + /v:minimal ^ + /m ^ + /p:Configuration=!Configuration! ^ + /p:Platform=!Platform! ^ + /t:Clean,Build ^ + || goto :ERROR + +if not exist "!BIN!\datagen.exe" ( echo FAIL: "!BIN!\datagen.exe" && goto :ERROR ) +if not exist "!BIN!\frametest.exe" ( echo FAIL: "!BIN!\frametest.exe" && goto :ERROR ) +if not exist "!BIN!\fullbench-dll.exe" ( echo FAIL: "!BIN!\fullbench-dll.exe" && goto :ERROR ) +if not exist "!BIN!\fullbench.exe" ( echo FAIL: "!BIN!\fullbench.exe" && goto :ERROR ) +if not exist "!BIN!\fuzzer.exe" ( echo FAIL: "!BIN!\fuzzer.exe" && goto :ERROR ) +if not exist "!BIN!\liblz4.dll" ( echo FAIL: "!BIN!\liblz4.dll" && goto :ERROR ) +if not exist "!BIN!\liblz4.lib" ( echo FAIL: "!BIN!\liblz4.lib" && goto :ERROR ) +if not exist "!BIN!\liblz4_static.lib" ( echo FAIL: "!BIN!\liblz4_static.lib" && goto :ERROR ) +if not exist "!BIN!\lz4.exe" ( echo FAIL: "!BIN!\lz4.exe" && goto :ERROR ) + +set /a errorno=0 +goto :END + +:ERROR + +:END +exit /B %errorno% diff --git a/build/VS2022/_setup.bat b/build/VS2022/_setup.bat new file mode 100644 index 0000000000000000000000000000000000000000..b4dda51b033f7fad862213cd75ef44fae3aec7b9 --- /dev/null +++ b/build/VS2022/_setup.bat @@ -0,0 +1,35 @@ +set /a errorno=1 +for /F "delims=#" %%E in ('"prompt #$E# & for %%E in (1) do rem"') do set "esc=%%E" + +rem https://github.com/Microsoft/vswhere +rem https://github.com/microsoft/vswhere/wiki/Find-VC#batch + +set "vswhere=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" +if not exist "%vswhere%" ( + echo Failed to find "vswhere.exe". Please install the latest version of Visual Studio. + goto :ERROR +) + +set "InstallDir=" +for /f "usebackq tokens=*" %%i in ( + `"%vswhere%" -latest ^ + -products * ^ + -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 ^ + -property installationPath` +) do ( + set "InstallDir=%%i" +) +if "%InstallDir%" == "" ( + echo Failed to find Visual C++. Please install the latest version of Visual C++. + goto :ERROR +) + +call "%InstallDir%\VC\Auxiliary\Build\vcvars64.bat" || goto :ERROR + +set /a errorno=0 +goto :END + +:ERROR + +:END +exit /B %errorno% diff --git a/build/VS2022/_test.bat b/build/VS2022/_test.bat new file mode 100644 index 0000000000000000000000000000000000000000..4614fa99ff0559e77c5278ef4ef0109c8bf339fa --- /dev/null +++ b/build/VS2022/_test.bat @@ -0,0 +1,38 @@ +set /a errorno=1 +for /F "delims=#" %%E in ('"prompt #$E# & for %%E in (1) do rem"') do set "esc=%%E" + +@rem set "Configuration=Debug" +@rem set "Platform=Win32" + +set "BIN=.\bin\!Platform!_!Configuration!" +set "TEST_FILES=..\..\tests\COPYING" + +echo !BIN!\lz4 -h + !BIN!\lz4 -h || goto :ERROR + +echo !BIN!\lz4 -i1b + !BIN!\lz4 -i1b || goto :ERROR + +echo !BIN!\lz4 -i1b5 + !BIN!\lz4 -i1b5 || goto :ERROR + +echo !BIN!\lz4 -i1b10 + !BIN!\lz4 -i1b10 || goto :ERROR + +echo !BIN!\lz4 -i1b15 + !BIN!\lz4 -i1b15 || goto :ERROR + +echo fullbench +!BIN!\fullbench.exe --no-prompt -i1 %TEST_FILES% || goto :ERROR + +echo fuzzer +!BIN!\fuzzer.exe -v -T30s || goto :ERROR + + +set /a errorno=0 +goto :END + +:ERROR + +:END +exit /B %errorno% diff --git a/build/VS2022/build-and-test-win32-debug.bat b/build/VS2022/build-and-test-win32-debug.bat new file mode 100644 index 0000000000000000000000000000000000000000..e745f87cd780168d49f53154ec0cef7932aa2aac --- /dev/null +++ b/build/VS2022/build-and-test-win32-debug.bat @@ -0,0 +1,26 @@ +@setlocal enabledelayedexpansion +@echo off +set /a errorno=1 +for /F "delims=#" %%E in ('"prompt #$E# & for %%E in (1) do rem"') do set "esc=%%E" + +call _setup.bat || goto :ERROR + +set "Configuration=Debug" +set "Platform=Win32" + +call _build.bat || goto :ERROR +call _test.bat || goto :ERROR + + +echo Build Status -%esc%[92m SUCCEEDED %esc%[0m +set /a errorno=0 +goto :END + + +:ERROR +echo Abort by error. +echo Build Status -%esc%[91m ERROR %esc%[0m + + +:END +exit /B %errorno% diff --git a/build/VS2022/build-and-test-win32-release.bat b/build/VS2022/build-and-test-win32-release.bat new file mode 100644 index 0000000000000000000000000000000000000000..f21007b68bf4521b9abf4178385cb01118e369d2 --- /dev/null +++ b/build/VS2022/build-and-test-win32-release.bat @@ -0,0 +1,26 @@ +@setlocal enabledelayedexpansion +@echo off +set /a errorno=1 +for /F "delims=#" %%E in ('"prompt #$E# & for %%E in (1) do rem"') do set "esc=%%E" + +call _setup.bat || goto :ERROR + +set "Configuration=Release" +set "Platform=Win32" + +call _build.bat || goto :ERROR +call _test.bat || goto :ERROR + + +echo Build Status -%esc%[92m SUCCEEDED %esc%[0m +set /a errorno=0 +goto :END + + +:ERROR +echo Abort by error. +echo Build Status -%esc%[91m ERROR %esc%[0m + + +:END +exit /B %errorno% diff --git a/build/VS2022/build-and-test-x64-debug.bat b/build/VS2022/build-and-test-x64-debug.bat new file mode 100644 index 0000000000000000000000000000000000000000..9d64a6fdbebc6302a93fd1b0f102fa072c2dab77 --- /dev/null +++ b/build/VS2022/build-and-test-x64-debug.bat @@ -0,0 +1,26 @@ +@setlocal enabledelayedexpansion +@echo off +set /a errorno=1 +for /F "delims=#" %%E in ('"prompt #$E# & for %%E in (1) do rem"') do set "esc=%%E" + +call _setup.bat || goto :ERROR + +set "Configuration=Debug" +set "Platform=x64" + +call _build.bat || goto :ERROR +call _test.bat || goto :ERROR + + +echo Build Status -%esc%[92m SUCCEEDED %esc%[0m +set /a errorno=0 +goto :END + + +:ERROR +echo Abort by error. +echo Build Status -%esc%[91m ERROR %esc%[0m + + +:END +exit /B %errorno% diff --git a/build/VS2022/build-and-test-x64-release.bat b/build/VS2022/build-and-test-x64-release.bat new file mode 100644 index 0000000000000000000000000000000000000000..3ebb18f5d2e64ffa162e9b17d735f3c9e5ea06d1 --- /dev/null +++ b/build/VS2022/build-and-test-x64-release.bat @@ -0,0 +1,26 @@ +@setlocal enabledelayedexpansion +@echo off +set /a errorno=1 +for /F "delims=#" %%E in ('"prompt #$E# & for %%E in (1) do rem"') do set "esc=%%E" + +call _setup.bat || goto :ERROR + +set "Configuration=Release" +set "Platform=x64" + +call _build.bat || goto :ERROR +call _test.bat || goto :ERROR + + +echo Build Status -%esc%[92m SUCCEEDED %esc%[0m +set /a errorno=0 +goto :END + + +:ERROR +echo Abort by error. +echo Build Status -%esc%[91m ERROR %esc%[0m + + +:END +exit /B %errorno% diff --git a/build/VS2022/datagen/datagen.vcxproj b/build/VS2022/datagen/datagen.vcxproj index 69034d410e1c718abf9cac2abb8908b1ba352a2b..a65a5d5bb7b229b8f855e045f95831cc04d16aa9 100644 --- a/build/VS2022/datagen/datagen.vcxproj +++ b/build/VS2022/datagen/datagen.vcxproj @@ -161,13 +161,17 @@ - + + + - + + + - \ No newline at end of file + diff --git a/build/VS2022/lz4.sln b/build/VS2022/lz4.sln index 6a2779f915b8f016c0eb0e23a6f7f7c805f6c529..10f8ec18cd7a85d714d2001097dde79c8002c81a 100644 --- a/build/VS2022/lz4.sln +++ b/build/VS2022/lz4.sln @@ -1,6 +1,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.28307.271 +# Visual Studio Version 17 +VisualStudioVersion = 17.6.33712.159 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "liblz4-dll", "liblz4-dll\liblz4-dll.vcxproj", "{9800039D-4AAA-43A4-BB78-FEF6F4836927}" EndProject @@ -20,6 +20,9 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "fullbench-dll", "fullbench- EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "lz4", "lz4\lz4.vcxproj", "{60A3115E-B988-41EE-8815-F4D4F253D866}" + ProjectSection(ProjectDependencies) = postProject + {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476} = {9092C5CC-3E71-41B3-BF68-4A7BDD8A5476} + EndProjectSection EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/build/VS2010/lz4/lz4.rc b/build/VS2022/lz4/lz4.rc similarity index 100% rename from build/VS2010/lz4/lz4.rc rename to build/VS2022/lz4/lz4.rc diff --git a/build/VS2017/lz4/lz4.vcxproj b/build/VS2022/lz4/lz4.vcxproj similarity index 83% rename from build/VS2017/lz4/lz4.vcxproj rename to build/VS2022/lz4/lz4.vcxproj index f16c1ec22d07ea9ab613c1647ce424272cb00062..3c964b42f2ed506a1a1c1ae80bda4ffc5063f1af 100644 --- a/build/VS2017/lz4/lz4.vcxproj +++ b/build/VS2022/lz4/lz4.vcxproj @@ -22,32 +22,32 @@ 15.0 {60A3115E-B988-41EE-8815-F4D4F253D866} lz4 - 8.1 + 10.0 Application true - v141 + v143 Unicode Application false - v141 + v143 false Unicode Application true - v141 + v143 MultiByte Application false - v141 + v143 true MultiByte @@ -105,6 +105,8 @@ Console false false + $(ProjectDir)..\bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories) + liblz4_static.lib;$(CoreLibraryDependencies);%(AdditionalDependencies) @@ -114,6 +116,10 @@ true true + + $(ProjectDir)..\bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories) + liblz4_static.lib;$(CoreLibraryDependencies);%(AdditionalDependencies) + @@ -130,6 +136,8 @@ true true Console + $(ProjectDir)..\bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories) + liblz4_static.lib;$(CoreLibraryDependencies);%(AdditionalDependencies) @@ -144,6 +152,8 @@ true true + $(ProjectDir)..\bin\$(Platform)_$(Configuration);%(AdditionalLibraryDirectories) + liblz4_static.lib;$(CoreLibraryDependencies);%(AdditionalDependencies) @@ -152,9 +162,12 @@ - + + + + @@ -163,8 +176,9 @@ - + + diff --git a/build/cmake/CMakeLists.txt b/build/cmake/CMakeLists.txt index eb7007b4eadec37e98b01f3f657d793f33d7d972..c372733aa57d995e2704bda8bd0b853ee603464f 100644 --- a/build/cmake/CMakeLists.txt +++ b/build/cmake/CMakeLists.txt @@ -6,48 +6,43 @@ # any warranty. # # For details, see . -# -# LZ4's CMake support is maintained by Evan Nemerson; when filing -# bugs please mention @nemequ to make sure I see it. -cmake_minimum_required(VERSION 2.8.12) + +cmake_minimum_required(VERSION 3.5) set(LZ4_TOP_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../..") # Parse version information -file(STRINGS "${LZ4_TOP_SOURCE_DIR}/lib/lz4.h" LZ4_VERSION_MAJOR REGEX "^#define LZ4_VERSION_MAJOR +([0-9]+) +.*$") -string(REGEX REPLACE "^#define LZ4_VERSION_MAJOR +([0-9]+) +.*$" "\\1" LZ4_VERSION_MAJOR "${LZ4_VERSION_MAJOR}") -file(STRINGS "${LZ4_TOP_SOURCE_DIR}/lib/lz4.h" LZ4_VERSION_MINOR REGEX "^#define LZ4_VERSION_MINOR +([0-9]+) +.*$") -string(REGEX REPLACE "^#define LZ4_VERSION_MINOR +([0-9]+) +.*$" "\\1" LZ4_VERSION_MINOR "${LZ4_VERSION_MINOR}") -file(STRINGS "${LZ4_TOP_SOURCE_DIR}/lib/lz4.h" LZ4_VERSION_RELEASE REGEX "^#define LZ4_VERSION_RELEASE +([0-9]+) +.*$") -string(REGEX REPLACE "^#define LZ4_VERSION_RELEASE +([0-9]+) +.*$" "\\1" LZ4_VERSION_RELEASE "${LZ4_VERSION_RELEASE}") +function(parse_lz4_version VERSION_TYPE) + file(STRINGS "${LZ4_TOP_SOURCE_DIR}/lib/lz4.h" version_line REGEX "^#define LZ4_VERSION_${VERSION_TYPE} +([0-9]+).*$") + string(REGEX REPLACE "^#define LZ4_VERSION_${VERSION_TYPE} +([0-9]+).*$" "\\1" version_number "${version_line}") + set(LZ4_VERSION_${VERSION_TYPE} ${version_number} PARENT_SCOPE) +endfunction() + +foreach(version_type IN ITEMS MAJOR MINOR RELEASE) + parse_lz4_version(${version_type}) +endforeach() + set(LZ4_VERSION_STRING "${LZ4_VERSION_MAJOR}.${LZ4_VERSION_MINOR}.${LZ4_VERSION_RELEASE}") mark_as_advanced(LZ4_VERSION_STRING LZ4_VERSION_MAJOR LZ4_VERSION_MINOR LZ4_VERSION_RELEASE) -if("${CMAKE_VERSION}" VERSION_LESS "3.0") - project(LZ4 C) -else() - cmake_policy (SET CMP0048 NEW) - project(LZ4 - VERSION ${LZ4_VERSION_STRING} - LANGUAGES C) -endif() +message(STATUS "Creating build script for LZ4 version: ${LZ4_VERSION_STRING}") + +project(LZ4 VERSION ${LZ4_VERSION_STRING} LANGUAGES C) + option(LZ4_BUILD_CLI "Build lz4 program" ON) -option(LZ4_BUILD_LEGACY_LZ4C "Build lz4c program with legacy argument support" ON) - -# If LZ4 is being bundled in another project, we don't want to -# install anything. However, we want to let people override this, so -# we'll use the LZ4_BUNDLED_MODE variable to let them do that; just -# set it to OFF in your project before you add_subdirectory(lz4/contrib/cmake_unofficial). -get_directory_property(LZ4_PARENT_DIRECTORY PARENT_DIRECTORY) -if("${LZ4_BUNDLED_MODE}" STREQUAL "") - # Bundled mode hasn't been set one way or the other, set the default - # depending on whether or not we are the top-level project. - if("${LZ4_PARENT_DIRECTORY}" STREQUAL "") - set(LZ4_BUNDLED_MODE OFF) - else() + + +# Determine if LZ4 is being built as part of another project. +# If LZ4 is bundled in another project, we don't want to install anything. +# Default behavior can be overridden by setting the LZ4_BUNDLED_MODE variable. +if(NOT DEFINED LZ4_BUNDLED_MODE) + get_directory_property(LZ4_IS_SUBPROJECT PARENT_DIRECTORY) + if(LZ4_IS_SUBPROJECT) set(LZ4_BUNDLED_MODE ON) + else() + set(LZ4_BUNDLED_MODE OFF) endif() endif() mark_as_advanced(LZ4_BUNDLED_MODE) @@ -80,19 +75,11 @@ set(LZ4_PROG_SOURCE_DIR "${LZ4_TOP_SOURCE_DIR}/programs") include_directories("${LZ4_LIB_SOURCE_DIR}") # CLI sources -set(LZ4_SOURCES - "${LZ4_LIB_SOURCE_DIR}/lz4.c" - "${LZ4_LIB_SOURCE_DIR}/lz4hc.c" - "${LZ4_LIB_SOURCE_DIR}/lz4.h" - "${LZ4_LIB_SOURCE_DIR}/lz4hc.h" - "${LZ4_LIB_SOURCE_DIR}/lz4frame.c" - "${LZ4_LIB_SOURCE_DIR}/lz4frame.h" - "${LZ4_LIB_SOURCE_DIR}/xxhash.c") -set(LZ4_CLI_SOURCES - "${LZ4_PROG_SOURCE_DIR}/bench.c" - "${LZ4_PROG_SOURCE_DIR}/lz4cli.c" - "${LZ4_PROG_SOURCE_DIR}/lz4io.c" - "${LZ4_PROG_SOURCE_DIR}/datagen.c") +file(GLOB LZ4_SOURCES + "${LZ4_LIB_SOURCE_DIR}/*.c") +file(GLOB LZ4_CLI_SOURCES + "${LZ4_PROG_SOURCE_DIR}/*.c") +list(APPEND LZ4_CLI_SOURCES ${LZ4_SOURCES}) # LZ4_CLI always use liblz4 sources directly. # Whether to use position independent code for the static library. If # we're building a shared library this is ignored and PIC is always @@ -100,6 +87,7 @@ set(LZ4_CLI_SOURCES option(LZ4_POSITION_INDEPENDENT_LIB "Use position independent code for static library (if applicable)" ON) # liblz4 +include(GNUInstallDirs) set(LZ4_LIBRARIES_BUILT) if(BUILD_SHARED_LIBS) add_library(lz4_shared SHARED ${LZ4_SOURCES}) @@ -130,11 +118,23 @@ if(BUILD_STATIC_LIBS) POSITION_INDEPENDENT_CODE ${LZ4_POSITION_INDEPENDENT_LIB}) list(APPEND LZ4_LIBRARIES_BUILT lz4_static) endif() +# Add unified target. +add_library(lz4 INTERFACE) +list(APPEND LZ4_LIBRARIES_BUILT lz4) +if(BUILD_SHARED_LIBS) + target_link_libraries(lz4 INTERFACE lz4_shared) +else() + target_link_libraries(lz4 INTERFACE lz4_static) +endif() +# xxhash namespace +if(BUILD_SHARED_LIBS) + target_compile_definitions(lz4_shared PRIVATE + XXH_NAMESPACE=LZ4_) +endif() if(BUILD_STATIC_LIBS) - set(LZ4_LINK_LIBRARY lz4_static) -else() - list(APPEND LZ4_CLI_SOURCES ${LZ4_SOURCES}) + target_compile_definitions(lz4_static PRIVATE + XXH_NAMESPACE=LZ4_) endif() # lz4 @@ -142,55 +142,44 @@ if (LZ4_BUILD_CLI) set(LZ4_PROGRAMS_BUILT lz4cli) add_executable(lz4cli ${LZ4_CLI_SOURCES}) set_target_properties(lz4cli PROPERTIES OUTPUT_NAME lz4) - if (BUILD_STATIC_LIBS) - target_link_libraries(lz4cli ${LZ4_LINK_LIBRARY}) - endif() -endif() - -# lz4c -if (LZ4_BUILD_LEGACY_LZ4C) - list(APPEND LZ4_PROGRAMS_BUILT lz4c) - add_executable(lz4c ${LZ4_CLI_SOURCES}) - set_target_properties(lz4c PROPERTIES COMPILE_DEFINITIONS "ENABLE_LZ4C_LEGACY_OPTIONS") - if (BUILD_STATIC_LIBS) - target_link_libraries(lz4c ${LZ4_LINK_LIBRARY}) - endif() endif() # Extra warning flags -include (CheckCCompilerFlag) -foreach (flag - # GCC-style - -Wall - -Wextra - -Wundef - -Wcast-qual - -Wcast-align - -Wshadow - -Wswitch-enum - -Wdeclaration-after-statement - -Wstrict-prototypes - -Wpointer-arith - - # MSVC-style - /W4) - # Because https://gcc.gnu.org/wiki/FAQ#wnowarning - string(REGEX REPLACE "\\-Wno\\-(.+)" "-W\\1" flag_to_test "${flag}") - string(REGEX REPLACE "[^a-zA-Z0-9]+" "_" test_name "CFLAG_${flag_to_test}") - - check_c_compiler_flag("${ADD_COMPILER_FLAGS_PREPEND} ${flag_to_test}" ${test_name}) - - if(${test_name}) - set(CMAKE_C_FLAGS "${flag} ${CMAKE_C_FLAGS}") - endif() +if(MSVC) + set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /W4") +else() + include (CheckCCompilerFlag) + foreach (flag + # GCC-style + -pedantic-errors + -Wall + -Wextra + -Wundef + -Wcast-qual + -Wcast-align + -Wshadow + -Wswitch-enum + -Wdeclaration-after-statement + -Wstrict-prototypes + -Wpointer-arith) + + # Because https://gcc.gnu.org/wiki/FAQ#wnowarning + string(REGEX REPLACE "\\-Wno\\-(.+)" "-W\\1" flag_to_test "${flag}") + string(REGEX REPLACE "[^a-zA-Z0-9]+" "_" test_name "CFLAG_${flag_to_test}") + + check_c_compiler_flag("${ADD_COMPILER_FLAGS_PREPEND} ${flag_to_test}" ${test_name}) + + if(${test_name}) + set(CMAKE_C_FLAGS_DEBUG "${flag} ${CMAKE_C_FLAGS_DEBUG}") + endif() + + unset(test_name) + unset(flag_to_test) + endforeach (flag) +endif() - unset(test_name) - unset(flag_to_test) -endforeach (flag) if(NOT LZ4_BUNDLED_MODE) - include(GNUInstallDirs) - install(TARGETS ${LZ4_PROGRAMS_BUILT} BUNDLE DESTINATION "${CMAKE_INSTALL_BINDIR}" RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") @@ -201,8 +190,9 @@ if(NOT LZ4_BUNDLED_MODE) RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}") install(FILES "${LZ4_LIB_SOURCE_DIR}/lz4.h" - "${LZ4_LIB_SOURCE_DIR}/lz4frame.h" "${LZ4_LIB_SOURCE_DIR}/lz4hc.h" + "${LZ4_LIB_SOURCE_DIR}/lz4frame.h" + "${LZ4_LIB_SOURCE_DIR}/lz4file.h" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") install(FILES "${LZ4_PROG_SOURCE_DIR}/lz4.1" DESTINATION "${CMAKE_INSTALL_MANDIR}/man1") @@ -233,16 +223,21 @@ if(NOT LZ4_BUNDLED_MODE) ${CMAKE_CURRENT_BINARY_DIR}/lz4ConfigVersion.cmake DESTINATION ${LZ4_PKG_INSTALLDIR}) - # install lz4cat and unlz4 symlinks on *nix + # Install lz4cat and unlz4 symlinks on Unix systems if(UNIX AND LZ4_BUILD_CLI) - install(CODE " - foreach(f lz4cat unlz4) - set(dest \"\$ENV{DESTDIR}${CMAKE_INSTALL_FULL_BINDIR}/\${f}\") - message(STATUS \"Symlinking: \${dest} -> lz4\") - execute_process( - COMMAND \"${CMAKE_COMMAND}\" -E create_symlink lz4 \"\${dest}\") - endforeach() - ") + foreach(cli_tool IN ITEMS lz4cat unlz4) + # Create a custom target for the symlink creation + add_custom_target("create_${cli_tool}_symlink" ALL + COMMAND ${CMAKE_COMMAND} -E create_symlink + $ ${cli_tool} + COMMENT "Creating symlink for ${cli_tool}" + VERBATIM) + + # Install the symlink into the binary installation directory + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${cli_tool}" + DESTINATION ${CMAKE_INSTALL_BINDIR} + RENAME ${cli_tool}) + endforeach() # create manpage aliases foreach(f lz4cat unlz4) diff --git a/contrib/meson/meson/GetLz4LibraryVersion.py b/build/meson/GetLz4LibraryVersion.py similarity index 87% rename from contrib/meson/meson/GetLz4LibraryVersion.py rename to build/meson/GetLz4LibraryVersion.py index d8abfcba0ccfbdfad72f32b3b01bb355045d0cd9..831fc5358e62b22aad7a876e8fc0bc27e5b983be 100644 --- a/contrib/meson/meson/GetLz4LibraryVersion.py +++ b/build/meson/GetLz4LibraryVersion.py @@ -15,9 +15,9 @@ def find_version_tuple(filepath): with open(filepath) as fd: version_file_data = fd.read() - patterns = r"""#\s*define\s+LZ4_VERSION_MAJOR\s+([0-9]+).*$ -#\s*define\s+LZ4_VERSION_MINOR\s+([0-9]+).*$ -#\s*define\s+LZ4_VERSION_RELEASE\s+([0-9]+).*$ + patterns = r"""\s*#\s*define\s+LZ4_VERSION_MAJOR\s+([0-9]+).*$ +\s*#\s*define\s+LZ4_VERSION_MINOR\s+([0-9]+).*$ +\s*#\s*define\s+LZ4_VERSION_RELEASE\s+([0-9]+).*$ """ regex = re.compile(patterns, re.MULTILINE) version_match = regex.search(version_file_data) diff --git a/contrib/meson/README.md b/build/meson/README.md similarity index 100% rename from contrib/meson/README.md rename to build/meson/README.md diff --git a/contrib/meson/meson.build b/build/meson/meson.build similarity index 83% rename from contrib/meson/meson.build rename to build/meson/meson.build index 39672c8c4538a02492927f6b788599ab7c4e96dc..fc6408af6ced1bb450e21f17701ab90103b74a96 100644 --- a/contrib/meson/meson.build +++ b/build/meson/meson.build @@ -13,15 +13,19 @@ project( 'lz4', - ['c'], + 'c', license: 'BSD-2-Clause-Patent AND GPL-2.0-or-later', default_options: [ 'c_std=c99', 'buildtype=release', 'warning_level=3' ], - version: 'DUMMY', - meson_version: '>=0.49.0' + version: run_command( + find_program('GetLz4LibraryVersion.py'), + '../../lib/lz4.h', + check: true + ).stdout().strip(), + meson_version: '>=0.58.0' ) subdir('meson') diff --git a/contrib/meson/meson/contrib/gen_manual/meson.build b/build/meson/meson/contrib/gen_manual/meson.build similarity index 94% rename from contrib/meson/meson/contrib/gen_manual/meson.build rename to build/meson/meson/contrib/gen_manual/meson.build index 84a95a9b5766d7430c691049d7a74842cfe5df39..c4349aa3fca46cd16e4c68325bdc1bc4a1ba3695 100644 --- a/contrib/meson/meson/contrib/gen_manual/meson.build +++ b/build/meson/meson/contrib/gen_manual/meson.build @@ -10,7 +10,7 @@ lz4_source_root = '../../../../..' -add_languages('cpp') +add_languages('cpp', native: true) sources = files( lz4_source_root / 'contrib/gen_manual/gen_manual.cpp' @@ -33,7 +33,7 @@ foreach mp : manual_pages output: '@0@_manual.html'.format(mp), command: [ gen_manual, - lz4_version, + meson.project_version(), '@INPUT@', '@OUTPUT@', ], diff --git a/contrib/meson/meson/contrib/meson.build b/build/meson/meson/contrib/meson.build similarity index 100% rename from contrib/meson/meson/contrib/meson.build rename to build/meson/meson/contrib/meson.build diff --git a/contrib/meson/meson/examples/meson.build b/build/meson/meson/examples/meson.build similarity index 70% rename from contrib/meson/meson/examples/meson.build rename to build/meson/meson/examples/meson.build index 65f54ca09d6a1386463cbe18a2dad2843c3c0fe2..dd263340381729e94333e5f631824ae1f4cad5a7 100644 --- a/contrib/meson/meson/examples/meson.build +++ b/build/meson/meson/examples/meson.build @@ -11,15 +11,15 @@ lz4_source_root = '../../../..' examples = { - 'printVersion': 'printVersion.c', - 'doubleBuffer': 'blockStreaming_doubleBuffer.c', + 'print_version': 'print_version.c', + 'blockStreaming_doubleBuffer': 'blockStreaming_doubleBuffer.c', 'dictionaryRandomAccess': 'dictionaryRandomAccess.c', - 'ringBuffer': 'blockStreaming_ringBuffer.c', - 'ringBufferHC': 'HCStreaming_ringBuffer.c', - 'lineCompress': 'blockStreaming_lineByLine.c', + 'blockStreaming_ringBuffer': 'blockStreaming_ringBuffer.c', + 'streamingHC_ringBuffer': 'streamingHC_ringBuffer.c', + 'blockStreaming_lineByLine': 'blockStreaming_lineByLine.c', 'frameCompress': 'frameCompress.c', - 'compressFunctions': 'compress_functions.c', - 'simpleBuffer': 'simple_buffer.c', + 'bench_functions': 'bench_functions.c', + 'simple_buffer': 'simple_buffer.c', } foreach e, src : examples diff --git a/contrib/meson/meson/lib/meson.build b/build/meson/meson/lib/meson.build similarity index 69% rename from contrib/meson/meson/lib/meson.build rename to build/meson/meson/lib/meson.build index 469cd091a4e6ceb9cb2e60e8c3553ccaa25469e4..4acf614187abb3287d84984efb270fbd943c3987 100644 --- a/contrib/meson/meson/lib/meson.build +++ b/build/meson/meson/lib/meson.build @@ -17,41 +17,49 @@ sources = files( lz4_source_root / 'lib/xxhash.c' ) +if get_option('unstable') + sources += files(lz4_source_root / 'lib/lz4file.c') +endif + c_args = [] if host_machine.system() == 'windows' and get_option('default_library') != 'static' c_args += '-DLZ4_DLL_EXPORT=1' endif -if get_option('unstable') - compile_args += '-DLZ4_STATIC_LINKING_ONLY' - if get_option('default_library') != 'static' - c_args += '-DLZ4_PUBLISH_STATIC_FUNCTIONS' - endif -endif - liblz4 = library( 'lz4', sources, + c_args: c_args, install: true, - version: lz4_version, + version: meson.project_version(), gnu_symbol_visibility: 'hidden' ) liblz4_dep = declare_dependency( link_with: liblz4, + compile_args: compile_args, include_directories: include_directories(lz4_source_root / 'lib') ) -if get_option('tests') or get_option('programs') or get_option('examples') - liblz4_internal = static_library( - 'lz4-internal', - objects: liblz4.extract_all_objects(recursive: true), - gnu_symbol_visibility: 'hidden' - ) +meson.override_dependency('liblz4', liblz4_dep) + +if get_option('tests') or get_option('programs') or get_option('examples') or get_option('ossfuzz') + if get_option('default_library') == 'shared' + liblz4_internal = static_library( + 'lz4-internal', + objects: liblz4.extract_all_objects(recursive: true), + gnu_symbol_visibility: 'hidden' + ) + elif get_option('default_library') == 'static' + liblz4_internal = liblz4 + elif get_option('default_library') == 'both' + liblz4_internal = liblz4.get_static_lib() + endif liblz4_internal_dep = declare_dependency( link_with: liblz4_internal, + compile_args: compile_args, include_directories: include_directories(lz4_source_root / 'lib') ) endif @@ -61,7 +69,7 @@ pkgconfig.generate( name: 'lz4', filebase: 'liblz4', description: 'extremely fast lossless compression algorithm library', - version: lz4_version, + version: meson.project_version(), url: 'http://www.lz4.org/' ) @@ -73,4 +81,7 @@ install_headers( if get_option('default_library') != 'shared' install_headers(lz4_source_root / 'lib/lz4frame_static.h') + if get_option('unstable') + install_headers(lz4_source_root / 'lib/lz4file.h') + endif endif diff --git a/contrib/meson/meson/meson.build b/build/meson/meson/meson.build similarity index 30% rename from contrib/meson/meson/meson.build rename to build/meson/meson/meson.build index 9e8b8c699856c138c06b42a0392f59c94ff60256..90337bb6d15775a969bc9c6d5227fda1fa6c072d 100644 --- a/contrib/meson/meson/meson.build +++ b/build/meson/meson/meson.build @@ -10,48 +10,112 @@ cc = meson.get_compiler('c') +fs = import('fs') pkgconfig = import('pkgconfig') lz4_source_root = '../../..' -lz4_version = meson.project_version() - -lz4_h_file = lz4_source_root / 'lib/lz4.h' -GetLz4LibraryVersion_py = find_program('GetLz4LibraryVersion.py') -lz4_version = run_command(GetLz4LibraryVersion_py, lz4_h_file, check: true).stdout().strip() -message('Project version is now: @0@'.format(lz4_version)) - add_project_arguments('-DXXH_NAMESPACE=LZ4_', language: 'c') if get_option('debug') - add_project_arguments(cc.get_supported_arguments([ - '-Wcast-qual', - '-Wcast-align', - '-Wshadow', - '-Wswitch-enum', - '-Wdeclaration-after-statement', - '-Wstrict-prototypes', - '-Wundef', - '-Wpointer-arith', - '-Wstrict-aliasing=1', - '-DLZ4_DEBUG=@0@'.format(get_option('debug-level')), - ] + add_project_arguments(cc.get_supported_arguments( + '-Wcast-qual', + '-Wcast-align', + '-Wshadow', + '-Wswitch-enum', + '-Wdeclaration-after-statement', + '-Wstrict-prototypes', + '-Wundef', + '-Wpointer-arith', + '-Wstrict-aliasing=1', + '-DLZ4_DEBUG=@0@'.format(get_option('debug-level')) + ), + language: 'c' + ) +endif + +compile_args = [] + +if not get_option('align-test') + add_project_arguments('-DLZ4_ALIGN_TEST=0', language: 'c') +endif + +if get_option('disable-memory-allocation') + if get_option('default_library') != 'static' + error('Memory allocation can only be disabled in static builds') + endif + + add_project_arguments('-DLZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION') + compile_args += '-DLZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION' +endif + +add_project_arguments( + '-DLZ4_DISTANCE_MAX=@0@'.format(get_option('distance-max')), + language: 'c' +) +compile_args += '-DLZ4_DISTANCE_MAX=@0@'.format(get_option('distance-max')) + +if not get_option('fast-dec-loop').auto() + add_project_arguments( + '-DLZ4_FAST_DEC_LOOP=@0@'.format( + get_option('fast-dec-loop').enabled() ? 1 : 0 ), - language: 'c', + language: 'c' ) endif +if get_option('force-sw-bitcount') + add_project_arguments('-DLZ4_FORCE_SW_BITCOUNT', language: 'c') +endif + +if get_option('freestanding') + add_project_arguments('-DLZ4_FREESTANDING=1', language: 'c') + compile_args += '-DLZ4_FREESTANDING=1' +endif + if get_option('memory-usage') > 0 add_project_arguments( '-DLZ4_MEMORY_USAGE=@0@'.format(get_option('memory-usage')), language: 'c' ) + compile_args += '-DLZ4_MEMORY_USAGE=@0@'.format(get_option('memory-usage')) endif +if get_option('endianness-independent-output') + if get_option('default_library') != 'static' + error('Endianness-independent output can only be enabled in static builds') + endif + + add_project_arguments('-DLZ4_STATIC_LINKING_ONLY_ENDIANNESS_INDEPENDENT_OUTPUT') + compile_args += '-DLZ4_STATIC_LINKING_ONLY_ENDIANNESS_INDEPENDENT_OUTPUT' +endif + +if get_option('unstable') + add_project_arguments('-DLZ4_STATIC_LINKING_ONLY', language: 'c') + compile_args += '-DLZ4_STATIC_LINKING_ONLY' + if get_option('default_library') != 'static' + add_project_arguments('-DLZ4_PUBLISH_STATIC_FUNCTIONS', language: 'c') + compile_args += '-DLZ4_PUBLISH_STATIC_FUNCTIONS' + + add_project_arguments('-DLZ4F_PUBLISH_STATIC_FUNCTIONS', language: 'c') + compile_args += '-DLZ4F_PUBLISH_STATIC_FUNCTIONS' + endif +endif + +if get_option('user-memory-functions') + add_project_arguments('-DLZ4_USER_MEMORY_FUNCTIONS', language: 'c') +endif + +run_env = environment() + subdir('lib') if get_option('programs') subdir('programs') +else + lz4 = disabler() + lz4cat = disabler() + unlz4 = disabler() endif if get_option('tests') @@ -65,3 +129,7 @@ endif if get_option('examples') subdir('examples') endif + +if get_option('ossfuzz') + subdir('ossfuzz') +endif diff --git a/build/meson/meson/ossfuzz/meson.build b/build/meson/meson/ossfuzz/meson.build new file mode 100644 index 0000000000000000000000000000000000000000..9945d8c51bb05a144fd778dfb6815af30e52ce89 --- /dev/null +++ b/build/meson/meson/ossfuzz/meson.build @@ -0,0 +1,35 @@ +fuzzers = [ + 'compress_frame_fuzzer', + 'compress_fuzzer', + 'compress_hc_fuzzer', + 'decompress_frame_fuzzer', + 'decompress_fuzzer', + 'round_trip_frame_uncompressed_fuzzer', + 'round_trip_fuzzer', + 'round_trip_hc_fuzzer', + 'round_trip_stream_fuzzer' +] + +c_args = cc.get_supported_arguments( + '-Wno-unused-function', + '-Wno-sign-compare', + '-Wno-declaration-after-statement' +) + +foreach f : fuzzers + lib = static_library( + f, + lz4_source_root / 'ossfuzz/@0@.c'.format(f), + lz4_source_root / 'ossfuzz/lz4_helpers.c', + lz4_source_root / 'ossfuzz/fuzz_data_producer.c', + c_args: c_args, + dependencies: [liblz4_internal_dep] + ) + + executable( + f, + lz4_source_root / 'ossfuzz/standaloneengine.c', + link_with: lib, + dependencies: [liblz4_internal_dep] + ) +endforeach diff --git a/contrib/meson/meson/programs/meson.build b/build/meson/meson/programs/meson.build similarity index 55% rename from contrib/meson/meson/programs/meson.build rename to build/meson/meson/programs/meson.build index f9d5bf1c94a2ba9468f690ad0f5f2ce5dc05fc6f..16f802b11629cd7e026ab53f9ecabdd86ece9ba4 100644 --- a/contrib/meson/meson/programs/meson.build +++ b/build/meson/meson/programs/meson.build @@ -10,22 +10,69 @@ lz4_source_root = '../../../..' +# note: +# it would be preferable to use some kind of glob or wildcard expansion here... sources = files( lz4_source_root / 'programs/bench.c', - lz4_source_root / 'programs/datagen.c', + lz4_source_root / 'programs/lorem.c', lz4_source_root / 'programs/lz4cli.c', lz4_source_root / 'programs/lz4io.c', + lz4_source_root / 'programs/util.c', + lz4_source_root / 'programs/threadpool.c', + lz4_source_root / 'programs/timefn.c', ) +# Initialize an empty list for extra dependencies +extra_deps = [] + +if get_option('enable_multithread') + pthread_dep = dependency('threads', required : true) + extra_deps += [pthread_dep] + multithread_args = ['-DLZ4IO_MULTITHREAD'] +else + multithread_args = [] +endif + lz4 = executable( 'lz4', sources, include_directories: include_directories(lz4_source_root / 'programs'), - dependencies: [liblz4_internal_dep], + dependencies: [liblz4_internal_dep] + extra_deps, + c_args: multithread_args, export_dynamic: get_option('debug') and host_machine.system() == 'windows', install: true ) +lz4cat = custom_target( + 'lz4cat', + input: lz4, + output: 'lz4cat', + command: [ + 'ln', + '--symbolic', + '--force', + fs.name(lz4.full_path()), + '@OUTPUT@' + ] +) + +unlz4 = custom_target( + 'unlz4', + input: lz4, + output: 'unlz4', + command: [ + 'ln', + '--symbolic', + '--force', + fs.name(lz4.full_path()), + '@OUTPUT@' + ] +) + +meson.override_find_program('lz4', lz4) + +run_env.prepend('PATH', meson.current_build_dir()) + install_man(lz4_source_root / 'programs/lz4.1') if meson.version().version_compare('>=0.61.0') diff --git a/contrib/meson/meson/tests/meson.build b/build/meson/meson/tests/meson.build similarity index 36% rename from contrib/meson/meson/tests/meson.build rename to build/meson/meson/tests/meson.build index 18479e4b5fad4439d09b5af492b9e376a960923a..4cf86a63531070c16045980f7ced36764910ac83 100644 --- a/contrib/meson/meson/tests/meson.build +++ b/build/meson/meson/tests/meson.build @@ -10,43 +10,153 @@ lz4_source_root = '../../../..' -exes = { - 'fullbench': { - 'sources': files(lz4_source_root / 'tests/fullbench.c'), +fuzzer_time = 90 +test_exes = { + 'abiTest': { + 'sources': files(lz4_source_root / 'tests/abiTest.c'), + 'test': false, + }, + 'checkFrame': { + 'sources': files(lz4_source_root / 'tests/checkFrame.c'), 'include_directories': include_directories(lz4_source_root / 'programs'), }, - 'fuzzer': { - 'sources': files(lz4_source_root / 'tests/fuzzer.c'), + 'checkTag': { + 'sources': files(lz4_source_root / 'tests/checkTag.c'), + 'test': false, + }, + 'datagen': { + 'sources': files( + lz4_source_root / 'programs/lorem.c', + lz4_source_root / 'tests/datagencli.c', + lz4_source_root / 'tests/datagen.c', + lz4_source_root / 'tests/loremOut.c', + ), 'include_directories': include_directories(lz4_source_root / 'programs'), }, + 'decompress-partial-usingDict.c': { + 'sources': files(lz4_source_root / 'tests/decompress-partial-usingDict.c'), + }, + 'decompress-partial.c': { + 'sources': files(lz4_source_root / 'tests/decompress-partial.c'), + }, 'frametest': { 'sources': files(lz4_source_root / 'tests/frametest.c'), 'include_directories': include_directories(lz4_source_root / 'programs'), + 'args': ['-v', '-T@0@s'.format(fuzzer_time)], + 'test': false, }, - 'roundTripTest': { - 'sources': files(lz4_source_root / 'tests/roundTripTest.c'), + 'freestanding': { + 'sources': files(lz4_source_root / 'tests/freestanding.c'), + 'c_args': ['-ffreestanding', '-Wno-unused-parameter', '-Wno-declaration-after-statement'], + 'link_args': ['-nostdlib'], + 'build': cc.get_id() in ['gcc', 'clang'] and + host_machine.system() == 'linux' and host_machine.cpu_family() == 'x86_64', + 'override_options': ['optimization=1'], }, - 'datagen': { - 'sources': files(lz4_source_root / 'tests/datagencli.c'), - 'objects': lz4.extract_objects(lz4_source_root / 'programs/datagen.c'), + 'fullbench': { + 'sources': files(lz4_source_root / 'tests/fullbench.c'), 'include_directories': include_directories(lz4_source_root / 'programs'), + 'args': ['--no-prompt', '-i1', files(lz4_source_root / 'tests/COPYING')], + 'test': false, }, - 'checkFrame': { - 'sources': files(lz4_source_root / 'tests/checkFrame.c'), + 'fuzzer': { + 'sources': files(lz4_source_root / 'tests/fuzzer.c'), 'include_directories': include_directories(lz4_source_root / 'programs'), + 'args': ['-T@0@s'.format(fuzzer_time)], + 'test': false, }, - 'checkTag': { - 'sources': files(lz4_source_root / 'tests/checkTag.c'), + 'roundTripTest': { + 'sources': files(lz4_source_root / 'tests/roundTripTest.c'), + 'test': false, }, } -foreach e, attrs : exes - executable( +targets = {} + +foreach e, attrs : test_exes + if not attrs.get('build', true) + targets += {e: disabler()} + continue + endif + + t = executable( e, attrs.get('sources'), + c_args: attrs.get('c_args', []), + link_args: attrs.get('link_args', []), objects: attrs.get('objects', []), dependencies: [liblz4_internal_dep], include_directories: attrs.get('include_directories', []), - install: false + install: false, + override_options: attrs.get('override_options', []) + ) + + targets += {e: t} + + if not attrs.get('test', true) + continue + endif + + test( + e, + t, + args: attrs.get('params', []), + timeout: 120 + ) +endforeach + +fs = import('fs') + +run_env.prepend('PATH', meson.current_build_dir()) + +test_scripts = { + 'lz4-basic': { + 'depends': [lz4, lz4cat, unlz4, targets['datagen']], + }, + 'lz4-dict': { + 'depends': [lz4, targets['datagen']], + }, + 'lz4-contentSize': { + 'depends': [lz4, targets['datagen']], + }, + 'lz4-fast-hugefile': { + 'depends': [lz4, targets['datagen']], + }, + 'lz4-frame-concatenation': { + 'depends': [lz4, targets['datagen']], + }, + 'lz4-multiple': { + 'depends': [lz4, targets['datagen']], + }, + 'lz4-multiple-legacy': { + 'depends': [lz4, targets['datagen']], + }, + 'lz4-opt-parser': { + 'depends': [lz4, targets['datagen']], + }, + 'lz4-skippable': { + 'depends': [lz4], + }, + 'lz4-sparse': { + 'depends': [lz4, targets['datagen']], + }, + 'lz4-testmode': { + 'depends': [lz4, targets['datagen']], + }, + 'lz4hc-hugefile': { + 'depends': [lz4, targets['datagen']], + }, +} + +foreach s, attrs : test_scripts + script = find_program(lz4_source_root / 'tests/test-@0@.sh'.format(s)) + + test( + '@0@'.format(s), + script, + depends: attrs.get('depends', []), + workdir: fs.parent(script.full_path()), + env: run_env, + timeout: 360 ) endforeach diff --git a/contrib/meson/meson_options.txt b/build/meson/meson_options.txt similarity index 43% rename from contrib/meson/meson_options.txt rename to build/meson/meson_options.txt index ccb32de0a988775a8d0fac2c1314601138c2049d..d9c30d63b22b48813ae8056adc4343662cb87746 100644 --- a/contrib/meson/meson_options.txt +++ b/build/meson/meson_options.txt @@ -8,17 +8,37 @@ # in the COPYING file in the root directory of this source tree). # ############################################################################# +option('enable_multithread', type: 'boolean', value: true, + description: 'Enable multi-threading support') +option('align-test', type: 'boolean', value: true, + description: 'See LZ4_ALIGN_TEST') +option('contrib', type: 'boolean', value: false, + description: 'Enable contrib') option('debug-level', type: 'integer', min: 0, max: 7, value: 1, description: 'Enable run-time debug. See lib/lz4hc.c') -option('unstable', type: 'boolean', value: false, - description: 'Expose unstable interfaces') -option('programs', type: 'boolean', value: false, - description: 'Enable programs build') -option('tests', type: 'boolean', value: false, - description: 'Enable tests build') -option('contrib', type: 'boolean', value: false, - description: 'Enable contrib build') +option('disable-memory-allocation', type: 'boolean', value: false, + description: 'See LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION. Static builds only') +option('distance-max', type: 'integer', min: 0, max: 65535, value: 65535, + description: 'See LZ4_DISTANCE_MAX') +option('endianness-independent-output', type: 'boolean', value: false, + description: 'See LZ4_STATIC_LINKING_ONLY_ENDIANNESS_INDEPENDENT_OUTPUT. Static builds only') option('examples', type: 'boolean', value: false, - description: 'Enable examples build') -option('memory-usage', type: 'integer', min: 0, value: 0, + description: 'Enable examples') +option('fast-dec-loop', type: 'feature', value: 'auto', + description: 'See LZ4_FAST_DEC_LOOP') +option('force-sw-bitcount', type: 'boolean', value: false, + description: 'See LZ4_FORCE_SW_BITCOUNT') +option('freestanding', type: 'boolean', value: false, + description: 'See LZ4_FREESTANDING') +option('memory-usage', type: 'integer', min: 0, max: 20, value: 0, description: 'See LZ4_MEMORY_USAGE. 0 means use the LZ4 default') +option('ossfuzz', type: 'boolean', value: true, + description: 'Enable ossfuzz') +option('programs', type: 'boolean', value: false, + description: 'Enable programs') +option('tests', type: 'boolean', value: false, + description: 'Enable tests') +option('unstable', type: 'boolean', value: false, + description: 'Expose unstable interfaces') +option('user-memory-functions', type: 'boolean', value: false, + description: 'See LZ4_USER_MEMORY_FUNCTIONS') diff --git a/build/visual/README.md b/build/visual/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e96c42a415d9d0eeff6b92d653e49e4393226fe9 --- /dev/null +++ b/build/visual/README.md @@ -0,0 +1,5 @@ +These scripts will generate Visual Studio Solutions for a selected set of supported versions of MS Visual. + +For these scripts to work, both `cmake` and the relevant Visual Studio version must be locally installed on the system where the script is run. + +If `cmake` is installed into a non-standard directory, or user wants to test a specific version of `cmake`, the target `cmake` directory can be provided via the environment variable `CMAKE_PATH`. diff --git a/build/visual/generate_solution.cmd b/build/visual/generate_solution.cmd new file mode 100644 index 0000000000000000000000000000000000000000..644d8122a52a6a1967bbc1e1bc4669e345a37621 --- /dev/null +++ b/build/visual/generate_solution.cmd @@ -0,0 +1,55 @@ +:: Requires 1 parameter == GENERATOR +@echo off +setlocal + +:: Set path +set "BUILD_BASE_DIR=%~dp0" :: Use the directory where the script is located +set "CMAKELIST_DIR=..\..\cmake" + +if "%~1"=="" ( + echo No generator specified as first parameter + exit /b 1 +) +set "GENERATOR=%~1" + +:: Check if a user-defined CMAKE_PATH is set and prioritize it +if defined CMAKE_PATH ( + set "CMAKE_EXECUTABLE=%CMAKE_PATH%\cmake.exe" + echo Using user-defined cmake at %CMAKE_PATH% +) else ( + :: Attempt to find cmake in the system PATH + where cmake >nul 2>&1 + if %ERRORLEVEL% neq 0 ( + :: Use the default standard cmake installation directory if not found in PATH + set "CMAKE_PATH=C:\Program Files\CMake\bin" + echo CMake not in system PATH => using default CMAKE_PATH=%CMAKE_PATH% + set "CMAKE_EXECUTABLE=%CMAKE_PATH%\cmake.exe" + ) else ( + set "CMAKE_EXECUTABLE=cmake" + echo CMake found in system PATH. + ) +) + +:: Set the build directory to a subdirectory named after the generator +set "BUILD_DIR=%BUILD_BASE_DIR%\%GENERATOR%" + +:: Create the build directory if it doesn't exist +if not exist "%BUILD_DIR%" mkdir "%BUILD_DIR%" + +:: Run CMake to configure the project and generate the solution +pushd "%BUILD_DIR%" +"%CMAKE_EXECUTABLE%" -G "%GENERATOR%" "%CMAKELIST_DIR%" +if %ERRORLEVEL% neq 0 goto :error + +:: If successful, end script +echo Build configuration successful for %GENERATOR%. +goto :end + +:error +echo Failed to configure build for %GENERATOR%. +exit /b 1 + +:end +popd +endlocal +@echo on diff --git a/build/visual/generate_vs2015.cmd b/build/visual/generate_vs2015.cmd new file mode 100644 index 0000000000000000000000000000000000000000..9b64a4f04ce256d48977990304c60beaacb38f48 --- /dev/null +++ b/build/visual/generate_vs2015.cmd @@ -0,0 +1,3 @@ +@echo off +:: Call the central script with the specific generator for VS2015 +call generate_solution.cmd "Visual Studio 14 2015" diff --git a/build/visual/generate_vs2017.cmd b/build/visual/generate_vs2017.cmd new file mode 100644 index 0000000000000000000000000000000000000000..d5ab8fcc1c36bc8514ea0a90b02b8f2c60f85206 --- /dev/null +++ b/build/visual/generate_vs2017.cmd @@ -0,0 +1,3 @@ +@echo off +:: Call the central script with the specific generator for VS2017 +call generate_solution.cmd "Visual Studio 15 2017" diff --git a/build/visual/generate_vs2019.cmd b/build/visual/generate_vs2019.cmd new file mode 100644 index 0000000000000000000000000000000000000000..653fc6e88353d3df8616ffb6cd41d7f9b654fabf --- /dev/null +++ b/build/visual/generate_vs2019.cmd @@ -0,0 +1,3 @@ +@echo off +:: Call the central script with the specific generator for VS2019 +call generate_solution.cmd "Visual Studio 16 2019" diff --git a/build/visual/generate_vs2022.cmd b/build/visual/generate_vs2022.cmd new file mode 100644 index 0000000000000000000000000000000000000000..a48f744d2c292cbf7ca70068f4c1a7f30a572d22 --- /dev/null +++ b/build/visual/generate_vs2022.cmd @@ -0,0 +1,3 @@ +@echo off +:: Call the central script with the specific generator for VS2022 +call generate_solution.cmd "Visual Studio 17 2022" diff --git a/contrib/djgpp/Makefile b/contrib/djgpp/Makefile index 8cd3580823992bb22052ce78d315975ab73abbde..f6388b4aaf2a7022ddc53fafb8fd1ea533b6bda6 100644 --- a/contrib/djgpp/Makefile +++ b/contrib/djgpp/Makefile @@ -7,9 +7,9 @@ DESTDIR ?= /opt/local # Version numbers VERSION ?= 129 RELEASE ?= r$(VERSION) -LIBVER_MAJOR=$(shell sed -n '/define LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < lib/lz4.h) -LIBVER_MINOR=$(shell sed -n '/define LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < lib/lz4.h) -LIBVER_PATCH=$(shell sed -n '/define LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < lib/lz4.h) +LIBVER_MAJOR=$(shell sed -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < lib/lz4.h) +LIBVER_MINOR=$(shell sed -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < lib/lz4.h) +LIBVER_PATCH=$(shell sed -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < lib/lz4.h) LIBVER=$(LIBVER_MAJOR).$(LIBVER_MINOR).$(LIBVER_PATCH) ###################################################################### @@ -19,7 +19,7 @@ CC = $(CROSS)-gcc AR = $(CROSS)-ar LD = $(CROSS)-gcc -CFLAGS ?= -O3 -std=gnu99 -Wall -Wextra -Wundef -Wshadow -Wcast-qual -Wcast-align -Wstrict-prototypes -pedantic -DLZ4_VERSION=\"$(RELEASE)\" +CFLAGS ?= -O3 -std=gnu99 -Wall -Wextra -Wundef -Wshadow -Wcast-qual -Wcast-align -Wstrict-prototypes -Wpedantic -DLZ4_VERSION=\"$(RELEASE)\" LDFLAGS ?= -s SRC = programs/bench.c programs/lz4io.c programs/lz4cli.c OBJ = $(SRC:.c=.o) diff --git a/contrib/gen_manual/Makefile b/contrib/gen_manual/Makefile index 262c80de85514b0d15ef42c31bfa1a07dc8ddc32..49daad49f59de22d4e6f35914eb5e850ffee8981 100644 --- a/contrib/gen_manual/Makefile +++ b/contrib/gen_manual/Makefile @@ -39,9 +39,9 @@ LZ4API = ../../lib/lz4.h LZ4MANUAL = ../../doc/lz4_manual.html LZ4FAPI = ../../lib/lz4frame.h LZ4FMANUAL = ../../doc/lz4frame_manual.html -LIBVER_MAJOR_SCRIPT:=`sed -n '/define LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LZ4API)` -LIBVER_MINOR_SCRIPT:=`sed -n '/define LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LZ4API)` -LIBVER_PATCH_SCRIPT:=`sed -n '/define LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LZ4API)` +LIBVER_MAJOR_SCRIPT:=`sed -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LZ4API)` +LIBVER_MINOR_SCRIPT:=`sed -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LZ4API)` +LIBVER_PATCH_SCRIPT:=`sed -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LZ4API)` LIBVER_SCRIPT:= $(LIBVER_MAJOR_SCRIPT).$(LIBVER_MINOR_SCRIPT).$(LIBVER_PATCH_SCRIPT) LZ4VER := $(shell echo $(LIBVER_SCRIPT)) diff --git a/contrib/gen_manual/gen-lz4-manual.sh b/contrib/gen_manual/gen-lz4-manual.sh index 73a721482009e44b6cc05e79df0e074cc716e34b..7bbfe18f27c4121124d111a3a280d7ca8af4641c 100644 --- a/contrib/gen_manual/gen-lz4-manual.sh +++ b/contrib/gen_manual/gen-lz4-manual.sh @@ -1,8 +1,8 @@ #!/bin/sh -LIBVER_MAJOR_SCRIPT=`sed -n '/define LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ../../lib/lz4.h` -LIBVER_MINOR_SCRIPT=`sed -n '/define LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ../../lib/lz4.h` -LIBVER_PATCH_SCRIPT=`sed -n '/define LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ../../lib/lz4.h` +LIBVER_MAJOR_SCRIPT=`sed -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ../../lib/lz4.h` +LIBVER_MINOR_SCRIPT=`sed -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ../../lib/lz4.h` +LIBVER_PATCH_SCRIPT=`sed -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ../../lib/lz4.h` LIBVER_SCRIPT=$LIBVER_MAJOR_SCRIPT.$LIBVER_MINOR_SCRIPT.$LIBVER_PATCH_SCRIPT echo LZ4_VERSION=$LIBVER_SCRIPT diff --git a/contrib/snap/snapcraft.yaml b/contrib/snap/snapcraft.yaml index ae16537ade243da33784811c7b800c8823309a8f..7757a10d886fdbce2a291376263d28b121548fb4 100644 --- a/contrib/snap/snapcraft.yaml +++ b/contrib/snap/snapcraft.yaml @@ -20,6 +20,7 @@ description: > LZ4 library is provided as open-source software using BSD 2-Clause license. confinement: strict grade: stable +base: core20 apps: lz4: diff --git a/doc/lz4_Frame_format.md b/doc/lz4_Frame_format.md index 97a2cbe3433cb3bbaef40af1063a155a2a4f0388..24f2734f3e6a58ab87495f8c3455f214bc521121 100644 --- a/doc/lz4_Frame_format.md +++ b/doc/lz4_Frame_format.md @@ -16,7 +16,7 @@ Distribution of this document is unlimited. ### Version -1.6.2 (12/08/2020) +1.6.4 (28/12/2023) Introduction @@ -61,9 +61,9 @@ and associated error message explaining which parameter is unsupported. General Structure of LZ4 Frame format ------------------------------------- -| MagicNb | F. Descriptor | Block | (...) | EndMark | C. Checksum | -|:-------:|:-------------:| ----- | ----- | ------- | ----------- | -| 4 bytes | 3-15 bytes | | | 4 bytes | 0-4 bytes | +| MagicNb | F. Descriptor | Data Block | (...) | EndMark | C. Checksum | +|:-------:|:-------------:| ---------- | ----- | ------- | ----------- | +| 4 bytes | 3-15 bytes | | | 4 bytes | 0-4 bytes | __Magic Number__ @@ -219,24 +219,26 @@ It can be skipped by a decoder, or used to validate content correctness. __Dictionary ID__ -Dict-ID is only present if the associated flag is set. -It's an unsigned 32-bits value, stored using little-endian convention. A dictionary is useful to compress short input sequences. -The compressor can take advantage of the dictionary context -to encode the input in a more compact manner. -It works as a kind of “known prefix” which is used by -both the compressor and the decompressor to “warm-up” reference tables. - -The decompressor can use Dict-ID identifier to determine -which dictionary must be used to correctly decode data. -The compressor and the decompressor must use exactly the same dictionary. -It's presumed that the 32-bits dictID uniquely identifies a dictionary. +When present, the compressor can take advantage of dictionary's content +as a kind of “known prefix” to encode the input in a more compact manner. -Within a single frame, a single dictionary can be defined. When the frame descriptor defines independent blocks, -each block will be initialized with the same dictionary. +every block is initialized with the same dictionary. If the frame descriptor defines linked blocks, -the dictionary will only be used once, at the beginning of the frame. +the dictionary is only used once, at the beginning of the frame. + +The compressor and the decompressor must employ exactly the same dictionary for the data to be decodable. + +The Dict-ID field is offered as a way to help the decoder determine +which dictionary must be used to correctly decode the compressed frame. +Dict-ID is only present if the associated flag is set. +It's an unsigned 32-bits value, stored using little-endian convention. +Within a single frame, only a single Dict-ID field can be defined. + +Note that the Dict-ID field is optional. +Knowledge of which dictionary to employ can also be passed off-band, +for example, it could be implied by the context of the application. __Header Checksum__ @@ -269,7 +271,7 @@ The size does not include the block checksum if present. _Block_Size_ shall never be larger than _Block_Maximum_Size_. Such an outcome could potentially happen for non-compressible sources. -In such a case, such data block must be passed using uncompressed format. +In such a case, such data block **must** be passed using uncompressed format. A value of `0x00000000` is invalid, and signifies an _EndMark_ instead. Note that this is different from a value of `0x80000000` (highest bit set), @@ -397,6 +399,10 @@ and trigger an error if it does not fit within acceptable range. Version changes --------------- +1.6.4 : minor clarifications for Dictionaries + +1.6.3 : minor : clarify Data Block + 1.6.2 : clarifies specification of _EndMark_ 1.6.1 : introduced terms "LZ4 Frame Header" and "LZ4 Frame Footer" @@ -427,6 +433,6 @@ Version changes 0.6 : settled : stream size uses 8 bytes, endian convention is little endian -0.5: added copyright notice +0.5 : added copyright notice 0.4 : changed format to Google Doc compatible OpenDocument diff --git a/doc/lz4_manual.html b/doc/lz4_manual.html index 6fafb2142114367635bd26dfe263e0061c8821b5..28d0930157d1373f9fe94ae6fc45ffd24ad02a5c 100644 --- a/doc/lz4_manual.html +++ b/doc/lz4_manual.html @@ -1,16 +1,16 @@ -1.9.4 Manual +1.10.0 Manual -

1.9.4 Manual

+

1.10.0 Manual


Contents

  1. Introduction
  2. Version
  3. -
  4. Tuning parameter
  5. +
  6. Tuning memory usage
  7. Simple Functions
  8. Advanced Functions
  9. Streaming Compression Functions
  10. @@ -83,15 +83,16 @@
    const char* LZ4_versionString (void);   /**< library version string; useful to check dll version; requires v1.7.5+ */
     

    -

    Tuning parameter

    
    +

    Tuning memory usage

    
     
     
    #ifndef LZ4_MEMORY_USAGE
     # define LZ4_MEMORY_USAGE LZ4_MEMORY_USAGE_DEFAULT
     #endif
    -

    Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; ) - Increasing memory usage improves compression ratio, at the cost of speed. +

    Can be selected at compile time, by setting LZ4_MEMORY_USAGE. + Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB) + Increasing memory usage improves compression ratio, generally at the cost of speed. Reduced memory usage may improve speed at the cost of ratio, thanks to better cache locality. - Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache + Default value is 14, for 16KB, which nicely fits into most L1 caches.


    @@ -114,8 +115,9 @@


    int LZ4_decompress_safe (const char* src, char* dst, int compressedSize, int dstCapacity);
    -

    compressedSize : is the exact complete size of the compressed block. - dstCapacity : is the size of destination buffer (which must be already allocated), presumed an upper bound of decompressed size. +

    @compressedSize : is the exact complete size of the compressed block. + @dstCapacity : is the size of destination buffer (which must be already allocated), + presumed an upper bound of decompressed size. @return : the number of bytes decompressed into destination buffer (necessarily <= dstCapacity) If destination buffer is not large enough, decoding will stop and output an error code (negative value). If the source stream is detected malformed, the function will stop decoding and return a negative result. @@ -159,19 +161,20 @@ int LZ4_compress_fast_extState (void* state, const char* src, char* dst, int src


    -
    int LZ4_compress_destSize (const char* src, char* dst, int* srcSizePtr, int targetDstSize);
    +
    int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize);
     

    Reverse the logic : compresses as much data as possible from 'src' buffer - into already allocated buffer 'dst', of size >= 'targetDestSize'. + into already allocated buffer 'dst', of size >= 'dstCapacity'. This function either compresses the entire 'src' content into 'dst' if it's large enough, or fill 'dst' buffer completely with as much data as possible from 'src'. note: acceleration parameter is fixed to "default". - *srcSizePtr : will be modified to indicate how many bytes where read from 'src' to fill 'dst'. + *srcSizePtr : in+out parameter. Initially contains size of input. + Will be modified to indicate how many bytes where read from 'src' to fill 'dst'. New value is necessarily <= input value. - @return : Nb bytes written into 'dst' (necessarily <= targetDestSize) + @return : Nb bytes written into 'dst' (necessarily <= dstCapacity) or 0 if compression fails. - Note : from v1.8.2 to v1.9.1, this function had a bug (fixed un v1.9.2+): + Note : from v1.8.2 to v1.9.1, this function had a bug (fixed in v1.9.2+): the produced compressed content could, in specific circumstances, require to be decompressed into a destination buffer larger by at least 1 byte than the content to decompress. @@ -222,6 +225,24 @@ int LZ4_compress_fast_extState (void* state, const char* src, char* dst, int src

    Streaming Compression Functions

    
     
    +
    #if !defined(RC_INVOKED) /* https://docs.microsoft.com/en-us/windows/win32/menurc/predefined-macros */
    +#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
    +LZ4_stream_t* LZ4_createStream(void);
    +int           LZ4_freeStream (LZ4_stream_t* streamPtr);
    +#endif /* !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) */
    +#endif
    +

    + - RC_INVOKED is predefined symbol of rc.exe (the resource compiler which is part of MSVC/Visual Studio). + https://docs.microsoft.com/en-us/windows/win32/menurc/predefined-macros + + - Since rc.exe is a legacy compiler, it truncates long symbol (> 30 chars) + and reports warning "RC4011: identifier truncated". + + - To eliminate the warning, we surround long preprocessor symbol with + "#if !defined(RC_INVOKED) ... #endif" block that means + "skip this block when rc.exe is trying to read it". +


    +
    void LZ4_resetStream_fast (LZ4_stream_t* streamPtr);
     

    Use this to prepare an LZ4_stream_t for a new chain of dependent blocks (e.g., LZ4_compress_fast_continue()). @@ -252,10 +273,55 @@ int LZ4_compress_fast_extState (void* state, const char* src, char* dst, int src LZ4_loadDict() triggers a reset, so any previous data will be forgotten. The same dictionary will have to be loaded on decompression side for successful decoding. Dictionary are useful for better compression of small data (KB range). - While LZ4 accept any input as dictionary, - results are generally better when using Zstandard's Dictionary Builder. + While LZ4 itself accepts any input as dictionary, dictionary efficiency is also a topic. + When in doubt, employ the Zstandard's Dictionary Builder. Loading a size of 0 is allowed, and is the same as reset. - @return : loaded dictionary size, in bytes (necessarily <= 64 KB) + @return : loaded dictionary size, in bytes (note: only the last 64 KB are loaded) + +


    + +
    int LZ4_loadDictSlow(LZ4_stream_t* streamPtr, const char* dictionary, int dictSize);
    +

    Same as LZ4_loadDict(), + but uses a bit more cpu to reference the dictionary content more thoroughly. + This is expected to slightly improve compression ratio. + The extra-cpu cost is likely worth it if the dictionary is re-used across multiple sessions. + @return : loaded dictionary size, in bytes (note: only the last 64 KB are loaded) + +


    + +
    void
    +LZ4_attach_dictionary(LZ4_stream_t* workingStream,
    +                const LZ4_stream_t* dictionaryStream);
    +

    + This allows efficient re-use of a static dictionary multiple times. + + Rather than re-loading the dictionary buffer into a working context before + each compression, or copying a pre-loaded dictionary's LZ4_stream_t into a + working LZ4_stream_t, this function introduces a no-copy setup mechanism, + in which the working stream references @dictionaryStream in-place. + + Several assumptions are made about the state of @dictionaryStream. + Currently, only states which have been prepared by LZ4_loadDict() or + LZ4_loadDictSlow() should be expected to work. + + Alternatively, the provided @dictionaryStream may be NULL, + in which case any existing dictionary stream is unset. + + If a dictionary is provided, it replaces any pre-existing stream history. + The dictionary contents are the only history that can be referenced and + logically immediately precede the data compressed in the first subsequent + compression call. + + The dictionary will only remain attached to the working stream through the + first compression call, at the end of which it is cleared. + @dictionaryStream stream (and source buffer) must remain in-place / accessible / unchanged + through the completion of the compression session. + + Note: there is no equivalent LZ4_attach_*() method on the decompression side + because there is no initialization cost, hence no need to share the cost across multiple sessions. + To decompress LZ4 blocks using dictionary, attached or not, + just employ the regular LZ4_setStreamDecode() for streaming, + or the stateless LZ4_decompress_safe_usingDict() for one-shot decompression.


    @@ -296,10 +362,12 @@ int LZ4_compress_fast_extState (void* state, const char* src, char* dst, int src

    Streaming Decompression Functions

      Bufferless synchronous API
     
    -
    #if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
    +
    #if !defined(RC_INVOKED) /* https://docs.microsoft.com/en-us/windows/win32/menurc/predefined-macros */
    +#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
     LZ4_streamDecode_t* LZ4_createStreamDecode(void);
     int                 LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream);
     #endif /* !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION) */
    +#endif
     

    creation / destruction of streaming decompression tracking context. A tracking context can be re-used multiple times. @@ -332,10 +400,23 @@ int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream); LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, int srcSize, int dstCapacity); -

    These decoding functions allow decompression of consecutive blocks in "streaming" mode. - A block is an unsplittable entity, it must be presented entirely to a decompression function. - Decompression functions only accepts one block at a time. - The last 64KB of previously decoded data *must* remain available and unmodified at the memory position where they were decoded. +

    This decoding function allows decompression of consecutive blocks in "streaming" mode. + The difference with the usual independent blocks is that + new blocks are allowed to find references into former blocks. + A block is an unsplittable entity, and must be presented entirely to the decompression function. + LZ4_decompress_safe_continue() only accepts one block at a time. + It's modeled after `LZ4_decompress_safe()` and behaves similarly. + + @LZ4_streamDecode : decompression state, tracking the position in memory of past data + @compressedSize : exact complete size of one compressed block. + @dstCapacity : size of destination buffer (which must be already allocated), + must be an upper bound of decompressed size. + @return : number of bytes decompressed into destination buffer (necessarily <= dstCapacity) + If destination buffer is not large enough, decoding will stop and output an error code (negative value). + If the source stream is detected malformed, the function will stop decoding and return a negative result. + + The last 64KB of previously decoded data *must* remain available and unmodified + at the memory position where they were previously decoded. If less than 64KB of data has been decoded, all the data must be present. Special : if decompression side sets a ring buffer, it must respect one of the following conditions : @@ -361,15 +442,27 @@ LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, LZ4_decompress_safe_usingDict(const char* src, char* dst, int srcSize, int dstCapacity, const char* dictStart, int dictSize); -

    These decoding functions work the same as - a combination of LZ4_setStreamDecode() followed by LZ4_decompress_*_continue() - They are stand-alone, and don't need an LZ4_streamDecode_t structure. +

    Works the same as + a combination of LZ4_setStreamDecode() followed by LZ4_decompress_safe_continue() + However, it's stateless: it doesn't need any LZ4_streamDecode_t state. Dictionary is presumed stable : it must remain accessible and unmodified during decompression. Performance tip : Decompression speed can be substantially increased when dst == dictStart + dictSize.


    +
    int
    +LZ4_decompress_safe_partial_usingDict(const char* src, char* dst,
    +                                      int compressedSize,
    +                                      int targetOutputSize, int maxOutputSize,
    +                                      const char* dictStart, int dictSize);
    +

    Behaves the same as LZ4_decompress_safe_partial() + with the added ability to specify a memory segment for past data. + Performance tip : Decompression speed can be substantially increased + when dst == dictStart + dictSize. + +


    +

    Experimental section

      Symbols declared in this section must be considered unstable. Their
      signatures or semantics may change, or they may be removed altogether in the
    @@ -400,33 +493,9 @@ LZ4_decompress_safe_usingDict(const char* src, char* dst,
      
     


    -
    LZ4LIB_STATIC_API void
    -LZ4_attach_dictionary(LZ4_stream_t* workingStream,
    -                const LZ4_stream_t* dictionaryStream);
    -

    This is an experimental API that allows - efficient use of a static dictionary many times. - - Rather than re-loading the dictionary buffer into a working context before - each compression, or copying a pre-loaded dictionary's LZ4_stream_t into a - working LZ4_stream_t, this function introduces a no-copy setup mechanism, - in which the working stream references the dictionary stream in-place. - - Several assumptions are made about the state of the dictionary stream. - Currently, only streams which have been prepared by LZ4_loadDict() should - be expected to work. - - Alternatively, the provided dictionaryStream may be NULL, - in which case any existing dictionary stream is unset. - - If a dictionary is provided, it replaces any pre-existing stream history. - The dictionary contents are the only history that can be referenced and - logically immediately precede the data compressed in the first subsequent - compression call. - - The dictionary will only remain attached to the working stream through the - first compression call, at the end of which it is cleared. The dictionary - stream (and source buffer) must remain in-place / accessible / unchanged - through the completion of the first compression call on the stream. +

    int LZ4_compress_destSize_extState(void* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize, int acceleration);
    +

    Same as LZ4_compress_destSize(), but using an externally allocated state. + Also: exposes @acceleration


    @@ -496,7 +565,7 @@ LZ4_attach_dictionary(LZ4_stream_t* workingStream, If you need static allocation, declare or allocate an LZ4_stream_t object.


    -
    LZ4_stream_t* LZ4_initStream (void* buffer, size_t size);
    +
    LZ4_stream_t* LZ4_initStream (void* stateBuffer, size_t size);
     

    An LZ4_stream_t structure must be initialized at least once. This is automatically done when invoking LZ4_createStream(), but it's not when the structure is simply declared on stack (for example). @@ -568,11 +637,12 @@ LZ4_DEPRECATED("use LZ4_decompress_safe() instead") LZ4LIB_API int LZ4_uncompres LZ4_DEPRECATED("use LZ4_decompress_fast_usingDict() instead") LZ4LIB_API int LZ4_decompress_fast_withPrefix64k (const char* src, char* dst, int originalSize);


    -
    LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe() instead")
    +
    LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_partial() instead")
     int LZ4_decompress_fast (const char* src, char* dst, int originalSize);
    -LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_continue() instead")
    +LZ4_DEPRECATED("This function is deprecated and unsafe. Consider migrating towards LZ4_decompress_safe_continue() instead. "
    +               "Note that the contract will change (requires block's compressed size, instead of decompressed size)")
     int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, int originalSize);
    -LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_usingDict() instead")
    +LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_partial_usingDict() instead")
     int LZ4_decompress_fast_usingDict (const char* src, char* dst, int originalSize, const char* dictStart, int dictSize);
     

    These functions used to be faster than LZ4_decompress_safe(), but this is no longer the case. They are now slower. diff --git a/doc/lz4frame_manual.html b/doc/lz4frame_manual.html index cfb437e47ee6e4a3e9197a99b0d7d54dafab4ab5..b3a021cd9703f33f4f3086c4c2c019a0b95d16ac 100644 --- a/doc/lz4frame_manual.html +++ b/doc/lz4frame_manual.html @@ -1,10 +1,10 @@ -1.9.4 Manual +1.10.0 Manual -

    1.9.4 Manual

    +

    1.10.0 Manual


    Contents

      @@ -18,7 +18,10 @@
    1. Compression
    2. Decompression functions
    3. Streaming decompression functions
    4. -
    5. Bulk processing dictionary API
    6. +
    7. Dictionary compression API
    8. +
    9. Bulk processing dictionary compression
    10. +
    11. Advanced compression operations
    12. +
    13. Custom memory allocation

    Introduction

    @@ -76,13 +79,13 @@
     } LZ4F_frameType_t;
     

    typedef struct {
    -  LZ4F_blockSizeID_t     blockSizeID;         /* max64KB, max256KB, max1MB, max4MB; 0 == default */
    -  LZ4F_blockMode_t       blockMode;           /* LZ4F_blockLinked, LZ4F_blockIndependent; 0 == default */
    -  LZ4F_contentChecksum_t contentChecksumFlag; /* 1: frame terminated with 32-bit checksum of decompressed data; 0: disabled (default) */
    +  LZ4F_blockSizeID_t     blockSizeID;         /* max64KB, max256KB, max1MB, max4MB; 0 == default (LZ4F_max64KB) */
    +  LZ4F_blockMode_t       blockMode;           /* LZ4F_blockLinked, LZ4F_blockIndependent; 0 == default (LZ4F_blockLinked) */
    +  LZ4F_contentChecksum_t contentChecksumFlag; /* 1: add a 32-bit checksum of frame's decompressed data; 0 == default (disabled) */
       LZ4F_frameType_t       frameType;           /* read-only field : LZ4F_frame or LZ4F_skippableFrame */
       unsigned long long     contentSize;         /* Size of uncompressed content ; 0 == unknown */
       unsigned               dictID;              /* Dictionary ID, sent by compressor to help decoder select correct dictionary; 0 == no dictID provided */
    -  LZ4F_blockChecksum_t   blockChecksumFlag;   /* 1: each block followed by a checksum of block's compressed data; 0: disabled (default) */
    +  LZ4F_blockChecksum_t   blockChecksumFlag;   /* 1: each block followed by a checksum of block's compressed data; 0 == default (disabled) */
     } LZ4F_frameInfo_t;
     

    makes it possible to set or read frame parameters. Structure must be first init to 0, using memset() or LZ4F_INIT_FRAMEINFO, @@ -105,6 +108,27 @@

    Simple compression function

    
     
    +
    size_t LZ4F_compressFrame(void* dstBuffer, size_t dstCapacity,
    +                                const void* srcBuffer, size_t srcSize,
    +                                const LZ4F_preferences_t* preferencesPtr);
    +

    Compress srcBuffer content into an LZ4-compressed frame. + It's a one shot operation, all input content is consumed, and all output is generated. + + Note : it's a stateless operation (no LZ4F_cctx state needed). + In order to reduce load on the allocator, LZ4F_compressFrame(), by default, + uses the stack to allocate space for the compression state and some table. + If this usage of the stack is too much for your application, + consider compiling `lz4frame.c` with compile-time macro LZ4F_HEAPMODE set to 1 instead. + All state allocations will use the Heap. + It also means each invocation of LZ4F_compressFrame() will trigger several internal alloc/free invocations. + + @dstCapacity MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr). + @preferencesPtr is optional : one can provide NULL, in which case all preferences are set to default. + @return : number of bytes written into dstBuffer. + or an error code if it fails (can be tested using LZ4F_isError()) + +


    +
    size_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr);
     

    Returns the maximum possible compressed size with LZ4F_compressFrame() given srcSize and preferences. `preferencesPtr` is optional. It can be replaced by NULL, in which case, the function will assume default preferences. @@ -113,14 +137,8 @@


    -
    size_t LZ4F_compressFrame(void* dstBuffer, size_t dstCapacity,
    -                                const void* srcBuffer, size_t srcSize,
    -                                const LZ4F_preferences_t* preferencesPtr);
    -

    Compress an entire srcBuffer into a valid LZ4 frame. - dstCapacity MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr). - The LZ4F_preferences_t structure is optional : you can provide NULL as argument. All preferences will be set to default. - @return : number of bytes written into dstBuffer. - or an error code if it fails (can be tested using LZ4F_isError()) +

    int LZ4F_compressionLevel_max(void);   /* v1.8.0+ */
    +

    @return maximum allowed compression level (currently: 12)


    @@ -157,7 +175,7 @@ LZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_cctx* cctx); const LZ4F_preferences_t* prefsPtr);

    will write the frame header into dstBuffer. dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes. - `prefsPtr` is optional : you can provide NULL as argument, all preferences will then be set to default. + `prefsPtr` is optional : NULL can be provided to set all preferences to default. @return : number of bytes written into dstBuffer for the header or an error code (which can be tested using LZ4F_isError()) @@ -227,8 +245,9 @@ LZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_cctx* cctx);

    Decompression functions

    
     
     
    typedef struct {
    -  unsigned stableDst;     /* pledges that last 64KB decompressed data will remain available unmodified between invocations.
    -                           * This optimization skips storage operations in tmp buffers. */
    +  unsigned stableDst;     /* pledges that last 64KB decompressed data is present right before @dstBuffer pointer.
    +                           * This optimization skips internal storage operations.
    +                           * Once set, this pledge must remain valid up to the end of current frame. */
       unsigned skipChecksums; /* disable checksum calculation and verification, even when one is present in frame, to save CPU time.
                                * Setting this option to 1 once disables all checksums for the rest of the frame. */
       unsigned reserved1;     /* must be set to zero for forward compatibility */
    @@ -329,6 +348,11 @@ LZ4F_decompress(LZ4F_dctx* dctx,
      `dstBuffer` can freely change between each consecutive function invocation.
      `dstBuffer` content will be overwritten.
     
    +  Note: if `LZ4F_getFrameInfo()` is called before `LZ4F_decompress()`, srcBuffer must be updated to reflect
    +  the number of bytes consumed after reading the frame header. Failure to update srcBuffer before calling
    +  `LZ4F_decompress()` will cause decompression failure or, even worse, successful but incorrect decompression.
    +  See the `LZ4F_getFrameInfo()` docs for details.
    +
      @return : an hint of how many `srcSize` bytes LZ4F_decompress() expects for next call.
       Schematically, it's the size of the current (or remaining) compressed block + header of next block.
       Respecting the hint provides some small speed benefit, because it skips intermediate buffers.
    @@ -353,84 +377,113 @@ LZ4F_decompress(LZ4F_dctx* dctx,
       and start a new one using same context resources. 
     


    -
    typedef enum { LZ4F_LIST_ERRORS(LZ4F_GENERATE_ENUM)
    -              _LZ4F_dummy_error_enum_for_c89_never_used } LZ4F_errorCodes;
    -

    -
    LZ4FLIB_STATIC_API size_t LZ4F_getBlockSize(LZ4F_blockSizeID_t blockSizeID);
    -

    Return, in scalar format (size_t), - the maximum block size associated with blockSizeID. -


    +

    Dictionary compression API

    
     
    -
    LZ4FLIB_STATIC_API size_t
    -LZ4F_uncompressedUpdate(LZ4F_cctx* cctx,
    -                        void* dstBuffer, size_t dstCapacity,
    -                  const void* srcBuffer, size_t srcSize,
    -                  const LZ4F_compressOptions_t* cOptPtr);
    -

    LZ4F_uncompressedUpdate() can be called repetitively to add as much data uncompressed data as necessary. - Important rule: dstCapacity MUST be large enough to store the entire source buffer as - no compression is done for this operation - If this condition is not respected, LZ4F_uncompressedUpdate() will fail (result is an errorCode). - After an error, the state is left in a UB state, and must be re-initialized or freed. - If previously a compressed block was written, buffered data is flushed - before appending uncompressed data is continued. - This is only supported when LZ4F_blockIndependent is used - `cOptPtr` is optional : NULL can be provided, in which case all options are set to default. - @return : number of bytes written into `dstBuffer` (it can be zero, meaning input data was just buffered). - or an error code if it fails (which can be tested using LZ4F_isError()) +

    size_t
    +LZ4F_compressBegin_usingDict(LZ4F_cctx* cctx,
    +                            void* dstBuffer, size_t dstCapacity,
    +                      const void* dictBuffer, size_t dictSize,
    +                      const LZ4F_preferences_t* prefsPtr);
    +

    Inits dictionary compression streaming, and writes the frame header into dstBuffer. + @dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes. + @prefsPtr is optional : one may provide NULL as argument, + however, it's the only way to provide dictID in the frame header. + @dictBuffer must outlive the compression session. + @return : number of bytes written into dstBuffer for the header, + or an error code (which can be tested using LZ4F_isError()) + NOTE: The LZ4Frame spec allows each independent block to be compressed with the dictionary, + but this entry supports a more limited scenario, where only the first block uses the dictionary. + This is still useful for small data, which only need one block anyway. + For larger inputs, one may be more interested in LZ4F_compressFrame_usingCDict() below.


    -

    Bulk processing dictionary API

    
    +
    size_t
    +LZ4F_decompress_usingDict(LZ4F_dctx* dctxPtr,
    +                          void* dstBuffer, size_t* dstSizePtr,
    +                    const void* srcBuffer, size_t* srcSizePtr,
    +                    const void* dict, size_t dictSize,
    +                    const LZ4F_decompressOptions_t* decompressOptionsPtr);
    +

    Same as LZ4F_decompress(), using a predefined dictionary. + Dictionary is used "in place", without any preprocessing. + It must remain accessible throughout the entire frame decoding. +


    + +

    Bulk processing dictionary compression

    
     
    -
    LZ4FLIB_STATIC_API LZ4F_CDict* LZ4F_createCDict(const void* dictBuffer, size_t dictSize);
    -LZ4FLIB_STATIC_API void        LZ4F_freeCDict(LZ4F_CDict* CDict);
    -

    When compressing multiple messages / blocks using the same dictionary, it's recommended to load it just once. +

    LZ4F_CDict* LZ4F_createCDict(const void* dictBuffer, size_t dictSize);
    +void        LZ4F_freeCDict(LZ4F_CDict* CDict);
    +

    When compressing multiple messages / blocks using the same dictionary, it's recommended to initialize it just once. LZ4_createCDict() will create a digested dictionary, ready to start future compression operations without startup delay. LZ4_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only. - `dictBuffer` can be released after LZ4_CDict creation, since its content is copied within CDict + @dictBuffer can be released after LZ4_CDict creation, since its content is copied within CDict.


    -
    LZ4FLIB_STATIC_API size_t
    +
    size_t
     LZ4F_compressFrame_usingCDict(LZ4F_cctx* cctx,
                                   void* dst, size_t dstCapacity,
                             const void* src, size_t srcSize,
                             const LZ4F_CDict* cdict,
                             const LZ4F_preferences_t* preferencesPtr);
     

    Compress an entire srcBuffer into a valid LZ4 frame using a digested Dictionary. - cctx must point to a context created by LZ4F_createCompressionContext(). - If cdict==NULL, compress without a dictionary. - dstBuffer MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr). + @cctx must point to a context created by LZ4F_createCompressionContext(). + If @cdict==NULL, compress without a dictionary. + @dstBuffer MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr). If this condition is not respected, function will fail (@return an errorCode). - The LZ4F_preferences_t structure is optional : you may provide NULL as argument, - but it's not recommended, as it's the only way to provide dictID in the frame header. + The LZ4F_preferences_t structure is optional : one may provide NULL as argument, + but it's not recommended, as it's the only way to provide @dictID in the frame header. @return : number of bytes written into dstBuffer. - or an error code if it fails (can be tested using LZ4F_isError()) + or an error code if it fails (can be tested using LZ4F_isError()) + Note: for larger inputs generating multiple independent blocks, + this entry point uses the dictionary for each block.


    -
    LZ4FLIB_STATIC_API size_t
    +
    size_t
     LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctx,
                                   void* dstBuffer, size_t dstCapacity,
                             const LZ4F_CDict* cdict,
                             const LZ4F_preferences_t* prefsPtr);
     

    Inits streaming dictionary compression, and writes the frame header into dstBuffer. - dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes. - `prefsPtr` is optional : you may provide NULL as argument, - however, it's the only way to provide dictID in the frame header. + @dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes. + @prefsPtr is optional : one may provide NULL as argument, + note however that it's the only way to insert a @dictID in the frame header. + @cdict must outlive the compression session. @return : number of bytes written into dstBuffer for the header, - or an error code (which can be tested using LZ4F_isError()) + or an error code, which can be tested using LZ4F_isError(). +


    + +
    typedef enum { LZ4F_LIST_ERRORS(LZ4F_GENERATE_ENUM)
    +              _LZ4F_dummy_error_enum_for_c89_never_used } LZ4F_errorCodes;
    +

    +

    Advanced compression operations

    
    +
    +
    LZ4FLIB_STATIC_API size_t LZ4F_getBlockSize(LZ4F_blockSizeID_t blockSizeID);
    +

    @return, in scalar format (size_t), + the maximum block size associated with @blockSizeID, + or an error code (can be tested using LZ4F_isError()) if @blockSizeID is invalid.


    LZ4FLIB_STATIC_API size_t
    -LZ4F_decompress_usingDict(LZ4F_dctx* dctxPtr,
    -                          void* dstBuffer, size_t* dstSizePtr,
    -                    const void* srcBuffer, size_t* srcSizePtr,
    -                    const void* dict, size_t dictSize,
    -                    const LZ4F_decompressOptions_t* decompressOptionsPtr);
    -

    Same as LZ4F_decompress(), using a predefined dictionary. - Dictionary is used "in place", without any preprocessing. - It must remain accessible throughout the entire frame decoding. +LZ4F_uncompressedUpdate(LZ4F_cctx* cctx, + void* dstBuffer, size_t dstCapacity, + const void* srcBuffer, size_t srcSize, + const LZ4F_compressOptions_t* cOptPtr); +

    LZ4F_uncompressedUpdate() can be called repetitively to add data stored as uncompressed blocks. + Important rule: dstCapacity MUST be large enough to store the entire source buffer as + no compression is done for this operation + If this condition is not respected, LZ4F_uncompressedUpdate() will fail (result is an errorCode). + After an error, the state is left in a UB state, and must be re-initialized or freed. + If previously a compressed block was written, buffered data is flushed first, + before appending uncompressed data is continued. + This operation is only supported when LZ4F_blockIndependent is used. + `cOptPtr` is optional : NULL can be provided, in which case all options are set to default. + @return : number of bytes written into `dstBuffer` (it can be zero, meaning input data was just buffered). + or an error code if it fails (which can be tested using LZ4F_isError()) +


    +

    Custom memory allocation

    
    +
     
    typedef void* (*LZ4F_AllocFunction) (void* opaqueState, size_t size);
     typedef void* (*LZ4F_CallocFunction) (void* opaqueState, size_t size);
     typedef void  (*LZ4F_FreeFunction) (void* opaqueState, void* address);
    diff --git a/examples/.gitignore b/examples/.gitignore
    index ddc8e216fa64efbaf23d1dae64b36882fba545b0..521d1447df7efdee88da5ccb8249fdbefe2f678c 100644
    --- a/examples/.gitignore
    +++ b/examples/.gitignore
    @@ -1,11 +1,12 @@
     /Makefile.lz4*
    -/printVersion
    -/doubleBuffer
    -/dictionaryRandomAccess
    -/ringBuffer
    -/ringBufferHC
    -/lineCompress
    +/print_version
    +/simple_buffer
     /frameCompress
     /fileCompress
    -/simpleBuffer
    +/blockStreaming_doubleBuffer
    +/blockStreaming_ringBuffer
    +/streamingHC_ringBuffer
    +/blockStreaming_lineByLine
    +/dictionaryRandomAccess
    +/bench_functions
     /*.exe
    diff --git a/examples/COPYING b/examples/COPYING
    index d159169d1050894d3ea3b98e1c965c4058208fe1..c728282bf0c88d16f64db747332efb440f652c05 100644
    --- a/examples/COPYING
    +++ b/examples/COPYING
    @@ -1,339 +1,83 @@
    -                    GNU GENERAL PUBLIC LICENSE
    -                       Version 2, June 1991
    -
    - Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
    - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
    - Everyone is permitted to copy and distribute verbatim copies
    - of this license document, but changing it is not allowed.
    -
    -                            Preamble
    -
    -  The licenses for most software are designed to take away your
    -freedom to share and change it.  By contrast, the GNU General Public
    -License is intended to guarantee your freedom to share and change free
    -software--to make sure the software is free for all its users.  This
    -General Public License applies to most of the Free Software
    -Foundation's software and to any other program whose authors commit to
    -using it.  (Some other Free Software Foundation software is covered by
    -the GNU Lesser General Public License instead.)  You can apply it to
    -your programs, too.
    -
    -  When we speak of free software, we are referring to freedom, not
    -price.  Our General Public Licenses are designed to make sure that you
    -have the freedom to distribute copies of free software (and charge for
    -this service if you wish), that you receive source code or can get it
    -if you want it, that you can change the software or use pieces of it
    -in new free programs; and that you know you can do these things.
    -
    -  To protect your rights, we need to make restrictions that forbid
    -anyone to deny you these rights or to ask you to surrender the rights.
    -These restrictions translate to certain responsibilities for you if you
    -distribute copies of the software, or if you modify it.
    -
    -  For example, if you distribute copies of such a program, whether
    -gratis or for a fee, you must give the recipients all the rights that
    -you have.  You must make sure that they, too, receive or can get the
    -source code.  And you must show them these terms so they know their
    -rights.
    -
    -  We protect your rights with two steps: (1) copyright the software, and
    -(2) offer you this license which gives you legal permission to copy,
    -distribute and/or modify the software.
    -
    -  Also, for each author's protection and ours, we want to make certain
    -that everyone understands that there is no warranty for this free
    -software.  If the software is modified by someone else and passed on, we
    -want its recipients to know that what they have is not the original, so
    -that any problems introduced by others will not reflect on the original
    -authors' reputations.
    -
    -  Finally, any free program is threatened constantly by software
    -patents.  We wish to avoid the danger that redistributors of a free
    -program will individually obtain patent licenses, in effect making the
    -program proprietary.  To prevent this, we have made it clear that any
    -patent must be licensed for everyone's free use or not licensed at all.
    -
    -  The precise terms and conditions for copying, distribution and
    -modification follow.
    -
    -                    GNU GENERAL PUBLIC LICENSE
    -   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
    -
    -  0. This License applies to any program or other work which contains
    -a notice placed by the copyright holder saying it may be distributed
    -under the terms of this General Public License.  The "Program", below,
    -refers to any such program or work, and a "work based on the Program"
    -means either the Program or any derivative work under copyright law:
    -that is to say, a work containing the Program or a portion of it,
    -either verbatim or with modifications and/or translated into another
    -language.  (Hereinafter, translation is included without limitation in
    -the term "modification".)  Each licensee is addressed as "you".
    -
    -Activities other than copying, distribution and modification are not
    -covered by this License; they are outside its scope.  The act of
    -running the Program is not restricted, and the output from the Program
    -is covered only if its contents constitute a work based on the
    -Program (independent of having been made by running the Program).
    -Whether that is true depends on what the Program does.
    -
    -  1. You may copy and distribute verbatim copies of the Program's
    -source code as you receive it, in any medium, provided that you
    -conspicuously and appropriately publish on each copy an appropriate
    -copyright notice and disclaimer of warranty; keep intact all the
    -notices that refer to this License and to the absence of any warranty;
    -and give any other recipients of the Program a copy of this License
    -along with the Program.
    -
    -You may charge a fee for the physical act of transferring a copy, and
    -you may at your option offer warranty protection in exchange for a fee.
    -
    -  2. You may modify your copy or copies of the Program or any portion
    -of it, thus forming a work based on the Program, and copy and
    -distribute such modifications or work under the terms of Section 1
    -above, provided that you also meet all of these conditions:
    -
    -    a) You must cause the modified files to carry prominent notices
    -    stating that you changed the files and the date of any change.
    -
    -    b) You must cause any work that you distribute or publish, that in
    -    whole or in part contains or is derived from the Program or any
    -    part thereof, to be licensed as a whole at no charge to all third
    -    parties under the terms of this License.
    -
    -    c) If the modified program normally reads commands interactively
    -    when run, you must cause it, when started running for such
    -    interactive use in the most ordinary way, to print or display an
    -    announcement including an appropriate copyright notice and a
    -    notice that there is no warranty (or else, saying that you provide
    -    a warranty) and that users may redistribute the program under
    -    these conditions, and telling the user how to view a copy of this
    -    License.  (Exception: if the Program itself is interactive but
    -    does not normally print such an announcement, your work based on
    -    the Program is not required to print an announcement.)
    -
    -These requirements apply to the modified work as a whole.  If
    -identifiable sections of that work are not derived from the Program,
    -and can be reasonably considered independent and separate works in
    -themselves, then this License, and its terms, do not apply to those
    -sections when you distribute them as separate works.  But when you
    -distribute the same sections as part of a whole which is a work based
    -on the Program, the distribution of the whole must be on the terms of
    -this License, whose permissions for other licensees extend to the
    -entire whole, and thus to each and every part regardless of who wrote it.
    -
    -Thus, it is not the intent of this section to claim rights or contest
    -your rights to work written entirely by you; rather, the intent is to
    -exercise the right to control the distribution of derivative or
    -collective works based on the Program.
    -
    -In addition, mere aggregation of another work not based on the Program
    -with the Program (or with a work based on the Program) on a volume of
    -a storage or distribution medium does not bring the other work under
    -the scope of this License.
    -
    -  3. You may copy and distribute the Program (or a work based on it,
    -under Section 2) in object code or executable form under the terms of
    -Sections 1 and 2 above provided that you also do one of the following:
    -
    -    a) Accompany it with the complete corresponding machine-readable
    -    source code, which must be distributed under the terms of Sections
    -    1 and 2 above on a medium customarily used for software interchange; or,
    -
    -    b) Accompany it with a written offer, valid for at least three
    -    years, to give any third party, for a charge no more than your
    -    cost of physically performing source distribution, a complete
    -    machine-readable copy of the corresponding source code, to be
    -    distributed under the terms of Sections 1 and 2 above on a medium
    -    customarily used for software interchange; or,
    -
    -    c) Accompany it with the information you received as to the offer
    -    to distribute corresponding source code.  (This alternative is
    -    allowed only for noncommercial distribution and only if you
    -    received the program in object code or executable form with such
    -    an offer, in accord with Subsection b above.)
    -
    -The source code for a work means the preferred form of the work for
    -making modifications to it.  For an executable work, complete source
    -code means all the source code for all modules it contains, plus any
    -associated interface definition files, plus the scripts used to
    -control compilation and installation of the executable.  However, as a
    -special exception, the source code distributed need not include
    -anything that is normally distributed (in either source or binary
    -form) with the major components (compiler, kernel, and so on) of the
    -operating system on which the executable runs, unless that component
    -itself accompanies the executable.
    -
    -If distribution of executable or object code is made by offering
    -access to copy from a designated place, then offering equivalent
    -access to copy the source code from the same place counts as
    -distribution of the source code, even though third parties are not
    -compelled to copy the source along with the object code.
    -
    -  4. You may not copy, modify, sublicense, or distribute the Program
    -except as expressly provided under this License.  Any attempt
    -otherwise to copy, modify, sublicense or distribute the Program is
    -void, and will automatically terminate your rights under this License.
    -However, parties who have received copies, or rights, from you under
    -this License will not have their licenses terminated so long as such
    -parties remain in full compliance.
    -
    -  5. You are not required to accept this License, since you have not
    -signed it.  However, nothing else grants you permission to modify or
    -distribute the Program or its derivative works.  These actions are
    -prohibited by law if you do not accept this License.  Therefore, by
    -modifying or distributing the Program (or any work based on the
    -Program), you indicate your acceptance of this License to do so, and
    -all its terms and conditions for copying, distributing or modifying
    -the Program or works based on it.
    -
    -  6. Each time you redistribute the Program (or any work based on the
    -Program), the recipient automatically receives a license from the
    -original licensor to copy, distribute or modify the Program subject to
    -these terms and conditions.  You may not impose any further
    -restrictions on the recipients' exercise of the rights granted herein.
    -You are not responsible for enforcing compliance by third parties to
    -this License.
    -
    -  7. If, as a consequence of a court judgment or allegation of patent
    -infringement or for any other reason (not limited to patent issues),
    -conditions are imposed on you (whether by court order, agreement or
    -otherwise) that contradict the conditions of this License, they do not
    -excuse you from the conditions of this License.  If you cannot
    -distribute so as to satisfy simultaneously your obligations under this
    -License and any other pertinent obligations, then as a consequence you
    -may not distribute the Program at all.  For example, if a patent
    -license would not permit royalty-free redistribution of the Program by
    -all those who receive copies directly or indirectly through you, then
    -the only way you could satisfy both it and this License would be to
    -refrain entirely from distribution of the Program.
    -
    -If any portion of this section is held invalid or unenforceable under
    -any particular circumstance, the balance of the section is intended to
    -apply and the section as a whole is intended to apply in other
    -circumstances.
    -
    -It is not the purpose of this section to induce you to infringe any
    -patents or other property right claims or to contest validity of any
    -such claims; this section has the sole purpose of protecting the
    -integrity of the free software distribution system, which is
    -implemented by public license practices.  Many people have made
    -generous contributions to the wide range of software distributed
    -through that system in reliance on consistent application of that
    -system; it is up to the author/donor to decide if he or she is willing
    -to distribute software through any other system and a licensee cannot
    -impose that choice.
    -
    -This section is intended to make thoroughly clear what is believed to
    -be a consequence of the rest of this License.
    -
    -  8. If the distribution and/or use of the Program is restricted in
    -certain countries either by patents or by copyrighted interfaces, the
    -original copyright holder who places the Program under this License
    -may add an explicit geographical distribution limitation excluding
    -those countries, so that distribution is permitted only in or among
    -countries not thus excluded.  In such case, this License incorporates
    -the limitation as if written in the body of this License.
    -
    -  9. The Free Software Foundation may publish revised and/or new versions
    -of the General Public License from time to time.  Such new versions will
    -be similar in spirit to the present version, but may differ in detail to
    -address new problems or concerns.
    -
    -Each version is given a distinguishing version number.  If the Program
    -specifies a version number of this License which applies to it and "any
    -later version", you have the option of following the terms and conditions
    -either of that version or of any later version published by the Free
    -Software Foundation.  If the Program does not specify a version number of
    -this License, you may choose any version ever published by the Free Software
    -Foundation.
    -
    -  10. If you wish to incorporate parts of the Program into other free
    -programs whose distribution conditions are different, write to the author
    -to ask for permission.  For software which is copyrighted by the Free
    -Software Foundation, write to the Free Software Foundation; we sometimes
    -make exceptions for this.  Our decision will be guided by the two goals
    -of preserving the free status of all derivatives of our free software and
    -of promoting the sharing and reuse of software generally.
    -
    -                            NO WARRANTY
    -
    -  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
    -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
    -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
    -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
    -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
    -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
    -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
    -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
    -REPAIR OR CORRECTION.
    -
    -  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
    -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
    -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
    -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
    -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
    -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
    -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
    -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
    -POSSIBILITY OF SUCH DAMAGES.
    -
    -                     END OF TERMS AND CONDITIONS
    -
    -            How to Apply These Terms to Your New Programs
    -
    -  If you develop a new program, and you want it to be of the greatest
    -possible use to the public, the best way to achieve this is to make it
    -free software which everyone can redistribute and change under these terms.
    -
    -  To do so, attach the following notices to the program.  It is safest
    -to attach them to the start of each source file to most effectively
    -convey the exclusion of warranty; and each file should have at least
    -the "copyright" line and a pointer to where the full notice is found.
    -
    -    
    -    Copyright (C)   
    -
    -    This program is free software; you can redistribute it and/or modify
    -    it under the terms of the GNU General Public License as published by
    -    the Free Software Foundation; either version 2 of the License, or
    -    (at your option) any later version.
    -
    -    This program is distributed in the hope that it will be useful,
    -    but WITHOUT ANY WARRANTY; without even the implied warranty of
    -    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    -    GNU General Public License for more details.
    -
    -    You should have received a copy of the GNU General Public License along
    -    with this program; if not, write to the Free Software Foundation, Inc.,
    -    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
    -
    -Also add information on how to contact you by electronic and paper mail.
    -
    -If the program is interactive, make it output a short notice like this
    -when it starts in an interactive mode:
    -
    -    Gnomovision version 69, Copyright (C) year name of author
    -    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    -    This is free software, and you are welcome to redistribute it
    -    under certain conditions; type `show c' for details.
    -
    -The hypothetical commands `show w' and `show c' should show the appropriate
    -parts of the General Public License.  Of course, the commands you use may
    -be called something other than `show w' and `show c'; they could even be
    -mouse-clicks or menu items--whatever suits your program.
    -
    -You should also get your employer (if you work as a programmer) or your
    -school, if any, to sign a "copyright disclaimer" for the program, if
    -necessary.  Here is a sample; alter the names:
    -
    -  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
    -  `Gnomovision' (which makes passes at compilers) written by James Hacker.
    -
    -  , 1 April 1989
    -  Ty Coon, President of Vice
    -
    -This General Public License does not permit incorporating your program into
    -proprietary programs.  If your program is a subroutine library, you may
    -consider it more useful to permit linking proprietary applications with the
    -library.  If this is what you want to do, use the GNU Lesser General
    -Public License instead of this License.
    +Full name:
    +GNU General Public License v2.0 or later
    +
    +Short identifier:
    +GPL-2.0-or-later
    +
    +Text:
    +GNU GENERAL PUBLIC LICENSE
    +Version 2, June 1991
    +
    +Copyright (C) 1989, 1991 Free Software Foundation, Inc.
    +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
    +
    +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
    +
    +Preamble
    +
    +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
    +
    +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
    +
    +To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
    +
    +For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
    +
    +We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
    +
    +Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
    +
    +Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
    +
    +The precise terms and conditions for copying, distribution and modification follow.
    +
    +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
    +
    +0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
    +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
    +
    +1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
    +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
    +
    +2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
    +a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
    +b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
    +c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
    +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
    +
    +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
    +
    +In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
    +
    +3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
    +a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
    +b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
    +c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
    +The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
    +
    +If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
    +
    +4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
    +
    +5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
    +
    +6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
    +
    +7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
    +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
    +
    +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
    +
    +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
    +
    +8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
    +
    +9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
    +Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
    +
    +10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
    +NO WARRANTY
    +
    +11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
    +
    +12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
    diff --git a/examples/Makefile b/examples/Makefile
    index 8be5c81e989b355011a2500a55dce8fd4d967c0a..91a4f4842b52fdfbba14388934d83e10cd3852e2 100644
    --- a/examples/Makefile
    +++ b/examples/Makefile
    @@ -27,71 +27,57 @@
     # kindly provided by Takayuki Matsuoka
     # ##########################################################################
     
    -CPPFLAGS += -I../lib
    -CFLAGS   ?= -O3
    -CFLAGS   += -std=gnu99 -Wall -Wextra -Wundef -Wshadow -Wcast-align -Wstrict-prototypes
    -FLAGS    := $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $(MOREFLAGS)
    +LIBDIR    := ../lib
     
    -TESTFILE  = Makefile
    -LZ4DIR   := ../lib
    -LZ4       = ../programs/lz4
    +CPPFLAGS  += -I$(LIBDIR)
    +USERCFLAGS:= $(CFLAGS)
    +WFLAGS     = -std=gnu99 -Wall -Wextra -Wundef -Wshadow -Wcast-align -Wstrict-prototypes -Wc++-compat
    +CFLAGS     = $(WFLAGS) -O2 $(USERCFLAGS)
     
    -include ../Makefile.inc
    +TESTFILE   = Makefile
    +SLIBLZ4   := $(LIBDIR)/liblz4.a
    +LZ4DIR     = ../programs
    +LZ4        = $(LZ4DIR)/lz4
     
     default: all
     
    -all: printVersion doubleBuffer dictionaryRandomAccess ringBuffer ringBufferHC \
    -     lineCompress frameCompress fileCompress simpleBuffer
    +$(SLIBLZ4): $(LIBDIR)/lz4.c $(LIBDIR)/lz4hc.c $(LIBDIR)/lz4frame.c $(LIBDIR)/lz4.h $(LIBDIR)/lz4hc.h $(LIBDIR)/lz4frame.h $(LIBDIR)/lz4frame_static.h
    +	$(MAKE) -j -C $(LIBDIR) liblz4.a
     
    -$(LZ4DIR)/liblz4.a: $(LZ4DIR)/lz4.c $(LZ4DIR)/lz4hc.c $(LZ4DIR)/lz4frame.c $(LZ4DIR)/lz4.h $(LZ4DIR)/lz4hc.h $(LZ4DIR)/lz4frame.h $(LZ4DIR)/lz4frame_static.h
    -	$(MAKE) -C $(LZ4DIR) liblz4.a
    +ALL = print_version \
    +	  simple_buffer \
    +	  frameCompress \
    +	  fileCompress \
    +      blockStreaming_doubleBuffer \
    +	  blockStreaming_ringBuffer \
    +	  streamingHC_ringBuffer \
    +      blockStreaming_lineByLine \
    +	  dictionaryRandomAccess \
    +	  bench_functions
     
    -printVersion: printVersion.c $(LZ4DIR)/liblz4.a
    -	$(CC) $(FLAGS) $^ -o $@$(EXT)
    +.PHONY: all
    +all: $(ALL)
     
    -doubleBuffer: blockStreaming_doubleBuffer.c $(LZ4DIR)/liblz4.a
    -	$(CC) $(FLAGS) $^ -o $@$(EXT)
    -
    -dictionaryRandomAccess: dictionaryRandomAccess.c $(LZ4DIR)/liblz4.a
    -	$(CC) $(FLAGS) $^ -o $@$(EXT)
    -
    -ringBuffer  : blockStreaming_ringBuffer.c $(LZ4DIR)/liblz4.a
    -	$(CC) $(FLAGS) $^ -o $@$(EXT)
    -
    -ringBufferHC: HCStreaming_ringBuffer.c $(LZ4DIR)/liblz4.a
    -	$(CC) $(FLAGS) $^ -o $@$(EXT)
    -
    -lineCompress: blockStreaming_lineByLine.c $(LZ4DIR)/liblz4.a
    -	$(CC) $(FLAGS) $^ -o $@$(EXT)
    -
    -frameCompress: frameCompress.c $(LZ4DIR)/liblz4.a
    -	$(CC) $(FLAGS) $^ -o $@$(EXT)
    -
    -fileCompress: fileCompress.c $(LZ4DIR)/liblz4.a
    -	$(CC) $(FLAGS) $^ -o $@$(EXT)
    -
    -compressFunctions: compress_functions.c $(LZ4DIR)/liblz4.a
    -	$(CC) $(FLAGS) $^ -o $@$(EXT) -lrt
    -
    -simpleBuffer: simple_buffer.c $(LZ4DIR)/liblz4.a
    -	$(CC) $(FLAGS) $^ -o $@$(EXT)
    +$(ALL): $(SLIBLZ4)
     
    +.PHONY:$(LZ4)
     $(LZ4) :
    -	$(MAKE) -C ../programs lz4
    +	$(MAKE) -j -C $(LZ4DIR) lz4
     
    +.PHONY: test
     test : all $(LZ4)
     	@echo "\n=== Print Version ==="
    -	./printVersion$(EXT)
    +	./print_version$(EXT)
     	@echo "\n=== Simple compression example ==="
    -	./simpleBuffer$(EXT)
    +	./simple_buffer$(EXT)
     	@echo "\n=== Double-buffer ==="
    -	./doubleBuffer$(EXT) $(TESTFILE)
    +	./blockStreaming_doubleBuffer$(EXT) $(TESTFILE)
     	@echo "\n=== Ring Buffer ==="
    -	./ringBuffer$(EXT)   $(TESTFILE)
    +	./blockStreaming_ringBuffer$(EXT)   $(TESTFILE)
     	@echo "\n=== Ring Buffer + LZ4 HC ==="
    -	./ringBufferHC$(EXT) $(TESTFILE)
    +	./streamingHC_ringBuffer$(EXT) $(TESTFILE)
     	@echo "\n=== Compress line by line ==="
    -	./lineCompress$(EXT) $(TESTFILE)
    +	./blockStreaming_lineByLine$(EXT) $(TESTFILE)
     	@echo "\n=== Dictionary Random Access ==="
     	./dictionaryRandomAccess$(EXT) $(TESTFILE) $(TESTFILE) 1100 1400
     	@echo "\n=== Frame compression ==="
    @@ -100,15 +86,10 @@ test : all $(LZ4)
     	@echo "\n=== file compression ==="
     	./fileCompress$(EXT) $(TESTFILE)
     	$(LZ4) -vt $(TESTFILE).lz4
    +	@echo "\n=== Q&D benchmark ==="
    +	./bench_functions$(EXT) 10000
     
    -.PHONY: cxxtest
    -cxxtest: CFLAGS := -O3 -Wall -Wextra -Wundef -Wshadow -Wcast-align -Werror
    -cxxtest: clean
    -	CC=$(CXX) $(MAKE) -C . all CFLAGS="$(CFLAGS)"
    -
    +.PHONY: clean
     clean:
    -	@rm -f core *.o *.dec *-0 *-9 *-8192 *.lz4s *.lz4 \
    -	 printVersion$(EXT) doubleBuffer$(EXT) dictionaryRandomAccess$(EXT) \
    -	 ringBuffer$(EXT) ringBufferHC$(EXT) lineCompress$(EXT) frameCompress$(EXT) \
    -	 fileCompress$(EXT) compressFunctions$(EXT) simpleBuffer$(EXT)
    +	@$(RM) core *.o *.dec *-0 *-9 *-8192 *.lz4s *.lz4 $(ALL)
     	@echo Cleaning completed
    diff --git a/examples/compress_functions.c b/examples/bench_functions.c
    similarity index 77%
    rename from examples/compress_functions.c
    rename to examples/bench_functions.c
    index 2a9d1245106046547816eca2a05ca6c9b45b760c..67b08ee55e893c489ffd8fc270820c2b64426cfe 100644
    --- a/examples/compress_functions.c
    +++ b/examples/bench_functions.c
    @@ -1,5 +1,5 @@
     /*
    - * compress_functions.c
    + * bench_functions.c
      * Copyright  : Kyle Harper
      * License    : Follows same licensing as the lz4.c/lz4.h program at any given time.  Currently, BSD 2.
      * Description: A program to demonstrate the various compression functions involved in when using LZ4_compress_default().  The idea
    @@ -67,8 +67,10 @@
     #include    /* for atoi() memcmp() */
     #include    /* for uint_types */
     #include  /* for PRIu64 */
    -#include      /* for clock_gettime() */
    +#include      /* for clock() */
     #include    /* for setlocale() */
    +#include    /* for INT_MAX */
    +#include 
     
     /* We need to know what one billion is for clock timing. */
     #define BILLION 1000000000L
    @@ -82,46 +84,45 @@
     #define ID__LZ4_DECOMPRESS_FAST         6
     
     
    -
     /*
      * Easy show-error-and-bail function.
      */
     void run_screaming(const char *message, const int code) {
    -  printf("%s\n", message);
    +  printf("%s \n", message);
       exit(code);
     }
     
    -
     /*
      * Centralize the usage function to keep main cleaner.
      */
    -void usage(const char *message) {
    -  printf("Usage: ./argPerformanceTesting \n");
    +void usage(const char* exeName, const char* message) {
    +  printf("Usage: %s  \n", exeName);
       run_screaming(message, 1);
       return;
     }
     
    +#define CHECK(c) { if (!(c)) { run_screaming(#c, 1); } }
     
     
     /*
    - * Runs the benchmark for LZ4_compress_* based on function_id.
    + * Runs the benchmark for LZ4_* function based on function_id.
    + * @return : benchmark duration, in ns
      */
     uint64_t bench(
         const char *known_good_dst,
         const int function_id,
    -    const int iterations,
    +    int iterations,
         const char *src,
         char *dst,
         const size_t src_size,
         const size_t max_dst_size,
         const size_t comp_size
       ) {
    -  uint64_t time_taken = 0;
       int rv = 0;
       const int warm_up = 5000;
    -  struct timespec start, end;
       const int acceleration = 1;
       LZ4_stream_t state;
    +  clock_t start = clock();
     
       // Select the right function to perform the benchmark on.  We perform 5000 initial loops to warm the cache and ensure that dst
       // remains matching to known_good_dst between successive calls.
    @@ -129,40 +130,40 @@ uint64_t bench(
         case ID__LZ4_COMPRESS_DEFAULT:
           printf("Starting benchmark for function: LZ4_compress_default()\n");
           for(int junk=0; junk requires more iterations to measure something
    +    if (end == start) {
    +      assert(iterations < (INT_MAX / 10));
    +      iterations *= 10;
    +      printf("not enough iterations => increase nb of iterations to %i \n", iterations);
    +      return bench(known_good_dst, function_id, iterations, src, dst, src_size, max_dst_size, comp_size);
    +    }
     
    +    return (uint64_t)((double)(end - start) / CLOCKS_PER_SEC * BILLION);
    +  }
    +}
     
     
     /*
    @@ -235,32 +242,33 @@ uint64_t bench(
      */
     int main(int argc, char **argv) {
       // Get and verify options.  There's really only 1:  How many iterations to run.
    +  const char* exeName = argv[0];
       int iterations = 1000000;
       if (argc > 1)
         iterations = atoi(argv[1]);
       if (iterations < 1)
    -    usage("Argument 1 (iterations) must be > 0.");
    +    usage(exeName, "Argument 1 (iterations) must be > 0.");
     
       // First we will create 2 sources (char *) of 2000 bytes each.  One normal text, the other highly-compressible text.
    -  const char *src    = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed luctus purus et risus vulputate, et mollis orci ullamcorper. Nulla facilisi. Fusce in ligula sed purus varius aliquet interdum vitae justo. Proin quis diam velit. Nulla varius iaculis auctor. Cras volutpat, justo eu dictum pulvinar, elit sem porttitor metus, et imperdiet metus sapien et ante. Nullam nisi nulla, ornare eu tristique eu, dignissim vitae diam. Nulla sagittis porta libero, a accumsan felis sagittis scelerisque.  Integer laoreet eleifend congue. Etiam rhoncus leo vel dolor fermentum, quis luctus nisl iaculis. Praesent a erat sapien. Aliquam semper mi in lorem ultrices ultricies. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In feugiat risus sed enim ultrices, at sodales nulla tristique. Maecenas eget pellentesque justo, sed pellentesque lectus. Fusce sagittis sit amet elit vel varius. Donec sed ligula nec ligula vulputate rutrum sed ut lectus. Etiam congue pharetra leo vitae cursus. Morbi enim ante, porttitor ut varius vel, tincidunt quis justo. Nunc iaculis, risus id ultrices semper, metus est efficitur ligula, vel posuere risus nunc eget purus. Ut lorem turpis, condimentum at sem sed, porta aliquam turpis. In ut sapien a nulla dictum tincidunt quis sit amet lorem. Fusce at est egestas, luctus neque eu, consectetur tortor. Phasellus eleifend ultricies nulla ac lobortis.  Morbi maximus quam cursus vehicula iaculis. Maecenas cursus vel justo ut rutrum. Curabitur magna orci, dignissim eget dapibus vitae, finibus id lacus. Praesent rhoncus mattis augue vitae bibendum. Praesent porta mauris non ultrices fermentum. Quisque vulputate ipsum in sodales pulvinar. Aliquam nec mollis felis. Donec vitae augue pulvinar, congue nisl sed, pretium purus. Fusce lobortis mi ac neque scelerisque semper. Pellentesque vel est vitae magna aliquet aliquet. Nam non dolor. Nulla facilisi. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Morbi ac lacinia felis metus.";
    -  const char *hc_src = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    +  const char src[]    = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed luctus purus et risus vulputate, et mollis orci ullamcorper. Nulla facilisi. Fusce in ligula sed purus varius aliquet interdum vitae justo. Proin quis diam velit. Nulla varius iaculis auctor. Cras volutpat, justo eu dictum pulvinar, elit sem porttitor metus, et imperdiet metus sapien et ante. Nullam nisi nulla, ornare eu tristique eu, dignissim vitae diam. Nulla sagittis porta libero, a accumsan felis sagittis scelerisque.  Integer laoreet eleifend congue. Etiam rhoncus leo vel dolor fermentum, quis luctus nisl iaculis. Praesent a erat sapien. Aliquam semper mi in lorem ultrices ultricies. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In feugiat risus sed enim ultrices, at sodales nulla tristique. Maecenas eget pellentesque justo, sed pellentesque lectus. Fusce sagittis sit amet elit vel varius. Donec sed ligula nec ligula vulputate rutrum sed ut lectus. Etiam congue pharetra leo vitae cursus. Morbi enim ante, porttitor ut varius vel, tincidunt quis justo. Nunc iaculis, risus id ultrices semper, metus est efficitur ligula, vel posuere risus nunc eget purus. Ut lorem turpis, condimentum at sem sed, porta aliquam turpis. In ut sapien a nulla dictum tincidunt quis sit amet lorem. Fusce at est egestas, luctus neque eu, consectetur tortor. Phasellus eleifend ultricies nulla ac lobortis.  Morbi maximus quam cursus vehicula iaculis. Maecenas cursus vel justo ut rutrum. Curabitur magna orci, dignissim eget dapibus vitae, finibus id lacus. Praesent rhoncus mattis augue vitae bibendum. Praesent porta mauris non ultrices fermentum. Quisque vulputate ipsum in sodales pulvinar. Aliquam nec mollis felis. Donec vitae augue pulvinar, congue nisl sed, pretium purus. Fusce lobortis mi ac neque scelerisque semper. Pellentesque vel est vitae magna aliquet aliquet. Nam non dolor. Nulla facilisi. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Morbi ac lacinia felis metus.";
    +  const char hc_src[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
       // Set and derive sizes.  Since we're using strings, use strlen() + 1 for \0.
       const size_t src_size = strlen(src) + 1;
    -  const size_t max_dst_size = LZ4_compressBound(src_size);
    +  const size_t max_dst_size = (size_t)LZ4_compressBound((int)src_size);
       int bytes_returned = 0;
       // Now build allocations for the data we'll be playing with.
    -  char *dst               = calloc(1, max_dst_size);
    -  char *known_good_dst    = calloc(1, max_dst_size);
    -  char *known_good_hc_dst = calloc(1, max_dst_size);
    +  char *dst               = (char*)calloc(1, max_dst_size);
    +  char *known_good_dst    = (char*)calloc(1, max_dst_size);
    +  char *known_good_hc_dst = (char*)calloc(1, max_dst_size);
       if (dst == NULL || known_good_dst == NULL || known_good_hc_dst == NULL)
         run_screaming("Couldn't allocate memory for the destination buffers.  Sad :(", 1);
     
       // Create known-good buffers to verify our tests with other functions will produce the same results.
    -  bytes_returned = LZ4_compress_default(src, known_good_dst, src_size, max_dst_size);
    +  bytes_returned = LZ4_compress_default(src, known_good_dst, (int)src_size, (int)max_dst_size);
       if (bytes_returned < 1)
         run_screaming("Couldn't create a known-good destination buffer for comparison... this is bad.", 1);
       const size_t src_comp_size = bytes_returned;
    -  bytes_returned = LZ4_compress_default(hc_src, known_good_hc_dst, src_size, max_dst_size);
    +  bytes_returned = LZ4_compress_default(hc_src, known_good_hc_dst, (int)src_size, (int)max_dst_size);
       if (bytes_returned < 1)
         run_screaming("Couldn't create a known-good (highly compressible) destination buffer for comparison... this is bad.", 1);
       const size_t hc_src_comp_size = bytes_returned;
    @@ -272,7 +280,7 @@ int main(int argc, char **argv) {
       /* LZ4_compress_fast() */
       // Using this function is identical to LZ4_compress_default except we need to specify an "acceleration" value.  Defaults to 1.
       memset(dst, 0, max_dst_size);
    -  bytes_returned = LZ4_compress_fast(src, dst, src_size, max_dst_size, 1);
    +  bytes_returned = LZ4_compress_fast(src, dst, (int)src_size, (int)max_dst_size, 1);
       if (bytes_returned < 1)
         run_screaming("Failed to compress src using LZ4_compress_fast.  echo $? for return code.", bytes_returned);
       if (memcmp(dst, known_good_dst, bytes_returned) != 0)
    @@ -282,7 +290,7 @@ int main(int argc, char **argv) {
       // Using this function directly requires that we build an LZ4_stream_t struct ourselves.  We do NOT have to reset it ourselves.
       memset(dst, 0, max_dst_size);
       LZ4_stream_t state;
    -  bytes_returned = LZ4_compress_fast_extState(&state, src, dst, src_size, max_dst_size, 1);
    +  bytes_returned = LZ4_compress_fast_extState(&state, src, dst, (int)src_size, (int)max_dst_size, 1);
       if (bytes_returned < 1)
         run_screaming("Failed to compress src using LZ4_compress_fast_extState.  echo $? for return code.", bytes_returned);
       if (memcmp(dst, known_good_dst, bytes_returned) != 0)
    @@ -315,7 +323,8 @@ int main(int argc, char **argv) {
        * Remember, we cannot call LZ4_compress_generic() directly (yet) so it's disabled.
        */
       // Suite A - Normal Compressibility
    -  char *dst_d = calloc(1, src_size);
    +  char *dst_d = (char*)calloc(1, src_size);
    +  CHECK(dst_d!=NULL);
       memset(dst, 0, max_dst_size);
       printf("\nStarting suite A:  Normal compressible text.\n");
       uint64_t time_taken__default       = bench(known_good_dst, ID__LZ4_COMPRESS_DEFAULT,       iterations, src,            dst,   src_size, max_dst_size, src_comp_size);
    @@ -336,26 +345,27 @@ int main(int argc, char **argv) {
     
       // Report and leave.
       setlocale(LC_ALL, "");
    -  const char *format        = "|%-14s|%-30s|%'14.9f|%'16d|%'14d|%'13.2f%%|\n";
    +  const char *format        = "|%-14s|%-30s|%'14.9f|%'16d|%'14llu|%'13.2f%%|\n";
       const char *header_format = "|%-14s|%-30s|%14s|%16s|%14s|%14s|\n";
       const char *separator     = "+--------------+------------------------------+--------------+----------------+--------------+--------------+\n";
    +  uint64_t iterllu = (uint64_t)iterations;
       printf("\n");
       printf("%s", separator);
       printf(header_format, "Source", "Function Benchmarked", "Total Seconds", "Iterations/sec", "ns/Iteration", "% of default");
       printf("%s", separator);
    -  printf(format, "Normal Text", "LZ4_compress_default()",       (double)time_taken__default       / BILLION, (int)(iterations / ((double)time_taken__default       /BILLION)), (int)time_taken__default       / iterations, (double)time_taken__default       * 100 / time_taken__default);
    -  printf(format, "Normal Text", "LZ4_compress_fast()",          (double)time_taken__fast          / BILLION, (int)(iterations / ((double)time_taken__fast          /BILLION)), (int)time_taken__fast          / iterations, (double)time_taken__fast          * 100 / time_taken__default);
    -  printf(format, "Normal Text", "LZ4_compress_fast_extState()", (double)time_taken__fast_extstate / BILLION, (int)(iterations / ((double)time_taken__fast_extstate /BILLION)), (int)time_taken__fast_extstate / iterations, (double)time_taken__fast_extstate * 100 / time_taken__default);
    +  printf(format, "Normal Text", "LZ4_compress_default()",       (double)time_taken__default       / BILLION, (int)(iterations / ((double)time_taken__default       /BILLION)), time_taken__default       / iterllu, (double)time_taken__default       * 100 / time_taken__default);
    +  printf(format, "Normal Text", "LZ4_compress_fast()",          (double)time_taken__fast          / BILLION, (int)(iterations / ((double)time_taken__fast          /BILLION)), time_taken__fast          / iterllu, (double)time_taken__fast          * 100 / time_taken__default);
    +  printf(format, "Normal Text", "LZ4_compress_fast_extState()", (double)time_taken__fast_extstate / BILLION, (int)(iterations / ((double)time_taken__fast_extstate /BILLION)), time_taken__fast_extstate / iterllu, (double)time_taken__fast_extstate * 100 / time_taken__default);
       //printf(format, "Normal Text", "LZ4_compress_generic()",       (double)time_taken__generic       / BILLION, (int)(iterations / ((double)time_taken__generic       /BILLION)), (int)time_taken__generic       / iterations, (double)time_taken__generic       * 100 / time_taken__default);
    -  printf(format, "Normal Text", "LZ4_decompress_safe()",        (double)time_taken__decomp_safe   / BILLION, (int)(iterations / ((double)time_taken__decomp_safe   /BILLION)), (int)time_taken__decomp_safe   / iterations, (double)time_taken__decomp_safe   * 100 / time_taken__default);
    -  printf(format, "Normal Text", "LZ4_decompress_fast()",        (double)time_taken__decomp_fast   / BILLION, (int)(iterations / ((double)time_taken__decomp_fast   /BILLION)), (int)time_taken__decomp_fast   / iterations, (double)time_taken__decomp_fast   * 100 / time_taken__default);
    +  printf(format, "Normal Text", "LZ4_decompress_safe()",        (double)time_taken__decomp_safe   / BILLION, (int)(iterations / ((double)time_taken__decomp_safe   /BILLION)), time_taken__decomp_safe   / iterllu, (double)time_taken__decomp_safe   * 100 / time_taken__default);
    +  printf(format, "Normal Text", "LZ4_decompress_fast()",        (double)time_taken__decomp_fast   / BILLION, (int)(iterations / ((double)time_taken__decomp_fast   /BILLION)), time_taken__decomp_fast   / iterllu, (double)time_taken__decomp_fast   * 100 / time_taken__default);
       printf(header_format, "", "", "", "", "", "");
    -  printf(format, "Compressible", "LZ4_compress_default()",       (double)time_taken_hc__default       / BILLION, (int)(iterations / ((double)time_taken_hc__default       /BILLION)), (int)time_taken_hc__default       / iterations, (double)time_taken_hc__default       * 100 / time_taken_hc__default);
    -  printf(format, "Compressible", "LZ4_compress_fast()",          (double)time_taken_hc__fast          / BILLION, (int)(iterations / ((double)time_taken_hc__fast          /BILLION)), (int)time_taken_hc__fast          / iterations, (double)time_taken_hc__fast          * 100 / time_taken_hc__default);
    -  printf(format, "Compressible", "LZ4_compress_fast_extState()", (double)time_taken_hc__fast_extstate / BILLION, (int)(iterations / ((double)time_taken_hc__fast_extstate /BILLION)), (int)time_taken_hc__fast_extstate / iterations, (double)time_taken_hc__fast_extstate * 100 / time_taken_hc__default);
    +  printf(format, "Compressible", "LZ4_compress_default()",       (double)time_taken_hc__default       / BILLION, (int)(iterations / ((double)time_taken_hc__default       /BILLION)), time_taken_hc__default       / iterllu, (double)time_taken_hc__default       * 100 / time_taken_hc__default);
    +  printf(format, "Compressible", "LZ4_compress_fast()",          (double)time_taken_hc__fast          / BILLION, (int)(iterations / ((double)time_taken_hc__fast          /BILLION)), time_taken_hc__fast          / iterllu, (double)time_taken_hc__fast          * 100 / time_taken_hc__default);
    +  printf(format, "Compressible", "LZ4_compress_fast_extState()", (double)time_taken_hc__fast_extstate / BILLION, (int)(iterations / ((double)time_taken_hc__fast_extstate /BILLION)), time_taken_hc__fast_extstate / iterllu, (double)time_taken_hc__fast_extstate * 100 / time_taken_hc__default);
       //printf(format, "Compressible", "LZ4_compress_generic()",       (double)time_taken_hc__generic       / BILLION, (int)(iterations / ((double)time_taken_hc__generic       /BILLION)), (int)time_taken_hc__generic       / iterations, (double)time_taken_hc__generic       * 100 / time_taken_hc__default);
    -  printf(format, "Compressible", "LZ4_decompress_safe()",        (double)time_taken_hc__decomp_safe   / BILLION, (int)(iterations / ((double)time_taken_hc__decomp_safe   /BILLION)), (int)time_taken_hc__decomp_safe   / iterations, (double)time_taken_hc__decomp_safe   * 100 / time_taken_hc__default);
    -  printf(format, "Compressible", "LZ4_decompress_fast()",        (double)time_taken_hc__decomp_fast   / BILLION, (int)(iterations / ((double)time_taken_hc__decomp_fast   /BILLION)), (int)time_taken_hc__decomp_fast   / iterations, (double)time_taken_hc__decomp_fast   * 100 / time_taken_hc__default);
    +  printf(format, "Compressible", "LZ4_decompress_safe()",        (double)time_taken_hc__decomp_safe   / BILLION, (int)(iterations / ((double)time_taken_hc__decomp_safe   /BILLION)), time_taken_hc__decomp_safe   / iterllu, (double)time_taken_hc__decomp_safe   * 100 / time_taken_hc__default);
    +  printf(format, "Compressible", "LZ4_decompress_fast()",        (double)time_taken_hc__decomp_fast   / BILLION, (int)(iterations / ((double)time_taken_hc__decomp_fast   /BILLION)), time_taken_hc__decomp_fast   / iterllu, (double)time_taken_hc__decomp_fast   * 100 / time_taken_hc__default);
       printf("%s", separator);
       printf("\n");
       printf("All done, ran %d iterations per test.\n", iterations);
    diff --git a/examples/fileCompress.c b/examples/fileCompress.c
    index 4486ea8b06f99513ce3c8ac698f47a8396221947..81f8067d068b4d534a3cf64ceeee90e5df14d0c1 100644
    --- a/examples/fileCompress.c
    +++ b/examples/fileCompress.c
    @@ -1,7 +1,7 @@
     /* LZ4file API example : compress a file
      * Modified from an example code by anjiahao
      *
    - * This example will demonstrate how 
    + * This example will demonstrate how
      * to manipulate lz4 compressed files like
      * normal files */
     
    @@ -41,6 +41,7 @@ static int compress_file(FILE* f_in, FILE* f_out)
         void* const buf = malloc(CHUNK_SIZE);
         if (!buf) {
             printf("error: memory allocation failed \n");
    +        return 1;
         }
     
         /* Of course, you can also use prefsPtr to
    diff --git a/examples/printVersion.c b/examples/print_version.c
    similarity index 100%
    rename from examples/printVersion.c
    rename to examples/print_version.c
    diff --git a/examples/HCStreaming_ringBuffer.c b/examples/streamingHC_ringBuffer.c
    similarity index 100%
    rename from examples/HCStreaming_ringBuffer.c
    rename to examples/streamingHC_ringBuffer.c
    diff --git a/lib/Makefile b/lib/Makefile
    index 06503cb2a6ed0c7e54e3012fb524b2689f822ed9..c8ac4d80b41222f70689a09c35b4ae52da79a0ff 100644
    --- a/lib/Makefile
    +++ b/lib/Makefile
    @@ -1,6 +1,6 @@
     # ################################################################
     # LZ4 library - Makefile
    -# Copyright (C) Yann Collet 2011-2020
    +# Copyright (C) Yann Collet 2011-2023
     # All rights reserved.
     #
     # This Makefile is validated for Linux, macOS, *BSD, Hurd, Solaris, MSYS2 targets
    @@ -31,12 +31,12 @@
     #  - LZ4 source repository : https://github.com/lz4/lz4
     #  - LZ4 forum froup : https://groups.google.com/forum/#!forum/lz4c
     # ################################################################
    -SED = sed
    +SED ?= sed
     
     # Version numbers
    -LIBVER_MAJOR_SCRIPT:=`$(SED) -n '/define LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ./lz4.h`
    -LIBVER_MINOR_SCRIPT:=`$(SED) -n '/define LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ./lz4.h`
    -LIBVER_PATCH_SCRIPT:=`$(SED) -n '/define LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ./lz4.h`
    +LIBVER_MAJOR_SCRIPT:=`$(SED) -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ./lz4.h`
    +LIBVER_MINOR_SCRIPT:=`$(SED) -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ./lz4.h`
    +LIBVER_PATCH_SCRIPT:=`$(SED) -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < ./lz4.h`
     LIBVER_SCRIPT:= $(LIBVER_MAJOR_SCRIPT).$(LIBVER_MINOR_SCRIPT).$(LIBVER_PATCH_SCRIPT)
     LIBVER_MAJOR := $(shell echo $(LIBVER_MAJOR_SCRIPT))
     LIBVER_MINOR := $(shell echo $(LIBVER_MINOR_SCRIPT))
    @@ -47,13 +47,12 @@ BUILD_SHARED:=yes
     BUILD_STATIC:=yes
     
     CPPFLAGS+= -DXXH_NAMESPACE=LZ4_
    -CPPFLAGS+= $(MOREFLAGS)
    -CFLAGS  ?= -O3
    +USERCFLAGS:= -O3 $(CFLAGS)
     DEBUGFLAGS:= -Wall -Wextra -Wcast-qual -Wcast-align -Wshadow \
                  -Wswitch-enum -Wdeclaration-after-statement -Wstrict-prototypes \
                  -Wundef -Wpointer-arith -Wstrict-aliasing=1
    -CFLAGS  += $(DEBUGFLAGS)
    -FLAGS    = $(CFLAGS) $(CPPFLAGS) $(LDFLAGS)
    +CFLAGS   = $(DEBUGFLAGS) $(USERCFLAGS)
    +ALLFLAGS = $(CFLAGS) $(CPPFLAGS) $(LDFLAGS)
     
     SRCFILES := $(sort $(wildcard *.c))
     
    @@ -65,12 +64,17 @@ ifeq ($(TARGET_OS), Darwin)
     	SHARED_EXT = dylib
     	SHARED_EXT_MAJOR = $(LIBVER_MAJOR).$(SHARED_EXT)
     	SHARED_EXT_VER = $(LIBVER).$(SHARED_EXT)
    -	SONAME_FLAGS = -install_name $(libdir)/liblz4.$(SHARED_EXT_MAJOR) -compatibility_version $(LIBVER_MAJOR) -current_version $(LIBVER)
    +	SONAME_FLAGS = -install_name $(libdir)/liblz4.$(SHARED_EXT_MAJOR) -compatibility_version $(LIBVER_MAJOR) -current_version $(LIBVER) -dynamiclib
     else
    -	SONAME_FLAGS = -Wl,-soname=liblz4.$(SHARED_EXT).$(LIBVER_MAJOR)
    -	SHARED_EXT = so
    -	SHARED_EXT_MAJOR = $(SHARED_EXT).$(LIBVER_MAJOR)
    -	SHARED_EXT_VER = $(SHARED_EXT).$(LIBVER)
    +	ifeq ($(WINBASED),yes)
    +		SHARED_EXT = dll
    +		SHARED_EXT_VER = $(SHARED_EXT)
    +	else  # posix non-mac
    +		SONAME_FLAGS = -Wl,-soname=liblz4.$(SHARED_EXT).$(LIBVER_MAJOR)
    +		SHARED_EXT = so
    +		SHARED_EXT_MAJOR = $(SHARED_EXT).$(LIBVER_MAJOR)
    +		SHARED_EXT_VER = $(SHARED_EXT).$(LIBVER)
    +	endif
     endif
     
     .PHONY: default
    @@ -79,19 +83,21 @@ default: lib-release
     # silent mode by default; verbose can be triggered by V=1 or VERBOSE=1
     $(V)$(VERBOSE).SILENT:
     
    +.PHONY:lib-release
     lib-release: DEBUGFLAGS :=
    -lib-release: lib
    +lib-release: lib liblz4.pc
     
     .PHONY: lib
     lib: liblz4.a liblz4
     
     .PHONY: all
    -all: lib
    +all: lib liblz4.pc
     
     .PHONY: all32
     all32: CFLAGS+=-m32
     all32: all
     
    +CLEAN += liblz4.a
     liblz4.a: $(SRCFILES)
     ifeq ($(BUILD_STATIC),yes)  # can be disabled on command line
     	@echo compiling static library
    @@ -100,9 +106,11 @@ ifeq ($(BUILD_STATIC),yes)  # can be disabled on command line
     endif
     
     ifeq ($(WINBASED),yes)
    +
    +CLEAN += $(liblz4-dll.rc)
     liblz4-dll.rc: liblz4-dll.rc.in
     	@echo creating library resource
    -	$(SED) -e 's|@LIBLZ4@|$(LIBLZ4)|' \
    +	$(SED) -e 's|@LIBLZ4@|$(LIBLZ4_NAME)|' \
              -e 's|@LIBVER_MAJOR@|$(LIBVER_MAJOR)|g' \
              -e 's|@LIBVER_MINOR@|$(LIBVER_MINOR)|g' \
              -e 's|@LIBVER_PATCH@|$(LIBVER_PATCH)|g' \
    @@ -111,31 +119,47 @@ liblz4-dll.rc: liblz4-dll.rc.in
     liblz4-dll.o: liblz4-dll.rc
     	$(WINDRES) -i liblz4-dll.rc -o liblz4-dll.o
     
    +CLEAN += $(LIBLZ4_EXP)
     $(LIBLZ4): $(SRCFILES) liblz4-dll.o
    +  ifeq ($(BUILD_SHARED),yes)
     	@echo compiling dynamic library $(LIBVER)
    -	$(CC) $(FLAGS) -DLZ4_DLL_EXPORT=1 -shared $^ -o dll/$@.dll -Wl,--out-implib,dll/$(LIBLZ4_EXP)
    +	$(CC) $(ALLFLAGS) -DLZ4_DLL_EXPORT=1 -shared $^ -o $@ -Wl,--out-implib,$(LIBLZ4_EXP)
    +  endif
     
     else   # not windows
     
     $(LIBLZ4): $(SRCFILES)
    +  ifeq ($(BUILD_SHARED),yes)
     	@echo compiling dynamic library $(LIBVER)
    -	$(CC) $(FLAGS) -shared $^ -fPIC -fvisibility=hidden $(SONAME_FLAGS) -o $@
    +	$(CC) $(ALLFLAGS) -shared $^ -fPIC -fvisibility=hidden $(SONAME_FLAGS) -o $@
     	@echo creating versioned links
     	$(LN_SF) $@ liblz4.$(SHARED_EXT_MAJOR)
     	$(LN_SF) $@ liblz4.$(SHARED_EXT)
    +  endif
     
     endif
    +CLEAN += $(LIBLZ4)
     
     .PHONY: liblz4
     liblz4: $(LIBLZ4)
     
    +CLEAN += liblz4.pc
    +liblz4.pc: liblz4.pc.in Makefile
    +	@echo creating pkgconfig
    +	$(SED) -e 's|@PREFIX@|$(prefix)|' \
    +           -e 's|@LIBDIR@|$(libdir)|' \
    +           -e 's|@INCLUDEDIR@|$(includedir)|' \
    +           -e 's|@VERSION@|$(LIBVER)|' \
    +           -e 's|=${prefix}/|=$${prefix}/|' \
    +           $< >$@
    +
     .PHONY: clean
     clean:
     ifeq ($(WINBASED),yes)
     	$(RM) *.rc
     endif
    -	$(RM) core *.o liblz4.pc dll/$(LIBLZ4).dll dll/$(LIBLZ4_EXP)
    -	$(RM) *.a *.$(SHARED_EXT) *.$(SHARED_EXT_MAJOR) *.$(SHARED_EXT_VER)
    +	$(RM) $(CLEAN) core *.o *.a
    +	$(RM) *.$(SHARED_EXT) *.$(SHARED_EXT_MAJOR) *.$(SHARED_EXT_VER)
     	@echo Cleaning library completed
     
     #-----------------------------------------------------------------------------
    @@ -169,30 +193,23 @@ PKGCONFIGDIR ?= $(libdir)/pkgconfig
       endif
     pkgconfigdir ?= $(PKGCONFIGDIR)
     
    -liblz4.pc: liblz4.pc.in Makefile
    -	@echo creating pkgconfig
    -	$(SED) -e 's|@PREFIX@|$(prefix)|' \
    -         -e 's|@LIBDIR@|$(libdir)|' \
    -         -e 's|@INCLUDEDIR@|$(includedir)|' \
    -         -e 's|@VERSION@|$(LIBVER)|' \
    -         -e 's|=${prefix}/|=$${prefix}/|' \
    -          $< >$@
    -
    +.PHONY: install
     install: lib liblz4.pc
    -	$(INSTALL_DIR) $(DESTDIR)$(pkgconfigdir)/ $(DESTDIR)$(includedir)/ $(DESTDIR)$(libdir)/ $(DESTDIR)$(bindir)/
    +	$(MAKE_DIR) $(DESTDIR)$(pkgconfigdir)/ $(DESTDIR)$(includedir)/ $(DESTDIR)$(libdir)/ $(DESTDIR)$(bindir)/
     	$(INSTALL_DATA) liblz4.pc $(DESTDIR)$(pkgconfigdir)/
     	@echo Installing libraries in $(DESTDIR)$(libdir)
       ifeq ($(BUILD_STATIC),yes)
     	$(INSTALL_DATA) liblz4.a $(DESTDIR)$(libdir)/liblz4.a
     	$(INSTALL_DATA) lz4frame_static.h $(DESTDIR)$(includedir)/lz4frame_static.h
    +	$(INSTALL_DATA) lz4file.h $(DESTDIR)$(includedir)/lz4file.h
       endif
       ifeq ($(BUILD_SHARED),yes)
     # Traditionally, one installs the DLLs in the bin directory as programs
     # search them first in their directory. This allows to not pollute system
     # directories (like c:/windows/system32), nor modify the PATH variable.
         ifeq ($(WINBASED),yes)
    -	$(INSTALL_PROGRAM) dll/$(LIBLZ4).dll $(DESTDIR)$(bindir)
    -	$(INSTALL_PROGRAM) dll/$(LIBLZ4_EXP) $(DESTDIR)$(libdir)
    +	$(INSTALL_PROGRAM) $(LIBLZ4) $(DESTDIR)$(bindir)
    +	$(INSTALL_PROGRAM) $(LIBLZ4_EXP) $(DESTDIR)$(libdir)
         else
     	$(INSTALL_PROGRAM) liblz4.$(SHARED_EXT_VER) $(DESTDIR)$(libdir)
     	$(LN_SF) liblz4.$(SHARED_EXT_VER) $(DESTDIR)$(libdir)/liblz4.$(SHARED_EXT_MAJOR)
    @@ -205,10 +222,11 @@ install: lib liblz4.pc
     	$(INSTALL_DATA) lz4frame.h $(DESTDIR)$(includedir)/lz4frame.h
     	@echo lz4 libraries installed
     
    +.PHONY: uninstall
     uninstall:
     	$(RM) $(DESTDIR)$(pkgconfigdir)/liblz4.pc
    -  ifeq (WINBASED,1)
    -	$(RM) $(DESTDIR)$(bindir)/$(LIBLZ4).dll
    +  ifeq (WINBASED,yes)
    +	$(RM) $(DESTDIR)$(bindir)/$(LIBLZ4)
     	$(RM) $(DESTDIR)$(libdir)/$(LIBLZ4_EXP)
       else
     	$(RM) $(DESTDIR)$(libdir)/liblz4.$(SHARED_EXT)
    @@ -220,6 +238,7 @@ uninstall:
     	$(RM) $(DESTDIR)$(includedir)/lz4hc.h
     	$(RM) $(DESTDIR)$(includedir)/lz4frame.h
     	$(RM) $(DESTDIR)$(includedir)/lz4frame_static.h
    +	$(RM) $(DESTDIR)$(includedir)/lz4file.h
     	@echo lz4 libraries successfully uninstalled
     
     endif
    diff --git a/lib/README.md b/lib/README.md
    index 08d1cef2bf8ad2ef3878ddaa71c4d5470db12a6b..9039da35af3b2fc28e81fee494953a3b939d2b0e 100644
    --- a/lib/README.md
    +++ b/lib/README.md
    @@ -100,7 +100,7 @@ The following build macro can be selected to adjust source code behavior at comp
       passed as argument to become a compression state is suitably aligned.
       This test can be disabled if it proves flaky, by setting this value to 0.
     
    -- `LZ4_USER_MEMORY_FUNCTIONS` : replace calls to ``'s `malloc()`, `calloc()` and `free()`
    +- `LZ4_USER_MEMORY_FUNCTIONS` : replace calls to ``'s `malloc()`, `calloc()` and `free()`
       by user-defined functions, which must be named `LZ4_malloc()`, `LZ4_calloc()` and `LZ4_free()`.
       User functions must be available at link time.
     
    @@ -108,6 +108,12 @@ The following build macro can be selected to adjust source code behavior at comp
       Remove support of dynamic memory allocation.
       For more details, see description of this macro in `lib/lz4.c`.
     
    +- `LZ4_STATIC_LINKING_ONLY_ENDIANNESS_INDEPENDENT_OUTPUT` : experimental feature aimed at producing the same
    +  compressed output on platforms of different endianness (i.e. little-endian and big-endian).
    +  Output on little-endian platforms shall remain unchanged, while big-endian platforms will start producing
    +  the same output as little-endian ones. This isn't expected to impact backward- and forward-compatibility
    +  in any way.
    +
     - `LZ4_FREESTANDING` : by setting this build macro to 1,
       LZ4/HC removes dependencies on the C standard library,
       including allocation functions and `memmove()`, `memcpy()`, and `memset()`.
    @@ -115,6 +121,24 @@ The following build macro can be selected to adjust source code behavior at comp
       (embedded, bootloader, etc).
       For more details, see description of this macro in `lib/lz4.h`.
     
    +- `LZ4_HEAPMODE` : Select how stateless compression functions like `LZ4_compress_default()`
    +  allocate memory for their hash table,
    +  in memory stack (0:default, fastest), or in memory heap (1:requires malloc()).
    +
    +- `LZ4HC_HEAPMODE` :  Select how stateless HC compression functions like `LZ4_compress_HC()`
    +  allocate memory for their workspace:
    +  in stack (0), or in heap (1:default).
    +  Since workspace is rather large, stack can be inconvenient, hence heap mode is recommended.
    +
    +- `LZ4F_HEAPMODE` : selects how `LZ4F_compressFrame()` allocates the compression state,
    +  either on stack (default, value 0) or using heap memory (value 1).
    +
    +
    +#### Makefile variables
    +
    +The following `Makefile` variables can be selected to alter the profile of produced binaries :
    +- `BUILD_SHARED` : generate `liblz4` dynamic library (enabled by default)
    +- `BUILD_STATIC` : generate `liblz4` static library (enabled by default)
     
     
     #### Amalgamation
    diff --git a/lib/lz4.c b/lib/lz4.c
    index 654bfdf32f96ac633a5d4bc4dde097dbdff46882..a2f7abee19fb9a5c768f2a6c266acf5b571f0855 100644
    --- a/lib/lz4.c
    +++ b/lib/lz4.c
    @@ -1,6 +1,6 @@
     /*
        LZ4 - Fast LZ compression algorithm
    -   Copyright (C) 2011-2020, Yann Collet.
    +   Copyright (C) 2011-2023, Yann Collet.
     
        BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
     
    @@ -37,7 +37,8 @@
     **************************************/
     /*
      * LZ4_HEAPMODE :
    - * Select how default compression functions will allocate memory for their hash table,
    + * Select how stateless compression functions like `LZ4_compress_default()`
    + * allocate memory for their hash table,
      * in memory stack (0:default, fastest), or in memory heap (1:requires malloc()).
      */
     #ifndef LZ4_HEAPMODE
    @@ -78,7 +79,7 @@
       ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) \
       || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) )
     #    define LZ4_FORCE_MEMORY_ACCESS 2
    -#  elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || defined(__GNUC__)
    +#  elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || defined(__GNUC__) || defined(_MSC_VER)
     #    define LZ4_FORCE_MEMORY_ACCESS 1
     #  endif
     #endif
    @@ -105,15 +106,13 @@
     #  define LZ4_SRC_INCLUDED 1
     #endif
     
    -#ifndef LZ4_STATIC_LINKING_ONLY
    -#define LZ4_STATIC_LINKING_ONLY
    -#endif
    -
     #ifndef LZ4_DISABLE_DEPRECATE_WARNINGS
    -#define LZ4_DISABLE_DEPRECATE_WARNINGS /* due to LZ4_decompress_safe_withPrefix64k */
    +#  define LZ4_DISABLE_DEPRECATE_WARNINGS /* due to LZ4_decompress_safe_withPrefix64k */
     #endif
     
    -#define LZ4_STATIC_LINKING_ONLY  /* LZ4_DISTANCE_MAX */
    +#ifndef LZ4_STATIC_LINKING_ONLY
    +#  define LZ4_STATIC_LINKING_ONLY
    +#endif
     #include "lz4.h"
     /* see also "memory routines" below */
     
    @@ -125,14 +124,17 @@
     #  include                /* only present in VS2005+ */
     #  pragma warning(disable : 4127)   /* disable: C4127: conditional expression is constant */
     #  pragma warning(disable : 6237)   /* disable: C6237: conditional expression is always 0 */
    +#  pragma warning(disable : 6239)   /* disable: C6239: ( && ) always evaluates to the result of  */
    +#  pragma warning(disable : 6240)   /* disable: C6240: ( && ) always evaluates to the result of  */
    +#  pragma warning(disable : 6326)   /* disable: C6326: Potential comparison of a constant with another constant */
     #endif  /* _MSC_VER */
     
     #ifndef LZ4_FORCE_INLINE
    -#  ifdef _MSC_VER    /* Visual Studio */
    +#  if defined (_MSC_VER) && !defined (__clang__)    /* MSVC */
     #    define LZ4_FORCE_INLINE static __forceinline
     #  else
     #    if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L   /* C99 */
    -#      ifdef __GNUC__
    +#      if defined (__GNUC__) || defined (__clang__)
     #        define LZ4_FORCE_INLINE static inline __attribute__((always_inline))
     #      else
     #        define LZ4_FORCE_INLINE static inline
    @@ -279,7 +281,7 @@ static const int LZ4_minLength = (MFLIMIT+1);
        static int g_debuglog_enable = 1;
     #  define DEBUGLOG(l, ...) {                          \
             if ((g_debuglog_enable) && (l<=LZ4_DEBUG)) {  \
    -            fprintf(stderr, __FILE__ ": ");           \
    +            fprintf(stderr, __FILE__  " %i: ", __LINE__); \
                 fprintf(stderr, __VA_ARGS__);             \
                 fprintf(stderr, " \n");                   \
         }   }
    @@ -364,6 +366,11 @@ static unsigned LZ4_isLittleEndian(void)
         return one.c[0];
     }
     
    +#if defined(__GNUC__) || defined(__INTEL_COMPILER)
    +#define LZ4_PACK( __Declaration__ ) __Declaration__ __attribute__((__packed__))
    +#elif defined(_MSC_VER)
    +#define LZ4_PACK( __Declaration__ ) __pragma( pack(push, 1) ) __Declaration__ __pragma( pack(pop))
    +#endif
     
     #if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2)
     /* lie to the compiler about data alignment; use with caution */
    @@ -379,14 +386,16 @@ static void LZ4_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; }
     
     /* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */
     /* currently only defined for gcc and icc */
    -typedef union { U16 u16; U32 u32; reg_t uArch; } __attribute__((packed)) LZ4_unalign;
    +LZ4_PACK(typedef struct { U16 u16; }) LZ4_unalign16;
    +LZ4_PACK(typedef struct { U32 u32; }) LZ4_unalign32;
    +LZ4_PACK(typedef struct { reg_t uArch; }) LZ4_unalignST;
     
    -static U16 LZ4_read16(const void* ptr) { return ((const LZ4_unalign*)ptr)->u16; }
    -static U32 LZ4_read32(const void* ptr) { return ((const LZ4_unalign*)ptr)->u32; }
    -static reg_t LZ4_read_ARCH(const void* ptr) { return ((const LZ4_unalign*)ptr)->uArch; }
    +static U16 LZ4_read16(const void* ptr) { return ((const LZ4_unalign16*)ptr)->u16; }
    +static U32 LZ4_read32(const void* ptr) { return ((const LZ4_unalign32*)ptr)->u32; }
    +static reg_t LZ4_read_ARCH(const void* ptr) { return ((const LZ4_unalignST*)ptr)->uArch; }
     
    -static void LZ4_write16(void* memPtr, U16 value) { ((LZ4_unalign*)memPtr)->u16 = value; }
    -static void LZ4_write32(void* memPtr, U32 value) { ((LZ4_unalign*)memPtr)->u32 = value; }
    +static void LZ4_write16(void* memPtr, U16 value) { ((LZ4_unalign16*)memPtr)->u16 = value; }
    +static void LZ4_write32(void* memPtr, U32 value) { ((LZ4_unalign32*)memPtr)->u32 = value; }
     
     #else  /* safe and portable access using memcpy() */
     
    @@ -424,9 +433,21 @@ static U16 LZ4_readLE16(const void* memPtr)
             return LZ4_read16(memPtr);
         } else {
             const BYTE* p = (const BYTE*)memPtr;
    -        return (U16)((U16)p[0] + (p[1]<<8));
    +        return (U16)((U16)p[0] | (p[1]<<8));
    +    }
    +}
    +
    +#ifdef LZ4_STATIC_LINKING_ONLY_ENDIANNESS_INDEPENDENT_OUTPUT
    +static U32 LZ4_readLE32(const void* memPtr)
    +{
    +    if (LZ4_isLittleEndian()) {
    +        return LZ4_read32(memPtr);
    +    } else {
    +        const BYTE* p = (const BYTE*)memPtr;
    +        return (U32)p[0] | (p[1]<<8) | (p[2]<<16) | (p[3]<<24);
         }
     }
    +#endif
     
     static void LZ4_writeLE16(void* memPtr, U16 value)
     {
    @@ -509,7 +530,7 @@ LZ4_wildCopy32(void* dstPtr, const void* srcPtr, void* dstEnd)
     
     /* LZ4_memcpy_using_offset()  presumes :
      * - dstEnd >= dstPtr + MINMATCH
    - * - there is at least 8 bytes available to write after dstEnd */
    + * - there is at least 12 bytes available to write after dstEnd */
     LZ4_FORCE_INLINE void
     LZ4_memcpy_using_offset(BYTE* dstPtr, const BYTE* srcPtr, BYTE* dstEnd, const size_t offset)
     {
    @@ -524,12 +545,12 @@ LZ4_memcpy_using_offset(BYTE* dstPtr, const BYTE* srcPtr, BYTE* dstEnd, const si
         case 2:
             LZ4_memcpy(v, srcPtr, 2);
             LZ4_memcpy(&v[2], srcPtr, 2);
    -#if defined(_MSC_VER) && (_MSC_VER <= 1933) /* MSVC 2022 ver 17.3 or earlier */
    +#if defined(_MSC_VER) && (_MSC_VER <= 1937) /* MSVC 2022 ver 17.7 or earlier */
     #  pragma warning(push)
     #  pragma warning(disable : 6385) /* warning C6385: Reading invalid data from 'v'. */
     #endif
             LZ4_memcpy(&v[4], v, 4);
    -#if defined(_MSC_VER) && (_MSC_VER <= 1933) /* MSVC 2022 ver 17.3 or earlier */
    +#if defined(_MSC_VER) && (_MSC_VER <= 1937) /* MSVC 2022 ver 17.7 or earlier */
     #  pragma warning(pop)
     #endif
             break;
    @@ -776,7 +797,12 @@ LZ4_FORCE_INLINE U32 LZ4_hash5(U64 sequence, tableType_t const tableType)
     LZ4_FORCE_INLINE U32 LZ4_hashPosition(const void* const p, tableType_t const tableType)
     {
         if ((sizeof(reg_t)==8) && (tableType != byU16)) return LZ4_hash5(LZ4_read_ARCH(p), tableType);
    +
    +#ifdef LZ4_STATIC_LINKING_ONLY_ENDIANNESS_INDEPENDENT_OUTPUT
    +    return LZ4_hash4(LZ4_readLE32(p), tableType);
    +#else
         return LZ4_hash4(LZ4_read32(p), tableType);
    +#endif
     }
     
     LZ4_FORCE_INLINE void LZ4_clearHash(U32 h, void* tableBase, tableType_t const tableType)
    @@ -803,23 +829,19 @@ LZ4_FORCE_INLINE void LZ4_putIndexOnHash(U32 idx, U32 h, void* tableBase, tableT
         }
     }
     
    +/* LZ4_putPosition*() : only used in byPtr mode */
     LZ4_FORCE_INLINE void LZ4_putPositionOnHash(const BYTE* p, U32 h,
    -                                  void* tableBase, tableType_t const tableType,
    -                            const BYTE* srcBase)
    +                                  void* tableBase, tableType_t const tableType)
     {
    -    switch (tableType)
    -    {
    -    case clearedTable: { /* illegal! */ assert(0); return; }
    -    case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = p; return; }
    -    case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); return; }
    -    case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); return; }
    -    }
    +    const BYTE** const hashTable = (const BYTE**)tableBase;
    +    assert(tableType == byPtr); (void)tableType;
    +    hashTable[h] = p;
     }
     
    -LZ4_FORCE_INLINE void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase)
    +LZ4_FORCE_INLINE void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType)
     {
         U32 const h = LZ4_hashPosition(p, tableType);
    -    LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase);
    +    LZ4_putPositionOnHash(p, h, tableBase, tableType);
     }
     
     /* LZ4_getIndexOnHash() :
    @@ -844,20 +866,18 @@ LZ4_FORCE_INLINE U32 LZ4_getIndexOnHash(U32 h, const void* tableBase, tableType_
         assert(0); return 0;  /* forbidden case */
     }
     
    -static const BYTE* LZ4_getPositionOnHash(U32 h, const void* tableBase, tableType_t tableType, const BYTE* srcBase)
    +static const BYTE* LZ4_getPositionOnHash(U32 h, const void* tableBase, tableType_t tableType)
     {
    -    if (tableType == byPtr) { const BYTE* const* hashTable = (const BYTE* const*) tableBase; return hashTable[h]; }
    -    if (tableType == byU32) { const U32* const hashTable = (const U32*) tableBase; return hashTable[h] + srcBase; }
    -    { const U16* const hashTable = (const U16*) tableBase; return hashTable[h] + srcBase; }   /* default, to ensure a return */
    +    assert(tableType == byPtr); (void)tableType;
    +    { const BYTE* const* hashTable = (const BYTE* const*) tableBase; return hashTable[h]; }
     }
     
     LZ4_FORCE_INLINE const BYTE*
     LZ4_getPosition(const BYTE* p,
    -                const void* tableBase, tableType_t tableType,
    -                const BYTE* srcBase)
    +                const void* tableBase, tableType_t tableType)
     {
         U32 const h = LZ4_hashPosition(p, tableType);
    -    return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase);
    +    return LZ4_getPositionOnHash(h, tableBase, tableType);
     }
     
     LZ4_FORCE_INLINE void
    @@ -901,9 +921,9 @@ LZ4_prepareTable(LZ4_stream_t_internal* const cctx,
         cctx->dictSize = 0;
     }
     
    -/** LZ4_compress_generic() :
    +/** LZ4_compress_generic_validated() :
      *  inlined, to ensure branches are decided at compilation time.
    - *  Presumed already validated at this stage:
    + *  The following conditions are presumed already validated:
      *  - source != NULL
      *  - inputSize > 0
      */
    @@ -921,10 +941,10 @@ LZ4_FORCE_INLINE int LZ4_compress_generic_validated(
                      const int acceleration)
     {
         int result;
    -    const BYTE* ip = (const BYTE*) source;
    +    const BYTE* ip = (const BYTE*)source;
     
         U32 const startIndex = cctx->currentOffset;
    -    const BYTE* base = (const BYTE*) source - startIndex;
    +    const BYTE* base = (const BYTE*)source - startIndex;
         const BYTE* lowLimit;
     
         const LZ4_stream_t_internal* dictCtx = (const LZ4_stream_t_internal*) cctx->dictCtx;
    @@ -932,7 +952,8 @@ LZ4_FORCE_INLINE int LZ4_compress_generic_validated(
             dictDirective == usingDictCtx ? dictCtx->dictionary : cctx->dictionary;
         const U32 dictSize =
             dictDirective == usingDictCtx ? dictCtx->dictSize : cctx->dictSize;
    -    const U32 dictDelta = (dictDirective == usingDictCtx) ? startIndex - dictCtx->currentOffset : 0;   /* make indexes in dictCtx comparable with index in current context */
    +    const U32 dictDelta =
    +        (dictDirective == usingDictCtx) ? startIndex - dictCtx->currentOffset : 0;   /* make indexes in dictCtx comparable with indexes in current context */
     
         int const maybe_extMem = (dictDirective == usingExtDict) || (dictDirective == usingDictCtx);
         U32 const prefixIdxLimit = startIndex - dictSize;   /* used when dictDirective == dictSmall */
    @@ -957,11 +978,11 @@ LZ4_FORCE_INLINE int LZ4_compress_generic_validated(
     
         DEBUGLOG(5, "LZ4_compress_generic_validated: srcSize=%i, tableType=%u", inputSize, tableType);
         assert(ip != NULL);
    +    if (tableType == byU16) assert(inputSize=LZ4_64Klimit)) { return 0; }  /* Size too large (not within 64K limit) */
    -    if (tableType==byPtr) assert(dictDirective==noDict);      /* only supported use case with byPtr */
         assert(acceleration >= 1);
     
         lowLimit = (const BYTE*)source - (dictDirective == withPrefix64k ? dictSize : 0);
    @@ -981,7 +1002,12 @@ LZ4_FORCE_INLINE int LZ4_compress_generic_validated(
         if (inputSizehashTable, tableType, base);
    +    {   U32 const h = LZ4_hashPosition(ip, tableType);
    +        if (tableType == byPtr) {
    +            LZ4_putPositionOnHash(ip, h, cctx->hashTable, byPtr);
    +        } else {
    +            LZ4_putIndexOnHash(startIndex, h, cctx->hashTable, tableType);
    +    }   }
         ip++; forwardH = LZ4_hashPosition(ip, tableType);
     
         /* Main Loop */
    @@ -1004,9 +1030,9 @@ LZ4_FORCE_INLINE int LZ4_compress_generic_validated(
                     if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals;
                     assert(ip < mflimitPlusOne);
     
    -                match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType, base);
    +                match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType);
                     forwardH = LZ4_hashPosition(forwardIp, tableType);
    -                LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base);
    +                LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType);
     
                 } while ( (match+LZ4_DISTANCE_MAX < ip)
                        || (LZ4_read32(match) != LZ4_read32(ip)) );
    @@ -1077,7 +1103,10 @@ LZ4_FORCE_INLINE int LZ4_compress_generic_validated(
     
             /* Catch up */
             filledIp = ip;
    -        while (((ip>anchor) & (match > lowLimit)) && (unlikely(ip[-1]==match[-1]))) { ip--; match--; }
    +        assert(ip > anchor); /* this is always true as ip has been advanced before entering the main loop */
    +        if ((match > lowLimit) && unlikely(ip[-1] == match[-1])) {
    +            do { ip--; match--; } while (((ip > anchor) & (match > lowLimit)) && (unlikely(ip[-1] == match[-1])));
    +        }
     
             /* Encode Literals */
             {   unsigned const litLength = (unsigned)(ip - anchor);
    @@ -1092,7 +1121,7 @@ LZ4_FORCE_INLINE int LZ4_compress_generic_validated(
                     goto _last_literals;
                 }
                 if (litLength >= RUN_MASK) {
    -                int len = (int)(litLength - RUN_MASK);
    +                unsigned len = litLength - RUN_MASK;
                     *token = (RUN_MASK<= 255 ; len-=255) *op++ = 255;
                     *op++ = (BYTE)len;
    @@ -1204,13 +1233,19 @@ _next_match:
             if (ip >= mflimitPlusOne) break;
     
             /* Fill table */
    -        LZ4_putPosition(ip-2, cctx->hashTable, tableType, base);
    +        {   U32 const h = LZ4_hashPosition(ip-2, tableType);
    +            if (tableType == byPtr) {
    +                LZ4_putPositionOnHash(ip-2, h, cctx->hashTable, byPtr);
    +            } else {
    +                U32 const idx = (U32)((ip-2) - base);
    +                LZ4_putIndexOnHash(idx, h, cctx->hashTable, tableType);
    +        }   }
     
             /* Test next position */
             if (tableType == byPtr) {
     
    -            match = LZ4_getPosition(ip, cctx->hashTable, tableType, base);
    -            LZ4_putPosition(ip, cctx->hashTable, tableType, base);
    +            match = LZ4_getPosition(ip, cctx->hashTable, tableType);
    +            LZ4_putPosition(ip, cctx->hashTable, tableType);
                 if ( (match+LZ4_DISTANCE_MAX >= ip)
                   && (LZ4_read32(match) == LZ4_read32(ip)) )
                 { token=op++; *token=0; goto _next_match; }
    @@ -1224,6 +1259,7 @@ _next_match:
                 if (dictDirective == usingDictCtx) {
                     if (matchIndex < startIndex) {
                         /* there was no match, try the dictionary */
    +                    assert(tableType == byU32);
                         matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32);
                         match = dictBase + matchIndex;
                         lowLimit = dictionary;   /* required for match length counter */
    @@ -1377,9 +1413,10 @@ int LZ4_compress_fast_extState(void* state, const char* source, char* dest, int
      */
     int LZ4_compress_fast_extState_fastReset(void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration)
     {
    -    LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)state)->internal_donotuse;
    +    LZ4_stream_t_internal* const ctx = &((LZ4_stream_t*)state)->internal_donotuse;
         if (acceleration < 1) acceleration = LZ4_ACCELERATION_DEFAULT;
         if (acceleration > LZ4_ACCELERATION_MAX) acceleration = LZ4_ACCELERATION_MAX;
    +    assert(ctx != NULL);
     
         if (dstCapacity >= LZ4_compressBound(srcSize)) {
             if (srcSize < LZ4_64Klimit) {
    @@ -1413,17 +1450,17 @@ int LZ4_compress_fast_extState_fastReset(void* state, const char* src, char* dst
     }
     
     
    -int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
    +int LZ4_compress_fast(const char* src, char* dest, int srcSize, int dstCapacity, int acceleration)
     {
         int result;
     #if (LZ4_HEAPMODE)
    -    LZ4_stream_t* ctxPtr = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t));   /* malloc-calloc always properly aligned */
    +    LZ4_stream_t* const ctxPtr = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t));   /* malloc-calloc always properly aligned */
         if (ctxPtr == NULL) return 0;
     #else
         LZ4_stream_t ctx;
         LZ4_stream_t* const ctxPtr = &ctx;
     #endif
    -    result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration);
    +    result = LZ4_compress_fast_extState(ctxPtr, src, dest, srcSize, dstCapacity, acceleration);
     
     #if (LZ4_HEAPMODE)
         FREEMEM(ctxPtr);
    @@ -1432,43 +1469,51 @@ int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutp
     }
     
     
    -int LZ4_compress_default(const char* src, char* dst, int srcSize, int maxOutputSize)
    +int LZ4_compress_default(const char* src, char* dst, int srcSize, int dstCapacity)
     {
    -    return LZ4_compress_fast(src, dst, srcSize, maxOutputSize, 1);
    +    return LZ4_compress_fast(src, dst, srcSize, dstCapacity, 1);
     }
     
     
     /* Note!: This function leaves the stream in an unclean/broken state!
      * It is not safe to subsequently use the same state with a _fastReset() or
      * _continue() call without resetting it. */
    -static int LZ4_compress_destSize_extState (LZ4_stream_t* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize)
    +static int LZ4_compress_destSize_extState_internal(LZ4_stream_t* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize, int acceleration)
     {
         void* const s = LZ4_initStream(state, sizeof (*state));
         assert(s != NULL); (void)s;
     
         if (targetDstSize >= LZ4_compressBound(*srcSizePtr)) {  /* compression success is guaranteed */
    -        return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, 1);
    +        return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, acceleration);
         } else {
             if (*srcSizePtr < LZ4_64Klimit) {
    -            return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, byU16, noDict, noDictIssue, 1);
    +            return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, byU16, noDict, noDictIssue, acceleration);
             } else {
                 tableType_t const addrMode = ((sizeof(void*)==4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32;
    -            return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, addrMode, noDict, noDictIssue, 1);
    +            return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, addrMode, noDict, noDictIssue, acceleration);
         }   }
     }
     
    +int LZ4_compress_destSize_extState(void* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize, int acceleration)
    +{
    +    int const r = LZ4_compress_destSize_extState_internal((LZ4_stream_t*)state, src, dst, srcSizePtr, targetDstSize, acceleration);
    +    /* clean the state on exit */
    +    LZ4_initStream(state, sizeof (LZ4_stream_t));
    +    return r;
    +}
    +
     
     int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize)
     {
     #if (LZ4_HEAPMODE)
    -    LZ4_stream_t* ctx = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t));   /* malloc-calloc always properly aligned */
    +    LZ4_stream_t* const ctx = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t));   /* malloc-calloc always properly aligned */
         if (ctx == NULL) return 0;
     #else
         LZ4_stream_t ctxBody;
    -    LZ4_stream_t* ctx = &ctxBody;
    +    LZ4_stream_t* const ctx = &ctxBody;
     #endif
     
    -    int result = LZ4_compress_destSize_extState(ctx, src, dst, srcSizePtr, targetDstSize);
    +    int result = LZ4_compress_destSize_extState_internal(ctx, src, dst, srcSizePtr, targetDstSize, 1);
     
     #if (LZ4_HEAPMODE)
         FREEMEM(ctx);
    @@ -1537,14 +1582,17 @@ int LZ4_freeStream (LZ4_stream_t* LZ4_stream)
     #endif
     
     
    +typedef enum { _ld_fast, _ld_slow } LoadDict_mode_e;
     #define HASH_UNIT sizeof(reg_t)
    -int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize)
    +int LZ4_loadDict_internal(LZ4_stream_t* LZ4_dict,
    +                    const char* dictionary, int dictSize,
    +                    LoadDict_mode_e _ld)
     {
    -    LZ4_stream_t_internal* dict = &LZ4_dict->internal_donotuse;
    +    LZ4_stream_t_internal* const dict = &LZ4_dict->internal_donotuse;
         const tableType_t tableType = byU32;
         const BYTE* p = (const BYTE*)dictionary;
         const BYTE* const dictEnd = p + dictSize;
    -    const BYTE* base;
    +    U32 idx32;
     
         DEBUGLOG(4, "LZ4_loadDict (%i bytes from %p into %p)", dictSize, dictionary, LZ4_dict);
     
    @@ -1567,19 +1615,46 @@ int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize)
         }
     
         if ((dictEnd - p) > 64 KB) p = dictEnd - 64 KB;
    -    base = dictEnd - dict->currentOffset;
         dict->dictionary = p;
         dict->dictSize = (U32)(dictEnd - p);
         dict->tableType = (U32)tableType;
    +    idx32 = dict->currentOffset - dict->dictSize;
     
         while (p <= dictEnd-HASH_UNIT) {
    -        LZ4_putPosition(p, dict->hashTable, tableType, base);
    -        p+=3;
    +        U32 const h = LZ4_hashPosition(p, tableType);
    +        /* Note: overwriting => favors positions end of dictionary */
    +        LZ4_putIndexOnHash(idx32, h, dict->hashTable, tableType);
    +        p+=3; idx32+=3;
    +    }
    +
    +    if (_ld == _ld_slow) {
    +        /* Fill hash table with additional references, to improve compression capability */
    +        p = dict->dictionary;
    +        idx32 = dict->currentOffset - dict->dictSize;
    +        while (p <= dictEnd-HASH_UNIT) {
    +            U32 const h = LZ4_hashPosition(p, tableType);
    +            U32 const limit = dict->currentOffset - 64 KB;
    +            if (LZ4_getIndexOnHash(h, dict->hashTable, tableType) <= limit) {
    +                /* Note: not overwriting => favors positions beginning of dictionary */
    +                LZ4_putIndexOnHash(idx32, h, dict->hashTable, tableType);
    +            }
    +            p++; idx32++;
    +        }
         }
     
         return (int)dict->dictSize;
     }
     
    +int LZ4_loadDict(LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize)
    +{
    +    return LZ4_loadDict_internal(LZ4_dict, dictionary, dictSize, _ld_fast);
    +}
    +
    +int LZ4_loadDictSlow(LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize)
    +{
    +    return LZ4_loadDict_internal(LZ4_dict, dictionary, dictSize, _ld_slow);
    +}
    +
     void LZ4_attach_dictionary(LZ4_stream_t* workingStream, const LZ4_stream_t* dictionaryStream)
     {
         const LZ4_stream_t_internal* dictCtx = (dictionaryStream == NULL) ? NULL :
    @@ -1711,7 +1786,7 @@ int LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream,
     /* Hidden debug function, to force-test external dictionary mode */
     int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int srcSize)
     {
    -    LZ4_stream_t_internal* streamPtr = &LZ4_dict->internal_donotuse;
    +    LZ4_stream_t_internal* const streamPtr = &LZ4_dict->internal_donotuse;
         int result;
     
         LZ4_renormDictT(streamPtr, srcSize);
    @@ -1774,7 +1849,7 @@ typedef enum { decode_full_block = 0, partial_decode = 1 } earlyEnd_directive;
      * does not know end of input
      * presumes input is well formed
      * note : will consume at least one byte */
    -size_t read_long_length_no_check(const BYTE** pp)
    +static size_t read_long_length_no_check(const BYTE** pp)
     {
         size_t b, l = 0;
         do { b = **pp; (*pp)++; l += b; } while (b==255);
    @@ -1911,6 +1986,17 @@ read_variable_length(const BYTE** ip, const BYTE* ilimit,
         if (initial_check && unlikely((*ip) >= ilimit)) {    /* read limit reached */
             return rvl_error;
         }
    +    s = **ip;
    +    (*ip)++;
    +    length += s;
    +    if (unlikely((*ip) > ilimit)) {    /* read limit reached */
    +        return rvl_error;
    +    }
    +    /* accumulator overflow detection (32-bit mode only) */
    +    if ((sizeof(length) < 8) && unlikely(length > ((Rvl_t)(-1)/2)) ) {
    +        return rvl_error;
    +    }
    +    if (likely(s != 255)) return length;
         do {
             s = **ip;
             (*ip)++;
    @@ -1919,10 +2005,10 @@ read_variable_length(const BYTE** ip, const BYTE* ilimit,
                 return rvl_error;
             }
             /* accumulator overflow detection (32-bit mode only) */
    -        if ((sizeof(length)<8) && unlikely(length > ((Rvl_t)(-1)/2)) ) {
    +        if ((sizeof(length) < 8) && unlikely(length > ((Rvl_t)(-1)/2)) ) {
                 return rvl_error;
             }
    -    } while (s==255);
    +    } while (s == 255);
     
         return length;
     }
    @@ -1988,63 +2074,73 @@ LZ4_decompress_generic(
          * note : fast loop may show a regression for some client arm chips. */
     #if LZ4_FAST_DEC_LOOP
             if ((oend - op) < FASTLOOP_SAFE_DISTANCE) {
    -            DEBUGLOG(6, "skip fast decode loop");
    +            DEBUGLOG(6, "move to safe decode loop");
                 goto safe_decode;
             }
     
             /* Fast loop : decode sequences as long as output < oend-FASTLOOP_SAFE_DISTANCE */
    +        DEBUGLOG(6, "using fast decode loop");
             while (1) {
                 /* Main fastloop assertion: We can always wildcopy FASTLOOP_SAFE_DISTANCE */
                 assert(oend - op >= FASTLOOP_SAFE_DISTANCE);
                 assert(ip < iend);
                 token = *ip++;
                 length = token >> ML_BITS;  /* literal length */
    +            DEBUGLOG(7, "blockPos%6u: litLength token = %u", (unsigned)(op-(BYTE*)dst), (unsigned)length);
     
                 /* decode literal length */
                 if (length == RUN_MASK) {
                     size_t const addl = read_variable_length(&ip, iend-RUN_MASK, 1);
    -                if (addl == rvl_error) { goto _output_error; }
    +                if (addl == rvl_error) {
    +                    DEBUGLOG(6, "error reading long literal length");
    +                    goto _output_error;
    +                }
                     length += addl;
                     if (unlikely((uptrval)(op)+length<(uptrval)(op))) { goto _output_error; } /* overflow detection */
                     if (unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */
     
                     /* copy literals */
    -                cpy = op+length;
                     LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH);
    -                if ((cpy>oend-32) || (ip+length>iend-32)) { goto safe_literal_copy; }
    -                LZ4_wildCopy32(op, ip, cpy);
    -                ip += length; op = cpy;
    -            } else {
    -                cpy = op+length;
    -                DEBUGLOG(7, "copy %u bytes in a 16-bytes stripe", (unsigned)length);
    +                if ((op+length>oend-32) || (ip+length>iend-32)) { goto safe_literal_copy; }
    +                LZ4_wildCopy32(op, ip, op+length);
    +                ip += length; op += length;
    +            } else if (ip <= iend-(16 + 1/*max lit + offset + nextToken*/)) {
                     /* We don't need to check oend, since we check it once for each loop below */
    -                if (ip > iend-(16 + 1/*max lit + offset + nextToken*/)) { goto safe_literal_copy; }
    +                DEBUGLOG(7, "copy %u bytes in a 16-bytes stripe", (unsigned)length);
                     /* Literals can only be <= 14, but hope compilers optimize better when copy by a register size */
                     LZ4_memcpy(op, ip, 16);
    -                ip += length; op = cpy;
    +                ip += length; op += length;
    +            } else {
    +                goto safe_literal_copy;
                 }
     
                 /* get offset */
                 offset = LZ4_readLE16(ip); ip+=2;
    +            DEBUGLOG(6, "blockPos%6u: offset = %u", (unsigned)(op-(BYTE*)dst), (unsigned)offset);
                 match = op - offset;
                 assert(match <= op);  /* overflow check */
     
                 /* get matchlength */
                 length = token & ML_MASK;
    +            DEBUGLOG(7, "  match length token = %u (len==%u)", (unsigned)length, (unsigned)length+MINMATCH);
     
                 if (length == ML_MASK) {
                     size_t const addl = read_variable_length(&ip, iend - LASTLITERALS + 1, 0);
    -                if (addl == rvl_error) { goto _output_error; }
    +                if (addl == rvl_error) {
    +                    DEBUGLOG(5, "error reading long match length");
    +                    goto _output_error;
    +                }
                     length += addl;
                     length += MINMATCH;
    +                DEBUGLOG(7, "  long match length == %u", (unsigned)length);
                     if (unlikely((uptrval)(op)+length<(uptrval)op)) { goto _output_error; } /* overflow detection */
    -                if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) { goto _output_error; } /* Error : offset outside buffers */
                     if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) {
                         goto safe_match_copy;
                     }
                 } else {
                     length += MINMATCH;
                     if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) {
    +                    DEBUGLOG(7, "moving to safe_match_copy (ml==%u)", (unsigned)length);
                         goto safe_match_copy;
                     }
     
    @@ -2062,7 +2158,10 @@ LZ4_decompress_generic(
                             continue;
                 }   }   }
     
    -            if (checkOffset && (unlikely(match + dictSize < lowPrefix))) { goto _output_error; } /* Error : offset outside buffers */
    +            if ( checkOffset && (unlikely(match + dictSize < lowPrefix)) ) {
    +                DEBUGLOG(5, "Error : pos=%zi, offset=%zi => outside buffers", op-lowPrefix, op-match);
    +                goto _output_error;
    +            }
                 /* match starting within external dictionary */
                 if ((dict==usingExtDict) && (match < lowPrefix)) {
                     assert(dictEnd != NULL);
    @@ -2071,7 +2170,8 @@ LZ4_decompress_generic(
                             DEBUGLOG(7, "partialDecoding: dictionary match, close to dstEnd");
                             length = MIN(length, (size_t)(oend-op));
                         } else {
    -                        goto _output_error;  /* end-of-block condition violated */
    +                        DEBUGLOG(6, "end-of-block condition violated")
    +                        goto _output_error;
                     }   }
     
                     if (length <= (size_t)(lowPrefix-match)) {
    @@ -2111,10 +2211,12 @@ LZ4_decompress_generic(
     #endif
     
             /* Main Loop : decode remaining sequences where output < FASTLOOP_SAFE_DISTANCE */
    +        DEBUGLOG(6, "using safe decode loop");
             while (1) {
                 assert(ip < iend);
                 token = *ip++;
                 length = token >> ML_BITS;  /* literal length */
    +            DEBUGLOG(7, "blockPos%6u: litLength token = %u", (unsigned)(op-(BYTE*)dst), (unsigned)length);
     
                 /* A two-stage shortcut for the most common case:
                  * 1) If the literal length is 0..14, and there is enough space,
    @@ -2135,6 +2237,7 @@ LZ4_decompress_generic(
                     /* The second stage: prepare for match copying, decode full info.
                      * If it doesn't work out, the info won't be wasted. */
                     length = token & ML_MASK; /* match length */
    +                DEBUGLOG(7, "blockPos%6u: matchLength token = %u (len=%u)", (unsigned)(op-(BYTE*)dst), (unsigned)length, (unsigned)length + 4);
                     offset = LZ4_readLE16(ip); ip += 2;
                     match = op - offset;
                     assert(match <= op); /* check overflow */
    @@ -2166,11 +2269,12 @@ LZ4_decompress_generic(
                     if (unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */
                 }
     
    -            /* copy literals */
    -            cpy = op+length;
     #if LZ4_FAST_DEC_LOOP
             safe_literal_copy:
     #endif
    +            /* copy literals */
    +            cpy = op+length;
    +
                 LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH);
                 if ((cpy>oend-MFLIMIT) || (ip+length>iend-(2+1+LASTLITERALS))) {
                     /* We've either hit the input parsing restriction or the output parsing restriction.
    @@ -2206,9 +2310,10 @@ LZ4_decompress_generic(
                           * so check that we exactly consume the input and don't overrun the output buffer.
                           */
                         if ((ip+length != iend) || (cpy > oend)) {
    -                        DEBUGLOG(6, "should have been last run of literals")
    -                        DEBUGLOG(6, "ip(%p) + length(%i) = %p != iend (%p)", ip, (int)length, ip+length, iend);
    -                        DEBUGLOG(6, "or cpy(%p) > oend(%p)", cpy, oend);
    +                        DEBUGLOG(5, "should have been last run of literals")
    +                        DEBUGLOG(5, "ip(%p) + length(%i) = %p != iend (%p)", ip, (int)length, ip+length, iend);
    +                        DEBUGLOG(5, "or cpy(%p) > (oend-MFLIMIT)(%p)", cpy, oend-MFLIMIT);
    +                        DEBUGLOG(5, "after writing %u bytes / %i bytes available", (unsigned)(op-(BYTE*)dst), outputSize);
                             goto _output_error;
                         }
                     }
    @@ -2234,6 +2339,7 @@ LZ4_decompress_generic(
     
                 /* get matchlength */
                 length = token & ML_MASK;
    +            DEBUGLOG(7, "blockPos%6u: matchLength token = %u", (unsigned)(op-(BYTE*)dst), (unsigned)length);
     
         _copy_match:
                 if (length == ML_MASK) {
    @@ -2323,7 +2429,7 @@ LZ4_decompress_generic(
                     while (op < cpy) { *op++ = *match++; }
                 } else {
                     LZ4_memcpy(op, match, 8);
    -                if (length > 16)  { LZ4_wildCopy8(op+8, match+8, cpy); }
    +                if (length > 16) { LZ4_wildCopy8(op+8, match+8, cpy); }
                 }
                 op = cpy;   /* wildcopy correction */
             }
    @@ -2418,6 +2524,7 @@ int LZ4_decompress_safe_forceExtDict(const char* source, char* dest,
                                          int compressedSize, int maxOutputSize,
                                          const void* dictStart, size_t dictSize)
     {
    +    DEBUGLOG(5, "LZ4_decompress_safe_forceExtDict");
         return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize,
                                       decode_full_block, usingExtDict,
                                       (BYTE*)dest, (const BYTE*)dictStart, dictSize);
    diff --git a/lib/lz4.h b/lib/lz4.h
    index 491c6087c417754ff4662a02c1bfc9ddc13d43e1..80e3e5ca04d22db9ec4980dfc43672a13984aa15 100644
    --- a/lib/lz4.h
    +++ b/lib/lz4.h
    @@ -1,7 +1,7 @@
     /*
      *  LZ4 - Fast LZ compression algorithm
      *  Header File
    - *  Copyright (C) 2011-2020, Yann Collet.
    + *  Copyright (C) 2011-2023, Yann Collet.
     
        BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
     
    @@ -129,8 +129,8 @@ extern "C" {
     
     /*------   Version   ------*/
     #define LZ4_VERSION_MAJOR    1    /* for breaking interface changes  */
    -#define LZ4_VERSION_MINOR    9    /* for new (non-breaking) interface capabilities */
    -#define LZ4_VERSION_RELEASE  4    /* for tweaks, bug-fixes, or development */
    +#define LZ4_VERSION_MINOR   10    /* for new (non-breaking) interface capabilities */
    +#define LZ4_VERSION_RELEASE  0    /* for tweaks, bug-fixes, or development */
     
     #define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE)
     
    @@ -144,23 +144,25 @@ LZ4LIB_API const char* LZ4_versionString (void);   /**< library version string;
     
     
     /*-************************************
    -*  Tuning parameter
    +*  Tuning memory usage
     **************************************/
    -#define LZ4_MEMORY_USAGE_MIN 10
    -#define LZ4_MEMORY_USAGE_DEFAULT 14
    -#define LZ4_MEMORY_USAGE_MAX 20
    -
     /*!
      * LZ4_MEMORY_USAGE :
    - * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; )
    - * Increasing memory usage improves compression ratio, at the cost of speed.
    + * Can be selected at compile time, by setting LZ4_MEMORY_USAGE.
    + * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB)
    + * Increasing memory usage improves compression ratio, generally at the cost of speed.
      * Reduced memory usage may improve speed at the cost of ratio, thanks to better cache locality.
    - * Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache
    + * Default value is 14, for 16KB, which nicely fits into most L1 caches.
      */
     #ifndef LZ4_MEMORY_USAGE
     # define LZ4_MEMORY_USAGE LZ4_MEMORY_USAGE_DEFAULT
     #endif
     
    +/* These are absolute limits, they should not be changed by users */
    +#define LZ4_MEMORY_USAGE_MIN 10
    +#define LZ4_MEMORY_USAGE_DEFAULT 14
    +#define LZ4_MEMORY_USAGE_MAX 20
    +
     #if (LZ4_MEMORY_USAGE < LZ4_MEMORY_USAGE_MIN)
     #  error "LZ4_MEMORY_USAGE is too small !"
     #endif
    @@ -189,8 +191,9 @@ LZ4LIB_API const char* LZ4_versionString (void);   /**< library version string;
     LZ4LIB_API int LZ4_compress_default(const char* src, char* dst, int srcSize, int dstCapacity);
     
     /*! LZ4_decompress_safe() :
    - *  compressedSize : is the exact complete size of the compressed block.
    - *  dstCapacity : is the size of destination buffer (which must be already allocated), presumed an upper bound of decompressed size.
    + * @compressedSize : is the exact complete size of the compressed block.
    + * @dstCapacity : is the size of destination buffer (which must be already allocated),
    + *                presumed an upper bound of decompressed size.
      * @return : the number of bytes decompressed into destination buffer (necessarily <= dstCapacity)
      *           If destination buffer is not large enough, decoding will stop and output an error code (negative value).
      *           If the source stream is detected malformed, the function will stop decoding and return a negative result.
    @@ -242,20 +245,20 @@ LZ4LIB_API int LZ4_compress_fast (const char* src, char* dst, int srcSize, int d
     LZ4LIB_API int LZ4_sizeofState(void);
     LZ4LIB_API int LZ4_compress_fast_extState (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);
     
    -
     /*! LZ4_compress_destSize() :
      *  Reverse the logic : compresses as much data as possible from 'src' buffer
    - *  into already allocated buffer 'dst', of size >= 'targetDestSize'.
    + *  into already allocated buffer 'dst', of size >= 'dstCapacity'.
      *  This function either compresses the entire 'src' content into 'dst' if it's large enough,
      *  or fill 'dst' buffer completely with as much data as possible from 'src'.
      *  note: acceleration parameter is fixed to "default".
      *
    - * *srcSizePtr : will be modified to indicate how many bytes where read from 'src' to fill 'dst'.
    + * *srcSizePtr : in+out parameter. Initially contains size of input.
    + *               Will be modified to indicate how many bytes where read from 'src' to fill 'dst'.
      *               New value is necessarily <= input value.
    - * @return : Nb bytes written into 'dst' (necessarily <= targetDestSize)
    + * @return : Nb bytes written into 'dst' (necessarily <= dstCapacity)
      *           or 0 if compression fails.
      *
    - * Note : from v1.8.2 to v1.9.1, this function had a bug (fixed un v1.9.2+):
    + * Note : from v1.8.2 to v1.9.1, this function had a bug (fixed in v1.9.2+):
      *        the produced compressed content could, in specific circumstances,
      *        require to be decompressed into a destination buffer larger
      *        by at least 1 byte than the content to decompress.
    @@ -266,8 +269,7 @@ LZ4LIB_API int LZ4_compress_fast_extState (void* state, const char* src, char* d
      *        a dstCapacity which is > decompressedSize, by at least 1 byte.
      *        See https://github.com/lz4/lz4/issues/859 for details
      */
    -LZ4LIB_API int LZ4_compress_destSize (const char* src, char* dst, int* srcSizePtr, int targetDstSize);
    -
    +LZ4LIB_API int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize);
     
     /*! LZ4_decompress_safe_partial() :
      *  Decompress an LZ4 compressed block, of size 'srcSize' at position 'src',
    @@ -311,7 +313,7 @@ LZ4LIB_API int LZ4_decompress_safe_partial (const char* src, char* dst, int srcS
     ***********************************************/
     typedef union LZ4_stream_u LZ4_stream_t;  /* incomplete type (defined later) */
     
    -/**
    +/*!
      Note about RC_INVOKED
     
      - RC_INVOKED is predefined symbol of rc.exe (the resource compiler which is part of MSVC/Visual Studio).
    @@ -361,13 +363,58 @@ LZ4LIB_API void LZ4_resetStream_fast (LZ4_stream_t* streamPtr);
      *  LZ4_loadDict() triggers a reset, so any previous data will be forgotten.
      *  The same dictionary will have to be loaded on decompression side for successful decoding.
      *  Dictionary are useful for better compression of small data (KB range).
    - *  While LZ4 accept any input as dictionary,
    - *  results are generally better when using Zstandard's Dictionary Builder.
    + *  While LZ4 itself accepts any input as dictionary, dictionary efficiency is also a topic.
    + *  When in doubt, employ the Zstandard's Dictionary Builder.
      *  Loading a size of 0 is allowed, and is the same as reset.
    - * @return : loaded dictionary size, in bytes (necessarily <= 64 KB)
    + * @return : loaded dictionary size, in bytes (note: only the last 64 KB are loaded)
      */
     LZ4LIB_API int LZ4_loadDict (LZ4_stream_t* streamPtr, const char* dictionary, int dictSize);
     
    +/*! LZ4_loadDictSlow() : v1.10.0+
    + *  Same as LZ4_loadDict(),
    + *  but uses a bit more cpu to reference the dictionary content more thoroughly.
    + *  This is expected to slightly improve compression ratio.
    + *  The extra-cpu cost is likely worth it if the dictionary is re-used across multiple sessions.
    + * @return : loaded dictionary size, in bytes (note: only the last 64 KB are loaded)
    + */
    +LZ4LIB_API int LZ4_loadDictSlow(LZ4_stream_t* streamPtr, const char* dictionary, int dictSize);
    +
    +/*! LZ4_attach_dictionary() : stable since v1.10.0
    + *
    + *  This allows efficient re-use of a static dictionary multiple times.
    + *
    + *  Rather than re-loading the dictionary buffer into a working context before
    + *  each compression, or copying a pre-loaded dictionary's LZ4_stream_t into a
    + *  working LZ4_stream_t, this function introduces a no-copy setup mechanism,
    + *  in which the working stream references @dictionaryStream in-place.
    + *
    + *  Several assumptions are made about the state of @dictionaryStream.
    + *  Currently, only states which have been prepared by LZ4_loadDict() or
    + *  LZ4_loadDictSlow() should be expected to work.
    + *
    + *  Alternatively, the provided @dictionaryStream may be NULL,
    + *  in which case any existing dictionary stream is unset.
    + *
    + *  If a dictionary is provided, it replaces any pre-existing stream history.
    + *  The dictionary contents are the only history that can be referenced and
    + *  logically immediately precede the data compressed in the first subsequent
    + *  compression call.
    + *
    + *  The dictionary will only remain attached to the working stream through the
    + *  first compression call, at the end of which it is cleared.
    + * @dictionaryStream stream (and source buffer) must remain in-place / accessible / unchanged
    + *  through the completion of the compression session.
    + *
    + *  Note: there is no equivalent LZ4_attach_*() method on the decompression side
    + *  because there is no initialization cost, hence no need to share the cost across multiple sessions.
    + *  To decompress LZ4 blocks using dictionary, attached or not,
    + *  just employ the regular LZ4_setStreamDecode() for streaming,
    + *  or the stateless LZ4_decompress_safe_usingDict() for one-shot decompression.
    + */
    +LZ4LIB_API void
    +LZ4_attach_dictionary(LZ4_stream_t* workingStream,
    +                const LZ4_stream_t* dictionaryStream);
    +
     /*! LZ4_compress_fast_continue() :
      *  Compress 'src' content using data from previously compressed blocks, for better compression ratio.
      * 'dst' buffer must be already allocated.
    @@ -443,11 +490,24 @@ LZ4LIB_API int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const
     LZ4LIB_API int LZ4_decoderRingBufferSize(int maxBlockSize);
     #define LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize) (65536 + 14 + (maxBlockSize))  /* for static allocation; maxBlockSize presumed valid */
     
    -/*! LZ4_decompress_*_continue() :
    - *  These decoding functions allow decompression of consecutive blocks in "streaming" mode.
    - *  A block is an unsplittable entity, it must be presented entirely to a decompression function.
    - *  Decompression functions only accepts one block at a time.
    - *  The last 64KB of previously decoded data *must* remain available and unmodified at the memory position where they were decoded.
    +/*! LZ4_decompress_safe_continue() :
    + *  This decoding function allows decompression of consecutive blocks in "streaming" mode.
    + *  The difference with the usual independent blocks is that
    + *  new blocks are allowed to find references into former blocks.
    + *  A block is an unsplittable entity, and must be presented entirely to the decompression function.
    + *  LZ4_decompress_safe_continue() only accepts one block at a time.
    + *  It's modeled after `LZ4_decompress_safe()` and behaves similarly.
    + *
    + * @LZ4_streamDecode : decompression state, tracking the position in memory of past data
    + * @compressedSize : exact complete size of one compressed block.
    + * @dstCapacity : size of destination buffer (which must be already allocated),
    + *                must be an upper bound of decompressed size.
    + * @return : number of bytes decompressed into destination buffer (necessarily <= dstCapacity)
    + *           If destination buffer is not large enough, decoding will stop and output an error code (negative value).
    + *           If the source stream is detected malformed, the function will stop decoding and return a negative result.
    + *
    + *  The last 64KB of previously decoded data *must* remain available and unmodified
    + *  at the memory position where they were previously decoded.
      *  If less than 64KB of data has been decoded, all the data must be present.
      *
      *  Special : if decompression side sets a ring buffer, it must respect one of the following conditions :
    @@ -474,10 +534,10 @@ LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode,
                             int srcSize, int dstCapacity);
     
     
    -/*! LZ4_decompress_*_usingDict() :
    - *  These decoding functions work the same as
    - *  a combination of LZ4_setStreamDecode() followed by LZ4_decompress_*_continue()
    - *  They are stand-alone, and don't need an LZ4_streamDecode_t structure.
    +/*! LZ4_decompress_safe_usingDict() :
    + *  Works the same as
    + *  a combination of LZ4_setStreamDecode() followed by LZ4_decompress_safe_continue()
    + *  However, it's stateless: it doesn't need any LZ4_streamDecode_t state.
      *  Dictionary is presumed stable : it must remain accessible and unmodified during decompression.
      *  Performance tip : Decompression speed can be substantially increased
      *                    when dst == dictStart + dictSize.
    @@ -487,6 +547,12 @@ LZ4_decompress_safe_usingDict(const char* src, char* dst,
                                   int srcSize, int dstCapacity,
                                   const char* dictStart, int dictSize);
     
    +/*! LZ4_decompress_safe_partial_usingDict() :
    + *  Behaves the same as LZ4_decompress_safe_partial()
    + *  with the added ability to specify a memory segment for past data.
    + *  Performance tip : Decompression speed can be substantially increased
    + *                    when dst == dictStart + dictSize.
    + */
     LZ4LIB_API int
     LZ4_decompress_safe_partial_usingDict(const char* src, char* dst,
                                           int compressedSize,
    @@ -526,9 +592,9 @@ LZ4_decompress_safe_partial_usingDict(const char* src, char* dst,
     #define LZ4_STATIC_3504398509
     
     #ifdef LZ4_PUBLISH_STATIC_FUNCTIONS
    -#define LZ4LIB_STATIC_API LZ4LIB_API
    +# define LZ4LIB_STATIC_API LZ4LIB_API
     #else
    -#define LZ4LIB_STATIC_API
    +# define LZ4LIB_STATIC_API
     #endif
     
     
    @@ -544,36 +610,11 @@ LZ4_decompress_safe_partial_usingDict(const char* src, char* dst,
      */
     LZ4LIB_STATIC_API int LZ4_compress_fast_extState_fastReset (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);
     
    -/*! LZ4_attach_dictionary() :
    - *  This is an experimental API that allows
    - *  efficient use of a static dictionary many times.
    - *
    - *  Rather than re-loading the dictionary buffer into a working context before
    - *  each compression, or copying a pre-loaded dictionary's LZ4_stream_t into a
    - *  working LZ4_stream_t, this function introduces a no-copy setup mechanism,
    - *  in which the working stream references the dictionary stream in-place.
    - *
    - *  Several assumptions are made about the state of the dictionary stream.
    - *  Currently, only streams which have been prepared by LZ4_loadDict() should
    - *  be expected to work.
    - *
    - *  Alternatively, the provided dictionaryStream may be NULL,
    - *  in which case any existing dictionary stream is unset.
    - *
    - *  If a dictionary is provided, it replaces any pre-existing stream history.
    - *  The dictionary contents are the only history that can be referenced and
    - *  logically immediately precede the data compressed in the first subsequent
    - *  compression call.
    - *
    - *  The dictionary will only remain attached to the working stream through the
    - *  first compression call, at the end of which it is cleared. The dictionary
    - *  stream (and source buffer) must remain in-place / accessible / unchanged
    - *  through the completion of the first compression call on the stream.
    +/*! LZ4_compress_destSize_extState() : introduced in v1.10.0
    + *  Same as LZ4_compress_destSize(), but using an externally allocated state.
    + *  Also: exposes @acceleration
      */
    -LZ4LIB_STATIC_API void
    -LZ4_attach_dictionary(LZ4_stream_t* workingStream,
    -                const LZ4_stream_t* dictionaryStream);
    -
    +int LZ4_compress_destSize_extState(void* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize, int acceleration);
     
     /*! In-place compression and decompression
      *
    @@ -685,7 +726,7 @@ struct LZ4_stream_t_internal {
         /* Implicit padding to ensure structure is aligned */
     };
     
    -#define LZ4_STREAM_MINSIZE  ((1UL << LZ4_MEMORY_USAGE) + 32)  /* static size, for inter-version compatibility */
    +#define LZ4_STREAM_MINSIZE  ((1UL << (LZ4_MEMORY_USAGE)) + 32)  /* static size, for inter-version compatibility */
     union LZ4_stream_u {
         char minStateSize[LZ4_STREAM_MINSIZE];
         LZ4_stream_t_internal internal_donotuse;
    @@ -706,7 +747,7 @@ union LZ4_stream_u {
      *  Note2: An LZ4_stream_t structure guarantees correct alignment and size.
      *  Note3: Before v1.9.0, use LZ4_resetStream() instead
     **/
    -LZ4LIB_API LZ4_stream_t* LZ4_initStream (void* buffer, size_t size);
    +LZ4LIB_API LZ4_stream_t* LZ4_initStream (void* stateBuffer, size_t size);
     
     
     /*! LZ4_streamDecode_t :
    @@ -818,11 +859,12 @@ LZ4_DEPRECATED("use LZ4_decompress_fast_usingDict() instead") LZ4LIB_API int LZ4
      *         But they may happen if input data is invalid (error or intentional tampering).
      *         As a consequence, use these functions in trusted environments with trusted data **only**.
      */
    -LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe() instead")
    +LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_partial() instead")
     LZ4LIB_API int LZ4_decompress_fast (const char* src, char* dst, int originalSize);
    -LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_continue() instead")
    +LZ4_DEPRECATED("This function is deprecated and unsafe. Consider migrating towards LZ4_decompress_safe_continue() instead. "
    +               "Note that the contract will change (requires block's compressed size, instead of decompressed size)")
     LZ4LIB_API int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, int originalSize);
    -LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_usingDict() instead")
    +LZ4_DEPRECATED("This function is deprecated and unsafe. Consider using LZ4_decompress_safe_partial_usingDict() instead")
     LZ4LIB_API int LZ4_decompress_fast_usingDict (const char* src, char* dst, int originalSize, const char* dictStart, int dictSize);
     
     /*! LZ4_resetStream() :
    diff --git a/lib/lz4file.c b/lib/lz4file.c
    index eaf9b1704d2bb6673d8661dcef4130bcf94b1790..a4197ea80dd4b0c30d9f96e0b81bcd58eed1b14a 100644
    --- a/lib/lz4file.c
    +++ b/lib/lz4file.c
    @@ -31,11 +31,21 @@
      * - LZ4 homepage : http://www.lz4.org
      * - LZ4 source repository : https://github.com/lz4/lz4
      */
    -#include 
    +#include   /* malloc, free */
     #include 
    +#include 
     #include "lz4.h"
     #include "lz4file.h"
     
    +static LZ4F_errorCode_t returnErrorCode(LZ4F_errorCodes code)
    +{
    +    return (LZ4F_errorCode_t)-(ptrdiff_t)code;
    +}
    +#undef RETURN_ERROR
    +#define RETURN_ERROR(e) return returnErrorCode(LZ4F_ERROR_ ## e)
    +
    +/* =====   read API   ===== */
    +
     struct LZ4_readFile_s {
       LZ4F_dctx* dctxPtr;
       FILE* fp;
    @@ -45,76 +55,80 @@ struct LZ4_readFile_s {
       size_t srcBufMaxSize;
     };
     
    -struct LZ4_writeFile_s {
    -  LZ4F_cctx* cctxPtr;
    -  FILE* fp;
    -  LZ4_byte* dstBuf;
    -  size_t maxWriteSize;
    -  size_t dstBufMaxSize;
    -  LZ4F_errorCode_t errCode;
    -};
    +static void LZ4F_freeReadFile(LZ4_readFile_t* lz4fRead)
    +{
    +  if (lz4fRead==NULL) return;
    +  LZ4F_freeDecompressionContext(lz4fRead->dctxPtr);
    +  free(lz4fRead->srcBuf);
    +  free(lz4fRead);
    +}
    +
    +static void LZ4F_freeAndNullReadFile(LZ4_readFile_t** statePtr)
    +{
    +  assert(statePtr != NULL);
    +  LZ4F_freeReadFile(*statePtr);
    +  *statePtr = NULL;
    +}
     
     LZ4F_errorCode_t LZ4F_readOpen(LZ4_readFile_t** lz4fRead, FILE* fp)
     {
       char buf[LZ4F_HEADER_SIZE_MAX];
       size_t consumedSize;
       LZ4F_errorCode_t ret;
    -  LZ4F_frameInfo_t info;
     
       if (fp == NULL || lz4fRead == NULL) {
    -    return -LZ4F_ERROR_GENERIC;
    +    RETURN_ERROR(parameter_null);
       }
     
       *lz4fRead = (LZ4_readFile_t*)calloc(1, sizeof(LZ4_readFile_t));
       if (*lz4fRead == NULL) {
    -    return -LZ4F_ERROR_allocation_failed;
    +    RETURN_ERROR(allocation_failed);
       }
     
    -  ret = LZ4F_createDecompressionContext(&(*lz4fRead)->dctxPtr, LZ4F_getVersion());
    +  ret = LZ4F_createDecompressionContext(&(*lz4fRead)->dctxPtr, LZ4F_VERSION);
       if (LZ4F_isError(ret)) {
    -    free(*lz4fRead);
    +    LZ4F_freeAndNullReadFile(lz4fRead);
         return ret;
       }
     
       (*lz4fRead)->fp = fp;
       consumedSize = fread(buf, 1, sizeof(buf), (*lz4fRead)->fp);
       if (consumedSize != sizeof(buf)) {
    -    free(*lz4fRead);
    -    return -LZ4F_ERROR_GENERIC;
    +    LZ4F_freeAndNullReadFile(lz4fRead);
    +    RETURN_ERROR(io_read);
       }
     
    -  ret = LZ4F_getFrameInfo((*lz4fRead)->dctxPtr, &info, buf, &consumedSize);
    -  if (LZ4F_isError(ret)) {
    -      LZ4F_freeDecompressionContext((*lz4fRead)->dctxPtr);
    -      free(*lz4fRead);
    -      return ret;
    +  { LZ4F_frameInfo_t info;
    +    LZ4F_errorCode_t const r = LZ4F_getFrameInfo((*lz4fRead)->dctxPtr, &info, buf, &consumedSize);
    +    if (LZ4F_isError(r)) {
    +      LZ4F_freeAndNullReadFile(lz4fRead);
    +      return r;
         }
     
    -  switch (info.blockSizeID) {
    -    case LZ4F_default :
    -    case LZ4F_max64KB :
    -      (*lz4fRead)->srcBufMaxSize = 64 * 1024;
    -      break;
    -    case LZ4F_max256KB:
    -      (*lz4fRead)->srcBufMaxSize = 256 * 1024;
    -      break;
    -    case LZ4F_max1MB:
    -      (*lz4fRead)->srcBufMaxSize = 1 * 1024 * 1024;
    -      break;
    -    case LZ4F_max4MB:
    -      (*lz4fRead)->srcBufMaxSize = 4 * 1024 * 1024;
    -      break;
    -    default:
    -      LZ4F_freeDecompressionContext((*lz4fRead)->dctxPtr);
    -      free(*lz4fRead);
    -      return -LZ4F_ERROR_maxBlockSize_invalid;
    +    switch (info.blockSizeID) {
    +      case LZ4F_default :
    +      case LZ4F_max64KB :
    +        (*lz4fRead)->srcBufMaxSize = 64 * 1024;
    +        break;
    +      case LZ4F_max256KB:
    +        (*lz4fRead)->srcBufMaxSize = 256 * 1024;
    +        break;
    +      case LZ4F_max1MB:
    +        (*lz4fRead)->srcBufMaxSize = 1 * 1024 * 1024;
    +        break;
    +      case LZ4F_max4MB:
    +        (*lz4fRead)->srcBufMaxSize = 4 * 1024 * 1024;
    +        break;
    +      default:
    +        LZ4F_freeAndNullReadFile(lz4fRead);
    +        RETURN_ERROR(maxBlockSize_invalid);
    +    }
       }
     
       (*lz4fRead)->srcBuf = (LZ4_byte*)malloc((*lz4fRead)->srcBufMaxSize);
       if ((*lz4fRead)->srcBuf == NULL) {
    -    LZ4F_freeDecompressionContext((*lz4fRead)->dctxPtr);
    -    free(lz4fRead);
    -    return -LZ4F_ERROR_allocation_failed;
    +    LZ4F_freeAndNullReadFile(lz4fRead);
    +    RETURN_ERROR(allocation_failed);
       }
     
       (*lz4fRead)->srcBufSize = sizeof(buf) - consumedSize;
    @@ -129,7 +143,7 @@ size_t LZ4F_read(LZ4_readFile_t* lz4fRead, void* buf, size_t size)
       size_t next = 0;
     
       if (lz4fRead == NULL || buf == NULL)
    -    return -LZ4F_ERROR_GENERIC;
    +    RETURN_ERROR(parameter_null);
     
       while (next < size) {
         size_t srcsize = lz4fRead->srcBufSize - lz4fRead->srcBufNext;
    @@ -142,12 +156,10 @@ size_t LZ4F_read(LZ4_readFile_t* lz4fRead, void* buf, size_t size)
             lz4fRead->srcBufSize = ret;
             srcsize = lz4fRead->srcBufSize;
             lz4fRead->srcBufNext = 0;
    -      }
    -      else if (ret == 0) {
    +      } else if (ret == 0) {
             break;
    -      }
    -      else {
    -        return -LZ4F_ERROR_GENERIC;
    +      } else {
    +        RETURN_ERROR(io_read);
           }
         }
     
    @@ -171,24 +183,48 @@ size_t LZ4F_read(LZ4_readFile_t* lz4fRead, void* buf, size_t size)
     LZ4F_errorCode_t LZ4F_readClose(LZ4_readFile_t* lz4fRead)
     {
       if (lz4fRead == NULL)
    -    return -LZ4F_ERROR_GENERIC;
    -  LZ4F_freeDecompressionContext(lz4fRead->dctxPtr);
    -  free(lz4fRead->srcBuf);
    -  free(lz4fRead);
    +    RETURN_ERROR(parameter_null);
    +  LZ4F_freeReadFile(lz4fRead);
       return LZ4F_OK_NoError;
     }
     
    +/* =====   write API   ===== */
    +
    +struct LZ4_writeFile_s {
    +  LZ4F_cctx* cctxPtr;
    +  FILE* fp;
    +  LZ4_byte* dstBuf;
    +  size_t maxWriteSize;
    +  size_t dstBufMaxSize;
    +  LZ4F_errorCode_t errCode;
    +};
    +
    +static void LZ4F_freeWriteFile(LZ4_writeFile_t* state)
    +{
    +  if (state == NULL) return;
    +  LZ4F_freeCompressionContext(state->cctxPtr);
    +  free(state->dstBuf);
    +  free(state);
    +}
    +
    +static void LZ4F_freeAndNullWriteFile(LZ4_writeFile_t** statePtr)
    +{
    +  assert(statePtr != NULL);
    +  LZ4F_freeWriteFile(*statePtr);
    +  *statePtr = NULL;
    +}
    +
     LZ4F_errorCode_t LZ4F_writeOpen(LZ4_writeFile_t** lz4fWrite, FILE* fp, const LZ4F_preferences_t* prefsPtr)
     {
       LZ4_byte buf[LZ4F_HEADER_SIZE_MAX];
       size_t ret;
     
       if (fp == NULL || lz4fWrite == NULL)
    -    return -LZ4F_ERROR_GENERIC;
    +    RETURN_ERROR(parameter_null);
     
    -  *lz4fWrite = (LZ4_writeFile_t*)malloc(sizeof(LZ4_writeFile_t));
    +  *lz4fWrite = (LZ4_writeFile_t*)calloc(1, sizeof(LZ4_writeFile_t));
       if (*lz4fWrite == NULL) {
    -    return -LZ4F_ERROR_allocation_failed;
    +    RETURN_ERROR(allocation_failed);
       }
       if (prefsPtr != NULL) {
         switch (prefsPtr->frameInfo.blockSizeID) {
    @@ -206,8 +242,8 @@ LZ4F_errorCode_t LZ4F_writeOpen(LZ4_writeFile_t** lz4fWrite, FILE* fp, const LZ4
             (*lz4fWrite)->maxWriteSize = 4 * 1024 * 1024;
             break;
           default:
    -        free(lz4fWrite);
    -        return -LZ4F_ERROR_maxBlockSize_invalid;
    +        LZ4F_freeAndNullWriteFile(lz4fWrite);
    +        RETURN_ERROR(maxBlockSize_invalid);
           }
         } else {
           (*lz4fWrite)->maxWriteSize = 64 * 1024;
    @@ -216,30 +252,25 @@ LZ4F_errorCode_t LZ4F_writeOpen(LZ4_writeFile_t** lz4fWrite, FILE* fp, const LZ4
       (*lz4fWrite)->dstBufMaxSize = LZ4F_compressBound((*lz4fWrite)->maxWriteSize, prefsPtr);
       (*lz4fWrite)->dstBuf = (LZ4_byte*)malloc((*lz4fWrite)->dstBufMaxSize);
       if ((*lz4fWrite)->dstBuf == NULL) {
    -    free(*lz4fWrite);
    -    return -LZ4F_ERROR_allocation_failed;
    +    LZ4F_freeAndNullWriteFile(lz4fWrite);
    +    RETURN_ERROR(allocation_failed);
       }
     
    -  ret = LZ4F_createCompressionContext(&(*lz4fWrite)->cctxPtr, LZ4F_getVersion());
    +  ret = LZ4F_createCompressionContext(&(*lz4fWrite)->cctxPtr, LZ4F_VERSION);
       if (LZ4F_isError(ret)) {
    -      free((*lz4fWrite)->dstBuf);
    -      free(*lz4fWrite);
    +      LZ4F_freeAndNullWriteFile(lz4fWrite);
           return ret;
       }
     
       ret = LZ4F_compressBegin((*lz4fWrite)->cctxPtr, buf, LZ4F_HEADER_SIZE_MAX, prefsPtr);
       if (LZ4F_isError(ret)) {
    -      LZ4F_freeCompressionContext((*lz4fWrite)->cctxPtr);
    -      free((*lz4fWrite)->dstBuf);
    -      free(*lz4fWrite);
    +      LZ4F_freeAndNullWriteFile(lz4fWrite);
           return ret;
       }
     
       if (ret != fwrite(buf, 1, ret, fp)) {
    -    LZ4F_freeCompressionContext((*lz4fWrite)->cctxPtr);
    -    free((*lz4fWrite)->dstBuf);
    -    free(*lz4fWrite);
    -    return -LZ4F_ERROR_GENERIC;
    +    LZ4F_freeAndNullWriteFile(lz4fWrite);
    +    RETURN_ERROR(io_write);
       }
     
       (*lz4fWrite)->fp = fp;
    @@ -247,15 +278,15 @@ LZ4F_errorCode_t LZ4F_writeOpen(LZ4_writeFile_t** lz4fWrite, FILE* fp, const LZ4
       return LZ4F_OK_NoError;
     }
     
    -size_t LZ4F_write(LZ4_writeFile_t* lz4fWrite, void* buf, size_t size)
    +size_t LZ4F_write(LZ4_writeFile_t* lz4fWrite, const void* buf, size_t size)
     {
    -  LZ4_byte* p = (LZ4_byte*)buf;
    +  const LZ4_byte* p = (const LZ4_byte*)buf;
       size_t remain = size;
       size_t chunk;
       size_t ret;
     
       if (lz4fWrite == NULL || buf == NULL)
    -    return -LZ4F_ERROR_GENERIC;
    +    RETURN_ERROR(parameter_null);
       while (remain) {
         if (remain > lz4fWrite->maxWriteSize)
           chunk = lz4fWrite->maxWriteSize;
    @@ -271,9 +302,9 @@ size_t LZ4F_write(LZ4_writeFile_t* lz4fWrite, void* buf, size_t size)
           return ret;
         }
     
    -    if(ret != fwrite(lz4fWrite->dstBuf, 1, ret, lz4fWrite->fp)) {
    -      lz4fWrite->errCode = -LZ4F_ERROR_GENERIC;
    -      return -LZ4F_ERROR_GENERIC;
    +    if (ret != fwrite(lz4fWrite->dstBuf, 1, ret, lz4fWrite->fp)) {
    +      lz4fWrite->errCode = returnErrorCode(LZ4F_ERROR_io_write);
    +      RETURN_ERROR(io_write);
         }
     
         p += chunk;
    @@ -287,8 +318,9 @@ LZ4F_errorCode_t LZ4F_writeClose(LZ4_writeFile_t* lz4fWrite)
     {
       LZ4F_errorCode_t ret = LZ4F_OK_NoError;
     
    -  if (lz4fWrite == NULL)
    -    return -LZ4F_ERROR_GENERIC;
    +  if (lz4fWrite == NULL) {
    +    RETURN_ERROR(parameter_null);
    +  }
     
       if (lz4fWrite->errCode == LZ4F_OK_NoError) {
         ret =  LZ4F_compressEnd(lz4fWrite->cctxPtr,
    @@ -299,13 +331,11 @@ LZ4F_errorCode_t LZ4F_writeClose(LZ4_writeFile_t* lz4fWrite)
         }
     
         if (ret != fwrite(lz4fWrite->dstBuf, 1, ret, lz4fWrite->fp)) {
    -      ret = -LZ4F_ERROR_GENERIC;
    +      ret = returnErrorCode(LZ4F_ERROR_io_write);
         }
       }
     
     out:
    -  LZ4F_freeCompressionContext(lz4fWrite->cctxPtr);
    -  free(lz4fWrite->dstBuf);
    -  free(lz4fWrite);
    +  LZ4F_freeWriteFile(lz4fWrite);
       return ret;
     }
    diff --git a/lib/lz4file.h b/lib/lz4file.h
    index 5527130720fbe06188e1929a64d58706e17a1b1d..598ad705ea9ff34552b62b1c2368afedd4ad62c5 100644
    --- a/lib/lz4file.h
    +++ b/lib/lz4file.h
    @@ -38,7 +38,7 @@ extern "C" {
     #ifndef LZ4FILE_H
     #define LZ4FILE_H
     
    -#include 
    +#include   /* FILE* */
     #include "lz4frame_static.h"
     
     typedef struct LZ4_readFile_s LZ4_readFile_t;
    @@ -78,7 +78,7 @@ LZ4FLIB_STATIC_API LZ4F_errorCode_t LZ4F_writeOpen(LZ4_writeFile_t** lz4fWrite,
      * `buf` write data buffer.
      * `size` write data buffer size.
      */
    -LZ4FLIB_STATIC_API size_t LZ4F_write(LZ4_writeFile_t* lz4fWrite, void* buf, size_t size);
    +LZ4FLIB_STATIC_API size_t LZ4F_write(LZ4_writeFile_t* lz4fWrite, const void* buf, size_t size);
     
     /*! LZ4F_writeClose() :
      * Close lz4file handle.
    diff --git a/lib/lz4frame.c b/lib/lz4frame.c
    index 174f9ae4f21798f6c3fb34c3911ade0324b4ab6a..f89c05579951884cddaba4325b48636478986366 100644
    --- a/lib/lz4frame.c
    +++ b/lib/lz4frame.c
    @@ -44,6 +44,7 @@
     /*-************************************
     *  Compiler Options
     **************************************/
    +#include 
     #ifdef _MSC_VER    /* Visual Studio */
     #  pragma warning(disable : 4127)   /* disable: C4127: conditional expression is constant */
     #endif
    @@ -54,8 +55,8 @@
     **************************************/
     /*
      * LZ4F_HEAPMODE :
    - * Select how default compression functions will allocate memory for their hash table,
    - * in memory stack (0:default, fastest), or in memory heap (1:requires malloc()).
    + * Control how LZ4F_compressFrame allocates the Compression State,
    + * either on stack (0:default, fastest), or in memory heap (1:requires malloc()).
      */
     #ifndef LZ4F_HEAPMODE
     #  define LZ4F_HEAPMODE 0
    @@ -125,8 +126,9 @@ static void* LZ4F_malloc(size_t s, LZ4F_CustomMem cmem)
     
     static void LZ4F_free(void* p, LZ4F_CustomMem cmem)
     {
    -    /* custom malloc defined : use it */
    +    if (p == NULL) return;
         if (cmem.customFree != NULL) {
    +        /* custom allocation defined : use it */
             cmem.customFree(cmem.opaqueState, p);
             return;
         }
    @@ -153,7 +155,7 @@ static void LZ4F_free(void* p, LZ4F_CustomMem cmem)
     static int g_debuglog_enable = 1;
     #  define DEBUGLOG(l, ...) {                                  \
                     if ((g_debuglog_enable) && (l<=LZ4_DEBUG)) {  \
    -                    fprintf(stderr, __FILE__ ": ");           \
    +                    fprintf(stderr, __FILE__ " (%i): ", __LINE__ );  \
                         fprintf(stderr, __VA_ARGS__);             \
                         fprintf(stderr, " \n");                   \
                 }   }
    @@ -186,9 +188,9 @@ static U32 LZ4F_readLE32 (const void* src)
     {
         const BYTE* const srcPtr = (const BYTE*)src;
         U32 value32 = srcPtr[0];
    -    value32 += ((U32)srcPtr[1])<< 8;
    -    value32 += ((U32)srcPtr[2])<<16;
    -    value32 += ((U32)srcPtr[3])<<24;
    +    value32 |= ((U32)srcPtr[1])<< 8;
    +    value32 |= ((U32)srcPtr[2])<<16;
    +    value32 |= ((U32)srcPtr[3])<<24;
         return value32;
     }
     
    @@ -205,13 +207,13 @@ static U64 LZ4F_readLE64 (const void* src)
     {
         const BYTE* const srcPtr = (const BYTE*)src;
         U64 value64 = srcPtr[0];
    -    value64 += ((U64)srcPtr[1]<<8);
    -    value64 += ((U64)srcPtr[2]<<16);
    -    value64 += ((U64)srcPtr[3]<<24);
    -    value64 += ((U64)srcPtr[4]<<32);
    -    value64 += ((U64)srcPtr[5]<<40);
    -    value64 += ((U64)srcPtr[6]<<48);
    -    value64 += ((U64)srcPtr[7]<<56);
    +    value64 |= ((U64)srcPtr[1]<<8);
    +    value64 |= ((U64)srcPtr[2]<<16);
    +    value64 |= ((U64)srcPtr[3]<<24);
    +    value64 |= ((U64)srcPtr[4]<<32);
    +    value64 |= ((U64)srcPtr[5]<<40);
    +    value64 |= ((U64)srcPtr[6]<<48);
    +    value64 |= ((U64)srcPtr[7]<<56);
         return value64;
     }
     
    @@ -257,14 +259,15 @@ static const size_t BFSize = LZ4F_BLOCK_CHECKSUM_SIZE;  /* block footer : checks
     *  Structures and local types
     **************************************/
     
    -typedef enum { LZ4B_COMPRESSED, LZ4B_UNCOMPRESSED} LZ4F_blockCompression_t;
    +typedef enum { LZ4B_COMPRESSED, LZ4B_UNCOMPRESSED} LZ4F_BlockCompressMode_e;
    +typedef enum { ctxNone, ctxFast, ctxHC } LZ4F_CtxType_e;
     
     typedef struct LZ4F_cctx_s
     {
         LZ4F_CustomMem cmem;
         LZ4F_preferences_t prefs;
         U32    version;
    -    U32    cStage;
    +    U32    cStage;     /* 0 : compression uninitialized ; 1 : initialized, can compress */
         const LZ4F_CDict* cdict;
         size_t maxBlockSize;
         size_t maxBufferSize;
    @@ -275,8 +278,8 @@ typedef struct LZ4F_cctx_s
         XXH32_state_t xxh;
         void*  lz4CtxPtr;
         U16    lz4CtxAlloc; /* sized for: 0 = none, 1 = lz4 ctx, 2 = lz4hc ctx */
    -    U16    lz4CtxState; /* in use as: 0 = none, 1 = lz4 ctx, 2 = lz4hc ctx */
    -    LZ4F_blockCompression_t  blockCompression;
    +    U16    lz4CtxType;  /* in use as: 0 = none, 1 = lz4 ctx, 2 = lz4hc ctx */
    +    LZ4F_BlockCompressMode_e  blockCompressMode;
     } LZ4F_cctx_t;
     
     
    @@ -314,9 +317,14 @@ static LZ4F_errorCode_t LZ4F_returnErrorCode(LZ4F_errorCodes code)
     
     #define RETURN_ERROR(e) return LZ4F_returnErrorCode(LZ4F_ERROR_ ## e)
     
    -#define RETURN_ERROR_IF(c,e) if (c) RETURN_ERROR(e)
    +#define RETURN_ERROR_IF(c,e) do {  \
    +        if (c) {                   \
    +            DEBUGLOG(3, "Error: " #c); \
    +            RETURN_ERROR(e);       \
    +        }                          \
    +    } while (0)
     
    -#define FORWARD_IF_ERROR(r)  if (LZ4F_isError(r)) return (r)
    +#define FORWARD_IF_ERROR(r) do { if (LZ4F_isError(r)) return (r); } while (0)
     
     unsigned LZ4F_getVersion(void) { return LZ4F_VERSION; }
     
    @@ -429,6 +437,7 @@ size_t LZ4F_compressFrame_usingCDict(LZ4F_cctx* cctx,
         BYTE* dstPtr = dstStart;
         BYTE* const dstEnd = dstStart + dstCapacity;
     
    +    DEBUGLOG(4, "LZ4F_compressFrame_usingCDict (srcSize=%u)", (unsigned)srcSize);
         if (preferencesPtr!=NULL)
             prefs = *preferencesPtr;
         else
    @@ -494,7 +503,7 @@ size_t LZ4F_compressFrame(void* dstBuffer, size_t dstCapacity,
             LZ4_initStream(&lz4ctx, sizeof(lz4ctx));
             cctxPtr->lz4CtxPtr = &lz4ctx;
             cctxPtr->lz4CtxAlloc = 1;
    -        cctxPtr->lz4CtxState = 1;
    +        cctxPtr->lz4CtxType = ctxFast;
         }
     #endif
         DEBUGLOG(4, "LZ4F_compressFrame");
    @@ -539,18 +548,19 @@ LZ4F_createCDict_advanced(LZ4F_CustomMem cmem, const void* dictBuffer, size_t di
             dictSize = 64 KB;
         }
         cdict->dictContent = LZ4F_malloc(dictSize, cmem);
    +    /* note: using @cmem to allocate => can't use default create */
         cdict->fastCtx = (LZ4_stream_t*)LZ4F_malloc(sizeof(LZ4_stream_t), cmem);
    -    if (cdict->fastCtx)
    -        LZ4_initStream(cdict->fastCtx, sizeof(LZ4_stream_t));
         cdict->HCCtx = (LZ4_streamHC_t*)LZ4F_malloc(sizeof(LZ4_streamHC_t), cmem);
    -    if (cdict->HCCtx)
    -        LZ4_initStream(cdict->HCCtx, sizeof(LZ4_streamHC_t));
         if (!cdict->dictContent || !cdict->fastCtx || !cdict->HCCtx) {
             LZ4F_freeCDict(cdict);
             return NULL;
         }
         memcpy(cdict->dictContent, dictStart, dictSize);
    -    LZ4_loadDict (cdict->fastCtx, (const char*)cdict->dictContent, (int)dictSize);
    +    LZ4_initStream(cdict->fastCtx, sizeof(LZ4_stream_t));
    +    LZ4_loadDictSlow(cdict->fastCtx, (const char*)cdict->dictContent, (int)dictSize);
    +    LZ4_initStreamHC(cdict->HCCtx, sizeof(LZ4_streamHC_t));
    +    /* note: we don't know at this point which compression level is going to be used
    +     * as a consequence, HCCtx is created for the more common HC mode */
         LZ4_setCompressionLevel(cdict->HCCtx, LZ4HC_CLEVEL_DEFAULT);
         LZ4_loadDictHC(cdict->HCCtx, (const char*)cdict->dictContent, (int)dictSize);
         return cdict;
    @@ -616,7 +626,6 @@ LZ4F_createCompressionContext(LZ4F_cctx** LZ4F_compressionContextPtr, unsigned v
         return LZ4F_OK_NoError;
     }
     
    -
     LZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_cctx* cctxPtr)
     {
         if (cctxPtr != NULL) {  /* support free on NULL */
    @@ -641,7 +650,7 @@ static void LZ4F_initStream(void* ctx,
                                 int level,
                                 LZ4F_blockMode_t blockMode) {
         if (level < LZ4HC_CLEVEL_MIN) {
    -        if (cdict != NULL || blockMode == LZ4F_blockLinked) {
    +        if (cdict || blockMode == LZ4F_blockLinked) {
                 /* In these cases, we will call LZ4_compress_fast_continue(),
                  * which needs an already reset context. Otherwise, we'll call a
                  * one-shot API. The non-continued APIs internally perform their own
    @@ -649,11 +658,18 @@ static void LZ4F_initStream(void* ctx,
                  * tableType they need the context to be in. So in that case this
                  * would be misguided / wasted work. */
                 LZ4_resetStream_fast((LZ4_stream_t*)ctx);
    +            if (cdict)
    +                LZ4_attach_dictionary((LZ4_stream_t*)ctx, cdict->fastCtx);
             }
    -        LZ4_attach_dictionary((LZ4_stream_t *)ctx, cdict ? cdict->fastCtx : NULL);
    +        /* In these cases, we'll call a one-shot API.
    +         * The non-continued APIs internally perform their own resets
    +         * at the beginning of their calls, where they know
    +         * which tableType they need the context to be in.
    +         * Therefore, a reset here would be wasted work. */
         } else {
             LZ4_resetStreamHC_fast((LZ4_streamHC_t*)ctx, level);
    -        LZ4_attach_HC_dictionary((LZ4_streamHC_t *)ctx, cdict ? cdict->HCCtx : NULL);
    +        if (cdict)
    +            LZ4_attach_HC_dictionary((LZ4_streamHC_t*)ctx, cdict->HCCtx);
         }
     }
     
    @@ -668,14 +684,12 @@ static int ctxTypeID_to_size(int ctxTypeID) {
         }
     }
     
    -/*! LZ4F_compressBegin_usingCDict() :
    - *  init streaming compression AND writes frame header into @dstBuffer.
    - * @dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.
    - * @return : number of bytes written into @dstBuffer for the header
    - *           or an error code (can be tested using LZ4F_isError())
    +/* LZ4F_compressBegin_internal()
    + * Note: only accepts @cdict _or_ @dictBuffer as non NULL.
      */
    -size_t LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctxPtr,
    +size_t LZ4F_compressBegin_internal(LZ4F_cctx* cctx,
                               void* dstBuffer, size_t dstCapacity,
    +                          const void* dictBuffer, size_t dictSize,
                               const LZ4F_CDict* cdict,
                               const LZ4F_preferences_t* preferencesPtr)
     {
    @@ -685,71 +699,85 @@ size_t LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctxPtr,
     
         RETURN_ERROR_IF(dstCapacity < maxFHSize, dstMaxSize_tooSmall);
         if (preferencesPtr == NULL) preferencesPtr = &prefNull;
    -    cctxPtr->prefs = *preferencesPtr;
    +    cctx->prefs = *preferencesPtr;
     
         /* cctx Management */
    -    {   U16 const ctxTypeID = (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) ? 1 : 2;
    +    {   U16 const ctxTypeID = (cctx->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) ? 1 : 2;
             int requiredSize = ctxTypeID_to_size(ctxTypeID);
    -        int allocatedSize = ctxTypeID_to_size(cctxPtr->lz4CtxAlloc);
    +        int allocatedSize = ctxTypeID_to_size(cctx->lz4CtxAlloc);
             if (allocatedSize < requiredSize) {
                 /* not enough space allocated */
    -            LZ4F_free(cctxPtr->lz4CtxPtr, cctxPtr->cmem);
    -            if (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) {
    +            LZ4F_free(cctx->lz4CtxPtr, cctx->cmem);
    +            if (cctx->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) {
                     /* must take ownership of memory allocation,
                      * in order to respect custom allocator contract */
    -                cctxPtr->lz4CtxPtr = LZ4F_malloc(sizeof(LZ4_stream_t), cctxPtr->cmem);
    -                if (cctxPtr->lz4CtxPtr)
    -                    LZ4_initStream(cctxPtr->lz4CtxPtr, sizeof(LZ4_stream_t));
    +                cctx->lz4CtxPtr = LZ4F_malloc(sizeof(LZ4_stream_t), cctx->cmem);
    +                if (cctx->lz4CtxPtr)
    +                    LZ4_initStream(cctx->lz4CtxPtr, sizeof(LZ4_stream_t));
                 } else {
    -                cctxPtr->lz4CtxPtr = LZ4F_malloc(sizeof(LZ4_streamHC_t), cctxPtr->cmem);
    -                if (cctxPtr->lz4CtxPtr)
    -                    LZ4_initStreamHC(cctxPtr->lz4CtxPtr, sizeof(LZ4_streamHC_t));
    +                cctx->lz4CtxPtr = LZ4F_malloc(sizeof(LZ4_streamHC_t), cctx->cmem);
    +                if (cctx->lz4CtxPtr)
    +                    LZ4_initStreamHC(cctx->lz4CtxPtr, sizeof(LZ4_streamHC_t));
                 }
    -            RETURN_ERROR_IF(cctxPtr->lz4CtxPtr == NULL, allocation_failed);
    -            cctxPtr->lz4CtxAlloc = ctxTypeID;
    -            cctxPtr->lz4CtxState = ctxTypeID;
    -        } else if (cctxPtr->lz4CtxState != ctxTypeID) {
    +            RETURN_ERROR_IF(cctx->lz4CtxPtr == NULL, allocation_failed);
    +            cctx->lz4CtxAlloc = ctxTypeID;
    +            cctx->lz4CtxType = ctxTypeID;
    +        } else if (cctx->lz4CtxType != ctxTypeID) {
                 /* otherwise, a sufficient buffer is already allocated,
                  * but we need to reset it to the correct context type */
    -            if (cctxPtr->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) {
    -                LZ4_initStream((LZ4_stream_t*)cctxPtr->lz4CtxPtr, sizeof(LZ4_stream_t));
    +            if (cctx->prefs.compressionLevel < LZ4HC_CLEVEL_MIN) {
    +                LZ4_initStream((LZ4_stream_t*)cctx->lz4CtxPtr, sizeof(LZ4_stream_t));
                 } else {
    -                LZ4_initStreamHC((LZ4_streamHC_t*)cctxPtr->lz4CtxPtr, sizeof(LZ4_streamHC_t));
    -                LZ4_setCompressionLevel((LZ4_streamHC_t*)cctxPtr->lz4CtxPtr, cctxPtr->prefs.compressionLevel);
    +                LZ4_initStreamHC((LZ4_streamHC_t*)cctx->lz4CtxPtr, sizeof(LZ4_streamHC_t));
    +                LZ4_setCompressionLevel((LZ4_streamHC_t*)cctx->lz4CtxPtr, cctx->prefs.compressionLevel);
                 }
    -            cctxPtr->lz4CtxState = ctxTypeID;
    +            cctx->lz4CtxType = ctxTypeID;
         }   }
     
         /* Buffer Management */
    -    if (cctxPtr->prefs.frameInfo.blockSizeID == 0)
    -        cctxPtr->prefs.frameInfo.blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT;
    -    cctxPtr->maxBlockSize = LZ4F_getBlockSize(cctxPtr->prefs.frameInfo.blockSizeID);
    +    if (cctx->prefs.frameInfo.blockSizeID == 0)
    +        cctx->prefs.frameInfo.blockSizeID = LZ4F_BLOCKSIZEID_DEFAULT;
    +    cctx->maxBlockSize = LZ4F_getBlockSize(cctx->prefs.frameInfo.blockSizeID);
     
         {   size_t const requiredBuffSize = preferencesPtr->autoFlush ?
    -                ((cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked) ? 64 KB : 0) :  /* only needs past data up to window size */
    -                cctxPtr->maxBlockSize + ((cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked) ? 128 KB : 0);
    -
    -        if (cctxPtr->maxBufferSize < requiredBuffSize) {
    -            cctxPtr->maxBufferSize = 0;
    -            LZ4F_free(cctxPtr->tmpBuff, cctxPtr->cmem);
    -            cctxPtr->tmpBuff = (BYTE*)LZ4F_calloc(requiredBuffSize, cctxPtr->cmem);
    -            RETURN_ERROR_IF(cctxPtr->tmpBuff == NULL, allocation_failed);
    -            cctxPtr->maxBufferSize = requiredBuffSize;
    +                ((cctx->prefs.frameInfo.blockMode == LZ4F_blockLinked) ? 64 KB : 0) :  /* only needs past data up to window size */
    +                cctx->maxBlockSize + ((cctx->prefs.frameInfo.blockMode == LZ4F_blockLinked) ? 128 KB : 0);
    +
    +        if (cctx->maxBufferSize < requiredBuffSize) {
    +            cctx->maxBufferSize = 0;
    +            LZ4F_free(cctx->tmpBuff, cctx->cmem);
    +            cctx->tmpBuff = (BYTE*)LZ4F_malloc(requiredBuffSize, cctx->cmem);
    +            RETURN_ERROR_IF(cctx->tmpBuff == NULL, allocation_failed);
    +            cctx->maxBufferSize = requiredBuffSize;
         }   }
    -    cctxPtr->tmpIn = cctxPtr->tmpBuff;
    -    cctxPtr->tmpInSize = 0;
    -    (void)XXH32_reset(&(cctxPtr->xxh), 0);
    +    cctx->tmpIn = cctx->tmpBuff;
    +    cctx->tmpInSize = 0;
    +    (void)XXH32_reset(&(cctx->xxh), 0);
     
         /* context init */
    -    cctxPtr->cdict = cdict;
    -    if (cctxPtr->prefs.frameInfo.blockMode == LZ4F_blockLinked) {
    +    cctx->cdict = cdict;
    +    if (cctx->prefs.frameInfo.blockMode == LZ4F_blockLinked) {
             /* frame init only for blockLinked : blockIndependent will be init at each block */
    -        LZ4F_initStream(cctxPtr->lz4CtxPtr, cdict, cctxPtr->prefs.compressionLevel, LZ4F_blockLinked);
    +        LZ4F_initStream(cctx->lz4CtxPtr, cdict, cctx->prefs.compressionLevel, LZ4F_blockLinked);
         }
         if (preferencesPtr->compressionLevel >= LZ4HC_CLEVEL_MIN) {
    -        LZ4_favorDecompressionSpeed((LZ4_streamHC_t*)cctxPtr->lz4CtxPtr, (int)preferencesPtr->favorDecSpeed);
    +        LZ4_favorDecompressionSpeed((LZ4_streamHC_t*)cctx->lz4CtxPtr, (int)preferencesPtr->favorDecSpeed);
    +    }
    +    if (dictBuffer) {
    +        assert(cdict == NULL);
    +        RETURN_ERROR_IF(dictSize > INT_MAX, parameter_invalid);
    +        if (cctx->lz4CtxType == ctxFast) {
    +            /* lz4 fast*/
    +            LZ4_loadDict((LZ4_stream_t*)cctx->lz4CtxPtr, (const char*)dictBuffer, (int)dictSize);
    +        } else {
    +            /* lz4hc */
    +            assert(cctx->lz4CtxType == ctxHC);
    +            LZ4_loadDictHC((LZ4_streamHC_t*)cctx->lz4CtxPtr, (const char*)dictBuffer, (int)dictSize);
    +        }
         }
     
    +    /* Stage 2 : Write Frame Header */
    +
         /* Magic Number */
         LZ4F_writeLE32(dstPtr, LZ4F_MAGICNUMBER);
         dstPtr += 4;
    @@ -757,22 +785,22 @@ size_t LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctxPtr,
     
             /* FLG Byte */
             *dstPtr++ = (BYTE)(((1 & _2BITS) << 6)    /* Version('01') */
    -            + ((cctxPtr->prefs.frameInfo.blockMode & _1BIT ) << 5)
    -            + ((cctxPtr->prefs.frameInfo.blockChecksumFlag & _1BIT ) << 4)
    -            + ((unsigned)(cctxPtr->prefs.frameInfo.contentSize > 0) << 3)
    -            + ((cctxPtr->prefs.frameInfo.contentChecksumFlag & _1BIT ) << 2)
    -            +  (cctxPtr->prefs.frameInfo.dictID > 0) );
    +            + ((cctx->prefs.frameInfo.blockMode & _1BIT ) << 5)
    +            + ((cctx->prefs.frameInfo.blockChecksumFlag & _1BIT ) << 4)
    +            + ((unsigned)(cctx->prefs.frameInfo.contentSize > 0) << 3)
    +            + ((cctx->prefs.frameInfo.contentChecksumFlag & _1BIT ) << 2)
    +            +  (cctx->prefs.frameInfo.dictID > 0) );
             /* BD Byte */
    -        *dstPtr++ = (BYTE)((cctxPtr->prefs.frameInfo.blockSizeID & _3BITS) << 4);
    +        *dstPtr++ = (BYTE)((cctx->prefs.frameInfo.blockSizeID & _3BITS) << 4);
             /* Optional Frame content size field */
    -        if (cctxPtr->prefs.frameInfo.contentSize) {
    -            LZ4F_writeLE64(dstPtr, cctxPtr->prefs.frameInfo.contentSize);
    +        if (cctx->prefs.frameInfo.contentSize) {
    +            LZ4F_writeLE64(dstPtr, cctx->prefs.frameInfo.contentSize);
                 dstPtr += 8;
    -            cctxPtr->totalInSize = 0;
    +            cctx->totalInSize = 0;
             }
             /* Optional dictionary ID field */
    -        if (cctxPtr->prefs.frameInfo.dictID) {
    -            LZ4F_writeLE32(dstPtr, cctxPtr->prefs.frameInfo.dictID);
    +        if (cctx->prefs.frameInfo.dictID) {
    +            LZ4F_writeLE32(dstPtr, cctx->prefs.frameInfo.dictID);
                 dstPtr += 4;
             }
             /* Header CRC Byte */
    @@ -780,24 +808,54 @@ size_t LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctxPtr,
             dstPtr++;
         }
     
    -    cctxPtr->cStage = 1;   /* header written, now request input data block */
    +    cctx->cStage = 1;   /* header written, now request input data block */
         return (size_t)(dstPtr - dstStart);
     }
     
    +size_t LZ4F_compressBegin(LZ4F_cctx* cctx,
    +                          void* dstBuffer, size_t dstCapacity,
    +                          const LZ4F_preferences_t* preferencesPtr)
    +{
    +    return LZ4F_compressBegin_internal(cctx, dstBuffer, dstCapacity,
    +                                        NULL, 0,
    +                                        NULL, preferencesPtr);
    +}
     
    -/*! LZ4F_compressBegin() :
    - *  init streaming compression AND writes frame header into @dstBuffer.
    - * @dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.
    - * @preferencesPtr can be NULL, in which case default parameters are selected.
    - * @return : number of bytes written into dstBuffer for the header
    - *        or an error code (can be tested using LZ4F_isError())
    - */
    -size_t LZ4F_compressBegin(LZ4F_cctx* cctxPtr,
    +/* LZ4F_compressBegin_usingDictOnce:
    + * Hidden implementation,
    + * employed for multi-threaded compression
    + * when frame defines linked blocks */
    +size_t LZ4F_compressBegin_usingDictOnce(LZ4F_cctx* cctx,
    +                          void* dstBuffer, size_t dstCapacity,
    +                          const void* dict, size_t dictSize,
    +                          const LZ4F_preferences_t* preferencesPtr)
    +{
    +    return LZ4F_compressBegin_internal(cctx, dstBuffer, dstCapacity,
    +                                        dict, dictSize,
    +                                        NULL, preferencesPtr);
    +}
    +
    +size_t LZ4F_compressBegin_usingDict(LZ4F_cctx* cctx,
    +                          void* dstBuffer, size_t dstCapacity,
    +                          const void* dict, size_t dictSize,
    +                          const LZ4F_preferences_t* preferencesPtr)
    +{
    +    /* note : incorrect implementation :
    +     * this will only use the dictionary once,
    +     * instead of once *per* block when frames defines independent blocks */
    +    return LZ4F_compressBegin_usingDictOnce(cctx, dstBuffer, dstCapacity,
    +                                        dict, dictSize,
    +                                        preferencesPtr);
    +}
    +
    +size_t LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctx,
                               void* dstBuffer, size_t dstCapacity,
    +                          const LZ4F_CDict* cdict,
                               const LZ4F_preferences_t* preferencesPtr)
     {
    -    return LZ4F_compressBegin_usingCDict(cctxPtr, dstBuffer, dstCapacity,
    -                                         NULL, preferencesPtr);
    +    return LZ4F_compressBegin_internal(cctx, dstBuffer, dstCapacity,
    +                                        NULL, 0,
    +                                       cdict, preferencesPtr);
     }
     
     
    @@ -891,9 +949,10 @@ static int LZ4F_doNotCompressBlock(void* ctx, const char* src, char* dst, int sr
         return 0;
     }
     
    -static compressFunc_t LZ4F_selectCompression(LZ4F_blockMode_t blockMode, int level, LZ4F_blockCompression_t  compressMode)
    +static compressFunc_t LZ4F_selectCompression(LZ4F_blockMode_t blockMode, int level, LZ4F_BlockCompressMode_e  compressMode)
     {
    -    if (compressMode == LZ4B_UNCOMPRESSED) return LZ4F_doNotCompressBlock;
    +    if (compressMode == LZ4B_UNCOMPRESSED)
    +        return LZ4F_doNotCompressBlock;
         if (level < LZ4HC_CLEVEL_MIN) {
             if (blockMode == LZ4F_blockIndependent) return LZ4F_compressBlock;
             return LZ4F_compressBlock_continue;
    @@ -931,7 +990,7 @@ static size_t LZ4F_compressUpdateImpl(LZ4F_cctx* cctxPtr,
                          void* dstBuffer, size_t dstCapacity,
                          const void* srcBuffer, size_t srcSize,
                          const LZ4F_compressOptions_t* compressOptionsPtr,
    -                     LZ4F_blockCompression_t blockCompression)
    +                     LZ4F_BlockCompressMode_e blockCompression)
       {
         size_t const blockSize = cctxPtr->maxBlockSize;
         const BYTE* srcPtr = (const BYTE*)srcBuffer;
    @@ -951,10 +1010,10 @@ static size_t LZ4F_compressUpdateImpl(LZ4F_cctx* cctxPtr,
             RETURN_ERROR(dstMaxSize_tooSmall);
     
         /* flush currently written block, to continue with new block compression */
    -    if (cctxPtr->blockCompression != blockCompression) {
    +    if (cctxPtr->blockCompressMode != blockCompression) {
             bytesWritten = LZ4F_flush(cctxPtr, dstBuffer, dstCapacity, compressOptionsPtr);
             dstPtr += bytesWritten;
    -        cctxPtr->blockCompression = blockCompression;
    +        cctxPtr->blockCompressMode = blockCompression;
         }
     
         if (compressOptionsPtr == NULL) compressOptionsPtr = &k_cOptionsNull;
    @@ -1068,13 +1127,9 @@ size_t LZ4F_compressUpdate(LZ4F_cctx* cctxPtr,
                                        compressOptionsPtr, LZ4B_COMPRESSED);
     }
     
    -/*! LZ4F_compressUpdate() :
    - *  LZ4F_compressUpdate() can be called repetitively to compress as much data as necessary.
    - *  When successful, the function always entirely consumes @srcBuffer.
    - *  src data is either buffered or compressed into @dstBuffer.
    - *  If previously an uncompressed block was written, buffered data is flushed
    - *  before appending compressed data is continued.
    - *  This is only supported when LZ4F_blockIndependent is used
    +/*! LZ4F_uncompressedUpdate() :
    + *  Same as LZ4F_compressUpdate(), but requests blocks to be sent uncompressed.
    + *  This symbol is only supported when LZ4F_blockIndependent is used
      * @dstCapacity MUST be >= LZ4F_compressBound(srcSize, preferencesPtr).
      * @compressOptionsPtr is optional : provide NULL to mean "default".
      * @return : the number of bytes written into dstBuffer. It can be zero, meaning input data was just buffered.
    @@ -1084,8 +1139,8 @@ size_t LZ4F_compressUpdate(LZ4F_cctx* cctxPtr,
     size_t LZ4F_uncompressedUpdate(LZ4F_cctx* cctxPtr,
                                    void* dstBuffer, size_t dstCapacity,
                              const void* srcBuffer, size_t srcSize,
    -                         const LZ4F_compressOptions_t* compressOptionsPtr) {
    -    RETURN_ERROR_IF(cctxPtr->prefs.frameInfo.blockMode != LZ4F_blockIndependent, blockMode_invalid);
    +                         const LZ4F_compressOptions_t* compressOptionsPtr)
    +{
         return LZ4F_compressUpdateImpl(cctxPtr,
                                        dstBuffer, dstCapacity,
                                        srcBuffer, srcSize,
    @@ -1115,7 +1170,7 @@ size_t LZ4F_flush(LZ4F_cctx* cctxPtr,
         (void)compressOptionsPtr;   /* not useful (yet) */
     
         /* select compression function */
    -    compress = LZ4F_selectCompression(cctxPtr->prefs.frameInfo.blockMode, cctxPtr->prefs.compressionLevel, cctxPtr->blockCompression);
    +    compress = LZ4F_selectCompression(cctxPtr->prefs.frameInfo.blockMode, cctxPtr->prefs.compressionLevel, cctxPtr->blockCompressMode);
     
         /* compress tmp buffer */
         dstPtr += LZ4F_makeBlock(dstPtr,
    @@ -1170,13 +1225,12 @@ size_t LZ4F_compressEnd(LZ4F_cctx* cctxPtr,
         if (cctxPtr->prefs.frameInfo.contentChecksumFlag == LZ4F_contentChecksumEnabled) {
             U32 const xxh = XXH32_digest(&(cctxPtr->xxh));
             RETURN_ERROR_IF(dstCapacity < 8, dstMaxSize_tooSmall);
    -        DEBUGLOG(5,"Writing 32-bit content checksum");
    +        DEBUGLOG(5,"Writing 32-bit content checksum (0x%0X)", xxh);
             LZ4F_writeLE32(dstPtr, xxh);
             dstPtr+=4;   /* content Checksum */
         }
     
         cctxPtr->cStage = 0;   /* state is now re-usable (with identical preferences) */
    -    cctxPtr->maxBufferSize = 0;  /* reuse HC context */
     
         if (cctxPtr->prefs.frameInfo.contentSize) {
             if (cctxPtr->prefs.frameInfo.contentSize != cctxPtr->totalInSize)
    @@ -1270,13 +1324,14 @@ LZ4F_errorCode_t LZ4F_freeDecompressionContext(LZ4F_dctx* dctx)
     
     
     /*==---   Streaming Decompression operations   ---==*/
    -
     void LZ4F_resetDecompressionContext(LZ4F_dctx* dctx)
     {
    +    DEBUGLOG(5, "LZ4F_resetDecompressionContext");
         dctx->dStage = dstage_getFrameHeader;
         dctx->dict = NULL;
         dctx->dictSize = 0;
         dctx->skipChecksum = 0;
    +    dctx->frameRemainingSize = 0;
     }
     
     
    @@ -1333,6 +1388,7 @@ static size_t LZ4F_decodeHeader(LZ4F_dctx* dctx, const void* src, size_t srcSize
             if (((FLG>>1)&_1BIT) != 0) RETURN_ERROR(reservedFlag_set); /* Reserved bit */
             if (version != 1) RETURN_ERROR(headerVersion_wrong);       /* Version Number, only supported value */
         }
    +    DEBUGLOG(6, "contentSizeFlag: %u", contentSizeFlag);
     
         /* Frame Header Size */
         frameHeaderSize = minFHSize + (contentSizeFlag?8:0) + (dictIDFlag?4:0);
    @@ -1369,8 +1425,9 @@ static size_t LZ4F_decodeHeader(LZ4F_dctx* dctx, const void* src, size_t srcSize
         dctx->frameInfo.contentChecksumFlag = (LZ4F_contentChecksum_t)contentChecksumFlag;
         dctx->frameInfo.blockSizeID = (LZ4F_blockSizeID_t)blockSizeID;
         dctx->maxBlockSize = LZ4F_getBlockSize((LZ4F_blockSizeID_t)blockSizeID);
    -    if (contentSizeFlag)
    +    if (contentSizeFlag) {
             dctx->frameRemainingSize = dctx->frameInfo.contentSize = LZ4F_readLE64(srcPtr+6);
    +    }
         if (dictIDFlag)
             dctx->frameInfo.dictID = LZ4F_readLE32(srcPtr + frameHeaderSize - 5);
     
    @@ -1570,7 +1627,7 @@ size_t LZ4F_decompress(LZ4F_dctx* dctx,
         size_t nextSrcSizeHint = 1;
     
     
    -    DEBUGLOG(5, "LZ4F_decompress : %p,%u => %p,%u",
    +    DEBUGLOG(5, "LZ4F_decompress: src[%p](%u) => dst[%p](%u)",
                 srcBuffer, (unsigned)*srcSizePtr, dstBuffer, (unsigned)*dstSizePtr);
         if (dstBuffer == NULL) assert(*dstSizePtr == 0);
         MEM_INIT(&optionsNull, 0, sizeof(optionsNull));
    @@ -1722,10 +1779,10 @@ size_t LZ4F_decompress(LZ4F_dctx* dctx,
                         /* history management (linked blocks only)*/
                         if (dctx->frameInfo.blockMode == LZ4F_blockLinked) {
                             LZ4F_updateDict(dctx, dstPtr, sizeToCopy, dstStart, 0);
    -                }   }
    -
    -                srcPtr += sizeToCopy;
    -                dstPtr += sizeToCopy;
    +                    }
    +                    srcPtr += sizeToCopy;
    +                    dstPtr += sizeToCopy;
    +                }
                     if (sizeToCopy == dctx->tmpInTarget) {   /* all done */
                         if (dctx->frameInfo.blockChecksumFlag) {
                             dctx->tmpInSize = 0;
    @@ -1959,6 +2016,7 @@ size_t LZ4F_decompress(LZ4F_dctx* dctx,
                 if (!dctx->skipChecksum) {
                     U32 const readCRC = LZ4F_readLE32(selectedIn);
                     U32 const resultCRC = XXH32_digest(&(dctx->xxh));
    +                DEBUGLOG(4, "frame checksum: stored 0x%0X vs 0x%0X processed", readCRC, resultCRC);
     #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
                     RETURN_ERROR_IF(readCRC != resultCRC, contentChecksum_invalid);
     #else
    diff --git a/lib/lz4frame.h b/lib/lz4frame.h
    index 1bdf6c4fcba57536ff3c97936e1217e5aebb6797..b8ae32276707dfeabff7acc2f2eea604d975df0d 100644
    --- a/lib/lz4frame.h
    +++ b/lib/lz4frame.h
    @@ -173,16 +173,16 @@ typedef LZ4F_contentChecksum_t contentChecksum_t;
      *  setting all parameters to default.
      *  It's then possible to update selectively some parameters */
     typedef struct {
    -  LZ4F_blockSizeID_t     blockSizeID;         /* max64KB, max256KB, max1MB, max4MB; 0 == default */
    -  LZ4F_blockMode_t       blockMode;           /* LZ4F_blockLinked, LZ4F_blockIndependent; 0 == default */
    -  LZ4F_contentChecksum_t contentChecksumFlag; /* 1: frame terminated with 32-bit checksum of decompressed data; 0: disabled (default) */
    +  LZ4F_blockSizeID_t     blockSizeID;         /* max64KB, max256KB, max1MB, max4MB; 0 == default (LZ4F_max64KB) */
    +  LZ4F_blockMode_t       blockMode;           /* LZ4F_blockLinked, LZ4F_blockIndependent; 0 == default (LZ4F_blockLinked) */
    +  LZ4F_contentChecksum_t contentChecksumFlag; /* 1: add a 32-bit checksum of frame's decompressed data; 0 == default (disabled) */
       LZ4F_frameType_t       frameType;           /* read-only field : LZ4F_frame or LZ4F_skippableFrame */
       unsigned long long     contentSize;         /* Size of uncompressed content ; 0 == unknown */
       unsigned               dictID;              /* Dictionary ID, sent by compressor to help decoder select correct dictionary; 0 == no dictID provided */
    -  LZ4F_blockChecksum_t   blockChecksumFlag;   /* 1: each block followed by a checksum of block's compressed data; 0: disabled (default) */
    +  LZ4F_blockChecksum_t   blockChecksumFlag;   /* 1: each block followed by a checksum of block's compressed data; 0 == default (disabled) */
     } LZ4F_frameInfo_t;
     
    -#define LZ4F_INIT_FRAMEINFO   { LZ4F_default, LZ4F_blockLinked, LZ4F_noContentChecksum, LZ4F_frame, 0ULL, 0U, LZ4F_noBlockChecksum }    /* v1.8.3+ */
    +#define LZ4F_INIT_FRAMEINFO   { LZ4F_max64KB, LZ4F_blockLinked, LZ4F_noContentChecksum, LZ4F_frame, 0ULL, 0U, LZ4F_noBlockChecksum }    /* v1.8.3+ */
     
     /*! LZ4F_preferences_t :
      *  makes it possible to supply advanced compression instructions to streaming interface.
    @@ -204,7 +204,26 @@ typedef struct {
     *  Simple compression function
     ***********************************/
     
    -LZ4FLIB_API int LZ4F_compressionLevel_max(void);   /* v1.8.0+ */
    +/*! LZ4F_compressFrame() :
    + *  Compress srcBuffer content into an LZ4-compressed frame.
    + *  It's a one shot operation, all input content is consumed, and all output is generated.
    + *
    + *  Note : it's a stateless operation (no LZ4F_cctx state needed).
    + *  In order to reduce load on the allocator, LZ4F_compressFrame(), by default,
    + *  uses the stack to allocate space for the compression state and some table.
    + *  If this usage of the stack is too much for your application,
    + *  consider compiling `lz4frame.c` with compile-time macro LZ4F_HEAPMODE set to 1 instead.
    + *  All state allocations will use the Heap.
    + *  It also means each invocation of LZ4F_compressFrame() will trigger several internal alloc/free invocations.
    + *
    + * @dstCapacity MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr).
    + * @preferencesPtr is optional : one can provide NULL, in which case all preferences are set to default.
    + * @return : number of bytes written into dstBuffer.
    + *           or an error code if it fails (can be tested using LZ4F_isError())
    + */
    +LZ4FLIB_API size_t LZ4F_compressFrame(void* dstBuffer, size_t dstCapacity,
    +                                const void* srcBuffer, size_t srcSize,
    +                                const LZ4F_preferences_t* preferencesPtr);
     
     /*! LZ4F_compressFrameBound() :
      *  Returns the maximum possible compressed size with LZ4F_compressFrame() given srcSize and preferences.
    @@ -214,16 +233,11 @@ LZ4FLIB_API int LZ4F_compressionLevel_max(void);   /* v1.8.0+ */
      */
     LZ4FLIB_API size_t LZ4F_compressFrameBound(size_t srcSize, const LZ4F_preferences_t* preferencesPtr);
     
    -/*! LZ4F_compressFrame() :
    - *  Compress an entire srcBuffer into a valid LZ4 frame.
    - *  dstCapacity MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr).
    - *  The LZ4F_preferences_t structure is optional : you can provide NULL as argument. All preferences will be set to default.
    - * @return : number of bytes written into dstBuffer.
    - *           or an error code if it fails (can be tested using LZ4F_isError())
    +
    +/*! LZ4F_compressionLevel_max() :
    + * @return maximum allowed compression level (currently: 12)
      */
    -LZ4FLIB_API size_t LZ4F_compressFrame(void* dstBuffer, size_t dstCapacity,
    -                                const void* srcBuffer, size_t srcSize,
    -                                const LZ4F_preferences_t* preferencesPtr);
    +LZ4FLIB_API int LZ4F_compressionLevel_max(void);   /* v1.8.0+ */
     
     
     /*-***********************************
    @@ -278,7 +292,7 @@ LZ4FLIB_API LZ4F_errorCode_t LZ4F_freeCompressionContext(LZ4F_cctx* cctx);
     /*! LZ4F_compressBegin() :
      *  will write the frame header into dstBuffer.
      *  dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.
    - * `prefsPtr` is optional : you can provide NULL as argument, all preferences will then be set to default.
    + * `prefsPtr` is optional : NULL can be provided to set all preferences to default.
      * @return : number of bytes written into dstBuffer for the header
      *           or an error code (which can be tested using LZ4F_isError())
      */
    @@ -355,8 +369,9 @@ typedef struct LZ4F_dctx_s LZ4F_dctx;   /* incomplete type */
     typedef LZ4F_dctx* LZ4F_decompressionContext_t;   /* compatibility with previous API versions */
     
     typedef struct {
    -  unsigned stableDst;     /* pledges that last 64KB decompressed data will remain available unmodified between invocations.
    -                           * This optimization skips storage operations in tmp buffers. */
    +  unsigned stableDst;     /* pledges that last 64KB decompressed data is present right before @dstBuffer pointer.
    +                           * This optimization skips internal storage operations.
    +                           * Once set, this pledge must remain valid up to the end of current frame. */
       unsigned skipChecksums; /* disable checksum calculation and verification, even when one is present in frame, to save CPU time.
                                * Setting this option to 1 once disables all checksums for the rest of the frame. */
       unsigned reserved1;     /* must be set to zero for forward compatibility */
    @@ -463,6 +478,11 @@ LZ4F_getFrameInfo(LZ4F_dctx* dctx,
      * `dstBuffer` can freely change between each consecutive function invocation.
      * `dstBuffer` content will be overwritten.
      *
    + *  Note: if `LZ4F_getFrameInfo()` is called before `LZ4F_decompress()`, srcBuffer must be updated to reflect
    + *  the number of bytes consumed after reading the frame header. Failure to update srcBuffer before calling
    + *  `LZ4F_decompress()` will cause decompression failure or, even worse, successful but incorrect decompression.
    + *  See the `LZ4F_getFrameInfo()` docs for details.
    + *
      * @return : an hint of how many `srcSize` bytes LZ4F_decompress() expects for next call.
      *  Schematically, it's the size of the current (or remaining) compressed block + header of next block.
      *  Respecting the hint provides some small speed benefit, because it skips intermediate buffers.
    @@ -493,6 +513,109 @@ LZ4F_decompress(LZ4F_dctx* dctx,
     LZ4FLIB_API void LZ4F_resetDecompressionContext(LZ4F_dctx* dctx);   /* always successful */
     
     
    +/**********************************
    + *  Dictionary compression API
    + *********************************/
    +
    +/* A Dictionary is useful for the compression of small messages (KB range).
    + * It dramatically improves compression efficiency.
    + *
    + * LZ4 can ingest any input as dictionary, though only the last 64 KB are useful.
    + * Better results are generally achieved by using Zstandard's Dictionary Builder
    + * to generate a high-quality dictionary from a set of samples.
    + *
    + * The same dictionary will have to be used on the decompression side
    + * for decoding to be successful.
    + * To help identify the correct dictionary at decoding stage,
    + * the frame header allows optional embedding of a dictID field.
    + */
    +
    +/*! LZ4F_compressBegin_usingDict() : stable since v1.10
    + *  Inits dictionary compression streaming, and writes the frame header into dstBuffer.
    + * @dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.
    + * @prefsPtr is optional : one may provide NULL as argument,
    + *  however, it's the only way to provide dictID in the frame header.
    + * @dictBuffer must outlive the compression session.
    + * @return : number of bytes written into dstBuffer for the header,
    + *           or an error code (which can be tested using LZ4F_isError())
    + *  NOTE: The LZ4Frame spec allows each independent block to be compressed with the dictionary,
    + *        but this entry supports a more limited scenario, where only the first block uses the dictionary.
    + *        This is still useful for small data, which only need one block anyway.
    + *        For larger inputs, one may be more interested in LZ4F_compressFrame_usingCDict() below.
    + */
    +LZ4FLIB_API size_t
    +LZ4F_compressBegin_usingDict(LZ4F_cctx* cctx,
    +                            void* dstBuffer, size_t dstCapacity,
    +                      const void* dictBuffer, size_t dictSize,
    +                      const LZ4F_preferences_t* prefsPtr);
    +
    +/*! LZ4F_decompress_usingDict() : stable since v1.10
    + *  Same as LZ4F_decompress(), using a predefined dictionary.
    + *  Dictionary is used "in place", without any preprocessing.
    +**  It must remain accessible throughout the entire frame decoding. */
    +LZ4FLIB_API size_t
    +LZ4F_decompress_usingDict(LZ4F_dctx* dctxPtr,
    +                          void* dstBuffer, size_t* dstSizePtr,
    +                    const void* srcBuffer, size_t* srcSizePtr,
    +                    const void* dict, size_t dictSize,
    +                    const LZ4F_decompressOptions_t* decompressOptionsPtr);
    +
    +/*****************************************
    + *  Bulk processing dictionary compression
    + *****************************************/
    +
    +/* Loading a dictionary has a cost, since it involves construction of tables.
    + * The Bulk processing dictionary API makes it possible to share this cost
    + * over an arbitrary number of compression jobs, even concurrently,
    + * markedly improving compression latency for these cases.
    + *
    + * Note that there is no corresponding bulk API for the decompression side,
    + * because dictionary does not carry any initialization cost for decompression.
    + * Use the regular LZ4F_decompress_usingDict() there.
    + */
    +typedef struct LZ4F_CDict_s LZ4F_CDict;
    +
    +/*! LZ4_createCDict() : stable since v1.10
    + *  When compressing multiple messages / blocks using the same dictionary, it's recommended to initialize it just once.
    + *  LZ4_createCDict() will create a digested dictionary, ready to start future compression operations without startup delay.
    + *  LZ4_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only.
    + * @dictBuffer can be released after LZ4_CDict creation, since its content is copied within CDict. */
    +LZ4FLIB_API LZ4F_CDict* LZ4F_createCDict(const void* dictBuffer, size_t dictSize);
    +LZ4FLIB_API void        LZ4F_freeCDict(LZ4F_CDict* CDict);
    +
    +/*! LZ4_compressFrame_usingCDict() : stable since v1.10
    + *  Compress an entire srcBuffer into a valid LZ4 frame using a digested Dictionary.
    + * @cctx must point to a context created by LZ4F_createCompressionContext().
    + *  If @cdict==NULL, compress without a dictionary.
    + * @dstBuffer MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr).
    + *  If this condition is not respected, function will fail (@return an errorCode).
    + *  The LZ4F_preferences_t structure is optional : one may provide NULL as argument,
    + *  but it's not recommended, as it's the only way to provide @dictID in the frame header.
    + * @return : number of bytes written into dstBuffer.
    + *           or an error code if it fails (can be tested using LZ4F_isError())
    + *  Note: for larger inputs generating multiple independent blocks,
    + *        this entry point uses the dictionary for each block. */
    +LZ4FLIB_API size_t
    +LZ4F_compressFrame_usingCDict(LZ4F_cctx* cctx,
    +                              void* dst, size_t dstCapacity,
    +                        const void* src, size_t srcSize,
    +                        const LZ4F_CDict* cdict,
    +                        const LZ4F_preferences_t* preferencesPtr);
    +
    +/*! LZ4F_compressBegin_usingCDict() : stable since v1.10
    + *  Inits streaming dictionary compression, and writes the frame header into dstBuffer.
    + * @dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.
    + * @prefsPtr is optional : one may provide NULL as argument,
    + *  note however that it's the only way to insert a @dictID in the frame header.
    + * @cdict must outlive the compression session.
    + * @return : number of bytes written into dstBuffer for the header,
    + *           or an error code, which can be tested using LZ4F_isError(). */
    +LZ4FLIB_API size_t
    +LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctx,
    +                              void* dstBuffer, size_t dstCapacity,
    +                        const LZ4F_CDict* cdict,
    +                        const LZ4F_preferences_t* prefsPtr);
    +
     
     #if defined (__cplusplus)
     }
    @@ -503,11 +626,8 @@ LZ4FLIB_API void LZ4F_resetDecompressionContext(LZ4F_dctx* dctx);   /* always su
     #if defined(LZ4F_STATIC_LINKING_ONLY) && !defined(LZ4F_H_STATIC_09782039843)
     #define LZ4F_H_STATIC_09782039843
     
    -#if defined (__cplusplus)
    -extern "C" {
    -#endif
    -
    -/* These declarations are not stable and may change in the future.
    +/* Note :
    + * The below declarations are not stable and may change in the future.
      * They are therefore only safe to depend on
      * when the caller is statically linked against the library.
      * To access their declarations, define LZ4F_STATIC_LINKING_ONLY.
    @@ -517,6 +637,11 @@ extern "C" {
      * by defining LZ4F_PUBLISH_STATIC_FUNCTIONS.
      * Use at your own risk.
      */
    +
    +#if defined (__cplusplus)
    +extern "C" {
    +#endif
    +
     #ifdef LZ4F_PUBLISH_STATIC_FUNCTIONS
     # define LZ4FLIB_STATIC_API LZ4FLIB_API
     #else
    @@ -530,7 +655,7 @@ extern "C" {
             ITEM(ERROR_GENERIC) \
             ITEM(ERROR_maxBlockSize_invalid) \
             ITEM(ERROR_blockMode_invalid) \
    -        ITEM(ERROR_contentChecksumFlag_invalid) \
    +        ITEM(ERROR_parameter_invalid) \
             ITEM(ERROR_compressionLevel_invalid) \
             ITEM(ERROR_headerVersion_wrong) \
             ITEM(ERROR_blockChecksum_invalid) \
    @@ -548,6 +673,8 @@ extern "C" {
             ITEM(ERROR_frameDecoding_alreadyStarted) \
             ITEM(ERROR_compressionState_uninitialized) \
             ITEM(ERROR_parameter_null) \
    +        ITEM(ERROR_io_write) \
    +        ITEM(ERROR_io_read) \
             ITEM(ERROR_maxCode)
     
     #define LZ4F_GENERATE_ENUM(ENUM) LZ4F_##ENUM,
    @@ -558,22 +685,26 @@ typedef enum { LZ4F_LIST_ERRORS(LZ4F_GENERATE_ENUM)
     
     LZ4FLIB_STATIC_API LZ4F_errorCodes LZ4F_getErrorCode(size_t functionResult);
     
    +/**********************************
    + *  Advanced compression operations
    + *********************************/
     
     /*! LZ4F_getBlockSize() :
    - *  Return, in scalar format (size_t),
    - *  the maximum block size associated with blockSizeID.
    + * @return, in scalar format (size_t),
    + *          the maximum block size associated with @blockSizeID,
    + *          or an error code (can be tested using LZ4F_isError()) if @blockSizeID is invalid.
     **/
     LZ4FLIB_STATIC_API size_t LZ4F_getBlockSize(LZ4F_blockSizeID_t blockSizeID);
     
     /*! LZ4F_uncompressedUpdate() :
    - *  LZ4F_uncompressedUpdate() can be called repetitively to add as much data uncompressed data as necessary.
    + *  LZ4F_uncompressedUpdate() can be called repetitively to add data stored as uncompressed blocks.
      *  Important rule: dstCapacity MUST be large enough to store the entire source buffer as
      *  no compression is done for this operation
      *  If this condition is not respected, LZ4F_uncompressedUpdate() will fail (result is an errorCode).
      *  After an error, the state is left in a UB state, and must be re-initialized or freed.
    - *  If previously a compressed block was written, buffered data is flushed
    + *  If previously a compressed block was written, buffered data is flushed first,
      *  before appending uncompressed data is continued.
    - *  This is only supported when LZ4F_blockIndependent is used
    + *  This operation is only supported when LZ4F_blockIndependent is used.
      * `cOptPtr` is optional : NULL can be provided, in which case all options are set to default.
      * @return : number of bytes written into `dstBuffer` (it can be zero, meaning input data was just buffered).
      *           or an error code if it fails (which can be tested using LZ4F_isError())
    @@ -585,82 +716,10 @@ LZ4F_uncompressedUpdate(LZ4F_cctx* cctx,
                       const LZ4F_compressOptions_t* cOptPtr);
     
     /**********************************
    - *  Bulk processing dictionary API
    + *  Custom memory allocation
      *********************************/
     
    -/* A Dictionary is useful for the compression of small messages (KB range).
    - * It dramatically improves compression efficiency.
    - *
    - * LZ4 can ingest any input as dictionary, though only the last 64 KB are useful.
    - * Best results are generally achieved by using Zstandard's Dictionary Builder
    - * to generate a high-quality dictionary from a set of samples.
    - *
    - * Loading a dictionary has a cost, since it involves construction of tables.
    - * The Bulk processing dictionary API makes it possible to share this cost
    - * over an arbitrary number of compression jobs, even concurrently,
    - * markedly improving compression latency for these cases.
    - *
    - * The same dictionary will have to be used on the decompression side
    - * for decoding to be successful.
    - * To help identify the correct dictionary at decoding stage,
    - * the frame header allows optional embedding of a dictID field.
    - */
    -typedef struct LZ4F_CDict_s LZ4F_CDict;
    -
    -/*! LZ4_createCDict() :
    - *  When compressing multiple messages / blocks using the same dictionary, it's recommended to load it just once.
    - *  LZ4_createCDict() will create a digested dictionary, ready to start future compression operations without startup delay.
    - *  LZ4_CDict can be created once and shared by multiple threads concurrently, since its usage is read-only.
    - * `dictBuffer` can be released after LZ4_CDict creation, since its content is copied within CDict */
    -LZ4FLIB_STATIC_API LZ4F_CDict* LZ4F_createCDict(const void* dictBuffer, size_t dictSize);
    -LZ4FLIB_STATIC_API void        LZ4F_freeCDict(LZ4F_CDict* CDict);
    -
    -
    -/*! LZ4_compressFrame_usingCDict() :
    - *  Compress an entire srcBuffer into a valid LZ4 frame using a digested Dictionary.
    - *  cctx must point to a context created by LZ4F_createCompressionContext().
    - *  If cdict==NULL, compress without a dictionary.
    - *  dstBuffer MUST be >= LZ4F_compressFrameBound(srcSize, preferencesPtr).
    - *  If this condition is not respected, function will fail (@return an errorCode).
    - *  The LZ4F_preferences_t structure is optional : you may provide NULL as argument,
    - *  but it's not recommended, as it's the only way to provide dictID in the frame header.
    - * @return : number of bytes written into dstBuffer.
    - *           or an error code if it fails (can be tested using LZ4F_isError()) */
    -LZ4FLIB_STATIC_API size_t
    -LZ4F_compressFrame_usingCDict(LZ4F_cctx* cctx,
    -                              void* dst, size_t dstCapacity,
    -                        const void* src, size_t srcSize,
    -                        const LZ4F_CDict* cdict,
    -                        const LZ4F_preferences_t* preferencesPtr);
    -
    -
    -/*! LZ4F_compressBegin_usingCDict() :
    - *  Inits streaming dictionary compression, and writes the frame header into dstBuffer.
    - *  dstCapacity must be >= LZ4F_HEADER_SIZE_MAX bytes.
    - * `prefsPtr` is optional : you may provide NULL as argument,
    - *  however, it's the only way to provide dictID in the frame header.
    - * @return : number of bytes written into dstBuffer for the header,
    - *           or an error code (which can be tested using LZ4F_isError()) */
    -LZ4FLIB_STATIC_API size_t
    -LZ4F_compressBegin_usingCDict(LZ4F_cctx* cctx,
    -                              void* dstBuffer, size_t dstCapacity,
    -                        const LZ4F_CDict* cdict,
    -                        const LZ4F_preferences_t* prefsPtr);
    -
    -
    -/*! LZ4F_decompress_usingDict() :
    - *  Same as LZ4F_decompress(), using a predefined dictionary.
    - *  Dictionary is used "in place", without any preprocessing.
    -**  It must remain accessible throughout the entire frame decoding. */
    -LZ4FLIB_STATIC_API size_t
    -LZ4F_decompress_usingDict(LZ4F_dctx* dctxPtr,
    -                          void* dstBuffer, size_t* dstSizePtr,
    -                    const void* srcBuffer, size_t* srcSizePtr,
    -                    const void* dict, size_t dictSize,
    -                    const LZ4F_decompressOptions_t* decompressOptionsPtr);
    -
    -
    -/*! Custom memory allocation :
    +/*! Custom memory allocation : v1.9.4+
      *  These prototypes make it possible to pass custom allocation/free functions.
      *  LZ4F_customMem is provided at state creation time, using LZ4F_create*_advanced() listed below.
      *  All allocation/free operations will be completed using these custom variants instead of regular  ones.
    diff --git a/lib/lz4hc.c b/lib/lz4hc.c
    index b21ad6bb599439c0ef90354ecb45cbbc84048042..4d8c36a6978fcae09e4c4a936572b4b271513466 100644
    --- a/lib/lz4hc.c
    +++ b/lib/lz4hc.c
    @@ -39,9 +39,10 @@
     ***************************************/
     
     /*! HEAPMODE :
    - *  Select how default compression function will allocate workplace memory,
    - *  in stack (0:fastest), or in heap (1:requires malloc()).
    - *  Since workplace is rather large, heap mode is recommended.
    + *  Select how stateless HC compression functions like `LZ4_compress_HC()`
    + *  allocate memory for their workspace:
    + *  in stack (0:fastest), or in heap (1:default, requires malloc()).
    + *  Since workspace is rather large, heap mode is recommended.
     **/
     #ifndef LZ4HC_HEAPMODE
     #  define LZ4HC_HEAPMODE 1
    @@ -51,19 +52,19 @@
     /*===    Dependency    ===*/
     #define LZ4_HC_STATIC_LINKING_ONLY
     #include "lz4hc.h"
    +#include 
     
     
    -/*===   Common definitions   ===*/
    -#if defined(__GNUC__)
    +/*===   Shared lz4.c code   ===*/
    +#ifndef LZ4_SRC_INCLUDED
    +# if defined(__GNUC__)
     #  pragma GCC diagnostic ignored "-Wunused-function"
    -#endif
    -#if defined (__clang__)
    +# endif
    +# if defined (__clang__)
     #  pragma clang diagnostic ignored "-Wunused-function"
    -#endif
    -
    -#define LZ4_COMMONDEFS_ONLY
    -#ifndef LZ4_SRC_INCLUDED
    -#include "lz4.c"   /* LZ4_count, constants, mem */
    +# endif
    +# define LZ4_COMMONDEFS_ONLY
    +# include "lz4.c"   /* LZ4_count, constants, mem */
     #endif
     
     
    @@ -79,17 +80,158 @@ typedef enum { noDictCtx, usingDictCtxHc } dictCtx_directive;
     /*===   Macros   ===*/
     #define MIN(a,b)   ( (a) < (b) ? (a) : (b) )
     #define MAX(a,b)   ( (a) > (b) ? (a) : (b) )
    -#define HASH_FUNCTION(i)         (((i) * 2654435761U) >> ((MINMATCH*8)-LZ4HC_HASH_LOG))
    -#define DELTANEXTMAXD(p)         chainTable[(p) & LZ4HC_MAXD_MASK]    /* flexible, LZ4HC_MAXD dependent */
    +
    +
    +/*===   Levels definition   ===*/
    +typedef enum { lz4mid, lz4hc, lz4opt } lz4hc_strat_e;
    +typedef struct {
    +    lz4hc_strat_e strat;
    +    int nbSearches;
    +    U32 targetLength;
    +} cParams_t;
    +static const cParams_t k_clTable[LZ4HC_CLEVEL_MAX+1] = {
    +    { lz4mid,    2, 16 },  /* 0, unused */
    +    { lz4mid,    2, 16 },  /* 1, unused */
    +    { lz4mid,    2, 16 },  /* 2 */
    +    { lz4hc,     4, 16 },  /* 3 */
    +    { lz4hc,     8, 16 },  /* 4 */
    +    { lz4hc,    16, 16 },  /* 5 */
    +    { lz4hc,    32, 16 },  /* 6 */
    +    { lz4hc,    64, 16 },  /* 7 */
    +    { lz4hc,   128, 16 },  /* 8 */
    +    { lz4hc,   256, 16 },  /* 9 */
    +    { lz4opt,   96, 64 },  /*10==LZ4HC_CLEVEL_OPT_MIN*/
    +    { lz4opt,  512,128 },  /*11 */
    +    { lz4opt,16384,LZ4_OPT_NUM },  /* 12==LZ4HC_CLEVEL_MAX */
    +};
    +
    +static cParams_t LZ4HC_getCLevelParams(int cLevel)
    +{
    +    /* note : clevel convention is a bit different from lz4frame,
    +     * possibly something worth revisiting for consistency */
    +    if (cLevel < 1)
    +        cLevel = LZ4HC_CLEVEL_DEFAULT;
    +    cLevel = MIN(LZ4HC_CLEVEL_MAX, cLevel);
    +    return k_clTable[cLevel];
    +}
    +
    +
    +/*===   Hashing   ===*/
    +#define LZ4HC_HASHSIZE 4
    +#define HASH_FUNCTION(i)      (((i) * 2654435761U) >> ((MINMATCH*8)-LZ4HC_HASH_LOG))
    +static U32 LZ4HC_hashPtr(const void* ptr) { return HASH_FUNCTION(LZ4_read32(ptr)); }
    +
    +#if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2)
    +/* lie to the compiler about data alignment; use with caution */
    +static U64 LZ4_read64(const void* memPtr) { return *(const U64*) memPtr; }
    +
    +#elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1)
    +/* __pack instructions are safer, but compiler specific */
    +LZ4_PACK(typedef struct { U64 u64; }) LZ4_unalign64;
    +static U64 LZ4_read64(const void* ptr) { return ((const LZ4_unalign64*)ptr)->u64; }
    +
    +#else  /* safe and portable access using memcpy() */
    +static U64 LZ4_read64(const void* memPtr)
    +{
    +    U64 val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val;
    +}
    +
    +#endif /* LZ4_FORCE_MEMORY_ACCESS */
    +
    +#define LZ4MID_HASHSIZE 8
    +#define LZ4MID_HASHLOG (LZ4HC_HASH_LOG-1)
    +#define LZ4MID_HASHTABLESIZE (1 << LZ4MID_HASHLOG)
    +
    +static U32 LZ4MID_hash4(U32 v) { return (v * 2654435761U) >> (32-LZ4MID_HASHLOG); }
    +static U32 LZ4MID_hash4Ptr(const void* ptr) { return LZ4MID_hash4(LZ4_read32(ptr)); }
    +/* note: hash7 hashes the lower 56-bits.
    + * It presumes input was read using little endian.*/
    +static U32 LZ4MID_hash7(U64 v) { return (U32)(((v  << (64-56)) * 58295818150454627ULL) >> (64-LZ4MID_HASHLOG)) ; }
    +static U64 LZ4_readLE64(const void* memPtr);
    +static U32 LZ4MID_hash8Ptr(const void* ptr) { return LZ4MID_hash7(LZ4_readLE64(ptr)); }
    +
    +static U64 LZ4_readLE64(const void* memPtr)
    +{
    +    if (LZ4_isLittleEndian()) {
    +        return LZ4_read64(memPtr);
    +    } else {
    +        const BYTE* p = (const BYTE*)memPtr;
    +        /* note: relies on the compiler to simplify this expression */
    +        return (U64)p[0] | ((U64)p[1]<<8) | ((U64)p[2]<<16) | ((U64)p[3]<<24)
    +            | ((U64)p[4]<<32) | ((U64)p[5]<<40) | ((U64)p[6]<<48) | ((U64)p[7]<<56);
    +    }
    +}
    +
    +
    +/*===   Count match length   ===*/
    +LZ4_FORCE_INLINE
    +unsigned LZ4HC_NbCommonBytes32(U32 val)
    +{
    +    assert(val != 0);
    +    if (LZ4_isLittleEndian()) {
    +#     if defined(_MSC_VER) && (_MSC_VER >= 1400) && !defined(LZ4_FORCE_SW_BITCOUNT)
    +        unsigned long r;
    +        _BitScanReverse(&r, val);
    +        return (unsigned)((31 - r) >> 3);
    +#     elif (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \
    +                            ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \
    +                                        !defined(LZ4_FORCE_SW_BITCOUNT)
    +        return (unsigned)__builtin_clz(val) >> 3;
    +#     else
    +        val >>= 8;
    +        val = ((((val + 0x00FFFF00) | 0x00FFFFFF) + val) |
    +              (val + 0x00FF0000)) >> 24;
    +        return (unsigned)val ^ 3;
    +#     endif
    +    } else {
    +#     if defined(_MSC_VER) && (_MSC_VER >= 1400) && !defined(LZ4_FORCE_SW_BITCOUNT)
    +        unsigned long r;
    +        _BitScanForward(&r, val);
    +        return (unsigned)(r >> 3);
    +#     elif (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \
    +                            ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \
    +                                        !defined(LZ4_FORCE_SW_BITCOUNT)
    +        return (unsigned)__builtin_ctz(val) >> 3;
    +#     else
    +        const U32 m = 0x01010101;
    +        return (unsigned)((((val - 1) ^ val) & (m - 1)) * m) >> 24;
    +#     endif
    +    }
    +}
    +
    +/** LZ4HC_countBack() :
    + * @return : negative value, nb of common bytes before ip/match */
    +LZ4_FORCE_INLINE
    +int LZ4HC_countBack(const BYTE* const ip, const BYTE* const match,
    +                    const BYTE* const iMin, const BYTE* const mMin)
    +{
    +    int back = 0;
    +    int const min = (int)MAX(iMin - ip, mMin - match);
    +    assert(min <= 0);
    +    assert(ip >= iMin); assert((size_t)(ip-iMin) < (1U<<31));
    +    assert(match >= mMin); assert((size_t)(match - mMin) < (1U<<31));
    +
    +    while ((back - min) > 3) {
    +        U32 const v = LZ4_read32(ip + back - 4) ^ LZ4_read32(match + back - 4);
    +        if (v) {
    +            return (back - (int)LZ4HC_NbCommonBytes32(v));
    +        } else back -= 4; /* 4-byte step */
    +    }
    +    /* check remainder if any */
    +    while ( (back > min)
    +         && (ip[back-1] == match[back-1]) )
    +            back--;
    +    return back;
    +}
    +
    +/*===   Chain table updates   ===*/
     #define DELTANEXTU16(table, pos) table[(U16)(pos)]   /* faster */
     /* Make fields passed to, and updated by LZ4HC_encodeSequence explicit */
     #define UPDATABLE(ip, op, anchor) &ip, &op, &anchor
     
    -static U32 LZ4HC_hashPtr(const void* ptr) { return HASH_FUNCTION(LZ4_read32(ptr)); }
    -
     
     /**************************************
    -*  HC Compression
    +*  Init
     **************************************/
     static void LZ4HC_clearTables (LZ4HC_CCtx_internal* hc4)
     {
    @@ -101,6 +243,7 @@ static void LZ4HC_init_internal (LZ4HC_CCtx_internal* hc4, const BYTE* start)
     {
         size_t const bufferSize = (size_t)(hc4->end - hc4->prefixStart);
         size_t newStartingOffset = bufferSize + hc4->dictLimit;
    +    DEBUGLOG(5, "LZ4HC_init_internal");
         assert(newStartingOffset >= bufferSize);  /* check overflow */
         if (newStartingOffset > 1 GB) {
             LZ4HC_clearTables(hc4);
    @@ -116,6 +259,524 @@ static void LZ4HC_init_internal (LZ4HC_CCtx_internal* hc4, const BYTE* start)
     }
     
     
    +/**************************************
    +*  Encode
    +**************************************/
    +/* LZ4HC_encodeSequence() :
    + * @return : 0 if ok,
    + *           1 if buffer issue detected */
    +LZ4_FORCE_INLINE int LZ4HC_encodeSequence (
    +    const BYTE** _ip,
    +    BYTE** _op,
    +    const BYTE** _anchor,
    +    int matchLength,
    +    int offset,
    +    limitedOutput_directive limit,
    +    BYTE* oend)
    +{
    +#define ip      (*_ip)
    +#define op      (*_op)
    +#define anchor  (*_anchor)
    +
    +    size_t length;
    +    BYTE* const token = op++;
    +
    +#if defined(LZ4_DEBUG) && (LZ4_DEBUG >= 6)
    +    static const BYTE* start = NULL;
    +    static U32 totalCost = 0;
    +    U32 const pos = (start==NULL) ? 0 : (U32)(anchor - start);
    +    U32 const ll = (U32)(ip - anchor);
    +    U32 const llAdd = (ll>=15) ? ((ll-15) / 255) + 1 : 0;
    +    U32 const mlAdd = (matchLength>=19) ? ((matchLength-19) / 255) + 1 : 0;
    +    U32 const cost = 1 + llAdd + ll + 2 + mlAdd;
    +    if (start==NULL) start = anchor;  /* only works for single segment */
    +    /* g_debuglog_enable = (pos >= 2228) & (pos <= 2262); */
    +    DEBUGLOG(6, "pos:%7u -- literals:%4u, match:%4i, offset:%5i, cost:%4u + %5u",
    +                pos,
    +                (U32)(ip - anchor), matchLength, offset,
    +                cost, totalCost);
    +    totalCost += cost;
    +#endif
    +
    +    /* Encode Literal length */
    +    length = (size_t)(ip - anchor);
    +    LZ4_STATIC_ASSERT(notLimited == 0);
    +    /* Check output limit */
    +    if (limit && ((op + (length / 255) + length + (2 + 1 + LASTLITERALS)) > oend)) {
    +        DEBUGLOG(6, "Not enough room to write %i literals (%i bytes remaining)",
    +                (int)length, (int)(oend - op));
    +        return 1;
    +    }
    +    if (length >= RUN_MASK) {
    +        size_t len = length - RUN_MASK;
    +        *token = (RUN_MASK << ML_BITS);
    +        for(; len >= 255 ; len -= 255) *op++ = 255;
    +        *op++ = (BYTE)len;
    +    } else {
    +        *token = (BYTE)(length << ML_BITS);
    +    }
    +
    +    /* Copy Literals */
    +    LZ4_wildCopy8(op, anchor, op + length);
    +    op += length;
    +
    +    /* Encode Offset */
    +    assert(offset <= LZ4_DISTANCE_MAX );
    +    assert(offset > 0);
    +    LZ4_writeLE16(op, (U16)(offset)); op += 2;
    +
    +    /* Encode MatchLength */
    +    assert(matchLength >= MINMATCH);
    +    length = (size_t)matchLength - MINMATCH;
    +    if (limit && (op + (length / 255) + (1 + LASTLITERALS) > oend)) {
    +        DEBUGLOG(6, "Not enough room to write match length");
    +        return 1;   /* Check output limit */
    +    }
    +    if (length >= ML_MASK) {
    +        *token += ML_MASK;
    +        length -= ML_MASK;
    +        for(; length >= 510 ; length -= 510) { *op++ = 255; *op++ = 255; }
    +        if (length >= 255) { length -= 255; *op++ = 255; }
    +        *op++ = (BYTE)length;
    +    } else {
    +        *token += (BYTE)(length);
    +    }
    +
    +    /* Prepare next loop */
    +    ip += matchLength;
    +    anchor = ip;
    +
    +    return 0;
    +
    +#undef ip
    +#undef op
    +#undef anchor
    +}
    +
    +
    +typedef struct {
    +    int off;
    +    int len;
    +    int back;  /* negative value */
    +} LZ4HC_match_t;
    +
    +LZ4HC_match_t LZ4HC_searchExtDict(const BYTE* ip, U32 ipIndex,
    +        const BYTE* const iLowLimit, const BYTE* const iHighLimit,
    +        const LZ4HC_CCtx_internal* dictCtx, U32 gDictEndIndex,
    +        int currentBestML, int nbAttempts)
    +{
    +    size_t const lDictEndIndex = (size_t)(dictCtx->end - dictCtx->prefixStart) + dictCtx->dictLimit;
    +    U32 lDictMatchIndex = dictCtx->hashTable[LZ4HC_hashPtr(ip)];
    +    U32 matchIndex = lDictMatchIndex + gDictEndIndex - (U32)lDictEndIndex;
    +    int offset = 0, sBack = 0;
    +    assert(lDictEndIndex <= 1 GB);
    +    if (lDictMatchIndex>0)
    +        DEBUGLOG(7, "lDictEndIndex = %zu, lDictMatchIndex = %u", lDictEndIndex, lDictMatchIndex);
    +    while (ipIndex - matchIndex <= LZ4_DISTANCE_MAX && nbAttempts--) {
    +        const BYTE* const matchPtr = dictCtx->prefixStart - dictCtx->dictLimit + lDictMatchIndex;
    +
    +        if (LZ4_read32(matchPtr) == LZ4_read32(ip)) {
    +            int mlt;
    +            int back = 0;
    +            const BYTE* vLimit = ip + (lDictEndIndex - lDictMatchIndex);
    +            if (vLimit > iHighLimit) vLimit = iHighLimit;
    +            mlt = (int)LZ4_count(ip+MINMATCH, matchPtr+MINMATCH, vLimit) + MINMATCH;
    +            back = (ip > iLowLimit) ? LZ4HC_countBack(ip, matchPtr, iLowLimit, dictCtx->prefixStart) : 0;
    +            mlt -= back;
    +            if (mlt > currentBestML) {
    +                currentBestML = mlt;
    +                offset = (int)(ipIndex - matchIndex);
    +                sBack = back;
    +                DEBUGLOG(7, "found match of length %i within extDictCtx", currentBestML);
    +        }   }
    +
    +        {   U32 const nextOffset = DELTANEXTU16(dictCtx->chainTable, lDictMatchIndex);
    +            lDictMatchIndex -= nextOffset;
    +            matchIndex -= nextOffset;
    +    }   }
    +
    +    {   LZ4HC_match_t md;
    +        md.len = currentBestML;
    +        md.off = offset;
    +        md.back = sBack;
    +        return md;
    +    }
    +}
    +
    +typedef LZ4HC_match_t (*LZ4MID_searchIntoDict_f)(const BYTE* ip, U32 ipIndex,
    +        const BYTE* const iHighLimit,
    +        const LZ4HC_CCtx_internal* dictCtx, U32 gDictEndIndex);
    +
    +static LZ4HC_match_t LZ4MID_searchHCDict(const BYTE* ip, U32 ipIndex,
    +        const BYTE* const iHighLimit,
    +        const LZ4HC_CCtx_internal* dictCtx, U32 gDictEndIndex)
    +{
    +    return LZ4HC_searchExtDict(ip,ipIndex,
    +                            ip, iHighLimit,
    +                            dictCtx, gDictEndIndex,
    +                            MINMATCH-1, 2);
    +}
    +
    +static LZ4HC_match_t LZ4MID_searchExtDict(const BYTE* ip, U32 ipIndex,
    +        const BYTE* const iHighLimit,
    +        const LZ4HC_CCtx_internal* dictCtx, U32 gDictEndIndex)
    +{
    +    size_t const lDictEndIndex = (size_t)(dictCtx->end - dictCtx->prefixStart) + dictCtx->dictLimit;
    +    const U32* const hash4Table = dictCtx->hashTable;
    +    const U32* const hash8Table = hash4Table + LZ4MID_HASHTABLESIZE;
    +    DEBUGLOG(7, "LZ4MID_searchExtDict (ipIdx=%u)", ipIndex);
    +
    +    /* search long match first */
    +    {   U32 l8DictMatchIndex = hash8Table[LZ4MID_hash8Ptr(ip)];
    +        U32 m8Index = l8DictMatchIndex + gDictEndIndex - (U32)lDictEndIndex;
    +        assert(lDictEndIndex <= 1 GB);
    +        if (ipIndex - m8Index <= LZ4_DISTANCE_MAX) {
    +            const BYTE* const matchPtr = dictCtx->prefixStart - dictCtx->dictLimit + l8DictMatchIndex;
    +            const size_t safeLen = MIN(lDictEndIndex - l8DictMatchIndex, (size_t)(iHighLimit - ip));
    +            int mlt = (int)LZ4_count(ip, matchPtr, ip + safeLen);
    +            if (mlt >= MINMATCH) {
    +                LZ4HC_match_t md;
    +                DEBUGLOG(7, "Found long ExtDict match of len=%u", mlt);
    +                md.len = mlt;
    +                md.off = (int)(ipIndex - m8Index);
    +                md.back = 0;
    +                return md;
    +            }
    +        }
    +    }
    +
    +    /* search for short match second */
    +    {   U32 l4DictMatchIndex = hash4Table[LZ4MID_hash4Ptr(ip)];
    +        U32 m4Index = l4DictMatchIndex + gDictEndIndex - (U32)lDictEndIndex;
    +        if (ipIndex - m4Index <= LZ4_DISTANCE_MAX) {
    +            const BYTE* const matchPtr = dictCtx->prefixStart - dictCtx->dictLimit + l4DictMatchIndex;
    +            const size_t safeLen = MIN(lDictEndIndex - l4DictMatchIndex, (size_t)(iHighLimit - ip));
    +            int mlt = (int)LZ4_count(ip, matchPtr, ip + safeLen);
    +            if (mlt >= MINMATCH) {
    +                LZ4HC_match_t md;
    +                DEBUGLOG(7, "Found short ExtDict match of len=%u", mlt);
    +                md.len = mlt;
    +                md.off = (int)(ipIndex - m4Index);
    +                md.back = 0;
    +                return md;
    +            }
    +        }
    +    }
    +
    +    /* nothing found */
    +    {   LZ4HC_match_t const md = {0, 0, 0 };
    +        return md;
    +    }
    +}
    +
    +/**************************************
    +*  Mid Compression (level 2)
    +**************************************/
    +
    +LZ4_FORCE_INLINE void
    +LZ4MID_addPosition(U32* hTable, U32 hValue, U32 index)
    +{
    +    hTable[hValue] = index;
    +}
    +
    +#define ADDPOS8(_p, _idx) LZ4MID_addPosition(hash8Table, LZ4MID_hash8Ptr(_p), _idx)
    +#define ADDPOS4(_p, _idx) LZ4MID_addPosition(hash4Table, LZ4MID_hash4Ptr(_p), _idx)
    +
    +/* Fill hash tables with references into dictionary.
    + * The resulting table is only exploitable by LZ4MID (level 2) */
    +static void
    +LZ4MID_fillHTable (LZ4HC_CCtx_internal* cctx, const void* dict, size_t size)
    +{
    +    U32* const hash4Table = cctx->hashTable;
    +    U32* const hash8Table = hash4Table + LZ4MID_HASHTABLESIZE;
    +    const BYTE* const prefixPtr = (const BYTE*)dict;
    +    U32 const prefixIdx = cctx->dictLimit;
    +    U32 const target = prefixIdx + (U32)size - LZ4MID_HASHSIZE;
    +    U32 idx = cctx->nextToUpdate;
    +    assert(dict == cctx->prefixStart);
    +    DEBUGLOG(4, "LZ4MID_fillHTable (size:%zu)", size);
    +    if (size <= LZ4MID_HASHSIZE)
    +        return;
    +
    +    for (; idx < target; idx += 3) {
    +        ADDPOS4(prefixPtr+idx-prefixIdx, idx);
    +        ADDPOS8(prefixPtr+idx+1-prefixIdx, idx+1);
    +    }
    +
    +    idx = (size > 32 KB + LZ4MID_HASHSIZE) ? target - 32 KB : cctx->nextToUpdate;
    +    for (; idx < target; idx += 1) {
    +        ADDPOS8(prefixPtr+idx-prefixIdx, idx);
    +    }
    +
    +    cctx->nextToUpdate = target;
    +}
    +
    +static LZ4MID_searchIntoDict_f select_searchDict_function(const LZ4HC_CCtx_internal* dictCtx)
    +{
    +    if (dictCtx == NULL) return NULL;
    +    if (LZ4HC_getCLevelParams(dictCtx->compressionLevel).strat == lz4mid)
    +        return LZ4MID_searchExtDict;
    +    return LZ4MID_searchHCDict;
    +}
    +
    +static int LZ4MID_compress (
    +    LZ4HC_CCtx_internal* const ctx,
    +    const char* const src,
    +    char* const dst,
    +    int* srcSizePtr,
    +    int const maxOutputSize,
    +    const limitedOutput_directive limit,
    +    const dictCtx_directive dict
    +    )
    +{
    +    U32* const hash4Table = ctx->hashTable;
    +    U32* const hash8Table = hash4Table + LZ4MID_HASHTABLESIZE;
    +    const BYTE* ip = (const BYTE*)src;
    +    const BYTE* anchor = ip;
    +    const BYTE* const iend = ip + *srcSizePtr;
    +    const BYTE* const mflimit = iend - MFLIMIT;
    +    const BYTE* const matchlimit = (iend - LASTLITERALS);
    +    const BYTE* const ilimit = (iend - LZ4MID_HASHSIZE);
    +    BYTE* op = (BYTE*)dst;
    +    BYTE* oend = op + maxOutputSize;
    +
    +    const BYTE* const prefixPtr = ctx->prefixStart;
    +    const U32 prefixIdx = ctx->dictLimit;
    +    const U32 ilimitIdx = (U32)(ilimit - prefixPtr) + prefixIdx;
    +    const BYTE* const dictStart = ctx->dictStart;
    +    const U32 dictIdx = ctx->lowLimit;
    +    const U32 gDictEndIndex = ctx->lowLimit;
    +    const LZ4MID_searchIntoDict_f searchIntoDict = (dict == usingDictCtxHc) ? select_searchDict_function(ctx->dictCtx) : NULL;
    +    unsigned matchLength;
    +    unsigned matchDistance;
    +
    +    /* input sanitization */
    +    DEBUGLOG(5, "LZ4MID_compress (%i bytes)", *srcSizePtr);
    +    if (dict == usingDictCtxHc) DEBUGLOG(5, "usingDictCtxHc");
    +    assert(*srcSizePtr >= 0);
    +    if (*srcSizePtr) assert(src != NULL);
    +    if (maxOutputSize) assert(dst != NULL);
    +    if (*srcSizePtr < 0) return 0;  /* invalid */
    +    if (maxOutputSize < 0) return 0; /* invalid */
    +    if (*srcSizePtr > LZ4_MAX_INPUT_SIZE) {
    +        /* forbidden: no input is allowed to be that large */
    +        return 0;
    +    }
    +    if (limit == fillOutput) oend -= LASTLITERALS;  /* Hack for support LZ4 format restriction */
    +    if (*srcSizePtr < LZ4_minLength)
    +        goto _lz4mid_last_literals;  /* Input too small, no compression (all literals) */
    +
    +    /* main loop */
    +    while (ip <= mflimit) {
    +        const U32 ipIndex = (U32)(ip - prefixPtr) + prefixIdx;
    +        /* search long match */
    +        {   U32 const h8 = LZ4MID_hash8Ptr(ip);
    +            U32 const pos8 = hash8Table[h8];
    +            assert(h8 < LZ4MID_HASHTABLESIZE);
    +            assert(pos8 < ipIndex);
    +            LZ4MID_addPosition(hash8Table, h8, ipIndex);
    +            if (ipIndex - pos8 <= LZ4_DISTANCE_MAX) {
    +                /* match candidate found */
    +                if (pos8 >= prefixIdx) {
    +                    const BYTE* const matchPtr = prefixPtr + pos8 - prefixIdx;
    +                    assert(matchPtr < ip);
    +                    matchLength = LZ4_count(ip, matchPtr, matchlimit);
    +                    if (matchLength >= MINMATCH) {
    +                        DEBUGLOG(7, "found long match at pos %u (len=%u)", pos8, matchLength);
    +                        matchDistance = ipIndex - pos8;
    +                        goto _lz4mid_encode_sequence;
    +                    }
    +                } else {
    +                    if (pos8 >= dictIdx) {
    +                        /* extDict match candidate */
    +                        const BYTE* const matchPtr = dictStart + (pos8 - dictIdx);
    +                        const size_t safeLen = MIN(prefixIdx - pos8, (size_t)(matchlimit - ip));
    +                        matchLength = LZ4_count(ip, matchPtr, ip + safeLen);
    +                        if (matchLength >= MINMATCH) {
    +                            DEBUGLOG(7, "found long match at ExtDict pos %u (len=%u)", pos8, matchLength);
    +                            matchDistance = ipIndex - pos8;
    +                            goto _lz4mid_encode_sequence;
    +                        }
    +                    }
    +                }
    +        }   }
    +        /* search short match */
    +        {   U32 const h4 = LZ4MID_hash4Ptr(ip);
    +            U32 const pos4 = hash4Table[h4];
    +            assert(h4 < LZ4MID_HASHTABLESIZE);
    +            assert(pos4 < ipIndex);
    +            LZ4MID_addPosition(hash4Table, h4, ipIndex);
    +            if (ipIndex - pos4 <= LZ4_DISTANCE_MAX) {
    +                /* match candidate found */
    +                if (pos4 >= prefixIdx) {
    +                /* only search within prefix */
    +                    const BYTE* const matchPtr = prefixPtr + (pos4 - prefixIdx);
    +                    assert(matchPtr < ip);
    +                    assert(matchPtr >= prefixPtr);
    +                    matchLength = LZ4_count(ip, matchPtr, matchlimit);
    +                    if (matchLength >= MINMATCH) {
    +                        /* short match found, let's just check ip+1 for longer */
    +                        U32 const h8 = LZ4MID_hash8Ptr(ip+1);
    +                        U32 const pos8 = hash8Table[h8];
    +                        U32 const m2Distance = ipIndex + 1 - pos8;
    +                        matchDistance = ipIndex - pos4;
    +                        if ( m2Distance <= LZ4_DISTANCE_MAX
    +                        && pos8 >= prefixIdx /* only search within prefix */
    +                        && likely(ip < mflimit)
    +                        ) {
    +                            const BYTE* const m2Ptr = prefixPtr + (pos8 - prefixIdx);
    +                            unsigned ml2 = LZ4_count(ip+1, m2Ptr, matchlimit);
    +                            if (ml2 > matchLength) {
    +                                LZ4MID_addPosition(hash8Table, h8, ipIndex+1);
    +                                ip++;
    +                                matchLength = ml2;
    +                                matchDistance = m2Distance;
    +                        }   }
    +                        goto _lz4mid_encode_sequence;
    +                    }
    +                } else {
    +                    if (pos4 >= dictIdx) {
    +                        /* extDict match candidate */
    +                        const BYTE* const matchPtr = dictStart + (pos4 - dictIdx);
    +                        const size_t safeLen = MIN(prefixIdx - pos4, (size_t)(matchlimit - ip));
    +                        matchLength = LZ4_count(ip, matchPtr, ip + safeLen);
    +                        if (matchLength >= MINMATCH) {
    +                            DEBUGLOG(7, "found match at ExtDict pos %u (len=%u)", pos4, matchLength);
    +                            matchDistance = ipIndex - pos4;
    +                            goto _lz4mid_encode_sequence;
    +                        }
    +                    }
    +                }
    +        }   }
    +        /* no match found in prefix */
    +        if ( (dict == usingDictCtxHc)
    +          && (ipIndex - gDictEndIndex < LZ4_DISTANCE_MAX - 8) ) {
    +            /* search a match into external dictionary */
    +            LZ4HC_match_t dMatch = searchIntoDict(ip, ipIndex,
    +                    matchlimit,
    +                    ctx->dictCtx, gDictEndIndex);
    +            if (dMatch.len >= MINMATCH) {
    +                DEBUGLOG(7, "found Dictionary match (offset=%i)", dMatch.off);
    +                assert(dMatch.back == 0);
    +                matchLength = (unsigned)dMatch.len;
    +                matchDistance = (unsigned)dMatch.off;
    +                goto _lz4mid_encode_sequence;
    +            }
    +        }
    +        /* no match found */
    +        ip += 1 + ((ip-anchor) >> 9);  /* skip faster over incompressible data */
    +        continue;
    +
    +_lz4mid_encode_sequence:
    +        /* catch back */
    +        while (((ip > anchor) & ((U32)(ip-prefixPtr) > matchDistance)) && (unlikely(ip[-1] == ip[-(int)matchDistance-1]))) {
    +            ip--;  matchLength++;
    +        };
    +
    +        /* fill table with beginning of match */
    +        ADDPOS8(ip+1, ipIndex+1);
    +        ADDPOS8(ip+2, ipIndex+2);
    +        ADDPOS4(ip+1, ipIndex+1);
    +
    +        /* encode */
    +        {   BYTE* const saved_op = op;
    +            /* LZ4HC_encodeSequence always updates @op; on success, it updates @ip and @anchor */
    +            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
    +                    (int)matchLength, (int)matchDistance,
    +                    limit, oend) ) {
    +                op = saved_op;  /* restore @op value before failed LZ4HC_encodeSequence */
    +                goto _lz4mid_dest_overflow;
    +            }
    +        }
    +
    +        /* fill table with end of match */
    +        {   U32 endMatchIdx = (U32)(ip-prefixPtr) + prefixIdx;
    +            U32 pos_m2 = endMatchIdx - 2;
    +            if (pos_m2 < ilimitIdx) {
    +                if (likely(ip - prefixPtr > 5)) {
    +                    ADDPOS8(ip-5, endMatchIdx - 5);
    +                }
    +                ADDPOS8(ip-3, endMatchIdx - 3);
    +                ADDPOS8(ip-2, endMatchIdx - 2);
    +                ADDPOS4(ip-2, endMatchIdx - 2);
    +                ADDPOS4(ip-1, endMatchIdx - 1);
    +            }
    +        }
    +    }
    +
    +_lz4mid_last_literals:
    +    /* Encode Last Literals */
    +    {   size_t lastRunSize = (size_t)(iend - anchor);  /* literals */
    +        size_t llAdd = (lastRunSize + 255 - RUN_MASK) / 255;
    +        size_t const totalSize = 1 + llAdd + lastRunSize;
    +        if (limit == fillOutput) oend += LASTLITERALS;  /* restore correct value */
    +        if (limit && (op + totalSize > oend)) {
    +            if (limit == limitedOutput) return 0;  /* not enough space in @dst */
    +            /* adapt lastRunSize to fill 'dest' */
    +            lastRunSize  = (size_t)(oend - op) - 1 /*token*/;
    +            llAdd = (lastRunSize + 256 - RUN_MASK) / 256;
    +            lastRunSize -= llAdd;
    +        }
    +        DEBUGLOG(6, "Final literal run : %i literals", (int)lastRunSize);
    +        ip = anchor + lastRunSize;  /* can be != iend if limit==fillOutput */
    +
    +        if (lastRunSize >= RUN_MASK) {
    +            size_t accumulator = lastRunSize - RUN_MASK;
    +            *op++ = (RUN_MASK << ML_BITS);
    +            for(; accumulator >= 255 ; accumulator -= 255)
    +                *op++ = 255;
    +            *op++ = (BYTE) accumulator;
    +        } else {
    +            *op++ = (BYTE)(lastRunSize << ML_BITS);
    +        }
    +        assert(lastRunSize <= (size_t)(oend - op));
    +        LZ4_memcpy(op, anchor, lastRunSize);
    +        op += lastRunSize;
    +    }
    +
    +    /* End */
    +    DEBUGLOG(5, "compressed %i bytes into %i bytes", *srcSizePtr, (int)((char*)op - dst));
    +    assert(ip >= (const BYTE*)src);
    +    assert(ip <= iend);
    +    *srcSizePtr = (int)(ip - (const BYTE*)src);
    +    assert((char*)op >= dst);
    +    assert(op <= oend);
    +    assert((char*)op - dst < INT_MAX);
    +    return (int)((char*)op - dst);
    +
    +_lz4mid_dest_overflow:
    +    if (limit == fillOutput) {
    +        /* Assumption : @ip, @anchor, @optr and @matchLength must be set correctly */
    +        size_t const ll = (size_t)(ip - anchor);
    +        size_t const ll_addbytes = (ll + 240) / 255;
    +        size_t const ll_totalCost = 1 + ll_addbytes + ll;
    +        BYTE* const maxLitPos = oend - 3; /* 2 for offset, 1 for token */
    +        DEBUGLOG(6, "Last sequence is overflowing : %u literals, %u remaining space",
    +                (unsigned)ll, (unsigned)(oend-op));
    +        if (op + ll_totalCost <= maxLitPos) {
    +            /* ll validated; now adjust match length */
    +            size_t const bytesLeftForMl = (size_t)(maxLitPos - (op+ll_totalCost));
    +            size_t const maxMlSize = MINMATCH + (ML_MASK-1) + (bytesLeftForMl * 255);
    +            assert(maxMlSize < INT_MAX);
    +            if ((size_t)matchLength > maxMlSize) matchLength= (unsigned)maxMlSize;
    +            if ((oend + LASTLITERALS) - (op + ll_totalCost + 2) - 1 + matchLength >= MFLIMIT) {
    +            DEBUGLOG(6, "Let's encode a last sequence (ll=%u, ml=%u)", (unsigned)ll, matchLength);
    +                LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
    +                        (int)matchLength, (int)matchDistance,
    +                        notLimited, oend);
    +        }   }
    +        DEBUGLOG(6, "Let's finish with a run of literals (%u bytes left)", (unsigned)(oend-op));
    +        goto _lz4mid_last_literals;
    +    }
    +    /* compression failed */
    +    return 0;
    +}
    +
    +
    +/**************************************
    +*  HC Compression - Search
    +**************************************/
    +
     /* Update chains up to ip (excluded) */
     LZ4_FORCE_INLINE void LZ4HC_Insert (LZ4HC_CCtx_internal* hc4, const BYTE* ip)
     {
    @@ -130,31 +791,14 @@ LZ4_FORCE_INLINE void LZ4HC_Insert (LZ4HC_CCtx_internal* hc4, const BYTE* ip)
     
         while (idx < target) {
             U32 const h = LZ4HC_hashPtr(prefixPtr+idx-prefixIdx);
    -        size_t delta = idx - hashTable[h];
    -        if (delta>LZ4_DISTANCE_MAX) delta = LZ4_DISTANCE_MAX;
    -        DELTANEXTU16(chainTable, idx) = (U16)delta;
    -        hashTable[h] = idx;
    -        idx++;
    -    }
    -
    -    hc4->nextToUpdate = target;
    -}
    -
    -/** LZ4HC_countBack() :
    - * @return : negative value, nb of common bytes before ip/match */
    -LZ4_FORCE_INLINE
    -int LZ4HC_countBack(const BYTE* const ip, const BYTE* const match,
    -                    const BYTE* const iMin, const BYTE* const mMin)
    -{
    -    int back = 0;
    -    int const min = (int)MAX(iMin - ip, mMin - match);
    -    assert(min <= 0);
    -    assert(ip >= iMin); assert((size_t)(ip-iMin) < (1U<<31));
    -    assert(match >= mMin); assert((size_t)(match - mMin) < (1U<<31));
    -    while ( (back > min)
    -         && (ip[back-1] == match[back-1]) )
    -            back--;
    -    return back;
    +        size_t delta = idx - hashTable[h];
    +        if (delta>LZ4_DISTANCE_MAX) delta = LZ4_DISTANCE_MAX;
    +        DELTANEXTU16(chainTable, idx) = (U16)delta;
    +        hashTable[h] = idx;
    +        idx++;
    +    }
    +
    +    hc4->nextToUpdate = target;
     }
     
     #if defined(_MSC_VER)
    @@ -236,22 +880,21 @@ static int LZ4HC_protectDictEnd(U32 const dictLimit, U32 const matchIndex)
     typedef enum { rep_untested, rep_not, rep_confirmed } repeat_state_e;
     typedef enum { favorCompressionRatio=0, favorDecompressionSpeed } HCfavor_e;
     
    -LZ4_FORCE_INLINE int
    +
    +LZ4_FORCE_INLINE LZ4HC_match_t
     LZ4HC_InsertAndGetWiderMatch (
             LZ4HC_CCtx_internal* const hc4,
             const BYTE* const ip,
             const BYTE* const iLowLimit, const BYTE* const iHighLimit,
             int longest,
    -        const BYTE** matchpos,
    -        const BYTE** startpos,
             const int maxNbAttempts,
             const int patternAnalysis, const int chainSwap,
             const dictCtx_directive dict,
             const HCfavor_e favorDecSpeed)
     {
         U16* const chainTable = hc4->chainTable;
    -    U32* const HashTable = hc4->hashTable;
    -    const LZ4HC_CCtx_internal * const dictCtx = hc4->dictCtx;
    +    U32* const hashTable = hc4->hashTable;
    +    const LZ4HC_CCtx_internal* const dictCtx = hc4->dictCtx;
         const BYTE* const prefixPtr = hc4->prefixStart;
         const U32 prefixIdx = hc4->dictLimit;
         const U32 ipIndex = (U32)(ip - prefixPtr) + prefixIdx;
    @@ -267,22 +910,24 @@ LZ4HC_InsertAndGetWiderMatch (
         U32 matchIndex;
         repeat_state_e repeat = rep_untested;
         size_t srcPatternLength = 0;
    +    int offset = 0, sBack = 0;
     
         DEBUGLOG(7, "LZ4HC_InsertAndGetWiderMatch");
         /* First Match */
    -    LZ4HC_Insert(hc4, ip);
    -    matchIndex = HashTable[LZ4HC_hashPtr(ip)];
    -    DEBUGLOG(7, "First match at index %u / %u (lowestMatchIndex)",
    -                matchIndex, lowestMatchIndex);
    +    LZ4HC_Insert(hc4, ip);  /* insert all prior positions up to ip (excluded) */
    +    matchIndex = hashTable[LZ4HC_hashPtr(ip)];
    +    DEBUGLOG(7, "First candidate match for pos %u found at index %u / %u (lowestMatchIndex)",
    +                ipIndex, matchIndex, lowestMatchIndex);
     
         while ((matchIndex>=lowestMatchIndex) && (nbAttempts>0)) {
             int matchLength=0;
             nbAttempts--;
             assert(matchIndex < ipIndex);
             if (favorDecSpeed && (ipIndex - matchIndex < 8)) {
    -            /* do nothing */
    +            /* do nothing:
    +             * favorDecSpeed intentionally skips matches with offset < 8 */
             } else if (matchIndex >= prefixIdx) {   /* within current Prefix */
    -            const BYTE* const matchPtr = prefixPtr + matchIndex - prefixIdx;
    +            const BYTE* const matchPtr = prefixPtr + (matchIndex - prefixIdx);
                 assert(matchPtr < ip);
                 assert(longest >= 1);
                 if (LZ4_read16(iLowLimit + longest - 1) == LZ4_read16(matchPtr - lookBackLength + longest - 1)) {
    @@ -292,10 +937,11 @@ LZ4HC_InsertAndGetWiderMatch (
                         matchLength -= back;
                         if (matchLength > longest) {
                             longest = matchLength;
    -                        *matchpos = matchPtr + back;
    -                        *startpos = ip + back;
    +                        offset = (int)(ipIndex - matchIndex);
    +                        sBack = back;
    +                        DEBUGLOG(7, "Found match of len=%i within prefix, offset=%i, back=%i", longest, offset, -back);
                 }   }   }
    -        } else {   /* lowestMatchIndex <= matchIndex < dictLimit */
    +        } else {   /* lowestMatchIndex <= matchIndex < dictLimit : within Ext Dict */
                 const BYTE* const matchPtr = dictStart + (matchIndex - dictIdx);
                 assert(matchIndex >= dictIdx);
                 if ( likely(matchIndex <= prefixIdx - 4)
    @@ -310,8 +956,9 @@ LZ4HC_InsertAndGetWiderMatch (
                     matchLength -= back;
                     if (matchLength > longest) {
                         longest = matchLength;
    -                    *matchpos = prefixPtr - prefixIdx + matchIndex + back;   /* virtual pos, relative to ip, to retrieve offset */
    -                    *startpos = ip + back;
    +                    offset = (int)(ipIndex - matchIndex);
    +                    sBack = back;
    +                    DEBUGLOG(7, "Found match of len=%i within dict, offset=%i, back=%i", longest, offset, -back);
             }   }   }
     
             if (chainSwap && matchLength==longest) {   /* better match => select a better chain */
    @@ -344,6 +991,7 @@ LZ4HC_InsertAndGetWiderMatch (
                     if (repeat == rep_untested) {
                         if ( ((pattern & 0xFFFF) == (pattern >> 16))
                           &  ((pattern & 0xFF)   == (pattern >> 24)) ) {
    +                        DEBUGLOG(7, "Repeat pattern detected, char %02X", pattern >> 24);
                             repeat = rep_confirmed;
                             srcPatternLength = LZ4HC_countPattern(ip+sizeof(pattern), iHighLimit, pattern) + sizeof(pattern);
                         } else {
    @@ -352,7 +1000,7 @@ LZ4HC_InsertAndGetWiderMatch (
                     if ( (repeat == rep_confirmed) && (matchCandidateIdx >= lowestMatchIndex)
                       && LZ4HC_protectDictEnd(prefixIdx, matchCandidateIdx) ) {
                         const int extDict = matchCandidateIdx < prefixIdx;
    -                    const BYTE* const matchPtr = (extDict ? dictStart - dictIdx : prefixPtr - prefixIdx) + matchCandidateIdx;
    +                    const BYTE* const matchPtr = extDict ? dictStart + (matchCandidateIdx - dictIdx) : prefixPtr + (matchCandidateIdx - prefixIdx);
                         if (LZ4_read32(matchPtr) == pattern) {  /* good candidate */
                             const BYTE* const iLimit = extDict ? dictEnd : iHighLimit;
                             size_t forwardPatternLength = LZ4HC_countPattern(matchPtr+sizeof(pattern), iLimit, pattern) + sizeof(pattern);
    @@ -398,8 +1046,9 @@ LZ4HC_InsertAndGetWiderMatch (
                                                 if ((size_t)(ip - prefixPtr) + prefixIdx - matchIndex > LZ4_DISTANCE_MAX) break;
                                                 assert(maxML < 2 GB);
                                                 longest = (int)maxML;
    -                                            *matchpos = prefixPtr - prefixIdx + matchIndex;   /* virtual pos, relative to ip, to retrieve offset */
    -                                            *startpos = ip;
    +                                            offset = (int)(ipIndex - matchIndex);
    +                                            assert(sBack == 0);
    +                                            DEBUGLOG(7, "Found repeat pattern match of len=%i, offset=%i", longest, offset);
                                             }
                                             {   U32 const distToNextPattern = DELTANEXTU16(chainTable, matchIndex);
                                                 if (distToNextPattern > matchIndex) break;  /* avoid overflow */
    @@ -416,11 +1065,12 @@ LZ4HC_InsertAndGetWiderMatch (
     
         if ( dict == usingDictCtxHc
           && nbAttempts > 0
    -      && ipIndex - lowestMatchIndex < LZ4_DISTANCE_MAX) {
    +      && withinStartDistance) {
             size_t const dictEndOffset = (size_t)(dictCtx->end - dictCtx->prefixStart) + dictCtx->dictLimit;
             U32 dictMatchIndex = dictCtx->hashTable[LZ4HC_hashPtr(ip)];
             assert(dictEndOffset <= 1 GB);
             matchIndex = dictMatchIndex + lowestMatchIndex - (U32)dictEndOffset;
    +        if (dictMatchIndex>0) DEBUGLOG(7, "dictEndOffset = %zu, dictMatchIndex = %u => relative matchIndex = %i", dictEndOffset, dictMatchIndex, (int)dictMatchIndex - (int)dictEndOffset);
             while (ipIndex - matchIndex <= LZ4_DISTANCE_MAX && nbAttempts--) {
                 const BYTE* const matchPtr = dictCtx->prefixStart - dictCtx->dictLimit + dictMatchIndex;
     
    @@ -434,8 +1084,9 @@ LZ4HC_InsertAndGetWiderMatch (
                     mlt -= back;
                     if (mlt > longest) {
                         longest = mlt;
    -                    *matchpos = prefixPtr - prefixIdx + matchIndex + back;
    -                    *startpos = ip + back;
    +                    offset = (int)(ipIndex - matchIndex);
    +                    sBack = back;
    +                    DEBUGLOG(7, "found match of length %i within extDictCtx", longest);
                 }   }
     
                 {   U32 const nextOffset = DELTANEXTU16(dictCtx->chainTable, dictMatchIndex);
    @@ -443,112 +1094,29 @@ LZ4HC_InsertAndGetWiderMatch (
                     matchIndex -= nextOffset;
         }   }   }
     
    -    return longest;
    +    {   LZ4HC_match_t md;
    +        assert(longest >= 0);
    +        md.len = longest;
    +        md.off = offset;
    +        md.back = sBack;
    +        return md;
    +    }
     }
     
    -LZ4_FORCE_INLINE int
    +LZ4_FORCE_INLINE LZ4HC_match_t
     LZ4HC_InsertAndFindBestMatch(LZ4HC_CCtx_internal* const hc4,   /* Index table will be updated */
                            const BYTE* const ip, const BYTE* const iLimit,
    -                       const BYTE** matchpos,
                            const int maxNbAttempts,
                            const int patternAnalysis,
                            const dictCtx_directive dict)
     {
    -    const BYTE* uselessPtr = ip;
    +    DEBUGLOG(7, "LZ4HC_InsertAndFindBestMatch");
         /* note : LZ4HC_InsertAndGetWiderMatch() is able to modify the starting position of a match (*startpos),
          * but this won't be the case here, as we define iLowLimit==ip,
          * so LZ4HC_InsertAndGetWiderMatch() won't be allowed to search past ip */
    -    return LZ4HC_InsertAndGetWiderMatch(hc4, ip, ip, iLimit, MINMATCH-1, matchpos, &uselessPtr, maxNbAttempts, patternAnalysis, 0 /*chainSwap*/, dict, favorCompressionRatio);
    +    return LZ4HC_InsertAndGetWiderMatch(hc4, ip, ip, iLimit, MINMATCH-1, maxNbAttempts, patternAnalysis, 0 /*chainSwap*/, dict, favorCompressionRatio);
     }
     
    -/* LZ4HC_encodeSequence() :
    - * @return : 0 if ok,
    - *           1 if buffer issue detected */
    -LZ4_FORCE_INLINE int LZ4HC_encodeSequence (
    -    const BYTE** _ip,
    -    BYTE** _op,
    -    const BYTE** _anchor,
    -    int matchLength,
    -    const BYTE* const match,
    -    limitedOutput_directive limit,
    -    BYTE* oend)
    -{
    -#define ip      (*_ip)
    -#define op      (*_op)
    -#define anchor  (*_anchor)
    -
    -    size_t length;
    -    BYTE* const token = op++;
    -
    -#if defined(LZ4_DEBUG) && (LZ4_DEBUG >= 6)
    -    static const BYTE* start = NULL;
    -    static U32 totalCost = 0;
    -    U32 const pos = (start==NULL) ? 0 : (U32)(anchor - start);
    -    U32 const ll = (U32)(ip - anchor);
    -    U32 const llAdd = (ll>=15) ? ((ll-15) / 255) + 1 : 0;
    -    U32 const mlAdd = (matchLength>=19) ? ((matchLength-19) / 255) + 1 : 0;
    -    U32 const cost = 1 + llAdd + ll + 2 + mlAdd;
    -    if (start==NULL) start = anchor;  /* only works for single segment */
    -    /* g_debuglog_enable = (pos >= 2228) & (pos <= 2262); */
    -    DEBUGLOG(6, "pos:%7u -- literals:%4u, match:%4i, offset:%5u, cost:%4u + %5u",
    -                pos,
    -                (U32)(ip - anchor), matchLength, (U32)(ip-match),
    -                cost, totalCost);
    -    totalCost += cost;
    -#endif
    -
    -    /* Encode Literal length */
    -    length = (size_t)(ip - anchor);
    -    LZ4_STATIC_ASSERT(notLimited == 0);
    -    /* Check output limit */
    -    if (limit && ((op + (length / 255) + length + (2 + 1 + LASTLITERALS)) > oend)) {
    -        DEBUGLOG(6, "Not enough room to write %i literals (%i bytes remaining)",
    -                (int)length, (int)(oend - op));
    -        return 1;
    -    }
    -    if (length >= RUN_MASK) {
    -        size_t len = length - RUN_MASK;
    -        *token = (RUN_MASK << ML_BITS);
    -        for(; len >= 255 ; len -= 255) *op++ = 255;
    -        *op++ = (BYTE)len;
    -    } else {
    -        *token = (BYTE)(length << ML_BITS);
    -    }
    -
    -    /* Copy Literals */
    -    LZ4_wildCopy8(op, anchor, op + length);
    -    op += length;
    -
    -    /* Encode Offset */
    -    assert( (ip - match) <= LZ4_DISTANCE_MAX );   /* note : consider providing offset as a value, rather than as a pointer difference */
    -    LZ4_writeLE16(op, (U16)(ip - match)); op += 2;
    -
    -    /* Encode MatchLength */
    -    assert(matchLength >= MINMATCH);
    -    length = (size_t)matchLength - MINMATCH;
    -    if (limit && (op + (length / 255) + (1 + LASTLITERALS) > oend)) {
    -        DEBUGLOG(6, "Not enough room to write match length");
    -        return 1;   /* Check output limit */
    -    }
    -    if (length >= ML_MASK) {
    -        *token += ML_MASK;
    -        length -= ML_MASK;
    -        for(; length >= 510 ; length -= 510) { *op++ = 255; *op++ = 255; }
    -        if (length >= 255) { length -= 255; *op++ = 255; }
    -        *op++ = (BYTE)length;
    -    } else {
    -        *token += (BYTE)(length);
    -    }
    -
    -    /* Prepare next loop */
    -    ip += matchLength;
    -    anchor = ip;
    -
    -    return 0;
    -}
    -#undef ip
    -#undef op
    -#undef anchor
     
     LZ4_FORCE_INLINE int LZ4HC_compress_hashChain (
         LZ4HC_CCtx_internal* const ctx,
    @@ -574,127 +1142,130 @@ LZ4_FORCE_INLINE int LZ4HC_compress_hashChain (
         BYTE* op = (BYTE*) dest;
         BYTE* oend = op + maxOutputSize;
     
    -    int   ml0, ml, ml2, ml3;
         const BYTE* start0;
    -    const BYTE* ref0;
    -    const BYTE* ref = NULL;
         const BYTE* start2 = NULL;
    -    const BYTE* ref2 = NULL;
         const BYTE* start3 = NULL;
    -    const BYTE* ref3 = NULL;
    +    LZ4HC_match_t m0, m1, m2, m3;
    +    const LZ4HC_match_t nomatch = {0, 0, 0};
     
         /* init */
    +    DEBUGLOG(5, "LZ4HC_compress_hashChain (dict?=>%i)", dict);
         *srcSizePtr = 0;
         if (limit == fillOutput) oend -= LASTLITERALS;                  /* Hack for support LZ4 format restriction */
         if (inputSize < LZ4_minLength) goto _last_literals;             /* Input too small, no compression (all literals) */
     
         /* Main Loop */
         while (ip <= mflimit) {
    -        ml = LZ4HC_InsertAndFindBestMatch(ctx, ip, matchlimit, &ref, maxNbAttempts, patternAnalysis, dict);
    -        if (ml encode ML1 */
    +        if (m2.len <= m1.len) { /* No better match => encode ML1 immediately */
                 optr = op;
    -            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ref, limit, oend)) goto _dest_overflow;
    +            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
    +                    m1.len, m1.off,
    +                    limit, oend) )
    +                goto _dest_overflow;
                 continue;
             }
     
             if (start0 < ip) {   /* first match was skipped at least once */
    -            if (start2 < ip + ml0) {  /* squeezing ML1 between ML0(original ML1) and ML2 */
    -                ip = start0; ref = ref0; ml = ml0;  /* restore initial ML1 */
    +            if (start2 < ip + m0.len) {  /* squeezing ML1 between ML0(original ML1) and ML2 */
    +                ip = start0; m1 = m0;  /* restore initial Match1 */
             }   }
     
             /* Here, start0==ip */
             if ((start2 - ip) < 3) {  /* First Match too small : removed */
    -            ml = ml2;
                 ip = start2;
    -            ref =ref2;
    +            m1 = m2;
                 goto _Search2;
             }
     
     _Search3:
    -        /* At this stage, we have :
    -        *  ml2 > ml1, and
    -        *  ip1+3 <= ip2 (usually < ip1+ml1) */
             if ((start2 - ip) < OPTIMAL_ML) {
                 int correction;
    -            int new_ml = ml;
    +            int new_ml = m1.len;
                 if (new_ml > OPTIMAL_ML) new_ml = OPTIMAL_ML;
    -            if (ip+new_ml > start2 + ml2 - MINMATCH) new_ml = (int)(start2 - ip) + ml2 - MINMATCH;
    +            if (ip+new_ml > start2 + m2.len - MINMATCH)
    +                new_ml = (int)(start2 - ip) + m2.len - MINMATCH;
                 correction = new_ml - (int)(start2 - ip);
                 if (correction > 0) {
                     start2 += correction;
    -                ref2 += correction;
    -                ml2 -= correction;
    +                m2.len -= correction;
                 }
             }
    -        /* Now, we have start2 = ip+new_ml, with new_ml = min(ml, OPTIMAL_ML=18) */
     
    -        if (start2 + ml2 <= mflimit) {
    -            ml3 = LZ4HC_InsertAndGetWiderMatch(ctx,
    -                            start2 + ml2 - 3, start2, matchlimit, ml2, &ref3, &start3,
    +        if (start2 + m2.len <= mflimit) {
    +            start3 = start2 + m2.len - 3;
    +            m3 = LZ4HC_InsertAndGetWiderMatch(ctx,
    +                            start3, start2, matchlimit, m2.len,
                                 maxNbAttempts, patternAnalysis, 0, dict, favorCompressionRatio);
    +            start3 += m3.back;
             } else {
    -            ml3 = ml2;
    +            m3 = nomatch;  /* do not search further */
             }
     
    -        if (ml3 == ml2) {  /* No better match => encode ML1 and ML2 */
    +        if (m3.len <= m2.len) {  /* No better match => encode ML1 and ML2 */
                 /* ip & ref are known; Now for ml */
    -            if (start2 < ip+ml)  ml = (int)(start2 - ip);
    +            if (start2 < ip+m1.len) m1.len = (int)(start2 - ip);
                 /* Now, encode 2 sequences */
                 optr = op;
    -            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ref, limit, oend)) goto _dest_overflow;
    +            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
    +                    m1.len, m1.off,
    +                    limit, oend) )
    +                goto _dest_overflow;
                 ip = start2;
                 optr = op;
    -            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml2, ref2, limit, oend)) {
    -                ml  = ml2;
    -                ref = ref2;
    +            if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
    +                    m2.len, m2.off,
    +                    limit, oend) ) {
    +                m1 = m2;
                     goto _dest_overflow;
                 }
                 continue;
             }
     
    -        if (start3 < ip+ml+3) {  /* Not enough space for match 2 : remove it */
    -            if (start3 >= (ip+ml)) {  /* can write Seq1 immediately ==> Seq2 is removed, so Seq3 becomes Seq1 */
    -                if (start2 < ip+ml) {
    -                    int correction = (int)(ip+ml - start2);
    +        if (start3 < ip+m1.len+3) {  /* Not enough space for match 2 : remove it */
    +            if (start3 >= (ip+m1.len)) {  /* can write Seq1 immediately ==> Seq2 is removed, so Seq3 becomes Seq1 */
    +                if (start2 < ip+m1.len) {
    +                    int correction = (int)(ip+m1.len - start2);
                         start2 += correction;
    -                    ref2 += correction;
    -                    ml2 -= correction;
    -                    if (ml2 < MINMATCH) {
    +                    m2.len -= correction;
    +                    if (m2.len < MINMATCH) {
                             start2 = start3;
    -                        ref2 = ref3;
    -                        ml2 = ml3;
    +                        m2 = m3;
                         }
                     }
     
                     optr = op;
    -                if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ref, limit, oend)) goto _dest_overflow;
    +                if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
    +                        m1.len, m1.off,
    +                        limit, oend) )
    +                    goto _dest_overflow;
                     ip  = start3;
    -                ref = ref3;
    -                ml  = ml3;
    +                m1 = m3;
     
                     start0 = start2;
    -                ref0 = ref2;
    -                ml0 = ml2;
    +                m0 = m2;
                     goto _Search2;
                 }
     
                 start2 = start3;
    -            ref2 = ref3;
    -            ml2 = ml3;
    +            m2 = m3;
                 goto _Search3;
             }
     
    @@ -703,29 +1274,32 @@ _Search3:
             * let's write the first one ML1.
             * ip & ref are known; Now decide ml.
             */
    -        if (start2 < ip+ml) {
    +        if (start2 < ip+m1.len) {
                 if ((start2 - ip) < OPTIMAL_ML) {
                     int correction;
    -                if (ml > OPTIMAL_ML) ml = OPTIMAL_ML;
    -                if (ip + ml > start2 + ml2 - MINMATCH) ml = (int)(start2 - ip) + ml2 - MINMATCH;
    -                correction = ml - (int)(start2 - ip);
    +                if (m1.len > OPTIMAL_ML) m1.len = OPTIMAL_ML;
    +                if (ip + m1.len > start2 + m2.len - MINMATCH)
    +                    m1.len = (int)(start2 - ip) + m2.len - MINMATCH;
    +                correction = m1.len - (int)(start2 - ip);
                     if (correction > 0) {
                         start2 += correction;
    -                    ref2 += correction;
    -                    ml2 -= correction;
    +                    m2.len -= correction;
                     }
                 } else {
    -                ml = (int)(start2 - ip);
    +                m1.len = (int)(start2 - ip);
                 }
             }
             optr = op;
    -        if (LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ref, limit, oend)) goto _dest_overflow;
    +        if ( LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor),
    +                m1.len, m1.off,
    +                limit, oend) )
    +            goto _dest_overflow;
     
             /* ML2 becomes ML1 */
    -        ip = start2; ref = ref2; ml = ml2;
    +        ip = start2; m1 = m2;
     
             /* ML3 becomes ML2 */
    -        start2 = start3; ref2 = ref3; ml2 = ml3;
    +        start2 = start3; m2 = m3;
     
             /* let's find a new ML3 */
             goto _Search3;
    @@ -765,7 +1339,7 @@ _last_literals:
     
     _dest_overflow:
         if (limit == fillOutput) {
    -        /* Assumption : ip, anchor, ml and ref must be set correctly */
    +        /* Assumption : @ip, @anchor, @optr and @m1 must be set correctly */
             size_t const ll = (size_t)(ip - anchor);
             size_t const ll_addbytes = (ll + 240) / 255;
             size_t const ll_totalCost = 1 + ll_addbytes + ll;
    @@ -776,10 +1350,10 @@ _dest_overflow:
                 /* ll validated; now adjust match length */
                 size_t const bytesLeftForMl = (size_t)(maxLitPos - (op+ll_totalCost));
                 size_t const maxMlSize = MINMATCH + (ML_MASK-1) + (bytesLeftForMl * 255);
    -            assert(maxMlSize < INT_MAX); assert(ml >= 0);
    -            if ((size_t)ml > maxMlSize) ml = (int)maxMlSize;
    -            if ((oend + LASTLITERALS) - (op + ll_totalCost + 2) - 1 + ml >= MFLIMIT) {
    -                LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ref, notLimited, oend);
    +            assert(maxMlSize < INT_MAX); assert(m1.len >= 0);
    +            if ((size_t)m1.len > maxMlSize) m1.len = (int)maxMlSize;
    +            if ((oend + LASTLITERALS) - (op + ll_totalCost + 2) - 1 + m1.len >= MFLIMIT) {
    +                LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), m1.len, m1.off, notLimited, oend);
             }   }
             goto _last_literals;
         }
    @@ -796,54 +1370,34 @@ static int LZ4HC_compress_optimal( LZ4HC_CCtx_internal* ctx,
         const dictCtx_directive dict,
         const HCfavor_e favorDecSpeed);
     
    -
    -LZ4_FORCE_INLINE int LZ4HC_compress_generic_internal (
    -    LZ4HC_CCtx_internal* const ctx,
    -    const char* const src,
    -    char* const dst,
    -    int* const srcSizePtr,
    -    int const dstCapacity,
    -    int cLevel,
    -    const limitedOutput_directive limit,
    -    const dictCtx_directive dict
    -    )
    +LZ4_FORCE_INLINE int
    +LZ4HC_compress_generic_internal (
    +            LZ4HC_CCtx_internal* const ctx,
    +            const char* const src,
    +            char* const dst,
    +            int* const srcSizePtr,
    +            int const dstCapacity,
    +            int cLevel,
    +            const limitedOutput_directive limit,
    +            const dictCtx_directive dict
    +            )
     {
    -    typedef enum { lz4hc, lz4opt } lz4hc_strat_e;
    -    typedef struct {
    -        lz4hc_strat_e strat;
    -        int nbSearches;
    -        U32 targetLength;
    -    } cParams_t;
    -    static const cParams_t clTable[LZ4HC_CLEVEL_MAX+1] = {
    -        { lz4hc,     2, 16 },  /* 0, unused */
    -        { lz4hc,     2, 16 },  /* 1, unused */
    -        { lz4hc,     2, 16 },  /* 2, unused */
    -        { lz4hc,     4, 16 },  /* 3 */
    -        { lz4hc,     8, 16 },  /* 4 */
    -        { lz4hc,    16, 16 },  /* 5 */
    -        { lz4hc,    32, 16 },  /* 6 */
    -        { lz4hc,    64, 16 },  /* 7 */
    -        { lz4hc,   128, 16 },  /* 8 */
    -        { lz4hc,   256, 16 },  /* 9 */
    -        { lz4opt,   96, 64 },  /*10==LZ4HC_CLEVEL_OPT_MIN*/
    -        { lz4opt,  512,128 },  /*11 */
    -        { lz4opt,16384,LZ4_OPT_NUM },  /* 12==LZ4HC_CLEVEL_MAX */
    -    };
    -
    -    DEBUGLOG(4, "LZ4HC_compress_generic(ctx=%p, src=%p, srcSize=%d, limit=%d)",
    -                ctx, src, *srcSizePtr, limit);
    +    DEBUGLOG(5, "LZ4HC_compress_generic_internal(src=%p, srcSize=%d)",
    +                src, *srcSizePtr);
     
         if (limit == fillOutput && dstCapacity < 1) return 0;   /* Impossible to store anything */
    -    if ((U32)*srcSizePtr > (U32)LZ4_MAX_INPUT_SIZE) return 0;    /* Unsupported input size (too large or negative) */
    +    if ((U32)*srcSizePtr > (U32)LZ4_MAX_INPUT_SIZE) return 0;  /* Unsupported input size (too large or negative) */
     
         ctx->end += *srcSizePtr;
    -    if (cLevel < 1) cLevel = LZ4HC_CLEVEL_DEFAULT;   /* note : convention is different from lz4frame, maybe something to review */
    -    cLevel = MIN(LZ4HC_CLEVEL_MAX, cLevel);
    -    {   cParams_t const cParam = clTable[cLevel];
    +    {   cParams_t const cParam = LZ4HC_getCLevelParams(cLevel);
             HCfavor_e const favor = ctx->favorDecSpeed ? favorDecompressionSpeed : favorCompressionRatio;
             int result;
     
    -        if (cParam.strat == lz4hc) {
    +        if (cParam.strat == lz4mid) {
    +            result = LZ4MID_compress(ctx,
    +                                src, dst, srcSizePtr, dstCapacity,
    +                                limit, dict);
    +        } else if (cParam.strat == lz4hc) {
                 result = LZ4HC_compress_hashChain(ctx,
                                     src, dst, srcSizePtr, dstCapacity,
                                     cParam.nbSearches, limit, dict);
    @@ -852,7 +1406,7 @@ LZ4_FORCE_INLINE int LZ4HC_compress_generic_internal (
                 result = LZ4HC_compress_optimal(ctx,
                                     src, dst, srcSizePtr, dstCapacity,
                                     cParam.nbSearches, cParam.targetLength, limit,
    -                                cLevel == LZ4HC_CLEVEL_MAX,   /* ultra mode */
    +                                cLevel >= LZ4HC_CLEVEL_MAX,   /* ultra mode */
                                     dict, favor);
             }
             if (result <= 0) ctx->dirty = 1;
    @@ -877,6 +1431,13 @@ LZ4HC_compress_generic_noDictCtx (
         return LZ4HC_compress_generic_internal(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit, noDictCtx);
     }
     
    +static int isStateCompatible(const LZ4HC_CCtx_internal* ctx1, const LZ4HC_CCtx_internal* ctx2)
    +{
    +    int const isMid1 = LZ4HC_getCLevelParams(ctx1->compressionLevel).strat == lz4mid;
    +    int const isMid2 = LZ4HC_getCLevelParams(ctx2->compressionLevel).strat == lz4mid;
    +    return !(isMid1 ^ isMid2);
    +}
    +
     static int
     LZ4HC_compress_generic_dictCtx (
             LZ4HC_CCtx_internal* const ctx,
    @@ -893,7 +1454,7 @@ LZ4HC_compress_generic_dictCtx (
         if (position >= 64 KB) {
             ctx->dictCtx = NULL;
             return LZ4HC_compress_generic_noDictCtx(ctx, src, dst, srcSizePtr, dstCapacity, cLevel, limit);
    -    } else if (position == 0 && *srcSizePtr > 4 KB) {
    +    } else if (position == 0 && *srcSizePtr > 4 KB && isStateCompatible(ctx, ctx->dictCtx)) {
             LZ4_memcpy(ctx, ctx->dictCtx, sizeof(LZ4HC_CCtx_internal));
             LZ4HC_setExternalDict(ctx, (const BYTE *)src);
             ctx->compressionLevel = (short)cLevel;
    @@ -965,6 +1526,7 @@ int LZ4_compress_HC(const char* src, char* dst, int srcSize, int dstCapacity, in
         LZ4_streamHC_t state;
         LZ4_streamHC_t* const statePtr = &state;
     #endif
    +    DEBUGLOG(5, "LZ4_compress_HC")
         cSize = LZ4_compress_HC_extStateHC(statePtr, src, dst, srcSize, dstCapacity, compressionLevel);
     #if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1
         FREEMEM(statePtr);
    @@ -1032,18 +1594,16 @@ void LZ4_resetStreamHC (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)
     
     void LZ4_resetStreamHC_fast (LZ4_streamHC_t* LZ4_streamHCPtr, int compressionLevel)
     {
    -    DEBUGLOG(4, "LZ4_resetStreamHC_fast(%p, %d)", LZ4_streamHCPtr, compressionLevel);
    -    if (LZ4_streamHCPtr->internal_donotuse.dirty) {
    +    LZ4HC_CCtx_internal* const s = &LZ4_streamHCPtr->internal_donotuse;
    +    DEBUGLOG(5, "LZ4_resetStreamHC_fast(%p, %d)", LZ4_streamHCPtr, compressionLevel);
    +    if (s->dirty) {
             LZ4_initStreamHC(LZ4_streamHCPtr, sizeof(*LZ4_streamHCPtr));
         } else {
    -        /* preserve end - prefixStart : can trigger clearTable's threshold */
    -        if (LZ4_streamHCPtr->internal_donotuse.end != NULL) {
    -            LZ4_streamHCPtr->internal_donotuse.end -= (uptrval)LZ4_streamHCPtr->internal_donotuse.prefixStart;
    -        } else {
    -            assert(LZ4_streamHCPtr->internal_donotuse.prefixStart == NULL);
    -        }
    -        LZ4_streamHCPtr->internal_donotuse.prefixStart = NULL;
    -        LZ4_streamHCPtr->internal_donotuse.dictCtx = NULL;
    +        assert(s->end >= s->prefixStart);
    +        s->dictLimit += (U32)(s->end - s->prefixStart);
    +        s->prefixStart = NULL;
    +        s->end = NULL;
    +        s->dictCtx = NULL;
         }
         LZ4_setCompressionLevel(LZ4_streamHCPtr, compressionLevel);
     }
    @@ -1067,7 +1627,9 @@ int LZ4_loadDictHC (LZ4_streamHC_t* LZ4_streamHCPtr,
                   const char* dictionary, int dictSize)
     {
         LZ4HC_CCtx_internal* const ctxPtr = &LZ4_streamHCPtr->internal_donotuse;
    -    DEBUGLOG(4, "LZ4_loadDictHC(ctx:%p, dict:%p, dictSize:%d)", LZ4_streamHCPtr, dictionary, dictSize);
    +    cParams_t cp;
    +    DEBUGLOG(4, "LZ4_loadDictHC(ctx:%p, dict:%p, dictSize:%d, clevel=%d)", LZ4_streamHCPtr, dictionary, dictSize, ctxPtr->compressionLevel);
    +    assert(dictSize >= 0);
         assert(LZ4_streamHCPtr != NULL);
         if (dictSize > 64 KB) {
             dictionary += (size_t)dictSize - 64 KB;
    @@ -1077,10 +1639,15 @@ int LZ4_loadDictHC (LZ4_streamHC_t* LZ4_streamHCPtr,
         {   int const cLevel = ctxPtr->compressionLevel;
             LZ4_initStreamHC(LZ4_streamHCPtr, sizeof(*LZ4_streamHCPtr));
             LZ4_setCompressionLevel(LZ4_streamHCPtr, cLevel);
    +        cp = LZ4HC_getCLevelParams(cLevel);
         }
         LZ4HC_init_internal (ctxPtr, (const BYTE*)dictionary);
         ctxPtr->end = (const BYTE*)dictionary + dictSize;
    -    if (dictSize >= 4) LZ4HC_Insert (ctxPtr, ctxPtr->end-3);
    +    if (cp.strat == lz4mid) {
    +        LZ4MID_fillHTable (ctxPtr, dictionary, (size_t)dictSize);
    +    } else {
    +        if (dictSize >= LZ4HC_HASHSIZE) LZ4HC_Insert (ctxPtr, ctxPtr->end-3);
    +    }
         return dictSize;
     }
     
    @@ -1093,8 +1660,10 @@ void LZ4_attach_HC_dictionary(LZ4_streamHC_t *working_stream, const LZ4_streamHC
     static void LZ4HC_setExternalDict(LZ4HC_CCtx_internal* ctxPtr, const BYTE* newBlock)
     {
         DEBUGLOG(4, "LZ4HC_setExternalDict(%p, %p)", ctxPtr, newBlock);
    -    if (ctxPtr->end >= ctxPtr->prefixStart + 4)
    -        LZ4HC_Insert (ctxPtr, ctxPtr->end-3);   /* Referencing remaining dictionary content */
    +    if ( (ctxPtr->end >= ctxPtr->prefixStart + 4)
    +      && (LZ4HC_getCLevelParams(ctxPtr->compressionLevel).strat != lz4mid) ) {
    +        LZ4HC_Insert (ctxPtr, ctxPtr->end-3);  /* Referencing remaining dictionary content */
    +    }
     
         /* Only one memory segment for extDict, so any previous extDict is lost at this stage */
         ctxPtr->lowLimit  = ctxPtr->dictLimit;
    @@ -1119,7 +1688,8 @@ LZ4_compressHC_continue_generic (LZ4_streamHC_t* LZ4_streamHCPtr,
                     LZ4_streamHCPtr, src, *srcSizePtr, limit);
         assert(ctxPtr != NULL);
         /* auto-init if forgotten */
    -    if (ctxPtr->prefixStart == NULL) LZ4HC_init_internal (ctxPtr, (const BYTE*) src);
    +    if (ctxPtr->prefixStart == NULL)
    +        LZ4HC_init_internal (ctxPtr, (const BYTE*) src);
     
         /* Check overflow */
         if ((size_t)(ctxPtr->end - ctxPtr->prefixStart) + ctxPtr->dictLimit > 2 GB) {
    @@ -1140,7 +1710,8 @@ LZ4_compressHC_continue_generic (LZ4_streamHC_t* LZ4_streamHCPtr,
                 if (sourceEnd > dictEnd) sourceEnd = dictEnd;
                 ctxPtr->lowLimit += (U32)(sourceEnd - ctxPtr->dictStart);
                 ctxPtr->dictStart += (U32)(sourceEnd - ctxPtr->dictStart);
    -            if (ctxPtr->dictLimit - ctxPtr->lowLimit < 4) {
    +            /* invalidate dictionary is it's too small */
    +            if (ctxPtr->dictLimit - ctxPtr->lowLimit < LZ4HC_HASHSIZE) {
                     ctxPtr->lowLimit = ctxPtr->dictLimit;
                     ctxPtr->dictStart = ctxPtr->prefixStart;
         }   }   }
    @@ -1150,6 +1721,7 @@ LZ4_compressHC_continue_generic (LZ4_streamHC_t* LZ4_streamHCPtr,
     
     int LZ4_compress_HC_continue (LZ4_streamHC_t* LZ4_streamHCPtr, const char* src, char* dst, int srcSize, int dstCapacity)
     {
    +    DEBUGLOG(5, "LZ4_compress_HC_continue");
         if (dstCapacity < LZ4_compressBound(srcSize))
             return LZ4_compressHC_continue_generic (LZ4_streamHCPtr, src, dst, &srcSize, dstCapacity, limitedOutput);
         else
    @@ -1162,7 +1734,6 @@ int LZ4_compress_HC_continue_destSize (LZ4_streamHC_t* LZ4_streamHCPtr, const ch
     }
     
     
    -
     /* LZ4_saveDictHC :
      * save history content
      * into a user-provided buffer
    @@ -1179,10 +1750,10 @@ int LZ4_saveDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, char* safeBuffer, int dictS
         if (dictSize > prefixSize) dictSize = prefixSize;
         if (safeBuffer == NULL) assert(dictSize == 0);
         if (dictSize > 0)
    -        LZ4_memmove(safeBuffer, streamPtr->end - dictSize, dictSize);
    +        LZ4_memmove(safeBuffer, streamPtr->end - dictSize, (size_t)dictSize);
         {   U32 const endIndex = (U32)(streamPtr->end - streamPtr->prefixStart) + streamPtr->dictLimit;
    -        streamPtr->end = (const BYTE*)safeBuffer + dictSize;
    -        streamPtr->prefixStart = streamPtr->end - dictSize;
    +        streamPtr->end = (safeBuffer == NULL) ? NULL : (const BYTE*)safeBuffer + dictSize;
    +        streamPtr->prefixStart = (const BYTE*)safeBuffer;
             streamPtr->dictLimit = endIndex - (U32)dictSize;
             streamPtr->lowLimit = endIndex - (U32)dictSize;
             streamPtr->dictStart = streamPtr->prefixStart;
    @@ -1193,75 +1764,6 @@ int LZ4_saveDictHC (LZ4_streamHC_t* LZ4_streamHCPtr, char* safeBuffer, int dictS
     }
     
     
    -/***************************************************
    -*  Deprecated Functions
    -***************************************************/
    -
    -/* These functions currently generate deprecation warnings */
    -
    -/* Wrappers for deprecated compression functions */
    -int LZ4_compressHC(const char* src, char* dst, int srcSize) { return LZ4_compress_HC (src, dst, srcSize, LZ4_compressBound(srcSize), 0); }
    -int LZ4_compressHC_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC(src, dst, srcSize, maxDstSize, 0); }
    -int LZ4_compressHC2(const char* src, char* dst, int srcSize, int cLevel) { return LZ4_compress_HC (src, dst, srcSize, LZ4_compressBound(srcSize), cLevel); }
    -int LZ4_compressHC2_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize, int cLevel) { return LZ4_compress_HC(src, dst, srcSize, maxDstSize, cLevel); }
    -int LZ4_compressHC_withStateHC (void* state, const char* src, char* dst, int srcSize) { return LZ4_compress_HC_extStateHC (state, src, dst, srcSize, LZ4_compressBound(srcSize), 0); }
    -int LZ4_compressHC_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC_extStateHC (state, src, dst, srcSize, maxDstSize, 0); }
    -int LZ4_compressHC2_withStateHC (void* state, const char* src, char* dst, int srcSize, int cLevel) { return LZ4_compress_HC_extStateHC(state, src, dst, srcSize, LZ4_compressBound(srcSize), cLevel); }
    -int LZ4_compressHC2_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize, int cLevel) { return LZ4_compress_HC_extStateHC(state, src, dst, srcSize, maxDstSize, cLevel); }
    -int LZ4_compressHC_continue (LZ4_streamHC_t* ctx, const char* src, char* dst, int srcSize) { return LZ4_compress_HC_continue (ctx, src, dst, srcSize, LZ4_compressBound(srcSize)); }
    -int LZ4_compressHC_limitedOutput_continue (LZ4_streamHC_t* ctx, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC_continue (ctx, src, dst, srcSize, maxDstSize); }
    -
    -
    -/* Deprecated streaming functions */
    -int LZ4_sizeofStreamStateHC(void) { return sizeof(LZ4_streamHC_t); }
    -
    -/* state is presumed correctly sized, aka >= sizeof(LZ4_streamHC_t)
    - * @return : 0 on success, !=0 if error */
    -int LZ4_resetStreamStateHC(void* state, char* inputBuffer)
    -{
    -    LZ4_streamHC_t* const hc4 = LZ4_initStreamHC(state, sizeof(*hc4));
    -    if (hc4 == NULL) return 1;   /* init failed */
    -    LZ4HC_init_internal (&hc4->internal_donotuse, (const BYTE*)inputBuffer);
    -    return 0;
    -}
    -
    -#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
    -void* LZ4_createHC (const char* inputBuffer)
    -{
    -    LZ4_streamHC_t* const hc4 = LZ4_createStreamHC();
    -    if (hc4 == NULL) return NULL;   /* not enough memory */
    -    LZ4HC_init_internal (&hc4->internal_donotuse, (const BYTE*)inputBuffer);
    -    return hc4;
    -}
    -
    -int LZ4_freeHC (void* LZ4HC_Data)
    -{
    -    if (!LZ4HC_Data) return 0;  /* support free on NULL */
    -    FREEMEM(LZ4HC_Data);
    -    return 0;
    -}
    -#endif
    -
    -int LZ4_compressHC2_continue (void* LZ4HC_Data, const char* src, char* dst, int srcSize, int cLevel)
    -{
    -    return LZ4HC_compress_generic (&((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse, src, dst, &srcSize, 0, cLevel, notLimited);
    -}
    -
    -int LZ4_compressHC2_limitedOutput_continue (void* LZ4HC_Data, const char* src, char* dst, int srcSize, int dstCapacity, int cLevel)
    -{
    -    return LZ4HC_compress_generic (&((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse, src, dst, &srcSize, dstCapacity, cLevel, limitedOutput);
    -}
    -
    -char* LZ4_slideInputBufferHC(void* LZ4HC_Data)
    -{
    -    LZ4_streamHC_t* const ctx = (LZ4_streamHC_t*)LZ4HC_Data;
    -    const BYTE* bufferStart = ctx->internal_donotuse.prefixStart - ctx->internal_donotuse.dictLimit + ctx->internal_donotuse.lowLimit;
    -    LZ4_resetStreamHC_fast(ctx, ctx->internal_donotuse.compressionLevel);
    -    /* avoid const char * -> char * conversion warning :( */
    -    return (char*)(uptrval)bufferStart;
    -}
    -
    -
     /* ================================================
      *  LZ4 Optimal parser (levels [LZ4HC_CLEVEL_OPT_MIN - LZ4HC_CLEVEL_MAX])
      * ===============================================*/
    @@ -1282,7 +1784,6 @@ LZ4_FORCE_INLINE int LZ4HC_literalsPrice(int const litlen)
         return price;
     }
     
    -
     /* requires mlen >= MINMATCH */
     LZ4_FORCE_INLINE int LZ4HC_sequencePrice(int litlen, int mlen)
     {
    @@ -1298,12 +1799,6 @@ LZ4_FORCE_INLINE int LZ4HC_sequencePrice(int litlen, int mlen)
         return price;
     }
     
    -
    -typedef struct {
    -    int off;
    -    int len;
    -} LZ4HC_match_t;
    -
     LZ4_FORCE_INLINE LZ4HC_match_t
     LZ4HC_FindLongerMatch(LZ4HC_CCtx_internal* const ctx,
                           const BYTE* ip, const BYTE* const iHighLimit,
    @@ -1311,19 +1806,17 @@ LZ4HC_FindLongerMatch(LZ4HC_CCtx_internal* const ctx,
                           const dictCtx_directive dict,
                           const HCfavor_e favorDecSpeed)
     {
    -    LZ4HC_match_t match = { 0 , 0 };
    -    const BYTE* matchPtr = NULL;
    +    LZ4HC_match_t const match0 = { 0 , 0, 0 };
         /* note : LZ4HC_InsertAndGetWiderMatch() is able to modify the starting position of a match (*startpos),
          * but this won't be the case here, as we define iLowLimit==ip,
    -     * so LZ4HC_InsertAndGetWiderMatch() won't be allowed to search past ip */
    -    int matchLength = LZ4HC_InsertAndGetWiderMatch(ctx, ip, ip, iHighLimit, minLen, &matchPtr, &ip, nbSearches, 1 /*patternAnalysis*/, 1 /*chainSwap*/, dict, favorDecSpeed);
    -    if (matchLength <= minLen) return match;
    +    ** so LZ4HC_InsertAndGetWiderMatch() won't be allowed to search past ip */
    +    LZ4HC_match_t md = LZ4HC_InsertAndGetWiderMatch(ctx, ip, ip, iHighLimit, minLen, nbSearches, 1 /*patternAnalysis*/, 1 /*chainSwap*/, dict, favorDecSpeed);
    +    assert(md.back == 0);
    +    if (md.len <= minLen) return match0;
         if (favorDecSpeed) {
    -        if ((matchLength>18) & (matchLength<=36)) matchLength=18;   /* favor shortcut */
    +        if ((md.len>18) & (md.len<=36)) md.len=18;   /* favor dec.speed (shortcut) */
         }
    -    match.len = matchLength;
    -    match.off = (int)(ip-matchPtr);
    -    return match;
    +    return md;
     }
     
     
    @@ -1356,7 +1849,7 @@ static int LZ4HC_compress_optimal ( LZ4HC_CCtx_internal* ctx,
         BYTE* opSaved = (BYTE*) dst;
         BYTE* oend = op + dstCapacity;
         int ovml = MINMATCH;  /* overflow - last sequence */
    -    const BYTE* ovref = NULL;
    +    int ovoff = 0;
     
         /* init */
     #if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1
    @@ -1379,11 +1872,10 @@ static int LZ4HC_compress_optimal ( LZ4HC_CCtx_internal* ctx,
              if ((size_t)firstMatch.len > sufficient_len) {
                  /* good enough solution : immediate encoding */
                  int const firstML = firstMatch.len;
    -             const BYTE* const matchPos = ip - firstMatch.off;
                  opSaved = op;
    -             if ( LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), firstML, matchPos, limit, oend) ) {  /* updates ip, op and anchor */
    +             if ( LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), firstML, firstMatch.off, limit, oend) ) {  /* updates ip, op and anchor */
                      ovml = firstML;
    -                 ovref = matchPos;
    +                 ovoff = firstMatch.off;
                      goto _dest_overflow;
                  }
                  continue;
    @@ -1401,11 +1893,11 @@ static int LZ4HC_compress_optimal ( LZ4HC_CCtx_internal* ctx,
                                  rPos, cost, opt[rPos].litlen);
              }   }
              /* set prices using initial match */
    -         {   int mlen = MINMATCH;
    -             int const matchML = firstMatch.len;   /* necessarily < sufficient_len < LZ4_OPT_NUM */
    +         {   int const matchML = firstMatch.len;   /* necessarily < sufficient_len < LZ4_OPT_NUM */
                  int const offset = firstMatch.off;
    +             int mlen;
                  assert(matchML < LZ4_OPT_NUM);
    -             for ( ; mlen <= matchML ; mlen++) {
    +             for (mlen = MINMATCH ; mlen <= matchML ; mlen++) {
                      int const cost = LZ4HC_sequencePrice(llen, mlen);
                      opt[mlen].mlen = mlen;
                      opt[mlen].off = offset;
    @@ -1557,9 +2049,9 @@ encode: /* cur, last_match_pos, best_mlen, best_off must be set */
                      assert(ml >= MINMATCH);
                      assert((offset >= 1) && (offset <= LZ4_DISTANCE_MAX));
                      opSaved = op;
    -                 if ( LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, ip - offset, limit, oend) ) {  /* updates ip, op and anchor */
    +                 if ( LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ml, offset, limit, oend) ) {  /* updates ip, op and anchor */
                          ovml = ml;
    -                     ovref = ip - offset;
    +                     ovoff = offset;
                          goto _dest_overflow;
              }   }   }
          }  /* while (ip <= mflimit) */
    @@ -1618,14 +2110,83 @@ if (limit == fillOutput) {
              if ((oend + LASTLITERALS) - (op + ll_totalCost + 2) - 1 + ovml >= MFLIMIT) {
                  DEBUGLOG(6, "Space to end : %i + ml (%i)", (int)((oend + LASTLITERALS) - (op + ll_totalCost + 2) - 1), ovml);
                  DEBUGLOG(6, "Before : ip = %p, anchor = %p", ip, anchor);
    -             LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ovml, ovref, notLimited, oend);
    +             LZ4HC_encodeSequence(UPDATABLE(ip, op, anchor), ovml, ovoff, notLimited, oend);
                  DEBUGLOG(6, "After : ip = %p, anchor = %p", ip, anchor);
          }   }
          goto _last_literals;
     }
     _return_label:
     #if defined(LZ4HC_HEAPMODE) && LZ4HC_HEAPMODE==1
    -     FREEMEM(opt);
    +     if (opt) FREEMEM(opt);
     #endif
          return retval;
     }
    +
    +
    +/***************************************************
    +*  Deprecated Functions
    +***************************************************/
    +
    +/* These functions currently generate deprecation warnings */
    +
    +/* Wrappers for deprecated compression functions */
    +int LZ4_compressHC(const char* src, char* dst, int srcSize) { return LZ4_compress_HC (src, dst, srcSize, LZ4_compressBound(srcSize), 0); }
    +int LZ4_compressHC_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC(src, dst, srcSize, maxDstSize, 0); }
    +int LZ4_compressHC2(const char* src, char* dst, int srcSize, int cLevel) { return LZ4_compress_HC (src, dst, srcSize, LZ4_compressBound(srcSize), cLevel); }
    +int LZ4_compressHC2_limitedOutput(const char* src, char* dst, int srcSize, int maxDstSize, int cLevel) { return LZ4_compress_HC(src, dst, srcSize, maxDstSize, cLevel); }
    +int LZ4_compressHC_withStateHC (void* state, const char* src, char* dst, int srcSize) { return LZ4_compress_HC_extStateHC (state, src, dst, srcSize, LZ4_compressBound(srcSize), 0); }
    +int LZ4_compressHC_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC_extStateHC (state, src, dst, srcSize, maxDstSize, 0); }
    +int LZ4_compressHC2_withStateHC (void* state, const char* src, char* dst, int srcSize, int cLevel) { return LZ4_compress_HC_extStateHC(state, src, dst, srcSize, LZ4_compressBound(srcSize), cLevel); }
    +int LZ4_compressHC2_limitedOutput_withStateHC (void* state, const char* src, char* dst, int srcSize, int maxDstSize, int cLevel) { return LZ4_compress_HC_extStateHC(state, src, dst, srcSize, maxDstSize, cLevel); }
    +int LZ4_compressHC_continue (LZ4_streamHC_t* ctx, const char* src, char* dst, int srcSize) { return LZ4_compress_HC_continue (ctx, src, dst, srcSize, LZ4_compressBound(srcSize)); }
    +int LZ4_compressHC_limitedOutput_continue (LZ4_streamHC_t* ctx, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_HC_continue (ctx, src, dst, srcSize, maxDstSize); }
    +
    +
    +/* Deprecated streaming functions */
    +int LZ4_sizeofStreamStateHC(void) { return sizeof(LZ4_streamHC_t); }
    +
    +/* state is presumed correctly sized, aka >= sizeof(LZ4_streamHC_t)
    + * @return : 0 on success, !=0 if error */
    +int LZ4_resetStreamStateHC(void* state, char* inputBuffer)
    +{
    +    LZ4_streamHC_t* const hc4 = LZ4_initStreamHC(state, sizeof(*hc4));
    +    if (hc4 == NULL) return 1;   /* init failed */
    +    LZ4HC_init_internal (&hc4->internal_donotuse, (const BYTE*)inputBuffer);
    +    return 0;
    +}
    +
    +#if !defined(LZ4_STATIC_LINKING_ONLY_DISABLE_MEMORY_ALLOCATION)
    +void* LZ4_createHC (const char* inputBuffer)
    +{
    +    LZ4_streamHC_t* const hc4 = LZ4_createStreamHC();
    +    if (hc4 == NULL) return NULL;   /* not enough memory */
    +    LZ4HC_init_internal (&hc4->internal_donotuse, (const BYTE*)inputBuffer);
    +    return hc4;
    +}
    +
    +int LZ4_freeHC (void* LZ4HC_Data)
    +{
    +    if (!LZ4HC_Data) return 0;  /* support free on NULL */
    +    FREEMEM(LZ4HC_Data);
    +    return 0;
    +}
    +#endif
    +
    +int LZ4_compressHC2_continue (void* LZ4HC_Data, const char* src, char* dst, int srcSize, int cLevel)
    +{
    +    return LZ4HC_compress_generic (&((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse, src, dst, &srcSize, 0, cLevel, notLimited);
    +}
    +
    +int LZ4_compressHC2_limitedOutput_continue (void* LZ4HC_Data, const char* src, char* dst, int srcSize, int dstCapacity, int cLevel)
    +{
    +    return LZ4HC_compress_generic (&((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse, src, dst, &srcSize, dstCapacity, cLevel, limitedOutput);
    +}
    +
    +char* LZ4_slideInputBufferHC(void* LZ4HC_Data)
    +{
    +    LZ4HC_CCtx_internal* const s = &((LZ4_streamHC_t*)LZ4HC_Data)->internal_donotuse;
    +    const BYTE* const bufferStart = s->prefixStart - s->dictLimit + s->lowLimit;
    +    LZ4_resetStreamHC_fast((LZ4_streamHC_t*)LZ4HC_Data, s->compressionLevel);
    +    /* ugly conversion trick, required to evade (const char*) -> (char*) cast-qual warning :( */
    +    return (char*)(uptrval)bufferStart;
    +}
    diff --git a/lib/lz4hc.h b/lib/lz4hc.h
    index e937acfefd857f1b2be158cd3a5ba3a85a389f07..992bc8cdd7703e7ff49b01137a00bf6f004683a6 100644
    --- a/lib/lz4hc.h
    +++ b/lib/lz4hc.h
    @@ -44,7 +44,7 @@ extern "C" {
     
     
     /* --- Useful constants --- */
    -#define LZ4HC_CLEVEL_MIN         3
    +#define LZ4HC_CLEVEL_MIN         2
     #define LZ4HC_CLEVEL_DEFAULT     9
     #define LZ4HC_CLEVEL_OPT_MIN    10
     #define LZ4HC_CLEVEL_MAX        12
    @@ -126,6 +126,8 @@ LZ4LIB_API int             LZ4_freeStreamHC (LZ4_streamHC_t* streamHCPtr);
     
       After reset, a first "fictional block" can be designated as initial dictionary,
       using LZ4_loadDictHC() (Optional).
    +  Note: In order for LZ4_loadDictHC() to create the correct data structure,
    +  it is essential to set the compression level _before_ loading the dictionary.
     
       Invoke LZ4_compress_HC_continue() to compress each successive block.
       The number of blocks is unlimited.
    @@ -135,12 +137,12 @@ LZ4LIB_API int             LZ4_freeStreamHC (LZ4_streamHC_t* streamHCPtr);
       It's allowed to update compression level anytime between blocks,
       using LZ4_setCompressionLevel() (experimental).
     
    -  'dst' buffer should be sized to handle worst case scenarios
    + @dst buffer should be sized to handle worst case scenarios
       (see LZ4_compressBound(), it ensures compression success).
       In case of failure, the API does not guarantee recovery,
       so the state _must_ be reset.
       To ensure compression success
    -  whenever `dst` buffer size cannot be made >= LZ4_compressBound(),
    +  whenever @dst buffer size cannot be made >= LZ4_compressBound(),
       consider using LZ4_compress_HC_continue_destSize().
     
       Whenever previous input blocks can't be preserved unmodified in-place during compression of next blocks,
    @@ -176,6 +178,34 @@ LZ4LIB_API int LZ4_compress_HC_continue_destSize(LZ4_streamHC_t* LZ4_streamHCPtr
     LZ4LIB_API int LZ4_saveDictHC (LZ4_streamHC_t* streamHCPtr, char* safeBuffer, int maxDictSize);
     
     
    +/*! LZ4_attach_HC_dictionary() : stable since v1.10.0
    + *  This API allows for the efficient re-use of a static dictionary many times.
    + *
    + *  Rather than re-loading the dictionary buffer into a working context before
    + *  each compression, or copying a pre-loaded dictionary's LZ4_streamHC_t into a
    + *  working LZ4_streamHC_t, this function introduces a no-copy setup mechanism,
    + *  in which the working stream references the dictionary stream in-place.
    + *
    + *  Several assumptions are made about the state of the dictionary stream.
    + *  Currently, only streams which have been prepared by LZ4_loadDictHC() should
    + *  be expected to work.
    + *
    + *  Alternatively, the provided dictionary stream pointer may be NULL, in which
    + *  case any existing dictionary stream is unset.
    + *
    + *  A dictionary should only be attached to a stream without any history (i.e.,
    + *  a stream that has just been reset).
    + *
    + *  The dictionary will remain attached to the working stream only for the
    + *  current stream session. Calls to LZ4_resetStreamHC(_fast) will remove the
    + *  dictionary context association from the working stream. The dictionary
    + *  stream (and source buffer) must remain in-place / accessible / unchanged
    + *  through the lifetime of the stream session.
    + */
    +LZ4LIB_API void
    +LZ4_attach_HC_dictionary(LZ4_streamHC_t* working_stream,
    +                   const LZ4_streamHC_t* dictionary_stream);
    +
     
     /*^**********************************************
      * !!!!!!   STATIC LINKING ONLY   !!!!!!
    @@ -204,18 +234,18 @@ LZ4LIB_API int LZ4_saveDictHC (LZ4_streamHC_t* streamHCPtr, char* safeBuffer, in
     typedef struct LZ4HC_CCtx_internal LZ4HC_CCtx_internal;
     struct LZ4HC_CCtx_internal
     {
    -    LZ4_u32   hashTable[LZ4HC_HASHTABLESIZE];
    -    LZ4_u16   chainTable[LZ4HC_MAXD];
    -    const LZ4_byte* end;       /* next block here to continue on current prefix */
    +    LZ4_u32 hashTable[LZ4HC_HASHTABLESIZE];
    +    LZ4_u16 chainTable[LZ4HC_MAXD];
    +    const LZ4_byte* end;     /* next block here to continue on current prefix */
         const LZ4_byte* prefixStart;  /* Indexes relative to this position */
         const LZ4_byte* dictStart; /* alternate reference for extDict */
    -    LZ4_u32   dictLimit;       /* below that point, need extDict */
    -    LZ4_u32   lowLimit;        /* below that point, no more dict */
    -    LZ4_u32   nextToUpdate;    /* index from which to continue dictionary update */
    -    short     compressionLevel;
    -    LZ4_i8    favorDecSpeed;   /* favor decompression speed if this flag set,
    -                                  otherwise, favor compression ratio */
    -    LZ4_i8    dirty;           /* stream has to be fully reset if this flag is set */
    +    LZ4_u32 dictLimit;       /* below that point, need extDict */
    +    LZ4_u32 lowLimit;        /* below that point, no more history */
    +    LZ4_u32 nextToUpdate;    /* index from which to continue dictionary update */
    +    short   compressionLevel;
    +    LZ4_i8  favorDecSpeed;   /* favor decompression speed if this flag set,
    +                                otherwise, favor compression ratio */
    +    LZ4_i8  dirty;           /* stream has to be fully reset if this flag is set */
         const LZ4HC_CCtx_internal* dictCtx;
     };
     
    @@ -376,35 +406,6 @@ LZ4LIB_STATIC_API int LZ4_compress_HC_extStateHC_fastReset (
         int srcSize, int dstCapacity,
         int compressionLevel);
     
    -/*! LZ4_attach_HC_dictionary() :
    - *  This is an experimental API that allows for the efficient use of a
    - *  static dictionary many times.
    - *
    - *  Rather than re-loading the dictionary buffer into a working context before
    - *  each compression, or copying a pre-loaded dictionary's LZ4_streamHC_t into a
    - *  working LZ4_streamHC_t, this function introduces a no-copy setup mechanism,
    - *  in which the working stream references the dictionary stream in-place.
    - *
    - *  Several assumptions are made about the state of the dictionary stream.
    - *  Currently, only streams which have been prepared by LZ4_loadDictHC() should
    - *  be expected to work.
    - *
    - *  Alternatively, the provided dictionary stream pointer may be NULL, in which
    - *  case any existing dictionary stream is unset.
    - *
    - *  A dictionary should only be attached to a stream without any history (i.e.,
    - *  a stream that has just been reset).
    - *
    - *  The dictionary will remain attached to the working stream only for the
    - *  current stream session. Calls to LZ4_resetStreamHC(_fast) will remove the
    - *  dictionary context association from the working stream. The dictionary
    - *  stream (and source buffer) must remain in-place / accessible / unchanged
    - *  through the lifetime of the stream session.
    - */
    -LZ4LIB_STATIC_API void LZ4_attach_HC_dictionary(
    -          LZ4_streamHC_t *working_stream,
    -    const LZ4_streamHC_t *dictionary_stream);
    -
     #if defined (__cplusplus)
     }
     #endif
    diff --git a/lib/xxhash.c b/lib/xxhash.c
    index ff28749e316434a13123667848e6692e35bfb059..e1326196bfe5056aff435b0a75d61a529ee3096e 100644
    --- a/lib/xxhash.c
    +++ b/lib/xxhash.c
    @@ -120,12 +120,12 @@ static void* XXH_memcpy(void* dest, const void* src, size_t size) { return memcp
     /* *************************************
     *  Compiler Specific Options
     ***************************************/
    -#ifdef _MSC_VER    /* Visual Studio */
    +#if defined (_MSC_VER) && !defined (__clang__)    /* MSVC */
     #  pragma warning(disable : 4127)      /* disable: C4127: conditional expression is constant */
     #  define FORCE_INLINE static __forceinline
     #else
     #  if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L   /* C99 */
    -#    ifdef __GNUC__
    +#    if defined (__GNUC__) || defined (__clang__)
     #      define FORCE_INLINE static inline __attribute__((always_inline))
     #    else
     #      define FORCE_INLINE static inline
    @@ -213,7 +213,7 @@ static U32 XXH_swap32 (U32 x)
     /* *************************************
     *  Architecture Macros
     ***************************************/
    -typedef enum { XXH_bigEndian=0, XXH_littleEndian=1 } XXH_endianess;
    +typedef enum { XXH_bigEndian=0, XXH_littleEndian=1 } XXH_endianness;
     
     /* XXH_CPU_LITTLE_ENDIAN can be defined externally, for example on the compiler command line */
     #ifndef XXH_CPU_LITTLE_ENDIAN
    @@ -231,7 +231,7 @@ static int XXH_isLittleEndian(void)
     *****************************/
     typedef enum { XXH_aligned, XXH_unaligned } XXH_alignment;
     
    -FORCE_INLINE U32 XXH_readLE32_align(const void* ptr, XXH_endianess endian, XXH_alignment align)
    +FORCE_INLINE U32 XXH_readLE32_align(const void* ptr, XXH_endianness endian, XXH_alignment align)
     {
         if (align==XXH_unaligned)
             return endian==XXH_littleEndian ? XXH_read32(ptr) : XXH_swap32(XXH_read32(ptr));
    @@ -239,7 +239,7 @@ FORCE_INLINE U32 XXH_readLE32_align(const void* ptr, XXH_endianess endian, XXH_a
             return endian==XXH_littleEndian ? *(const U32*)ptr : XXH_swap32(*(const U32*)ptr);
     }
     
    -FORCE_INLINE U32 XXH_readLE32(const void* ptr, XXH_endianess endian)
    +FORCE_INLINE U32 XXH_readLE32(const void* ptr, XXH_endianness endian)
     {
         return XXH_readLE32_align(ptr, endian, XXH_unaligned);
     }
    @@ -289,7 +289,7 @@ static U32 XXH32_avalanche(U32 h32)
     
     static U32
     XXH32_finalize(U32 h32, const void* ptr, size_t len,
    -                XXH_endianess endian, XXH_alignment align)
    +                XXH_endianness endian, XXH_alignment align)
     
     {
         const BYTE* p = (const BYTE*)ptr;
    @@ -350,7 +350,7 @@ XXH32_finalize(U32 h32, const void* ptr, size_t len,
     
     FORCE_INLINE U32
     XXH32_endian_align(const void* input, size_t len, U32 seed,
    -                    XXH_endianess endian, XXH_alignment align)
    +                    XXH_endianness endian, XXH_alignment align)
     {
         const BYTE* p = (const BYTE*)input;
         const BYTE* bEnd = p + len;
    @@ -398,7 +398,7 @@ XXH_PUBLIC_API unsigned int XXH32 (const void* input, size_t len, unsigned int s
         XXH32_update(&state, input, len);
         return XXH32_digest(&state);
     #else
    -    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
    +    XXH_endianness endian_detected = (XXH_endianness)XXH_CPU_LITTLE_ENDIAN;
     
         if (XXH_FORCE_ALIGN_CHECK) {
             if ((((size_t)input) & 3) == 0) {   /* Input is 4-bytes aligned, leverage the speed benefit */
    @@ -449,7 +449,7 @@ XXH_PUBLIC_API XXH_errorcode XXH32_reset(XXH32_state_t* statePtr, unsigned int s
     
     
     FORCE_INLINE XXH_errorcode
    -XXH32_update_endian(XXH32_state_t* state, const void* input, size_t len, XXH_endianess endian)
    +XXH32_update_endian(XXH32_state_t* state, const void* input, size_t len, XXH_endianness endian)
     {
         if (input==NULL)
     #if defined(XXH_ACCEPT_NULL_INPUT_POINTER) && (XXH_ACCEPT_NULL_INPUT_POINTER>=1)
    @@ -514,7 +514,7 @@ XXH32_update_endian(XXH32_state_t* state, const void* input, size_t len, XXH_end
     
     XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* state_in, const void* input, size_t len)
     {
    -    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
    +    XXH_endianness endian_detected = (XXH_endianness)XXH_CPU_LITTLE_ENDIAN;
     
         if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
             return XXH32_update_endian(state_in, input, len, XXH_littleEndian);
    @@ -524,7 +524,7 @@ XXH_PUBLIC_API XXH_errorcode XXH32_update (XXH32_state_t* state_in, const void*
     
     
     FORCE_INLINE U32
    -XXH32_digest_endian (const XXH32_state_t* state, XXH_endianess endian)
    +XXH32_digest_endian (const XXH32_state_t* state, XXH_endianness endian)
     {
         U32 h32;
     
    @@ -545,7 +545,7 @@ XXH32_digest_endian (const XXH32_state_t* state, XXH_endianess endian)
     
     XXH_PUBLIC_API unsigned int XXH32_digest (const XXH32_state_t* state_in)
     {
    -    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
    +    XXH_endianness endian_detected = (XXH_endianness)XXH_CPU_LITTLE_ENDIAN;
     
         if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
             return XXH32_digest_endian(state_in, XXH_littleEndian);
    @@ -642,7 +642,7 @@ static U64 XXH_swap64 (U64 x)
     }
     #endif
     
    -FORCE_INLINE U64 XXH_readLE64_align(const void* ptr, XXH_endianess endian, XXH_alignment align)
    +FORCE_INLINE U64 XXH_readLE64_align(const void* ptr, XXH_endianness endian, XXH_alignment align)
     {
         if (align==XXH_unaligned)
             return endian==XXH_littleEndian ? XXH_read64(ptr) : XXH_swap64(XXH_read64(ptr));
    @@ -650,7 +650,7 @@ FORCE_INLINE U64 XXH_readLE64_align(const void* ptr, XXH_endianess endian, XXH_a
             return endian==XXH_littleEndian ? *(const U64*)ptr : XXH_swap64(*(const U64*)ptr);
     }
     
    -FORCE_INLINE U64 XXH_readLE64(const void* ptr, XXH_endianess endian)
    +FORCE_INLINE U64 XXH_readLE64(const void* ptr, XXH_endianness endian)
     {
         return XXH_readLE64_align(ptr, endian, XXH_unaligned);
     }
    @@ -700,7 +700,7 @@ static U64 XXH64_avalanche(U64 h64)
     
     static U64
     XXH64_finalize(U64 h64, const void* ptr, size_t len,
    -               XXH_endianess endian, XXH_alignment align)
    +               XXH_endianness endian, XXH_alignment align)
     {
         const BYTE* p = (const BYTE*)ptr;
     
    @@ -809,7 +809,7 @@ XXH64_finalize(U64 h64, const void* ptr, size_t len,
     
     FORCE_INLINE U64
     XXH64_endian_align(const void* input, size_t len, U64 seed,
    -                XXH_endianess endian, XXH_alignment align)
    +                XXH_endianness endian, XXH_alignment align)
     {
         const BYTE* p = (const BYTE*)input;
         const BYTE* bEnd = p + len;
    @@ -861,7 +861,7 @@ XXH_PUBLIC_API unsigned long long XXH64 (const void* input, size_t len, unsigned
         XXH64_update(&state, input, len);
         return XXH64_digest(&state);
     #else
    -    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
    +    XXH_endianness endian_detected = (XXH_endianness)XXH_CPU_LITTLE_ENDIAN;
     
         if (XXH_FORCE_ALIGN_CHECK) {
             if ((((size_t)input) & 7)==0) {  /* Input is aligned, let's leverage the speed advantage */
    @@ -909,7 +909,7 @@ XXH_PUBLIC_API XXH_errorcode XXH64_reset(XXH64_state_t* statePtr, unsigned long
     }
     
     FORCE_INLINE XXH_errorcode
    -XXH64_update_endian (XXH64_state_t* state, const void* input, size_t len, XXH_endianess endian)
    +XXH64_update_endian (XXH64_state_t* state, const void* input, size_t len, XXH_endianness endian)
     {
         if (input==NULL)
     #if defined(XXH_ACCEPT_NULL_INPUT_POINTER) && (XXH_ACCEPT_NULL_INPUT_POINTER>=1)
    @@ -970,7 +970,7 @@ XXH64_update_endian (XXH64_state_t* state, const void* input, size_t len, XXH_en
     
     XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* state_in, const void* input, size_t len)
     {
    -    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
    +    XXH_endianness endian_detected = (XXH_endianness)XXH_CPU_LITTLE_ENDIAN;
     
         if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
             return XXH64_update_endian(state_in, input, len, XXH_littleEndian);
    @@ -978,7 +978,7 @@ XXH_PUBLIC_API XXH_errorcode XXH64_update (XXH64_state_t* state_in, const void*
             return XXH64_update_endian(state_in, input, len, XXH_bigEndian);
     }
     
    -FORCE_INLINE U64 XXH64_digest_endian (const XXH64_state_t* state, XXH_endianess endian)
    +FORCE_INLINE U64 XXH64_digest_endian (const XXH64_state_t* state, XXH_endianness endian)
     {
         U64 h64;
     
    @@ -1004,7 +1004,7 @@ FORCE_INLINE U64 XXH64_digest_endian (const XXH64_state_t* state, XXH_endianess
     
     XXH_PUBLIC_API unsigned long long XXH64_digest (const XXH64_state_t* state_in)
     {
    -    XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN;
    +    XXH_endianness endian_detected = (XXH_endianness)XXH_CPU_LITTLE_ENDIAN;
     
         if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT)
             return XXH64_digest_endian(state_in, XXH_littleEndian);
    diff --git a/ossfuzz/decompress_fuzzer.c b/ossfuzz/decompress_fuzzer.c
    index 490b3fd6ecf009129f9ecbdc01184eb1fdfd82eb..b537af8428f3849ea31fa9fced334768d2a324c0 100644
    --- a/ossfuzz/decompress_fuzzer.c
    +++ b/ossfuzz/decompress_fuzzer.c
    @@ -67,7 +67,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
         /* Partial decompression with small prefix. */
         LZ4_decompress_safe_partial_usingDict((char const*)dataAfterDict, dst, size,
                                       dstCapacity, dstCapacity, smallDict, smallDictSize);
    -    /* Partial decompression wtih large prefix. */
    +    /* Partial decompression with large prefix. */
         LZ4_decompress_safe_partial_usingDict((char const*)dataAfterDict, dst, size,
                                       dstCapacity, dstCapacity, largeDict, largeDictSize);
         free(dst);
    diff --git a/ossfuzz/fuzz_helpers.h b/ossfuzz/fuzz_helpers.h
    index efd9acfea24d8a515f0ca30aa027088dda670956..4ef1c98e9e89450aa3a4c681fa22c6067ffde85a 100644
    --- a/ossfuzz/fuzz_helpers.h
    +++ b/ossfuzz/fuzz_helpers.h
    @@ -44,7 +44,7 @@ extern "C" {
               : (fprintf(stderr, "%s: %u: Assertion: `%s' failed. %s\n", __FILE__, \
                          __LINE__, FUZZ_QUOTE(cond), (msg)),                       \
                  abort()))
    -#define FUZZ_ASSERT(cond) FUZZ_ASSERT_MSG((cond), "");
    +#define FUZZ_ASSERT(cond) FUZZ_ASSERT_MSG((cond), "")
     
     #if defined(__GNUC__)
     #define FUZZ_STATIC static __inline __attribute__((unused))
    diff --git a/programs/.gitignore b/programs/.gitignore
    index 9ffadd9ce7576a307ecd00c3b67d37c4ff03e38a..c89f52a4868af1db7cca7c17e922a1727c0eb9cd 100644
    --- a/programs/.gitignore
    +++ b/programs/.gitignore
    @@ -4,6 +4,7 @@ unlz4
     lz4cat
     lz4c
     lz4c32
    +lz4-nomt
     lz4-wlib
     datagen
     frametest
    diff --git a/programs/COPYING b/programs/COPYING
    index d159169d1050894d3ea3b98e1c965c4058208fe1..c728282bf0c88d16f64db747332efb440f652c05 100644
    --- a/programs/COPYING
    +++ b/programs/COPYING
    @@ -1,339 +1,83 @@
    -                    GNU GENERAL PUBLIC LICENSE
    -                       Version 2, June 1991
    -
    - Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
    - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
    - Everyone is permitted to copy and distribute verbatim copies
    - of this license document, but changing it is not allowed.
    -
    -                            Preamble
    -
    -  The licenses for most software are designed to take away your
    -freedom to share and change it.  By contrast, the GNU General Public
    -License is intended to guarantee your freedom to share and change free
    -software--to make sure the software is free for all its users.  This
    -General Public License applies to most of the Free Software
    -Foundation's software and to any other program whose authors commit to
    -using it.  (Some other Free Software Foundation software is covered by
    -the GNU Lesser General Public License instead.)  You can apply it to
    -your programs, too.
    -
    -  When we speak of free software, we are referring to freedom, not
    -price.  Our General Public Licenses are designed to make sure that you
    -have the freedom to distribute copies of free software (and charge for
    -this service if you wish), that you receive source code or can get it
    -if you want it, that you can change the software or use pieces of it
    -in new free programs; and that you know you can do these things.
    -
    -  To protect your rights, we need to make restrictions that forbid
    -anyone to deny you these rights or to ask you to surrender the rights.
    -These restrictions translate to certain responsibilities for you if you
    -distribute copies of the software, or if you modify it.
    -
    -  For example, if you distribute copies of such a program, whether
    -gratis or for a fee, you must give the recipients all the rights that
    -you have.  You must make sure that they, too, receive or can get the
    -source code.  And you must show them these terms so they know their
    -rights.
    -
    -  We protect your rights with two steps: (1) copyright the software, and
    -(2) offer you this license which gives you legal permission to copy,
    -distribute and/or modify the software.
    -
    -  Also, for each author's protection and ours, we want to make certain
    -that everyone understands that there is no warranty for this free
    -software.  If the software is modified by someone else and passed on, we
    -want its recipients to know that what they have is not the original, so
    -that any problems introduced by others will not reflect on the original
    -authors' reputations.
    -
    -  Finally, any free program is threatened constantly by software
    -patents.  We wish to avoid the danger that redistributors of a free
    -program will individually obtain patent licenses, in effect making the
    -program proprietary.  To prevent this, we have made it clear that any
    -patent must be licensed for everyone's free use or not licensed at all.
    -
    -  The precise terms and conditions for copying, distribution and
    -modification follow.
    -
    -                    GNU GENERAL PUBLIC LICENSE
    -   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
    -
    -  0. This License applies to any program or other work which contains
    -a notice placed by the copyright holder saying it may be distributed
    -under the terms of this General Public License.  The "Program", below,
    -refers to any such program or work, and a "work based on the Program"
    -means either the Program or any derivative work under copyright law:
    -that is to say, a work containing the Program or a portion of it,
    -either verbatim or with modifications and/or translated into another
    -language.  (Hereinafter, translation is included without limitation in
    -the term "modification".)  Each licensee is addressed as "you".
    -
    -Activities other than copying, distribution and modification are not
    -covered by this License; they are outside its scope.  The act of
    -running the Program is not restricted, and the output from the Program
    -is covered only if its contents constitute a work based on the
    -Program (independent of having been made by running the Program).
    -Whether that is true depends on what the Program does.
    -
    -  1. You may copy and distribute verbatim copies of the Program's
    -source code as you receive it, in any medium, provided that you
    -conspicuously and appropriately publish on each copy an appropriate
    -copyright notice and disclaimer of warranty; keep intact all the
    -notices that refer to this License and to the absence of any warranty;
    -and give any other recipients of the Program a copy of this License
    -along with the Program.
    -
    -You may charge a fee for the physical act of transferring a copy, and
    -you may at your option offer warranty protection in exchange for a fee.
    -
    -  2. You may modify your copy or copies of the Program or any portion
    -of it, thus forming a work based on the Program, and copy and
    -distribute such modifications or work under the terms of Section 1
    -above, provided that you also meet all of these conditions:
    -
    -    a) You must cause the modified files to carry prominent notices
    -    stating that you changed the files and the date of any change.
    -
    -    b) You must cause any work that you distribute or publish, that in
    -    whole or in part contains or is derived from the Program or any
    -    part thereof, to be licensed as a whole at no charge to all third
    -    parties under the terms of this License.
    -
    -    c) If the modified program normally reads commands interactively
    -    when run, you must cause it, when started running for such
    -    interactive use in the most ordinary way, to print or display an
    -    announcement including an appropriate copyright notice and a
    -    notice that there is no warranty (or else, saying that you provide
    -    a warranty) and that users may redistribute the program under
    -    these conditions, and telling the user how to view a copy of this
    -    License.  (Exception: if the Program itself is interactive but
    -    does not normally print such an announcement, your work based on
    -    the Program is not required to print an announcement.)
    -
    -These requirements apply to the modified work as a whole.  If
    -identifiable sections of that work are not derived from the Program,
    -and can be reasonably considered independent and separate works in
    -themselves, then this License, and its terms, do not apply to those
    -sections when you distribute them as separate works.  But when you
    -distribute the same sections as part of a whole which is a work based
    -on the Program, the distribution of the whole must be on the terms of
    -this License, whose permissions for other licensees extend to the
    -entire whole, and thus to each and every part regardless of who wrote it.
    -
    -Thus, it is not the intent of this section to claim rights or contest
    -your rights to work written entirely by you; rather, the intent is to
    -exercise the right to control the distribution of derivative or
    -collective works based on the Program.
    -
    -In addition, mere aggregation of another work not based on the Program
    -with the Program (or with a work based on the Program) on a volume of
    -a storage or distribution medium does not bring the other work under
    -the scope of this License.
    -
    -  3. You may copy and distribute the Program (or a work based on it,
    -under Section 2) in object code or executable form under the terms of
    -Sections 1 and 2 above provided that you also do one of the following:
    -
    -    a) Accompany it with the complete corresponding machine-readable
    -    source code, which must be distributed under the terms of Sections
    -    1 and 2 above on a medium customarily used for software interchange; or,
    -
    -    b) Accompany it with a written offer, valid for at least three
    -    years, to give any third party, for a charge no more than your
    -    cost of physically performing source distribution, a complete
    -    machine-readable copy of the corresponding source code, to be
    -    distributed under the terms of Sections 1 and 2 above on a medium
    -    customarily used for software interchange; or,
    -
    -    c) Accompany it with the information you received as to the offer
    -    to distribute corresponding source code.  (This alternative is
    -    allowed only for noncommercial distribution and only if you
    -    received the program in object code or executable form with such
    -    an offer, in accord with Subsection b above.)
    -
    -The source code for a work means the preferred form of the work for
    -making modifications to it.  For an executable work, complete source
    -code means all the source code for all modules it contains, plus any
    -associated interface definition files, plus the scripts used to
    -control compilation and installation of the executable.  However, as a
    -special exception, the source code distributed need not include
    -anything that is normally distributed (in either source or binary
    -form) with the major components (compiler, kernel, and so on) of the
    -operating system on which the executable runs, unless that component
    -itself accompanies the executable.
    -
    -If distribution of executable or object code is made by offering
    -access to copy from a designated place, then offering equivalent
    -access to copy the source code from the same place counts as
    -distribution of the source code, even though third parties are not
    -compelled to copy the source along with the object code.
    -
    -  4. You may not copy, modify, sublicense, or distribute the Program
    -except as expressly provided under this License.  Any attempt
    -otherwise to copy, modify, sublicense or distribute the Program is
    -void, and will automatically terminate your rights under this License.
    -However, parties who have received copies, or rights, from you under
    -this License will not have their licenses terminated so long as such
    -parties remain in full compliance.
    -
    -  5. You are not required to accept this License, since you have not
    -signed it.  However, nothing else grants you permission to modify or
    -distribute the Program or its derivative works.  These actions are
    -prohibited by law if you do not accept this License.  Therefore, by
    -modifying or distributing the Program (or any work based on the
    -Program), you indicate your acceptance of this License to do so, and
    -all its terms and conditions for copying, distributing or modifying
    -the Program or works based on it.
    -
    -  6. Each time you redistribute the Program (or any work based on the
    -Program), the recipient automatically receives a license from the
    -original licensor to copy, distribute or modify the Program subject to
    -these terms and conditions.  You may not impose any further
    -restrictions on the recipients' exercise of the rights granted herein.
    -You are not responsible for enforcing compliance by third parties to
    -this License.
    -
    -  7. If, as a consequence of a court judgment or allegation of patent
    -infringement or for any other reason (not limited to patent issues),
    -conditions are imposed on you (whether by court order, agreement or
    -otherwise) that contradict the conditions of this License, they do not
    -excuse you from the conditions of this License.  If you cannot
    -distribute so as to satisfy simultaneously your obligations under this
    -License and any other pertinent obligations, then as a consequence you
    -may not distribute the Program at all.  For example, if a patent
    -license would not permit royalty-free redistribution of the Program by
    -all those who receive copies directly or indirectly through you, then
    -the only way you could satisfy both it and this License would be to
    -refrain entirely from distribution of the Program.
    -
    -If any portion of this section is held invalid or unenforceable under
    -any particular circumstance, the balance of the section is intended to
    -apply and the section as a whole is intended to apply in other
    -circumstances.
    -
    -It is not the purpose of this section to induce you to infringe any
    -patents or other property right claims or to contest validity of any
    -such claims; this section has the sole purpose of protecting the
    -integrity of the free software distribution system, which is
    -implemented by public license practices.  Many people have made
    -generous contributions to the wide range of software distributed
    -through that system in reliance on consistent application of that
    -system; it is up to the author/donor to decide if he or she is willing
    -to distribute software through any other system and a licensee cannot
    -impose that choice.
    -
    -This section is intended to make thoroughly clear what is believed to
    -be a consequence of the rest of this License.
    -
    -  8. If the distribution and/or use of the Program is restricted in
    -certain countries either by patents or by copyrighted interfaces, the
    -original copyright holder who places the Program under this License
    -may add an explicit geographical distribution limitation excluding
    -those countries, so that distribution is permitted only in or among
    -countries not thus excluded.  In such case, this License incorporates
    -the limitation as if written in the body of this License.
    -
    -  9. The Free Software Foundation may publish revised and/or new versions
    -of the General Public License from time to time.  Such new versions will
    -be similar in spirit to the present version, but may differ in detail to
    -address new problems or concerns.
    -
    -Each version is given a distinguishing version number.  If the Program
    -specifies a version number of this License which applies to it and "any
    -later version", you have the option of following the terms and conditions
    -either of that version or of any later version published by the Free
    -Software Foundation.  If the Program does not specify a version number of
    -this License, you may choose any version ever published by the Free Software
    -Foundation.
    -
    -  10. If you wish to incorporate parts of the Program into other free
    -programs whose distribution conditions are different, write to the author
    -to ask for permission.  For software which is copyrighted by the Free
    -Software Foundation, write to the Free Software Foundation; we sometimes
    -make exceptions for this.  Our decision will be guided by the two goals
    -of preserving the free status of all derivatives of our free software and
    -of promoting the sharing and reuse of software generally.
    -
    -                            NO WARRANTY
    -
    -  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
    -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
    -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
    -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
    -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
    -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
    -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
    -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
    -REPAIR OR CORRECTION.
    -
    -  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
    -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
    -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
    -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
    -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
    -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
    -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
    -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
    -POSSIBILITY OF SUCH DAMAGES.
    -
    -                     END OF TERMS AND CONDITIONS
    -
    -            How to Apply These Terms to Your New Programs
    -
    -  If you develop a new program, and you want it to be of the greatest
    -possible use to the public, the best way to achieve this is to make it
    -free software which everyone can redistribute and change under these terms.
    -
    -  To do so, attach the following notices to the program.  It is safest
    -to attach them to the start of each source file to most effectively
    -convey the exclusion of warranty; and each file should have at least
    -the "copyright" line and a pointer to where the full notice is found.
    -
    -    
    -    Copyright (C)   
    -
    -    This program is free software; you can redistribute it and/or modify
    -    it under the terms of the GNU General Public License as published by
    -    the Free Software Foundation; either version 2 of the License, or
    -    (at your option) any later version.
    -
    -    This program is distributed in the hope that it will be useful,
    -    but WITHOUT ANY WARRANTY; without even the implied warranty of
    -    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    -    GNU General Public License for more details.
    -
    -    You should have received a copy of the GNU General Public License along
    -    with this program; if not, write to the Free Software Foundation, Inc.,
    -    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
    -
    -Also add information on how to contact you by electronic and paper mail.
    -
    -If the program is interactive, make it output a short notice like this
    -when it starts in an interactive mode:
    -
    -    Gnomovision version 69, Copyright (C) year name of author
    -    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    -    This is free software, and you are welcome to redistribute it
    -    under certain conditions; type `show c' for details.
    -
    -The hypothetical commands `show w' and `show c' should show the appropriate
    -parts of the General Public License.  Of course, the commands you use may
    -be called something other than `show w' and `show c'; they could even be
    -mouse-clicks or menu items--whatever suits your program.
    -
    -You should also get your employer (if you work as a programmer) or your
    -school, if any, to sign a "copyright disclaimer" for the program, if
    -necessary.  Here is a sample; alter the names:
    -
    -  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
    -  `Gnomovision' (which makes passes at compilers) written by James Hacker.
    -
    -  , 1 April 1989
    -  Ty Coon, President of Vice
    -
    -This General Public License does not permit incorporating your program into
    -proprietary programs.  If your program is a subroutine library, you may
    -consider it more useful to permit linking proprietary applications with the
    -library.  If this is what you want to do, use the GNU Lesser General
    -Public License instead of this License.
    +Full name:
    +GNU General Public License v2.0 or later
    +
    +Short identifier:
    +GPL-2.0-or-later
    +
    +Text:
    +GNU GENERAL PUBLIC LICENSE
    +Version 2, June 1991
    +
    +Copyright (C) 1989, 1991 Free Software Foundation, Inc.
    +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
    +
    +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
    +
    +Preamble
    +
    +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
    +
    +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
    +
    +To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
    +
    +For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
    +
    +We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
    +
    +Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
    +
    +Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
    +
    +The precise terms and conditions for copying, distribution and modification follow.
    +
    +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
    +
    +0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
    +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
    +
    +1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
    +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
    +
    +2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
    +a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
    +b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
    +c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
    +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
    +
    +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
    +
    +In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
    +
    +3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
    +a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
    +b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
    +c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
    +The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
    +
    +If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
    +
    +4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
    +
    +5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
    +
    +6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
    +
    +7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
    +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
    +
    +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
    +
    +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
    +
    +8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
    +
    +9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
    +Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
    +
    +10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
    +NO WARRANTY
    +
    +11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
    +
    +12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
    diff --git a/programs/Makefile b/programs/Makefile
    index ace0d0374f78c19144cff85e8da29441f0b0674e..643ce14fbe261a7d533b49be01daeb473ccae8e3 100644
    --- a/programs/Makefile
    +++ b/programs/Makefile
    @@ -1,6 +1,6 @@
     # ##########################################################################
     # LZ4 programs - Makefile
    -# Copyright (C) Yann Collet 2011-2020
    +# Copyright (C) Yann Collet 2011-2023
     #
     # This Makefile is validated for Linux, macOS, *BSD, Hurd, Solaris, MSYS2 targets
     #
    @@ -28,30 +28,30 @@
     # lz4c  : CLU, supporting also legacy lz4demo arguments
     # lz4c32: Same as lz4c, but forced to compile in 32-bits mode
     # ##########################################################################
    -SED = sed
    +SED ?= sed
     
     # Version numbers
    -LZ4DIR   := ../lib
    -LIBVER_SRC := $(LZ4DIR)/lz4.h
    -LIBVER_MAJOR_SCRIPT:=`$(SED) -n '/define LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
    -LIBVER_MINOR_SCRIPT:=`$(SED) -n '/define LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
    -LIBVER_PATCH_SCRIPT:=`$(SED) -n '/define LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
    +LIBDIR   := ../lib
    +LIBVER_SRC := $(LIBDIR)/lz4.h
    +LIBVER_MAJOR_SCRIPT:=`$(SED) -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MAJOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
    +LIBVER_MINOR_SCRIPT:=`$(SED) -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_MINOR/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
    +LIBVER_PATCH_SCRIPT:=`$(SED) -n '/define[[:blank:]][[:blank:]]*LZ4_VERSION_RELEASE/s/.*[[:blank:]]\([0-9][0-9]*\).*/\1/p' < $(LIBVER_SRC)`
     LIBVER_SCRIPT:= $(LIBVER_MAJOR_SCRIPT).$(LIBVER_MINOR_SCRIPT).$(LIBVER_PATCH_SCRIPT)
     LIBVER_MAJOR := $(shell echo $(LIBVER_MAJOR_SCRIPT))
     LIBVER_MINOR := $(shell echo $(LIBVER_MINOR_SCRIPT))
     LIBVER_PATCH := $(shell echo $(LIBVER_PATCH_SCRIPT))
     LIBVER   := $(shell echo $(LIBVER_SCRIPT))
     
    -LIBFILES  = $(wildcard $(LZ4DIR)/*.c)
    +LIBFILES  = $(wildcard $(LIBDIR)/*.c)
     SRCFILES  = $(sort $(LIBFILES) $(wildcard *.c))
     OBJFILES  = $(SRCFILES:.c=.o)
     
    -CPPFLAGS += -I$(LZ4DIR) -DXXH_NAMESPACE=LZ4_
    -CFLAGS   ?= -O3
     DEBUGFLAGS= -Wall -Wextra -Wundef -Wcast-qual -Wcast-align -Wshadow \
                 -Wswitch-enum -Wdeclaration-after-statement -Wstrict-prototypes \
                 -Wpointer-arith -Wstrict-aliasing=1
    -CFLAGS   += $(DEBUGFLAGS) $(MOREFLAGS)
    +USERCFLAGS:= -O3 $(CFLAGS) # -O3 can be overruled by user-provided -Ox level
    +CFLAGS    = $(DEBUGFLAGS) $(USERCFLAGS)
    +CPPFLAGS += -I$(LIBDIR) -DXXH_NAMESPACE=LZ4_
     
     include ../Makefile.inc
     
    @@ -60,20 +60,37 @@ ifeq ($(TARGET_OS)$(shell $(OS_VERSION)),SunOS5.10)
     LDFLAGS  += -lrt
     endif
     
    -FLAGS     = $(CFLAGS) $(CPPFLAGS) $(LDFLAGS)
    +ALLFLAGS  = $(CFLAGS) $(CPPFLAGS) $(LDFLAGS)
    +
    +# thread detection
    +NUM_SYMBOL   := \#
    +NO_THREAD_MSG:= ==> no multithread support: building for single-thread mode only
    +HAVE_PTHREAD := $(shell printf '$(NUM_SYMBOL)include \nint main(void) { return 0; }' > have_pthread.c && $(CC) $(ALLFLAGS) -o have_pthread$(EXT) have_pthread.c -pthread 2> $(VOID) && rm -f have_pthread$(EXT) && echo 1 || echo 0; rm have_pthread.c)
    +HAVE_MULTITHREAD  := $(shell [ "$(HAVE_PTHREAD)" -eq "1" -o -n "$(filter Windows%,$(OS))" ] && echo 1 || echo 0)
    +ifeq ($(HAVE_MULTITHREAD), 1)
    +  THREAD_MSG := ==> building with multithreading support
    +  THREAD_CPP := -DLZ4IO_MULTITHREAD
    +  ifeq ($(HAVE_PTHREAD), 1)
    +    THREAD_LD  := -pthread
    +  endif
    +else
    +  THREAD_MSG := $(NO_THREAD_MSG)
    +endif
     
     LZ4_VERSION=$(LIBVER)
    -MD2ROFF   = ronn
    +MD2ROFF    = ronn
     MD2ROFF_FLAGS = --roff --warnings --manual="User Commands" --organization="lz4 $(LZ4_VERSION)"
     
    -
    +.PHONY:default
     default: lz4-release
     
     # silent mode by default; verbose can be triggered by V=1 or VERBOSE=1
     $(V)$(VERBOSE).SILENT:
     
    -all: lz4 lz4c
    +.PHONY:all
    +all: lz4 lz4-nomt lz4c unlz4 lz4cat
     
    +.PHONY:all32
     all32: CFLAGS+=-m32
     all32: all
     
    @@ -81,64 +98,89 @@ ifeq ($(WINBASED),yes)
     lz4-exe.rc: lz4-exe.rc.in
     	@echo creating executable resource
     	$(SED) -e 's|@PROGNAME@|lz4|' \
    -         -e 's|@LIBVER_MAJOR@|$(LIBVER_MAJOR)|g' \
    -         -e 's|@LIBVER_MINOR@|$(LIBVER_MINOR)|g' \
    -         -e 's|@LIBVER_PATCH@|$(LIBVER_PATCH)|g' \
    -         -e 's|@EXT@|$(EXT)|g' \
    -          $< >$@
    +           -e 's|@LIBVER_MAJOR@|$(LIBVER_MAJOR)|g' \
    +           -e 's|@LIBVER_MINOR@|$(LIBVER_MINOR)|g' \
    +           -e 's|@LIBVER_PATCH@|$(LIBVER_PATCH)|g' \
    +           -e 's|@EXT@|.exe|g' \
    +           $< >$@
     
     lz4-exe.o: lz4-exe.rc
     	$(WINDRES) -i lz4-exe.rc -o lz4-exe.o
     
    +lz4: CPPFLAGS += $(THREAD_CPP)
    +lz4: LDFLAGS += $(THREAD_LD)
     lz4: $(OBJFILES) lz4-exe.o
    -	$(CC) $(FLAGS) $^ -o $@$(EXT)
    +	echo "$(THREAD_MSG)"
    +	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
     else
    +lz4: CPPFLAGS += $(THREAD_CPP)
    +lz4: LDFLAGS += $(THREAD_LD)
     lz4: $(OBJFILES)
    -	$(CC) $(FLAGS) $(OBJFILES) -o $@$(EXT) $(LDLIBS)
    +	echo "$(THREAD_MSG)"
    +	$(CC) $(ALLFLAGS) $(OBJFILES) -o $@$(EXT) $(LDLIBS)
     endif
    +CLEAN += lz4
     
     .PHONY: lz4-release
     lz4-release: DEBUGFLAGS=
    +lz4-release: CPPFLAGS+=-DNDEBUG
     lz4-release: lz4
     
    +CLEAN += lz4-nomt
    +lz4-nomt: $(SRCFILES)
    +	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
    +
    +CLEAN += lz4-wlib
     lz4-wlib: LIBFILES =
    -lz4-wlib: SRCFILES+= $(LZ4DIR)/xxhash.c  # benchmark unit needs XXH64()
    -lz4-wlib: LDFLAGS += -L $(LZ4DIR)
    +lz4-wlib: SRCFILES+= $(LIBDIR)/xxhash.c  # benchmark unit needs XXH64()
    +lz4-wlib: LDFLAGS += -L $(LIBDIR)
     lz4-wlib: LDLIBS   = -llz4
     lz4-wlib: liblz4 $(OBJFILES)
     	@echo WARNING: $@ must link to an extended variant of the dynamic library which also exposes unstable symbols
    -	$(CC) $(FLAGS) $(OBJFILES) -o $@$(EXT) $(LDLIBS)
    +	$(CC) $(ALLFLAGS) $(OBJFILES) -o $@$(EXT) $(LDLIBS)
     
     .PHONY:liblz4
     liblz4:
    -	CPPFLAGS="-DLZ4F_PUBLISH_STATIC_FUNCTIONS -DLZ4_PUBLISH_STATIC_FUNCTIONS" $(MAKE) -C $(LZ4DIR) liblz4
    +	CPPFLAGS="-DLZ4F_PUBLISH_STATIC_FUNCTIONS -DLZ4_PUBLISH_STATIC_FUNCTIONS" $(MAKE) -C $(LIBDIR) liblz4
     
    +CLEAN += lz4c
     lz4c: lz4
     	$(LN_SF) lz4$(EXT) lz4c$(EXT)
     
    +CLEAN += lz4c32
     lz4c32: CFLAGS += -m32
     lz4c32 : $(SRCFILES)
    -	$(CC) $(FLAGS) $^ -o $@$(EXT)
    +	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
    +
    +CLEAN += unlz4
    +unlz4: lz4
    +	$(LN_SF) lz4$(EXT) unlz4$(EXT)
    +
    +CLEAN += lz4cat
    +lz4cat: lz4
    +	$(LN_SF) lz4$(EXT) lz4cat$(EXT)
     
     lz4.1: lz4.1.md $(LIBVER_SRC)
     	cat $< | $(MD2ROFF) $(MD2ROFF_FLAGS) | $(SED) -n '/^\.\\\".*/!p' > $@
     
    +.PHONY:man
     man: lz4.1
     
    +.PHONY:clean-man
     clean-man:
     	$(RM) lz4.1
     
    +.PHONY:preview-man
     preview-man: clean-man man
     	man ./lz4.1
     
    +.PHONY:clean
     clean:
     ifeq ($(WINBASED),yes)
     	$(RM) *.rc
     endif
    -	$(MAKE) -C $(LZ4DIR) $@ > $(VOID)
    -	$(RM) core *.o *.test tmp* \
    -           lz4$(EXT) lz4c$(EXT) lz4c32$(EXT) lz4-wlib$(EXT) \
    -           unlz4$(EXT) lz4cat$(EXT)
    +	$(MAKE) -C $(LIBDIR) $@ > $(VOID)
    +	$(RM) $(CLEAN) *.o tmp* *.test core
     	@echo Cleaning completed
     
     
    @@ -147,12 +189,6 @@ endif
     #-----------------------------------------------------------------------------
     ifeq ($(POSIX_ENV),Yes)
     
    -unlz4: lz4
    -	$(LN_SF) lz4$(EXT) unlz4$(EXT)
    -
    -lz4cat: lz4
    -	$(LN_SF) lz4$(EXT) lz4cat$(EXT)
    -
     DESTDIR     ?=
     # directory variables : GNU conventions prefer lowercase
     # see https://www.gnu.org/prep/standards/html_node/Makefile-Conventions.html
    @@ -170,9 +206,10 @@ mandir      ?= $(MANDIR)
     MAN1DIR     ?= $(mandir)/man1
     man1dir     ?= $(MAN1DIR)
     
    +.PHONY: install
     install: lz4
     	@echo Installing binaries in $(DESTDIR)$(bindir)
    -	$(INSTALL_DIR) $(DESTDIR)$(bindir)/ $(DESTDIR)$(man1dir)/
    +	$(MAKE_DIR) $(DESTDIR)$(bindir)/ $(DESTDIR)$(man1dir)/
     	$(INSTALL_PROGRAM) lz4$(EXT) $(DESTDIR)$(bindir)/lz4$(EXT)
     	$(LN_SF) lz4$(EXT) $(DESTDIR)$(bindir)/lz4c$(EXT)
     	$(LN_SF) lz4$(EXT) $(DESTDIR)$(bindir)/lz4cat$(EXT)
    @@ -184,6 +221,7 @@ install: lz4
     	$(LN_SF) lz4.1 $(DESTDIR)$(man1dir)/unlz4.1
     	@echo lz4 installation completed
     
    +.PHONY: uninstall
     uninstall:
     	$(RM) $(DESTDIR)$(bindir)/lz4cat$(EXT)
     	$(RM) $(DESTDIR)$(bindir)/unlz4$(EXT)
    diff --git a/programs/README.md b/programs/README.md
    index c1995afeafe41657f38fba7657a5fc6c08efb8b5..104e31a0f76298de1fb80940e29c7415477b14e8 100644
    --- a/programs/README.md
    +++ b/programs/README.md
    @@ -2,38 +2,68 @@ Command Line Interface for LZ4 library
     ============================================
     
     ### Build
    -The Command Line Interface (CLI) can be generated
    -using the `make` command without any additional parameters.
    -
    -The `Makefile` script supports all [standard conventions](https://www.gnu.org/prep/standards/html_node/Makefile-Conventions.html),
    -including standard targets (`all`, `install`, `clean`, etc.)
    -and standard variables (`CC`, `CFLAGS`, `CPPFLAGS`, etc.).
    -
    -For advanced use cases, there are targets to different variations of the CLI:
    -- `lz4` : default CLI, with a command line syntax close to gzip
    -- `lz4c` : Same as `lz4` with additional support legacy lz4 commands (incompatible with gzip)
    -- `lz4c32` : Same as `lz4c`, but forced to compile in 32-bits mode
    +The `lz4` Command Line Interface (CLI) is generated
    +using the `make` command, no additional parameter required.
     
     The CLI generates and decodes [LZ4-compressed frames](../doc/lz4_Frame_format.md).
     
    +For more control over the build process,
    +the `Makefile` script supports all [standard conventions](https://www.gnu.org/prep/standards/html_node/Makefile-Conventions.html),
    +including standard targets (`all`, `install`, `clean`, etc.)
    +and standard variables (`CC`, `CFLAGS`, `CPPFLAGS`, etc.).
     
    -#### Aggregation of parameters
    -CLI supports aggregation of parameters i.e. `-b1`, `-e18`, and `-i1` can be joined into `-b1e18i1`.
    -
    -
    -#### Benchmark in Command Line Interface
    -CLI includes in-memory compression benchmark module for lz4.
    -The benchmark is conducted using a given filename.
    -The file is read into memory.
    -It makes benchmark more precise as it eliminates I/O overhead.
    +The makefile offer several targets for various use cases:
    +- `lz4` : default CLI, with a command line syntax similar to gzip
    +- `lz4c` : supports legacy lz4 commands (incompatible with gzip)
    +- `lz4c32` : Same as `lz4c`, but generates a 32-bits executable
    +- `unlz4`, `lz4cat` : symlinks to `lz4`, default to decompression and `cat` compressed files
    +- `man` : generates the man page, from `lz4.1.md` markdown source
    +
    +#### Makefile Build variables
    +- `HAVE_MULTITHREAD` : build with multithreading support. Detection is generally automatic, but can be forced to `0` or `1` if needed. This is for example useful when cross-compiling for Windows from Linux.
    +- `HAVE_PTHREAD` : determines presence of `` support. Detection is automatic, but can be forced to `0` or `1` if needed. This is in turn used by `make` to automatically trigger multithreading support.
    +
    +#### C Preprocessor Build variables
    +These variables are read by the preprocessor at compilation time. They influence executable behavior, such as default starting values, and are exposed from `programs/lz4conf.h`. These variables can manipulated by any build system.
    +Assignment methods vary depending on environments.
    +On a typical `posix` + `gcc` + `make` setup, they can be defined with `CPPFLAGS=-DVARIABLE=value` assignment.
    +- `LZ4_CLEVEL_DEFAULT`: default compression level when none provided. Default is `1`.
    +- `LZ4IO_MULTITHREAD`: enable multithreading support. Default is disabled.
    +- `LZ4_NBWORKERS_DEFAULT`: default nb of worker threads used in multithreading mode (can be overridden with command `-T#`).
    +   Default is `0`, which means "auto-determine" based on local cpu.
    +- `LZ4_NBWORKERS_MAX`: absolute maximum nb of workers that can be requested at runtime.
    +   Currently set to 200 by default.
    +   This is mostly meant to protect the system against unreasonable and likely bogus requests, such as a million threads.
    +- `LZ4_BLOCKSIZEID_DEFAULT`: default `lz4` block size code. Valid values are [4-7], corresponding to 64 KB, 256 KB, 1 MB and 4 MB. At the time of this writing, default is 7, corresponding to 4 MB block size.
    +
    +#### Environment Variables
    +It's possible to pass some parameters to `lz4` via environment variables.
    +This can be useful in situations where `lz4` is known to be invoked (from within a script for example) but there is no way to pass `lz4` parameters to influence the compression session.
    +The environment variable has higher priority than binary default, but lower priority than corresponding runtime command.
    +When set as global environment variables, it can enforce personalized defaults different from the binary set ones.
    +
    +`LZ4_CLEVEL` can be used to specify a default compression level that `lz4` employs for compression when no other compression level is specified on command line. Executable default is generally `1`.
    +
    +`LZ4_NBWORKERS` can be used to specify a default number of threads that `lz4` will employ for compression. Executable default is generally `0`, which means auto-determined based on local cpu. This functionality is only relevant when `lz4` is compiled with multithreading support. The maximum number of workers is capped at `LZ4_NBWORKERS_MAX` (`200` by default).
    +
    +### Aggregation of parameters
    +The `lz4` CLI supports aggregation for short commands. For example, `-d`, `-q`, and `-f` can be joined into `-dqf`.
    +Aggregation doesn't work for `--long-commands`, which **must** be separated.
    +
    +
    +### Benchmark in Command Line Interface
    +`lz4` CLI includes an in-memory compression benchmark module, triggered by command `-b#`, with `#` representing the compression level.
    +The benchmark is conducted on a provided list of filenames.
    +The files are then read entirely into memory, to eliminate I/O overhead.
    +When multiple files are provided, they are bundled into the same benchmark session (though each file is a separate compression / decompression). Using `-S` command separates them (one session per file).
    +When no file is provided, uses an internal Lorem Ipsum generator instead.
     
     The benchmark measures ratio, compressed size, compression and decompression speed.
    -One can select compression levels starting from `-b` and ending with `-e`.
    -The `-i` parameter selects a number of seconds used for each of tested levels.
    -
    +One can select multiple compression levels starting from `-b` and ending with `-e` (ascending).
    +The `-i` parameter selects a number of seconds used for each session.
     
     
    -#### Usage of Command Line Interface
    +### Usage of Command Line Interface
     The full list of commands can be obtained with `-h` or `-H` parameter:
     ```
     Usage :
    diff --git a/programs/bench.c b/programs/bench.c
    index 4d35ef92ac0b63ce9db2dbd0c4be0f6821557dfd..64e28ca08f72d73725f8a294c96bbae49e81d423 100644
    --- a/programs/bench.c
    +++ b/programs/bench.c
    @@ -43,9 +43,10 @@
     #include         /* clock_t, clock, CLOCKS_PER_SEC */
     #include       /* assert */
     
    -#include "datagen.h"     /* RDG_genBuffer */
    +#include "lorem.h"       /* LOREM_genBuffer */
     #include "xxhash.h"
     #include "bench.h"
    +#include "timefn.h"
     
     #define LZ4_STATIC_LINKING_ONLY
     #include "lz4.h"
    @@ -66,7 +67,7 @@
     #define NBSECONDS             3
     #define TIMELOOP_MICROSEC     1*1000000ULL /* 1 second */
     #define TIMELOOP_NANOSEC      1*1000000000ULL /* 1 second */
    -#define ACTIVEPERIOD_MICROSEC 70*1000000ULL /* 70 seconds */
    +#define ACTIVEPERIOD_NANOSEC 70*1000000000ULL /* 70 seconds */
     #define COOLPERIOD_SEC        10
     #define DECOMP_MULT           1 /* test decompression DECOMP_MULT times longer than compression */
     
    @@ -78,14 +79,14 @@
     
     static const size_t maxMemory = (sizeof(size_t)==4)  ?  (2 GB - 64 MB) : (size_t)(1ULL << ((sizeof(size_t)*8)-31));
     
    -static U32 g_compressibilityDefault = 50;
    -
     
     /* *************************************
     *  console display
     ***************************************/
    +#define DISPLAYOUT(...)      fprintf(stdout, __VA_ARGS__)
    +#define OUTLEVEL(l, ...)     if (g_displayLevel>=(l)) { DISPLAYOUT(__VA_ARGS__); }
     #define DISPLAY(...)         fprintf(stderr, __VA_ARGS__)
    -#define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
    +#define DISPLAYLEVEL(l, ...) if (g_displayLevel>=(l)) { DISPLAY(__VA_ARGS__); }
     static U32 g_displayLevel = 2;   /* 0 : no display;   1: errors;   2 : + result + interaction + warnings;   3 : + progression;   4 : + information */
     
     #define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \
    @@ -103,14 +104,14 @@ static clock_t g_time = 0;
     #  define DEBUG 0
     #endif
     #define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__);
    -#define END_PROCESS(error, ...)                                             \
    -{                                                                         \
    +#define END_PROCESS(error, ...)                                           \
    +do {                                                                      \
         DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \
         DISPLAYLEVEL(1, "Error %i : ", error);                                \
         DISPLAYLEVEL(1, __VA_ARGS__);                                         \
         DISPLAYLEVEL(1, "\n");                                                \
         exit(error);                                                          \
    -}
    +} while (0)
     
     #define LZ4_isError(errcode) (errcode==0)
     
    @@ -186,7 +187,7 @@ LZ4_compressInitStream(struct compressionParameters* pThis)
         pThis->LZ4_dictStream = LZ4_createStream();
         pThis->LZ4_streamHC = NULL;
         pThis->LZ4_dictStreamHC = NULL;
    -    LZ4_loadDict(pThis->LZ4_dictStream, pThis->dictBuf, pThis->dictSize);
    +    LZ4_loadDictSlow(pThis->LZ4_dictStream, pThis->dictBuf, pThis->dictSize);
     }
     
     static void
    @@ -196,81 +197,84 @@ LZ4_compressInitStreamHC(struct compressionParameters* pThis)
         pThis->LZ4_dictStream = NULL;
         pThis->LZ4_streamHC = LZ4_createStreamHC();
         pThis->LZ4_dictStreamHC = LZ4_createStreamHC();
    +    LZ4_resetStreamHC_fast(pThis->LZ4_dictStreamHC, pThis->cLevel);
         LZ4_loadDictHC(pThis->LZ4_dictStreamHC, pThis->dictBuf, pThis->dictSize);
     }
     
     static void
    -LZ4_compressResetNoStream(const struct compressionParameters* pThis)
    +LZ4_compressResetNoStream(const struct compressionParameters* cparams)
     {
    -    (void)pThis;
    +    (void)cparams;
     }
     
     static void
    -LZ4_compressResetStream(const struct compressionParameters* pThis)
    +LZ4_compressResetStream(const struct compressionParameters* cparams)
     {
    -    LZ4_resetStream_fast(pThis->LZ4_stream);
    -    LZ4_attach_dictionary(pThis->LZ4_stream, pThis->LZ4_dictStream);
    +    LZ4_resetStream_fast(cparams->LZ4_stream);
    +    LZ4_attach_dictionary(cparams->LZ4_stream, cparams->LZ4_dictStream);
     }
     
     static void
    -LZ4_compressResetStreamHC(const struct compressionParameters* pThis)
    +LZ4_compressResetStreamHC(const struct compressionParameters* cparams)
     {
    -    LZ4_resetStreamHC_fast(pThis->LZ4_streamHC, pThis->cLevel);
    -    LZ4_attach_HC_dictionary(pThis->LZ4_streamHC, pThis->LZ4_dictStreamHC);
    +    LZ4_resetStreamHC_fast(cparams->LZ4_streamHC, cparams->cLevel);
    +    LZ4_attach_HC_dictionary(cparams->LZ4_streamHC, cparams->LZ4_dictStreamHC);
     }
     
     static int
    -LZ4_compressBlockNoStream(const struct compressionParameters* pThis,
    +LZ4_compressBlockNoStream(const struct compressionParameters* cparams,
                               const char* src, char* dst,
                               int srcSize, int dstSize)
     {
    -    int const acceleration = (pThis->cLevel < 0) ? -pThis->cLevel + 1 : 1;
    +    int const acceleration = (cparams->cLevel < 0) ? -cparams->cLevel + 1 : 1;
         return LZ4_compress_fast(src, dst, srcSize, dstSize, acceleration);
     }
     
     static int
    -LZ4_compressBlockNoStreamHC(const struct compressionParameters* pThis,
    +LZ4_compressBlockNoStreamHC(const struct compressionParameters* cparams,
                                 const char* src, char* dst,
                                 int srcSize, int dstSize)
     {
    -    return LZ4_compress_HC(src, dst, srcSize, dstSize, pThis->cLevel);
    +    return LZ4_compress_HC(src, dst, srcSize, dstSize, cparams->cLevel);
     }
     
     static int
    -LZ4_compressBlockStream(const struct compressionParameters* pThis,
    +LZ4_compressBlockStream(const struct compressionParameters* cparams,
                             const char* src, char* dst,
                             int srcSize, int dstSize)
     {
    -    int const acceleration = (pThis->cLevel < 0) ? -pThis->cLevel + 1 : 1;
    -    return LZ4_compress_fast_continue(pThis->LZ4_stream, src, dst, srcSize, dstSize, acceleration);
    +    int const acceleration = (cparams->cLevel < 0) ? -cparams->cLevel + 1 : 1;
    +    LZ4_compressResetStream(cparams);
    +    return LZ4_compress_fast_continue(cparams->LZ4_stream, src, dst, srcSize, dstSize, acceleration);
     }
     
     static int
    -LZ4_compressBlockStreamHC(const struct compressionParameters* pThis,
    +LZ4_compressBlockStreamHC(const struct compressionParameters* cparams,
                               const char* src, char* dst,
                               int srcSize, int dstSize)
     {
    -    return LZ4_compress_HC_continue(pThis->LZ4_streamHC, src, dst, srcSize, dstSize);
    +    LZ4_compressResetStreamHC(cparams);
    +    return LZ4_compress_HC_continue(cparams->LZ4_streamHC, src, dst, srcSize, dstSize);
     }
     
     static void
    -LZ4_compressCleanupNoStream(const struct compressionParameters* pThis)
    +LZ4_compressCleanupNoStream(const struct compressionParameters* cparams)
     {
    -    (void)pThis;
    +    (void)cparams;
     }
     
     static void
    -LZ4_compressCleanupStream(const struct compressionParameters* pThis)
    +LZ4_compressCleanupStream(const struct compressionParameters* cparams)
     {
    -    LZ4_freeStream(pThis->LZ4_stream);
    -    LZ4_freeStream(pThis->LZ4_dictStream);
    +    LZ4_freeStream(cparams->LZ4_stream);
    +    LZ4_freeStream(cparams->LZ4_dictStream);
     }
     
     static void
    -LZ4_compressCleanupStreamHC(const struct compressionParameters* pThis)
    +LZ4_compressCleanupStreamHC(const struct compressionParameters* cparams)
     {
    -    LZ4_freeStreamHC(pThis->LZ4_streamHC);
    -    LZ4_freeStreamHC(pThis->LZ4_dictStreamHC);
    +    LZ4_freeStreamHC(cparams->LZ4_streamHC);
    +    LZ4_freeStreamHC(cparams->LZ4_dictStreamHC);
     }
     
     static void
    @@ -367,6 +371,7 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
         size_t const maxInSize = (size_t)LZ4_MAX_INPUT_SIZE / decMultiplier;
         size_t const maxDecSize = srcSize < maxInSize ? srcSize * decMultiplier : LZ4_MAX_INPUT_SIZE;
         void* const resultBuffer = malloc(maxDecSize);
    +    int benchError = 0;
         U32 nbBlocks;
         struct compressionParameters compP;
     
    @@ -410,7 +415,7 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
         }   }   }
     
         /* warming up memory */
    -    RDG_genBuffer(compressedBuffer, maxCompressedSize, 0.10, 0.50, 1);
    +    memset(compressedBuffer, ' ', maxCompressedSize);
     
         /* decode-only mode : copy input to @compressedBuffer */
         if (g_decodeOnly) {
    @@ -423,11 +428,11 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
         /* Bench */
         {   U64 fastestC = (U64)(-1LL), fastestD = (U64)(-1LL);
             U64 const crcOrig = XXH64(srcBuffer, srcSize, 0);
    -        UTIL_time_t coolTime = UTIL_getTime();
    +        TIME_t coolTime = TIME_getTime();
             U64 const maxTime = (g_nbSeconds * TIMELOOP_NANOSEC) + 100;
             U32 nbCompressionLoops = (U32)((5 MB) / (srcSize+1)) + 1;  /* conservative initial compression speed estimate */
             U32 nbDecodeLoops = (U32)((200 MB) / (srcSize+1)) + 1;  /* conservative initial decode speed estimate */
    -        U64 totalCTime=0, totalDTime=0;
    +        Duration_ns totalCTime=0, totalDTime=0;
             U32 cCompleted=(g_decodeOnly==1), dCompleted=0;
     #       define NB_MARKS 4
             const char* const marks[NB_MARKS] = { " |", " /", " =",  "\\" };
    @@ -437,23 +442,27 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
             double ratio = 0.;
     
             DISPLAYLEVEL(2, "\r%79s\r", "");
    +        if (g_nbSeconds==0) { nbCompressionLoops = 1; nbDecodeLoops = 1; }
             while (!cCompleted || !dCompleted) {
                 /* overheat protection */
    -            if (UTIL_clockSpanMicro(coolTime) > ACTIVEPERIOD_MICROSEC) {
    +            if (TIME_clockSpan_ns(coolTime) > ACTIVEPERIOD_NANOSEC) {
                     DISPLAYLEVEL(2, "\rcooling down ...    \r");
                     UTIL_sleep(COOLPERIOD_SEC);
    -                coolTime = UTIL_getTime();
    +                coolTime = TIME_getTime();
                 }
     
                 /* Compression */
                 DISPLAYLEVEL(2, "%2s-%-17.17s :%10u ->\r", marks[markNb], displayName, (U32)totalRSize);
    -            if (!cCompleted) memset(compressedBuffer, 0xE5, maxCompressedSize);  /* warm up and erase compressed buffer */
    +            if (!cCompleted) {
    +                memset(compressedBuffer, 0xE5, maxCompressedSize);  /* warm up and erase compressed buffer */
    +                { U32 blockNb; for (blockNb=0; blockNb 0) {
    -                        if (clockSpan < fastestC * nbCompressionLoops)
    -                            fastestC = clockSpan / nbCompressionLoops;
    +                {   Duration_ns const duration_ns = TIME_clockSpan_ns(timeStart);
    +                    if (duration_ns > 0) {
    +                        if (duration_ns < fastestC * nbCompressionLoops)
    +                            fastestC = duration_ns / nbCompressionLoops;
                             assert(fastestC > 0);
                             nbCompressionLoops = (U32)(TIMELOOP_NANOSEC / fastestC) + 1;  /* aim for ~1sec */
                         } else {
                             assert(nbCompressionLoops < 40000000);   /* avoid overflow */
                             nbCompressionLoops *= 100;
                         }
    -                    totalCTime += clockSpan;
    +                    totalCTime += duration_ns;
                         cCompleted = totalCTime>maxTime;
                     }
     
    @@ -485,10 +497,11 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
                     cSize += !cSize;  /* avoid div by 0 */
                     ratio = (double)totalRSize / (double)cSize;
                     markNb = (markNb+1) % NB_MARKS;
    -                DISPLAYLEVEL(2, "%2s-%-17.17s :%10u ->%10u (%5.3f),%6.1f MB/s\r",
    +                OUTLEVEL(2, "%2s-%-17.17s :%10u ->%10u (%5.3f),%6.1f MB/s\r",
                             marks[markNb], displayName,
                             (U32)totalRSize, (U32)cSize, ratio,
    -                        ((double)totalRSize / fastestC) * 1000 );
    +                        ((double)totalRSize / (double)fastestC) * 1000 );
    +                fflush(NULL);
                 }
                 (void)fastestD; (void)crcOrig;   /*  unused when decompression disabled */
     #if 1
    @@ -496,14 +509,14 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
                 if (!dCompleted) memset(resultBuffer, 0xD6, srcSize);  /* warm result buffer */
     
                 UTIL_sleepMilli(5); /* give processor time to other processes */
    -            UTIL_waitForNextTick();
    +            TIME_waitForNextTick();
     
                 if (!dCompleted) {
                     const DecFunction_f decFunction = g_decodeOnly ?
                         LZ4F_decompress_binding : LZ4_decompress_safe_usingDict;
                     const char* const decString = g_decodeOnly ?
                         "LZ4F_decompress" : "LZ4_decompress_safe_usingDict";
    -                UTIL_time_t const clockStart = UTIL_getTime();
    +                TIME_t const timeStart = TIME_getTime();
                     U32 nbLoops;
     
                     for (nbLoops=0; nbLoops < nbDecodeLoops; nbLoops++) {
    @@ -522,22 +535,22 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
                                     decString, blockNb, (unsigned)blockTable[blockNb].srcSize);
                                 if (g_decodeOnly)
                                     DISPLAY("Is input using LZ4 Frame format ? \n");
    -                            END_PROCESS(2, "error during decoding");
    +                            benchError = 1;
                                 break;
                             }
                             blockTable[blockNb].resSize = (size_t)regenSize;
                     }   }
    -                {   U64 const clockSpan = UTIL_clockSpanNano(clockStart);
    -                    if (clockSpan > 0) {
    -                        if (clockSpan < fastestD * nbDecodeLoops)
    -                            fastestD = clockSpan / nbDecodeLoops;
    +                {   Duration_ns const duration_ns = TIME_clockSpan_ns(timeStart);
    +                    if (duration_ns > 0) {
    +                        if (duration_ns < fastestD * nbDecodeLoops)
    +                            fastestD = duration_ns / nbDecodeLoops;
                             assert(fastestD > 0);
                             nbDecodeLoops = (U32)(TIMELOOP_NANOSEC / fastestD) + 1;  /* aim for ~1sec */
                         } else {
                             assert(nbDecodeLoops < 40000000);   /* avoid overflow */
                             nbDecodeLoops *= 100;
                         }
    -                    totalDTime += clockSpan;
    +                    totalDTime += duration_ns;
                         dCompleted = totalDTime > (DECOMP_MULT*maxTime);
                 }   }
     
    @@ -548,11 +561,12 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
                 }
                 markNb = (markNb+1) % NB_MARKS;
                 ratio  = (double)totalRSize / (double)cSize;
    -            DISPLAYLEVEL(2, "%2s-%-17.17s :%10u ->%10u (%5.3f),%6.1f MB/s ,%6.1f MB/s\r",
    +            OUTLEVEL(2, "%2s-%-17.17s :%10u ->%10u (%5.3f),%6.1f MB/s, %6.1f MB/s\r",
                         marks[markNb], displayName,
                         (U32)totalRSize, (U32)cSize, ratio,
    -                    ((double)totalRSize / fastestC) * 1000,
    -                    ((double)totalRSize / fastestD) * 1000);
    +                    ((double)totalRSize / (double)fastestC) * 1000,
    +                    ((double)totalRSize / (double)fastestD) * 1000);
    +            fflush(NULL);
     
                 /* CRC Checking (not possible in decode-only mode)*/
                 if (!g_decodeOnly) {
    @@ -560,6 +574,7 @@ static int BMK_benchMem(const void* srcBuffer, size_t srcSize,
                     if (crcOrig!=crcCheck) {
                         size_t u;
                         DISPLAY("\n!!! WARNING !!! %17s : Invalid Checksum : %x != %x   \n", displayName, (unsigned)crcOrig, (unsigned)crcCheck);
    +                    benchError = 1;
                         for (u=0; u 1) ? mfName : fileNamesTable[0];
    -        BMK_benchCLevel(srcBuffer, benchedSize,
    +        benchError = BMK_benchCLevel(srcBuffer, benchedSize,
                             displayName, cLevel, cLevelLast,
                             fileSizes, nbFiles,
                             dictBuf, dictSize);
    @@ -729,28 +749,35 @@ static void BMK_benchFileTable(const char** fileNamesTable, unsigned nbFiles,
         /* clean up */
         free(srcBuffer);
         free(fileSizes);
    +    return benchError;
     }
     
     
    -static void BMK_syntheticTest(int cLevel, int cLevelLast, double compressibility,
    -                              const char* dictBuf, int dictSize)
    +static int BMK_syntheticTest(int cLevel, int cLevelLast,
    +                             const char* dictBuf, int dictSize)
     {
    -    char name[20] = {0};
    -    size_t benchedSize = 10000000;
    +    int benchError = 0;
    +    size_t const benchedSize = 10000000;
         void* const srcBuffer = malloc(benchedSize);
     
         /* Memory allocation */
         if (!srcBuffer) END_PROCESS(21, "not enough memory");
     
         /* Fill input buffer */
    -    RDG_genBuffer(srcBuffer, benchedSize, compressibility, 0.0, 0);
    +    LOREM_genBuffer(srcBuffer, benchedSize, 0);
     
         /* Bench */
    -    snprintf (name, sizeof(name), "Synthetic %2u%%", (unsigned)(compressibility*100));
    -    BMK_benchCLevel(srcBuffer, benchedSize, name, cLevel, cLevelLast, &benchedSize, 1, dictBuf, dictSize);
    +    benchError = BMK_benchCLevel(srcBuffer, benchedSize,
    +                    "Lorem ipsum",
    +                    cLevel, cLevelLast,
    +                    &benchedSize,
    +                    1,
    +                    dictBuf, dictSize);
     
         /* clean up */
         free(srcBuffer);
    +
    +    return benchError;
     }
     
     
    @@ -759,15 +786,16 @@ BMK_benchFilesSeparately(const char** fileNamesTable, unsigned nbFiles,
                        int cLevel, int cLevelLast,
                        const char* dictBuf, int dictSize)
     {
    +    int benchError = 0;
         unsigned fileNb;
         if (cLevel > LZ4HC_CLEVEL_MAX) cLevel = LZ4HC_CLEVEL_MAX;
         if (cLevelLast > LZ4HC_CLEVEL_MAX) cLevelLast = LZ4HC_CLEVEL_MAX;
         if (cLevelLast < cLevel) cLevelLast = cLevel;
     
         for (fileNb=0; fileNb
    +#include  /* INT_MAX */
    +#include  /* malloc, abort */
    +#include  /* memcpy */
    +
    +/* Define the word pool
    + * Note: all words must have a len <= 16 */
    +static const char* kWords[] = {
    +    "lorem",        "ipsum",      "dolor",       "sit",          "amet",
    +    "consectetur",  "adipiscing", "elit",        "sed",          "do",
    +    "eiusmod",      "tempor",     "incididunt",  "ut",           "labore",
    +    "et",           "dolore",     "magna",       "aliqua",       "dis",
    +    "lectus",       "vestibulum", "mattis",      "ullamcorper",  "velit",
    +    "commodo",      "a",          "lacus",       "arcu",         "magnis",
    +    "parturient",   "montes",     "nascetur",    "ridiculus",    "mus",
    +    "mauris",       "nulla",      "malesuada",   "pellentesque", "eget",
    +    "gravida",      "in",         "dictum",      "non",          "erat",
    +    "nam",          "voluptat",   "maecenas",    "blandit",      "aliquam",
    +    "etiam",        "enim",       "lobortis",    "scelerisque",  "fermentum",
    +    "dui",          "faucibus",   "ornare",      "at",           "elementum",
    +    "eu",           "facilisis",  "odio",        "morbi",        "quis",
    +    "eros",         "donec",      "ac",          "orci",         "purus",
    +    "turpis",       "cursus",     "leo",         "vel",          "porta",
    +    "consequat",    "interdum",   "varius",      "vulputate",    "aliquet",
    +    "pharetra",     "nunc",       "auctor",      "urna",         "id",
    +    "metus",        "viverra",    "nibh",        "cras",         "mi",
    +    "unde",         "omnis",      "iste",        "natus",        "error",
    +    "perspiciatis", "voluptatem", "accusantium", "doloremque",   "laudantium",
    +    "totam",        "rem",        "aperiam",     "eaque",        "ipsa",
    +    "quae",         "ab",         "illo",        "inventore",    "veritatis",
    +    "quasi",        "architecto", "beatae",      "vitae",        "dicta",
    +    "sunt",         "explicabo",  "nemo",        "ipsam",        "quia",
    +    "voluptas",     "aspernatur", "aut",         "odit",         "fugit",
    +    "consequuntur", "magni",      "dolores",     "eos",          "qui",
    +    "ratione",      "sequi",      "nesciunt",    "neque",        "porro",
    +    "quisquam",     "est",        "dolorem",     "adipisci",     "numquam",
    +    "eius",         "modi",       "tempora",     "incidunt",     "magnam",
    +    "quaerat",      "ad",         "minima",      "veniam",       "nostrum",
    +    "ullam",        "corporis",   "suscipit",    "laboriosam",   "nisi",
    +    "aliquid",      "ex",         "ea",          "commodi",      "consequatur",
    +    "autem",        "eum",        "iure",        "voluptate",    "esse",
    +    "quam",         "nihil",      "molestiae",   "illum",        "fugiat",
    +    "quo",          "pariatur",   "vero",        "accusamus",    "iusto",
    +    "dignissimos",  "ducimus",    "blanditiis",  "praesentium",  "voluptatum",
    +    "deleniti",     "atque",      "corrupti",    "quos",         "quas",
    +    "molestias",    "excepturi",  "sint",        "occaecati",    "cupiditate",
    +    "provident",    "similique",  "culpa",       "officia",      "deserunt",
    +    "mollitia",     "animi",      "laborum",     "dolorum",      "fuga",
    +    "harum",        "quidem",     "rerum",       "facilis",      "expedita",
    +    "distinctio",   "libero",     "tempore",     "cum",          "soluta",
    +    "nobis",        "eligendi",   "optio",       "cumque",       "impedit",
    +    "minus",        "quod",       "maxime",      "placeat",      "facere",
    +    "possimus",     "assumenda",  "repellendus", "temporibus",   "quibusdam",
    +    "officiis",     "debitis",    "saepe",       "eveniet",      "voluptates",
    +    "repudiandae",  "recusandae", "itaque",      "earum",        "hic",
    +    "tenetur",      "sapiente",   "delectus",    "reiciendis",   "cillum",
    +    "maiores",      "alias",      "perferendis", "doloribus",    "asperiores",
    +    "repellat",     "minim",      "nostrud",     "exercitation", "ullamco",
    +    "laboris",      "aliquip",    "duis",        "aute",         "irure",
    +};
    +#define KNBWORDS (sizeof(kWords) / sizeof(kWords[0]))
    +static const unsigned kNbWords = KNBWORDS;
    +
    +static const char* g_words[KNBWORDS] = { NULL };
    +static unsigned g_wordLen[KNBWORDS] = {0};
    +static char* g_wordBuffer = NULL;
    +
    +/* simple 1-dimension distribution, based on word's length, favors small words
    + */
    +static const int kWeights[]      = { 0, 8, 6, 4, 3, 2 };
    +static const unsigned kNbWeights = sizeof(kWeights) / sizeof(kWeights[0]);
    +
    +#define DISTRIB_SIZE_MAX 650
    +static int g_distrib[DISTRIB_SIZE_MAX] = { 0 };
    +static unsigned g_distribCount         = 0;
    +
    +static void countFreqs(
    +        const unsigned wordLen[],
    +        size_t nbWords,
    +        const int* weights,
    +        unsigned long nbWeights)
    +{
    +    unsigned total = 0;
    +    size_t w;
    +    for (w = 0; w < nbWords; w++) {
    +        size_t len = wordLen[w];
    +        int lmax;
    +        if (len >= nbWeights)
    +            len = nbWeights - 1;
    +        lmax = weights[len];
    +        total += (unsigned)lmax;
    +    }
    +    g_distribCount = total;
    +    assert(g_distribCount <= DISTRIB_SIZE_MAX);
    +}
    +
    +static void init_word_len(
    +        const char* words[],
    +        size_t nbWords)
    +{
    +    size_t n;
    +    assert(words != NULL);
    +    for (n=0; n= nbWeights)
    +            len = nbWeights - 1;
    +        lmax = weights[len];
    +        for (l = 0; l < lmax; l++) {
    +            g_distrib[d++] = (int)w;
    +        }
    +    }
    +}
    +
    +/* Note: this unit only works when invoked sequentially.
    + * No concurrent access is allowed */
    +static char* g_ptr         = NULL;
    +static size_t g_nbChars    = 0;
    +static size_t g_maxChars   = 10000000;
    +static unsigned g_randRoot = 0;
    +
    +#define RDG_rotl32(x, r) ((x << r) | (x >> (32 - r)))
    +static unsigned LOREM_rand(unsigned range)
    +{
    +    static const unsigned prime1 = 2654435761U;
    +    static const unsigned prime2 = 2246822519U;
    +    unsigned rand32              = g_randRoot;
    +    rand32 *= prime1;
    +    rand32 ^= prime2;
    +    rand32     = RDG_rotl32(rand32, 13);
    +    g_randRoot = rand32;
    +    return (unsigned)(((unsigned long long)rand32 * range) >> 32);
    +}
    +
    +static void writeLastCharacters(void)
    +{
    +    size_t lastChars = g_maxChars - g_nbChars;
    +    assert(g_maxChars >= g_nbChars);
    +    if (lastChars == 0)
    +        return;
    +    g_ptr[g_nbChars++] = '.';
    +    if (lastChars > 2) {
    +        memset(g_ptr + g_nbChars, ' ', lastChars - 2);
    +    }
    +    if (lastChars > 1) {
    +        g_ptr[g_maxChars - 1] = '\n';
    +    }
    +    g_nbChars = g_maxChars;
    +}
    +
    +static void generateLastWord(const char* word, size_t wordLen, int upCase)
    +{
    +    if (g_nbChars + wordLen + 2 > g_maxChars) {
    +        writeLastCharacters();
    +        return;
    +    }
    +    memcpy(g_ptr + g_nbChars, word, wordLen);
    +    if (upCase) {
    +        static const char toUp = 'A' - 'a';
    +        g_ptr[g_nbChars]       = (char)(g_ptr[g_nbChars] + toUp);
    +    }
    +    g_nbChars += wordLen;
    +    writeLastCharacters();
    +}
    +
    +#define MAX(a,b)  ((a)<(b)?(b):(a))
    +static void generateWord(const char* word, size_t wordLen, const char* separator, size_t sepLen, int upCase)
    +{
    +    size_t const wlen = MAX(16, wordLen + 2);
    +    if (g_nbChars + wlen > g_maxChars) {
    +        generateLastWord(word, wordLen, upCase);
    +        return;
    +    }
    +    assert(wordLen <= 16);
    +    memcpy(g_ptr + g_nbChars, word, 16);
    +    if (upCase) {
    +        static const char toUp = 'A' - 'a';
    +        g_ptr[g_nbChars]       = (char)(g_ptr[g_nbChars] + toUp);
    +    }
    +    g_nbChars += wordLen;
    +    assert(sepLen <= 2);
    +    memcpy(g_ptr + g_nbChars, separator, 2);
    +    g_nbChars += sepLen;
    +}
    +
    +static int about(unsigned target)
    +{
    +    return (int)(LOREM_rand(target) + LOREM_rand(target) + 1);
    +}
    +
    +/* Function to generate a random sentence */
    +static void generateSentence(int nbWords)
    +{
    +    int commaPos       = about(9);
    +    int comma2         = commaPos + about(7);
    +    int qmark          = (LOREM_rand(11) == 7);
    +    const char* endSep = qmark ? "? " : ". ";
    +    int i;
    +    for (i = 0; i < nbWords; i++) {
    +        int const wordID       = g_distrib[LOREM_rand(g_distribCount)];
    +        const char* sep        = " ";
    +        size_t sepLen = 1;
    +        if (i == commaPos)
    +            sep = ", ", sepLen=2;
    +        if (i == comma2)
    +            sep = ", ", sepLen=2;
    +        if (i == nbWords - 1)
    +            sep = endSep, sepLen=2;
    +        generateWord(g_words[wordID], g_wordLen[wordID], sep, sepLen, i == 0);
    +    }
    +}
    +
    +static void generateParagraph(int nbSentences)
    +{
    +    int i;
    +    for (i = 0; i < nbSentences; i++) {
    +        int wordsPerSentence = about(11);
    +        generateSentence(wordsPerSentence);
    +    }
    +    if (g_nbChars < g_maxChars) {
    +        g_ptr[g_nbChars++] = '\n';
    +    }
    +    if (g_nbChars < g_maxChars) {
    +        g_ptr[g_nbChars++] = '\n';
    +    }
    +}
    +
    +/* It's "common" for lorem ipsum generators to start with the same first
    + * pre-defined sentence */
    +static void generateFirstSentence(void)
    +{
    +    int i;
    +    for (i = 0; i < 18; i++) {
    +        const char* separator = " ";
    +        size_t sepLen = 1;
    +        if (i == 4)
    +            separator = ", ", sepLen=2;
    +        if (i == 7)
    +            separator = ", ", sepLen=2;
    +        generateWord(g_words[i], g_wordLen[i], separator, sepLen, i == 0);
    +    }
    +    generateWord(g_words[18], g_wordLen[18], ". ", 2, 0);
    +}
    +
    +size_t
    +LOREM_genBlock(void* buffer, size_t size, unsigned seed, int first, int fill)
    +{
    +    g_ptr = (char*)buffer;
    +    assert(size < INT_MAX);
    +    g_maxChars = size;
    +    g_nbChars  = 0;
    +    g_randRoot = seed;
    +    if (g_distribCount == 0) {
    +        init_word_len(kWords, kNbWords);
    +        init_word_buffer();
    +        init_word_distrib(g_wordLen, kNbWords, kWeights, kNbWeights);
    +    }
    +
    +    if (first) {
    +        generateFirstSentence();
    +    }
    +    while (g_nbChars < g_maxChars) {
    +        int sentencePerParagraph = about(7);
    +        generateParagraph(sentencePerParagraph);
    +        if (!fill)
    +            break; /* only generate one paragraph in not-fill mode */
    +    }
    +    g_ptr = NULL;
    +    return g_nbChars;
    +}
    +
    +void LOREM_genBuffer(void* buffer, size_t size, unsigned seed)
    +{
    +    LOREM_genBlock(buffer, size, seed, 1, 1);
    +}
    diff --git a/programs/lorem.h b/programs/lorem.h
    new file mode 100644
    index 0000000000000000000000000000000000000000..4b7bf57f428e301bf8d42ebedf92fe7ee3e770ba
    --- /dev/null
    +++ b/programs/lorem.h
    @@ -0,0 +1,46 @@
    +/*
    +    lorem.h - lorem ipsum generator
    +    Copyright (C) Yann Collet 2024
    +
    +    GPL v2 License
    +
    +    This program is free software; you can redistribute it and/or modify
    +    it under the terms of the GNU General Public License as published by
    +    the Free Software Foundation; either version 2 of the License, or
    +    (at your option) any later version.
    +
    +    This program is distributed in the hope that it will be useful,
    +    but WITHOUT ANY WARRANTY; without even the implied warranty of
    +    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    +    GNU General Public License for more details.
    +
    +    You should have received a copy of the GNU General Public License along
    +    with this program; if not, write to the Free Software Foundation, Inc.,
    +    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
    +
    +    You can contact the author at :
    +   - LZ4 source repository : https://github.com/lz4/lz4
    +   - Public forum : https://groups.google.com/forum/#!forum/lz4c
    +*/
    +
    +
    +#include    /* size_t */
    +
    +/*
    + * LOREM_genBuffer():
    + * Generate @size bytes of compressible data using lorem ipsum generator
    + * into provided @buffer.
    + */
    +void LOREM_genBuffer(void* buffer, size_t size, unsigned seed);
    +
    +/*
    + * LOREM_genBlock():
    + * Similar to LOREM_genBuffer, with additional controls :
    + * - @first : generate the first sentence
    + * - @fill : fill the entire @buffer,
    + *           if ==0: generate one paragraph at most.
    + * @return : nb of bytes generated into @buffer.
    + */
    +size_t LOREM_genBlock(void* buffer, size_t size,
    +                      unsigned seed,
    +                      int first, int fill);
    diff --git a/programs/lz4.1 b/programs/lz4.1
    index 7cb98d639df71b08b00a45f7aab17f5f60c82df0..e9631e8d794e1153413ec0d3b160a91e12aa6867 100644
    --- a/programs/lz4.1
    +++ b/programs/lz4.1
    @@ -1,5 +1,5 @@
     .
    -.TH "LZ4" "1" "August 2022" "lz4 v1.9.4" "User Commands"
    +.TH "LZ4" "1" "July 2024" "lz4 1.10.0" "User Commands"
     .
     .SH "NAME"
     \fBlz4\fR \- lz4, unlz4, lz4cat \- Compress or decompress \.lz4 files
    @@ -17,7 +17,7 @@
     When writing scripts that need to decompress files, it is recommended to always use the name \fBlz4\fR with appropriate arguments (\fBlz4 \-d\fR or \fBlz4 \-dc\fR) instead of the names \fBunlz4\fR and \fBlz4cat\fR\.
     .
     .SH "DESCRIPTION"
    -\fBlz4\fR is an extremely fast lossless compression algorithm, based on \fBbyte\-aligned LZ77\fR family of compression scheme\. \fBlz4\fR offers compression speeds > 500 MB/s per core, linearly scalable with multi\-core CPUs\. It features an extremely fast decoder, offering speed in multiple GB/s per core, typically reaching RAM speed limit on multi\-core systems\. The native file format is the \fB\.lz4\fR format\.
    +\fBlz4\fR is a CLI based on \fBliblz4\fR, an extremely fast implementation of lossless compression algorithm\. It provides a default compression speed of typically > 500 MB/s per core\. Speed can traded for higher compression ratio, by increasing the compression level parameter\. While decompression is single\-threaded, it reaches multiple GB/s, generally fast enough to be I/O bound\. \fBlz4\fR native file format is the \fB\.lz4\fR format\.
     .
     .SS "Difference between lz4 and gzip"
     \fBlz4\fR supports a command line syntax similar \fIbut not identical\fR to \fBgzip(1)\fR\. Differences are :
    @@ -58,7 +58,7 @@ Similarly, \fBlz4 \-m \-d\fR can decompress multiple \fB*\.lz4\fR files\.
     It\'s possible to opt\-in to erase source files on successful compression or decompression, using \fB\-\-rm\fR command\.
     .
     .IP "\(bu" 4
    -Consequently, \fBlz4 \-m \-\-rm\fR behaves the same as \fBgzip\fR\.
    +Consequently, \fBlz4 \-m \-\-rm\fR features a behavior closer to the \fBgzip\fR one\.
     .
     .IP "" 0
     .
    @@ -107,7 +107,7 @@ Benchmark mode, using \fB#\fR compression level\.
     .
     .TP
     \fB\-\-list\fR
    -List information about \.lz4 files\. note : current implementation is limited to single\-frame \.lz4 files\.
    +List information about \.lz4 files\. For detailed information on files with multiple frames, use \fB\-v\fR\. \fB\-\-list\fR automatically triggers \fB\-m\fR modifier\.
     .
     .SS "Operation modifiers"
     .
    @@ -124,6 +124,10 @@ Switch to ultra\-fast compression levels\. The higher the value, the faster the
     Set highest compression level\. Same as \-12\.
     .
     .TP
    +\fB\-T#\fR, \fB\-\-threads=#\fR
    +Use \fB#\fR threads for compression\. When \fB0\fR, or none provided: automatically determined from nb of detected cores\.
    +.
    +.TP
     \fB\-\-favor\-decSpeed\fR
     Generate compressed data optimized for decompression speed\. Compressed data will be larger as a consequence (typically by ~0\.5%), while decompression speed will be improved by 5\-20%, depending on use cases\. This option only works in combination with very high compression levels (>=10)\.
     .
    @@ -242,6 +246,17 @@ Benchmark multiple compression levels, from b# to e# (included)
     \fB\-i#\fR
     Minimum evaluation time in seconds [1\-9] (default : 3)
     .
    +.SS "Environment Variables"
    +It\'s possible to pass some parameters to \fBlz4\fR via environment variables\. This can be useful in situations where \fBlz4\fR is known to be invoked (from a script for example) but there is no way to pass \fBlz4\fR parameters to influence the compression session\. The environment variable has higher priority than executable default, but lower priority than corresponding runtime command\. When set as global environment variables, it can be a way to enforce personalized defaults different from the executable set ones\.
    +.
    +.TP
    +\fBLZ4_CLEVEL\fR
    +specify a default compression level that \fBlz4\fR employs for compression when no other compression level is specified on command line\. Executable default is generally \fB1\fR\.
    +.
    +.TP
    +\fBLZ4_NBWORKERS\fR
    +specify a default number of threads that \fBlz4\fR will employ for compression\. Executable default is generally \fB0\fR, which means auto\-determined based on local cpu\. This functionality is only relevant when \fBlz4\fR is compiled with multithreading support\. The maximum number of workers is capped at \fBLZ4_NBWORKERS_MAX\fR (\fB200\fR by default)\.
    +.
     .SH "BUGS"
     Report bugs at: https://github\.com/lz4/lz4/issues
     .
    diff --git a/programs/lz4.1.md b/programs/lz4.1.md
    index 06c06cf0fa42f431174afbe1ca383be17efd1b4e..553cabc353816911b94afce6e672402e1c4f543f 100644
    --- a/programs/lz4.1.md
    +++ b/programs/lz4.1.md
    @@ -18,13 +18,11 @@ it is recommended to always use the name `lz4` with appropriate arguments
     DESCRIPTION
     -----------
     
    -`lz4` is an extremely fast lossless compression algorithm,
    -based on **byte-aligned LZ77** family of compression scheme.
    -`lz4` offers compression speeds > 500 MB/s per core,
    -linearly scalable with multi-core CPUs.
    -It features an extremely fast decoder, offering speed in multiple GB/s per core,
    -typically reaching RAM speed limit on multi-core systems.
    -The native file format is the `.lz4` format.
    +`lz4` is a CLI based on `liblz4`, an extremely fast implementation of lossless compression algorithm.
    +It provides a default compression speed of typically > 500 MB/s per core.
    +Speed can traded for higher compression ratio, by increasing the compression level parameter.
    +While decompression is single-threaded, it reaches multiple GB/s, generally fast enough to be I/O bound.
    +`lz4` native file format is the `.lz4` format.
     
     ### Difference between lz4 and gzip
     
    @@ -59,7 +57,7 @@ Default behaviors can be modified by opt-in commands, detailed below.
       * Similarly, `lz4 -m -d` can decompress multiple `*.lz4` files.
       * It's possible to opt-in to erase source files
         on successful compression or decompression, using `--rm` command.
    -  * Consequently, `lz4 -m --rm` behaves the same as `gzip`.
    +  * Consequently, `lz4 -m --rm` features a behavior closer to the `gzip` one.
     
     ### Concatenation of .lz4 files
     
    @@ -115,7 +113,8 @@ only the latest one will be applied.
     
     * `--list`:
       List information about .lz4 files.
    -  note : current implementation is limited to single-frame .lz4 files.
    +  For detailed information on files with multiple frames, use `-v`.
    +  `--list` automatically triggers `-m` modifier.
     
     ### Operation modifiers
     
    @@ -138,6 +137,10 @@ only the latest one will be applied.
     * `--best`:
       Set highest compression level. Same as -12.
     
    +* `-T#`, `--threads=#`:
    +  Use `#` threads for compression.
    +  When `0`, or none provided: automatically determined from nb of detected cores.
    +
     * `--favor-decSpeed`:
       Generate compressed data optimized for decompression speed.
       Compressed data will be larger as a consequence (typically by ~0.5%),
    @@ -244,6 +247,20 @@ only the latest one will be applied.
       Minimum evaluation time in seconds \[1-9\] (default : 3)
     
     
    +### Environment Variables
    +
    +It's possible to pass some parameters to `lz4` via environment variables.
    +This can be useful in situations where `lz4` is known to be invoked (from a script for example) but there is no way to pass `lz4` parameters to influence the compression session.
    +The environment variable has higher priority than executable default, but lower priority than corresponding runtime command.
    +When set as global environment variables, it can be a way to enforce personalized defaults different from the executable set ones.
    +
    +* `LZ4_CLEVEL`:
    +  specify a default compression level that `lz4` employs for compression when no other compression level is specified on command line. Executable default is generally `1`.
    +
    +* `LZ4_NBWORKERS`:
    +  specify a default number of threads that `lz4` will employ for compression. Executable default is generally `0`, which means auto-determined based on local cpu. This functionality is only relevant when `lz4` is compiled with multithreading support. The maximum number of workers is capped at `LZ4_NBWORKERS_MAX` (`200` by default).
    +
    +
     BUGS
     ----
     
    diff --git a/programs/lz4cli.c b/programs/lz4cli.c
    index 8c3f9fd93492abb53b2cae9c5547968ff3e8d3f2..ccba8f1850ee31941972a1af6bb605a0d0008ff4 100644
    --- a/programs/lz4cli.c
    +++ b/programs/lz4cli.c
    @@ -1,6 +1,6 @@
     /*
       LZ4cli - LZ4 Command Line Interface
    -  Copyright (C) Yann Collet 2011-2020
    +  Copyright (C) Yann Collet 2011-2023
     
       GPL v2 License
     
    @@ -31,6 +31,14 @@
     */
     
     
    +/*-************************************
    +*  Compiler options
    +**************************************/
    +#ifdef _MSC_VER    /* Visual Studio */
    +#  pragma warning(disable : 4127)    /* disable: C4127: conditional expression is constant */
    +#endif
    +
    +
     /****************************
     *  Includes
     *****************************/
    @@ -39,6 +47,7 @@
     #include     /* fprintf, getchar */
     #include    /* exit, calloc, free */
     #include    /* strcmp, strlen */
    +#include "lz4conf.h"  /* compile-time constants */
     #include "bench.h"    /* BMK_benchFile, BMK_SetNbIterations, BMK_SetBlocksize, BMK_SetPause */
     #include "lz4io.h"    /* LZ4IO_compressFilename, LZ4IO_decompressFilename, LZ4IO_compressMultipleFilenames */
     #include "lz4hc.h"    /* LZ4HC_CLEVEL_MAX */
    @@ -48,9 +57,14 @@
     /*****************************
     *  Constants
     ******************************/
    -#define COMPRESSOR_NAME "LZ4 command line interface"
    +#if LZ4IO_MULTITHREAD
    +# define IO_MT "multithread"
    +#else
    +# define IO_MT "single-thread"
    +#endif
    +#define COMPRESSOR_NAME "lz4"
     #define AUTHOR "Yann Collet"
    -#define WELCOME_MESSAGE "*** %s %i-bits v%s, by %s ***\n", COMPRESSOR_NAME, (int)(sizeof(void*)*8), LZ4_versionString(), AUTHOR
    +#define WELCOME_MESSAGE "*** %s v%s %i-bit %s, by %s ***\n", COMPRESSOR_NAME, LZ4_versionString(), (int)(sizeof(void*)*8), IO_MT, AUTHOR
     #define LZ4_EXTENSION ".lz4"
     #define LZ4CAT "lz4cat"
     #define UNLZ4 "unlz4"
    @@ -61,30 +75,35 @@ static int g_lz4c_legacy_commands = 0;
     #define MB *(1U<<20)
     #define GB *(1U<<30)
     
    -#define LZ4_BLOCKSIZEID_DEFAULT 7
    -
     
     /*-************************************
     *  Macros
     ***************************************/
     #define DISPLAYOUT(...)        fprintf(stdout, __VA_ARGS__)
     #define DISPLAY(...)           fprintf(stderr, __VA_ARGS__)
    -#define DISPLAYLEVEL(l, ...)   if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }
    +#define DISPLAYLEVEL(l, ...)   do { if (displayLevel>=l) DISPLAY(__VA_ARGS__); } while (0)
     static unsigned displayLevel = 2;   /* 0 : no display ; 1: errors only ; 2 : downgradable normal ; 3 : non-downgradable normal; 4 : + information */
     
     
     /*-************************************
    -*  Exceptions
    +*  Errors and Messages
     ***************************************/
    -#define DEBUG 0
    -#define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__);
    -#define EXM_THROW(error, ...)                                             \
    -{                                                                         \
    -    DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \
    -    DISPLAYLEVEL(1, "Error %i : ", error);                                \
    -    DISPLAYLEVEL(1, __VA_ARGS__);                                         \
    -    DISPLAYLEVEL(1, "\n");                                                \
    -    exit(error);                                                          \
    +#ifndef DEBUG
    +#  define DEBUG 0
    +#endif
    +#define DEBUGOUTPUT(...) do { if (DEBUG) DISPLAY(__VA_ARGS__); } while (0)
    +#define END_PROCESS(error, ...)                                   \
    +do {                                                              \
    +    DEBUGOUTPUT("Error in %s, line %i : \n", __FILE__, __LINE__); \
    +    DISPLAYLEVEL(1, "Error %i : ", error);                        \
    +    DISPLAYLEVEL(1, __VA_ARGS__);                                 \
    +    DISPLAYLEVEL(1, "\n");                                        \
    +    exit(error);                                                  \
    +} while (0)
    +
    +static void errorOut(const char* msg)
    +{
    +    DISPLAYLEVEL(1, "%s \n", msg); exit(1);
     }
     
     
    @@ -110,11 +129,10 @@ static int usage(const char* exeName)
         DISPLAY( "input   : a filename \n");
         DISPLAY( "          with no FILE, or when FILE is - or %s, read standard input\n", stdinmark);
         DISPLAY( "Arguments : \n");
    -    DISPLAY( " -1     : Fast compression (default) \n");
    -    DISPLAY( " -9     : High compression \n");
    +    DISPLAY( " -1     : fast compression (default) \n");
    +    DISPLAY( " -%2d    : slowest compression level \n", LZ4HC_CLEVEL_MAX);
    +    DISPLAY( " -T#    : use # threads for compression (default:%i==auto) \n", LZ4_NBWORKERS_DEFAULT);
         DISPLAY( " -d     : decompression (default for %s extension)\n", LZ4_EXTENSION);
    -    DISPLAY( " -z     : force compression \n");
    -    DISPLAY( " -D FILE: use FILE as dictionary \n");
         DISPLAY( " -f     : overwrite output without prompting \n");
         DISPLAY( " -k     : preserve source files(s)  (default) \n");
         DISPLAY( "--rm    : remove source file(s) after successful de/compression \n");
    @@ -138,8 +156,10 @@ static int usage_advanced(const char* exeName)
         DISPLAY( " -r     : operate recursively on directories (sets also -m) \n");
     #endif
         DISPLAY( " -l     : compress using Legacy format (Linux kernel compression)\n");
    +    DISPLAY( " -z     : force compression \n");
    +    DISPLAY( " -D FILE: use FILE as dictionary (compression & decompression)\n");
         DISPLAY( " -B#    : cut file into blocks of size # bytes [32+] \n");
    -    DISPLAY( "                     or predefined block size [4-7] (default: 7) \n");
    +    DISPLAY( "                     or predefined block size [4-7] (default: %i) \n", LZ4_BLOCKSIZEID_DEFAULT);
         DISPLAY( " -BI    : Block Independence (default) \n");
         DISPLAY( " -BD    : Block dependency (improves compression ratio) \n");
         DISPLAY( " -BX    : enable block checksum (default:disabled) \n");
    @@ -279,6 +299,34 @@ static unsigned readU32FromChar(const char** stringPtr)
         return result;
     }
     
    +#define CLEAN_RETURN(i) { operationResult = (i); goto _cleanup; }
    +
    +#define NEXT_FIELD(ptr) {         \
    +    if (*argument == '=') {       \
    +        ptr = ++argument;         \
    +        argument += strlen(ptr);  \
    +    } else {                      \
    +        argNb++;                  \
    +        if (argNb >= argCount) {  \
    +            DISPLAYLEVEL(1, "error: missing command argument \n"); \
    +            CLEAN_RETURN(1);      \
    +        }                         \
    +        ptr = argv[argNb];        \
    +        assert(ptr != NULL);      \
    +        if (ptr[0]=='-') {        \
    +            DISPLAYLEVEL(1, "error: command cannot be separated from its argument by another command \n"); \
    +            CLEAN_RETURN(1);      \
    +}   }   }
    +
    +#define NEXT_UINT32(val32) {      \
    +    const char* __nb;             \
    +    NEXT_FIELD(__nb);             \
    +    val32 = readU32FromChar(&__nb); \
    +    if(*__nb != 0) {              \
    +        errorOut("error: only numeric values with optional suffixes K, KB, KiB, M, MB, MiB are allowed"); \
    +    }                             \
    +}
    +
     /** longCommandWArg() :
      *  check if *stringPtr is the same as longCommand.
      *  If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
    @@ -307,10 +355,40 @@ static operationMode_e determineOpMode(const char* inputFilename)
         else return om_compress;
     }
     
    -int main(int argc, const char** argv)
    +#define ENV_NBTHREADS "LZ4_NBWORKERS"
    +
    +static unsigned init_nbWorkers(void)
    +{
    +    const char* const env = getenv(ENV_NBTHREADS);
    +    if (env != NULL) {
    +        const char* ptr = env;
    +        if ((*ptr>='0') && (*ptr<='9')) {
    +            return readU32FromChar(&ptr);
    +        }
    +        DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: not a valid unsigned value \n", ENV_NBTHREADS, env);
    +    }
    +    return LZ4_NBWORKERS_DEFAULT;
    +}
    +
    +#define ENV_CLEVEL "LZ4_CLEVEL"
    +
    +static int init_cLevel(void)
    +{
    +    const char* const env = getenv(ENV_CLEVEL);
    +    if (env != NULL) {
    +        const char* ptr = env;
    +        if ((*ptr>='0') && (*ptr<='9')) {
    +            return (int)readU32FromChar(&ptr);
    +        }
    +        DISPLAYLEVEL(2, "Ignore environment variable setting %s=%s: not a valid unsigned value \n", ENV_CLEVEL, env);
    +    }
    +    return LZ4_CLEVEL_DEFAULT;
    +}
    +
    +int main(int argCount, const char** argv)
     {
    -    int i,
    -        cLevel=1,
    +    int argNb,
    +        cLevel=init_cLevel(),
             cLevelLast=-10000,
             legacy_format=0,
             forceStdout=0,
    @@ -319,12 +397,13 @@ int main(int argc, const char** argv)
             multiple_inputs=0,
             all_arguments_are_files=0,
             operationResult=0;
    +    unsigned nbWorkers = init_nbWorkers();
         operationMode_e mode = om_auto;
         const char* input_filename = NULL;
         const char* output_filename= NULL;
         const char* dictionary_filename = NULL;
         char* dynNameSpace = NULL;
    -    const char** inFileNames = (const char**)calloc((size_t)argc, sizeof(char*));
    +    const char** inFileNames = (const char**)calloc((size_t)argCount, sizeof(char*));
         unsigned ifnIdx=0;
         LZ4IO_prefs_t* const prefs = LZ4IO_defaultPreferences();
         const char nullOutput[] = NULL_OUTPUT;
    @@ -339,7 +418,8 @@ int main(int argc, const char** argv)
         /* Init */
         if (inFileNames==NULL) {
             DISPLAY("Allocation error : not enough memory \n");
    -        return 1;
    +        operationResult = 1;
    +        goto _cleanup;
         }
         inFileNames[0] = stdinmark;
         LZ4IO_setOverwrite(prefs, 0);
    @@ -359,8 +439,8 @@ int main(int argc, const char** argv)
         if (exeNameMatch(exeName, LZ4_LEGACY)) { g_lz4c_legacy_commands=1; }
     
         /* command switches */
    -    for(i=1; i 1) {
    +        DISPLAYLEVEL(2, "warning: this executable doesn't support multithreading \n");
    +    }
    +#endif
    +    if ((mode == om_compress) || (mode == om_bench)) {
             DISPLAYLEVEL(4, "Blocks size : %u KB\n", (U32)(blockSize>>10));
    +    }
     
         if (multiple_inputs) {
             input_filename = inFileNames[0];
    @@ -676,16 +775,7 @@ int main(int argc, const char** argv)
         }
     
         /* No output filename ==> try to select one automatically (when possible) */
    -    while ((!output_filename) && (multiple_inputs==0)) {
    -        if (!IS_CONSOLE(stdout) && mode != om_list) {
    -            /* Default to stdout whenever stdout is not the console.
    -             * Note : this policy may change in the future, therefore don't rely on it !
    -             * To ensure `stdout` is explicitly selected, use `-c` command flag.
    -             * Conversely, to ensure output will not become `stdout`, use `-m` command flag */
    -            DISPLAYLEVEL(1, "Warning : using stdout as default output. Do not rely on this behavior: use explicit `-c` instead ! \n");
    -            output_filename = stdoutmark;
    -            break;
    -        }
    +    if ((!output_filename) && (multiple_inputs==0)) {
             if (mode == om_auto) {  /* auto-determine compression or decompression, based on file extension */
                 mode = determineOpMode(input_filename);
             }
    @@ -697,9 +787,9 @@ int main(int argc, const char** argv)
                 strcat(dynNameSpace, LZ4_EXTENSION);
                 output_filename = dynNameSpace;
                 DISPLAYLEVEL(2, "Compressed filename will be : %s \n", output_filename);
    -            break;
             }
    -        if (mode == om_decompress) {/* decompress to file (automatic output name only works if input filename has correct format extension) */
    +        if (mode == om_decompress) {
    +            /* decompress to file (automatic output name only works if input filename has correct format extension) */
                 size_t outl;
                 size_t const inl = strlen(input_filename);
                 dynNameSpace = (char*)calloc(1,inl+1);
    @@ -712,7 +802,6 @@ int main(int argc, const char** argv)
                 output_filename = dynNameSpace;
                 DISPLAYLEVEL(2, "Decoding file %s \n", output_filename);
             }
    -        break;
         }
     
         if (mode == om_list) {
    @@ -757,13 +846,27 @@ int main(int argc, const char** argv)
         } else if (mode == om_list){
             operationResult = LZ4IO_displayCompressedFilesInfo(inFileNames, ifnIdx);
         } else {   /* compression is default action */
    +#if LZ4IO_MULTITHREAD
    +        if (nbWorkers != 1) {
    +            if (nbWorkers==0)
    +                nbWorkers = (unsigned)LZ4IO_defaultNbWorkers();
    +            if (nbWorkers > LZ4_NBWORKERS_MAX) {
    +                DISPLAYLEVEL(3, "Requested %u threads too large => automatically reduced to %u \n",
    +                            nbWorkers, LZ4_NBWORKERS_MAX);
    +                nbWorkers = LZ4_NBWORKERS_MAX;
    +            } else {
    +                DISPLAYLEVEL(3, "Using %u threads for compression \n", nbWorkers);
    +            }
    +        }
    +        LZ4IO_setNbWorkers(prefs, (int)nbWorkers);
    +#endif
             if (legacy_format) {
                 DISPLAYLEVEL(3, "! Generating LZ4 Legacy format (deprecated) ! \n");
                 if(multiple_inputs){
                     const char* const leg_extension = !strcmp(output_filename,stdoutmark) ? stdoutmark : LZ4_EXTENSION;
    -                LZ4IO_compressMultipleFilenames_Legacy(inFileNames, (int)ifnIdx, leg_extension, cLevel, prefs);
    +                operationResult = LZ4IO_compressMultipleFilenames_Legacy(inFileNames, (int)ifnIdx, leg_extension, cLevel, prefs);
                 } else {
    -                LZ4IO_compressFilename_Legacy(input_filename, output_filename, cLevel, prefs);
    +                operationResult = LZ4IO_compressFilename_Legacy(input_filename, output_filename, cLevel, prefs);
                 }
             } else {
                 if (multiple_inputs) {
    diff --git a/programs/lz4conf.h b/programs/lz4conf.h
    new file mode 100644
    index 0000000000000000000000000000000000000000..93e09ae37a5cd64ba78a6761525ab2ba453d02f0
    --- /dev/null
    +++ b/programs/lz4conf.h
    @@ -0,0 +1,71 @@
    +/*
    +  LZ4conf.h - compile-time parameters
    +  Copyright (C) Yann Collet 2011-2024
    +  GPL v2 License
    +
    +  This program is free software; you can redistribute it and/or modify
    +  it under the terms of the GNU General Public License as published by
    +  the Free Software Foundation; either version 2 of the License, or
    +  (at your option) any later version.
    +
    +  This program is distributed in the hope that it will be useful,
    +  but WITHOUT ANY WARRANTY; without even the implied warranty of
    +  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    +  GNU General Public License for more details.
    +
    +  You should have received a copy of the GNU General Public License along
    +  with this program; if not, write to the Free Software Foundation, Inc.,
    +  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
    +
    +  You can contact the author at :
    +  - LZ4 source repository : https://github.com/lz4/lz4
    +  - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
    +*/
    +
    +#ifndef LZ4CONF_H_32432
    +#define LZ4CONF_H_32432
    +
    +
    +/* Default compression level.
    + * Can be overridden by environment variable LZ4_CLEVEL.
    + * Can be overridden at runtime using -# command */
    +#ifndef LZ4_CLEVEL_DEFAULT
    +# define LZ4_CLEVEL_DEFAULT 1
    +#endif
    +
    +/* Determines if multithreading is enabled or not
    + * Default: disabled */
    +#ifndef LZ4IO_MULTITHREAD
    +# ifdef _WIN32
    +    /* Windows support Completion Ports */
    +#   define LZ4IO_MULTITHREAD 1
    +# else
    +    /* Requires  support.
    +     * Can't be reliably and portably tested at source code level */
    +#   define LZ4IO_MULTITHREAD 0
    +# endif
    +#endif
    +
    +/* Determines default nb of threads for compression
    + * Default value is 0, which means "auto" :
    + * nb of threads is determined from detected local cpu.
    + * Can be overriden by Environment Variable LZ4_NBWORKERS.
    + * Can be overridden at runtime using -T# command */
    +#ifndef LZ4_NBWORKERS_DEFAULT
    +# define LZ4_NBWORKERS_DEFAULT 0
    +#endif
    +
    +/* Maximum nb of compression threads selectable at runtime */
    +#ifndef LZ4_NBWORKERS_MAX
    +# define LZ4_NBWORKERS_MAX 200
    +#endif
    +
    +/* Determines default lz4 block size when none provided.
    + * Default value is 7, which represents 4 MB.
    + * Can be overridden at runtime using -B# command */
    +#ifndef LZ4_BLOCKSIZEID_DEFAULT
    +# define LZ4_BLOCKSIZEID_DEFAULT 7
    +#endif
    +
    +
    +#endif  /* LZ4CONF_H_32432 */
    diff --git a/programs/lz4io.c b/programs/lz4io.c
    index 8b70b916887b960f6d9347a0ee87a767e2084229..17274e2b0921fa7e76161437688d8f013cbf6651 100644
    --- a/programs/lz4io.c
    +++ b/programs/lz4io.c
    @@ -1,6 +1,6 @@
     /*
       LZ4io.c - LZ4 File/Stream Interface
    -  Copyright (C) Yann Collet 2011-2020
    +  Copyright (C) Yann Collet 2011-2024
     
       GPL v2 License
     
    @@ -46,18 +46,21 @@
     *  Includes
     *****************************/
     #include "platform.h"  /* Large File Support, SET_BINARY_MODE, SET_SPARSE_FILE_MODE, PLATFORM_POSIX_VERSION, __64BIT__ */
    +#include "timefn.h"    /* TIME_ */
     #include "util.h"      /* UTIL_getFileStat, UTIL_setFileStat */
     #include      /* fprintf, fopen, fread, stdin, stdout, fflush, getchar */
     #include     /* malloc, free */
     #include     /* strerror, strcmp, strlen */
    -#include       /* clock */
    +#include       /* clock_t, for cpu-time */
     #include  /* stat64 */
     #include   /* stat64 */
    -#include "lz4.h"       /* still required for legacy format */
    -#include "lz4hc.h"     /* still required for legacy format */
    -#define LZ4F_STATIC_LINKING_ONLY
    -#include "lz4frame.h"
    +#include "lz4conf.h"   /* compile-time constants */
     #include "lz4io.h"
    +#include "lz4.h"       /* required for legacy format */
    +#include "lz4hc.h"     /* required for legacy format */
    +#define LZ4F_STATIC_LINKING_ONLY
    +#include "lz4frame.h"  /* LZ4F_* */
    +#include "xxhash.h"    /* frame checksum (MT mode) */
     
     
     /*****************************
    @@ -85,27 +88,57 @@
     #define LZ4IO_BLOCKSIZEID_DEFAULT 7
     #define LZ4_MAX_DICT_SIZE (64 KB)
     
    +#undef MIN
    +#define MIN(a,b)  ((a)<(b)?(a):(b))
     
     /**************************************
    -*  Macros
    +*  Time and Display
     **************************************/
     #define DISPLAY(...)         fprintf(stderr, __VA_ARGS__)
     #define DISPLAYOUT(...)      fprintf(stdout, __VA_ARGS__)
    -#define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); }
    +#define DISPLAYLEVEL(l, ...) if (g_displayLevel>=l) { DISPLAY(__VA_ARGS__); if (g_displayLevel>=4) fflush(stderr); }
     static int g_displayLevel = 0;   /* 0 : no display  ; 1: errors  ; 2 : + result + interaction + warnings ; 3 : + progression; 4 : + information */
     
     #define DISPLAYUPDATE(l, ...) if (g_displayLevel>=l) { \
    -            if ( ((clock() - g_time) > refreshRate)    \
    +            if ( (TIME_clockSpan_ns(g_time) > refreshRate)  \
                   || (g_displayLevel>=4) ) {               \
    -                g_time = clock();                      \
    +                g_time = TIME_getTime();               \
                     DISPLAY(__VA_ARGS__);                  \
                     if (g_displayLevel>=4) fflush(stderr); \
             }   }
    -static const clock_t refreshRate = CLOCKS_PER_SEC / 6;
    -static clock_t g_time = 0;
    +static const Duration_ns refreshRate = 200000000;
    +static TIME_t g_time = { 0 };
     
    -#define LZ4IO_STATIC_ASSERT(c)   { enum { LZ4IO_static_assert = 1/(int)(!!(c)) }; }   /* use after variable declarations */
    +static double cpuLoad_sec(clock_t cpuStart)
    +{
    +#ifdef _WIN32
    +    FILETIME creationTime, exitTime, kernelTime, userTime;
    +    (void)cpuStart;
    +    GetProcessTimes(GetCurrentProcess(), &creationTime, &exitTime, &kernelTime, &userTime);
    +    assert(kernelTime.dwHighDateTime == 0);
    +    assert(userTime.dwHighDateTime == 0);
    +    return ((double)kernelTime.dwLowDateTime + (double)userTime.dwLowDateTime) * 100. / 1000000000.;
    +#else
    +    return (double)(clock() - cpuStart) / CLOCKS_PER_SEC;
    +#endif
    +}
     
    +static void LZ4IO_finalTimeDisplay(TIME_t timeStart, clock_t cpuStart, unsigned long long size)
    +{
    +#if LZ4IO_MULTITHREAD
    +    if (!TIME_support_MT_measurements()) {
    +        DISPLAYLEVEL(5, "time measurements not compatible with multithreading \n");
    +    } else
    +#endif
    +    {
    +        Duration_ns duration_ns = TIME_clockSpan_ns(timeStart);
    +        double const seconds = (double)(duration_ns + !duration_ns) / (double)1000000000.;
    +        double const cpuLoad_s = cpuLoad_sec(cpuStart);
    +        DISPLAYLEVEL(3,"Done in %.2f s ==> %.2f MiB/s  (cpu load : %.0f%%)\n", seconds,
    +                        (double)size / seconds / 1024. / 1024.,
    +                        (cpuLoad_s / seconds) * 100.);
    +    }
    +}
     
     /**************************************
     *  Exceptions
    @@ -114,15 +147,34 @@ static clock_t g_time = 0;
     #  define DEBUG 0
     #endif
     #define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__);
    -#define END_PROCESS(error, ...)                                           \
    -{                                                                         \
    -    DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \
    -    DISPLAYLEVEL(1, "Error %i : ", error);                                \
    -    DISPLAYLEVEL(1, __VA_ARGS__);                                         \
    -    DISPLAYLEVEL(1, " \n");                                               \
    -    exit(error);                                                          \
    +#define END_PROCESS(error, ...)                                   \
    +{                                                                 \
    +    DEBUGOUTPUT("Error in %s, line %i : \n", __FILE__, __LINE__); \
    +    DISPLAYLEVEL(1, "Error %i : ", error);                        \
    +    DISPLAYLEVEL(1, __VA_ARGS__);                                 \
    +    DISPLAYLEVEL(1, " \n");                                       \
    +    fflush(NULL);                                                 \
    +    exit(error);                                                  \
     }
     
    +#define LZ4IO_STATIC_ASSERT(c)   { enum { LZ4IO_static_assert = 1/(int)(!!(c)) }; }   /* use after variable declarations */
    +
    +
    +/* ************************************************** */
    +/* ****************** Init functions ******************** */
    +/* ************************************************** */
    +
    +int LZ4IO_defaultNbWorkers(void)
    +{
    +#if LZ4IO_MULTITHREAD
    +    int const nbCores = UTIL_countCores();
    +    int const spared = 1 + ((unsigned)nbCores >> 3);
    +    if (nbCores <= spared) return 1;
    +    return nbCores - spared;
    +#else
    +    return 1;
    +#endif
    +}
     
     /* ************************************************** */
     /* ****************** Parameters ******************** */
    @@ -143,34 +195,43 @@ struct LZ4IO_prefs_s {
         unsigned favorDecSpeed;
         const char* dictionaryFilename;
         int removeSrcFile;
    +    int nbWorkers;
     };
     
    -LZ4IO_prefs_t* LZ4IO_defaultPreferences(void)
    +void LZ4IO_freePreferences(LZ4IO_prefs_t* prefs)
     {
    -    LZ4IO_prefs_t* const ret = (LZ4IO_prefs_t*)malloc(sizeof(*ret));
    -    if (!ret) END_PROCESS(21, "Allocation error : not enough memory");
    -    ret->passThrough = 0;
    -    ret->overwrite = 1;
    -    ret->testMode = 0;
    -    ret->blockSizeId = LZ4IO_BLOCKSIZEID_DEFAULT;
    -    ret->blockSize = 0;
    -    ret->blockChecksum = 0;
    -    ret->streamChecksum = 1;
    -    ret->blockIndependence = 1;
    -    ret->sparseFileSupport = 1;
    -    ret->contentSizeFlag = 0;
    -    ret->useDictionary = 0;
    -    ret->favorDecSpeed = 0;
    -    ret->dictionaryFilename = NULL;
    -    ret->removeSrcFile = 0;
    -    return ret;
    +    free(prefs);
     }
     
    -void LZ4IO_freePreferences(LZ4IO_prefs_t* prefs)
    +LZ4IO_prefs_t* LZ4IO_defaultPreferences(void)
     {
    -    free(prefs);
    +    LZ4IO_prefs_t* const prefs = (LZ4IO_prefs_t*)malloc(sizeof(*prefs));
    +    if (!prefs) END_PROCESS(11, "Can't even allocate LZ4IO preferences");
    +    prefs->passThrough = 0;
    +    prefs->overwrite = 1;
    +    prefs->testMode = 0;
    +    prefs->blockSizeId = LZ4IO_BLOCKSIZEID_DEFAULT;
    +    prefs->blockSize = 0;
    +    prefs->blockChecksum = 0;
    +    prefs->streamChecksum = 1;
    +    prefs->blockIndependence = 1;
    +    prefs->sparseFileSupport = 1;
    +    prefs->contentSizeFlag = 0;
    +    prefs->useDictionary = 0;
    +    prefs->favorDecSpeed = 0;
    +    prefs->dictionaryFilename = NULL;
    +    prefs->removeSrcFile = 0;
    +    prefs->nbWorkers = LZ4IO_defaultNbWorkers();
    +    return prefs;
     }
     
    +int LZ4IO_setNbWorkers(LZ4IO_prefs_t* const prefs, int nbWorkers)
    +{
    +    if (nbWorkers < 1 ) nbWorkers = 1;
    +    nbWorkers = MIN(nbWorkers, LZ4_NBWORKERS_MAX);
    +    prefs->nbWorkers = nbWorkers;
    +    return nbWorkers;
    +}
     
     int LZ4IO_setDictionaryFilename(LZ4IO_prefs_t* const prefs, const char* dictionaryFilename)
     {
    @@ -186,7 +247,6 @@ int LZ4IO_setPassThrough(LZ4IO_prefs_t* const prefs, int yes)
        return prefs->passThrough;
     }
     
    -
     /* Default setting : overwrite = 1; return : overwrite mode (0/1) */
     int LZ4IO_setOverwrite(LZ4IO_prefs_t* const prefs, int yes)
     {
    @@ -284,7 +344,6 @@ void LZ4IO_setRemoveSrcFile(LZ4IO_prefs_t* const prefs, unsigned flag)
     }
     
     
    -
     /* ************************************************************************ **
     ** ********************** String functions ********************* **
     ** ************************************************************************ */
    @@ -325,11 +384,16 @@ static FILE* LZ4IO_openSrcFile(const char* srcFileName)
             DISPLAYLEVEL(4,"Using stdin for input \n");
             f = stdin;
             SET_BINARY_MODE(stdin);
    -    } else {
    -        f = fopen(srcFileName, "rb");
    -        if (f==NULL) DISPLAYLEVEL(1, "%s: %s \n", srcFileName, strerror(errno));
    +        return f;
         }
     
    +    if (UTIL_isDirectory(srcFileName)) {
    +        DISPLAYLEVEL(1, "lz4: %s is a directory -- ignored \n", srcFileName);
    +        return NULL;
    +    }
    +
    +    f = fopen(srcFileName, "rb");
    +    if (f==NULL) DISPLAYLEVEL(1, "%s: %s \n", srcFileName, strerror(errno));
         return f;
     }
     
    @@ -337,7 +401,8 @@ static FILE* LZ4IO_openSrcFile(const char* srcFileName)
      *  prefs is writable, because sparseFileSupport might be updated.
      *  condition : `dstFileName` must be non-NULL.
      * @result : FILE* to `dstFileName`, or NULL if it fails */
    -static FILE* LZ4IO_openDstFile(const char* dstFileName, const LZ4IO_prefs_t* const prefs)
    +static FILE*
    +LZ4IO_openDstFile(const char* dstFileName, const LZ4IO_prefs_t* const prefs)
     {
         FILE* f;
         assert(dstFileName != NULL);
    @@ -381,6 +446,311 @@ static FILE* LZ4IO_openDstFile(const char* dstFileName, const LZ4IO_prefs_t* con
     }
     
     
    +/***************************************
    +*   MT I/O
    +***************************************/
    +
    +#include "threadpool.h"
    +
    +typedef struct {
    +    void* buf;
    +    size_t size;
    +    unsigned long long rank;
    +} BufferDesc;
    +
    +typedef struct {
    +    unsigned long long expectedRank;
    +    BufferDesc* buffers;
    +    size_t capacity;
    +    size_t blockSize;
    +    unsigned long long totalCSize;
    +} WriteRegister;
    +
    +static void WR_destroy(WriteRegister* wr)
    +{
    +    free(wr->buffers);
    +}
    +
    +#define WR_INITIAL_BUFFER_POOL_SIZE 16
    +/* Note: WR_init() can fail (allocation)
    + * check that wr->buffers!= NULL for success */
    +static WriteRegister WR_init(size_t blockSize)
    +{
    +    WriteRegister wr = { 0, NULL, WR_INITIAL_BUFFER_POOL_SIZE, 0, 0 };
    +    wr.buffers = (BufferDesc*)calloc(1, WR_INITIAL_BUFFER_POOL_SIZE * sizeof(BufferDesc));
    +    wr.blockSize = blockSize;
    +    return wr;
    +}
    +
    +static void WR_addBufDesc(WriteRegister* wr, const BufferDesc* bd)
    +{
    +    if (wr->buffers[wr->capacity-1].buf != NULL) {
    +        /* buffer capacity is full : extend it */
    +        size_t const oldCapacity = wr->capacity;
    +        size_t const addedCapacity = MIN(oldCapacity, 256);
    +        size_t const newCapacity = oldCapacity + addedCapacity;
    +        size_t const newSize = newCapacity * sizeof(BufferDesc);
    +        void* const newBuf = realloc(wr->buffers, newSize);
    +        if (newBuf == NULL) {
    +            END_PROCESS(39, "cannot extend register of buffers")
    +        }
    +        wr->buffers = (BufferDesc*)newBuf;
    +        memset(wr->buffers + oldCapacity, 0, addedCapacity * sizeof(BufferDesc));
    +        wr->buffers[oldCapacity] = bd[0];
    +        wr->capacity = newCapacity;
    +    } else {
    +        /* at least one position (the last one) is free, i.e. buffer==NULL */
    +        size_t n;
    +        for (n=0; ncapacity; n++) {
    +            if (wr->buffers[n].buf == NULL) {
    +                wr->buffers[n] = bd[0];
    +                break;
    +            }
    +        }
    +        assert(n != wr->capacity);
    +    }
    +}
    +
    +static int WR_isPresent(WriteRegister* wr, unsigned long long id)
    +{
    +    size_t n;
    +    for (n=0; ncapacity; n++) {
    +        if (wr->buffers[n].buf == NULL) {
    +            /* no more buffers stored */
    +            return 0;
    +        }
    +        if (wr->buffers[n].rank == id)
    +            return 1;
    +    }
    +    return 0;
    +}
    +
    +/* Note: requires @id to exist! */
    +static BufferDesc WR_getBufID(WriteRegister* wr, unsigned long long id)
    +{
    +    size_t n;
    +    for (n=0; ncapacity; n++) {
    +        if (wr->buffers[n].buf == NULL) {
    +            /* no more buffers stored */
    +            break;
    +        }
    +        if (wr->buffers[n].rank == id)
    +            return wr->buffers[n];
    +    }
    +    END_PROCESS(41, "buffer ID not found");
    +}
    +
    +static void WR_removeBuffID(WriteRegister* wr, unsigned long long id)
    +{
    +    size_t n;
    +    for (n=0; ncapacity; n++) {
    +        if (wr->buffers[n].buf == NULL) {
    +            /* no more buffers stored */
    +            return;
    +        }
    +        if (wr->buffers[n].rank == id) {
    +            free(wr->buffers[n].buf);
    +            break;
    +        }
    +    }
    +    /* overwrite buffer descriptor, scale others down*/
    +    n++;
    +    for (; n < wr->capacity; n++) {
    +        wr->buffers[n-1] = wr->buffers[n];
    +        if (wr->buffers[n].buf == NULL)
    +            return;
    +    }
    +    {   BufferDesc const nullBd = { NULL, 0, 0 };
    +        wr->buffers[wr->capacity-1] = nullBd;
    +    }
    +}
    +
    +typedef struct {
    +    WriteRegister* wr;
    +    void* cBuf;
    +    size_t cSize;
    +    unsigned long long blockNb;
    +    FILE* out;
    +} WriteJobDesc;
    +
    +static void LZ4IO_writeBuffer(BufferDesc bufDesc, FILE* out)
    +{
    +    size_t const size = bufDesc.size;
    +    if (fwrite(bufDesc.buf, 1, size, out) != size) {
    +        END_PROCESS(38, "Write error : cannot write compressed block");
    +    }
    +}
    +
    +static void LZ4IO_checkWriteOrder(void* arg)
    +{
    +    WriteJobDesc* const wjd = (WriteJobDesc*)arg;
    +    size_t const cSize = wjd->cSize;
    +    WriteRegister* const wr = wjd->wr;
    +
    +    if (wjd->blockNb != wr->expectedRank) {
    +        /* incorrect order : let's store this buffer for later write */
    +        BufferDesc bd;
    +        bd.buf = wjd->cBuf;
    +        bd.size = wjd->cSize;
    +        bd.rank = wjd->blockNb;
    +        WR_addBufDesc(wr, &bd);
    +        free(wjd);  /* because wjd is pod */
    +        return;
    +    }
    +
    +    /* expected block ID : let's write this block */
    +    {   BufferDesc bd;
    +        bd.buf = wjd->cBuf;
    +        bd.size = wjd->cSize;
    +        bd.rank = wjd->blockNb;
    +        LZ4IO_writeBuffer(bd, wjd->out);
    +    }
    +    wr->expectedRank++;
    +    wr->totalCSize += cSize;
    +    free(wjd->cBuf);
    +    /* and check for more blocks, previously saved */
    +    while (WR_isPresent(wr, wr->expectedRank)) {
    +        BufferDesc const bd = WR_getBufID(wr, wr->expectedRank);
    +        LZ4IO_writeBuffer(bd, wjd->out);
    +        wr->totalCSize += bd.size;
    +        WR_removeBuffID(wr, wr->expectedRank);
    +        wr->expectedRank++;
    +    }
    +    free(wjd);  /* because wjd is pod */
    +    {   unsigned long long const processedSize = (unsigned long long)(wr->expectedRank-1) * wr->blockSize;
    +        DISPLAYUPDATE(2, "\rRead : %u MiB   ==> %.2f%%   ",
    +                (unsigned)(processedSize >> 20),
    +                (double)wr->totalCSize / (double)processedSize * 100.);
    +    }
    +}
    +
    +typedef size_t (*compress_f)(
    +    const void* parameters,
    +    void* dst,
    +    size_t dstCapacity,
    +    const void* src,
    +    size_t srcSize,
    +    size_t prefixSize);
    +
    +typedef struct {
    +    TPool* wpool;
    +    void* buffer;
    +    size_t prefixSize;
    +    size_t inSize;
    +    unsigned long long blockNb;
    +    compress_f compress;
    +    const void* compressParameters;
    +    FILE* fout;
    +    WriteRegister* wr;
    +    size_t maxCBlockSize;
    +    int lastBlock;
    +} CompressJobDesc;
    +
    +static void LZ4IO_compressChunk(void* arg)
    +{
    +    CompressJobDesc* const cjd = (CompressJobDesc*)arg;
    +    size_t const outCapacity = cjd->maxCBlockSize;
    +    void* const out_buff = malloc(outCapacity);
    +    if (!out_buff)
    +        END_PROCESS(33, "Allocation error : can't allocate output buffer to compress new chunk");
    +    {   char* const inBuff = (char*)cjd->buffer + cjd->prefixSize;
    +        size_t const cSize = cjd->compress(cjd->compressParameters, out_buff, outCapacity, inBuff, cjd->inSize, cjd->prefixSize);
    +
    +        /* check for write */
    +        {   WriteJobDesc* const wjd = (WriteJobDesc*)malloc(sizeof(*wjd));
    +            if (wjd == NULL) {
    +                END_PROCESS(35, "Allocation error : can't describe new write job");
    +            }
    +            wjd->cBuf = out_buff;
    +            wjd->cSize = (size_t)cSize;
    +            wjd->blockNb = cjd->blockNb;
    +            wjd->out = cjd->fout;
    +            wjd->wr = cjd->wr;
    +            TPool_submitJob(cjd->wpool, LZ4IO_checkWriteOrder, wjd);
    +    }   }
    +}
    +
    +static void LZ4IO_compressAndFreeChunk(void* arg)
    +{
    +    CompressJobDesc* const cjd = (CompressJobDesc*)arg;
    +    LZ4IO_compressChunk(arg);
    +    /* clean up */
    +    free(cjd->buffer);
    +    free(cjd); /* because cjd is pod */
    +}
    +
    +/* one ReadTracker per file to compress */
    +typedef struct {
    +    TPool* tPool;
    +    TPool* wpool;
    +    FILE* fin;
    +    size_t chunkSize;
    +    unsigned long long totalReadSize;
    +    unsigned long long blockNb;
    +    XXH32_state_t* xxh32;
    +    compress_f compress;
    +    const void* compressParameters;
    +    void* prefix; /* if it exists, assumed to be filled with 64 KB */
    +    FILE* fout;
    +    WriteRegister* wr;
    +    size_t maxCBlockSize;
    +} ReadTracker;
    +
    +static void LZ4IO_readAndProcess(void* arg)
    +{
    +    ReadTracker* const rjd = (ReadTracker*)arg;
    +    size_t const chunkSize = rjd->chunkSize;
    +    size_t const prefixSize = (rjd->prefix != NULL) * 64 KB;
    +    size_t const bufferSize = chunkSize + prefixSize;
    +    void* const buffer = malloc(bufferSize);
    +    if (!buffer)
    +        END_PROCESS(31, "Allocation error : can't allocate buffer to read new chunk");
    +    if (prefixSize) {
    +        assert(prefixSize == 64 KB);
    +        memcpy(buffer, rjd->prefix, prefixSize);
    +    }
    +    {   char* const in_buff = (char*)buffer + prefixSize;
    +        size_t const inSize = fread(in_buff, (size_t)1, chunkSize, rjd->fin);
    +        if (inSize > chunkSize) {
    +            END_PROCESS(32, "Read error (read %u > %u [chunk size])", (unsigned)inSize, (unsigned)chunkSize);
    +        }
    +        rjd->totalReadSize += inSize;
    +        /* special case: nothing left: stop read operation */
    +        if (inSize == 0) {
    +            free(buffer);
    +            return;
    +        }
    +        /* process read input */
    +        {   CompressJobDesc* const cjd = (CompressJobDesc*)malloc(sizeof(*cjd));
    +            if (cjd==NULL) {
    +                END_PROCESS(33, "Allocation error : can't describe new compression job");
    +            }
    +            if (rjd->xxh32) {
    +                XXH32_update(rjd->xxh32, in_buff, inSize);
    +            }
    +            if (rjd->prefix) {
    +                /* dependent blocks mode */
    +                memcpy(rjd->prefix, in_buff + inSize - 64 KB, 64 KB);
    +            }
    +            cjd->wpool = rjd->wpool;
    +            cjd->buffer = buffer; /* transfer ownership */
    +            cjd->prefixSize = prefixSize;
    +            cjd->inSize = inSize;
    +            cjd->blockNb = rjd->blockNb;
    +            cjd->compress = rjd->compress;
    +            cjd->compressParameters = rjd->compressParameters;
    +            cjd->fout = rjd->fout;
    +            cjd->wr = rjd->wr;
    +            cjd->maxCBlockSize = rjd->maxCBlockSize;
    +            cjd->lastBlock = inSize < chunkSize;
    +            TPool_submitJob(rjd->tPool, LZ4IO_compressAndFreeChunk, cjd);
    +            if (inSize == chunkSize) {
    +                /* likely more => read another chunk */
    +                rjd->blockNb++;
    +                TPool_submitJob(rjd->tPool, LZ4IO_readAndProcess, rjd);
    +    }   }   }
    +}
    +
     
     /***************************************
     *   Legacy Compression
    @@ -400,95 +770,151 @@ static void LZ4IO_writeLE32 (void* p, unsigned value32)
         dstPtr[3] = (unsigned char)(value32 >> 24);
     }
     
    -static int LZ4IO_LZ4_compress(const char* src, char* dst, int srcSize, int dstSize, int cLevel)
    +
    +typedef struct {
    +    int cLevel;
    +} CompressLegacyState;
    +
    +static size_t LZ4IO_compressBlockLegacy_fast(
    +    const void* params,
    +    void* dst,
    +    size_t dstCapacity,
    +    const void* src,
    +    size_t srcSize,
    +    size_t prefixSize
    +)
     {
    -    (void)cLevel;
    -    return LZ4_compress_fast(src, dst, srcSize, dstSize, 1);
    +    const CompressLegacyState* const clevel = (const CompressLegacyState*)params;
    +    int const acceleration = (clevel->cLevel < 0) ? -clevel->cLevel : 0;
    +    int const cSize = LZ4_compress_fast((const char*)src, (char*)dst + LZ4IO_LEGACY_BLOCK_HEADER_SIZE, (int)srcSize, (int)dstCapacity, acceleration);
    +    if (cSize < 0)
    +        END_PROCESS(51, "fast compression failed");
    +    LZ4IO_writeLE32(dst, (unsigned)cSize);
    +    assert(prefixSize == 0); (void)prefixSize;
    +    return (size_t) cSize + LZ4IO_LEGACY_BLOCK_HEADER_SIZE;
     }
     
    -/* LZ4IO_compressFilename_Legacy :
    - * This function is intentionally "hidden" (not published in .h)
    - * It generates compressed streams using the old 'legacy' format */
    -int LZ4IO_compressFilename_Legacy(const char* input_filename, const char* output_filename,
    -                                  int compressionlevel, const LZ4IO_prefs_t* prefs)
    +static size_t LZ4IO_compressBlockLegacy_HC(
    +    const void* params,
    +    void* dst,
    +    size_t dstCapacity,
    +    const void* src,
    +    size_t srcSize,
    +    size_t prefixSize
    +)
     {
    -    typedef int (*compress_f)(const char* src, char* dst, int srcSize, int dstSize, int cLevel);
    -    compress_f const compressionFunction = (compressionlevel < 3) ? LZ4IO_LZ4_compress : LZ4_compress_HC;
    -    unsigned long long filesize = 0;
    -    unsigned long long compressedfilesize = MAGICNUMBER_SIZE;
    -    char* in_buff;
    -    char* out_buff;
    -    const int outBuffSize = LZ4_compressBound(LEGACY_BLOCKSIZE);
    -    FILE* const finput = LZ4IO_openSrcFile(input_filename);
    -    FILE* foutput;
    -    clock_t clockEnd;
    -
    -    /* Init */
    -    clock_t const clockStart = clock();
    -    if (finput == NULL)
    -        END_PROCESS(20, "%s : open file error ", input_filename);
    +    const CompressLegacyState* const cs = (const CompressLegacyState*)params;
    +    int const clevel = cs->cLevel;
    +    int const cSize = LZ4_compress_HC((const char*)src, (char*)dst + LZ4IO_LEGACY_BLOCK_HEADER_SIZE, (int)srcSize, (int)dstCapacity, clevel);
    +    if (cSize < 0)
    +        END_PROCESS(52, "HC compression failed");
    +    LZ4IO_writeLE32(dst, (unsigned)cSize);
    +    assert(prefixSize == 0); (void)prefixSize;
    +    return (size_t) cSize + LZ4IO_LEGACY_BLOCK_HEADER_SIZE;
    +}
     
    +/* LZ4IO_compressLegacy_internal :
    + * Implementation of LZ4IO_compressFilename_Legacy.
    + * @return: 0 if success, !0 if error
    + */
    +static int LZ4IO_compressLegacy_internal(unsigned long long* readSize,
    +                                  const char* input_filename,
    +                                  const char* output_filename,
    +                                  int compressionlevel,
    +                                  const LZ4IO_prefs_t* prefs)
    +{
    +    int clResult = 0;
    +    compress_f const compressionFunction = (compressionlevel < 3) ? LZ4IO_compressBlockLegacy_fast : LZ4IO_compressBlockLegacy_HC;
    +    FILE* const finput = LZ4IO_openSrcFile(input_filename);
    +    FILE* foutput = NULL;
    +    TPool* const tPool = TPool_create(prefs->nbWorkers, 4);
    +    TPool* const wPool = TPool_create(1, 4);
    +    WriteRegister wr = WR_init(LEGACY_BLOCKSIZE);
    +
    +    /* Init & checks */
    +    *readSize = 0;
    +    if (finput == NULL) {
    +        /* read file error : recoverable */
    +        clResult = 1;
    +        goto _cfl_clean;
    +    }
         foutput = LZ4IO_openDstFile(output_filename, prefs);
         if (foutput == NULL) {
    -        fclose(finput);
    -        END_PROCESS(20, "%s : open file error ", input_filename);
    +        /* write file error : recoverable */
    +        clResult = 1;
    +        goto _cfl_clean;
         }
    +    if (tPool == NULL || wPool == NULL)
    +        END_PROCESS(21, "threadpool creation error ");
    +    if (wr.buffers == NULL)
    +        END_PROCESS(22, "can't allocate write register");
     
    -    /* Allocate Memory */
    -    in_buff = (char*)malloc(LEGACY_BLOCKSIZE);
    -    out_buff = (char*)malloc((size_t)outBuffSize + 4);
    -    if (!in_buff || !out_buff)
    -        END_PROCESS(21, "Allocation error : not enough memory");
     
         /* Write Archive Header */
    -    LZ4IO_writeLE32(out_buff, LEGACY_MAGICNUMBER);
    -    if (fwrite(out_buff, 1, MAGICNUMBER_SIZE, foutput) != MAGICNUMBER_SIZE)
    -        END_PROCESS(22, "Write error : cannot write header");
    -
    -    /* Main Loop */
    -    while (1) {
    -        int outSize;
    -        /* Read Block */
    -        size_t const inSize = fread(in_buff, (size_t)1, (size_t)LEGACY_BLOCKSIZE, finput);
    -        if (inSize == 0) break;
    -        assert(inSize <= LEGACY_BLOCKSIZE);
    -        filesize += inSize;
    -
    -        /* Compress Block */
    -        outSize = compressionFunction(in_buff, out_buff+4, (int)inSize, outBuffSize, compressionlevel);
    -        assert(outSize >= 0);
    -        compressedfilesize += (unsigned long long)outSize+4;
    -        DISPLAYUPDATE(2, "\rRead : %i MiB  ==> %.2f%%   ",
    -                (int)(filesize>>20), (double)compressedfilesize/filesize*100);
    -
    -        /* Write Block */
    -        assert(outSize > 0);
    -        assert(outSize < outBuffSize);
    -        LZ4IO_writeLE32(out_buff, (unsigned)outSize);
    -        if (fwrite(out_buff, 1, (size_t)outSize+4, foutput) != (size_t)(outSize+4)) {
    -            END_PROCESS(24, "Write error : cannot write compressed block");
    -    }   }
    -    if (ferror(finput)) END_PROCESS(24, "Error while reading %s ", input_filename);
    -
    -    /* Status */
    -    clockEnd = clock();
    -    clockEnd += (clockEnd==clockStart); /* avoid division by zero (speed) */
    -    filesize += !filesize;   /* avoid division by zero (ratio) */
    -    DISPLAYLEVEL(2, "\r%79s\r", "");   /* blank line */
    -    DISPLAYLEVEL(2,"Compressed %llu bytes into %llu bytes ==> %.2f%%\n",
    -        filesize, compressedfilesize, (double)compressedfilesize / filesize * 100);
    -    {   double const seconds = (double)(clockEnd - clockStart) / CLOCKS_PER_SEC;
    -        DISPLAYLEVEL(4,"Done in %.2f s ==> %.2f MiB/s\n", seconds,
    -                        (double)filesize / seconds / 1024 / 1024);
    +    {   char outHeader[MAGICNUMBER_SIZE];
    +        LZ4IO_writeLE32(outHeader, LEGACY_MAGICNUMBER);
    +        if (fwrite(outHeader, 1, MAGICNUMBER_SIZE, foutput) != MAGICNUMBER_SIZE)
    +            END_PROCESS(23, "Write error : cannot write header");
    +    }
    +    wr.totalCSize = MAGICNUMBER_SIZE;
    +
    +    {   CompressLegacyState cls;
    +        ReadTracker rjd;
    +        cls.cLevel = compressionlevel;
    +        rjd.tPool = tPool;
    +        rjd.wpool = wPool;
    +        rjd.fin = finput;
    +        rjd.chunkSize = LEGACY_BLOCKSIZE;
    +        rjd.totalReadSize = 0;
    +        rjd.blockNb = 0;
    +        rjd.xxh32 = NULL;
    +        rjd.compress = compressionFunction;
    +        rjd.compressParameters = &cls;
    +        rjd.prefix = NULL;
    +        rjd.fout = foutput;
    +        rjd.wr = ≀
    +        rjd.maxCBlockSize = (size_t)LZ4_compressBound(LEGACY_BLOCKSIZE) + LZ4IO_LEGACY_BLOCK_HEADER_SIZE;
    +        /* Ignite the job chain */
    +        TPool_submitJob(tPool, LZ4IO_readAndProcess, &rjd);
    +        /* Wait for all completion */
    +        TPool_jobsCompleted(tPool);
    +        TPool_jobsCompleted(wPool);
    +
    +        /* Status */
    +        DISPLAYLEVEL(2, "\r%79s\r", "");    /* blank line */
    +        DISPLAYLEVEL(2,"Compressed %llu bytes into %llu bytes ==> %.2f%% \n",
    +                    rjd.totalReadSize, wr.totalCSize,
    +                    (double)wr.totalCSize / (double)(rjd.totalReadSize + !rjd.totalReadSize) * 100.);
    +        *readSize = rjd.totalReadSize;
         }
     
         /* Close & Free */
    -    free(in_buff);
    -    free(out_buff);
    -    fclose(finput);
    -    if (!LZ4IO_isStdout(output_filename)) fclose(foutput);  /* do not close stdout */
    +_cfl_clean:
    +    WR_destroy(&wr);
    +    TPool_free(wPool);
    +    TPool_free(tPool);
    +    if (finput) fclose(finput);
    +    if (foutput && !LZ4IO_isStdout(output_filename)) fclose(foutput);  /* do not close stdout */
    +
    +    return clResult;
    +}
     
    -    return 0;
    +/* LZ4IO_compressFilename_Legacy :
    + * This function is intentionally "hidden" (not published in .h)
    + * It generates compressed streams using the old 'legacy' format
    + * @return: 0 if success, !0 if error
    + */
    +int LZ4IO_compressFilename_Legacy(const char* input_filename,
    +                                  const char* output_filename,
    +                                  int compressionlevel,
    +                                  const LZ4IO_prefs_t* prefs)
    +{
    +    TIME_t const timeStart = TIME_getTime();
    +    clock_t const cpuStart = clock();
    +    unsigned long long processed = 0;
    +    int r = LZ4IO_compressLegacy_internal(&processed, input_filename, output_filename, compressionlevel, prefs);
    +    LZ4IO_finalTimeDisplay(timeStart, cpuStart, processed);
    +    return r;
     }
     
     #define FNSPACE 30
    @@ -500,6 +926,9 @@ int LZ4IO_compressMultipleFilenames_Legacy(
                                 const char* suffix,
                                 int compressionLevel, const LZ4IO_prefs_t* prefs)
     {
    +    TIME_t const timeStart = TIME_getTime();
    +    clock_t const cpuStart = clock();
    +    unsigned long long totalProcessed = 0;
         int i;
         int missed_files = 0;
         char* dstFileName = (char*)malloc(FNSPACE);
    @@ -510,11 +939,13 @@ int LZ4IO_compressMultipleFilenames_Legacy(
     
         /* loop on each file */
         for (i=0; iuseDictionary) return NULL;
    -    dictionaryBuffer = LZ4IO_createDict(&dictionarySize, prefs->dictionaryFilename);
    +    if (!io_prefs->useDictionary) return NULL;
    +    dictionaryBuffer = LZ4IO_createDict(&dictionarySize, io_prefs->dictionaryFilename);
         if (!dictionaryBuffer) END_PROCESS(29, "Dictionary error : could not create dictionary");
         cdict = LZ4F_createCDict(dictionaryBuffer, dictionarySize);
         free(dictionaryBuffer);
         return cdict;
     }
     
    -static cRess_t LZ4IO_createCResources(const LZ4IO_prefs_t* const prefs)
    +static cRess_t LZ4IO_createCResources(const LZ4IO_prefs_t* io_prefs)
     {
    -    const size_t blockSize = prefs->blockSize;
    +    const size_t chunkSize = 4 MB;
         cRess_t ress;
    +    memset(&ress, 0, sizeof(ress));
    +
    +    /* set compression advanced parameters */
    +    ress.preparedPrefs.autoFlush = 1;
    +    ress.preparedPrefs.frameInfo.blockMode = (LZ4F_blockMode_t)io_prefs->blockIndependence;
    +    ress.preparedPrefs.frameInfo.blockSizeID = (LZ4F_blockSizeID_t)io_prefs->blockSizeId;
    +    ress.preparedPrefs.frameInfo.blockChecksumFlag = (LZ4F_blockChecksum_t)io_prefs->blockChecksum;
    +    ress.preparedPrefs.frameInfo.contentChecksumFlag = (LZ4F_contentChecksum_t)io_prefs->streamChecksum;
    +    ress.preparedPrefs.favorDecSpeed = io_prefs->favorDecSpeed;
    +
    +    /* Allocate compression state */
    +    {   LZ4F_errorCode_t const errorCode = LZ4F_createCompressionContext(&(ress.ctx), LZ4F_VERSION);
    +        if (LZ4F_isError(errorCode))
    +            END_PROCESS(30, "Allocation error : can't create LZ4F context : %s", LZ4F_getErrorName(errorCode));
    +    }
    +    assert(ress.ctx != NULL);
     
    -    LZ4F_errorCode_t const errorCode = LZ4F_createCompressionContext(&(ress.ctx), LZ4F_VERSION);
    -    if (LZ4F_isError(errorCode)) END_PROCESS(30, "Allocation error : can't create LZ4F context : %s", LZ4F_getErrorName(errorCode));
    -
    -    /* Allocate Memory */
    -    ress.srcBuffer = malloc(blockSize);
    -    ress.srcBufferSize = blockSize;
    -    ress.dstBufferSize = LZ4F_compressFrameBound(blockSize, NULL);   /* cover worst case */
    +    /* Allocate Buffers */
    +    ress.srcBuffer = malloc(chunkSize);
    +    ress.srcBufferSize = chunkSize;
    +    ress.dstBufferSize = LZ4F_compressFrameBound(chunkSize, &ress.preparedPrefs);
         ress.dstBuffer = malloc(ress.dstBufferSize);
    -    if (!ress.srcBuffer || !ress.dstBuffer) END_PROCESS(31, "Allocation error : not enough memory");
    +    if (!ress.srcBuffer || !ress.dstBuffer)
    +        END_PROCESS(31, "Allocation error : can't allocate buffers");
     
    -    ress.cdict = LZ4IO_createCDict(prefs);
    +    ress.cdict = LZ4IO_createCDict(io_prefs);
    +
    +    /* will be created it needed */
    +    ress.tPool = NULL;
    +    ress.wPool = NULL;
     
         return ress;
     }
     
    -static void LZ4IO_freeCResources(cRess_t ress)
    +typedef struct {
    +    const LZ4F_preferences_t* prefs;
    +    const LZ4F_CDict* cdict;
    +} LZ4IO_CfcParameters;
    +
    +static size_t LZ4IO_compressFrameChunk(const void* params,
    +                                    void* dst, size_t dstCapacity,
    +                                    const void* src, size_t srcSize,
    +                                    size_t prefixSize)
     {
    -    free(ress.srcBuffer);
    -    free(ress.dstBuffer);
    +    const LZ4IO_CfcParameters* const cfcp = (const LZ4IO_CfcParameters*)params;
    +    LZ4F_cctx* cctx = NULL;
    +    {   LZ4F_errorCode_t const ccr = LZ4F_createCompressionContext(&cctx, LZ4F_VERSION);
    +        if (cctx==NULL || LZ4F_isError(ccr))
    +            END_PROCESS(51, "unable to create a LZ4F compression context");
    +    }
    +    /* init state, and writes frame header, will be overwritten at next stage. */
    +    if (prefixSize) {
    +        size_t const whr = LZ4F_compressBegin_usingDict(cctx, dst, dstCapacity, (const char*)src - prefixSize, prefixSize, cfcp->prefs);
    +        if (LZ4F_isError(whr))
    +            END_PROCESS(52, "error initializing LZ4F compression context with prefix");
    +        assert(prefixSize == 64 KB);
    +    } else {
    +        size_t const whr = LZ4F_compressBegin_usingCDict(cctx, dst, dstCapacity, cfcp->cdict, cfcp->prefs);
    +        if (LZ4F_isError(whr))
    +            END_PROCESS(53, "error initializing LZ4F compression context");
    +    }
    +    /* let's now compress, overwriting unused header */
    +    {   size_t const cSize = LZ4F_compressUpdate(cctx, dst, dstCapacity, src, srcSize, NULL);
    +        if (LZ4F_isError(cSize))
    +            END_PROCESS(55, "error compressing with LZ4F_compressUpdate");
     
    -    LZ4F_freeCDict(ress.cdict);
    -    ress.cdict = NULL;
    +        LZ4F_freeCompressionContext(cctx);
    +        return (size_t) cSize;
    +    }
    +}
     
    -    { LZ4F_errorCode_t const errorCode = LZ4F_freeCompressionContext(ress.ctx);
    -      if (LZ4F_isError(errorCode)) END_PROCESS(35, "Error : can't free LZ4F context resource : %s", LZ4F_getErrorName(errorCode)); }
    +/*
    + * LZ4IO_compressFilename_extRess()
    + * result : 0 : compression completed correctly
    + *          1 : missing or pb opening srcFileName
    + */
    +int
    +LZ4IO_compressFilename_extRess_MT(unsigned long long* inStreamSize,
    +                               cRess_t* ress,
    +                               const char* srcFileName, const char* dstFileName,
    +                               int compressionLevel,
    +                               const LZ4IO_prefs_t* const io_prefs)
    +{
    +    unsigned long long filesize = 0;
    +    unsigned long long compressedfilesize = 0;
    +    FILE* dstFile;
    +    void* const srcBuffer = ress->srcBuffer;
    +    void* const dstBuffer = ress->dstBuffer;
    +    const size_t dstBufferSize = ress->dstBufferSize;
    +    const size_t chunkSize = 4 MB;  /* each job should be "sufficiently large" */
    +    size_t readSize;
    +    LZ4F_compressionContext_t ctx = ress->ctx;   /* just a pointer */
    +    LZ4F_preferences_t prefs;
    +
    +    /* Init */
    +    FILE* const srcFile = LZ4IO_openSrcFile(srcFileName);
    +    if (srcFile == NULL) return 1;
    +    dstFile = LZ4IO_openDstFile(dstFileName, io_prefs);
    +    if (dstFile == NULL) { fclose(srcFile); return 1; }
    +
    +    /* Adjust compression parameters */
    +    prefs = ress->preparedPrefs;
    +    prefs.compressionLevel = compressionLevel;
    +    if (io_prefs->contentSizeFlag) {
    +      U64 const fileSize = UTIL_getOpenFileSize(srcFile);
    +      prefs.frameInfo.contentSize = fileSize;   /* == 0 if input == stdin */
    +      if (fileSize==0)
    +          DISPLAYLEVEL(3, "Warning : cannot determine input content size \n");
    +    }
    +
    +    /* read first chunk */
    +    assert(chunkSize <= ress->srcBufferSize);
    +    readSize  = fread(srcBuffer, (size_t)1, chunkSize, srcFile);
    +    if (ferror(srcFile))
    +        END_PROCESS(40, "Error reading first chunk (%u bytes) of '%s' ", (unsigned)chunkSize, srcFileName);
    +    filesize += readSize;
    +
    +    /* single-block file */
    +    if (readSize < chunkSize) {
    +        /* Compress in single pass */
    +        size_t const cSize = LZ4F_compressFrame_usingCDict(ctx, dstBuffer, dstBufferSize, srcBuffer, readSize, ress->cdict, &prefs);
    +        if (LZ4F_isError(cSize))
    +            END_PROCESS(41, "Compression failed : %s", LZ4F_getErrorName(cSize));
    +        compressedfilesize = cSize;
    +        DISPLAYUPDATE(2, "\rRead : %u MiB   ==> %.2f%%   ",
    +                      (unsigned)(filesize>>20), (double)compressedfilesize/(double)(filesize+!filesize)*100);   /* avoid division by zero */
    +
    +        /* Write Block */
    +        if (fwrite(dstBuffer, 1, cSize, dstFile) != cSize) {
    +            END_PROCESS(42, "Write error : failed writing single-block compressed frame");
    +    }   }
    +
    +    else
    +
    +    /* multiple-blocks file */
    +    {   WriteRegister wr = WR_init(chunkSize);
    +        void* prefixBuffer = NULL;
    +
    +        int checksum = (int)prefs.frameInfo.contentChecksumFlag;
    +        XXH32_state_t* xxh32 = NULL;
    +
    +        LZ4IO_CfcParameters cfcp;
    +        ReadTracker rjd;
    +
    +        if (ress->tPool == NULL) {
    +            ress->tPool = TPool_create(io_prefs->nbWorkers, 4);
    +            assert(ress->wPool == NULL);
    +            ress->wPool = TPool_create(1, 4);
    +            if (ress->tPool == NULL || ress->wPool == NULL)
    +                END_PROCESS(43, "can't create threadpools");
    +        }
    +        cfcp.prefs = &prefs;
    +        cfcp.cdict = ress->cdict;
    +        rjd.tPool = ress->tPool;
    +        rjd.wpool = ress->wPool;
    +        rjd.fin = srcFile;
    +        rjd.chunkSize = chunkSize;
    +        rjd.totalReadSize = 0;
    +        rjd.blockNb = 0;
    +        rjd.xxh32 = xxh32;
    +        rjd.compress = LZ4IO_compressFrameChunk;
    +        rjd.compressParameters = &cfcp;
    +        rjd.prefix = NULL;
    +        rjd.fout = dstFile;
    +        rjd.wr = ≀
    +        rjd.maxCBlockSize = LZ4F_compressFrameBound(chunkSize, &prefs);
    +
    +        /* process frame checksum externally */
    +        if (checksum) {
    +            xxh32 = XXH32_createState();
    +            if (xxh32==NULL)
    +                END_PROCESS(42, "could not init checksum");
    +            XXH32_reset(xxh32, 0);
    +            XXH32_update(xxh32, srcBuffer, readSize);
    +            rjd.xxh32 = xxh32;
    +        }
    +
    +        /* block dependency */
    +        if (prefs.frameInfo.blockMode == LZ4F_blockLinked) {
    +            prefixBuffer = malloc(64 KB);
    +            if (prefixBuffer==NULL)
    +                END_PROCESS(43, "cannot allocate small dictionary buffer");
    +            rjd.prefix = prefixBuffer;
    +        }
    +
    +        /* Write Frame Header */
    +        /* note: simplification: do not employ dictionary when input size >= 4 MB,
    +         * the benefit is very limited anyway, and is not worth the dependency cost */
    +        {   size_t const headerSize = LZ4F_compressBegin(ctx, dstBuffer, dstBufferSize, &prefs);
    +            if (LZ4F_isError(headerSize))
    +                END_PROCESS(44, "File header generation failed : %s", LZ4F_getErrorName(headerSize));
    +            if (fwrite(dstBuffer, 1, headerSize, dstFile) != headerSize)
    +                END_PROCESS(45, "Write error : cannot write header");
    +            compressedfilesize = headerSize;
    +        }
    +        /* avoid duplicating effort to process content checksum (done externally) */
    +        prefs.frameInfo.contentChecksumFlag = LZ4F_noContentChecksum;
    +
    +        /* process first block */
    +        {   CompressJobDesc cjd;
    +            cjd.wpool = ress->wPool;
    +            cjd.buffer = srcBuffer;
    +            cjd.prefixSize = 0;
    +            cjd.inSize = readSize;
    +            cjd.blockNb = 0;
    +            cjd.compress = LZ4IO_compressFrameChunk;
    +            cjd.compressParameters = &cfcp;
    +            cjd.fout = dstFile;
    +            cjd.wr = ≀
    +            cjd.maxCBlockSize = rjd.maxCBlockSize;
    +            cjd.lastBlock = 0;
    +            TPool_submitJob(ress->tPool, LZ4IO_compressChunk, &cjd);
    +            rjd.totalReadSize = readSize;
    +            rjd.blockNb = 1;
    +            if (prefixBuffer) {
    +                assert(readSize >= 64 KB);
    +                memcpy(prefixBuffer, (char*)srcBuffer + readSize - 64 KB, 64 KB);
    +            }
    +
    +            /* Start the job chain */
    +            TPool_submitJob(ress->tPool, LZ4IO_readAndProcess, &rjd);
    +
    +            /* Wait for all completion */
    +            TPool_jobsCompleted(ress->tPool);
    +            TPool_jobsCompleted(ress->wPool);
    +            compressedfilesize += wr.totalCSize;
    +        }
    +
    +        /* End of Frame mark */
    +        {   size_t endSize = 4;
    +            assert(dstBufferSize >= 8);
    +            memset(dstBuffer, 0, 4);
    +            if (checksum) {
    +                /* handle frame checksum externally
    +                 * note: LZ4F_compressEnd already wrote a (bogus) checksum */
    +                U32 const crc = XXH32_digest(xxh32);
    +                LZ4IO_writeLE32( (char*)dstBuffer + 4, crc);
    +                endSize = 8;
    +            }
    +            if (fwrite(dstBuffer, 1, endSize, dstFile) != endSize)
    +                END_PROCESS(49, "Write error : cannot write end of frame");
    +            compressedfilesize += endSize;
    +            filesize = rjd.totalReadSize;
    +        }
    +
    +        /* clean up*/
    +        free(prefixBuffer);
    +        XXH32_freeState(xxh32);
    +        WR_destroy(&wr);
    +    }
    +
    +    /* Release file handlers */
    +    fclose (srcFile);
    +    if (!LZ4IO_isStdout(dstFileName)) fclose(dstFile);  /* do not close stdout */
    +
    +    /* Copy owner, file permissions and modification time */
    +    {   stat_t statbuf;
    +        if (!LZ4IO_isStdin(srcFileName)
    +         && !LZ4IO_isStdout(dstFileName)
    +         && !LZ4IO_isDevNull(dstFileName)
    +         && UTIL_getFileStat(srcFileName, &statbuf)) {
    +            UTIL_setFileStat(dstFileName, &statbuf);
    +    }   }
    +
    +    if (io_prefs->removeSrcFile) {  /* remove source file : --rm */
    +        if (remove(srcFileName))
    +            END_PROCESS(50, "Remove error : %s: %s", srcFileName, strerror(errno));
    +    }
    +
    +    /* Final Status */
    +    DISPLAYLEVEL(2, "\r%79s\r", "");
    +    DISPLAYLEVEL(2, "Compressed %llu bytes into %llu bytes ==> %.2f%%\n",
    +                    filesize, compressedfilesize,
    +                    (double)compressedfilesize / (double)(filesize + !filesize /* avoid division by zero */ ) * 100.);
    +    *inStreamSize = filesize;
    +
    +    return 0;
     }
     
     /*
    @@ -658,20 +1362,22 @@ static void LZ4IO_freeCResources(cRess_t ress)
      * result : 0 : compression completed correctly
      *          1 : missing or pb opening srcFileName
      */
    -static int
    -LZ4IO_compressFilename_extRess(cRess_t ress,
    +int
    +LZ4IO_compressFilename_extRess_ST(unsigned long long* inStreamSize,
    +                               const cRess_t* ress,
                                    const char* srcFileName, const char* dstFileName,
    -                               int compressionLevel, const LZ4IO_prefs_t* const io_prefs)
    +                               int compressionLevel,
    +                               const LZ4IO_prefs_t* const io_prefs)
     {
         unsigned long long filesize = 0;
         unsigned long long compressedfilesize = 0;
         FILE* dstFile;
    -    void* const srcBuffer = ress.srcBuffer;
    -    void* const dstBuffer = ress.dstBuffer;
    -    const size_t dstBufferSize = ress.dstBufferSize;
    +    void* const srcBuffer = ress->srcBuffer;
    +    void* const dstBuffer = ress->dstBuffer;
    +    const size_t dstBufferSize = ress->dstBufferSize;
         const size_t blockSize = io_prefs->blockSize;
         size_t readSize;
    -    LZ4F_compressionContext_t ctx = ress.ctx;   /* just a pointer */
    +    LZ4F_compressionContext_t ctx = ress->ctx;   /* just a pointer */
         LZ4F_preferences_t prefs;
     
         /* Init */
    @@ -681,14 +1387,9 @@ LZ4IO_compressFilename_extRess(cRess_t ress,
         if (dstFile == NULL) { fclose(srcFile); return 1; }
         memset(&prefs, 0, sizeof(prefs));
     
    -    /* Set compression parameters */
    -    prefs.autoFlush = 1;
    +    /* Adjust compression parameters */
    +    prefs = ress->preparedPrefs;
         prefs.compressionLevel = compressionLevel;
    -    prefs.frameInfo.blockMode = (LZ4F_blockMode_t)io_prefs->blockIndependence;
    -    prefs.frameInfo.blockSizeID = (LZ4F_blockSizeID_t)io_prefs->blockSizeId;
    -    prefs.frameInfo.blockChecksumFlag = (LZ4F_blockChecksum_t)io_prefs->blockChecksum;
    -    prefs.frameInfo.contentChecksumFlag = (LZ4F_contentChecksum_t)io_prefs->streamChecksum;
    -    prefs.favorDecSpeed = io_prefs->favorDecSpeed;
         if (io_prefs->contentSizeFlag) {
           U64 const fileSize = UTIL_getOpenFileSize(srcFile);
           prefs.frameInfo.contentSize = fileSize;   /* == 0 if input == stdin */
    @@ -704,12 +1405,12 @@ LZ4IO_compressFilename_extRess(cRess_t ress,
         /* single-block file */
         if (readSize < blockSize) {
             /* Compress in single pass */
    -        size_t const cSize = LZ4F_compressFrame_usingCDict(ctx, dstBuffer, dstBufferSize, srcBuffer, readSize, ress.cdict, &prefs);
    +        size_t const cSize = LZ4F_compressFrame_usingCDict(ctx, dstBuffer, dstBufferSize, srcBuffer, readSize, ress->cdict, &prefs);
             if (LZ4F_isError(cSize))
                 END_PROCESS(41, "Compression failed : %s", LZ4F_getErrorName(cSize));
             compressedfilesize = cSize;
             DISPLAYUPDATE(2, "\rRead : %u MiB   ==> %.2f%%   ",
    -                      (unsigned)(filesize>>20), (double)compressedfilesize/(filesize+!filesize)*100);   /* avoid division by zero */
    +                      (unsigned)(filesize>>20), (double)compressedfilesize/(double)(filesize+!filesize)*100);   /* avoid division by zero */
     
             /* Write Block */
             if (fwrite(dstBuffer, 1, cSize, dstFile) != cSize) {
    @@ -721,8 +1422,9 @@ LZ4IO_compressFilename_extRess(cRess_t ress,
         /* multiple-blocks file */
         {
             /* Write Frame Header */
    -        size_t const headerSize = LZ4F_compressBegin_usingCDict(ctx, dstBuffer, dstBufferSize, ress.cdict, &prefs);
    -        if (LZ4F_isError(headerSize)) END_PROCESS(43, "File header generation failed : %s", LZ4F_getErrorName(headerSize));
    +        size_t const headerSize = LZ4F_compressBegin_usingCDict(ctx, dstBuffer, dstBufferSize, ress->cdict, &prefs);
    +        if (LZ4F_isError(headerSize))
    +            END_PROCESS(43, "File header generation failed : %s", LZ4F_getErrorName(headerSize));
             if (fwrite(dstBuffer, 1, headerSize, dstFile) != headerSize)
                 END_PROCESS(44, "Write error : cannot write header");
             compressedfilesize += headerSize;
    @@ -734,7 +1436,8 @@ LZ4IO_compressFilename_extRess(cRess_t ress,
                     END_PROCESS(45, "Compression failed : %s", LZ4F_getErrorName(outSize));
                 compressedfilesize += outSize;
                 DISPLAYUPDATE(2, "\rRead : %u MiB   ==> %.2f%%   ",
    -                        (unsigned)(filesize>>20), (double)compressedfilesize/filesize*100);
    +                        (unsigned)(filesize>>20),
    +                        (double)compressedfilesize / (double)filesize * 100.);
     
                 /* Write Block */
                 if (fwrite(dstBuffer, 1, outSize, dstFile) != outSize)
    @@ -753,7 +1456,8 @@ LZ4IO_compressFilename_extRess(cRess_t ress,
                 if (fwrite(dstBuffer, 1, endSize, dstFile) != endSize)
                     END_PROCESS(49, "Write error : cannot write end of frame");
                 compressedfilesize += endSize;
    -    }   }
    +        }
    +    }
     
         /* Release file handlers */
         fclose (srcFile);
    @@ -777,36 +1481,43 @@ LZ4IO_compressFilename_extRess(cRess_t ress,
         DISPLAYLEVEL(2, "\r%79s\r", "");
         DISPLAYLEVEL(2, "Compressed %llu bytes into %llu bytes ==> %.2f%%\n",
                         filesize, compressedfilesize,
    -                    (double)compressedfilesize / (filesize + !filesize /* avoid division by zero */ ) * 100);
    +                    (double)compressedfilesize / (double)(filesize + !filesize /* avoid division by zero */ ) * 100.);
    +    *inStreamSize = filesize;
     
         return 0;
     }
     
    +static int
    +LZ4IO_compressFilename_extRess(unsigned long long* inStreamSize,
    +                               cRess_t* ress,
    +                               const char* srcFileName, const char* dstFileName,
    +                               int compressionLevel,
    +                               const LZ4IO_prefs_t* const io_prefs)
    +{
    +    if (LZ4IO_MULTITHREAD)
    +        return LZ4IO_compressFilename_extRess_MT(inStreamSize, ress, srcFileName, dstFileName, compressionLevel, io_prefs);
    +    /* Only single-thread available */
    +    return LZ4IO_compressFilename_extRess_ST(inStreamSize, ress, srcFileName, dstFileName, compressionLevel, io_prefs);
    +}
     
     int LZ4IO_compressFilename(const char* srcFileName, const char* dstFileName, int compressionLevel, const LZ4IO_prefs_t* prefs)
     {
    -    UTIL_time_t const timeStart = UTIL_getTime();
    +    TIME_t const timeStart = TIME_getTime();
         clock_t const cpuStart = clock();
    -    cRess_t const ress = LZ4IO_createCResources(prefs);
    +    cRess_t ress = LZ4IO_createCResources(prefs);
    +    unsigned long long processed;
     
    -    int const result = LZ4IO_compressFilename_extRess(ress, srcFileName, dstFileName, compressionLevel, prefs);
    +    int const result = LZ4IO_compressFilename_extRess(&processed, &ress, srcFileName, dstFileName, compressionLevel, prefs);
     
         /* Free resources */
         LZ4IO_freeCResources(ress);
     
         /* Final Status */
    -    {   clock_t const cpuEnd = clock();
    -        double const cpuLoad_s = (double)(cpuEnd - cpuStart) / CLOCKS_PER_SEC;
    -        U64 const timeLength_ns = UTIL_clockSpanNano(timeStart);
    -        double const timeLength_s = (double)timeLength_ns / 1000000000;
    -        DISPLAYLEVEL(4, "Completed in %.2f sec  (cpu load : %.0f%%)\n",
    -                        timeLength_s, (cpuLoad_s / timeLength_s) * 100);
    -    }
    +    LZ4IO_finalTimeDisplay(timeStart, cpuStart, processed);
     
         return result;
     }
     
    -
     int LZ4IO_compressMultipleFilenames(
                                   const char** inFileNamesTable, int ifntSize,
                                   const char* suffix,
    @@ -819,17 +1530,22 @@ int LZ4IO_compressMultipleFilenames(
         size_t ofnSize = FNSPACE;
         const size_t suffixSize = strlen(suffix);
         cRess_t ress;
    +    unsigned long long totalProcessed = 0;
    +    TIME_t timeStart = TIME_getTime();
    +    clock_t cpuStart = clock();
     
         if (dstFileName == NULL) return ifntSize;   /* not enough memory */
         ress = LZ4IO_createCResources(prefs);
     
         /* loop on each file */
         for (i=0; i compress into a file => generate its name */
    @@ -844,14 +1560,16 @@ int LZ4IO_compressMultipleFilenames(
             strcpy(dstFileName, inFileNamesTable[i]);
             strcat(dstFileName, suffix);
     
    -        missed_files += LZ4IO_compressFilename_extRess(ress,
    +        missed_files += LZ4IO_compressFilename_extRess(&processed, &ress,
                                     inFileNamesTable[i], dstFileName,
                                     compressionLevel, prefs);
    +        totalProcessed += processed;
         }
     
         /* Close & Free */
         LZ4IO_freeCResources(ress);
         free(dstFileName);
    +    LZ4IO_finalTimeDisplay(timeStart, cpuStart, totalProcessed);
     
         return missed_files;
     }
    @@ -861,10 +1579,10 @@ int LZ4IO_compressMultipleFilenames(
     /* ********************** LZ4 file-stream Decompression **************** */
     /* ********************************************************************* */
     
    -/* It's presumed that s points to a memory space of size >= 4 */
    -static unsigned LZ4IO_readLE32 (const void* s)
    +/* It's presumed that @p points to a memory space of size >= 4 */
    +static unsigned LZ4IO_readLE32 (const void* p)
     {
    -    const unsigned char* const srcPtr = (const unsigned char*)s;
    +    const unsigned char* const srcPtr = (const unsigned char*)p;
         unsigned value32 = srcPtr[0];
         value32 += (unsigned)srcPtr[1] <<  8;
         value32 += (unsigned)srcPtr[2] << 16;
    @@ -949,7 +1667,7 @@ static void LZ4IO_fwriteSparseEnd(FILE* file, unsigned storedSkips)
         if (storedSkips>0) {   /* implies sparseFileSupport>0 */
             const char lastZeroByte[1] = { 0 };
             if (UTIL_fseek(file, storedSkips-1, SEEK_CUR) != 0)
    -            END_PROCESS(68, "Final skip error (sparse file)\n");
    +            END_PROCESS(69, "Final skip error (sparse file)\n");
             if (fwrite(lastZeroByte, 1, 1, file) != 1)
                 END_PROCESS(69, "Write error : cannot write last zero\n");
         }
    @@ -958,6 +1676,152 @@ static void LZ4IO_fwriteSparseEnd(FILE* file, unsigned storedSkips)
     
     static unsigned g_magicRead = 0;   /* out-parameter of LZ4IO_decodeLegacyStream() */
     
    +#if LZ4IO_MULTITHREAD
    +
    +typedef struct {
    +    void* buffer;
    +    size_t size;
    +    FILE* f;
    +    int sparseEnable;
    +    unsigned* storedSkips;
    +    const unsigned long long* totalSize;
    +} ChunkToWrite;
    +
    +static void LZ4IO_writeDecodedChunk(void* arg)
    +{
    +    ChunkToWrite* const ctw = (ChunkToWrite*)arg;
    +    assert(ctw != NULL);
    +
    +    /* note: works because only 1 thread */
    +    *ctw->storedSkips = LZ4IO_fwriteSparse(ctw->f, ctw->buffer, ctw->size, ctw->sparseEnable, *ctw->storedSkips); /* success or die */
    +    DISPLAYUPDATE(2, "\rDecompressed : %u MiB  ", (unsigned)(ctw->totalSize[0] >>20));
    +
    +    /* clean up */
    +    free(ctw);
    +}
    +
    +typedef struct {
    +    void* inBuffer;
    +    size_t inSize;
    +    void* outBuffer;
    +    unsigned long long* totalSize;
    +    TPool* wPool;
    +    FILE* foutput;
    +    int sparseEnable;
    +    unsigned* storedSkips;
    +} LegacyBlockInput;
    +
    +static void LZ4IO_decompressBlockLegacy(void* arg)
    +{
    +    int decodedSize;
    +    LegacyBlockInput* const lbi = (LegacyBlockInput*)arg;
    +
    +    decodedSize = LZ4_decompress_safe((const char*)lbi->inBuffer, (char*)lbi->outBuffer, (int)lbi->inSize, LEGACY_BLOCKSIZE);
    +    if (decodedSize < 0) END_PROCESS(64, "Decoding Failed ! Corrupted input detected !");
    +    *lbi->totalSize += (unsigned long long)decodedSize; /* note: works because only 1 thread */
    +
    +    /* push to write thread */
    +    {   ChunkToWrite* const ctw = (ChunkToWrite*)malloc(sizeof(*ctw));
    +        if (ctw==NULL) {
    +            END_PROCESS(33, "Allocation error : can't describe new write job");
    +        }
    +        ctw->buffer = lbi->outBuffer;
    +        ctw->size = (size_t)decodedSize;
    +        ctw->f = lbi->foutput;
    +        ctw->sparseEnable = lbi->sparseEnable;
    +        ctw->storedSkips = lbi->storedSkips;
    +        ctw->totalSize = lbi->totalSize;
    +        TPool_submitJob(lbi->wPool, LZ4IO_writeDecodedChunk, ctw);
    +    }
    +
    +    /* clean up */
    +    free(lbi);
    +}
    +
    +static unsigned long long
    +LZ4IO_decodeLegacyStream(FILE* finput, FILE* foutput, const LZ4IO_prefs_t* prefs)
    +{
    +    unsigned long long streamSize = 0;
    +    unsigned storedSkips = 0;
    +
    +    TPool* const tPool = TPool_create(1, 1);
    +    TPool* const wPool = TPool_create(1, 1);
    +#define NB_BUFFSETS 4 /* 1 being read, 1 being processed, 1 being written, 1 being queued */
    +    void* inBuffs[NB_BUFFSETS];
    +    void* outBuffs[NB_BUFFSETS];
    +    int bSetNb;
    +
    +    if (tPool == NULL || wPool == NULL)
    +        END_PROCESS(21, "threadpool creation error ");
    +
    +    /* allocate buffers up front */
    +    for (bSetNb=0; bSetNb LZ4_COMPRESSBOUND(LEGACY_BLOCKSIZE)) {
    +            /* Cannot read next block : maybe new stream ? */
    +            g_magicRead = blockSize;
    +            break;
    +        }
    +
    +        /* Read Block */
    +        {   size_t const sizeCheck = fread(inBuffs[bSetNb], 1, blockSize, finput);
    +            if (sizeCheck != blockSize)
    +                END_PROCESS(63, "Read error : cannot access compressed block !");
    +            /* push to decoding thread */
    +            {   LegacyBlockInput* const lbi = (LegacyBlockInput*)malloc(sizeof(*lbi));
    +                if (lbi==NULL)
    +                    END_PROCESS(64, "Allocation error : not enough memory to allocate job descriptor");
    +                lbi->inBuffer = inBuffs[bSetNb];
    +                lbi->inSize = blockSize;
    +                lbi->outBuffer = outBuffs[bSetNb];
    +                lbi->wPool = wPool;
    +                lbi->totalSize = &streamSize;
    +                lbi->foutput = foutput;
    +                lbi->sparseEnable = prefs->sparseFileSupport;
    +                lbi->storedSkips = &storedSkips;
    +                TPool_submitJob(tPool, LZ4IO_decompressBlockLegacy, lbi);
    +            }
    +        }
    +    }
    +    if (ferror(finput)) END_PROCESS(65, "Read error : ferror");
    +
    +    /* Wait for all completion */
    +    TPool_jobsCompleted(tPool);
    +    TPool_jobsCompleted(wPool);
    +
    +    /* flush last zeroes */
    +    LZ4IO_fwriteSparseEnd(foutput, storedSkips);
    +
    +    /* Free */
    +    TPool_free(wPool);
    +    TPool_free(tPool);
    +    for (bSetNb=0; bSetNb LZ4_COMPRESSBOUND(LEGACY_BLOCKSIZE)) {
    @@ -987,16 +1852,16 @@ LZ4IO_decodeLegacyStream(FILE* finput, FILE* foutput, const LZ4IO_prefs_t* prefs
     
             /* Read Block */
             { size_t const sizeCheck = fread(in_buff, 1, blockSize, finput);
    -          if (sizeCheck != blockSize) END_PROCESS(53, "Read error : cannot access compressed block !"); }
    +          if (sizeCheck != blockSize) END_PROCESS(63, "Read error : cannot access compressed block !"); }
     
             /* Decode Block */
             {   int const decodeSize = LZ4_decompress_safe(in_buff, out_buff, (int)blockSize, LEGACY_BLOCKSIZE);
    -            if (decodeSize < 0) END_PROCESS(54, "Decoding Failed ! Corrupted input detected !");
    +            if (decodeSize < 0) END_PROCESS(64, "Decoding Failed ! Corrupted input detected !");
                 streamSize += (unsigned long long)decodeSize;
                 /* Write Block */
                 storedSkips = LZ4IO_fwriteSparse(foutput, out_buff, (size_t)decodeSize, prefs->sparseFileSupport, storedSkips); /* success or die */
         }   }
    -    if (ferror(finput)) END_PROCESS(55, "Read error : ferror");
    +    if (ferror(finput)) END_PROCESS(65, "Read error : ferror");
     
         LZ4IO_fwriteSparseEnd(foutput, storedSkips);
     
    @@ -1006,7 +1871,7 @@ LZ4IO_decodeLegacyStream(FILE* finput, FILE* foutput, const LZ4IO_prefs_t* prefs
     
         return streamSize;
     }
    -
    +#endif
     
     
     typedef struct {
    @@ -1064,6 +1929,271 @@ static void LZ4IO_freeDResources(dRess_t ress)
     }
     
     
    +#if LZ4IO_MULTITHREAD
    +
    +#define INBUFF_SIZE (4 MB)
    +#define OUTBUFF_SIZE (1 * INBUFF_SIZE)
    +#define OUTBUFF_QUEUE 1
    +#define PBUFFERS_NB (1 /* being decompressed */ + OUTBUFF_QUEUE + 1 /* being written to io */)
    +
    +typedef struct {
    +    void* ptr;
    +    size_t capacity;
    +    size_t size;
    +} Buffer;
    +
    +/* BufferPool:
    + * Based on ayncio property :
    + * all buffers are allocated and released in order,
    + * maximum nb of buffers limited by queues */
    +
    +typedef struct {
    +    Buffer buffers[PBUFFERS_NB];
    +    int availNext;
    +    int usedIdx;
    +} BufferPool;
    +
    +static void LZ4IO_freeBufferPool(BufferPool* bp)
    +{
    +    int i;
    +    if (bp==NULL) return;
    +    for (i=0; ibuffers[i].ptr);
    +    free(bp);
    +}
    +
    +static BufferPool* LZ4IO_createBufferPool(size_t bufSize)
    +{
    +    BufferPool* const bp = (BufferPool*)calloc(1, sizeof(*bp));
    +    int i;
    +    if (bp==NULL) return NULL;
    +    for (i=0; ibuffers[i].ptr = malloc(bufSize);
    +        if (bp->buffers[i].ptr == NULL) {
    +            LZ4IO_freeBufferPool(bp);
    +            return NULL;
    +        }
    +         bp->buffers[i].capacity = bufSize;
    +         bp->buffers[i].size = 0;
    +    }
    +    bp->availNext = 0;
    +    bp->usedIdx = 0;
    +    return bp;
    +}
    +
    +/* Note: Thread Sanitizer can be detected with below macro
    + * but it's not guaranteed (doesn't seem to work with clang) */
    +#ifdef __SANITIZE_THREAD__
    +# undef LZ4IO_NO_TSAN_ONLY
    +#endif
    +
    +static Buffer BufPool_getBuffer(BufferPool* bp)
    +{
    +    assert(bp != NULL);
    +#ifdef LZ4IO_NO_TSAN_ONLY
    +    /* The following assert() are susceptible to race conditions */
    +    assert(bp->availNext >= bp->usedIdx);
    +    assert(bp->availNext < bp->usedIdx + PBUFFERS_NB);
    +#endif
    +    {   int id = bp->availNext++ % PBUFFERS_NB;
    +        assert(bp->buffers[id].size == 0);
    +        return bp->buffers[id];
    +}   }
    +
    +void BufPool_releaseBuffer(BufferPool* bp, Buffer buf)
    +{
    +    assert(bp != NULL);
    +#ifdef LZ4IO_NO_TSAN_ONLY
    +    /* The following assert() is susceptible to race conditions */
    +    assert(bp->usedIdx < bp->availNext);
    +#endif
    +    {   int id = bp->usedIdx++ % PBUFFERS_NB;
    +        assert(bp->buffers[id].ptr == buf.ptr);
    +        bp->buffers[id].size = 0;
    +}   }
    +
    +typedef struct {
    +    Buffer bufOut;
    +    FILE* fOut;
    +    BufferPool* bp;
    +    int sparseEnable;
    +    unsigned* storedSkips;
    +    unsigned long long* totalSize;
    +} LZ4FChunkToWrite;
    +
    +static void LZ4IO_writeDecodedLZ4FChunk(void* arg)
    +{
    +    LZ4FChunkToWrite* const ctw = (LZ4FChunkToWrite*)arg;
    +    assert(ctw != NULL);
    +
    +    /* note: works because only 1 thread */
    +    *ctw->storedSkips = LZ4IO_fwriteSparse(ctw->fOut, ctw->bufOut.ptr, ctw->bufOut.size, ctw->sparseEnable, *ctw->storedSkips); /* success or die */
    +    *ctw->totalSize += (unsigned long long)ctw->bufOut.size; /* note: works because only 1 thread */
    +    DISPLAYUPDATE(2, "\rDecompressed : %u MiB  ", (unsigned)(ctw->totalSize[0] >> 20));
    +
    +    /* clean up */
    +    BufPool_releaseBuffer(ctw->bp, ctw->bufOut);
    +    free(ctw);
    +}
    +
    +typedef struct {
    +    LZ4F_dctx* dctx;
    +    const void* inBuffer;
    +    size_t inSize;
    +    const void* dictBuffer;
    +    size_t dictBufferSize;
    +    BufferPool* bp;
    +    unsigned long long* totalSize;
    +    LZ4F_errorCode_t* lastStatus;
    +    TPool* wPool;
    +    FILE* foutput;
    +    int sparseEnable;
    +    unsigned* storedSkips;
    +} LZ4FChunk;
    +
    +static void LZ4IO_decompressLZ4FChunk(void* arg)
    +{
    +    LZ4FChunk* const lz4fc = (LZ4FChunk*)arg;
    +    const char* inPtr = (const char*)lz4fc->inBuffer;
    +    size_t pos = 0;
    +
    +    while ((pos < lz4fc->inSize)) {  /* still to read */
    +        size_t remainingInSize = lz4fc->inSize - pos;
    +        Buffer b = BufPool_getBuffer(lz4fc->bp);
    +        if (b.capacity != OUTBUFF_SIZE)
    +            END_PROCESS(33, "Could not allocate output buffer!");
    +        assert(b.size == 0);
    +        b.size = b.capacity;
    +        {   size_t nextToLoad = LZ4F_decompress_usingDict(lz4fc->dctx,
    +                                b.ptr, &b.size,
    +                                inPtr + pos, &remainingInSize,
    +                                lz4fc->dictBuffer, lz4fc->dictBufferSize,
    +                                NULL);
    +            if (LZ4F_isError(nextToLoad))
    +                END_PROCESS(34, "Decompression error : %s", LZ4F_getErrorName(nextToLoad));
    +            *lz4fc->lastStatus = nextToLoad;
    +        }
    +        assert(remainingInSize <= lz4fc->inSize - pos);
    +        pos += remainingInSize;
    +        assert(b.size <= b.capacity);
    +
    +        /* push to write thread */
    +        {   LZ4FChunkToWrite* const ctw = (LZ4FChunkToWrite*)malloc(sizeof(*ctw));
    +            if (ctw==NULL) {
    +                END_PROCESS(35, "Allocation error : can't describe new write job");
    +            }
    +            ctw->bufOut = b;
    +            ctw->fOut = lz4fc->foutput;
    +            ctw->bp = lz4fc->bp;
    +            ctw->sparseEnable = lz4fc->sparseEnable;
    +            ctw->storedSkips = lz4fc->storedSkips;
    +            ctw->totalSize = lz4fc->totalSize;
    +            TPool_submitJob(lz4fc->wPool, LZ4IO_writeDecodedLZ4FChunk, ctw);
    +        }
    +    }
    +
    +    /* clean up */
    +    free(lz4fc);
    +}
    +
    +static unsigned long long
    +LZ4IO_decompressLZ4F(dRess_t ress,
    +                     FILE* const srcFile, FILE* const dstFile,
    +                     const LZ4IO_prefs_t* const prefs)
    +{
    +    unsigned long long filesize = 0;
    +    LZ4F_errorCode_t nextToLoad;
    +    LZ4F_errorCode_t lastStatus = 1;
    +    unsigned storedSkips = 0;
    +    LZ4F_decompressOptions_t const dOpt_skipCrc = { 0, 1, 0, 0 };
    +    const LZ4F_decompressOptions_t* const dOptPtr =
    +        ((prefs->blockChecksum==0) && (prefs->streamChecksum==0)) ?
    +        &dOpt_skipCrc : NULL;
    +    TPool* const tPool = TPool_create(1, 1);
    +    TPool* const wPool = TPool_create(1, 1);
    +    BufferPool* const bp = LZ4IO_createBufferPool(OUTBUFF_SIZE);
    +#define NB_BUFFSETS 4 /* 1 being read, 1 being processed, 1 being written, 1 being queued */
    +    void* inBuffs[NB_BUFFSETS];
    +    int bSetNb;
    +
    +    /* checks */
    +    if (tPool == NULL || wPool == NULL || bp==NULL)
    +        END_PROCESS(22, "threadpool creation error ");
    +
    +    /* allocate buffers up front */
    +    for (bSetNb=0; bSetNbdctx = ress.dCtx;
    +            lbi->inBuffer = inBuffs[bSetNb];
    +            lbi->inSize = readSize;
    +            lbi->dictBuffer = ress.dictBuffer;
    +            lbi->dictBufferSize = ress.dictBufferSize;
    +            lbi->bp = bp;
    +            lbi->wPool = wPool;
    +            lbi->totalSize = &filesize;
    +            lbi->lastStatus = &lastStatus;
    +            lbi->foutput = dstFile;
    +            lbi->sparseEnable = prefs->sparseFileSupport;
    +            lbi->storedSkips = &storedSkips;
    +            TPool_submitJob(tPool, LZ4IO_decompressLZ4FChunk, lbi);
    +        }
    +        if (readSize < INBUFF_SIZE) break;   /* likely reached end of stream */
    +    }
    +    assert(feof(srcFile));
    +
    +    /* Wait for all decompression completion */
    +    TPool_jobsCompleted(tPool);
    +
    +    /* flush */
    +    if (lastStatus != 0) {
    +        END_PROCESS(26, "LZ4F frame decoding could not complete: invalid frame");
    +    }
    +    TPool_jobsCompleted(wPool);
    +    if (!prefs->testMode) LZ4IO_fwriteSparseEnd(dstFile, storedSkips);
    +
    +    /* Clean */
    +    for (bSetNb=0; bSetNbtestMode) LZ4IO_fwriteSparseEnd(dstFile, storedSkips);
    -    if (nextToLoad!=0) END_PROCESS(68, "Unfinished stream");
    +    if (nextToLoad!=0)
    +        END_PROCESS(68, "Unfinished stream (nextToLoad=%u)", (unsigned)nextToLoad);
     
         return filesize;
     }
     
    +#endif /* LZ4IO_MULTITHREAD */
     
     /* LZ4IO_passThrough:
      * just output the same content as input, no decoding.
    @@ -1170,7 +2302,6 @@ LZ4IO_passThrough(FILE* finput, FILE* foutput,
      * read and forget from input.
     **/
     #define SKIP_BUFF_SIZE (16 KB)
    -#define MIN(a,b)   ( ((a)<(b)) ? (a) : (b) )
     static int skipStream(FILE* f, unsigned offset)
     {
         char buf[SKIP_BUFF_SIZE];
    @@ -1271,7 +2402,8 @@ selectDecoder(dRess_t ress,
     
     
     static int
    -LZ4IO_decompressSrcFile(dRess_t ress,
    +LZ4IO_decompressSrcFile(unsigned long long* outGenSize,
    +                        dRess_t ress,
                             const char* input_filename, const char* output_filename,
                             const LZ4IO_prefs_t* const prefs)
     {
    @@ -1302,7 +2434,8 @@ LZ4IO_decompressSrcFile(dRess_t ress,
     
         /* Final Status */
         DISPLAYLEVEL(2, "\r%79s\r", "");
    -    DISPLAYLEVEL(2, "%-20.20s : decoded %llu bytes \n", input_filename, filesize);
    +    DISPLAYLEVEL(2, "%-30.30s : decoded %llu bytes \n", input_filename, filesize);
    +    *outGenSize = filesize;
         (void)output_filename;
     
         return result;
    @@ -1310,8 +2443,10 @@ LZ4IO_decompressSrcFile(dRess_t ress,
     
     
     static int
    -LZ4IO_decompressDstFile(dRess_t ress,
    -                        const char* input_filename, const char* output_filename,
    +LZ4IO_decompressDstFile(unsigned long long* outGenSize,
    +                        dRess_t ress,
    +                        const char* input_filename,
    +                        const char* output_filename,
                             const LZ4IO_prefs_t* const prefs)
     {
         int result;
    @@ -1325,7 +2460,7 @@ LZ4IO_decompressDstFile(dRess_t ress,
             stat_result = 1;
     
         ress.dstFile = foutput;
    -    result = LZ4IO_decompressSrcFile(ress, input_filename, output_filename, prefs);
    +    result = LZ4IO_decompressSrcFile(outGenSize, ress, input_filename, output_filename, prefs);
     
         fclose(foutput);
     
    @@ -1348,16 +2483,15 @@ LZ4IO_decompressDstFile(dRess_t ress,
     int LZ4IO_decompressFilename(const char* input_filename, const char* output_filename, const LZ4IO_prefs_t* prefs)
     {
         dRess_t const ress = LZ4IO_createDResources(prefs);
    -    clock_t const start = clock();
    -
    -    int const status = LZ4IO_decompressDstFile(ress, input_filename, output_filename, prefs);
    -
    -    clock_t const end = clock();
    -    double const seconds = (double)(end - start) / CLOCKS_PER_SEC;
    -    DISPLAYLEVEL(4, "Done in %.2f sec  \n", seconds);
    +    TIME_t const timeStart = TIME_getTime();
    +    clock_t const cpuStart = clock();
    +    unsigned long long processed = 0;
     
    +    int const errStat = LZ4IO_decompressDstFile(&processed, ress, input_filename, output_filename, prefs);
    +    if (errStat)
    +        LZ4IO_finalTimeDisplay(timeStart, cpuStart, processed);
         LZ4IO_freeDResources(ress);
    -    return status;
    +    return errStat;
     }
     
     
    @@ -1367,12 +2501,15 @@ int LZ4IO_decompressMultipleFilenames(
                                 const LZ4IO_prefs_t* prefs)
     {
         int i;
    +    unsigned long long totalProcessed = 0;
         int skippedFiles = 0;
         int missingFiles = 0;
         char* outFileName = (char*)malloc(FNSPACE);
         size_t ofnSize = FNSPACE;
         size_t const suffixSize = strlen(suffix);
         dRess_t ress = LZ4IO_createDResources(prefs);
    +    TIME_t timeStart = TIME_getTime();
    +    clock_t cpuStart = clock();
     
         if (outFileName==NULL) END_PROCESS(70, "Memory allocation error");
         if (prefs->blockChecksum==0 && prefs->streamChecksum==0) {
    @@ -1381,10 +2518,12 @@ int LZ4IO_decompressMultipleFilenames(
         ress.dstFile = LZ4IO_openDstFile(stdoutmark, prefs);
     
         for (i=0; iframeCount + 1,
                                                  LZ4IO_frameTypeNames[frameInfo.frameType],
                                                  bTypeBuffer,
                                                  frameInfo.lz4FrameInfo.contentChecksumFlag ? "XXH32" : "-");
                                     if (frameInfo.lz4FrameInfo.contentSize) {
    -                                    {   double const ratio = (double)(totalBlocksSize + hSize) / frameInfo.lz4FrameInfo.contentSize * 100;
    -                                        DISPLAYLEVEL(3, " %20llu %20llu %9.2f%%\n",
    -                                                     totalBlocksSize + hSize,
    -                                                     frameInfo.lz4FrameInfo.contentSize,
    -                                                     ratio);
    -                                    }
    +                                    double const ratio = (double)(totalBlocksSize + hSize) / (double)frameInfo.lz4FrameInfo.contentSize * 100;
    +                                    if (displayNow) DISPLAYOUT(" %20llu %20llu %9.2f%%\n",
    +                                                    totalBlocksSize + hSize,
    +                                                    frameInfo.lz4FrameInfo.contentSize,
    +                                                    ratio);
                                         /* Now we've consumed frameInfo we can use it to store the total contentSize */
                                         frameInfo.lz4FrameInfo.contentSize += cfinfo->frameSummary.lz4FrameInfo.contentSize;
                                     }
                                     else {
    -                                    DISPLAYLEVEL(3, " %20llu %20s %9s \n", totalBlocksSize + hSize, "-", "-");
    +                                    if (displayNow) DISPLAYOUT(" %20llu %20s %9s \n", totalBlocksSize + hSize, "-", "-");
                                         cfinfo->allContentSize = 0;
                                     }
                                     result = LZ4IO_LZ4F_OK;
    @@ -1653,7 +2793,7 @@ LZ4IO_getCompressedFileInfo(LZ4IO_cFileInfo_t* cfinfo, const char* input_filenam
                         break;
                     }
                     if (totalBlocksSize) {
    -                    DISPLAYLEVEL(3, "    %6llu %14s %5s %8s %20llu %20s %9s\n",
    +                    if (displayNow) DISPLAYOUT("    %6llu %14s %5s %8s %20llu %20s %9s\n",
                                      cfinfo->frameCount + 1,
                                      LZ4IO_frameTypeNames[frameInfo.frameType],
                                      "-", "-",
    @@ -1675,7 +2815,7 @@ LZ4IO_getCompressedFileInfo(LZ4IO_cFileInfo_t* cfinfo, const char* input_filenam
                     int const errorNb = fseek_u32(finput, size, SEEK_CUR);
                     if (errorNb != 0)
                         END_PROCESS(43, "Stream error : cannot skip skippable area");
    -                DISPLAYLEVEL(3, "    %6llu %14s %5s %8s %20u %20s %9s\n",
    +                if (displayNow) DISPLAYOUT("    %6llu %14s %5s %8s %20u %20s %9s\n",
                                  cfinfo->frameCount + 1,
                                  "SkippableFrame",
                                  "-", "-", size + 8, "-", "-");
    @@ -1707,7 +2847,7 @@ int LZ4IO_displayCompressedFilesInfo(const char** inFileNames, size_t ifnIdx)
         int result = 0;
         size_t idx = 0;
         if (g_displayLevel < 3) {
    -        DISPLAYOUT("%10s %14s %5s %11s %13s %9s   %s\n",
    +        DISPLAYOUT("%10s %14s %5s %11s %13s %8s   %s\n",
                     "Frames", "Type", "Block", "Compressed", "Uncompressed", "Ratio", "Filename");
         }
         for (; idx < ifnIdx; idx++) {
    @@ -1718,34 +2858,39 @@ int LZ4IO_displayCompressedFilesInfo(const char** inFileNames, size_t ifnIdx)
                 DISPLAYLEVEL(1, "lz4: %s is not a regular file \n", inFileNames[idx]);
                 return 1;
             }
    -        DISPLAYLEVEL(3, "%s(%llu/%llu)\n", cfinfo.fileName, (unsigned long long)idx + 1, (unsigned  long long)ifnIdx);
    -        DISPLAYLEVEL(3, "    %6s %14s %5s %8s %20s %20s %9s\n",
    -                     "Frame", "Type", "Block", "Checksum", "Compressed", "Uncompressed", "Ratio")
    -        {   LZ4IO_infoResult const op_result = LZ4IO_getCompressedFileInfo(&cfinfo, inFileNames[idx]);
    +        if (g_displayLevel >= 3) {
    +            /* verbose mode */
    +            DISPLAYOUT("%s(%llu/%llu)\n", cfinfo.fileName, (unsigned long long)idx + 1, (unsigned  long long)ifnIdx);
    +            DISPLAYOUT("    %6s %14s %5s %8s %20s %20s %9s\n",
    +                        "Frame", "Type", "Block", "Checksum", "Compressed", "Uncompressed", "Ratio");
    +        }
    +        {   LZ4IO_infoResult const op_result = LZ4IO_getCompressedFileInfo(&cfinfo, inFileNames[idx], g_displayLevel >= 3);
                 if (op_result != LZ4IO_LZ4F_OK) {
                     assert(op_result == LZ4IO_format_not_known);
                     DISPLAYLEVEL(1, "lz4: %s: File format not recognized \n", inFileNames[idx]);
                     return 1;
             }   }
    -        DISPLAYLEVEL(3, "\n");
    +        if (g_displayLevel >= 3) {
    +            DISPLAYOUT("\n");
    +        }
             if (g_displayLevel < 3) {
    -            /* Display Summary */
    -            {   char buffers[3][10];
    -                DISPLAYOUT("%10llu %14s %5s %11s %13s ",
    -                        cfinfo.frameCount,
    -                        cfinfo.eqFrameTypes ? LZ4IO_frameTypeNames[cfinfo.frameSummary.frameType] : "-" ,
    -                        cfinfo.eqBlockTypes ? LZ4IO_blockTypeID(cfinfo.frameSummary.lz4FrameInfo.blockSizeID,
    -                                                                cfinfo.frameSummary.lz4FrameInfo.blockMode, buffers[0]) : "-",
    -                        LZ4IO_toHuman((long double)cfinfo.fileSize, buffers[1]),
    -                        cfinfo.allContentSize ? LZ4IO_toHuman((long double)cfinfo.frameSummary.lz4FrameInfo.contentSize, buffers[2]) : "-");
    -                if (cfinfo.allContentSize) {
    -                    double const ratio = (double)cfinfo.fileSize / cfinfo.frameSummary.lz4FrameInfo.contentSize * 100;
    -                    DISPLAYOUT("%9.2f%%  %s \n", ratio, cfinfo.fileName);
    -                } else {
    -                    DISPLAYOUT("%9s   %s\n",
    -                            "-",
    -                            cfinfo.fileName);
    -        }   }   }  /* if (g_displayLevel < 3) */
    +            /* Display summary */
    +            char buffers[3][10];
    +            DISPLAYOUT("%10llu %14s %5s %11s %13s ",
    +                    cfinfo.frameCount,
    +                    cfinfo.eqFrameTypes ? LZ4IO_frameTypeNames[cfinfo.frameSummary.frameType] : "-" ,
    +                    cfinfo.eqBlockTypes ? LZ4IO_blockTypeID(cfinfo.frameSummary.lz4FrameInfo.blockSizeID,
    +                                                            cfinfo.frameSummary.lz4FrameInfo.blockMode, buffers[0]) : "-",
    +                    LZ4IO_toHuman((long double)cfinfo.fileSize, buffers[1]),
    +                    cfinfo.allContentSize ? LZ4IO_toHuman((long double)cfinfo.frameSummary.lz4FrameInfo.contentSize, buffers[2]) : "-");
    +            if (cfinfo.allContentSize) {
    +                double const ratio = (double)cfinfo.fileSize / (double)cfinfo.frameSummary.lz4FrameInfo.contentSize * 100;
    +                DISPLAYOUT("%8.2f%%  %s \n", ratio, cfinfo.fileName);
    +            } else {
    +                DISPLAYOUT("%8s   %s\n",
    +                        "-",
    +                        cfinfo.fileName);
    +        }   }  /* if (g_displayLevel < 3) */
         }  /* for (; idx < ifnIdx; idx++) */
     
         return result;
    diff --git a/programs/lz4io.h b/programs/lz4io.h
    index 0cfb1d20c1c2f2af1af5bf90497a2fc52f04b8c8..e987d0b84cd897e7ab6ae04f64e19ebc184b293f 100644
    --- a/programs/lz4io.h
    +++ b/programs/lz4io.h
    @@ -1,6 +1,6 @@
     /*
       LZ4io.h - LZ4 File/Stream Interface
    -  Copyright (C) Yann Collet 2011-2020
    +  Copyright (C) Yann Collet 2011-2023
       GPL v2 License
     
       This program is free software; you can redistribute it and/or modify
    @@ -58,9 +58,9 @@ LZ4IO_prefs_t* LZ4IO_defaultPreferences(void);
     void LZ4IO_freePreferences(LZ4IO_prefs_t* prefs);
     
     
    -/* ************************************************** */
    -/* ****************** Functions ********************* */
    -/* ************************************************** */
    +/* *************************************************** */
    +/* ****************** Processing ********************* */
    +/* *************************************************** */
     
     /* if output_filename == stdoutmark, writes to stdout */
     int LZ4IO_compressFilename(const char* input_filename, const char* output_filename, int compressionlevel, const LZ4IO_prefs_t* prefs);
    @@ -75,6 +75,9 @@ int LZ4IO_decompressMultipleFilenames(const char** inFileNamesTable, int ifntSiz
     /* ****************** Parameters ******************** */
     /* ************************************************** */
     
    +int LZ4IO_setNbWorkers(LZ4IO_prefs_t* const prefs, int nbWorkers);
    +int LZ4IO_defaultNbWorkers(void);
    +
     int LZ4IO_setDictionaryFilename(LZ4IO_prefs_t* const prefs, const char* dictionaryFilename);
     
     /* Default setting : passThrough = 0;
    diff --git a/programs/platform.h b/programs/platform.h
    index 43a171bf91c8a0b5ee8aad1c1d0f49621660fedb..eece7e3d18bf089b541625800c2a15697ce8f7ce 100644
    --- a/programs/platform.h
    +++ b/programs/platform.h
    @@ -48,7 +48,9 @@ extern "C" {
       || defined __x86_64__s || defined _M_X64                                                                          /* x86 64-bit */    \
       || defined __arm64__ || defined __aarch64__ || defined __ARM64_ARCH_8__                                           /* ARM 64-bit */    \
       || (defined __mips  && (__mips == 64 || __mips == 4 || __mips == 3))                                              /* MIPS 64-bit */   \
    -  || defined _LP64 || defined __LP64__ /* NetBSD, OpenBSD */ || defined __64BIT__ /* AIX */ || defined _ADDR64 /* Cray */               \
    +  || defined __loongarch64                                                                                          /* LoongArch 64-bit */  \
    +  || (defined __riscv && defined __riscv_xlen && (__riscv_xlen == 64))                                              /* Riscv 64-bit */  \
    +  || defined _LP64 || defined __LP64__ /* NetBSD, OpenBSD */ || defined __64BIT__ /* AIX */ || defined _ADDR64      /* Cray */               \
       || (defined __SIZEOF_POINTER__ && __SIZEOF_POINTER__ == 8) /* gcc */
     #  if !defined(__64BIT__)
     #    define __64BIT__  1
    diff --git a/programs/threadpool.c b/programs/threadpool.c
    new file mode 100644
    index 0000000000000000000000000000000000000000..c58f1699bb9f6af89b5b2b611ce5b8e539bf95bc
    --- /dev/null
    +++ b/programs/threadpool.c
    @@ -0,0 +1,430 @@
    +/*
    +  threadpool.h - part of lz4 project
    +  Copyright (C) Yann Collet 2023
    +  GPL v2 License
    +
    +  This program is free software; you can redistribute it and/or modify
    +  it under the terms of the GNU General Public License as published by
    +  the Free Software Foundation; either version 2 of the License, or
    +  (at your option) any later version.
    +
    +  This program is distributed in the hope that it will be useful,
    +  but WITHOUT ANY WARRANTY; without even the implied warranty of
    +  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    +  GNU General Public License for more details.
    +
    +  You should have received a copy of the GNU General Public License along
    +  with this program; if not, write to the Free Software Foundation, Inc.,
    +  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
    +
    +  You can contact the author at :
    +  - LZ4 source repository : https://github.com/lz4/lz4
    +  - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
    +*/
    +
    +
    +/* ======   Dependencies   ======= */
    +#include 
    +#include "lz4conf.h"  /* LZ4IO_MULTITHREAD */
    +#include "threadpool.h"
    +
    +
    +/* ======   Compiler specifics   ====== */
    +#if defined(_MSC_VER)
    +#  pragma warning(disable : 4204)        /* disable: C4204: non-constant aggregate initializer */
    +#endif
    +
    +#if !LZ4IO_MULTITHREAD
    +
    +/* ===================================================== */
    +/* Backup implementation with no multi-threading support */
    +/* ===================================================== */
    +
    +/* Non-zero size, to ensure g_poolCtx != NULL */
    +struct TPool_s {
    +    int dummy;
    +};
    +static TPool g_poolCtx;
    +
    +TPool* TPool_create(int numThreads, int queueSize) {
    +    (void)numThreads;
    +    (void)queueSize;
    +    return &g_poolCtx;
    +}
    +
    +void TPool_free(TPool* ctx) {
    +    assert(!ctx || ctx == &g_poolCtx);
    +    (void)ctx;
    +}
    +
    +void TPool_submitJob(TPool* ctx, void (*job_function)(void*), void* arg) {
    +    (void)ctx;
    +    job_function(arg);
    +}
    +
    +void TPool_jobsCompleted(TPool* ctx) {
    +    assert(!ctx || ctx == &g_poolCtx);
    +    (void)ctx;
    +}
    +
    +
    +#elif defined(_WIN32)
    +
    +/* Window TPool implementation using Completion Ports */
    +#include 
    +
    +typedef struct TPool_s {
    +    HANDLE completionPort;
    +    HANDLE* workerThreads;
    +    int nbWorkers;
    +    int queueSize;
    +    LONG nbPendingJobs;
    +    HANDLE jobSlotAvail;  /* For queue size control */
    +    HANDLE allJobsCompleted; /* Event */
    +} TPool;
    +
    +void TPool_free(TPool* pool)
    +{
    +    if (!pool) return;
    +
    +    /* Signal workers to exit by posting NULL completions */
    +    {   int i;
    +        for (i = 0; i < pool->nbWorkers; i++) {
    +            PostQueuedCompletionStatus(pool->completionPort, 0, 0, NULL);
    +        }
    +    }
    +
    +    /* Wait for worker threads to finish */
    +    WaitForMultipleObjects(pool->nbWorkers, pool->workerThreads, TRUE, INFINITE);
    +
    +    /* Close thread handles and completion port */
    +    {   int i;
    +        for (i = 0; i < pool->nbWorkers; i++) {
    +            CloseHandle(pool->workerThreads[i]);
    +        }
    +    }
    +    free(pool->workerThreads);
    +    CloseHandle(pool->completionPort);
    +
    +    /* Clean up synchronization objects */
    +    CloseHandle(pool->jobSlotAvail);
    +    CloseHandle(pool->allJobsCompleted);
    +
    +    free(pool);
    +}
    +
    +static DWORD WINAPI WorkerThread(LPVOID lpParameter)
    +{
    +    TPool* const pool = (TPool*)lpParameter;
    +    DWORD bytesTransferred;
    +    ULONG_PTR completionKey;
    +    LPOVERLAPPED overlapped;
    +
    +    while (GetQueuedCompletionStatus(pool->completionPort,
    +                                    &bytesTransferred, &completionKey,
    +                                    &overlapped, INFINITE)) {
    +
    +        /* End signal */
    +        if (overlapped == NULL) { break; }
    +
    +        /* Execute job */
    +        ((void (*)(void*))completionKey)(overlapped);
    +
    +        /* Signal job completion */
    +        if (InterlockedDecrement(&pool->nbPendingJobs) == 0) {
    +            SetEvent(pool->allJobsCompleted);
    +        }
    +        ReleaseSemaphore(pool->jobSlotAvail, 1, NULL);
    +    }
    +
    +    return 0;
    +}
    +
    +TPool* TPool_create(int nbWorkers, int queueSize)
    +{
    +    TPool* pool;
    +
    +    /* parameters sanitization */
    +    if (nbWorkers <= 0 || queueSize <= 0) return NULL;
    +    if (nbWorkers>LZ4_NBWORKERS_MAX) nbWorkers=LZ4_NBWORKERS_MAX;
    +
    +    pool = calloc(1, sizeof(TPool));
    +    if (!pool) return NULL;
    +
    +    /* Create completion port */
    +    pool->completionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, nbWorkers);
    +    if (!pool->completionPort) { goto _cleanup; }
    +
    +    /* Create worker threads */
    +    pool->nbWorkers = nbWorkers;
    +    pool->workerThreads = (HANDLE*)malloc(sizeof(HANDLE) * nbWorkers);
    +    if (pool->workerThreads == NULL) { goto _cleanup; }
    +
    +    {   int i;
    +        for (i = 0; i < nbWorkers; i++) {
    +            pool->workerThreads[i] = CreateThread(NULL, 0, WorkerThread, pool, 0, NULL);
    +            if (!pool->workerThreads[i]) { goto _cleanup; }
    +        }
    +    }
    +
    +    /* Initialize sync objects members */
    +    pool->queueSize = queueSize;
    +    pool->nbPendingJobs = 0;
    +
    +    pool->jobSlotAvail = CreateSemaphore(NULL, queueSize+nbWorkers, queueSize+nbWorkers, NULL);
    +    if (!pool->jobSlotAvail) { goto _cleanup; }
    +
    +    pool->allJobsCompleted = CreateEvent(NULL, FALSE, FALSE, NULL);
    +    if (!pool->allJobsCompleted) { goto _cleanup; }
    +
    +    return pool;
    +
    +_cleanup:
    +    TPool_free(pool);
    +    return NULL;
    +}
    +
    +
    +void TPool_submitJob(TPool* pool, void (*job_function)(void*), void* arg)
    +{
    +    assert(pool);
    +
    +    /* Atomically increment pending jobs and check for overflow */
    +    WaitForSingleObject(pool->jobSlotAvail, INFINITE);
    +    ResetEvent(pool->allJobsCompleted);
    +    InterlockedIncrement(&pool->nbPendingJobs);
    +
    +    /* Post the job directly to the completion port */
    +    PostQueuedCompletionStatus(pool->completionPort,
    +                               0, /* Bytes transferred not used */
    +                               (ULONG_PTR)job_function, /* Store function pointer in completionKey */
    +                               (LPOVERLAPPED)arg);      /* Store argument in overlapped */
    +}
    +
    +void TPool_jobsCompleted(TPool* pool)
    +{
    +    assert(pool);
    +    WaitForSingleObject(pool->allJobsCompleted, INFINITE);
    +}
    +
    +#else
    +
    +/* pthread availability assumed */
    +#include   /* malloc, free */
    +#include  /* pthread_* */
    +
    +/* A job is just a function with an opaque argument */
    +typedef struct TPool_job_s {
    +    void (*job_function)(void*);
    +    void *arg;
    +} TPool_job;
    +
    +struct TPool_s {
    +    pthread_t* threads;
    +    size_t threadCapacity;
    +    size_t threadLimit;
    +
    +    /* The queue is a circular buffer */
    +    TPool_job* queue;
    +    size_t queueHead;
    +    size_t queueTail;
    +    size_t queueSize;
    +
    +    /* The number of threads working on jobs */
    +    size_t numThreadsBusy;
    +    /* Indicates if the queue is empty */
    +    int queueEmpty;
    +
    +    /* The mutex protects the queue */
    +    pthread_mutex_t queueMutex;
    +    /* Condition variable for pushers to wait on when the queue is full */
    +    pthread_cond_t queuePushCond;
    +    /* Condition variables for poppers to wait on when the queue is empty */
    +    pthread_cond_t queuePopCond;
    +    /* Indicates if the queue is shutting down */
    +    int shutdown;
    +};
    +
    +static void TPool_shutdown(TPool* ctx);
    +
    +void TPool_free(TPool* ctx) {
    +    if (!ctx) { return; }
    +    TPool_shutdown(ctx);
    +    pthread_mutex_destroy(&ctx->queueMutex);
    +    pthread_cond_destroy(&ctx->queuePushCond);
    +    pthread_cond_destroy(&ctx->queuePopCond);
    +    free(ctx->queue);
    +    free(ctx->threads);
    +    free(ctx);
    +}
    +
    +static void* TPool_thread(void* opaque);
    +
    +TPool* TPool_create(int nbThreads, int queueSize)
    +{
    +    TPool* ctx;
    +    /* Check parameters */
    +    if (nbThreads<1 || queueSize<1) { return NULL; }
    +    /* Allocate the context and zero initialize */
    +    ctx = (TPool*)calloc(1, sizeof(TPool));
    +    if (!ctx) { return NULL; }
    +    /* init pthread variables */
    +    {   int error = 0;
    +        error |= pthread_mutex_init(&ctx->queueMutex, NULL);
    +        error |= pthread_cond_init(&ctx->queuePushCond, NULL);
    +        error |= pthread_cond_init(&ctx->queuePopCond, NULL);
    +        if (error) { TPool_free(ctx); return NULL; }
    +    }
    +    /* Initialize the job queue.
    +     * It needs one extra space since one space is wasted to differentiate
    +     * empty and full queues.
    +     */
    +    ctx->queueSize = (size_t)queueSize + 1;
    +    ctx->queue = (TPool_job*)calloc(1, ctx->queueSize * sizeof(TPool_job));
    +    if (ctx->queue == NULL) {
    +        TPool_free(ctx);
    +        return NULL;
    +    }
    +    ctx->queueHead = 0;
    +    ctx->queueTail = 0;
    +    ctx->numThreadsBusy = 0;
    +    ctx->queueEmpty = 1;
    +    ctx->shutdown = 0;
    +    /* Allocate space for the thread handles */
    +    ctx->threads = (pthread_t*)calloc(1, (size_t)nbThreads * sizeof(pthread_t));
    +    if (ctx->threads == NULL) {
    +        TPool_free(ctx);
    +        return NULL;
    +    }
    +    ctx->threadCapacity = 0;
    +    /* Initialize the threads */
    +    {   int i;
    +        for (i = 0; i < nbThreads; ++i) {
    +            if (pthread_create(&ctx->threads[i], NULL, &TPool_thread, ctx)) {
    +                ctx->threadCapacity = (size_t)i;
    +                TPool_free(ctx);
    +                return NULL;
    +        }   }
    +        ctx->threadCapacity = (size_t)nbThreads;
    +        ctx->threadLimit = (size_t)nbThreads;
    +    }
    +    return ctx;
    +}
    +
    +/* TPool_thread() :
    + * Work thread for the thread pool.
    + * Waits for jobs and executes them.
    + * @returns : NULL on failure else non-null.
    + */
    +static void* TPool_thread(void* opaque) {
    +    TPool* const ctx = (TPool*)opaque;
    +    if (!ctx) { return NULL; }
    +    for (;;) {
    +        /* Lock the mutex and wait for a non-empty queue or until shutdown */
    +        pthread_mutex_lock(&ctx->queueMutex);
    +
    +        while ( ctx->queueEmpty
    +            || (ctx->numThreadsBusy >= ctx->threadLimit) ) {
    +            if (ctx->shutdown) {
    +                /* even if !queueEmpty, (possible if numThreadsBusy >= threadLimit),
    +                 * a few threads will be shutdown while !queueEmpty,
    +                 * but enough threads will remain active to finish the queue */
    +                pthread_mutex_unlock(&ctx->queueMutex);
    +                return opaque;
    +            }
    +            pthread_cond_wait(&ctx->queuePopCond, &ctx->queueMutex);
    +        }
    +        /* Pop a job off the queue */
    +        {   TPool_job const job = ctx->queue[ctx->queueHead];
    +            ctx->queueHead = (ctx->queueHead + 1) % ctx->queueSize;
    +            ctx->numThreadsBusy++;
    +            ctx->queueEmpty = (ctx->queueHead == ctx->queueTail);
    +            /* Unlock the mutex, signal a pusher, and run the job */
    +            pthread_cond_signal(&ctx->queuePushCond);
    +            pthread_mutex_unlock(&ctx->queueMutex);
    +
    +            job.job_function(job.arg);
    +
    +            /* If the intended queue size was 0, signal after finishing job */
    +            pthread_mutex_lock(&ctx->queueMutex);
    +            ctx->numThreadsBusy--;
    +            pthread_cond_signal(&ctx->queuePushCond);
    +            pthread_mutex_unlock(&ctx->queueMutex);
    +        }
    +    }  /* for (;;) */
    +    assert(0);  /* Unreachable */
    +}
    +
    +/*! TPool_shutdown() :
    +    Shutdown the queue, wake any sleeping threads, and join all of the threads.
    +*/
    +static void TPool_shutdown(TPool* ctx) {
    +    /* Shut down the queue */
    +    pthread_mutex_lock(&ctx->queueMutex);
    +    ctx->shutdown = 1;
    +    pthread_mutex_unlock(&ctx->queueMutex);
    +    /* Wake up sleeping threads */
    +    pthread_cond_broadcast(&ctx->queuePushCond);
    +    pthread_cond_broadcast(&ctx->queuePopCond);
    +    /* Join all of the threads */
    +    {   size_t i;
    +        for (i = 0; i < ctx->threadCapacity; ++i) {
    +            pthread_join(ctx->threads[i], NULL);  /* note : could fail */
    +    }   }
    +}
    +
    +
    +/*! TPool_jobsCompleted() :
    + *  Waits for all queued jobs to finish executing.
    + */
    +void TPool_jobsCompleted(TPool* ctx){
    +    pthread_mutex_lock(&ctx->queueMutex);
    +    while(!ctx->queueEmpty || ctx->numThreadsBusy > 0) {
    +        pthread_cond_wait(&ctx->queuePushCond, &ctx->queueMutex);
    +    }
    +    pthread_mutex_unlock(&ctx->queueMutex);
    +}
    +
    +/**
    + * Returns 1 if the queue is full and 0 otherwise.
    + *
    + * When queueSize is 1 (pool was created with an intended queueSize of 0),
    + * then a queue is empty if there is a thread free _and_ no job is waiting.
    + */
    +static int isQueueFull(TPool const* ctx) {
    +    if (ctx->queueSize > 1) {
    +        return ctx->queueHead == ((ctx->queueTail + 1) % ctx->queueSize);
    +    } else {
    +        return (ctx->numThreadsBusy == ctx->threadLimit) ||
    +               !ctx->queueEmpty;
    +    }
    +}
    +
    +static void
    +TPool_submitJob_internal(TPool* ctx, void (*job_function)(void*), void *arg)
    +{
    +    TPool_job job;
    +    job.job_function = job_function;
    +    job.arg = arg;
    +    assert(ctx != NULL);
    +    if (ctx->shutdown) return;
    +
    +    ctx->queueEmpty = 0;
    +    ctx->queue[ctx->queueTail] = job;
    +    ctx->queueTail = (ctx->queueTail + 1) % ctx->queueSize;
    +    pthread_cond_signal(&ctx->queuePopCond);
    +}
    +
    +void TPool_submitJob(TPool* ctx, void (*job_function)(void*), void* arg)
    +{
    +    assert(ctx != NULL);
    +    pthread_mutex_lock(&ctx->queueMutex);
    +    /* Wait until there is space in the queue for the new job */
    +    while (isQueueFull(ctx) && (!ctx->shutdown)) {
    +        pthread_cond_wait(&ctx->queuePushCond, &ctx->queueMutex);
    +    }
    +    TPool_submitJob_internal(ctx, job_function, arg);
    +    pthread_mutex_unlock(&ctx->queueMutex);
    +}
    +
    +#endif  /* LZ4IO_NO_MT */
    diff --git a/programs/threadpool.h b/programs/threadpool.h
    new file mode 100644
    index 0000000000000000000000000000000000000000..5ea121d876b514c7d4a8120bd40e0c4ff9469c3e
    --- /dev/null
    +++ b/programs/threadpool.h
    @@ -0,0 +1,68 @@
    +/*
    +  threadpool.h - part of lz4 project
    +  Copyright (C) Yann Collet 2023
    +  GPL v2 License
    +
    +  This program is free software; you can redistribute it and/or modify
    +  it under the terms of the GNU General Public License as published by
    +  the Free Software Foundation; either version 2 of the License, or
    +  (at your option) any later version.
    +
    +  This program is distributed in the hope that it will be useful,
    +  but WITHOUT ANY WARRANTY; without even the implied warranty of
    +  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    +  GNU General Public License for more details.
    +
    +  You should have received a copy of the GNU General Public License along
    +  with this program; if not, write to the Free Software Foundation, Inc.,
    +  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
    +
    +  You can contact the author at :
    +  - LZ4 source repository : https://github.com/lz4/lz4
    +  - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
    +*/
    +
    +#ifndef THREADPOOL_H
    +#define THREADPOOL_H
    +
    +#if defined (__cplusplus)
    +extern "C" {
    +#endif
    +
    +typedef struct TPool_s TPool;
    +
    +/*! TPool_create() :
    + *  Create a thread pool with at most @nbThreads.
    + * @nbThreads must be at least 1.
    + * @queueSize is the maximum number of pending jobs before blocking.
    + * @return : TPool* pointer on success, else NULL.
    +*/
    +TPool* TPool_create(int nbThreads, int queueSize);
    +
    +/*! TPool_free() :
    + *  Free a thread pool returned by TPool_create().
    + *  Waits for the completion of running jobs before freeing resources.
    + */
    +void TPool_free(TPool* ctx);
    +
    +/*! TPool_submitJob() :
    + *  Add @job_function(arg) to the thread pool.
    + * @ctx must be valid.
    + *  Invocation can block if queue is full.
    + *  Note: Ensure @arg's lifetime extends until @job_function completes.
    + *  Alternatively, @arg's lifetime must be managed by @job_function.
    + */
    +void TPool_submitJob(TPool* ctx, void (*job_function)(void*), void* arg);
    +
    +/*! TPool_jobsCompleted() :
    + *  Blocks until all queued jobs are completed.
    + */
    +void TPool_jobsCompleted(TPool* ctx);
    +
    +
    +
    +#if defined (__cplusplus)
    +}
    +#endif
    +
    +#endif /* THREADPOOL_H */
    diff --git a/programs/timefn.c b/programs/timefn.c
    new file mode 100644
    index 0000000000000000000000000000000000000000..ef2e238956249a3adb0c0a3d406c614b2883b0dc
    --- /dev/null
    +++ b/programs/timefn.c
    @@ -0,0 +1,175 @@
    +/*
    +  timefn.c - portable time measurement functions
    +  Copyright (C) Yann Collet 2023
    +
    +  GPL v2 License
    +
    +  This program is free software; you can redistribute it and/or modify
    +  it under the terms of the GNU General Public License as published by
    +  the Free Software Foundation; either version 2 of the License, or
    +  (at your option) any later version.
    +
    +  This program is distributed in the hope that it will be useful,
    +  but WITHOUT ANY WARRANTY; without even the implied warranty of
    +  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    +  GNU General Public License for more details.
    +
    +  You should have received a copy of the GNU General Public License along
    +  with this program; if not, write to the Free Software Foundation, Inc.,
    +  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
    +
    +  You can contact the author at :
    +  - LZ4 source repository : https://github.com/lz4/lz4
    +  - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
    +*/
    +
    +/* ===  Dependencies  === */
    +
    +#include "timefn.h"
    +#include  /* CLOCK_MONOTONIC, TIME_UTC */
    +
    +/*-****************************************
    + *  Time functions
    + ******************************************/
    +
    +#if defined(_WIN32) /* Windows */
    +
    +#    include    /* perror */
    +#    include   /* abort */
    +#    include  /* LARGE_INTEGER */
    +
    +TIME_t TIME_getTime(void)
    +{
    +    static LARGE_INTEGER ticksPerSecond;
    +    static int init = 0;
    +    if (!init) {
    +        if (!QueryPerformanceFrequency(&ticksPerSecond)) {
    +            perror("timefn::QueryPerformanceFrequency");
    +            abort();
    +        }
    +        init = 1;
    +    }
    +    {
    +        TIME_t r;
    +        LARGE_INTEGER x;
    +        QueryPerformanceCounter(&x);
    +        r.t = (Duration_ns)(x.QuadPart * 1000000000ULL / ticksPerSecond.QuadPart);
    +        return r;
    +    }
    +}
    +
    +#elif defined(__APPLE__) && defined(__MACH__)
    +
    +#    include  /* mach_timebase_info_data_t, mach_timebase_info, mach_absolute_time */
    +
    +TIME_t TIME_getTime(void)
    +{
    +    static mach_timebase_info_data_t rate;
    +    static int init = 0;
    +    if (!init) {
    +        mach_timebase_info(&rate);
    +        init = 1;
    +    }
    +    {
    +        TIME_t r;
    +        r.t = mach_absolute_time() * (Duration_ns)rate.numer
    +                / (Duration_ns)rate.denom;
    +        return r;
    +    }
    +}
    +
    +
    +/* POSIX.1-2001 (optional) */
    +#elif defined(CLOCK_MONOTONIC)
    +
    +#include    /* abort */
    +#include     /* perror */
    +
    +TIME_t TIME_getTime(void)
    +{
    +    /* time must be initialized, othersize it may fail msan test.
    +     * No good reason, likely a limitation of timespec_get() for some target */
    +    struct timespec time = { 0, 0 };
    +    if (clock_gettime(CLOCK_MONOTONIC, &time) != 0) {
    +        perror("timefn::clock_gettime(CLOCK_MONOTONIC)");
    +        abort();
    +    }
    +    {   TIME_t r;
    +        r.t = (Duration_ns)time.tv_sec * 1000000000ULL
    +                + (Duration_ns)time.tv_nsec;
    +        return r;
    +    }
    +}
    +
    +
    +/* C11 requires support of timespec_get().
    + * However, FreeBSD 11 claims C11 compliance while lacking timespec_get().
    + * Double confirm timespec_get() support by checking the definition of TIME_UTC.
    + * However, some versions of Android manage to simultaneously define TIME_UTC
    + * and lack timespec_get() support... */
    +#elif (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* C11 */) \
    +        && defined(TIME_UTC) && !defined(__ANDROID__)
    +
    +#    include   /* perror */
    +#    include  /* abort */
    +
    +TIME_t TIME_getTime(void)
    +{
    +    /* time must be initialized, othersize it may fail msan test */
    +    struct timespec time = { 0, 0 };
    +    if (timespec_get(&time, TIME_UTC) != TIME_UTC) {
    +        perror("timefn::timespec_get(TIME_UTC)");
    +        abort();
    +    }
    +    {
    +        TIME_t r;
    +        r.t = (Duration_ns)time.tv_sec * 1000000000ULL
    +                + (Duration_ns)time.tv_nsec;
    +        return r;
    +    }
    +}
    +
    +#else /* relies on standard C90 (note : clock_t produces wrong measurements \
    +         for multi-threaded workloads) */
    +
    +TIME_t TIME_getTime(void)
    +{
    +    TIME_t r;
    +    r.t = (Duration_ns)clock() * 1000000000ULL / CLOCKS_PER_SEC;
    +    return r;
    +}
    +
    +#    define TIME_MT_MEASUREMENTS_NOT_SUPPORTED
    +
    +#endif
    +
    +/* ==== Common functions, valid for all time API ==== */
    +
    +Duration_ns TIME_span_ns(TIME_t clockStart, TIME_t clockEnd)
    +{
    +    return clockEnd.t - clockStart.t;
    +}
    +
    +Duration_ns TIME_clockSpan_ns(TIME_t clockStart)
    +{
    +    TIME_t const clockEnd = TIME_getTime();
    +    return TIME_span_ns(clockStart, clockEnd);
    +}
    +
    +void TIME_waitForNextTick(void)
    +{
    +    TIME_t const clockStart = TIME_getTime();
    +    TIME_t clockEnd;
    +    do {
    +        clockEnd = TIME_getTime();
    +    } while (TIME_span_ns(clockStart, clockEnd) == 0);
    +}
    +
    +int TIME_support_MT_measurements(void)
    +{
    +#if defined(TIME_MT_MEASUREMENTS_NOT_SUPPORTED)
    +    return 0;
    +#else
    +    return 1;
    +#endif
    +}
    diff --git a/programs/timefn.h b/programs/timefn.h
    new file mode 100644
    index 0000000000000000000000000000000000000000..e675a026949628ac8518ceb7332190d266557f11
    --- /dev/null
    +++ b/programs/timefn.h
    @@ -0,0 +1,72 @@
    +/*
    +  timefn.h - portable time measurement functions
    +  Copyright (C) Yann Collet 2023
    +
    +  GPL v2 License
    +
    +  This program is free software; you can redistribute it and/or modify
    +  it under the terms of the GNU General Public License as published by
    +  the Free Software Foundation; either version 2 of the License, or
    +  (at your option) any later version.
    +
    +  This program is distributed in the hope that it will be useful,
    +  but WITHOUT ANY WARRANTY; without even the implied warranty of
    +  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    +  GNU General Public License for more details.
    +
    +  You should have received a copy of the GNU General Public License along
    +  with this program; if not, write to the Free Software Foundation, Inc.,
    +  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
    +
    +  You can contact the author at :
    +  - LZ4 source repository : https://github.com/lz4/lz4
    +  - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
    +*/
    +
    +#ifndef TIMEFN
    +#define TIMEFN
    +
    +#if defined(__cplusplus)
    +extern "C" {
    +#endif
    +
    +/*-****************************************
    + *  Types
    + ******************************************/
    +
    +typedef unsigned long long Duration_ns;
    +
    +/* TIME_t contains a nanosecond time counter.
    + * The absolute value is not meaningful.
    + * It's only valid to compute Duration_ns between 2 measurements. */
    +typedef struct {
    +    Duration_ns t;
    +} TIME_t;
    +#define TIME_INITIALIZER { 0 }
    +
    +/*-****************************************
    + *  Time functions
    + ******************************************/
    +
    +/* @return a TIME_t value to be compared to another one in order to compute a duration.
    + * The absolute value returned is meaningless */
    +TIME_t TIME_getTime(void);
    +
    +/* Timer resolution can be low on some platforms.
    + * To improve accuracy, it's recommended to wait for a new tick
    + * before starting benchmark measurements */
    +void TIME_waitForNextTick(void);
    +
    +/* tells if TIME_getTime() returns correct time measurements
    + * in scenarios involving multi-threaded workload.
    + * note : this is not the case if only C90 clock_t measurements are available */
    +int TIME_support_MT_measurements(void);
    +
    +Duration_ns TIME_span_ns(TIME_t clockStart, TIME_t clockEnd);
    +Duration_ns TIME_clockSpan_ns(TIME_t clockStart);
    +
    +#if defined(__cplusplus)
    +}
    +#endif
    +
    +#endif /* TIMEFN */
    diff --git a/programs/util.c b/programs/util.c
    new file mode 100644
    index 0000000000000000000000000000000000000000..170b5a7bda18911366a1976bc2e5d11a8d135027
    --- /dev/null
    +++ b/programs/util.c
    @@ -0,0 +1,165 @@
    +/*
    +    util.h - utility functions
    +    Copyright (C) 2023, Yann Collet
    +
    +    This program is free software; you can redistribute it and/or modify
    +    it under the terms of the GNU General Public License as published by
    +    the Free Software Foundation; either version 2 of the License, or
    +    (at your option) any later version.
    +
    +    This program is distributed in the hope that it will be useful,
    +    but WITHOUT ANY WARRANTY; without even the implied warranty of
    +    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    +    GNU General Public License for more details.
    +
    +    You should have received a copy of the GNU General Public License along
    +    with this program; if not, write to the Free Software Foundation, Inc.,
    +    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
    +*/
    +
    +#if defined (__cplusplus)
    +extern "C" {
    +#endif
    +
    +
    +/*-****************************************
    +*  Dependencies
    +******************************************/
    +#include "util.h"   /* note : ensure that platform.h is included first ! */
    +
    +/*-****************************************
    +*  count the number of cores
    +******************************************/
    +
    +#if defined(_WIN32)
    +
    +#include 
    +
    +int UTIL_countCores(void)
    +{
    +    static int numCores = 0;
    +    if (numCores != 0) return numCores;
    +
    +    {   SYSTEM_INFO sysinfo;
    +        GetSystemInfo(&sysinfo);
    +        numCores = sysinfo.dwNumberOfProcessors;
    +    }
    +
    +    if (numCores == 0) {
    +        /* Unexpected result, fall back on 1 */
    +        return numCores = 1;
    +    }
    +
    +    return numCores;
    +}
    +
    +#elif defined(__APPLE__)
    +
    +#include 
    +
    +/* Use apple-provided syscall
    + * see: man 3 sysctl */
    +int UTIL_countCores(void)
    +{
    +    static S32 numCores = 0; /* apple specifies int32_t */
    +    if (numCores != 0) return (int)numCores;
    +
    +    {   size_t size = sizeof(S32);
    +        int const ret = sysctlbyname("hw.logicalcpu", &numCores, &size, NULL, 0);
    +        if (ret != 0) {
    +            /* error: fall back on 1 */
    +            numCores = 1;
    +        }
    +    }
    +    return (int)numCores;
    +}
    +
    +#elif defined(__linux__)
    +
    +int UTIL_countCores(void)
    +{
    +    static int numCores = 0;
    +
    +    if (numCores != 0) return numCores;
    +
    +    numCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
    +    if (numCores == -1) {
    +        /* value not queryable, fall back on 1 */
    +        return numCores = 1;
    +    }
    +
    +    return numCores;
    +}
    +
    +#elif defined(__FreeBSD__)
    +
    +#include   /* perror */
    +#include 
    +#include 
    +#include 
    +
    +/* Use physical core sysctl when available
    + * see: man 4 smp, man 3 sysctl */
    +int UTIL_countCores(void)
    +{
    +    static int numCores = 0; /* freebsd sysctl is native int sized */
    +    if (numCores != 0) return numCores;
    +
    +#if __FreeBSD_version >= 1300008
    +    {   size_t size = sizeof(numCores);
    +        int ret = sysctlbyname("kern.smp.cores", &numCores, &size, NULL, 0);
    +        if (ret == 0) {
    +            int perCore = 1;
    +            ret = sysctlbyname("kern.smp.threads_per_core", &perCore, &size, NULL, 0);
    +            /* default to physical cores if logical cannot be read */
    +            if (ret != 0) /* error */
    +                return numCores;
    +            numCores *= perCore;
    +            return numCores;
    +        }
    +        if (errno != ENOENT) {
    +            perror("lz4: can't get number of cpus");
    +            exit(1);
    +        }
    +        /* sysctl not present, fall through to older sysconf method */
    +    }
    +#endif
    +
    +    numCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
    +    if (numCores == -1) {
    +        /* value not queryable, fall back on 1 */
    +        numCores = 1;
    +    }
    +    return numCores;
    +}
    +
    +#elif defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__CYGWIN__)
    +
    +/* Use POSIX sysconf
    + * see: man 3 sysconf */
    +int UTIL_countCores(void)
    +{
    +    static int numCores = 0;
    +    if (numCores != 0) return numCores;
    +
    +    numCores = (int)sysconf(_SC_NPROCESSORS_ONLN);
    +    if (numCores == -1) {
    +        /* value not queryable, fall back on 1 */
    +        numCores = 1;
    +    }
    +    return numCores;
    +}
    +
    +#else
    +
    +int UTIL_countCores(void)
    +{
    +    /* no clue */
    +    return 1;
    +}
    +
    +#endif
    +
    +#if defined (__cplusplus)
    +}
    +#endif
    diff --git a/programs/util.h b/programs/util.h
    index 3192ddcb207a6e986509cf6ea39ea2c0ce00a5c1..88efe05f71f4f877cc29551f595c5f945c4adee1 100644
    --- a/programs/util.h
    +++ b/programs/util.h
    @@ -1,6 +1,6 @@
     /*
         util.h - utility functions
    -    Copyright (C) 2016-2020, Przemyslaw Skibinski, Yann Collet
    +    Copyright (C) 2016-2023, Przemyslaw Skibinski, Yann Collet
     
         This program is free software; you can redistribute it and/or modify
         it under the terms of the GNU General Public License as published by
    @@ -91,6 +91,10 @@ extern "C" {
     #   define UTIL_fseek fseek
     #endif
     
    +/*-****************************************
    +*  Local host Core counting
    +******************************************/
    +int UTIL_countCores(void);
     
     /*-****************************************
     *  Sleep functions: Windows - Posix - others
    @@ -195,148 +199,16 @@ UTIL_STATIC void* UTIL_realloc(void* ptr, size_t size)
     /*-****************************************
     *  String functions
     ******************************************/
    -/*
    - * A modified version of realloc().
    - * If UTIL_realloc() fails the original block is freed.
    -*/
    +/* supports a==NULL or b==NULL */
     UTIL_STATIC int UTIL_sameString(const char* a, const char* b)
     {
    -    assert(a!=NULL && b!=NULL);  /* unsupported scenario */
    +    assert(a != NULL || b != NULL);  /* unsupported scenario */
         if (a==NULL) return 0;
         if (b==NULL) return 0;
         return !strcmp(a,b);
     }
     
     
    -/*-****************************************
    -*  Time functions
    -******************************************/
    -#if defined(_WIN32)   /* Windows */
    -
    -    typedef LARGE_INTEGER UTIL_time_t;
    -    UTIL_STATIC UTIL_time_t UTIL_getTime(void) { UTIL_time_t x; QueryPerformanceCounter(&x); return x; }
    -    UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd)
    -    {
    -        static LARGE_INTEGER ticksPerSecond;
    -        static int init = 0;
    -        if (!init) {
    -            if (!QueryPerformanceFrequency(&ticksPerSecond))
    -                fprintf(stderr, "ERROR: QueryPerformanceFrequency() failure\n");
    -            init = 1;
    -        }
    -        return 1000000ULL*(clockEnd.QuadPart - clockStart.QuadPart)/ticksPerSecond.QuadPart;
    -    }
    -    UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd)
    -    {
    -        static LARGE_INTEGER ticksPerSecond;
    -        static int init = 0;
    -        if (!init) {
    -            if (!QueryPerformanceFrequency(&ticksPerSecond))
    -                fprintf(stderr, "ERROR: QueryPerformanceFrequency() failure\n");
    -            init = 1;
    -        }
    -        return 1000000000ULL*(clockEnd.QuadPart - clockStart.QuadPart)/ticksPerSecond.QuadPart;
    -    }
    -
    -#elif defined(__APPLE__) && defined(__MACH__)
    -
    -    #include 
    -    typedef U64 UTIL_time_t;
    -    UTIL_STATIC UTIL_time_t UTIL_getTime(void) { return mach_absolute_time(); }
    -    UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd)
    -    {
    -        static mach_timebase_info_data_t rate;
    -        static int init = 0;
    -        if (!init) {
    -            mach_timebase_info(&rate);
    -            init = 1;
    -        }
    -        return (((clockEnd - clockStart) * (U64)rate.numer) / ((U64)rate.denom)) / 1000ULL;
    -    }
    -    UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd)
    -    {
    -        static mach_timebase_info_data_t rate;
    -        static int init = 0;
    -        if (!init) {
    -            mach_timebase_info(&rate);
    -            init = 1;
    -        }
    -        return ((clockEnd - clockStart) * (U64)rate.numer) / ((U64)rate.denom);
    -    }
    -
    -#elif (PLATFORM_POSIX_VERSION >= 200112L) && (defined __UCLIBC__ || (defined(__GLIBC__) && ((__GLIBC__ == 2 && __GLIBC_MINOR__ >= 17) || __GLIBC__ > 2) ) )
    -
    -    #include 
    -    typedef struct timespec UTIL_time_t;
    -    UTIL_STATIC UTIL_time_t UTIL_getTime(void)
    -    {
    -        UTIL_time_t now;
    -        if (clock_gettime(CLOCK_MONOTONIC, &now))
    -            fprintf(stderr, "ERROR: Failed to get time\n");   /* we could also exit() */
    -        return now;
    -    }
    -    UTIL_STATIC UTIL_time_t UTIL_getSpanTime(UTIL_time_t begin, UTIL_time_t end)
    -    {
    -        UTIL_time_t diff;
    -        if (end.tv_nsec < begin.tv_nsec) {
    -            diff.tv_sec = (end.tv_sec - 1) - begin.tv_sec;
    -            diff.tv_nsec = (end.tv_nsec + 1000000000ULL) - begin.tv_nsec;
    -        } else {
    -            diff.tv_sec = end.tv_sec - begin.tv_sec;
    -            diff.tv_nsec = end.tv_nsec - begin.tv_nsec;
    -        }
    -        return diff;
    -    }
    -    UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t begin, UTIL_time_t end)
    -    {
    -        UTIL_time_t const diff = UTIL_getSpanTime(begin, end);
    -        U64 micro = 0;
    -        micro += 1000000ULL * diff.tv_sec;
    -        micro += diff.tv_nsec / 1000ULL;
    -        return micro;
    -    }
    -    UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t begin, UTIL_time_t end)
    -    {
    -        UTIL_time_t const diff = UTIL_getSpanTime(begin, end);
    -        U64 nano = 0;
    -        nano += 1000000000ULL * diff.tv_sec;
    -        nano += diff.tv_nsec;
    -        return nano;
    -    }
    -
    -#else   /* relies on standard C (note : clock_t measurements can be wrong when using multi-threading) */
    -
    -    typedef clock_t UTIL_time_t;
    -    UTIL_STATIC UTIL_time_t UTIL_getTime(void) { return clock(); }
    -    UTIL_STATIC U64 UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd) { return 1000000ULL * (clockEnd - clockStart) / CLOCKS_PER_SEC; }
    -    UTIL_STATIC U64 UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd) { return 1000000000ULL * (clockEnd - clockStart) / CLOCKS_PER_SEC; }
    -#endif
    -
    -
    -/* returns time span in microseconds */
    -UTIL_STATIC U64 UTIL_clockSpanMicro(UTIL_time_t clockStart)
    -{
    -    UTIL_time_t const clockEnd = UTIL_getTime();
    -    return UTIL_getSpanTimeMicro(clockStart, clockEnd);
    -}
    -
    -/* returns time span in nanoseconds */
    -UTIL_STATIC U64 UTIL_clockSpanNano(UTIL_time_t clockStart)
    -{
    -    UTIL_time_t const clockEnd = UTIL_getTime();
    -    return UTIL_getSpanTimeNano(clockStart, clockEnd);
    -}
    -
    -UTIL_STATIC void UTIL_waitForNextTick(void)
    -{
    -    UTIL_time_t const clockStart = UTIL_getTime();
    -    UTIL_time_t clockEnd;
    -    do {
    -        clockEnd = UTIL_getTime();
    -    } while (UTIL_getSpanTimeNano(clockStart, clockEnd) == 0);
    -}
    -
    -
     
     /*-****************************************
     *  File functions
    @@ -412,7 +284,6 @@ UTIL_STATIC int UTIL_getFileStat(const char* infilename, stat_t *statbuf)
         return 1;
     }
     
    -
     UTIL_STATIC int UTIL_isRegFD(int fd)
     {
         stat_t statbuf;
    @@ -423,26 +294,25 @@ UTIL_STATIC int UTIL_isRegFD(int fd)
         return UTIL_getFDStat(fd, &statbuf); /* Only need to know whether it is a regular file */
     }
     
    -
     UTIL_STATIC int UTIL_isRegFile(const char* infilename)
     {
         stat_t statbuf;
         return UTIL_getFileStat(infilename, &statbuf); /* Only need to know whether it is a regular file */
     }
     
    -
    -UTIL_STATIC U32 UTIL_isDirectory(const char* infilename)
    +UTIL_STATIC int UTIL_isDirectory(const char* infilename)
     {
    -    int r;
         stat_t statbuf;
    +    int r;
     #if defined(_MSC_VER)
         r = _stat64(infilename, &statbuf);
    -    if (!r && (statbuf.st_mode & _S_IFDIR)) return 1;
    +    if (r) return 0;
    +    return (statbuf.st_mode & S_IFDIR);
     #else
         r = stat(infilename, &statbuf);
    -    if (!r && S_ISDIR(statbuf.st_mode)) return 1;
    +    if (r) return 0;
    +    return (S_ISDIR(statbuf.st_mode));
     #endif
    -    return 0;
     }
     
     
    diff --git a/tests/.gitignore b/tests/.gitignore
    index c7d8f19b8c6edfd352abc2d3c7ed3ec13cbe3a7e..48ae042f9d8e453de1b92059f477af87c07455ed 100644
    --- a/tests/.gitignore
    +++ b/tests/.gitignore
    @@ -5,6 +5,8 @@ frametest
     frametest32
     fullbench
     fullbench32
    +fullbench-lib
    +fullbench-dll
     fuzzer
     fuzzer32
     fasttest
    diff --git a/tests/COPYING b/tests/COPYING
    index d159169d1050894d3ea3b98e1c965c4058208fe1..c728282bf0c88d16f64db747332efb440f652c05 100644
    --- a/tests/COPYING
    +++ b/tests/COPYING
    @@ -1,339 +1,83 @@
    -                    GNU GENERAL PUBLIC LICENSE
    -                       Version 2, June 1991
    -
    - Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
    - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
    - Everyone is permitted to copy and distribute verbatim copies
    - of this license document, but changing it is not allowed.
    -
    -                            Preamble
    -
    -  The licenses for most software are designed to take away your
    -freedom to share and change it.  By contrast, the GNU General Public
    -License is intended to guarantee your freedom to share and change free
    -software--to make sure the software is free for all its users.  This
    -General Public License applies to most of the Free Software
    -Foundation's software and to any other program whose authors commit to
    -using it.  (Some other Free Software Foundation software is covered by
    -the GNU Lesser General Public License instead.)  You can apply it to
    -your programs, too.
    -
    -  When we speak of free software, we are referring to freedom, not
    -price.  Our General Public Licenses are designed to make sure that you
    -have the freedom to distribute copies of free software (and charge for
    -this service if you wish), that you receive source code or can get it
    -if you want it, that you can change the software or use pieces of it
    -in new free programs; and that you know you can do these things.
    -
    -  To protect your rights, we need to make restrictions that forbid
    -anyone to deny you these rights or to ask you to surrender the rights.
    -These restrictions translate to certain responsibilities for you if you
    -distribute copies of the software, or if you modify it.
    -
    -  For example, if you distribute copies of such a program, whether
    -gratis or for a fee, you must give the recipients all the rights that
    -you have.  You must make sure that they, too, receive or can get the
    -source code.  And you must show them these terms so they know their
    -rights.
    -
    -  We protect your rights with two steps: (1) copyright the software, and
    -(2) offer you this license which gives you legal permission to copy,
    -distribute and/or modify the software.
    -
    -  Also, for each author's protection and ours, we want to make certain
    -that everyone understands that there is no warranty for this free
    -software.  If the software is modified by someone else and passed on, we
    -want its recipients to know that what they have is not the original, so
    -that any problems introduced by others will not reflect on the original
    -authors' reputations.
    -
    -  Finally, any free program is threatened constantly by software
    -patents.  We wish to avoid the danger that redistributors of a free
    -program will individually obtain patent licenses, in effect making the
    -program proprietary.  To prevent this, we have made it clear that any
    -patent must be licensed for everyone's free use or not licensed at all.
    -
    -  The precise terms and conditions for copying, distribution and
    -modification follow.
    -
    -                    GNU GENERAL PUBLIC LICENSE
    -   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
    -
    -  0. This License applies to any program or other work which contains
    -a notice placed by the copyright holder saying it may be distributed
    -under the terms of this General Public License.  The "Program", below,
    -refers to any such program or work, and a "work based on the Program"
    -means either the Program or any derivative work under copyright law:
    -that is to say, a work containing the Program or a portion of it,
    -either verbatim or with modifications and/or translated into another
    -language.  (Hereinafter, translation is included without limitation in
    -the term "modification".)  Each licensee is addressed as "you".
    -
    -Activities other than copying, distribution and modification are not
    -covered by this License; they are outside its scope.  The act of
    -running the Program is not restricted, and the output from the Program
    -is covered only if its contents constitute a work based on the
    -Program (independent of having been made by running the Program).
    -Whether that is true depends on what the Program does.
    -
    -  1. You may copy and distribute verbatim copies of the Program's
    -source code as you receive it, in any medium, provided that you
    -conspicuously and appropriately publish on each copy an appropriate
    -copyright notice and disclaimer of warranty; keep intact all the
    -notices that refer to this License and to the absence of any warranty;
    -and give any other recipients of the Program a copy of this License
    -along with the Program.
    -
    -You may charge a fee for the physical act of transferring a copy, and
    -you may at your option offer warranty protection in exchange for a fee.
    -
    -  2. You may modify your copy or copies of the Program or any portion
    -of it, thus forming a work based on the Program, and copy and
    -distribute such modifications or work under the terms of Section 1
    -above, provided that you also meet all of these conditions:
    -
    -    a) You must cause the modified files to carry prominent notices
    -    stating that you changed the files and the date of any change.
    -
    -    b) You must cause any work that you distribute or publish, that in
    -    whole or in part contains or is derived from the Program or any
    -    part thereof, to be licensed as a whole at no charge to all third
    -    parties under the terms of this License.
    -
    -    c) If the modified program normally reads commands interactively
    -    when run, you must cause it, when started running for such
    -    interactive use in the most ordinary way, to print or display an
    -    announcement including an appropriate copyright notice and a
    -    notice that there is no warranty (or else, saying that you provide
    -    a warranty) and that users may redistribute the program under
    -    these conditions, and telling the user how to view a copy of this
    -    License.  (Exception: if the Program itself is interactive but
    -    does not normally print such an announcement, your work based on
    -    the Program is not required to print an announcement.)
    -
    -These requirements apply to the modified work as a whole.  If
    -identifiable sections of that work are not derived from the Program,
    -and can be reasonably considered independent and separate works in
    -themselves, then this License, and its terms, do not apply to those
    -sections when you distribute them as separate works.  But when you
    -distribute the same sections as part of a whole which is a work based
    -on the Program, the distribution of the whole must be on the terms of
    -this License, whose permissions for other licensees extend to the
    -entire whole, and thus to each and every part regardless of who wrote it.
    -
    -Thus, it is not the intent of this section to claim rights or contest
    -your rights to work written entirely by you; rather, the intent is to
    -exercise the right to control the distribution of derivative or
    -collective works based on the Program.
    -
    -In addition, mere aggregation of another work not based on the Program
    -with the Program (or with a work based on the Program) on a volume of
    -a storage or distribution medium does not bring the other work under
    -the scope of this License.
    -
    -  3. You may copy and distribute the Program (or a work based on it,
    -under Section 2) in object code or executable form under the terms of
    -Sections 1 and 2 above provided that you also do one of the following:
    -
    -    a) Accompany it with the complete corresponding machine-readable
    -    source code, which must be distributed under the terms of Sections
    -    1 and 2 above on a medium customarily used for software interchange; or,
    -
    -    b) Accompany it with a written offer, valid for at least three
    -    years, to give any third party, for a charge no more than your
    -    cost of physically performing source distribution, a complete
    -    machine-readable copy of the corresponding source code, to be
    -    distributed under the terms of Sections 1 and 2 above on a medium
    -    customarily used for software interchange; or,
    -
    -    c) Accompany it with the information you received as to the offer
    -    to distribute corresponding source code.  (This alternative is
    -    allowed only for noncommercial distribution and only if you
    -    received the program in object code or executable form with such
    -    an offer, in accord with Subsection b above.)
    -
    -The source code for a work means the preferred form of the work for
    -making modifications to it.  For an executable work, complete source
    -code means all the source code for all modules it contains, plus any
    -associated interface definition files, plus the scripts used to
    -control compilation and installation of the executable.  However, as a
    -special exception, the source code distributed need not include
    -anything that is normally distributed (in either source or binary
    -form) with the major components (compiler, kernel, and so on) of the
    -operating system on which the executable runs, unless that component
    -itself accompanies the executable.
    -
    -If distribution of executable or object code is made by offering
    -access to copy from a designated place, then offering equivalent
    -access to copy the source code from the same place counts as
    -distribution of the source code, even though third parties are not
    -compelled to copy the source along with the object code.
    -
    -  4. You may not copy, modify, sublicense, or distribute the Program
    -except as expressly provided under this License.  Any attempt
    -otherwise to copy, modify, sublicense or distribute the Program is
    -void, and will automatically terminate your rights under this License.
    -However, parties who have received copies, or rights, from you under
    -this License will not have their licenses terminated so long as such
    -parties remain in full compliance.
    -
    -  5. You are not required to accept this License, since you have not
    -signed it.  However, nothing else grants you permission to modify or
    -distribute the Program or its derivative works.  These actions are
    -prohibited by law if you do not accept this License.  Therefore, by
    -modifying or distributing the Program (or any work based on the
    -Program), you indicate your acceptance of this License to do so, and
    -all its terms and conditions for copying, distributing or modifying
    -the Program or works based on it.
    -
    -  6. Each time you redistribute the Program (or any work based on the
    -Program), the recipient automatically receives a license from the
    -original licensor to copy, distribute or modify the Program subject to
    -these terms and conditions.  You may not impose any further
    -restrictions on the recipients' exercise of the rights granted herein.
    -You are not responsible for enforcing compliance by third parties to
    -this License.
    -
    -  7. If, as a consequence of a court judgment or allegation of patent
    -infringement or for any other reason (not limited to patent issues),
    -conditions are imposed on you (whether by court order, agreement or
    -otherwise) that contradict the conditions of this License, they do not
    -excuse you from the conditions of this License.  If you cannot
    -distribute so as to satisfy simultaneously your obligations under this
    -License and any other pertinent obligations, then as a consequence you
    -may not distribute the Program at all.  For example, if a patent
    -license would not permit royalty-free redistribution of the Program by
    -all those who receive copies directly or indirectly through you, then
    -the only way you could satisfy both it and this License would be to
    -refrain entirely from distribution of the Program.
    -
    -If any portion of this section is held invalid or unenforceable under
    -any particular circumstance, the balance of the section is intended to
    -apply and the section as a whole is intended to apply in other
    -circumstances.
    -
    -It is not the purpose of this section to induce you to infringe any
    -patents or other property right claims or to contest validity of any
    -such claims; this section has the sole purpose of protecting the
    -integrity of the free software distribution system, which is
    -implemented by public license practices.  Many people have made
    -generous contributions to the wide range of software distributed
    -through that system in reliance on consistent application of that
    -system; it is up to the author/donor to decide if he or she is willing
    -to distribute software through any other system and a licensee cannot
    -impose that choice.
    -
    -This section is intended to make thoroughly clear what is believed to
    -be a consequence of the rest of this License.
    -
    -  8. If the distribution and/or use of the Program is restricted in
    -certain countries either by patents or by copyrighted interfaces, the
    -original copyright holder who places the Program under this License
    -may add an explicit geographical distribution limitation excluding
    -those countries, so that distribution is permitted only in or among
    -countries not thus excluded.  In such case, this License incorporates
    -the limitation as if written in the body of this License.
    -
    -  9. The Free Software Foundation may publish revised and/or new versions
    -of the General Public License from time to time.  Such new versions will
    -be similar in spirit to the present version, but may differ in detail to
    -address new problems or concerns.
    -
    -Each version is given a distinguishing version number.  If the Program
    -specifies a version number of this License which applies to it and "any
    -later version", you have the option of following the terms and conditions
    -either of that version or of any later version published by the Free
    -Software Foundation.  If the Program does not specify a version number of
    -this License, you may choose any version ever published by the Free Software
    -Foundation.
    -
    -  10. If you wish to incorporate parts of the Program into other free
    -programs whose distribution conditions are different, write to the author
    -to ask for permission.  For software which is copyrighted by the Free
    -Software Foundation, write to the Free Software Foundation; we sometimes
    -make exceptions for this.  Our decision will be guided by the two goals
    -of preserving the free status of all derivatives of our free software and
    -of promoting the sharing and reuse of software generally.
    -
    -                            NO WARRANTY
    -
    -  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
    -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
    -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
    -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
    -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
    -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
    -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
    -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
    -REPAIR OR CORRECTION.
    -
    -  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
    -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
    -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
    -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
    -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
    -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
    -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
    -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
    -POSSIBILITY OF SUCH DAMAGES.
    -
    -                     END OF TERMS AND CONDITIONS
    -
    -            How to Apply These Terms to Your New Programs
    -
    -  If you develop a new program, and you want it to be of the greatest
    -possible use to the public, the best way to achieve this is to make it
    -free software which everyone can redistribute and change under these terms.
    -
    -  To do so, attach the following notices to the program.  It is safest
    -to attach them to the start of each source file to most effectively
    -convey the exclusion of warranty; and each file should have at least
    -the "copyright" line and a pointer to where the full notice is found.
    -
    -    
    -    Copyright (C)   
    -
    -    This program is free software; you can redistribute it and/or modify
    -    it under the terms of the GNU General Public License as published by
    -    the Free Software Foundation; either version 2 of the License, or
    -    (at your option) any later version.
    -
    -    This program is distributed in the hope that it will be useful,
    -    but WITHOUT ANY WARRANTY; without even the implied warranty of
    -    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    -    GNU General Public License for more details.
    -
    -    You should have received a copy of the GNU General Public License along
    -    with this program; if not, write to the Free Software Foundation, Inc.,
    -    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
    -
    -Also add information on how to contact you by electronic and paper mail.
    -
    -If the program is interactive, make it output a short notice like this
    -when it starts in an interactive mode:
    -
    -    Gnomovision version 69, Copyright (C) year name of author
    -    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    -    This is free software, and you are welcome to redistribute it
    -    under certain conditions; type `show c' for details.
    -
    -The hypothetical commands `show w' and `show c' should show the appropriate
    -parts of the General Public License.  Of course, the commands you use may
    -be called something other than `show w' and `show c'; they could even be
    -mouse-clicks or menu items--whatever suits your program.
    -
    -You should also get your employer (if you work as a programmer) or your
    -school, if any, to sign a "copyright disclaimer" for the program, if
    -necessary.  Here is a sample; alter the names:
    -
    -  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
    -  `Gnomovision' (which makes passes at compilers) written by James Hacker.
    -
    -  , 1 April 1989
    -  Ty Coon, President of Vice
    -
    -This General Public License does not permit incorporating your program into
    -proprietary programs.  If your program is a subroutine library, you may
    -consider it more useful to permit linking proprietary applications with the
    -library.  If this is what you want to do, use the GNU Lesser General
    -Public License instead of this License.
    +Full name:
    +GNU General Public License v2.0 or later
    +
    +Short identifier:
    +GPL-2.0-or-later
    +
    +Text:
    +GNU GENERAL PUBLIC LICENSE
    +Version 2, June 1991
    +
    +Copyright (C) 1989, 1991 Free Software Foundation, Inc.
    +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
    +
    +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
    +
    +Preamble
    +
    +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.
    +
    +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.
    +
    +To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.
    +
    +For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
    +
    +We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.
    +
    +Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.
    +
    +Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.
    +
    +The precise terms and conditions for copying, distribution and modification follow.
    +
    +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
    +
    +0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".
    +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.
    +
    +1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.
    +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.
    +
    +2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:
    +a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
    +b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
    +c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
    +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.
    +
    +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.
    +
    +In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.
    +
    +3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:
    +a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
    +b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
    +c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
    +The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.
    +
    +If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.
    +
    +4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
    +
    +5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.
    +
    +6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.
    +
    +7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.
    +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.
    +
    +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.
    +
    +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.
    +
    +8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.
    +
    +9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
    +Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.
    +
    +10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.
    +NO WARRANTY
    +
    +11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
    +
    +12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
    diff --git a/tests/Makefile b/tests/Makefile
    index 93a5581c285d4e93a3461ee62637e20b3326a74a..47e2774d3589cd087517b7469a1bd880962de24a 100644
    --- a/tests/Makefile
    +++ b/tests/Makefile
    @@ -28,20 +28,20 @@
     # datagen : generates synthetic data samples for tests & benchmarks
     # ##########################################################################
     
    -LZ4DIR  := ../lib
    +LIBDIR  := ../lib
     PRGDIR  := ../programs
     TESTDIR := versionsTest
     PYTHON  ?= python3
     
     DEBUGLEVEL?= 1
     DEBUGFLAGS = -g -DLZ4_DEBUG=$(DEBUGLEVEL)
    -CFLAGS  ?= -O3 # can select custom optimization flags. Example : CFLAGS=-O2 make
    -CFLAGS  += -Wall -Wextra -Wundef -Wcast-qual -Wcast-align -Wshadow \
    -           -Wswitch-enum -Wdeclaration-after-statement -Wstrict-prototypes \
    -           -Wpointer-arith -Wstrict-aliasing=1
    -CFLAGS  += $(DEBUGFLAGS) $(MOREFLAGS)
    -CPPFLAGS+= -I$(LZ4DIR) -I$(PRGDIR) -DXXH_NAMESPACE=LZ4_
    -FLAGS    = $(CFLAGS) $(CPPFLAGS) $(LDFLAGS)
    +USERCFLAGS:= -O3 $(CFLAGS) # appended for higher priority
    +WFLAGS    = -Wall -Wextra -Wundef -Wcast-qual -Wcast-align -Wshadow \
    +            -Wswitch-enum -Wdeclaration-after-statement -Wstrict-prototypes \
    +            -Wpointer-arith -Wstrict-aliasing=1
    +CFLAGS    = $(WFLAGS) $(DEBUGFLAGS) $(USERCFLAGS)
    +CPPFLAGS += -I$(LIBDIR) -I$(PRGDIR) -DXXH_NAMESPACE=LZ4_
    +ALLFLAGS  = $(CFLAGS) $(CPPFLAGS) $(LDFLAGS)
     
     include ../Makefile.inc
     
    @@ -56,83 +56,97 @@ NB_LOOPS     ?= -i1
     .PHONY: default
     default: all
     
    +.PHONY: all
     all: fullbench fuzzer frametest roundTripTest datagen checkFrame decompress-partial
     
    +.PHONY: all32
     all32: CFLAGS+=-m32
     all32: all
     
    +.PHONY: lz4
     lz4:
     	$(MAKE) -C $(PRGDIR) $@ CFLAGS="$(CFLAGS)"
     
    +.PHONY: lib liblz4.pc
     lib liblz4.pc:
    -	$(MAKE) -C $(LZ4DIR) $@ CFLAGS="$(CFLAGS)"
    +	$(MAKE) -C $(LIBDIR) $@ CFLAGS="$(CFLAGS)"
     
     lz4c unlz4 lz4cat: lz4
     	$(LN_SF) $(LZ4) $(PRGDIR)/$@
     
    -lz4c32:   # create a 32-bits version for 32/64 interop tests
    +.PHONY: lz4c32
    +lz4c32:  # create a 32-bits version for 32/64 interop tests
     	$(MAKE) -C $(PRGDIR) $@ CFLAGS="-m32 $(CFLAGS)"
     
    -%.o : $(LZ4DIR)/%.c $(LZ4DIR)/%.h
    +# *.o objects are from library
    +%.o : $(LIBDIR)/%.c $(LIBDIR)/%.h
     	$(CC) -c $(CFLAGS) $(CPPFLAGS) $< -o $@
     
    +CLEAN += fullbench
     fullbench : DEBUGLEVEL=0
    +fullbench : CPPFLAGS += -DNDEBUG
     fullbench : lz4.o lz4hc.o lz4frame.o xxhash.o fullbench.c
    -	$(CC) $(FLAGS) $^ -o $@$(EXT)
    -
    -$(LZ4DIR)/liblz4.a:
    -	$(MAKE) -C $(LZ4DIR) liblz4.a
    -
    -fullbench-lib: fullbench.c $(LZ4DIR)/liblz4.a
    -	$(CC) $(FLAGS) $^ -o $@$(EXT)
    -
    -fullbench-dll: fullbench.c $(LZ4DIR)/xxhash.c
    -	$(MAKE) -C $(LZ4DIR) liblz4
    -	$(CC) $(FLAGS) $^ -o $@$(EXT) -DLZ4_DLL_IMPORT=1 $(LZ4DIR)/dll/$(LIBLZ4).dll
    +	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
    +
    +.PHONY: $(LIBDIR)/liblz4.a
    +$(LIBDIR)/liblz4.a:
    +	$(MAKE) -C $(LIBDIR) liblz4.a
    +
    +CLEAN += fullbench-lib
    +fullbench-lib : DEBUGLEVEL=0
    +fullbench-lib : CPPFLAGS += -DNDEBUG
    +fullbench-lib: fullbench.c $(LIBDIR)/liblz4.a
    +	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
    +
    +# Note: Windows only
    +ifeq ($(WINBASED),yes)
    +CLEAN += fullbench-dll
    +fullbench-dll : DEBUGLEVEL=0
    +fullbench-dll : CPPFLAGS += -DNDEBUG
    +fullbench-dll: fullbench.c $(LIBDIR)/xxhash.c
    +	$(MAKE) -C $(LIBDIR) liblz4
    +	$(CC) $(ALLFLAGS) $^ -o $@$(EXT) -DLZ4_DLL_IMPORT=1 $(LIBDIR)/dll/$(LIBLZ4).dll
    +endif
     
     # test LZ4_USER_MEMORY_FUNCTIONS
     fullbench-wmalloc: CPPFLAGS += -DLZ4_USER_MEMORY_FUNCTIONS
     fullbench-wmalloc: fullbench
     
    +CLEAN += fuzzer
     fuzzer  : lz4.o lz4hc.o xxhash.o fuzzer.c
    -	$(CC) $(FLAGS) $^ -o $@$(EXT)
    +	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
     
    +CLEAN += frametest
     frametest: lz4frame.o lz4.o lz4hc.o xxhash.o frametest.c
    -	$(CC) $(FLAGS) $^ -o $@$(EXT)
    +	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
     
    +CLEAN += roundTripTest
     roundTripTest : lz4.o lz4hc.o xxhash.o roundTripTest.c
    -	$(CC) $(FLAGS) $^ -o $@$(EXT)
    +	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
     
    -datagen : $(PRGDIR)/datagen.c datagencli.c
    -	$(CC) $(FLAGS) -I$(PRGDIR) $^ -o $@$(EXT)
    +CLEAN += datagen
    +datagen: CPPFLAGS+=-DNDEBUG
    +datagen : datagen.c $(PRGDIR)/lorem.c loremOut.c datagencli.c
    +	$(CC) $(ALLFLAGS) -I$(PRGDIR) $^ -o $@$(EXT)
     
    +CLEAN += checkFrame
     checkFrame : lz4frame.o lz4.o lz4hc.o xxhash.o checkFrame.c
    -	$(CC) $(FLAGS) $^ -o $@$(EXT)
    +	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
     
    +CLEAN += decompress-partial
     decompress-partial: lz4.o decompress-partial.c
    -	$(CC) $(FLAGS) $^ -o $@$(EXT)
    +	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
     
    +CLEAN += decompress-partial-usingDict
     decompress-partial-usingDict: lz4.o decompress-partial-usingDict.c
    -	$(CC) $(FLAGS) $^ -o $@$(EXT)
    -
    -freestanding: freestanding.c
    -	$(CC) -ffreestanding -nostdlib $^ -o $@$(EXT)
    +	$(CC) $(ALLFLAGS) $^ -o $@$(EXT)
     
     .PHONY: clean
     clean:
    -	@$(MAKE) -C $(LZ4DIR) $@ > $(VOID)
    +	@$(MAKE) -C $(LIBDIR) $@ > $(VOID)
     	@$(MAKE) -C $(PRGDIR) $@ > $(VOID)
    -	@$(RM) -rf core *.o *.test tmp* \
    -        fullbench-dll$(EXT) fullbench-lib$(EXT) \
    -        fullbench$(EXT) fullbench32$(EXT) \
    -        fuzzer$(EXT) fuzzer32$(EXT) \
    -        frametest$(EXT) frametest32$(EXT) \
    -        fasttest$(EXT) roundTripTest$(EXT) \
    -        datagen$(EXT) checkTag$(EXT) \
    -        frameTest$(EXT) decompress-partial$(EXT) \
    -        abiTest$(EXT) freestanding$(EXT) \
    -        lz4_all.c
    -	@$(RM) -rf $(TESTDIR)
    +	@$(RM) $(CLEAN) core *.o *.test tmp*
    +	@$(RM) -r $(TESTDIR)
     	@echo Cleaning completed
     
     .PHONY: versionsTest
    @@ -143,67 +157,63 @@ versionsTest:
     listTest: lz4
     	QEMU_SYS=$(QEMU_SYS) $(PYTHON) test-lz4-list.py
     
    +# Note: requires liblz4 installed
    +CLEAN += abiTest
     abiTest: LDLIBS += -llz4
     
     .PHONY: abiTests
     abiTests:
     	$(PYTHON) test-lz4-abi.py
     
    -checkTag: checkTag.c $(LZ4DIR)/lz4.h
    -	$(CC) $(FLAGS) $< -o $@$(EXT)
    +CLEAN += checkTag
    +checkTag: checkTag.c $(LIBDIR)/lz4.h
    +	$(CC) $(ALLFLAGS) $< -o $@$(EXT)
     
     #-----------------------------------------------------------------------------
     # validated only for Linux, OSX, BSD, Hurd and Solaris targets
     #-----------------------------------------------------------------------------
     ifeq ($(POSIX_ENV),Yes)
     
    -MD5:=md5sum
    -ifneq (,$(filter $(shell $(UNAME)), Darwin ))
    -MD5:=md5 -r
    -endif
    -
    -# note : we should probably settle on a single compare utility
    -CMP:=cmp
    -GREP:=grep
    -DIFF:=diff
    -ifneq (,$(filter $(shell $(UNAME)),SunOS))
    -DIFF:=gdiff
    -endif
    -
    -CAT:=cat
    -DD:=dd
    -DATAGEN:=./datagen
    +MD5 ?= $(if $(filter Darwin,$(shell $(UNAME))),md5 -r,md5sum)
    +GREP?= grep
    +CAT ?= cat
    +DATAGEN?=./datagen
    +PATH:=../programs:$(shell pwd):$(PATH)
     
     .PHONY: list
     list:
    -	@$(MAKE) -pRrq -f $(lastword $(MAKEFILE_LIST)) : 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | sort | egrep -v -e '^[^[:alnum:]]' -e '^$@$$' | xargs
    +	$(GREP) '^[^#[:space:]].*:' Makefile | sed 's/:.*//' | sort | uniq
    +
    +ifneq ($(TARGETSEARCH),NO)
    +ALL_TARGETS := $(shell make list TARGETSEARCH=NO)
    +endif
    +TEST_TARGETS := $(filter test%,$(ALL_TARGETS))
    +.PHONY: $(TEST_TARGETS) # all targets starting by `test` are now .PHONY
    +
    +test_targets:
    +	@echo TEST_TARGETS = $(TEST_TARGETS)
     
     .PHONY: check
     check: test-lz4-essentials
     
    -.PHONY: test
     test: test-lz4 test-lz4c test-frametest test-fullbench test-fuzzer test-amalgamation listTest test-decompress-partial
     
    -.PHONY: test32
     test32: CFLAGS+=-m32
     test32: test
     
    -.PHONY: test-amalgamation
     test-amalgamation: lz4_all.o
     
    -lz4_all.c: $(LZ4DIR)/lz4.c $(LZ4DIR)/lz4hc.c $(LZ4DIR)/lz4frame.c
    +CLEAN += lz4_all.c
    +lz4_all.c: $(LIBDIR)/lz4.c $(LIBDIR)/lz4hc.c $(LIBDIR)/lz4frame.c
     	$(CAT) $^ > $@
     
    -.PHONY: test-install
     test-install: lz4 lib liblz4.pc
     	lz4_root=.. ./test_install.sh
     
    -.PHONY: test-compile-with-lz4-memory-usage
     test-compile-with-lz4-memory-usage:
     	$(MAKE) clean; CFLAGS=-O0 CPPFLAGS=-D'LZ4_MEMORY_USAGE=LZ4_MEMORY_USAGE_MIN' $(MAKE) all
     	$(MAKE) clean; CFLAGS=-O0 CPPFLAGS=-D'LZ4_MEMORY_USAGE=LZ4_MEMORY_USAGE_MAX' $(MAKE) all
     
    -.PHONY: test-lz4-sparse
     # Rules regarding Temporary test files :
     # Each test must use its own unique set of names during execution.
     # Each temporary test file must begin by an FPREFIX.
    @@ -211,312 +221,55 @@ test-compile-with-lz4-memory-usage:
     # All FPREFIX must start with `tmp`, for `make clean`
     # All tests must clean their temporary test files on successful completion,
     # and only their test files : do not employ sweeping statements such `rm tmp*` or `rm *.lz4`
    -test-lz4-sparse: FPREFIX = tmp-tls
     test-lz4-sparse: lz4 datagen
     	@echo "\n ---- test sparse file support ----"
    -	$(DATAGEN) -g5M  -P100 > $(FPREFIX)dg5M
    -	$(LZ4) -B4D $(FPREFIX)dg5M -c | $(LZ4) -dv --sparse > $(FPREFIX)cB4
    -	$(DIFF) -s $(FPREFIX)dg5M $(FPREFIX)cB4
    -	$(LZ4) -B5D $(FPREFIX)dg5M -c | $(LZ4) -dv --sparse > $(FPREFIX)cB5
    -	$(DIFF) -s $(FPREFIX)dg5M $(FPREFIX)cB5
    -	$(LZ4) -B6D $(FPREFIX)dg5M -c | $(LZ4) -dv --sparse > $(FPREFIX)cB6
    -	$(DIFF) -s $(FPREFIX)dg5M $(FPREFIX)cB6
    -	$(LZ4) -B7D $(FPREFIX)dg5M -c | $(LZ4) -dv --sparse > $(FPREFIX)cB7
    -	$(DIFF) -s $(FPREFIX)dg5M $(FPREFIX)cB7
    -	$(LZ4) $(FPREFIX)dg5M -c | $(LZ4) -dv --no-sparse > $(FPREFIX)nosparse
    -	$(DIFF) -s $(FPREFIX)dg5M $(FPREFIX)nosparse
    -	ls -ls $(FPREFIX)*
    -	$(DATAGEN) -s1 -g1200007 -P100 | $(LZ4) | $(LZ4) -dv --sparse > $(FPREFIX)odd   # Odd size file (to generate non-full last block)
    -	$(DATAGEN) -s1 -g1200007 -P100 | $(DIFF) -s - $(FPREFIX)odd
    -	ls -ls $(FPREFIX)odd
    -	@$(RM) $(FPREFIX)*
    -	@echo "\n Compatibility with Console :"
    -	echo "Hello World 1 !" | $(LZ4) | $(LZ4) -d -c
    -	echo "Hello World 2 !" | $(LZ4) | $(LZ4) -d | $(CAT)
    -	echo "Hello World 3 !" | $(LZ4) --no-frame-crc | $(LZ4) -d -c
    -	@echo "\n Compatibility with Append :"
    -	$(DATAGEN) -P100 -g1M > $(FPREFIX)dg1M
    -	$(CAT) $(FPREFIX)dg1M $(FPREFIX)dg1M > $(FPREFIX)2M
    -	$(LZ4) -B5 -v $(FPREFIX)dg1M $(FPREFIX)c
    -	$(LZ4) -d -v $(FPREFIX)c $(FPREFIX)r
    -	$(LZ4) -d -v $(FPREFIX)c -c >> $(FPREFIX)r
    -	ls -ls $(FPREFIX)*
    -	$(DIFF) $(FPREFIX)2M $(FPREFIX)r
    -	@$(RM) $(FPREFIX)*
    -
    -test-lz4-contentSize: FPREFIX = tmp-lzc
    +	./test-lz4-sparse.sh
    +
     test-lz4-contentSize: lz4 datagen
     	@echo "\n ---- test original size support ----"
    -	$(DATAGEN) -g15M > $(FPREFIX)
    -	$(LZ4) -v $(FPREFIX) -c | $(LZ4) -t
    -	$(LZ4) -v --content-size $(FPREFIX) -c | $(LZ4) -d > $(FPREFIX)-dup
    -	$(DIFF) $(FPREFIX) $(FPREFIX)-dup
    -	$(LZ4) -f $(FPREFIX) -c > $(FPREFIX).lz4 # compressed with content size
    -	$(LZ4) --content-size $(FPREFIX) -c > $(FPREFIX)-wcz.lz4
    -	! $(DIFF) $(FPREFIX).lz4 $(FPREFIX)-wcz.lz4  # must differ, due to content size
    -	$(LZ4) --content-size < $(FPREFIX) > $(FPREFIX)-wcz2.lz4 # can determine content size because stdin is just a file
    -	$(DIFF) $(FPREFIX)-wcz.lz4 $(FPREFIX)-wcz2.lz4  # both must contain content size
    -	$(CAT) $(FPREFIX) | $(LZ4) > $(FPREFIX)-ncz.lz4
    -	$(DIFF) $(FPREFIX).lz4 $(FPREFIX)-ncz.lz4  # both don't have content size
    -	$(CAT) $(FPREFIX) | $(LZ4) --content-size > $(FPREFIX)-ncz2.lz4 # can't determine content size
    -	$(DIFF) $(FPREFIX).lz4 $(FPREFIX)-ncz2.lz4  # both don't have content size
    -	@$(RM) $(FPREFIX)*
    -
    -test-lz4-frame-concatenation: FPREFIX = tmp-lfc
    +	./test-lz4-contentSize.sh
    +
     test-lz4-frame-concatenation: lz4 datagen
     	@echo "\n ---- test frame concatenation ----"
    -	@echo -n > $(FPREFIX)-empty
    -	@echo hi > $(FPREFIX)-nonempty
    -	$(CAT) $(FPREFIX)-nonempty $(FPREFIX)-empty $(FPREFIX)-nonempty > $(FPREFIX)-src
    -	$(LZ4) -zq $(FPREFIX)-empty -c > $(FPREFIX)-empty.lz4
    -	$(LZ4) -zq $(FPREFIX)-nonempty -c > $(FPREFIX)-nonempty.lz4
    -	$(CAT) $(FPREFIX)-nonempty.lz4 $(FPREFIX)-empty.lz4 $(FPREFIX)-nonempty.lz4 > $(FPREFIX)-concat.lz4
    -	$(LZ4) -d $(FPREFIX)-concat.lz4 -c > $(FPREFIX)-result
    -	$(CMP) $(FPREFIX)-src $(FPREFIX)-result
    -	@$(RM) $(FPREFIX)*
    -	@echo frame concatenation test completed
    -
    -test-lz4-multiple: FPREFIX = tmp-tml
    +	./test-lz4-frame-concatenation.sh
    +
     test-lz4-multiple: lz4 datagen
     	@echo "\n ---- test multiple files ----"
    -	@$(DATAGEN) -s1        > $(FPREFIX)1 2> $(VOID)
    -	@$(DATAGEN) -s2 -g100K > $(FPREFIX)2 2> $(VOID)
    -	@$(DATAGEN) -s3 -g200K > $(FPREFIX)3 2> $(VOID)
    -	# compress multiple files : one .lz4 per source file
    -	$(LZ4) -f -m $(FPREFIX)*
    -	test -f $(FPREFIX)1.lz4
    -	test -f $(FPREFIX)2.lz4
    -	test -f $(FPREFIX)3.lz4
    -	# decompress multiple files : one output file per .lz4
    -	mv $(FPREFIX)1 $(FPREFIX)1-orig
    -	mv $(FPREFIX)2 $(FPREFIX)2-orig
    -	mv $(FPREFIX)3 $(FPREFIX)3-orig
    -	$(LZ4) -d -f -m $(FPREFIX)*.lz4
    -	$(CMP) $(FPREFIX)1 $(FPREFIX)1-orig   # must be identical
    -	$(CMP) $(FPREFIX)2 $(FPREFIX)2-orig
    -	$(CMP) $(FPREFIX)3 $(FPREFIX)3-orig
    -	# compress multiple files into stdout
    -	$(CAT) $(FPREFIX)1.lz4 $(FPREFIX)2.lz4 $(FPREFIX)3.lz4 > $(FPREFIX)-concat1
    -	$(RM) $(FPREFIX)*.lz4
    -	$(LZ4) -m $(FPREFIX)1 $(FPREFIX)2 $(FPREFIX)3 -c > $(FPREFIX)-concat2
    -	test ! -f $(FPREFIX)1.lz4  # must not create .lz4 artefact
    -	$(CMP) $(FPREFIX)-concat1 $(FPREFIX)-concat2  # must be equivalent
    -	# decompress multiple files into stdout
    -	$(RM) $(FPREFIX)-concat1 $(FPREFIX)-concat2
    -	$(LZ4) -f -m $(FPREFIX)1 $(FPREFIX)2 $(FPREFIX)3   # generate .lz4 to decompress
    -	$(CAT) $(FPREFIX)1 $(FPREFIX)2 $(FPREFIX)3 > $(FPREFIX)-concat1   # create concatenated reference
    -	$(RM) $(FPREFIX)1 $(FPREFIX)2 $(FPREFIX)3
    -	$(LZ4) -d -m $(FPREFIX)1.lz4 $(FPREFIX)2.lz4 $(FPREFIX)3.lz4 -c > $(FPREFIX)-concat2
    -	test ! -f $(FPREFIX)1  # must not create file artefact
    -	$(CMP) $(FPREFIX)-concat1 $(FPREFIX)-concat2  # must be equivalent
    -	# compress multiple files, one of which is absent (must fail)
    -	! $(LZ4) -f -m $(FPREFIX)-concat1 notHere $(FPREFIX)-concat2  # must fail : notHere not present
    -	# test lz4-compressed file
    -	$(LZ4) -tm $(FPREFIX)-concat1.lz4
    -	$(LZ4) -tm $(FPREFIX)-concat1.lz4 $(FPREFIX)-concat2.lz4
    -	# test multiple lz4 files, one of which is absent (must fail)
    -	! $(LZ4) -tm $(FPREFIX)-concat1.lz4 notHere.lz4 $(FPREFIX)-concat2.lz4
    -	@$(RM) $(FPREFIX)*
    -
    -test-lz4-multiple-legacy: FPREFIX = tmp-lml
    +	./test-lz4-multiple.sh
    +
     test-lz4-multiple-legacy: lz4 datagen
     	@echo "\n ---- test multiple files (Legacy format) ----"
    -	@$(DATAGEN) -s1        > $(FPREFIX)1 2> $(VOID)
    -	@$(DATAGEN) -s2 -g100K > $(FPREFIX)2 2> $(VOID)
    -	@$(DATAGEN) -s3 -g200K > $(FPREFIX)3 2> $(VOID)
    -	# compress multiple files using legacy format: one .lz4 per source file
    -	$(LZ4) -f -l -m $(FPREFIX)*
    -	test -f $(FPREFIX)1.lz4
    -	test -f $(FPREFIX)2.lz4
    -	test -f $(FPREFIX)3.lz4
    -	# decompress multiple files compressed using legacy format: one output file per .lz4
    -	mv $(FPREFIX)1 $(FPREFIX)1-orig
    -	mv $(FPREFIX)2 $(FPREFIX)2-orig
    -	mv $(FPREFIX)3 $(FPREFIX)3-orig
    -	$(LZ4) -d -f -m $(FPREFIX)*.lz4
    -	$(LZ4) -l -d -f -m $(FPREFIX)*.lz4 # -l mustn't impact -d option
    -	$(CMP) $(FPREFIX)1 $(FPREFIX)1-orig   # must be identical
    -	$(CMP) $(FPREFIX)2 $(FPREFIX)2-orig
    -	$(CMP) $(FPREFIX)3 $(FPREFIX)3-orig
    -	# compress multiple files into stdout using legacy format
    -	$(CAT) $(FPREFIX)1.lz4 $(FPREFIX)2.lz4 $(FPREFIX)3.lz4 > $(FPREFIX)-concat1
    -	$(RM) $(FPREFIX)*.lz4
    -	$(LZ4) -l -m $(FPREFIX)1 $(FPREFIX)2 $(FPREFIX)3 -c > $(FPREFIX)-concat2
    -	test ! -f $(FPREFIX)1.lz4  # must not create .lz4 artefact
    -	$(CMP) $(FPREFIX)-concat1 $(FPREFIX)-concat2  # must be equivalent
    -	# # # decompress multiple files into stdout using legacy format
    -	$(RM) $(FPREFIX)-concat1 $(FPREFIX)-concat2
    -	$(LZ4) -l -f -m $(FPREFIX)1 $(FPREFIX)2 $(FPREFIX)3   # generate .lz4 to decompress
    -	$(CAT) $(FPREFIX)1 $(FPREFIX)2 $(FPREFIX)3 > $(FPREFIX)-concat1   # create concatenated reference
    -	$(RM) $(FPREFIX)1 $(FPREFIX)2 $(FPREFIX)3
    -	$(LZ4) -d -m $(FPREFIX)1.lz4 $(FPREFIX)2.lz4 $(FPREFIX)3.lz4 -c > $(FPREFIX)-concat2
    -	$(LZ4) -d -l -m $(FPREFIX)1.lz4 $(FPREFIX)2.lz4 $(FPREFIX)3.lz4 -c > $(FPREFIX)-concat2 # -l mustn't impact option -d
    -	test ! -f $(FPREFIX)1  # must not create file artefact
    -	$(CMP) $(FPREFIX)-concat1 $(FPREFIX)-concat2  # must be equivalent
    -	# # # compress multiple files, one of which is absent (must fail)
    -	! $(LZ4) -f -l -m $(FPREFIX)-concat1 notHere-legacy $(FPREFIX)-concat2  # must fail : notHere-legacy not present
    -	@$(RM) $(FPREFIX)*
    -
    -SKIPFILE = goldenSamples/skip.bin
    -test-lz4-skippable: FPREFIX = tmp-lsk
    -test-lz4-skippable: lz4 datagen
    +	./test-lz4-multiple-legacy.sh
    +
    +test-lz4-skippable: lz4
     	@echo "\n ---- test lz4 with skippable frames ----"
    -	$(LZ4) -dc $(SKIPFILE)
    -	$(LZ4) -dc < $(SKIPFILE)
    -	cat $(SKIPFILE) | $(LZ4) -dc
    -	echo "Hello from Valid Frame!\n" | $(LZ4) -c > $(FPREFIX).lz4
    -	cat $(SKIPFILE) $(FPREFIX).lz4 $(SKIPFILE) | $(LZ4) -dc
    -	$(RM) $(FPREFIX)*
    +	./test-lz4-skippable.sh
     
    -test-lz4-basic: FPREFIX = tmp-tlb
     test-lz4-basic: lz4 datagen unlz4 lz4cat
     	@echo "\n ---- test lz4 basic compression/decompression ----"
    -	$(DATAGEN) -g0       | $(LZ4) -v     | $(LZ4) -t
    -	$(DATAGEN) -g16KB    | $(LZ4) -9     | $(LZ4) -t
    -	$(DATAGEN) -g20KB > $(FPREFIX)-dg20k
    -	$(LZ4) < $(FPREFIX)-dg20k | $(LZ4) -d > $(FPREFIX)-dec
    -	$(DIFF) -q $(FPREFIX)-dg20k $(FPREFIX)-dec
    -	$(LZ4) --no-frame-crc < $(FPREFIX)-dg20k | $(LZ4) -d > $(FPREFIX)-dec
    -	$(DIFF) -q $(FPREFIX)-dg20k $(FPREFIX)-dec
    -	$(DATAGEN)           | $(LZ4) -BI    | $(LZ4) -t
    -	$(DATAGEN)           | $(LZ4) --no-crc | $(LZ4) -t
    -	$(DATAGEN) -g6M -P99 | $(LZ4) -9BD   | $(LZ4) -t
    -	$(DATAGEN) -g17M     | $(LZ4) -9v    | $(LZ4) -qt
    -	$(DATAGEN) -g33M     | $(LZ4) --no-frame-crc | $(LZ4) -t
    -	$(DATAGEN) -g256MB   | $(LZ4) -vqB4D | $(LZ4) -t --no-crc
    -	@echo "hello world" > $(FPREFIX)-hw
    -	$(LZ4) --rm -f $(FPREFIX)-hw $(FPREFIX)-hw.lz4
    -	test ! -f $(FPREFIX)-hw                      # must fail (--rm)
    -	test   -f $(FPREFIX)-hw.lz4
    -	$(PRGDIR)/lz4cat $(FPREFIX)-hw.lz4 | $(GREP) "hello world"
    -	$(PRGDIR)/unlz4 --rm $(FPREFIX)-hw.lz4 $(FPREFIX)-hw
    -	test   -f $(FPREFIX)-hw
    -	test ! -f $(FPREFIX)-hw.lz4                  # must fail (--rm)
    -	test ! -f $(FPREFIX)-hw.lz4.lz4              # must fail (unlz4)
    -	$(PRGDIR)/lz4cat $(FPREFIX)-hw               # pass-through mode
    -	test   -f $(FPREFIX)-hw
    -	test ! -f $(FPREFIX)-hw.lz4                  # must fail (lz4cat)
    -	$(LZ4) $(FPREFIX)-hw $(FPREFIX)-hw.lz4          # creates $(FPREFIX)-hw.lz4
    -	$(PRGDIR)/lz4cat < $(FPREFIX)-hw.lz4 > $(FPREFIX)3  # checks lz4cat works with stdin (#285)
    -	$(DIFF) -q $(FPREFIX)-hw $(FPREFIX)3
    -	$(PRGDIR)/lz4cat < $(FPREFIX)-hw > $(FPREFIX)2      # checks lz4cat works in pass-through mode
    -	$(DIFF) -q $(FPREFIX)-hw $(FPREFIX)2
    -	cp $(FPREFIX)-hw ./-d
    -	$(LZ4) --rm -- -d -d.lz4               # compresses ./d into ./-d.lz4
    -	test   -f ./-d.lz4
    -	test ! -f ./-d
    -	mv ./-d.lz4 ./-z
    -	$(LZ4) -d --rm -- -z $(FPREFIX)4          # uncompresses ./-z into $(FPREFIX)4
    -	test ! -f ./-z
    -	$(DIFF) -q $(FPREFIX)-hw $(FPREFIX)4
    -	! $(LZ4) $(FPREFIX)2 $(FPREFIX)3 $(FPREFIX)4    # must fail: refuse to handle 3+ file names
    -	$(LZ4) -f $(FPREFIX)-hw                   # create $(FPREFIX)-hw.lz4, for next tests
    -	$(LZ4) --list $(FPREFIX)-hw.lz4           # test --list on valid single-frame file
    -	$(LZ4) --list < $(FPREFIX)-hw.lz4         # test --list from stdin (file only)
    -	$(CAT) $(FPREFIX)-hw >> $(FPREFIX)-hw.lz4
    -	! $(LZ4) -f $(FPREFIX)-hw.lz4             # uncompress valid frame followed by invalid data (must fail now)
    -	$(LZ4) -BX $(FPREFIX)-hw -c -q | $(LZ4) -tv  # test block checksum
    -	# $(DATAGEN) -g20KB generates the same file every single time
    -	# cannot save output of $(DATAGEN) -g20KB as input file to lz4 because the following shell commands are run before $(DATAGEN) -g20KB
    -	test "$(shell $(DATAGEN) -g20KB | $(LZ4) -c --fast | wc -c)" -lt "$(shell $(DATAGEN) -g20KB | $(LZ4) -c --fast=9 | wc -c)" # -1 vs -9
    -	test "$(shell $(DATAGEN) -g20KB | $(LZ4) -c -1 | wc -c)" -lt "$(shell $(DATAGEN) -g20KB| $(LZ4) -c --fast=1 | wc -c)" # 1 vs -1
    -	test "$(shell $(DATAGEN) -g20KB | $(LZ4) -c --fast=1 | wc -c)" -eq "$(shell $(DATAGEN) -g20KB| $(LZ4) -c --fast| wc -c)" # checks default fast compression is -1
    -	! $(LZ4) -c --fast=0 $(FPREFIX)-dg20K # lz4 should fail when fast=0
    -	! $(LZ4) -c --fast=-1 $(FPREFIX)-dg20K # lz4 should fail when fast=-1
    -	# High --fast values can result in out-of-bound dereferences #876
    -	$(DATAGEN) -g1M | $(LZ4) -c --fast=999999999 > /dev/null
    -	# Test for #596
    -	@echo "TEST" > $(FPREFIX)-test
    -	$(LZ4) -m $(FPREFIX)-test
    -	$(LZ4) $(FPREFIX)-test.lz4 $(FPREFIX)-test2
    -	$(DIFF) -q $(FPREFIX)-test $(FPREFIX)-test2
    -	@$(RM) $(FPREFIX)*
    -
    -
    -test-lz4-dict: FPREFIX = tmp-dict
    +	./test-lz4-basic.sh
    +
     test-lz4-dict: lz4 datagen
     	@echo "\n ---- test lz4 compression/decompression with dictionary ----"
    -	$(DATAGEN) -g16KB > $(FPREFIX)
    -	$(DATAGEN) -g32KB > $(FPREFIX)-sample-32k
    -	< $(FPREFIX)-sample-32k $(LZ4) -D $(FPREFIX) | $(LZ4) -dD $(FPREFIX) | diff - $(FPREFIX)-sample-32k
    -	$(DATAGEN) -g128MB > $(FPREFIX)-sample-128m
    -	< $(FPREFIX)-sample-128m $(LZ4) -D $(FPREFIX) | $(LZ4) -dD $(FPREFIX) | diff - $(FPREFIX)-sample-128m
    -	touch $(FPREFIX)-sample-0
    -	< $(FPREFIX)-sample-0 $(LZ4) -D $(FPREFIX) | $(LZ4) -dD $(FPREFIX) | diff - $(FPREFIX)-sample-0
    -
    -	< $(FPREFIX)-sample-32k $(LZ4) -D $(FPREFIX)-sample-0 | $(LZ4) -dD $(FPREFIX)-sample-0 | diff - $(FPREFIX)-sample-32k
    -	< $(FPREFIX)-sample-0 $(LZ4) -D $(FPREFIX)-sample-0 | $(LZ4) -dD $(FPREFIX)-sample-0 | diff - $(FPREFIX)-sample-0
    -
    -	@echo "\n ---- test lz4 dictionary loading ----"
    -	$(DATAGEN) -g128KB > $(FPREFIX)-data-128KB
    -	set -e; \
    -	for l in 0 1 4 128 32767 32768 32769 65535 65536 65537 98303 98304 98305 131071 131072 131073; do \
    -		$(DATAGEN) -g$$l > $(FPREFIX)-$$l; \
    -		$(DD) if=$(FPREFIX)-$$l of=$(FPREFIX)-$$l-tail bs=1 count=65536 skip=$$((l > 65536 ? l - 65536 : 0)); \
    -		< $(FPREFIX)-$$l      $(LZ4) -D stdin $(FPREFIX)-data-128KB -c | $(LZ4) -dD $(FPREFIX)-$$l-tail | $(DIFF) - $(FPREFIX)-data-128KB; \
    -		< $(FPREFIX)-$$l-tail $(LZ4) -D stdin $(FPREFIX)-data-128KB -c | $(LZ4) -dD $(FPREFIX)-$$l      | $(DIFF) - $(FPREFIX)-data-128KB; \
    -	done
    -	@$(RM) $(FPREFIX)*
    +	./test-lz4-dict.sh
     
     test-lz4hc-hugefile: lz4 datagen
     	@echo "\n ---- test HC compression/decompression of huge files ----"
    -	$(DATAGEN) -g4200MB | $(LZ4) -v3BD | $(LZ4) -qt
    +	./test-lz4hc-hugefile.sh
     
    -test-lz4-fast-hugefile: FPREFIX = tmp-lfh
     test-lz4-fast-hugefile: lz4 datagen
     	@echo "\n ---- test huge files compression/decompression ----"
    -	$(DATAGEN) -g6GB    | $(LZ4) -vB5D | $(LZ4) -qt
    -	# test large file size [2-4] GB
    -	@$(DATAGEN) -g3G -P100 | $(LZ4) -vv | $(LZ4) --decompress --force --sparse - $(FPREFIX)1
    -	@ls -ls $(FPREFIX)1
    -	@$(DATAGEN) -g3G -P100 | $(LZ4) --quiet --content-size | $(LZ4) --verbose --decompress --force --sparse - $(FPREFIX)2
    -	@ls -ls $(FPREFIX)2
    -	$(DIFF) -s $(FPREFIX)1 $(FPREFIX)2
    -	@$(RM) $(FPREFIX)*
    +	./test-lz4-fast-hugefile.sh
     
     test-lz4-hugefile: test-lz4-fast-hugefile test-lz4hc-hugefile
     
    -test-lz4-testmode: FPREFIX = tmp-ltm
     test-lz4-testmode: lz4 datagen
     	@echo "\n ---- bench mode ----"
    -	$(LZ4) -bi0
    -	$(DATAGEN) > $(FPREFIX)
    -	$(LZ4) -f $(FPREFIX) -c > $(FPREFIX).lz4
    -	$(LZ4) -bdi0 $(FPREFIX).lz4 # test benchmark decode-only mode
    -	$(LZ4) -bdi0 --no-crc $(FPREFIX).lz4 # test benchmark decode-only mode
    -	@echo "\n ---- test mode ----"
    -	! $(DATAGEN) | $(LZ4) -t
    -	! $(DATAGEN) | $(LZ4) -tf
    -	@echo "\n ---- pass-through mode ----"
    -	@echo "Why hello there " > $(FPREFIX)2.lz4
    -	! $(LZ4) -f $(FPREFIX)2.lz4 > $(VOID)
    -	! $(DATAGEN) | $(LZ4) -dc  > $(VOID)
    -	! $(DATAGEN) | $(LZ4) -df > $(VOID)
    -	$(DATAGEN) | $(LZ4) -dcf > $(VOID)
    -	@echo "Hello World !" > $(FPREFIX)1
    -	$(LZ4) -dcf $(FPREFIX)1
    -	@echo "from underground..." > $(FPREFIX)2
    -	$(LZ4) -dcfm $(FPREFIX)1 $(FPREFIX)2
    -	@echo "\n ---- non-existing source (must fail cleanly) ----"
    -	! $(LZ4)     file-does-not-exist
    -	! $(LZ4) -f  file-does-not-exist
    -	! $(LZ4) -t  file-does-not-exist
    -	! $(LZ4) -fm file1-dne file2-dne
    -	@$(RM) $(FPREFIX)*
    +	./test-lz4-testmode.sh
     
     test-lz4-opt-parser: lz4 datagen
     	@echo "\n ---- test opt-parser ----"
    -	$(DATAGEN) -g16KB      | $(LZ4) -12      | $(LZ4) -t
    -	$(DATAGEN) -P10        | $(LZ4) -12B4    | $(LZ4) -t
    -	$(DATAGEN) -g256K      | $(LZ4) -12B4D   | $(LZ4) -t
    -	$(DATAGEN) -g512K -P25 | $(LZ4) -12BD    | $(LZ4) -t
    -	$(DATAGEN) -g1M        | $(LZ4) -12B5    | $(LZ4) -t
    -	$(DATAGEN) -g1M -s2    | $(LZ4) -12B4D   | $(LZ4) -t
    -	$(DATAGEN) -g2M -P99   | $(LZ4) -11B4D   | $(LZ4) -t
    -	$(DATAGEN) -g4M        | $(LZ4) -11vq    | $(LZ4) -qt
    -	$(DATAGEN) -g8M        | $(LZ4) -11B4    | $(LZ4) -t
    -	$(DATAGEN) -g16M -P90  | $(LZ4) -11B5    | $(LZ4) -t
    -	$(DATAGEN) -g32M -P10  | $(LZ4) -11B5D   | $(LZ4) -t
    +	./test-lz4-opt-parser.sh
     
     test-lz4-essentials : lz4 datagen test-lz4-basic test-lz4-multiple test-lz4-multiple-legacy \
                           test-lz4-frame-concatenation test-lz4-testmode \
    @@ -609,10 +362,36 @@ test-decompress-partial : decompress-partial decompress-partial-usingDict
     	@echo "\n ---- test decompress-partial-usingDict ----"
     	./decompress-partial-usingDict$(EXT)
     
    +
    +#-----------------------------------------------------------------------------
    +# freestanding test only for Linux x86_64
    +#-----------------------------------------------------------------------------
    +UNAME_S ?= $(if $(filter Windows_NT,$(OS)),Windows,$(shell uname -s))
    +UNAME_P ?= $(if $(filter Windows_NT,$(OS)),Unknown,$(shell uname -p))
    +
    +FREESTANDING_CFLAGS := -ffreestanding -nostdlib
    +
    +ifneq ($(UNAME_S), Linux)
    +  FREESTANDING_CFLAGS :=
    +endif
    +
    +ifneq ($(UNAME_P), x86_64)
    +  FREESTANDING_CFLAGS :=
    +endif
    +
    +CLEAN += freestanding
    +freestanding: freestanding.c
    +	$(CC) $(FREESTANDING_CFLAGS) $^ -o $@$(EXT)
    +
     test-freestanding: freestanding
     	@echo "\n ---- test freestanding ----"
    +ifeq ($(FREESTANDING_CFLAGS),)
    +	@echo "\n (skip)"
    +else
     	./freestanding$(EXT)
     	-strace ./freestanding$(EXT)
     	-ltrace ./freestanding$(EXT)
    +endif
    +
     
     endif
    diff --git a/tests/checkFrame.c b/tests/checkFrame.c
    index 946805ff4853a8c613831dfa5139c359da4e9bed..f083520f1e29e2a005f78b4060b985c47ce36813 100644
    --- a/tests/checkFrame.c
    +++ b/tests/checkFrame.c
    @@ -1,76 +1,85 @@
    -  /*
    -      checkFrame - verify frame headers
    -      Copyright (C) Yann Collet 2014-2020
    -
    -      GPL v2 License
    -
    -      This program is free software; you can redistribute it and/or modify
    -      it under the terms of the GNU General Public License as published by
    -      the Free Software Foundation; either version 2 of the License, or
    -      (at your option) any later version.
    -
    -      This program is distributed in the hope that it will be useful,
    -      but WITHOUT ANY WARRANTY; without even the implied warranty of
    -      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    -      GNU General Public License for more details.
    -
    -      You should have received a copy of the GNU General Public License along
    -      with this program; if not, write to the Free Software Foundation, Inc.,
    -      51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
    -
    -      You can contact the author at :
    -      - LZ4 homepage : http://www.lz4.org
    -      - LZ4 source repository : https://github.com/lz4/lz4
    -  */
    -
    -  /*-************************************
    -  *  Includes
    -  **************************************/
    -  #include "util.h"       /* U32 */
    -  #include      /* malloc, free */
    -  #include       /* fprintf */
    -  #include      /* strcmp */
    -  #include        /* clock_t, clock(), CLOCKS_PER_SEC */
    -  #include 
    -  #include "lz4frame.h"   /* include multiple times to test correctness/safety */
    -  #include "lz4frame.h"
    -  #define LZ4F_STATIC_LINKING_ONLY
    -  #include "lz4frame.h"
    -  #include "lz4frame.h"
    -  #include "lz4.h"        /* LZ4_VERSION_STRING */
    -  #define XXH_STATIC_LINKING_ONLY
    -  #include "xxhash.h"     /* XXH64 */
    -
    -
    -  /*-************************************
    -  *  Constants
    -  **************************************/
    -  #define KB *(1U<<10)
    -  #define MB *(1U<<20)
    -  #define GB *(1U<<30)
    -
    -
    -  /*-************************************
    -  *  Macros
    -  **************************************/
    -  #define DISPLAY(...)          fprintf(stderr, __VA_ARGS__)
    -  #define DISPLAYLEVEL(l, ...)  if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }
    -
    -  /**************************************
    -  *  Exceptions
    -  ***************************************/
    -  #ifndef DEBUG
    -  #  define DEBUG 0
    -  #endif
    -  #define DEBUGOUTPUT(...) if (DEBUG) DISPLAY(__VA_ARGS__);
    -  #define EXM_THROW(error, ...)                                             \
    -{                                                                         \
    +/*
    +    checkFrame - verify frame headers
    +    Copyright (C) Yann Collet 2014-2020
    +
    +    GPL v2 License
    +
    +    This program is free software; you can redistribute it and/or modify
    +    it under the terms of the GNU General Public License as published by
    +    the Free Software Foundation; either version 2 of the License, or
    +    (at your option) any later version.
    +
    +    This program is distributed in the hope that it will be useful,
    +    but WITHOUT ANY WARRANTY; without even the implied warranty of
    +    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    +    GNU General Public License for more details.
    +
    +    You should have received a copy of the GNU General Public License along
    +    with this program; if not, write to the Free Software Foundation, Inc.,
    +    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
    +
    +    You can contact the author at :
    +    - LZ4 homepage : http://www.lz4.org
    +    - LZ4 source repository : https://github.com/lz4/lz4
    +*/
    +
    +
    +/*-************************************
    +*  Compiler options
    +**************************************/
    +#ifdef _MSC_VER    /* Visual Studio */
    +#  pragma warning(disable : 4127)    /* disable: C4127: conditional expression is constant */
    +#endif
    +
    +
    +/*-************************************
    +*  Includes
    +**************************************/
    +#include "util.h"       /* U32 */
    +#include      /* malloc, free */
    +#include       /* fprintf */
    +#include      /* strcmp */
    +#include        /* clock_t, clock(), CLOCKS_PER_SEC */
    +#include 
    +#include "lz4frame.h"   /* include multiple times to test correctness/safety */
    +#include "lz4frame.h"
    +#define LZ4F_STATIC_LINKING_ONLY
    +#include "lz4frame.h"
    +#include "lz4frame.h"
    +#include "lz4.h"        /* LZ4_VERSION_STRING */
    +#define XXH_STATIC_LINKING_ONLY
    +#include "xxhash.h"     /* XXH64 */
    +
    +
    +/*-************************************
    +*  Constants
    +**************************************/
    +#define KB *(1U<<10)
    +#define MB *(1U<<20)
    +#define GB *(1U<<30)
    +
    +
    +/*-************************************
    +*  Macros
    +**************************************/
    +#define DISPLAY(...)          fprintf(stderr, __VA_ARGS__)
    +#define DISPLAYLEVEL(l, ...)  if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }
    +
    +/**************************************
    +*  Exceptions
    +***************************************/
    +#ifndef DEBUG
    +#  define DEBUG 0
    +#endif
    +#define DEBUGOUTPUT(...) do { if (DEBUG) DISPLAY(__VA_ARGS__); } while (0)
    +#define EXM_THROW(error, ...)                                           \
    +do {                                                                      \
         DEBUGOUTPUT("Error defined at %s, line %i : \n", __FILE__, __LINE__); \
         DISPLAYLEVEL(1, "Error %i : ", error);                                \
         DISPLAYLEVEL(1, __VA_ARGS__);                                         \
         DISPLAYLEVEL(1, " \n");                                               \
    -    return(error);                                                          \
    -}
    +    return(error);                                                        \
    +} while (0)
     
     
     
    diff --git a/tests/cmake/CMakeLists.txt b/tests/cmake/CMakeLists.txt
    new file mode 100644
    index 0000000000000000000000000000000000000000..707772451c8a28ea01f440b2bec786112389fd2c
    --- /dev/null
    +++ b/tests/cmake/CMakeLists.txt
    @@ -0,0 +1,28 @@
    +cmake_minimum_required(VERSION 3.5)
    +
    +project(cmake_install_test LANGUAGES C)
    +
    +# Find LZ4 installation in Config mode
    +find_package(lz4 CONFIG REQUIRED)
    +
    +# Verify that the universal target always exists
    +if (NOT TARGET LZ4::lz4)
    +  message(FATAL_ERROR "LZ4::lz4 target does not exist!")
    +endif()
    +
    +# Verify that the location property is set
    +get_property(LZ4_LOCATION TARGET LZ4::lz4_shared PROPERTY LOCATION)
    +if (NOT LZ4_LOCATION)
    +  message(FATAL_ERROR "Missing LOCATION property for LZ4::lz4_shared!")
    +endif()
    +
    +# Verify that the include directory property is set
    +get_property(LZ4_SHARED_INCLUDE_DIRECTORIES TARGET LZ4::lz4_shared PROPERTY INTERFACE_INCLUDE_DIRECTORIES)
    +if (NOT LZ4_SHARED_INCLUDE_DIRECTORIES)
    +  message(FATAL_ERROR "Missing INTERFACE_INCLUDE_DIRECTORIES property for LZ4::lz4_shared!")
    +endif()
    +
    +# Add a test that builds against the installation
    +set(LZ4_TESTS_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/..")
    +add_executable(decompress-partial "${LZ4_TESTS_SOURCE_DIR}/decompress-partial.c")
    +target_link_libraries(decompress-partial LZ4::lz4_shared)
    diff --git a/programs/datagen.c b/tests/datagen.c
    similarity index 98%
    rename from programs/datagen.c
    rename to tests/datagen.c
    index f44864024240f01ff5414e444e266c74c3b612eb..4b5039a43ef0a5d8f210227e2e2009b3c254c22a 100644
    --- a/programs/datagen.c
    +++ b/tests/datagen.c
    @@ -1,6 +1,6 @@
     /*
         datagen.c - compressible data generator test tool
    -    Copyright (C) Yann Collet 2012-2020
    +    Copyright (C) Yann Collet 2012-2024
     
         GPL v2 License
     
    @@ -52,7 +52,6 @@
     typedef BYTE litDistribTable[LTSIZE];
     
     
    -
     /*********************************************************
     *  Local Functions
     *********************************************************/
    @@ -133,7 +132,7 @@ void RDG_genBlock(void* buffer, size_t buffSize, size_t prefixSize, double match
                 /* Copy (within 32K) */
                 size_t match;
                 size_t d;
    -            int length = RDG_RANDLENGTH + 4;
    +            size_t length = RDG_RANDLENGTH + 4;
                 U32 offset = RDG_RAND15BITS + 1;
                 if (offset > pos) offset = (U32)pos;
                 match = pos - offset;
    diff --git a/programs/datagen.h b/tests/datagen.h
    similarity index 72%
    rename from programs/datagen.h
    rename to tests/datagen.h
    index c20c9c7df3cc4b7308d222ca8ef1c0b67362d644..4d73c404866031cce178a69b37b796240202743f 100644
    --- a/programs/datagen.h
    +++ b/tests/datagen.h
    @@ -1,6 +1,6 @@
     /*
         datagen.h - compressible data generator header
    -    Copyright (C) Yann Collet 2012-2020
    +    Copyright (C) Yann Collet 2012-2024
     
         GPL v2 License
     
    @@ -26,15 +26,17 @@
     
     #include    /* size_t */
     
    +/* RDG_genOut():
    + * Generate @size bytes of compressible data into stdout.
    + * Compressibility can be controlled using @matchProba.
    + * @LitProba is optional, and affect variability of bytes. If @litProba==0.0, default value is used.
    + * Generated data can be influenced using @seed.
    + * If @matchProba, @litProba and @seed are equal, the function always generates the same content.
    + */
     void RDG_genOut(unsigned long long size, double matchProba, double litProba, unsigned seed);
    +
    +/*
    + * RDG_genBuffer():
    + * Same as RDG_genOut, but generates data into provided @buffer
    + */
     void RDG_genBuffer(void* buffer, size_t size, double matchProba, double litProba, unsigned seed);
    -/* RDG_genOut
    -   Generate 'size' bytes of compressible data into stdout.
    -   Compressibility can be controlled using 'matchProba'.
    -   'LitProba' is optional, and affect variability of bytes. If litProba==0.0, default value is used.
    -   Generated data can be selected using 'seed'.
    -   If (matchProba, litProba and seed) are equal, the function always generate the same content.
    -
    -   RDG_genBuffer
    -   Same as RDG_genOut, but generate data into provided buffer
    -*/
    diff --git a/tests/datagencli.c b/tests/datagencli.c
    index ccb27dfc6886bcfe8da27a407bebc7d736e78ec0..6990043ee3ab4ea014f138300073388baf40fcad 100644
    --- a/tests/datagencli.c
    +++ b/tests/datagencli.c
    @@ -24,12 +24,14 @@
        - Public forum : https://groups.google.com/forum/#!forum/lz4c
     */
     
    +
     /**************************************
     *  Includes
     **************************************/
     #include "util.h"      /* U32 */
     #include      /* fprintf, stderr */
     #include "datagen.h"   /* RDG_generate */
    +#include "loremOut.h"  /* LOREM_genOut */
     #include "lz4.h"       /* LZ4_VERSION_STRING */
     
     
    @@ -37,7 +39,8 @@
     *  Compiler specific
     **************************************/
     #ifdef _MSC_VER    /* Visual Studio */
    -#define strtoull    _strtoui64  /* https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/strtoui64-wcstoui64-strtoui64-l-wcstoui64-l */
    +# pragma warning(disable : 4127)    /* disable: C4127: conditional expression is constant */
    +# define strtoull  _strtoui64  /* https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/strtoui64-wcstoui64-strtoui64-l-wcstoui64-l */
     #endif
     
     
    @@ -50,14 +53,14 @@
     
     #define SIZE_DEFAULT (64 KB)
     #define SEED_DEFAULT 0
    -#define COMPRESSIBILITY_DEFAULT 50
    +#define COMPRESSIBILITY_NOT_SET 9999
     
     
     /**************************************
     *  Macros
     **************************************/
     #define DISPLAY(...)         fprintf(stderr, __VA_ARGS__)
    -#define DISPLAYLEVEL(l, ...) if (displayLevel>=l) { DISPLAY(__VA_ARGS__); }
    +#define DISPLAYLEVEL(l, ...) do { if (displayLevel>=(l)) DISPLAY(__VA_ARGS__); } while (0)
     static unsigned displayLevel = 2;
     
     
    @@ -73,7 +76,7 @@ static int usage(char* programName)
         DISPLAY( "Arguments :\n");
         DISPLAY( " -g#    : generate # data (default:%i)\n", SIZE_DEFAULT);
         DISPLAY( " -s#    : Select seed (default:%i)\n", SEED_DEFAULT);
    -    DISPLAY( " -P#    : Select compressibility in %% (default:%i%%)\n", COMPRESSIBILITY_DEFAULT);
    +    DISPLAY( " -P#    : Select compressibility in %% (range [0-100])\n");
         DISPLAY( " -h     : display help and exit\n");
         DISPLAY( "Special values :\n");
         DISPLAY( " -P0    : generate incompressible noise\n");
    @@ -85,28 +88,24 @@ static int usage(char* programName)
     int main(int argc, char** argv)
     {
         int argNb;
    -    double proba = (double)COMPRESSIBILITY_DEFAULT / 100;
    +    unsigned long long proba = COMPRESSIBILITY_NOT_SET;
         double litProba = 0.0;
         U64 size = SIZE_DEFAULT;
    -    U32 seed = SEED_DEFAULT;
    +    unsigned seed = SEED_DEFAULT;
         char* programName;
     
         /* Check command line */
         programName = argv[0];
    -    for(argNb=1; argNb