diff --git a/doc/contribute.rst b/doc/contribute.rst index 0abb1538..12850c2a 100644 --- a/doc/contribute.rst +++ b/doc/contribute.rst @@ -89,12 +89,18 @@ The meaning of those integers is filter dependent and is described below. bitshuffle .......... -compression_opts: (**block_size**, **lz4 compression**) +compression_opts: (**block_size**, **compression**, **level**) - **block size**: Number of elements (not bytes) per block. It MUST be a mulitple of 8. Default: 0 for a block size of about 8 kB. -- **lz4 compression**: 0: disabled (default), 2: enabled. +- **compression**: + + * 0: No compression + * 2: LZ4 + * 3: Zstd + +- **level**: Compression level, only used with Zstd compression. By default the filter uses bitshuffle, but does NOT compress with LZ4. diff --git a/doc/information.rst b/doc/information.rst index 1c761868..8dcd19b1 100644 --- a/doc/information.rst +++ b/doc/information.rst @@ -50,7 +50,7 @@ HDF5 filters and compression libraries HDF5 compression filters and compression libraries sources were obtained from: * LZ4 plugin (commit d48f960) and lz4 (v1.9.3): https://github.com/nexusformat/HDF5-External-Filter-Plugins and https://github.com/Blosc/c-blosc/tree/v1.21.1/internal-complibs/lz4-1.9.3 -* bitshuffle plugin (0.3.5): https://github.com/kiyo-masui/bitshuffle +* bitshuffle plugin (0.4.2 + patch `PR #122 `_) and zstd (v1.5.0): https://github.com/kiyo-masui/bitshuffle and https://github.com/Blosc/c-blosc/tree/v1.21.1/internal-complibs/zstd-1.5.0 * bzip2 plugin (from PyTables v3.7.0) and bzip2 (v1.0.8): https://github.com/PyTables/PyTables/, https://sourceware.org/git/bzip2.git * hdf5-blosc plugin (v1.0.0), c-blosc (v1.21.1) and snappy (v1.1.9): https://github.com/Blosc/hdf5-blosc, https://github.com/Blosc/c-blosc and https://github.com/google/snappy * FCIDECOMP plugin (v1.0.2) and CharLS (branch 1.x-master SHA1 ID: 25160a42fb62e71e4b0ce081f5cb3f8bb73938b5): diff --git a/setup.py b/setup.py index fe2f2815..1a3356af 100644 --- a/setup.py +++ b/setup.py @@ -539,37 +539,6 @@ def prefix(directory, files): """Mapping plugin name to library name they depend on""" -# bitshuffle (+lz4) plugin -# Plugins from https://github.com/kiyo-masui/bitshuffle -bithsuffle_dir = 'src/bitshuffle' - -# Set compile args for both MSVC and others, list is stripped at build time -extra_compile_args = ['-O3', '-ffast-math', '-std=c99', '-fopenmp'] -extra_compile_args += ['/Ox', '/fp:fast', '/openmp'] -if platform.machine() == "ppc64le": - # Required on ppc64le - sse2_options = {'extra_compile_args': ['-DUSESSE2'] } -else: - sse2_options = {} -extra_link_args = ['-fopenmp', '/openmp'] - -bithsuffle_plugin = HDF5PluginExtension( - "hdf5plugin.plugins.libh5bshuf", - sources=prefix(bithsuffle_dir, - ["src/bshuf_h5plugin.c", "src/bshuf_h5filter.c", - "src/bitshuffle.c", "src/bitshuffle_core.c", - "src/iochain.c", "lz4/lz4.c"]), - depends=prefix(bithsuffle_dir, - ["src/bitshuffle.h", "src/bitshuffle_core.h", - "src/iochain.h", 'src/bshuf_h5filter.h', - "lz4/lz4.h"]), - include_dirs=prefix(bithsuffle_dir, ['src/', 'lz4/']), - extra_compile_args=extra_compile_args, - extra_link_args=extra_link_args, - sse2=sse2_options, - ) - - # blosc plugin # Plugin from https://github.com/Blosc/hdf5-blosc # c-blosc from https://github.com/Blosc/c-blosc @@ -633,10 +602,14 @@ def prefix(directory, files): define_macros.append(('HAVE_ZLIB', 1)) # zstd -sources += glob(blosc_dir +'internal-complibs/zstd*/*/*.c') -depends += glob(blosc_dir +'internal-complibs/zstd*/*/*.h') -include_dirs += glob(blosc_dir + 'internal-complibs/zstd*') -include_dirs += glob(blosc_dir + 'internal-complibs/zstd*/common') +zstd_sources = glob(blosc_dir +'internal-complibs/zstd*/*/*.c') +zstd_depends = glob(blosc_dir +'internal-complibs/zstd*/*/*.h') +zstd_include_dirs = glob(blosc_dir + 'internal-complibs/zstd*') +zstd_include_dirs += glob(blosc_dir + 'internal-complibs/zstd*/common') + +sources += zstd_sources +depends += zstd_depends +include_dirs += zstd_include_dirs define_macros.append(('HAVE_ZSTD', 1)) extra_compile_args = ['-std=gnu99'] # Needed to build manylinux1 wheels @@ -664,19 +637,50 @@ def prefix(directory, files): # HDF5Plugin-Zstandard zstandard_dir = os.path.join("src", "HDF5Plugin-Zstandard") -zstandard_include_dirs = glob(blosc_dir + 'internal-complibs/zstd*') -zstandard_include_dirs += glob(blosc_dir + 'internal-complibs/zstd*/common') zstandard_sources = [os.path.join(zstandard_dir, 'zstd_h5plugin.c')] -zstandard_sources += glob(blosc_dir +'internal-complibs/zstd*/*/*.c') +zstandard_sources += zstd_sources zstandard_depends = [os.path.join(zstandard_dir, 'zstd_h5plugin.h')] -zstandard_depends += glob(blosc_dir +'internal-complibs/zstd*/*/*.h') +zstandard_depends += zstd_depends zstandard_plugin = HDF5PluginExtension( "hdf5plugin.plugins.libh5zstd", sources=zstandard_sources, depends=zstandard_depends, - include_dirs=zstandard_include_dirs, + include_dirs=zstd_include_dirs, ) +# bitshuffle (+lz4 or zstd) plugin +# Plugins from https://github.com/kiyo-masui/bitshuffle +bithsuffle_dir = 'src/bitshuffle' + +# Set compile args for both MSVC and others, list is stripped at build time +extra_compile_args = ['-O3', '-ffast-math', '-std=c99', '-fopenmp'] +extra_compile_args += ['/Ox', '/fp:fast', '/openmp'] +if platform.machine() == "ppc64le": + # Required on ppc64le + sse2_options = {'extra_compile_args': ['-DUSESSE2'] } +else: + sse2_options = {} +extra_link_args = ['-fopenmp', '/openmp'] +define_macros = [("ZSTD_SUPPORT", 1)] + +bithsuffle_plugin = HDF5PluginExtension( + "hdf5plugin.plugins.libh5bshuf", + sources=prefix(bithsuffle_dir, + ["src/bshuf_h5plugin.c", "src/bshuf_h5filter.c", + "src/bitshuffle.c", "src/bitshuffle_core.c", + "src/iochain.c", "lz4/lz4.c"]) + zstd_sources, + depends=prefix(bithsuffle_dir, + ["src/bitshuffle.h", "src/bitshuffle_core.h", + "src/iochain.h", 'src/bshuf_h5filter.h', + "lz4/lz4.h"]) + zstd_depends, + include_dirs=prefix(bithsuffle_dir, ['src/', 'lz4/']) + zstd_include_dirs, + define_macros=define_macros, + extra_compile_args=extra_compile_args, + extra_link_args=extra_link_args, + sse2=sse2_options, + ) + + # lz4 plugin # Source from https://github.com/nexusformat/HDF5-External-Filter-Plugins diff --git a/src/bitshuffle/.github/workflows/flake8_cython.cfg b/src/bitshuffle/.github/workflows/flake8_cython.cfg new file mode 100644 index 00000000..9e5b5389 --- /dev/null +++ b/src/bitshuffle/.github/workflows/flake8_cython.cfg @@ -0,0 +1,4 @@ +[flake8] +filename=*.pyx,*.pxd +select=E302,E203,E111,E114,E221,E303,E128,E231,E126,E265,E305,E301,E127,E261,E271,E129,W291,E222,E241,E123,F403,C400,C401,C402,C403,C404,C405,C406,C407,C408,C409,C410,C411 +show_source=True diff --git a/src/bitshuffle/.github/workflows/flake8_python.cfg b/src/bitshuffle/.github/workflows/flake8_python.cfg new file mode 100644 index 00000000..b0760928 --- /dev/null +++ b/src/bitshuffle/.github/workflows/flake8_python.cfg @@ -0,0 +1,3 @@ +[flake8] +ignore=E501,E203,W503,E266 +show_source=True diff --git a/src/bitshuffle/.github/workflows/install_hdf5.sh b/src/bitshuffle/.github/workflows/install_hdf5.sh new file mode 100644 index 00000000..58b2bdb4 --- /dev/null +++ b/src/bitshuffle/.github/workflows/install_hdf5.sh @@ -0,0 +1,10 @@ +HDF5_VERSION=$1 + +# Download and install HDF5 $HDF5_VERSION from source for building wheels +curl https://support.hdfgroup.org/ftp/HDF5/releases/hdf5-${HDF5_VERSION%.*}/hdf5-$HDF5_VERSION/src/hdf5-$HDF5_VERSION.tar.gz -O -s +tar -xzf hdf5-$HDF5_VERSION.tar.gz +cd hdf5-$HDF5_VERSION +./configure --prefix=/usr/local +make -j 2 +make install +cd .. diff --git a/src/bitshuffle/.github/workflows/lint.yml b/src/bitshuffle/.github/workflows/lint.yml new file mode 100644 index 00000000..6d828a1c --- /dev/null +++ b/src/bitshuffle/.github/workflows/lint.yml @@ -0,0 +1,32 @@ +name: bitshuffle-ci-build +on: + pull_request: + branches: + - master + push: + branches: + - master + +jobs: + + lint-code: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Set up Python 3.10 + uses: actions/setup-python@v2 + with: + python-version: "3.10" + + - name: Install pip dependencies + run: | + pip install black flake8 + + - name: Run flake8 + run: | + flake8 --config $GITHUB_WORKSPACE/.github/workflows/flake8_python.cfg bitshuffle tests + flake8 --config $GITHUB_WORKSPACE/.github/workflows/flake8_cython.cfg bitshuffle tests + + - name: Check code with black + run: black --check . diff --git a/src/bitshuffle/.github/workflows/main.yml b/src/bitshuffle/.github/workflows/main.yml new file mode 100644 index 00000000..8ec96b64 --- /dev/null +++ b/src/bitshuffle/.github/workflows/main.yml @@ -0,0 +1,58 @@ +name: bitshuffle-ci-build +on: + pull_request: + branches: + - master + push: + branches: + - master + +jobs: + run-tests: + + strategy: + matrix: + python-version: ["3.6", "3.7", "3.10"] + os: [ubuntu-latest, macos-latest] + exclude: + - os: macos-latest + python-version: "3.6" + + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v2 + + - name: Install apt dependencies + if: ${{ matrix.os == 'ubuntu-latest' }} + run: | + sudo apt-get install -y libhdf5-serial-dev hdf5-tools pkg-config + + - name: Install homebrew dependencies + if: ${{ matrix.os == 'macos-latest' }} + run: | + brew install hdf5 pkg-config + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + + - name: Install h5py + if: ${{ matrix.os == 'macos-latest' }} + run: | + pip install h5py + + - name: Install pip dependencies + run: | + pip install Cython + pip install -r requirements.txt + pip install pytest + + # Pull in ZSTD repo + git submodule update --init + + # Installing the plugin to arbitrary directory to check the install script. + python setup.py install --h5plugin --h5plugin-dir ~/hdf5/lib --zstd + + - name: Run tests + run: pytest -v . diff --git a/src/bitshuffle/.github/workflows/wheels.yml b/src/bitshuffle/.github/workflows/wheels.yml new file mode 100644 index 00000000..def84e0b --- /dev/null +++ b/src/bitshuffle/.github/workflows/wheels.yml @@ -0,0 +1,98 @@ +name: Build bitshuffle wheels and upload to PyPI + +on: + workflow_dispatch: + release: + types: + - published + +jobs: + build_wheels: + name: Build wheels on ${{ matrix.os }} and hdf5-${{ matrix.hdf5 }} + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, macos-latest] + hdf5: ["1.10.7"] + + steps: + # Checkout bitshuffle + - uses: actions/checkout@v2 + + # Build wheels for linux and x86 platforms + - name: Build wheels + uses: pypa/cibuildwheel@v2.3.1 + with: + output-dir: ./wheelhouse-hdf5-${{ matrix.hdf5}} + env: + CIBW_SKIP: "pp* *musllinux*" + CIBW_ARCHS_LINUX: "x86_64" + CIBW_BEFORE_ALL: | + chmod +x .github/workflows/install_hdf5.sh + .github/workflows/install_hdf5.sh ${{ matrix.hdf5 }} + git submodule update --init + CIBW_ENVIRONMENT: | + LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib ENABLE_ZSTD=1 + CIBW_TEST_REQUIRES: pytest + # Install different version of HDF5 for unit tests to ensure the + # wheels are independent of HDF5 installation + # CIBW_BEFORE_TEST: | + # chmod +x .github/workflows/install_hdf5.sh + # .github/workflows/install_hdf5.sh 1.8.11 + # Run units tests but disable test_h5plugin.py + CIBW_TEST_COMMAND: pytest {package}/tests + + # Package wheels and host on CI + - uses: actions/upload-artifact@v2 + with: + path: ./wheelhouse-hdf5-${{ matrix.hdf5 }}/*.whl + + build_sdist: + name: Build source distribution + strategy: + matrix: + python-version: ["3.8"] + + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Install apt dependencies + run: | + sudo apt-get install -y libhdf5-serial-dev hdf5-tools pkg-config + + - name: Install Python + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + + - name: Install pip dependencies + run: | + pip install -r requirements.txt + + - name: Build sdist + run: python setup.py sdist + + - uses: actions/upload-artifact@v2 + with: + path: dist/*.tar.gz + + # Upload to PyPI + upload_pypi: + needs: [build_wheels, build_sdist] + runs-on: ubuntu-latest + # Upload to PyPI on every tag + # if: github.event_name == 'push' && startsWith(github.event.ref, 'refs/tags') + # Alternatively, to publish when a GitHub Release is created, use the following rule: + if: github.event_name == 'release' && github.event.action == 'published' + steps: + - uses: actions/download-artifact@v2 + with: + name: artifact + path: dist + + - uses: pypa/gh-action-pypi-publish@v1.4.2 + with: + user: __token__ + password: ${{ secrets.pypi_password }} + # To test: repository_url: https://test.pypi.org/legacy/ diff --git a/src/bitshuffle/.gitignore b/src/bitshuffle/.gitignore index d8d6cf49..f4a98eab 100644 --- a/src/bitshuffle/.gitignore +++ b/src/bitshuffle/.gitignore @@ -75,3 +75,5 @@ doc/generated bitshuffle/ext.c bitshuffle/h5.c +# ItelliJ +.idea diff --git a/src/bitshuffle/.gitmodules b/src/bitshuffle/.gitmodules new file mode 100644 index 00000000..5ebea353 --- /dev/null +++ b/src/bitshuffle/.gitmodules @@ -0,0 +1,3 @@ +[submodule "zstd"] + path = zstd + url = https://github.com/facebook/zstd diff --git a/src/bitshuffle/.travis.yml b/src/bitshuffle/.travis.yml deleted file mode 100644 index 7b5b4994..00000000 --- a/src/bitshuffle/.travis.yml +++ /dev/null @@ -1,33 +0,0 @@ -language: python -os: linux -# To test filter plugins, need hdf5 1.8.11+, present in Trusty but not Precise. -dist: trusty -# Required to get Trusty. -#sudo: true -python: - - "2.7" - - "3.4" - - "3.5" - - "3.6" -addons: - apt: - packages: - - libhdf5-serial-dev - - hdf5-tools -install: - - "pip install -U pip virtualenv" - # Ensures the system hdf5 headers/libs will be used whatever its version - - "export HDF5_DIR=/usr/lib" - - "pip install -r requirements.txt" - # Installing the plugin to arbitrary directory to check the install script. - - "python setup.py install --h5plugin --h5plugin-dir ~/hdf5/lib" - # Ensure it's installable and usable in virtualenv - - "virtualenv ~/venv" - - "travis_wait 30 ~/venv/bin/pip -v install --no-binary=h5py ." - - "~/venv/bin/pip -v install nose" -# Can't be somewhere that has a 'bitshuffle' directory as nose will use that -# copy instead of installed package. -script: - - "cd ~" - - "nosetests -v bitshuffle" # Test the system install - - "venv/bin/nosetests -v bitshuffle" # Test the virtualenv install diff --git a/src/bitshuffle/README.rst b/src/bitshuffle/README.rst index 343b4c62..7e4be25f 100644 --- a/src/bitshuffle/README.rst +++ b/src/bitshuffle/README.rst @@ -21,12 +21,12 @@ is performed within blocks of data roughly 8kB long [1]_. This does not in itself compress data, only rearranges it for more efficient compression. To perform the actual compression you will need a compression -library. Bitshuffle has been designed to be well matched Marc Lehmann's -LZF_ as well as LZ4_. Note that because Bitshuffle modifies the data at the bit +library. Bitshuffle has been designed to be well matched to Marc Lehmann's +LZF_ as well as LZ4_ and ZSTD_. Note that because Bitshuffle modifies the data at the bit level, sophisticated entropy reducing compression libraries such as GZIP and BZIP are unlikely to achieve significantly better compression than simpler and -faster duplicate-string-elimination algorithms such as LZF and LZ4. Bitshuffle -thus includes routines (and HDF5 filter options) to apply LZ4 compression to +faster duplicate-string-elimination algorithms such as LZF, LZ4 and ZSTD. Bitshuffle +thus includes routines (and HDF5 filter options) to apply LZ4 and ZSTD compression to each block after shuffling [2]_. The Bitshuffle algorithm relies on neighbouring elements of a dataset being @@ -50,7 +50,7 @@ used outside of python and in command line utilities such as ``h5dump``. .. [1] Chosen to fit comfortably within L1 cache as well as be well matched window of the LZF compression library. -.. [2] Over applying bitshuffle to the full dataset then applying LZ4 +.. [2] Over applying bitshuffle to the full dataset then applying LZ4/ZSTD compression, this has the tremendous advantage that the block is already in the L1 cache. @@ -62,6 +62,8 @@ used outside of python and in command line utilities such as ``h5dump``. .. _LZ4: https://code.google.com/p/lz4/ +.. _ZSTD: https://github.com/facebook/zstd + Applications ------------ @@ -96,14 +98,15 @@ Installation for Python ----------------------- Installation requires python 2.7+ or 3.3+, HDF5 1.8.4 or later, HDF5 for python -(h5py), Numpy and Cython. Bitshuffle must be linked against the same version of -HDF5 as h5py, which in practice means h5py must be built from source_ rather -than pre-built wheels [3]_. To use the dynamically loaded HDF5 filter requires -HDF5 1.8.11 or later. +(h5py), Numpy and Cython. Bitshuffle is linked against HDF5. To use the dynamically +loaded HDF5 filter requires HDF5 1.8.11 or later. If ZSTD support is enabled the ZSTD +repo needs to pulled into bitshuffle before installation with:: + + git submodule update --init -To install:: +To install bitshuffle:: - python setup.py install [--h5plugin [--h5plugin-dir=spam]] + python setup.py install [--h5plugin [--h5plugin-dir=spam] --zstd] To get finer control of installation options, including whether to compile with OpenMP multi-threading, copy the ``setup.cfg.example`` to ``setup.cfg`` @@ -114,15 +117,14 @@ Bitshuffle and LZF filters outside of python), set the environment variable ``HDF5_PLUGIN_PATH`` to the value of ``--h5plugin-dir`` or use HDF5's default search location of ``/usr/local/hdf5/lib/plugin``. +ZSTD support is enabled with ``--zstd``. + If you get an error about missing source files when building the extensions, try upgrading setuptools. There is a weird bug where setuptools prior to 0.7 doesn't work properly with Cython in some cases. .. _source: http://docs.h5py.org/en/latest/build.html#source-installation -.. [3] Typically you will be able to install Bitshuffle, but there will be - errors when creating and reading datasets. - Usage from Python ----------------- @@ -138,9 +140,13 @@ the filter will be available only within python and only after importing The filter can be added to new datasets either through the `h5py` low level interface or through the convenience functions provided in `bitshuffle.h5`. See the docstrings and unit tests for examples. For `h5py` -version 2.5.0 and later Bitshuffle can added to new datasets through the +version 2.5.0 and later Bitshuffle can be added to new datasets through the high level interface, as in the example below. +The compression algorithm can be configured using the `filter_opts` in +`bitshuffle.h5.create_dataset()`. LZ4 is chosen with: +`(BLOCK_SIZE, h5.H5_COMPRESS_LZ4)` and ZSTD with: +`(BLOCK_SIZE, h5.H5_COMPRESS_ZSTD, COMP_LVL)`. See `test_h5filter.py` for an example. Example h5py ------------ diff --git a/src/bitshuffle/bitshuffle/__init__.py b/src/bitshuffle/bitshuffle/__init__.py index 06d53b37..3f7c0380 100644 --- a/src/bitshuffle/bitshuffle/__init__.py +++ b/src/bitshuffle/bitshuffle/__init__.py @@ -1,3 +1,4 @@ +# flake8: noqa """ Filter for improving compression of typed binary data. @@ -11,11 +12,43 @@ bitunshuffle compress_lz4 decompress_lz4 + compress_zstd + decompress_zstd """ from __future__ import absolute_import -from bitshuffle.ext import (__version__, bitshuffle, bitunshuffle, using_NEON, using_SSE2, - using_AVX2, compress_lz4, decompress_lz4) +from bitshuffle.ext import ( + __version__, + __zstd__, + bitshuffle, + bitunshuffle, + using_NEON, + using_SSE2, + using_AVX2, + compress_lz4, + decompress_lz4, +) + +# Import ZSTD API if enabled +zstd_api = [] +if __zstd__: + from bitshuffle.ext import ( + compress_zstd, + decompress_zstd, + ) + + zstd_api += ["compress_zstd", "decompress_zstd"] + +__all__ = [ + "__version__", + "bitshuffle", + "bitunshuffle", + "using_NEON", + "using_SSE2", + "using_AVX2", + "compress_lz4", + "decompress_lz4", +] + zstd_api diff --git a/src/bitshuffle/bitshuffle/ext.pyx b/src/bitshuffle/bitshuffle/ext.pyx index 6c344d80..edc9c588 100644 --- a/src/bitshuffle/bitshuffle/ext.pyx +++ b/src/bitshuffle/bitshuffle/ext.pyx @@ -16,7 +16,7 @@ np.import_array() # Repeat each calculation this many times. For timing. cdef int REPEATC = 1 -#cdef int REPEATC = 32 +# cdef int REPEATC = 32 REPEAT = REPEATC @@ -25,22 +25,31 @@ cdef extern from b"bitshuffle.h": int bshuf_using_SSE2() int bshuf_using_AVX2() int bshuf_bitshuffle(void *A, void *B, int size, int elem_size, - int block_size) + int block_size) nogil int bshuf_bitunshuffle(void *A, void *B, int size, int elem_size, - int block_size) + int block_size) nogil int bshuf_compress_lz4_bound(int size, int elem_size, int block_size) int bshuf_compress_lz4(void *A, void *B, int size, int elem_size, - int block_size) + int block_size) nogil int bshuf_decompress_lz4(void *A, void *B, int size, int elem_size, - int block_size) + int block_size) nogil + IF ZSTD_SUPPORT: + int bshuf_compress_zstd_bound(int size, int elem_size, int block_size) + int bshuf_compress_zstd(void *A, void *B, int size, int elem_size, + int block_size, const int comp_lvl) nogil + int bshuf_decompress_zstd(void *A, void *B, int size, int elem_size, + int block_size) nogil int BSHUF_VERSION_MAJOR int BSHUF_VERSION_MINOR int BSHUF_VERSION_POINT +__version__ = "%d.%d.%d" % (BSHUF_VERSION_MAJOR, BSHUF_VERSION_MINOR, + BSHUF_VERSION_POINT) -__version__ = str("%d.%d.%d").format(BSHUF_VERSION_MAJOR, BSHUF_VERSION_MINOR, - BSHUF_VERSION_POINT) - +IF ZSTD_SUPPORT: + __zstd__ = True +ELSE: + __zstd__ = False # Prototypes from bitshuffle.c cdef extern int bshuf_copy(void *A, void *B, int size, int elem_size) @@ -290,8 +299,9 @@ def bitshuffle(np.ndarray arr not None, int block_size=0): cdef void* arr_ptr = &arr_flat[0] cdef void* out_ptr = &out_flat[0] - for ii in range(REPEATC): - count = bshuf_bitshuffle(arr_ptr, out_ptr, size, itemsize, block_size) + with nogil: + for ii in range(REPEATC): + count = bshuf_bitshuffle(arr_ptr, out_ptr, size, itemsize, block_size) if count < 0: msg = "Failed. Error code %d." excp = RuntimeError(msg % count, count) @@ -333,8 +343,9 @@ def bitunshuffle(np.ndarray arr not None, int block_size=0): cdef void* arr_ptr = &arr_flat[0] cdef void* out_ptr = &out_flat[0] - for ii in range(REPEATC): - count = bshuf_bitunshuffle(arr_ptr, out_ptr, size, itemsize, block_size) + with nogil: + for ii in range(REPEATC): + count = bshuf_bitunshuffle(arr_ptr, out_ptr, size, itemsize, block_size) if count < 0: msg = "Failed. Error code %d." excp = RuntimeError(msg % count, count) @@ -382,8 +393,9 @@ def compress_lz4(np.ndarray arr not None, int block_size=0): out_flat = out.view(np.uint8).ravel() cdef void* arr_ptr = &arr_flat[0] cdef void* out_ptr = &out_flat[0] - for ii in range(REPEATC): - count = bshuf_compress_lz4(arr_ptr, out_ptr, size, itemsize, block_size) + with nogil: + for ii in range(REPEATC): + count = bshuf_compress_lz4(arr_ptr, out_ptr, size, itemsize, block_size) if count < 0: msg = "Failed. Error code %d." excp = RuntimeError(msg % count, count) @@ -433,9 +445,10 @@ def decompress_lz4(np.ndarray arr not None, shape, dtype, int block_size=0): out_flat = out.view(np.uint8).ravel() cdef void* arr_ptr = &arr_flat[0] cdef void* out_ptr = &out_flat[0] - for ii in range(REPEATC): - count = bshuf_decompress_lz4(arr_ptr, out_ptr, size, itemsize, - block_size) + with nogil: + for ii in range(REPEATC): + count = bshuf_decompress_lz4(arr_ptr, out_ptr, size, itemsize, + block_size) if count < 0: msg = "Failed. Error code %d." excp = RuntimeError(msg % count, count) @@ -447,3 +460,110 @@ def decompress_lz4(np.ndarray arr not None, shape, dtype, int block_size=0): return out +IF ZSTD_SUPPORT: + @cython.boundscheck(False) + @cython.wraparound(False) + def compress_zstd(np.ndarray arr not None, int block_size=0, int comp_lvl=1): + """Bitshuffle then compress an array using ZSTD. + + Parameters + ---------- + arr : numpy array + Data to be processed. + block_size : positive integer + Block size in number of elements. By default, block size is chosen + automatically. + comp_lvl : positive integer + Compression level applied by ZSTD + + Returns + ------- + out : array with np.uint8 data type + Buffer holding compressed data. + + """ + + cdef int ii, size, itemsize, count=0 + shape = (arr.shape[i] for i in range(arr.ndim)) + if not arr.flags['C_CONTIGUOUS']: + msg = "Input array must be C-contiguous." + raise ValueError(msg) + size = arr.size + dtype = arr.dtype + itemsize = dtype.itemsize + + max_out_size = bshuf_compress_zstd_bound(size, itemsize, block_size) + + cdef np.ndarray out + out = np.empty(max_out_size, dtype=np.uint8) + + cdef np.ndarray[dtype=np.uint8_t, ndim=1, mode="c"] arr_flat + arr_flat = arr.view(np.uint8).ravel() + cdef np.ndarray[dtype=np.uint8_t, ndim=1, mode="c"] out_flat + out_flat = out.view(np.uint8).ravel() + cdef void* arr_ptr = &arr_flat[0] + cdef void* out_ptr = &out_flat[0] + with nogil: + for ii in range(REPEATC): + count = bshuf_compress_zstd(arr_ptr, out_ptr, size, itemsize, block_size, comp_lvl) + if count < 0: + msg = "Failed. Error code %d." + excp = RuntimeError(msg % count, count) + raise excp + return out[:count] + + @cython.boundscheck(False) + @cython.wraparound(False) + def decompress_zstd(np.ndarray arr not None, shape, dtype, int block_size=0): + """Decompress a buffer using ZSTD then bitunshuffle it yielding an array. + + Parameters + ---------- + arr : numpy array + Input data to be decompressed. + shape : tuple of integers + Shape of the output (decompressed array). Must match the shape of the + original data array before compression. + dtype : numpy dtype + Datatype of the output array. Must match the data type of the original + data array before compression. + block_size : positive integer + Block size in number of elements. Must match value used for + compression. + + Returns + ------- + out : numpy array with shape *shape* and data type *dtype* + Decompressed data. + + """ + + cdef int ii, size, itemsize, count=0 + if not arr.flags['C_CONTIGUOUS']: + msg = "Input array must be C-contiguous." + raise ValueError(msg) + size = np.prod(shape) + itemsize = dtype.itemsize + + cdef np.ndarray out + out = np.empty(tuple(shape), dtype=dtype) + + cdef np.ndarray[dtype=np.uint8_t, ndim=1, mode="c"] arr_flat + arr_flat = arr.view(np.uint8).ravel() + cdef np.ndarray[dtype=np.uint8_t, ndim=1, mode="c"] out_flat + out_flat = out.view(np.uint8).ravel() + cdef void* arr_ptr = &arr_flat[0] + cdef void* out_ptr = &out_flat[0] + with nogil: + for ii in range(REPEATC): + count = bshuf_decompress_zstd(arr_ptr, out_ptr, size, itemsize, + block_size) + if count < 0: + msg = "Failed. Error code %d." + excp = RuntimeError(msg % count, count) + raise excp + if count != arr.size: + msg = "Decompressed different number of bytes than input buffer size." + msg += "Input buffer %d, decompressed %d." % (arr.size, count) + raise RuntimeError(msg, count) + return out diff --git a/src/bitshuffle/bitshuffle/h5.pyx b/src/bitshuffle/bitshuffle/h5.pyx index cd7a0f05..c92e24c8 100644 --- a/src/bitshuffle/bitshuffle/h5.pyx +++ b/src/bitshuffle/bitshuffle/h5.pyx @@ -14,6 +14,7 @@ Constants H5FILTER : The Bitshuffle HDF5 filter integer identifier. H5_COMPRESS_LZ4 : Filter option flag for LZ4 compression. + H5_COMPRESS_ZSTD : Filter option flag for ZSTD compression. Functions ========= @@ -42,9 +43,10 @@ Examples from __future__ import absolute_import, division, print_function, unicode_literals +import sys import numpy import h5py -from h5py import h5d, h5s, h5t, h5p, filters +from h5py import h5d, h5fd, h5s, h5t, h5p, h5z, defs, filters cimport cython @@ -53,11 +55,39 @@ cdef extern from b"bshuf_h5filter.h": int bshuf_register_h5filter() int BSHUF_H5FILTER int BSHUF_H5_COMPRESS_LZ4 + int BSHUF_H5_COMPRESS_ZSTD + +cdef extern int init_filter(const char* libname) cdef int LZF_FILTER = 32000 H5FILTER = BSHUF_H5FILTER H5_COMPRESS_LZ4 = BSHUF_H5_COMPRESS_LZ4 +H5_COMPRESS_ZSTD = BSHUF_H5_COMPRESS_ZSTD + +# Init HDF5 dynamic loading with HDF5 library used by h5py +if not sys.platform.startswith('win'): + if sys.version_info[0] >= 3: + libs = [bytes(h5d.__file__, encoding='utf-8'), + bytes(h5fd.__file__, encoding='utf-8'), + bytes(h5s.__file__, encoding='utf-8'), + bytes(h5t.__file__, encoding='utf-8'), + bytes(h5p.__file__, encoding='utf-8'), + bytes(h5z.__file__, encoding='utf-8'), + bytes(defs.__file__, encoding='utf-8')] + else: + libs = [h5d.__file__, h5fd.__file__, h5s.__file__, h5t.__file__, + h5p.__file__, h5z.__file__, defs.__file__] + + # Ensure all symbols are loaded + success = -1 + for lib in libs: + success = init_filter(lib) + if success == 0: + break + + if success == -1: + raise RuntimeError("Failed to load all HDF5 symbols using these libs: {}".format(libs)) def register_h5_filter(): @@ -101,7 +131,7 @@ def create_dataset(parent, name, shape, dtype, chunks=None, maxshape=None, tmp_shape = maxshape if maxshape is not None else shape # Validate chunk shape chunks_larger = (numpy.array([ not i>=j - for i,j in zip(tmp_shape,chunks) if i is not None])).any() + for i, j in zip(tmp_shape, chunks) if i is not None])).any() if isinstance(chunks, tuple) and chunks_larger: errmsg = ("Chunk shape must not be greater than data shape in any " "dimension. {} is not compatible with {}".format(chunks, shape)) @@ -190,11 +220,11 @@ def create_bitshuffle_lzf_dataset(parent, name, shape, dtype, chunks=None, def create_bitshuffle_compressed_dataset(parent, name, shape, dtype, - chunks=None, maxshape=None, - fillvalue=None, track_times=None): + chunks=None, maxshape=None, + fillvalue=None, track_times=None): """Create dataset with bitshuffle+internal LZ4 compression.""" - filter_pipeline = [H5FILTER,] + filter_pipeline = [H5FILTER, ] filter_opts = [(0, H5_COMPRESS_LZ4)] dset_id = create_dataset(parent, name, shape, dtype, chunks=chunks, filter_pipeline=filter_pipeline, diff --git a/src/bitshuffle/bitshuffle/tests/__init__.py b/src/bitshuffle/bitshuffle/tests/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/src/bitshuffle/bitshuffle/tests/make_regression_tdata.py b/src/bitshuffle/bitshuffle/tests/make_regression_tdata.py deleted file mode 100644 index 07045383..00000000 --- a/src/bitshuffle/bitshuffle/tests/make_regression_tdata.py +++ /dev/null @@ -1,42 +0,0 @@ -""" -Script to create data used for regression testing. - -""" - -import numpy as np -from numpy import random -import h5py - -import bitshuffle -from bitshuffle import h5 - -BLOCK_SIZE = 64 # Smallish such that datasets have many blocks but are small. -FILTER_PIPELINE = [h5.H5FILTER,] -FILTER_OPTS = [(BLOCK_SIZE, h5.H5_COMPRESS_LZ4)] - -OUT_FILE = "bitshuffle/tests/data/regression_%s.h5" % bitshuffle.__version__ - -DTYPES = ['a1', 'a2', 'a3', 'a4', 'a6', 'a8', 'a10'] - - -f = h5py.File(OUT_FILE, 'w') -g_comp = f.create_group("compressed") -g_orig = f.create_group("origional") - -for dtype in DTYPES: - for rep in ['a', 'b', 'c']: - dset_name = "%s_%s" % (dtype, rep) - dtype = np.dtype(dtype) - n_elem = 3 * BLOCK_SIZE + random.randint(0, BLOCK_SIZE) - shape = (n_elem,) - chunks = shape - data = random.randint(0, 255, n_elem * dtype.itemsize) - data = data.astype(np.uint8).view(dtype) - - g_orig.create_dataset(dset_name, data=data) - - h5.create_dataset(g_comp, dset_name, shape, dtype, chunks=chunks, - filter_pipeline=FILTER_PIPELINE, filter_opts=FILTER_OPTS) - g_comp[dset_name][:] = data - -f.close() diff --git a/src/bitshuffle/bitshuffle/tests/test_h5filter.py b/src/bitshuffle/bitshuffle/tests/test_h5filter.py deleted file mode 100644 index 6739b998..00000000 --- a/src/bitshuffle/bitshuffle/tests/test_h5filter.py +++ /dev/null @@ -1,91 +0,0 @@ -from __future__ import absolute_import, division, print_function, unicode_literals - -import unittest -import os -import glob - -import numpy as np -import h5py -from h5py import h5f, h5d, h5z, h5t, h5s, filters -from subprocess import Popen, PIPE, STDOUT - -from bitshuffle import h5 - - -os.environ["HDF5_PLUGIN_PATH"] = "" - - -class TestFilter(unittest.TestCase): - - def test_filter(self): - shape = (32 * 1024 + 783,) - chunks = (4 * 1024 + 23,) - dtype = np.int64 - data = np.arange(shape[0]) - fname = "tmp_test_filters.h5" - f = h5py.File(fname) - h5.create_dataset(f, b"range", shape, dtype, chunks, - filter_pipeline=(32008, 32000), - filter_flags=(h5z.FLAG_MANDATORY, h5z.FLAG_MANDATORY), - filter_opts=None) - f["range"][:] = data - - f.close() - - f = h5py.File(fname, 'r') - d = f['range'][:] - self.assertTrue(np.all(d == data)) - f.close() - - def test_with_block_size(self): - shape = (128 * 1024 + 783,) - chunks = (4 * 1024 + 23,) - dtype = np.int64 - data = np.arange(shape[0]) - fname = "tmp_test_filters.h5" - f = h5py.File(fname) - h5.create_dataset(f, b"range", shape, dtype, chunks, - filter_pipeline=(32008, 32000), - filter_flags=(h5z.FLAG_MANDATORY, h5z.FLAG_MANDATORY), - filter_opts=((680,), ()), - ) - f["range"][:] = data - - f.close() - #os.system('h5dump -H -p tmp_test_filters.h5') - - f = h5py.File(fname, 'r') - d = f['range'][:] - self.assertTrue(np.all(d == data)) - f.close() - - def test_with_compression(self): - shape = (128 * 1024 + 783,) - chunks = (4 * 1024 + 23,) - dtype = np.int64 - data = np.arange(shape[0]) - fname = "tmp_test_filters.h5" - f = h5py.File(fname) - h5.create_dataset(f, b"range", shape, dtype, chunks, - filter_pipeline=(32008,), - filter_flags=(h5z.FLAG_MANDATORY,), - filter_opts=((0, h5.H5_COMPRESS_LZ4),), - ) - f["range"][:] = data - - f.close() - #os.system('h5dump -H -p tmp_test_filters.h5') - - f = h5py.File(fname, 'r') - d = f['range'][:] - self.assertTrue(np.all(d == data)) - f.close() - - def tearDown(self): - files = glob.glob("tmp_test_*") - for f in files: - os.remove(f) - - -if __name__ == "__main__": - unittest.main() diff --git a/src/bitshuffle/bitshuffle/tests/test_h5plugin.py b/src/bitshuffle/bitshuffle/tests/test_h5plugin.py deleted file mode 100644 index 220d55da..00000000 --- a/src/bitshuffle/bitshuffle/tests/test_h5plugin.py +++ /dev/null @@ -1,83 +0,0 @@ -from __future__ import absolute_import, division, print_function, unicode_literals -import unittest -import os, os.path -import glob - -import numpy as np -import h5py -from h5py import h5f, h5d, h5z, h5t, h5s, filters -from subprocess import Popen, PIPE, STDOUT - -import bitshuffle - - -plugin_dir = os.path.join(os.path.dirname(bitshuffle.__file__), - 'plugin') -os.environ["HDF5_PLUGIN_PATH"] = plugin_dir - - -H5VERSION = h5py.h5.get_libversion() -if (H5VERSION[0] < 1 or (H5VERSION[0] == 1 - and (H5VERSION[1] < 8 or (H5VERSION[1] == 8 and H5VERSION[2] < 11)))): - H51811P = False -else: - H51811P = True - - -class TestFilterPlugins(unittest.TestCase): - - def test_plugins(self): - if not H51811P: - return - shape = (32 * 1024,) - chunks = (4 * 1024,) - dtype = np.int64 - data = np.arange(shape[0]) - fname = "tmp_test_filters.h5" - f = h5py.File(fname) - tid = h5t.py_create(dtype, logical=1) - sid = h5s.create_simple(shape, shape) - # Different API's for different h5py versions. - try: - dcpl = filters.generate_dcpl(shape, dtype, chunks, None, None, - None, None, None, None) - except TypeError: - dcpl = filters.generate_dcpl(shape, dtype, chunks, None, None, - None, None, None) - dcpl.set_filter(32008, h5z.FLAG_MANDATORY) - dcpl.set_filter(32000, h5z.FLAG_MANDATORY) - dset_id = h5d.create(f.id, b"range", tid, sid, dcpl=dcpl) - dset_id.write(h5s.ALL, h5s.ALL, data) - f.close() - - # Make sure the filters are working outside of h5py by calling h5dump - h5dump = Popen(['h5dump', fname], - stdout=PIPE, stderr=STDOUT) - stdout, nothing = h5dump.communicate() - err = h5dump.returncode - self.assertEqual(err, 0) - - - f = h5py.File(fname, 'r') - d = f['range'][:] - self.assertTrue(np.all(d == data)) - f.close() - - - #def test_h5py_hl(self): - # if not H51811P: - # return - # # Does not appear to be supported by h5py. - # fname = "tmp_test_h5py_hl.h5" - # f = h5py.File(fname) - # f.create_dataset("range", np.arange(1024, dtype=np.int64), - # compression=32008) - - def tearDown(self): - files = glob.glob("tmp_test_*") - for f in files: - os.remove(f) - - -if __name__ == "__main__": - unittest.main() diff --git a/src/bitshuffle/bitshuffle/tests/test_regression.py b/src/bitshuffle/bitshuffle/tests/test_regression.py deleted file mode 100644 index 2862cace..00000000 --- a/src/bitshuffle/bitshuffle/tests/test_regression.py +++ /dev/null @@ -1,40 +0,0 @@ -""" -Test that data encoded with earlier versions can still be decoded correctly. - -""" - -from __future__ import absolute_import, division, print_function - -import unittest -from os import path - -import numpy as np -import h5py - -import bitshuffle -from bitshuffle import h5 - - -TEST_DATA_DIR = path.dirname(bitshuffle.__file__) + "/tests/data" - -OUT_FILE_TEMPLATE = TEST_DATA_DIR + "/regression_%s.h5" - -VERSIONS = ["0.1.3",] - - -class TestAll(unittest.TestCase): - - def test_regression(self): - for version in VERSIONS: - file_name = OUT_FILE_TEMPLATE % version - f = h5py.File(file_name) - g_orig = f["origional"] - g_comp = f["compressed"] - - for dset_name in g_comp.keys(): - self.assertTrue(np.all(g_comp[dset_name][:] - == g_orig[dset_name][:])) - - -if __name__ == "__main__": - unittest.main() diff --git a/src/bitshuffle/lz4/LICENSE b/src/bitshuffle/lz4/LICENSE index b566df30..74c2cdd7 100644 --- a/src/bitshuffle/lz4/LICENSE +++ b/src/bitshuffle/lz4/LICENSE @@ -1,5 +1,5 @@ LZ4 Library -Copyright (c) 2011-2014, Yann Collet +Copyright (c) 2011-2016, Yann Collet All rights reserved. Redistribution and use in source and binary forms, with or without modification, @@ -21,4 +21,4 @@ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/bitshuffle/lz4/lz4.c b/src/bitshuffle/lz4/lz4.c index 08cf6b5c..9f5e9bfa 100644 --- a/src/bitshuffle/lz4/lz4.c +++ b/src/bitshuffle/lz4/lz4.c @@ -1,6 +1,6 @@ /* LZ4 - Fast LZ compression algorithm - Copyright (C) 2011-2015, Yann Collet. + Copyright (C) 2011-present, Yann Collet. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) @@ -28,135 +28,365 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. You can contact the author at : - - LZ4 source repository : https://github.com/Cyan4973/lz4 - - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c + - LZ4 homepage : http://www.lz4.org + - LZ4 source repository : https://github.com/lz4/lz4 */ - -/************************************** +/*-************************************ * Tuning parameters **************************************/ /* - * HEAPMODE : + * LZ4_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()). */ -#define HEAPMODE 0 +#ifndef LZ4_HEAPMODE +# define LZ4_HEAPMODE 0 +#endif /* - * ACCELERATION_DEFAULT : + * LZ4_ACCELERATION_DEFAULT : * Select "acceleration" for LZ4_compress_fast() when parameter value <= 0 */ -#define ACCELERATION_DEFAULT 1 +#define LZ4_ACCELERATION_DEFAULT 1 +/* + * LZ4_ACCELERATION_MAX : + * Any "acceleration" value higher than this threshold + * get treated as LZ4_ACCELERATION_MAX instead (fix #876) + */ +#define LZ4_ACCELERATION_MAX 65537 -/************************************** +/*-************************************ * CPU Feature Detection **************************************/ +/* LZ4_FORCE_MEMORY_ACCESS + * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable. + * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal. + * The below switch allow to select different access method for improved performance. + * Method 0 (default) : use `memcpy()`. Safe and portable. + * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable). + * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`. + * Method 2 : direct access. This method is portable but violate C standard. + * It can generate buggy code on targets which assembly generation depends on alignment. + * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6) + * See https://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details. + * Prefer these methods in priority order (0 > 1 > 2) + */ +#ifndef LZ4_FORCE_MEMORY_ACCESS /* can be defined externally */ +# if defined(__GNUC__) && \ + ( 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__) +# define LZ4_FORCE_MEMORY_ACCESS 1 +# endif +#endif + /* * LZ4_FORCE_SW_BITCOUNT * Define this parameter if your target system or compiler does not support hardware bit count */ -#if defined(_MSC_VER) && defined(_WIN32_WCE) /* Visual Studio for Windows CE does not support Hardware bit count */ +#if defined(_MSC_VER) && defined(_WIN32_WCE) /* Visual Studio for WinCE doesn't support Hardware bit count */ +# undef LZ4_FORCE_SW_BITCOUNT /* avoid double def */ # define LZ4_FORCE_SW_BITCOUNT #endif -/************************************** -* Includes + +/*-************************************ +* Dependency **************************************/ +/* + * LZ4_SRC_INCLUDED: + * Amalgamation flag, whether lz4.c is included + */ +#ifndef LZ4_SRC_INCLUDED +# 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 */ +#endif + +#define LZ4_STATIC_LINKING_ONLY /* LZ4_DISTANCE_MAX */ #include "lz4.h" +/* see also "memory routines" below */ -/************************************** +/*-************************************ * Compiler Options **************************************/ -#ifdef _MSC_VER /* Visual Studio */ -# define FORCE_INLINE static __forceinline -# include -# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ -# pragma warning(disable : 4293) /* disable: C4293: too large shift (32-bits) */ -#else -# if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */ -# if defined(__GNUC__) || defined(__clang__) -# define FORCE_INLINE static inline __attribute__((always_inline)) -# else -# define FORCE_INLINE static inline -# endif -# else -# define FORCE_INLINE static -# endif /* __STDC_VERSION__ */ +#if defined(_MSC_VER) && (_MSC_VER >= 1400) /* Visual Studio 2005+ */ +# include /* only present in VS2005+ */ +# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ #endif /* _MSC_VER */ -/* LZ4_GCC_VERSION is defined into lz4.h */ -#if (LZ4_GCC_VERSION >= 302) || (__INTEL_COMPILER >= 800) || defined(__clang__) +#ifndef LZ4_FORCE_INLINE +# ifdef _MSC_VER /* Visual Studio */ +# define LZ4_FORCE_INLINE static __forceinline +# else +# if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */ +# ifdef __GNUC__ +# define LZ4_FORCE_INLINE static inline __attribute__((always_inline)) +# else +# define LZ4_FORCE_INLINE static inline +# endif +# else +# define LZ4_FORCE_INLINE static +# endif /* __STDC_VERSION__ */ +# endif /* _MSC_VER */ +#endif /* LZ4_FORCE_INLINE */ + +/* LZ4_FORCE_O2 and LZ4_FORCE_INLINE + * gcc on ppc64le generates an unrolled SIMDized loop for LZ4_wildCopy8, + * together with a simple 8-byte copy loop as a fall-back path. + * However, this optimization hurts the decompression speed by >30%, + * because the execution does not go to the optimized loop + * for typical compressible data, and all of the preamble checks + * before going to the fall-back path become useless overhead. + * This optimization happens only with the -O3 flag, and -O2 generates + * a simple 8-byte copy loop. + * With gcc on ppc64le, all of the LZ4_decompress_* and LZ4_wildCopy8 + * functions are annotated with __attribute__((optimize("O2"))), + * and also LZ4_wildCopy8 is forcibly inlined, so that the O2 attribute + * of LZ4_wildCopy8 does not affect the compression speed. + */ +#if defined(__PPC64__) && defined(__LITTLE_ENDIAN__) && defined(__GNUC__) && !defined(__clang__) +# define LZ4_FORCE_O2 __attribute__((optimize("O2"))) +# undef LZ4_FORCE_INLINE +# define LZ4_FORCE_INLINE static __inline __attribute__((optimize("O2"),always_inline)) +#else +# define LZ4_FORCE_O2 +#endif + +#if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__) # define expect(expr,value) (__builtin_expect ((expr),(value)) ) #else # define expect(expr,value) (expr) #endif +#ifndef likely #define likely(expr) expect((expr) != 0, 1) +#endif +#ifndef unlikely #define unlikely(expr) expect((expr) != 0, 0) +#endif + +/* Should the alignment test prove unreliable, for some reason, + * it can be disabled by setting LZ4_ALIGN_TEST to 0 */ +#ifndef LZ4_ALIGN_TEST /* can be externally provided */ +# define LZ4_ALIGN_TEST 1 +#endif -/************************************** +/*-************************************ * Memory routines **************************************/ -#include /* malloc, calloc, free */ -#define ALLOCATOR(n,s) calloc(n,s) -#define FREEMEM free +#ifdef LZ4_USER_MEMORY_FUNCTIONS +/* memory management functions can be customized by user project. + * Below functions must exist somewhere in the Project + * and be available at link time */ +void* LZ4_malloc(size_t s); +void* LZ4_calloc(size_t n, size_t s); +void LZ4_free(void* p); +# define ALLOC(s) LZ4_malloc(s) +# define ALLOC_AND_ZERO(s) LZ4_calloc(1,s) +# define FREEMEM(p) LZ4_free(p) +#else +# include /* malloc, calloc, free */ +# define ALLOC(s) malloc(s) +# define ALLOC_AND_ZERO(s) calloc(1,s) +# define FREEMEM(p) free(p) +#endif + #include /* memset, memcpy */ -#define MEM_INIT memset +#define MEM_INIT(p,v,s) memset((p),(v),(s)) + + +/*-************************************ +* Common Constants +**************************************/ +#define MINMATCH 4 + +#define WILDCOPYLENGTH 8 +#define LASTLITERALS 5 /* see ../doc/lz4_Block_format.md#parsing-restrictions */ +#define MFLIMIT 12 /* see ../doc/lz4_Block_format.md#parsing-restrictions */ +#define MATCH_SAFEGUARD_DISTANCE ((2*WILDCOPYLENGTH) - MINMATCH) /* ensure it's possible to write 2 x wildcopyLength without overflowing output buffer */ +#define FASTLOOP_SAFE_DISTANCE 64 +static const int LZ4_minLength = (MFLIMIT+1); + +#define KB *(1 <<10) +#define MB *(1 <<20) +#define GB *(1U<<30) + +#define LZ4_DISTANCE_ABSOLUTE_MAX 65535 +#if (LZ4_DISTANCE_MAX > LZ4_DISTANCE_ABSOLUTE_MAX) /* max supported by LZ4 format */ +# error "LZ4_DISTANCE_MAX is too big : must be <= 65535" +#endif + +#define ML_BITS 4 +#define ML_MASK ((1U<= 199901L) /* C99 */ +#if defined(LZ4_DEBUG) && (LZ4_DEBUG>=1) +# include +#else +# ifndef assert +# define assert(condition) ((void)0) +# endif +#endif + +#define LZ4_STATIC_ASSERT(c) { enum { LZ4_static_assert = 1/(int)(!!(c)) }; } /* use after variable declarations */ + +#if defined(LZ4_DEBUG) && (LZ4_DEBUG>=2) +# include + static int g_debuglog_enable = 1; +# define DEBUGLOG(l, ...) { \ + if ((g_debuglog_enable) && (l<=LZ4_DEBUG)) { \ + fprintf(stderr, __FILE__ ": "); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, " \n"); \ + } } +#else +# define DEBUGLOG(l, ...) {} /* disabled */ +#endif + +static int LZ4_isAligned(const void* ptr, size_t alignment) +{ + return ((size_t)ptr & (alignment -1)) == 0; +} + + +/*-************************************ +* Types +**************************************/ +#include +#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) # include typedef uint8_t BYTE; typedef uint16_t U16; typedef uint32_t U32; typedef int32_t S32; typedef uint64_t U64; + typedef uintptr_t uptrval; #else +# if UINT_MAX != 4294967295UL +# error "LZ4 code (when not C++ or C99) assumes that sizeof(int) == 4" +# endif typedef unsigned char BYTE; typedef unsigned short U16; typedef unsigned int U32; typedef signed int S32; typedef unsigned long long U64; + typedef size_t uptrval; /* generally true, except OpenVMS-64 */ +#endif + +#if defined(__x86_64__) + typedef U64 reg_t; /* 64-bits in x32 mode */ +#else + typedef size_t reg_t; /* 32-bits in x32 mode */ #endif +typedef enum { + notLimited = 0, + limitedOutput = 1, + fillOutput = 2 +} limitedOutput_directive; -/************************************** + +/*-************************************ * Reading and writing into memory **************************************/ -#define STEPSIZE sizeof(size_t) -static unsigned LZ4_64bits(void) { return sizeof(void*)==8; } +/** + * LZ4 relies on memcpy with a constant size being inlined. In freestanding + * environments, the compiler can't assume the implementation of memcpy() is + * standard compliant, so it can't apply its specialized memcpy() inlining + * logic. When possible, use __builtin_memcpy() to tell the compiler to analyze + * memcpy() as if it were standard compliant, so it can inline it in freestanding + * environments. This is needed when decompressing the Linux Kernel, for example. + */ +#if defined(__GNUC__) && (__GNUC__ >= 4) +#define LZ4_memcpy(dst, src, size) __builtin_memcpy(dst, src, size) +#else +#define LZ4_memcpy(dst, src, size) memcpy(dst, src, size) +#endif static unsigned LZ4_isLittleEndian(void) { - const union { U32 i; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */ + const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */ return one.c[0]; } +#if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2) +/* lie to the compiler about data alignment; use with caution */ + +static U16 LZ4_read16(const void* memPtr) { return *(const U16*) memPtr; } +static U32 LZ4_read32(const void* memPtr) { return *(const U32*) memPtr; } +static reg_t LZ4_read_ARCH(const void* memPtr) { return *(const reg_t*) memPtr; } + +static void LZ4_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; } +static void LZ4_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; } + +#elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1) + +/* __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)) unalign; + +static U16 LZ4_read16(const void* ptr) { return ((const unalign*)ptr)->u16; } +static U32 LZ4_read32(const void* ptr) { return ((const unalign*)ptr)->u32; } +static reg_t LZ4_read_ARCH(const void* ptr) { return ((const unalign*)ptr)->uArch; } + +static void LZ4_write16(void* memPtr, U16 value) { ((unalign*)memPtr)->u16 = value; } +static void LZ4_write32(void* memPtr, U32 value) { ((unalign*)memPtr)->u32 = value; } + +#else /* safe and portable access using memcpy() */ + static U16 LZ4_read16(const void* memPtr) { - U16 val16; - memcpy(&val16, memPtr, 2); - return val16; + U16 val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val; +} + +static U32 LZ4_read32(const void* memPtr) +{ + U32 val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val; } +static reg_t LZ4_read_ARCH(const void* memPtr) +{ + reg_t val; LZ4_memcpy(&val, memPtr, sizeof(val)); return val; +} + +static void LZ4_write16(void* memPtr, U16 value) +{ + LZ4_memcpy(memPtr, &value, sizeof(value)); +} + +static void LZ4_write32(void* memPtr, U32 value) +{ + LZ4_memcpy(memPtr, &value, sizeof(value)); +} + +#endif /* LZ4_FORCE_MEMORY_ACCESS */ + + static U16 LZ4_readLE16(const void* memPtr) { - if (LZ4_isLittleEndian()) - { + if (LZ4_isLittleEndian()) { return LZ4_read16(memPtr); - } - else - { + } else { const BYTE* p = (const BYTE*)memPtr; return (U16)((U16)p[0] + (p[1]<<8)); } @@ -164,167 +394,232 @@ static U16 LZ4_readLE16(const void* memPtr) static void LZ4_writeLE16(void* memPtr, U16 value) { - if (LZ4_isLittleEndian()) - { - memcpy(memPtr, &value, 2); - } - else - { + if (LZ4_isLittleEndian()) { + LZ4_write16(memPtr, value); + } else { BYTE* p = (BYTE*)memPtr; p[0] = (BYTE) value; p[1] = (BYTE)(value>>8); } } -static U32 LZ4_read32(const void* memPtr) +/* customized variant of memcpy, which can overwrite up to 8 bytes beyond dstEnd */ +LZ4_FORCE_INLINE +void LZ4_wildCopy8(void* dstPtr, const void* srcPtr, void* dstEnd) { - U32 val32; - memcpy(&val32, memPtr, 4); - return val32; -} + BYTE* d = (BYTE*)dstPtr; + const BYTE* s = (const BYTE*)srcPtr; + BYTE* const e = (BYTE*)dstEnd; -static U64 LZ4_read64(const void* memPtr) -{ - U64 val64; - memcpy(&val64, memPtr, 8); - return val64; + do { LZ4_memcpy(d,s,8); d+=8; s+=8; } while (d= 16. */ +LZ4_FORCE_INLINE void +LZ4_wildCopy32(void* dstPtr, const void* srcPtr, void* dstEnd) +{ + BYTE* d = (BYTE*)dstPtr; + const BYTE* s = (const BYTE*)srcPtr; + BYTE* const e = (BYTE*)dstEnd; -#define KB *(1 <<10) -#define MB *(1 <<20) -#define GB *(1U<<30) + do { LZ4_memcpy(d,s,16); LZ4_memcpy(d+16,s+16,16); d+=32; s+=32; } while (d= dstPtr + MINMATCH + * - there is at least 8 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) +{ + BYTE v[8]; -#define ML_BITS 4 -#define ML_MASK ((1U<= dstPtr + MINMATCH); + switch(offset) { + case 1: + MEM_INIT(v, *srcPtr, 8); + break; + case 2: + LZ4_memcpy(v, srcPtr, 2); + LZ4_memcpy(&v[2], srcPtr, 2); + LZ4_memcpy(&v[4], v, 4); + break; + case 4: + LZ4_memcpy(v, srcPtr, 4); + LZ4_memcpy(&v[4], srcPtr, 4); + break; + default: + LZ4_memcpy_using_offset_base(dstPtr, srcPtr, dstEnd, offset); + return; + } -/************************************** -* Common Utils -**************************************/ -#define LZ4_STATIC_ASSERT(c) { enum { LZ4_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */ + LZ4_memcpy(dstPtr, v, 8); + dstPtr += 8; + while (dstPtr < dstEnd) { + LZ4_memcpy(dstPtr, v, 8); + dstPtr += 8; + } +} +#endif -/************************************** +/*-************************************ * Common functions **************************************/ -static unsigned LZ4_NbCommonBytes (register size_t val) +static unsigned LZ4_NbCommonBytes (reg_t val) { - if (LZ4_isLittleEndian()) - { - if (LZ4_64bits()) - { -# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) + assert(val != 0); + if (LZ4_isLittleEndian()) { + if (sizeof(val) == 8) { +# if defined(_MSC_VER) && (_MSC_VER >= 1800) && defined(_M_AMD64) && !defined(LZ4_FORCE_SW_BITCOUNT) + /* x64 CPUS without BMI support interpret `TZCNT` as `REP BSF` */ + return (unsigned)_tzcnt_u64(val) >> 3; +# elif defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) unsigned long r = 0; - _BitScanForward64( &r, (U64)val ); - return (int)(r>>3); -# elif (defined(__clang__) || (LZ4_GCC_VERSION >= 304)) && !defined(LZ4_FORCE_SW_BITCOUNT) - return (__builtin_ctzll((U64)val) >> 3); + _BitScanForward64(&r, (U64)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_ctzll((U64)val) >> 3; # else - static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 }; - return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58]; + const U64 m = 0x0101010101010101ULL; + val ^= val - 1; + return (unsigned)(((U64)((val & (m - 1)) * m)) >> 56); # endif - } - else /* 32 bits */ - { -# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) + } else /* 32 bits */ { +# if defined(_MSC_VER) && (_MSC_VER >= 1400) && !defined(LZ4_FORCE_SW_BITCOUNT) unsigned long r; - _BitScanForward( &r, (U32)val ); - return (int)(r>>3); -# elif (defined(__clang__) || (LZ4_GCC_VERSION >= 304)) && !defined(LZ4_FORCE_SW_BITCOUNT) - return (__builtin_ctz((U32)val) >> 3); + _BitScanForward(&r, (U32)val); + return (unsigned)r >> 3; +# elif (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \ + ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \ + !defined(__TINYC__) && !defined(LZ4_FORCE_SW_BITCOUNT) + return (unsigned)__builtin_ctz((U32)val) >> 3; # else - static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 }; - return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27]; + const U32 m = 0x01010101; + return (unsigned)((((val - 1) ^ val) & (m - 1)) * m) >> 24; # endif } - } - else /* Big Endian CPU */ - { - if (LZ4_64bits()) - { -# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT) - unsigned long r = 0; - _BitScanReverse64( &r, val ); - return (unsigned)(r>>3); -# elif (defined(__clang__) || (LZ4_GCC_VERSION >= 304)) && !defined(LZ4_FORCE_SW_BITCOUNT) - return (__builtin_clzll((U64)val) >> 3); + } else /* Big Endian CPU */ { + if (sizeof(val)==8) { +# if (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \ + ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \ + !defined(__TINYC__) && !defined(LZ4_FORCE_SW_BITCOUNT) + return (unsigned)__builtin_clzll((U64)val) >> 3; # else +#if 1 + /* this method is probably faster, + * but adds a 128 bytes lookup table */ + static const unsigned char ctz7_tab[128] = { + 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, + }; + U64 const mask = 0x0101010101010101ULL; + U64 const t = (((val >> 8) - mask) | val) & mask; + return ctz7_tab[(t * 0x0080402010080402ULL) >> 57]; +#else + /* this method doesn't consume memory space like the previous one, + * but it contains several branches, + * that may end up slowing execution */ + static const U32 by32 = sizeof(val)*4; /* 32 on 64 bits (goal), 16 on 32 bits. + Just to avoid some static analyzer complaining about shift by 32 on 32-bits target. + Note that this code path is never triggered in 32-bits mode. */ unsigned r; - if (!(val>>32)) { r=4; } else { r=0; val>>=32; } + if (!(val>>by32)) { r=4; } else { r=0; val>>=by32; } if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; } r += (!val); return r; +#endif # endif - } - else /* 32 bits */ - { -# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) - unsigned long r = 0; - _BitScanReverse( &r, (unsigned long)val ); - return (unsigned)(r>>3); -# elif (defined(__clang__) || (LZ4_GCC_VERSION >= 304)) && !defined(LZ4_FORCE_SW_BITCOUNT) - return (__builtin_clz((U32)val) >> 3); + } else /* 32 bits */ { +# if (defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 3) || \ + ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 4))))) && \ + !defined(LZ4_FORCE_SW_BITCOUNT) + return (unsigned)__builtin_clz((U32)val) >> 3; # else - unsigned r; - if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; } - r += (!val); - return r; + val >>= 8; + val = ((((val + 0x00FFFF00) | 0x00FFFFFF) + val) | + (val + 0x00FF0000)) >> 24; + return (unsigned)val ^ 3; # endif } } } -static unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit) + +#define STEPSIZE sizeof(reg_t) +LZ4_FORCE_INLINE +unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit) { const BYTE* const pStart = pIn; - while (likely(pIn compression run slower on incompressible data */ -/************************************** +/*-************************************ * Local Structures and types **************************************/ -typedef struct { - U32 hashTable[HASH_SIZE_U32]; - U32 currentOffset; - U32 initCheck; - const BYTE* dictionary; - BYTE* bufferStart; /* obsolete, used for slideInputBuffer */ - U32 dictSize; -} LZ4_stream_t_internal; - -typedef enum { notLimited = 0, limitedOutput = 1 } limitedOutput_directive; -typedef enum { byPtr, byU32, byU16 } tableType_t; - -typedef enum { noDict = 0, withPrefix64k, usingExtDict } dict_directive; +typedef enum { clearedTable = 0, byPtr, byU32, byU16 } tableType_t; + +/** + * This enum distinguishes several different modes of accessing previous + * content in the stream. + * + * - noDict : There is no preceding content. + * - withPrefix64k : Table entries up to ctx->dictSize before the current blob + * blob being compressed are valid and refer to the preceding + * content (of length ctx->dictSize), which is available + * contiguously preceding in memory the content currently + * being compressed. + * - usingExtDict : Like withPrefix64k, but the preceding content is somewhere + * else in memory, starting at ctx->dictionary with length + * ctx->dictSize. + * - usingDictCtx : Like usingExtDict, but everything concerning the preceding + * content is in a separate context, pointed to by + * ctx->dictCtx. ctx->dictionary, ctx->dictSize, and table + * entries in the current context that refer to positions + * preceding the beginning of the current compression are + * ignored. Instead, ctx->dictCtx->dictionary and ctx->dictCtx + * ->dictSize describe the location and size of the preceding + * content, and matches are found by looking in the ctx + * ->dictCtx->hashTable. + */ +typedef enum { noDict = 0, withPrefix64k, usingExtDict, usingDictCtx } dict_directive; typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive; -typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive; -typedef enum { full = 0, partial = 1 } earlyEnd_directive; - -/************************************** +/*-************************************ * Local Utils **************************************/ int LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; } +const char* LZ4_versionString(void) { return LZ4_VERSION_STRING; } int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); } -int LZ4_sizeofState() { return LZ4_STREAMSIZE; } +int LZ4_sizeofState(void) { return LZ4_STREAMSIZE; } + + +/*-************************************ +* Internal Definitions used in Tests +**************************************/ +#if defined (__cplusplus) +extern "C" { +#endif +int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int srcSize); +int LZ4_decompress_safe_forceExtDict(const char* source, char* dest, + int compressedSize, int maxOutputSize, + const void* dictStart, size_t dictSize); -/******************************** +#if defined (__cplusplus) +} +#endif + +/*-****************************** * Compression functions ********************************/ - -static U32 LZ4_hashSequence(U32 sequence, tableType_t const tableType) +LZ4_FORCE_INLINE U32 LZ4_hash4(U32 sequence, tableType_t const tableType) { if (tableType == byU16) - return (((sequence) * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1))); + return ((sequence * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1))); else - return (((sequence) * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG)); + return ((sequence * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG)); } -static const U64 prime5bytes = 889523592379ULL; -static U32 LZ4_hashSequence64(size_t sequence, tableType_t const tableType) +LZ4_FORCE_INLINE U32 LZ4_hash5(U64 sequence, tableType_t const tableType) { const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG+1 : LZ4_HASHLOG; - const U32 hashMask = (1<> (40 - hashLog)) & hashMask; + if (LZ4_isLittleEndian()) { + const U64 prime5bytes = 889523592379ULL; + return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog)); + } else { + const U64 prime8bytes = 11400714785074694791ULL; + return (U32)(((sequence >> 24) * prime8bytes) >> (64 - hashLog)); + } } -static U32 LZ4_hashSequenceT(size_t sequence, tableType_t const tableType) +LZ4_FORCE_INLINE U32 LZ4_hashPosition(const void* const p, tableType_t const tableType) { - if (LZ4_64bits()) - return LZ4_hashSequence64(sequence, tableType); - return LZ4_hashSequence((U32)sequence, tableType); + if ((sizeof(reg_t)==8) && (tableType != byU16)) return LZ4_hash5(LZ4_read_ARCH(p), tableType); + return LZ4_hash4(LZ4_read32(p), tableType); } -static U32 LZ4_hashPosition(const void* p, tableType_t tableType) { return LZ4_hashSequenceT(LZ4_read_ARCH(p), tableType); } +LZ4_FORCE_INLINE void LZ4_clearHash(U32 h, void* tableBase, tableType_t const tableType) +{ + switch (tableType) + { + default: /* fallthrough */ + case clearedTable: { /* illegal! */ assert(0); return; } + case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = NULL; return; } + case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = 0; return; } + case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = 0; return; } + } +} -static void LZ4_putPositionOnHash(const BYTE* p, U32 h, void* tableBase, tableType_t const tableType, const BYTE* srcBase) +LZ4_FORCE_INLINE void LZ4_putIndexOnHash(U32 idx, U32 h, void* tableBase, tableType_t const tableType) { switch (tableType) { + default: /* fallthrough */ + case clearedTable: /* fallthrough */ + case byPtr: { /* illegal! */ assert(0); return; } + case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = idx; return; } + case byU16: { U16* hashTable = (U16*) tableBase; assert(idx < 65536); hashTable[h] = (U16)idx; return; } + } +} + +LZ4_FORCE_INLINE void LZ4_putPositionOnHash(const BYTE* p, U32 h, + void* tableBase, tableType_t const tableType, + const BYTE* srcBase) +{ + 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; } } } -static 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, const BYTE* srcBase) { - U32 h = LZ4_hashPosition(p, tableType); + U32 const h = LZ4_hashPosition(p, tableType); LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase); } -static const BYTE* LZ4_getPositionOnHash(U32 h, void* tableBase, tableType_t tableType, const BYTE* srcBase) +/* LZ4_getIndexOnHash() : + * Index of match position registered in hash table. + * hash position must be calculated by using base+index, or dictBase+index. + * Assumption 1 : only valid if tableType == byU32 or byU16. + * Assumption 2 : h is presumed valid (within limits of hash table) + */ +LZ4_FORCE_INLINE U32 LZ4_getIndexOnHash(U32 h, const void* tableBase, tableType_t tableType) +{ + LZ4_STATIC_ASSERT(LZ4_MEMORY_USAGE > 2); + if (tableType == byU32) { + const U32* const hashTable = (const U32*) tableBase; + assert(h < (1U << (LZ4_MEMORY_USAGE-2))); + return hashTable[h]; + } + if (tableType == byU16) { + const U16* const hashTable = (const U16*) tableBase; + assert(h < (1U << (LZ4_MEMORY_USAGE-1))); + return hashTable[h]; + } + assert(0); return 0; /* forbidden case */ +} + +static const BYTE* LZ4_getPositionOnHash(U32 h, const void* tableBase, tableType_t tableType, const BYTE* srcBase) { - if (tableType == byPtr) { const BYTE** hashTable = (const BYTE**) tableBase; return hashTable[h]; } - if (tableType == byU32) { U32* hashTable = (U32*) tableBase; return hashTable[h] + srcBase; } - { U16* hashTable = (U16*) tableBase; return hashTable[h] + srcBase; } /* default, to ensure a return */ + 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 */ } -static const BYTE* LZ4_getPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase) +LZ4_FORCE_INLINE const BYTE* +LZ4_getPosition(const BYTE* p, + const void* tableBase, tableType_t tableType, + const BYTE* srcBase) { - U32 h = LZ4_hashPosition(p, tableType); + U32 const h = LZ4_hashPosition(p, tableType); return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase); } -FORCE_INLINE int LZ4_compress_generic( - void* const ctx, +LZ4_FORCE_INLINE void +LZ4_prepareTable(LZ4_stream_t_internal* const cctx, + const int inputSize, + const tableType_t tableType) { + /* If the table hasn't been used, it's guaranteed to be zeroed out, and is + * therefore safe to use no matter what mode we're in. Otherwise, we figure + * out if it's safe to leave as is or whether it needs to be reset. + */ + if ((tableType_t)cctx->tableType != clearedTable) { + assert(inputSize >= 0); + if ((tableType_t)cctx->tableType != tableType + || ((tableType == byU16) && cctx->currentOffset + (unsigned)inputSize >= 0xFFFFU) + || ((tableType == byU32) && cctx->currentOffset > 1 GB) + || tableType == byPtr + || inputSize >= 4 KB) + { + DEBUGLOG(4, "LZ4_prepareTable: Resetting table in %p", cctx); + MEM_INIT(cctx->hashTable, 0, LZ4_HASHTABLESIZE); + cctx->currentOffset = 0; + cctx->tableType = (U32)clearedTable; + } else { + DEBUGLOG(4, "LZ4_prepareTable: Re-use hash table (no reset)"); + } + } + + /* Adding a gap, so all previous entries are > LZ4_DISTANCE_MAX back, is faster + * than compressing without a gap. However, compressing with + * currentOffset == 0 is faster still, so we preserve that case. + */ + if (cctx->currentOffset != 0 && tableType == byU32) { + DEBUGLOG(5, "LZ4_prepareTable: adding 64KB to currentOffset"); + cctx->currentOffset += 64 KB; + } + + /* Finally, clear history */ + cctx->dictCtx = NULL; + cctx->dictionary = NULL; + cctx->dictSize = 0; +} + +/** LZ4_compress_generic() : + * inlined, to ensure branches are decided at compilation time. + * Presumed already validated at this stage: + * - source != NULL + * - inputSize > 0 + */ +LZ4_FORCE_INLINE int LZ4_compress_generic_validated( + LZ4_stream_t_internal* const cctx, const char* const source, char* const dest, const int inputSize, + int *inputConsumed, /* only written when outputDirective == fillOutput */ const int maxOutputSize, - const limitedOutput_directive outputLimited, + const limitedOutput_directive outputDirective, const tableType_t tableType, - const dict_directive dict, + const dict_directive dictDirective, const dictIssue_directive dictIssue, - const U32 acceleration) + const int acceleration) { - LZ4_stream_t_internal* const dictPtr = (LZ4_stream_t_internal*)ctx; - + int result; const BYTE* ip = (const BYTE*) source; - const BYTE* base; + + U32 const startIndex = cctx->currentOffset; + const BYTE* base = (const BYTE*) source - startIndex; const BYTE* lowLimit; - const BYTE* const lowRefLimit = ip - dictPtr->dictSize; - const BYTE* const dictionary = dictPtr->dictionary; - const BYTE* const dictEnd = dictionary + dictPtr->dictSize; - const size_t dictDelta = dictEnd - (const BYTE*)source; + + const LZ4_stream_t_internal* dictCtx = (const LZ4_stream_t_internal*) cctx->dictCtx; + const BYTE* const dictionary = + 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 */ + + int const maybe_extMem = (dictDirective == usingExtDict) || (dictDirective == usingDictCtx); + U32 const prefixIdxLimit = startIndex - dictSize; /* used when dictDirective == dictSmall */ + const BYTE* const dictEnd = dictionary ? dictionary + dictSize : dictionary; const BYTE* anchor = (const BYTE*) source; const BYTE* const iend = ip + inputSize; - const BYTE* const mflimit = iend - MFLIMIT; + const BYTE* const mflimitPlusOne = iend - MFLIMIT + 1; const BYTE* const matchlimit = iend - LASTLITERALS; + /* the dictCtx currentOffset is indexed on the start of the dictionary, + * while a dictionary in the current context precedes the currentOffset */ + const BYTE* dictBase = !dictionary ? NULL : (dictDirective == usingDictCtx) ? + dictionary + dictSize - dictCtx->currentOffset : + dictionary + dictSize - startIndex; + BYTE* op = (BYTE*) dest; BYTE* const olimit = op + maxOutputSize; + U32 offset = 0; U32 forwardH; - size_t refDelta=0; - /* Init conditions */ - if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported input size, too large (or negative) */ - switch(dict) - { - case noDict: - default: - base = (const BYTE*)source; - lowLimit = (const BYTE*)source; - break; - case withPrefix64k: - base = (const BYTE*)source - dictPtr->currentOffset; - lowLimit = (const BYTE*)source - dictPtr->dictSize; - break; - case usingExtDict: - base = (const BYTE*)source - dictPtr->currentOffset; - lowLimit = (const BYTE*)source; - break; + DEBUGLOG(5, "LZ4_compress_generic_validated: srcSize=%i, tableType=%u", inputSize, tableType); + assert(ip != NULL); + /* If init conditions are not met, we don't have to mark stream + * as having dirty context, since no action was taken yet */ + if (outputDirective == fillOutput && maxOutputSize < 1) { return 0; } /* Impossible to store anything */ + if ((tableType == byU16) && (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); + + /* Update context state */ + if (dictDirective == usingDictCtx) { + /* Subsequent linked blocks can't use the dictionary. */ + /* Instead, they use the block we just compressed. */ + cctx->dictCtx = NULL; + cctx->dictSize = (U32)inputSize; + } else { + cctx->dictSize += (U32)inputSize; } - if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */ - if (inputSizecurrentOffset += (U32)inputSize; + cctx->tableType = (U32)tableType; + + if (inputSizehashTable, tableType, base); ip++; forwardH = LZ4_hashPosition(ip, tableType); /* Main Loop */ - for ( ; ; ) - { + for ( ; ; ) { const BYTE* match; BYTE* token; - { + const BYTE* filledIp; + + /* Find a match */ + if (tableType == byPtr) { const BYTE* forwardIp = ip; - unsigned step = 1; - unsigned searchMatchNb = acceleration << LZ4_skipTrigger; + int step = 1; + int searchMatchNb = acceleration << LZ4_skipTrigger; + do { + U32 const h = forwardH; + ip = forwardIp; + forwardIp += step; + step = (searchMatchNb++ >> LZ4_skipTrigger); + + if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals; + assert(ip < mflimitPlusOne); - /* Find a match */ + match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType, base); + forwardH = LZ4_hashPosition(forwardIp, tableType); + LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base); + + } while ( (match+LZ4_DISTANCE_MAX < ip) + || (LZ4_read32(match) != LZ4_read32(ip)) ); + + } else { /* byU32, byU16 */ + + const BYTE* forwardIp = ip; + int step = 1; + int searchMatchNb = acceleration << LZ4_skipTrigger; do { - U32 h = forwardH; + U32 const h = forwardH; + U32 const current = (U32)(forwardIp - base); + U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType); + assert(matchIndex <= current); + assert(forwardIp - base < (ptrdiff_t)(2 GB - 1)); ip = forwardIp; forwardIp += step; step = (searchMatchNb++ >> LZ4_skipTrigger); - if (unlikely(forwardIp > mflimit)) goto _last_literals; + if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals; + assert(ip < mflimitPlusOne); - match = LZ4_getPositionOnHash(h, ctx, tableType, base); - if (dict==usingExtDict) - { - if (match<(const BYTE*)source) - { - refDelta = dictDelta; + 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; + matchIndex += dictDelta; /* make dictCtx index comparable with current context */ lowLimit = dictionary; + } else { + match = base + matchIndex; + lowLimit = (const BYTE*)source; } - else - { - refDelta = 0; + } else if (dictDirective==usingExtDict) { + if (matchIndex < startIndex) { + DEBUGLOG(7, "extDict candidate: matchIndex=%5u < startIndex=%5u", matchIndex, startIndex); + assert(startIndex - matchIndex >= MINMATCH); + match = dictBase + matchIndex; + lowLimit = dictionary; + } else { + match = base + matchIndex; lowLimit = (const BYTE*)source; } + } else { /* single continuous memory segment */ + match = base + matchIndex; } forwardH = LZ4_hashPosition(forwardIp, tableType); - LZ4_putPositionOnHash(ip, h, ctx, tableType, base); + LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType); + + DEBUGLOG(7, "candidate at pos=%u (offset=%u \n", matchIndex, current - matchIndex); + if ((dictIssue == dictSmall) && (matchIndex < prefixIdxLimit)) { continue; } /* match outside of valid area */ + assert(matchIndex < current); + if ( ((tableType != byU16) || (LZ4_DISTANCE_MAX < LZ4_DISTANCE_ABSOLUTE_MAX)) + && (matchIndex+LZ4_DISTANCE_MAX < current)) { + continue; + } /* too far */ + assert((current - matchIndex) <= LZ4_DISTANCE_MAX); /* match now expected within distance */ + + if (LZ4_read32(match) == LZ4_read32(ip)) { + if (maybe_extMem) offset = current - matchIndex; + break; /* match found */ + } - } while ( ((dictIssue==dictSmall) ? (match < lowRefLimit) : 0) - || ((tableType==byU16) ? 0 : (match + MAX_DISTANCE < ip)) - || (LZ4_read32(match+refDelta) != LZ4_read32(ip)) ); + } while(1); } /* Catch up */ - while ((ip>anchor) && (match+refDelta > lowLimit) && (unlikely(ip[-1]==match[refDelta-1]))) { ip--; match--; } + filledIp = ip; + while (((ip>anchor) & (match > lowLimit)) && (unlikely(ip[-1]==match[-1]))) { ip--; match--; } - { - /* Encode Literal length */ - unsigned litLength = (unsigned)(ip - anchor); + /* Encode Literals */ + { unsigned const litLength = (unsigned)(ip - anchor); token = op++; - if ((outputLimited) && (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit))) - return 0; /* Check output limit */ - if (litLength>=RUN_MASK) - { - int len = (int)litLength-RUN_MASK; - *token=(RUN_MASK< olimit)) ) { + return 0; /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */ + } + if ((outputDirective == fillOutput) && + (unlikely(op + (litLength+240)/255 /* litlen */ + litLength /* literals */ + 2 /* offset */ + 1 /* token */ + MFLIMIT - MINMATCH /* min last literals so last match is <= end - MFLIMIT */ > olimit))) { + op--; + goto _last_literals; + } + if (litLength >= RUN_MASK) { + int len = (int)(litLength - RUN_MASK); + *token = (RUN_MASK<= 255 ; len-=255) *op++ = 255; *op++ = (BYTE)len; } else *token = (BYTE)(litLength< olimit)) { + /* the match was too close to the end, rewind and go to last literals */ + op = token; + goto _last_literals; + } + /* Encode Offset */ - LZ4_writeLE16(op, (U16)(ip-match)); op+=2; + if (maybe_extMem) { /* static test */ + DEBUGLOG(6, " with offset=%u (ext if > %i)", offset, (int)(ip - (const BYTE*)source)); + assert(offset <= LZ4_DISTANCE_MAX && offset > 0); + LZ4_writeLE16(op, (U16)offset); op+=2; + } else { + DEBUGLOG(6, " with offset=%u (same segment)", (U32)(ip - match)); + assert(ip-match <= LZ4_DISTANCE_MAX); + LZ4_writeLE16(op, (U16)(ip - match)); op+=2; + } /* Encode MatchLength */ - { - unsigned matchLength; + { unsigned matchCode; - if ((dict==usingExtDict) && (lowLimit==dictionary)) - { - const BYTE* limit; - match += refDelta; - limit = ip + (dictEnd-match); + if ( (dictDirective==usingExtDict || dictDirective==usingDictCtx) + && (lowLimit==dictionary) /* match within extDict */ ) { + const BYTE* limit = ip + (dictEnd-match); + assert(dictEnd > match); if (limit > matchlimit) limit = matchlimit; - matchLength = LZ4_count(ip+MINMATCH, match+MINMATCH, limit); - ip += MINMATCH + matchLength; - if (ip==limit) - { - unsigned more = LZ4_count(ip, (const BYTE*)source, matchlimit); - matchLength += more; + matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, limit); + ip += (size_t)matchCode + MINMATCH; + if (ip==limit) { + unsigned const more = LZ4_count(limit, (const BYTE*)source, matchlimit); + matchCode += more; ip += more; } - } - else - { - matchLength = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit); - ip += MINMATCH + matchLength; + DEBUGLOG(6, " with matchLength=%u starting in extDict", matchCode+MINMATCH); + } else { + matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit); + ip += (size_t)matchCode + MINMATCH; + DEBUGLOG(6, " with matchLength=%u", matchCode+MINMATCH); } - if ((outputLimited) && (unlikely(op + (1 + LASTLITERALS) + (matchLength>>8) > olimit))) - return 0; /* Check output limit */ - if (matchLength>=ML_MASK) - { - *token += ML_MASK; - matchLength -= ML_MASK; - for (; matchLength >= 510 ; matchLength-=510) { *op++ = 255; *op++ = 255; } - if (matchLength >= 255) { matchLength-=255; *op++ = 255; } - *op++ = (BYTE)matchLength; + if ((outputDirective) && /* Check output buffer overflow */ + (unlikely(op + (1 + LASTLITERALS) + (matchCode+240)/255 > olimit)) ) { + if (outputDirective == fillOutput) { + /* Match description too long : reduce it */ + U32 newMatchCode = 15 /* in token */ - 1 /* to avoid needing a zero byte */ + ((U32)(olimit - op) - 1 - LASTLITERALS) * 255; + ip -= matchCode - newMatchCode; + assert(newMatchCode < matchCode); + matchCode = newMatchCode; + if (unlikely(ip <= filledIp)) { + /* We have already filled up to filledIp so if ip ends up less than filledIp + * we have positions in the hash table beyond the current position. This is + * a problem if we reuse the hash table. So we have to remove these positions + * from the hash table. + */ + const BYTE* ptr; + DEBUGLOG(5, "Clearing %u positions", (U32)(filledIp - ip)); + for (ptr = ip; ptr <= filledIp; ++ptr) { + U32 const h = LZ4_hashPosition(ptr, tableType); + LZ4_clearHash(h, cctx->hashTable, tableType); + } + } + } else { + assert(outputDirective == limitedOutput); + return 0; /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */ + } } - else *token += (BYTE)(matchLength); + if (matchCode >= ML_MASK) { + *token += ML_MASK; + matchCode -= ML_MASK; + LZ4_write32(op, 0xFFFFFFFF); + while (matchCode >= 4*255) { + op+=4; + LZ4_write32(op, 0xFFFFFFFF); + matchCode -= 4*255; + } + op += matchCode / 255; + *op++ = (BYTE)(matchCode % 255); + } else + *token += (BYTE)(matchCode); } + /* Ensure we have enough space for the last literals. */ + assert(!(outputDirective == fillOutput && op + 1 + LASTLITERALS > olimit)); anchor = ip; /* Test end of chunk */ - if (ip > mflimit) break; + if (ip >= mflimitPlusOne) break; /* Fill table */ - LZ4_putPosition(ip-2, ctx, tableType, base); + LZ4_putPosition(ip-2, cctx->hashTable, tableType, base); /* Test next position */ - match = LZ4_getPosition(ip, ctx, tableType, base); - if (dict==usingExtDict) - { - if (match<(const BYTE*)source) - { - refDelta = dictDelta; - lowLimit = dictionary; + if (tableType == byPtr) { + + match = LZ4_getPosition(ip, cctx->hashTable, tableType, base); + LZ4_putPosition(ip, cctx->hashTable, tableType, base); + if ( (match+LZ4_DISTANCE_MAX >= ip) + && (LZ4_read32(match) == LZ4_read32(ip)) ) + { token=op++; *token=0; goto _next_match; } + + } else { /* byU32, byU16 */ + + U32 const h = LZ4_hashPosition(ip, tableType); + U32 const current = (U32)(ip-base); + U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType); + assert(matchIndex < current); + if (dictDirective == usingDictCtx) { + if (matchIndex < startIndex) { + /* there was no match, try the dictionary */ + matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32); + match = dictBase + matchIndex; + lowLimit = dictionary; /* required for match length counter */ + matchIndex += dictDelta; + } else { + match = base + matchIndex; + lowLimit = (const BYTE*)source; /* required for match length counter */ + } + } else if (dictDirective==usingExtDict) { + if (matchIndex < startIndex) { + match = dictBase + matchIndex; + lowLimit = dictionary; /* required for match length counter */ + } else { + match = base + matchIndex; + lowLimit = (const BYTE*)source; /* required for match length counter */ + } + } else { /* single memory segment */ + match = base + matchIndex; } - else - { - refDelta = 0; - lowLimit = (const BYTE*)source; + LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType); + assert(matchIndex < current); + if ( ((dictIssue==dictSmall) ? (matchIndex >= prefixIdxLimit) : 1) + && (((tableType==byU16) && (LZ4_DISTANCE_MAX == LZ4_DISTANCE_ABSOLUTE_MAX)) ? 1 : (matchIndex+LZ4_DISTANCE_MAX >= current)) + && (LZ4_read32(match) == LZ4_read32(ip)) ) { + token=op++; + *token=0; + if (maybe_extMem) offset = current - matchIndex; + DEBUGLOG(6, "seq.start:%i, literals=%u, match.start:%i", + (int)(anchor-(const BYTE*)source), 0, (int)(ip-(const BYTE*)source)); + goto _next_match; } } - LZ4_putPosition(ip, ctx, tableType, base); - if ( ((dictIssue==dictSmall) ? (match>=lowRefLimit) : 1) - && (match+MAX_DISTANCE>=ip) - && (LZ4_read32(match+refDelta)==LZ4_read32(ip)) ) - { token=op++; *token=0; goto _next_match; } /* Prepare next loop */ forwardH = LZ4_hashPosition(++ip, tableType); + } _last_literals: /* Encode Last Literals */ - { - const size_t lastRun = (size_t)(iend - anchor); - if ((outputLimited) && ((op - (BYTE*)dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize)) - return 0; /* Check output limit */ - if (lastRun >= RUN_MASK) - { + { size_t lastRun = (size_t)(iend - anchor); + if ( (outputDirective) && /* Check output buffer overflow */ + (op + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > olimit)) { + if (outputDirective == fillOutput) { + /* adapt lastRun to fill 'dst' */ + assert(olimit >= op); + lastRun = (size_t)(olimit-op) - 1/*token*/; + lastRun -= (lastRun + 256 - RUN_MASK) / 256; /*additional length tokens*/ + } else { + assert(outputDirective == limitedOutput); + return 0; /* cannot compress within `dst` budget. Stored indexes in hash table are nonetheless fine */ + } + } + DEBUGLOG(6, "Final literal run : %i literals", (int)lastRun); + if (lastRun >= RUN_MASK) { size_t accumulator = lastRun - RUN_MASK; *op++ = RUN_MASK << ML_BITS; for(; accumulator >= 255 ; accumulator-=255) *op++ = 255; *op++ = (BYTE) accumulator; - } - else - { + } else { *op++ = (BYTE)(lastRun<= LZ4_compressBound(inputSize)) - { - if (inputSize < LZ4_64Klimit) - return LZ4_compress_generic(state, source, dest, inputSize, 0, notLimited, byU16, noDict, noDictIssue, acceleration); - else - return LZ4_compress_generic(state, source, dest, inputSize, 0, notLimited, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue, acceleration); - } - else - { - if (inputSize < LZ4_64Klimit) - return LZ4_compress_generic(state, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration); - else - return LZ4_compress_generic(state, source, dest, inputSize, maxOutputSize, limitedOutput, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue, acceleration); - } -} - - -int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) -{ -#if (HEAPMODE) - void* ctxPtr = ALLOCATOR(1, sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */ -#else - LZ4_stream_t ctx; - void* ctxPtr = &ctx; -#endif - - int result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration); - -#if (HEAPMODE) - FREEMEM(ctxPtr); -#endif - return result; -} - - -int LZ4_compress_default(const char* source, char* dest, int inputSize, int maxOutputSize) -{ - return LZ4_compress_fast(source, dest, inputSize, maxOutputSize, 1); -} - - -/* hidden debug function */ -/* strangely enough, gcc generates faster code when this function is uncommented, even if unused */ -int LZ4_compress_fast_force(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) -{ - LZ4_stream_t ctx; - - LZ4_resetStream(&ctx); - - if (inputSize < LZ4_64Klimit) - return LZ4_compress_generic(&ctx, source, dest, inputSize, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration); - else - return LZ4_compress_generic(&ctx, source, dest, inputSize, maxOutputSize, limitedOutput, LZ4_64bits() ? byU32 : byPtr, noDict, noDictIssue, acceleration); -} - - -/******************************** -* destSize variant -********************************/ - -static int LZ4_compress_destSize_generic( - void* const ctx, - const char* const src, - char* const dst, - int* const srcSizePtr, - const int targetDstSize, - const tableType_t tableType) -{ - const BYTE* ip = (const BYTE*) src; - const BYTE* base = (const BYTE*) src; - const BYTE* lowLimit = (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; - - BYTE* op = (BYTE*) dst; - BYTE* const oend = op + targetDstSize; - BYTE* const oMaxLit = op + targetDstSize - 2 /* offset */ - 8 /* because 8+MINMATCH==MFLIMIT */ - 1 /* token */; - BYTE* const oMaxMatch = op + targetDstSize - (LASTLITERALS + 1 /* token */); - BYTE* const oMaxSeq = oMaxLit - 1 /* token */; - - U32 forwardH; - - - /* Init conditions */ - if (targetDstSize < 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 ((tableType == byU16) && (*srcSizePtr>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */ - if (*srcSizePtr> LZ4_skipTrigger); - - if (unlikely(forwardIp > mflimit)) - goto _last_literals; - - match = LZ4_getPositionOnHash(h, ctx, tableType, base); - forwardH = LZ4_hashPosition(forwardIp, tableType); - LZ4_putPositionOnHash(ip, h, ctx, tableType, base); - - } while ( ((tableType==byU16) ? 0 : (match + MAX_DISTANCE < ip)) - || (LZ4_read32(match) != LZ4_read32(ip)) ); - } - - /* Catch up */ - while ((ip>anchor) && (match > lowLimit) && (unlikely(ip[-1]==match[-1]))) { ip--; match--; } - - { - /* Encode Literal length */ - unsigned litLength = (unsigned)(ip - anchor); - token = op++; - if (op + ((litLength+240)/255) + litLength > oMaxLit) - { - /* Not enough space for a last match */ - op--; - goto _last_literals; - } - if (litLength>=RUN_MASK) - { - unsigned len = litLength - RUN_MASK; - *token=(RUN_MASK<= 255 ; len-=255) *op++ = 255; - *op++ = (BYTE)len; - } - else *token = (BYTE)(litLength< oMaxMatch) - { - /* Match description too long : reduce it */ - matchLength = (15-1) + (oMaxMatch-op) * 255; - } - //printf("offset %5i, matchLength%5i \n", (int)(ip-match), matchLength + MINMATCH); - ip += MINMATCH + matchLength; - - if (matchLength>=ML_MASK) - { - *token += ML_MASK; - matchLength -= ML_MASK; - while (matchLength >= 255) { matchLength-=255; *op++ = 255; } - *op++ = (BYTE)matchLength; - } - else *token += (BYTE)(matchLength); - } - - anchor = ip; + } + LZ4_memcpy(op, anchor, lastRun); + ip = anchor + lastRun; + op += lastRun; + } - /* Test end of block */ - if (ip > mflimit) break; - if (op > oMaxSeq) break; + if (outputDirective == fillOutput) { + *inputConsumed = (int) (((const char*)ip)-source); + } + result = (int)(((char*)op) - dest); + assert(result > 0); + DEBUGLOG(5, "LZ4_compress_generic: compressed %i bytes into %i bytes", inputSize, result); + return result; +} - /* Fill table */ - LZ4_putPosition(ip-2, ctx, tableType, base); +/** LZ4_compress_generic() : + * inlined, to ensure branches are decided at compilation time; + * takes care of src == (NULL, 0) + * and forward the rest to LZ4_compress_generic_validated */ +LZ4_FORCE_INLINE int LZ4_compress_generic( + LZ4_stream_t_internal* const cctx, + const char* const src, + char* const dst, + const int srcSize, + int *inputConsumed, /* only written when outputDirective == fillOutput */ + const int dstCapacity, + const limitedOutput_directive outputDirective, + const tableType_t tableType, + const dict_directive dictDirective, + const dictIssue_directive dictIssue, + const int acceleration) +{ + DEBUGLOG(5, "LZ4_compress_generic: srcSize=%i, dstCapacity=%i", + srcSize, dstCapacity); + + if ((U32)srcSize > (U32)LZ4_MAX_INPUT_SIZE) { return 0; } /* Unsupported srcSize, too large (or negative) */ + if (srcSize == 0) { /* src == NULL supported if srcSize == 0 */ + if (outputDirective != notLimited && dstCapacity <= 0) return 0; /* no output, can't write anything */ + DEBUGLOG(5, "Generating an empty block"); + assert(outputDirective == notLimited || dstCapacity >= 1); + assert(dst != NULL); + dst[0] = 0; + if (outputDirective == fillOutput) { + assert (inputConsumed != NULL); + *inputConsumed = 0; + } + return 1; + } + assert(src != NULL); - /* Test next position */ - match = LZ4_getPosition(ip, ctx, tableType, base); - LZ4_putPosition(ip, ctx, tableType, base); - if ( (match+MAX_DISTANCE>=ip) - && (LZ4_read32(match)==LZ4_read32(ip)) ) - { token=op++; *token=0; goto _next_match; } + return LZ4_compress_generic_validated(cctx, src, dst, srcSize, + inputConsumed, /* only written into if outputDirective == fillOutput */ + dstCapacity, outputDirective, + tableType, dictDirective, dictIssue, acceleration); +} - /* Prepare next loop */ - forwardH = LZ4_hashPosition(++ip, tableType); - } -_last_literals: - /* Encode Last Literals */ - { - size_t lastRunSize = (size_t)(iend - anchor); - if (op + 1 /* token */ + ((lastRunSize+240)/255) /* litLength */ + lastRunSize /* literals */ > oend) - { - /* adapt lastRunSize to fill 'dst' */ - lastRunSize = (oend-op) - 1; - lastRunSize -= (lastRunSize+240)/255; +int LZ4_compress_fast_extState(void* state, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) +{ + LZ4_stream_t_internal* const ctx = & LZ4_initStream(state, sizeof(LZ4_stream_t)) -> internal_donotuse; + assert(ctx != NULL); + if (acceleration < 1) acceleration = LZ4_ACCELERATION_DEFAULT; + if (acceleration > LZ4_ACCELERATION_MAX) acceleration = LZ4_ACCELERATION_MAX; + if (maxOutputSize >= LZ4_compressBound(inputSize)) { + if (inputSize < LZ4_64Klimit) { + return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, byU16, noDict, noDictIssue, acceleration); + } else { + const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > LZ4_DISTANCE_MAX)) ? byPtr : byU32; + return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration); } - ip = anchor + lastRunSize; + } else { + if (inputSize < LZ4_64Klimit) { + return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration); + } else { + const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > LZ4_DISTANCE_MAX)) ? byPtr : byU32; + return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, noDict, noDictIssue, acceleration); + } + } +} - 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; +/** + * LZ4_compress_fast_extState_fastReset() : + * A variant of LZ4_compress_fast_extState(). + * + * Using this variant avoids an expensive initialization step. It is only safe + * to call if the state buffer is known to be correctly initialized already + * (see comment in lz4.h on LZ4_resetStream_fast() for a definition of + * "correctly initialized"). + */ +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; + if (acceleration < 1) acceleration = LZ4_ACCELERATION_DEFAULT; + if (acceleration > LZ4_ACCELERATION_MAX) acceleration = LZ4_ACCELERATION_MAX; + + if (dstCapacity >= LZ4_compressBound(srcSize)) { + if (srcSize < LZ4_64Klimit) { + const tableType_t tableType = byU16; + LZ4_prepareTable(ctx, srcSize, tableType); + if (ctx->currentOffset) { + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, dictSmall, acceleration); + } else { + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration); + } + } else { + const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32; + LZ4_prepareTable(ctx, srcSize, tableType); + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration); } - else - { - *op++ = (BYTE)(lastRunSize<currentOffset) { + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, dictSmall, acceleration); + } else { + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration); + } + } else { + const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > LZ4_DISTANCE_MAX)) ? byPtr : byU32; + LZ4_prepareTable(ctx, srcSize, tableType); + return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration); } - memcpy(op, anchor, lastRunSize); - op += lastRunSize; } +} + + +int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) +{ + int result; +#if (LZ4_HEAPMODE) + LZ4_stream_t* ctxPtr = 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); + +#if (LZ4_HEAPMODE) + FREEMEM(ctxPtr); +#endif + return result; +} + - /* End */ - *srcSizePtr = (int) (((const char*)ip)-src); - return (int) (((char*)op)-dst); +int LZ4_compress_default(const char* src, char* dst, int srcSize, int maxOutputSize) +{ + return LZ4_compress_fast(src, dst, srcSize, maxOutputSize, 1); } -static int LZ4_compress_destSize_extState (void* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize) +/* 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) { - LZ4_resetStream((LZ4_stream_t*)state); + void* const s = LZ4_initStream(state, sizeof (*state)); + assert(s != NULL); (void)s; - if (targetDstSize >= LZ4_compressBound(*srcSizePtr)) /* compression success is guaranteed */ - { + if (targetDstSize >= LZ4_compressBound(*srcSizePtr)) { /* compression success is guaranteed */ return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, 1); - } - else - { - if (*srcSizePtr < LZ4_64Klimit) - return LZ4_compress_destSize_generic(state, src, dst, srcSizePtr, targetDstSize, byU16); - else - return LZ4_compress_destSize_generic(state, src, dst, srcSizePtr, targetDstSize, LZ4_64bits() ? byU32 : byPtr); - } + } else { + if (*srcSizePtr < LZ4_64Klimit) { + return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, byU16, noDict, noDictIssue, 1); + } 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); + } } } int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize) { -#if (HEAPMODE) - void* ctx = ALLOCATOR(1, sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */ +#if (LZ4_HEAPMODE) + LZ4_stream_t* ctx = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */ + if (ctx == NULL) return 0; #else LZ4_stream_t ctxBody; - void* ctx = &ctxBody; + LZ4_stream_t* ctx = &ctxBody; #endif int result = LZ4_compress_destSize_extState(ctx, src, dst, srcSizePtr, targetDstSize); -#if (HEAPMODE) +#if (LZ4_HEAPMODE) FREEMEM(ctx); #endif return result; @@ -928,76 +1416,142 @@ int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targe -/******************************** +/*-****************************** * Streaming functions ********************************/ LZ4_stream_t* LZ4_createStream(void) { - LZ4_stream_t* lz4s = (LZ4_stream_t*)ALLOCATOR(8, LZ4_STREAMSIZE_U64); + LZ4_stream_t* const lz4s = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t)); LZ4_STATIC_ASSERT(LZ4_STREAMSIZE >= sizeof(LZ4_stream_t_internal)); /* A compilation error here means LZ4_STREAMSIZE is not large enough */ - LZ4_resetStream(lz4s); + DEBUGLOG(4, "LZ4_createStream %p", lz4s); + if (lz4s == NULL) return NULL; + LZ4_initStream(lz4s, sizeof(*lz4s)); return lz4s; } +static size_t LZ4_stream_t_alignment(void) +{ +#if LZ4_ALIGN_TEST + typedef struct { char c; LZ4_stream_t t; } t_a; + return sizeof(t_a) - sizeof(LZ4_stream_t); +#else + return 1; /* effectively disabled */ +#endif +} + +LZ4_stream_t* LZ4_initStream (void* buffer, size_t size) +{ + DEBUGLOG(5, "LZ4_initStream"); + if (buffer == NULL) { return NULL; } + if (size < sizeof(LZ4_stream_t)) { return NULL; } + if (!LZ4_isAligned(buffer, LZ4_stream_t_alignment())) return NULL; + MEM_INIT(buffer, 0, sizeof(LZ4_stream_t_internal)); + return (LZ4_stream_t*)buffer; +} + +/* resetStream is now deprecated, + * prefer initStream() which is more general */ void LZ4_resetStream (LZ4_stream_t* LZ4_stream) { - MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t)); + DEBUGLOG(5, "LZ4_resetStream (ctx:%p)", LZ4_stream); + MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t_internal)); +} + +void LZ4_resetStream_fast(LZ4_stream_t* ctx) { + LZ4_prepareTable(&(ctx->internal_donotuse), 0, byU32); } int LZ4_freeStream (LZ4_stream_t* LZ4_stream) { + if (!LZ4_stream) return 0; /* support free on NULL */ + DEBUGLOG(5, "LZ4_freeStream %p", LZ4_stream); FREEMEM(LZ4_stream); return (0); } -#define HASH_UNIT sizeof(size_t) +#define HASH_UNIT sizeof(reg_t) int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize) { - LZ4_stream_t_internal* dict = (LZ4_stream_t_internal*) LZ4_dict; + LZ4_stream_t_internal* 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; - if ((dict->initCheck) || (dict->currentOffset > 1 GB)) /* Uninitialized structure, or reuse overflow */ - LZ4_resetStream(LZ4_dict); + DEBUGLOG(4, "LZ4_loadDict (%i bytes from %p into %p)", dictSize, dictionary, LZ4_dict); - if (dictSize < (int)HASH_UNIT) - { - dict->dictionary = NULL; - dict->dictSize = 0; + /* It's necessary to reset the context, + * and not just continue it with prepareTable() + * to avoid any risk of generating overflowing matchIndex + * when compressing using this dictionary */ + LZ4_resetStream(LZ4_dict); + + /* We always increment the offset by 64 KB, since, if the dict is longer, + * we truncate it to the last 64k, and if it's shorter, we still want to + * advance by a whole window length so we can provide the guarantee that + * there are only valid offsets in the window, which allows an optimization + * in LZ4_compress_fast_continue() where it uses noDictIssue even when the + * dictionary isn't a full 64k. */ + dict->currentOffset += 64 KB; + + if (dictSize < (int)HASH_UNIT) { return 0; } if ((dictEnd - p) > 64 KB) p = dictEnd - 64 KB; - dict->currentOffset += 64 KB; - base = p - dict->currentOffset; + base = dictEnd - dict->currentOffset; dict->dictionary = p; dict->dictSize = (U32)(dictEnd - p); - dict->currentOffset += dict->dictSize; + dict->tableType = (U32)tableType; - while (p <= dictEnd-HASH_UNIT) - { - LZ4_putPosition(p, dict->hashTable, byU32, base); + while (p <= dictEnd-HASH_UNIT) { + LZ4_putPosition(p, dict->hashTable, tableType, base); p+=3; } - return dict->dictSize; + return (int)dict->dictSize; +} + +void LZ4_attach_dictionary(LZ4_stream_t* workingStream, const LZ4_stream_t* dictionaryStream) { + const LZ4_stream_t_internal* dictCtx = dictionaryStream == NULL ? NULL : + &(dictionaryStream->internal_donotuse); + + DEBUGLOG(4, "LZ4_attach_dictionary (%p, %p, size %u)", + workingStream, dictionaryStream, + dictCtx != NULL ? dictCtx->dictSize : 0); + + if (dictCtx != NULL) { + /* If the current offset is zero, we will never look in the + * external dictionary context, since there is no value a table + * entry can take that indicate a miss. In that case, we need + * to bump the offset to something non-zero. + */ + if (workingStream->internal_donotuse.currentOffset == 0) { + workingStream->internal_donotuse.currentOffset = 64 KB; + } + + /* Don't actually attach an empty dictionary. + */ + if (dictCtx->dictSize == 0) { + dictCtx = NULL; + } + } + workingStream->internal_donotuse.dictCtx = dictCtx; } -static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, const BYTE* src) +static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, int nextSize) { - if ((LZ4_dict->currentOffset > 0x80000000) || - ((size_t)LZ4_dict->currentOffset > (size_t)src)) /* address space overflow */ - { + assert(nextSize >= 0); + if (LZ4_dict->currentOffset + (unsigned)nextSize > 0x80000000) { /* potential ptrdiff_t overflow (32-bits mode) */ /* rescale hash table */ - U32 delta = LZ4_dict->currentOffset - 64 KB; + U32 const delta = LZ4_dict->currentOffset - 64 KB; const BYTE* dictEnd = LZ4_dict->dictionary + LZ4_dict->dictSize; int i; - for (i=0; ihashTable[i] < delta) LZ4_dict->hashTable[i]=0; else LZ4_dict->hashTable[i] -= delta; } @@ -1008,22 +1562,33 @@ static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, const BYTE* src) } -int LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration) +int LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream, + const char* source, char* dest, + int inputSize, int maxOutputSize, + int acceleration) { - LZ4_stream_t_internal* streamPtr = (LZ4_stream_t_internal*)LZ4_stream; - const BYTE* const dictEnd = streamPtr->dictionary + streamPtr->dictSize; + const tableType_t tableType = byU32; + LZ4_stream_t_internal* streamPtr = &LZ4_stream->internal_donotuse; + const BYTE* dictEnd = streamPtr->dictionary + streamPtr->dictSize; - const BYTE* smallest = (const BYTE*) source; - if (streamPtr->initCheck) return 0; /* Uninitialized structure detected */ - if ((streamPtr->dictSize>0) && (smallest>dictEnd)) smallest = dictEnd; - LZ4_renormDictT(streamPtr, smallest); - if (acceleration < 1) acceleration = ACCELERATION_DEFAULT; + DEBUGLOG(5, "LZ4_compress_fast_continue (inputSize=%i)", inputSize); + + LZ4_renormDictT(streamPtr, inputSize); /* avoid index overflow */ + if (acceleration < 1) acceleration = LZ4_ACCELERATION_DEFAULT; + if (acceleration > LZ4_ACCELERATION_MAX) acceleration = LZ4_ACCELERATION_MAX; + + /* invalidate tiny dictionaries */ + if ( (streamPtr->dictSize-1 < 4-1) /* intentional underflow */ + && (dictEnd != (const BYTE*)source) ) { + DEBUGLOG(5, "LZ4_compress_fast_continue: dictSize(%u) at addr:%p is too small", streamPtr->dictSize, streamPtr->dictionary); + streamPtr->dictSize = 0; + streamPtr->dictionary = (const BYTE*)source; + dictEnd = (const BYTE*)source; + } /* Check overlapping input/dictionary space */ - { - const BYTE* sourceEnd = (const BYTE*) source + inputSize; - if ((sourceEnd > streamPtr->dictionary) && (sourceEnd < dictEnd)) - { + { const BYTE* sourceEnd = (const BYTE*) source + inputSize; + if ((sourceEnd > streamPtr->dictionary) && (sourceEnd < dictEnd)) { streamPtr->dictSize = (U32)(dictEnd - sourceEnd); if (streamPtr->dictSize > 64 KB) streamPtr->dictSize = 64 KB; if (streamPtr->dictSize < 4) streamPtr->dictSize = 0; @@ -1032,63 +1597,85 @@ int LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream, const char* source, ch } /* prefix mode : source data follows dictionary */ - if (dictEnd == (const BYTE*)source) - { - int result; + if (dictEnd == (const BYTE*)source) { if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) - result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, withPrefix64k, dictSmall, acceleration); + return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, dictSmall, acceleration); else - result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, withPrefix64k, noDictIssue, acceleration); - streamPtr->dictSize += (U32)inputSize; - streamPtr->currentOffset += (U32)inputSize; - return result; + return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, noDictIssue, acceleration); } /* external dictionary mode */ - { - int result; - if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) - result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, usingExtDict, dictSmall, acceleration); - else - result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, usingExtDict, noDictIssue, acceleration); + { int result; + if (streamPtr->dictCtx) { + /* We depend here on the fact that dictCtx'es (produced by + * LZ4_loadDict) guarantee that their tables contain no references + * to offsets between dictCtx->currentOffset - 64 KB and + * dictCtx->currentOffset - dictCtx->dictSize. This makes it safe + * to use noDictIssue even when the dict isn't a full 64 KB. + */ + if (inputSize > 4 KB) { + /* For compressing large blobs, it is faster to pay the setup + * cost to copy the dictionary's tables into the active context, + * so that the compression loop is only looking into one table. + */ + LZ4_memcpy(streamPtr, streamPtr->dictCtx, sizeof(*streamPtr)); + result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration); + } else { + result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingDictCtx, noDictIssue, acceleration); + } + } else { + if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) { + result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, dictSmall, acceleration); + } else { + result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration); + } + } streamPtr->dictionary = (const BYTE*)source; streamPtr->dictSize = (U32)inputSize; - streamPtr->currentOffset += (U32)inputSize; return result; } } -/* Hidden debug function, to force external dictionary mode */ -int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int inputSize) +/* 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_stream_t_internal*)LZ4_dict; + LZ4_stream_t_internal* streamPtr = &LZ4_dict->internal_donotuse; int result; - const BYTE* const dictEnd = streamPtr->dictionary + streamPtr->dictSize; - const BYTE* smallest = dictEnd; - if (smallest > (const BYTE*) source) smallest = (const BYTE*) source; - LZ4_renormDictT((LZ4_stream_t_internal*)LZ4_dict, smallest); + LZ4_renormDictT(streamPtr, srcSize); - result = LZ4_compress_generic(LZ4_dict, source, dest, inputSize, 0, notLimited, byU32, usingExtDict, noDictIssue, 1); + if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) { + result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, dictSmall, 1); + } else { + result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, noDictIssue, 1); + } streamPtr->dictionary = (const BYTE*)source; - streamPtr->dictSize = (U32)inputSize; - streamPtr->currentOffset += (U32)inputSize; + streamPtr->dictSize = (U32)srcSize; return result; } +/*! LZ4_saveDict() : + * If previously compressed data block is not guaranteed to remain available at its memory location, + * save it into a safer place (char* safeBuffer). + * Note : you don't need to call LZ4_loadDict() afterwards, + * dictionary is immediately usable, you can therefore call LZ4_compress_fast_continue(). + * Return : saved dictionary size in bytes (necessarily <= dictSize), or 0 if error. + */ int LZ4_saveDict (LZ4_stream_t* LZ4_dict, char* safeBuffer, int dictSize) { - LZ4_stream_t_internal* dict = (LZ4_stream_t_internal*) LZ4_dict; - const BYTE* previousDictEnd = dict->dictionary + dict->dictSize; + LZ4_stream_t_internal* const dict = &LZ4_dict->internal_donotuse; + const BYTE* const previousDictEnd = dict->dictionary + dict->dictSize; - if ((U32)dictSize > 64 KB) dictSize = 64 KB; /* useless to define a dictionary > 64 KB */ - if ((U32)dictSize > dict->dictSize) dictSize = dict->dictSize; + if ((U32)dictSize > 64 KB) { dictSize = 64 KB; } /* useless to define a dictionary > 64 KB */ + if ((U32)dictSize > dict->dictSize) { dictSize = (int)dict->dictSize; } - memmove(safeBuffer, previousDictEnd - dictSize, dictSize); + if (safeBuffer == NULL) assert(dictSize == 0); + if (dictSize > 0) + memmove(safeBuffer, previousDictEnd - dictSize, dictSize); dict->dictionary = (const BYTE*)safeBuffer; dict->dictSize = (U32)dictSize; @@ -1098,246 +1685,606 @@ int LZ4_saveDict (LZ4_stream_t* LZ4_dict, char* safeBuffer, int dictSize) -/******************************* -* Decompression functions -*******************************/ -/* - * This generic decompression function cover all use cases. - * It shall be instantiated several times, using different sets of directives - * Note that it is essential this generic function is really inlined, - * in order to remove useless branches during compilation optimization. +/*-******************************* + * Decompression functions + ********************************/ + +typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive; +typedef enum { decode_full_block = 0, partial_decode = 1 } earlyEnd_directive; + +#undef MIN +#define MIN(a,b) ( (a) < (b) ? (a) : (b) ) + +/* Read the variable-length literal or match length. + * + * ip - pointer to use as input. + * lencheck - end ip. Return an error if ip advances >= lencheck. + * loop_check - check ip >= lencheck in body of loop. Returns loop_error if so. + * initial_check - check ip >= lencheck before start of loop. Returns initial_error if so. + * error (output) - error code. Should be set to 0 before call. */ -FORCE_INLINE int LZ4_decompress_generic( - const char* const source, - char* const dest, - int inputSize, - int outputSize, /* If endOnInput==endOnInputSize, this value is the max size of Output Buffer. */ - - int endOnInput, /* endOnOutputSize, endOnInputSize */ - int partialDecoding, /* full, partial */ - int targetOutputSize, /* only used if partialDecoding==partial */ - int dict, /* noDict, withPrefix64k, usingExtDict */ - const BYTE* const lowPrefix, /* == dest if dict == noDict */ +typedef enum { loop_error = -2, initial_error = -1, ok = 0 } variable_length_error; +LZ4_FORCE_INLINE unsigned +read_variable_length(const BYTE**ip, const BYTE* lencheck, + int loop_check, int initial_check, + variable_length_error* error) +{ + U32 length = 0; + U32 s; + if (initial_check && unlikely((*ip) >= lencheck)) { /* overflow detection */ + *error = initial_error; + return length; + } + do { + s = **ip; + (*ip)++; + length += s; + if (loop_check && unlikely((*ip) >= lencheck)) { /* overflow detection */ + *error = loop_error; + return length; + } + } while (s==255); + + return length; +} + +/*! LZ4_decompress_generic() : + * This generic decompression function covers all use cases. + * It shall be instantiated several times, using different sets of directives. + * Note that it is important for performance that this function really get inlined, + * in order to remove useless branches during compilation optimization. + */ +LZ4_FORCE_INLINE int +LZ4_decompress_generic( + const char* const src, + char* const dst, + int srcSize, + int outputSize, /* If endOnInput==endOnInputSize, this value is `dstCapacity` */ + + endCondition_directive endOnInput, /* endOnOutputSize, endOnInputSize */ + earlyEnd_directive partialDecoding, /* full, partial */ + dict_directive dict, /* noDict, withPrefix64k, usingExtDict */ + const BYTE* const lowPrefix, /* always <= dst, == dst when no prefix */ const BYTE* const dictStart, /* only if dict==usingExtDict */ const size_t dictSize /* note : = 0 if noDict */ ) { - /* Local Variables */ - const BYTE* ip = (const BYTE*) source; - const BYTE* const iend = ip + inputSize; + if (src == NULL) { return -1; } - BYTE* op = (BYTE*) dest; - BYTE* const oend = op + outputSize; - BYTE* cpy; - BYTE* oexit = op + targetOutputSize; - const BYTE* const lowLimit = lowPrefix - dictSize; + { const BYTE* ip = (const BYTE*) src; + const BYTE* const iend = ip + srcSize; - const BYTE* const dictEnd = (const BYTE*)dictStart + dictSize; - const size_t dec32table[] = {4, 1, 2, 1, 4, 4, 4, 4}; - const size_t dec64table[] = {0, 0, 0, (size_t)-1, 0, 1, 2, 3}; + BYTE* op = (BYTE*) dst; + BYTE* const oend = op + outputSize; + BYTE* cpy; - const int safeDecode = (endOnInput==endOnInputSize); - const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB))); + const BYTE* const dictEnd = (dictStart == NULL) ? NULL : dictStart + dictSize; + const int safeDecode = (endOnInput==endOnInputSize); + const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB))); - /* Special cases */ - if ((partialDecoding) && (oexit> oend-MFLIMIT)) oexit = oend-MFLIMIT; /* targetOutputSize too high => decode everything */ - if ((endOnInput) && (unlikely(outputSize==0))) return ((inputSize==1) && (*ip==0)) ? 0 : -1; /* Empty output buffer */ - if ((!endOnInput) && (unlikely(outputSize==0))) return (*ip==0?1:-1); + /* Set up the "end" pointers for the shortcut. */ + const BYTE* const shortiend = iend - (endOnInput ? 14 : 8) /*maxLL*/ - 2 /*offset*/; + const BYTE* const shortoend = oend - (endOnInput ? 14 : 8) /*maxLL*/ - 18 /*maxML*/; - /* Main Loop */ - while (1) - { + const BYTE* match; + size_t offset; unsigned token; size_t length; - const BYTE* match; - /* get literal length */ - token = *ip++; - if ((length=(token>>ML_BITS)) == RUN_MASK) - { - unsigned s; - do - { - s = *ip++; - length += s; - } - while (likely((endOnInput)?ip(partialDecoding?oexit:oend-MFLIMIT)) || (ip+length>iend-(2+1+LASTLITERALS))) ) - || ((!endOnInput) && (cpy>oend-COPYLENGTH))) - { - if (partialDecoding) - { - if (cpy > oend) goto _output_error; /* Error : write attempt beyond end of output buffer */ - if ((endOnInput) && (ip+length > iend)) goto _output_error; /* Error : read attempt beyond end of input buffer */ + /* Fast loop : decode sequences as long as output < iend-FASTLOOP_SAFE_DISTANCE */ + while (1) { + /* Main fastloop assertion: We can always wildcopy FASTLOOP_SAFE_DISTANCE */ + assert(oend - op >= FASTLOOP_SAFE_DISTANCE); + if (endOnInput) { assert(ip < iend); } + token = *ip++; + length = token >> ML_BITS; /* literal length */ + + assert(!endOnInput || ip <= iend); /* ip < iend before the increment */ + + /* decode literal length */ + if (length == RUN_MASK) { + variable_length_error error = ok; + length += read_variable_length(&ip, iend-RUN_MASK, (int)endOnInput, (int)endOnInput, &error); + if (error == initial_error) { goto _output_error; } + if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)(op))) { goto _output_error; } /* overflow detection */ + if ((safeDecode) && unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */ + + /* copy literals */ + cpy = op+length; + LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH); + if (endOnInput) { /* LZ4_decompress_safe() */ + if ((cpy>oend-32) || (ip+length>iend-32)) { goto safe_literal_copy; } + LZ4_wildCopy32(op, ip, cpy); + } else { /* LZ4_decompress_fast() */ + if (cpy>oend-8) { goto safe_literal_copy; } + LZ4_wildCopy8(op, ip, cpy); /* LZ4_decompress_fast() cannot copy more than 8 bytes at a time : + * it doesn't know input length, and only relies on end-of-block properties */ + } + ip += length; op = cpy; + } else { + cpy = op+length; + if (endOnInput) { /* LZ4_decompress_safe() */ + DEBUGLOG(7, "copy %u bytes in a 16-bytes stripe", (unsigned)length); + /* 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; } + /* Literals can only be 14, but hope compilers optimize if we copy by a register size */ + LZ4_memcpy(op, ip, 16); + } else { /* LZ4_decompress_fast() */ + /* LZ4_decompress_fast() cannot copy more than 8 bytes at a time : + * it doesn't know input length, and relies on end-of-block properties */ + LZ4_memcpy(op, ip, 8); + if (length > 8) { LZ4_memcpy(op+8, ip+8, 8); } + } + ip += length; op = cpy; } - else - { - if ((!endOnInput) && (cpy != oend)) goto _output_error; /* Error : block decoding must stop exactly there */ - if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) goto _output_error; /* Error : input must be consumed */ + + /* get offset */ + offset = LZ4_readLE16(ip); ip+=2; + match = op - offset; + assert(match <= op); + + /* get matchlength */ + length = token & ML_MASK; + + if (length == ML_MASK) { + variable_length_error error = ok; + if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) { goto _output_error; } /* Error : offset outside buffers */ + length += read_variable_length(&ip, iend - LASTLITERALS + 1, (int)endOnInput, 0, &error); + if (error != ok) { goto _output_error; } + if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) { goto _output_error; } /* overflow detection */ + length += MINMATCH; + if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) { + goto safe_match_copy; + } + } else { + length += MINMATCH; + if (op + length >= oend - FASTLOOP_SAFE_DISTANCE) { + goto safe_match_copy; + } + + /* Fastpath check: Avoids a branch in LZ4_wildCopy32 if true */ + if ((dict == withPrefix64k) || (match >= lowPrefix)) { + if (offset >= 8) { + assert(match >= lowPrefix); + assert(match <= op); + assert(op + 18 <= oend); + + LZ4_memcpy(op, match, 8); + LZ4_memcpy(op+8, match+8, 8); + LZ4_memcpy(op+16, match+16, 2); + op += length; + continue; + } } } + + if (checkOffset && (unlikely(match + dictSize < lowPrefix))) { goto _output_error; } /* Error : offset outside buffers */ + /* match starting within external dictionary */ + if ((dict==usingExtDict) && (match < lowPrefix)) { + if (unlikely(op+length > oend-LASTLITERALS)) { + if (partialDecoding) { + DEBUGLOG(7, "partialDecoding: dictionary match, close to dstEnd"); + length = MIN(length, (size_t)(oend-op)); + } else { + goto _output_error; /* end-of-block condition violated */ + } } + + if (length <= (size_t)(lowPrefix-match)) { + /* match fits entirely within external dictionary : just copy */ + memmove(op, dictEnd - (lowPrefix-match), length); + op += length; + } else { + /* match stretches into both external dictionary and current block */ + size_t const copySize = (size_t)(lowPrefix - match); + size_t const restSize = length - copySize; + LZ4_memcpy(op, dictEnd - copySize, copySize); + op += copySize; + if (restSize > (size_t)(op - lowPrefix)) { /* overlap copy */ + BYTE* const endOfMatch = op + restSize; + const BYTE* copyFrom = lowPrefix; + while (op < endOfMatch) { *op++ = *copyFrom++; } + } else { + LZ4_memcpy(op, lowPrefix, restSize); + op += restSize; + } } + continue; } - memcpy(op, ip, length); - ip += length; - op += length; - break; /* Necessarily EOF, due to parsing restrictions */ - } - LZ4_wildCopy(op, ip, cpy); - ip += length; op = cpy; - /* get offset */ - match = cpy - LZ4_readLE16(ip); ip+=2; - if ((checkOffset) && (unlikely(match < lowLimit))) goto _output_error; /* Error : offset outside destination buffer */ + /* copy match within block */ + cpy = op + length; - /* get matchlength */ - length = token & ML_MASK; - if (length == ML_MASK) - { - unsigned s; - do - { - if ((endOnInput) && (ip > iend-LASTLITERALS)) goto _output_error; - s = *ip++; - length += s; - } while (s==255); - if ((safeDecode) && unlikely((size_t)(op+length)<(size_t)op)) goto _output_error; /* overflow detection */ + assert((op <= oend) && (oend-op >= 32)); + if (unlikely(offset<16)) { + LZ4_memcpy_using_offset(op, match, cpy, offset); + } else { + LZ4_wildCopy32(op, match, cpy); + } + + op = cpy; /* wildcopy correction */ } - length += MINMATCH; + safe_decode: +#endif - /* check external dictionary */ - if ((dict==usingExtDict) && (match < lowPrefix)) - { - if (unlikely(op+length > oend-LASTLITERALS)) goto _output_error; /* doesn't respect parsing restriction */ + /* Main Loop : decode remaining sequences where output < FASTLOOP_SAFE_DISTANCE */ + while (1) { + token = *ip++; + length = token >> ML_BITS; /* literal length */ + + assert(!endOnInput || ip <= iend); /* ip < iend before the increment */ + + /* A two-stage shortcut for the most common case: + * 1) If the literal length is 0..14, and there is enough space, + * enter the shortcut and copy 16 bytes on behalf of the literals + * (in the fast mode, only 8 bytes can be safely copied this way). + * 2) Further if the match length is 4..18, copy 18 bytes in a similar + * manner; but we ensure that there's enough space in the output for + * those 18 bytes earlier, upon entering the shortcut (in other words, + * there is a combined check for both stages). + */ + if ( (endOnInput ? length != RUN_MASK : length <= 8) + /* strictly "less than" on input, to re-enter the loop with at least one byte */ + && likely((endOnInput ? ip < shortiend : 1) & (op <= shortoend)) ) { + /* Copy the literals */ + LZ4_memcpy(op, ip, endOnInput ? 16 : 8); + op += length; ip += length; + + /* 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 */ + offset = LZ4_readLE16(ip); ip += 2; + match = op - offset; + assert(match <= op); /* check overflow */ + + /* Do not deal with overlapping matches. */ + if ( (length != ML_MASK) + && (offset >= 8) + && (dict==withPrefix64k || match >= lowPrefix) ) { + /* Copy the match. */ + LZ4_memcpy(op + 0, match + 0, 8); + LZ4_memcpy(op + 8, match + 8, 8); + LZ4_memcpy(op +16, match +16, 2); + op += length + MINMATCH; + /* Both stages worked, load the next token. */ + continue; + } - if (length <= (size_t)(lowPrefix-match)) - { - /* match can be copied as a single segment from external dictionary */ - match = dictEnd - (lowPrefix-match); - memmove(op, match, length); op += length; + /* The second stage didn't work out, but the info is ready. + * Propel it right to the point of match copying. */ + goto _copy_match; + } + + /* decode literal length */ + if (length == RUN_MASK) { + variable_length_error error = ok; + length += read_variable_length(&ip, iend-RUN_MASK, (int)endOnInput, (int)endOnInput, &error); + if (error == initial_error) { goto _output_error; } + if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)(op))) { goto _output_error; } /* overflow detection */ + if ((safeDecode) && unlikely((uptrval)(ip)+length<(uptrval)(ip))) { goto _output_error; } /* overflow detection */ } - else + + /* copy literals */ + cpy = op+length; +#if LZ4_FAST_DEC_LOOP + safe_literal_copy: +#endif + LZ4_STATIC_ASSERT(MFLIMIT >= WILDCOPYLENGTH); + if ( ((endOnInput) && ((cpy>oend-MFLIMIT) || (ip+length>iend-(2+1+LASTLITERALS))) ) + || ((!endOnInput) && (cpy>oend-WILDCOPYLENGTH)) ) { - /* match encompass external dictionary and current segment */ - size_t copySize = (size_t)(lowPrefix-match); - memcpy(op, dictEnd - copySize, copySize); - op += copySize; - copySize = length - copySize; - if (copySize > (size_t)(op-lowPrefix)) /* overlap within current segment */ - { - BYTE* const endOfMatch = op + copySize; - const BYTE* copyFrom = lowPrefix; - while (op < endOfMatch) *op++ = *copyFrom++; + /* We've either hit the input parsing restriction or the output parsing restriction. + * In the normal scenario, decoding a full block, it must be the last sequence, + * otherwise it's an error (invalid input or dimensions). + * In partialDecoding scenario, it's necessary to ensure there is no buffer overflow. + */ + if (partialDecoding) { + /* Since we are partial decoding we may be in this block because of the output parsing + * restriction, which is not valid since the output buffer is allowed to be undersized. + */ + assert(endOnInput); + DEBUGLOG(7, "partialDecoding: copying literals, close to input or output end") + DEBUGLOG(7, "partialDecoding: literal length = %u", (unsigned)length); + DEBUGLOG(7, "partialDecoding: remaining space in dstBuffer : %i", (int)(oend - op)); + DEBUGLOG(7, "partialDecoding: remaining space in srcBuffer : %i", (int)(iend - ip)); + /* Finishing in the middle of a literals segment, + * due to lack of input. + */ + if (ip+length > iend) { + length = (size_t)(iend-ip); + cpy = op + length; + } + /* Finishing in the middle of a literals segment, + * due to lack of output space. + */ + if (cpy > oend) { + cpy = oend; + assert(op<=oend); + length = (size_t)(oend-op); + } + } else { + /* We must be on the last sequence because of the parsing limitations so check + * that we exactly regenerate the original size (must be exact when !endOnInput). + */ + if ((!endOnInput) && (cpy != oend)) { goto _output_error; } + /* We must be on the last sequence (or invalid) because of the parsing limitations + * so check that we exactly consume the input and don't overrun the output buffer. + */ + if ((endOnInput) && ((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); + goto _output_error; + } + } + memmove(op, ip, length); /* supports overlapping memory regions; only matters for in-place decompression scenarios */ + ip += length; + op += length; + /* Necessarily EOF when !partialDecoding. + * When partialDecoding, it is EOF if we've either + * filled the output buffer or + * can't proceed with reading an offset for following match. + */ + if (!partialDecoding || (cpy == oend) || (ip >= (iend-2))) { + break; + } + } else { + LZ4_wildCopy8(op, ip, cpy); /* may overwrite up to WILDCOPYLENGTH beyond cpy */ + ip += length; op = cpy; + } + + /* get offset */ + offset = LZ4_readLE16(ip); ip+=2; + match = op - offset; + + /* get matchlength */ + length = token & ML_MASK; + + _copy_match: + if (length == ML_MASK) { + variable_length_error error = ok; + length += read_variable_length(&ip, iend - LASTLITERALS + 1, (int)endOnInput, 0, &error); + if (error != ok) goto _output_error; + if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error; /* overflow detection */ + } + length += MINMATCH; + +#if LZ4_FAST_DEC_LOOP + safe_match_copy: +#endif + if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) goto _output_error; /* Error : offset outside buffers */ + /* match starting within external dictionary */ + if ((dict==usingExtDict) && (match < lowPrefix)) { + if (unlikely(op+length > oend-LASTLITERALS)) { + if (partialDecoding) length = MIN(length, (size_t)(oend-op)); + else goto _output_error; /* doesn't respect parsing restriction */ } - else - { - memcpy(op, lowPrefix, copySize); + + if (length <= (size_t)(lowPrefix-match)) { + /* match fits entirely within external dictionary : just copy */ + memmove(op, dictEnd - (lowPrefix-match), length); + op += length; + } else { + /* match stretches into both external dictionary and current block */ + size_t const copySize = (size_t)(lowPrefix - match); + size_t const restSize = length - copySize; + LZ4_memcpy(op, dictEnd - copySize, copySize); op += copySize; + if (restSize > (size_t)(op - lowPrefix)) { /* overlap copy */ + BYTE* const endOfMatch = op + restSize; + const BYTE* copyFrom = lowPrefix; + while (op < endOfMatch) *op++ = *copyFrom++; + } else { + LZ4_memcpy(op, lowPrefix, restSize); + op += restSize; + } } + continue; + } + assert(match >= lowPrefix); + + /* copy match within block */ + cpy = op + length; + + /* partialDecoding : may end anywhere within the block */ + assert(op<=oend); + if (partialDecoding && (cpy > oend-MATCH_SAFEGUARD_DISTANCE)) { + size_t const mlen = MIN(length, (size_t)(oend-op)); + const BYTE* const matchEnd = match + mlen; + BYTE* const copyEnd = op + mlen; + if (matchEnd > op) { /* overlap copy */ + while (op < copyEnd) { *op++ = *match++; } + } else { + LZ4_memcpy(op, match, mlen); } + op = copyEnd; + if (op == oend) { break; } + continue; } - continue; - } - /* copy repeated sequence */ - cpy = op + length; - if (unlikely((op-match)<8)) - { - const size_t dec64 = dec64table[op-match]; - op[0] = match[0]; - op[1] = match[1]; - op[2] = match[2]; - op[3] = match[3]; - match += dec32table[op-match]; - LZ4_copy4(op+4, match); - op += 8; match -= dec64; - } else { LZ4_copy8(op, match); op+=8; match+=8; } - - if (unlikely(cpy>oend-12)) - { - if (cpy > oend-LASTLITERALS) goto _output_error; /* Error : last LASTLITERALS bytes must be literals */ - if (op < oend-8) - { - LZ4_wildCopy(op, match, oend-8); - match += (oend-8) - op; - op = oend-8; + if (unlikely(offset<8)) { + LZ4_write32(op, 0); /* silence msan warning when offset==0 */ + op[0] = match[0]; + op[1] = match[1]; + op[2] = match[2]; + op[3] = match[3]; + match += inc32table[offset]; + LZ4_memcpy(op+4, match, 4); + match -= dec64table[offset]; + } else { + LZ4_memcpy(op, match, 8); + match += 8; + } + op += 8; + + if (unlikely(cpy > oend-MATCH_SAFEGUARD_DISTANCE)) { + BYTE* const oCopyLimit = oend - (WILDCOPYLENGTH-1); + if (cpy > oend-LASTLITERALS) { goto _output_error; } /* Error : last LASTLITERALS bytes must be literals (uncompressed) */ + if (op < oCopyLimit) { + LZ4_wildCopy8(op, match, oCopyLimit); + match += oCopyLimit - op; + op = oCopyLimit; + } + while (op < cpy) { *op++ = *match++; } + } else { + LZ4_memcpy(op, match, 8); + if (length > 16) { LZ4_wildCopy8(op+8, match+8, cpy); } } - while (op= sizeof(LZ4_streamDecode_t_internal)); /* A compilation error here means LZ4_STREAMDECODESIZE is not large enough */ return lz4s; } int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream) { + if (LZ4_stream == NULL) { return 0; } /* support free on NULL */ FREEMEM(LZ4_stream); return 0; } -/* - * LZ4_setStreamDecode - * Use this function to instruct where to find the dictionary - * This function is not necessary if previous data is still available where it was decoded. - * Loading a size of 0 is allowed (same effect as no dictionary). - * Return : 1 if OK, 0 if error +/*! LZ4_setStreamDecode() : + * Use this function to instruct where to find the dictionary. + * This function is not necessary if previous data is still available where it was decoded. + * Loading a size of 0 is allowed (same effect as no dictionary). + * @return : 1 if OK, 0 if error */ int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize) { - LZ4_streamDecode_t_internal* lz4sd = (LZ4_streamDecode_t_internal*) LZ4_streamDecode; + LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse; lz4sd->prefixSize = (size_t) dictSize; lz4sd->prefixEnd = (const BYTE*) dictionary + dictSize; lz4sd->externalDict = NULL; @@ -1345,6 +2292,25 @@ int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dicti return 1; } +/*! LZ4_decoderRingBufferSize() : + * when setting a ring buffer for streaming decompression (optional scenario), + * provides the minimum size of this ring buffer + * to be compatible with any source respecting maxBlockSize condition. + * Note : in a ring buffer scenario, + * blocks are presumed decompressed next to each other. + * When not enough space remains for next block (remainingSize < maxBlockSize), + * decoding resumes from beginning of ring buffer. + * @return : minimum ring buffer size, + * or 0 if there is an error (invalid maxBlockSize). + */ +int LZ4_decoderRingBufferSize(int maxBlockSize) +{ + if (maxBlockSize < 0) return 0; + if (maxBlockSize > LZ4_MAX_INPUT_SIZE) return 0; + if (maxBlockSize < 16) maxBlockSize = 16; + return LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize); +} + /* *_continue() : These decoding functions allow decompression of multiple blocks in "streaming" mode. @@ -1352,58 +2318,75 @@ int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dicti If it's not possible, save the relevant part of decoded data into a safe buffer, and indicate where it stands using LZ4_setStreamDecode() */ +LZ4_FORCE_O2 int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxOutputSize) { - LZ4_streamDecode_t_internal* lz4sd = (LZ4_streamDecode_t_internal*) LZ4_streamDecode; + LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse; int result; - if (lz4sd->prefixEnd == (BYTE*)dest) - { - result = LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, - endOnInputSize, full, 0, - usingExtDict, lz4sd->prefixEnd - lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize); + if (lz4sd->prefixSize == 0) { + /* The first call, no dictionary yet. */ + assert(lz4sd->extDictSize == 0); + result = LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize); + if (result <= 0) return result; + lz4sd->prefixSize = (size_t)result; + lz4sd->prefixEnd = (BYTE*)dest + result; + } else if (lz4sd->prefixEnd == (BYTE*)dest) { + /* They're rolling the current segment. */ + if (lz4sd->prefixSize >= 64 KB - 1) + result = LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize); + else if (lz4sd->extDictSize == 0) + result = LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize, + lz4sd->prefixSize); + else + result = LZ4_decompress_safe_doubleDict(source, dest, compressedSize, maxOutputSize, + lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize); if (result <= 0) return result; - lz4sd->prefixSize += result; + lz4sd->prefixSize += (size_t)result; lz4sd->prefixEnd += result; - } - else - { + } else { + /* The buffer wraps around, or they're switching to another buffer. */ lz4sd->extDictSize = lz4sd->prefixSize; lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize; - result = LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, - endOnInputSize, full, 0, - usingExtDict, (BYTE*)dest, lz4sd->externalDict, lz4sd->extDictSize); + result = LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize, + lz4sd->externalDict, lz4sd->extDictSize); if (result <= 0) return result; - lz4sd->prefixSize = result; + lz4sd->prefixSize = (size_t)result; lz4sd->prefixEnd = (BYTE*)dest + result; } return result; } +LZ4_FORCE_O2 int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize) { - LZ4_streamDecode_t_internal* lz4sd = (LZ4_streamDecode_t_internal*) LZ4_streamDecode; + LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse; int result; + assert(originalSize >= 0); - if (lz4sd->prefixEnd == (BYTE*)dest) - { - result = LZ4_decompress_generic(source, dest, 0, originalSize, - endOnOutputSize, full, 0, - usingExtDict, lz4sd->prefixEnd - lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize); + if (lz4sd->prefixSize == 0) { + assert(lz4sd->extDictSize == 0); + result = LZ4_decompress_fast(source, dest, originalSize); + if (result <= 0) return result; + lz4sd->prefixSize = (size_t)originalSize; + lz4sd->prefixEnd = (BYTE*)dest + originalSize; + } else if (lz4sd->prefixEnd == (BYTE*)dest) { + if (lz4sd->prefixSize >= 64 KB - 1 || lz4sd->extDictSize == 0) + result = LZ4_decompress_fast(source, dest, originalSize); + else + result = LZ4_decompress_fast_doubleDict(source, dest, originalSize, + lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize); if (result <= 0) return result; - lz4sd->prefixSize += originalSize; + lz4sd->prefixSize += (size_t)originalSize; lz4sd->prefixEnd += originalSize; - } - else - { + } else { lz4sd->extDictSize = lz4sd->prefixSize; - lz4sd->externalDict = (BYTE*)dest - lz4sd->extDictSize; - result = LZ4_decompress_generic(source, dest, 0, originalSize, - endOnOutputSize, full, 0, - usingExtDict, (BYTE*)dest, lz4sd->externalDict, lz4sd->extDictSize); + lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize; + result = LZ4_decompress_fast_extDict(source, dest, originalSize, + lz4sd->externalDict, lz4sd->extDictSize); if (result <= 0) return result; - lz4sd->prefixSize = originalSize; + lz4sd->prefixSize = (size_t)originalSize; lz4sd->prefixEnd = (BYTE*)dest + originalSize; } @@ -1418,99 +2401,95 @@ Advanced decoding functions : the dictionary must be explicitly provided within parameters */ -FORCE_INLINE int LZ4_decompress_usingDict_generic(const char* source, char* dest, int compressedSize, int maxOutputSize, int safe, const char* dictStart, int dictSize) +int LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize) { if (dictSize==0) - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, noDict, (BYTE*)dest, NULL, 0); - if (dictStart+dictSize == dest) - { - if (dictSize >= (int)(64 KB - 1)) - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, withPrefix64k, (BYTE*)dest-64 KB, NULL, 0); - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, noDict, (BYTE*)dest-dictSize, NULL, 0); + return LZ4_decompress_safe(source, dest, compressedSize, maxOutputSize); + if (dictStart+dictSize == dest) { + if (dictSize >= 64 KB - 1) { + return LZ4_decompress_safe_withPrefix64k(source, dest, compressedSize, maxOutputSize); + } + assert(dictSize >= 0); + return LZ4_decompress_safe_withSmallPrefix(source, dest, compressedSize, maxOutputSize, (size_t)dictSize); } - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, safe, full, 0, usingExtDict, (BYTE*)dest, (const BYTE*)dictStart, dictSize); -} - -int LZ4_decompress_safe_usingDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize) -{ - return LZ4_decompress_usingDict_generic(source, dest, compressedSize, maxOutputSize, 1, dictStart, dictSize); + assert(dictSize >= 0); + return LZ4_decompress_safe_forceExtDict(source, dest, compressedSize, maxOutputSize, dictStart, (size_t)dictSize); } int LZ4_decompress_fast_usingDict(const char* source, char* dest, int originalSize, const char* dictStart, int dictSize) { - return LZ4_decompress_usingDict_generic(source, dest, 0, originalSize, 0, dictStart, dictSize); -} - -/* debug function */ -int LZ4_decompress_safe_forceExtDict(const char* source, char* dest, int compressedSize, int maxOutputSize, const char* dictStart, int dictSize) -{ - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, usingExtDict, (BYTE*)dest, (const BYTE*)dictStart, dictSize); + if (dictSize==0 || dictStart+dictSize == dest) + return LZ4_decompress_fast(source, dest, originalSize); + assert(dictSize >= 0); + return LZ4_decompress_fast_extDict(source, dest, originalSize, dictStart, (size_t)dictSize); } -/*************************************************** +/*=************************************************* * Obsolete Functions ***************************************************/ /* obsolete compression functions */ -int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize) { return LZ4_compress_default(source, dest, inputSize, maxOutputSize); } -int LZ4_compress(const char* source, char* dest, int inputSize) { return LZ4_compress_default(source, dest, inputSize, LZ4_compressBound(inputSize)); } -int LZ4_compress_limitedOutput_withState (void* state, const char* src, char* dst, int srcSize, int dstSize) { return LZ4_compress_fast_extState(state, src, dst, srcSize, dstSize, 1); } -int LZ4_compress_withState (void* state, const char* src, char* dst, int srcSize) { return LZ4_compress_fast_extState(state, src, dst, srcSize, LZ4_compressBound(srcSize), 1); } -int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* src, char* dst, int srcSize, int maxDstSize) { return LZ4_compress_fast_continue(LZ4_stream, src, dst, srcSize, maxDstSize, 1); } -int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize) { return LZ4_compress_fast_continue(LZ4_stream, source, dest, inputSize, LZ4_compressBound(inputSize), 1); } +int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize) +{ + return LZ4_compress_default(source, dest, inputSize, maxOutputSize); +} +int LZ4_compress(const char* src, char* dest, int srcSize) +{ + return LZ4_compress_default(src, dest, srcSize, LZ4_compressBound(srcSize)); +} +int LZ4_compress_limitedOutput_withState (void* state, const char* src, char* dst, int srcSize, int dstSize) +{ + return LZ4_compress_fast_extState(state, src, dst, srcSize, dstSize, 1); +} +int LZ4_compress_withState (void* state, const char* src, char* dst, int srcSize) +{ + return LZ4_compress_fast_extState(state, src, dst, srcSize, LZ4_compressBound(srcSize), 1); +} +int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* src, char* dst, int srcSize, int dstCapacity) +{ + return LZ4_compress_fast_continue(LZ4_stream, src, dst, srcSize, dstCapacity, 1); +} +int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize) +{ + return LZ4_compress_fast_continue(LZ4_stream, source, dest, inputSize, LZ4_compressBound(inputSize), 1); +} /* -These function names are deprecated and should no longer be used. +These decompression functions are deprecated and should no longer be used. They are only provided here for compatibility with older user programs. - LZ4_uncompress is totally equivalent to LZ4_decompress_fast - LZ4_uncompress_unknownOutputSize is totally equivalent to LZ4_decompress_safe */ -int LZ4_uncompress (const char* source, char* dest, int outputSize) { return LZ4_decompress_fast(source, dest, outputSize); } -int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize) { return LZ4_decompress_safe(source, dest, isize, maxOutputSize); } - +int LZ4_uncompress (const char* source, char* dest, int outputSize) +{ + return LZ4_decompress_fast(source, dest, outputSize); +} +int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize) +{ + return LZ4_decompress_safe(source, dest, isize, maxOutputSize); +} /* Obsolete Streaming functions */ -int LZ4_sizeofStreamState() { return LZ4_STREAMSIZE; } - -static void LZ4_init(LZ4_stream_t_internal* lz4ds, BYTE* base) -{ - MEM_INIT(lz4ds, 0, LZ4_STREAMSIZE); - lz4ds->bufferStart = base; -} +int LZ4_sizeofStreamState(void) { return LZ4_STREAMSIZE; } int LZ4_resetStreamState(void* state, char* inputBuffer) { - if ((((size_t)state) & 3) != 0) return 1; /* Error : pointer is not aligned on 4-bytes boundary */ - LZ4_init((LZ4_stream_t_internal*)state, (BYTE*)inputBuffer); + (void)inputBuffer; + LZ4_resetStream((LZ4_stream_t*)state); return 0; } void* LZ4_create (char* inputBuffer) { - void* lz4ds = ALLOCATOR(8, LZ4_STREAMSIZE_U64); - LZ4_init ((LZ4_stream_t_internal*)lz4ds, (BYTE*)inputBuffer); - return lz4ds; -} - -char* LZ4_slideInputBuffer (void* LZ4_Data) -{ - LZ4_stream_t_internal* ctx = (LZ4_stream_t_internal*)LZ4_Data; - int dictSize = LZ4_saveDict((LZ4_stream_t*)LZ4_Data, (char*)ctx->bufferStart, 64 KB); - return (char*)(ctx->bufferStart + dictSize); -} - -/* Obsolete streaming decompression functions */ - -int LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int compressedSize, int maxOutputSize) -{ - return LZ4_decompress_generic(source, dest, compressedSize, maxOutputSize, endOnInputSize, full, 0, withPrefix64k, (BYTE*)dest - 64 KB, NULL, 64 KB); + (void)inputBuffer; + return LZ4_createStream(); } -int LZ4_decompress_fast_withPrefix64k(const char* source, char* dest, int originalSize) +char* LZ4_slideInputBuffer (void* state) { - return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, full, 0, withPrefix64k, (BYTE*)dest - 64 KB, NULL, 64 KB); + /* avoid const char * -> char * conversion warning */ + return (char *)(uptrval)((LZ4_stream_t*)state)->internal_donotuse.dictionary; } #endif /* LZ4_COMMONDEFS_ONLY */ - diff --git a/src/bitshuffle/lz4/lz4.h b/src/bitshuffle/lz4/lz4.h index 3e740022..7ab1e483 100644 --- a/src/bitshuffle/lz4/lz4.h +++ b/src/bitshuffle/lz4/lz4.h @@ -1,7 +1,7 @@ /* - LZ4 - Fast LZ compression algorithm - Header File - Copyright (C) 2011-2015, Yann Collet. + * LZ4 - Fast LZ compression algorithm + * Header File + * Copyright (C) 2011-present, Yann Collet. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) @@ -29,330 +29,744 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. You can contact the author at : - - LZ4 source repository : https://github.com/Cyan4973/lz4 - - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c + - LZ4 homepage : http://www.lz4.org + - LZ4 source repository : https://github.com/lz4/lz4 */ -#pragma once - #if defined (__cplusplus) extern "C" { #endif +#ifndef LZ4_H_2983827168210 +#define LZ4_H_2983827168210 + +/* --- Dependency --- */ +#include /* size_t */ + + +/** + Introduction + + LZ4 is lossless compression algorithm, providing compression speed >500 MB/s per core, + scalable with multi-cores CPU. It features an extremely fast decoder, with speed in + multiple GB/s per core, typically reaching RAM speed limits on multi-core systems. + + The LZ4 compression library provides in-memory compression and decompression functions. + It gives full buffer control to user. + Compression can be done in: + - a single step (described as Simple Functions) + - a single step, reusing a context (described in Advanced Functions) + - unbounded multiple steps (described as Streaming compression) + + lz4.h generates and decodes LZ4-compressed blocks (doc/lz4_Block_format.md). + Decompressing such a compressed block requires additional metadata. + Exact metadata depends on exact decompression function. + For the typical case of LZ4_decompress_safe(), + metadata includes block's compressed size, and maximum bound of decompressed size. + Each application is free to encode and pass such metadata in whichever way it wants. + + lz4.h only handle blocks, it can not generate Frames. + + Blocks are different from Frames (doc/lz4_Frame_format.md). + Frames bundle both blocks and metadata in a specified manner. + Embedding metadata is required for compressed data to be self-contained and portable. + Frame format is delivered through a companion API, declared in lz4frame.h. + The `lz4` CLI can only manage frames. +*/ + +/*^*************************************************************** +* Export parameters +*****************************************************************/ /* - * lz4.h provides block compression functions, and gives full buffer control to programmer. - * If you need to generate inter-operable compressed data (respecting LZ4 frame specification), - * and can let the library handle its own memory, please use lz4frame.h instead. +* LZ4_DLL_EXPORT : +* Enable exporting of functions when building a Windows DLL +* LZ4LIB_VISIBILITY : +* Control library symbols visibility. */ +#ifndef LZ4LIB_VISIBILITY +# if defined(__GNUC__) && (__GNUC__ >= 4) +# define LZ4LIB_VISIBILITY __attribute__ ((visibility ("default"))) +# else +# define LZ4LIB_VISIBILITY +# endif +#endif +#if defined(LZ4_DLL_EXPORT) && (LZ4_DLL_EXPORT==1) +# define LZ4LIB_API __declspec(dllexport) LZ4LIB_VISIBILITY +#elif defined(LZ4_DLL_IMPORT) && (LZ4_DLL_IMPORT==1) +# define LZ4LIB_API __declspec(dllimport) LZ4LIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/ +#else +# define LZ4LIB_API LZ4LIB_VISIBILITY +#endif -/************************************** -* Version -**************************************/ +/*------ Version ------*/ #define LZ4_VERSION_MAJOR 1 /* for breaking interface changes */ -#define LZ4_VERSION_MINOR 7 /* for new (non-breaking) interface capabilities */ -#define LZ4_VERSION_RELEASE 1 /* for tweaks, bug-fixes, or development */ +#define LZ4_VERSION_MINOR 9 /* for new (non-breaking) interface capabilities */ +#define LZ4_VERSION_RELEASE 3 /* for tweaks, bug-fixes, or development */ + #define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE) -int LZ4_versionNumber (void); -/************************************** +#define LZ4_LIB_VERSION LZ4_VERSION_MAJOR.LZ4_VERSION_MINOR.LZ4_VERSION_RELEASE +#define LZ4_QUOTE(str) #str +#define LZ4_EXPAND_AND_QUOTE(str) LZ4_QUOTE(str) +#define LZ4_VERSION_STRING LZ4_EXPAND_AND_QUOTE(LZ4_LIB_VERSION) + +LZ4LIB_API int LZ4_versionNumber (void); /**< library version number; useful to check dll version */ +LZ4LIB_API const char* LZ4_versionString (void); /**< library version string; useful to check dll version */ + + +/*-************************************ * Tuning parameter **************************************/ -/* +/*! * LZ4_MEMORY_USAGE : * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) - * Increasing memory usage improves compression ratio - * Reduced memory usage can improve speed, due to cache effect + * Increasing memory usage improves compression ratio. + * Reduced memory usage may improve speed, thanks to better cache locality. * Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */ -#define LZ4_MEMORY_USAGE 14 +#ifndef LZ4_MEMORY_USAGE +# define LZ4_MEMORY_USAGE 14 +#endif -/************************************** +/*-************************************ * Simple Functions **************************************/ - -int LZ4_compress_default(const char* source, char* dest, int sourceSize, int maxDestSize); -int LZ4_decompress_safe (const char* source, char* dest, int compressedSize, int maxDecompressedSize); - -/* -LZ4_compress_default() : - Compresses 'sourceSize' bytes from buffer 'source' - into already allocated 'dest' buffer of size 'maxDestSize'. - Compression is guaranteed to succeed if 'maxDestSize' >= LZ4_compressBound(sourceSize). - It also runs faster, so it's a recommended setting. - If the function cannot compress 'source' into a more limited 'dest' budget, - compression stops *immediately*, and the function result is zero. - As a consequence, 'dest' content is not valid. - This function never writes outside 'dest' buffer, nor read outside 'source' buffer. - sourceSize : Max supported value is LZ4_MAX_INPUT_VALUE - maxDestSize : full or partial size of buffer 'dest' (which must be already allocated) - return : the number of bytes written into buffer 'dest' (necessarily <= maxOutputSize) - or 0 if compression fails - -LZ4_decompress_safe() : - compressedSize : is the precise full size of the compressed block. - maxDecompressedSize : is the size of destination buffer, which must be already allocated. - return : the number of bytes decompressed into destination buffer (necessarily <= maxDecompressedSize) - If destination buffer is not large enough, decoding will stop and output an error code (<0). - If the source stream is detected malformed, the function will stop decoding and return a negative result. - This function is protected against buffer overflow exploits, including malicious data packets. - It never writes outside output buffer, nor reads outside input buffer. -*/ +/*! LZ4_compress_default() : + * Compresses 'srcSize' bytes from buffer 'src' + * into already allocated 'dst' buffer of size 'dstCapacity'. + * Compression is guaranteed to succeed if 'dstCapacity' >= LZ4_compressBound(srcSize). + * It also runs faster, so it's a recommended setting. + * If the function cannot compress 'src' into a more limited 'dst' budget, + * compression stops *immediately*, and the function result is zero. + * In which case, 'dst' content is undefined (invalid). + * srcSize : max supported value is LZ4_MAX_INPUT_SIZE. + * dstCapacity : size of buffer 'dst' (which must be already allocated) + * @return : the number of bytes written into buffer 'dst' (necessarily <= dstCapacity) + * or 0 if compression fails + * Note : This function is protected against buffer overflow scenarios (never writes outside 'dst' buffer, nor read outside 'source' buffer). + */ +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. + * @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. + * Note 1 : This function is protected against malicious data packets : + * it will never writes outside 'dst' buffer, nor read outside 'source' buffer, + * even if the compressed block is maliciously modified to order the decoder to do these actions. + * In such case, the decoder stops immediately, and considers the compressed block malformed. + * Note 2 : compressedSize and dstCapacity must be provided to the function, the compressed block does not contain them. + * The implementation is free to send / store / derive this information in whichever way is most beneficial. + * If there is a need for a different format which bundles together both compressed data and its metadata, consider looking at lz4frame.h instead. + */ +LZ4LIB_API int LZ4_decompress_safe (const char* src, char* dst, int compressedSize, int dstCapacity); -/************************************** +/*-************************************ * Advanced Functions **************************************/ #define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */ #define LZ4_COMPRESSBOUND(isize) ((unsigned)(isize) > (unsigned)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16) -/* -LZ4_compressBound() : +/*! LZ4_compressBound() : Provides the maximum size that LZ4 compression may output in a "worst case" scenario (input data not compressible) This function is primarily useful for memory allocation purposes (destination buffer size). Macro LZ4_COMPRESSBOUND() is also provided for compilation-time evaluation (stack memory allocation for example). - Note that LZ4_compress_default() compress faster when dest buffer size is >= LZ4_compressBound(srcSize) + Note that LZ4_compress_default() compresses faster when dstCapacity is >= LZ4_compressBound(srcSize) inputSize : max supported value is LZ4_MAX_INPUT_SIZE return : maximum output size in a "worst case" scenario - or 0, if input size is too large ( > LZ4_MAX_INPUT_SIZE) + or 0, if input size is incorrect (too large or negative) */ -int LZ4_compressBound(int inputSize); +LZ4LIB_API int LZ4_compressBound(int inputSize); -/* -LZ4_compress_fast() : - Same as LZ4_compress_default(), but allows to select an "acceleration" factor. +/*! LZ4_compress_fast() : + Same as LZ4_compress_default(), but allows selection of "acceleration" factor. The larger the acceleration value, the faster the algorithm, but also the lesser the compression. It's a trade-off. It can be fine tuned, with each successive value providing roughly +~3% to speed. An acceleration value of "1" is the same as regular LZ4_compress_default() - Values <= 0 will be replaced by ACCELERATION_DEFAULT (see lz4.c), which is 1. + Values <= 0 will be replaced by LZ4_ACCELERATION_DEFAULT (currently == 1, see lz4.c). + Values > LZ4_ACCELERATION_MAX will be replaced by LZ4_ACCELERATION_MAX (currently == 65537, see lz4.c). */ -int LZ4_compress_fast (const char* source, char* dest, int sourceSize, int maxDestSize, int acceleration); +LZ4LIB_API int LZ4_compress_fast (const char* src, char* dst, int srcSize, int dstCapacity, int acceleration); -/* -LZ4_compress_fast_extState() : - Same compression function, just using an externally allocated memory space to store compression state. - Use LZ4_sizeofState() to know how much memory must be allocated, - and allocate it on 8-bytes boundaries (using malloc() typically). - Then, provide it as 'void* state' to compression function. -*/ -int LZ4_sizeofState(void); -int LZ4_compress_fast_extState (void* state, const char* source, char* dest, int inputSize, int maxDestSize, int acceleration); - +/*! LZ4_compress_fast_extState() : + * Same as LZ4_compress_fast(), using an externally allocated memory space for its state. + * Use LZ4_sizeofState() to know how much memory must be allocated, + * and allocate it on 8-bytes boundaries (using `malloc()` typically). + * Then, provide this buffer as `void* state` to compression function. + */ +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, by compressing as much data as possible from 'source' buffer - into already allocated buffer 'dest' of size 'targetDestSize'. - This function either compresses the entire 'source' content into 'dest' if it's large enough, - or fill 'dest' buffer completely with as much data as possible from 'source'. - *sourceSizePtr : will be modified to indicate how many bytes where read from 'source' to fill 'dest'. - New value is necessarily <= old value. - return : Nb bytes written into 'dest' (necessarily <= targetDestSize) - or 0 if compression fails -*/ -int LZ4_compress_destSize (const char* source, char* dest, int* sourceSizePtr, int targetDestSize); +/*! LZ4_compress_destSize() : + * Reverse the logic : compresses as much data as possible from 'src' buffer + * into already allocated buffer 'dst', of size >= 'targetDestSize'. + * 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'. + * New value is necessarily <= input value. + * @return : Nb bytes written into 'dst' (necessarily <= targetDestSize) + * or 0 if compression fails. + * + * Note : from v1.8.2 to v1.9.1, this function had a bug (fixed un 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. + * If an application uses `LZ4_compress_destSize()`, + * it's highly recommended to update liblz4 to v1.9.2 or better. + * If this can't be done or ensured, + * the receiving decompression function should provide + * 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); -/* -LZ4_decompress_fast() : - originalSize : is the original and therefore uncompressed size - return : the number of bytes read from the source buffer (in other words, the compressed size) - If the source stream is detected malformed, the function will stop decoding and return a negative result. - Destination buffer must be already allocated. Its size must be a minimum of 'originalSize' bytes. - note : This function fully respect memory boundaries for properly formed compressed data. - It is a bit faster than LZ4_decompress_safe(). - However, it does not provide any protection against intentionally modified data stream (malicious input). - Use this function in trusted environment only (data to decode comes from a trusted source). -*/ -int LZ4_decompress_fast (const char* source, char* dest, int originalSize); -/* -LZ4_decompress_safe_partial() : - This function decompress a compressed block of size 'compressedSize' at position 'source' - into destination buffer 'dest' of size 'maxDecompressedSize'. - The function tries to stop decompressing operation as soon as 'targetOutputSize' has been reached, - reducing decompression time. - return : the number of bytes decoded in the destination buffer (necessarily <= maxDecompressedSize) - Note : this number can be < 'targetOutputSize' should the compressed block to decode be smaller. - Always control how many bytes were decoded. - If the source stream is detected malformed, the function will stop decoding and return a negative result. - This function never writes outside of output buffer, and never reads outside of input buffer. It is therefore protected against malicious data packets -*/ -int LZ4_decompress_safe_partial (const char* source, char* dest, int compressedSize, int targetOutputSize, int maxDecompressedSize); +/*! LZ4_decompress_safe_partial() : + * Decompress an LZ4 compressed block, of size 'srcSize' at position 'src', + * into destination buffer 'dst' of size 'dstCapacity'. + * Up to 'targetOutputSize' bytes will be decoded. + * The function stops decoding on reaching this objective. + * This can be useful to boost performance + * whenever only the beginning of a block is required. + * + * @return : the number of bytes decoded in `dst` (necessarily <= targetOutputSize) + * If source stream is detected malformed, function returns a negative result. + * + * Note 1 : @return can be < targetOutputSize, if compressed block contains less data. + * + * Note 2 : targetOutputSize must be <= dstCapacity + * + * Note 3 : this function effectively stops decoding on reaching targetOutputSize, + * so dstCapacity is kind of redundant. + * This is because in older versions of this function, + * decoding operation would still write complete sequences. + * Therefore, there was no guarantee that it would stop writing at exactly targetOutputSize, + * it could write more bytes, though only up to dstCapacity. + * Some "margin" used to be required for this operation to work properly. + * Thankfully, this is no longer necessary. + * The function nonetheless keeps the same signature, in an effort to preserve API compatibility. + * + * Note 4 : If srcSize is the exact size of the block, + * then targetOutputSize can be any value, + * including larger than the block's decompressed size. + * The function will, at most, generate block's decompressed size. + * + * Note 5 : If srcSize is _larger_ than block's compressed size, + * then targetOutputSize **MUST** be <= block's decompressed size. + * Otherwise, *silent corruption will occur*. + */ +LZ4LIB_API int LZ4_decompress_safe_partial (const char* src, char* dst, int srcSize, int targetOutputSize, int dstCapacity); -/*********************************************** +/*-********************************************* * Streaming Compression Functions ***********************************************/ -#define LZ4_STREAMSIZE_U64 ((1 << (LZ4_MEMORY_USAGE-3)) + 4) -#define LZ4_STREAMSIZE (LZ4_STREAMSIZE_U64 * sizeof(long long)) -/* - * LZ4_stream_t - * information structure to track an LZ4 stream. - * important : init this structure content before first use ! - * note : only allocated directly the structure if you are statically linking LZ4 - * If you are using liblz4 as a DLL, please use below construction methods instead. - */ -typedef struct { long long table[LZ4_STREAMSIZE_U64]; } LZ4_stream_t; +typedef union LZ4_stream_u LZ4_stream_t; /* incomplete type (defined later) */ -/* - * LZ4_resetStream - * Use this function to init an allocated LZ4_stream_t structure - */ -void LZ4_resetStream (LZ4_stream_t* streamPtr); +LZ4LIB_API LZ4_stream_t* LZ4_createStream(void); +LZ4LIB_API int LZ4_freeStream (LZ4_stream_t* streamPtr); -/* - * LZ4_createStream will allocate and initialize an LZ4_stream_t structure - * LZ4_freeStream releases its memory. - * In the context of a DLL (liblz4), please use these methods rather than the static struct. - * They are more future proof, in case of a change of LZ4_stream_t size. +/*! LZ4_resetStream_fast() : v1.9.0+ + * Use this to prepare an LZ4_stream_t for a new chain of dependent blocks + * (e.g., LZ4_compress_fast_continue()). + * + * An LZ4_stream_t must be initialized once before usage. + * This is automatically done when created by LZ4_createStream(). + * However, should the LZ4_stream_t be simply declared on stack (for example), + * it's necessary to initialize it first, using LZ4_initStream(). + * + * After init, start any new stream with LZ4_resetStream_fast(). + * A same LZ4_stream_t can be re-used multiple times consecutively + * and compress multiple streams, + * provided that it starts each new stream with LZ4_resetStream_fast(). + * + * LZ4_resetStream_fast() is much faster than LZ4_initStream(), + * but is not compatible with memory regions containing garbage data. + * + * Note: it's only useful to call LZ4_resetStream_fast() + * in the context of streaming compression. + * The *extState* functions perform their own resets. + * Invoking LZ4_resetStream_fast() before is redundant, and even counterproductive. */ -LZ4_stream_t* LZ4_createStream(void); -int LZ4_freeStream (LZ4_stream_t* streamPtr); - -/* - * LZ4_loadDict - * Use this function to load a static dictionary into LZ4_stream. - * Any previous data will be forgotten, only 'dictionary' will remain in memory. - * Loading a size of 0 is allowed. - * Return : dictionary size, in bytes (necessarily <= 64 KB) +LZ4LIB_API void LZ4_resetStream_fast (LZ4_stream_t* streamPtr); + +/*! LZ4_loadDict() : + * Use this function to reference a static dictionary into LZ4_stream_t. + * The dictionary must remain available during compression. + * 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. + * Loading a size of 0 is allowed, and is the same as reset. + * @return : loaded dictionary size, in bytes (necessarily <= 64 KB) */ -int LZ4_loadDict (LZ4_stream_t* streamPtr, const char* dictionary, int dictSize); +LZ4LIB_API int LZ4_loadDict (LZ4_stream_t* streamPtr, const char* dictionary, int dictSize); -/* - * LZ4_compress_fast_continue - * Compress buffer content 'src', using data from previously compressed blocks as dictionary to improve compression ratio. - * Important : Previous data blocks are assumed to still be present and unmodified ! +/*! LZ4_compress_fast_continue() : + * Compress 'src' content using data from previously compressed blocks, for better compression ratio. * 'dst' buffer must be already allocated. - * If maxDstSize >= LZ4_compressBound(srcSize), compression is guaranteed to succeed, and runs faster. - * If not, and if compressed data cannot fit into 'dst' buffer size, compression stops, and function returns a zero. + * If dstCapacity >= LZ4_compressBound(srcSize), compression is guaranteed to succeed, and runs faster. + * + * @return : size of compressed block + * or 0 if there is an error (typically, cannot fit into 'dst'). + * + * Note 1 : Each invocation to LZ4_compress_fast_continue() generates a new block. + * Each block has precise boundaries. + * Each block must be decompressed separately, calling LZ4_decompress_*() with relevant metadata. + * It's not possible to append blocks together and expect a single invocation of LZ4_decompress_*() to decompress them together. + * + * Note 2 : The previous 64KB of source data is __assumed__ to remain present, unmodified, at same address in memory ! + * + * Note 3 : When input is structured as a double-buffer, each buffer can have any size, including < 64 KB. + * Make sure that buffers are separated, by at least one byte. + * This construction ensures that each block only depends on previous block. + * + * Note 4 : If input buffer is a ring-buffer, it can have any size, including < 64 KB. + * + * Note 5 : After an error, the stream status is undefined (invalid), it can only be reset or freed. */ -int LZ4_compress_fast_continue (LZ4_stream_t* streamPtr, const char* src, char* dst, int srcSize, int maxDstSize, int acceleration); - -/* - * LZ4_saveDict - * If previously compressed data block is not guaranteed to remain available at its memory location - * save it into a safer place (char* safeBuffer) - * Note : you don't need to call LZ4_loadDict() afterwards, - * dictionary is immediately usable, you can therefore call LZ4_compress_fast_continue() - * Return : saved dictionary size in bytes (necessarily <= dictSize), or 0 if error +LZ4LIB_API int LZ4_compress_fast_continue (LZ4_stream_t* streamPtr, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration); + +/*! LZ4_saveDict() : + * If last 64KB data cannot be guaranteed to remain available at its current memory location, + * save it into a safer place (char* safeBuffer). + * This is schematically equivalent to a memcpy() followed by LZ4_loadDict(), + * but is much faster, because LZ4_saveDict() doesn't need to rebuild tables. + * @return : saved dictionary size in bytes (necessarily <= maxDictSize), or 0 if error. */ -int LZ4_saveDict (LZ4_stream_t* streamPtr, char* safeBuffer, int dictSize); +LZ4LIB_API int LZ4_saveDict (LZ4_stream_t* streamPtr, char* safeBuffer, int maxDictSize); -/************************************************ +/*-********************************************** * Streaming Decompression Functions +* Bufferless synchronous API ************************************************/ +typedef union LZ4_streamDecode_u LZ4_streamDecode_t; /* tracking context */ -#define LZ4_STREAMDECODESIZE_U64 4 -#define LZ4_STREAMDECODESIZE (LZ4_STREAMDECODESIZE_U64 * sizeof(unsigned long long)) -typedef struct { unsigned long long table[LZ4_STREAMDECODESIZE_U64]; } LZ4_streamDecode_t; -/* - * LZ4_streamDecode_t - * information structure to track an LZ4 stream. - * init this structure content using LZ4_setStreamDecode or memset() before first use ! - * - * In the context of a DLL (liblz4) please prefer usage of construction methods below. - * They are more future proof, in case of a change of LZ4_streamDecode_t size in the future. - * LZ4_createStreamDecode will allocate and initialize an LZ4_streamDecode_t structure - * LZ4_freeStreamDecode releases its memory. +/*! LZ4_createStreamDecode() and LZ4_freeStreamDecode() : + * creation / destruction of streaming decompression tracking context. + * A tracking context can be re-used multiple times. */ -LZ4_streamDecode_t* LZ4_createStreamDecode(void); -int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream); +LZ4LIB_API LZ4_streamDecode_t* LZ4_createStreamDecode(void); +LZ4LIB_API int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream); + +/*! LZ4_setStreamDecode() : + * An LZ4_streamDecode_t context can be allocated once and re-used multiple times. + * Use this function to start decompression of a new stream of blocks. + * A dictionary can optionally be set. Use NULL or size 0 for a reset order. + * Dictionary is presumed stable : it must remain accessible and unmodified during next decompression. + * @return : 1 if OK, 0 if error + */ +LZ4LIB_API int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize); + +/*! LZ4_decoderRingBufferSize() : v1.8.2+ + * Note : in a ring buffer scenario (optional), + * blocks are presumed decompressed next to each other + * up to the moment there is not enough remaining space for next block (remainingSize < maxBlockSize), + * at which stage it resumes from beginning of ring buffer. + * When setting such a ring buffer for streaming decompression, + * provides the minimum size of this ring buffer + * to be compatible with any source respecting maxBlockSize condition. + * @return : minimum ring buffer size, + * or 0 if there is an error (invalid maxBlockSize). + */ +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. + * 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 : + * - Decompression buffer size is _at least_ LZ4_decoderRingBufferSize(maxBlockSize). + * maxBlockSize is the maximum size of any single block. It can have any value > 16 bytes. + * In which case, encoding and decoding buffers do not need to be synchronized. + * Actually, data can be produced by any source compliant with LZ4 format specification, and respecting maxBlockSize. + * - Synchronized mode : + * Decompression buffer size is _exactly_ the same as compression buffer size, + * and follows exactly same update rule (block boundaries at same positions), + * and decoding function is provided with exact decompressed size of each block (exception for last block of the stream), + * _then_ decoding & encoding ring buffer can have any size, including small ones ( < 64 KB). + * - Decompression buffer is larger than encoding buffer, by a minimum of maxBlockSize more bytes. + * In which case, encoding and decoding buffers do not need to be synchronized, + * and encoding ring buffer can have any size, including small ones ( < 64 KB). + * + * Whenever these conditions are not possible, + * save the last 64KB of decoded data into a safe buffer where it can't be modified during decompression, + * then indicate where this data is saved using LZ4_setStreamDecode(), before decompressing next block. +*/ +LZ4LIB_API int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst, int srcSize, int dstCapacity); -/* - * LZ4_setStreamDecode - * Use this function to instruct where to find the dictionary. - * Setting a size of 0 is allowed (same effect as reset). - * Return : 1 if OK, 0 if error + +/*! 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. + * 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_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize); +LZ4LIB_API int LZ4_decompress_safe_usingDict (const char* src, char* dst, int srcSize, int dstCapcity, const char* dictStart, int dictSize); -/* -*_continue() : - These decoding functions allow decompression of multiple blocks in "streaming" mode. - Previously decoded blocks *must* remain available at the memory position where they were decoded (up to 64 KB) - In the case of a ring buffers, decoding buffer must be either : - - Exactly same size as encoding buffer, with same update rule (block boundaries at same positions) - In which case, the decoding & encoding ring buffer can have any size, including very small ones ( < 64 KB). - - Larger than encoding buffer, by a minimum of maxBlockSize more bytes. - maxBlockSize is implementation dependent. It's the maximum size you intend to compress into a single block. - In which case, encoding and decoding buffers do not need to be synchronized, - and encoding ring buffer can have any size, including small ones ( < 64 KB). - - _At least_ 64 KB + 8 bytes + maxBlockSize. - In which case, encoding and decoding buffers do not need to be synchronized, - and encoding ring buffer can have any size, including larger than decoding buffer. - Whenever these conditions are not possible, save the last 64KB of decoded data into a safe buffer, - and indicate where it is saved using LZ4_setStreamDecode() -*/ -int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int compressedSize, int maxDecompressedSize); -int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize); +#endif /* LZ4_H_2983827168210 */ -/* -Advanced decoding functions : -*_usingDict() : - These decoding functions work the same as - a combination of LZ4_setStreamDecode() followed by LZ4_decompress_x_continue() - They are stand-alone. They don't need nor update an LZ4_streamDecode_t structure. -*/ -int LZ4_decompress_safe_usingDict (const char* source, char* dest, int compressedSize, int maxDecompressedSize, const char* dictStart, int dictSize); -int LZ4_decompress_fast_usingDict (const char* source, char* dest, int originalSize, const char* dictStart, int dictSize); +/*^************************************* + * !!!!!! STATIC LINKING ONLY !!!!!! + ***************************************/ + +/*-**************************************************************************** + * 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 + * future. They are therefore only safe to depend on when the caller is + * statically linked against the library. + * + * To protect against unsafe usage, not only are the declarations guarded, + * the definitions are hidden by default + * when building LZ4 as a shared/dynamic library. + * + * In order to access these declarations, + * define LZ4_STATIC_LINKING_ONLY in your application + * before including LZ4's headers. + * + * In order to make their implementations accessible dynamically, you must + * define LZ4_PUBLISH_STATIC_FUNCTIONS when building the LZ4 library. + ******************************************************************************/ + +#ifdef LZ4_STATIC_LINKING_ONLY + +#ifndef LZ4_STATIC_3504398509 +#define LZ4_STATIC_3504398509 +#ifdef LZ4_PUBLISH_STATIC_FUNCTIONS +#define LZ4LIB_STATIC_API LZ4LIB_API +#else +#define LZ4LIB_STATIC_API +#endif + + +/*! LZ4_compress_fast_extState_fastReset() : + * A variant of LZ4_compress_fast_extState(). + * + * Using this variant avoids an expensive initialization step. + * It is only safe to call if the state buffer is known to be correctly initialized already + * (see above comment on LZ4_resetStream_fast() for a definition of "correctly initialized"). + * From a high level, the difference is that + * this function initializes the provided state with a call to something like LZ4_resetStream_fast() + * while LZ4_compress_fast_extState() starts with a call to LZ4_resetStream(). + */ +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. + */ +LZ4LIB_STATIC_API void LZ4_attach_dictionary(LZ4_stream_t* workingStream, const LZ4_stream_t* dictionaryStream); -/************************************** +/*! In-place compression and decompression + * + * It's possible to have input and output sharing the same buffer, + * for highly contrained memory environments. + * In both cases, it requires input to lay at the end of the buffer, + * and decompression to start at beginning of the buffer. + * Buffer size must feature some margin, hence be larger than final size. + * + * |<------------------------buffer--------------------------------->| + * |<-----------compressed data--------->| + * |<-----------decompressed size------------------>| + * |<----margin---->| + * + * This technique is more useful for decompression, + * since decompressed size is typically larger, + * and margin is short. + * + * In-place decompression will work inside any buffer + * which size is >= LZ4_DECOMPRESS_INPLACE_BUFFER_SIZE(decompressedSize). + * This presumes that decompressedSize > compressedSize. + * Otherwise, it means compression actually expanded data, + * and it would be more efficient to store such data with a flag indicating it's not compressed. + * This can happen when data is not compressible (already compressed, or encrypted). + * + * For in-place compression, margin is larger, as it must be able to cope with both + * history preservation, requiring input data to remain unmodified up to LZ4_DISTANCE_MAX, + * and data expansion, which can happen when input is not compressible. + * As a consequence, buffer size requirements are much higher, + * and memory savings offered by in-place compression are more limited. + * + * There are ways to limit this cost for compression : + * - Reduce history size, by modifying LZ4_DISTANCE_MAX. + * Note that it is a compile-time constant, so all compressions will apply this limit. + * Lower values will reduce compression ratio, except when input_size < LZ4_DISTANCE_MAX, + * so it's a reasonable trick when inputs are known to be small. + * - Require the compressor to deliver a "maximum compressed size". + * This is the `dstCapacity` parameter in `LZ4_compress*()`. + * When this size is < LZ4_COMPRESSBOUND(inputSize), then compression can fail, + * in which case, the return code will be 0 (zero). + * The caller must be ready for these cases to happen, + * and typically design a backup scheme to send data uncompressed. + * The combination of both techniques can significantly reduce + * the amount of margin required for in-place compression. + * + * In-place compression can work in any buffer + * which size is >= (maxCompressedSize) + * with maxCompressedSize == LZ4_COMPRESSBOUND(srcSize) for guaranteed compression success. + * LZ4_COMPRESS_INPLACE_BUFFER_SIZE() depends on both maxCompressedSize and LZ4_DISTANCE_MAX, + * so it's possible to reduce memory requirements by playing with them. + */ + +#define LZ4_DECOMPRESS_INPLACE_MARGIN(compressedSize) (((compressedSize) >> 8) + 32) +#define LZ4_DECOMPRESS_INPLACE_BUFFER_SIZE(decompressedSize) ((decompressedSize) + LZ4_DECOMPRESS_INPLACE_MARGIN(decompressedSize)) /**< note: presumes that compressedSize < decompressedSize. note2: margin is overestimated a bit, since it could use compressedSize instead */ + +#ifndef LZ4_DISTANCE_MAX /* history window size; can be user-defined at compile time */ +# define LZ4_DISTANCE_MAX 65535 /* set to maximum value by default */ +#endif + +#define LZ4_COMPRESS_INPLACE_MARGIN (LZ4_DISTANCE_MAX + 32) /* LZ4_DISTANCE_MAX can be safely replaced by srcSize when it's smaller */ +#define LZ4_COMPRESS_INPLACE_BUFFER_SIZE(maxCompressedSize) ((maxCompressedSize) + LZ4_COMPRESS_INPLACE_MARGIN) /**< maxCompressedSize is generally LZ4_COMPRESSBOUND(inputSize), but can be set to any lower value, with the risk that compression can fail (return code 0(zero)) */ + +#endif /* LZ4_STATIC_3504398509 */ +#endif /* LZ4_STATIC_LINKING_ONLY */ + + + +#ifndef LZ4_H_98237428734687 +#define LZ4_H_98237428734687 + +/*-************************************************************ + * Private Definitions + ************************************************************** + * Do not use these definitions directly. + * They are only exposed to allow static allocation of `LZ4_stream_t` and `LZ4_streamDecode_t`. + * Accessing members will expose user code to API and/or ABI break in future versions of the library. + **************************************************************/ +#define LZ4_HASHLOG (LZ4_MEMORY_USAGE-2) +#define LZ4_HASHTABLESIZE (1 << LZ4_MEMORY_USAGE) +#define LZ4_HASH_SIZE_U32 (1 << LZ4_HASHLOG) /* required as macro for static allocation */ + +#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) +# include + typedef int8_t LZ4_i8; + typedef uint8_t LZ4_byte; + typedef uint16_t LZ4_u16; + typedef uint32_t LZ4_u32; +#else + typedef signed char LZ4_i8; + typedef unsigned char LZ4_byte; + typedef unsigned short LZ4_u16; + typedef unsigned int LZ4_u32; +#endif + +typedef struct LZ4_stream_t_internal LZ4_stream_t_internal; +struct LZ4_stream_t_internal { + LZ4_u32 hashTable[LZ4_HASH_SIZE_U32]; + LZ4_u32 currentOffset; + LZ4_u32 tableType; + const LZ4_byte* dictionary; + const LZ4_stream_t_internal* dictCtx; + LZ4_u32 dictSize; +}; + +typedef struct { + const LZ4_byte* externalDict; + size_t extDictSize; + const LZ4_byte* prefixEnd; + size_t prefixSize; +} LZ4_streamDecode_t_internal; + + +/*! LZ4_stream_t : + * Do not use below internal definitions directly ! + * Declare or allocate an LZ4_stream_t instead. + * LZ4_stream_t can also be created using LZ4_createStream(), which is recommended. + * The structure definition can be convenient for static allocation + * (on stack, or as part of larger structure). + * Init this structure with LZ4_initStream() before first use. + * note : only use this definition in association with static linking ! + * this definition is not API/ABI safe, and may change in future versions. + */ +#define LZ4_STREAMSIZE 16416 /* static size, for inter-version compatibility */ +#define LZ4_STREAMSIZE_VOIDP (LZ4_STREAMSIZE / sizeof(void*)) +union LZ4_stream_u { + void* table[LZ4_STREAMSIZE_VOIDP]; + LZ4_stream_t_internal internal_donotuse; +}; /* previously typedef'd to LZ4_stream_t */ + + +/*! LZ4_initStream() : v1.9.0+ + * 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). + * + * Use LZ4_initStream() to properly initialize a newly declared LZ4_stream_t. + * It can also initialize any arbitrary buffer of sufficient size, + * and will @return a pointer of proper type upon initialization. + * + * Note : initialization fails if size and alignment conditions are not respected. + * In which case, the function will @return NULL. + * 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); + + +/*! LZ4_streamDecode_t : + * information structure to track an LZ4 stream during decompression. + * init this structure using LZ4_setStreamDecode() before first use. + * note : only use in association with static linking ! + * this definition is not API/ABI safe, + * and may change in a future version ! + */ +#define LZ4_STREAMDECODESIZE_U64 (4 + ((sizeof(void*)==16) ? 2 : 0) /*AS-400*/ ) +#define LZ4_STREAMDECODESIZE (LZ4_STREAMDECODESIZE_U64 * sizeof(unsigned long long)) +union LZ4_streamDecode_u { + unsigned long long table[LZ4_STREAMDECODESIZE_U64]; + LZ4_streamDecode_t_internal internal_donotuse; +} ; /* previously typedef'd to LZ4_streamDecode_t */ + + + +/*-************************************ * Obsolete Functions **************************************/ -/* Deprecate Warnings */ -/* Should these warnings messages be a problem, - it is generally possible to disable them, - with -Wno-deprecated-declarations for gcc - or _CRT_SECURE_NO_WARNINGS in Visual for example. - You can also define LZ4_DEPRECATE_WARNING_DEFBLOCK. */ -#ifndef LZ4_DEPRECATE_WARNING_DEFBLOCK -# define LZ4_DEPRECATE_WARNING_DEFBLOCK -# define LZ4_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) -# if (LZ4_GCC_VERSION >= 405) || defined(__clang__) -# define LZ4_DEPRECATED(message) __attribute__((deprecated(message))) -# elif (LZ4_GCC_VERSION >= 301) -# define LZ4_DEPRECATED(message) __attribute__((deprecated)) + +/*! Deprecation warnings + * + * Deprecated functions make the compiler generate a warning when invoked. + * This is meant to invite users to update their source code. + * Should deprecation warnings be a problem, it is generally possible to disable them, + * typically with -Wno-deprecated-declarations for gcc + * or _CRT_SECURE_NO_WARNINGS in Visual. + * + * Another method is to define LZ4_DISABLE_DEPRECATE_WARNINGS + * before including the header file. + */ +#ifdef LZ4_DISABLE_DEPRECATE_WARNINGS +# define LZ4_DEPRECATED(message) /* disable deprecation warnings */ +#else +# if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */ +# define LZ4_DEPRECATED(message) [[deprecated(message)]] # elif defined(_MSC_VER) # define LZ4_DEPRECATED(message) __declspec(deprecated(message)) +# elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ * 10 + __GNUC_MINOR__ >= 45)) +# define LZ4_DEPRECATED(message) __attribute__((deprecated(message))) +# elif defined(__GNUC__) && (__GNUC__ * 10 + __GNUC_MINOR__ >= 31) +# define LZ4_DEPRECATED(message) __attribute__((deprecated)) # else -# pragma message("WARNING: You need to implement LZ4_DEPRECATED for this compiler") -# define LZ4_DEPRECATED(message) +# pragma message("WARNING: LZ4_DEPRECATED needs custom implementation for this compiler") +# define LZ4_DEPRECATED(message) /* disabled */ # endif -#endif /* LZ4_DEPRECATE_WARNING_DEFBLOCK */ - -/* Obsolete compression functions */ -/* These functions are planned to start generate warnings by r131 approximately */ -int LZ4_compress (const char* source, char* dest, int sourceSize); -int LZ4_compress_limitedOutput (const char* source, char* dest, int sourceSize, int maxOutputSize); -int LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize); -int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize); -int LZ4_compress_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize); -int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize, int maxOutputSize); - -/* Obsolete decompression functions */ -/* These function names are completely deprecated and must no longer be used. - They are only provided here for compatibility with older programs. - - LZ4_uncompress is the same as LZ4_decompress_fast - - LZ4_uncompress_unknownOutputSize is the same as LZ4_decompress_safe - These function prototypes are now disabled; uncomment them only if you really need them. - It is highly recommended to stop using these prototypes and migrate to maintained ones */ -/* int LZ4_uncompress (const char* source, char* dest, int outputSize); */ -/* int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize); */ - -/* Obsolete streaming functions; use new streaming interface whenever possible */ -LZ4_DEPRECATED("use LZ4_createStream() instead") void* LZ4_create (char* inputBuffer); -LZ4_DEPRECATED("use LZ4_createStream() instead") int LZ4_sizeofStreamState(void); -LZ4_DEPRECATED("use LZ4_resetStream() instead") int LZ4_resetStreamState(void* state, char* inputBuffer); -LZ4_DEPRECATED("use LZ4_saveDict() instead") char* LZ4_slideInputBuffer (void* state); - -/* Obsolete streaming decoding functions */ -LZ4_DEPRECATED("use LZ4_decompress_safe_usingDict() instead") int LZ4_decompress_safe_withPrefix64k (const char* src, char* dst, int compressedSize, int maxDstSize); -LZ4_DEPRECATED("use LZ4_decompress_fast_usingDict() instead") int LZ4_decompress_fast_withPrefix64k (const char* src, char* dst, int originalSize); +#endif /* LZ4_DISABLE_DEPRECATE_WARNINGS */ + +/*! Obsolete compression functions (since v1.7.3) */ +LZ4_DEPRECATED("use LZ4_compress_default() instead") LZ4LIB_API int LZ4_compress (const char* src, char* dest, int srcSize); +LZ4_DEPRECATED("use LZ4_compress_default() instead") LZ4LIB_API int LZ4_compress_limitedOutput (const char* src, char* dest, int srcSize, int maxOutputSize); +LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") LZ4LIB_API int LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize); +LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") LZ4LIB_API int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize); +LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") LZ4LIB_API int LZ4_compress_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize); +LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") LZ4LIB_API int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest, int inputSize, int maxOutputSize); + +/*! Obsolete decompression functions (since v1.8.0) */ +LZ4_DEPRECATED("use LZ4_decompress_fast() instead") LZ4LIB_API int LZ4_uncompress (const char* source, char* dest, int outputSize); +LZ4_DEPRECATED("use LZ4_decompress_safe() instead") LZ4LIB_API int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize); + +/* Obsolete streaming functions (since v1.7.0) + * degraded functionality; do not use! + * + * In order to perform streaming compression, these functions depended on data + * that is no longer tracked in the state. They have been preserved as well as + * possible: using them will still produce a correct output. However, they don't + * actually retain any history between compression calls. The compression ratio + * achieved will therefore be no better than compressing each chunk + * independently. + */ +LZ4_DEPRECATED("Use LZ4_createStream() instead") LZ4LIB_API void* LZ4_create (char* inputBuffer); +LZ4_DEPRECATED("Use LZ4_createStream() instead") LZ4LIB_API int LZ4_sizeofStreamState(void); +LZ4_DEPRECATED("Use LZ4_resetStream() instead") LZ4LIB_API int LZ4_resetStreamState(void* state, char* inputBuffer); +LZ4_DEPRECATED("Use LZ4_saveDict() instead") LZ4LIB_API char* LZ4_slideInputBuffer (void* state); + +/*! Obsolete streaming decoding functions (since v1.7.0) */ +LZ4_DEPRECATED("use LZ4_decompress_safe_usingDict() instead") LZ4LIB_API int LZ4_decompress_safe_withPrefix64k (const char* src, char* dst, int compressedSize, int maxDstSize); +LZ4_DEPRECATED("use LZ4_decompress_fast_usingDict() instead") LZ4LIB_API int LZ4_decompress_fast_withPrefix64k (const char* src, char* dst, int originalSize); + +/*! Obsolete LZ4_decompress_fast variants (since v1.9.0) : + * These functions used to be faster than LZ4_decompress_safe(), + * but this is no longer the case. They are now slower. + * This is because LZ4_decompress_fast() doesn't know the input size, + * and therefore must progress more cautiously into the input buffer to not read beyond the end of block. + * On top of that `LZ4_decompress_fast()` is not protected vs malformed or malicious inputs, making it a security liability. + * As a consequence, LZ4_decompress_fast() is strongly discouraged, and deprecated. + * + * The last remaining LZ4_decompress_fast() specificity is that + * it can decompress a block without knowing its compressed size. + * Such functionality can be achieved in a more secure manner + * by employing LZ4_decompress_safe_partial(). + * + * Parameters: + * originalSize : is the uncompressed size to regenerate. + * `dst` must be already allocated, its size must be >= 'originalSize' bytes. + * @return : number of bytes read from source buffer (== compressed size). + * The function expects to finish at block's end exactly. + * If the source stream is detected malformed, the function stops decoding and returns a negative result. + * note : LZ4_decompress_fast*() requires originalSize. Thanks to this information, it never writes past the output buffer. + * However, since it doesn't know its 'src' size, it may read an unknown amount of input, past input buffer bounds. + * Also, since match offsets are not validated, match reads from 'src' may underflow too. + * These issues never happen if input (compressed) data is correct. + * 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") +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") +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") +LZ4LIB_API int LZ4_decompress_fast_usingDict (const char* src, char* dst, int originalSize, const char* dictStart, int dictSize); + +/*! LZ4_resetStream() : + * An LZ4_stream_t structure must be initialized at least once. + * This is done with LZ4_initStream(), or LZ4_resetStream(). + * Consider switching to LZ4_initStream(), + * invoking LZ4_resetStream() will trigger deprecation warnings in the future. + */ +LZ4LIB_API void LZ4_resetStream (LZ4_stream_t* streamPtr); + + +#endif /* LZ4_H_98237428734687 */ #if defined (__cplusplus) diff --git a/src/bitshuffle/pyproject.toml b/src/bitshuffle/pyproject.toml new file mode 100644 index 00000000..8b2a6860 --- /dev/null +++ b/src/bitshuffle/pyproject.toml @@ -0,0 +1,10 @@ +# Include dependencies when building wheels on cibuildwheel +[build-system] +requires = [ + "setuptools>=0.7", + "Cython>=0.19", + "oldest-supported-numpy", + "h5py>=2.4.0", +] + +build-backend = "setuptools.build_meta" diff --git a/src/bitshuffle/requirements.txt b/src/bitshuffle/requirements.txt index 2f0d0fbb..34c51ec6 100644 --- a/src/bitshuffle/requirements.txt +++ b/src/bitshuffle/requirements.txt @@ -2,4 +2,4 @@ setuptools>=0.7 Cython>=0.19 numpy>=1.6.1 -h5py>=2.4.0 --no-binary=h5py +h5py>=2.4.0 diff --git a/src/bitshuffle/setup.py b/src/bitshuffle/setup.py index 830991cd..ff99b8ef 100644 --- a/src/bitshuffle/setup.py +++ b/src/bitshuffle/setup.py @@ -1,4 +1,5 @@ from __future__ import absolute_import, division, print_function + # I didn't import unicode_literals. They break setuptools or Cython in python # 2.7, but python 3 seems to be happy with them. @@ -9,156 +10,216 @@ from setuptools.command.build_ext import build_ext as build_ext_ from setuptools.command.develop import develop as develop_ from setuptools.command.install import install as install_ +from Cython.Compiler.Main import default_options import shutil import subprocess import sys +import platform VERSION_MAJOR = 0 -VERSION_MINOR = 3 -VERSION_POINT = 5 +VERSION_MINOR = 4 +VERSION_POINT = 2 +# Define ZSTD macro for cython compilation +default_options["compile_time_env"] = {"ZSTD_SUPPORT": False} # Only unset in the 'release' branch and in tags. -VERSION_DEV = 0 +VERSION_DEV = None VERSION = "%d.%d.%d" % (VERSION_MAJOR, VERSION_MINOR, VERSION_POINT) if VERSION_DEV: VERSION = VERSION + ".dev%d" % VERSION_DEV -COMPILE_FLAGS = ['-O3', '-ffast-math', '-march=native', '-std=c99'] +COMPILE_FLAGS = ["-O3", "-ffast-math", "-std=c99"] # Cython breaks strict aliasing rules. -COMPILE_FLAGS += ['-fno-strict-aliasing'] -COMPILE_FLAGS += ['-fPIC'] -COMPILE_FLAGS_MSVC = ['/Ox', '/fp:fast'] +COMPILE_FLAGS += ["-fno-strict-aliasing"] +COMPILE_FLAGS += ["-fPIC"] +COMPILE_FLAGS_MSVC = ["/Ox", "/fp:fast"] MACROS = [ - ('BSHUF_VERSION_MAJOR', VERSION_MAJOR), - ('BSHUF_VERSION_MINOR', VERSION_MINOR), - ('BSHUF_VERSION_POINT', VERSION_POINT), + ("BSHUF_VERSION_MAJOR", VERSION_MAJOR), + ("BSHUF_VERSION_MINOR", VERSION_MINOR), + ("BSHUF_VERSION_POINT", VERSION_POINT), ] -H5PLUGINS_DEFAULT = '/usr/local/hdf5/lib/plugin' +H5PLUGINS_DEFAULT = "/usr/local/hdf5/lib/plugin" +MARCH_DEFAULT = "native" # OSX's clang compliler does not support OpenMP. -if sys.platform == 'darwin': +if sys.platform == "darwin": OMP_DEFAULT = False else: OMP_DEFAULT = True FALLBACK_CONFIG = { - 'include_dirs': [], - 'library_dirs': [], - 'libraries': [], - 'extra_compile_args': [], - 'extra_link_args': [], + "include_dirs": [], + "library_dirs": [], + "libraries": [], + "extra_compile_args": [], + "extra_link_args": [], } -if 'HDF5_DIR' in os.environ: - FALLBACK_CONFIG['include_dirs'] += [os.environ['HDF5_DIR'] + '/include'] # macports - FALLBACK_CONFIG['library_dirs'] += [os.environ['HDF5_DIR'] + '/lib'] # macports -elif sys.platform == 'darwin': +if "HDF5_DIR" in os.environ: + FALLBACK_CONFIG["include_dirs"] += [os.environ["HDF5_DIR"] + "/include"] # macports + FALLBACK_CONFIG["library_dirs"] += [os.environ["HDF5_DIR"] + "/lib"] # macports +elif sys.platform == "darwin": # putting here both macports and homebrew paths will generate # "ld: warning: dir not found" at the linking phase - FALLBACK_CONFIG['include_dirs'] += ['/opt/local/include'] # macports - FALLBACK_CONFIG['library_dirs'] += ['/opt/local/lib'] # macports - FALLBACK_CONFIG['include_dirs'] += ['/usr/local/include'] # homebrew - FALLBACK_CONFIG['library_dirs'] += ['/usr/local/lib'] # homebrew -elif sys.platform.startswith('freebsd'): - FALLBACK_CONFIG['include_dirs'] += ['/usr/local/include'] # homebrew - FALLBACK_CONFIG['library_dirs'] += ['/usr/local/lib'] # homebrew - -FALLBACK_CONFIG['include_dirs'] = [d for d in FALLBACK_CONFIG['include_dirs'] - if path.isdir(d)] -FALLBACK_CONFIG['library_dirs'] = [d for d in FALLBACK_CONFIG['library_dirs'] - if path.isdir(d)] + FALLBACK_CONFIG["include_dirs"] += ["/opt/local/include"] # macports + FALLBACK_CONFIG["library_dirs"] += ["/opt/local/lib"] # macports + FALLBACK_CONFIG["include_dirs"] += ["/usr/local/include"] # homebrew + FALLBACK_CONFIG["library_dirs"] += ["/usr/local/lib"] # homebrew +elif sys.platform.startswith("freebsd"): + FALLBACK_CONFIG["include_dirs"] += ["/usr/local/include"] # homebrew + FALLBACK_CONFIG["library_dirs"] += ["/usr/local/lib"] # homebrew + +FALLBACK_CONFIG["include_dirs"] = [ + d for d in FALLBACK_CONFIG["include_dirs"] if path.isdir(d) +] +FALLBACK_CONFIG["library_dirs"] = [ + d for d in FALLBACK_CONFIG["library_dirs"] if path.isdir(d) +] -FALLBACK_CONFIG['extra_compile_args'] = ['-DH5_BUILT_AS_DYNAMIC_LIB'] +FALLBACK_CONFIG["extra_compile_args"] = ["-DH5_BUILT_AS_DYNAMIC_LIB"] def pkgconfig(*packages, **kw): - config = kw.setdefault('config', {}) - optional_args = kw.setdefault('optional', '') - flag_map = {'include_dirs': ['--cflags-only-I', 2], - 'library_dirs': ['--libs-only-L', 2], - 'libraries': ['--libs-only-l', 2], - 'extra_compile_args': ['--cflags-only-other', 0], - 'extra_link_args': ['--libs-only-other', 0], - } + config = kw.setdefault("config", {}) + optional_args = kw.setdefault("optional", "") + flag_map = { + "include_dirs": ["--cflags-only-I", 2], + "library_dirs": ["--libs-only-L", 2], + "libraries": ["--libs-only-l", 2], + "extra_compile_args": ["--cflags-only-other", 0], + "extra_link_args": ["--libs-only-other", 0], + } for package in packages: try: subprocess.check_output(["pkg-config", package]) except (subprocess.CalledProcessError, OSError): - print("Can't find %s with pkg-config fallback to " - "static config" % package) + print( + "Can't find %s with pkg-config fallback to " "static config" % package + ) for distutils_key in flag_map: config.setdefault(distutils_key, []).extend( - FALLBACK_CONFIG[distutils_key]) - config['libraries'].append(package) + FALLBACK_CONFIG[distutils_key] + ) + config["libraries"].append(package) else: for distutils_key, (pkg_option, n) in flag_map.items(): - items = subprocess.check_output( - ['pkg-config', optional_args, pkg_option, package] - ).decode('utf8').split() + items = ( + subprocess.check_output( + ["pkg-config", optional_args, pkg_option, package] + ) + .decode("utf8") + .split() + ) opt = config.setdefault(distutils_key, []) opt.extend([i[n:] for i in items]) return config +zstd_headers = ["zstd/lib/zstd.h"] +zstd_lib = ["zstd/lib/"] +zstd_sources = glob.glob("zstd/lib/common/*.c") +zstd_sources += glob.glob("zstd/lib/compress/*.c") +zstd_sources += glob.glob("zstd/lib/decompress/*.c") + ext_bshuf = Extension( "bitshuffle.ext", - sources=["bitshuffle/ext.pyx", "src/bitshuffle.c", - "src/bitshuffle_core.c", "src/iochain.c", - "lz4/lz4.c"], + sources=[ + "bitshuffle/ext.pyx", + "src/bitshuffle.c", + "src/bitshuffle_core.c", + "src/iochain.c", + "lz4/lz4.c", + ], include_dirs=["src/", "lz4/"], - depends=["src/bitshuffle.h", "src/bitshuffle_core.h", - "src/iochain.h", "lz4/lz4.h"], + depends=["src/bitshuffle.h", "src/bitshuffle_core.h", "src/iochain.h", "lz4/lz4.h"], libraries=[], define_macros=MACROS, ) h5filter = Extension( "bitshuffle.h5", - sources=["bitshuffle/h5.pyx", "src/bshuf_h5filter.c", - "src/bitshuffle.c", "src/bitshuffle_core.c", - "src/iochain.c", "lz4/lz4.c"], - depends=["src/bitshuffle.h", "src/bitshuffle_core.h", - "src/iochain.h", "src/bshuf_h5filter.h", - "lz4/lz4.h"], - define_macros=MACROS, - **pkgconfig("hdf5", config=dict( - include_dirs=["src/", "lz4/"])) + sources=[ + "bitshuffle/h5.pyx", + "src/bshuf_h5filter.c", + "src/bitshuffle.c", + "src/bitshuffle_core.c", + "src/iochain.c", + "lz4/lz4.c", + ], + depends=[ + "src/bitshuffle.h", + "src/bitshuffle_core.h", + "src/iochain.h", + "src/bshuf_h5filter.h", + "lz4/lz4.h", + ], + define_macros=MACROS + [("H5_USE_18_API", None)], + **pkgconfig("hdf5", config=dict(include_dirs=["src/", "lz4/"])) ) +if not sys.platform.startswith("win"): + h5filter.sources.append("src/hdf5_dl.c") + h5filter.libraries.remove("hdf5") + filter_plugin = Extension( "bitshuffle.plugin.libh5bshuf", - sources=["src/bshuf_h5plugin.c", "src/bshuf_h5filter.c", - "src/bitshuffle.c", "src/bitshuffle_core.c", - "src/iochain.c", "lz4/lz4.c"], - depends=["src/bitshuffle.h", "src/bitshuffle_core.h", - "src/iochain.h", 'src/bshuf_h5filter.h', - "lz4/lz4.h"], + sources=[ + "src/bshuf_h5plugin.c", + "src/bshuf_h5filter.c", + "src/bitshuffle.c", + "src/bitshuffle_core.c", + "src/iochain.c", + "lz4/lz4.c", + ], + depends=[ + "src/bitshuffle.h", + "src/bitshuffle_core.h", + "src/iochain.h", + "src/bshuf_h5filter.h", + "lz4/lz4.h", + ], define_macros=MACROS, - **pkgconfig("hdf5", config=dict( - include_dirs=["src/", "lz4/"])) + **pkgconfig("hdf5", config=dict(include_dirs=["src/", "lz4/"])) ) lzf_plugin = Extension( "bitshuffle.plugin.libh5LZF", - sources=["src/lzf_h5plugin.c", "lzf/lzf_filter.c", - "lzf/lzf/lzf_c.c", "lzf/lzf/lzf_d.c"], - depends=["lzf/lzf_filter.h", "lzf/lzf/lzf.h", - "lzf/lzf/lzfP.h"], - **pkgconfig("hdf5", config=dict( - include_dirs=["lzf/", "lzf/lzf/"])) + sources=[ + "src/lzf_h5plugin.c", + "lzf/lzf_filter.c", + "lzf/lzf/lzf_c.c", + "lzf/lzf/lzf_d.c", + ], + depends=["lzf/lzf_filter.h", "lzf/lzf/lzf.h", "lzf/lzf/lzfP.h"], + **pkgconfig("hdf5", config=dict(include_dirs=["lzf/", "lzf/lzf/"])) ) EXTENSIONS = [ext_bshuf, h5filter] + +# For enabling ZSTD support when building wheels +if "ENABLE_ZSTD" in os.environ: + default_options["compile_time_env"] = {"ZSTD_SUPPORT": True} + for ext in EXTENSIONS: + if ext.name in [ + "bitshuffle.ext", + "bitshuffle.h5", + "bitshuffle.plugin.libh5bshuf", + ]: + ext.sources += zstd_sources + ext.include_dirs += zstd_lib + ext.depends += zstd_headers + ext.define_macros += [("ZSTD_SUPPORT", 1)] + # Check for plugin hdf5 plugin support (hdf5 >= 1.8.11) HDF5_PLUGIN_SUPPORT = False -CPATHS = os.environ['CPATH'].split(':') if 'CPATH' in os.environ else [] +CPATHS = os.environ["CPATH"].split(":") if "CPATH" in os.environ else [] for p in ["/usr/include"] + pkgconfig("hdf5")["include_dirs"] + CPATHS: if os.path.exists(os.path.join(p, "H5PLextern.h")): HDF5_PLUGIN_SUPPORT = True @@ -170,31 +231,50 @@ def pkgconfig(*packages, **kw): class develop(develop_): def run(self): # Dummy directory for copying build plugins. - if not path.isdir('bitshuffle/plugin'): - os.mkdir('bitshuffle/plugin') + if not path.isdir("bitshuffle/plugin"): + os.mkdir("bitshuffle/plugin") develop_.run(self) # Custom installation to include installing dynamic filters. class install(install_): user_options = install_.user_options + [ - ('h5plugin', None, - 'Install HDF5 filter plugins for use outside of python.'), - ('h5plugin-dir=', None, - 'Where to install filter plugins. Default %s.' % H5PLUGINS_DEFAULT), + ("h5plugin", None, "Install HDF5 filter plugins for use outside of python."), + ( + "h5plugin-dir=", + None, + "Where to install filter plugins. Default %s." % H5PLUGINS_DEFAULT, + ), + ("zstd", None, "Install ZSTD support."), ] def initialize_options(self): install_.initialize_options(self) self.h5plugin = False + self.zstd = False self.h5plugin_dir = H5PLUGINS_DEFAULT def finalize_options(self): install_.finalize_options(self) - if self.h5plugin not in ('0', '1', True, False): - raise ValueError("Invalid h5plugin argument. Mut be '0' or '1'.") + if self.h5plugin not in ("0", "1", True, False): + raise ValueError("Invalid h5plugin argument. Must be '0' or '1'.") self.h5plugin = int(self.h5plugin) self.h5plugin_dir = path.abspath(self.h5plugin_dir) + self.zstd = self.zstd + + # Add ZSTD files and macro to extensions if ZSTD enabled + if self.zstd: + default_options["compile_time_env"] = {"ZSTD_SUPPORT": True} + for ext in EXTENSIONS: + if ext.name in [ + "bitshuffle.ext", + "bitshuffle.h5", + "bitshuffle.plugin.libh5bshuf", + ]: + ext.sources += zstd_sources + ext.include_dirs += zstd_lib + ext.depends += zstd_headers + ext.define_macros += [("ZSTD_SUPPORT", 1)] def run(self): install_.run(self) @@ -214,37 +294,49 @@ def run(self): plugin_libs = glob.glob(path.join(plugin_build, "*")) for plugin_lib in plugin_libs: plugin_name = path.split(plugin_lib)[1] - shutil.copy2(plugin_lib, - path.join(self.h5plugin_dir, plugin_name)) + shutil.copy2(plugin_lib, path.join(self.h5plugin_dir, plugin_name)) print("Installed HDF5 filter plugins to %s" % self.h5plugin_dir) # Command line or site.cfg specification of OpenMP. class build_ext(build_ext_): user_options = build_ext_.user_options + [ - ('omp=', None, "Whether to compile with OpenMP threading. Default" - " on current system is %s." % str(OMP_DEFAULT)) + ( + "omp=", + None, + "Whether to compile with OpenMP threading. Default" + " on current system is %s." % str(OMP_DEFAULT), + ), + ( + "march=", + None, + "Generate instructions for a specific machine type. Default is %s." + % MARCH_DEFAULT, + ), ] - boolean_options = build_ext_.boolean_options + ['omp'] + boolean_options = build_ext_.boolean_options + ["omp"] def initialize_options(self): build_ext_.initialize_options(self) self.omp = OMP_DEFAULT + self.march = MARCH_DEFAULT def finalize_options(self): # For some reason this gets run twice. Careful to print messages and # add arguments only one time. build_ext_.finalize_options(self) - if self.omp not in ('0', '1', True, False): + if self.omp not in ("0", "1", True, False): raise ValueError("Invalid omp argument. Mut be '0' or '1'.") self.omp = int(self.omp) import numpy as np + ext_bshuf.include_dirs.append(np.get_include()) # Required only by old version of setuptools < 18.0 from Cython.Build import cythonize + self.extensions = cythonize(self.extensions) for ext in self.extensions: ext._needs_stub = False @@ -252,7 +344,7 @@ def finalize_options(self): def build_extensions(self): c = self.compiler.compiler_type - if self.omp not in ('0', '1', True, False): + if self.omp not in ("0", "1", True, False): raise ValueError("Invalid omp argument. Mut be '0' or '1'.") self.omp = int(self.omp) @@ -264,14 +356,22 @@ def build_extensions(self): print("#################################\n") # More portable to pass -fopenmp to linker. # self.libraries += ['gomp'] - if self.compiler.compiler_type == 'msvc': - openmpflag = '/openmp' + if self.compiler.compiler_type == "msvc": + openmpflag = "/openmp" compileflags = COMPILE_FLAGS_MSVC else: - openmpflag = '-fopenmp' - compileflags = COMPILE_FLAGS + openmpflag = "-fopenmp" + archi = platform.machine() + if archi in ("i386", "x86_64"): + compileflags = COMPILE_FLAGS + ["-march=%s" % self.march] + else: + compileflags = COMPILE_FLAGS + ["-mcpu=%s" % self.march] + if archi == "ppc64le": + compileflags = COMPILE_FLAGS + ["-DNO_WARN_X86_INTRINSICS"] for e in self.extensions: - e.extra_compile_args = list(set(e.extra_compile_args).union(compileflags)) + e.extra_compile_args = list( + set(e.extra_compile_args).union(compileflags) + ) if openmpflag not in e.extra_compile_args: e.extra_compile_args += [openmpflag] if openmpflag not in e.extra_link_args: @@ -281,35 +381,32 @@ def build_extensions(self): # Don't install numpy/cython/hdf5 if not needed -for cmd in ["sdist", "clean", - "--help", "--help-commands", "--version"]: +for cmd in ["sdist", "clean", "--help", "--help-commands", "--version"]: if cmd in sys.argv: setup_requires = [] break else: setup_requires = ["Cython>=0.19", "numpy>=1.6.1"] -with open('requirements.txt') as f: +with open("requirements.txt") as f: requires = f.read().splitlines() requires = [r.split()[0] for r in requires] -with open('README.rst') as r: +with open("README.rst") as r: long_description = r.read() # TODO hdf5 support should be an "extra". Figure out how to set this up. setup( - name='bitshuffle', + name="bitshuffle", version=VERSION, - - packages=['bitshuffle', 'bitshuffle.tests'], + packages=["bitshuffle", "bitshuffle"], scripts=[], ext_modules=EXTENSIONS, - cmdclass={'build_ext': build_ext, 'install': install, 'develop': develop}, + cmdclass={"build_ext": build_ext, "install": install, "develop": develop}, setup_requires=setup_requires, install_requires=requires, # extras_require={'H5': ["h5py"]}, - package_data={'': ['data/*']}, - + package_data={"": ["data/*"]}, # metadata for upload to PyPI author="Kiyoshi Wesley Masui", author_email="kiyo@physics.ubc.ca", @@ -317,7 +414,6 @@ def build_extensions(self): long_description=long_description, license="MIT", url="https://github.com/kiyo-masui/bitshuffle", - download_url=("https://github.com/kiyo-masui/bitshuffle/tarball/%s" - % VERSION), - keywords=['compression', 'hdf5', 'numpy'], + download_url=("https://github.com/kiyo-masui/bitshuffle/tarball/%s" % VERSION), + keywords=["compression", "hdf5", "numpy"], ) diff --git a/src/bitshuffle/src/bitshuffle.c b/src/bitshuffle/src/bitshuffle.c index 54ff045f..ba5cde3a 100644 --- a/src/bitshuffle/src/bitshuffle.c +++ b/src/bitshuffle/src/bitshuffle.c @@ -14,15 +14,14 @@ #include "bitshuffle_internals.h" #include "lz4.h" +#ifdef ZSTD_SUPPORT +#include "zstd.h" +#endif + #include #include -// Constants. -// Use fast decompression instead of safe decompression for LZ4. -#define BSHUF_LZ4_DECOMPRESS_FAST - - // Macros. #define CHECK_ERR_FREE_LZ(count, buf) if (count < 0) { \ free(buf); return count - 1000; } @@ -30,7 +29,7 @@ /* Bitshuffle and compress a single block. */ int64_t bshuf_compress_lz4_block(ioc_chain *C_ptr, \ - const size_t size, const size_t elem_size) { + const size_t size, const size_t elem_size, const int option) { int64_t nbytes, count; void *tmp_buf_bshuf; @@ -42,7 +41,8 @@ int64_t bshuf_compress_lz4_block(ioc_chain *C_ptr, \ tmp_buf_bshuf = malloc(size * elem_size); if (tmp_buf_bshuf == NULL) return -1; - tmp_buf_lz4 = malloc(LZ4_compressBound(size * elem_size)); + int dst_capacity = LZ4_compressBound(size * elem_size); + tmp_buf_lz4 = malloc(dst_capacity); if (tmp_buf_lz4 == NULL){ free(tmp_buf_bshuf); return -1; @@ -58,7 +58,7 @@ int64_t bshuf_compress_lz4_block(ioc_chain *C_ptr, \ free(tmp_buf_bshuf); return count; } - nbytes = LZ4_compress((const char*) tmp_buf_bshuf, (char*) tmp_buf_lz4, size * elem_size); + nbytes = LZ4_compress_default((const char*) tmp_buf_bshuf, (char*) tmp_buf_lz4, size * elem_size, dst_capacity); free(tmp_buf_bshuf); CHECK_ERR_FREE_LZ(nbytes, tmp_buf_lz4); @@ -76,7 +76,7 @@ int64_t bshuf_compress_lz4_block(ioc_chain *C_ptr, \ /* Decompress and bitunshuffle a single block. */ int64_t bshuf_decompress_lz4_block(ioc_chain *C_ptr, - const size_t size, const size_t elem_size) { + const size_t size, const size_t elem_size, const int option) { int64_t nbytes, count; void *out, *tmp_buf; @@ -96,23 +96,100 @@ int64_t bshuf_decompress_lz4_block(ioc_chain *C_ptr, tmp_buf = malloc(size * elem_size); if (tmp_buf == NULL) return -1; -#ifdef BSHUF_LZ4_DECOMPRESS_FAST - nbytes = LZ4_decompress_fast((const char*) in + 4, (char*) tmp_buf, size * elem_size); + nbytes = LZ4_decompress_safe((const char*) in + 4, (char *) tmp_buf, nbytes_from_header, + size * elem_size); CHECK_ERR_FREE_LZ(nbytes, tmp_buf); - if (nbytes != nbytes_from_header) { + if (nbytes != size * elem_size) { free(tmp_buf); return -91; } -#else - nbytes = LZ4_decompress_safe((const char*) in + 4, (char *) tmp_buf, nbytes_from_header, - size * elem_size); + nbytes = nbytes_from_header; + + count = bshuf_untrans_bit_elem(tmp_buf, out, size, elem_size); + CHECK_ERR_FREE(count, tmp_buf); + nbytes += 4; + + free(tmp_buf); + return nbytes; +} + +#ifdef ZSTD_SUPPORT +/* Bitshuffle and compress a single block. */ +int64_t bshuf_compress_zstd_block(ioc_chain *C_ptr, \ + const size_t size, const size_t elem_size, const int comp_lvl) { + + int64_t nbytes, count; + void *tmp_buf_bshuf; + void *tmp_buf_zstd; + size_t this_iter; + const void *in; + void *out; + + tmp_buf_bshuf = malloc(size * elem_size); + if (tmp_buf_bshuf == NULL) return -1; + + size_t tmp_buf_zstd_size = ZSTD_compressBound(size * elem_size); + tmp_buf_zstd = malloc(tmp_buf_zstd_size); + if (tmp_buf_zstd == NULL){ + free(tmp_buf_bshuf); + return -1; + } + + in = ioc_get_in(C_ptr, &this_iter); + ioc_set_next_in(C_ptr, &this_iter, (void*) ((char*) in + size * elem_size)); + + count = bshuf_trans_bit_elem(in, tmp_buf_bshuf, size, elem_size); + if (count < 0) { + free(tmp_buf_zstd); + free(tmp_buf_bshuf); + return count; + } + nbytes = ZSTD_compress(tmp_buf_zstd, tmp_buf_zstd_size, (const void*)tmp_buf_bshuf, size * elem_size, comp_lvl); + free(tmp_buf_bshuf); + CHECK_ERR_FREE_LZ(nbytes, tmp_buf_zstd); + + out = ioc_get_out(C_ptr, &this_iter); + ioc_set_next_out(C_ptr, &this_iter, (void *) ((char *) out + nbytes + 4)); + + bshuf_write_uint32_BE(out, nbytes); + memcpy((char *) out + 4, tmp_buf_zstd, nbytes); + + free(tmp_buf_zstd); + + return nbytes + 4; +} + + +/* Decompress and bitunshuffle a single block. */ +int64_t bshuf_decompress_zstd_block(ioc_chain *C_ptr, + const size_t size, const size_t elem_size, const int option) { + + int64_t nbytes, count; + void *out, *tmp_buf; + const void *in; + size_t this_iter; + int32_t nbytes_from_header; + + in = ioc_get_in(C_ptr, &this_iter); + nbytes_from_header = bshuf_read_uint32_BE(in); + ioc_set_next_in(C_ptr, &this_iter, + (void*) ((char*) in + nbytes_from_header + 4)); + + out = ioc_get_out(C_ptr, &this_iter); + ioc_set_next_out(C_ptr, &this_iter, + (void *) ((char *) out + size * elem_size)); + + tmp_buf = malloc(size * elem_size); + if (tmp_buf == NULL) return -1; + + nbytes = ZSTD_decompress(tmp_buf, size * elem_size, (void *)((char *) in + 4), nbytes_from_header); CHECK_ERR_FREE_LZ(nbytes, tmp_buf); if (nbytes != size * elem_size) { free(tmp_buf); return -91; } + nbytes = nbytes_from_header; -#endif count = bshuf_untrans_bit_elem(tmp_buf, out, size, elem_size); CHECK_ERR_FREE(count, tmp_buf); nbytes += 4; @@ -120,6 +197,7 @@ int64_t bshuf_decompress_lz4_block(ioc_chain *C_ptr, free(tmp_buf); return nbytes; } +#endif // ZSTD_SUPPORT /* ---- Public functions ---- @@ -153,13 +231,49 @@ size_t bshuf_compress_lz4_bound(const size_t size, int64_t bshuf_compress_lz4(const void* in, void* out, const size_t size, const size_t elem_size, size_t block_size) { return bshuf_blocked_wrap_fun(&bshuf_compress_lz4_block, in, out, size, - elem_size, block_size); + elem_size, block_size, 0/*option*/); } int64_t bshuf_decompress_lz4(const void* in, void* out, const size_t size, const size_t elem_size, size_t block_size) { return bshuf_blocked_wrap_fun(&bshuf_decompress_lz4_block, in, out, size, - elem_size, block_size); + elem_size, block_size, 0/*option*/); } +#ifdef ZSTD_SUPPORT +size_t bshuf_compress_zstd_bound(const size_t size, + const size_t elem_size, size_t block_size) { + + size_t bound, leftover; + + if (block_size == 0) { + block_size = bshuf_default_block_size(elem_size); + } + if (block_size % BSHUF_BLOCKED_MULT) return -81; + + // Note that each block gets a 4 byte header. + // Size of full blocks. + bound = (ZSTD_compressBound(block_size * elem_size) + 4) * (size / block_size); + // Size of partial blocks, if any. + leftover = ((size % block_size) / BSHUF_BLOCKED_MULT) * BSHUF_BLOCKED_MULT; + if (leftover) bound += ZSTD_compressBound(leftover * elem_size) + 4; + // Size of uncompressed data not fitting into any blocks. + bound += (size % BSHUF_BLOCKED_MULT) * elem_size; + return bound; +} + + +int64_t bshuf_compress_zstd(const void* in, void* out, const size_t size, + const size_t elem_size, size_t block_size, const int comp_lvl) { + return bshuf_blocked_wrap_fun(&bshuf_compress_zstd_block, in, out, size, + elem_size, block_size, comp_lvl); +} + + +int64_t bshuf_decompress_zstd(const void* in, void* out, const size_t size, + const size_t elem_size, size_t block_size) { + return bshuf_blocked_wrap_fun(&bshuf_decompress_zstd_block, in, out, size, + elem_size, block_size, 0/*option*/); +} +#endif // ZSTD_SUPPORT diff --git a/src/bitshuffle/src/bitshuffle.h b/src/bitshuffle/src/bitshuffle.h index 3df95f47..1a13dd17 100644 --- a/src/bitshuffle/src/bitshuffle.h +++ b/src/bitshuffle/src/bitshuffle.h @@ -35,6 +35,10 @@ extern "C" { #endif +/* + * ---- LZ4 Interface ---- + */ + /* ---- bshuf_compress_lz4_bound ---- * * Bound on size of data compressed with *bshuf_compress_lz4*. @@ -94,11 +98,6 @@ int64_t bshuf_compress_lz4(const void* in, void* out, const size_t size, const s * To properly unshuffle bitshuffled data, *size*, *elem_size* and *block_size* * must patch the parameters used to compress the data. * - * NOT TO BE USED WITH UNTRUSTED DATA: This routine uses the function - * LZ4_decompress_fast from LZ4, which does not protect against maliciously - * formed datasets. By modifying the compressed data, this function could be - * coerced into leaving the boundaries of the input buffer. - * * Parameters * ---------- * in : input buffer @@ -116,6 +115,89 @@ int64_t bshuf_compress_lz4(const void* in, void* out, const size_t size, const s int64_t bshuf_decompress_lz4(const void* in, void* out, const size_t size, const size_t elem_size, size_t block_size); +/* + * ---- ZSTD Interface ---- + */ + +#ifdef ZSTD_SUPPORT +/* ---- bshuf_compress_zstd_bound ---- + * + * Bound on size of data compressed with *bshuf_compress_zstd*. + * + * Parameters + * ---------- + * size : number of elements in input + * elem_size : element size of typed data + * block_size : Process in blocks of this many elements. Pass 0 to + * select automatically (recommended). + * + * Returns + * ------- + * Bound on compressed data size. + * + */ +size_t bshuf_compress_zstd_bound(const size_t size, + const size_t elem_size, size_t block_size); + +/* ---- bshuf_compress_zstd ---- + * + * Bitshuffled and compress the data using zstd. + * + * Transpose within elements, in blocks of data of *block_size* elements then + * compress the blocks using ZSTD. In the output buffer, each block is prefixed + * by a 4 byte integer giving the compressed size of that block. + * + * Output buffer must be large enough to hold the compressed data. This could + * be in principle substantially larger than the input buffer. Use the routine + * *bshuf_compress_zstd_bound* to get an upper limit. + * + * Parameters + * ---------- + * in : input buffer, must be of size * elem_size bytes + * out : output buffer, must be large enough to hold data. + * size : number of elements in input + * elem_size : element size of typed data + * block_size : Process in blocks of this many elements. Pass 0 to + * select automatically (recommended). + * comp_lvl : compression level applied + * + * Returns + * ------- + * number of bytes used in output buffer, negative error-code if failed. + * + */ +int64_t bshuf_compress_zstd(const void* in, void* out, const size_t size, const size_t + elem_size, size_t block_size, const int comp_lvl); + + +/* ---- bshuf_decompress_zstd ---- + * + * Undo compression and bitshuffling. + * + * Decompress data then un-bitshuffle it in blocks of *block_size* elements. + * + * To properly unshuffle bitshuffled data, *size*, *elem_size* and *block_size* + * must patch the parameters used to compress the data. + * + * Parameters + * ---------- + * in : input buffer + * out : output buffer, must be of size * elem_size bytes + * size : number of elements in input + * elem_size : element size of typed data + * block_size : Process in blocks of this many elements. Pass 0 to + * select automatically (recommended). + * + * Returns + * ------- + * number of bytes consumed in *input* buffer, negative error-code if failed. + * + */ +int64_t bshuf_decompress_zstd(const void* in, void* out, const size_t size, + const size_t elem_size, size_t block_size); + +#endif // ZSTD_SUPPORT + #ifdef __cplusplus } // extern "C" #endif diff --git a/src/bitshuffle/src/bitshuffle_core.c b/src/bitshuffle/src/bitshuffle_core.c index 8028e3a6..ef33bf55 100644 --- a/src/bitshuffle/src/bitshuffle_core.c +++ b/src/bitshuffle/src/bitshuffle_core.c @@ -20,13 +20,15 @@ #define USEAVX2 #endif -#if defined(__SSE2__) +#if defined(__SSE2__) || defined(NO_WARN_X86_INTRINSICS) #define USESSE2 #endif #if defined(__ARM_NEON__) || (__ARM_NEON) +#ifdef __aarch64__ #define USEARMNEON #endif +#endif // Conditional includes for SSE2 and AVX2. #ifdef USEAVX2 @@ -1665,7 +1667,7 @@ int64_t bshuf_untrans_bit_elem(const void* in, void* out, const size_t size, /* Wrap a function for processing a single block to process an entire buffer in * parallel. */ int64_t bshuf_blocked_wrap_fun(bshufBlockFunDef fun, const void* in, void* out, \ - const size_t size, const size_t elem_size, size_t block_size) { + const size_t size, const size_t elem_size, size_t block_size, const int option) { omp_size_t ii = 0; int64_t err = 0; @@ -1691,7 +1693,7 @@ int64_t bshuf_blocked_wrap_fun(bshufBlockFunDef fun, const void* in, void* out, private(count) reduction(+ : cum_count) #endif for (ii = 0; ii < (omp_size_t)( size / block_size ); ii ++) { - count = fun(&C, block_size, elem_size); + count = fun(&C, block_size, elem_size, option); if (count < 0) err = count; cum_count += count; } @@ -1699,7 +1701,7 @@ int64_t bshuf_blocked_wrap_fun(bshufBlockFunDef fun, const void* in, void* out, last_block_size = size % block_size; last_block_size = last_block_size - last_block_size % BSHUF_BLOCKED_MULT; if (last_block_size) { - count = fun(&C, last_block_size, elem_size); + count = fun(&C, last_block_size, elem_size, option); if (count < 0) err = count; cum_count += count; } @@ -1723,7 +1725,7 @@ int64_t bshuf_blocked_wrap_fun(bshufBlockFunDef fun, const void* in, void* out, /* Bitshuffle a single block. */ int64_t bshuf_bitshuffle_block(ioc_chain *C_ptr, \ - const size_t size, const size_t elem_size) { + const size_t size, const size_t elem_size, const int option) { size_t this_iter; const void *in; @@ -1746,7 +1748,7 @@ int64_t bshuf_bitshuffle_block(ioc_chain *C_ptr, \ /* Bitunshuffle a single block. */ int64_t bshuf_bitunshuffle_block(ioc_chain* C_ptr, \ - const size_t size, const size_t elem_size) { + const size_t size, const size_t elem_size, const int option) { size_t this_iter; @@ -1840,7 +1842,7 @@ int64_t bshuf_bitshuffle(const void* in, void* out, const size_t size, const size_t elem_size, size_t block_size) { return bshuf_blocked_wrap_fun(&bshuf_bitshuffle_block, in, out, size, - elem_size, block_size); + elem_size, block_size, 0/*option*/); } @@ -1848,7 +1850,7 @@ int64_t bshuf_bitunshuffle(const void* in, void* out, const size_t size, const size_t elem_size, size_t block_size) { return bshuf_blocked_wrap_fun(&bshuf_bitunshuffle_block, in, out, size, - elem_size, block_size); + elem_size, block_size, 0/*option*/); } diff --git a/src/bitshuffle/src/bitshuffle_core.h b/src/bitshuffle/src/bitshuffle_core.h index 7f66b6d3..fba7301c 100644 --- a/src/bitshuffle/src/bitshuffle_core.h +++ b/src/bitshuffle/src/bitshuffle_core.h @@ -47,8 +47,8 @@ // These are usually set in the setup.py. #ifndef BSHUF_VERSION_MAJOR #define BSHUF_VERSION_MAJOR 0 -#define BSHUF_VERSION_MINOR 3 -#define BSHUF_VERSION_POINT 5 +#define BSHUF_VERSION_MINOR 4 +#define BSHUF_VERSION_POINT 0 #endif #ifdef __cplusplus @@ -67,6 +67,18 @@ extern "C" { int bshuf_using_SSE2(void); +/* ---- bshuf_using_NEON ---- + * + * Whether routines where compiled with the NEON instruction set. + * + * Returns + * ------- + * 1 if using NEON, 0 otherwise. + * + */ +int bshuf_using_NEON(void); + + /* ---- bshuf_using_AVX2 ---- * * Whether routines where compiled with the AVX2 instruction set. diff --git a/src/bitshuffle/src/bitshuffle_internals.h b/src/bitshuffle/src/bitshuffle_internals.h index e039925c..59356f10 100644 --- a/src/bitshuffle/src/bitshuffle_internals.h +++ b/src/bitshuffle/src/bitshuffle_internals.h @@ -61,12 +61,12 @@ int64_t bshuf_untrans_bit_elem(const void* in, void* out, const size_t size, /* Function definition for worker functions that process a single block. */ typedef int64_t (*bshufBlockFunDef)(ioc_chain* C_ptr, - const size_t size, const size_t elem_size); + const size_t size, const size_t elem_size, const int option); /* Wrap a function for processing a single block to process an entire buffer in * parallel. */ int64_t bshuf_blocked_wrap_fun(bshufBlockFunDef fun, const void* in, void* out, - const size_t size, const size_t elem_size, size_t block_size); + const size_t size, const size_t elem_size, size_t block_size, const int option); #ifdef __cplusplus } // extern "C" diff --git a/src/bitshuffle/src/bshuf_h5filter.c b/src/bitshuffle/src/bshuf_h5filter.c index f67a4a2b..114b91ff 100644 --- a/src/bitshuffle/src/bshuf_h5filter.c +++ b/src/bitshuffle/src/bshuf_h5filter.c @@ -78,6 +78,10 @@ herr_t bshuf_h5_set_local(hid_t dcpl, hid_t type, hid_t space){ break; case BSHUF_H5_COMPRESS_LZ4: break; + #ifdef ZSTD_SUPPORT + case BSHUF_H5_COMPRESS_ZSTD: + break; + #endif default: PUSH_ERR("bshuf_h5_set_local", H5E_CALLBACK, "Invalid bitshuffle compression."); @@ -96,7 +100,7 @@ size_t bshuf_h5_filter(unsigned int flags, size_t cd_nelmts, size_t *buf_size, void **buf) { size_t size, elem_size; - int err; + int err = -1; char msg[80]; size_t block_size = 0; size_t buf_size_out, nbytes_uncomp, nbytes_out; @@ -109,14 +113,25 @@ size_t bshuf_h5_filter(unsigned int flags, size_t cd_nelmts, return 0; } elem_size = cd_values[2]; +#ifdef ZSTD_SUPPORT + const int comp_lvl = cd_values[5]; +#endif // User specified block size. if (cd_nelmts > 3) block_size = cd_values[3]; if (block_size == 0) block_size = bshuf_default_block_size(elem_size); + +#ifndef ZSTD_SUPPORT + if (cd_nelmts > 4 && (cd_values[4] == BSHUF_H5_COMPRESS_ZSTD)) { + PUSH_ERR("bshuf_h5_filter", H5E_CALLBACK, + "ZSTD compression filter chosen but ZSTD support not installed."); + return 0; + } +#endif - // Compression in addition to bitshiffle. - if (cd_nelmts > 4 && cd_values[4] == BSHUF_H5_COMPRESS_LZ4) { + // Compression in addition to bitshuffle. + if (cd_nelmts > 4 && (cd_values[4] == BSHUF_H5_COMPRESS_LZ4 || cd_values[4] == BSHUF_H5_COMPRESS_ZSTD)) { if (flags & H5Z_FLAG_REVERSE) { // First eight bytes is the number of bytes in the output buffer, // little endian. @@ -128,8 +143,17 @@ size_t bshuf_h5_filter(unsigned int flags, size_t cd_nelmts, buf_size_out = nbytes_uncomp; } else { nbytes_uncomp = nbytes; - buf_size_out = bshuf_compress_lz4_bound(nbytes_uncomp / elem_size, - elem_size, block_size) + 12; + // Pick which compressions library to use + if(cd_values[4] == BSHUF_H5_COMPRESS_LZ4) { + buf_size_out = bshuf_compress_lz4_bound(nbytes_uncomp / elem_size, + elem_size, block_size) + 12; + } +#ifdef ZSTD_SUPPORT + else if (cd_values[4] == BSHUF_H5_COMPRESS_ZSTD) { + buf_size_out = bshuf_compress_zstd_bound(nbytes_uncomp / elem_size, + elem_size, block_size) + 12; + } +#endif } } else { nbytes_uncomp = nbytes; @@ -151,10 +175,18 @@ size_t bshuf_h5_filter(unsigned int flags, size_t cd_nelmts, return 0; } - if (cd_nelmts > 4 && cd_values[4] == BSHUF_H5_COMPRESS_LZ4) { + if (cd_nelmts > 4 && (cd_values[4] == BSHUF_H5_COMPRESS_LZ4 || cd_values[4] == BSHUF_H5_COMPRESS_ZSTD)) { if (flags & H5Z_FLAG_REVERSE) { // Bit unshuffle/decompress. - err = bshuf_decompress_lz4(in_buf, out_buf, size, elem_size, block_size); + // Pick which compressions library to use + if(cd_values[4] == BSHUF_H5_COMPRESS_LZ4) { + err = bshuf_decompress_lz4(in_buf, out_buf, size, elem_size, block_size); + } +#ifdef ZSTD_SUPPORT + else if (cd_values[4] == BSHUF_H5_COMPRESS_ZSTD) { + err = bshuf_decompress_zstd(in_buf, out_buf, size, elem_size, block_size); + } +#endif nbytes_out = nbytes_uncomp; } else { // Bit shuffle/compress. @@ -165,9 +197,20 @@ size_t bshuf_h5_filter(unsigned int flags, size_t cd_nelmts, // have the same representation. bshuf_write_uint64_BE(out_buf, nbytes_uncomp); bshuf_write_uint32_BE((char*) out_buf + 8, block_size * elem_size); - err = bshuf_compress_lz4(in_buf, (char*) out_buf + 12, size, - elem_size, block_size); nbytes_out = err + 12; } } else { - if (flags & H5Z_FLAG_REVERSE) { + if(cd_values[4] == BSHUF_H5_COMPRESS_LZ4) { + err = bshuf_compress_lz4(in_buf, (char*) out_buf + 12, size, + elem_size, block_size); + } +#ifdef ZSTD_SUPPORT + else if (cd_values[4] == BSHUF_H5_COMPRESS_ZSTD) { + err = bshuf_compress_zstd(in_buf, (char*) out_buf + 12, size, + elem_size, block_size, comp_lvl); + } +#endif + nbytes_out = err + 12; + } + } else { + if (flags & H5Z_FLAG_REVERSE) { // Bit unshuffle. err = bshuf_bitunshuffle(in_buf, out_buf, size, elem_size, block_size); } else { @@ -215,4 +258,3 @@ int bshuf_register_h5filter(void){ } return retval; } - diff --git a/src/bitshuffle/src/bshuf_h5filter.h b/src/bitshuffle/src/bshuf_h5filter.h index 0a8fa6a3..54ee6775 100644 --- a/src/bitshuffle/src/bshuf_h5filter.h +++ b/src/bitshuffle/src/bshuf_h5filter.h @@ -32,6 +32,10 @@ #ifndef BSHUF_H5FILTER_H #define BSHUF_H5FILTER_H +#ifdef __cplusplus +extern "C" { +#endif + #define H5Z_class_t_vers 2 #include "hdf5.h" @@ -40,6 +44,7 @@ #define BSHUF_H5_COMPRESS_LZ4 2 +#define BSHUF_H5_COMPRESS_ZSTD 3 extern H5Z_class_t bshuf_H5Filter[1]; @@ -55,5 +60,8 @@ extern H5Z_class_t bshuf_H5Filter[1]; */ int bshuf_register_h5filter(void); +#ifdef __cplusplus +} // extern "C" +#endif #endif // BSHUF_H5FILTER_H diff --git a/src/bitshuffle/src/hdf5_dl.c b/src/bitshuffle/src/hdf5_dl.c new file mode 100644 index 00000000..8e47fb80 --- /dev/null +++ b/src/bitshuffle/src/hdf5_dl.c @@ -0,0 +1,358 @@ +# /*########################################################################## +# +# Copyright (c) 2019 European Synchrotron Radiation Facility +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# ###########################################################################*/ +/* This provides replacement for HDF5 functions/variables used by filters. + * + * Those replacement provides no-op functions by default and if init_filter + * is called it provides access to HDF5 functions/variables through dynamic + * loading. + * This is useful on Linux/macOS to avoid linking the plugin with a dedicated + * HDF5 library. + */ +#include +#include +#include +#include "hdf5.h" + + +/*Function types*/ +/*H5*/ +typedef herr_t (*DL_func_H5open)(void); +/*H5E*/ +typedef herr_t (* DL_func_H5Epush1)( + const char *file, const char *func, unsigned line, + H5E_major_t maj, H5E_minor_t min, const char *str); +typedef herr_t (* DL_func_H5Epush2)( + hid_t err_stack, const char *file, const char *func, unsigned line, + hid_t cls_id, hid_t maj_id, hid_t min_id, const char *msg, ...); +/*H5P*/ +typedef herr_t (* DL_func_H5Pget_filter_by_id2)(hid_t plist_id, H5Z_filter_t id, + unsigned int *flags/*out*/, size_t *cd_nelmts/*out*/, + unsigned cd_values[]/*out*/, size_t namelen, char name[]/*out*/, + unsigned *filter_config/*out*/); +typedef int (* DL_func_H5Pget_chunk)( + hid_t plist_id, int max_ndims, hsize_t dim[]/*out*/); +typedef herr_t (* DL_func_H5Pmodify_filter)( + hid_t plist_id, H5Z_filter_t filter, + unsigned int flags, size_t cd_nelmts, + const unsigned int cd_values[/*cd_nelmts*/]); +/*H5T*/ +typedef size_t (* DL_func_H5Tget_size)( + hid_t type_id); +typedef H5T_class_t (* DL_func_H5Tget_class)(hid_t type_id); +typedef hid_t (* DL_func_H5Tget_super)(hid_t type); +typedef herr_t (* DL_func_H5Tclose)(hid_t type_id); +/*H5Z*/ +typedef herr_t (* DL_func_H5Zregister)( + const void *cls); + + +static struct { + /*H5*/ + DL_func_H5open H5open; + /*H5E*/ + DL_func_H5Epush1 H5Epush1; + DL_func_H5Epush2 H5Epush2; + /*H5P*/ + DL_func_H5Pget_filter_by_id2 H5Pget_filter_by_id2; + DL_func_H5Pget_chunk H5Pget_chunk; + DL_func_H5Pmodify_filter H5Pmodify_filter; + /*H5T*/ + DL_func_H5Tget_size H5Tget_size; + DL_func_H5Tget_class H5Tget_class; + DL_func_H5Tget_super H5Tget_super; + DL_func_H5Tclose H5Tclose; + /*H5T*/ + DL_func_H5Zregister H5Zregister; +} DL_H5Functions = { + NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; + +static struct { + /*HDF5 variables*/ + void *h5e_cantregister_ptr; + void *h5e_callback_ptr; + void *h5e_pline_ptr; + void *h5e_err_cls_ptr; +} H5Variables_ptr = { + NULL, NULL, NULL, NULL}; + +/*HDF5 variables*/ +hid_t H5E_CANTREGISTER_g = -1; +hid_t H5E_CALLBACK_g = -1; +hid_t H5E_PLINE_g = -1; +hid_t H5E_ERR_CLS_g = -1; + + +static bool is_init = false; + +/* + * Try to find a symbol within a library + * + * handle: Handle to the library + * symbol: Symbol to look for + * Returns: a pointer to the symbol or NULL + * if the symbol can't be found + */ +void *find_sym(void *handle, const char *symbol) { + + void *ret = NULL, *err = NULL; + dlerror(); /* clear error code */ + ret = dlsym(handle, symbol); + + if(ret != NULL && (err = dlerror()) == NULL) + return ret; + else + return NULL; +} + +/* + * Check that all symbols have been loaded + * + * Returns: -1 if an error occured, 0 for success + */ +int check_symbols() { + + if(DL_H5Functions.H5open == NULL) + return -1; + + /*H5E*/ + if(DL_H5Functions.H5Epush1 == NULL) + return -1; + + if(DL_H5Functions.H5Epush2 == NULL) + return -1; + + /*H5P*/ + if(DL_H5Functions.H5Pget_filter_by_id2 == NULL) + return -1; + + if(DL_H5Functions.H5Pget_chunk == NULL) + return -1; + + if(DL_H5Functions.H5Pmodify_filter == NULL) + return -1; + + /*H5T*/ + if(DL_H5Functions.H5Tget_size == NULL) + return -1; + + if(DL_H5Functions.H5Tget_class == NULL) + return -1; + + if(DL_H5Functions.H5Tget_super == NULL) + return -1; + + if(DL_H5Functions.H5Tclose == NULL) + return -1; + + /*H5Z*/ + if(DL_H5Functions.H5Zregister == NULL) + return -1; + + /*Variables*/ + if(H5Variables_ptr.h5e_cantregister_ptr == NULL) + return -1; + + if(H5Variables_ptr.h5e_callback_ptr == NULL) + return -1; + + if(H5Variables_ptr.h5e_pline_ptr == NULL) + return -1; + + if(H5Variables_ptr.h5e_err_cls_ptr == NULL) + return -1; + + return 0; + +} + +/* Initialize the dynamic loading of symbols and register the plugin + * + * libname: Name of the DLL from which to load libHDF5 symbols + * Returns: -1 if an error occured, 0 for success + */ +int init_filter(const char *libname) +{ + int retval = -1; + void *handle = NULL; + + handle = dlopen(libname, RTLD_LAZY | RTLD_LOCAL); + + if (handle != NULL) { + /*H5*/ + if(DL_H5Functions.H5open == NULL) + // find_sym will return NULL if it fails so no need to check return ptr + DL_H5Functions.H5open = (DL_func_H5open)find_sym(handle, "H5open"); + + /*H5E*/ + if(DL_H5Functions.H5Epush1 == NULL) + DL_H5Functions.H5Epush1 = (DL_func_H5Epush1)find_sym(handle, "H5Epush1"); + + if(DL_H5Functions.H5Epush2 == NULL) + DL_H5Functions.H5Epush2 = (DL_func_H5Epush2)find_sym(handle, "H5Epush2"); + + /*H5P*/ + if(DL_H5Functions.H5Pget_filter_by_id2 == NULL) + DL_H5Functions.H5Pget_filter_by_id2 = + (DL_func_H5Pget_filter_by_id2)find_sym(handle, "H5Pget_filter_by_id2"); + + if(DL_H5Functions.H5Pget_chunk == NULL) + DL_H5Functions.H5Pget_chunk = (DL_func_H5Pget_chunk)find_sym(handle, "H5Pget_chunk"); + + if(DL_H5Functions.H5Pmodify_filter == NULL) + DL_H5Functions.H5Pmodify_filter = + (DL_func_H5Pmodify_filter)find_sym(handle, "H5Pmodify_filter"); + + /*H5T*/ + if(DL_H5Functions.H5Tget_size == NULL) + DL_H5Functions.H5Tget_size = (DL_func_H5Tget_size)find_sym(handle, "H5Tget_size"); + + if(DL_H5Functions.H5Tget_class == NULL) + DL_H5Functions.H5Tget_class = (DL_func_H5Tget_class)find_sym(handle, "H5Tget_class"); + + if(DL_H5Functions.H5Tget_super == NULL) + DL_H5Functions.H5Tget_super = (DL_func_H5Tget_super)find_sym(handle, "H5Tget_super"); + + if(DL_H5Functions.H5Tclose == NULL) + DL_H5Functions.H5Tclose = (DL_func_H5Tclose)find_sym(handle, "H5Tclose"); + + /*H5Z*/ + if(DL_H5Functions.H5Zregister == NULL) + DL_H5Functions.H5Zregister = (DL_func_H5Zregister)find_sym(handle, "H5Zregister"); + + /*Variables*/ + if(H5Variables_ptr.h5e_cantregister_ptr == NULL) + H5Variables_ptr.h5e_cantregister_ptr = find_sym(handle, "H5E_CANTREGISTER_g"); + + if(H5Variables_ptr.h5e_callback_ptr == NULL) + H5Variables_ptr.h5e_callback_ptr = find_sym(handle, "H5E_CALLBACK_g"); + + if(H5Variables_ptr.h5e_pline_ptr == NULL) + H5Variables_ptr.h5e_pline_ptr = find_sym(handle, "H5E_PLINE_g"); + + if(H5Variables_ptr.h5e_err_cls_ptr == NULL) + H5Variables_ptr.h5e_err_cls_ptr = find_sym(handle, "H5E_ERR_CLS_g"); + + retval = check_symbols(); + if(!retval) { + H5E_CANTREGISTER_g = *((hid_t *)H5Variables_ptr.h5e_cantregister_ptr); + H5E_CALLBACK_g = *((hid_t *)H5Variables_ptr.h5e_callback_ptr); + H5E_PLINE_g = *((hid_t *)H5Variables_ptr.h5e_pline_ptr); + H5E_ERR_CLS_g = *((hid_t *)H5Variables_ptr.h5e_err_cls_ptr); + is_init = true; + } + } + + return retval; +}; + + +#define CALL(fallback, func, ...)\ + if(DL_H5Functions.func != NULL) {\ + return DL_H5Functions.func(__VA_ARGS__);\ + } else {\ + return fallback;\ + } + + +/*Function wrappers*/ +/*H5*/ +herr_t H5open(void) +{ +CALL(0, H5open) +}; + +/*H5E*/ +herr_t H5Epush1(const char *file, const char *func, unsigned line, + H5E_major_t maj, H5E_minor_t min, const char *str) +{ +CALL(0, H5Epush1, file, func, line, maj, min, str) +} + +herr_t H5Epush2(hid_t err_stack, const char *file, const char *func, unsigned line, + hid_t cls_id, hid_t maj_id, hid_t min_id, const char *fmt, ...) +{ + if(DL_H5Functions.H5Epush2 != NULL) { + /* Avoid using variadic: convert fmt+ ... to a message sting */ + va_list ap; + char msg_string[256]; /*Buffer hopefully wide enough*/ + + va_start(ap, fmt); + vsnprintf(msg_string, sizeof(msg_string), fmt, ap); + msg_string[sizeof(msg_string) - 1] = '\0'; + va_end(ap); + + return DL_H5Functions.H5Epush2(err_stack, file, func, line, cls_id, maj_id, min_id, msg_string); + } else { + return 0; + } +} + +/*H5P*/ +herr_t H5Pget_filter_by_id2(hid_t plist_id, H5Z_filter_t id, + unsigned int *flags/*out*/, size_t *cd_nelmts/*out*/, + unsigned cd_values[]/*out*/, size_t namelen, char name[]/*out*/, + unsigned *filter_config/*out*/) +{ +CALL(0, H5Pget_filter_by_id2, plist_id, id, flags, cd_nelmts, cd_values, namelen, name, filter_config) +} + +int H5Pget_chunk(hid_t plist_id, int max_ndims, hsize_t dim[]/*out*/) +{ +CALL(0, H5Pget_chunk, plist_id, max_ndims, dim) +} + +herr_t H5Pmodify_filter(hid_t plist_id, H5Z_filter_t filter, + unsigned int flags, size_t cd_nelmts, + const unsigned int cd_values[/*cd_nelmts*/]) +{ +CALL(0, H5Pmodify_filter, plist_id, filter, flags, cd_nelmts, cd_values) +} + +/*H5T*/ +size_t H5Tget_size(hid_t type_id) +{ +CALL(0, H5Tget_size, type_id) +} + +H5T_class_t H5Tget_class(hid_t type_id) +{ +CALL(H5T_NO_CLASS, H5Tget_class, type_id) +} + + +hid_t H5Tget_super(hid_t type) +{ +CALL(0, H5Tget_super, type) +} + +herr_t H5Tclose(hid_t type_id) +{ +CALL(0, H5Tclose, type_id) +} + +/*H5Z*/ +herr_t H5Zregister(const void *cls) +{ +CALL(-1, H5Zregister, cls) +} diff --git a/src/bitshuffle/bitshuffle/tests/data/regression_0.1.3.h5 b/src/bitshuffle/tests/data/regression_0.1.3.h5 similarity index 99% rename from src/bitshuffle/bitshuffle/tests/data/regression_0.1.3.h5 rename to src/bitshuffle/tests/data/regression_0.1.3.h5 index ee8373f7..875b751b 100644 Binary files a/src/bitshuffle/bitshuffle/tests/data/regression_0.1.3.h5 and b/src/bitshuffle/tests/data/regression_0.1.3.h5 differ diff --git a/src/bitshuffle/tests/data/regression_0.4.0.h5 b/src/bitshuffle/tests/data/regression_0.4.0.h5 new file mode 100644 index 00000000..4ee84136 Binary files /dev/null and b/src/bitshuffle/tests/data/regression_0.4.0.h5 differ diff --git a/src/bitshuffle/tests/make_regression_tdata.py b/src/bitshuffle/tests/make_regression_tdata.py new file mode 100644 index 00000000..03deb422 --- /dev/null +++ b/src/bitshuffle/tests/make_regression_tdata.py @@ -0,0 +1,69 @@ +""" +Script to create data used for regression testing. + +""" + +import numpy as np +from numpy import random +import h5py + +import bitshuffle +from bitshuffle import h5 +from h5py import h5z + +BLOCK_SIZE = 64 # Smallish such that datasets have many blocks but are small. +COMP_LVL = 10 # ZSTD compression level +FILTER_PIPELINE = [h5.H5FILTER] +FILTER_OPTS = [ + [(BLOCK_SIZE, h5.H5_COMPRESS_LZ4)], + [(BLOCK_SIZE, h5.H5_COMPRESS_ZSTD, COMP_LVL)], +] + +OUT_FILE = "tests/data/regression_%s.h5" % bitshuffle.__version__ + +DTYPES = ["a1", "a2", "a3", "a4", "a6", "a8", "a10"] + +f = h5py.File(OUT_FILE, "w") +g_orig = f.create_group("origional") +g_comp_lz4 = f.create_group("compressed") +g_comp_zstd = f.create_group("compressed_zstd") + +for dtype in DTYPES: + for rep in ["a", "b", "c"]: + dset_name = "%s_%s" % (dtype, rep) + dtype = np.dtype(dtype) + n_elem = 3 * BLOCK_SIZE + random.randint(0, BLOCK_SIZE) + shape = (n_elem,) + chunks = shape + data = random.randint(0, 255, n_elem * dtype.itemsize) + data = data.astype(np.uint8).view(dtype) + + g_orig.create_dataset(dset_name, data=data) + + # Create LZ4 compressed data + h5.create_dataset( + g_comp_lz4, + bytes(dset_name, "utf-8"), + shape, + dtype, + chunks=chunks, + filter_pipeline=FILTER_PIPELINE, + filter_flags=(h5z.FLAG_MANDATORY,), + filter_opts=FILTER_OPTS[0], + ) + g_comp_lz4[dset_name][:] = data + + # Create ZSTD compressed data + h5.create_dataset( + g_comp_zstd, + bytes(dset_name, "utf-8"), + shape, + dtype, + chunks=chunks, + filter_pipeline=FILTER_PIPELINE, + filter_flags=(h5z.FLAG_MANDATORY,), + filter_opts=FILTER_OPTS[1], + ) + g_comp_zstd[dset_name][:] = data + +f.close() diff --git a/src/bitshuffle/bitshuffle/tests/test_ext.py b/src/bitshuffle/tests/test_ext.py similarity index 85% rename from src/bitshuffle/bitshuffle/tests/test_ext.py rename to src/bitshuffle/tests/test_ext.py index 11be1ffd..b2577c0d 100644 --- a/src/bitshuffle/bitshuffle/tests/test_ext.py +++ b/src/bitshuffle/tests/test_ext.py @@ -2,29 +2,33 @@ import unittest import time -import timeit import numpy as np from numpy import random -from bitshuffle import ext +from bitshuffle import ext, __zstd__ # If we are doing timeings by what factor to increase workload. # Remember to change `ext.REPEATC`. TIME = 0 -#TIME = 8 # 8kB blocks same as final blocking. +# TIME = 8 # 8kB blocks same as final blocking. BLOCK = 1024 -TEST_DTYPES = [np.uint8, np.uint16, np.int32, np.uint64, np.float32, - np.float64, np.complex128] -TEST_DTYPES += [b'a3', b'a5', b'a6', b'a7', b'a9', b'a11', b'a12', b'a24', - b'a48'] +TEST_DTYPES = [ + np.uint8, + np.uint16, + np.int32, + np.uint64, + np.float32, + np.float64, + np.complex128, +] +TEST_DTYPES += [b"a3", b"a5", b"a6", b"a7", b"a9", b"a11", b"a12", b"a24", b"a48"] class TestProfile(unittest.TestCase): - def setUp(self): n = 1024 # bytes. if TIME: @@ -50,11 +54,9 @@ def tearDown(self): out = self.fun(self.data) delta_ts.append(time.time() - t0) except RuntimeError as err: - if (len(err.args) > 1 and (err.args[1] == -11) - and not ext.using_SSE2()): + if len(err.args) > 1 and (err.args[1] == -11) and not ext.using_SSE2(): return - if (len(err.args) > 1 and (err.args[1] == -12) - and not ext.using_AVX2()): + if len(err.args) > 1 and (err.args[1] == -12) and not ext.using_AVX2(): return else: raise @@ -62,13 +64,13 @@ def tearDown(self): size_i = self.data.size * self.data.dtype.itemsize size_o = out.size * out.dtype.itemsize size = max([size_i, size_o]) - speed = (ext.REPEAT * size / delta_t / 1024**3) # GB/s + speed = ext.REPEAT * size / delta_t / 1024**3 # GB/s if TIME: - print("%-20s: %5.2f s/GB, %5.2f GB/s" % (self.case, 1./speed, speed)) - if not self.check is None: + print("%-20s: %5.2f s/GB, %5.2f GB/s" % (self.case, 1.0 / speed, speed)) + if self.check is not None: ans = self.check(self.data).view(np.uint8) self.assertTrue(np.all(ans == out.view(np.uint8))) - if not self.check_data is None: + if self.check_data is not None: ans = self.check_data.view(np.uint8) self.assertTrue(np.all(ans == out.view(np.uint8))) @@ -122,8 +124,9 @@ def test_01g_trans_byte_elem_128(self): def test_01h_trans_byte_elem_96(self): self.case = "byte T elem SSE 96" n = self.data.size // 128 * 96 - dt = np.dtype([(str('a'), np.int32), (str('b'), np.int32), - (str('c'), np.int32)]) + dt = np.dtype( + [(str("a"), np.int32), (str("b"), np.int32), (str("c"), np.int32)] + ) self.data = self.data[:n].view(dt) self.fun = ext.trans_byte_elem_SSE self.check = trans_byte_elem @@ -131,9 +134,15 @@ def test_01h_trans_byte_elem_96(self): def test_01i_trans_byte_elem_80(self): self.case = "byte T elem SSE 80" n = self.data.size // 128 * 80 - dt = np.dtype([(str('a'), np.int16), (str('b'), np.int16), - (str('c'), np.int16), (str('d'), np.int16), - (str('e'), np.int16)]) + dt = np.dtype( + [ + (str("a"), np.int16), + (str("b"), np.int16), + (str("c"), np.int16), + (str("d"), np.int16), + (str("e"), np.int16), + ] + ) self.data = self.data[:n].view(dt) self.fun = ext.trans_byte_elem_SSE self.check = trans_byte_elem @@ -359,16 +368,34 @@ def test_10b_bitunshuffle_64(self): def test_10c_compress_64(self): self.case = "compress 64" self.data = self.data.view(np.float64) - self.fun = lambda x:ext.compress_lz4(x, BLOCK) + self.fun = lambda x: ext.compress_lz4(x, BLOCK) def test_10d_decompress_64(self): self.case = "decompress 64" pre_trans = self.data.view(np.float64) self.data = ext.compress_lz4(pre_trans, BLOCK) - self.fun = lambda x: ext.decompress_lz4(x, pre_trans.shape, - pre_trans.dtype, BLOCK) + self.fun = lambda x: ext.decompress_lz4( + x, pre_trans.shape, pre_trans.dtype, BLOCK + ) + self.check_data = pre_trans + + @unittest.skipUnless(__zstd__, "ZSTD support not included") + def test_10c_compress_z64(self): + self.case = "compress zstd 64" + self.data = self.data.view(np.float64) + self.fun = lambda x: ext.compress_zstd(x, BLOCK) + + @unittest.skipUnless(__zstd__, "ZSTD support not included") + def test_10d_decompress_z64(self): + self.case = "decompress zstd 64" + pre_trans = self.data.view(np.float64) + self.data = ext.compress_zstd(pre_trans, BLOCK) + self.fun = lambda x: ext.decompress_zstd( + x, pre_trans.shape, pre_trans.dtype, BLOCK + ) self.check_data = pre_trans + """ Commented out to prevent nose from finding them. class TestDevCases(unittest.TestCase): @@ -435,11 +462,10 @@ def deactivated_test_bitshuffle(self): class TestOddLengths(unittest.TestCase): - def setUp(self): self.reps = 10 self.nmax = 128 * 8 - #self.nmax = 4 * 8 # XXX + # self.nmax = 4 * 8 # XXX self.fun = ext.copy self.check = lambda x: x @@ -485,11 +511,9 @@ def tearDown(self): ans = self.check(data).view(np.uint8) self.assertTrue(np.all(out == ans)) except RuntimeError as err: - if (len(err.args) > 1 and (err.args[1] == -11) - and not ext.using_SSE2()): + if len(err.args) > 1 and (err.args[1] == -11) and not ext.using_SSE2(): return - if (len(err.args) > 1 and (err.args[1] == -12) - and not ext.using_AVX2()): + if len(err.args) > 1 and (err.args[1] == -12) and not ext.using_AVX2(): return else: raise @@ -513,8 +537,7 @@ def test_circle(self): shuff = ext.bitshuffle(data) out = ext.bitunshuffle(shuff) self.assertTrue(out.dtype is data.dtype) - self.assertTrue(np.all(data.view(np.uint8) - == out.view(np.uint8))) + self.assertTrue(np.all(data.view(np.uint8) == out.view(np.uint8))) def test_circle_with_compression(self): nmax = 100000 @@ -530,12 +553,29 @@ def test_circle_with_compression(self): shuff = ext.compress_lz4(data) out = ext.decompress_lz4(shuff, data.shape, data.dtype) self.assertTrue(out.dtype is data.dtype) - self.assertTrue(np.all(data.view(np.uint8) - == out.view(np.uint8))) + self.assertTrue(np.all(data.view(np.uint8) == out.view(np.uint8))) + + @unittest.skipUnless(__zstd__, "ZSTD support not included") + def test_circle_with_zstd_compression(self): + nmax = 100000 + reps = 20 + for dtype in TEST_DTYPES: + itemsize = np.dtype(dtype).itemsize + nbyte_max = nmax * itemsize + dbuf = random.randint(0, 255, nbyte_max).astype(np.uint8) + dbuf = dbuf.view(dtype) + for ii in range(reps): + n = random.randint(0, nmax, 1)[0] + data = dbuf[:n] + shuff = ext.compress_zstd(data) + out = ext.decompress_zstd(shuff, data.shape, data.dtype) + self.assertTrue(out.dtype is data.dtype) + self.assertTrue(np.all(data.view(np.uint8) == out.view(np.uint8))) # Python implementations for checking results. + def trans_byte_elem(arr): dtype = arr.dtype itemsize = dtype.itemsize @@ -546,7 +586,7 @@ def trans_byte_elem(arr): out_buf = np.empty((itemsize, nelem), dtype=np.uint8) for ii in range(nelem): for jj in range(itemsize): - out_buf[jj,ii] = in_buf[ii,jj] + out_buf[jj, ii] = in_buf[ii, jj] return out_buf.flat[:].view(dtype) @@ -558,10 +598,10 @@ def trans_bit_byte(arr): bits.shape = (n * itemsize, 8) # We have to reverse the order of the bits both for unpacking and packing, # since we want to call the least significant bit the first bit. - bits = bits[:,::-1] + bits = bits[:, ::-1] bits_shuff = (bits.T).copy() bits_shuff.shape = (n * itemsize, 8) - bits_shuff = bits_shuff[:,::-1] + bits_shuff = bits_shuff[:, ::-1] arr_bt = np.packbits(bits_shuff.flat[:]) return arr_bt.view(dtype) @@ -574,15 +614,14 @@ def trans_bit_elem(arr): bits.shape = (n * itemsize, 8) # We have to reverse the order of the bits both for unpacking and packing, # since we want to call the least significant bit the first bit. - bits = bits[:,::-1].copy() + bits = bits[:, ::-1].copy() bits.shape = (n, itemsize * 8) bits_shuff = (bits.T).copy() bits_shuff.shape = (n * itemsize, 8) - bits_shuff = bits_shuff[:,::-1] + bits_shuff = bits_shuff[:, ::-1] arr_bt = np.packbits(bits_shuff.flat[:]) return arr_bt.view(dtype) - if __name__ == "__main__": unittest.main() diff --git a/src/bitshuffle/tests/test_h5filter.py b/src/bitshuffle/tests/test_h5filter.py new file mode 100644 index 00000000..2dbb2c3f --- /dev/null +++ b/src/bitshuffle/tests/test_h5filter.py @@ -0,0 +1,138 @@ +from __future__ import absolute_import, division, print_function, unicode_literals + +import unittest +import os +import glob + +import numpy as np +import h5py +import pytest +from h5py import h5z + +from bitshuffle import h5, __zstd__ + + +os.environ["HDF5_PLUGIN_PATH"] = "" + + +class TestFilter(unittest.TestCase): + def test_filter(self): + shape = (32 * 1024 + 783,) + chunks = (4 * 1024 + 23,) + dtype = np.int64 + data = np.arange(shape[0]) + fname = "tmp_test_filters.h5" + f = h5py.File(fname, "w") + h5.create_dataset( + f, + b"range", + shape, + dtype, + chunks, + filter_pipeline=(32008, 32000), + filter_flags=(h5z.FLAG_MANDATORY, h5z.FLAG_MANDATORY), + filter_opts=None, + ) + f["range"][:] = data + + f.close() + + f = h5py.File(fname, "r") + d = f["range"][:] + self.assertTrue(np.all(d == data)) + f.close() + + def test_with_block_size(self): + shape = (128 * 1024 + 783,) + chunks = (4 * 1024 + 23,) + dtype = np.int64 + data = np.arange(shape[0]) + fname = "tmp_test_filters.h5" + f = h5py.File(fname, "w") + h5.create_dataset( + f, + b"range", + shape, + dtype, + chunks, + filter_pipeline=(32008, 32000), + filter_flags=(h5z.FLAG_MANDATORY, h5z.FLAG_MANDATORY), + filter_opts=((680,), ()), + ) + f["range"][:] = data + + f.close() + # os.system('h5dump -H -p tmp_test_filters.h5') + + f = h5py.File(fname, "r") + d = f["range"][:] + self.assertTrue(np.all(d == data)) + f.close() + + def test_with_lz4_compression(self): + shape = (128 * 1024 + 783,) + chunks = (4 * 1024 + 23,) + dtype = np.int64 + data = np.arange(shape[0]) + fname = "tmp_test_filters.h5" + f = h5py.File(fname, "w") + h5.create_dataset( + f, + b"range", + shape, + dtype, + chunks, + filter_pipeline=(32008,), + filter_flags=(h5z.FLAG_MANDATORY,), + filter_opts=((0, h5.H5_COMPRESS_LZ4),), + ) + f["range"][:] = data + + f.close() + # os.system('h5dump -H -p tmp_test_filters.h5') + + f = h5py.File(fname, "r") + d = f["range"][:] + self.assertTrue(np.all(d == data)) + f.close() + + @pytest.mark.skipif( + __zstd__ is False, + reason="Bitshuffle has not been built with ZSTD support.", + ) + def test_with_zstd_compression(self): + shape = (128 * 1024 + 783,) + chunks = (4 * 1024 + 23,) + compression_lvl = 10 + dtype = np.int64 + data = np.arange(shape[0]) + fname = "tmp_test_filters.h5" + f = h5py.File(fname, "w") + h5.create_dataset( + f, + b"range", + shape, + dtype, + chunks, + filter_pipeline=(32008,), + filter_flags=(h5z.FLAG_MANDATORY,), + filter_opts=((0, h5.H5_COMPRESS_ZSTD, compression_lvl),), + ) + f["range"][:] = data + + f.close() + # os.system('h5dump -H -p tmp_test_filters.h5') + + f = h5py.File(fname, "r") + d = f["range"][:] + self.assertTrue(np.all(d == data)) + f.close() + + def tearDown(self): + files = glob.glob("tmp_test_*") + for f in files: + os.remove(f) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/bitshuffle/tests/test_h5plugin.py b/src/bitshuffle/tests/test_h5plugin.py new file mode 100644 index 00000000..001fa9da --- /dev/null +++ b/src/bitshuffle/tests/test_h5plugin.py @@ -0,0 +1,66 @@ +from __future__ import absolute_import, division, print_function, unicode_literals +import unittest +import os +import glob + +import numpy as np +import h5py +import pytest +from subprocess import Popen, PIPE, STDOUT + +import bitshuffle + + +plugin_dir = os.path.join(os.path.dirname(bitshuffle.__file__), "plugin") +os.environ["HDF5_PLUGIN_PATH"] = plugin_dir + + +H5VERSION = h5py.h5.get_libversion() +if H5VERSION[0] < 1 or ( + H5VERSION[0] == 1 + and (H5VERSION[1] < 8 or (H5VERSION[1] == 8 and H5VERSION[2] < 11)) +): + H51811P = False +else: + H51811P = True + + +class TestFilterPlugins(unittest.TestCase): + @pytest.mark.skipif( + "CIBUILDWHEEL" in os.environ, + reason="Can't build dynamic HDF5 plugin into bitshuffle wheel.", + ) + def test_plugins(self): + if not H51811P: + return + shape = (32 * 1024,) + chunks = (4 * 1024,) + dtype = np.int64 + data = np.arange(shape[0]) + fname = "tmp_test_filters.h5" + f = h5py.File(fname, "w") + dset = f.create_dataset( + "range", shape=shape, dtype=dtype, chunks=chunks, compression=32008 + ) + dset[:] = data + f.close() + + # Make sure the filters are working outside of h5py by calling h5dump + h5dump = Popen(["h5dump", fname], stdout=PIPE, stderr=STDOUT) + stdout, nothing = h5dump.communicate() + err = h5dump.returncode + self.assertEqual(err, 0) + + f = h5py.File(fname, "r") + d = f["range"][:] + self.assertTrue(np.all(d == data)) + f.close() + + def tearDown(self): + files = glob.glob("tmp_test_*") + for f in files: + os.remove(f) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/bitshuffle/tests/test_regression.py b/src/bitshuffle/tests/test_regression.py new file mode 100644 index 00000000..bb9febc4 --- /dev/null +++ b/src/bitshuffle/tests/test_regression.py @@ -0,0 +1,46 @@ +""" +Test that data encoded with earlier versions can still be decoded correctly. + +""" + +from __future__ import absolute_import, division, print_function + +import pathlib +import unittest + +import numpy as np +import h5py +from bitshuffle import __zstd__ + +from packaging import version + +TEST_DATA_DIR = pathlib.Path(__file__).parent / "data" + +OUT_FILE_TEMPLATE = "regression_%s.h5" + +VERSIONS = ["0.1.3", "0.4.0"] + + +class TestAll(unittest.TestCase): + def test_regression(self): + for rev in VERSIONS: + file_name = TEST_DATA_DIR / (OUT_FILE_TEMPLATE % rev) + f = h5py.File(file_name, "r") + g_orig = f["original"] + g_comp = f["compressed"] + + for dset_name in g_comp.keys(): + self.assertTrue(np.all(g_comp[dset_name][:] == g_orig[dset_name][:])) + + # Only run ZSTD comparison on versions >= 0.4.0 and if ZSTD support + # has been built into bitshuffle + if version.parse(rev) >= version.parse("0.4.0") and __zstd__: + g_comp_zstd = f["compressed_zstd"] + for dset_name in g_comp_zstd.keys(): + self.assertTrue( + np.all(g_comp_zstd[dset_name][:] == g_orig[dset_name][:]) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/bitshuffle/zstd b/src/bitshuffle/zstd new file mode 160000 index 00000000..18d02cbf --- /dev/null +++ b/src/bitshuffle/zstd @@ -0,0 +1 @@ +Subproject commit 18d02cbf2e0654de08093094f1a77cfd231f11d7 diff --git a/src/hdf5plugin/__init__.py b/src/hdf5plugin/__init__.py index a731a1fa..6f8f7938 100644 --- a/src/hdf5plugin/__init__.py +++ b/src/hdf5plugin/__init__.py @@ -141,18 +141,48 @@ class Bitshuffle(_FilterRefClass): The number of elements per block. It needs to be divisible by eight (default is 0, about 8kB per block) Default: 0 (for about 8kB per block). - :param bool lz4: - Whether to use lz4 compression or not as part of the filter. - Default: True + :param str cname: + `lz4` (default), `none`, `zstd` + :param int clevel: Compression level, used only for `zstd` compression. + Can be negative, and must be below or equal to 22 (maximum compression). + Default: 3. """ filter_id = BSHUF_ID - def __init__(self, nelems=0, lz4=True): + __COMPRESSIONS = { + 'none': 0, + 'lz4': 2, + 'zstd': 3, + } + + def __init__(self, nelems=0, cname=None, clevel=3, lz4=None): nelems = int(nelems) assert nelems % 8 == 0 - - lz4_enabled = 2 if lz4 else 0 - self.filter_options = (nelems, lz4_enabled) + assert clevel <= 22 + + if lz4 is not None: + if cname is not None: + raise ValueError("Providing both cname and lz4 arguments is not supported") + _logger.warning( + "Depreaction: hdf5plugin.Bitshuffle's lz4 argument is deprecated, " + "use cname='lz4' or 'none' instead.") + cname = 'lz4' if lz4 else 'none' + + if cname in (True, False): + _logger.warning( + "Depreaction: hdf5plugin.Bitshuffle's boolean argument is deprecated, " + "use cname='lz4' or 'none' instead.") + cname = 'lz4' if cname else 'none' + + if cname is None: + cname = 'lz4' + if cname not in self.__COMPRESSIONS: + raise ValueError("Unsupported compression: %s" % cname) + + if cname == 'zstd': + self.filter_options = (nelems, self.__COMPRESSIONS[cname], clevel) + else: + self.filter_options = (nelems, self.__COMPRESSIONS[cname]) class Blosc(_FilterRefClass): diff --git a/src/hdf5plugin/test.py b/src/hdf5plugin/test.py index 25047b67..277aa7e1 100644 --- a/src/hdf5plugin/test.py +++ b/src/hdf5plugin/test.py @@ -107,7 +107,7 @@ def _test(self, return filters[0] @unittest.skipUnless(should_test("bshuf"), "Bitshuffle filter not available") - def testBitshuffle(self): + def testDepreactedBitshuffle(self): """Write/read test with bitshuffle filter plugin""" self._test('bshuf') # Default options @@ -119,6 +119,25 @@ def testBitshuffle(self): filter_ = self._test('bshuf', dtype, compressed=lz4, nelems=nelems, lz4=lz4) self.assertEqual(filter_[2][3:], (nelems, 2 if lz4 else 0)) + @unittest.skipUnless(should_test("bshuf"), "Bitshuffle filter not available") + def testBitshuffle(self): + """Write/read test with bitshuffle filter plugin""" + self._test('bshuf') # Default options + + compression_ids = { + 'none': 0, + 'lz4': 2, + 'zstd': 3 + } + + # Specify options + for cname in ('none', 'lz4', 'zstd'): + for dtype in (numpy.int8, numpy.int16, numpy.int32, numpy.int64): + for nelems in (1024, 2048): + with self.subTest(cname=cname, dtype=dtype, nelems=nelems): + filter_ = self._test('bshuf', dtype, compressed=cname!='none', nelems=nelems, cname=cname) + self.assertEqual(filter_[2][3:5], (nelems, compression_ids[cname])) + @unittest.skipUnless(should_test("blosc"), "Blosc filter not available") def testBlosc(self): """Write/read test with blosc filter plugin"""