diff --git a/Makefile b/Makefile
index adba9cad..53abb346 100644
--- a/Makefile
+++ b/Makefile
@@ -27,10 +27,8 @@ BITSHUFFLE_UNPACKED:=$(TARGET)/bitshuffle-extracted.log
$(BITSHUFFLE_ARCHIVE):
@mkdir -p $(@D)
- curl -L -o$@ https://github.com/kiyo-masui/bitshuffle/archive/$(BITSHUFFLE_VERSION).tar.gz
$(BITSHUFFLE_UNPACKED): $(BITSHUFFLE_ARCHIVE)
- $(TAR) xvfz $< -C $(TARGET)
touch $@
$(BITSHUFFLE_SRC): $(BITSHUFFLE_UNPACKED)
@@ -67,18 +65,13 @@ endif
$(SNAPPY_ARCHIVE):
@mkdir -p $(@D)
- curl -L -o$@ https://github.com/google/snappy/releases/download/$(SNAPPY_VERSION)/snappy-$(SNAPPY_VERSION).tar.gz
$(SNAPPY_UNPACKED): $(SNAPPY_ARCHIVE)
- $(TAR) xvfz $< -C $(TARGET)
touch $@
$(SNAPPY_GIT_UNPACKED):
@mkdir -p $(SNAPPY_OUT)
- rm -rf $(SNAPPY_SRC_DIR)
@mkdir -p $(SNAPPY_SRC_DIR)
- git clone $(SNAPPY_GIT_REPO_URL) $(SNAPPY_SRC_DIR)
- git --git-dir=$(SNAPPY_SRC_DIR)/.git --work-tree=$(SNAPPY_SRC_DIR) checkout -b local/snappy-$(SNAPPY_VERSION) $(SNAPPY_GIT_REV)
touch $@
$(SNAPPY_CMAKE_CACHE): $(SNAPPY_GIT_UNPACKED)
diff --git a/Makefile.common b/Makefile.common
index 8c060e35..d8a966b2 100755
--- a/Makefile.common
+++ b/Makefile.common
@@ -99,7 +99,7 @@ ifeq ($(IBM_JDK_7),)
else
Linux-x86_64_CXXFLAGS := -include $(IBM_JDK_LIB)/jni_md.h -include $(IBM_JDK_LIB)/jniport.h -I$(JAVA_HOME)/include -O2 -fPIC -fvisibility=hidden -m64 -std=c++11
endif
-Linux-x86_64_LINKFLAGS := -shared -static-libgcc -static-libstdc++
+Linux-x86_64_LINKFLAGS := -shared -static-libgcc -lstdc++
Linux-x86_64_LIBNAME := libsnappyjava.so
Linux-x86_64_SNAPPY_FLAGS :=
diff --git a/pom.xml b/pom.xml
new file mode 100644
index 00000000..32d2c862
--- /dev/null
+++ b/pom.xml
@@ -0,0 +1,110 @@
+
+
+ 4.0.0
+ org.xerial.snappy
+ snappy-java
+ jar
+ snappy-java: A fast compression/decompression library
+ 1.1.10.1
+ snappy-java
+
+ xerial.org
+
+ https://github.com/xerial/snappy-java
+
+
+ The Apache Software License, Version 2.0
+ http://www.apache.org/licenses/LICENSE-2.0.txt
+ repo
+
+
+
+
+ leo
+ Taro L. Saito
+ leo@xerial.org
+ Xerial Project
+
+ Architect
+ Project Manager
+ Chief Developer
+
+ +9
+
+
+
+ GitHub
+ http://github.com/xerial/snappy-java/issues/list
+
+ 2011
+
+ scm:git@github.com:xerial/snappy-java.git
+ scm:git:git@github.com:xerial/snappy-java.git
+ git@github.com:xerial/snappy-java.git
+
+
+ 1.8
+ 1.8
+
+
+
+ junit
+ junit
+ 4.13
+ test
+
+
+ org.codehaus.plexus
+ plexus-classworlds
+ 2.7.0
+ test
+
+
+ org.xerial.java
+ xerial-core
+ 2.1
+ test
+
+
+ org.wvlet.airframe
+ airframe-log_2.12
+ 23.1.4
+ test
+
+
+ org.osgi
+ org.osgi.core
+ 6.0.0
+ provided
+
+
+ org.apache.hadoop
+ hadoop-common
+ 2.10.2
+ test
+
+
+ org.xerial.snappy
+ snappy-java
+
+
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-source-plugin
+
+
+ attach-sources
+
+ jar
+
+
+
+
+
+
+
diff --git a/target/bitshuffle-0.3.4/.gitignore b/target/bitshuffle-0.3.4/.gitignore
new file mode 100644
index 00000000..d8d6cf49
--- /dev/null
+++ b/target/bitshuffle-0.3.4/.gitignore
@@ -0,0 +1,77 @@
+## C
+
+# Object files
+*.o
+*.ko
+*.obj
+*.elf
+
+# Libraries
+*.lib
+*.a
+
+# Shared objects (inc. Windows DLLs)
+*.dll
+*.so
+*.so.*
+*.dylib
+
+# Executables
+*.exe
+*.out
+*.app
+*.i*86
+*.x86_64
+*.hex
+
+
+## Python
+*.py[cod]
+
+# C extensions
+*.so
+
+# Packages
+*.egg
+*.egg-info
+dist
+build
+eggs
+parts
+bin
+var
+sdist
+develop-eggs
+.installed.cfg
+lib
+lib64
+__pycache__
+
+# Installer logs
+pip-log.txt
+
+# Unit test / coverage reports
+.coverage
+.tox
+nosetests.xml
+
+# Translations
+*.mo
+
+# Mr Developer
+.mr.developer.cfg
+.project
+.pydevproject
+
+# Documentation builds
+doc/_build
+doc/generated
+
+## Editor files and backups.
+*.swp
+*.swo
+
+# Generated files
+bitshuffle/ext.c
+bitshuffle/h5.c
+
diff --git a/target/bitshuffle-0.3.4/.travis.yml b/target/bitshuffle-0.3.4/.travis.yml
new file mode 100644
index 00000000..7b5b4994
--- /dev/null
+++ b/target/bitshuffle-0.3.4/.travis.yml
@@ -0,0 +1,33 @@
+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/target/bitshuffle-0.3.4/LICENSE b/target/bitshuffle-0.3.4/LICENSE
new file mode 100644
index 00000000..1365ed69
--- /dev/null
+++ b/target/bitshuffle-0.3.4/LICENSE
@@ -0,0 +1,21 @@
+Bitshuffle - Filter for improving compression of typed binary data.
+
+Copyright (c) 2014 Kiyoshi Masui (kiyo@physics.ubc.ca)
+
+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.
diff --git a/target/bitshuffle-0.3.4/MANIFEST.in b/target/bitshuffle-0.3.4/MANIFEST.in
new file mode 100644
index 00000000..00746c64
--- /dev/null
+++ b/target/bitshuffle-0.3.4/MANIFEST.in
@@ -0,0 +1,10 @@
+recursive-include src *.h *.c
+recursive-include bitshuffle *.pyx
+recursive-include lz4 *.h *.c
+recursive-include lzf *.h *.c
+include setup.cfg.example
+include LICENSE
+include README.rst
+include requirements.txt
+exclude setup.cfg
+
diff --git a/target/bitshuffle-0.3.4/README.rst b/target/bitshuffle-0.3.4/README.rst
new file mode 100644
index 00000000..343b4c62
--- /dev/null
+++ b/target/bitshuffle-0.3.4/README.rst
@@ -0,0 +1,240 @@
+==========
+Bitshuffle
+==========
+
+Filter for improving compression of typed binary data.
+
+Bitshuffle is an algorithm that rearranges typed, binary data for improving
+compression, as well as a python/C package that implements this algorithm
+within the Numpy framework.
+
+The library can be used along side HDF5 to compress and decompress datasets and
+is integrated through the `dynamically loaded filters`_ framework. Bitshuffle
+is HDF5 filter number ``32008``.
+
+Algorithmically, Bitshuffle is closely related to HDF5's `Shuffle filter`_
+except it operates at the bit level instead of the byte level. Arranging a
+typed data array in to a matrix with the elements as the rows and the bits
+within the elements as the columns, Bitshuffle "transposes" the matrix,
+such that all the least-significant-bits are in a row, etc. This transpose
+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
+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
+each block after shuffling [2]_.
+
+The Bitshuffle algorithm relies on neighbouring elements of a dataset being
+highly correlated to improve data compression. Any correlations that span at
+least 24 elements of the dataset may be exploited to improve compression.
+
+Bitshuffle was designed with performance in mind. On most machines the
+time required for Bitshuffle+LZ4 is insignificant compared to the time required
+to read or write the compressed data to disk. Because it is able to exploit the
+SSE and AVX instruction sets present on modern Intel and AMD processors, on
+these machines compression is only marginally slower than an out-of-cache
+memory copy. On modern x86 processors you can expect Bitshuffle to have a
+throughput of roughly 1 byte per clock cycle, and on the Haswell generation of
+Intel processors (2013) and later, you can expect up to 2 bytes per clock
+cycle. In addition, Bitshuffle is parallelized using OpenMP.
+
+As a bonus, Bitshuffle ships with a dynamically loaded version of
+`h5py`'s LZF compression filter, such that the filter can be transparently
+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
+ compression, this has the tremendous advantage that the block is
+ already in the L1 cache.
+
+.. _`dynamically loaded filters`: http://www.hdfgroup.org/HDF5/doc/Advanced/DynamicallyLoadedFilters/HDF5DynamicallyLoadedFilters.pdf
+
+.. _`Shuffle filter`: http://www.hdfgroup.org/HDF5/doc_resource/H5Shuffle_Perf.pdf
+
+.. _LZF: http://oldhome.schmorp.de/marc/liblzf.html
+
+.. _LZ4: https://code.google.com/p/lz4/
+
+
+Applications
+------------
+
+Bitshuffle might be right for your application if:
+
+- You need to compress typed binary data.
+- Your data is arranged such that adjacent elements over the fastest varying
+ index of your dataset are similar (highly correlated).
+- A special case of the previous point is if you are only exercising a subset
+ of the bits in your data-type, as is often true of integer data.
+- You need both high compression ratios and high performance.
+
+
+Comparing Bitshuffle to other compression algorithms and HDF5 filters:
+
+- Bitshuffle is less general than many other compression algorithms.
+ To achieve good compression ratios, consecutive elements of your data must
+ be highly correlated.
+- For the right datasets, Bitshuffle is one of the few compression
+ algorithms that promises both high throughput and high compression ratios.
+- Bitshuffle should have roughly the same throughput as Shuffle, but
+ may obtain higher compression ratios.
+- The MAFISC_ filter actually includes something similar to Bitshuffle as one of
+ its prefilters, However, MAFICS's emphasis is on obtaining high compression
+ ratios at all costs, sacrificing throughput.
+
+.. _MAFISC: http://wr.informatik.uni-hamburg.de/research/projects/icomex/mafisc
+
+
+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.
+
+To install::
+
+ python setup.py install [--h5plugin [--h5plugin-dir=spam]]
+
+To get finer control of installation options, including whether to compile
+with OpenMP multi-threading, copy the ``setup.cfg.example`` to ``setup.cfg``
+and edit the values therein.
+
+If using the dynamically loaded HDF5 filter (which gives you access to the
+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``.
+
+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
+-----------------
+
+The `bitshuffle` module contains routines for shuffling and unshuffling
+Numpy arrays.
+
+If installed with the dynamically loaded filter plugins, Bitshuffle can be used
+in conjunction with HDF5 both inside and outside of python, in the same way as
+any other filter; simply by specifying the filter number ``32008``. Otherwise
+the filter will be available only within python and only after importing
+`bitshuffle.h5`. Reading Bitshuffle encoded datasets will be transparent.
+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
+high level interface, as in the example below.
+
+
+Example h5py
+------------
+::
+
+ import h5py
+ import numpy
+ import bitshuffle.h5
+
+ print(h5py.__version__) # >= '2.5.0'
+
+ f = h5py.File(filename, "w")
+
+ # block_size = 0 let Bitshuffle choose its value
+ block_size = 0
+
+ dataset = f.create_dataset(
+ "data",
+ (100, 100, 100),
+ compression=bitshuffle.h5.H5FILTER,
+ compression_opts=(block_size, bitshuffle.h5.H5_COMPRESS_LZ4),
+ dtype='float32',
+ )
+
+ # create some random data
+ array = numpy.random.rand(100, 100, 100)
+ array = array.astype('float32')
+
+ dataset[:] = array
+
+ f.close()
+
+
+Usage from C
+------------
+
+If you wish to use Bitshuffle in your C program and would prefer not to use the
+HDF5 dynamically loaded filter, the C library in the ``src/`` directory is
+self-contained and complete.
+
+
+Usage from Java
+---------------
+
+You can use Bitshuffle even in Java and the routines for shuffling and unshuffling
+are ported into `snappy-java`_. To use the routines, you need to add the following
+dependency to your pom.xml::
+
+
+ org.xerial.snappy
+ snappy-java
+ 1.1.3-M1
+
+
+First, import org.xerial.snapy.BitShuffle in your Java code::
+
+ import org.xerial.snappy.BitShuffle;
+
+Then, you use them like this::
+
+ int[] data = new int[] {1, 3, 34, 43, 34};
+ byte[] shuffledData = BitShuffle.bitShuffle(data);
+ int[] result = BitShuffle.bitUnShuffleIntArray(shuffledData);
+
+.. _`snappy-java`: https://github.com/xerial/snappy-java
+
+
+Anaconda
+--------
+
+The conda package can be build via::
+
+ conda build conda-recipe
+
+
+For Best Results
+----------------
+
+Here are a few tips to help you get the most out of Bitshuffle:
+
+- For multi-dimensional datasets, order your data such that the fastest varying
+ dimension is the one over which your data is most correlated (have
+ values that change the least), or fake this using chunks.
+- To achieve the highest throughput, use a data type that is 64 *bytes* or
+ smaller. If you have a very large compound data type, consider adding a
+ dimension to your datasets instead.
+- To make full use of the SSE2 instruction set, use a data type whose size
+ is a multiple of 2 bytes. For the AVX2 instruction set, use a data type whose
+ size is a multiple of 4 bytes.
+
+
+Citing Bitshuffle
+-----------------
+
+Bitshuffle was initially described in
+http://dx.doi.org/10.1016/j.ascom.2015.07.002, pre-print available at
+http://arxiv.org/abs/1503.00638.
diff --git a/target/bitshuffle-0.3.4/bitshuffle/__init__.py b/target/bitshuffle-0.3.4/bitshuffle/__init__.py
new file mode 100644
index 00000000..8ad676c9
--- /dev/null
+++ b/target/bitshuffle-0.3.4/bitshuffle/__init__.py
@@ -0,0 +1,20 @@
+"""
+Filter for improving compression of typed binary data.
+
+Functions
+=========
+
+ using_SSE2
+ using_AVX2
+ bitshuffle
+ bitunshuffle
+ compress_lz4
+ decompress_lz4
+
+"""
+
+from __future__ import absolute_import
+
+
+from bitshuffle.ext import (__version__, bitshuffle, bitunshuffle, using_SSE2,
+ using_AVX2, compress_lz4, decompress_lz4)
diff --git a/target/bitshuffle-0.3.4/bitshuffle/ext.pyx b/target/bitshuffle-0.3.4/bitshuffle/ext.pyx
new file mode 100644
index 00000000..cd8a461f
--- /dev/null
+++ b/target/bitshuffle-0.3.4/bitshuffle/ext.pyx
@@ -0,0 +1,410 @@
+"""
+Wrappers for public and private bitshuffle routines
+
+"""
+
+from __future__ import absolute_import, division, print_function, unicode_literals
+
+import numpy as np
+
+cimport numpy as np
+cimport cython
+
+
+np.import_array()
+
+
+# Repeat each calculation this many times. For timing.
+cdef int REPEATC = 1
+#cdef int REPEATC = 32
+
+REPEAT = REPEATC
+
+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 bshuf_bitunshuffle(void *A, void *B, int size, int elem_size,
+ int block_size)
+ 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 bshuf_decompress_lz4(void *A, void *B, int size, int elem_size,
+ int block_size)
+ int BSHUF_VERSION_MAJOR
+ int BSHUF_VERSION_MINOR
+ int BSHUF_VERSION_POINT
+
+
+__version__ = str("%d.%d.%d").format(BSHUF_VERSION_MAJOR, BSHUF_VERSION_MINOR,
+ BSHUF_VERSION_POINT)
+
+
+# Prototypes from bitshuffle.c
+cdef extern int bshuf_copy(void *A, void *B, int size, int elem_size)
+cdef extern int bshuf_trans_byte_elem_scal(void *A, void *B, int size, int elem_size)
+cdef extern int bshuf_trans_byte_elem_SSE(void *A, void *B, int size, int elem_size)
+cdef extern int bshuf_trans_bit_byte_scal(void *A, void *B, int size, int elem_size)
+cdef extern int bshuf_trans_bit_byte_SSE(void *A, void *B, int size, int elem_size)
+cdef extern int bshuf_trans_bit_byte_AVX(void *A, void *B, int size, int elem_size)
+cdef extern int bshuf_trans_bitrow_eight(void *A, void *B, int size, int elem_size)
+cdef extern int bshuf_trans_bit_elem_AVX(void *A, void *B, int size, int elem_size)
+cdef extern int bshuf_trans_bit_elem_SSE(void *A, void *B, int size, int elem_size)
+cdef extern int bshuf_trans_bit_elem_scal(void *A, void *B, int size, int elem_size)
+cdef extern int bshuf_trans_byte_bitrow_SSE(void *A, void *B, int size, int elem_size)
+cdef extern int bshuf_trans_byte_bitrow_AVX(void *A, void *B, int size, int elem_size)
+cdef extern int bshuf_trans_byte_bitrow_scal(void *A, void *B, int size, int elem_size)
+cdef extern int bshuf_shuffle_bit_eightelem_scal(void *A, void *B, int size, int elem_size)
+cdef extern int bshuf_shuffle_bit_eightelem_SSE(void *A, void *B, int size, int elem_size)
+cdef extern int bshuf_shuffle_bit_eightelem_AVX(void *A, void *B, int size, int elem_size)
+cdef extern int bshuf_untrans_bit_elem_SSE(void *A, void *B, int size, int elem_size)
+cdef extern int bshuf_untrans_bit_elem_AVX(void *A, void *B, int size, int elem_size)
+cdef extern int bshuf_untrans_bit_elem_scal(void *A, void *B, int size, int elem_size)
+cdef extern int bshuf_trans_bit_elem(void *A, void *B, int size, int elem_size)
+cdef extern int bshuf_untrans_bit_elem(void *A, void *B, int size, int elem_size)
+
+
+ctypedef int (*Cfptr) (void *A, void *B, int size, int elem_size)
+
+
+def using_SSE2():
+ """Whether compiled using SSE2 instructions."""
+ if bshuf_using_SSE2():
+ return True
+ else:
+ return False
+
+
+def using_AVX2():
+ """Whether compiled using AVX2 instructions."""
+ if bshuf_using_AVX2():
+ return True
+ else:
+ return False
+
+
+def _setup_arr(arr):
+ shape = tuple(arr.shape)
+ 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
+ out = np.empty(shape, dtype=dtype)
+ return out, size, itemsize
+
+
+@cython.boundscheck(False)
+@cython.wraparound(False)
+cdef _wrap_C_fun(Cfptr fun, np.ndarray arr):
+ """Wrap a C function with standard call signature."""
+
+ cdef int ii, size, itemsize, count=0
+ cdef np.ndarray out
+ out, size, itemsize = _setup_arr(arr)
+
+ 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]
+
+ for ii in range(REPEATC):
+ count = fun(arr_ptr, out_ptr, size, itemsize)
+ if count < 0:
+ msg = "Failed. Error code %d."
+ excp = RuntimeError(msg % count, count)
+ raise excp
+ return out
+
+
+def copy(np.ndarray arr not None):
+ """Copies the data.
+
+ For testing and profiling purposes.
+
+ """
+ return _wrap_C_fun(&bshuf_copy, arr)
+
+
+def trans_byte_elem_scal(np.ndarray arr not None):
+ """Transpose bytes within words but not bits.
+
+ """
+ return _wrap_C_fun(&bshuf_trans_byte_elem_scal, arr)
+
+
+def trans_byte_elem_SSE(np.ndarray arr not None):
+ """Transpose bytes within array elements.
+
+ """
+ return _wrap_C_fun(&bshuf_trans_byte_elem_SSE, arr)
+
+
+def trans_bit_byte_scal(np.ndarray arr not None):
+ return _wrap_C_fun(&bshuf_trans_bit_byte_scal, arr)
+
+
+def trans_bit_byte_SSE(np.ndarray arr not None):
+ return _wrap_C_fun(&bshuf_trans_bit_byte_SSE, arr)
+
+
+def trans_bit_byte_AVX(np.ndarray arr not None):
+ return _wrap_C_fun(&bshuf_trans_bit_byte_AVX, arr)
+
+
+def trans_bitrow_eight(np.ndarray arr not None):
+ return _wrap_C_fun(&bshuf_trans_bitrow_eight, arr)
+
+
+def trans_bit_elem_AVX(np.ndarray arr not None):
+ return _wrap_C_fun(&bshuf_trans_bit_elem_AVX, arr)
+
+
+def trans_bit_elem_scal(np.ndarray arr not None):
+ return _wrap_C_fun(&bshuf_trans_bit_elem_scal, arr)
+
+
+def trans_bit_elem_SSE(np.ndarray arr not None):
+ return _wrap_C_fun(&bshuf_trans_bit_elem_SSE, arr)
+
+
+def trans_byte_bitrow_SSE(np.ndarray arr not None):
+ return _wrap_C_fun(&bshuf_trans_byte_bitrow_SSE, arr)
+
+
+def trans_byte_bitrow_AVX(np.ndarray arr not None):
+ return _wrap_C_fun(&bshuf_trans_byte_bitrow_AVX, arr)
+
+
+def trans_byte_bitrow_scal(np.ndarray arr not None):
+ return _wrap_C_fun(&bshuf_trans_byte_bitrow_scal, arr)
+
+
+def shuffle_bit_eightelem_scal(np.ndarray arr not None):
+ return _wrap_C_fun(&bshuf_shuffle_bit_eightelem_scal, arr)
+
+
+def shuffle_bit_eightelem_SSE(np.ndarray arr not None):
+ return _wrap_C_fun(&bshuf_shuffle_bit_eightelem_SSE, arr)
+
+
+def shuffle_bit_eightelem_AVX(np.ndarray arr not None):
+ return _wrap_C_fun(&bshuf_shuffle_bit_eightelem_AVX, arr)
+
+
+def untrans_bit_elem_SSE(np.ndarray arr not None):
+ return _wrap_C_fun(&bshuf_untrans_bit_elem_SSE, arr)
+
+
+def untrans_bit_elem_AVX(np.ndarray arr not None):
+ return _wrap_C_fun(&bshuf_untrans_bit_elem_AVX, arr)
+
+
+def untrans_bit_elem_scal(np.ndarray arr not None):
+ return _wrap_C_fun(&bshuf_untrans_bit_elem_scal, arr)
+
+
+def trans_bit_elem(np.ndarray arr not None):
+ return _wrap_C_fun(&bshuf_trans_bit_elem, arr)
+
+
+def untrans_bit_elem(np.ndarray arr not None):
+ return _wrap_C_fun(&bshuf_untrans_bit_elem, arr)
+
+
+@cython.boundscheck(False)
+@cython.wraparound(False)
+def bitshuffle(np.ndarray arr not None, int block_size=0):
+ """Bitshuffle an array.
+
+ Output array is the same shape and data type as input array but underlying
+ buffer has been bitshuffled.
+
+ Parameters
+ ----------
+ arr : numpy array
+ Data to ne processed.
+ block_size : positive integer
+ Block size in number of elements. By default, block size is chosen
+ automatically.
+
+ Returns
+ -------
+ out : numpy array
+ Array with the same shape as input but underlying data has been
+ bitshuffled.
+
+ """
+
+ cdef int ii, size, itemsize, count=0
+ cdef np.ndarray out
+ out, size, itemsize = _setup_arr(arr)
+
+ 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]
+
+ 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)
+ raise excp
+ return out
+
+
+@cython.boundscheck(False)
+@cython.wraparound(False)
+def bitunshuffle(np.ndarray arr not None, int block_size=0):
+ """Bitshuffle an array.
+
+ Output array is the same shape and data type as input array but underlying
+ buffer has been un-bitshuffled.
+
+ Parameters
+ ----------
+ arr : numpy array
+ Data to ne processed.
+ block_size : positive integer
+ Block size in number of elements. Must match value used for shuffling.
+
+ Returns
+ -------
+ out : numpy array
+ Array with the same shape as input but underlying data has been
+ un-bitshuffled.
+
+ """
+
+ cdef int ii, size, itemsize, count=0
+ cdef np.ndarray out
+ out, size, itemsize = _setup_arr(arr)
+
+ 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]
+
+ 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)
+ raise excp
+ return out
+
+
+@cython.boundscheck(False)
+@cython.wraparound(False)
+def compress_lz4(np.ndarray arr not None, int block_size=0):
+ """Bitshuffle then compress an array using LZ4.
+
+ Parameters
+ ----------
+ arr : numpy array
+ Data to ne processed.
+ block_size : positive integer
+ Block size in number of elements. By default, block size is chosen
+ automatically.
+
+ 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_lz4_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]
+ 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)
+ raise excp
+ return out[:count]
+
+
+@cython.boundscheck(False)
+@cython.wraparound(False)
+def decompress_lz4(np.ndarray arr not None, shape, dtype, int block_size=0):
+ """Decompress a buffer using LZ4 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]
+ 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)
+ 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/target/bitshuffle-0.3.4/bitshuffle/h5.pyx b/target/bitshuffle-0.3.4/bitshuffle/h5.pyx
new file mode 100644
index 00000000..cd7a0f05
--- /dev/null
+++ b/target/bitshuffle-0.3.4/bitshuffle/h5.pyx
@@ -0,0 +1,205 @@
+"""
+HDF5 support for Bitshuffle.
+
+To read a dataset that uses the Bitshuffle filter using h5py, simply import
+this module (unless you have installed the Bitshuffle dynamically loaded
+filter, in which case importing this module is unnecessary).
+
+To create a new dataset that includes the Bitshuffle filter, use one of the
+convenience functions provided.
+
+
+Constants
+=========
+
+ H5FILTER : The Bitshuffle HDF5 filter integer identifier.
+ H5_COMPRESS_LZ4 : Filter option flag for LZ4 compression.
+
+Functions
+=========
+
+ create_dataset
+ create_bitshuffle_lzf_dataset
+ create_bitshuffle_compressed_dataset
+
+Examples
+========
+
+ >>> import numpy as np
+ >>> import h5py
+ >>> import bitshuffle.h5
+
+ >>> shape = (123, 456)
+ >>> chunks = (10, 456)
+ >>> dtype = np.float64
+
+ >>> f = h5py.File("tmp_test.h5")
+ >>> bitshuffle.h5.create_bitshuffle_compressed_dataset(
+ f, "some_data", shape, dtype, chunks)
+ >>> f["some_data"][:] = 42
+
+"""
+
+from __future__ import absolute_import, division, print_function, unicode_literals
+
+import numpy
+import h5py
+from h5py import h5d, h5s, h5t, h5p, filters
+
+cimport cython
+
+
+cdef extern from b"bshuf_h5filter.h":
+ int bshuf_register_h5filter()
+ int BSHUF_H5FILTER
+ int BSHUF_H5_COMPRESS_LZ4
+
+cdef int LZF_FILTER = 32000
+
+H5FILTER = BSHUF_H5FILTER
+H5_COMPRESS_LZ4 = BSHUF_H5_COMPRESS_LZ4
+
+
+def register_h5_filter():
+ ret = bshuf_register_h5filter()
+ if ret < 0:
+ raise RuntimeError("Failed to register bitshuffle HDF5 filter.", ret)
+
+
+register_h5_filter()
+
+
+def create_dataset(parent, name, shape, dtype, chunks=None, maxshape=None,
+ fillvalue=None, track_times=None,
+ filter_pipeline=(), filter_flags=None, filter_opts=None):
+ """Create a dataset with an arbitrary filter pipeline.
+
+ Return a new low-level dataset identifier.
+
+ Much of this code is copied from h5py, but couldn't reuse much code due to
+ unstable API.
+
+ """
+
+ if hasattr(filter_pipeline, "__getitem__"):
+ filter_pipeline = list(filter_pipeline)
+ else:
+ filter_pipeline = [filter_pipeline]
+ filter_flags = [filter_flags]
+ filter_opts = [filter_opts]
+ nfilters = len(filter_pipeline)
+ if filter_flags is None:
+ filter_flags = [None] * nfilters
+ if filter_opts is None:
+ filter_opts = [None] * nfilters
+ if not len(filter_flags) == nfilters or not len(filter_opts) == nfilters:
+ msg = "Supplied incompatible number of filters, flags, and options."
+ raise ValueError(msg)
+
+ shape = tuple(shape)
+
+ 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()
+ 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))
+ raise ValueError(errmsg)
+
+ if isinstance(dtype, h5py.Datatype):
+ # Named types are used as-is
+ tid = dtype.id
+ dtype = tid.dtype # Following code needs this
+ else:
+ # Validate dtype
+ dtype = numpy.dtype(dtype)
+ tid = h5t.py_create(dtype, logical=1)
+
+ if shape == ():
+ if any((chunks, filter_pipeline)):
+ raise TypeError("Scalar datasets don't support chunk/filter options")
+ if maxshape and maxshape != ():
+ raise TypeError("Scalar datasets cannot be extended")
+ return h5p.create(h5p.DATASET_CREATE)
+
+ def rq_tuple(tpl, name):
+ """Check if chunks/maxshape match dataset rank"""
+ if tpl in (None, True):
+ return
+ try:
+ tpl = tuple(tpl)
+ except TypeError:
+ raise TypeError('"%s" argument must be None or a sequence object' % name)
+ if len(tpl) != len(shape):
+ raise ValueError('"%s" must have same rank as dataset shape' % name)
+
+ rq_tuple(chunks, 'chunks')
+ rq_tuple(maxshape, 'maxshape')
+
+ if (chunks is True) or (chunks is None and filter_pipeline):
+ chunks = filters.guess_chunk(shape, maxshape, dtype.itemsize)
+
+ if maxshape is True:
+ maxshape = (None,)*len(shape)
+
+ dcpl = h5p.create(h5p.DATASET_CREATE)
+ if chunks is not None:
+ dcpl.set_chunk(chunks)
+ dcpl.set_fill_time(h5d.FILL_TIME_ALLOC) # prevent resize glitch
+
+ if fillvalue is not None:
+ fillvalue = numpy.array(fillvalue)
+ dcpl.set_fill_value(fillvalue)
+
+ if track_times in (True, False):
+ dcpl.set_obj_track_times(track_times)
+ elif track_times is not None:
+ raise TypeError("track_times must be either True or False")
+
+ for ii in range(nfilters):
+ this_filter = filter_pipeline[ii]
+ this_flags = filter_flags[ii]
+ this_opts = filter_opts[ii]
+ if this_flags is None:
+ this_flags = 0
+ if this_opts is None:
+ this_opts = ()
+ dcpl.set_filter(this_filter, this_flags, this_opts)
+
+ if maxshape is not None:
+ maxshape = tuple(m if m is not None else h5s.UNLIMITED
+ for m in maxshape)
+ sid = h5s.create_simple(shape, maxshape)
+
+ dset_id = h5d.create(parent.id, name, tid, sid, dcpl=dcpl)
+
+ return dset_id
+
+
+def create_bitshuffle_lzf_dataset(parent, name, shape, dtype, chunks=None,
+ maxshape=None, fillvalue=None,
+ track_times=None):
+ """Create dataset with a filter pipeline including bitshuffle and LZF"""
+
+ filter_pipeline = [H5FILTER, LZF_FILTER]
+ dset_id = create_dataset(parent, name, shape, dtype, chunks=chunks,
+ filter_pipeline=filter_pipeline, maxshape=maxshape,
+ fillvalue=fillvalue, track_times=track_times)
+ return dset_id
+
+
+def create_bitshuffle_compressed_dataset(parent, name, shape, dtype,
+ chunks=None, maxshape=None,
+ fillvalue=None, track_times=None):
+ """Create dataset with bitshuffle+internal LZ4 compression."""
+
+ filter_pipeline = [H5FILTER,]
+ filter_opts = [(0, H5_COMPRESS_LZ4)]
+ dset_id = create_dataset(parent, name, shape, dtype, chunks=chunks,
+ filter_pipeline=filter_pipeline,
+ filter_opts=filter_opts, maxshape=maxshape,
+ fillvalue=fillvalue, track_times=track_times)
+ return dset_id
+
+
diff --git a/target/bitshuffle-0.3.4/bitshuffle/tests/__init__.py b/target/bitshuffle-0.3.4/bitshuffle/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/target/bitshuffle-0.3.4/bitshuffle/tests/data/regression_0.1.3.h5 b/target/bitshuffle-0.3.4/bitshuffle/tests/data/regression_0.1.3.h5
new file mode 100644
index 00000000..ee8373f7
Binary files /dev/null and b/target/bitshuffle-0.3.4/bitshuffle/tests/data/regression_0.1.3.h5 differ
diff --git a/target/bitshuffle-0.3.4/bitshuffle/tests/make_regression_tdata.py b/target/bitshuffle-0.3.4/bitshuffle/tests/make_regression_tdata.py
new file mode 100644
index 00000000..07045383
--- /dev/null
+++ b/target/bitshuffle-0.3.4/bitshuffle/tests/make_regression_tdata.py
@@ -0,0 +1,42 @@
+"""
+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/target/bitshuffle-0.3.4/bitshuffle/tests/test_ext.py b/target/bitshuffle-0.3.4/bitshuffle/tests/test_ext.py
new file mode 100644
index 00000000..11be1ffd
--- /dev/null
+++ b/target/bitshuffle-0.3.4/bitshuffle/tests/test_ext.py
@@ -0,0 +1,588 @@
+from __future__ import absolute_import, division, print_function, unicode_literals
+
+import unittest
+import time
+import timeit
+
+import numpy as np
+from numpy import random
+
+from bitshuffle import ext
+
+
+# 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.
+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']
+
+
+class TestProfile(unittest.TestCase):
+
+ def setUp(self):
+ n = 1024 # bytes.
+ if TIME:
+ n *= TIME
+ # Almost random bits, but now quite. All bits exercised (to fully test
+ # transpose) but still slightly compresible.
+ self.data = random.randint(0, 200, n).astype(np.uint8)
+ self.fun = ext.copy
+ self.check = None
+ self.check_data = None
+ self.case = "None"
+
+ def tearDown(self):
+ """Performs all tests and timings."""
+ if TIME:
+ reps = 10
+ else:
+ reps = 1
+ delta_ts = []
+ try:
+ for ii in range(reps):
+ t0 = time.time()
+ 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()):
+ return
+ if (len(err.args) > 1 and (err.args[1] == -12)
+ and not ext.using_AVX2()):
+ return
+ else:
+ raise
+ delta_t = min(delta_ts)
+ 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
+ if TIME:
+ print("%-20s: %5.2f s/GB, %5.2f GB/s" % (self.case, 1./speed, speed))
+ if not self.check is 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:
+ ans = self.check_data.view(np.uint8)
+ self.assertTrue(np.all(ans == out.view(np.uint8)))
+
+ def test_00_copy(self):
+ self.case = "copy"
+ self.fun = ext.copy
+ self.check = lambda x: x
+
+ def test_01a_trans_byte_elem_scal_16(self):
+ self.case = "byte T elem scal 16"
+ self.data = self.data.view(np.int16)
+ self.fun = ext.trans_byte_elem_scal
+ self.check = trans_byte_elem
+
+ def test_01b_trans_byte_elem_scal_32(self):
+ self.case = "byte T elem scal 32"
+ self.data = self.data.view(np.int32)
+ self.fun = ext.trans_byte_elem_scal
+ self.check = trans_byte_elem
+
+ def test_01c_trans_byte_elem_scal_64(self):
+ self.case = "byte T elem scal 64"
+ self.data = self.data.view(np.int64)
+ self.fun = ext.trans_byte_elem_scal
+ self.check = trans_byte_elem
+
+ def test_01d_trans_byte_elem_16(self):
+ self.case = "byte T elem SSE 16"
+ self.data = self.data.view(np.int16)
+ self.fun = ext.trans_byte_elem_SSE
+ self.check = trans_byte_elem
+
+ def test_01e_trans_byte_elem_32(self):
+ self.case = "byte T elem SSE 32"
+ self.data = self.data.view(np.float32)
+ self.fun = ext.trans_byte_elem_SSE
+ self.check = trans_byte_elem
+
+ def test_01f_trans_byte_elem_64(self):
+ self.case = "byte T elem SSE 64"
+ self.data = self.data.view(np.float64)
+ self.fun = ext.trans_byte_elem_SSE
+ self.check = trans_byte_elem
+
+ def test_01g_trans_byte_elem_128(self):
+ self.case = "byte T elem SSE 128"
+ self.data = self.data.view(np.complex128)
+ self.fun = ext.trans_byte_elem_SSE
+ self.check = trans_byte_elem
+
+ 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)])
+ self.data = self.data[:n].view(dt)
+ self.fun = ext.trans_byte_elem_SSE
+ self.check = trans_byte_elem
+
+ 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)])
+ self.data = self.data[:n].view(dt)
+ self.fun = ext.trans_byte_elem_SSE
+ self.check = trans_byte_elem
+
+ def test_03a_trans_bit_byte(self):
+ self.case = "bit T byte scal 64"
+ self.data = self.data.view(np.float64)
+ self.fun = ext.trans_bit_byte_scal
+ self.check = trans_bit_byte
+
+ def test_03d_trans_bit_byte_SSE(self):
+ self.case = "bit T byte SSE 64"
+ self.data = self.data.view(np.float64)
+ self.fun = ext.trans_bit_byte_SSE
+ self.check = trans_bit_byte
+
+ def test_03f_trans_bit_byte_AVX(self):
+ self.case = "bit T byte AVX 64"
+ self.data = self.data.view(np.float64)
+ self.fun = ext.trans_bit_byte_AVX
+ self.check = trans_bit_byte
+
+ def test_03g_trans_bit_byte_AVX_32(self):
+ self.case = "bit T byte AVX 32"
+ self.data = self.data.view(np.float32)
+ self.fun = ext.trans_bit_byte_AVX
+ self.check = trans_bit_byte
+
+ def test_04a_trans_bit_elem_AVX(self):
+ self.case = "bit T elem AVX 64"
+ self.data = self.data.view(np.float64)
+ self.fun = ext.trans_bit_elem_AVX
+ self.check = trans_bit_elem
+
+ def test_04b_trans_bit_elem_AVX_128(self):
+ self.case = "bit T elem AVX 128"
+ self.data = self.data.view(np.complex128)
+ self.fun = ext.trans_bit_elem_AVX
+ self.check = trans_bit_elem
+
+ def test_04c_trans_bit_elem_AVX_32(self):
+ self.case = "bit T elem AVX 32"
+ self.data = self.data.view(np.float32)
+ self.fun = ext.trans_bit_elem_AVX
+ self.check = trans_bit_elem
+
+ def test_04d_trans_bit_elem_AVX_16(self):
+ self.case = "bit T elem AVX 16"
+ self.data = self.data.view(np.int16)
+ self.fun = ext.trans_bit_elem_AVX
+ self.check = trans_bit_elem
+
+ def test_04e_trans_bit_elem_64(self):
+ self.case = "bit T elem scal 64"
+ self.data = self.data.view(np.float64)
+ self.fun = ext.trans_bit_elem_scal
+ self.check = trans_bit_elem
+
+ def test_04f_trans_bit_elem_SSE_32(self):
+ self.case = "bit T elem SSE 32"
+ self.data = self.data.view(np.float32)
+ self.fun = ext.trans_bit_elem_SSE
+ self.check = trans_bit_elem
+
+ def test_04g_trans_bit_elem_SSE_64(self):
+ self.case = "bit T elem SSE 64"
+ self.data = self.data.view(np.float64)
+ self.fun = ext.trans_bit_elem_SSE
+ self.check = trans_bit_elem
+
+ def test_06a_untrans_bit_elem_16(self):
+ self.case = "bit U elem SSE 16"
+ pre_trans = self.data.view(np.int16)
+ self.data = trans_bit_elem(pre_trans)
+ self.fun = ext.untrans_bit_elem_SSE
+ self.check_data = pre_trans
+
+ def test_06b_untrans_bit_elem_128(self):
+ self.case = "bit U elem SSE 128"
+ pre_trans = self.data.view(np.complex128)
+ self.data = trans_bit_elem(pre_trans)
+ self.fun = ext.untrans_bit_elem_SSE
+ self.check_data = pre_trans
+
+ def test_06c_untrans_bit_elem_32(self):
+ self.case = "bit U elem SSE 32"
+ pre_trans = self.data.view(np.float32)
+ self.data = trans_bit_elem(pre_trans)
+ self.fun = ext.untrans_bit_elem_SSE
+ self.check_data = pre_trans
+
+ def test_06d_untrans_bit_elem_32(self):
+ self.case = "bit U elem AVX 32"
+ pre_trans = self.data.view(np.float32)
+ self.data = trans_bit_elem(pre_trans)
+ self.fun = ext.untrans_bit_elem_AVX
+ self.check_data = pre_trans
+
+ def test_06e_untrans_bit_elem_64(self):
+ self.case = "bit U elem SSE 64"
+ pre_trans = self.data.view(np.float64)
+ self.data = trans_bit_elem(pre_trans)
+ self.fun = ext.untrans_bit_elem_SSE
+ self.check_data = pre_trans
+
+ def test_06f_untrans_bit_elem_64(self):
+ self.case = "bit U elem AVX 64"
+ pre_trans = self.data.view(np.float64)
+ self.data = trans_bit_elem(pre_trans)
+ self.fun = ext.untrans_bit_elem_AVX
+ self.check_data = pre_trans
+
+ def test_06g_untrans_bit_elem_64(self):
+ self.case = "bit U elem scal 64"
+ pre_trans = self.data.view(np.float64)
+ self.data = trans_bit_elem(pre_trans)
+ self.fun = ext.untrans_bit_elem_scal
+ self.check_data = pre_trans
+
+ def test_07a_trans_byte_bitrow_64(self):
+ self.case = "byte T row scal 64"
+ self.data = self.data.view(np.float64)
+ self.fun = ext.trans_byte_bitrow_scal
+
+ def test_07b_trans_byte_bitrow_SSE_64(self):
+ self.case = "byte T row SSE 64"
+ self.data = self.data.view(np.float64)
+ self.fun = ext.trans_byte_bitrow_SSE
+ self.check = ext.trans_byte_bitrow_scal
+
+ def test_07c_trans_byte_bitrow_AVX_64(self):
+ self.case = "byte T row AVX 64"
+ self.data = self.data.view(np.float64)
+ self.fun = ext.trans_byte_bitrow_AVX
+ self.check = ext.trans_byte_bitrow_scal
+
+ def test_08a_shuffle_bit_eight_scal_64(self):
+ self.case = "bit S eight scal 64"
+ self.data = self.data.view(np.float64)
+ self.fun = ext.shuffle_bit_eightelem_scal
+
+ def test_08b_shuffle_bit_eight_SSE_64(self):
+ self.case = "bit S eight SSE 64"
+ self.data = self.data.view(np.float64)
+ self.fun = ext.shuffle_bit_eightelem_SSE
+ self.check = ext.shuffle_bit_eightelem_scal
+
+ def test_08c_shuffle_bit_eight_AVX_32(self):
+ self.case = "bit S eight AVX 32"
+ self.data = self.data.view(np.float32)
+ self.fun = ext.shuffle_bit_eightelem_AVX
+ self.check = ext.shuffle_bit_eightelem_scal
+
+ def test_08d_shuffle_bit_eight_AVX_64(self):
+ self.case = "bit S eight AVX 64"
+ self.data = self.data.view(np.float64)
+ self.fun = ext.shuffle_bit_eightelem_AVX
+ self.check = ext.shuffle_bit_eightelem_scal
+
+ def test_08e_shuffle_bit_eight_AVX_16(self):
+ self.case = "bit S eight AVX 16"
+ self.data = self.data.view(np.int16)
+ self.fun = ext.shuffle_bit_eightelem_AVX
+ self.check = ext.shuffle_bit_eightelem_scal
+
+ def test_08f_shuffle_bit_eight_AVX_128(self):
+ self.case = "bit S eight AVX 128"
+ self.data = self.data.view(np.complex128)
+ self.fun = ext.shuffle_bit_eightelem_AVX
+ self.check = ext.shuffle_bit_eightelem_scal
+
+ def test_09a_trans_bit_elem_scal_64(self):
+ self.case = "bit T elem scal 64"
+ self.data = self.data.view(np.float64)
+ self.fun = ext.trans_bit_elem_scal
+ self.check = trans_bit_elem
+
+ def test_09b_trans_bit_elem_SSE_64(self):
+ self.case = "bit T elem SSE 64"
+ self.data = self.data.view(np.float64)
+ self.fun = ext.trans_bit_elem_SSE
+ self.check = trans_bit_elem
+
+ def test_09c_trans_bit_elem_AVX_64(self):
+ self.case = "bit T elem AVX 64"
+ self.data = self.data.view(np.float64)
+ self.fun = ext.trans_bit_elem_AVX
+ self.check = trans_bit_elem
+
+ def test_09d_untrans_bit_elem_scal_64(self):
+ self.case = "bit U elem scal 64"
+ pre_trans = self.data.view(np.float64)
+ self.data = trans_bit_elem(pre_trans)
+ self.fun = ext.untrans_bit_elem_scal
+ self.check_data = pre_trans
+
+ def test_09e_untrans_bit_elem_SSE_64(self):
+ self.case = "bit U elem SSE 64"
+ pre_trans = self.data.view(np.float64)
+ self.data = trans_bit_elem(pre_trans)
+ self.fun = ext.untrans_bit_elem_SSE
+ self.check_data = pre_trans
+
+ def test_09f_untrans_bit_elem_AVX_64(self):
+ self.case = "bit U elem AVX 64"
+ pre_trans = self.data.view(np.float64)
+ self.data = trans_bit_elem(pre_trans)
+ self.fun = ext.untrans_bit_elem_AVX
+ self.check_data = pre_trans
+
+ def test_10a_bitshuffle_64(self):
+ self.case = "bitshuffle 64"
+ self.data = self.data.view(np.float64)
+ self.fun = lambda x: ext.bitshuffle(x, BLOCK)
+
+ def test_10b_bitunshuffle_64(self):
+ self.case = "bitunshuffle 64"
+ pre_trans = self.data.view(np.float64)
+ self.data = ext.bitshuffle(pre_trans, BLOCK)
+ self.fun = lambda x: ext.bitunshuffle(x, BLOCK)
+ self.check_data = pre_trans
+
+ 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)
+
+ 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.check_data = pre_trans
+
+"""
+Commented out to prevent nose from finding them.
+class TestDevCases(unittest.TestCase):
+
+ def deactivated_test_trans_byte_bitrow_AVX(self):
+ d = np.arange(256, dtype=np.uint32)
+ #d = ext.trans_bit_elem(d)
+ t = ext.trans_byte_bitrow_AVX(d).view(np.uint8)
+ t1 = ext.trans_byte_bitrow_SSE(d).view(np.uint8)
+ t.shape = (32, 32)
+ t1.shape = (32, 32)
+ #print t[:20,:18]
+ self.assertTrue(np.all(t == t1))
+
+ def deactivated_test_untrans_bit_elem(self):
+ d = np.arange(32, dtype=np.uint16)
+ #d = random.randint(0, 2**7, 256).astype(np.uint16)
+ d1 = ext.trans_bit_elem(d)
+ #print d
+ t = ext.untrans_bit_elem_AVX(d1)
+ #t1 = ext.untrans_bit_byte_scal(d1)
+ #print np.reshape(d1.view(np.uint8), (16, 4))
+ #print np.reshape(t1.view(np.uint8), (2, 32))
+ #print np.reshape(t2.view(np.uint8), (32, 2))
+ #print np.reshape(t.view(np.uint8), (32, 2))
+
+ def deactivated_test_trans_bit_byte(self):
+ d = np.arange(16, dtype=np.uint16)
+ t = ext.trans_bit_byte_scal(d)
+ #print t
+ t1 = trans_bit_byte(d)
+ #print t1
+ self.assertTrue(np.all(t == t1))
+
+ def deactivated_test_trans_byte_bitrow_SSE(self):
+ d = np.arange(256, dtype = np.uint8)
+ t = ext.trans_byte_bitrow_scal(d)
+ #print np.reshape(t, (32, 8))
+ t1 = ext.trans_byte_bitrow_SSE(d)
+ #print np.reshape(t1, (32, 8))
+ self.assertTrue(np.all(t == t1))
+
+ def deactivated_test_trans_byte_elem_SSE(self):
+ d = np.empty(16, dtype=([('a', 'u4'), ('b', 'u4'), ('c', 'u4')]))
+ d['a'] = np.arange(16) * 1
+ d['b'] = np.arange(16) * 2
+ d['c'] = np.arange(16) * 3
+ #print d.dtype.itemsize
+ #print np.reshape(d.view(np.uint8), (16, 12))
+ t1 = ext.trans_byte_elem_SSE(d)
+ #print np.reshape(t1.view(np.uint8), (12, 16))
+ t0 = trans_byte_elem(d)
+ #print np.reshape(t0.view(np.uint8), (12, 16))
+ self.assertTrue(np.all(t0.view(np.uint8) == t1.view(np.uint8)))
+
+ def deactivated_test_bitshuffle(self):
+ d = np.arange(128, dtype=np.uint16)
+ t1 = ext.bitshuffle(d)
+ #print t1
+ t2 = ext.bitunshuffle(t1)
+ #print t2
+ self.assertTrue(np.all(t2.view(np.uint8) == d.view(np.uint8)))
+"""
+
+
+class TestOddLengths(unittest.TestCase):
+
+ def setUp(self):
+ self.reps = 10
+ self.nmax = 128 * 8
+ #self.nmax = 4 * 8 # XXX
+ self.fun = ext.copy
+ self.check = lambda x: x
+
+ def test_trans_bit_elem_SSE(self):
+ self.fun = ext.trans_bit_elem_SSE
+ self.check = trans_bit_elem
+
+ def test_untrans_bit_elem_SSE(self):
+ self.fun = lambda x: ext.untrans_bit_elem_SSE(ext.trans_bit_elem(x))
+ self.check = lambda x: x
+
+ def test_trans_bit_elem_AVX(self):
+ self.fun = ext.trans_bit_elem_AVX
+ self.check = trans_bit_elem
+
+ def test_untrans_bit_elem_AVX(self):
+ self.fun = lambda x: ext.untrans_bit_elem_SSE(ext.trans_bit_elem(x))
+ self.check = lambda x: x
+
+ def test_trans_bit_elem_scal(self):
+ self.fun = ext.trans_bit_elem_scal
+ self.check = trans_bit_elem
+
+ def test_untrans_bit_elem_scal(self):
+ self.fun = lambda x: ext.untrans_bit_elem_scal(ext.trans_bit_elem(x))
+ self.check = lambda x: x
+
+ def test_trans_byte_elem_SSE(self):
+ self.fun = ext.trans_byte_elem_SSE
+ self.check = trans_byte_elem
+
+ def tearDown(self):
+ try:
+ for dtype in TEST_DTYPES:
+ itemsize = np.dtype(dtype).itemsize
+ nbyte_max = self.nmax * itemsize
+ dbuf = random.randint(0, 255, nbyte_max).astype(np.uint8)
+ dbuf = dbuf.view(dtype)
+ for ii in range(self.reps):
+ n = random.randint(0, self.nmax // 8, 1)[0] * 8
+ data = dbuf[:n]
+ out = self.fun(data).view(np.uint8)
+ 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()):
+ return
+ if (len(err.args) > 1 and (err.args[1] == -12)
+ and not ext.using_AVX2()):
+ return
+ else:
+ raise
+
+
+class TestBitShuffleCircle(unittest.TestCase):
+ """Ensure that final filter is circularly consistant for any data type and
+ any length buffer."""
+
+ def test_circle(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.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)))
+
+ def test_circle_with_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_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)))
+
+
+# Python implementations for checking results.
+
+def trans_byte_elem(arr):
+ dtype = arr.dtype
+ itemsize = dtype.itemsize
+ in_buf = arr.flat[:].view(np.uint8)
+ nelem = in_buf.size // itemsize
+ in_buf.shape = (nelem, itemsize)
+
+ 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]
+ return out_buf.flat[:].view(dtype)
+
+
+def trans_bit_byte(arr):
+ n = arr.size
+ dtype = arr.dtype
+ itemsize = dtype.itemsize
+ bits = np.unpackbits(arr.view(np.uint8))
+ 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_shuff = (bits.T).copy()
+ bits_shuff.shape = (n * itemsize, 8)
+ bits_shuff = bits_shuff[:,::-1]
+ arr_bt = np.packbits(bits_shuff.flat[:])
+ return arr_bt.view(dtype)
+
+
+def trans_bit_elem(arr):
+ n = arr.size
+ dtype = arr.dtype
+ itemsize = dtype.itemsize
+ bits = np.unpackbits(arr.view(np.uint8))
+ 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.shape = (n, itemsize * 8)
+ bits_shuff = (bits.T).copy()
+ bits_shuff.shape = (n * itemsize, 8)
+ 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/target/bitshuffle-0.3.4/bitshuffle/tests/test_h5filter.py b/target/bitshuffle-0.3.4/bitshuffle/tests/test_h5filter.py
new file mode 100644
index 00000000..6739b998
--- /dev/null
+++ b/target/bitshuffle-0.3.4/bitshuffle/tests/test_h5filter.py
@@ -0,0 +1,91 @@
+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/target/bitshuffle-0.3.4/bitshuffle/tests/test_h5plugin.py b/target/bitshuffle-0.3.4/bitshuffle/tests/test_h5plugin.py
new file mode 100644
index 00000000..220d55da
--- /dev/null
+++ b/target/bitshuffle-0.3.4/bitshuffle/tests/test_h5plugin.py
@@ -0,0 +1,83 @@
+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/target/bitshuffle-0.3.4/bitshuffle/tests/test_regression.py b/target/bitshuffle-0.3.4/bitshuffle/tests/test_regression.py
new file mode 100644
index 00000000..2862cace
--- /dev/null
+++ b/target/bitshuffle-0.3.4/bitshuffle/tests/test_regression.py
@@ -0,0 +1,40 @@
+"""
+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/target/bitshuffle-0.3.4/conda-recipe/bld.bat b/target/bitshuffle-0.3.4/conda-recipe/bld.bat
new file mode 100644
index 00000000..ccbb10f9
--- /dev/null
+++ b/target/bitshuffle-0.3.4/conda-recipe/bld.bat
@@ -0,0 +1,3 @@
+SET CONDA_HOME=%PREFIX%
+"%PYTHON%" setup.py install
+if errorlevel 1 exit 1
diff --git a/target/bitshuffle-0.3.4/conda-recipe/build.sh b/target/bitshuffle-0.3.4/conda-recipe/build.sh
new file mode 100644
index 00000000..34c3a689
--- /dev/null
+++ b/target/bitshuffle-0.3.4/conda-recipe/build.sh
@@ -0,0 +1,2 @@
+export CONDA_HOME=$PREFIX
+$PYTHON setup.py install # Python command to install the script
diff --git a/target/bitshuffle-0.3.4/conda-recipe/meta.yaml b/target/bitshuffle-0.3.4/conda-recipe/meta.yaml
new file mode 100644
index 00000000..ac227e2b
--- /dev/null
+++ b/target/bitshuffle-0.3.4/conda-recipe/meta.yaml
@@ -0,0 +1,27 @@
+package:
+ name: bitshuffle
+ version: 0.2.1
+source:
+ # git_url: https://github.com/kiyo-masui/bitshuffle.git
+ # git_rev: 0.2.1
+ path: ..
+ patches:
+ - setup.py.patch
+
+requirements:
+ build:
+ - python
+ - setuptools
+ - cython
+ - numpy
+ - h5py
+ - hdf5
+ run:
+ - python
+ - numpy
+ - h5py
+ - cython
+
+about:
+ home: https://github.com/kiyo-masui/bitshuffle/blob/master/setup.py
+ summary: "bitshuffle library."
diff --git a/target/bitshuffle-0.3.4/conda-recipe/setup.py.patch b/target/bitshuffle-0.3.4/conda-recipe/setup.py.patch
new file mode 100644
index 00000000..437a5ffa
--- /dev/null
+++ b/target/bitshuffle-0.3.4/conda-recipe/setup.py.patch
@@ -0,0 +1,13 @@
+--- setup.py 2016-01-19 16:56:12.954563000 +0100
++++ xxx.py 2016-01-19 16:56:00.817087000 +0100
+@@ -40,8 +40,8 @@
+
+ # Copied from h5py.
+ # TODO, figure out what the canonacal way to do this should be.
+-INCLUDE_DIRS = []
+-LIBRARY_DIRS = []
++INCLUDE_DIRS = [os.environ['CONDA_HOME'] + '/include']
++LIBRARY_DIRS = [os.environ['CONDA_HOME'] + '/lib']
+ if sys.platform == 'darwin':
+ # putting here both macports and homebrew paths will generate
+ # "ld: warning: dir not found" at the linking phase
diff --git a/target/bitshuffle-0.3.4/lz4/LICENSE b/target/bitshuffle-0.3.4/lz4/LICENSE
new file mode 100644
index 00000000..b566df30
--- /dev/null
+++ b/target/bitshuffle-0.3.4/lz4/LICENSE
@@ -0,0 +1,24 @@
+LZ4 Library
+Copyright (c) 2011-2014, Yann Collet
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright notice, this
+ list of conditions and the following disclaimer in the documentation and/or
+ other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+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
diff --git a/target/bitshuffle-0.3.4/lz4/README.md b/target/bitshuffle-0.3.4/lz4/README.md
new file mode 100644
index 00000000..f6ebf5e1
--- /dev/null
+++ b/target/bitshuffle-0.3.4/lz4/README.md
@@ -0,0 +1,21 @@
+LZ4 - Library Files
+================================
+
+The __lib__ directory contains several files, but you don't necessarily need them all.
+
+To integrate fast LZ4 compression/decompression into your program, you basically just need "**lz4.c**" and "**lz4.h**".
+
+For more compression at the cost of compression speed (while preserving decompression speed), use **lz4hc** on top of regular lz4. `lz4hc` only provides compression functions. It also needs `lz4` to compile properly.
+
+If you want to produce files or data streams compatible with `lz4` command line utility, use **lz4frame**. This library encapsulates lz4-compressed blocks into the [official interoperable frame format]. In order to work properly, lz4frame needs lz4 and lz4hc, and also **xxhash**, which provides error detection algorithm.
+(_Advanced stuff_ : It's possible to hide xxhash symbols into a local namespace. This is what `liblz4` does, to avoid symbol duplication in case a user program would link to several libraries containing xxhash symbols.)
+
+A more complex "lz4frame_static.h" is also provided, although its usage is not recommended. It contains definitions which are not guaranteed to remain stable within future versions. Use for static linking ***only***.
+
+The other files are not source code. There are :
+
+ - LICENSE : contains the BSD license text
+ - Makefile : script to compile or install lz4 library (static or dynamic)
+ - liblz4.pc.in : for pkg-config (make install)
+
+[official interoperable frame format]: ../lz4_Frame_format.md
diff --git a/target/bitshuffle-0.3.4/lz4/lz4.c b/target/bitshuffle-0.3.4/lz4/lz4.c
new file mode 100644
index 00000000..08cf6b5c
--- /dev/null
+++ b/target/bitshuffle-0.3.4/lz4/lz4.c
@@ -0,0 +1,1516 @@
+/*
+ LZ4 - Fast LZ compression algorithm
+ Copyright (C) 2011-2015, Yann Collet.
+
+ BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following disclaimer
+ in the documentation and/or other materials provided with the
+ distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+
+ You can contact the author at :
+ - LZ4 source repository : https://github.com/Cyan4973/lz4
+ - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
+*/
+
+
+/**************************************
+* Tuning parameters
+**************************************/
+/*
+ * 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
+
+/*
+ * ACCELERATION_DEFAULT :
+ * Select "acceleration" for LZ4_compress_fast() when parameter value <= 0
+ */
+#define ACCELERATION_DEFAULT 1
+
+
+/**************************************
+* CPU Feature Detection
+**************************************/
+/*
+ * 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 */
+# define LZ4_FORCE_SW_BITCOUNT
+#endif
+
+
+/**************************************
+* Includes
+**************************************/
+#include "lz4.h"
+
+
+/**************************************
+* 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__ */
+#endif /* _MSC_VER */
+
+/* LZ4_GCC_VERSION is defined into lz4.h */
+#if (LZ4_GCC_VERSION >= 302) || (__INTEL_COMPILER >= 800) || defined(__clang__)
+# define expect(expr,value) (__builtin_expect ((expr),(value)) )
+#else
+# define expect(expr,value) (expr)
+#endif
+
+#define likely(expr) expect((expr) != 0, 1)
+#define unlikely(expr) expect((expr) != 0, 0)
+
+
+/**************************************
+* Memory routines
+**************************************/
+#include /* malloc, calloc, free */
+#define ALLOCATOR(n,s) calloc(n,s)
+#define FREEMEM free
+#include /* memset, memcpy */
+#define MEM_INIT memset
+
+
+/**************************************
+* Basic Types
+**************************************/
+#if 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;
+#else
+ typedef unsigned char BYTE;
+ typedef unsigned short U16;
+ typedef unsigned int U32;
+ typedef signed int S32;
+ typedef unsigned long long U64;
+#endif
+
+
+/**************************************
+* Reading and writing into memory
+**************************************/
+#define STEPSIZE sizeof(size_t)
+
+static unsigned LZ4_64bits(void) { return sizeof(void*)==8; }
+
+static unsigned LZ4_isLittleEndian(void)
+{
+ const union { U32 i; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */
+ return one.c[0];
+}
+
+
+static U16 LZ4_read16(const void* memPtr)
+{
+ U16 val16;
+ memcpy(&val16, memPtr, 2);
+ return val16;
+}
+
+static U16 LZ4_readLE16(const void* memPtr)
+{
+ if (LZ4_isLittleEndian())
+ {
+ return LZ4_read16(memPtr);
+ }
+ else
+ {
+ const BYTE* p = (const BYTE*)memPtr;
+ return (U16)((U16)p[0] + (p[1]<<8));
+ }
+}
+
+static void LZ4_writeLE16(void* memPtr, U16 value)
+{
+ if (LZ4_isLittleEndian())
+ {
+ memcpy(memPtr, &value, 2);
+ }
+ else
+ {
+ BYTE* p = (BYTE*)memPtr;
+ p[0] = (BYTE) value;
+ p[1] = (BYTE)(value>>8);
+ }
+}
+
+static U32 LZ4_read32(const void* memPtr)
+{
+ U32 val32;
+ memcpy(&val32, memPtr, 4);
+ return val32;
+}
+
+static U64 LZ4_read64(const void* memPtr)
+{
+ U64 val64;
+ memcpy(&val64, memPtr, 8);
+ return val64;
+}
+
+static size_t LZ4_read_ARCH(const void* p)
+{
+ if (LZ4_64bits())
+ return (size_t)LZ4_read64(p);
+ else
+ return (size_t)LZ4_read32(p);
+}
+
+
+static void LZ4_copy4(void* dstPtr, const void* srcPtr) { memcpy(dstPtr, srcPtr, 4); }
+
+static void LZ4_copy8(void* dstPtr, const void* srcPtr) { memcpy(dstPtr, srcPtr, 8); }
+
+/* customized version of memcpy, which may overwrite up to 7 bytes beyond dstEnd */
+static void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd)
+{
+ BYTE* d = (BYTE*)dstPtr;
+ const BYTE* s = (const BYTE*)srcPtr;
+ BYTE* e = (BYTE*)dstEnd;
+ do { LZ4_copy8(d,s); d+=8; s+=8; } while (d>3);
+# elif (defined(__clang__) || (LZ4_GCC_VERSION >= 304)) && !defined(LZ4_FORCE_SW_BITCOUNT)
+ return (__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];
+# endif
+ }
+ else /* 32 bits */
+ {
+# if defined(_MSC_VER) && !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);
+# 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];
+# 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
+ unsigned r;
+ if (!(val>>32)) { r=4; } else { r=0; val>>=32; }
+ if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
+ r += (!val);
+ return r;
+# 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
+ unsigned r;
+ if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
+ r += (!val);
+ return r;
+# endif
+ }
+ }
+}
+
+static 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 { 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; }
+int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); }
+int LZ4_sizeofState() { return LZ4_STREAMSIZE; }
+
+
+
+/********************************
+* Compression functions
+********************************/
+
+static U32 LZ4_hashSequence(U32 sequence, tableType_t const tableType)
+{
+ if (tableType == byU16)
+ return (((sequence) * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1)));
+ else
+ return (((sequence) * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG));
+}
+
+static const U64 prime5bytes = 889523592379ULL;
+static U32 LZ4_hashSequence64(size_t sequence, tableType_t const tableType)
+{
+ const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG+1 : LZ4_HASHLOG;
+ const U32 hashMask = (1<> (40 - hashLog)) & hashMask;
+}
+
+static U32 LZ4_hashSequenceT(size_t sequence, tableType_t const tableType)
+{
+ if (LZ4_64bits())
+ return LZ4_hashSequence64(sequence, tableType);
+ return LZ4_hashSequence((U32)sequence, tableType);
+}
+
+static U32 LZ4_hashPosition(const void* p, tableType_t tableType) { return LZ4_hashSequenceT(LZ4_read_ARCH(p), tableType); }
+
+static void LZ4_putPositionOnHash(const BYTE* p, U32 h, void* tableBase, tableType_t const tableType, const BYTE* srcBase)
+{
+ switch (tableType)
+ {
+ 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)
+{
+ U32 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)
+{
+ 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 */
+}
+
+static const BYTE* LZ4_getPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase)
+{
+ U32 h = LZ4_hashPosition(p, tableType);
+ return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase);
+}
+
+FORCE_INLINE int LZ4_compress_generic(
+ void* const ctx,
+ const char* const source,
+ char* const dest,
+ const int inputSize,
+ const int maxOutputSize,
+ const limitedOutput_directive outputLimited,
+ const tableType_t tableType,
+ const dict_directive dict,
+ const dictIssue_directive dictIssue,
+ const U32 acceleration)
+{
+ LZ4_stream_t_internal* const dictPtr = (LZ4_stream_t_internal*)ctx;
+
+ const BYTE* ip = (const BYTE*) source;
+ const BYTE* base;
+ 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 BYTE* anchor = (const BYTE*) source;
+ const BYTE* const iend = ip + inputSize;
+ const BYTE* const mflimit = iend - MFLIMIT;
+ const BYTE* const matchlimit = iend - LASTLITERALS;
+
+ BYTE* op = (BYTE*) dest;
+ BYTE* const olimit = op + maxOutputSize;
+
+ 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;
+ }
+ if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */
+ if (inputSize> LZ4_skipTrigger);
+
+ if (unlikely(forwardIp > mflimit)) goto _last_literals;
+
+ match = LZ4_getPositionOnHash(h, ctx, tableType, base);
+ if (dict==usingExtDict)
+ {
+ if (match<(const BYTE*)source)
+ {
+ refDelta = dictDelta;
+ lowLimit = dictionary;
+ }
+ else
+ {
+ refDelta = 0;
+ lowLimit = (const BYTE*)source;
+ }
+ }
+ forwardH = LZ4_hashPosition(forwardIp, tableType);
+ LZ4_putPositionOnHash(ip, h, ctx, tableType, base);
+
+ } while ( ((dictIssue==dictSmall) ? (match < lowRefLimit) : 0)
+ || ((tableType==byU16) ? 0 : (match + MAX_DISTANCE < ip))
+ || (LZ4_read32(match+refDelta) != LZ4_read32(ip)) );
+ }
+
+ /* Catch up */
+ while ((ip>anchor) && (match+refDelta > lowLimit) && (unlikely(ip[-1]==match[refDelta-1]))) { ip--; match--; }
+
+ {
+ /* Encode Literal length */
+ unsigned 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<= 255 ; len-=255) *op++ = 255;
+ *op++ = (BYTE)len;
+ }
+ else *token = (BYTE)(litLength< 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;
+ ip += more;
+ }
+ }
+ else
+ {
+ matchLength = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit);
+ ip += MINMATCH + matchLength;
+ }
+
+ 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;
+ }
+ else *token += (BYTE)(matchLength);
+ }
+
+ anchor = ip;
+
+ /* Test end of chunk */
+ if (ip > mflimit) break;
+
+ /* Fill table */
+ LZ4_putPosition(ip-2, ctx, tableType, base);
+
+ /* Test next position */
+ match = LZ4_getPosition(ip, ctx, tableType, base);
+ if (dict==usingExtDict)
+ {
+ if (match<(const BYTE*)source)
+ {
+ refDelta = dictDelta;
+ lowLimit = dictionary;
+ }
+ else
+ {
+ refDelta = 0;
+ lowLimit = (const BYTE*)source;
+ }
+ }
+ 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 accumulator = lastRun - RUN_MASK;
+ *op++ = RUN_MASK << ML_BITS;
+ for(; accumulator >= 255 ; accumulator-=255) *op++ = 255;
+ *op++ = (BYTE) accumulator;
+ }
+ 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;
+
+ /* Test end of block */
+ if (ip > mflimit) break;
+ if (op > oMaxSeq) break;
+
+ /* Fill table */
+ LZ4_putPosition(ip-2, ctx, tableType, base);
+
+ /* 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; }
+
+ /* 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;
+ }
+ ip = anchor + lastRunSize;
+
+ if (lastRunSize >= RUN_MASK)
+ {
+ size_t accumulator = lastRunSize - RUN_MASK;
+ *op++ = RUN_MASK << ML_BITS;
+ for(; accumulator >= 255 ; accumulator-=255) *op++ = 255;
+ *op++ = (BYTE) accumulator;
+ }
+ else
+ {
+ *op++ = (BYTE)(lastRunSize<= 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);
+ }
+}
+
+
+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 */
+#else
+ LZ4_stream_t ctxBody;
+ void* ctx = &ctxBody;
+#endif
+
+ int result = LZ4_compress_destSize_extState(ctx, src, dst, srcSizePtr, targetDstSize);
+
+#if (HEAPMODE)
+ FREEMEM(ctx);
+#endif
+ return result;
+}
+
+
+
+/********************************
+* Streaming functions
+********************************/
+
+LZ4_stream_t* LZ4_createStream(void)
+{
+ LZ4_stream_t* lz4s = (LZ4_stream_t*)ALLOCATOR(8, LZ4_STREAMSIZE_U64);
+ LZ4_STATIC_ASSERT(LZ4_STREAMSIZE >= sizeof(LZ4_stream_t_internal)); /* A compilation error here means LZ4_STREAMSIZE is not large enough */
+ LZ4_resetStream(lz4s);
+ return lz4s;
+}
+
+void LZ4_resetStream (LZ4_stream_t* LZ4_stream)
+{
+ MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t));
+}
+
+int LZ4_freeStream (LZ4_stream_t* LZ4_stream)
+{
+ FREEMEM(LZ4_stream);
+ return (0);
+}
+
+
+#define HASH_UNIT sizeof(size_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;
+ 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);
+
+ if (dictSize < (int)HASH_UNIT)
+ {
+ dict->dictionary = NULL;
+ dict->dictSize = 0;
+ return 0;
+ }
+
+ if ((dictEnd - p) > 64 KB) p = dictEnd - 64 KB;
+ dict->currentOffset += 64 KB;
+ base = p - dict->currentOffset;
+ dict->dictionary = p;
+ dict->dictSize = (U32)(dictEnd - p);
+ dict->currentOffset += dict->dictSize;
+
+ while (p <= dictEnd-HASH_UNIT)
+ {
+ LZ4_putPosition(p, dict->hashTable, byU32, base);
+ p+=3;
+ }
+
+ return dict->dictSize;
+}
+
+
+static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, const BYTE* src)
+{
+ if ((LZ4_dict->currentOffset > 0x80000000) ||
+ ((size_t)LZ4_dict->currentOffset > (size_t)src)) /* address space overflow */
+ {
+ /* rescale hash table */
+ U32 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;
+ }
+ LZ4_dict->currentOffset = 64 KB;
+ if (LZ4_dict->dictSize > 64 KB) LZ4_dict->dictSize = 64 KB;
+ LZ4_dict->dictionary = dictEnd - LZ4_dict->dictSize;
+ }
+}
+
+
+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 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;
+
+ /* Check overlapping input/dictionary space */
+ {
+ 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;
+ streamPtr->dictionary = dictEnd - streamPtr->dictSize;
+ }
+ }
+
+ /* prefix mode : source data follows dictionary */
+ if (dictEnd == (const BYTE*)source)
+ {
+ int result;
+ if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))
+ result = LZ4_compress_generic(LZ4_stream, source, dest, inputSize, maxOutputSize, limitedOutput, byU32, 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;
+ }
+
+ /* 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);
+ 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)
+{
+ LZ4_stream_t_internal* streamPtr = (LZ4_stream_t_internal*)LZ4_dict;
+ 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);
+
+ result = LZ4_compress_generic(LZ4_dict, source, dest, inputSize, 0, notLimited, byU32, usingExtDict, noDictIssue, 1);
+
+ streamPtr->dictionary = (const BYTE*)source;
+ streamPtr->dictSize = (U32)inputSize;
+ streamPtr->currentOffset += (U32)inputSize;
+
+ return result;
+}
+
+
+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;
+
+ if ((U32)dictSize > 64 KB) dictSize = 64 KB; /* useless to define a dictionary > 64 KB */
+ if ((U32)dictSize > dict->dictSize) dictSize = dict->dictSize;
+
+ memmove(safeBuffer, previousDictEnd - dictSize, dictSize);
+
+ dict->dictionary = (const BYTE*)safeBuffer;
+ dict->dictSize = (U32)dictSize;
+
+ return 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.
+ */
+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 */
+ 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;
+
+ BYTE* op = (BYTE*) dest;
+ BYTE* const oend = op + outputSize;
+ BYTE* cpy;
+ BYTE* oexit = op + targetOutputSize;
+ const BYTE* const lowLimit = lowPrefix - dictSize;
+
+ 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};
+
+ 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);
+
+
+ /* Main Loop */
+ while (1)
+ {
+ 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 */
+ }
+ 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 */
+ }
+ 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 */
+
+ /* 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 */
+ }
+ length += MINMATCH;
+
+ /* check external dictionary */
+ if ((dict==usingExtDict) && (match < lowPrefix))
+ {
+ if (unlikely(op+length > oend-LASTLITERALS)) goto _output_error; /* doesn't respect parsing restriction */
+
+ 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;
+ }
+ else
+ {
+ /* 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++;
+ }
+ else
+ {
+ memcpy(op, lowPrefix, copySize);
+ op += copySize;
+ }
+ }
+ 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;
+ }
+ while (opprefixSize = (size_t) dictSize;
+ lz4sd->prefixEnd = (const BYTE*) dictionary + dictSize;
+ lz4sd->externalDict = NULL;
+ lz4sd->extDictSize = 0;
+ return 1;
+}
+
+/*
+*_continue() :
+ These decoding functions allow decompression of multiple blocks in "streaming" mode.
+ Previously decoded blocks must still be available at the memory position where they were decoded.
+ If it's not possible, save the relevant part of decoded data into a safe buffer,
+ and indicate where it stands using LZ4_setStreamDecode()
+*/
+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;
+ 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 (result <= 0) return result;
+ lz4sd->prefixSize += result;
+ lz4sd->prefixEnd += result;
+ }
+ else
+ {
+ 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);
+ if (result <= 0) return result;
+ lz4sd->prefixSize = result;
+ lz4sd->prefixEnd = (BYTE*)dest + result;
+ }
+
+ return result;
+}
+
+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;
+ int result;
+
+ 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 (result <= 0) return result;
+ lz4sd->prefixSize += originalSize;
+ lz4sd->prefixEnd += originalSize;
+ }
+ 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);
+ if (result <= 0) return result;
+ lz4sd->prefixSize = originalSize;
+ lz4sd->prefixEnd = (BYTE*)dest + originalSize;
+ }
+
+ return result;
+}
+
+
+/*
+Advanced decoding functions :
+*_usingDict() :
+ These decoding functions work the same as "_continue" ones,
+ 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)
+{
+ 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_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);
+}
+
+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);
+}
+
+
+/***************************************************
+* 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); }
+
+/*
+These function names 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); }
+
+
+/* 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_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);
+ 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);
+}
+
+int LZ4_decompress_fast_withPrefix64k(const char* source, char* dest, int originalSize)
+{
+ return LZ4_decompress_generic(source, dest, 0, originalSize, endOnOutputSize, full, 0, withPrefix64k, (BYTE*)dest - 64 KB, NULL, 64 KB);
+}
+
+#endif /* LZ4_COMMONDEFS_ONLY */
+
diff --git a/target/bitshuffle-0.3.4/lz4/lz4.h b/target/bitshuffle-0.3.4/lz4/lz4.h
new file mode 100644
index 00000000..3e740022
--- /dev/null
+++ b/target/bitshuffle-0.3.4/lz4/lz4.h
@@ -0,0 +1,360 @@
+/*
+ LZ4 - Fast LZ compression algorithm
+ Header File
+ Copyright (C) 2011-2015, Yann Collet.
+
+ BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following disclaimer
+ in the documentation and/or other materials provided with the
+ distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+
+ You can contact the author at :
+ - LZ4 source repository : https://github.com/Cyan4973/lz4
+ - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c
+*/
+#pragma once
+
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+/*
+ * 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.
+*/
+
+/**************************************
+* 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_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE)
+int LZ4_versionNumber (void);
+
+/**************************************
+* 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
+ * Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache
+ */
+#define LZ4_MEMORY_USAGE 14
+
+
+/**************************************
+* 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.
+*/
+
+
+/**************************************
+* 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() :
+ 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)
+ 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)
+*/
+int LZ4_compressBound(int inputSize);
+
+/*
+LZ4_compress_fast() :
+ Same as LZ4_compress_default(), but allows to select an "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.
+*/
+int LZ4_compress_fast (const char* source, char* dest, int sourceSize, int maxDestSize, 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_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_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);
+
+
+/***********************************************
+* 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;
+
+/*
+ * LZ4_resetStream
+ * Use this function to init an allocated LZ4_stream_t structure
+ */
+void LZ4_resetStream (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_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)
+ */
+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 !
+ * '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.
+ */
+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
+ */
+int LZ4_saveDict (LZ4_stream_t* streamPtr, char* safeBuffer, int dictSize);
+
+
+/************************************************
+* Streaming Decompression Functions
+************************************************/
+
+#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_streamDecode_t* LZ4_createStreamDecode(void);
+int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream);
+
+/*
+ * 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
+ */
+int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, 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);
+
+
+/*
+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);
+
+
+
+/**************************************
+* 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))
+# elif defined(_MSC_VER)
+# define LZ4_DEPRECATED(message) __declspec(deprecated(message))
+# else
+# pragma message("WARNING: You need to implement LZ4_DEPRECATED for this compiler")
+# define LZ4_DEPRECATED(message)
+# 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);
+
+
+#if defined (__cplusplus)
+}
+#endif
diff --git a/target/bitshuffle-0.3.4/lzf/LICENSE.txt b/target/bitshuffle-0.3.4/lzf/LICENSE.txt
new file mode 100644
index 00000000..3787a007
--- /dev/null
+++ b/target/bitshuffle-0.3.4/lzf/LICENSE.txt
@@ -0,0 +1,34 @@
+Copyright Notice and Statement for LZF filter
+
+Copyright (c) 2008-2009 Andrew Collette
+http://h5py.alfven.org
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+a. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+b. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the
+ distribution.
+
+c. Neither the name of the author nor the names of contributors may
+ be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+
diff --git a/target/bitshuffle-0.3.4/lzf/README.txt b/target/bitshuffle-0.3.4/lzf/README.txt
new file mode 100644
index 00000000..c6ad62c3
--- /dev/null
+++ b/target/bitshuffle-0.3.4/lzf/README.txt
@@ -0,0 +1,84 @@
+===============================
+LZF filter for HDF5, revision 3
+===============================
+
+The LZF filter provides high-speed compression with acceptable compression
+performance, resulting in much faster performance than DEFLATE, at the
+cost of a slightly lower compression ratio. It's appropriate for large
+datasets of low to moderate complexity, for which some compression is
+much better than none, but for which the speed of DEFLATE is unacceptable.
+
+This filter has been tested against HDF5 versions 1.6.5 through 1.8.3. It
+is released under the BSD license (see LICENSE.txt for details).
+
+
+Using the filter from HDF5
+--------------------------
+
+There is exactly one new public function declared in lzf_filter.h, with
+the following signature:
+
+ int register_lzf(void)
+
+Calling this will register the filter with the HDF5 library. A non-negative
+return value indicates success. If the registration fails, an error is pushed
+onto the current error stack and a negative value is returned.
+
+It's strongly recommended to use the SHUFFLE filter with LZF, as it's
+cheap, supported by all current versions of HDF5, and can significantly
+improve the compression ratio. An example C program ("example.c") is included
+which demonstrates the proper use of the filter.
+
+
+Compiling
+---------
+
+The filter consists of a single .c file and header, along with an embedded
+version of the LZF compression library. Since the filter is stateless, it's
+recommended to statically link the entire thing into your program; for
+example:
+
+ $ gcc -O2 -lhdf5 lzf/*.c lzf_filter.c myprog.c -o myprog
+
+It can also be built as a shared library, although you will have to install
+the resulting library somewhere the runtime linker can find it:
+
+ $ gcc -O2 -lhdf5 -fPIC -shared lzf/*.c lzf_filter.c -o liblzf_filter.so
+
+A similar procedure should be used for building C++ code. As in these
+examples, using option -O1 or higher is strongly recommended for increased
+performance.
+
+
+Contact
+-------
+
+This filter is maintained as part of the HDF5 for Python (h5py) project. The
+goal of h5py is to provide access to the majority of the HDF5 C API and feature
+set from Python. The most recent version of h5py (1.1) includes the LZF
+filter by default.
+
+* Downloads and bug tracker: http://h5py.googlecode.com
+
+* Main web site and documentation: http://h5py.alfven.org
+
+* Contact email: h5py at alfven dot org
+
+
+History of changes
+------------------
+
+Revision 3 (6/25/09)
+ Fix issue with changed filter struct definition under HDF5 1.8.3.
+
+Revision 2
+ Minor speed enhancement.
+
+Revision 1
+ Initial release.
+
+
+
+
+
+
diff --git a/target/bitshuffle-0.3.4/lzf/README_bitshuffle.txt b/target/bitshuffle-0.3.4/lzf/README_bitshuffle.txt
new file mode 100644
index 00000000..d620a925
--- /dev/null
+++ b/target/bitshuffle-0.3.4/lzf/README_bitshuffle.txt
@@ -0,0 +1,3 @@
+The LZF filter for HDF5 is part of the h5py project (http://h5py.alfven.org).
+The version included with bitshuffle is from version 2.3 of h5py with no
+modifications other than the addition of this README.
diff --git a/target/bitshuffle-0.3.4/lzf/example.c b/target/bitshuffle-0.3.4/lzf/example.c
new file mode 100644
index 00000000..23dd776c
--- /dev/null
+++ b/target/bitshuffle-0.3.4/lzf/example.c
@@ -0,0 +1,106 @@
+/*
+ Copyright (C) 2009 Andrew Collette
+ http://h5py.alfven.org
+ License: BSD (see LICENSE.txt)
+
+ Example program demonstrating use of the LZF filter from C code.
+
+ To compile this program:
+
+ h5cc -DH5_USE_16_API lzf/*.c lzf_filter.c example.c -o example
+
+ To run:
+
+ $ ./example
+ Success!
+ $ h5ls -v test_lzf.hdf5
+ Opened "test_lzf.hdf5" with sec2 driver.
+ dset Dataset {100/100, 100/100, 100/100}
+ Location: 0:1:0:976
+ Links: 1
+ Modified: 2009-02-15 16:35:11 PST
+ Chunks: {1, 100, 100} 40000 bytes
+ Storage: 4000000 logical bytes, 174288 allocated bytes, 2295.05% utilization
+ Filter-0: shuffle-2 OPT {4}
+ Filter-1: lzf-32000 OPT {1, 261, 40000}
+ Type: native float
+*/
+
+#include
+#include "hdf5.h"
+#include "lzf_filter.h"
+
+#define SIZE 100*100*100
+#define SHAPE {100,100,100}
+#define CHUNKSHAPE {1,100,100}
+
+int main(){
+
+ static float data[SIZE];
+ static float data_out[SIZE];
+ const hsize_t shape[] = SHAPE;
+ const hsize_t chunkshape[] = CHUNKSHAPE;
+ int r, i;
+ int return_code = 1;
+
+ hid_t fid, sid, dset, plist = 0;
+
+ for(i=0; i0) H5Dclose(dset);
+ if(sid>0) H5Sclose(sid);
+ if(plist>0) H5Pclose(plist);
+ if(fid>0) H5Fclose(fid);
+
+ return return_code;
+}
+
diff --git a/target/bitshuffle-0.3.4/lzf/lzf/lzf.h b/target/bitshuffle-0.3.4/lzf/lzf/lzf.h
new file mode 100644
index 00000000..919b6e6b
--- /dev/null
+++ b/target/bitshuffle-0.3.4/lzf/lzf/lzf.h
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2000-2008 Marc Alexander Lehmann
+ *
+ * Redistribution and use in source and binary forms, with or without modifica-
+ * tion, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
+ * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
+ * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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 OTH-
+ * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * the GNU General Public License ("GPL") version 2 or any later version,
+ * in which case the provisions of the GPL are applicable instead of
+ * the above. If you wish to allow the use of your version of this file
+ * only under the terms of the GPL and not to allow others to use your
+ * version of this file under the BSD license, indicate your decision
+ * by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL. If you do not delete the
+ * provisions above, a recipient may use your version of this file under
+ * either the BSD or the GPL.
+ */
+
+#ifndef LZF_H
+#define LZF_H
+
+/***********************************************************************
+**
+** lzf -- an extremely fast/free compression/decompression-method
+** http://liblzf.plan9.de/
+**
+** This algorithm is believed to be patent-free.
+**
+***********************************************************************/
+
+#define LZF_VERSION 0x0105 /* 1.5, API version */
+
+/*
+ * Compress in_len bytes stored at the memory block starting at
+ * in_data and write the result to out_data, up to a maximum length
+ * of out_len bytes.
+ *
+ * If the output buffer is not large enough or any error occurs return 0,
+ * otherwise return the number of bytes used, which might be considerably
+ * more than in_len (but less than 104% of the original size), so it
+ * makes sense to always use out_len == in_len - 1), to ensure _some_
+ * compression, and store the data uncompressed otherwise (with a flag, of
+ * course.
+ *
+ * lzf_compress might use different algorithms on different systems and
+ * even different runs, thus might result in different compressed strings
+ * depending on the phase of the moon or similar factors. However, all
+ * these strings are architecture-independent and will result in the
+ * original data when decompressed using lzf_decompress.
+ *
+ * The buffers must not be overlapping.
+ *
+ * If the option LZF_STATE_ARG is enabled, an extra argument must be
+ * supplied which is not reflected in this header file. Refer to lzfP.h
+ * and lzf_c.c.
+ *
+ */
+unsigned int
+lzf_compress (const void *const in_data, unsigned int in_len,
+ void *out_data, unsigned int out_len);
+
+/*
+ * Decompress data compressed with some version of the lzf_compress
+ * function and stored at location in_data and length in_len. The result
+ * will be stored at out_data up to a maximum of out_len characters.
+ *
+ * If the output buffer is not large enough to hold the decompressed
+ * data, a 0 is returned and errno is set to E2BIG. Otherwise the number
+ * of decompressed bytes (i.e. the original length of the data) is
+ * returned.
+ *
+ * If an error in the compressed data is detected, a zero is returned and
+ * errno is set to EINVAL.
+ *
+ * This function is very fast, about as fast as a copying loop.
+ */
+unsigned int
+lzf_decompress (const void *const in_data, unsigned int in_len,
+ void *out_data, unsigned int out_len);
+
+#endif
+
diff --git a/target/bitshuffle-0.3.4/lzf/lzf/lzfP.h b/target/bitshuffle-0.3.4/lzf/lzf/lzfP.h
new file mode 100644
index 00000000..8414da4d
--- /dev/null
+++ b/target/bitshuffle-0.3.4/lzf/lzf/lzfP.h
@@ -0,0 +1,166 @@
+/*
+ * Copyright (c) 2000-2007 Marc Alexander Lehmann
+ *
+ * Redistribution and use in source and binary forms, with or without modifica-
+ * tion, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
+ * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
+ * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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 OTH-
+ * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * the GNU General Public License ("GPL") version 2 or any later version,
+ * in which case the provisions of the GPL are applicable instead of
+ * the above. If you wish to allow the use of your version of this file
+ * only under the terms of the GPL and not to allow others to use your
+ * version of this file under the BSD license, indicate your decision
+ * by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL. If you do not delete the
+ * provisions above, a recipient may use your version of this file under
+ * either the BSD or the GPL.
+ */
+
+#ifndef LZFP_h
+#define LZFP_h
+
+#define STANDALONE 1 /* at the moment, this is ok. */
+
+#ifndef STANDALONE
+# include "lzf.h"
+#endif
+
+/*
+ * Size of hashtable is (1 << HLOG) * sizeof (char *)
+ * decompression is independent of the hash table size
+ * the difference between 15 and 14 is very small
+ * for small blocks (and 14 is usually a bit faster).
+ * For a low-memory/faster configuration, use HLOG == 13;
+ * For best compression, use 15 or 16 (or more, up to 23).
+ */
+#ifndef HLOG
+# define HLOG 17 /* Avoid pathological case at HLOG=16 A.C. 2/15/09 */
+#endif
+
+/*
+ * Sacrifice very little compression quality in favour of compression speed.
+ * This gives almost the same compression as the default code, and is
+ * (very roughly) 15% faster. This is the preferred mode of operation.
+ */
+#ifndef VERY_FAST
+# define VERY_FAST 1
+#endif
+
+/*
+ * Sacrifice some more compression quality in favour of compression speed.
+ * (roughly 1-2% worse compression for large blocks and
+ * 9-10% for small, redundant, blocks and >>20% better speed in both cases)
+ * In short: when in need for speed, enable this for binary data,
+ * possibly disable this for text data.
+ */
+#ifndef ULTRA_FAST
+# define ULTRA_FAST 1
+#endif
+
+/*
+ * Unconditionally aligning does not cost very much, so do it if unsure
+ */
+#ifndef STRICT_ALIGN
+# define STRICT_ALIGN !(defined(__i386) || defined (__amd64))
+#endif
+
+/*
+ * You may choose to pre-set the hash table (might be faster on some
+ * modern cpus and large (>>64k) blocks, and also makes compression
+ * deterministic/repeatable when the configuration otherwise is the same).
+ */
+#ifndef INIT_HTAB
+# define INIT_HTAB 0
+#endif
+
+/* =======================================================================
+ Changing things below this line may break the HDF5 LZF filter.
+ A.C. 2/15/09
+ =======================================================================
+*/
+
+/*
+ * Avoid assigning values to errno variable? for some embedding purposes
+ * (linux kernel for example), this is neccessary. NOTE: this breaks
+ * the documentation in lzf.h.
+ */
+#ifndef AVOID_ERRNO
+# define AVOID_ERRNO 0
+#endif
+
+/*
+ * Wether to pass the LZF_STATE variable as argument, or allocate it
+ * on the stack. For small-stack environments, define this to 1.
+ * NOTE: this breaks the prototype in lzf.h.
+ */
+#ifndef LZF_STATE_ARG
+# define LZF_STATE_ARG 0
+#endif
+
+/*
+ * Wether to add extra checks for input validity in lzf_decompress
+ * and return EINVAL if the input stream has been corrupted. This
+ * only shields against overflowing the input buffer and will not
+ * detect most corrupted streams.
+ * This check is not normally noticable on modern hardware
+ * (<1% slowdown), but might slow down older cpus considerably.
+ */
+
+#ifndef CHECK_INPUT
+# define CHECK_INPUT 1
+#endif
+
+/*****************************************************************************/
+/* nothing should be changed below */
+
+typedef unsigned char u8;
+
+typedef const u8 *LZF_STATE[1 << (HLOG)];
+
+#if !STRICT_ALIGN
+/* for unaligned accesses we need a 16 bit datatype. */
+# include
+# if USHRT_MAX == 65535
+ typedef unsigned short u16;
+# elif UINT_MAX == 65535
+ typedef unsigned int u16;
+# else
+# undef STRICT_ALIGN
+# define STRICT_ALIGN 1
+# endif
+#endif
+
+#if ULTRA_FAST
+# if defined(VERY_FAST)
+# undef VERY_FAST
+# endif
+#endif
+
+#if INIT_HTAB
+# ifdef __cplusplus
+# include
+# else
+# include
+# endif
+#endif
+
+#endif
+
diff --git a/target/bitshuffle-0.3.4/lzf/lzf/lzf_c.c b/target/bitshuffle-0.3.4/lzf/lzf/lzf_c.c
new file mode 100644
index 00000000..fbfd4cce
--- /dev/null
+++ b/target/bitshuffle-0.3.4/lzf/lzf/lzf_c.c
@@ -0,0 +1,296 @@
+/*
+ * Copyright (c) 2000-2008 Marc Alexander Lehmann
+ *
+ * Redistribution and use in source and binary forms, with or without modifica-
+ * tion, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
+ * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
+ * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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 OTH-
+ * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * the GNU General Public License ("GPL") version 2 or any later version,
+ * in which case the provisions of the GPL are applicable instead of
+ * the above. If you wish to allow the use of your version of this file
+ * only under the terms of the GPL and not to allow others to use your
+ * version of this file under the BSD license, indicate your decision
+ * by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL. If you do not delete the
+ * provisions above, a recipient may use your version of this file under
+ * either the BSD or the GPL.
+ */
+
+#include "lzfP.h"
+
+#define HSIZE (1 << (HLOG))
+
+/*
+ * don't play with this unless you benchmark!
+ * decompression is not dependent on the hash function
+ * the hashing function might seem strange, just believe me
+ * it works ;)
+ */
+#ifndef FRST
+# define FRST(p) (((p[0]) << 8) | p[1])
+# define NEXT(v,p) (((v) << 8) | p[2])
+# if ULTRA_FAST
+# define IDX(h) ((( h >> (3*8 - HLOG)) - h ) & (HSIZE - 1))
+# elif VERY_FAST
+# define IDX(h) ((( h >> (3*8 - HLOG)) - h*5) & (HSIZE - 1))
+# else
+# define IDX(h) ((((h ^ (h << 5)) >> (3*8 - HLOG)) - h*5) & (HSIZE - 1))
+# endif
+#endif
+/*
+ * IDX works because it is very similar to a multiplicative hash, e.g.
+ * ((h * 57321 >> (3*8 - HLOG)) & (HSIZE - 1))
+ * the latter is also quite fast on newer CPUs, and compresses similarly.
+ *
+ * the next one is also quite good, albeit slow ;)
+ * (int)(cos(h & 0xffffff) * 1e6)
+ */
+
+#if 0
+/* original lzv-like hash function, much worse and thus slower */
+# define FRST(p) (p[0] << 5) ^ p[1]
+# define NEXT(v,p) ((v) << 5) ^ p[2]
+# define IDX(h) ((h) & (HSIZE - 1))
+#endif
+
+#define MAX_LIT (1 << 5)
+#define MAX_OFF (1 << 13)
+#define MAX_REF ((1 << 8) + (1 << 3))
+
+#if __GNUC__ >= 3
+# define expect(expr,value) __builtin_expect ((expr),(value))
+# define inline inline
+#else
+# define expect(expr,value) (expr)
+# define inline static
+#endif
+
+#define expect_false(expr) expect ((expr) != 0, 0)
+#define expect_true(expr) expect ((expr) != 0, 1)
+
+/*
+ * compressed format
+ *
+ * 000LLLLL ; literal
+ * LLLooooo oooooooo ; backref L
+ * 111ooooo LLLLLLLL oooooooo ; backref L+7
+ *
+ */
+
+unsigned int
+lzf_compress (const void *const in_data, unsigned int in_len,
+ void *out_data, unsigned int out_len
+#if LZF_STATE_ARG
+ , LZF_STATE htab
+#endif
+ )
+{
+#if !LZF_STATE_ARG
+ LZF_STATE htab;
+#endif
+ const u8 **hslot;
+ const u8 *ip = (const u8 *)in_data;
+ u8 *op = (u8 *)out_data;
+ const u8 *in_end = ip + in_len;
+ u8 *out_end = op + out_len;
+ const u8 *ref;
+
+ /* off requires a type wide enough to hold a general pointer difference.
+ * ISO C doesn't have that (size_t might not be enough and ptrdiff_t only
+ * works for differences within a single object). We also assume that no
+ * no bit pattern traps. Since the only platform that is both non-POSIX
+ * and fails to support both assumptions is windows 64 bit, we make a
+ * special workaround for it.
+ */
+#if ( defined (WIN32) && defined (_M_X64) ) || defined (_WIN64)
+ unsigned _int64 off; /* workaround for missing POSIX compliance */
+#else
+ unsigned long off;
+#endif
+ unsigned int hval;
+ int lit;
+
+ if (!in_len || !out_len)
+ return 0;
+
+#if INIT_HTAB
+ memset (htab, 0, sizeof (htab));
+# if 0
+ for (hslot = htab; hslot < htab + HSIZE; hslot++)
+ *hslot++ = ip;
+# endif
+#endif
+
+ lit = 0; op++; /* start run */
+
+ hval = FRST (ip);
+ while (ip < in_end - 2)
+ {
+ hval = NEXT (hval, ip);
+ hslot = htab + IDX (hval);
+ ref = *hslot; *hslot = ip;
+
+ if (1
+#if INIT_HTAB
+ && ref < ip /* the next test will actually take care of this, but this is faster */
+#endif
+ && (off = ip - ref - 1) < MAX_OFF
+ && ip + 4 < in_end
+ && ref > (u8 *)in_data
+#if STRICT_ALIGN
+ && ref[0] == ip[0]
+ && ref[1] == ip[1]
+ && ref[2] == ip[2]
+#else
+ && *(u16 *)ref == *(u16 *)ip
+ && ref[2] == ip[2]
+#endif
+ )
+ {
+ /* match found at *ref++ */
+ unsigned int len = 2;
+ unsigned int maxlen = in_end - ip - len;
+ maxlen = maxlen > MAX_REF ? MAX_REF : maxlen;
+
+ if (expect_false (op + 3 + 1 >= out_end)) /* first a faster conservative test */
+ if (op - !lit + 3 + 1 >= out_end) /* second the exact but rare test */
+ return 0;
+
+ op [- lit - 1] = lit - 1; /* stop run */
+ op -= !lit; /* undo run if length is zero */
+
+ for (;;)
+ {
+ if (expect_true (maxlen > 16))
+ {
+ len++; if (ref [len] != ip [len]) break;
+ len++; if (ref [len] != ip [len]) break;
+ len++; if (ref [len] != ip [len]) break;
+ len++; if (ref [len] != ip [len]) break;
+
+ len++; if (ref [len] != ip [len]) break;
+ len++; if (ref [len] != ip [len]) break;
+ len++; if (ref [len] != ip [len]) break;
+ len++; if (ref [len] != ip [len]) break;
+
+ len++; if (ref [len] != ip [len]) break;
+ len++; if (ref [len] != ip [len]) break;
+ len++; if (ref [len] != ip [len]) break;
+ len++; if (ref [len] != ip [len]) break;
+
+ len++; if (ref [len] != ip [len]) break;
+ len++; if (ref [len] != ip [len]) break;
+ len++; if (ref [len] != ip [len]) break;
+ len++; if (ref [len] != ip [len]) break;
+ }
+
+ do
+ len++;
+ while (len < maxlen && ref[len] == ip[len]);
+
+ break;
+ }
+
+ len -= 2; /* len is now #octets - 1 */
+ ip++;
+
+ if (len < 7)
+ {
+ *op++ = (off >> 8) + (len << 5);
+ }
+ else
+ {
+ *op++ = (off >> 8) + ( 7 << 5);
+ *op++ = len - 7;
+ }
+
+ *op++ = off;
+ lit = 0; op++; /* start run */
+
+ ip += len + 1;
+
+ if (expect_false (ip >= in_end - 2))
+ break;
+
+#if ULTRA_FAST || VERY_FAST
+ --ip;
+# if VERY_FAST && !ULTRA_FAST
+ --ip;
+# endif
+ hval = FRST (ip);
+
+ hval = NEXT (hval, ip);
+ htab[IDX (hval)] = ip;
+ ip++;
+
+# if VERY_FAST && !ULTRA_FAST
+ hval = NEXT (hval, ip);
+ htab[IDX (hval)] = ip;
+ ip++;
+# endif
+#else
+ ip -= len + 1;
+
+ do
+ {
+ hval = NEXT (hval, ip);
+ htab[IDX (hval)] = ip;
+ ip++;
+ }
+ while (len--);
+#endif
+ }
+ else
+ {
+ /* one more literal byte we must copy */
+ if (expect_false (op >= out_end))
+ return 0;
+
+ lit++; *op++ = *ip++;
+
+ if (expect_false (lit == MAX_LIT))
+ {
+ op [- lit - 1] = lit - 1; /* stop run */
+ lit = 0; op++; /* start run */
+ }
+ }
+ }
+
+ if (op + 3 > out_end) /* at most 3 bytes can be missing here */
+ return 0;
+
+ while (ip < in_end)
+ {
+ lit++; *op++ = *ip++;
+
+ if (expect_false (lit == MAX_LIT))
+ {
+ op [- lit - 1] = lit - 1; /* stop run */
+ lit = 0; op++; /* start run */
+ }
+ }
+
+ op [- lit - 1] = lit - 1; /* end run */
+ op -= !lit; /* undo run if length is zero */
+
+ return op - (u8 *)out_data;
+}
+
diff --git a/target/bitshuffle-0.3.4/lzf/lzf/lzf_d.c b/target/bitshuffle-0.3.4/lzf/lzf/lzf_d.c
new file mode 100644
index 00000000..2e2eedaa
--- /dev/null
+++ b/target/bitshuffle-0.3.4/lzf/lzf/lzf_d.c
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) 2000-2007 Marc Alexander Lehmann
+ *
+ * Redistribution and use in source and binary forms, with or without modifica-
+ * tion, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
+ * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
+ * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+ * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
+ * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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 OTH-
+ * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * the GNU General Public License ("GPL") version 2 or any later version,
+ * in which case the provisions of the GPL are applicable instead of
+ * the above. If you wish to allow the use of your version of this file
+ * only under the terms of the GPL and not to allow others to use your
+ * version of this file under the BSD license, indicate your decision
+ * by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL. If you do not delete the
+ * provisions above, a recipient may use your version of this file under
+ * either the BSD or the GPL.
+ */
+
+#include "lzfP.h"
+
+#if AVOID_ERRNO
+# define SET_ERRNO(n)
+#else
+# include
+# define SET_ERRNO(n) errno = (n)
+#endif
+
+/* ASM is slower than C in HDF5 tests -- A.C. 2/5/09
+#ifndef __STRICT_ANSI__
+#ifndef H5PY_DISABLE_LZF_ASM
+#if (__i386 || __amd64) && __GNUC__ >= 3
+# define lzf_movsb(dst, src, len) \
+ asm ("rep movsb" \
+ : "=D" (dst), "=S" (src), "=c" (len) \
+ : "0" (dst), "1" (src), "2" (len));
+#endif
+#endif
+#endif
+*/
+
+unsigned int
+lzf_decompress (const void *const in_data, unsigned int in_len,
+ void *out_data, unsigned int out_len)
+{
+ u8 const *ip = (const u8 *)in_data;
+ u8 *op = (u8 *)out_data;
+ u8 const *const in_end = ip + in_len;
+ u8 *const out_end = op + out_len;
+
+ do
+ {
+ unsigned int ctrl = *ip++;
+
+ if (ctrl < (1 << 5)) /* literal run */
+ {
+ ctrl++;
+
+ if (op + ctrl > out_end)
+ {
+ SET_ERRNO (E2BIG);
+ return 0;
+ }
+
+#if CHECK_INPUT
+ if (ip + ctrl > in_end)
+ {
+ SET_ERRNO (EINVAL);
+ return 0;
+ }
+#endif
+
+#ifdef lzf_movsb
+ lzf_movsb (op, ip, ctrl);
+#else
+ do
+ *op++ = *ip++;
+ while (--ctrl);
+#endif
+ }
+ else /* back reference */
+ {
+ unsigned int len = ctrl >> 5;
+
+ u8 *ref = op - ((ctrl & 0x1f) << 8) - 1;
+
+#if CHECK_INPUT
+ if (ip >= in_end)
+ {
+ SET_ERRNO (EINVAL);
+ return 0;
+ }
+#endif
+ if (len == 7)
+ {
+ len += *ip++;
+#if CHECK_INPUT
+ if (ip >= in_end)
+ {
+ SET_ERRNO (EINVAL);
+ return 0;
+ }
+#endif
+ }
+
+ ref -= *ip++;
+
+ if (op + len + 2 > out_end)
+ {
+ SET_ERRNO (E2BIG);
+ return 0;
+ }
+
+ if (ref < (u8 *)out_data)
+ {
+ SET_ERRNO (EINVAL);
+ return 0;
+ }
+
+#ifdef lzf_movsb
+ len += 2;
+ lzf_movsb (op, ref, len);
+#else
+ *op++ = *ref++;
+ *op++ = *ref++;
+
+ do
+ *op++ = *ref++;
+ while (--len);
+#endif
+ }
+ }
+ while (ip < in_end);
+
+ return op - (u8 *)out_data;
+}
+
diff --git a/target/bitshuffle-0.3.4/lzf/lzf_filter.c b/target/bitshuffle-0.3.4/lzf/lzf_filter.c
new file mode 100644
index 00000000..c6dd4b0e
--- /dev/null
+++ b/target/bitshuffle-0.3.4/lzf/lzf_filter.c
@@ -0,0 +1,261 @@
+/***** Preamble block *********************************************************
+*
+* This file is part of h5py, a low-level Python interface to the HDF5 library.
+*
+* Copyright (C) 2008 Andrew Collette
+* http://h5py.alfven.org
+* License: BSD (See LICENSE.txt for full license)
+*
+* $Date$
+*
+****** End preamble block ****************************************************/
+
+/*
+ Implements an LZF filter module for HDF5, using the BSD-licensed library
+ by Marc Alexander Lehmann (http://www.goof.com/pcg/marc/liblzf.html).
+
+ No Python-specific code is used. The filter behaves like the DEFLATE
+ filter, in that it is called for every type and space, and returns 0
+ if the data cannot be compressed.
+
+ The only public function is (int) register_lzf(void), which passes on
+ the result from H5Zregister.
+*/
+
+#include
+#include
+#include
+#include "hdf5.h"
+#include "lzf/lzf.h"
+#include "lzf_filter.h"
+
+/* Our own versions of H5Epush_sim, as it changed in 1.8 */
+#if H5_VERS_MAJOR == 1 && H5_VERS_MINOR < 7
+
+#define PUSH_ERR(func, minor, str) H5Epush(__FILE__, func, __LINE__, H5E_PLINE, minor, str)
+#define H5PY_GET_FILTER H5Pget_filter_by_id
+
+#else
+
+#define PUSH_ERR(func, minor, str) H5Epush1(__FILE__, func, __LINE__, H5E_PLINE, minor, str)
+#define H5PY_GET_FILTER(a,b,c,d,e,f,g) H5Pget_filter_by_id2(a,b,c,d,e,f,g,NULL)
+
+#endif
+
+/* Deal with the mutiple definitions for H5Z_class_t.
+ Note: Only HDF5 1.6 and 1.8 are supported.
+
+ (1) The old class should always be used for HDF5 1.6
+ (2) The new class should always be used for HDF5 1.8 < 1.8.3
+ (3) The old class should be used for HDF5 1.8 >= 1.8.3 only if the
+ macro H5_USE_16_API is set
+*/
+
+#if H5_VERS_MAJOR == 1 && H5_VERS_MINOR == 8 && (H5_VERS_RELEASE < 3 || !H5_USE_16_API)
+#define H5PY_H5Z_NEWCLS 1
+#else
+#define H5PY_H5Z_NEWCLS 0
+#endif
+
+size_t lzf_filter(unsigned flags, size_t cd_nelmts,
+ const unsigned cd_values[], size_t nbytes,
+ size_t *buf_size, void **buf);
+
+herr_t lzf_set_local(hid_t dcpl, hid_t type, hid_t space);
+
+
+/* Try to register the filter, passing on the HDF5 return value */
+int register_lzf(void){
+
+ int retval;
+
+#if H5PY_H5Z_NEWCLS
+ H5Z_class_t filter_class = {
+ H5Z_CLASS_T_VERS,
+ (H5Z_filter_t)(H5PY_FILTER_LZF),
+ 1, 1,
+ "lzf",
+ NULL,
+ (H5Z_set_local_func_t)(lzf_set_local),
+ (H5Z_func_t)(lzf_filter)
+ };
+#else
+ H5Z_class_t filter_class = {
+ (H5Z_filter_t)(H5PY_FILTER_LZF),
+ "lzf",
+ NULL,
+ (H5Z_set_local_func_t)(lzf_set_local),
+ (H5Z_func_t)(lzf_filter)
+ };
+#endif
+
+ retval = H5Zregister(&filter_class);
+ if(retval<0){
+ PUSH_ERR("register_lzf", H5E_CANTREGISTER, "Can't register LZF filter");
+ }
+ return retval;
+}
+
+/* Filter setup. Records the following inside the DCPL:
+
+ 1. If version information is not present, set slots 0 and 1 to the filter
+ revision and LZF API version, respectively.
+
+ 2. Compute the chunk size in bytes and store it in slot 2.
+*/
+herr_t lzf_set_local(hid_t dcpl, hid_t type, hid_t space){
+
+ int ndims;
+ int i;
+ herr_t r;
+
+ unsigned int bufsize;
+ hsize_t chunkdims[32];
+
+ unsigned int flags;
+ size_t nelements = 8;
+ unsigned values[] = {0,0,0,0,0,0,0,0};
+
+ r = H5PY_GET_FILTER(dcpl, H5PY_FILTER_LZF, &flags, &nelements, values, 0, NULL);
+ if(r<0) return -1;
+
+ if(nelements < 3) nelements = 3; /* First 3 slots reserved. If any higher
+ slots are used, preserve the contents. */
+
+ /* It seems the H5Z_FLAG_REVERSE flag doesn't work here, so we have to be
+ careful not to clobber any existing version info */
+ if(values[0]==0) values[0] = H5PY_FILTER_LZF_VERSION;
+ if(values[1]==0) values[1] = LZF_VERSION;
+
+ ndims = H5Pget_chunk(dcpl, 32, chunkdims);
+ if(ndims<0) return -1;
+ if(ndims>32){
+ PUSH_ERR("lzf_set_local", H5E_CALLBACK, "Chunk rank exceeds limit");
+ return -1;
+ }
+
+ bufsize = H5Tget_size(type);
+ if(bufsize==0) return -1;
+
+ for(i=0;i=3)&&(cd_values[2]!=0)){
+ outbuf_size = cd_values[2]; /* Precomputed buffer guess */
+ }else{
+ outbuf_size = (*buf_size);
+ }
+
+#ifdef H5PY_LZF_DEBUG
+ fprintf(stderr, "Decompress %d chunk w/buffer %d\n", nbytes, outbuf_size);
+#endif
+
+ while(!status){
+
+ free(outbuf);
+ outbuf = malloc(outbuf_size);
+
+ if(outbuf == NULL){
+ PUSH_ERR("lzf_filter", H5E_CALLBACK, "Can't allocate decompression buffer");
+ goto failed;
+ }
+
+ status = lzf_decompress(*buf, nbytes, outbuf, outbuf_size);
+
+ if(!status){ /* compression failed */
+
+ if(errno == E2BIG){
+ outbuf_size += (*buf_size);
+#ifdef H5PY_LZF_DEBUG
+ fprintf(stderr, " Too small: %d\n", outbuf_size);
+#endif
+ } else if(errno == EINVAL) {
+
+ PUSH_ERR("lzf_filter", H5E_CALLBACK, "Invalid data for LZF decompression");
+ goto failed;
+
+ } else {
+ PUSH_ERR("lzf_filter", H5E_CALLBACK, "Unknown LZF decompression error");
+ goto failed;
+ }
+
+ } /* if !status */
+
+ } /* while !status */
+
+ } /* compressing vs decompressing */
+
+ if(status != 0){
+
+ free(*buf);
+ *buf = outbuf;
+ *buf_size = outbuf_size;
+
+ return status; /* Size of compressed/decompressed data */
+ }
+
+ failed:
+
+ free(outbuf);
+ return 0;
+
+} /* End filter function */
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/target/bitshuffle-0.3.4/lzf/lzf_filter.h b/target/bitshuffle-0.3.4/lzf/lzf_filter.h
new file mode 100644
index 00000000..27dff83a
--- /dev/null
+++ b/target/bitshuffle-0.3.4/lzf/lzf_filter.h
@@ -0,0 +1,38 @@
+/***** Preamble block *********************************************************
+*
+* This file is part of h5py, a low-level Python interface to the HDF5 library.
+*
+* Copyright (C) 2008 Andrew Collette
+* http://h5py.alfven.org
+* License: BSD (See LICENSE.txt for full license)
+*
+* $Date$
+*
+****** End preamble block ****************************************************/
+
+
+#ifndef H5PY_LZF_H
+#define H5PY_LZF_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Filter revision number, starting at 1 */
+#define H5PY_FILTER_LZF_VERSION 4
+
+/* Filter ID registered with the HDF Group as of 2/6/09. For maintenance
+ requests, contact the filter author directly. */
+#define H5PY_FILTER_LZF 32000
+
+/* Register the filter with the library. Returns a negative value on failure,
+ and a non-negative value on success.
+*/
+int register_lzf(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/target/bitshuffle-0.3.4/requirements.txt b/target/bitshuffle-0.3.4/requirements.txt
new file mode 100644
index 00000000..2f0d0fbb
--- /dev/null
+++ b/target/bitshuffle-0.3.4/requirements.txt
@@ -0,0 +1,5 @@
+# Order matters
+setuptools>=0.7
+Cython>=0.19
+numpy>=1.6.1
+h5py>=2.4.0 --no-binary=h5py
diff --git a/target/bitshuffle-0.3.4/setup.cfg.example b/target/bitshuffle-0.3.4/setup.cfg.example
new file mode 100644
index 00000000..6bd2ccfb
--- /dev/null
+++ b/target/bitshuffle-0.3.4/setup.cfg.example
@@ -0,0 +1,10 @@
+[install]
+# These control the installation of the hdf5 dynamically loaded filter plugin.
+h5plugin = 0
+h5plugin-dir = /usr/local/hdf5/lib/plugin
+
+[build_ext]
+# Whether to compile with OpenMP multi-threading. Default is system dependant:
+# False on OSX (since the clang compiler does not yet support OpenMP) and True
+# otherwise.
+omp = 1
diff --git a/target/bitshuffle-0.3.4/setup.py b/target/bitshuffle-0.3.4/setup.py
new file mode 100644
index 00000000..5417dbde
--- /dev/null
+++ b/target/bitshuffle-0.3.4/setup.py
@@ -0,0 +1,303 @@
+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.
+
+import glob
+import os
+from os import path
+from setuptools import setup, Extension
+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_
+import shutil
+import subprocess
+import sys
+
+
+VERSION_MAJOR = 0
+VERSION_MINOR = 3
+VERSION_POINT = 4
+
+# Only unset in the 'release' branch and in tags.
+VERSION_DEV = 0
+
+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']
+# Cython breaks strict aliasing rules.
+COMPILE_FLAGS += ["-fno-strict-aliasing"]
+
+MACROS = [
+ ('BSHUF_VERSION_MAJOR', VERSION_MAJOR),
+ ('BSHUF_VERSION_MINOR', VERSION_MINOR),
+ ('BSHUF_VERSION_POINT', VERSION_POINT),
+]
+
+
+H5PLUGINS_DEFAULT = '/usr/local/hdf5/lib/plugin'
+
+# OSX's clang compliler does not support OpenMP.
+if sys.platform == 'darwin':
+ OMP_DEFAULT = False
+else:
+ OMP_DEFAULT = True
+
+FALLBACK_CONFIG = {
+ 'include_dirs': [],
+ 'library_dirs': [],
+ 'libraries': [],
+ 'extra_compile_args': [],
+ 'extra_link_args': [],
+}
+
+if 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)]
+
+
+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],
+ }
+ 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)
+ for distutils_key in flag_map:
+ config.setdefault(distutils_key, []).extend(
+ 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()
+ opt = config.setdefault(distutils_key, [])
+ opt.extend([i[n:] for i in items])
+ return config
+
+
+ext_bshuf = Extension(
+ "bitshuffle.ext",
+ 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"],
+ libraries=[],
+ extra_compile_args=COMPILE_FLAGS,
+ 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/"],
+ extra_compile_args=COMPILE_FLAGS))
+)
+
+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"],
+ define_macros=MACROS,
+ **pkgconfig("hdf5", config=dict(
+ include_dirs=["src/", "lz4/"],
+ extra_compile_args=['-fPIC', '-g'] + COMPILE_FLAGS))
+)
+
+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/"],
+ extra_compile_args=['-fPIC', '-g'] + COMPILE_FLAGS))
+)
+
+
+EXTENSIONS = [ext_bshuf, h5filter]
+# Check for plugin hdf5 plugin support (hdf5 >= 1.8.11)
+HDF5_PLUGIN_SUPPORT = False
+for p in ["/usr/include"] + pkgconfig("hdf5")["include_dirs"]:
+ if os.path.exists(os.path.join(p, "H5PLextern.h")):
+ HDF5_PLUGIN_SUPPORT = True
+
+if HDF5_PLUGIN_SUPPORT:
+ EXTENSIONS.extend([filter_plugin, lzf_plugin])
+
+
+class develop(develop_):
+ def run(self):
+ # Dummy directory for copying build plugins.
+ 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),
+ ]
+
+ def initialize_options(self):
+ install_.initialize_options(self)
+ self.h5plugin = 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'.")
+ self.h5plugin = int(self.h5plugin)
+ self.h5plugin_dir = path.abspath(self.h5plugin_dir)
+
+ def run(self):
+ install_.run(self)
+ if self.h5plugin:
+ if not HDF5_PLUGIN_SUPPORT:
+ print("HDF5 < 1.8.11, not installing filter plugins.")
+ return
+ plugin_build = path.join(self.build_lib, "bitshuffle", "plugin")
+ try:
+ os.makedirs(self.h5plugin_dir)
+ except OSError as e:
+ if e.args[0] == 17:
+ # Directory already exists, this is fine.
+ pass
+ else:
+ raise
+ 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))
+ 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))
+ ]
+ boolean_options = build_ext_.boolean_options + ['omp']
+
+ def initialize_options(self):
+ build_ext_.initialize_options(self)
+ self.omp = OMP_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):
+ 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())
+
+ if self.omp:
+ if not hasattr(self, "_printed_omp_message"):
+ self._printed_omp_message = True
+ print("\n#################################")
+ print("# Compiling with OpenMP support #")
+ print("#################################\n")
+ # More portable to pass -fopenmp to linker.
+ # self.libraries += ['gomp']
+ for e in self.extensions:
+ if '-fopenmp' not in e.extra_compile_args:
+ e.extra_compile_args += ['-fopenmp']
+ if '-fopenmp' not in e.extra_link_args:
+ e.extra_link_args += ['-fopenmp']
+
+ # 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
+
+
+# Don't install numpy/cython/hdf5 if not needed
+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:
+ requires = f.read().splitlines()
+ requires = [r.split()[0] for r in requires]
+
+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',
+ version=VERSION,
+
+ packages=['bitshuffle', 'bitshuffle.tests'],
+ scripts=[],
+ ext_modules=EXTENSIONS,
+ cmdclass={'build_ext': build_ext, 'install': install, 'develop': develop},
+ setup_requires=setup_requires,
+ install_requires=requires,
+ # extras_require={'H5': ["h5py"]},
+ package_data={'': ['data/*']},
+
+ # metadata for upload to PyPI
+ author="Kiyoshi Wesley Masui",
+ author_email="kiyo@physics.ubc.ca",
+ description="Bitshuffle filter for improving typed data compression.",
+ 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'],
+)
diff --git a/target/bitshuffle-0.3.4/src/bitshuffle.c b/target/bitshuffle-0.3.4/src/bitshuffle.c
new file mode 100644
index 00000000..54ff045f
--- /dev/null
+++ b/target/bitshuffle-0.3.4/src/bitshuffle.c
@@ -0,0 +1,165 @@
+/*
+ * Bitshuffle - Filter for improving compression of typed binary data.
+ *
+ * Author: Kiyoshi Masui
+ * Website: http://www.github.com/kiyo-masui/bitshuffle
+ * Created: 2014
+ *
+ * See LICENSE file for details about copyright and rights to use.
+ *
+ */
+
+#include "bitshuffle.h"
+#include "bitshuffle_core.h"
+#include "bitshuffle_internals.h"
+#include "lz4.h"
+
+#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; }
+
+
+/* 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) {
+
+ int64_t nbytes, count;
+ void *tmp_buf_bshuf;
+ void *tmp_buf_lz4;
+ size_t this_iter;
+ const void *in;
+ void *out;
+
+ tmp_buf_bshuf = malloc(size * elem_size);
+ if (tmp_buf_bshuf == NULL) return -1;
+
+ tmp_buf_lz4 = malloc(LZ4_compressBound(size * elem_size));
+ if (tmp_buf_lz4 == 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_lz4);
+ free(tmp_buf_bshuf);
+ return count;
+ }
+ nbytes = LZ4_compress((const char*) tmp_buf_bshuf, (char*) tmp_buf_lz4, size * elem_size);
+ free(tmp_buf_bshuf);
+ CHECK_ERR_FREE_LZ(nbytes, tmp_buf_lz4);
+
+ 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_lz4, nbytes);
+
+ free(tmp_buf_lz4);
+
+ return nbytes + 4;
+}
+
+
+/* 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) {
+
+ 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;
+
+#ifdef BSHUF_LZ4_DECOMPRESS_FAST
+ nbytes = LZ4_decompress_fast((const char*) in + 4, (char*) tmp_buf, size * elem_size);
+ CHECK_ERR_FREE_LZ(nbytes, tmp_buf);
+ if (nbytes != nbytes_from_header) {
+ free(tmp_buf);
+ return -91;
+ }
+#else
+ 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 != 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;
+
+ free(tmp_buf);
+ return nbytes;
+}
+
+
+/* ---- Public functions ----
+ *
+ * See header file for description and usage.
+ *
+ */
+
+size_t bshuf_compress_lz4_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 = (LZ4_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 += LZ4_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_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);
+}
+
+
+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);
+}
+
diff --git a/target/bitshuffle-0.3.4/src/bitshuffle.h b/target/bitshuffle-0.3.4/src/bitshuffle.h
new file mode 100644
index 00000000..3df95f47
--- /dev/null
+++ b/target/bitshuffle-0.3.4/src/bitshuffle.h
@@ -0,0 +1,123 @@
+/*
+ * Bitshuffle - Filter for improving compression of typed binary data.
+ *
+ * This file is part of Bitshuffle
+ * Author: Kiyoshi Masui
+ * Website: http://www.github.com/kiyo-masui/bitshuffle
+ * Created: 2014
+ *
+ * See LICENSE file for details about copyright and rights to use.
+ *
+ *
+ * Header File
+ *
+ * Worker routines return an int64_t which is the number of bytes processed
+ * if positive or an error code if negative.
+ *
+ * Error codes:
+ * -1 : Failed to allocate memory.
+ * -11 : Missing SSE.
+ * -12 : Missing AVX.
+ * -80 : Input size not a multiple of 8.
+ * -81 : block_size not multiple of 8.
+ * -91 : Decompression error, wrong number of bytes processed.
+ * -1YYY : Error internal to compression routine with error code -YYY.
+ */
+
+
+#ifndef BITSHUFFLE_H
+#define BITSHUFFLE_H
+
+#include
+#include "bitshuffle_core.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* ---- bshuf_compress_lz4_bound ----
+ *
+ * Bound on size of data compressed with *bshuf_compress_lz4*.
+ *
+ * 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_lz4_bound(const size_t size,
+ const size_t elem_size, size_t block_size);
+
+
+/* ---- bshuf_compress_lz4 ----
+ *
+ * Bitshuffled and compress the data using LZ4.
+ *
+ * Transpose within elements, in blocks of data of *block_size* elements then
+ * compress the blocks using LZ4. 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_lz4_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).
+ *
+ * Returns
+ * -------
+ * number of bytes used in output buffer, negative error-code if failed.
+ *
+ */
+int64_t bshuf_compress_lz4(const void* in, void* out, const size_t size, const size_t
+ elem_size, size_t block_size);
+
+
+/* ---- bshuf_decompress_lz4 ----
+ *
+ * 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.
+ *
+ * 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
+ * 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_lz4(const void* in, void* out, const size_t size,
+ const size_t elem_size, size_t block_size);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // BITSHUFFLE_H
diff --git a/target/bitshuffle-0.3.4/src/bitshuffle_core.c b/target/bitshuffle-0.3.4/src/bitshuffle_core.c
new file mode 100644
index 00000000..583e4fe8
--- /dev/null
+++ b/target/bitshuffle-0.3.4/src/bitshuffle_core.c
@@ -0,0 +1,1333 @@
+/*
+ * Bitshuffle - Filter for improving compression of typed binary data.
+ *
+ * Author: Kiyoshi Masui
+ * Website: http://www.github.com/kiyo-masui/bitshuffle
+ * Created: 2014
+ *
+ * See LICENSE file for details about copyright and rights to use.
+ *
+ */
+
+#include "bitshuffle_core.h"
+#include "bitshuffle_internals.h"
+
+#include
+#include
+
+
+#if defined(__AVX2__) && defined (__SSE2__)
+#define USEAVX2
+#endif
+
+#if defined(__SSE2__)
+#define USESSE2
+#endif
+
+
+// Conditional includes for SSE2 and AVX2.
+#ifdef USEAVX2
+#include
+#elif defined USESSE2
+#include
+#endif
+
+
+// Macros.
+#define CHECK_MULT_EIGHT(n) if (n % 8) return -80;
+#define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
+
+
+/* ---- Functions indicating compile time instruction set. ---- */
+
+int bshuf_using_SSE2(void) {
+#ifdef USESSE2
+ return 1;
+#else
+ return 0;
+#endif
+}
+
+
+int bshuf_using_AVX2(void) {
+#ifdef USEAVX2
+ return 1;
+#else
+ return 0;
+#endif
+}
+
+
+/* ---- Worker code not requiring special instruction sets. ----
+ *
+ * The following code does not use any x86 specific vectorized instructions
+ * and should compile on any machine
+ *
+ */
+
+/* Transpose 8x8 bit array packed into a single quadword *x*.
+ * *t* is workspace. */
+#define TRANS_BIT_8X8(x, t) { \
+ t = (x ^ (x >> 7)) & 0x00AA00AA00AA00AALL; \
+ x = x ^ t ^ (t << 7); \
+ t = (x ^ (x >> 14)) & 0x0000CCCC0000CCCCLL; \
+ x = x ^ t ^ (t << 14); \
+ t = (x ^ (x >> 28)) & 0x00000000F0F0F0F0LL; \
+ x = x ^ t ^ (t << 28); \
+ }
+
+/* Transpose 8x8 bit array along the diagonal from upper right
+ to lower left */
+#define TRANS_BIT_8X8_BE(x, t) { \
+ t = (x ^ (x >> 9)) & 0x0055005500550055LL; \
+ x = x ^ t ^ (t << 9); \
+ t = (x ^ (x >> 18)) & 0x0000333300003333LL; \
+ x = x ^ t ^ (t << 18); \
+ t = (x ^ (x >> 36)) & 0x000000000F0F0F0FLL; \
+ x = x ^ t ^ (t << 36); \
+ }
+
+/* Transpose of an array of arbitrarily typed elements. */
+#define TRANS_ELEM_TYPE(in, out, lda, ldb, type_t) { \
+ size_t ii, jj, kk; \
+ const type_t* in_type = (const type_t*) in; \
+ type_t* out_type = (type_t*) out; \
+ for(ii = 0; ii + 7 < lda; ii += 8) { \
+ for(jj = 0; jj < ldb; jj++) { \
+ for(kk = 0; kk < 8; kk++) { \
+ out_type[jj*lda + ii + kk] = \
+ in_type[ii*ldb + kk * ldb + jj]; \
+ } \
+ } \
+ } \
+ for(ii = lda - lda % 8; ii < lda; ii ++) { \
+ for(jj = 0; jj < ldb; jj++) { \
+ out_type[jj*lda + ii] = in_type[ii*ldb + jj]; \
+ } \
+ } \
+ }
+
+
+/* Memory copy with bshuf call signature. For testing and profiling. */
+int64_t bshuf_copy(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+
+ const char* in_b = (const char*) in;
+ char* out_b = (char*) out;
+
+ memcpy(out_b, in_b, size * elem_size);
+ return size * elem_size;
+}
+
+
+/* Transpose bytes within elements, starting partway through input. */
+int64_t bshuf_trans_byte_elem_remainder(const void* in, void* out, const size_t size,
+ const size_t elem_size, const size_t start) {
+
+ size_t ii, jj, kk;
+ const char* in_b = (const char*) in;
+ char* out_b = (char*) out;
+
+ CHECK_MULT_EIGHT(start);
+
+ if (size > start) {
+ // ii loop separated into 2 loops so the compiler can unroll
+ // the inner one.
+ for (ii = start; ii + 7 < size; ii += 8) {
+ for (jj = 0; jj < elem_size; jj++) {
+ for (kk = 0; kk < 8; kk++) {
+ out_b[jj * size + ii + kk]
+ = in_b[ii * elem_size + kk * elem_size + jj];
+ }
+ }
+ }
+ for (ii = size - size % 8; ii < size; ii ++) {
+ for (jj = 0; jj < elem_size; jj++) {
+ out_b[jj * size + ii] = in_b[ii * elem_size + jj];
+ }
+ }
+ }
+ return size * elem_size;
+}
+
+
+/* Transpose bytes within elements. */
+int64_t bshuf_trans_byte_elem_scal(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+
+ return bshuf_trans_byte_elem_remainder(in, out, size, elem_size, 0);
+}
+
+
+/* Transpose bits within bytes. */
+int64_t bshuf_trans_bit_byte_remainder(const void* in, void* out, const size_t size,
+ const size_t elem_size, const size_t start_byte) {
+
+ const uint64_t* in_b = (const uint64_t*) in;
+ uint8_t* out_b = (uint8_t*) out;
+
+ uint64_t x, t;
+
+ size_t ii, kk;
+ size_t nbyte = elem_size * size;
+ size_t nbyte_bitrow = nbyte / 8;
+
+ uint64_t e=1;
+ const int little_endian = *(uint8_t *) &e == 1;
+ const size_t bit_row_skip = little_endian ? nbyte_bitrow : -nbyte_bitrow;
+ const int64_t bit_row_offset = little_endian ? 0 : 7 * nbyte_bitrow;
+
+ CHECK_MULT_EIGHT(nbyte);
+ CHECK_MULT_EIGHT(start_byte);
+
+ for (ii = start_byte / 8; ii < nbyte_bitrow; ii ++) {
+ x = in_b[ii];
+ if (little_endian) {
+ TRANS_BIT_8X8(x, t);
+ } else {
+ TRANS_BIT_8X8_BE(x, t);
+ }
+ for (kk = 0; kk < 8; kk ++) {
+ out_b[bit_row_offset + kk * bit_row_skip + ii] = x;
+ x = x >> 8;
+ }
+ }
+ return size * elem_size;
+}
+
+
+/* Transpose bits within bytes. */
+int64_t bshuf_trans_bit_byte_scal(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+
+ return bshuf_trans_bit_byte_remainder(in, out, size, elem_size, 0);
+}
+
+
+/* General transpose of an array, optimized for large element sizes. */
+int64_t bshuf_trans_elem(const void* in, void* out, const size_t lda,
+ const size_t ldb, const size_t elem_size) {
+
+ size_t ii, jj;
+ const char* in_b = (const char*) in;
+ char* out_b = (char*) out;
+ for(ii = 0; ii < lda; ii++) {
+ for(jj = 0; jj < ldb; jj++) {
+ memcpy(&out_b[(jj*lda + ii) * elem_size],
+ &in_b[(ii*ldb + jj) * elem_size], elem_size);
+ }
+ }
+ return lda * ldb * elem_size;
+}
+
+
+/* Transpose rows of shuffled bits (size / 8 bytes) within groups of 8. */
+int64_t bshuf_trans_bitrow_eight(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+
+ size_t nbyte_bitrow = size / 8;
+
+ CHECK_MULT_EIGHT(size);
+
+ return bshuf_trans_elem(in, out, 8, elem_size, nbyte_bitrow);
+}
+
+
+/* Transpose bits within elements. */
+int64_t bshuf_trans_bit_elem_scal(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+
+ int64_t count;
+ void *tmp_buf;
+
+ CHECK_MULT_EIGHT(size);
+
+ tmp_buf = malloc(size * elem_size);
+ if (tmp_buf == NULL) return -1;
+
+ count = bshuf_trans_byte_elem_scal(in, out, size, elem_size);
+ CHECK_ERR_FREE(count, tmp_buf);
+ count = bshuf_trans_bit_byte_scal(out, tmp_buf, size, elem_size);
+ CHECK_ERR_FREE(count, tmp_buf);
+ count = bshuf_trans_bitrow_eight(tmp_buf, out, size, elem_size);
+
+ free(tmp_buf);
+
+ return count;
+}
+
+
+/* For data organized into a row for each bit (8 * elem_size rows), transpose
+ * the bytes. */
+int64_t bshuf_trans_byte_bitrow_scal(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+ size_t ii, jj, kk, nbyte_row;
+ const char *in_b;
+ char *out_b;
+
+
+ in_b = (const char*) in;
+ out_b = (char*) out;
+
+ nbyte_row = size / 8;
+
+ CHECK_MULT_EIGHT(size);
+
+ for (jj = 0; jj < elem_size; jj++) {
+ for (ii = 0; ii < nbyte_row; ii++) {
+ for (kk = 0; kk < 8; kk++) {
+ out_b[ii * 8 * elem_size + jj * 8 + kk] = \
+ in_b[(jj * 8 + kk) * nbyte_row + ii];
+ }
+ }
+ }
+ return size * elem_size;
+}
+
+
+/* Shuffle bits within the bytes of eight element blocks. */
+int64_t bshuf_shuffle_bit_eightelem_scal(const void* in, void* out, \
+ const size_t size, const size_t elem_size) {
+
+ const char *in_b;
+ char *out_b;
+ uint64_t x, t;
+ size_t ii, jj, kk;
+ size_t nbyte, out_index;
+
+ uint64_t e=1;
+ const int little_endian = *(uint8_t *) &e == 1;
+ const size_t elem_skip = little_endian ? elem_size : -elem_size;
+ const uint64_t elem_offset = little_endian ? 0 : 7 * elem_size;
+
+ CHECK_MULT_EIGHT(size);
+
+ in_b = (const char*) in;
+ out_b = (char*) out;
+
+ nbyte = elem_size * size;
+
+ for (jj = 0; jj < 8 * elem_size; jj += 8) {
+ for (ii = 0; ii + 8 * elem_size - 1 < nbyte; ii += 8 * elem_size) {
+ x = *((uint64_t*) &in_b[ii + jj]);
+ if (little_endian) {
+ TRANS_BIT_8X8(x, t);
+ } else {
+ TRANS_BIT_8X8_BE(x, t);
+ }
+ for (kk = 0; kk < 8; kk++) {
+ out_index = ii + jj / 8 + elem_offset + kk * elem_skip;
+ *((uint8_t*) &out_b[out_index]) = x;
+ x = x >> 8;
+ }
+ }
+ }
+ return size * elem_size;
+}
+
+
+/* Untranspose bits within elements. */
+int64_t bshuf_untrans_bit_elem_scal(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+
+ int64_t count;
+ void *tmp_buf;
+
+ CHECK_MULT_EIGHT(size);
+
+ tmp_buf = malloc(size * elem_size);
+ if (tmp_buf == NULL) return -1;
+
+ count = bshuf_trans_byte_bitrow_scal(in, tmp_buf, size, elem_size);
+ CHECK_ERR_FREE(count, tmp_buf);
+ count = bshuf_shuffle_bit_eightelem_scal(tmp_buf, out, size, elem_size);
+
+ free(tmp_buf);
+
+ return count;
+}
+
+
+/* ---- Worker code that uses SSE2 ----
+ *
+ * The following code makes use of the SSE2 instruction set and specialized
+ * 16 byte registers. The SSE2 instructions are present on modern x86
+ * processors. The first Intel processor microarchitecture supporting SSE2 was
+ * Pentium 4 (2000).
+ *
+ */
+
+#ifdef USESSE2
+
+/* Transpose bytes within elements for 16 bit elements. */
+int64_t bshuf_trans_byte_elem_SSE_16(const void* in, void* out, const size_t size) {
+
+ size_t ii;
+ const char *in_b = (const char*) in;
+ char *out_b = (char*) out;
+ __m128i a0, b0, a1, b1;
+
+ for (ii=0; ii + 15 < size; ii += 16) {
+ a0 = _mm_loadu_si128((__m128i *) &in_b[2*ii + 0*16]);
+ b0 = _mm_loadu_si128((__m128i *) &in_b[2*ii + 1*16]);
+
+ a1 = _mm_unpacklo_epi8(a0, b0);
+ b1 = _mm_unpackhi_epi8(a0, b0);
+
+ a0 = _mm_unpacklo_epi8(a1, b1);
+ b0 = _mm_unpackhi_epi8(a1, b1);
+
+ a1 = _mm_unpacklo_epi8(a0, b0);
+ b1 = _mm_unpackhi_epi8(a0, b0);
+
+ a0 = _mm_unpacklo_epi8(a1, b1);
+ b0 = _mm_unpackhi_epi8(a1, b1);
+
+ _mm_storeu_si128((__m128i *) &out_b[0*size + ii], a0);
+ _mm_storeu_si128((__m128i *) &out_b[1*size + ii], b0);
+ }
+ return bshuf_trans_byte_elem_remainder(in, out, size, 2,
+ size - size % 16);
+}
+
+
+/* Transpose bytes within elements for 32 bit elements. */
+int64_t bshuf_trans_byte_elem_SSE_32(const void* in, void* out, const size_t size) {
+
+ size_t ii;
+ const char *in_b;
+ char *out_b;
+ in_b = (const char*) in;
+ out_b = (char*) out;
+ __m128i a0, b0, c0, d0, a1, b1, c1, d1;
+
+ for (ii=0; ii + 15 < size; ii += 16) {
+ a0 = _mm_loadu_si128((__m128i *) &in_b[4*ii + 0*16]);
+ b0 = _mm_loadu_si128((__m128i *) &in_b[4*ii + 1*16]);
+ c0 = _mm_loadu_si128((__m128i *) &in_b[4*ii + 2*16]);
+ d0 = _mm_loadu_si128((__m128i *) &in_b[4*ii + 3*16]);
+
+ a1 = _mm_unpacklo_epi8(a0, b0);
+ b1 = _mm_unpackhi_epi8(a0, b0);
+ c1 = _mm_unpacklo_epi8(c0, d0);
+ d1 = _mm_unpackhi_epi8(c0, d0);
+
+ a0 = _mm_unpacklo_epi8(a1, b1);
+ b0 = _mm_unpackhi_epi8(a1, b1);
+ c0 = _mm_unpacklo_epi8(c1, d1);
+ d0 = _mm_unpackhi_epi8(c1, d1);
+
+ a1 = _mm_unpacklo_epi8(a0, b0);
+ b1 = _mm_unpackhi_epi8(a0, b0);
+ c1 = _mm_unpacklo_epi8(c0, d0);
+ d1 = _mm_unpackhi_epi8(c0, d0);
+
+ a0 = _mm_unpacklo_epi64(a1, c1);
+ b0 = _mm_unpackhi_epi64(a1, c1);
+ c0 = _mm_unpacklo_epi64(b1, d1);
+ d0 = _mm_unpackhi_epi64(b1, d1);
+
+ _mm_storeu_si128((__m128i *) &out_b[0*size + ii], a0);
+ _mm_storeu_si128((__m128i *) &out_b[1*size + ii], b0);
+ _mm_storeu_si128((__m128i *) &out_b[2*size + ii], c0);
+ _mm_storeu_si128((__m128i *) &out_b[3*size + ii], d0);
+ }
+ return bshuf_trans_byte_elem_remainder(in, out, size, 4,
+ size - size % 16);
+}
+
+
+/* Transpose bytes within elements for 64 bit elements. */
+int64_t bshuf_trans_byte_elem_SSE_64(const void* in, void* out, const size_t size) {
+
+ size_t ii;
+ const char* in_b = (const char*) in;
+ char* out_b = (char*) out;
+ __m128i a0, b0, c0, d0, e0, f0, g0, h0;
+ __m128i a1, b1, c1, d1, e1, f1, g1, h1;
+
+ for (ii=0; ii + 15 < size; ii += 16) {
+ a0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 0*16]);
+ b0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 1*16]);
+ c0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 2*16]);
+ d0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 3*16]);
+ e0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 4*16]);
+ f0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 5*16]);
+ g0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 6*16]);
+ h0 = _mm_loadu_si128((__m128i *) &in_b[8*ii + 7*16]);
+
+ a1 = _mm_unpacklo_epi8(a0, b0);
+ b1 = _mm_unpackhi_epi8(a0, b0);
+ c1 = _mm_unpacklo_epi8(c0, d0);
+ d1 = _mm_unpackhi_epi8(c0, d0);
+ e1 = _mm_unpacklo_epi8(e0, f0);
+ f1 = _mm_unpackhi_epi8(e0, f0);
+ g1 = _mm_unpacklo_epi8(g0, h0);
+ h1 = _mm_unpackhi_epi8(g0, h0);
+
+ a0 = _mm_unpacklo_epi8(a1, b1);
+ b0 = _mm_unpackhi_epi8(a1, b1);
+ c0 = _mm_unpacklo_epi8(c1, d1);
+ d0 = _mm_unpackhi_epi8(c1, d1);
+ e0 = _mm_unpacklo_epi8(e1, f1);
+ f0 = _mm_unpackhi_epi8(e1, f1);
+ g0 = _mm_unpacklo_epi8(g1, h1);
+ h0 = _mm_unpackhi_epi8(g1, h1);
+
+ a1 = _mm_unpacklo_epi32(a0, c0);
+ b1 = _mm_unpackhi_epi32(a0, c0);
+ c1 = _mm_unpacklo_epi32(b0, d0);
+ d1 = _mm_unpackhi_epi32(b0, d0);
+ e1 = _mm_unpacklo_epi32(e0, g0);
+ f1 = _mm_unpackhi_epi32(e0, g0);
+ g1 = _mm_unpacklo_epi32(f0, h0);
+ h1 = _mm_unpackhi_epi32(f0, h0);
+
+ a0 = _mm_unpacklo_epi64(a1, e1);
+ b0 = _mm_unpackhi_epi64(a1, e1);
+ c0 = _mm_unpacklo_epi64(b1, f1);
+ d0 = _mm_unpackhi_epi64(b1, f1);
+ e0 = _mm_unpacklo_epi64(c1, g1);
+ f0 = _mm_unpackhi_epi64(c1, g1);
+ g0 = _mm_unpacklo_epi64(d1, h1);
+ h0 = _mm_unpackhi_epi64(d1, h1);
+
+ _mm_storeu_si128((__m128i *) &out_b[0*size + ii], a0);
+ _mm_storeu_si128((__m128i *) &out_b[1*size + ii], b0);
+ _mm_storeu_si128((__m128i *) &out_b[2*size + ii], c0);
+ _mm_storeu_si128((__m128i *) &out_b[3*size + ii], d0);
+ _mm_storeu_si128((__m128i *) &out_b[4*size + ii], e0);
+ _mm_storeu_si128((__m128i *) &out_b[5*size + ii], f0);
+ _mm_storeu_si128((__m128i *) &out_b[6*size + ii], g0);
+ _mm_storeu_si128((__m128i *) &out_b[7*size + ii], h0);
+ }
+ return bshuf_trans_byte_elem_remainder(in, out, size, 8,
+ size - size % 16);
+}
+
+
+/* Transpose bytes within elements using best SSE algorithm available. */
+int64_t bshuf_trans_byte_elem_SSE(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+
+ int64_t count;
+
+ // Trivial cases: power of 2 bytes.
+ switch (elem_size) {
+ case 1:
+ count = bshuf_copy(in, out, size, elem_size);
+ return count;
+ case 2:
+ count = bshuf_trans_byte_elem_SSE_16(in, out, size);
+ return count;
+ case 4:
+ count = bshuf_trans_byte_elem_SSE_32(in, out, size);
+ return count;
+ case 8:
+ count = bshuf_trans_byte_elem_SSE_64(in, out, size);
+ return count;
+ }
+
+ // Worst case: odd number of bytes. Turns out that this is faster for
+ // (odd * 2) byte elements as well (hence % 4).
+ if (elem_size % 4) {
+ count = bshuf_trans_byte_elem_scal(in, out, size, elem_size);
+ return count;
+ }
+
+ // Multiple of power of 2: transpose hierarchically.
+ {
+ size_t nchunk_elem;
+ void* tmp_buf = malloc(size * elem_size);
+ if (tmp_buf == NULL) return -1;
+
+ if ((elem_size % 8) == 0) {
+ nchunk_elem = elem_size / 8;
+ TRANS_ELEM_TYPE(in, out, size, nchunk_elem, int64_t);
+ count = bshuf_trans_byte_elem_SSE_64(out, tmp_buf,
+ size * nchunk_elem);
+ bshuf_trans_elem(tmp_buf, out, 8, nchunk_elem, size);
+ } else if ((elem_size % 4) == 0) {
+ nchunk_elem = elem_size / 4;
+ TRANS_ELEM_TYPE(in, out, size, nchunk_elem, int32_t);
+ count = bshuf_trans_byte_elem_SSE_32(out, tmp_buf,
+ size * nchunk_elem);
+ bshuf_trans_elem(tmp_buf, out, 4, nchunk_elem, size);
+ } else {
+ // Not used since scalar algorithm is faster.
+ nchunk_elem = elem_size / 2;
+ TRANS_ELEM_TYPE(in, out, size, nchunk_elem, int16_t);
+ count = bshuf_trans_byte_elem_SSE_16(out, tmp_buf,
+ size * nchunk_elem);
+ bshuf_trans_elem(tmp_buf, out, 2, nchunk_elem, size);
+ }
+
+ free(tmp_buf);
+ return count;
+ }
+}
+
+
+/* Transpose bits within bytes. */
+int64_t bshuf_trans_bit_byte_SSE(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+
+ size_t ii, kk;
+ const char* in_b = (const char*) in;
+ char* out_b = (char*) out;
+ uint16_t* out_ui16;
+
+ int64_t count;
+
+ size_t nbyte = elem_size * size;
+
+ CHECK_MULT_EIGHT(nbyte);
+
+ __m128i xmm;
+ int32_t bt;
+
+ for (ii = 0; ii + 15 < nbyte; ii += 16) {
+ xmm = _mm_loadu_si128((__m128i *) &in_b[ii]);
+ for (kk = 0; kk < 8; kk++) {
+ bt = _mm_movemask_epi8(xmm);
+ xmm = _mm_slli_epi16(xmm, 1);
+ out_ui16 = (uint16_t*) &out_b[((7 - kk) * nbyte + ii) / 8];
+ *out_ui16 = bt;
+ }
+ }
+ count = bshuf_trans_bit_byte_remainder(in, out, size, elem_size,
+ nbyte - nbyte % 16);
+ return count;
+}
+
+
+/* Transpose bits within elements. */
+int64_t bshuf_trans_bit_elem_SSE(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+
+ int64_t count;
+
+ CHECK_MULT_EIGHT(size);
+
+ void* tmp_buf = malloc(size * elem_size);
+ if (tmp_buf == NULL) return -1;
+
+ count = bshuf_trans_byte_elem_SSE(in, out, size, elem_size);
+ CHECK_ERR_FREE(count, tmp_buf);
+ count = bshuf_trans_bit_byte_SSE(out, tmp_buf, size, elem_size);
+ CHECK_ERR_FREE(count, tmp_buf);
+ count = bshuf_trans_bitrow_eight(tmp_buf, out, size, elem_size);
+
+ free(tmp_buf);
+
+ return count;
+}
+
+
+/* For data organized into a row for each bit (8 * elem_size rows), transpose
+ * the bytes. */
+int64_t bshuf_trans_byte_bitrow_SSE(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+
+ size_t ii, jj;
+ const char* in_b = (const char*) in;
+ char* out_b = (char*) out;
+
+ CHECK_MULT_EIGHT(size);
+
+ size_t nrows = 8 * elem_size;
+ size_t nbyte_row = size / 8;
+
+ __m128i a0, b0, c0, d0, e0, f0, g0, h0;
+ __m128i a1, b1, c1, d1, e1, f1, g1, h1;
+ __m128 *as, *bs, *cs, *ds, *es, *fs, *gs, *hs;
+
+ for (ii = 0; ii + 7 < nrows; ii += 8) {
+ for (jj = 0; jj + 15 < nbyte_row; jj += 16) {
+ a0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 0)*nbyte_row + jj]);
+ b0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 1)*nbyte_row + jj]);
+ c0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 2)*nbyte_row + jj]);
+ d0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 3)*nbyte_row + jj]);
+ e0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 4)*nbyte_row + jj]);
+ f0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 5)*nbyte_row + jj]);
+ g0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 6)*nbyte_row + jj]);
+ h0 = _mm_loadu_si128((__m128i *) &in_b[(ii + 7)*nbyte_row + jj]);
+
+
+ a1 = _mm_unpacklo_epi8(a0, b0);
+ b1 = _mm_unpacklo_epi8(c0, d0);
+ c1 = _mm_unpacklo_epi8(e0, f0);
+ d1 = _mm_unpacklo_epi8(g0, h0);
+ e1 = _mm_unpackhi_epi8(a0, b0);
+ f1 = _mm_unpackhi_epi8(c0, d0);
+ g1 = _mm_unpackhi_epi8(e0, f0);
+ h1 = _mm_unpackhi_epi8(g0, h0);
+
+
+ a0 = _mm_unpacklo_epi16(a1, b1);
+ b0 = _mm_unpacklo_epi16(c1, d1);
+ c0 = _mm_unpackhi_epi16(a1, b1);
+ d0 = _mm_unpackhi_epi16(c1, d1);
+
+ e0 = _mm_unpacklo_epi16(e1, f1);
+ f0 = _mm_unpacklo_epi16(g1, h1);
+ g0 = _mm_unpackhi_epi16(e1, f1);
+ h0 = _mm_unpackhi_epi16(g1, h1);
+
+
+ a1 = _mm_unpacklo_epi32(a0, b0);
+ b1 = _mm_unpackhi_epi32(a0, b0);
+
+ c1 = _mm_unpacklo_epi32(c0, d0);
+ d1 = _mm_unpackhi_epi32(c0, d0);
+
+ e1 = _mm_unpacklo_epi32(e0, f0);
+ f1 = _mm_unpackhi_epi32(e0, f0);
+
+ g1 = _mm_unpacklo_epi32(g0, h0);
+ h1 = _mm_unpackhi_epi32(g0, h0);
+
+ // We don't have a storeh instruction for integers, so interpret
+ // as a float. Have a storel (_mm_storel_epi64).
+ as = (__m128 *) &a1;
+ bs = (__m128 *) &b1;
+ cs = (__m128 *) &c1;
+ ds = (__m128 *) &d1;
+ es = (__m128 *) &e1;
+ fs = (__m128 *) &f1;
+ gs = (__m128 *) &g1;
+ hs = (__m128 *) &h1;
+
+ _mm_storel_pi((__m64 *) &out_b[(jj + 0) * nrows + ii], *as);
+ _mm_storel_pi((__m64 *) &out_b[(jj + 2) * nrows + ii], *bs);
+ _mm_storel_pi((__m64 *) &out_b[(jj + 4) * nrows + ii], *cs);
+ _mm_storel_pi((__m64 *) &out_b[(jj + 6) * nrows + ii], *ds);
+ _mm_storel_pi((__m64 *) &out_b[(jj + 8) * nrows + ii], *es);
+ _mm_storel_pi((__m64 *) &out_b[(jj + 10) * nrows + ii], *fs);
+ _mm_storel_pi((__m64 *) &out_b[(jj + 12) * nrows + ii], *gs);
+ _mm_storel_pi((__m64 *) &out_b[(jj + 14) * nrows + ii], *hs);
+
+ _mm_storeh_pi((__m64 *) &out_b[(jj + 1) * nrows + ii], *as);
+ _mm_storeh_pi((__m64 *) &out_b[(jj + 3) * nrows + ii], *bs);
+ _mm_storeh_pi((__m64 *) &out_b[(jj + 5) * nrows + ii], *cs);
+ _mm_storeh_pi((__m64 *) &out_b[(jj + 7) * nrows + ii], *ds);
+ _mm_storeh_pi((__m64 *) &out_b[(jj + 9) * nrows + ii], *es);
+ _mm_storeh_pi((__m64 *) &out_b[(jj + 11) * nrows + ii], *fs);
+ _mm_storeh_pi((__m64 *) &out_b[(jj + 13) * nrows + ii], *gs);
+ _mm_storeh_pi((__m64 *) &out_b[(jj + 15) * nrows + ii], *hs);
+ }
+ for (jj = nbyte_row - nbyte_row % 16; jj < nbyte_row; jj ++) {
+ out_b[jj * nrows + ii + 0] = in_b[(ii + 0)*nbyte_row + jj];
+ out_b[jj * nrows + ii + 1] = in_b[(ii + 1)*nbyte_row + jj];
+ out_b[jj * nrows + ii + 2] = in_b[(ii + 2)*nbyte_row + jj];
+ out_b[jj * nrows + ii + 3] = in_b[(ii + 3)*nbyte_row + jj];
+ out_b[jj * nrows + ii + 4] = in_b[(ii + 4)*nbyte_row + jj];
+ out_b[jj * nrows + ii + 5] = in_b[(ii + 5)*nbyte_row + jj];
+ out_b[jj * nrows + ii + 6] = in_b[(ii + 6)*nbyte_row + jj];
+ out_b[jj * nrows + ii + 7] = in_b[(ii + 7)*nbyte_row + jj];
+ }
+ }
+ return size * elem_size;
+}
+
+
+/* Shuffle bits within the bytes of eight element blocks. */
+int64_t bshuf_shuffle_bit_eightelem_SSE(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+
+ CHECK_MULT_EIGHT(size);
+
+ // With a bit of care, this could be written such that such that it is
+ // in_buf = out_buf safe.
+ const char* in_b = (const char*) in;
+ uint16_t* out_ui16 = (uint16_t*) out;
+
+ size_t ii, jj, kk;
+ size_t nbyte = elem_size * size;
+
+ __m128i xmm;
+ int32_t bt;
+
+ if (elem_size % 2) {
+ bshuf_shuffle_bit_eightelem_scal(in, out, size, elem_size);
+ } else {
+ for (ii = 0; ii + 8 * elem_size - 1 < nbyte;
+ ii += 8 * elem_size) {
+ for (jj = 0; jj + 15 < 8 * elem_size; jj += 16) {
+ xmm = _mm_loadu_si128((__m128i *) &in_b[ii + jj]);
+ for (kk = 0; kk < 8; kk++) {
+ bt = _mm_movemask_epi8(xmm);
+ xmm = _mm_slli_epi16(xmm, 1);
+ size_t ind = (ii + jj / 8 + (7 - kk) * elem_size);
+ out_ui16[ind / 2] = bt;
+ }
+ }
+ }
+ }
+ return size * elem_size;
+}
+
+
+/* Untranspose bits within elements. */
+int64_t bshuf_untrans_bit_elem_SSE(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+
+ int64_t count;
+
+ CHECK_MULT_EIGHT(size);
+
+ void* tmp_buf = malloc(size * elem_size);
+ if (tmp_buf == NULL) return -1;
+
+ count = bshuf_trans_byte_bitrow_SSE(in, tmp_buf, size, elem_size);
+ CHECK_ERR_FREE(count, tmp_buf);
+ count = bshuf_shuffle_bit_eightelem_SSE(tmp_buf, out, size, elem_size);
+
+ free(tmp_buf);
+
+ return count;
+}
+
+#else // #ifdef USESSE2
+
+
+int64_t bshuf_untrans_bit_elem_SSE(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+ return -11;
+}
+
+
+int64_t bshuf_trans_bit_elem_SSE(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+ return -11;
+}
+
+
+int64_t bshuf_trans_byte_bitrow_SSE(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+ return -11;
+}
+
+
+int64_t bshuf_trans_bit_byte_SSE(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+ return -11;
+}
+
+
+int64_t bshuf_trans_byte_elem_SSE(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+ return -11;
+}
+
+
+int64_t bshuf_trans_byte_elem_SSE_64(const void* in, void* out, const size_t size) {
+ return -11;
+}
+
+
+int64_t bshuf_trans_byte_elem_SSE_32(const void* in, void* out, const size_t size) {
+ return -11;
+}
+
+
+int64_t bshuf_trans_byte_elem_SSE_16(const void* in, void* out, const size_t size) {
+ return -11;
+}
+
+
+int64_t bshuf_shuffle_bit_eightelem_SSE(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+ return -11;
+}
+
+
+#endif // #ifdef USESSE2
+
+
+/* ---- Code that requires AVX2. Intel Haswell (2013) and later. ---- */
+
+/* ---- Worker code that uses AVX2 ----
+ *
+ * The following code makes use of the AVX2 instruction set and specialized
+ * 32 byte registers. The AVX2 instructions are present on newer x86
+ * processors. The first Intel processor microarchitecture supporting AVX2 was
+ * Haswell (2013).
+ *
+ */
+
+#ifdef USEAVX2
+
+/* Transpose bits within bytes. */
+int64_t bshuf_trans_bit_byte_AVX(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+
+ size_t ii, kk;
+ const char* in_b = (const char*) in;
+ char* out_b = (char*) out;
+ int32_t* out_i32;
+
+ size_t nbyte = elem_size * size;
+
+ int64_t count;
+
+ __m256i ymm;
+ int32_t bt;
+
+ for (ii = 0; ii + 31 < nbyte; ii += 32) {
+ ymm = _mm256_loadu_si256((__m256i *) &in_b[ii]);
+ for (kk = 0; kk < 8; kk++) {
+ bt = _mm256_movemask_epi8(ymm);
+ ymm = _mm256_slli_epi16(ymm, 1);
+ out_i32 = (int32_t*) &out_b[((7 - kk) * nbyte + ii) / 8];
+ *out_i32 = bt;
+ }
+ }
+ count = bshuf_trans_bit_byte_remainder(in, out, size, elem_size,
+ nbyte - nbyte % 32);
+ return count;
+}
+
+
+/* Transpose bits within elements. */
+int64_t bshuf_trans_bit_elem_AVX(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+
+ int64_t count;
+
+ CHECK_MULT_EIGHT(size);
+
+ void* tmp_buf = malloc(size * elem_size);
+ if (tmp_buf == NULL) return -1;
+
+ count = bshuf_trans_byte_elem_SSE(in, out, size, elem_size);
+ CHECK_ERR_FREE(count, tmp_buf);
+ count = bshuf_trans_bit_byte_AVX(out, tmp_buf, size, elem_size);
+ CHECK_ERR_FREE(count, tmp_buf);
+ count = bshuf_trans_bitrow_eight(tmp_buf, out, size, elem_size);
+
+ free(tmp_buf);
+
+ return count;
+}
+
+
+/* For data organized into a row for each bit (8 * elem_size rows), transpose
+ * the bytes. */
+int64_t bshuf_trans_byte_bitrow_AVX(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+
+ size_t hh, ii, jj, kk, mm;
+ const char* in_b = (const char*) in;
+ char* out_b = (char*) out;
+
+ CHECK_MULT_EIGHT(size);
+
+ size_t nrows = 8 * elem_size;
+ size_t nbyte_row = size / 8;
+
+ if (elem_size % 4) return bshuf_trans_byte_bitrow_SSE(in, out, size,
+ elem_size);
+
+ __m256i ymm_0[8];
+ __m256i ymm_1[8];
+ __m256i ymm_storeage[8][4];
+
+ for (jj = 0; jj + 31 < nbyte_row; jj += 32) {
+ for (ii = 0; ii + 3 < elem_size; ii += 4) {
+ for (hh = 0; hh < 4; hh ++) {
+
+ for (kk = 0; kk < 8; kk ++){
+ ymm_0[kk] = _mm256_loadu_si256((__m256i *) &in_b[
+ (ii * 8 + hh * 8 + kk) * nbyte_row + jj]);
+ }
+
+ for (kk = 0; kk < 4; kk ++){
+ ymm_1[kk] = _mm256_unpacklo_epi8(ymm_0[kk * 2],
+ ymm_0[kk * 2 + 1]);
+ ymm_1[kk + 4] = _mm256_unpackhi_epi8(ymm_0[kk * 2],
+ ymm_0[kk * 2 + 1]);
+ }
+
+ for (kk = 0; kk < 2; kk ++){
+ for (mm = 0; mm < 2; mm ++){
+ ymm_0[kk * 4 + mm] = _mm256_unpacklo_epi16(
+ ymm_1[kk * 4 + mm * 2],
+ ymm_1[kk * 4 + mm * 2 + 1]);
+ ymm_0[kk * 4 + mm + 2] = _mm256_unpackhi_epi16(
+ ymm_1[kk * 4 + mm * 2],
+ ymm_1[kk * 4 + mm * 2 + 1]);
+ }
+ }
+
+ for (kk = 0; kk < 4; kk ++){
+ ymm_1[kk * 2] = _mm256_unpacklo_epi32(ymm_0[kk * 2],
+ ymm_0[kk * 2 + 1]);
+ ymm_1[kk * 2 + 1] = _mm256_unpackhi_epi32(ymm_0[kk * 2],
+ ymm_0[kk * 2 + 1]);
+ }
+
+ for (kk = 0; kk < 8; kk ++){
+ ymm_storeage[kk][hh] = ymm_1[kk];
+ }
+ }
+
+ for (mm = 0; mm < 8; mm ++) {
+
+ for (kk = 0; kk < 4; kk ++){
+ ymm_0[kk] = ymm_storeage[mm][kk];
+ }
+
+ ymm_1[0] = _mm256_unpacklo_epi64(ymm_0[0], ymm_0[1]);
+ ymm_1[1] = _mm256_unpacklo_epi64(ymm_0[2], ymm_0[3]);
+ ymm_1[2] = _mm256_unpackhi_epi64(ymm_0[0], ymm_0[1]);
+ ymm_1[3] = _mm256_unpackhi_epi64(ymm_0[2], ymm_0[3]);
+
+ ymm_0[0] = _mm256_permute2x128_si256(ymm_1[0], ymm_1[1], 32);
+ ymm_0[1] = _mm256_permute2x128_si256(ymm_1[2], ymm_1[3], 32);
+ ymm_0[2] = _mm256_permute2x128_si256(ymm_1[0], ymm_1[1], 49);
+ ymm_0[3] = _mm256_permute2x128_si256(ymm_1[2], ymm_1[3], 49);
+
+ _mm256_storeu_si256((__m256i *) &out_b[
+ (jj + mm * 2 + 0 * 16) * nrows + ii * 8], ymm_0[0]);
+ _mm256_storeu_si256((__m256i *) &out_b[
+ (jj + mm * 2 + 0 * 16 + 1) * nrows + ii * 8], ymm_0[1]);
+ _mm256_storeu_si256((__m256i *) &out_b[
+ (jj + mm * 2 + 1 * 16) * nrows + ii * 8], ymm_0[2]);
+ _mm256_storeu_si256((__m256i *) &out_b[
+ (jj + mm * 2 + 1 * 16 + 1) * nrows + ii * 8], ymm_0[3]);
+ }
+ }
+ }
+ for (ii = 0; ii < nrows; ii ++ ) {
+ for (jj = nbyte_row - nbyte_row % 32; jj < nbyte_row; jj ++) {
+ out_b[jj * nrows + ii] = in_b[ii * nbyte_row + jj];
+ }
+ }
+ return size * elem_size;
+}
+
+
+/* Shuffle bits within the bytes of eight element blocks. */
+int64_t bshuf_shuffle_bit_eightelem_AVX(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+
+ CHECK_MULT_EIGHT(size);
+
+ // With a bit of care, this could be written such that such that it is
+ // in_buf = out_buf safe.
+ const char* in_b = (const char*) in;
+ char* out_b = (char*) out;
+
+ size_t ii, jj, kk;
+ size_t nbyte = elem_size * size;
+
+ __m256i ymm;
+ int32_t bt;
+
+ if (elem_size % 4) {
+ return bshuf_shuffle_bit_eightelem_SSE(in, out, size, elem_size);
+ } else {
+ for (jj = 0; jj + 31 < 8 * elem_size; jj += 32) {
+ for (ii = 0; ii + 8 * elem_size - 1 < nbyte;
+ ii += 8 * elem_size) {
+ ymm = _mm256_loadu_si256((__m256i *) &in_b[ii + jj]);
+ for (kk = 0; kk < 8; kk++) {
+ bt = _mm256_movemask_epi8(ymm);
+ ymm = _mm256_slli_epi16(ymm, 1);
+ size_t ind = (ii + jj / 8 + (7 - kk) * elem_size);
+ * (int32_t *) &out_b[ind] = bt;
+ }
+ }
+ }
+ }
+ return size * elem_size;
+}
+
+
+/* Untranspose bits within elements. */
+int64_t bshuf_untrans_bit_elem_AVX(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+
+ int64_t count;
+
+ CHECK_MULT_EIGHT(size);
+
+ void* tmp_buf = malloc(size * elem_size);
+ if (tmp_buf == NULL) return -1;
+
+ count = bshuf_trans_byte_bitrow_AVX(in, tmp_buf, size, elem_size);
+ CHECK_ERR_FREE(count, tmp_buf);
+ count = bshuf_shuffle_bit_eightelem_AVX(tmp_buf, out, size, elem_size);
+
+ free(tmp_buf);
+ return count;
+}
+
+
+#else // #ifdef USEAVX2
+
+int64_t bshuf_trans_bit_byte_AVX(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+ return -12;
+}
+
+
+int64_t bshuf_trans_bit_elem_AVX(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+ return -12;
+}
+
+
+int64_t bshuf_trans_byte_bitrow_AVX(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+ return -12;
+}
+
+
+int64_t bshuf_shuffle_bit_eightelem_AVX(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+ return -12;
+}
+
+
+int64_t bshuf_untrans_bit_elem_AVX(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+ return -12;
+}
+
+#endif // #ifdef USEAVX2
+
+
+/* ---- Drivers selecting best instruction set at compile time. ---- */
+
+int64_t bshuf_trans_bit_elem(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+
+ int64_t count;
+#ifdef USEAVX2
+ count = bshuf_trans_bit_elem_AVX(in, out, size, elem_size);
+#elif defined(USESSE2)
+ count = bshuf_trans_bit_elem_SSE(in, out, size, elem_size);
+#else
+ count = bshuf_trans_bit_elem_scal(in, out, size, elem_size);
+#endif
+ return count;
+}
+
+
+int64_t bshuf_untrans_bit_elem(const void* in, void* out, const size_t size,
+ const size_t elem_size) {
+
+ int64_t count;
+#ifdef USEAVX2
+ count = bshuf_untrans_bit_elem_AVX(in, out, size, elem_size);
+#elif defined(USESSE2)
+ count = bshuf_untrans_bit_elem_SSE(in, out, size, elem_size);
+#else
+ count = bshuf_untrans_bit_elem_scal(in, out, size, elem_size);
+#endif
+ return count;
+}
+
+
+/* ---- Wrappers for implementing blocking ---- */
+
+/* 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) {
+
+ size_t ii;
+ int64_t err = 0;
+ int64_t count, cum_count=0;
+ size_t last_block_size;
+ size_t leftover_bytes;
+ size_t this_iter;
+ char *last_in;
+ char *last_out;
+
+
+ ioc_chain C;
+ ioc_init(&C, in, out);
+
+
+ if (block_size == 0) {
+ block_size = bshuf_default_block_size(elem_size);
+ }
+ if (block_size % BSHUF_BLOCKED_MULT) return -81;
+
+#if defined(_OPENMP)
+ #pragma omp parallel for schedule(dynamic, 1) \
+ private(count) reduction(+ : cum_count)
+#endif
+ for (ii = 0; ii < size / block_size; ii ++) {
+ count = fun(&C, block_size, elem_size);
+ if (count < 0) err = count;
+ cum_count += count;
+ }
+
+ 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);
+ if (count < 0) err = count;
+ cum_count += count;
+ }
+
+ if (err < 0) return err;
+
+ leftover_bytes = size % BSHUF_BLOCKED_MULT * elem_size;
+ //this_iter;
+ last_in = (char *) ioc_get_in(&C, &this_iter);
+ ioc_set_next_in(&C, &this_iter, (void *) (last_in + leftover_bytes));
+ last_out = (char *) ioc_get_out(&C, &this_iter);
+ ioc_set_next_out(&C, &this_iter, (void *) (last_out + leftover_bytes));
+
+ memcpy(last_out, last_in, leftover_bytes);
+
+ ioc_destroy(&C);
+
+ return cum_count + leftover_bytes;
+}
+
+
+/* Bitshuffle a single block. */
+int64_t bshuf_bitshuffle_block(ioc_chain *C_ptr, \
+ const size_t size, const size_t elem_size) {
+
+ size_t this_iter;
+ const void *in;
+ void *out;
+ int64_t count;
+
+
+
+ in = ioc_get_in(C_ptr, &this_iter);
+ ioc_set_next_in(C_ptr, &this_iter,
+ (void*) ((char*) in + size * elem_size));
+ out = ioc_get_out(C_ptr, &this_iter);
+ ioc_set_next_out(C_ptr, &this_iter,
+ (void *) ((char *) out + size * elem_size));
+
+ count = bshuf_trans_bit_elem(in, out, size, elem_size);
+ return count;
+}
+
+
+/* Bitunshuffle a single block. */
+int64_t bshuf_bitunshuffle_block(ioc_chain* C_ptr, \
+ const size_t size, const size_t elem_size) {
+
+
+ size_t this_iter;
+ const void *in;
+ void *out;
+ int64_t count;
+
+
+
+
+ in = ioc_get_in(C_ptr, &this_iter);
+ ioc_set_next_in(C_ptr, &this_iter,
+ (void*) ((char*) in + size * elem_size));
+ out = ioc_get_out(C_ptr, &this_iter);
+ ioc_set_next_out(C_ptr, &this_iter,
+ (void *) ((char *) out + size * elem_size));
+
+ count = bshuf_untrans_bit_elem(in, out, size, elem_size);
+ return count;
+}
+
+
+/* Write a 64 bit unsigned integer to a buffer in big endian order. */
+void bshuf_write_uint64_BE(void* buf, uint64_t num) {
+ int ii;
+ uint8_t* b = (uint8_t*) buf;
+ uint64_t pow28 = 1 << 8;
+ for (ii = 7; ii >= 0; ii--) {
+ b[ii] = num % pow28;
+ num = num / pow28;
+ }
+}
+
+
+/* Read a 64 bit unsigned integer from a buffer big endian order. */
+uint64_t bshuf_read_uint64_BE(void* buf) {
+ int ii;
+ uint8_t* b = (uint8_t*) buf;
+ uint64_t num = 0, pow28 = 1 << 8, cp = 1;
+ for (ii = 7; ii >= 0; ii--) {
+ num += b[ii] * cp;
+ cp *= pow28;
+ }
+ return num;
+}
+
+
+/* Write a 32 bit unsigned integer to a buffer in big endian order. */
+void bshuf_write_uint32_BE(void* buf, uint32_t num) {
+ int ii;
+ uint8_t* b = (uint8_t*) buf;
+ uint32_t pow28 = 1 << 8;
+ for (ii = 3; ii >= 0; ii--) {
+ b[ii] = num % pow28;
+ num = num / pow28;
+ }
+}
+
+
+/* Read a 32 bit unsigned integer from a buffer big endian order. */
+uint32_t bshuf_read_uint32_BE(const void* buf) {
+ int ii;
+ uint8_t* b = (uint8_t*) buf;
+ uint32_t num = 0, pow28 = 1 << 8, cp = 1;
+ for (ii = 3; ii >= 0; ii--) {
+ num += b[ii] * cp;
+ cp *= pow28;
+ }
+ return num;
+}
+
+
+/* ---- Public functions ----
+ *
+ * See header file for description and usage.
+ *
+ */
+
+size_t bshuf_default_block_size(const size_t elem_size) {
+ // This function needs to be absolutely stable between versions.
+ // Otherwise encoded data will not be decodable.
+
+ size_t block_size = BSHUF_TARGET_BLOCK_SIZE_B / elem_size;
+ // Ensure it is a required multiple.
+ block_size = (block_size / BSHUF_BLOCKED_MULT) * BSHUF_BLOCKED_MULT;
+ return MAX(block_size, BSHUF_MIN_RECOMMEND_BLOCK);
+}
+
+
+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);
+}
+
+
+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);
+}
+
+
+#undef TRANS_BIT_8X8
+#undef TRANS_ELEM_TYPE
+#undef MAX
+#undef CHECK_MULT_EIGHT
+#undef CHECK_ERR_FREE
+
+#undef USESSE2
+#undef USEAVX2
diff --git a/target/bitshuffle-0.3.4/src/bitshuffle_core.h b/target/bitshuffle-0.3.4/src/bitshuffle_core.h
new file mode 100644
index 00000000..4516ef40
--- /dev/null
+++ b/target/bitshuffle-0.3.4/src/bitshuffle_core.h
@@ -0,0 +1,156 @@
+/*
+ * Bitshuffle - Filter for improving compression of typed binary data.
+ *
+ * This file is part of Bitshuffle
+ * Author: Kiyoshi Masui
+ * Website: http://www.github.com/kiyo-masui/bitshuffle
+ * Created: 2014
+ *
+ * See LICENSE file for details about copyright and rights to use.
+ *
+ *
+ * Header File
+ *
+ * Worker routines return an int64_t which is the number of bytes processed
+ * if positive or an error code if negative.
+ *
+ * Error codes:
+ * -1 : Failed to allocate memory.
+ * -11 : Missing SSE.
+ * -12 : Missing AVX.
+ * -80 : Input size not a multiple of 8.
+ * -81 : block_size not multiple of 8.
+ * -91 : Decompression error, wrong number of bytes processed.
+ * -1YYY : Error internal to compression routine with error code -YYY.
+ */
+
+
+#ifndef BITSHUFFLE_CORE_H
+#define BITSHUFFLE_CORE_H
+
+// We assume GNU g++ defining `__cplusplus` has stdint.h
+#if (defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199900L) || defined(__cplusplus)
+#include
+#else
+ typedef unsigned char uint8_t;
+ typedef unsigned short uint16_t;
+ typedef unsigned int uint32_t;
+ typedef signed int int32_t;
+ typedef unsigned long long uint64_t;
+ typedef long long int64_t;
+#endif
+
+#include
+
+
+// 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 4
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* --- bshuf_using_SSE2 ----
+ *
+ * Whether routines where compiled with the SSE2 instruction set.
+ *
+ * Returns
+ * -------
+ * 1 if using SSE2, 0 otherwise.
+ *
+ */
+int bshuf_using_SSE2(void);
+
+
+/* ---- bshuf_using_AVX2 ----
+ *
+ * Whether routines where compiled with the AVX2 instruction set.
+ *
+ * Returns
+ * -------
+ * 1 if using AVX2, 0 otherwise.
+ *
+ */
+int bshuf_using_AVX2(void);
+
+
+/* ---- bshuf_default_block_size ----
+ *
+ * The default block size as function of element size.
+ *
+ * This is the block size used by the blocked routines (any routine
+ * taking a *block_size* argument) when the block_size is not provided
+ * (zero is passed).
+ *
+ * The results of this routine are guaranteed to be stable such that
+ * shuffled/compressed data can always be decompressed.
+ *
+ * Parameters
+ * ----------
+ * elem_size : element size of data to be shuffled/compressed.
+ *
+ */
+size_t bshuf_default_block_size(const size_t elem_size);
+
+
+/* ---- bshuf_bitshuffle ----
+ *
+ * Bitshuffle the data.
+ *
+ * Transpose the bits within elements, in blocks of *block_size*
+ * elements.
+ *
+ * Parameters
+ * ----------
+ * in : input buffer, must be of size * elem_size bytes
+ * 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 : Do transpose in blocks of this many elements. Pass 0 to
+ * select automatically (recommended).
+ *
+ * Returns
+ * -------
+ * number of bytes processed, negative error-code if failed.
+ *
+ */
+int64_t bshuf_bitshuffle(const void* in, void* out, const size_t size,
+ const size_t elem_size, size_t block_size);
+
+
+/* ---- bshuf_bitunshuffle ----
+ *
+ * Unshuffle bitshuffled data.
+ *
+ * Untranspose the bits within elements, in blocks of *block_size*
+ * elements.
+ *
+ * To properly unshuffle bitshuffled data, *size*, *elem_size* and *block_size*
+ * must match the parameters used to shuffle the data.
+ *
+ * Parameters
+ * ----------
+ * in : input buffer, must be of size * elem_size bytes
+ * 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 : Do transpose in blocks of this many elements. Pass 0 to
+ * select automatically (recommended).
+ *
+ * Returns
+ * -------
+ * number of bytes processed, negative error-code if failed.
+ *
+ */
+int64_t bshuf_bitunshuffle(const void* in, void* out, const size_t size,
+ const size_t elem_size, size_t block_size);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // BITSHUFFLE_CORE_H
diff --git a/target/bitshuffle-0.3.4/src/bitshuffle_internals.h b/target/bitshuffle-0.3.4/src/bitshuffle_internals.h
new file mode 100644
index 00000000..e039925c
--- /dev/null
+++ b/target/bitshuffle-0.3.4/src/bitshuffle_internals.h
@@ -0,0 +1,75 @@
+/*
+ * Bitshuffle - Filter for improving compression of typed binary data.
+ *
+ * This file is part of Bitshuffle
+ * Author: Kiyoshi Masui
+ * Website: http://www.github.com/kiyo-masui/bitshuffle
+ * Created: 2014
+ *
+ * See LICENSE file for details about copyright and rights to use.
+ */
+
+
+#ifndef BITSHUFFLE_INTERNALS_H
+#define BITSHUFFLE_INTERNALS_H
+
+// We assume GNU g++ defining `__cplusplus` has stdint.h
+#if (defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199900L) || defined(__cplusplus)
+#include
+#else
+ typedef unsigned char uint8_t;
+ typedef unsigned short uint16_t;
+ typedef unsigned int uint32_t;
+ typedef signed int int32_t;
+ typedef unsigned long long uint64_t;
+ typedef long long int64_t;
+#endif
+
+#include
+#include "iochain.h"
+
+
+// Constants.
+#ifndef BSHUF_MIN_RECOMMEND_BLOCK
+#define BSHUF_MIN_RECOMMEND_BLOCK 128
+#define BSHUF_BLOCKED_MULT 8 // Block sizes must be multiple of this.
+#define BSHUF_TARGET_BLOCK_SIZE_B 8192
+#endif
+
+
+// Macros.
+#define CHECK_ERR_FREE(count, buf) if (count < 0) { free(buf); return count; }
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* ---- Utility functions for internal use only ---- */
+
+int64_t bshuf_trans_bit_elem(const void* in, void* out, const size_t size,
+ const size_t elem_size);
+
+/* Read a 32 bit unsigned integer from a buffer big endian order. */
+uint32_t bshuf_read_uint32_BE(const void* buf);
+
+/* Write a 32 bit unsigned integer to a buffer in big endian order. */
+void bshuf_write_uint32_BE(void* buf, uint32_t num);
+
+int64_t bshuf_untrans_bit_elem(const void* in, void* out, const size_t size,
+ const size_t elem_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);
+
+/* 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);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif // BITSHUFFLE_INTERNALS_H
diff --git a/target/bitshuffle-0.3.4/src/bshuf_h5filter.c b/target/bitshuffle-0.3.4/src/bshuf_h5filter.c
new file mode 100644
index 00000000..f67a4a2b
--- /dev/null
+++ b/target/bitshuffle-0.3.4/src/bshuf_h5filter.c
@@ -0,0 +1,218 @@
+/*
+ * Bitshuffle HDF5 filter
+ *
+ * This file is part of Bitshuffle
+ * Author: Kiyoshi Masui
+ * Website: http://www.github.com/kiyo-masui/bitshuffle
+ * Created: 2014
+ *
+ * See LICENSE file for details about copyright and rights to use.
+ *
+ */
+
+#include "bitshuffle.h"
+#include "bshuf_h5filter.h"
+
+
+#define PUSH_ERR(func, minor, str) \
+ H5Epush1(__FILE__, func, __LINE__, H5E_PLINE, minor, str)
+
+
+// Prototypes from bitshuffle.c
+void bshuf_write_uint64_BE(void* buf, uint64_t num);
+uint64_t bshuf_read_uint64_BE(void* buf);
+void bshuf_write_uint32_BE(void* buf, uint32_t num);
+uint32_t bshuf_read_uint32_BE(const void* buf);
+
+
+// Only called on compresion, not on reverse.
+herr_t bshuf_h5_set_local(hid_t dcpl, hid_t type, hid_t space){
+
+ herr_t r;
+ size_t ii;
+
+ unsigned int elem_size;
+
+ unsigned int flags;
+ size_t nelements = 8;
+ size_t nelem_max = 11;
+ unsigned values[] = {0,0,0,0,0,0,0,0,0,0,0};
+ unsigned tmp_values[] = {0,0,0,0,0,0,0,0};
+ char msg[80];
+
+ r = H5Pget_filter_by_id2(dcpl, BSHUF_H5FILTER, &flags, &nelements,
+ tmp_values, 0, NULL, NULL);
+ if(r<0) return -1;
+
+ // First 3 slots reserved. Move any passed options to higher addresses.
+ for (ii=0; ii < nelements && ii + 3 < nelem_max; ii++) {
+ values[ii + 3] = tmp_values[ii];
+ }
+
+ nelements = 3 + nelements;
+
+ values[0] = BSHUF_VERSION_MAJOR;
+ values[1] = BSHUF_VERSION_MINOR;
+
+ elem_size = H5Tget_size(type);
+ if(elem_size <= 0) {
+ PUSH_ERR("bshuf_h5_set_local", H5E_CALLBACK,
+ "Invalid element size.");
+ return -1;
+ }
+
+ values[2] = elem_size;
+
+ // Validate user supplied arguments.
+ if (nelements > 3) {
+ if (values[3] % 8 || values[3] < 0) {
+ sprintf(msg, "Error in bitshuffle. Invalid block size: %d.",
+ values[3]);
+ PUSH_ERR("bshuf_h5_set_local", H5E_CALLBACK, msg);
+ return -1;
+ }
+ }
+ if (nelements > 4) {
+ switch (values[4]) {
+ case 0:
+ break;
+ case BSHUF_H5_COMPRESS_LZ4:
+ break;
+ default:
+ PUSH_ERR("bshuf_h5_set_local", H5E_CALLBACK,
+ "Invalid bitshuffle compression.");
+ }
+ }
+
+ r = H5Pmodify_filter(dcpl, BSHUF_H5FILTER, flags, nelements, values);
+ if(r<0) return -1;
+
+ return 1;
+}
+
+
+size_t bshuf_h5_filter(unsigned int flags, size_t cd_nelmts,
+ const unsigned int cd_values[], size_t nbytes,
+ size_t *buf_size, void **buf) {
+
+ size_t size, elem_size;
+ int err;
+ char msg[80];
+ size_t block_size = 0;
+ size_t buf_size_out, nbytes_uncomp, nbytes_out;
+ char* in_buf = *buf;
+ void *out_buf;
+
+ if (cd_nelmts < 3) {
+ PUSH_ERR("bshuf_h5_filter", H5E_CALLBACK,
+ "Not enough parameters.");
+ return 0;
+ }
+ elem_size = cd_values[2];
+
+ // 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);
+
+ // Compression in addition to bitshiffle.
+ if (cd_nelmts > 4 && cd_values[4] == BSHUF_H5_COMPRESS_LZ4) {
+ if (flags & H5Z_FLAG_REVERSE) {
+ // First eight bytes is the number of bytes in the output buffer,
+ // little endian.
+ nbytes_uncomp = bshuf_read_uint64_BE(in_buf);
+ // Override the block size with the one read from the header.
+ block_size = bshuf_read_uint32_BE((const char*) in_buf + 8) / elem_size;
+ // Skip over the header.
+ in_buf += 12;
+ 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;
+ }
+ } else {
+ nbytes_uncomp = nbytes;
+ buf_size_out = nbytes;
+ }
+
+ // TODO, remove this restriction by memcopying the extra.
+ if (nbytes_uncomp % elem_size) {
+ PUSH_ERR("bshuf_h5_filter", H5E_CALLBACK,
+ "Non integer number of elements.");
+ return 0;
+ }
+ size = nbytes_uncomp / elem_size;
+
+ out_buf = malloc(buf_size_out);
+ if (out_buf == NULL) {
+ PUSH_ERR("bshuf_h5_filter", H5E_CALLBACK,
+ "Could not allocate output buffer.");
+ return 0;
+ }
+
+ if (cd_nelmts > 4 && cd_values[4] == BSHUF_H5_COMPRESS_LZ4) {
+ if (flags & H5Z_FLAG_REVERSE) {
+ // Bit unshuffle/decompress.
+ err = bshuf_decompress_lz4(in_buf, out_buf, size, elem_size, block_size);
+ nbytes_out = nbytes_uncomp;
+ } else {
+ // Bit shuffle/compress.
+ // Write the header, described in
+ // http://www.hdfgroup.org/services/filters/HDF5_LZ4.pdf.
+ // Techincally we should be using signed integers instead of
+ // unsigned ones, however for valid inputs (positive numbers) these
+ // 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) {
+ // Bit unshuffle.
+ err = bshuf_bitunshuffle(in_buf, out_buf, size, elem_size,
+ block_size); } else {
+ // Bit shuffle.
+ err = bshuf_bitshuffle(in_buf, out_buf, size, elem_size,
+ block_size); } nbytes_out = nbytes; }
+ //printf("nb_in %d, nb_uncomp %d, nb_out %d, buf_out %d, block %d\n",
+ //nbytes, nbytes_uncomp, nbytes_out, buf_size_out, block_size);
+
+ if (err < 0) {
+ sprintf(msg, "Error in bitshuffle with error code %d.", err);
+ PUSH_ERR("bshuf_h5_filter", H5E_CALLBACK, msg);
+ free(out_buf);
+ return 0;
+ } else {
+ free(*buf);
+ *buf = out_buf;
+ *buf_size = buf_size_out;
+
+ return nbytes_out;
+ }
+}
+
+
+
+H5Z_class_t bshuf_H5Filter[1] = {{
+ H5Z_CLASS_T_VERS,
+ (H5Z_filter_t)(BSHUF_H5FILTER),
+ 1, 1,
+ "bitshuffle; see https://github.com/kiyo-masui/bitshuffle",
+ NULL,
+ (H5Z_set_local_func_t)(bshuf_h5_set_local),
+ (H5Z_func_t)(bshuf_h5_filter)
+}};
+
+
+int bshuf_register_h5filter(void){
+
+ int retval;
+
+ retval = H5Zregister(bshuf_H5Filter);
+ if(retval<0){
+ PUSH_ERR("bshuf_register_h5filter",
+ H5E_CANTREGISTER, "Can't register bitshuffle filter");
+ }
+ return retval;
+}
+
diff --git a/target/bitshuffle-0.3.4/src/bshuf_h5filter.h b/target/bitshuffle-0.3.4/src/bshuf_h5filter.h
new file mode 100644
index 00000000..0a8fa6a3
--- /dev/null
+++ b/target/bitshuffle-0.3.4/src/bshuf_h5filter.h
@@ -0,0 +1,59 @@
+/*
+ * Bitshuffle HDF5 filter
+ *
+ * This file is part of Bitshuffle
+ * Author: Kiyoshi Masui
+ * Website: http://www.github.com/kiyo-masui/bitshuffle
+ * Created: 2014
+ *
+ * See LICENSE file for details about copyright and rights to use.
+ *
+ *
+ * Header File
+ *
+ * Filter Options
+ * --------------
+ * block_size (option slot 0) : interger (optional)
+ * What block size to use (in elements not bytes). Default is 0,
+ * for which bitshuffle will pick a block size with a target of 8kb.
+ * Compression (option slot 1) : 0 or BSHUF_H5_COMPRESS_LZ4
+ * Whether to apply LZ4 compression to the data after bitshuffling.
+ * This is much faster than applying compression as a second filter
+ * because it is done when the small block of data is already in the
+ * L1 cache.
+ *
+ * For LZ4 compression, the compressed format of the data is the same as
+ * for the normal LZ4 filter described in
+ * http://www.hdfgroup.org/services/filters/HDF5_LZ4.pdf.
+ *
+ */
+
+
+#ifndef BSHUF_H5FILTER_H
+#define BSHUF_H5FILTER_H
+
+#define H5Z_class_t_vers 2
+#include "hdf5.h"
+
+
+#define BSHUF_H5FILTER 32008
+
+
+#define BSHUF_H5_COMPRESS_LZ4 2
+
+
+extern H5Z_class_t bshuf_H5Filter[1];
+
+
+/* ---- bshuf_register_h5filter ----
+ *
+ * Register the bitshuffle HDF5 filter within the HDF5 library.
+ *
+ * Call this before using the bitshuffle HDF5 filter from C unless
+ * using dynamically loaded filters.
+ *
+ */
+int bshuf_register_h5filter(void);
+
+
+#endif // BSHUF_H5FILTER_H
diff --git a/target/bitshuffle-0.3.4/src/bshuf_h5plugin.c b/target/bitshuffle-0.3.4/src/bshuf_h5plugin.c
new file mode 100644
index 00000000..22e99929
--- /dev/null
+++ b/target/bitshuffle-0.3.4/src/bshuf_h5plugin.c
@@ -0,0 +1,19 @@
+/*
+ * Dynamically loaded filter plugin for HDF5 Bitshuffle filter.
+ *
+ * This file is part of Bitshuffle
+ * Author: Kiyoshi Masui
+ * Website: http://www.github.com/kiyo-masui/bitshuffle
+ * Created: 2014
+ *
+ * See LICENSE file for details about copyright and rights to use.
+ *
+ */
+
+
+#include "bshuf_h5filter.h"
+#include "H5PLextern.h"
+
+H5PL_type_t H5PLget_plugin_type(void) {return H5PL_TYPE_FILTER;}
+const void* H5PLget_plugin_info(void) {return bshuf_H5Filter;}
+
diff --git a/target/bitshuffle-0.3.4/src/iochain.c b/target/bitshuffle-0.3.4/src/iochain.c
new file mode 100644
index 00000000..baa97296
--- /dev/null
+++ b/target/bitshuffle-0.3.4/src/iochain.c
@@ -0,0 +1,90 @@
+/*
+ * IOchain - Distribute a chain of dependant IO events amoung threads.
+ *
+ * This file is part of Bitshuffle
+ * Author: Kiyoshi Masui
+ * Website: http://www.github.com/kiyo-masui/bitshuffle
+ * Created: 2014
+ *
+ * See LICENSE file for details about copyright and rights to use.
+ *
+ */
+
+#include
+#include "iochain.h"
+
+
+void ioc_init(ioc_chain *C, const void *in_ptr_0, void *out_ptr_0) {
+#ifdef _OPENMP
+ omp_init_lock(&C->next_lock);
+ for (size_t ii = 0; ii < IOC_SIZE; ii ++) {
+ omp_init_lock(&(C->in_pl[ii].lock));
+ omp_init_lock(&(C->out_pl[ii].lock));
+ }
+#endif
+ C->next = 0;
+ C->in_pl[0].ptr = in_ptr_0;
+ C->out_pl[0].ptr = out_ptr_0;
+}
+
+
+void ioc_destroy(ioc_chain *C) {
+#ifdef _OPENMP
+ omp_destroy_lock(&C->next_lock);
+ for (size_t ii = 0; ii < IOC_SIZE; ii ++) {
+ omp_destroy_lock(&(C->in_pl[ii].lock));
+ omp_destroy_lock(&(C->out_pl[ii].lock));
+ }
+#endif
+}
+
+
+const void * ioc_get_in(ioc_chain *C, size_t *this_iter) {
+#ifdef _OPENMP
+ omp_set_lock(&C->next_lock);
+ #pragma omp flush
+#endif
+ *this_iter = C->next;
+ C->next ++;
+#ifdef _OPENMP
+ omp_set_lock(&(C->in_pl[*this_iter % IOC_SIZE].lock));
+ omp_set_lock(&(C->in_pl[(*this_iter + 1) % IOC_SIZE].lock));
+ omp_set_lock(&(C->out_pl[(*this_iter + 1) % IOC_SIZE].lock));
+ omp_unset_lock(&C->next_lock);
+#endif
+ return C->in_pl[*this_iter % IOC_SIZE].ptr;
+}
+
+
+void ioc_set_next_in(ioc_chain *C, size_t* this_iter, void* in_ptr) {
+ C->in_pl[(*this_iter + 1) % IOC_SIZE].ptr = in_ptr;
+#ifdef _OPENMP
+ omp_unset_lock(&(C->in_pl[(*this_iter + 1) % IOC_SIZE].lock));
+#endif
+}
+
+
+void * ioc_get_out(ioc_chain *C, size_t *this_iter) {
+#ifdef _OPENMP
+ omp_set_lock(&(C->out_pl[(*this_iter) % IOC_SIZE].lock));
+ #pragma omp flush
+#endif
+ void *out_ptr = C->out_pl[*this_iter % IOC_SIZE].ptr;
+#ifdef _OPENMP
+ omp_unset_lock(&(C->out_pl[(*this_iter) % IOC_SIZE].lock));
+#endif
+ return out_ptr;
+}
+
+
+void ioc_set_next_out(ioc_chain *C, size_t *this_iter, void* out_ptr) {
+ C->out_pl[(*this_iter + 1) % IOC_SIZE].ptr = out_ptr;
+#ifdef _OPENMP
+ omp_unset_lock(&(C->out_pl[(*this_iter + 1) % IOC_SIZE].lock));
+ // *in_pl[this_iter]* lock released at the end of the iteration to avoid being
+ // overtaken by previous threads and having *out_pl[this_iter]* corrupted.
+ // Especially worried about thread 0, iteration 0.
+ omp_unset_lock(&(C->in_pl[(*this_iter) % IOC_SIZE].lock));
+#endif
+}
+
diff --git a/target/bitshuffle-0.3.4/src/iochain.h b/target/bitshuffle-0.3.4/src/iochain.h
new file mode 100644
index 00000000..4e225d1b
--- /dev/null
+++ b/target/bitshuffle-0.3.4/src/iochain.h
@@ -0,0 +1,94 @@
+/*
+ * IOchain - Distribute a chain of dependant IO events amoung threads.
+ *
+ * This file is part of Bitshuffle
+ * Author: Kiyoshi Masui
+ * Website: http://www.github.com/kiyo-masui/bitshuffle
+ * Created: 2014
+ *
+ * See LICENSE file for details about copyright and rights to use.
+ *
+ *
+ * Header File
+ *
+ * Similar in concept to a queue. Each task includes reading an input
+ * and writing output, but the location of the input/output (the pointers)
+ * depend on the previous item in the chain.
+ *
+ * This is designed for parallelizing blocked compression/decompression IO,
+ * where the destination of a compressed block depends on the compressed size
+ * of all previous blocks.
+ *
+ * Implemented with OpenMP locks.
+ *
+ *
+ * Usage
+ * -----
+ * - Call `ioc_init` in serial block.
+ * - Each thread should create a local variable *size_t this_iter* and
+ * pass its address to all function calls. Its value will be set
+ * inside the functions and is used to identify the thread.
+ * - Each thread must call each of the `ioc_get*` and `ioc_set*` methods
+ * exactly once per iteration, starting with `ioc_get_in` and ending
+ * with `ioc_set_next_out`.
+ * - The order (`ioc_get_in`, `ioc_set_next_in`, *work*, `ioc_get_out`,
+ * `ioc_set_next_out`, *work*) is most efficient.
+ * - Have each thread call `ioc_end_pop`.
+ * - `ioc_get_in` is blocked until the previous entry's
+ * `ioc_set_next_in` is called.
+ * - `ioc_get_out` is blocked until the previous entry's
+ * `ioc_set_next_out` is called.
+ * - There are no blocks on the very first iteration.
+ * - Call `ioc_destroy` in serial block.
+ * - Safe for num_threads >= IOC_SIZE (but less efficient).
+ *
+ */
+
+
+#ifndef IOCHAIN_H
+#define IOCHAIN_H
+
+
+#include
+#ifdef _OPENMP
+#include
+#endif
+
+
+#define IOC_SIZE 33
+
+
+typedef struct ioc_ptr_and_lock {
+#ifdef _OPENMP
+ omp_lock_t lock;
+#endif
+ void *ptr;
+} ptr_and_lock;
+
+typedef struct ioc_const_ptr_and_lock {
+#ifdef _OPENMP
+ omp_lock_t lock;
+#endif
+ const void *ptr;
+} const_ptr_and_lock;
+
+
+typedef struct ioc_chain {
+#ifdef _OPENMP
+ omp_lock_t next_lock;
+#endif
+ size_t next;
+ const_ptr_and_lock in_pl[IOC_SIZE];
+ ptr_and_lock out_pl[IOC_SIZE];
+} ioc_chain;
+
+
+void ioc_init(ioc_chain *C, const void *in_ptr_0, void *out_ptr_0);
+void ioc_destroy(ioc_chain *C);
+const void * ioc_get_in(ioc_chain *C, size_t *this_iter);
+void ioc_set_next_in(ioc_chain *C, size_t* this_iter, void* in_ptr);
+void * ioc_get_out(ioc_chain *C, size_t *this_iter);
+void ioc_set_next_out(ioc_chain *C, size_t *this_iter, void* out_ptr);
+
+#endif // IOCHAIN_H
+
diff --git a/target/bitshuffle-0.3.4/src/lzf_h5plugin.c b/target/bitshuffle-0.3.4/src/lzf_h5plugin.c
new file mode 100644
index 00000000..cbf7e3d8
--- /dev/null
+++ b/target/bitshuffle-0.3.4/src/lzf_h5plugin.c
@@ -0,0 +1,42 @@
+/*
+ * Dynamically loaded filter plugin for HDF5 LZF filter.
+ *
+ * This file is part of Bitshuffle
+ * Author: Kiyoshi Masui
+ * Website: http://www.github.com/kiyo-masui/bitshuffle
+ * Created: 2014
+ *
+ * See LICENSE file for details about copyright and rights to use.
+ *
+ */
+
+
+#define H5Z_class_t_vers 2
+#include "lzf_filter.h"
+#include "H5PLextern.h"
+
+#include
+
+
+size_t lzf_filter(unsigned flags, size_t cd_nelmts,
+ const unsigned cd_values[], size_t nbytes,
+ size_t *buf_size, void **buf);
+
+
+herr_t lzf_set_local(hid_t dcpl, hid_t type, hid_t space);
+
+
+H5Z_class_t lzf_H5Filter[1] = {{
+ H5Z_CLASS_T_VERS,
+ (H5Z_filter_t)(H5PY_FILTER_LZF),
+ 1, 1,
+ "lzf",
+ NULL,
+ (H5Z_set_local_func_t)(lzf_set_local),
+ (H5Z_func_t)(lzf_filter)
+}};
+
+
+H5PL_type_t H5PLget_plugin_type(void) {return H5PL_TYPE_FILTER;}
+const void* H5PLget_plugin_info(void) {return lzf_H5Filter;}
+
diff --git a/target/snappy-1.1.10/AUTHORS b/target/snappy-1.1.10/AUTHORS
new file mode 100644
index 00000000..4858b377
--- /dev/null
+++ b/target/snappy-1.1.10/AUTHORS
@@ -0,0 +1 @@
+opensource@google.com
diff --git a/target/snappy-1.1.10/CMakeLists.txt b/target/snappy-1.1.10/CMakeLists.txt
new file mode 100644
index 00000000..68686f78
--- /dev/null
+++ b/target/snappy-1.1.10/CMakeLists.txt
@@ -0,0 +1,297 @@
+# Copyright 2019 Google Inc. All Rights Reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+
+cmake_minimum_required(VERSION 3.1)
+project(Snappy VERSION 1.1.8 LANGUAGES C CXX)
+
+# C++ standard can be overridden when this is used as a sub-project.
+if(NOT CMAKE_CXX_STANDARD)
+ # This project requires C++11.
+ set(CMAKE_CXX_STANDARD 11)
+ set(CMAKE_CXX_STANDARD_REQUIRED ON)
+ set(CMAKE_CXX_EXTENSIONS OFF)
+endif(NOT CMAKE_CXX_STANDARD)
+
+# BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to make
+# it prominent in the GUI.
+option(BUILD_SHARED_LIBS "Build shared libraries(DLLs)." OFF)
+
+option(SNAPPY_BUILD_TESTS "Build Snappy's own tests." ON)
+
+option(SNAPPY_FUZZING_BUILD "Build Snappy for fuzzing." OFF)
+
+option(SNAPPY_REQUIRE_AVX "Target processors with AVX support." OFF)
+
+option(SNAPPY_REQUIRE_AVX2 "Target processors with AVX2 support." OFF)
+
+option(SNAPPY_INSTALL "Install Snappy's header and library" ON)
+
+include(TestBigEndian)
+test_big_endian(SNAPPY_IS_BIG_ENDIAN)
+
+include(CheckIncludeFile)
+check_include_file("byteswap.h" HAVE_BYTESWAP_H)
+check_include_file("sys/endian.h" HAVE_SYS_ENDIAN_H)
+check_include_file("sys/mman.h" HAVE_SYS_MMAN_H)
+check_include_file("sys/resource.h" HAVE_SYS_RESOURCE_H)
+check_include_file("sys/time.h" HAVE_SYS_TIME_H)
+check_include_file("sys/uio.h" HAVE_SYS_UIO_H)
+check_include_file("unistd.h" HAVE_UNISTD_H)
+check_include_file("windows.h" HAVE_WINDOWS_H)
+
+include(CheckLibraryExists)
+check_library_exists(z zlibVersion "" HAVE_LIBZ)
+check_library_exists(lzo2 lzo1x_1_15_compress "" HAVE_LIBLZO2)
+
+include(CheckCXXCompilerFlag)
+CHECK_CXX_COMPILER_FLAG("/arch:AVX" HAVE_VISUAL_STUDIO_ARCH_AVX)
+CHECK_CXX_COMPILER_FLAG("/arch:AVX2" HAVE_VISUAL_STUDIO_ARCH_AVX2)
+CHECK_CXX_COMPILER_FLAG("-mavx" HAVE_CLANG_MAVX)
+CHECK_CXX_COMPILER_FLAG("-mbmi2" HAVE_CLANG_MBMI2)
+if(SNAPPY_REQUIRE_AVX2)
+ if(HAVE_VISUAL_STUDIO_ARCH_AVX2)
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /arch:AVX2")
+ endif(HAVE_VISUAL_STUDIO_ARCH_AVX2)
+ if(HAVE_CLANG_MAVX)
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mavx")
+ endif(HAVE_CLANG_MAVX)
+ if(HAVE_CLANG_MBMI2)
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mbmi2")
+ endif(HAVE_CLANG_MBMI2)
+elseif (SNAPPY_REQUIRE_AVX)
+ if(HAVE_VISUAL_STUDIO_ARCH_AVX)
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /arch:AVX")
+ endif(HAVE_VISUAL_STUDIO_ARCH_AVX)
+ if(HAVE_CLANG_MAVX)
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mavx")
+ endif(HAVE_CLANG_MAVX)
+endif(SNAPPY_REQUIRE_AVX2)
+
+include(CheckCXXSourceCompiles)
+check_cxx_source_compiles("
+int main() {
+ return __builtin_expect(0, 1);
+}" HAVE_BUILTIN_EXPECT)
+
+check_cxx_source_compiles("
+int main() {
+ return __builtin_ctzll(0);
+}" HAVE_BUILTIN_CTZ)
+
+check_cxx_source_compiles("
+#include
+
+int main() {
+ const __m128i *src = 0;
+ __m128i dest;
+ const __m128i shuffle_mask = _mm_load_si128(src);
+ const __m128i pattern = _mm_shuffle_epi8(_mm_loadl_epi64(src), shuffle_mask);
+ _mm_storeu_si128(&dest, pattern);
+ return 0;
+}" SNAPPY_HAVE_SSSE3)
+
+check_cxx_source_compiles("
+#include
+int main() {
+ return _bzhi_u32(0, 1);
+}" SNAPPY_HAVE_BMI2)
+
+include(CheckSymbolExists)
+check_symbol_exists("mmap" "sys/mman.h" HAVE_FUNC_MMAP)
+check_symbol_exists("sysconf" "unistd.h" HAVE_FUNC_SYSCONF)
+
+find_package(GTest QUIET)
+if(GTEST_FOUND)
+ set(HAVE_GTEST 1)
+endif(GTEST_FOUND)
+
+find_package(Gflags QUIET)
+if(GFLAGS_FOUND)
+ set(HAVE_GFLAGS 1)
+endif(GFLAGS_FOUND)
+
+configure_file(
+ "cmake/config.h.in"
+ "${PROJECT_BINARY_DIR}/config.h"
+)
+
+# We don't want to define HAVE_ macros in public headers. Instead, we use
+# CMake's variable substitution with 0/1 variables, which will be seen by the
+# preprocessor as constants.
+set(HAVE_SYS_UIO_H_01 ${HAVE_SYS_UIO_H})
+if(NOT HAVE_SYS_UIO_H_01)
+ set(HAVE_SYS_UIO_H_01 0)
+endif(NOT HAVE_SYS_UIO_H_01)
+
+if (SNAPPY_FUZZING_BUILD)
+ if (NOT "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
+ message(WARNING "Fuzzing builds are only supported with Clang")
+ endif (NOT "${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
+
+ if(NOT CMAKE_CXX_FLAGS MATCHES "-fsanitize=address")
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address")
+ endif(NOT CMAKE_CXX_FLAGS MATCHES "-fsanitize=address")
+
+ if(NOT CMAKE_CXX_FLAGS MATCHES "-fsanitize=fuzzer-no-link")
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=fuzzer-no-link")
+ endif(NOT CMAKE_CXX_FLAGS MATCHES "-fsanitize=fuzzer-no-link")
+endif (SNAPPY_FUZZING_BUILD)
+
+configure_file(
+ "snappy-stubs-public.h.in"
+ "${PROJECT_BINARY_DIR}/snappy-stubs-public.h")
+
+add_library(snappy "")
+target_sources(snappy
+ PRIVATE
+ "snappy-internal.h"
+ "snappy-stubs-internal.h"
+ "snappy-c.cc"
+ "snappy-sinksource.cc"
+ "snappy-stubs-internal.cc"
+ "snappy.cc"
+ "${PROJECT_BINARY_DIR}/config.h"
+
+ # Only CMake 3.3+ supports PUBLIC sources in targets exported by "install".
+ $<$:PUBLIC>
+ $
+ $
+ $
+ $
+ $
+ $
+ $
+ $
+)
+target_include_directories(snappy
+ PUBLIC
+ $
+ $
+ $
+)
+set_target_properties(snappy
+ PROPERTIES VERSION ${PROJECT_VERSION} SOVERSION ${PROJECT_VERSION_MAJOR})
+
+target_compile_definitions(snappy PRIVATE -DHAVE_CONFIG_H)
+if(BUILD_SHARED_LIBS)
+ set_target_properties(snappy PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON)
+endif(BUILD_SHARED_LIBS)
+
+if(SNAPPY_BUILD_TESTS)
+ enable_testing()
+
+ add_executable(snappy_unittest "")
+ target_sources(snappy_unittest
+ PRIVATE
+ "snappy_unittest.cc"
+ "snappy-test.cc"
+ )
+ target_compile_definitions(snappy_unittest PRIVATE -DHAVE_CONFIG_H)
+ target_link_libraries(snappy_unittest snappy ${GFLAGS_LIBRARIES})
+
+ if(HAVE_LIBZ)
+ target_link_libraries(snappy_unittest z)
+ endif(HAVE_LIBZ)
+ if(HAVE_LIBLZO2)
+ target_link_libraries(snappy_unittest lzo2)
+ endif(HAVE_LIBLZO2)
+
+ target_include_directories(snappy_unittest
+ BEFORE PRIVATE
+ "${PROJECT_SOURCE_DIR}"
+ "${GTEST_INCLUDE_DIRS}"
+ "${GFLAGS_INCLUDE_DIRS}"
+ )
+
+ add_test(
+ NAME snappy_unittest
+ WORKING_DIRECTORY "${PROJECT_SOURCE_DIR}"
+ COMMAND "${PROJECT_BINARY_DIR}/snappy_unittest")
+endif(SNAPPY_BUILD_TESTS)
+
+if(SNAPPY_FUZZING_BUILD)
+ add_executable(snappy_compress_fuzzer "")
+ target_sources(snappy_compress_fuzzer
+ PRIVATE "snappy_compress_fuzzer.cc"
+ )
+ target_link_libraries(snappy_compress_fuzzer snappy)
+ set_target_properties(snappy_compress_fuzzer
+ PROPERTIES LINK_FLAGS "-fsanitize=fuzzer"
+ )
+
+ add_executable(snappy_uncompress_fuzzer "")
+ target_sources(snappy_uncompress_fuzzer
+ PRIVATE "snappy_uncompress_fuzzer.cc"
+ )
+ target_link_libraries(snappy_uncompress_fuzzer snappy)
+ set_target_properties(snappy_uncompress_fuzzer
+ PROPERTIES LINK_FLAGS "-fsanitize=fuzzer"
+ )
+endif(SNAPPY_FUZZING_BUILD)
+
+# Must be included before CMAKE_INSTALL_INCLUDEDIR is used.
+include(GNUInstallDirs)
+
+if(SNAPPY_INSTALL)
+ install(TARGETS snappy
+ EXPORT SnappyTargets
+ RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
+ LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
+ )
+ install(
+ FILES
+ "snappy-c.h"
+ "snappy-sinksource.h"
+ "snappy.h"
+ "${PROJECT_BINARY_DIR}/snappy-stubs-public.h"
+ DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
+ )
+
+ include(CMakePackageConfigHelpers)
+ configure_package_config_file(
+ "cmake/${PROJECT_NAME}Config.cmake.in"
+ "${PROJECT_BINARY_DIR}/cmake/${PROJECT_NAME}Config.cmake"
+ INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}"
+ )
+ write_basic_package_version_file(
+ "${PROJECT_BINARY_DIR}/cmake/${PROJECT_NAME}ConfigVersion.cmake"
+ COMPATIBILITY SameMajorVersion
+ )
+ install(
+ EXPORT SnappyTargets
+ NAMESPACE Snappy::
+ DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}"
+ )
+ install(
+ FILES
+ "${PROJECT_BINARY_DIR}/cmake/${PROJECT_NAME}Config.cmake"
+ "${PROJECT_BINARY_DIR}/cmake/${PROJECT_NAME}ConfigVersion.cmake"
+ DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}"
+ )
+endif(SNAPPY_INSTALL)
diff --git a/target/snappy-1.1.10/CONTRIBUTING.md b/target/snappy-1.1.10/CONTRIBUTING.md
new file mode 100644
index 00000000..c7b84516
--- /dev/null
+++ b/target/snappy-1.1.10/CONTRIBUTING.md
@@ -0,0 +1,26 @@
+# How to Contribute
+
+We'd love to accept your patches and contributions to this project. There are
+just a few small guidelines you need to follow.
+
+## Contributor License Agreement
+
+Contributions to this project must be accompanied by a Contributor License
+Agreement. You (or your employer) retain the copyright to your contribution,
+this simply gives us permission to use and redistribute your contributions as
+part of the project. Head over to to see
+your current agreements on file or to sign a new one.
+
+You generally only need to submit a CLA once, so if you've already submitted one
+(even if it was for a different project), you probably don't need to do it
+again.
+
+## Code reviews
+
+All submissions, including submissions by project members, require review. We
+use GitHub pull requests for this purpose. Consult
+[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
+information on using pull requests.
+
+Please make sure that all the automated checks (CLA, AppVeyor, Travis) pass for
+your pull requests. Pull requests whose checks fail may be ignored.
diff --git a/target/snappy-1.1.10/COPYING b/target/snappy-1.1.10/COPYING
new file mode 100644
index 00000000..bd0e5971
--- /dev/null
+++ b/target/snappy-1.1.10/COPYING
@@ -0,0 +1,54 @@
+Copyright 2011, Google Inc.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+ * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+
+===
+
+Some of the benchmark data in testdata/ is licensed differently:
+
+ - fireworks.jpeg is Copyright 2013 Steinar H. Gunderson, and
+ is licensed under the Creative Commons Attribution 3.0 license
+ (CC-BY-3.0). See https://creativecommons.org/licenses/by/3.0/
+ for more information.
+
+ - kppkn.gtb is taken from the Gaviota chess tablebase set, and
+ is licensed under the MIT License. See
+ https://sites.google.com/site/gaviotachessengine/Home/endgame-tablebases-1
+ for more information.
+
+ - paper-100k.pdf is an excerpt (bytes 92160 to 194560) from the paper
+ “Combinatorial Modeling of Chromatin Features Quantitatively Predicts DNA
+ Replication Timing in _Drosophila_” by Federico Comoglio and Renato Paro,
+ which is licensed under the CC-BY license. See
+ http://www.ploscompbiol.org/static/license for more ifnormation.
+
+ - alice29.txt, asyoulik.txt, plrabn12.txt and lcet10.txt are from Project
+ Gutenberg. The first three have expired copyrights and are in the public
+ domain; the latter does not have expired copyright, but is still in the
+ public domain according to the license information
+ (http://www.gutenberg.org/ebooks/53).
diff --git a/target/snappy-1.1.10/NEWS b/target/snappy-1.1.10/NEWS
new file mode 100644
index 00000000..98048dbd
--- /dev/null
+++ b/target/snappy-1.1.10/NEWS
@@ -0,0 +1,188 @@
+Snappy v1.1.8, January 15th 2020:
+
+ * Small performance improvements.
+
+ * Removed snappy::string alias for std::string.
+
+ * Improved CMake configuration.
+
+Snappy v1.1.7, August 24th 2017:
+
+ * Improved CMake build support for 64-bit Linux distributions.
+
+ * MSVC builds now use MSVC-specific intrinsics that map to clzll.
+
+ * ARM64 (AArch64) builds use the code paths optimized for 64-bit processors.
+
+Snappy v1.1.6, July 12th 2017:
+
+This is a re-release of v1.1.5 with proper SONAME / SOVERSION values.
+
+Snappy v1.1.5, June 28th 2017:
+
+This release has broken SONAME / SOVERSION values. Users of snappy as a shared
+library should avoid 1.1.5 and use 1.1.6 instead. SONAME / SOVERSION errors will
+manifest as the dynamic library loader complaining that it cannot find snappy's
+shared library file (libsnappy.so / libsnappy.dylib), or that the library it
+found does not have the required version. 1.1.6 has the same code as 1.1.5, but
+carries build configuration fixes for the issues above.
+
+ * Add CMake build support. The autoconf build support is now deprecated, and
+ will be removed in the next release.
+
+ * Add AppVeyor configuration, for Windows CI coverage.
+
+ * Small performance improvement on little-endian PowerPC.
+
+ * Small performance improvement on LLVM with position-independent executables.
+
+ * Fix a few issues with various build environments.
+
+Snappy v1.1.4, January 25th 2017:
+
+ * Fix a 1% performance regression when snappy is used in PIE executables.
+
+ * Improve compression performance by 5%.
+
+ * Improve decompression performance by 20%.
+
+Snappy v1.1.3, July 6th 2015:
+
+This is the first release to be done from GitHub, which means that
+some minor things like the ChangeLog format has changed (git log
+format instead of svn log).
+
+ * Add support for Uncompress() from a Source to a Sink.
+
+ * Various minor changes to improve MSVC support; in particular,
+ the unit tests now compile and run under MSVC.
+
+
+Snappy v1.1.2, February 28th 2014:
+
+This is a maintenance release with no changes to the actual library
+source code.
+
+ * Stop distributing benchmark data files that have unclear
+ or unsuitable licensing.
+
+ * Add support for padding chunks in the framing format.
+
+
+Snappy v1.1.1, October 15th 2013:
+
+ * Add support for uncompressing to iovecs (scatter I/O).
+ The bulk of this patch was contributed by Mohit Aron.
+
+ * Speed up decompression by ~2%; much more so (~13-20%) on
+ a few benchmarks on given compilers and CPUs.
+
+ * Fix a few issues with MSVC compilation.
+
+ * Support truncated test data in the benchmark.
+
+
+Snappy v1.1.0, January 18th 2013:
+
+ * Snappy now uses 64 kB block size instead of 32 kB. On average,
+ this means it compresses about 3% denser (more so for some
+ inputs), at the same or better speeds.
+
+ * libsnappy no longer depends on iostream.
+
+ * Some small performance improvements in compression on x86
+ (0.5–1%).
+
+ * Various portability fixes for ARM-based platforms, for MSVC,
+ and for GNU/Hurd.
+
+
+Snappy v1.0.5, February 24th 2012:
+
+ * More speed improvements. Exactly how big will depend on
+ the architecture:
+
+ - 3–10% faster decompression for the base case (x86-64).
+
+ - ARMv7 and higher can now use unaligned accesses,
+ and will see about 30% faster decompression and
+ 20–40% faster compression.
+
+ - 32-bit platforms (ARM and 32-bit x86) will see 2–5%
+ faster compression.
+
+ These are all cumulative (e.g., ARM gets all three speedups).
+
+ * Fixed an issue where the unit test would crash on system
+ with less than 256 MB address space available,
+ e.g. some embedded platforms.
+
+ * Added a framing format description, for use over e.g. HTTP,
+ or for a command-line compressor. We do not have any
+ implementations of this at the current point, but there seems
+ to be enough of a general interest in the topic.
+ Also make the format description slightly clearer.
+
+ * Remove some compile-time warnings in -Wall
+ (mostly signed/unsigned comparisons), for easier embedding
+ into projects that use -Wall -Werror.
+
+
+Snappy v1.0.4, September 15th 2011:
+
+ * Speeded up the decompressor somewhat; typically about 2–8%
+ for Core i7, in 64-bit mode (comparable for Opteron).
+ Somewhat more for some tests, almost no gain for others.
+
+ * Make Snappy compile on certain platforms it didn't before
+ (Solaris with SunPro C++, HP-UX, AIX).
+
+ * Correct some minor errors in the format description.
+
+
+Snappy v1.0.3, June 2nd 2011:
+
+ * Speeded up the decompressor somewhat; about 3-6% for Core 2,
+ 6-13% for Core i7, and 5-12% for Opteron (all in 64-bit mode).
+
+ * Added compressed format documentation. This text is new,
+ but an earlier version from Zeev Tarantov was used as reference.
+
+ * Only link snappy_unittest against -lz and other autodetected
+ libraries, not libsnappy.so (which doesn't need any such dependency).
+
+ * Fixed some display issues in the microbenchmarks, one of which would
+ frequently make the test crash on GNU/Hurd.
+
+
+Snappy v1.0.2, April 29th 2011:
+
+ * Relicense to a BSD-type license.
+
+ * Added C bindings, contributed by Martin Gieseking.
+
+ * More Win32 fixes, in particular for MSVC.
+
+ * Replace geo.protodata with a newer version.
+
+ * Fix timing inaccuracies in the unit test when comparing Snappy
+ to other algorithms.
+
+
+Snappy v1.0.1, March 25th 2011:
+
+This is a maintenance release, mostly containing minor fixes.
+There is no new functionality. The most important fixes include:
+
+ * The COPYING file and all licensing headers now correctly state that
+ Snappy is licensed under the Apache 2.0 license.
+
+ * snappy_unittest should now compile natively under Windows,
+ as well as on embedded systems with no mmap().
+
+ * Various autotools nits have been fixed.
+
+
+Snappy v1.0, March 17th 2011:
+
+ * Initial version.
diff --git a/target/snappy-1.1.10/README.md b/target/snappy-1.1.10/README.md
new file mode 100644
index 00000000..cef40174
--- /dev/null
+++ b/target/snappy-1.1.10/README.md
@@ -0,0 +1,148 @@
+Snappy, a fast compressor/decompressor.
+
+
+Introduction
+============
+
+Snappy is a compression/decompression library. It does not aim for maximum
+compression, or compatibility with any other compression library; instead,
+it aims for very high speeds and reasonable compression. For instance,
+compared to the fastest mode of zlib, Snappy is an order of magnitude faster
+for most inputs, but the resulting compressed files are anywhere from 20% to
+100% bigger. (For more information, see "Performance", below.)
+
+Snappy has the following properties:
+
+ * Fast: Compression speeds at 250 MB/sec and beyond, with no assembler code.
+ See "Performance" below.
+ * Stable: Over the last few years, Snappy has compressed and decompressed
+ petabytes of data in Google's production environment. The Snappy bitstream
+ format is stable and will not change between versions.
+ * Robust: The Snappy decompressor is designed not to crash in the face of
+ corrupted or malicious input.
+ * Free and open source software: Snappy is licensed under a BSD-type license.
+ For more information, see the included COPYING file.
+
+Snappy has previously been called "Zippy" in some Google presentations
+and the like.
+
+
+Performance
+===========
+
+Snappy is intended to be fast. On a single core of a Core i7 processor
+in 64-bit mode, it compresses at about 250 MB/sec or more and decompresses at
+about 500 MB/sec or more. (These numbers are for the slowest inputs in our
+benchmark suite; others are much faster.) In our tests, Snappy usually
+is faster than algorithms in the same class (e.g. LZO, LZF, QuickLZ,
+etc.) while achieving comparable compression ratios.
+
+Typical compression ratios (based on the benchmark suite) are about 1.5-1.7x
+for plain text, about 2-4x for HTML, and of course 1.0x for JPEGs, PNGs and
+other already-compressed data. Similar numbers for zlib in its fastest mode
+are 2.6-2.8x, 3-7x and 1.0x, respectively. More sophisticated algorithms are
+capable of achieving yet higher compression rates, although usually at the
+expense of speed. Of course, compression ratio will vary significantly with
+the input.
+
+Although Snappy should be fairly portable, it is primarily optimized
+for 64-bit x86-compatible processors, and may run slower in other environments.
+In particular:
+
+ - Snappy uses 64-bit operations in several places to process more data at
+ once than would otherwise be possible.
+ - Snappy assumes unaligned 32 and 64-bit loads and stores are cheap.
+ On some platforms, these must be emulated with single-byte loads
+ and stores, which is much slower.
+ - Snappy assumes little-endian throughout, and needs to byte-swap data in
+ several places if running on a big-endian platform.
+
+Experience has shown that even heavily tuned code can be improved.
+Performance optimizations, whether for 64-bit x86 or other platforms,
+are of course most welcome; see "Contact", below.
+
+
+Building
+========
+
+You need the CMake version specified in [CMakeLists.txt](./CMakeLists.txt)
+or later to build:
+
+```bash
+mkdir build
+cd build && cmake ../ && make
+```
+
+Usage
+=====
+
+Note that Snappy, both the implementation and the main interface,
+is written in C++. However, several third-party bindings to other languages
+are available; see the [home page](docs/README.md) for more information.
+Also, if you want to use Snappy from C code, you can use the included C
+bindings in snappy-c.h.
+
+To use Snappy from your own C++ program, include the file "snappy.h" from
+your calling file, and link against the compiled library.
+
+There are many ways to call Snappy, but the simplest possible is
+
+```c++
+snappy::Compress(input.data(), input.size(), &output);
+```
+
+and similarly
+
+```c++
+snappy::Uncompress(input.data(), input.size(), &output);
+```
+
+where "input" and "output" are both instances of std::string.
+
+There are other interfaces that are more flexible in various ways, including
+support for custom (non-array) input sources. See the header file for more
+information.
+
+
+Tests and benchmarks
+====================
+
+When you compile Snappy, snappy_unittest is compiled in addition to the
+library itself. You do not need it to use the compressor from your own library,
+but it contains several useful components for Snappy development.
+
+First of all, it contains unit tests, verifying correctness on your machine in
+various scenarios. If you want to change or optimize Snappy, please run the
+tests to verify you have not broken anything. Note that if you have the
+Google Test library installed, unit test behavior (especially failures) will be
+significantly more user-friendly. You can find Google Test at
+
+ https://github.com/google/googletest
+
+You probably also want the gflags library for handling of command-line flags;
+you can find it at
+
+ https://gflags.github.io/gflags/
+
+In addition to the unit tests, snappy contains microbenchmarks used to
+tune compression and decompression performance. These are automatically run
+before the unit tests, but you can disable them using the flag
+--run_microbenchmarks=false if you have gflags installed (otherwise you will
+need to edit the source).
+
+Finally, snappy can benchmark Snappy against a few other compression libraries
+(zlib, LZO, LZF, and QuickLZ), if they were detected at configure time.
+To benchmark using a given file, give the compression algorithm you want to test
+Snappy against (e.g. --zlib) and then a list of one or more file names on the
+command line. The testdata/ directory contains the files used by the
+microbenchmark, which should provide a reasonably balanced starting point for
+benchmarking. (Note that baddata[1-3].snappy are not intended as benchmarks; they
+are used to verify correctness in the presence of corrupted data in the unit
+test.)
+
+
+Contact
+=======
+
+Snappy is distributed through GitHub. For the latest version, a bug tracker,
+and other information, see https://github.com/google/snappy.
diff --git a/target/snappy-1.1.10/cmake/SnappyConfig.cmake.in b/target/snappy-1.1.10/cmake/SnappyConfig.cmake.in
new file mode 100644
index 00000000..9e7d1346
--- /dev/null
+++ b/target/snappy-1.1.10/cmake/SnappyConfig.cmake.in
@@ -0,0 +1,33 @@
+# Copyright 2019 Google Inc. All Rights Reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are
+# met:
+#
+# * Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+# * Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following disclaimer
+# in the documentation and/or other materials provided with the
+# distribution.
+# * Neither the name of Google Inc. nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+
+@PACKAGE_INIT@
+
+include("${CMAKE_CURRENT_LIST_DIR}/SnappyTargets.cmake")
+
+check_required_components(Snappy)
\ No newline at end of file
diff --git a/target/snappy-1.1.10/cmake/config.h.in b/target/snappy-1.1.10/cmake/config.h.in
new file mode 100644
index 00000000..24f27efe
--- /dev/null
+++ b/target/snappy-1.1.10/cmake/config.h.in
@@ -0,0 +1,62 @@
+#ifndef THIRD_PARTY_SNAPPY_OPENSOURCE_CMAKE_CONFIG_H_
+#define THIRD_PARTY_SNAPPY_OPENSOURCE_CMAKE_CONFIG_H_
+
+/* Define to 1 if the compiler supports __builtin_ctz and friends. */
+#cmakedefine HAVE_BUILTIN_CTZ 1
+
+/* Define to 1 if the compiler supports __builtin_expect. */
+#cmakedefine HAVE_BUILTIN_EXPECT 1
+
+/* Define to 1 if you have the header file. */
+#cmakedefine HAVE_BYTESWAP_H 1
+
+/* Define to 1 if you have a definition for mmap() in . */
+#cmakedefine HAVE_FUNC_MMAP 1
+
+/* Define to 1 if you have a definition for sysconf() in . */
+#cmakedefine HAVE_FUNC_SYSCONF 1
+
+/* Define to 1 to use the gflags package for command-line parsing. */
+#cmakedefine HAVE_GFLAGS 1
+
+/* Define to 1 if you have Google Test. */
+#cmakedefine HAVE_GTEST 1
+
+/* Define to 1 if you have the `lzo2' library (-llzo2). */
+#cmakedefine HAVE_LIBLZO2 1
+
+/* Define to 1 if you have the `z' library (-lz). */
+#cmakedefine HAVE_LIBZ 1
+
+/* Define to 1 if you have the header file. */
+#cmakedefine HAVE_SYS_ENDIAN_H 1
+
+/* Define to 1 if you have the header file. */
+#cmakedefine HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the header file. */
+#cmakedefine HAVE_SYS_RESOURCE_H 1
+
+/* Define to 1 if you have the header file. */
+#cmakedefine HAVE_SYS_TIME_H 1
+
+/* Define to 1 if you have the header file. */
+#cmakedefine HAVE_SYS_UIO_H 1
+
+/* Define to 1 if you have the header file. */
+#cmakedefine HAVE_UNISTD_H 1
+
+/* Define to 1 if you have the header file. */
+#cmakedefine HAVE_WINDOWS_H 1
+
+/* Define to 1 if you target processors with SSSE3+ and have . */
+#cmakedefine01 SNAPPY_HAVE_SSSE3
+
+/* Define to 1 if you target processors with BMI2+ and have . */
+#cmakedefine01 SNAPPY_HAVE_BMI2
+
+/* Define to 1 if your processor stores words with the most significant byte
+ first (like Motorola and SPARC, unlike Intel and VAX). */
+#cmakedefine SNAPPY_IS_BIG_ENDIAN 1
+
+#endif // THIRD_PARTY_SNAPPY_OPENSOURCE_CMAKE_CONFIG_H_
diff --git a/target/snappy-1.1.10/docs/README.md b/target/snappy-1.1.10/docs/README.md
new file mode 100644
index 00000000..d5e0e638
--- /dev/null
+++ b/target/snappy-1.1.10/docs/README.md
@@ -0,0 +1,72 @@
+Snappy is a compression/decompression library. It does not aim for maximum
+compression, or compatibility with any other compression library; instead, it
+aims for very high speeds and reasonable compression. For instance, compared
+to the fastest mode of zlib, Snappy is an order of magnitude faster for most
+inputs, but the resulting compressed files are anywhere from 20% to 100%
+bigger. On a single core of a Core i7 processor in 64-bit mode, Snappy
+compresses at about 250 MB/sec or more and decompresses at about 500 MB/sec
+or more.
+
+Snappy is widely used inside Google, in everything from BigTable and MapReduce
+to our internal RPC systems. (Snappy has previously been referred to as "Zippy"
+in some presentations and the likes.)
+
+For more information, please see the [README](../README.md). Benchmarks against
+a few other compression libraries (zlib, LZO, LZF, FastLZ, and QuickLZ) are
+included in the source code distribution. The source code also contains a
+[formal format specification](../format_description.txt), as well
+as a specification for a [framing format](../framing_format.txt) useful for
+higher-level framing and encapsulation of Snappy data, e.g. for transporting
+Snappy-compressed data across HTTP in a streaming fashion. Note that the Snappy
+distribution currently has no code implementing the latter, but some of the
+ports do (see below).
+
+Snappy is written in C++, but C bindings are included, and several bindings to
+other languages are maintained by third parties:
+
+* C#: [Snappy for .NET](http://snappy4net.codeplex.com/) (P/Invoke wrapper),
+ [Snappy.NET](http://snappy.angeloflogic.com/) (P/Invoke wrapper),
+ [Snappy.Sharp](https://github.com/jeffesp/Snappy.Sharp) (native
+ reimplementation)
+* [C port](http://github.com/andikleen/snappy-c)
+* [C++ MSVC packaging](http://snappy.angeloflogic.com/) (plus Windows binaries,
+ NuGet packages and command-line tool)
+* Common Lisp: [Library bindings](http://flambard.github.com/thnappy/),
+ [native reimplementation](https://github.com/brown/snappy)
+* Erlang: [esnappy](https://github.com/thekvs/esnappy),
+ [snappy-erlang-nif](https://github.com/fdmanana/snappy-erlang-nif)
+* [Go](https://github.com/golang/snappy/)
+* [Haskell](http://hackage.haskell.org/package/snappy)
+* [Haxe](https://github.com/MaddinXx/hxsnappy) (C++/Neko)
+* [iOS packaging](https://github.com/ideawu/snappy-ios)
+* Java: [JNI wrapper](https://github.com/xerial/snappy-java) (including the
+ framing format), [native reimplementation](http://code.google.com/p/jsnappy/),
+ [other native reimplementation](https://github.com/dain/snappy) (including
+ the framing format)
+* [Lua](https://github.com/forhappy/lua-snappy)
+* [Node.js](https://github.com/kesla/node-snappy) (including the [framing
+ format](https://github.com/kesla/node-snappy-stream))
+* [Perl](http://search.cpan.org/dist/Compress-Snappy/)
+* [PHP](https://github.com/kjdev/php-ext-snappy)
+* [Python](http://pypi.python.org/pypi/python-snappy) (including a command-line
+ tool for the framing format)
+* [R](https://github.com/lulyon/R-snappy)
+* [Ruby](https://github.com/miyucy/snappy)
+* [Rust](https://github.com/BurntSushi/rust-snappy)
+* [Smalltalk](https://github.com/mumez/sqnappy) (including the framing format)
+
+Snappy is used or is available as an alternative in software such as
+
+* [MongoDB](https://www.mongodb.com/)
+* [Cassandra](http://cassandra.apache.org/)
+* [Couchbase](http://www.couchbase.com/)
+* [Hadoop](http://hadoop.apache.org/)
+* [LessFS](http://www.lessfs.com/wordpress/)
+* [LevelDB](https://github.com/google/leveldb) (which is in turn used by
+ [Google Chrome](http://chrome.google.com/))
+* [Lucene](http://lucene.apache.org/)
+* [VoltDB](http://voltdb.com/)
+
+If you know of more, do not hesitate to let us know. The easiest way to get in
+touch is via the
+[Snappy discussion mailing list](http://groups.google.com/group/snappy-compression).
diff --git a/target/snappy-1.1.10/format_description.txt b/target/snappy-1.1.10/format_description.txt
new file mode 100644
index 00000000..20db66c1
--- /dev/null
+++ b/target/snappy-1.1.10/format_description.txt
@@ -0,0 +1,110 @@
+Snappy compressed format description
+Last revised: 2011-10-05
+
+
+This is not a formal specification, but should suffice to explain most
+relevant parts of how the Snappy format works. It is originally based on
+text by Zeev Tarantov.
+
+Snappy is a LZ77-type compressor with a fixed, byte-oriented encoding.
+There is no entropy encoder backend nor framing layer -- the latter is
+assumed to be handled by other parts of the system.
+
+This document only describes the format, not how the Snappy compressor nor
+decompressor actually works. The correctness of the decompressor should not
+depend on implementation details of the compressor, and vice versa.
+
+
+1. Preamble
+
+The stream starts with the uncompressed length (up to a maximum of 2^32 - 1),
+stored as a little-endian varint. Varints consist of a series of bytes,
+where the lower 7 bits are data and the upper bit is set iff there are
+more bytes to be read. In other words, an uncompressed length of 64 would
+be stored as 0x40, and an uncompressed length of 2097150 (0x1FFFFE)
+would be stored as 0xFE 0xFF 0x7F.
+
+
+2. The compressed stream itself
+
+There are two types of elements in a Snappy stream: Literals and
+copies (backreferences). There is no restriction on the order of elements,
+except that the stream naturally cannot start with a copy. (Having
+two literals in a row is never optimal from a compression point of
+view, but nevertheless fully permitted.) Each element starts with a tag byte,
+and the lower two bits of this tag byte signal what type of element will
+follow:
+
+ 00: Literal
+ 01: Copy with 1-byte offset
+ 10: Copy with 2-byte offset
+ 11: Copy with 4-byte offset
+
+The interpretation of the upper six bits are element-dependent.
+
+
+2.1. Literals (00)
+
+Literals are uncompressed data stored directly in the byte stream.
+The literal length is stored differently depending on the length
+of the literal:
+
+ - For literals up to and including 60 bytes in length, the upper
+ six bits of the tag byte contain (len-1). The literal follows
+ immediately thereafter in the bytestream.
+ - For longer literals, the (len-1) value is stored after the tag byte,
+ little-endian. The upper six bits of the tag byte describe how
+ many bytes are used for the length; 60, 61, 62 or 63 for
+ 1-4 bytes, respectively. The literal itself follows after the
+ length.
+
+
+2.2. Copies
+
+Copies are references back into previous decompressed data, telling
+the decompressor to reuse data it has previously decoded.
+They encode two values: The _offset_, saying how many bytes back
+from the current position to read, and the _length_, how many bytes
+to copy. Offsets of zero can be encoded, but are not legal;
+similarly, it is possible to encode backreferences that would
+go past the end of the block (offset > current decompressed position),
+which is also nonsensical and thus not allowed.
+
+As in most LZ77-based compressors, the length can be larger than the offset,
+yielding a form of run-length encoding (RLE). For instance,
+"xababab" could be encoded as
+
+
+
+Note that since the current Snappy compressor works in 32 kB
+blocks and does not do matching across blocks, it will never produce
+a bitstream with offsets larger than about 32768. However, the
+decompressor should not rely on this, as it may change in the future.
+
+There are several different kinds of copy elements, depending on
+the amount of bytes to be copied (length), and how far back the
+data to be copied is (offset).
+
+
+2.2.1. Copy with 1-byte offset (01)
+
+These elements can encode lengths between [4..11] bytes and offsets
+between [0..2047] bytes. (len-4) occupies three bits and is stored
+in bits [2..4] of the tag byte. The offset occupies 11 bits, of which the
+upper three are stored in the upper three bits ([5..7]) of the tag byte,
+and the lower eight are stored in a byte following the tag byte.
+
+
+2.2.2. Copy with 2-byte offset (10)
+
+These elements can encode lengths between [1..64] and offsets from
+[0..65535]. (len-1) occupies six bits and is stored in the upper
+six bits ([2..7]) of the tag byte. The offset is stored as a
+little-endian 16-bit integer in the two bytes following the tag byte.
+
+
+2.2.3. Copy with 4-byte offset (11)
+
+These are like the copies with 2-byte offsets (see previous subsection),
+except that the offset is stored as a 32-bit integer instead of a
+16-bit integer (and thus will occupy four bytes).
diff --git a/target/snappy-1.1.10/framing_format.txt b/target/snappy-1.1.10/framing_format.txt
new file mode 100644
index 00000000..9764e83d
--- /dev/null
+++ b/target/snappy-1.1.10/framing_format.txt
@@ -0,0 +1,135 @@
+Snappy framing format description
+Last revised: 2013-10-25
+
+This format decribes a framing format for Snappy, allowing compressing to
+files or streams that can then more easily be decompressed without having
+to hold the entire stream in memory. It also provides data checksums to
+help verify integrity. It does not provide metadata checksums, so it does
+not protect against e.g. all forms of truncations.
+
+Implementation of the framing format is optional for Snappy compressors and
+decompressor; it is not part of the Snappy core specification.
+
+
+1. General structure
+
+The file consists solely of chunks, lying back-to-back with no padding
+in between. Each chunk consists first a single byte of chunk identifier,
+then a three-byte little-endian length of the chunk in bytes (from 0 to
+16777215, inclusive), and then the data if any. The four bytes of chunk
+header is not counted in the data length.
+
+The different chunk types are listed below. The first chunk must always
+be the stream identifier chunk (see section 4.1, below). The stream
+ends when the file ends -- there is no explicit end-of-file marker.
+
+
+2. File type identification
+
+The following identifiers for this format are recommended where appropriate.
+However, note that none have been registered officially, so this is only to
+be taken as a guideline. We use "Snappy framed" to distinguish between this
+format and raw Snappy data.
+
+ File extension: .sz
+ MIME type: application/x-snappy-framed
+ HTTP Content-Encoding: x-snappy-framed
+
+
+3. Checksum format
+
+Some chunks have data protected by a checksum (the ones that do will say so
+explicitly). The checksums are always masked CRC-32Cs.
+
+A description of CRC-32C can be found in RFC 3720, section 12.1, with
+examples in section B.4.
+
+Checksums are not stored directly, but masked, as checksumming data and
+then its own checksum can be problematic. The masking is the same as used
+in Apache Hadoop: Rotate the checksum by 15 bits, then add the constant
+0xa282ead8 (using wraparound as normal for unsigned integers). This is
+equivalent to the following C code:
+
+ uint32_t mask_checksum(uint32_t x) {
+ return ((x >> 15) | (x << 17)) + 0xa282ead8;
+ }
+
+Note that the masking is reversible.
+
+The checksum is always stored as a four bytes long integer, in little-endian.
+
+
+4. Chunk types
+
+The currently supported chunk types are described below. The list may
+be extended in the future.
+
+
+4.1. Stream identifier (chunk type 0xff)
+
+The stream identifier is always the first element in the stream.
+It is exactly six bytes long and contains "sNaPpY" in ASCII. This means that
+a valid Snappy framed stream always starts with the bytes
+
+ 0xff 0x06 0x00 0x00 0x73 0x4e 0x61 0x50 0x70 0x59
+
+The stream identifier chunk can come multiple times in the stream besides
+the first; if such a chunk shows up, it should simply be ignored, assuming
+it has the right length and contents. This allows for easy concatenation of
+compressed files without the need for re-framing.
+
+
+4.2. Compressed data (chunk type 0x00)
+
+Compressed data chunks contain a normal Snappy compressed bitstream;
+see the compressed format specification. The compressed data is preceded by
+the CRC-32C (see section 3) of the _uncompressed_ data.
+
+Note that the data portion of the chunk, i.e., the compressed contents,
+can be at most 16777211 bytes (2^24 - 1, minus the checksum).
+However, we place an additional restriction that the uncompressed data
+in a chunk must be no longer than 65536 bytes. This allows consumers to
+easily use small fixed-size buffers.
+
+
+4.3. Uncompressed data (chunk type 0x01)
+
+Uncompressed data chunks allow a compressor to send uncompressed,
+raw data; this is useful if, for instance, uncompressible or
+near-incompressible data is detected, and faster decompression is desired.
+
+As in the compressed chunks, the data is preceded by its own masked
+CRC-32C (see section 3).
+
+An uncompressed data chunk, like compressed data chunks, should contain
+no more than 65536 data bytes, so the maximum legal chunk length with the
+checksum is 65540.
+
+
+4.4. Padding (chunk type 0xfe)
+
+Padding chunks allow a compressor to increase the size of the data stream
+so that it complies with external demands, e.g. that the total number of
+bytes is a multiple of some value.
+
+All bytes of the padding chunk, except the chunk byte itself and the length,
+should be zero, but decompressors must not try to interpret or verify the
+padding data in any way.
+
+
+4.5. Reserved unskippable chunks (chunk types 0x02-0x7f)
+
+These are reserved for future expansion. A decoder that sees such a chunk
+should immediately return an error, as it must assume it cannot decode the
+stream correctly.
+
+Future versions of this specification may define meanings for these chunks.
+
+
+4.6. Reserved skippable chunks (chunk types 0x80-0xfd)
+
+These are also reserved for future expansion, but unlike the chunks
+described in 4.5, a decoder seeing these must skip them and continue
+decoding.
+
+Future versions of this specification may define meanings for these chunks.
diff --git a/target/snappy-1.1.10/snappy-c.cc b/target/snappy-1.1.10/snappy-c.cc
new file mode 100644
index 00000000..473a0b09
--- /dev/null
+++ b/target/snappy-1.1.10/snappy-c.cc
@@ -0,0 +1,90 @@
+// Copyright 2011 Martin Gieseking .
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+
+#include "snappy.h"
+#include "snappy-c.h"
+
+extern "C" {
+
+snappy_status snappy_compress(const char* input,
+ size_t input_length,
+ char* compressed,
+ size_t *compressed_length) {
+ if (*compressed_length < snappy_max_compressed_length(input_length)) {
+ return SNAPPY_BUFFER_TOO_SMALL;
+ }
+ snappy::RawCompress(input, input_length, compressed, compressed_length);
+ return SNAPPY_OK;
+}
+
+snappy_status snappy_uncompress(const char* compressed,
+ size_t compressed_length,
+ char* uncompressed,
+ size_t* uncompressed_length) {
+ size_t real_uncompressed_length;
+ if (!snappy::GetUncompressedLength(compressed,
+ compressed_length,
+ &real_uncompressed_length)) {
+ return SNAPPY_INVALID_INPUT;
+ }
+ if (*uncompressed_length < real_uncompressed_length) {
+ return SNAPPY_BUFFER_TOO_SMALL;
+ }
+ if (!snappy::RawUncompress(compressed, compressed_length, uncompressed)) {
+ return SNAPPY_INVALID_INPUT;
+ }
+ *uncompressed_length = real_uncompressed_length;
+ return SNAPPY_OK;
+}
+
+size_t snappy_max_compressed_length(size_t source_length) {
+ return snappy::MaxCompressedLength(source_length);
+}
+
+snappy_status snappy_uncompressed_length(const char *compressed,
+ size_t compressed_length,
+ size_t *result) {
+ if (snappy::GetUncompressedLength(compressed,
+ compressed_length,
+ result)) {
+ return SNAPPY_OK;
+ } else {
+ return SNAPPY_INVALID_INPUT;
+ }
+}
+
+snappy_status snappy_validate_compressed_buffer(const char *compressed,
+ size_t compressed_length) {
+ if (snappy::IsValidCompressedBuffer(compressed, compressed_length)) {
+ return SNAPPY_OK;
+ } else {
+ return SNAPPY_INVALID_INPUT;
+ }
+}
+
+} // extern "C"
diff --git a/target/snappy-1.1.10/snappy-c.h b/target/snappy-1.1.10/snappy-c.h
new file mode 100644
index 00000000..32aa0c6b
--- /dev/null
+++ b/target/snappy-1.1.10/snappy-c.h
@@ -0,0 +1,138 @@
+/*
+ * Copyright 2011 Martin Gieseking .
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+ *
+ * Plain C interface (a wrapper around the C++ implementation).
+ */
+
+#ifndef THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_C_H_
+#define THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_C_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include
+
+/*
+ * Return values; see the documentation for each function to know
+ * what each can return.
+ */
+typedef enum {
+ SNAPPY_OK = 0,
+ SNAPPY_INVALID_INPUT = 1,
+ SNAPPY_BUFFER_TOO_SMALL = 2
+} snappy_status;
+
+/*
+ * Takes the data stored in "input[0..input_length-1]" and stores
+ * it in the array pointed to by "compressed".
+ *
+ * signals the space available in "compressed".
+ * If it is not at least equal to "snappy_max_compressed_length(input_length)",
+ * SNAPPY_BUFFER_TOO_SMALL is returned. After successful compression,
+ * contains the true length of the compressed output,
+ * and SNAPPY_OK is returned.
+ *
+ * Example:
+ * size_t output_length = snappy_max_compressed_length(input_length);
+ * char* output = (char*)malloc(output_length);
+ * if (snappy_compress(input, input_length, output, &output_length)
+ * == SNAPPY_OK) {
+ * ... Process(output, output_length) ...
+ * }
+ * free(output);
+ */
+snappy_status snappy_compress(const char* input,
+ size_t input_length,
+ char* compressed,
+ size_t* compressed_length);
+
+/*
+ * Given data in "compressed[0..compressed_length-1]" generated by
+ * calling the snappy_compress routine, this routine stores
+ * the uncompressed data to
+ * uncompressed[0..uncompressed_length-1].
+ * Returns failure (a value not equal to SNAPPY_OK) if the message
+ * is corrupted and could not be decrypted.
+ *
+ * signals the space available in "uncompressed".
+ * If it is not at least equal to the value returned by
+ * snappy_uncompressed_length for this stream, SNAPPY_BUFFER_TOO_SMALL
+ * is returned. After successful decompression,
+ * contains the true length of the decompressed output.
+ *
+ * Example:
+ * size_t output_length;
+ * if (snappy_uncompressed_length(input, input_length, &output_length)
+ * != SNAPPY_OK) {
+ * ... fail ...
+ * }
+ * char* output = (char*)malloc(output_length);
+ * if (snappy_uncompress(input, input_length, output, &output_length)
+ * == SNAPPY_OK) {
+ * ... Process(output, output_length) ...
+ * }
+ * free(output);
+ */
+snappy_status snappy_uncompress(const char* compressed,
+ size_t compressed_length,
+ char* uncompressed,
+ size_t* uncompressed_length);
+
+/*
+ * Returns the maximal size of the compressed representation of
+ * input data that is "source_length" bytes in length.
+ */
+size_t snappy_max_compressed_length(size_t source_length);
+
+/*
+ * REQUIRES: "compressed[]" was produced by snappy_compress()
+ * Returns SNAPPY_OK and stores the length of the uncompressed data in
+ * *result normally. Returns SNAPPY_INVALID_INPUT on parsing error.
+ * This operation takes O(1) time.
+ */
+snappy_status snappy_uncompressed_length(const char* compressed,
+ size_t compressed_length,
+ size_t* result);
+
+/*
+ * Check if the contents of "compressed[]" can be uncompressed successfully.
+ * Does not return the uncompressed data; if so, returns SNAPPY_OK,
+ * or if not, returns SNAPPY_INVALID_INPUT.
+ * Takes time proportional to compressed_length, but is usually at least a
+ * factor of four faster than actual decompression.
+ */
+snappy_status snappy_validate_compressed_buffer(const char* compressed,
+ size_t compressed_length);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif /* THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_C_H_ */
diff --git a/target/snappy-1.1.10/snappy-internal.h b/target/snappy-1.1.10/snappy-internal.h
new file mode 100644
index 00000000..1e1c307f
--- /dev/null
+++ b/target/snappy-1.1.10/snappy-internal.h
@@ -0,0 +1,231 @@
+// Copyright 2008 Google Inc. All Rights Reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+//
+// Internals shared between the Snappy implementation and its unittest.
+
+#ifndef THIRD_PARTY_SNAPPY_SNAPPY_INTERNAL_H_
+#define THIRD_PARTY_SNAPPY_SNAPPY_INTERNAL_H_
+
+#include "snappy-stubs-internal.h"
+
+namespace snappy {
+namespace internal {
+
+// Working memory performs a single allocation to hold all scratch space
+// required for compression.
+class WorkingMemory {
+ public:
+ explicit WorkingMemory(size_t input_size);
+ ~WorkingMemory();
+
+ // Allocates and clears a hash table using memory in "*this",
+ // stores the number of buckets in "*table_size" and returns a pointer to
+ // the base of the hash table.
+ uint16* GetHashTable(size_t fragment_size, int* table_size) const;
+ char* GetScratchInput() const { return input_; }
+ char* GetScratchOutput() const { return output_; }
+
+ private:
+ char* mem_; // the allocated memory, never nullptr
+ size_t size_; // the size of the allocated memory, never 0
+ uint16* table_; // the pointer to the hashtable
+ char* input_; // the pointer to the input scratch buffer
+ char* output_; // the pointer to the output scratch buffer
+
+ // No copying
+ WorkingMemory(const WorkingMemory&);
+ void operator=(const WorkingMemory&);
+};
+
+// Flat array compression that does not emit the "uncompressed length"
+// prefix. Compresses "input" string to the "*op" buffer.
+//
+// REQUIRES: "input_length <= kBlockSize"
+// REQUIRES: "op" points to an array of memory that is at least
+// "MaxCompressedLength(input_length)" in size.
+// REQUIRES: All elements in "table[0..table_size-1]" are initialized to zero.
+// REQUIRES: "table_size" is a power of two
+//
+// Returns an "end" pointer into "op" buffer.
+// "end - op" is the compressed size of "input".
+char* CompressFragment(const char* input,
+ size_t input_length,
+ char* op,
+ uint16* table,
+ const int table_size);
+
+// Find the largest n such that
+//
+// s1[0,n-1] == s2[0,n-1]
+// and n <= (s2_limit - s2).
+//
+// Return make_pair(n, n < 8).
+// Does not read *s2_limit or beyond.
+// Does not read *(s1 + (s2_limit - s2)) or beyond.
+// Requires that s2_limit >= s2.
+//
+// Separate implementation for 64-bit, little-endian cpus.
+#if !defined(SNAPPY_IS_BIG_ENDIAN) && \
+ (defined(ARCH_K8) || defined(ARCH_PPC) || defined(ARCH_ARM))
+static inline std::pair FindMatchLength(const char* s1,
+ const char* s2,
+ const char* s2_limit) {
+ assert(s2_limit >= s2);
+ size_t matched = 0;
+
+ // This block isn't necessary for correctness; we could just start looping
+ // immediately. As an optimization though, it is useful. It creates some not
+ // uncommon code paths that determine, without extra effort, whether the match
+ // length is less than 8. In short, we are hoping to avoid a conditional
+ // branch, and perhaps get better code layout from the C++ compiler.
+ if (SNAPPY_PREDICT_TRUE(s2 <= s2_limit - 8)) {
+ uint64 a1 = UNALIGNED_LOAD64(s1);
+ uint64 a2 = UNALIGNED_LOAD64(s2);
+ if (a1 != a2) {
+ return std::pair(Bits::FindLSBSetNonZero64(a1 ^ a2) >> 3,
+ true);
+ } else {
+ matched = 8;
+ s2 += 8;
+ }
+ }
+
+ // Find out how long the match is. We loop over the data 64 bits at a
+ // time until we find a 64-bit block that doesn't match; then we find
+ // the first non-matching bit and use that to calculate the total
+ // length of the match.
+ while (SNAPPY_PREDICT_TRUE(s2 <= s2_limit - 8)) {
+ if (UNALIGNED_LOAD64(s2) == UNALIGNED_LOAD64(s1 + matched)) {
+ s2 += 8;
+ matched += 8;
+ } else {
+ uint64 x = UNALIGNED_LOAD64(s2) ^ UNALIGNED_LOAD64(s1 + matched);
+ int matching_bits = Bits::FindLSBSetNonZero64(x);
+ matched += matching_bits >> 3;
+ assert(matched >= 8);
+ return std::pair(matched, false);
+ }
+ }
+ while (SNAPPY_PREDICT_TRUE(s2 < s2_limit)) {
+ if (s1[matched] == *s2) {
+ ++s2;
+ ++matched;
+ } else {
+ return std::pair(matched, matched < 8);
+ }
+ }
+ return std::pair(matched, matched < 8);
+}
+#else
+static inline std::pair FindMatchLength(const char* s1,
+ const char* s2,
+ const char* s2_limit) {
+ // Implementation based on the x86-64 version, above.
+ assert(s2_limit >= s2);
+ int matched = 0;
+
+ while (s2 <= s2_limit - 4 &&
+ UNALIGNED_LOAD32(s2) == UNALIGNED_LOAD32(s1 + matched)) {
+ s2 += 4;
+ matched += 4;
+ }
+ if (LittleEndian::IsLittleEndian() && s2 <= s2_limit - 4) {
+ uint32 x = UNALIGNED_LOAD32(s2) ^ UNALIGNED_LOAD32(s1 + matched);
+ int matching_bits = Bits::FindLSBSetNonZero(x);
+ matched += matching_bits >> 3;
+ } else {
+ while ((s2 < s2_limit) && (s1[matched] == *s2)) {
+ ++s2;
+ ++matched;
+ }
+ }
+ return std::pair(matched, matched < 8);
+}
+#endif
+
+// Lookup tables for decompression code. Give --snappy_dump_decompression_table
+// to the unit test to recompute char_table.
+
+enum {
+ LITERAL = 0,
+ COPY_1_BYTE_OFFSET = 1, // 3 bit length + 3 bits of offset in opcode
+ COPY_2_BYTE_OFFSET = 2,
+ COPY_4_BYTE_OFFSET = 3
+};
+static const int kMaximumTagLength = 5; // COPY_4_BYTE_OFFSET plus the actual offset.
+
+// Data stored per entry in lookup table:
+// Range Bits-used Description
+// ------------------------------------
+// 1..64 0..7 Literal/copy length encoded in opcode byte
+// 0..7 8..10 Copy offset encoded in opcode byte / 256
+// 0..4 11..13 Extra bytes after opcode
+//
+// We use eight bits for the length even though 7 would have sufficed
+// because of efficiency reasons:
+// (1) Extracting a byte is faster than a bit-field
+// (2) It properly aligns copy offset so we do not need a <<8
+static const uint16 char_table[256] = {
+ 0x0001, 0x0804, 0x1001, 0x2001, 0x0002, 0x0805, 0x1002, 0x2002,
+ 0x0003, 0x0806, 0x1003, 0x2003, 0x0004, 0x0807, 0x1004, 0x2004,
+ 0x0005, 0x0808, 0x1005, 0x2005, 0x0006, 0x0809, 0x1006, 0x2006,
+ 0x0007, 0x080a, 0x1007, 0x2007, 0x0008, 0x080b, 0x1008, 0x2008,
+ 0x0009, 0x0904, 0x1009, 0x2009, 0x000a, 0x0905, 0x100a, 0x200a,
+ 0x000b, 0x0906, 0x100b, 0x200b, 0x000c, 0x0907, 0x100c, 0x200c,
+ 0x000d, 0x0908, 0x100d, 0x200d, 0x000e, 0x0909, 0x100e, 0x200e,
+ 0x000f, 0x090a, 0x100f, 0x200f, 0x0010, 0x090b, 0x1010, 0x2010,
+ 0x0011, 0x0a04, 0x1011, 0x2011, 0x0012, 0x0a05, 0x1012, 0x2012,
+ 0x0013, 0x0a06, 0x1013, 0x2013, 0x0014, 0x0a07, 0x1014, 0x2014,
+ 0x0015, 0x0a08, 0x1015, 0x2015, 0x0016, 0x0a09, 0x1016, 0x2016,
+ 0x0017, 0x0a0a, 0x1017, 0x2017, 0x0018, 0x0a0b, 0x1018, 0x2018,
+ 0x0019, 0x0b04, 0x1019, 0x2019, 0x001a, 0x0b05, 0x101a, 0x201a,
+ 0x001b, 0x0b06, 0x101b, 0x201b, 0x001c, 0x0b07, 0x101c, 0x201c,
+ 0x001d, 0x0b08, 0x101d, 0x201d, 0x001e, 0x0b09, 0x101e, 0x201e,
+ 0x001f, 0x0b0a, 0x101f, 0x201f, 0x0020, 0x0b0b, 0x1020, 0x2020,
+ 0x0021, 0x0c04, 0x1021, 0x2021, 0x0022, 0x0c05, 0x1022, 0x2022,
+ 0x0023, 0x0c06, 0x1023, 0x2023, 0x0024, 0x0c07, 0x1024, 0x2024,
+ 0x0025, 0x0c08, 0x1025, 0x2025, 0x0026, 0x0c09, 0x1026, 0x2026,
+ 0x0027, 0x0c0a, 0x1027, 0x2027, 0x0028, 0x0c0b, 0x1028, 0x2028,
+ 0x0029, 0x0d04, 0x1029, 0x2029, 0x002a, 0x0d05, 0x102a, 0x202a,
+ 0x002b, 0x0d06, 0x102b, 0x202b, 0x002c, 0x0d07, 0x102c, 0x202c,
+ 0x002d, 0x0d08, 0x102d, 0x202d, 0x002e, 0x0d09, 0x102e, 0x202e,
+ 0x002f, 0x0d0a, 0x102f, 0x202f, 0x0030, 0x0d0b, 0x1030, 0x2030,
+ 0x0031, 0x0e04, 0x1031, 0x2031, 0x0032, 0x0e05, 0x1032, 0x2032,
+ 0x0033, 0x0e06, 0x1033, 0x2033, 0x0034, 0x0e07, 0x1034, 0x2034,
+ 0x0035, 0x0e08, 0x1035, 0x2035, 0x0036, 0x0e09, 0x1036, 0x2036,
+ 0x0037, 0x0e0a, 0x1037, 0x2037, 0x0038, 0x0e0b, 0x1038, 0x2038,
+ 0x0039, 0x0f04, 0x1039, 0x2039, 0x003a, 0x0f05, 0x103a, 0x203a,
+ 0x003b, 0x0f06, 0x103b, 0x203b, 0x003c, 0x0f07, 0x103c, 0x203c,
+ 0x0801, 0x0f08, 0x103d, 0x203d, 0x1001, 0x0f09, 0x103e, 0x203e,
+ 0x1801, 0x0f0a, 0x103f, 0x203f, 0x2001, 0x0f0b, 0x1040, 0x2040
+};
+
+} // end namespace internal
+} // end namespace snappy
+
+#endif // THIRD_PARTY_SNAPPY_SNAPPY_INTERNAL_H_
diff --git a/target/snappy-1.1.10/snappy-sinksource.cc b/target/snappy-1.1.10/snappy-sinksource.cc
new file mode 100644
index 00000000..369a1321
--- /dev/null
+++ b/target/snappy-1.1.10/snappy-sinksource.cc
@@ -0,0 +1,104 @@
+// Copyright 2011 Google Inc. All Rights Reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+
+#include
+
+#include "snappy-sinksource.h"
+
+namespace snappy {
+
+Source::~Source() { }
+
+Sink::~Sink() { }
+
+char* Sink::GetAppendBuffer(size_t length, char* scratch) {
+ return scratch;
+}
+
+char* Sink::GetAppendBufferVariable(
+ size_t min_size, size_t desired_size_hint, char* scratch,
+ size_t scratch_size, size_t* allocated_size) {
+ *allocated_size = scratch_size;
+ return scratch;
+}
+
+void Sink::AppendAndTakeOwnership(
+ char* bytes, size_t n,
+ void (*deleter)(void*, const char*, size_t),
+ void *deleter_arg) {
+ Append(bytes, n);
+ (*deleter)(deleter_arg, bytes, n);
+}
+
+ByteArraySource::~ByteArraySource() { }
+
+size_t ByteArraySource::Available() const { return left_; }
+
+const char* ByteArraySource::Peek(size_t* len) {
+ *len = left_;
+ return ptr_;
+}
+
+void ByteArraySource::Skip(size_t n) {
+ left_ -= n;
+ ptr_ += n;
+}
+
+UncheckedByteArraySink::~UncheckedByteArraySink() { }
+
+void UncheckedByteArraySink::Append(const char* data, size_t n) {
+ // Do no copying if the caller filled in the result of GetAppendBuffer()
+ if (data != dest_) {
+ memcpy(dest_, data, n);
+ }
+ dest_ += n;
+}
+
+char* UncheckedByteArraySink::GetAppendBuffer(size_t len, char* scratch) {
+ return dest_;
+}
+
+void UncheckedByteArraySink::AppendAndTakeOwnership(
+ char* data, size_t n,
+ void (*deleter)(void*, const char*, size_t),
+ void *deleter_arg) {
+ if (data != dest_) {
+ memcpy(dest_, data, n);
+ (*deleter)(deleter_arg, data, n);
+ }
+ dest_ += n;
+}
+
+char* UncheckedByteArraySink::GetAppendBufferVariable(
+ size_t min_size, size_t desired_size_hint, char* scratch,
+ size_t scratch_size, size_t* allocated_size) {
+ *allocated_size = desired_size_hint;
+ return dest_;
+}
+
+} // namespace snappy
diff --git a/target/snappy-1.1.10/snappy-sinksource.h b/target/snappy-1.1.10/snappy-sinksource.h
new file mode 100644
index 00000000..8afcdaaa
--- /dev/null
+++ b/target/snappy-1.1.10/snappy-sinksource.h
@@ -0,0 +1,182 @@
+// Copyright 2011 Google Inc. All Rights Reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+
+#ifndef THIRD_PARTY_SNAPPY_SNAPPY_SINKSOURCE_H_
+#define THIRD_PARTY_SNAPPY_SNAPPY_SINKSOURCE_H_
+
+#include
+
+namespace snappy {
+
+// A Sink is an interface that consumes a sequence of bytes.
+class Sink {
+ public:
+ Sink() { }
+ virtual ~Sink();
+
+ // Append "bytes[0,n-1]" to this.
+ virtual void Append(const char* bytes, size_t n) = 0;
+
+ // Returns a writable buffer of the specified length for appending.
+ // May return a pointer to the caller-owned scratch buffer which
+ // must have at least the indicated length. The returned buffer is
+ // only valid until the next operation on this Sink.
+ //
+ // After writing at most "length" bytes, call Append() with the
+ // pointer returned from this function and the number of bytes
+ // written. Many Append() implementations will avoid copying
+ // bytes if this function returned an internal buffer.
+ //
+ // If a non-scratch buffer is returned, the caller may only pass a
+ // prefix of it to Append(). That is, it is not correct to pass an
+ // interior pointer of the returned array to Append().
+ //
+ // The default implementation always returns the scratch buffer.
+ virtual char* GetAppendBuffer(size_t length, char* scratch);
+
+ // For higher performance, Sink implementations can provide custom
+ // AppendAndTakeOwnership() and GetAppendBufferVariable() methods.
+ // These methods can reduce the number of copies done during
+ // compression/decompression.
+
+ // Append "bytes[0,n-1] to the sink. Takes ownership of "bytes"
+ // and calls the deleter function as (*deleter)(deleter_arg, bytes, n)
+ // to free the buffer. deleter function must be non NULL.
+ //
+ // The default implementation just calls Append and frees "bytes".
+ // Other implementations may avoid a copy while appending the buffer.
+ virtual void AppendAndTakeOwnership(
+ char* bytes, size_t n, void (*deleter)(void*, const char*, size_t),
+ void *deleter_arg);
+
+ // Returns a writable buffer for appending and writes the buffer's capacity to
+ // *allocated_size. Guarantees *allocated_size >= min_size.
+ // May return a pointer to the caller-owned scratch buffer which must have
+ // scratch_size >= min_size.
+ //
+ // The returned buffer is only valid until the next operation
+ // on this ByteSink.
+ //
+ // After writing at most *allocated_size bytes, call Append() with the
+ // pointer returned from this function and the number of bytes written.
+ // Many Append() implementations will avoid copying bytes if this function
+ // returned an internal buffer.
+ //
+ // If the sink implementation allocates or reallocates an internal buffer,
+ // it should use the desired_size_hint if appropriate. If a caller cannot
+ // provide a reasonable guess at the desired capacity, it should set
+ // desired_size_hint = 0.
+ //
+ // If a non-scratch buffer is returned, the caller may only pass
+ // a prefix to it to Append(). That is, it is not correct to pass an
+ // interior pointer to Append().
+ //
+ // The default implementation always returns the scratch buffer.
+ virtual char* GetAppendBufferVariable(
+ size_t min_size, size_t desired_size_hint, char* scratch,
+ size_t scratch_size, size_t* allocated_size);
+
+ private:
+ // No copying
+ Sink(const Sink&);
+ void operator=(const Sink&);
+};
+
+// A Source is an interface that yields a sequence of bytes
+class Source {
+ public:
+ Source() { }
+ virtual ~Source();
+
+ // Return the number of bytes left to read from the source
+ virtual size_t Available() const = 0;
+
+ // Peek at the next flat region of the source. Does not reposition
+ // the source. The returned region is empty iff Available()==0.
+ //
+ // Returns a pointer to the beginning of the region and store its
+ // length in *len.
+ //
+ // The returned region is valid until the next call to Skip() or
+ // until this object is destroyed, whichever occurs first.
+ //
+ // The returned region may be larger than Available() (for example
+ // if this ByteSource is a view on a substring of a larger source).
+ // The caller is responsible for ensuring that it only reads the
+ // Available() bytes.
+ virtual const char* Peek(size_t* len) = 0;
+
+ // Skip the next n bytes. Invalidates any buffer returned by
+ // a previous call to Peek().
+ // REQUIRES: Available() >= n
+ virtual void Skip(size_t n) = 0;
+
+ private:
+ // No copying
+ Source(const Source&);
+ void operator=(const Source&);
+};
+
+// A Source implementation that yields the contents of a flat array
+class ByteArraySource : public Source {
+ public:
+ ByteArraySource(const char* p, size_t n) : ptr_(p), left_(n) { }
+ virtual ~ByteArraySource();
+ virtual size_t Available() const;
+ virtual const char* Peek(size_t* len);
+ virtual void Skip(size_t n);
+ private:
+ const char* ptr_;
+ size_t left_;
+};
+
+// A Sink implementation that writes to a flat array without any bound checks.
+class UncheckedByteArraySink : public Sink {
+ public:
+ explicit UncheckedByteArraySink(char* dest) : dest_(dest) { }
+ virtual ~UncheckedByteArraySink();
+ virtual void Append(const char* data, size_t n);
+ virtual char* GetAppendBuffer(size_t len, char* scratch);
+ virtual char* GetAppendBufferVariable(
+ size_t min_size, size_t desired_size_hint, char* scratch,
+ size_t scratch_size, size_t* allocated_size);
+ virtual void AppendAndTakeOwnership(
+ char* bytes, size_t n, void (*deleter)(void*, const char*, size_t),
+ void *deleter_arg);
+
+ // Return the current output pointer so that a caller can see how
+ // many bytes were produced.
+ // Note: this is not a Sink method.
+ char* CurrentDestination() const { return dest_; }
+ private:
+ char* dest_;
+};
+
+} // namespace snappy
+
+#endif // THIRD_PARTY_SNAPPY_SNAPPY_SINKSOURCE_H_
diff --git a/target/snappy-1.1.10/snappy-stubs-internal.cc b/target/snappy-1.1.10/snappy-stubs-internal.cc
new file mode 100644
index 00000000..66ed2e90
--- /dev/null
+++ b/target/snappy-1.1.10/snappy-stubs-internal.cc
@@ -0,0 +1,42 @@
+// Copyright 2011 Google Inc. All Rights Reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+
+#include
+#include
+
+#include "snappy-stubs-internal.h"
+
+namespace snappy {
+
+void Varint::Append32(std::string* s, uint32 value) {
+ char buf[Varint::kMax32];
+ const char* p = Varint::Encode32(buf, value);
+ s->append(buf, p - buf);
+}
+
+} // namespace snappy
diff --git a/target/snappy-1.1.10/snappy-stubs-internal.h b/target/snappy-1.1.10/snappy-stubs-internal.h
new file mode 100644
index 00000000..4854689d
--- /dev/null
+++ b/target/snappy-1.1.10/snappy-stubs-internal.h
@@ -0,0 +1,606 @@
+// Copyright 2011 Google Inc. All Rights Reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+//
+// Various stubs for the open-source version of Snappy.
+
+#ifndef THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_INTERNAL_H_
+#define THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_INTERNAL_H_
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include
+
+#include
+#include
+#include
+
+#ifdef HAVE_SYS_MMAN_H
+#include
+#endif
+
+#ifdef HAVE_UNISTD_H
+#include
+#endif
+
+#if defined(_MSC_VER)
+#include
+#endif // defined(_MSC_VER)
+
+#ifndef __has_feature
+#define __has_feature(x) 0
+#endif
+
+#if __has_feature(memory_sanitizer)
+#include
+#define SNAPPY_ANNOTATE_MEMORY_IS_INITIALIZED(address, size) \
+ __msan_unpoison((address), (size))
+#else
+#define SNAPPY_ANNOTATE_MEMORY_IS_INITIALIZED(address, size) /* empty */
+#endif // __has_feature(memory_sanitizer)
+
+#include "snappy-stubs-public.h"
+
+#if defined(__x86_64__)
+
+// Enable 64-bit optimized versions of some routines.
+#define ARCH_K8 1
+
+#elif defined(__ppc64__)
+
+#define ARCH_PPC 1
+
+#elif defined(__aarch64__)
+
+#define ARCH_ARM 1
+
+#endif
+
+// Needed by OS X, among others.
+#ifndef MAP_ANONYMOUS
+#define MAP_ANONYMOUS MAP_ANON
+#endif
+
+// The size of an array, if known at compile-time.
+// Will give unexpected results if used on a pointer.
+// We undefine it first, since some compilers already have a definition.
+#ifdef ARRAYSIZE
+#undef ARRAYSIZE
+#endif
+#define ARRAYSIZE(a) (sizeof(a) / sizeof(*(a)))
+
+// Static prediction hints.
+#ifdef HAVE_BUILTIN_EXPECT
+#define SNAPPY_PREDICT_FALSE(x) (__builtin_expect(x, 0))
+#define SNAPPY_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1))
+#else
+#define SNAPPY_PREDICT_FALSE(x) x
+#define SNAPPY_PREDICT_TRUE(x) x
+#endif
+
+// This is only used for recomputing the tag byte table used during
+// decompression; for simplicity we just remove it from the open-source
+// version (anyone who wants to regenerate it can just do the call
+// themselves within main()).
+#define DEFINE_bool(flag_name, default_value, description) \
+ bool FLAGS_ ## flag_name = default_value
+#define DECLARE_bool(flag_name) \
+ extern bool FLAGS_ ## flag_name
+
+namespace snappy {
+
+static const uint32 kuint32max = static_cast(0xFFFFFFFF);
+static const int64 kint64max = static_cast(0x7FFFFFFFFFFFFFFFLL);
+
+// Potentially unaligned loads and stores.
+
+// x86, PowerPC, and ARM64 can simply do these loads and stores native.
+
+#if defined(__i386__) || defined(__x86_64__) || defined(__powerpc__) || \
+ defined(__aarch64__)
+
+#define UNALIGNED_LOAD16(_p) (*reinterpret_cast(_p))
+#define UNALIGNED_LOAD32(_p) (*reinterpret_cast(_p))
+#define UNALIGNED_LOAD64(_p) (*reinterpret_cast(_p))
+
+#define UNALIGNED_STORE16(_p, _val) (*reinterpret_cast(_p) = (_val))
+#define UNALIGNED_STORE32(_p, _val) (*reinterpret_cast(_p) = (_val))
+#define UNALIGNED_STORE64(_p, _val) (*reinterpret_cast(_p) = (_val))
+
+// ARMv7 and newer support native unaligned accesses, but only of 16-bit
+// and 32-bit values (not 64-bit); older versions either raise a fatal signal,
+// do an unaligned read and rotate the words around a bit, or do the reads very
+// slowly (trip through kernel mode). There's no simple #define that says just
+// “ARMv7 or higher”, so we have to filter away all ARMv5 and ARMv6
+// sub-architectures.
+//
+// This is a mess, but there's not much we can do about it.
+//
+// To further complicate matters, only LDR instructions (single reads) are
+// allowed to be unaligned, not LDRD (two reads) or LDM (many reads). Unless we
+// explicitly tell the compiler that these accesses can be unaligned, it can and
+// will combine accesses. On armcc, the way to signal this is done by accessing
+// through the type (uint32 __packed *), but GCC has no such attribute
+// (it ignores __attribute__((packed)) on individual variables). However,
+// we can tell it that a _struct_ is unaligned, which has the same effect,
+// so we do that.
+
+#elif defined(__arm__) && \
+ !defined(__ARM_ARCH_4__) && \
+ !defined(__ARM_ARCH_4T__) && \
+ !defined(__ARM_ARCH_5__) && \
+ !defined(__ARM_ARCH_5T__) && \
+ !defined(__ARM_ARCH_5TE__) && \
+ !defined(__ARM_ARCH_5TEJ__) && \
+ !defined(__ARM_ARCH_6__) && \
+ !defined(__ARM_ARCH_6J__) && \
+ !defined(__ARM_ARCH_6K__) && \
+ !defined(__ARM_ARCH_6Z__) && \
+ !defined(__ARM_ARCH_6ZK__) && \
+ !defined(__ARM_ARCH_6T2__)
+
+#if __GNUC__
+#define ATTRIBUTE_PACKED __attribute__((__packed__))
+#else
+#define ATTRIBUTE_PACKED
+#endif
+
+namespace base {
+namespace internal {
+
+struct Unaligned16Struct {
+ uint16 value;
+ uint8 dummy; // To make the size non-power-of-two.
+} ATTRIBUTE_PACKED;
+
+struct Unaligned32Struct {
+ uint32 value;
+ uint8 dummy; // To make the size non-power-of-two.
+} ATTRIBUTE_PACKED;
+
+} // namespace internal
+} // namespace base
+
+#define UNALIGNED_LOAD16(_p) \
+ ((reinterpret_cast(_p))->value)
+#define UNALIGNED_LOAD32(_p) \
+ ((reinterpret_cast(_p))->value)
+
+#define UNALIGNED_STORE16(_p, _val) \
+ ((reinterpret_cast< ::snappy::base::internal::Unaligned16Struct *>(_p))->value = \
+ (_val))
+#define UNALIGNED_STORE32(_p, _val) \
+ ((reinterpret_cast< ::snappy::base::internal::Unaligned32Struct *>(_p))->value = \
+ (_val))
+
+// TODO: NEON supports unaligned 64-bit loads and stores.
+// See if that would be more efficient on platforms supporting it,
+// at least for copies.
+
+inline uint64 UNALIGNED_LOAD64(const void *p) {
+ uint64 t;
+ memcpy(&t, p, sizeof t);
+ return t;
+}
+
+inline void UNALIGNED_STORE64(void *p, uint64 v) {
+ memcpy(p, &v, sizeof v);
+}
+
+#else
+
+// These functions are provided for architectures that don't support
+// unaligned loads and stores.
+
+inline uint16 UNALIGNED_LOAD16(const void *p) {
+ uint16 t;
+ memcpy(&t, p, sizeof t);
+ return t;
+}
+
+inline uint32 UNALIGNED_LOAD32(const void *p) {
+ uint32 t;
+ memcpy(&t, p, sizeof t);
+ return t;
+}
+
+inline uint64 UNALIGNED_LOAD64(const void *p) {
+ uint64 t;
+ memcpy(&t, p, sizeof t);
+ return t;
+}
+
+inline void UNALIGNED_STORE16(void *p, uint16 v) {
+ memcpy(p, &v, sizeof v);
+}
+
+inline void UNALIGNED_STORE32(void *p, uint32 v) {
+ memcpy(p, &v, sizeof v);
+}
+
+inline void UNALIGNED_STORE64(void *p, uint64 v) {
+ memcpy(p, &v, sizeof v);
+}
+
+#endif
+
+// The following guarantees declaration of the byte swap functions.
+#if defined(SNAPPY_IS_BIG_ENDIAN)
+
+#ifdef HAVE_SYS_BYTEORDER_H
+#include
+#endif
+
+#ifdef HAVE_SYS_ENDIAN_H
+#include
+#endif
+
+#ifdef _MSC_VER
+#include
+#define bswap_16(x) _byteswap_ushort(x)
+#define bswap_32(x) _byteswap_ulong(x)
+#define bswap_64(x) _byteswap_uint64(x)
+
+#elif defined(__APPLE__)
+// Mac OS X / Darwin features
+#include
+#define bswap_16(x) OSSwapInt16(x)
+#define bswap_32(x) OSSwapInt32(x)
+#define bswap_64(x) OSSwapInt64(x)
+
+#elif defined(HAVE_BYTESWAP_H)
+#include
+
+#elif defined(bswap32)
+// FreeBSD defines bswap{16,32,64} in (already #included).
+#define bswap_16(x) bswap16(x)
+#define bswap_32(x) bswap32(x)
+#define bswap_64(x) bswap64(x)
+
+#elif defined(BSWAP_64)
+// Solaris 10 defines BSWAP_{16,32,64} in (already #included).
+#define bswap_16(x) BSWAP_16(x)
+#define bswap_32(x) BSWAP_32(x)
+#define bswap_64(x) BSWAP_64(x)
+
+#else
+
+inline uint16 bswap_16(uint16 x) {
+ return (x << 8) | (x >> 8);
+}
+
+inline uint32 bswap_32(uint32 x) {
+ x = ((x & 0xff00ff00UL) >> 8) | ((x & 0x00ff00ffUL) << 8);
+ return (x >> 16) | (x << 16);
+}
+
+inline uint64 bswap_64(uint64 x) {
+ x = ((x & 0xff00ff00ff00ff00ULL) >> 8) | ((x & 0x00ff00ff00ff00ffULL) << 8);
+ x = ((x & 0xffff0000ffff0000ULL) >> 16) | ((x & 0x0000ffff0000ffffULL) << 16);
+ return (x >> 32) | (x << 32);
+}
+
+#endif
+
+#endif // defined(SNAPPY_IS_BIG_ENDIAN)
+
+// Convert to little-endian storage, opposite of network format.
+// Convert x from host to little endian: x = LittleEndian.FromHost(x);
+// convert x from little endian to host: x = LittleEndian.ToHost(x);
+//
+// Store values into unaligned memory converting to little endian order:
+// LittleEndian.Store16(p, x);
+//
+// Load unaligned values stored in little endian converting to host order:
+// x = LittleEndian.Load16(p);
+class LittleEndian {
+ public:
+ // Conversion functions.
+#if defined(SNAPPY_IS_BIG_ENDIAN)
+
+ static uint16 FromHost16(uint16 x) { return bswap_16(x); }
+ static uint16 ToHost16(uint16 x) { return bswap_16(x); }
+
+ static uint32 FromHost32(uint32 x) { return bswap_32(x); }
+ static uint32 ToHost32(uint32 x) { return bswap_32(x); }
+
+ static bool IsLittleEndian() { return false; }
+
+#else // !defined(SNAPPY_IS_BIG_ENDIAN)
+
+ static uint16 FromHost16(uint16 x) { return x; }
+ static uint16 ToHost16(uint16 x) { return x; }
+
+ static uint32 FromHost32(uint32 x) { return x; }
+ static uint32 ToHost32(uint32 x) { return x; }
+
+ static bool IsLittleEndian() { return true; }
+
+#endif // !defined(SNAPPY_IS_BIG_ENDIAN)
+
+ // Functions to do unaligned loads and stores in little-endian order.
+ static uint16 Load16(const void *p) {
+ return ToHost16(UNALIGNED_LOAD16(p));
+ }
+
+ static void Store16(void *p, uint16 v) {
+ UNALIGNED_STORE16(p, FromHost16(v));
+ }
+
+ static uint32 Load32(const void *p) {
+ return ToHost32(UNALIGNED_LOAD32(p));
+ }
+
+ static void Store32(void *p, uint32 v) {
+ UNALIGNED_STORE32(p, FromHost32(v));
+ }
+};
+
+// Some bit-manipulation functions.
+class Bits {
+ public:
+ // Return floor(log2(n)) for positive integer n.
+ static int Log2FloorNonZero(uint32 n);
+
+ // Return floor(log2(n)) for positive integer n. Returns -1 iff n == 0.
+ static int Log2Floor(uint32 n);
+
+ // Return the first set least / most significant bit, 0-indexed. Returns an
+ // undefined value if n == 0. FindLSBSetNonZero() is similar to ffs() except
+ // that it's 0-indexed.
+ static int FindLSBSetNonZero(uint32 n);
+
+#if defined(ARCH_K8) || defined(ARCH_PPC) || defined(ARCH_ARM)
+ static int FindLSBSetNonZero64(uint64 n);
+#endif // defined(ARCH_K8) || defined(ARCH_PPC) || defined(ARCH_ARM)
+
+ private:
+ // No copying
+ Bits(const Bits&);
+ void operator=(const Bits&);
+};
+
+#ifdef HAVE_BUILTIN_CTZ
+
+inline int Bits::Log2FloorNonZero(uint32 n) {
+ assert(n != 0);
+ // (31 ^ x) is equivalent to (31 - x) for x in [0, 31]. An easy proof
+ // represents subtraction in base 2 and observes that there's no carry.
+ //
+ // GCC and Clang represent __builtin_clz on x86 as 31 ^ _bit_scan_reverse(x).
+ // Using "31 ^" here instead of "31 -" allows the optimizer to strip the
+ // function body down to _bit_scan_reverse(x).
+ return 31 ^ __builtin_clz(n);
+}
+
+inline int Bits::Log2Floor(uint32 n) {
+ return (n == 0) ? -1 : Bits::Log2FloorNonZero(n);
+}
+
+inline int Bits::FindLSBSetNonZero(uint32 n) {
+ assert(n != 0);
+ return __builtin_ctz(n);
+}
+
+#if defined(ARCH_K8) || defined(ARCH_PPC) || defined(ARCH_ARM)
+inline int Bits::FindLSBSetNonZero64(uint64 n) {
+ assert(n != 0);
+ return __builtin_ctzll(n);
+}
+#endif // defined(ARCH_K8) || defined(ARCH_PPC) || defined(ARCH_ARM)
+
+#elif defined(_MSC_VER)
+
+inline int Bits::Log2FloorNonZero(uint32 n) {
+ assert(n != 0);
+ unsigned long where;
+ _BitScanReverse(&where, n);
+ return static_cast(where);
+}
+
+inline int Bits::Log2Floor(uint32 n) {
+ unsigned long where;
+ if (_BitScanReverse(&where, n))
+ return static_cast(where);
+ return -1;
+}
+
+inline int Bits::FindLSBSetNonZero(uint32 n) {
+ assert(n != 0);
+ unsigned long where;
+ if (_BitScanForward(&where, n))
+ return static_cast(where);
+ return 32;
+}
+
+#if defined(ARCH_K8) || defined(ARCH_PPC) || defined(ARCH_ARM)
+inline int Bits::FindLSBSetNonZero64(uint64 n) {
+ assert(n != 0);
+ unsigned long where;
+ if (_BitScanForward64(&where, n))
+ return static_cast(where);
+ return 64;
+}
+#endif // defined(ARCH_K8) || defined(ARCH_PPC) || defined(ARCH_ARM)
+
+#else // Portable versions.
+
+inline int Bits::Log2FloorNonZero(uint32 n) {
+ assert(n != 0);
+
+ int log = 0;
+ uint32 value = n;
+ for (int i = 4; i >= 0; --i) {
+ int shift = (1 << i);
+ uint32 x = value >> shift;
+ if (x != 0) {
+ value = x;
+ log += shift;
+ }
+ }
+ assert(value == 1);
+ return log;
+}
+
+inline int Bits::Log2Floor(uint32 n) {
+ return (n == 0) ? -1 : Bits::Log2FloorNonZero(n);
+}
+
+inline int Bits::FindLSBSetNonZero(uint32 n) {
+ assert(n != 0);
+
+ int rc = 31;
+ for (int i = 4, shift = 1 << 4; i >= 0; --i) {
+ const uint32 x = n << shift;
+ if (x != 0) {
+ n = x;
+ rc -= shift;
+ }
+ shift >>= 1;
+ }
+ return rc;
+}
+
+#if defined(ARCH_K8) || defined(ARCH_PPC) || defined(ARCH_ARM)
+// FindLSBSetNonZero64() is defined in terms of FindLSBSetNonZero().
+inline int Bits::FindLSBSetNonZero64(uint64 n) {
+ assert(n != 0);
+
+ const uint32 bottombits = static_cast(n);
+ if (bottombits == 0) {
+ // Bottom bits are zero, so scan in top bits
+ return 32 + FindLSBSetNonZero(static_cast(n >> 32));
+ } else {
+ return FindLSBSetNonZero(bottombits);
+ }
+}
+#endif // defined(ARCH_K8) || defined(ARCH_PPC) || defined(ARCH_ARM)
+
+#endif // End portable versions.
+
+// Variable-length integer encoding.
+class Varint {
+ public:
+ // Maximum lengths of varint encoding of uint32.
+ static const int kMax32 = 5;
+
+ // Attempts to parse a varint32 from a prefix of the bytes in [ptr,limit-1].
+ // Never reads a character at or beyond limit. If a valid/terminated varint32
+ // was found in the range, stores it in *OUTPUT and returns a pointer just
+ // past the last byte of the varint32. Else returns NULL. On success,
+ // "result <= limit".
+ static const char* Parse32WithLimit(const char* ptr, const char* limit,
+ uint32* OUTPUT);
+
+ // REQUIRES "ptr" points to a buffer of length sufficient to hold "v".
+ // EFFECTS Encodes "v" into "ptr" and returns a pointer to the
+ // byte just past the last encoded byte.
+ static char* Encode32(char* ptr, uint32 v);
+
+ // EFFECTS Appends the varint representation of "value" to "*s".
+ static void Append32(std::string* s, uint32 value);
+};
+
+inline const char* Varint::Parse32WithLimit(const char* p,
+ const char* l,
+ uint32* OUTPUT) {
+ const unsigned char* ptr = reinterpret_cast(p);
+ const unsigned char* limit = reinterpret_cast(l);
+ uint32 b, result;
+ if (ptr >= limit) return NULL;
+ b = *(ptr++); result = b & 127; if (b < 128) goto done;
+ if (ptr >= limit) return NULL;
+ b = *(ptr++); result |= (b & 127) << 7; if (b < 128) goto done;
+ if (ptr >= limit) return NULL;
+ b = *(ptr++); result |= (b & 127) << 14; if (b < 128) goto done;
+ if (ptr >= limit) return NULL;
+ b = *(ptr++); result |= (b & 127) << 21; if (b < 128) goto done;
+ if (ptr >= limit) return NULL;
+ b = *(ptr++); result |= (b & 127) << 28; if (b < 16) goto done;
+ return NULL; // Value is too long to be a varint32
+ done:
+ *OUTPUT = result;
+ return reinterpret_cast(ptr);
+}
+
+inline char* Varint::Encode32(char* sptr, uint32 v) {
+ // Operate on characters as unsigneds
+ unsigned char* ptr = reinterpret_cast(sptr);
+ static const int B = 128;
+ if (v < (1<<7)) {
+ *(ptr++) = v;
+ } else if (v < (1<<14)) {
+ *(ptr++) = v | B;
+ *(ptr++) = v>>7;
+ } else if (v < (1<<21)) {
+ *(ptr++) = v | B;
+ *(ptr++) = (v>>7) | B;
+ *(ptr++) = v>>14;
+ } else if (v < (1<<28)) {
+ *(ptr++) = v | B;
+ *(ptr++) = (v>>7) | B;
+ *(ptr++) = (v>>14) | B;
+ *(ptr++) = v>>21;
+ } else {
+ *(ptr++) = v | B;
+ *(ptr++) = (v>>7) | B;
+ *(ptr++) = (v>>14) | B;
+ *(ptr++) = (v>>21) | B;
+ *(ptr++) = v>>28;
+ }
+ return reinterpret_cast(ptr);
+}
+
+// If you know the internal layout of the std::string in use, you can
+// replace this function with one that resizes the string without
+// filling the new space with zeros (if applicable) --
+// it will be non-portable but faster.
+inline void STLStringResizeUninitialized(std::string* s, size_t new_size) {
+ s->resize(new_size);
+}
+
+// Return a mutable char* pointing to a string's internal buffer,
+// which may not be null-terminated. Writing through this pointer will
+// modify the string.
+//
+// string_as_array(&str)[i] is valid for 0 <= i < str.size() until the
+// next call to a string method that invalidates iterators.
+//
+// As of 2006-04, there is no standard-blessed way of getting a
+// mutable reference to a string's internal buffer. However, issue 530
+// (http://www.open-std.org/JTC1/SC22/WG21/docs/lwg-defects.html#530)
+// proposes this as the method. It will officially be part of the standard
+// for C++0x. This should already work on all current implementations.
+inline char* string_as_array(std::string* str) {
+ return str->empty() ? NULL : &*str->begin();
+}
+
+} // namespace snappy
+
+#endif // THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_INTERNAL_H_
diff --git a/target/snappy-1.1.10/snappy-stubs-public.h.in b/target/snappy-1.1.10/snappy-stubs-public.h.in
new file mode 100644
index 00000000..416ab997
--- /dev/null
+++ b/target/snappy-1.1.10/snappy-stubs-public.h.in
@@ -0,0 +1,74 @@
+// Copyright 2011 Google Inc. All Rights Reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+//
+// Various type stubs for the open-source version of Snappy.
+//
+// This file cannot include config.h, as it is included from snappy.h,
+// which is a public header. Instead, snappy-stubs-public.h is generated by
+// from snappy-stubs-public.h.in at configure time.
+
+#ifndef THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_PUBLIC_H_
+#define THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_PUBLIC_H_
+
+#include
+#include
+#include
+
+#if ${HAVE_SYS_UIO_H_01} // HAVE_SYS_UIO_H
+#include
+#endif // HAVE_SYS_UIO_H
+
+#define SNAPPY_MAJOR ${PROJECT_VERSION_MAJOR}
+#define SNAPPY_MINOR ${PROJECT_VERSION_MINOR}
+#define SNAPPY_PATCHLEVEL ${PROJECT_VERSION_PATCH}
+#define SNAPPY_VERSION \
+ ((SNAPPY_MAJOR << 16) | (SNAPPY_MINOR << 8) | SNAPPY_PATCHLEVEL)
+
+namespace snappy {
+
+using int8 = std::int8_t;
+using uint8 = std::uint8_t;
+using int16 = std::int16_t;
+using uint16 = std::uint16_t;
+using int32 = std::int32_t;
+using uint32 = std::uint32_t;
+using int64 = std::int64_t;
+using uint64 = std::uint64_t;
+
+#if !${HAVE_SYS_UIO_H_01} // !HAVE_SYS_UIO_H
+// Windows does not have an iovec type, yet the concept is universally useful.
+// It is simple to define it ourselves, so we put it inside our own namespace.
+struct iovec {
+ void* iov_base;
+ size_t iov_len;
+};
+#endif // !HAVE_SYS_UIO_H
+
+} // namespace snappy
+
+#endif // THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_STUBS_PUBLIC_H_
diff --git a/target/snappy-1.1.10/snappy-test.cc b/target/snappy-1.1.10/snappy-test.cc
new file mode 100644
index 00000000..83be2d36
--- /dev/null
+++ b/target/snappy-1.1.10/snappy-test.cc
@@ -0,0 +1,613 @@
+// Copyright 2011 Google Inc. All Rights Reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+//
+// Various stubs for the unit tests for the open-source version of Snappy.
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#ifdef HAVE_WINDOWS_H
+// Needed to be able to use std::max without workarounds in the source code.
+// https://support.microsoft.com/en-us/help/143208/prb-using-stl-in-windows-program-can-cause-min-max-conflicts
+#define NOMINMAX
+#include
+#endif
+
+#include "snappy-test.h"
+
+#include
+
+DEFINE_bool(run_microbenchmarks, true,
+ "Run microbenchmarks before doing anything else.");
+
+namespace snappy {
+
+std::string ReadTestDataFile(const std::string& base, size_t size_limit) {
+ std::string contents;
+ const char* srcdir = getenv("srcdir"); // This is set by Automake.
+ std::string prefix;
+ if (srcdir) {
+ prefix = std::string(srcdir) + "/";
+ }
+ file::GetContents(prefix + "testdata/" + base, &contents, file::Defaults()
+ ).CheckSuccess();
+ if (size_limit > 0) {
+ contents = contents.substr(0, size_limit);
+ }
+ return contents;
+}
+
+std::string ReadTestDataFile(const std::string& base) {
+ return ReadTestDataFile(base, 0);
+}
+
+std::string StrFormat(const char* format, ...) {
+ char buf[4096];
+ va_list ap;
+ va_start(ap, format);
+ vsnprintf(buf, sizeof(buf), format, ap);
+ va_end(ap);
+ return buf;
+}
+
+bool benchmark_running = false;
+int64 benchmark_real_time_us = 0;
+int64 benchmark_cpu_time_us = 0;
+std::string* benchmark_label = nullptr;
+int64 benchmark_bytes_processed = 0;
+
+void ResetBenchmarkTiming() {
+ benchmark_real_time_us = 0;
+ benchmark_cpu_time_us = 0;
+}
+
+#ifdef WIN32
+LARGE_INTEGER benchmark_start_real;
+FILETIME benchmark_start_cpu;
+#else // WIN32
+struct timeval benchmark_start_real;
+struct rusage benchmark_start_cpu;
+#endif // WIN32
+
+void StartBenchmarkTiming() {
+#ifdef WIN32
+ QueryPerformanceCounter(&benchmark_start_real);
+ FILETIME dummy;
+ CHECK(GetProcessTimes(
+ GetCurrentProcess(), &dummy, &dummy, &dummy, &benchmark_start_cpu));
+#else
+ gettimeofday(&benchmark_start_real, NULL);
+ if (getrusage(RUSAGE_SELF, &benchmark_start_cpu) == -1) {
+ perror("getrusage(RUSAGE_SELF)");
+ exit(1);
+ }
+#endif
+ benchmark_running = true;
+}
+
+void StopBenchmarkTiming() {
+ if (!benchmark_running) {
+ return;
+ }
+
+#ifdef WIN32
+ LARGE_INTEGER benchmark_stop_real;
+ LARGE_INTEGER benchmark_frequency;
+ QueryPerformanceCounter(&benchmark_stop_real);
+ QueryPerformanceFrequency(&benchmark_frequency);
+
+ double elapsed_real = static_cast(
+ benchmark_stop_real.QuadPart - benchmark_start_real.QuadPart) /
+ benchmark_frequency.QuadPart;
+ benchmark_real_time_us += elapsed_real * 1e6 + 0.5;
+
+ FILETIME benchmark_stop_cpu, dummy;
+ CHECK(GetProcessTimes(
+ GetCurrentProcess(), &dummy, &dummy, &dummy, &benchmark_stop_cpu));
+
+ ULARGE_INTEGER start_ulargeint;
+ start_ulargeint.LowPart = benchmark_start_cpu.dwLowDateTime;
+ start_ulargeint.HighPart = benchmark_start_cpu.dwHighDateTime;
+
+ ULARGE_INTEGER stop_ulargeint;
+ stop_ulargeint.LowPart = benchmark_stop_cpu.dwLowDateTime;
+ stop_ulargeint.HighPart = benchmark_stop_cpu.dwHighDateTime;
+
+ benchmark_cpu_time_us +=
+ (stop_ulargeint.QuadPart - start_ulargeint.QuadPart + 5) / 10;
+#else // WIN32
+ struct timeval benchmark_stop_real;
+ gettimeofday(&benchmark_stop_real, NULL);
+ benchmark_real_time_us +=
+ 1000000 * (benchmark_stop_real.tv_sec - benchmark_start_real.tv_sec);
+ benchmark_real_time_us +=
+ (benchmark_stop_real.tv_usec - benchmark_start_real.tv_usec);
+
+ struct rusage benchmark_stop_cpu;
+ if (getrusage(RUSAGE_SELF, &benchmark_stop_cpu) == -1) {
+ perror("getrusage(RUSAGE_SELF)");
+ exit(1);
+ }
+ benchmark_cpu_time_us += 1000000 * (benchmark_stop_cpu.ru_utime.tv_sec -
+ benchmark_start_cpu.ru_utime.tv_sec);
+ benchmark_cpu_time_us += (benchmark_stop_cpu.ru_utime.tv_usec -
+ benchmark_start_cpu.ru_utime.tv_usec);
+#endif // WIN32
+
+ benchmark_running = false;
+}
+
+void SetBenchmarkLabel(const std::string& str) {
+ if (benchmark_label) {
+ delete benchmark_label;
+ }
+ benchmark_label = new std::string(str);
+}
+
+void SetBenchmarkBytesProcessed(int64 bytes) {
+ benchmark_bytes_processed = bytes;
+}
+
+struct BenchmarkRun {
+ int64 real_time_us;
+ int64 cpu_time_us;
+};
+
+struct BenchmarkCompareCPUTime {
+ bool operator() (const BenchmarkRun& a, const BenchmarkRun& b) const {
+ return a.cpu_time_us < b.cpu_time_us;
+ }
+};
+
+void Benchmark::Run() {
+ for (int test_case_num = start_; test_case_num <= stop_; ++test_case_num) {
+ // Run a few iterations first to find out approximately how fast
+ // the benchmark is.
+ const int kCalibrateIterations = 100;
+ ResetBenchmarkTiming();
+ StartBenchmarkTiming();
+ (*function_)(kCalibrateIterations, test_case_num);
+ StopBenchmarkTiming();
+
+ // Let each test case run for about 200ms, but at least as many
+ // as we used to calibrate.
+ // Run five times and pick the median.
+ const int kNumRuns = 5;
+ const int kMedianPos = kNumRuns / 2;
+ int num_iterations = 0;
+ if (benchmark_real_time_us > 0) {
+ num_iterations = 200000 * kCalibrateIterations / benchmark_real_time_us;
+ }
+ num_iterations = std::max(num_iterations, kCalibrateIterations);
+ BenchmarkRun benchmark_runs[kNumRuns];
+
+ for (int run = 0; run < kNumRuns; ++run) {
+ ResetBenchmarkTiming();
+ StartBenchmarkTiming();
+ (*function_)(num_iterations, test_case_num);
+ StopBenchmarkTiming();
+
+ benchmark_runs[run].real_time_us = benchmark_real_time_us;
+ benchmark_runs[run].cpu_time_us = benchmark_cpu_time_us;
+ }
+
+ std::string heading = StrFormat("%s/%d", name_.c_str(), test_case_num);
+ std::string human_readable_speed;
+
+ std::nth_element(benchmark_runs,
+ benchmark_runs + kMedianPos,
+ benchmark_runs + kNumRuns,
+ BenchmarkCompareCPUTime());
+ int64 real_time_us = benchmark_runs[kMedianPos].real_time_us;
+ int64 cpu_time_us = benchmark_runs[kMedianPos].cpu_time_us;
+ if (cpu_time_us <= 0) {
+ human_readable_speed = "?";
+ } else {
+ int64 bytes_per_second =
+ benchmark_bytes_processed * 1000000 / cpu_time_us;
+ if (bytes_per_second < 1024) {
+ human_readable_speed =
+ StrFormat("%dB/s", static_cast(bytes_per_second));
+ } else if (bytes_per_second < 1024 * 1024) {
+ human_readable_speed = StrFormat(
+ "%.1fkB/s", bytes_per_second / 1024.0f);
+ } else if (bytes_per_second < 1024 * 1024 * 1024) {
+ human_readable_speed = StrFormat(
+ "%.1fMB/s", bytes_per_second / (1024.0f * 1024.0f));
+ } else {
+ human_readable_speed = StrFormat(
+ "%.1fGB/s", bytes_per_second / (1024.0f * 1024.0f * 1024.0f));
+ }
+ }
+
+ fprintf(stderr,
+#ifdef WIN32
+ "%-18s %10I64d %10I64d %10d %s %s\n",
+#else
+ "%-18s %10lld %10lld %10d %s %s\n",
+#endif
+ heading.c_str(),
+ static_cast(real_time_us * 1000 / num_iterations),
+ static_cast(cpu_time_us * 1000 / num_iterations),
+ num_iterations,
+ human_readable_speed.c_str(),
+ benchmark_label->c_str());
+ }
+}
+
+#ifdef HAVE_LIBZ
+
+ZLib::ZLib()
+ : comp_init_(false),
+ uncomp_init_(false) {
+ Reinit();
+}
+
+ZLib::~ZLib() {
+ if (comp_init_) { deflateEnd(&comp_stream_); }
+ if (uncomp_init_) { inflateEnd(&uncomp_stream_); }
+}
+
+void ZLib::Reinit() {
+ compression_level_ = Z_DEFAULT_COMPRESSION;
+ window_bits_ = MAX_WBITS;
+ mem_level_ = 8; // DEF_MEM_LEVEL
+ if (comp_init_) {
+ deflateEnd(&comp_stream_);
+ comp_init_ = false;
+ }
+ if (uncomp_init_) {
+ inflateEnd(&uncomp_stream_);
+ uncomp_init_ = false;
+ }
+ first_chunk_ = true;
+}
+
+void ZLib::Reset() {
+ first_chunk_ = true;
+}
+
+// --------- COMPRESS MODE
+
+// Initialization method to be called if we hit an error while
+// compressing. On hitting an error, call this method before returning
+// the error.
+void ZLib::CompressErrorInit() {
+ deflateEnd(&comp_stream_);
+ comp_init_ = false;
+ Reset();
+}
+
+int ZLib::DeflateInit() {
+ return deflateInit2(&comp_stream_,
+ compression_level_,
+ Z_DEFLATED,
+ window_bits_,
+ mem_level_,
+ Z_DEFAULT_STRATEGY);
+}
+
+int ZLib::CompressInit(Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong *sourceLen) {
+ int err;
+
+ comp_stream_.next_in = (Bytef*)source;
+ comp_stream_.avail_in = (uInt)*sourceLen;
+ if ((uLong)comp_stream_.avail_in != *sourceLen) return Z_BUF_ERROR;
+ comp_stream_.next_out = dest;
+ comp_stream_.avail_out = (uInt)*destLen;
+ if ((uLong)comp_stream_.avail_out != *destLen) return Z_BUF_ERROR;
+
+ if ( !first_chunk_ ) // only need to set up stream the first time through
+ return Z_OK;
+
+ if (comp_init_) { // we've already initted it
+ err = deflateReset(&comp_stream_);
+ if (err != Z_OK) {
+ LOG(WARNING) << "ERROR: Can't reset compress object; creating a new one";
+ deflateEnd(&comp_stream_);
+ comp_init_ = false;
+ }
+ }
+ if (!comp_init_) { // first use
+ comp_stream_.zalloc = (alloc_func)0;
+ comp_stream_.zfree = (free_func)0;
+ comp_stream_.opaque = (voidpf)0;
+ err = DeflateInit();
+ if (err != Z_OK) return err;
+ comp_init_ = true;
+ }
+ return Z_OK;
+}
+
+// In a perfect world we'd always have the full buffer to compress
+// when the time came, and we could just call Compress(). Alas, we
+// want to do chunked compression on our webserver. In this
+// application, we compress the header, send it off, then compress the
+// results, send them off, then compress the footer. Thus we need to
+// use the chunked compression features of zlib.
+int ZLib::CompressAtMostOrAll(Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong *sourceLen,
+ int flush_mode) { // Z_FULL_FLUSH or Z_FINISH
+ int err;
+
+ if ( (err=CompressInit(dest, destLen, source, sourceLen)) != Z_OK )
+ return err;
+
+ // This is used to figure out how many bytes we wrote *this chunk*
+ int compressed_size = comp_stream_.total_out;
+
+ // Some setup happens only for the first chunk we compress in a run
+ if ( first_chunk_ ) {
+ first_chunk_ = false;
+ }
+
+ // flush_mode is Z_FINISH for all mode, Z_SYNC_FLUSH for incremental
+ // compression.
+ err = deflate(&comp_stream_, flush_mode);
+
+ *sourceLen = comp_stream_.avail_in;
+
+ if ((err == Z_STREAM_END || err == Z_OK)
+ && comp_stream_.avail_in == 0
+ && comp_stream_.avail_out != 0 ) {
+ // we processed everything ok and the output buffer was large enough.
+ ;
+ } else if (err == Z_STREAM_END && comp_stream_.avail_in > 0) {
+ return Z_BUF_ERROR; // should never happen
+ } else if (err != Z_OK && err != Z_STREAM_END && err != Z_BUF_ERROR) {
+ // an error happened
+ CompressErrorInit();
+ return err;
+ } else if (comp_stream_.avail_out == 0) { // not enough space
+ err = Z_BUF_ERROR;
+ }
+
+ assert(err == Z_OK || err == Z_STREAM_END || err == Z_BUF_ERROR);
+ if (err == Z_STREAM_END)
+ err = Z_OK;
+
+ // update the crc and other metadata
+ compressed_size = comp_stream_.total_out - compressed_size; // delta
+ *destLen = compressed_size;
+
+ return err;
+}
+
+int ZLib::CompressChunkOrAll(Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong sourceLen,
+ int flush_mode) { // Z_FULL_FLUSH or Z_FINISH
+ const int ret =
+ CompressAtMostOrAll(dest, destLen, source, &sourceLen, flush_mode);
+ if (ret == Z_BUF_ERROR)
+ CompressErrorInit();
+ return ret;
+}
+
+// This routine only initializes the compression stream once. Thereafter, it
+// just does a deflateReset on the stream, which should be faster.
+int ZLib::Compress(Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong sourceLen) {
+ int err;
+ if ( (err=CompressChunkOrAll(dest, destLen, source, sourceLen,
+ Z_FINISH)) != Z_OK )
+ return err;
+ Reset(); // reset for next call to Compress
+
+ return Z_OK;
+}
+
+
+// --------- UNCOMPRESS MODE
+
+int ZLib::InflateInit() {
+ return inflateInit2(&uncomp_stream_, MAX_WBITS);
+}
+
+// Initialization method to be called if we hit an error while
+// uncompressing. On hitting an error, call this method before
+// returning the error.
+void ZLib::UncompressErrorInit() {
+ inflateEnd(&uncomp_stream_);
+ uncomp_init_ = false;
+ Reset();
+}
+
+int ZLib::UncompressInit(Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong *sourceLen) {
+ int err;
+
+ uncomp_stream_.next_in = (Bytef*)source;
+ uncomp_stream_.avail_in = (uInt)*sourceLen;
+ // Check for source > 64K on 16-bit machine:
+ if ((uLong)uncomp_stream_.avail_in != *sourceLen) return Z_BUF_ERROR;
+
+ uncomp_stream_.next_out = dest;
+ uncomp_stream_.avail_out = (uInt)*destLen;
+ if ((uLong)uncomp_stream_.avail_out != *destLen) return Z_BUF_ERROR;
+
+ if ( !first_chunk_ ) // only need to set up stream the first time through
+ return Z_OK;
+
+ if (uncomp_init_) { // we've already initted it
+ err = inflateReset(&uncomp_stream_);
+ if (err != Z_OK) {
+ LOG(WARNING)
+ << "ERROR: Can't reset uncompress object; creating a new one";
+ UncompressErrorInit();
+ }
+ }
+ if (!uncomp_init_) {
+ uncomp_stream_.zalloc = (alloc_func)0;
+ uncomp_stream_.zfree = (free_func)0;
+ uncomp_stream_.opaque = (voidpf)0;
+ err = InflateInit();
+ if (err != Z_OK) return err;
+ uncomp_init_ = true;
+ }
+ return Z_OK;
+}
+
+// If you compressed your data a chunk at a time, with CompressChunk,
+// you can uncompress it a chunk at a time with UncompressChunk.
+// Only difference bewteen chunked and unchunked uncompression
+// is the flush mode we use: Z_SYNC_FLUSH (chunked) or Z_FINISH (unchunked).
+int ZLib::UncompressAtMostOrAll(Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong *sourceLen,
+ int flush_mode) { // Z_SYNC_FLUSH or Z_FINISH
+ int err = Z_OK;
+
+ if ( (err=UncompressInit(dest, destLen, source, sourceLen)) != Z_OK ) {
+ LOG(WARNING) << "UncompressInit: Error: " << err << " SourceLen: "
+ << *sourceLen;
+ return err;
+ }
+
+ // This is used to figure out how many output bytes we wrote *this chunk*:
+ const uLong old_total_out = uncomp_stream_.total_out;
+
+ // This is used to figure out how many input bytes we read *this chunk*:
+ const uLong old_total_in = uncomp_stream_.total_in;
+
+ // Some setup happens only for the first chunk we compress in a run
+ if ( first_chunk_ ) {
+ first_chunk_ = false; // so we don't do this again
+
+ // For the first chunk *only* (to avoid infinite troubles), we let
+ // there be no actual data to uncompress. This sometimes triggers
+ // when the input is only the gzip header, say.
+ if ( *sourceLen == 0 ) {
+ *destLen = 0;
+ return Z_OK;
+ }
+ }
+
+ // We'll uncompress as much as we can. If we end OK great, otherwise
+ // if we get an error that seems to be the gzip footer, we store the
+ // gzip footer and return OK, otherwise we return the error.
+
+ // flush_mode is Z_SYNC_FLUSH for chunked mode, Z_FINISH for all mode.
+ err = inflate(&uncomp_stream_, flush_mode);
+
+ // Figure out how many bytes of the input zlib slurped up:
+ const uLong bytes_read = uncomp_stream_.total_in - old_total_in;
+ CHECK_LE(source + bytes_read, source + *sourceLen);
+ *sourceLen = uncomp_stream_.avail_in;
+
+ if ((err == Z_STREAM_END || err == Z_OK) // everything went ok
+ && uncomp_stream_.avail_in == 0) { // and we read it all
+ ;
+ } else if (err == Z_STREAM_END && uncomp_stream_.avail_in > 0) {
+ LOG(WARNING)
+ << "UncompressChunkOrAll: Received some extra data, bytes total: "
+ << uncomp_stream_.avail_in << " bytes: "
+ << std::string(reinterpret_cast(uncomp_stream_.next_in),
+ std::min(int(uncomp_stream_.avail_in), 20));
+ UncompressErrorInit();
+ return Z_DATA_ERROR; // what's the extra data for?
+ } else if (err != Z_OK && err != Z_STREAM_END && err != Z_BUF_ERROR) {
+ // an error happened
+ LOG(WARNING) << "UncompressChunkOrAll: Error: " << err
+ << " avail_out: " << uncomp_stream_.avail_out;
+ UncompressErrorInit();
+ return err;
+ } else if (uncomp_stream_.avail_out == 0) {
+ err = Z_BUF_ERROR;
+ }
+
+ assert(err == Z_OK || err == Z_BUF_ERROR || err == Z_STREAM_END);
+ if (err == Z_STREAM_END)
+ err = Z_OK;
+
+ *destLen = uncomp_stream_.total_out - old_total_out; // size for this call
+
+ return err;
+}
+
+int ZLib::UncompressChunkOrAll(Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong sourceLen,
+ int flush_mode) { // Z_SYNC_FLUSH or Z_FINISH
+ const int ret =
+ UncompressAtMostOrAll(dest, destLen, source, &sourceLen, flush_mode);
+ if (ret == Z_BUF_ERROR)
+ UncompressErrorInit();
+ return ret;
+}
+
+int ZLib::UncompressAtMost(Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong *sourceLen) {
+ return UncompressAtMostOrAll(dest, destLen, source, sourceLen, Z_SYNC_FLUSH);
+}
+
+// We make sure we've uncompressed everything, that is, the current
+// uncompress stream is at a compressed-buffer-EOF boundary. In gzip
+// mode, we also check the gzip footer to make sure we pass the gzip
+// consistency checks. We RETURN true iff both types of checks pass.
+bool ZLib::UncompressChunkDone() {
+ assert(!first_chunk_ && uncomp_init_);
+ // Make sure we're at the end-of-compressed-data point. This means
+ // if we call inflate with Z_FINISH we won't consume any input or
+ // write any output
+ Bytef dummyin, dummyout;
+ uLongf dummylen = 0;
+ if ( UncompressChunkOrAll(&dummyout, &dummylen, &dummyin, 0, Z_FINISH)
+ != Z_OK ) {
+ return false;
+ }
+
+ // Make sure that when we exit, we can start a new round of chunks later
+ Reset();
+
+ return true;
+}
+
+// Uncompresses the source buffer into the destination buffer.
+// The destination buffer must be long enough to hold the entire
+// decompressed contents.
+//
+// We only initialize the uncomp_stream once. Thereafter, we use
+// inflateReset, which should be faster.
+//
+// Returns Z_OK on success, otherwise, it returns a zlib error code.
+int ZLib::Uncompress(Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong sourceLen) {
+ int err;
+ if ( (err=UncompressChunkOrAll(dest, destLen, source, sourceLen,
+ Z_FINISH)) != Z_OK ) {
+ Reset(); // let us try to compress again
+ return err;
+ }
+ if ( !UncompressChunkDone() ) // calls Reset()
+ return Z_DATA_ERROR;
+ return Z_OK; // stream_end is ok
+}
+
+#endif // HAVE_LIBZ
+
+} // namespace snappy
diff --git a/target/snappy-1.1.10/snappy-test.h b/target/snappy-1.1.10/snappy-test.h
new file mode 100644
index 00000000..c8b7d388
--- /dev/null
+++ b/target/snappy-1.1.10/snappy-test.h
@@ -0,0 +1,525 @@
+// Copyright 2011 Google Inc. All Rights Reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+//
+// Various stubs for the unit tests for the open-source version of Snappy.
+
+#ifndef THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_TEST_H_
+#define THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_TEST_H_
+
+#include
+#include
+
+#include "snappy-stubs-internal.h"
+
+#include
+#include
+
+#ifdef HAVE_SYS_MMAN_H
+#include
+#endif
+
+#ifdef HAVE_SYS_RESOURCE_H
+#include
+#endif
+
+#ifdef HAVE_SYS_TIME_H
+#include
+#endif
+
+#ifdef HAVE_WINDOWS_H
+#include
+#endif
+
+#ifdef HAVE_GTEST
+
+#include
+#undef TYPED_TEST
+#define TYPED_TEST TEST
+#define INIT_GTEST(argc, argv) ::testing::InitGoogleTest(argc, *argv)
+
+#else
+
+// Stubs for if the user doesn't have Google Test installed.
+
+#define TEST(test_case, test_subcase) \
+ void Test_ ## test_case ## _ ## test_subcase()
+#define INIT_GTEST(argc, argv)
+
+#define TYPED_TEST TEST
+#define EXPECT_EQ CHECK_EQ
+#define EXPECT_NE CHECK_NE
+#define EXPECT_FALSE(cond) CHECK(!(cond))
+
+#endif
+
+#ifdef HAVE_GFLAGS
+
+#include
+
+// This is tricky; both gflags and Google Test want to look at the command line
+// arguments. Google Test seems to be the most happy with unknown arguments,
+// though, so we call it first and hope for the best.
+#define InitGoogle(argv0, argc, argv, remove_flags) \
+ INIT_GTEST(argc, argv); \
+ google::ParseCommandLineFlags(argc, argv, remove_flags);
+
+#else
+
+// If we don't have the gflags package installed, these can only be
+// changed at compile time.
+#define DEFINE_int32(flag_name, default_value, description) \
+ static int FLAGS_ ## flag_name = default_value;
+
+#define InitGoogle(argv0, argc, argv, remove_flags) \
+ INIT_GTEST(argc, argv)
+
+#endif
+
+#ifdef HAVE_LIBZ
+#include "zlib.h"
+#endif
+
+#ifdef HAVE_LIBLZO2
+#include "lzo/lzo1x.h"
+#endif
+
+namespace {
+
+namespace file {
+ int Defaults() { return 0; }
+
+ class DummyStatus {
+ public:
+ void CheckSuccess() { }
+ };
+
+ DummyStatus GetContents(
+ const std::string& filename, std::string* data, int unused) {
+ FILE* fp = fopen(filename.c_str(), "rb");
+ if (fp == NULL) {
+ perror(filename.c_str());
+ exit(1);
+ }
+
+ data->clear();
+ while (!feof(fp)) {
+ char buf[4096];
+ size_t ret = fread(buf, 1, 4096, fp);
+ if (ret == 0 && ferror(fp)) {
+ perror("fread");
+ exit(1);
+ }
+ data->append(std::string(buf, ret));
+ }
+
+ fclose(fp);
+
+ return DummyStatus();
+ }
+
+ inline DummyStatus SetContents(
+ const std::string& filename, const std::string& str, int unused) {
+ FILE* fp = fopen(filename.c_str(), "wb");
+ if (fp == NULL) {
+ perror(filename.c_str());
+ exit(1);
+ }
+
+ int ret = fwrite(str.data(), str.size(), 1, fp);
+ if (ret != 1) {
+ perror("fwrite");
+ exit(1);
+ }
+
+ fclose(fp);
+
+ return DummyStatus();
+ }
+} // namespace file
+
+} // namespace
+
+namespace snappy {
+
+#define FLAGS_test_random_seed 301
+using TypeParam = std::string;
+
+void Test_CorruptedTest_VerifyCorrupted();
+void Test_Snappy_SimpleTests();
+void Test_Snappy_MaxBlowup();
+void Test_Snappy_RandomData();
+void Test_Snappy_FourByteOffset();
+void Test_SnappyCorruption_TruncatedVarint();
+void Test_SnappyCorruption_UnterminatedVarint();
+void Test_SnappyCorruption_OverflowingVarint();
+void Test_Snappy_ReadPastEndOfBuffer();
+void Test_Snappy_FindMatchLength();
+void Test_Snappy_FindMatchLengthRandom();
+
+std::string ReadTestDataFile(const std::string& base, size_t size_limit);
+
+std::string ReadTestDataFile(const std::string& base);
+
+// A sprintf() variant that returns a std::string.
+// Not safe for general use due to truncation issues.
+std::string StrFormat(const char* format, ...);
+
+// A wall-time clock. This stub is not super-accurate, nor resistant to the
+// system time changing.
+class CycleTimer {
+ public:
+ CycleTimer() : real_time_us_(0) {}
+
+ void Start() {
+#ifdef WIN32
+ QueryPerformanceCounter(&start_);
+#else
+ gettimeofday(&start_, NULL);
+#endif
+ }
+
+ void Stop() {
+#ifdef WIN32
+ LARGE_INTEGER stop;
+ LARGE_INTEGER frequency;
+ QueryPerformanceCounter(&stop);
+ QueryPerformanceFrequency(&frequency);
+
+ double elapsed = static_cast(stop.QuadPart - start_.QuadPart) /
+ frequency.QuadPart;
+ real_time_us_ += elapsed * 1e6 + 0.5;
+#else
+ struct timeval stop;
+ gettimeofday(&stop, NULL);
+
+ real_time_us_ += 1000000 * (stop.tv_sec - start_.tv_sec);
+ real_time_us_ += (stop.tv_usec - start_.tv_usec);
+#endif
+ }
+
+ double Get() {
+ return real_time_us_ * 1e-6;
+ }
+
+ private:
+ int64 real_time_us_;
+#ifdef WIN32
+ LARGE_INTEGER start_;
+#else
+ struct timeval start_;
+#endif
+};
+
+// Minimalistic microbenchmark framework.
+
+typedef void (*BenchmarkFunction)(int, int);
+
+class Benchmark {
+ public:
+ Benchmark(const std::string& name, BenchmarkFunction function)
+ : name_(name), function_(function) {}
+
+ Benchmark* DenseRange(int start, int stop) {
+ start_ = start;
+ stop_ = stop;
+ return this;
+ }
+
+ void Run();
+
+ private:
+ const std::string name_;
+ const BenchmarkFunction function_;
+ int start_, stop_;
+};
+#define BENCHMARK(benchmark_name) \
+ Benchmark* Benchmark_ ## benchmark_name = \
+ (new Benchmark(#benchmark_name, benchmark_name))
+
+extern Benchmark* Benchmark_BM_UFlat;
+extern Benchmark* Benchmark_BM_UIOVec;
+extern Benchmark* Benchmark_BM_UValidate;
+extern Benchmark* Benchmark_BM_ZFlat;
+extern Benchmark* Benchmark_BM_ZFlatAll;
+extern Benchmark* Benchmark_BM_ZFlatIncreasingTableSize;
+
+void ResetBenchmarkTiming();
+void StartBenchmarkTiming();
+void StopBenchmarkTiming();
+void SetBenchmarkLabel(const std::string& str);
+void SetBenchmarkBytesProcessed(int64 bytes);
+
+#ifdef HAVE_LIBZ
+
+// Object-oriented wrapper around zlib.
+class ZLib {
+ public:
+ ZLib();
+ ~ZLib();
+
+ // Wipe a ZLib object to a virgin state. This differs from Reset()
+ // in that it also breaks any state.
+ void Reinit();
+
+ // Call this to make a zlib buffer as good as new. Here's the only
+ // case where they differ:
+ // CompressChunk(a); CompressChunk(b); CompressChunkDone(); vs
+ // CompressChunk(a); Reset(); CompressChunk(b); CompressChunkDone();
+ // You'll want to use Reset(), then, when you interrupt a compress
+ // (or uncompress) in the middle of a chunk and want to start over.
+ void Reset();
+
+ // According to the zlib manual, when you Compress, the destination
+ // buffer must have size at least src + .1%*src + 12. This function
+ // helps you calculate that. Augment this to account for a potential
+ // gzip header and footer, plus a few bytes of slack.
+ static int MinCompressbufSize(int uncompress_size) {
+ return uncompress_size + uncompress_size/1000 + 40;
+ }
+
+ // Compresses the source buffer into the destination buffer.
+ // sourceLen is the byte length of the source buffer.
+ // Upon entry, destLen is the total size of the destination buffer,
+ // which must be of size at least MinCompressbufSize(sourceLen).
+ // Upon exit, destLen is the actual size of the compressed buffer.
+ //
+ // This function can be used to compress a whole file at once if the
+ // input file is mmap'ed.
+ //
+ // Returns Z_OK if success, Z_MEM_ERROR if there was not
+ // enough memory, Z_BUF_ERROR if there was not enough room in the
+ // output buffer. Note that if the output buffer is exactly the same
+ // size as the compressed result, we still return Z_BUF_ERROR.
+ // (check CL#1936076)
+ int Compress(Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong sourceLen);
+
+ // Uncompresses the source buffer into the destination buffer.
+ // The destination buffer must be long enough to hold the entire
+ // decompressed contents.
+ //
+ // Returns Z_OK on success, otherwise, it returns a zlib error code.
+ int Uncompress(Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong sourceLen);
+
+ // Uncompress data one chunk at a time -- ie you can call this
+ // more than once. To get this to work you need to call per-chunk
+ // and "done" routines.
+ //
+ // Returns Z_OK if success, Z_MEM_ERROR if there was not
+ // enough memory, Z_BUF_ERROR if there was not enough room in the
+ // output buffer.
+
+ int UncompressAtMost(Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong *sourceLen);
+
+ // Checks gzip footer information, as needed. Mostly this just
+ // makes sure the checksums match. Whenever you call this, it
+ // will assume the last 8 bytes from the previous UncompressChunk
+ // call are the footer. Returns true iff everything looks ok.
+ bool UncompressChunkDone();
+
+ private:
+ int InflateInit(); // sets up the zlib inflate structure
+ int DeflateInit(); // sets up the zlib deflate structure
+
+ // These init the zlib data structures for compressing/uncompressing
+ int CompressInit(Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong *sourceLen);
+ int UncompressInit(Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong *sourceLen);
+ // Initialization method to be called if we hit an error while
+ // uncompressing. On hitting an error, call this method before
+ // returning the error.
+ void UncompressErrorInit();
+
+ // Helper function for Compress
+ int CompressChunkOrAll(Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong sourceLen,
+ int flush_mode);
+ int CompressAtMostOrAll(Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong *sourceLen,
+ int flush_mode);
+
+ // Likewise for UncompressAndUncompressChunk
+ int UncompressChunkOrAll(Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong sourceLen,
+ int flush_mode);
+
+ int UncompressAtMostOrAll(Bytef *dest, uLongf *destLen,
+ const Bytef *source, uLong *sourceLen,
+ int flush_mode);
+
+ // Initialization method to be called if we hit an error while
+ // compressing. On hitting an error, call this method before
+ // returning the error.
+ void CompressErrorInit();
+
+ int compression_level_; // compression level
+ int window_bits_; // log base 2 of the window size used in compression
+ int mem_level_; // specifies the amount of memory to be used by
+ // compressor (1-9)
+ z_stream comp_stream_; // Zlib stream data structure
+ bool comp_init_; // True if we have initialized comp_stream_
+ z_stream uncomp_stream_; // Zlib stream data structure
+ bool uncomp_init_; // True if we have initialized uncomp_stream_
+
+ // These are used only with chunked compression.
+ bool first_chunk_; // true if we need to emit headers with this chunk
+};
+
+#endif // HAVE_LIBZ
+
+} // namespace snappy
+
+DECLARE_bool(run_microbenchmarks);
+
+static inline void RunSpecifiedBenchmarks() {
+ if (!FLAGS_run_microbenchmarks) {
+ return;
+ }
+
+ fprintf(stderr, "Running microbenchmarks.\n");
+#ifndef NDEBUG
+ fprintf(stderr, "WARNING: Compiled with assertions enabled, will be slow.\n");
+#endif
+#ifndef __OPTIMIZE__
+ fprintf(stderr, "WARNING: Compiled without optimization, will be slow.\n");
+#endif
+ fprintf(stderr, "Benchmark Time(ns) CPU(ns) Iterations\n");
+ fprintf(stderr, "---------------------------------------------------\n");
+
+ snappy::Benchmark_BM_UFlat->Run();
+ snappy::Benchmark_BM_UIOVec->Run();
+ snappy::Benchmark_BM_UValidate->Run();
+ snappy::Benchmark_BM_ZFlat->Run();
+ snappy::Benchmark_BM_ZFlatAll->Run();
+ snappy::Benchmark_BM_ZFlatIncreasingTableSize->Run();
+
+ fprintf(stderr, "\n");
+}
+
+#ifndef HAVE_GTEST
+
+static inline int RUN_ALL_TESTS() {
+ fprintf(stderr, "Running correctness tests.\n");
+ snappy::Test_CorruptedTest_VerifyCorrupted();
+ snappy::Test_Snappy_SimpleTests();
+ snappy::Test_Snappy_MaxBlowup();
+ snappy::Test_Snappy_RandomData();
+ snappy::Test_Snappy_FourByteOffset();
+ snappy::Test_SnappyCorruption_TruncatedVarint();
+ snappy::Test_SnappyCorruption_UnterminatedVarint();
+ snappy::Test_SnappyCorruption_OverflowingVarint();
+ snappy::Test_Snappy_ReadPastEndOfBuffer();
+ snappy::Test_Snappy_FindMatchLength();
+ snappy::Test_Snappy_FindMatchLengthRandom();
+ fprintf(stderr, "All tests passed.\n");
+
+ return 0;
+}
+
+#endif // HAVE_GTEST
+
+// For main().
+namespace snappy {
+
+// Logging.
+
+#define LOG(level) LogMessage()
+#define VLOG(level) true ? (void)0 : \
+ snappy::LogMessageVoidify() & snappy::LogMessage()
+
+class LogMessage {
+ public:
+ LogMessage() { }
+ ~LogMessage() {
+ std::cerr << std::endl;
+ }
+
+ LogMessage& operator<<(const std::string& msg) {
+ std::cerr << msg;
+ return *this;
+ }
+ LogMessage& operator<<(int x) {
+ std::cerr << x;
+ return *this;
+ }
+};
+
+// Asserts, both versions activated in debug mode only,
+// and ones that are always active.
+
+#define CRASH_UNLESS(condition) \
+ SNAPPY_PREDICT_TRUE(condition) ? (void)0 : \
+ snappy::LogMessageVoidify() & snappy::LogMessageCrash()
+
+#ifdef _MSC_VER
+// ~LogMessageCrash calls abort() and therefore never exits. This is by design
+// so temporarily disable warning C4722.
+#pragma warning(push)
+#pragma warning(disable:4722)
+#endif
+
+class LogMessageCrash : public LogMessage {
+ public:
+ LogMessageCrash() { }
+ ~LogMessageCrash() {
+ std::cerr << std::endl;
+ abort();
+ }
+};
+
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif
+
+// This class is used to explicitly ignore values in the conditional
+// logging macros. This avoids compiler warnings like "value computed
+// is not used" and "statement has no effect".
+
+class LogMessageVoidify {
+ public:
+ LogMessageVoidify() { }
+ // This has to be an operator with a precedence lower than << but
+ // higher than ?:
+ void operator&(const LogMessage&) { }
+};
+
+#define CHECK(cond) CRASH_UNLESS(cond)
+#define CHECK_LE(a, b) CRASH_UNLESS((a) <= (b))
+#define CHECK_GE(a, b) CRASH_UNLESS((a) >= (b))
+#define CHECK_EQ(a, b) CRASH_UNLESS((a) == (b))
+#define CHECK_NE(a, b) CRASH_UNLESS((a) != (b))
+#define CHECK_LT(a, b) CRASH_UNLESS((a) < (b))
+#define CHECK_GT(a, b) CRASH_UNLESS((a) > (b))
+#define CHECK_OK(cond) (cond).CheckSuccess()
+
+} // namespace snappy
+
+#endif // THIRD_PARTY_SNAPPY_OPENSOURCE_SNAPPY_TEST_H_
diff --git a/target/snappy-1.1.10/snappy.cc b/target/snappy-1.1.10/snappy.cc
new file mode 100644
index 00000000..ce1eef46
--- /dev/null
+++ b/target/snappy-1.1.10/snappy.cc
@@ -0,0 +1,1661 @@
+// Copyright 2005 Google Inc. All Rights Reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+
+#include "snappy.h"
+#include "snappy-internal.h"
+#include "snappy-sinksource.h"
+
+#if !defined(SNAPPY_HAVE_SSSE3)
+// __SSSE3__ is defined by GCC and Clang. Visual Studio doesn't target SIMD
+// support between SSE2 and AVX (so SSSE3 instructions require AVX support), and
+// defines __AVX__ when AVX support is available.
+#if defined(__SSSE3__) || defined(__AVX__)
+#define SNAPPY_HAVE_SSSE3 1
+#else
+#define SNAPPY_HAVE_SSSE3 0
+#endif
+#endif // !defined(SNAPPY_HAVE_SSSE3)
+
+#if !defined(SNAPPY_HAVE_BMI2)
+// __BMI2__ is defined by GCC and Clang. Visual Studio doesn't target BMI2
+// specifically, but it does define __AVX2__ when AVX2 support is available.
+// Fortunately, AVX2 was introduced in Haswell, just like BMI2.
+//
+// BMI2 is not defined as a subset of AVX2 (unlike SSSE3 and AVX above). So,
+// GCC and Clang can build code with AVX2 enabled but BMI2 disabled, in which
+// case issuing BMI2 instructions results in a compiler error.
+#if defined(__BMI2__) || (defined(_MSC_VER) && defined(__AVX2__))
+#define SNAPPY_HAVE_BMI2 1
+#else
+#define SNAPPY_HAVE_BMI2 0
+#endif
+#endif // !defined(SNAPPY_HAVE_BMI2)
+
+#if SNAPPY_HAVE_SSSE3
+// Please do not replace with . or with headers that assume more
+// advanced SSE versions without checking with all the OWNERS.
+#include
+#endif
+
+#if SNAPPY_HAVE_BMI2
+// Please do not replace with . or with headers that assume more
+// advanced SSE versions without checking with all the OWNERS.
+#include
+#endif
+
+#include
+
+#include
+#include
+#include
+
+namespace snappy {
+
+using internal::COPY_1_BYTE_OFFSET;
+using internal::COPY_2_BYTE_OFFSET;
+using internal::LITERAL;
+using internal::char_table;
+using internal::kMaximumTagLength;
+
+// Any hash function will produce a valid compressed bitstream, but a good
+// hash function reduces the number of collisions and thus yields better
+// compression for compressible input, and more speed for incompressible
+// input. Of course, it doesn't hurt if the hash function is reasonably fast
+// either, as it gets called a lot.
+static inline uint32 HashBytes(uint32 bytes, int shift) {
+ uint32 kMul = 0x1e35a7bd;
+ return (bytes * kMul) >> shift;
+}
+static inline uint32 Hash(const char* p, int shift) {
+ return HashBytes(UNALIGNED_LOAD32(p), shift);
+}
+
+size_t MaxCompressedLength(size_t source_len) {
+ // Compressed data can be defined as:
+ // compressed := item* literal*
+ // item := literal* copy
+ //
+ // The trailing literal sequence has a space blowup of at most 62/60
+ // since a literal of length 60 needs one tag byte + one extra byte
+ // for length information.
+ //
+ // Item blowup is trickier to measure. Suppose the "copy" op copies
+ // 4 bytes of data. Because of a special check in the encoding code,
+ // we produce a 4-byte copy only if the offset is < 65536. Therefore
+ // the copy op takes 3 bytes to encode, and this type of item leads
+ // to at most the 62/60 blowup for representing literals.
+ //
+ // Suppose the "copy" op copies 5 bytes of data. If the offset is big
+ // enough, it will take 5 bytes to encode the copy op. Therefore the
+ // worst case here is a one-byte literal followed by a five-byte copy.
+ // I.e., 6 bytes of input turn into 7 bytes of "compressed" data.
+ //
+ // This last factor dominates the blowup, so the final estimate is:
+ return 32 + source_len + source_len/6;
+}
+
+namespace {
+
+void UnalignedCopy64(const void* src, void* dst) {
+ char tmp[8];
+ memcpy(tmp, src, 8);
+ memcpy(dst, tmp, 8);
+}
+
+void UnalignedCopy128(const void* src, void* dst) {
+ // memcpy gets vectorized when the appropriate compiler options are used.
+ // For example, x86 compilers targeting SSE2+ will optimize to an SSE2 load
+ // and store.
+ char tmp[16];
+ memcpy(tmp, src, 16);
+ memcpy(dst, tmp, 16);
+}
+
+// Copy [src, src+(op_limit-op)) to [op, (op_limit-op)) a byte at a time. Used
+// for handling COPY operations where the input and output regions may overlap.
+// For example, suppose:
+// src == "ab"
+// op == src + 2
+// op_limit == op + 20
+// After IncrementalCopySlow(src, op, op_limit), the result will have eleven
+// copies of "ab"
+// ababababababababababab
+// Note that this does not match the semantics of either memcpy() or memmove().
+inline char* IncrementalCopySlow(const char* src, char* op,
+ char* const op_limit) {
+ // TODO: Remove pragma when LLVM is aware this
+ // function is only called in cold regions and when cold regions don't get
+ // vectorized or unrolled.
+#ifdef __clang__
+#pragma clang loop unroll(disable)
+#endif
+ while (op < op_limit) {
+ *op++ = *src++;
+ }
+ return op_limit;
+}
+
+#if SNAPPY_HAVE_SSSE3
+
+// This is a table of shuffle control masks that can be used as the source
+// operand for PSHUFB to permute the contents of the destination XMM register
+// into a repeating byte pattern.
+alignas(16) const char pshufb_fill_patterns[7][16] = {
+ {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+ {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1},
+ {0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0},
+ {0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3},
+ {0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0},
+ {0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3},
+ {0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1},
+};
+
+#endif // SNAPPY_HAVE_SSSE3
+
+// Copy [src, src+(op_limit-op)) to [op, (op_limit-op)) but faster than
+// IncrementalCopySlow. buf_limit is the address past the end of the writable
+// region of the buffer.
+inline char* IncrementalCopy(const char* src, char* op, char* const op_limit,
+ char* const buf_limit) {
+ // Terminology:
+ //
+ // slop = buf_limit - op
+ // pat = op - src
+ // len = limit - op
+ assert(src < op);
+ assert(op <= op_limit);
+ assert(op_limit <= buf_limit);
+ // NOTE: The compressor always emits 4 <= len <= 64. It is ok to assume that
+ // to optimize this function but we have to also handle other cases in case
+ // the input does not satisfy these conditions.
+
+ size_t pattern_size = op - src;
+ // The cases are split into different branches to allow the branch predictor,
+ // FDO, and static prediction hints to work better. For each input we list the
+ // ratio of invocations that match each condition.
+ //
+ // input slop < 16 pat < 8 len > 16
+ // ------------------------------------------
+ // html|html4|cp 0% 1.01% 27.73%
+ // urls 0% 0.88% 14.79%
+ // jpg 0% 64.29% 7.14%
+ // pdf 0% 2.56% 58.06%
+ // txt[1-4] 0% 0.23% 0.97%
+ // pb 0% 0.96% 13.88%
+ // bin 0.01% 22.27% 41.17%
+ //
+ // It is very rare that we don't have enough slop for doing block copies. It
+ // is also rare that we need to expand a pattern. Small patterns are common
+ // for incompressible formats and for those we are plenty fast already.
+ // Lengths are normally not greater than 16 but they vary depending on the
+ // input. In general if we always predict len <= 16 it would be an ok
+ // prediction.
+ //
+ // In order to be fast we want a pattern >= 8 bytes and an unrolled loop
+ // copying 2x 8 bytes at a time.
+
+ // Handle the uncommon case where pattern is less than 8 bytes.
+ if (SNAPPY_PREDICT_FALSE(pattern_size < 8)) {
+#if SNAPPY_HAVE_SSSE3
+ // Load the first eight bytes into an 128-bit XMM register, then use PSHUFB
+ // to permute the register's contents in-place into a repeating sequence of
+ // the first "pattern_size" bytes.
+ // For example, suppose:
+ // src == "abc"
+ // op == op + 3
+ // After _mm_shuffle_epi8(), "pattern" will have five copies of "abc"
+ // followed by one byte of slop: abcabcabcabcabca.
+ //
+ // The non-SSE fallback implementation suffers from store-forwarding stalls
+ // because its loads and stores partly overlap. By expanding the pattern
+ // in-place, we avoid the penalty.
+ if (SNAPPY_PREDICT_TRUE(op <= buf_limit - 16)) {
+ const __m128i shuffle_mask = _mm_load_si128(
+ reinterpret_cast(pshufb_fill_patterns)
+ + pattern_size - 1);
+ const __m128i pattern = _mm_shuffle_epi8(
+ _mm_loadl_epi64(reinterpret_cast(src)), shuffle_mask);
+ // Uninitialized bytes are masked out by the shuffle mask.
+ // TODO: remove annotation and macro defs once MSan is fixed.
+ SNAPPY_ANNOTATE_MEMORY_IS_INITIALIZED(&pattern, sizeof(pattern));
+ pattern_size *= 16 / pattern_size;
+ char* op_end = std::min(op_limit, buf_limit - 15);
+ while (op < op_end) {
+ _mm_storeu_si128(reinterpret_cast<__m128i*>(op), pattern);
+ op += pattern_size;
+ }
+ if (SNAPPY_PREDICT_TRUE(op >= op_limit)) return op_limit;
+ }
+ return IncrementalCopySlow(src, op, op_limit);
+#else // !SNAPPY_HAVE_SSSE3
+ // If plenty of buffer space remains, expand the pattern to at least 8
+ // bytes. The way the following loop is written, we need 8 bytes of buffer
+ // space if pattern_size >= 4, 11 bytes if pattern_size is 1 or 3, and 10
+ // bytes if pattern_size is 2. Precisely encoding that is probably not
+ // worthwhile; instead, invoke the slow path if we cannot write 11 bytes
+ // (because 11 are required in the worst case).
+ if (SNAPPY_PREDICT_TRUE(op <= buf_limit - 11)) {
+ while (pattern_size < 8) {
+ UnalignedCopy64(src, op);
+ op += pattern_size;
+ pattern_size *= 2;
+ }
+ if (SNAPPY_PREDICT_TRUE(op >= op_limit)) return op_limit;
+ } else {
+ return IncrementalCopySlow(src, op, op_limit);
+ }
+#endif // SNAPPY_HAVE_SSSE3
+ }
+ assert(pattern_size >= 8);
+
+ // Copy 2x 8 bytes at a time. Because op - src can be < 16, a single
+ // UnalignedCopy128 might overwrite data in op. UnalignedCopy64 is safe
+ // because expanding the pattern to at least 8 bytes guarantees that
+ // op - src >= 8.
+ //
+ // Typically, the op_limit is the gating factor so try to simplify the loop
+ // based on that.
+ if (SNAPPY_PREDICT_TRUE(op_limit <= buf_limit - 16)) {
+ // There is at least one, and at most four 16-byte blocks. Writing four
+ // conditionals instead of a loop allows FDO to layout the code with respect
+ // to the actual probabilities of each length.
+ // TODO: Replace with loop with trip count hint.
+ UnalignedCopy64(src, op);
+ UnalignedCopy64(src + 8, op + 8);
+
+ if (op + 16 < op_limit) {
+ UnalignedCopy64(src + 16, op + 16);
+ UnalignedCopy64(src + 24, op + 24);
+ }
+ if (op + 32 < op_limit) {
+ UnalignedCopy64(src + 32, op + 32);
+ UnalignedCopy64(src + 40, op + 40);
+ }
+ if (op + 48 < op_limit) {
+ UnalignedCopy64(src + 48, op + 48);
+ UnalignedCopy64(src + 56, op + 56);
+ }
+ return op_limit;
+ }
+
+ // Fall back to doing as much as we can with the available slop in the
+ // buffer. This code path is relatively cold however so we save code size by
+ // avoiding unrolling and vectorizing.
+ //
+ // TODO: Remove pragma when when cold regions don't get vectorized
+ // or unrolled.
+#ifdef __clang__
+#pragma clang loop unroll(disable)
+#endif
+ for (char *op_end = buf_limit - 16; op < op_end; op += 16, src += 16) {
+ UnalignedCopy64(src, op);
+ UnalignedCopy64(src + 8, op + 8);
+ }
+ if (op >= op_limit)
+ return op_limit;
+
+ // We only take this branch if we didn't have enough slop and we can do a
+ // single 8 byte copy.
+ if (SNAPPY_PREDICT_FALSE(op <= buf_limit - 8)) {
+ UnalignedCopy64(src, op);
+ src += 8;
+ op += 8;
+ }
+ return IncrementalCopySlow(src, op, op_limit);
+}
+
+} // namespace
+
+template
+static inline char* EmitLiteral(char* op,
+ const char* literal,
+ int len) {
+ // The vast majority of copies are below 16 bytes, for which a
+ // call to memcpy is overkill. This fast path can sometimes
+ // copy up to 15 bytes too much, but that is okay in the
+ // main loop, since we have a bit to go on for both sides:
+ //
+ // - The input will always have kInputMarginBytes = 15 extra
+ // available bytes, as long as we're in the main loop, and
+ // if not, allow_fast_path = false.
+ // - The output will always have 32 spare bytes (see
+ // MaxCompressedLength).
+ assert(len > 0); // Zero-length literals are disallowed
+ int n = len - 1;
+ if (allow_fast_path && len <= 16) {
+ // Fits in tag byte
+ *op++ = LITERAL | (n << 2);
+
+ UnalignedCopy128(literal, op);
+ return op + len;
+ }
+
+ if (n < 60) {
+ // Fits in tag byte
+ *op++ = LITERAL | (n << 2);
+ } else {
+ int count = (Bits::Log2Floor(n) >> 3) + 1;
+ assert(count >= 1);
+ assert(count <= 4);
+ *op++ = LITERAL | ((59 + count) << 2);
+ // Encode in upcoming bytes.
+ // Write 4 bytes, though we may care about only 1 of them. The output buffer
+ // is guaranteed to have at least 3 more spaces left as 'len >= 61' holds
+ // here and there is a memcpy of size 'len' below.
+ LittleEndian::Store32(op, n);
+ op += count;
+ }
+ memcpy(op, literal, len);
+ return op + len;
+}
+
+template
+static inline char* EmitCopyAtMost64(char* op, size_t offset, size_t len) {
+ assert(len <= 64);
+ assert(len >= 4);
+ assert(offset < 65536);
+ assert(len_less_than_12 == (len < 12));
+
+ if (len_less_than_12 && SNAPPY_PREDICT_TRUE(offset < 2048)) {
+ // offset fits in 11 bits. The 3 highest go in the top of the first byte,
+ // and the rest go in the second byte.
+ *op++ = COPY_1_BYTE_OFFSET + ((len - 4) << 2) + ((offset >> 3) & 0xe0);
+ *op++ = offset & 0xff;
+ } else {
+ // Write 4 bytes, though we only care about 3 of them. The output buffer
+ // is required to have some slack, so the extra byte won't overrun it.
+ uint32 u = COPY_2_BYTE_OFFSET + ((len - 1) << 2) + (offset << 8);
+ LittleEndian::Store32(op, u);
+ op += 3;
+ }
+ return op;
+}
+
+template
+static inline char* EmitCopy(char* op, size_t offset, size_t len) {
+ assert(len_less_than_12 == (len < 12));
+ if (len_less_than_12) {
+ return EmitCopyAtMost64*len_less_than_12=*/true>(op, offset, len);
+ } else {
+ // A special case for len <= 64 might help, but so far measurements suggest
+ // it's in the noise.
+
+ // Emit 64 byte copies but make sure to keep at least four bytes reserved.
+ while (SNAPPY_PREDICT_FALSE(len >= 68)) {
+ op = EmitCopyAtMost64*len_less_than_12=*/false>(op, offset, 64);
+ len -= 64;
+ }
+
+ // One or two copies will now finish the job.
+ if (len > 64) {
+ op = EmitCopyAtMost64*len_less_than_12=*/false>(op, offset, 60);
+ len -= 60;
+ }
+
+ // Emit remainder.
+ if (len < 12) {
+ op = EmitCopyAtMost64*len_less_than_12=*/true>(op, offset, len);
+ } else {
+ op = EmitCopyAtMost64*len_less_than_12=*/false>(op, offset, len);
+ }
+ return op;
+ }
+}
+
+bool GetUncompressedLength(const char* start, size_t n, size_t* result) {
+ uint32 v = 0;
+ const char* limit = start + n;
+ if (Varint::Parse32WithLimit(start, limit, &v) != NULL) {
+ *result = v;
+ return true;
+ } else {
+ return false;
+ }
+}
+
+namespace {
+uint32 CalculateTableSize(uint32 input_size) {
+ static_assert(
+ kMaxHashTableSize >= kMinHashTableSize,
+ "kMaxHashTableSize should be greater or equal to kMinHashTableSize.");
+ if (input_size > kMaxHashTableSize) {
+ return kMaxHashTableSize;
+ }
+ if (input_size < kMinHashTableSize) {
+ return kMinHashTableSize;
+ }
+ // This is equivalent to Log2Ceiling(input_size), assuming input_size > 1.
+ // 2 << Log2Floor(x - 1) is equivalent to 1 << (1 + Log2Floor(x - 1)).
+ return 2u << Bits::Log2Floor(input_size - 1);
+}
+} // namespace
+
+namespace internal {
+WorkingMemory::WorkingMemory(size_t input_size) {
+ const size_t max_fragment_size = std::min(input_size, kBlockSize);
+ const size_t table_size = CalculateTableSize(max_fragment_size);
+ size_ = table_size * sizeof(*table_) + max_fragment_size +
+ MaxCompressedLength(max_fragment_size);
+ mem_ = std::allocator().allocate(size_);
+ table_ = reinterpret_cast(mem_);
+ input_ = mem_ + table_size * sizeof(*table_);
+ output_ = input_ + max_fragment_size;
+}
+
+WorkingMemory::~WorkingMemory() {
+ std::allocator().deallocate(mem_, size_);
+}
+
+uint16* WorkingMemory::GetHashTable(size_t fragment_size,
+ int* table_size) const {
+ const size_t htsize = CalculateTableSize(fragment_size);
+ memset(table_, 0, htsize * sizeof(*table_));
+ *table_size = htsize;
+ return table_;
+}
+} // end namespace internal
+
+// For 0 <= offset <= 4, GetUint32AtOffset(GetEightBytesAt(p), offset) will
+// equal UNALIGNED_LOAD32(p + offset). Motivation: On x86-64 hardware we have
+// empirically found that overlapping loads such as
+// UNALIGNED_LOAD32(p) ... UNALIGNED_LOAD32(p+1) ... UNALIGNED_LOAD32(p+2)
+// are slower than UNALIGNED_LOAD64(p) followed by shifts and casts to uint32.
+//
+// We have different versions for 64- and 32-bit; ideally we would avoid the
+// two functions and just inline the UNALIGNED_LOAD64 call into
+// GetUint32AtOffset, but GCC (at least not as of 4.6) is seemingly not clever
+// enough to avoid loading the value multiple times then. For 64-bit, the load
+// is done when GetEightBytesAt() is called, whereas for 32-bit, the load is
+// done at GetUint32AtOffset() time.
+
+#ifdef ARCH_K8
+
+typedef uint64 EightBytesReference;
+
+static inline EightBytesReference GetEightBytesAt(const char* ptr) {
+ return UNALIGNED_LOAD64(ptr);
+}
+
+static inline uint32 GetUint32AtOffset(uint64 v, int offset) {
+ assert(offset >= 0);
+ assert(offset <= 4);
+ return v >> (LittleEndian::IsLittleEndian() ? 8 * offset : 32 - 8 * offset);
+}
+
+#else
+
+typedef const char* EightBytesReference;
+
+static inline EightBytesReference GetEightBytesAt(const char* ptr) {
+ return ptr;
+}
+
+static inline uint32 GetUint32AtOffset(const char* v, int offset) {
+ assert(offset >= 0);
+ assert(offset <= 4);
+ return UNALIGNED_LOAD32(v + offset);
+}
+
+#endif
+
+// Flat array compression that does not emit the "uncompressed length"
+// prefix. Compresses "input" string to the "*op" buffer.
+//
+// REQUIRES: "input" is at most "kBlockSize" bytes long.
+// REQUIRES: "op" points to an array of memory that is at least
+// "MaxCompressedLength(input.size())" in size.
+// REQUIRES: All elements in "table[0..table_size-1]" are initialized to zero.
+// REQUIRES: "table_size" is a power of two
+//
+// Returns an "end" pointer into "op" buffer.
+// "end - op" is the compressed size of "input".
+namespace internal {
+char* CompressFragment(const char* input,
+ size_t input_size,
+ char* op,
+ uint16* table,
+ const int table_size) {
+ // "ip" is the input pointer, and "op" is the output pointer.
+ const char* ip = input;
+ assert(input_size <= kBlockSize);
+ assert((table_size & (table_size - 1)) == 0); // table must be power of two
+ const int shift = 32 - Bits::Log2Floor(table_size);
+ assert(static_cast(kuint32max >> shift) == table_size - 1);
+ const char* ip_end = input + input_size;
+ const char* base_ip = ip;
+ // Bytes in [next_emit, ip) will be emitted as literal bytes. Or
+ // [next_emit, ip_end) after the main loop.
+ const char* next_emit = ip;
+
+ const size_t kInputMarginBytes = 15;
+ if (SNAPPY_PREDICT_TRUE(input_size >= kInputMarginBytes)) {
+ const char* ip_limit = input + input_size - kInputMarginBytes;
+
+ for (uint32 next_hash = Hash(++ip, shift); ; ) {
+ assert(next_emit < ip);
+ // The body of this loop calls EmitLiteral once and then EmitCopy one or
+ // more times. (The exception is that when we're close to exhausting
+ // the input we goto emit_remainder.)
+ //
+ // In the first iteration of this loop we're just starting, so
+ // there's nothing to copy, so calling EmitLiteral once is
+ // necessary. And we only start a new iteration when the
+ // current iteration has determined that a call to EmitLiteral will
+ // precede the next call to EmitCopy (if any).
+ //
+ // Step 1: Scan forward in the input looking for a 4-byte-long match.
+ // If we get close to exhausting the input then goto emit_remainder.
+ //
+ // Heuristic match skipping: If 32 bytes are scanned with no matches
+ // found, start looking only at every other byte. If 32 more bytes are
+ // scanned (or skipped), look at every third byte, etc.. When a match is
+ // found, immediately go back to looking at every byte. This is a small
+ // loss (~5% performance, ~0.1% density) for compressible data due to more
+ // bookkeeping, but for non-compressible data (such as JPEG) it's a huge
+ // win since the compressor quickly "realizes" the data is incompressible
+ // and doesn't bother looking for matches everywhere.
+ //
+ // The "skip" variable keeps track of how many bytes there are since the
+ // last match; dividing it by 32 (ie. right-shifting by five) gives the
+ // number of bytes to move ahead for each iteration.
+ uint32 skip = 32;
+
+ const char* next_ip = ip;
+ const char* candidate;
+ do {
+ ip = next_ip;
+ uint32 hash = next_hash;
+ assert(hash == Hash(ip, shift));
+ uint32 bytes_between_hash_lookups = skip >> 5;
+ skip += bytes_between_hash_lookups;
+ next_ip = ip + bytes_between_hash_lookups;
+ if (SNAPPY_PREDICT_FALSE(next_ip > ip_limit)) {
+ goto emit_remainder;
+ }
+ next_hash = Hash(next_ip, shift);
+ candidate = base_ip + table[hash];
+ assert(candidate >= base_ip);
+ assert(candidate < ip);
+
+ table[hash] = ip - base_ip;
+ } while (SNAPPY_PREDICT_TRUE(UNALIGNED_LOAD32(ip) !=
+ UNALIGNED_LOAD32(candidate)));
+
+ // Step 2: A 4-byte match has been found. We'll later see if more
+ // than 4 bytes match. But, prior to the match, input
+ // bytes [next_emit, ip) are unmatched. Emit them as "literal bytes."
+ assert(next_emit + 16 <= ip_end);
+ op = EmitLiteral*allow_fast_path=*/true>(op, next_emit, ip - next_emit);
+
+ // Step 3: Call EmitCopy, and then see if another EmitCopy could
+ // be our next move. Repeat until we find no match for the
+ // input immediately after what was consumed by the last EmitCopy call.
+ //
+ // If we exit this loop normally then we need to call EmitLiteral next,
+ // though we don't yet know how big the literal will be. We handle that
+ // by proceeding to the next iteration of the main loop. We also can exit
+ // this loop via goto if we get close to exhausting the input.
+ EightBytesReference input_bytes;
+ uint32 candidate_bytes = 0;
+
+ do {
+ // We have a 4-byte match at ip, and no need to emit any
+ // "literal bytes" prior to ip.
+ const char* base = ip;
+ std::pair p =
+ FindMatchLength(candidate + 4, ip + 4, ip_end);
+ size_t matched = 4 + p.first;
+ ip += matched;
+ size_t offset = base - candidate;
+ assert(0 == memcmp(base, candidate, matched));
+ if (p.second) {
+ op = EmitCopy*len_less_than_12=*/true>(op, offset, matched);
+ } else {
+ op = EmitCopy*len_less_than_12=*/false>(op, offset, matched);
+ }
+ next_emit = ip;
+ if (SNAPPY_PREDICT_FALSE(ip >= ip_limit)) {
+ goto emit_remainder;
+ }
+ // We are now looking for a 4-byte match again. We read
+ // table[Hash(ip, shift)] for that. To improve compression,
+ // we also update table[Hash(ip - 1, shift)] and table[Hash(ip, shift)].
+ input_bytes = GetEightBytesAt(ip - 1);
+ uint32 prev_hash = HashBytes(GetUint32AtOffset(input_bytes, 0), shift);
+ table[prev_hash] = ip - base_ip - 1;
+ uint32 cur_hash = HashBytes(GetUint32AtOffset(input_bytes, 1), shift);
+ candidate = base_ip + table[cur_hash];
+ candidate_bytes = UNALIGNED_LOAD32(candidate);
+ table[cur_hash] = ip - base_ip;
+ } while (GetUint32AtOffset(input_bytes, 1) == candidate_bytes);
+
+ next_hash = HashBytes(GetUint32AtOffset(input_bytes, 2), shift);
+ ++ip;
+ }
+ }
+
+ emit_remainder:
+ // Emit the remaining bytes as a literal
+ if (next_emit < ip_end) {
+ op = EmitLiteral*allow_fast_path=*/false>(op, next_emit,
+ ip_end - next_emit);
+ }
+
+ return op;
+}
+} // end namespace internal
+
+// Called back at avery compression call to trace parameters and sizes.
+static inline void Report(const char *algorithm, size_t compressed_size,
+ size_t uncompressed_size) {}
+
+// Signature of output types needed by decompression code.
+// The decompression code is templatized on a type that obeys this
+// signature so that we do not pay virtual function call overhead in
+// the middle of a tight decompression loop.
+//
+// class DecompressionWriter {
+// public:
+// // Called before decompression
+// void SetExpectedLength(size_t length);
+//
+// // Called after decompression
+// bool CheckLength() const;
+//
+// // Called repeatedly during decompression
+// bool Append(const char* ip, size_t length);
+// bool AppendFromSelf(uint32 offset, size_t length);
+//
+// // The rules for how TryFastAppend differs from Append are somewhat
+// // convoluted:
+// //
+// // - TryFastAppend is allowed to decline (return false) at any
+// // time, for any reason -- just "return false" would be
+// // a perfectly legal implementation of TryFastAppend.
+// // The intention is for TryFastAppend to allow a fast path
+// // in the common case of a small append.
+// // - TryFastAppend is allowed to read up to bytes
+// // from the input buffer, whereas Append is allowed to read
+// // . However, if it returns true, it must leave
+// // at least five (kMaximumTagLength) bytes in the input buffer
+// // afterwards, so that there is always enough space to read the
+// // next tag without checking for a refill.
+// // - TryFastAppend must always return decline (return false)
+// // if is 61 or more, as in this case the literal length is not
+// // decoded fully. In practice, this should not be a big problem,
+// // as it is unlikely that one would implement a fast path accepting
+// // this much data.
+// //
+// bool TryFastAppend(const char* ip, size_t available, size_t length);
+// };
+
+static inline uint32 ExtractLowBytes(uint32 v, int n) {
+ assert(n >= 0);
+ assert(n <= 4);
+#if SNAPPY_HAVE_BMI2
+ return _bzhi_u32(v, 8 * n);
+#else
+ // This needs to be wider than uint32 otherwise `mask << 32` will be
+ // undefined.
+ uint64 mask = 0xffffffff;
+ return v & ~(mask << (8 * n));
+#endif
+}
+
+static inline bool LeftShiftOverflows(uint8 value, uint32 shift) {
+ assert(shift < 32);
+ static const uint8 masks[] = {
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
+ 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe};
+ return (value & masks[shift]) != 0;
+}
+
+// Helper class for decompression
+class SnappyDecompressor {
+ private:
+ Source* reader_; // Underlying source of bytes to decompress
+ const char* ip_; // Points to next buffered byte
+ const char* ip_limit_; // Points just past buffered bytes
+ uint32 peeked_; // Bytes peeked from reader (need to skip)
+ bool eof_; // Hit end of input without an error?
+ char scratch_[kMaximumTagLength]; // See RefillTag().
+
+ // Ensure that all of the tag metadata for the next tag is available
+ // in [ip_..ip_limit_-1]. Also ensures that [ip,ip+4] is readable even
+ // if (ip_limit_ - ip_ < 5).
+ //
+ // Returns true on success, false on error or end of input.
+ bool RefillTag();
+
+ public:
+ explicit SnappyDecompressor(Source* reader)
+ : reader_(reader),
+ ip_(NULL),
+ ip_limit_(NULL),
+ peeked_(0),
+ eof_(false) {
+ }
+
+ ~SnappyDecompressor() {
+ // Advance past any bytes we peeked at from the reader
+ reader_->Skip(peeked_);
+ }
+
+ // Returns true iff we have hit the end of the input without an error.
+ bool eof() const {
+ return eof_;
+ }
+
+ // Read the uncompressed length stored at the start of the compressed data.
+ // On success, stores the length in *result and returns true.
+ // On failure, returns false.
+ bool ReadUncompressedLength(uint32* result) {
+ assert(ip_ == NULL); // Must not have read anything yet
+ // Length is encoded in 1..5 bytes
+ *result = 0;
+ uint32 shift = 0;
+ while (true) {
+ if (shift >= 32) return false;
+ size_t n;
+ const char* ip = reader_->Peek(&n);
+ if (n == 0) return false;
+ const unsigned char c = *(reinterpret_cast(ip));
+ reader_->Skip(1);
+ uint32 val = c & 0x7f;
+ if (LeftShiftOverflows(static_cast(val), shift)) return false;
+ *result |= val << shift;
+ if (c < 128) {
+ break;
+ }
+ shift += 7;
+ }
+ return true;
+ }
+
+ // Process the next item found in the input.
+ // Returns true if successful, false on error or end of input.
+ template
+#if defined(__GNUC__) && defined(__x86_64__)
+ __attribute__((aligned(32)))
+#endif
+ void DecompressAllTags(Writer* writer) {
+ // In x86, pad the function body to start 16 bytes later. This function has
+ // a couple of hotspots that are highly sensitive to alignment: we have
+ // observed regressions by more than 20% in some metrics just by moving the
+ // exact same code to a different position in the benchmark binary.
+ //
+ // Putting this code on a 32-byte-aligned boundary + 16 bytes makes us hit
+ // the "lucky" case consistently. Unfortunately, this is a very brittle
+ // workaround, and future differences in code generation may reintroduce
+ // this regression. If you experience a big, difficult to explain, benchmark
+ // performance regression here, first try removing this hack.
+#if defined(__GNUC__) && defined(__x86_64__)
+ // Two 8-byte "NOP DWORD ptr [EAX + EAX*1 + 00000000H]" instructions.
+ asm(".byte 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00");
+ asm(".byte 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00");
+#endif
+
+ const char* ip = ip_;
+ // We could have put this refill fragment only at the beginning of the loop.
+ // However, duplicating it at the end of each branch gives the compiler more
+ // scope to optimize the expression based on the local
+ // context, which overall increases speed.
+ #define MAYBE_REFILL() \
+ if (ip_limit_ - ip < kMaximumTagLength) { \
+ ip_ = ip; \
+ if (!RefillTag()) return; \
+ ip = ip_; \
+ }
+
+ MAYBE_REFILL();
+ for ( ;; ) {
+ const unsigned char c = *(reinterpret_cast(ip++));
+
+ // Ratio of iterations that have LITERAL vs non-LITERAL for different
+ // inputs.
+ //
+ // input LITERAL NON_LITERAL
+ // -----------------------------------
+ // html|html4|cp 23% 77%
+ // urls 36% 64%
+ // jpg 47% 53%
+ // pdf 19% 81%
+ // txt[1-4] 25% 75%
+ // pb 24% 76%
+ // bin 24% 76%
+ if (SNAPPY_PREDICT_FALSE((c & 0x3) == LITERAL)) {
+ size_t literal_length = (c >> 2) + 1u;
+ if (writer->TryFastAppend(ip, ip_limit_ - ip, literal_length)) {
+ assert(literal_length < 61);
+ ip += literal_length;
+ // NOTE: There is no MAYBE_REFILL() here, as TryFastAppend()
+ // will not return true unless there's already at least five spare
+ // bytes in addition to the literal.
+ continue;
+ }
+ if (SNAPPY_PREDICT_FALSE(literal_length >= 61)) {
+ // Long literal.
+ const size_t literal_length_length = literal_length - 60;
+ literal_length =
+ ExtractLowBytes(LittleEndian::Load32(ip), literal_length_length) +
+ 1;
+ ip += literal_length_length;
+ }
+
+ size_t avail = ip_limit_ - ip;
+ while (avail < literal_length) {
+ if (!writer->Append(ip, avail)) return;
+ literal_length -= avail;
+ reader_->Skip(peeked_);
+ size_t n;
+ ip = reader_->Peek(&n);
+ avail = n;
+ peeked_ = avail;
+ if (avail == 0) return; // Premature end of input
+ ip_limit_ = ip + avail;
+ }
+ if (!writer->Append(ip, literal_length)) {
+ return;
+ }
+ ip += literal_length;
+ MAYBE_REFILL();
+ } else {
+ const size_t entry = char_table[c];
+ const size_t trailer =
+ ExtractLowBytes(LittleEndian::Load32(ip), entry >> 11);
+ const size_t length = entry & 0xff;
+ ip += entry >> 11;
+
+ // copy_offset/256 is encoded in bits 8..10. By just fetching
+ // those bits, we get copy_offset (since the bit-field starts at
+ // bit 8).
+ const size_t copy_offset = entry & 0x700;
+ if (!writer->AppendFromSelf(copy_offset + trailer, length)) {
+ return;
+ }
+ MAYBE_REFILL();
+ }
+ }
+
+#undef MAYBE_REFILL
+ }
+};
+
+bool SnappyDecompressor::RefillTag() {
+ const char* ip = ip_;
+ if (ip == ip_limit_) {
+ // Fetch a new fragment from the reader
+ reader_->Skip(peeked_); // All peeked bytes are used up
+ size_t n;
+ ip = reader_->Peek(&n);
+ peeked_ = n;
+ eof_ = (n == 0);
+ if (eof_) return false;
+ ip_limit_ = ip + n;
+ }
+
+ // Read the tag character
+ assert(ip < ip_limit_);
+ const unsigned char c = *(reinterpret_cast(ip));
+ const uint32 entry = char_table[c];
+ const uint32 needed = (entry >> 11) + 1; // +1 byte for 'c'
+ assert(needed <= sizeof(scratch_));
+
+ // Read more bytes from reader if needed
+ uint32 nbuf = ip_limit_ - ip;
+ if (nbuf < needed) {
+ // Stitch together bytes from ip and reader to form the word
+ // contents. We store the needed bytes in "scratch_". They
+ // will be consumed immediately by the caller since we do not
+ // read more than we need.
+ memmove(scratch_, ip, nbuf);
+ reader_->Skip(peeked_); // All peeked bytes are used up
+ peeked_ = 0;
+ while (nbuf < needed) {
+ size_t length;
+ const char* src = reader_->Peek(&length);
+ if (length == 0) return false;
+ uint32 to_add = std::min(needed - nbuf, length);
+ memcpy(scratch_ + nbuf, src, to_add);
+ nbuf += to_add;
+ reader_->Skip(to_add);
+ }
+ assert(nbuf == needed);
+ ip_ = scratch_;
+ ip_limit_ = scratch_ + needed;
+ } else if (nbuf < kMaximumTagLength) {
+ // Have enough bytes, but move into scratch_ so that we do not
+ // read past end of input
+ memmove(scratch_, ip, nbuf);
+ reader_->Skip(peeked_); // All peeked bytes are used up
+ peeked_ = 0;
+ ip_ = scratch_;
+ ip_limit_ = scratch_ + nbuf;
+ } else {
+ // Pass pointer to buffer returned by reader_.
+ ip_ = ip;
+ }
+ return true;
+}
+
+template
+static bool InternalUncompress(Source* r, Writer* writer) {
+ // Read the uncompressed length from the front of the compressed input
+ SnappyDecompressor decompressor(r);
+ uint32 uncompressed_len = 0;
+ if (!decompressor.ReadUncompressedLength(&uncompressed_len)) return false;
+
+ return InternalUncompressAllTags(&decompressor, writer, r->Available(),
+ uncompressed_len);
+}
+
+template
+static bool InternalUncompressAllTags(SnappyDecompressor* decompressor,
+ Writer* writer,
+ uint32 compressed_len,
+ uint32 uncompressed_len) {
+ Report("snappy_uncompress", compressed_len, uncompressed_len);
+
+ writer->SetExpectedLength(uncompressed_len);
+
+ // Process the entire input
+ decompressor->DecompressAllTags(writer);
+ writer->Flush();
+ return (decompressor->eof() && writer->CheckLength());
+}
+
+bool GetUncompressedLength(Source* source, uint32* result) {
+ SnappyDecompressor decompressor(source);
+ return decompressor.ReadUncompressedLength(result);
+}
+
+size_t Compress(Source* reader, Sink* writer) {
+ size_t written = 0;
+ size_t N = reader->Available();
+ const size_t uncompressed_size = N;
+ char ulength[Varint::kMax32];
+ char* p = Varint::Encode32(ulength, N);
+ writer->Append(ulength, p-ulength);
+ written += (p - ulength);
+
+ internal::WorkingMemory wmem(N);
+
+ while (N > 0) {
+ // Get next block to compress (without copying if possible)
+ size_t fragment_size;
+ const char* fragment = reader->Peek(&fragment_size);
+ assert(fragment_size != 0); // premature end of input
+ const size_t num_to_read = std::min(N, kBlockSize);
+ size_t bytes_read = fragment_size;
+
+ size_t pending_advance = 0;
+ if (bytes_read >= num_to_read) {
+ // Buffer returned by reader is large enough
+ pending_advance = num_to_read;
+ fragment_size = num_to_read;
+ } else {
+ char* scratch = wmem.GetScratchInput();
+ memcpy(scratch, fragment, bytes_read);
+ reader->Skip(bytes_read);
+
+ while (bytes_read < num_to_read) {
+ fragment = reader->Peek(&fragment_size);
+ size_t n = std::min(fragment_size, num_to_read - bytes_read);
+ memcpy(scratch + bytes_read, fragment, n);
+ bytes_read += n;
+ reader->Skip(n);
+ }
+ assert(bytes_read == num_to_read);
+ fragment = scratch;
+ fragment_size = num_to_read;
+ }
+ assert(fragment_size == num_to_read);
+
+ // Get encoding table for compression
+ int table_size;
+ uint16* table = wmem.GetHashTable(num_to_read, &table_size);
+
+ // Compress input_fragment and append to dest
+ const int max_output = MaxCompressedLength(num_to_read);
+
+ // Need a scratch buffer for the output, in case the byte sink doesn't
+ // have room for us directly.
+
+ // Since we encode kBlockSize regions followed by a region
+ // which is <= kBlockSize in length, a previously allocated
+ // scratch_output[] region is big enough for this iteration.
+ char* dest = writer->GetAppendBuffer(max_output, wmem.GetScratchOutput());
+ char* end = internal::CompressFragment(fragment, fragment_size, dest, table,
+ table_size);
+ writer->Append(dest, end - dest);
+ written += (end - dest);
+
+ N -= num_to_read;
+ reader->Skip(pending_advance);
+ }
+
+ Report("snappy_compress", written, uncompressed_size);
+
+ return written;
+}
+
+// -----------------------------------------------------------------------
+// IOVec interfaces
+// -----------------------------------------------------------------------
+
+// A type that writes to an iovec.
+// Note that this is not a "ByteSink", but a type that matches the
+// Writer template argument to SnappyDecompressor::DecompressAllTags().
+class SnappyIOVecWriter {
+ private:
+ // output_iov_end_ is set to iov + count and used to determine when
+ // the end of the iovs is reached.
+ const struct iovec* output_iov_end_;
+
+#if !defined(NDEBUG)
+ const struct iovec* output_iov_;
+#endif // !defined(NDEBUG)
+
+ // Current iov that is being written into.
+ const struct iovec* curr_iov_;
+
+ // Pointer to current iov's write location.
+ char* curr_iov_output_;
+
+ // Remaining bytes to write into curr_iov_output.
+ size_t curr_iov_remaining_;
+
+ // Total bytes decompressed into output_iov_ so far.
+ size_t total_written_;
+
+ // Maximum number of bytes that will be decompressed into output_iov_.
+ size_t output_limit_;
+
+ static inline char* GetIOVecPointer(const struct iovec* iov, size_t offset) {
+ return reinterpret_cast(iov->iov_base) + offset;
+ }
+
+ public:
+ // Does not take ownership of iov. iov must be valid during the
+ // entire lifetime of the SnappyIOVecWriter.
+ inline SnappyIOVecWriter(const struct iovec* iov, size_t iov_count)
+ : output_iov_end_(iov + iov_count),
+#if !defined(NDEBUG)
+ output_iov_(iov),
+#endif // !defined(NDEBUG)
+ curr_iov_(iov),
+ curr_iov_output_(iov_count ? reinterpret_cast(iov->iov_base)
+ : nullptr),
+ curr_iov_remaining_(iov_count ? iov->iov_len : 0),
+ total_written_(0),
+ output_limit_(-1) {}
+
+ inline void SetExpectedLength(size_t len) {
+ output_limit_ = len;
+ }
+
+ inline bool CheckLength() const {
+ return total_written_ == output_limit_;
+ }
+
+ inline bool Append(const char* ip, size_t len) {
+ if (total_written_ + len > output_limit_) {
+ return false;
+ }
+
+ return AppendNoCheck(ip, len);
+ }
+
+ inline bool AppendNoCheck(const char* ip, size_t len) {
+ while (len > 0) {
+ if (curr_iov_remaining_ == 0) {
+ // This iovec is full. Go to the next one.
+ if (curr_iov_ + 1 >= output_iov_end_) {
+ return false;
+ }
+ ++curr_iov_;
+ curr_iov_output_ = reinterpret_cast(curr_iov_->iov_base);
+ curr_iov_remaining_ = curr_iov_->iov_len;
+ }
+
+ const size_t to_write = std::min(len, curr_iov_remaining_);
+ memcpy(curr_iov_output_, ip, to_write);
+ curr_iov_output_ += to_write;
+ curr_iov_remaining_ -= to_write;
+ total_written_ += to_write;
+ ip += to_write;
+ len -= to_write;
+ }
+
+ return true;
+ }
+
+ inline bool TryFastAppend(const char* ip, size_t available, size_t len) {
+ const size_t space_left = output_limit_ - total_written_;
+ if (len <= 16 && available >= 16 + kMaximumTagLength && space_left >= 16 &&
+ curr_iov_remaining_ >= 16) {
+ // Fast path, used for the majority (about 95%) of invocations.
+ UnalignedCopy128(ip, curr_iov_output_);
+ curr_iov_output_ += len;
+ curr_iov_remaining_ -= len;
+ total_written_ += len;
+ return true;
+ }
+
+ return false;
+ }
+
+ inline bool AppendFromSelf(size_t offset, size_t len) {
+ // See SnappyArrayWriter::AppendFromSelf for an explanation of
+ // the "offset - 1u" trick.
+ if (offset - 1u >= total_written_) {
+ return false;
+ }
+ const size_t space_left = output_limit_ - total_written_;
+ if (len > space_left) {
+ return false;
+ }
+
+ // Locate the iovec from which we need to start the copy.
+ const iovec* from_iov = curr_iov_;
+ size_t from_iov_offset = curr_iov_->iov_len - curr_iov_remaining_;
+ while (offset > 0) {
+ if (from_iov_offset >= offset) {
+ from_iov_offset -= offset;
+ break;
+ }
+
+ offset -= from_iov_offset;
+ --from_iov;
+#if !defined(NDEBUG)
+ assert(from_iov >= output_iov_);
+#endif // !defined(NDEBUG)
+ from_iov_offset = from_iov->iov_len;
+ }
+
+ // Copy bytes starting from the iovec pointed to by from_iov_index to
+ // the current iovec.
+ while (len > 0) {
+ assert(from_iov <= curr_iov_);
+ if (from_iov != curr_iov_) {
+ const size_t to_copy =
+ std::min(from_iov->iov_len - from_iov_offset, len);
+ AppendNoCheck(GetIOVecPointer(from_iov, from_iov_offset), to_copy);
+ len -= to_copy;
+ if (len > 0) {
+ ++from_iov;
+ from_iov_offset = 0;
+ }
+ } else {
+ size_t to_copy = curr_iov_remaining_;
+ if (to_copy == 0) {
+ // This iovec is full. Go to the next one.
+ if (curr_iov_ + 1 >= output_iov_end_) {
+ return false;
+ }
+ ++curr_iov_;
+ curr_iov_output_ = reinterpret_cast(curr_iov_->iov_base);
+ curr_iov_remaining_ = curr_iov_->iov_len;
+ continue;
+ }
+ if (to_copy > len) {
+ to_copy = len;
+ }
+
+ IncrementalCopy(GetIOVecPointer(from_iov, from_iov_offset),
+ curr_iov_output_, curr_iov_output_ + to_copy,
+ curr_iov_output_ + curr_iov_remaining_);
+ curr_iov_output_ += to_copy;
+ curr_iov_remaining_ -= to_copy;
+ from_iov_offset += to_copy;
+ total_written_ += to_copy;
+ len -= to_copy;
+ }
+ }
+
+ return true;
+ }
+
+ inline void Flush() {}
+};
+
+bool RawUncompressToIOVec(const char* compressed, size_t compressed_length,
+ const struct iovec* iov, size_t iov_cnt) {
+ ByteArraySource reader(compressed, compressed_length);
+ return RawUncompressToIOVec(&reader, iov, iov_cnt);
+}
+
+bool RawUncompressToIOVec(Source* compressed, const struct iovec* iov,
+ size_t iov_cnt) {
+ SnappyIOVecWriter output(iov, iov_cnt);
+ return InternalUncompress(compressed, &output);
+}
+
+// -----------------------------------------------------------------------
+// Flat array interfaces
+// -----------------------------------------------------------------------
+
+// A type that writes to a flat array.
+// Note that this is not a "ByteSink", but a type that matches the
+// Writer template argument to SnappyDecompressor::DecompressAllTags().
+class SnappyArrayWriter {
+ private:
+ char* base_;
+ char* op_;
+ char* op_limit_;
+
+ public:
+ inline explicit SnappyArrayWriter(char* dst)
+ : base_(dst),
+ op_(dst),
+ op_limit_(dst) {
+ }
+
+ inline void SetExpectedLength(size_t len) {
+ op_limit_ = op_ + len;
+ }
+
+ inline bool CheckLength() const {
+ return op_ == op_limit_;
+ }
+
+ inline bool Append(const char* ip, size_t len) {
+ char* op = op_;
+ const size_t space_left = op_limit_ - op;
+ if (space_left < len) {
+ return false;
+ }
+ memcpy(op, ip, len);
+ op_ = op + len;
+ return true;
+ }
+
+ inline bool TryFastAppend(const char* ip, size_t available, size_t len) {
+ char* op = op_;
+ const size_t space_left = op_limit_ - op;
+ if (len <= 16 && available >= 16 + kMaximumTagLength && space_left >= 16) {
+ // Fast path, used for the majority (about 95%) of invocations.
+ UnalignedCopy128(ip, op);
+ op_ = op + len;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ inline bool AppendFromSelf(size_t offset, size_t len) {
+ char* const op_end = op_ + len;
+
+ // Check if we try to append from before the start of the buffer.
+ // Normally this would just be a check for "produced < offset",
+ // but "produced <= offset - 1u" is equivalent for every case
+ // except the one where offset==0, where the right side will wrap around
+ // to a very big number. This is convenient, as offset==0 is another
+ // invalid case that we also want to catch, so that we do not go
+ // into an infinite loop.
+ if (Produced() <= offset - 1u || op_end > op_limit_) return false;
+ op_ = IncrementalCopy(op_ - offset, op_, op_end, op_limit_);
+
+ return true;
+ }
+ inline size_t Produced() const {
+ assert(op_ >= base_);
+ return op_ - base_;
+ }
+ inline void Flush() {}
+};
+
+bool RawUncompress(const char* compressed, size_t n, char* uncompressed) {
+ ByteArraySource reader(compressed, n);
+ return RawUncompress(&reader, uncompressed);
+}
+
+bool RawUncompress(Source* compressed, char* uncompressed) {
+ SnappyArrayWriter output(uncompressed);
+ return InternalUncompress(compressed, &output);
+}
+
+bool Uncompress(const char* compressed, size_t n, std::string* uncompressed) {
+ size_t ulength;
+ if (!GetUncompressedLength(compressed, n, &ulength)) {
+ return false;
+ }
+ // On 32-bit builds: max_size() < kuint32max. Check for that instead
+ // of crashing (e.g., consider externally specified compressed data).
+ if (ulength > uncompressed->max_size()) {
+ return false;
+ }
+ STLStringResizeUninitialized(uncompressed, ulength);
+ return RawUncompress(compressed, n, string_as_array(uncompressed));
+}
+
+// A Writer that drops everything on the floor and just does validation
+class SnappyDecompressionValidator {
+ private:
+ size_t expected_;
+ size_t produced_;
+
+ public:
+ inline SnappyDecompressionValidator() : expected_(0), produced_(0) { }
+ inline void SetExpectedLength(size_t len) {
+ expected_ = len;
+ }
+ inline bool CheckLength() const {
+ return expected_ == produced_;
+ }
+ inline bool Append(const char* ip, size_t len) {
+ produced_ += len;
+ return produced_ <= expected_;
+ }
+ inline bool TryFastAppend(const char* ip, size_t available, size_t length) {
+ return false;
+ }
+ inline bool AppendFromSelf(size_t offset, size_t len) {
+ // See SnappyArrayWriter::AppendFromSelf for an explanation of
+ // the "offset - 1u" trick.
+ if (produced_ <= offset - 1u) return false;
+ produced_ += len;
+ return produced_ <= expected_;
+ }
+ inline void Flush() {}
+};
+
+bool IsValidCompressedBuffer(const char* compressed, size_t n) {
+ ByteArraySource reader(compressed, n);
+ SnappyDecompressionValidator writer;
+ return InternalUncompress(&reader, &writer);
+}
+
+bool IsValidCompressed(Source* compressed) {
+ SnappyDecompressionValidator writer;
+ return InternalUncompress(compressed, &writer);
+}
+
+void RawCompress(const char* input,
+ size_t input_length,
+ char* compressed,
+ size_t* compressed_length) {
+ ByteArraySource reader(input, input_length);
+ UncheckedByteArraySink writer(compressed);
+ Compress(&reader, &writer);
+
+ // Compute how many bytes were added
+ *compressed_length = (writer.CurrentDestination() - compressed);
+}
+
+size_t Compress(const char* input, size_t input_length,
+ std::string* compressed) {
+ // Pre-grow the buffer to the max length of the compressed output
+ STLStringResizeUninitialized(compressed, MaxCompressedLength(input_length));
+
+ size_t compressed_length;
+ RawCompress(input, input_length, string_as_array(compressed),
+ &compressed_length);
+ compressed->resize(compressed_length);
+ return compressed_length;
+}
+
+// -----------------------------------------------------------------------
+// Sink interface
+// -----------------------------------------------------------------------
+
+// A type that decompresses into a Sink. The template parameter
+// Allocator must export one method "char* Allocate(int size);", which
+// allocates a buffer of "size" and appends that to the destination.
+template
+class SnappyScatteredWriter {
+ Allocator allocator_;
+
+ // We need random access into the data generated so far. Therefore
+ // we keep track of all of the generated data as an array of blocks.
+ // All of the blocks except the last have length kBlockSize.
+ std::vector blocks_;
+ size_t expected_;
+
+ // Total size of all fully generated blocks so far
+ size_t full_size_;
+
+ // Pointer into current output block
+ char* op_base_; // Base of output block
+ char* op_ptr_; // Pointer to next unfilled byte in block
+ char* op_limit_; // Pointer just past block
+
+ inline size_t Size() const {
+ return full_size_ + (op_ptr_ - op_base_);
+ }
+
+ bool SlowAppend(const char* ip, size_t len);
+ bool SlowAppendFromSelf(size_t offset, size_t len);
+
+ public:
+ inline explicit SnappyScatteredWriter(const Allocator& allocator)
+ : allocator_(allocator),
+ full_size_(0),
+ op_base_(NULL),
+ op_ptr_(NULL),
+ op_limit_(NULL) {
+ }
+
+ inline void SetExpectedLength(size_t len) {
+ assert(blocks_.empty());
+ expected_ = len;
+ }
+
+ inline bool CheckLength() const {
+ return Size() == expected_;
+ }
+
+ // Return the number of bytes actually uncompressed so far
+ inline size_t Produced() const {
+ return Size();
+ }
+
+ inline bool Append(const char* ip, size_t len) {
+ size_t avail = op_limit_ - op_ptr_;
+ if (len <= avail) {
+ // Fast path
+ memcpy(op_ptr_, ip, len);
+ op_ptr_ += len;
+ return true;
+ } else {
+ return SlowAppend(ip, len);
+ }
+ }
+
+ inline bool TryFastAppend(const char* ip, size_t available, size_t length) {
+ char* op = op_ptr_;
+ const int space_left = op_limit_ - op;
+ if (length <= 16 && available >= 16 + kMaximumTagLength &&
+ space_left >= 16) {
+ // Fast path, used for the majority (about 95%) of invocations.
+ UnalignedCopy128(ip, op);
+ op_ptr_ = op + length;
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ inline bool AppendFromSelf(size_t offset, size_t len) {
+ char* const op_end = op_ptr_ + len;
+ // See SnappyArrayWriter::AppendFromSelf for an explanation of
+ // the "offset - 1u" trick.
+ if (SNAPPY_PREDICT_TRUE(offset - 1u < op_ptr_ - op_base_ &&
+ op_end <= op_limit_)) {
+ // Fast path: src and dst in current block.
+ op_ptr_ = IncrementalCopy(op_ptr_ - offset, op_ptr_, op_end, op_limit_);
+ return true;
+ }
+ return SlowAppendFromSelf(offset, len);
+ }
+
+ // Called at the end of the decompress. We ask the allocator
+ // write all blocks to the sink.
+ inline void Flush() { allocator_.Flush(Produced()); }
+};
+
+template
+bool SnappyScatteredWriter::SlowAppend(const char* ip, size_t len) {
+ size_t avail = op_limit_ - op_ptr_;
+ while (len > avail) {
+ // Completely fill this block
+ memcpy(op_ptr_, ip, avail);
+ op_ptr_ += avail;
+ assert(op_limit_ - op_ptr_ == 0);
+ full_size_ += (op_ptr_ - op_base_);
+ len -= avail;
+ ip += avail;
+
+ // Bounds check
+ if (full_size_ + len > expected_) {
+ return false;
+ }
+
+ // Make new block
+ size_t bsize = std::min(kBlockSize, expected_ - full_size_);
+ op_base_ = allocator_.Allocate(bsize);
+ op_ptr_ = op_base_;
+ op_limit_ = op_base_ + bsize;
+ blocks_.push_back(op_base_);
+ avail = bsize;
+ }
+
+ memcpy(op_ptr_, ip, len);
+ op_ptr_ += len;
+ return true;
+}
+
+template
+bool SnappyScatteredWriter::SlowAppendFromSelf(size_t offset,
+ size_t len) {
+ // Overflow check
+ // See SnappyArrayWriter::AppendFromSelf for an explanation of
+ // the "offset - 1u" trick.
+ const size_t cur = Size();
+ if (offset - 1u >= cur) return false;
+ if (expected_ - cur < len) return false;
+
+ // Currently we shouldn't ever hit this path because Compress() chops the
+ // input into blocks and does not create cross-block copies. However, it is
+ // nice if we do not rely on that, since we can get better compression if we
+ // allow cross-block copies and thus might want to change the compressor in
+ // the future.
+ size_t src = cur - offset;
+ while (len-- > 0) {
+ char c = blocks_[src >> kBlockLog][src & (kBlockSize-1)];
+ Append(&c, 1);
+ src++;
+ }
+ return true;
+}
+
+class SnappySinkAllocator {
+ public:
+ explicit SnappySinkAllocator(Sink* dest): dest_(dest) {}
+ ~SnappySinkAllocator() {}
+
+ char* Allocate(int size) {
+ Datablock block(new char[size], size);
+ blocks_.push_back(block);
+ return block.data;
+ }
+
+ // We flush only at the end, because the writer wants
+ // random access to the blocks and once we hand the
+ // block over to the sink, we can't access it anymore.
+ // Also we don't write more than has been actually written
+ // to the blocks.
+ void Flush(size_t size) {
+ size_t size_written = 0;
+ size_t block_size;
+ for (int i = 0; i < blocks_.size(); ++i) {
+ block_size = std::min(blocks_[i].size, size - size_written);
+ dest_->AppendAndTakeOwnership(blocks_[i].data, block_size,
+ &SnappySinkAllocator::Deleter, NULL);
+ size_written += block_size;
+ }
+ blocks_.clear();
+ }
+
+ private:
+ struct Datablock {
+ char* data;
+ size_t size;
+ Datablock(char* p, size_t s) : data(p), size(s) {}
+ };
+
+ static void Deleter(void* arg, const char* bytes, size_t size) {
+ delete[] bytes;
+ }
+
+ Sink* dest_;
+ std::vector blocks_;
+
+ // Note: copying this object is allowed
+};
+
+size_t UncompressAsMuchAsPossible(Source* compressed, Sink* uncompressed) {
+ SnappySinkAllocator allocator(uncompressed);
+ SnappyScatteredWriter writer(allocator);
+ InternalUncompress(compressed, &writer);
+ return writer.Produced();
+}
+
+bool Uncompress(Source* compressed, Sink* uncompressed) {
+ // Read the uncompressed length from the front of the compressed input
+ SnappyDecompressor decompressor(compressed);
+ uint32 uncompressed_len = 0;
+ if (!decompressor.ReadUncompressedLength(&uncompressed_len)) {
+ return false;
+ }
+
+ char c;
+ size_t allocated_size;
+ char* buf = uncompressed->GetAppendBufferVariable(
+ 1, uncompressed_len, &c, 1, &allocated_size);
+
+ const size_t compressed_len = compressed->Available();
+ // If we can get a flat buffer, then use it, otherwise do block by block
+ // uncompression
+ if (allocated_size >= uncompressed_len) {
+ SnappyArrayWriter writer(buf);
+ bool result = InternalUncompressAllTags(&decompressor, &writer,
+ compressed_len, uncompressed_len);
+ uncompressed->Append(buf, writer.Produced());
+ return result;
+ } else {
+ SnappySinkAllocator allocator(uncompressed);
+ SnappyScatteredWriter writer(allocator);
+ return InternalUncompressAllTags(&decompressor, &writer, compressed_len,
+ uncompressed_len);
+ }
+}
+
+} // namespace snappy
diff --git a/target/snappy-1.1.10/snappy.h b/target/snappy-1.1.10/snappy.h
new file mode 100644
index 00000000..e9805bfb
--- /dev/null
+++ b/target/snappy-1.1.10/snappy.h
@@ -0,0 +1,207 @@
+// Copyright 2005 and onwards Google Inc.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+//
+// A light-weight compression algorithm. It is designed for speed of
+// compression and decompression, rather than for the utmost in space
+// savings.
+//
+// For getting better compression ratios when you are compressing data
+// with long repeated sequences or compressing data that is similar to
+// other data, while still compressing fast, you might look at first
+// using BMDiff and then compressing the output of BMDiff with
+// Snappy.
+
+#ifndef THIRD_PARTY_SNAPPY_SNAPPY_H__
+#define THIRD_PARTY_SNAPPY_SNAPPY_H__
+
+#include
+#include
+
+#include "snappy-stubs-public.h"
+
+namespace snappy {
+ class Source;
+ class Sink;
+
+ // ------------------------------------------------------------------------
+ // Generic compression/decompression routines.
+ // ------------------------------------------------------------------------
+
+ // Compress the bytes read from "*source" and append to "*sink". Return the
+ // number of bytes written.
+ size_t Compress(Source* source, Sink* sink);
+
+ // Find the uncompressed length of the given stream, as given by the header.
+ // Note that the true length could deviate from this; the stream could e.g.
+ // be truncated.
+ //
+ // Also note that this leaves "*source" in a state that is unsuitable for
+ // further operations, such as RawUncompress(). You will need to rewind
+ // or recreate the source yourself before attempting any further calls.
+ bool GetUncompressedLength(Source* source, uint32* result);
+
+ // ------------------------------------------------------------------------
+ // Higher-level string based routines (should be sufficient for most users)
+ // ------------------------------------------------------------------------
+
+ // Sets "*compressed" to the compressed version of "input[0,input_length-1]".
+ // Original contents of *compressed are lost.
+ //
+ // REQUIRES: "input[]" is not an alias of "*compressed".
+ size_t Compress(const char* input, size_t input_length,
+ std::string* compressed);
+
+ // Decompresses "compressed[0,compressed_length-1]" to "*uncompressed".
+ // Original contents of "*uncompressed" are lost.
+ //
+ // REQUIRES: "compressed[]" is not an alias of "*uncompressed".
+ //
+ // returns false if the message is corrupted and could not be decompressed
+ bool Uncompress(const char* compressed, size_t compressed_length,
+ std::string* uncompressed);
+
+ // Decompresses "compressed" to "*uncompressed".
+ //
+ // returns false if the message is corrupted and could not be decompressed
+ bool Uncompress(Source* compressed, Sink* uncompressed);
+
+ // This routine uncompresses as much of the "compressed" as possible
+ // into sink. It returns the number of valid bytes added to sink
+ // (extra invalid bytes may have been added due to errors; the caller
+ // should ignore those). The emitted data typically has length
+ // GetUncompressedLength(), but may be shorter if an error is
+ // encountered.
+ size_t UncompressAsMuchAsPossible(Source* compressed, Sink* uncompressed);
+
+ // ------------------------------------------------------------------------
+ // Lower-level character array based routines. May be useful for
+ // efficiency reasons in certain circumstances.
+ // ------------------------------------------------------------------------
+
+ // REQUIRES: "compressed" must point to an area of memory that is at
+ // least "MaxCompressedLength(input_length)" bytes in length.
+ //
+ // Takes the data stored in "input[0..input_length]" and stores
+ // it in the array pointed to by "compressed".
+ //
+ // "*compressed_length" is set to the length of the compressed output.
+ //
+ // Example:
+ // char* output = new char[snappy::MaxCompressedLength(input_length)];
+ // size_t output_length;
+ // RawCompress(input, input_length, output, &output_length);
+ // ... Process(output, output_length) ...
+ // delete [] output;
+ void RawCompress(const char* input,
+ size_t input_length,
+ char* compressed,
+ size_t* compressed_length);
+
+ // Given data in "compressed[0..compressed_length-1]" generated by
+ // calling the Snappy::Compress routine, this routine
+ // stores the uncompressed data to
+ // uncompressed[0..GetUncompressedLength(compressed)-1]
+ // returns false if the message is corrupted and could not be decrypted
+ bool RawUncompress(const char* compressed, size_t compressed_length,
+ char* uncompressed);
+
+ // Given data from the byte source 'compressed' generated by calling
+ // the Snappy::Compress routine, this routine stores the uncompressed
+ // data to
+ // uncompressed[0..GetUncompressedLength(compressed,compressed_length)-1]
+ // returns false if the message is corrupted and could not be decrypted
+ bool RawUncompress(Source* compressed, char* uncompressed);
+
+ // Given data in "compressed[0..compressed_length-1]" generated by
+ // calling the Snappy::Compress routine, this routine
+ // stores the uncompressed data to the iovec "iov". The number of physical
+ // buffers in "iov" is given by iov_cnt and their cumulative size
+ // must be at least GetUncompressedLength(compressed). The individual buffers
+ // in "iov" must not overlap with each other.
+ //
+ // returns false if the message is corrupted and could not be decrypted
+ bool RawUncompressToIOVec(const char* compressed, size_t compressed_length,
+ const struct iovec* iov, size_t iov_cnt);
+
+ // Given data from the byte source 'compressed' generated by calling
+ // the Snappy::Compress routine, this routine stores the uncompressed
+ // data to the iovec "iov". The number of physical
+ // buffers in "iov" is given by iov_cnt and their cumulative size
+ // must be at least GetUncompressedLength(compressed). The individual buffers
+ // in "iov" must not overlap with each other.
+ //
+ // returns false if the message is corrupted and could not be decrypted
+ bool RawUncompressToIOVec(Source* compressed, const struct iovec* iov,
+ size_t iov_cnt);
+
+ // Returns the maximal size of the compressed representation of
+ // input data that is "source_bytes" bytes in length;
+ size_t MaxCompressedLength(size_t source_bytes);
+
+ // REQUIRES: "compressed[]" was produced by RawCompress() or Compress()
+ // Returns true and stores the length of the uncompressed data in
+ // *result normally. Returns false on parsing error.
+ // This operation takes O(1) time.
+ bool GetUncompressedLength(const char* compressed, size_t compressed_length,
+ size_t* result);
+
+ // Returns true iff the contents of "compressed[]" can be uncompressed
+ // successfully. Does not return the uncompressed data. Takes
+ // time proportional to compressed_length, but is usually at least
+ // a factor of four faster than actual decompression.
+ bool IsValidCompressedBuffer(const char* compressed,
+ size_t compressed_length);
+
+ // Returns true iff the contents of "compressed" can be uncompressed
+ // successfully. Does not return the uncompressed data. Takes
+ // time proportional to *compressed length, but is usually at least
+ // a factor of four faster than actual decompression.
+ // On success, consumes all of *compressed. On failure, consumes an
+ // unspecified prefix of *compressed.
+ bool IsValidCompressed(Source* compressed);
+
+ // The size of a compression block. Note that many parts of the compression
+ // code assumes that kBlockSize <= 65536; in particular, the hash table
+ // can only store 16-bit offsets, and EmitCopy() also assumes the offset
+ // is 65535 bytes or less. Note also that if you change this, it will
+ // affect the framing format (see framing_format.txt).
+ //
+ // Note that there might be older data around that is compressed with larger
+ // block sizes, so the decompression code should not rely on the
+ // non-existence of long backreferences.
+ static constexpr int kBlockLog = 16;
+ static constexpr size_t kBlockSize = 1 << kBlockLog;
+
+ static constexpr int kMinHashTableBits = 8;
+ static constexpr size_t kMinHashTableSize = 1 << kMinHashTableBits;
+
+ static constexpr int kMaxHashTableBits = 14;
+ static constexpr size_t kMaxHashTableSize = 1 << kMaxHashTableBits;
+} // end namespace snappy
+
+#endif // THIRD_PARTY_SNAPPY_SNAPPY_H__
diff --git a/target/snappy-1.1.10/snappy_compress_fuzzer.cc b/target/snappy-1.1.10/snappy_compress_fuzzer.cc
new file mode 100644
index 00000000..1d0119e1
--- /dev/null
+++ b/target/snappy-1.1.10/snappy_compress_fuzzer.cc
@@ -0,0 +1,59 @@
+// Copyright 2019 Google Inc. All Rights Reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+//
+// libFuzzer harness for fuzzing snappy compression code.
+
+#include
+#include
+#include
+#include
+
+#include "snappy.h"
+
+// Entry point for LibFuzzer.
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+ std::string input(reinterpret_cast(data), size);
+
+ std::string compressed;
+ size_t compressed_size =
+ snappy::Compress(input.data(), input.size(), &compressed);
+
+ (void)compressed_size; // Variable only used in debug builds.
+ assert(compressed_size == compressed.size());
+ assert(compressed.size() <= snappy::MaxCompressedLength(input.size()));
+ assert(snappy::IsValidCompressedBuffer(compressed.data(), compressed.size()));
+
+ std::string uncompressed_after_compress;
+ bool uncompress_succeeded = snappy::Uncompress(
+ compressed.data(), compressed.size(), &uncompressed_after_compress);
+
+ (void)uncompress_succeeded; // Variable only used in debug builds.
+ assert(uncompress_succeeded);
+ assert(input == uncompressed_after_compress);
+ return 0;
+}
diff --git a/target/snappy-1.1.10/snappy_uncompress_fuzzer.cc b/target/snappy-1.1.10/snappy_uncompress_fuzzer.cc
new file mode 100644
index 00000000..8071c00e
--- /dev/null
+++ b/target/snappy-1.1.10/snappy_uncompress_fuzzer.cc
@@ -0,0 +1,57 @@
+// Copyright 2019 Google Inc. All Rights Reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+//
+// libFuzzer harness for fuzzing snappy's decompression code.
+
+#include
+#include
+#include
+#include
+
+#include "snappy.h"
+
+// Entry point for LibFuzzer.
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+ std::string input(reinterpret_cast(data), size);
+
+ // Avoid self-crafted decompression bombs.
+ size_t uncompressed_size;
+ constexpr size_t kMaxUncompressedSize = 1 << 20;
+ bool get_uncompressed_length_succeeded = snappy::GetUncompressedLength(
+ input.data(), input.size(), &uncompressed_size);
+ if (!get_uncompressed_length_succeeded ||
+ (uncompressed_size > kMaxUncompressedSize)) {
+ return 0;
+ }
+
+ std::string uncompressed;
+ // The return value of snappy::Uncompress() is ignored because decompression
+ // will fail on invalid inputs.
+ snappy::Uncompress(input.data(), input.size(), &uncompressed);
+ return 0;
+}
diff --git a/target/snappy-1.1.10/snappy_unittest.cc b/target/snappy-1.1.10/snappy_unittest.cc
new file mode 100644
index 00000000..37159c32
--- /dev/null
+++ b/target/snappy-1.1.10/snappy_unittest.cc
@@ -0,0 +1,1506 @@
+// Copyright 2005 and onwards Google Inc.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 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.
+
+#include
+#include
+
+#include
+#include
+#include
+#include
+#include
+
+#include "snappy.h"
+#include "snappy-internal.h"
+#include "snappy-test.h"
+#include "snappy-sinksource.h"
+
+DEFINE_int32(start_len, -1,
+ "Starting prefix size for testing (-1: just full file contents)");
+DEFINE_int32(end_len, -1,
+ "Starting prefix size for testing (-1: just full file contents)");
+DEFINE_int32(bytes, 10485760,
+ "How many bytes to compress/uncompress per file for timing");
+
+DEFINE_bool(zlib, false,
+ "Run zlib compression (http://www.zlib.net)");
+DEFINE_bool(lzo, false,
+ "Run LZO compression (http://www.oberhumer.com/opensource/lzo/)");
+DEFINE_bool(snappy, true, "Run snappy compression");
+
+DEFINE_bool(write_compressed, false,
+ "Write compressed versions of each file to .comp");
+DEFINE_bool(write_uncompressed, false,
+ "Write uncompressed versions of each file to .uncomp");
+
+DEFINE_bool(snappy_dump_decompression_table, false,
+ "If true, we print the decompression table during tests.");
+
+namespace snappy {
+
+#if defined(HAVE_FUNC_MMAP) && defined(HAVE_FUNC_SYSCONF)
+
+// To test against code that reads beyond its input, this class copies a
+// string to a newly allocated group of pages, the last of which
+// is made unreadable via mprotect. Note that we need to allocate the
+// memory with mmap(), as POSIX allows mprotect() only on memory allocated
+// with mmap(), and some malloc/posix_memalign implementations expect to
+// be able to read previously allocated memory while doing heap allocations.
+class DataEndingAtUnreadablePage {
+ public:
+ explicit DataEndingAtUnreadablePage(const std::string& s) {
+ const size_t page_size = sysconf(_SC_PAGESIZE);
+ const size_t size = s.size();
+ // Round up space for string to a multiple of page_size.
+ size_t space_for_string = (size + page_size - 1) & ~(page_size - 1);
+ alloc_size_ = space_for_string + page_size;
+ mem_ = mmap(NULL, alloc_size_,
+ PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
+ CHECK_NE(MAP_FAILED, mem_);
+ protected_page_ = reinterpret_cast(mem_) + space_for_string;
+ char* dst = protected_page_ - size;
+ memcpy(dst, s.data(), size);
+ data_ = dst;
+ size_ = size;
+ // Make guard page unreadable.
+ CHECK_EQ(0, mprotect(protected_page_, page_size, PROT_NONE));
+ }
+
+ ~DataEndingAtUnreadablePage() {
+ const size_t page_size = sysconf(_SC_PAGESIZE);
+ // Undo the mprotect.
+ CHECK_EQ(0, mprotect(protected_page_, page_size, PROT_READ|PROT_WRITE));
+ CHECK_EQ(0, munmap(mem_, alloc_size_));
+ }
+
+ const char* data() const { return data_; }
+ size_t size() const { return size_; }
+
+ private:
+ size_t alloc_size_;
+ void* mem_;
+ char* protected_page_;
+ const char* data_;
+ size_t size_;
+};
+
+#else // defined(HAVE_FUNC_MMAP) && defined(HAVE_FUNC_SYSCONF)
+
+// Fallback for systems without mmap.
+using DataEndingAtUnreadablePage = std::string;
+
+#endif
+
+enum CompressorType {
+ ZLIB, LZO, SNAPPY
+};
+
+const char* names[] = {
+ "ZLIB", "LZO", "SNAPPY"
+};
+
+static size_t MinimumRequiredOutputSpace(size_t input_size,
+ CompressorType comp) {
+ switch (comp) {
+#ifdef ZLIB_VERSION
+ case ZLIB:
+ return ZLib::MinCompressbufSize(input_size);
+#endif // ZLIB_VERSION
+
+#ifdef LZO_VERSION
+ case LZO:
+ return input_size + input_size/64 + 16 + 3;
+#endif // LZO_VERSION
+
+ case SNAPPY:
+ return snappy::MaxCompressedLength(input_size);
+
+ default:
+ LOG(FATAL) << "Unknown compression type number " << comp;
+ return 0;
+ }
+}
+
+// Returns true if we successfully compressed, false otherwise.
+//
+// If compressed_is_preallocated is set, do not resize the compressed buffer.
+// This is typically what you want for a benchmark, in order to not spend
+// time in the memory allocator. If you do set this flag, however,
+// "compressed" must be preinitialized to at least MinCompressbufSize(comp)
+// number of bytes, and may contain junk bytes at the end after return.
+static bool Compress(const char* input, size_t input_size, CompressorType comp,
+ std::string* compressed, bool compressed_is_preallocated) {
+ if (!compressed_is_preallocated) {
+ compressed->resize(MinimumRequiredOutputSpace(input_size, comp));
+ }
+
+ switch (comp) {
+#ifdef ZLIB_VERSION
+ case ZLIB: {
+ ZLib zlib;
+ uLongf destlen = compressed->size();
+ int ret = zlib.Compress(
+ reinterpret_cast(string_as_array(compressed)),
+ &destlen,
+ reinterpret_cast(input),
+ input_size);
+ CHECK_EQ(Z_OK, ret);
+ if (!compressed_is_preallocated) {
+ compressed->resize(destlen);
+ }
+ return true;
+ }
+#endif // ZLIB_VERSION
+
+#ifdef LZO_VERSION
+ case LZO: {
+ unsigned char* mem = new unsigned char[LZO1X_1_15_MEM_COMPRESS];
+ lzo_uint destlen;
+ int ret = lzo1x_1_15_compress(
+ reinterpret_cast(input),
+ input_size,
+ reinterpret_cast(string_as_array(compressed)),
+ &destlen,
+ mem);
+ CHECK_EQ(LZO_E_OK, ret);
+ delete[] mem;
+ if (!compressed_is_preallocated) {
+ compressed->resize(destlen);
+ }
+ break;
+ }
+#endif // LZO_VERSION
+
+ case SNAPPY: {
+ size_t destlen;
+ snappy::RawCompress(input, input_size,
+ string_as_array(compressed),
+ &destlen);
+ CHECK_LE(destlen, snappy::MaxCompressedLength(input_size));
+ if (!compressed_is_preallocated) {
+ compressed->resize(destlen);
+ }
+ break;
+ }
+
+ default: {
+ return false; // the asked-for library wasn't compiled in
+ }
+ }
+ return true;
+}
+
+static bool Uncompress(const std::string& compressed, CompressorType comp,
+ int size, std::string* output) {
+ switch (comp) {
+#ifdef ZLIB_VERSION
+ case ZLIB: {
+ output->resize(size);
+ ZLib zlib;
+ uLongf destlen = output->size();
+ int ret = zlib.Uncompress(
+ reinterpret_cast(string_as_array(output)),
+ &destlen,
+ reinterpret_cast(compressed.data()),
+ compressed.size());
+ CHECK_EQ(Z_OK, ret);
+ CHECK_EQ(static_cast(size), destlen);
+ break;
+ }
+#endif // ZLIB_VERSION
+
+#ifdef LZO_VERSION
+ case LZO: {
+ output->resize(size);
+ lzo_uint destlen;
+ int ret = lzo1x_decompress(
+ reinterpret_cast(compressed.data()),
+ compressed.size(),
+ reinterpret_cast(string_as_array(output)),
+ &destlen,
+ NULL);
+ CHECK_EQ(LZO_E_OK, ret);
+ CHECK_EQ(static_cast(size), destlen);
+ break;
+ }
+#endif // LZO_VERSION
+
+ case SNAPPY: {
+ snappy::RawUncompress(compressed.data(), compressed.size(),
+ string_as_array(output));
+ break;
+ }
+
+ default: {
+ return false; // the asked-for library wasn't compiled in
+ }
+ }
+ return true;
+}
+
+static void Measure(const char* data,
+ size_t length,
+ CompressorType comp,
+ int repeats,
+ int block_size) {
+ // Run tests a few time and pick median running times
+ static const int kRuns = 5;
+ double ctime[kRuns];
+ double utime[kRuns];
+ int compressed_size = 0;
+
+ {
+ // Chop the input into blocks
+ int num_blocks = (length + block_size - 1) / block_size;
+ std::vector input(num_blocks);
+ std::vector input_length(num_blocks);
+ std::vector