Commit 10f466bb authored by Nikita Malyavin's avatar Nikita Malyavin

add xxh

parent 95d327aa
......@@ -162,8 +162,12 @@ IF(HAVE_MLOCK)
SET(MYSYS_SOURCES ${MYSYS_SOURCES} my_lockmem.c)
ENDIF()
set(XXHASH_BUILD_ENABLE_INLINE_API ON)
ADD_SUBDIRECTORY(../xxhash/cmake_unofficial ../xxhash/build)
ADD_CONVENIENCE_LIBRARY(mysys ${MYSYS_SOURCES})
MAYBE_DISABLE_IPO(mysys)
TARGET_LINK_LIBRARIES(mysys xxHash::xxhash)
TARGET_LINK_LIBRARIES(mysys dbug strings ${ZLIB_LIBRARY}
${LIBNSL} ${LIBM} ${LIBRT} ${CMAKE_DL_LIBS} ${LIBSOCKET} ${LIBEXECINFO})
DTRACE_INSTRUMENT(mysys)
......
......@@ -22,6 +22,7 @@
#include <m_string.h>
#include <m_ctype.h>
#include "hash.h"
#include "xxhash.h"
#define NO_RECORD ~((my_hash_value_type) 0)
#define LOWFIND 1
......@@ -45,8 +46,12 @@ my_hash_value_type my_hash_sort(CHARSET_INFO *cs, const uchar *key,
size_t length)
{
ulong nr1= 1, nr2= 4;
my_ci_hash_sort(cs, (uchar*) key, length, &nr1, &nr2);
return (my_hash_value_type) nr1;
if (cs != &my_charset_bin)
{
my_ci_hash_sort(cs, (uchar*) key, length, &nr1, &nr2);
return (my_hash_value_type) nr1;
}
return (my_hash_value_type) XXH3_64bits(key, length);
}
/**
......
......@@ -325,8 +325,8 @@ static inline my_hash_value_type calc_hash(CHARSET_INFO *cs,
size_t keylen)
{
ulong nr1= 1, nr2= 4;
my_ci_hash_sort(cs, (uchar*) key, keylen, &nr1, &nr2);
return nr1;
// my_ci_hash_sort(cs, (uchar*) key, keylen, &nr1, &nr2);
return my_hash_sort(cs, key, keylen);
}
#define MAX_LOAD 1.0 /* average number of elements in a bucket */
......
language: c
# Dump CPU info before start
before_install:
- cat /proc/cpuinfo || echo /proc/cpuinfo is not present
matrix:
fast_finish: true
include:
- name: General linux x64 tests
arch: amd64
addons:
apt:
packages:
- g++-multilib
- gcc-multilib
- cppcheck
script:
- make -B test-all
- make clean
- CFLAGS="-Werror" MOREFLAGS="-Wno-sign-conversion" make dispatch # removing sign conversion warnings due to a bug in gcc-5's definition of some AVX512 intrinsics
- make clean
- CFLAGS="-O1 -mavx512f -Werror" make
- make clean
- CFLAGS="-Wall -Wextra -Werror" make DISPATCH=1
- make clean
- CFLAGS="-std=c90 -pedantic -Wno-long-long -Werror" make xxhsum # check C90 + long long compliance
- make c90test # strict c90, with no long long support; resulting in no XXH64_* symbol
- make noxxh3test # check library can be compiled with XXH_NO_XXH3, resulting in no XXH3_* symbol
- name: Check results consistency on x64
arch: amd64
script:
- CPPFLAGS=-DXXH_VECTOR=XXH_SCALAR make check # Scalar code path
- make clean
- CPPFLAGS=-DXXH_VECTOR=XXH_SSE2 make check # SSE2 code path
- make clean
- CPPFLAGS="-mavx2 -DXXH_VECTOR=XXH_AVX2" make check # AVX2 code path
- make clean
- CPPFLAGS="-mavx512f -DXXH_VECTOR=XXH_AVX512" make check # AVX512 code path
- make clean
- CPPFLAGS=-DXXH_REROLL=1 make check # reroll code path (#240)
- make -C tests/bench
- name: macOS General Test
os: osx
compiler: clang
script:
- CFLAGS="-Werror" make # test library build
- make clean
- make test MOREFLAGS='-Werror' | tee # test scenario where `stdout` is not the console
- name: ARM compilation and consistency checks (Qemu)
dist: xenial
arch: amd64
addons:
apt:
packages:
- qemu-system-arm
- qemu-user-static
- gcc-arm-linux-gnueabi
- libc6-dev-armel-cross
script:
# arm (32-bit)
- CC=arm-linux-gnueabi-gcc CPPFLAGS=-DXXH_VECTOR=XXH_SCALAR LDFLAGS=-static RUN_ENV=qemu-arm-static make check # Scalar code path
- make clean
# NEON (32-bit)
- CC=arm-linux-gnueabi-gcc CPPFLAGS=-DXXH_VECTOR=XXH_NEON CFLAGS="-O3 -march=armv7-a -fPIC -mfloat-abi=softfp -mfpu=neon-vfpv4" LDFLAGS=-static RUN_ENV=qemu-arm-static make check # NEON code path
- name: aarch64 compilation and consistency checks
dist: xenial
arch: arm64
script:
# aarch64
- CPPFLAGS=-DXXH_VECTOR=XXH_SCALAR make check # Scalar code path
# NEON (64-bit)
- make clean
- CPPFLAGS=-DXXH_VECTOR=XXH_NEON make check # NEON code path
# clang
- make clean
- CC=clang CPPFLAGS=-DXXH_VECTOR=XXH_SCALAR make check # Scalar code path
# clang + NEON
- make clean
- CC=clang CPPFLAGS=-DXXH_VECTOR=XXH_NEON make check # NEON code path
# We need Bionic here because the QEMU versions shipped in the older repos
# do not support POWER8 emulation, and compiling QEMU from source is a pain.
- name: PowerPC + PPC64 compilation and consistency checks (Qemu on Bionic)
dist: bionic
arch: amd64
addons:
apt:
packages:
- qemu-system-ppc
- qemu-user-static
- gcc-powerpc-linux-gnu
- gcc-powerpc64-linux-gnu
- libc6-dev-powerpc-cross
- libc6-dev-ppc64-cross
script:
- CC=powerpc-linux-gnu-gcc RUN_ENV=qemu-ppc-static LDFLAGS=-static make check # Scalar code path
- make clean
- CC=powerpc64-linux-gnu-gcc RUN_ENV=qemu-ppc64-static CPPFLAGS=-DXXH_VECTOR=XXH_SCALAR CFLAGS="-O3" LDFLAGS="-static -m64" make check # Scalar code path
# VSX code
- make clean
- CC=powerpc64-linux-gnu-gcc RUN_ENV="qemu-ppc64-static -cpu power8" CPPFLAGS=-DXXH_VECTOR=XXH_VSX CFLAGS="-O3 -maltivec -mvsx -mcpu=power8 -mpower8-vector" LDFLAGS="-static -m64" make check # VSX code path
# altivec.h redefinition issue #426
- make clean
- CC=powerpc64-linux-gnu-gcc CPPFLAGS=-DXXH_VECTOR=XXH_VSX CFLAGS="-maltivec -mvsx -mcpu=power8 -mpower8-vector" make -C tests test_ppc_redefine
- name: PPC64LE compilation and consistency checks
dist: xenial
arch: ppc64le
script:
# Scalar (universal) code path
- CPPFLAGS=-DXXH_VECTOR=XXH_SCALAR LDFLAGS=-static make check
# VSX code path (64-bit)
- make clean
- CPPFLAGS=-DXXH_VECTOR=XXH_VSX CFLAGS="-O3 -maltivec -mvsx -mpower8-vector -mcpu=power8" LDFLAGS="-static" make check
# altivec.h redefinition issue #426
- make clean
- CPPFLAGS=-DXXH_VECTOR=XXH_VSX CFLAGS="-maltivec -mvsx -mcpu=power8 -mpower8-vector" make -C tests test_ppc_redefine
- name: IBM s390x compilation and consistency checks
dist: bionic
arch: s390x
script:
# Scalar (universal) code path
- CPPFLAGS=-DXXH_VECTOR=XXH_SCALAR LDFLAGS=-static make check
# s390x code path (64-bit)
- make clean
- CPPFLAGS=-DXXH_VECTOR=XXH_VSX CFLAGS="-O3 -march=arch11 -mzvector" LDFLAGS="-static" make check
- name: cmake build test
script:
- cd cmake_unofficial
- mkdir build
- cd build
- cmake ..
- CFLAGS=-Werror make
v0.8.1
- perf : much improved performance for XXH3 streaming variants, notably on gcc and msvc
- perf : improved XXH64 speed and latency on small inputs
- perf : small XXH32 speed and latency improvement on small inputs of random size
- perf : minor stack usage improvement for XXH32 and XXH64
- api : new experimental variants XXH3_*_withSecretandSeed()
- api : update XXH3_generateSecret(), can no generate secret of any size (>= XXH3_SECRET_SIZE_MIN)
- cli : xxhsum can now generate and check XXH3 checksums, using command `-H3`
- build: can build xxhash without XXH3, with new build macro XXH_NO_XXH3
- build: fix xxh_x86dispatch build with MSVC, by @apankrat
- build: XXH_INLINE_ALL can always be used safely, even after XXH_NAMESPACE or a previous XXH_INLINE_ALL
- build: improved PPC64LE vector support, by @mpe
- install: fix pkgconfig, by @ellert
- install: compatibility with Haiku, by @Begasus
- doc : code comments made compatible with doxygen, by @easyaspi314
- misc : XXH_ACCEPT_NULL_INPUT_POINTER is no longer necessary, all functions can accept NULL input pointers, as long as size == 0
- misc : complete refactor of CI tests on Github Actions, offering much larger coverage, by @t-mat
- misc : xxhsum code base split into multiple specialized units, within directory cli/, by @easyaspi314
v0.8.0
- api : stabilize XXH3
- cli : xxhsum can parse BSD-style --check lines, by @WayneD
- cli : `xxhsum -` accepts console input, requested by @jaki
- cli : xxhsum accepts -- separator, by @jaki
- cli : fix : print correct default algo for symlinked helpers, by @martinetd
- install: improved pkgconfig script, allowing custom install locations, requested by @ellert
v0.7.4
- perf: automatic vector detection and selection at runtime (`xxh_x86dispatch.h`), initiated by @easyaspi314
- perf: added AVX512 support, by @gzm55
- api : new: secret generator `XXH_generateSecret()`, suggested by @koraa
- api : fix: XXH3_state_t is movable, identified by @koraa
- api : fix: state is correctly aligned in AVX mode (unlike `malloc()`), by @easyaspi314
- api : fix: streaming generated wrong values in some combination of random ingestion lengths, reported by @WayneD
- cli : fix unicode print on Windows, by @easyaspi314
- cli : can `-c` check file generated by sfv
- build: `make DISPATCH=1` generates `xxhsum` and `libxxhash` with runtime vector detection (x86/x64 only)
- install: cygwin installation support
- doc : Cryptol specification of XXH32 and XXH64, by @weaversa
v0.7.3
- perf: improved speed for large inputs (~+20%)
- perf: improved latency for small inputs (~10%)
- perf: s390x Vectorial code, by @easyaspi314
- cli: improved support for Unicode filenames on Windows, thanks to @easyaspi314 and @t-mat
- api: `xxhash.h` can now be included in any order, with and without `XXH_STATIC_LINKING_ONLY` and `XXH_INLINE_ALL`
- build: xxHash's implementation transferred into `xxhash.h`. No more need to have `xxhash.c` in the `/include` directory for `XXH_INLINE_ALL` to work
- install: created pkg-config file, by @bket
- install: VCpkg installation instructions, by @LilyWangL
- doc: Highly improved code documentation, by @easyaspi314
- misc: New test tool in `/tests/collisions`: brute force collision tester for 64-bit hashes
v0.7.2
- Fixed collision ratio of `XXH128` for some specific input lengths, reported by @svpv
- Improved `VSX` and `NEON` variants, by @easyaspi314
- Improved performance of scalar code path (`XXH_VECTOR=0`), by @easyaspi314
- `xxhsum`: can generate 128-bit hashes with the `-H2` option (note: for experimental purposes only! `XXH128` is not yet frozen)
- `xxhsum`: option `-q` removes status notifications
v0.7.1
- Secret first: the algorithm computation can be altered by providing a "secret", which is any blob of bytes, of size >= `XXH3_SECRET_SIZE_MIN`.
- `seed` is still available, and acts as a secret generator
- updated `ARM NEON` variant by @easyaspi314
- Streaming implementation is available
- Improve compatibility and performance with Visual Studio, with help from @aras-p
- Better integration when using `XXH_INLINE_ALL`: do not pollute host namespace, use its own macros, such as `XXH_ASSERT()`, `XXH_ALIGN`, etc.
- 128-bit variant provides helper functions for comparison of hashes.
- Better `clang` generation of `rotl` instruction, thanks to @easyaspi314
- `XXH_REROLL` build macro to reduce binary size, by @easyaspi314
- Improved `cmake` script, by @Mezozoysky
- Full benchmark program provided in `/tests/bench`
# Doxygen config for xxHash
DOXYFILE_ENCODING = UTF-8
PROJECT_NAME = "xxHash"
PROJECT_NUMBER = "0.8.1"
PROJECT_BRIEF = "Extremely fast non-cryptographic hash function"
OUTPUT_DIRECTORY = doxygen
OUTPUT_LANGUAGE = English
# We already separate the internal docs.
INTERNAL_DOCS = YES
# Consistency
SORT_MEMBER_DOCS = NO
BRIEF_MEMBER_DESC = YES
REPEAT_BRIEF = YES
# Warnings
QUIET = YES
# Until we document everything
WARN_IF_UNDOCUMENTED = NO
# TODO: Add the other files. It is just xxhash.h for now.
FILE_PATTERNS = xxhash.h xxh_x86dispatch.c
# Note: xxHash's source files are technically ASCII only.
INPUT_ENCODING = UTF-8
TAB_SIZE = 4
MARKDOWN_SUPPORT = YES
# xxHash is a C library
OPTIMIZE_OUTPUT_FOR_C = YES
# So we can document the internals
EXTRACT_STATIC = YES
# Document the macros
MACRO_EXPANSION = YES
EXPAND_ONLY_PREDEF = YES
# Predefine some macros to clean up the output.
PREDEFINED = "XXH_DOXYGEN=" \
"XXH_PUBLIC_API=" \
"XXH_FORCE_INLINE=static inline" \
"XXH_NO_INLINE=static" \
"XXH_RESTRICT=restrict" \
"XSUM_API=" \
"XXH_STATIC_LINKING_ONLY" \
"XXH_IMPLEMENTATION" \
"XXH_PUREF=[[gnu::pure]]" \
"XXH_CONSTF=[[gnu::const]]" \
"XXH_MALLOCF=[[gnu::malloc]]" \
"XXH_ALIGN(N)=alignas(N)" \
"XXH_ALIGN_MEMBER(align,type)=alignas(align) type"
# We want HTML docs
GENERATE_HTML = YES
HTML_OUTPUT = html
HTML_FILE_EXTENSION = .html
# Tweak the colors a bit
HTML_COLORSTYLE_HUE = 220
HTML_COLORSTYLE_GAMMA = 100
HTML_COLORSTYLE_SAT = 100
# We don't want LaTeX.
GENERATE_LATEX = NO
xxHash Library
Copyright (c) 2012-2021 Yann Collet
All rights reserved.
BSD 2-Clause License (https://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 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.
xxHash - Extremely fast hash algorithm
======================================
xxHash is an Extremely fast Hash algorithm, processing at RAM speed limits.
Code is highly portable, and produces hashes identical across all platforms (little / big endian).
The library includes the following algorithms :
- XXH32 : generates 32-bit hashes, using 32-bit arithmetic
- XXH64 : generates 64-bit hashes, using 64-bit arithmetic
- XXH3 (since `v0.8.0`): generates 64 or 128-bit hashes, using vectorized arithmetic.
The 128-bit variant is called XXH128.
All variants successfully complete the [SMHasher](https://code.google.com/p/smhasher/wiki/SMHasher) test suite
which evaluates the quality of hash functions (collision, dispersion and randomness).
Additional tests, which evaluate more thoroughly speed and collision properties of 64-bit hashes, [are also provided](https://github.com/Cyan4973/xxHash/tree/dev/tests).
|Branch |Status |
|------------|---------|
|release | [![Build Status](https://github.com/Cyan4973/xxHash/actions/workflows/ci.yml/badge.svg?branch=release)](https://github.com/Cyan4973/xxHash/actions?query=branch%3Arelease+) |
|dev | [![Build Status](https://github.com/Cyan4973/xxHash/actions/workflows/ci.yml/badge.svg?branch=dev)](https://github.com/Cyan4973/xxHash/actions?query=branch%3Adev+) |
Benchmarks
-------------------------
The benchmarked reference system uses an Intel i7-9700K cpu, and runs Ubuntu x64 20.04.
The [open source benchmark program] is compiled with `clang` v10.0 using `-O3` flag.
| Hash Name | Width | Bandwidth (GB/s) | Small Data Velocity | Quality | Comment |
| --------- | ----- | ---------------- | ----- | --- | --- |
| __XXH3__ (SSE2) | 64 | 31.5 GB/s | 133.1 | 10
| __XXH128__ (SSE2) | 128 | 29.6 GB/s | 118.1 | 10
| _RAM sequential read_ | N/A | 28.0 GB/s | N/A | N/A | _for reference_
| City64 | 64 | 22.0 GB/s | 76.6 | 10
| T1ha2 | 64 | 22.0 GB/s | 99.0 | 9 | Slightly worse [collisions]
| City128 | 128 | 21.7 GB/s | 57.7 | 10
| __XXH64__ | 64 | 19.4 GB/s | 71.0 | 10
| SpookyHash | 64 | 19.3 GB/s | 53.2 | 10
| Mum | 64 | 18.0 GB/s | 67.0 | 9 | Slightly worse [collisions]
| __XXH32__ | 32 | 9.7 GB/s | 71.9 | 10
| City32 | 32 | 9.1 GB/s | 66.0 | 10
| Murmur3 | 32 | 3.9 GB/s | 56.1 | 10
| SipHash | 64 | 3.0 GB/s | 43.2 | 10
| FNV64 | 64 | 1.2 GB/s | 62.7 | 5 | Poor avalanche properties
| Blake2 | 256 | 1.1 GB/s | 5.1 | 10 | Cryptographic
| SHA1 | 160 | 0.8 GB/s | 5.6 | 10 | Cryptographic but broken
| MD5 | 128 | 0.6 GB/s | 7.8 | 10 | Cryptographic but broken
[open source benchmark program]: https://github.com/Cyan4973/xxHash/tree/release/tests/bench
[collisions]: https://github.com/Cyan4973/xxHash/wiki/Collision-ratio-comparison#collision-study
note 1: Small data velocity is a _rough_ evaluation of algorithm's efficiency on small data. For more detailed analysis, please refer to next paragraph.
note 2: some algorithms feature _faster than RAM_ speed. In which case, they can only reach their full speed potential when input is already in CPU cache (L3 or better). Otherwise, they max out on RAM speed limit.
### Small data
Performance on large data is only one part of the picture.
Hashing is also very useful in constructions like hash tables and bloom filters.
In these use cases, it's frequent to hash a lot of small data (starting at a few bytes).
Algorithm's performance can be very different for such scenarios, since parts of the algorithm,
such as initialization or finalization, become fixed cost.
The impact of branch mis-prediction also becomes much more present.
XXH3 has been designed for excellent performance on both long and small inputs,
which can be observed in the following graph:
![XXH3, latency, random size](https://user-images.githubusercontent.com/750081/61976089-aedeab00-af9f-11e9-9239-e5375d6c080f.png)
For a more detailed analysis, please visit the wiki :
https://github.com/Cyan4973/xxHash/wiki/Performance-comparison#benchmarks-concentrating-on-small-data-
Quality
-------------------------
Speed is not the only property that matters.
Produced hash values must respect excellent dispersion and randomness properties,
so that any sub-section of it can be used to maximally spread out a table or index,
as well as reduce the amount of collisions to the minimal theoretical level, following the [birthday paradox].
`xxHash` has been tested with Austin Appleby's excellent SMHasher test suite,
and passes all tests, ensuring reasonable quality levels.
It also passes extended tests from [newer forks of SMHasher], featuring additional scenarios and conditions.
Finally, xxHash provides its own [massive collision tester](https://github.com/Cyan4973/xxHash/tree/dev/tests/collisions),
able to generate and compare billions of hashes to test the limits of 64-bit hash algorithms.
On this front too, xxHash features good results, in line with the [birthday paradox].
A more detailed analysis is documented [in the wiki](https://github.com/Cyan4973/xxHash/wiki/Collision-ratio-comparison).
[birthday paradox]: https://en.wikipedia.org/wiki/Birthday_problem
[newer forks of SMHasher]: https://github.com/rurban/smhasher
### Build modifiers
The following macros can be set at compilation time to modify libxxhash's behavior. They are generally disabled by default.
- `XXH_INLINE_ALL`: Make all functions `inline`, with implementations being directly included within `xxhash.h`.
Inlining functions is beneficial for speed on small keys.
It's _extremely effective_ when key length is expressed as _a compile time constant_,
with performance improvements observed in the +200% range .
See [this article](https://fastcompression.blogspot.com/2018/03/xxhash-for-small-keys-impressive-power.html) for details.
- `XXH_PRIVATE_API`: same outcome as `XXH_INLINE_ALL`. Still available for legacy support.
The name underlines that `XXH_*` symbol names will not be exported.
- `XXH_NAMESPACE`: Prefixes all symbols with the value of `XXH_NAMESPACE`.
This macro can only use compilable character set.
Useful to evade symbol naming collisions,
in case of multiple inclusions of xxHash's source code.
Client applications still use the regular function names,
as symbols are automatically translated through `xxhash.h`.
- `XXH_FORCE_ALIGN_CHECK`: Use a faster direct read path when input is aligned.
This option can result in dramatic performance improvement when input to hash is aligned on 32 or 64-bit boundaries,
when running on architectures unable to load memory from unaligned addresses, or suffering a performance penalty from it.
It is (slightly) detrimental on platform with good unaligned memory access performance (same instruction for both aligned and unaligned accesses).
This option is automatically disabled on `x86`, `x64` and `aarch64`, and enabled on all other platforms.
- `XXH_FORCE_MEMORY_ACCESS`: The default method `0` uses a portable `memcpy()` notation.
Method `1` uses a gcc-specific `packed` attribute, which can provide better performance for some targets.
Method `2` forces unaligned reads, which is not standard compliant, but might sometimes be the only way to extract better read performance.
Method `3` uses a byteshift operation, which is best for old compilers which don't inline `memcpy()` or big-endian systems without a byteswap instruction.
- `XXH_VECTOR` : manually select a vector instruction set (default: auto-selected at compilation time). Available instruction sets are `XXH_SCALAR`, `XXH_SSE2`, `XXH_AVX2`, `XXH_AVX512`, `XXH_NEON` and `XXH_VSX`. Compiler may require additional flags to ensure proper support (for example, `gcc` on linux will require `-mavx2` for `AVX2`, and `-mavx512f` for `AVX512`).
- `XXH_NO_PREFETCH` : disable prefetching. Some platforms or situations may perform better without prefetching. XXH3 only.
- `XXH_PREFETCH_DIST` : select prefetching distance. For close-to-metal adaptation to specific hardware platforms. XXH3 only.
- `XXH_NO_STREAM`: Disables the streaming API, limiting it to single shot variants only.
- `XXH_SIZE_OPT`: `0`: default, optimize for speed
`1`: default for `-Os` and `-Oz`: disables some speed hacks for size optimization
`2`: makes code as small as possible, performance may cry
- `XXH_NO_INLINE_HINTS`: By default, xxHash uses `__attribute__((always_inline))` and `__forceinline` to improve performance at the cost of code size.
Defining this macro to 1 will mark all internal functions as `static`, allowing the compiler to decide whether to inline a function or not.
This is very useful when optimizing for smallest binary size,
and is automatically defined when compiling with `-O0`, `-Os`, `-Oz`, or `-fno-inline` on GCC and Clang.
This may also increase performance depending on compiler and architecture.
- `XXH32_ENDJMP`: Switch multi-branch finalization stage of XXH32 by a single jump.
This is generally undesirable for performance, especially when hashing inputs of random sizes.
But depending on exact architecture and compiler, a jump might provide slightly better performance on small inputs. Disabled by default.
- `XXH_NO_STDLIB`: Disable invocation of `<stdlib.h>` functions, notably `malloc()` and `free()`.
`libxxhash`'s `XXH*_createState()` will always fail and return `NULL`.
But one-shot hashing (like `XXH32()`) or streaming using statically allocated states
still work as expected.
This build flag is useful for embedded environments without dynamic allocation.
- `XXH_STATIC_LINKING_ONLY`: gives access to internal state declaration, required for static allocation.
Incompatible with dynamic linking, due to risks of ABI changes.
- `XXH_NO_XXH3` : removes symbols related to `XXH3` (both 64 & 128 bits) from generated binary.
Useful to reduce binary size, notably for applications which do not employ `XXH3`.
- `XXH_NO_LONG_LONG`: removes compilation of algorithms relying on 64-bit types (`XXH3` and `XXH64`). Only `XXH32` will be compiled.
Useful for targets (architectures and compilers) without 64-bit support.
- `XXH_IMPORT`: MSVC specific: should only be defined for dynamic linking, as it prevents linkage errors.
- `XXH_CPU_LITTLE_ENDIAN`: By default, endianness is determined by a runtime test resolved at compile time.
If, for some reason, the compiler cannot simplify the runtime test, it can cost performance.
It's possible to skip auto-detection and simply state that the architecture is little-endian by setting this macro to 1.
Setting it to 0 states big-endian.
- `XXH_DEBUGLEVEL` : When set to any value >= 1, enables `assert()` statements.
This (slightly) slows down execution, but may help finding bugs during debugging sessions.
When compiling the Command Line Interface `xxhsum` using `make`, the following environment variables can also be set :
- `DISPATCH=1` : use `xxh_x86dispatch.c`, to automatically select between `scalar`, `sse2`, `avx2` or `avx512` instruction set at runtime, depending on local host. This option is only valid for `x86`/`x64` systems.
- `XXH_1ST_SPEED_TARGET` : select an initial speed target, expressed in MB/s, for the first speed test in benchmark mode. Benchmark will adjust the target at subsequent iterations, but the first test is made "blindly" by targeting this speed. Currently conservatively set to 10 MB/s, to support very slow (emulated) platforms.
### Building xxHash - Using vcpkg
You can download and install xxHash using the [vcpkg](https://github.com/Microsoft/vcpkg) dependency manager:
git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
./vcpkg install xxhash
The xxHash port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository.
### Building and Using xxHash - tipi.build
You can work on xxHash and depend on it in your [tipi.build](https://tipi.build) projects by adding the following entry to your `.tipi/deps`:
```json
{
"Cyan4973/xxHash": { "@": "v0.8.1" }
}
```
An example of such usage can be found in the `/cli` folder of this project which, if built as root project will depend on the release `v0.8.1` of xxHash
To contribute to xxHash itself use tipi.build on this repository (change the target name appropriately to `linux` or `macos` or `windows`):
```bash
tipi . -t <target> --test all
```
### Example
The simplest example calls xxhash 64-bit variant as a one-shot function
generating a hash value from a single buffer, and invoked from a C/C++ program:
```C
#include "xxhash.h"
(...)
XXH64_hash_t hash = XXH64(buffer, size, seed);
}
```
Streaming variant is more involved, but makes it possible to provide data incrementally:
```C
#include "stdlib.h" /* abort() */
#include "xxhash.h"
XXH64_hash_t calcul_hash_streaming(FileHandler fh)
{
/* create a hash state */
XXH64_state_t* const state = XXH64_createState();
if (state==NULL) abort();
size_t const bufferSize = SOME_SIZE;
void* const buffer = malloc(bufferSize);
if (buffer==NULL) abort();
/* Initialize state with selected seed */
XXH64_hash_t const seed = 0; /* or any other value */
if (XXH64_reset(state, seed) == XXH_ERROR) abort();
/* Feed the state with input data, any size, any number of times */
(...)
while ( /* some data left */ ) {
size_t const length = get_more_data(buffer, bufferSize, fh);
if (XXH64_update(state, buffer, length) == XXH_ERROR) abort();
(...)
}
(...)
/* Produce the final hash value */
XXH64_hash_t const hash = XXH64_digest(state);
/* State could be re-used; but in this example, it is simply freed */
free(buffer);
XXH64_freeState(state);
return hash;
}
```
### License
The library files `xxhash.c` and `xxhash.h` are BSD licensed.
The utility `xxhsum` is GPL licensed.
### Other programming languages
Beyond the C reference version,
xxHash is also available from many different programming languages,
thanks to great contributors.
They are [listed here](http://www.xxhash.com/#other-languages).
### Packaging status
Many distributions bundle a package manager
which allows easy xxhash installation as both a `libxxhash` library
and `xxhsum` command line interface.
[![Packaging status](https://repology.org/badge/vertical-allrepos/xxhash.svg)](https://repology.org/project/xxhash/versions)
### Special Thanks
- Takayuki Matsuoka, aka @t-mat, for creating `xxhsum -c` and great support during early xxh releases
- Mathias Westerdahl, aka @JCash, for introducing the first version of `XXH64`
- Devin Hussey, aka @easyaspi314, for incredible low-level optimizations on `XXH3` and `XXH128`
# Security Policy
## Supported Versions
Security updates are applied only to the latest release.
## Reporting a Vulnerability
If you have discovered a security vulnerability in this project, please report it privately. **Do not disclose it as a public issue.** This gives us time to work with you to fix the issue before public exposure, reducing the chance that the exploit will be used before a patch is released.
Please disclose it at [security advisory](https://github.com/Cyan4973/xxHash/security/advisories/new).
This project is maintained by a team of volunteers on a reasonable-effort basis. As such, please give us at least 90 days to work on a fix before public exposure.
#---------------------------------#
# general configuration #
#---------------------------------#
version: 1.0.{build}
max_jobs: 2
#---------------------------------#
# environment configuration #
#---------------------------------#
clone_depth: 2
environment:
matrix:
- COMPILER: "visual"
ARCH: "x64"
TEST_XXHSUM: "true"
- COMPILER: "visual"
ARCH: "Win32"
TEST_XXHSUM: "true"
- COMPILER: "visual"
ARCH: "Win32"
APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2013
TEST_XXHSUM: "true"
- COMPILER: "visual"
ARCH: "ARM"
# Below tests are now disabled due to redundancy.
# Their equivalent already runs correctly on Github Actions.
# - COMPILER: "visual"
# ARCH: "x64"
# APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
# TEST_XXHSUM: "true"
# - COMPILER: "visual"
# ARCH: "ARM64"
# APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017
# # note: ARM64 is not available with Visual Studio 14 2015, which is default for Appveyor
# The following tests were also flacky on Appveyor, for various reasons.
# - COMPILER: "gcc"
# PLATFORM: "mingw64"
# - COMPILER: "gcc"
# PLATFORM: "mingw32"
# - COMPILER: "gcc"
# PLATFORM: "clang"
install:
- ECHO Installing %COMPILER% %PLATFORM% %ARCH%
- MKDIR bin
- if [%COMPILER%]==[gcc] SET PATH_ORIGINAL=%PATH%
- if [%COMPILER%]==[gcc] (
SET "PATH_MINGW32=c:\MinGW\bin;c:\MinGW\usr\bin" &&
SET "PATH_MINGW64=c:\msys64\mingw64\bin;c:\msys64\usr\bin" &&
COPY C:\MinGW\bin\mingw32-make.exe C:\MinGW\bin\make.exe &&
COPY C:\MinGW\bin\gcc.exe C:\MinGW\bin\cc.exe
)
#---------------------------------#
# build configuration #
#---------------------------------#
build_script:
- if [%PLATFORM%]==[mingw32] SET PATH=%PATH_MINGW32%;%PATH_ORIGINAL%
- if [%PLATFORM%]==[mingw64] SET PATH=%PATH_MINGW64%;%PATH_ORIGINAL%
- if [%PLATFORM%]==[clang] SET PATH=%PATH_MINGW64%;%PATH_ORIGINAL%
- ECHO ***
- ECHO Building %COMPILER% %PLATFORM% %ARCH%
- ECHO ***
- if [%COMPILER%]==[gcc] (
if [%PLATFORM%]==[clang] (
clang -v
) ELSE (
gcc -v
)
)
- if [%COMPILER%]==[gcc] (
echo ----- &&
make -v &&
echo ----- &&
if not [%PLATFORM%]==[clang] (
if [%PLATFORM%]==[mingw32] ( SET CPPFLAGS=-DPOOL_MT=0 ) &&
make -B clean test MOREFLAGS=-Werror
) ELSE (
SET CXXFLAGS=--std=c++14 &&
make -B clean test CC=clang CXX=clang++ MOREFLAGS="--target=x86_64-w64-mingw32 -Werror -Wno-pass-failed" NO_C90_TEST=true
) &&
make -C tests/bench
)
# note 1: strict c90 tests with clang fail, due to (erroneous) presence on `inline` keyword in some included system file
# note 2: multi-threading code doesn't work with mingw32, disabled through POOL_MT=0
# note 3: clang requires C++14 to compile sort because its own code contains c++14-only code
- if [%COMPILER%]==[visual] (
cd cmake_unofficial &&
cmake . -DCMAKE_BUILD_TYPE=Release -A %ARCH% -DXXHASH_C_FLAGS="/WX" &&
cmake --build . --config Release
)
#---------------------------------#
# tests configuration #
#---------------------------------#
test_script:
# note: can only run x86 and x64 binaries on Appveyor
# note: if %COMPILER%==gcc, xxhsum was already tested within `make test`
- if [%TEST_XXHSUM%]==[true] (
ECHO *** &&
ECHO Testing %COMPILER% %PLATFORM% %ARCH% &&
ECHO *** &&
cd Release &&
xxhsum.exe -bi1 &&
ECHO ------- xxhsum tested -------
)
#---------------------------------#
# artifacts configuration #
#---------------------------------#
# none yet
{
"Cyan4973/xxHash": { }
}
\ No newline at end of file
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
This directory contains source code dedicated to the `xxhsum` command line utility,
which is a user program of `libxxhash`.
Note that, in contrast with the library `libxxhash`, the command line utility `xxhsum` ships with GPLv2 license.
/*
* xxhsum - Command line interface for xxhash algorithms
* Copyright (C) 2013-2021 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
/*
* Checks for predefined macros by the compiler to try and get both the arch
* and the compiler version.
*/
#ifndef XSUM_ARCH_H
#define XSUM_ARCH_H
#include "xsum_config.h"
#define XSUM_LIB_VERSION XXH_VERSION_MAJOR.XXH_VERSION_MINOR.XXH_VERSION_RELEASE
#define XSUM_QUOTE(str) #str
#define XSUM_EXPAND_AND_QUOTE(str) XSUM_QUOTE(str)
#define XSUM_PROGRAM_VERSION XSUM_EXPAND_AND_QUOTE(XSUM_LIB_VERSION)
/* Show compiler versions in WELCOME_MESSAGE. XSUM_CC_VERSION_FMT will return the printf specifiers,
* and VERSION will contain the comma separated list of arguments to the XSUM_CC_VERSION_FMT string. */
#if defined(__clang_version__)
/* Clang does its own thing. */
# ifdef __apple_build_version__
# define XSUM_CC_VERSION_FMT "Apple Clang %s"
# else
# define XSUM_CC_VERSION_FMT "Clang %s"
# endif
# define XSUM_CC_VERSION __clang_version__
#elif defined(__VERSION__)
/* GCC and ICC */
# define XSUM_CC_VERSION_FMT "%s"
# ifdef __INTEL_COMPILER /* icc adds its prefix */
# define XSUM_CC_VERSION __VERSION__
# else /* assume GCC */
# define XSUM_CC_VERSION "GCC " __VERSION__
# endif
#elif defined(_MSC_FULL_VER) && defined(_MSC_BUILD)
/*
* MSVC
* "For example, if the version number of the Visual C++ compiler is
* 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706."
*
* https://docs.microsoft.com/en-us/cpp/preprocessor/predefined-macros?view=vs-2017
*/
# define XSUM_CC_VERSION_FMT "MSVC %02i.%02i.%05i.%02i"
# define XSUM_CC_VERSION _MSC_FULL_VER / 10000000 % 100, _MSC_FULL_VER / 100000 % 100, _MSC_FULL_VER % 100000, _MSC_BUILD
#elif defined(_MSC_VER) /* old MSVC */
# define XSUM_CC_VERSION_FMT "MSVC %02i.%02i"
# define XSUM_CC_VERSION _MSC_VER / 100, _MSC_VER % 100
#elif defined(__TINYC__)
/* tcc stores its version in the __TINYC__ macro. */
# define XSUM_CC_VERSION_FMT "tcc %i.%i.%i"
# define XSUM_CC_VERSION __TINYC__ / 10000 % 100, __TINYC__ / 100 % 100, __TINYC__ % 100
#else
# define XSUM_CC_VERSION_FMT "%s"
# define XSUM_CC_VERSION "unknown compiler"
#endif
/* makes the next part easier */
#if (defined(__x86_64__) || defined(_M_AMD64) || defined(_M_X64)) && !defined(_M_ARM64EC)
# define XSUM_ARCH_X64 1
# define XSUM_ARCH_X86 "x86_64"
#elif defined(__i386__) || defined(_M_IX86) || defined(_M_IX86_FP)
# define XSUM_ARCH_X86 "i386"
#endif
/* Try to detect the architecture. */
#if defined(XSUM_ARCH_X86)
# if defined(XXHSUM_DISPATCH)
# define XSUM_ARCH XSUM_ARCH_X86 " autoVec"
# elif defined(__AVX512F__)
# define XSUM_ARCH XSUM_ARCH_X86 " + AVX512"
# elif defined(__AVX2__)
# define XSUM_ARCH XSUM_ARCH_X86 " + AVX2"
# elif defined(__AVX__)
# define XSUM_ARCH XSUM_ARCH_X86 " + AVX"
# elif defined(_M_X64) || defined(_M_AMD64) || defined(__x86_64__) \
|| defined(__SSE2__) || (defined(_M_IX86_FP) && _M_IX86_FP == 2)
# define XSUM_ARCH XSUM_ARCH_X86 " + SSE2"
# else
# define XSUM_ARCH XSUM_ARCH_X86
# endif
#elif defined(__aarch64__) || defined(__arm64__) || defined(_M_ARM64) || defined(_M_ARM64EC)
# define XSUM_ARCH "aarch64 + NEON"
#elif defined(__arm__) || defined(__thumb__) || defined(__thumb2__) || defined(_M_ARM)
/* ARM has a lot of different features that can change xxHash significantly. */
# ifdef __ARM_ARCH
# define XSUM_ARCH_ARM_VER XSUM_EXPAND_AND_QUOTE(__ARM_ARCH)
# else
# define XSUM_ARCH_ARM_VER XSUM_EXPAND_AND_QUOTE(_M_ARM)
# endif
# if defined(_M_ARM) /* windows arm is always thumb-2 */ \
|| defined(__thumb2__) || (defined(__thumb__) && (__thumb__ == 2 || __ARM_ARCH >= 7))
# define XSUM_ARCH_THUMB " Thumb-2"
# elif defined(__thumb__)
# define XSUM_ARCH_THUMB " Thumb-1"
# else
# define XSUM_ARCH_THUMB ""
# endif
/* ARMv7 has unaligned by default */
# if defined(__ARM_FEATURE_UNALIGNED) || __ARM_ARCH >= 7 || defined(_M_ARM)
# define XSUM_ARCH_UNALIGNED " + unaligned"
# else
# define XSUM_ARCH_UNALIGNED ""
# endif
# if defined(__ARM_NEON) || defined(__ARM_NEON__) || defined(_M_ARM)
# define XSUM_ARCH_NEON " + NEON"
# else
# define XSUM_ARCH_NEON ""
# endif
# define XSUM_ARCH "ARMv" XSUM_ARCH_ARM_VER XSUM_ARCH_THUMB XSUM_ARCH_NEON XSUM_ARCH_UNALIGNED
#elif defined(__powerpc64__) || defined(__ppc64__) || defined(__PPC64__)
# if defined(__GNUC__) && defined(__POWER9_VECTOR__)
# define XSUM_ARCH "ppc64 + POWER9 vector"
# elif defined(__GNUC__) && defined(__POWER8_VECTOR__)
# define XSUM_ARCH "ppc64 + POWER8 vector"
# else
# define XSUM_ARCH "ppc64"
# endif
#elif defined(__powerpc__) || defined(__ppc__) || defined(__PPC__)
# define XSUM_ARCH "ppc"
#elif defined(__AVR)
# define XSUM_ARCH "AVR"
#elif defined(__mips64)
# define XSUM_ARCH "mips64"
#elif defined(__mips)
# define XSUM_ARCH "mips"
#elif defined(__s390x__)
# define XSUM_ARCH "s390x"
#elif defined(__s390__)
# define XSUM_ARCH "s390"
#else
# define XSUM_ARCH "unknown"
#endif
#endif /* XSUM_ARCH_H */
/*
* xsum_bench - Benchmark functions for xxhsum
* Copyright (C) 2013-2021 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
#include "xsum_output.h" /* XSUM_logLevel */
#include "xsum_bench.h"
#include "xsum_sanity_check.h" /* XSUM_fillTestBuffer */
#include "xsum_os_specific.h" /* XSUM_getFileSize */
#ifndef XXH_STATIC_LINKING_ONLY
# define XXH_STATIC_LINKING_ONLY
#endif
#include "../xxhash.h"
#ifdef XXHSUM_DISPATCH
# include "../xxh_x86dispatch.h" /* activate _dispatch() redirectors */
#endif
#include <stdlib.h> /* malloc, free */
#include <assert.h>
#include <string.h> /* strlen, memcpy */
#include <time.h> /* clock_t, clock, CLOCKS_PER_SEC */
#include <errno.h> /* errno */
#define TIMELOOP_S 1
#define TIMELOOP (TIMELOOP_S * CLOCKS_PER_SEC) /* target timing per iteration */
#define TIMELOOP_MIN (TIMELOOP / 2) /* minimum timing to validate a result */
/* Each benchmark iteration attempts to match TIMELOOP (1 second).
* The nb of loops is adjusted at each iteration to reach that target.
* However, initially, there is no information, so 1st iteration blindly targets an arbitrary speed.
* If it's too small, it will be adjusted, and a new attempt will be made.
* But if it's too large, the first iteration can be very long,
* before being fixed at second attempt.
* So prefer starting with small speed targets.
* XXH_1ST_SPEED_TARGET is defined in MB/s */
#ifndef XXH_1ST_SPEED_TARGET
# define XXH_1ST_SPEED_TARGET 10
#endif
#define MAX_MEM (2 GB - 64 MB)
static clock_t XSUM_clockSpan( clock_t start )
{
return clock() - start; /* works even if overflow; Typical max span ~ 30 mn */
}
static size_t XSUM_findMaxMem(XSUM_U64 requiredMem)
{
size_t const step = 64 MB;
void* testmem = NULL;
requiredMem = (((requiredMem >> 26) + 1) << 26);
requiredMem += 2*step;
if (requiredMem > MAX_MEM) requiredMem = MAX_MEM;
while (!testmem) {
if (requiredMem > step) requiredMem -= step;
else requiredMem >>= 1;
testmem = malloc ((size_t)requiredMem);
}
free (testmem);
/* keep some space available */
if (requiredMem > step) requiredMem -= step;
else requiredMem >>= 1;
return (size_t)requiredMem;
}
/*
* A secret buffer used for benchmarking XXH3's withSecret variants.
*
* In order for the bench to be realistic, the secret buffer would need to be
* pre-generated.
*
* Adding a pointer to the parameter list would be messy.
*/
static XSUM_U8 g_benchSecretBuf[XXH3_SECRET_SIZE_MIN];
/*
* Wrappers for the benchmark.
*
* If you would like to add other hashes to the bench, create a wrapper and add
* it to the g_hashesToBench table. It will automatically be added.
*/
typedef XSUM_U32 (*hashFunction)(const void* buffer, size_t bufferSize, XSUM_U32 seed);
static XSUM_U32 localXXH32(const void* buffer, size_t bufferSize, XSUM_U32 seed)
{
return XXH32(buffer, bufferSize, seed);
}
static XSUM_U32 localXXH32_stream(const void* buffer, size_t bufferSize, XSUM_U32 seed)
{
XXH32_state_t state;
(void)seed;
XXH32_reset(&state, seed);
XXH32_update(&state, buffer, bufferSize);
return (XSUM_U32)XXH32_digest(&state);
}
static XSUM_U32 localXXH64(const void* buffer, size_t bufferSize, XSUM_U32 seed)
{
return (XSUM_U32)XXH64(buffer, bufferSize, seed);
}
static XSUM_U32 localXXH64_stream(const void* buffer, size_t bufferSize, XSUM_U32 seed)
{
XXH64_state_t state;
(void)seed;
XXH64_reset(&state, seed);
XXH64_update(&state, buffer, bufferSize);
return (XSUM_U32)XXH64_digest(&state);
}
static XSUM_U32 localXXH3_64b(const void* buffer, size_t bufferSize, XSUM_U32 seed)
{
(void)seed;
return (XSUM_U32)XXH3_64bits(buffer, bufferSize);
}
static XSUM_U32 localXXH3_64b_seeded(const void* buffer, size_t bufferSize, XSUM_U32 seed)
{
return (XSUM_U32)XXH3_64bits_withSeed(buffer, bufferSize, seed);
}
static XSUM_U32 localXXH3_64b_secret(const void* buffer, size_t bufferSize, XSUM_U32 seed)
{
(void)seed;
return (XSUM_U32)XXH3_64bits_withSecret(buffer, bufferSize, g_benchSecretBuf, sizeof(g_benchSecretBuf));
}
static XSUM_U32 localXXH3_128b(const void* buffer, size_t bufferSize, XSUM_U32 seed)
{
(void)seed;
return (XSUM_U32)(XXH3_128bits(buffer, bufferSize).low64);
}
static XSUM_U32 localXXH3_128b_seeded(const void* buffer, size_t bufferSize, XSUM_U32 seed)
{
return (XSUM_U32)(XXH3_128bits_withSeed(buffer, bufferSize, seed).low64);
}
static XSUM_U32 localXXH3_128b_secret(const void* buffer, size_t bufferSize, XSUM_U32 seed)
{
(void)seed;
return (XSUM_U32)(XXH3_128bits_withSecret(buffer, bufferSize, g_benchSecretBuf, sizeof(g_benchSecretBuf)).low64);
}
static XSUM_U32 localXXH3_stream(const void* buffer, size_t bufferSize, XSUM_U32 seed)
{
XXH3_state_t state;
(void)seed;
XXH3_64bits_reset(&state);
XXH3_64bits_update(&state, buffer, bufferSize);
return (XSUM_U32)XXH3_64bits_digest(&state);
}
static XSUM_U32 localXXH3_stream_seeded(const void* buffer, size_t bufferSize, XSUM_U32 seed)
{
XXH3_state_t state;
XXH3_INITSTATE(&state);
XXH3_64bits_reset_withSeed(&state, (XXH64_hash_t)seed);
XXH3_64bits_update(&state, buffer, bufferSize);
return (XSUM_U32)XXH3_64bits_digest(&state);
}
static XSUM_U32 localXXH128_stream(const void* buffer, size_t bufferSize, XSUM_U32 seed)
{
XXH3_state_t state;
(void)seed;
XXH3_128bits_reset(&state);
XXH3_128bits_update(&state, buffer, bufferSize);
return (XSUM_U32)(XXH3_128bits_digest(&state).low64);
}
static XSUM_U32 localXXH128_stream_seeded(const void* buffer, size_t bufferSize, XSUM_U32 seed)
{
XXH3_state_t state;
XXH3_INITSTATE(&state);
XXH3_128bits_reset_withSeed(&state, (XXH64_hash_t)seed);
XXH3_128bits_update(&state, buffer, bufferSize);
return (XSUM_U32)(XXH3_128bits_digest(&state).low64);
}
typedef struct {
const char* name;
hashFunction func;
} hashInfo;
static const hashInfo g_hashesToBench[] = {
{ "XXH32", &localXXH32 },
{ "XXH64", &localXXH64 },
{ "XXH3_64b", &localXXH3_64b },
{ "XXH3_64b w/seed", &localXXH3_64b_seeded },
{ "XXH3_64b w/secret", &localXXH3_64b_secret },
{ "XXH128", &localXXH3_128b },
{ "XXH128 w/seed", &localXXH3_128b_seeded },
{ "XXH128 w/secret", &localXXH3_128b_secret },
{ "XXH32_stream", &localXXH32_stream },
{ "XXH64_stream", &localXXH64_stream },
{ "XXH3_stream", &localXXH3_stream },
{ "XXH3_stream w/seed",&localXXH3_stream_seeded },
{ "XXH128_stream", &localXXH128_stream },
{ "XXH128_stream w/seed",&localXXH128_stream_seeded },
};
#define NB_HASHFUNC (sizeof(g_hashesToBench) / sizeof(*g_hashesToBench))
#define NB_TESTFUNC (1 + 2 * NB_HASHFUNC)
int const g_nbTestFunctions = NB_TESTFUNC;
char g_testIDs[NB_TESTFUNC] = { 0 };
const char k_testIDs_default[NB_TESTFUNC] = { 0,
1 /*XXH32*/, 0,
1 /*XXH64*/, 0,
1 /*XXH3*/, 0, 0, 0, 0, 0,
1 /*XXH128*/ };
int g_nbIterations = NBLOOPS_DEFAULT;
#define HASHNAME_MAX 29
static void XSUM_benchHash(hashFunction h, const char* hName, int testID,
const void* buffer, size_t bufferSize)
{
XSUM_U32 nbh_perIteration = (XSUM_U32)((XXH_1ST_SPEED_TARGET MB) / (bufferSize+1)) + 1;
int iterationNb, nbIterations = g_nbIterations + !g_nbIterations /* min 1 */;
double fastestH = 100000000.;
assert(HASHNAME_MAX > 2);
XSUM_logVerbose(2, "\r%80s\r", ""); /* Clean display line */
for (iterationNb = 1; iterationNb <= nbIterations; iterationNb++) {
XSUM_U32 r=0;
clock_t cStart;
XSUM_logVerbose(2, "%2i-%-*.*s : %10u ->\r",
iterationNb,
HASHNAME_MAX, HASHNAME_MAX, hName,
(unsigned)bufferSize);
cStart = clock();
while (clock() == cStart); /* starts clock() at its exact beginning */
cStart = clock();
{ XSUM_U32 u;
for (u=0; u<nbh_perIteration; u++)
r += h(buffer, bufferSize, u);
}
if (r==0) XSUM_logVerbose(3,".\r"); /* do something with r to defeat compiler "optimizing" hash away */
{ clock_t const nbTicks = XSUM_clockSpan(cStart);
double const ticksPerHash = ((double)nbTicks / TIMELOOP) / nbh_perIteration;
/*
* clock() is the only decent portable timer, but it isn't very
* precise.
*
* Sometimes, this lack of precision is enough that the benchmark
* finishes before there are enough ticks to get a meaningful result.
*
* For example, on a Core 2 Duo (without any sort of Turbo Boost),
* the imprecise timer caused peculiar results like so:
*
* XXH3_64b 4800.0 MB/s // conveniently even
* XXH3_64b unaligned 4800.0 MB/s
* XXH3_64b seeded 9600.0 MB/s // magical 2x speedup?!
* XXH3_64b seeded unaligned 4800.0 MB/s
*
* If we sense a suspiciously low number of ticks, we increase the
* iterations until we can get something meaningful.
*/
if (nbTicks < TIMELOOP_MIN) {
/* Not enough time spent in benchmarking, risk of rounding bias */
if (nbTicks == 0) { /* faster than resolution timer */
nbh_perIteration *= 100;
} else {
/*
* update nbh_perIteration so that the next round lasts
* approximately 1 second.
*/
double nbh_perSecond = (1 / ticksPerHash) + 1;
if (nbh_perSecond > (double)(4000U<<20)) nbh_perSecond = (double)(4000U<<20); /* avoid overflow */
nbh_perIteration = (XSUM_U32)nbh_perSecond;
}
/* g_nbIterations==0 => quick evaluation, no claim of accuracy */
if (g_nbIterations>0) {
iterationNb--; /* new round for a more accurate speed evaluation */
continue;
}
}
if (ticksPerHash < fastestH) fastestH = ticksPerHash;
if (fastestH>0.) { /* avoid div by zero */
XSUM_logVerbose(2, "%2i-%-*.*s : %10u -> %8.0f it/s (%7.1f MB/s) \r",
iterationNb,
HASHNAME_MAX, HASHNAME_MAX, hName,
(unsigned)bufferSize,
(double)1 / fastestH,
((double)bufferSize / (1 MB)) / fastestH);
} }
{ double nbh_perSecond = (1 / fastestH) + 1;
if (nbh_perSecond > (double)(4000U<<20)) nbh_perSecond = (double)(4000U<<20); /* avoid overflow */
nbh_perIteration = (XSUM_U32)nbh_perSecond;
}
}
XSUM_logVerbose(1, "%2i#%-*.*s : %10u -> %8.0f it/s (%7.1f MB/s) \n",
testID,
HASHNAME_MAX, HASHNAME_MAX, hName,
(unsigned)bufferSize,
(double)1 / fastestH,
((double)bufferSize / (1 MB)) / fastestH);
if (XSUM_logLevel<1)
XSUM_logVerbose(0, "%u, ", (unsigned)((double)1 / fastestH));
}
/*
* Allocates a string containing s1 and s2 concatenated. Acts like strdup.
* The result must be freed.
*/
static char* XSUM_strcatDup(const char* s1, const char* s2)
{
assert(s1 != NULL);
assert(s2 != NULL);
{ size_t len1 = strlen(s1);
size_t len2 = strlen(s2);
char* buf = (char*)malloc(len1 + len2 + 1);
if (buf != NULL) {
/* strcpy(buf, s1) */
memcpy(buf, s1, len1);
/* strcat(buf, s2) */
memcpy(buf + len1, s2, len2 + 1);
}
return buf;
}
}
/*!
* XSUM_benchMem():
* buffer: Must be 16-byte aligned.
* The real allocated size of buffer is supposed to be >= (bufferSize+3).
* returns: 0 on success, 1 if error (invalid mode selected)
*/
static void XSUM_benchMem(const void* buffer, size_t bufferSize)
{
assert((((size_t)buffer) & 15) == 0); /* ensure alignment */
XSUM_fillTestBuffer(g_benchSecretBuf, sizeof(g_benchSecretBuf));
{ int i;
for (i = 1; i < (int)NB_TESTFUNC; i++) {
int const hashFuncID = (i-1) / 2;
assert(g_hashesToBench[hashFuncID].name != NULL);
if (g_testIDs[i] == 0) continue;
/* aligned */
if ((i % 2) == 1) {
XSUM_benchHash(g_hashesToBench[hashFuncID].func, g_hashesToBench[hashFuncID].name, i, buffer, bufferSize);
}
/* unaligned */
if ((i % 2) == 0) {
/* Append "unaligned". */
char* const hashNameBuf = XSUM_strcatDup(g_hashesToBench[hashFuncID].name, " unaligned");
assert(hashNameBuf != NULL);
XSUM_benchHash(g_hashesToBench[hashFuncID].func, hashNameBuf, i, ((const char*)buffer)+3, bufferSize);
free(hashNameBuf);
}
} }
}
static size_t XSUM_selectBenchedSize(const char* fileName)
{
XSUM_U64 const inFileSize = XSUM_getFileSize(fileName);
size_t benchedSize = (size_t) XSUM_findMaxMem(inFileSize);
if ((XSUM_U64)benchedSize > inFileSize) benchedSize = (size_t)inFileSize;
if (benchedSize < inFileSize) {
XSUM_log("Not enough memory for '%s' full size; testing %i MB only...\n", fileName, (int)(benchedSize>>20));
}
return benchedSize;
}
int XSUM_benchFiles(const char* fileNamesTable[], int nbFiles)
{
int fileIdx;
for (fileIdx=0; fileIdx<nbFiles; fileIdx++) {
const char* const inFileName = fileNamesTable[fileIdx];
assert(inFileName != NULL);
{ FILE* const inFile = XSUM_fopen( inFileName, "rb" );
size_t const benchedSize = XSUM_selectBenchedSize(inFileName);
char* const buffer = (char*)calloc(benchedSize+16+3, 1);
void* const alignedBuffer = (buffer+15) - (((size_t)(buffer+15)) & 0xF); /* align on next 16 bytes */
/* Checks */
if (inFile==NULL){
XSUM_log("Error: Could not open '%s': %s.\n", inFileName, strerror(errno));
free(buffer);
exit(11);
}
if(!buffer) {
XSUM_log("\nError: Out of memory.\n");
fclose(inFile);
exit(12);
}
/* Fill input buffer */
{ size_t const readSize = fread(alignedBuffer, 1, benchedSize, inFile);
fclose(inFile);
if(readSize != benchedSize) {
XSUM_log("\nError: Could not read '%s': %s.\n", inFileName, strerror(errno));
free(buffer);
exit(13);
} }
/* bench */
XSUM_benchMem(alignedBuffer, benchedSize);
free(buffer);
} }
return 0;
}
int XSUM_benchInternal(size_t keySize)
{
void* const buffer = calloc(keySize+16+3, 1);
if (buffer == NULL) {
XSUM_log("\nError: Out of memory.\n");
exit(12);
}
{ const void* const alignedBuffer = ((char*)buffer+15) - (((size_t)((char*)buffer+15)) & 0xF); /* align on next 16 bytes */
/* bench */
XSUM_logVerbose(1, "Sample of ");
if (keySize > 10 KB) {
XSUM_logVerbose(1, "%u KB", (unsigned)(keySize >> 10));
} else {
XSUM_logVerbose(1, "%u bytes", (unsigned)keySize);
}
XSUM_logVerbose(1, "... \n");
XSUM_benchMem(alignedBuffer, keySize);
free(buffer);
}
return 0;
}
/*
* xsum_bench - Benchmark functions for xxhsum
* Copyright (C) 2013-2021 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
#ifndef XSUM_BENCH_H
#define XSUM_BENCH_H
#include <stddef.h> /* size_t */
#define NBLOOPS_DEFAULT 3 /* Default number of benchmark iterations */
extern int const g_nbTestFunctions;
extern char g_testIDs[]; /* size : g_nbTestFunctions */
extern const char k_testIDs_default[];
extern int g_nbIterations;
int XSUM_benchInternal(size_t keySize);
int XSUM_benchFiles(const char* fileNamesTable[], int nbFiles);
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif /* XSUM_BENCH_H */
/*
* xxhsum - Command line interface for xxhash algorithms
* Copyright (C) 2013-2021 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
/*
* This contains various configuration parameters and feature detection for
* xxhsum.
*
* Similar to config.h in Autotools, this should be the first header included.
*/
#ifndef XSUM_CONFIG_H
#define XSUM_CONFIG_H
/* ************************************
* Compiler Options
**************************************/
/*
* Disable Visual C's warnings when using the "insecure" CRT functions instead
* of the "secure" _s functions.
*
* These functions are not portable, and aren't necessary if you are using the
* original functions properly.
*/
#if defined(_MSC_VER) || defined(_WIN32)
# ifndef _CRT_SECURE_NO_WARNINGS
# define _CRT_SECURE_NO_WARNINGS
# endif
#endif
/* Under Linux at least, pull in the *64 commands */
#ifndef _LARGEFILE64_SOURCE
# define _LARGEFILE64_SOURCE
#endif
#ifndef _FILE_OFFSET_BITS
# define _FILE_OFFSET_BITS 64
#endif
/*
* So we can use __attribute__((__format__))
*/
#ifdef __GNUC__
# define XSUM_ATTRIBUTE(x) __attribute__(x)
#else
# define XSUM_ATTRIBUTE(x)
#endif
#if !defined(_WIN32) && (defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__)) /* UNIX-like OS */ \
|| defined(__midipix__) || defined(__VMS))
# if (defined(__APPLE__) && defined(__MACH__)) || defined(__SVR4) || defined(_AIX) || defined(__hpux) /* POSIX.1-2001 (SUSv3) conformant */ \
|| defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) /* BSD distros */
# define XSUM_PLATFORM_POSIX_VERSION 200112L
# else
# if defined(__linux__) || defined(__linux)
# ifndef _POSIX_C_SOURCE
# define _POSIX_C_SOURCE 200112L /* use feature test macro */
# endif
# endif
# include <unistd.h> /* declares _POSIX_VERSION */
# if defined(_POSIX_VERSION) /* POSIX compliant */
# define XSUM_PLATFORM_POSIX_VERSION _POSIX_VERSION
# else
# define XSUM_PLATFORM_POSIX_VERSION 0
# endif
# endif
#endif
#if !defined(XSUM_PLATFORM_POSIX_VERSION)
# define XSUM_PLATFORM_POSIX_VERSION -1
#endif
#if !defined(S_ISREG)
# define S_ISREG(x) (((x) & S_IFMT) == S_IFREG)
#endif
/* ************************************
* Windows helpers
**************************************/
/*
* Whether to use the Windows UTF-16 APIs instead of the portable libc 8-bit
* ("ANSI") APIs.
*
* Windows is not UTF-8 clean by default, and the only way to access every file
* on the OS is to use UTF-16.
*
* Do note that xxhsum uses UTF-8 internally and only uses UTF-16 for command
* line arguments, console I/O, and opening files.
*
* Additionally, this guarantees all piped output is UTF-8.
*/
#if defined(XSUM_WIN32_USE_WCHAR) && !defined(_WIN32)
/* We use Windows APIs, only use this on Windows. */
# undef XSUM_WIN32_USE_WCHAR
#endif
#ifndef XSUM_WIN32_USE_WCHAR
# if defined(_WIN32)
# include <wchar.h>
# if WCHAR_MAX == 0xFFFFU /* UTF-16 wchar_t */
# define XSUM_WIN32_USE_WCHAR 1
# else
# define XSUM_WIN32_USE_WCHAR 0
# endif
# else
# define XSUM_WIN32_USE_WCHAR 0
# endif
#endif
#if !XSUM_WIN32_USE_WCHAR
/*
* It doesn't make sense to have one without the other.
* Due to XSUM_WIN32_USE_WCHAR being undef'd, this also handles
* non-WIN32 platforms.
*/
# undef XSUM_WIN32_USE_WMAIN
# define XSUM_WIN32_USE_WMAIN 0
#else
/*
* Whether to use wmain() or main().
*
* wmain() is preferred because we don't have to mess with internal hidden
* APIs.
*
* It always works on MSVC, but in MinGW, it only works on MinGW-w64 with the
* -municode flag.
*
* Therefore we have to use main() -- there is no better option.
*/
# ifndef XSUM_WIN32_USE_WMAIN
# if defined(_UNICODE) || defined(UNICODE) /* MinGW -municode */ \
|| defined(_MSC_VER) /* MSVC */
# define XSUM_WIN32_USE_WMAIN 1
# else
# define XSUM_WIN32_USE_WMAIN 0
# endif
# endif
/*
* It is always good practice to define these to prevent accidental use of the
* ANSI APIs, even if the program primarily uses UTF-8.
*/
# ifndef _UNICODE
# define _UNICODE
# endif
# ifndef UNICODE
# define UNICODE
# endif
#endif /* XSUM_WIN32_USE_WCHAR */
#ifndef XSUM_API
# ifdef XXH_INLINE_ALL
# define XSUM_API static
# else
# define XSUM_API
# endif
#endif
#ifndef XSUM_NO_TESTS
# define XSUM_NO_TESTS 0
#endif
/* ***************************
* Basic types
* ***************************/
#if defined(__cplusplus) /* C++ */ \
|| (defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) /* C99 */
# include <stdint.h>
typedef uint8_t XSUM_U8;
typedef uint32_t XSUM_U32;
typedef uint64_t XSUM_U64;
# else
# include <limits.h>
typedef unsigned char XSUM_U8;
# if UINT_MAX == 0xFFFFFFFFUL
typedef unsigned int XSUM_U32;
# else
typedef unsigned long XSUM_U32;
# endif
typedef unsigned long long XSUM_U64;
#endif /* not C++/C99 */
/* ***************************
* Common constants
* ***************************/
#define KB *( 1<<10)
#define MB *( 1<<20)
#define GB *(1U<<30)
#endif /* XSUM_CONFIG_H */
/*
* xxhsum - Command line interface for xxhash algorithms
* Copyright (C) 2013-2021 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
#include "xsum_os_specific.h" /* XSUM_API */
#include <sys/stat.h> /* stat() / _stat64() */
/*
* This file contains all of the ugly boilerplate to make xxhsum work across
* platforms.
*/
#if defined(_MSC_VER) || XSUM_WIN32_USE_WCHAR
typedef struct __stat64 XSUM_stat_t;
# if defined(_MSC_VER)
typedef int mode_t;
# endif
#else
typedef struct stat XSUM_stat_t;
#endif
#if (defined(__linux__) && (XSUM_PLATFORM_POSIX_VERSION >= 1)) \
|| (XSUM_PLATFORM_POSIX_VERSION >= 200112L) \
|| defined(__DJGPP__) \
|| defined(__MSYS__) \
|| defined(__HAIKU__)
# include <unistd.h> /* isatty */
# define XSUM_IS_CONSOLE(stdStream) isatty(fileno(stdStream))
#elif defined(MSDOS) || defined(OS2)
# include <io.h> /* _isatty */
# define XSUM_IS_CONSOLE(stdStream) _isatty(_fileno(stdStream))
#elif defined(WIN32) || defined(_WIN32)
# include <io.h> /* _isatty */
# include <windows.h> /* DeviceIoControl, HANDLE, FSCTL_SET_SPARSE */
# include <stdio.h> /* FILE */
static __inline int XSUM_IS_CONSOLE(FILE* stdStream)
{
DWORD dummy;
return _isatty(_fileno(stdStream)) && GetConsoleMode((HANDLE)_get_osfhandle(_fileno(stdStream)), &dummy);
}
#else
# define XSUM_IS_CONSOLE(stdStream) 0
#endif
#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(_WIN32)
# include <fcntl.h> /* _O_BINARY */
# include <io.h> /* _setmode, _fileno, _get_osfhandle */
# if !defined(__DJGPP__)
# include <windows.h> /* DeviceIoControl, HANDLE, FSCTL_SET_SPARSE */
# include <winioctl.h> /* FSCTL_SET_SPARSE */
# define XSUM_SET_BINARY_MODE(file) { int const unused=_setmode(_fileno(file), _O_BINARY); (void)unused; }
# else
# define XSUM_SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
# endif
#else
# define XSUM_SET_BINARY_MODE(file) ((void)file)
#endif
XSUM_API int XSUM_isConsole(FILE* stream)
{
return XSUM_IS_CONSOLE(stream);
}
XSUM_API void XSUM_setBinaryMode(FILE* stream)
{
XSUM_SET_BINARY_MODE(stream);
}
#if !XSUM_WIN32_USE_WCHAR
XSUM_API FILE* XSUM_fopen(const char* filename, const char* mode)
{
return fopen(filename, mode);
}
XSUM_ATTRIBUTE((__format__(__printf__, 2, 0)))
XSUM_API int XSUM_vfprintf(FILE* stream, const char* format, va_list ap)
{
return vfprintf(stream, format, ap);
}
static int XSUM_stat(const char* infilename, XSUM_stat_t* statbuf)
{
#if defined(_MSC_VER)
return _stat64(infilename, statbuf);
#else
return stat(infilename, statbuf);
#endif
}
#ifndef XSUM_NO_MAIN
int main(int argc, const char* argv[])
{
return XSUM_main(argc, argv);
}
#endif
/* Unicode helpers for Windows to make UTF-8 act as it should. */
#else
# include <windows.h>
# include <wchar.h>
/*****************************************************************************
* Unicode conversion tools
*****************************************************************************/
/*
* Converts a UTF-8 string to UTF-16. Acts like strdup. The string must be freed afterwards.
* This version allows keeping the output length.
*/
static wchar_t* XSUM_widenString(const char* str, int* lenOut)
{
int const len = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
if (lenOut != NULL) *lenOut = len;
if (len == 0) return NULL;
{ wchar_t* buf = (wchar_t*)malloc((size_t)len * sizeof(wchar_t));
if (buf != NULL) {
if (MultiByteToWideChar(CP_UTF8, 0, str, -1, buf, len) == 0) {
free(buf);
return NULL;
} }
return buf;
}
}
/*
* Converts a UTF-16 string to UTF-8. Acts like strdup. The string must be freed afterwards.
* This version allows keeping the output length.
*/
static char* XSUM_narrowString(const wchar_t *str, int *lenOut)
{
int len = WideCharToMultiByte(CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
if (lenOut != NULL) *lenOut = len;
if (len == 0) return NULL;
{ char* const buf = (char*)malloc((size_t)len * sizeof(char));
if (buf != NULL) {
if (WideCharToMultiByte(CP_UTF8, 0, str, -1, buf, len, NULL, NULL) == 0) {
free(buf);
return NULL;
} }
return buf;
}
}
/*****************************************************************************
* File helpers
*****************************************************************************/
/*
* fopen wrapper that supports UTF-8
*
* fopen will only accept ANSI filenames, which means that we can't open Unicode filenames.
*
* In order to open a Unicode filename, we need to convert filenames to UTF-16 and use _wfopen.
*/
XSUM_API FILE* XSUM_fopen(const char* filename, const char* mode)
{
FILE* f = NULL;
wchar_t* const wide_filename = XSUM_widenString(filename, NULL);
if (wide_filename != NULL) {
wchar_t* const wide_mode = XSUM_widenString(mode, NULL);
if (wide_mode != NULL) {
f = _wfopen(wide_filename, wide_mode);
free(wide_mode);
}
free(wide_filename);
}
return f;
}
/*
* stat() wrapper which supports UTF-8 filenames.
*/
static int XSUM_stat(const char* infilename, XSUM_stat_t* statbuf)
{
int r = -1;
wchar_t* const wide_filename = XSUM_widenString(infilename, NULL);
if (wide_filename != NULL) {
r = _wstat64(wide_filename, statbuf);
free(wide_filename);
}
return r;
}
/*
* In case it isn't available, this is what MSVC 2019 defines in stdarg.h.
*/
#if defined(_MSC_VER) && !defined(__clang__) && !defined(va_copy)
# define XSUM_va_copy(destination, source) ((destination) = (source))
#else
# define XSUM_va_copy(destination, source) va_copy(destination, source)
#endif
/*
* vasprintf for Windows.
*/
XSUM_ATTRIBUTE((__format__(__printf__, 2, 0)))
static int XSUM_vasprintf(char** strp, const char* format, va_list ap)
{
int size;
va_list copy;
/*
* To be safe, make a va_copy.
*
* Note that Microsoft doesn't use va_copy in its sample code:
* https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/vsprintf-vsprintf-l-vswprintf-vswprintf-l-vswprintf-l?view=vs-2019
*/
XSUM_va_copy(copy, ap);
/* Calculate how many characters we need */
size = _vscprintf(format, ap);
va_end(copy);
if (size < 0) {
*strp = NULL;
return size;
} else {
int ret;
*strp = (char*) malloc((size_t)size + 1);
if (*strp == NULL) {
return -1;
}
/* vsprintf into the new buffer */
ret = vsprintf(*strp, format, ap);
if (ret < 0) {
free(*strp);
*strp = NULL;
}
return ret;
}
}
/*
* fprintf wrapper that supports UTF-8.
*
* fprintf doesn't properly handle Unicode on Windows.
*
* Additionally, it is codepage sensitive on console and may crash the program.
*
* Instead, we use vsnprintf, and either print with fwrite or convert to UTF-16
* for console output and use the codepage-independent WriteConsoleW.
*
* Credit to t-mat: https://github.com/t-mat/xxHash/commit/5691423
*/
XSUM_ATTRIBUTE((__format__(__printf__, 2, 0)))
XSUM_API int XSUM_vfprintf(FILE *stream, const char *format, va_list ap)
{
int result;
char* u8_str = NULL;
/*
* Generate the UTF-8 output string with vasprintf.
*/
result = XSUM_vasprintf(&u8_str, format, ap);
if (result >= 0) {
const size_t nchar = (size_t)result + 1;
/*
* Check if we are outputting to a console. Don't use XSUM_isConsole
* directly -- we don't need to call _get_osfhandle twice.
*/
int fileNb = _fileno(stream);
intptr_t handle_raw = _get_osfhandle(fileNb);
HANDLE handle = (HANDLE)handle_raw;
DWORD dwTemp;
if (handle_raw < 0) {
result = -1;
} else if (_isatty(fileNb) && GetConsoleMode(handle, &dwTemp)) {
/*
* Convert to UTF-16 and output with WriteConsoleW.
*
* This is codepage independent and works on Windows XP's default
* msvcrt.dll.
*/
int len;
wchar_t* const u16_buf = XSUM_widenString(u8_str, &len);
if (u16_buf == NULL) {
result = -1;
} else {
if (WriteConsoleW(handle, u16_buf, (DWORD)len - 1, &dwTemp, NULL)) {
result = (int)dwTemp;
} else {
result = -1;
}
free(u16_buf);
}
} else {
/* fwrite the UTF-8 string if we are printing to a file */
result = (int)fwrite(u8_str, 1, nchar - 1, stream);
if (result == 0) {
result = -1;
}
}
free(u8_str);
}
return result;
}
#ifndef XSUM_NO_MAIN
/*****************************************************************************
* Command Line argument parsing
*****************************************************************************/
/* Converts a UTF-16 argv to UTF-8. */
static char** XSUM_convertArgv(int argc, wchar_t* utf16_argv[])
{
char** const utf8_argv = (char**)malloc((size_t)(argc + 1) * sizeof(char*));
if (utf8_argv != NULL) {
int i;
for (i = 0; i < argc; i++) {
utf8_argv[i] = XSUM_narrowString(utf16_argv[i], NULL);
if (utf8_argv[i] == NULL) {
/* Out of memory, whoops. */
while (i-- > 0) {
free(utf8_argv[i]);
}
free(utf8_argv);
return NULL;
}
}
utf8_argv[argc] = NULL;
}
return utf8_argv;
}
/* Frees arguments returned by XSUM_convertArgv */
static void XSUM_freeArgv(int argc, char** argv)
{
int i;
if (argv == NULL) {
return;
}
for (i = 0; i < argc; i++) {
free(argv[i]);
}
free(argv);
}
static int XSUM_wmain(int argc, wchar_t* utf16_argv[])
{
/* Convert the UTF-16 arguments to UTF-8. */
char** utf8_argv = XSUM_convertArgv(argc, utf16_argv);
if (utf8_argv == NULL) {
/* An unfortunate but incredibly unlikely error. */
fprintf(stderr, "xxhsum: error converting command line arguments!\n");
abort();
} else {
int ret;
/*
* MinGW's terminal uses full block buffering for stderr.
*
* This is nonstandard behavior and causes text to not display until
* the buffer fills.
*
* `setvbuf()` can easily correct this to make text display instantly.
*/
setvbuf(stderr, NULL, _IONBF, 0);
/* Call our real main function */
ret = XSUM_main(argc, (void*)utf8_argv);
/* Cleanup */
XSUM_freeArgv(argc, utf8_argv);
return ret;
}
}
#if XSUM_WIN32_USE_WMAIN
/*
* The preferred method of obtaining the real UTF-16 arguments. Always works
* on MSVC, sometimes works on MinGW-w64 depending on the compiler flags.
*/
#ifdef __cplusplus
extern "C"
#endif
int __cdecl wmain(int argc, wchar_t* utf16_argv[])
{
return XSUM_wmain(argc, utf16_argv);
}
#else /* !XSUM_WIN32_USE_WMAIN */
/*
* Wrap `XSUM_wmain()` using `main()` and `__wgetmainargs()` on MinGW without
* Unicode support.
*
* `__wgetmainargs()` is used in the CRT startup to retrieve the arguments for
* `wmain()`, so we use it on MinGW to emulate `wmain()`.
*
* It is an internal function and not declared in any public headers, so we
* have to declare it manually.
*
* An alternative that doesn't mess with internal APIs is `GetCommandLineW()`
* with `CommandLineToArgvW()`, but the former doesn't expand wildcards and the
* latter requires linking to Shell32.dll and its numerous dependencies.
*
* This method keeps our dependencies to kernel32.dll and the CRT.
*
* https://docs.microsoft.com/en-us/cpp/c-runtime-library/getmainargs-wgetmainargs?view=vs-2019
*/
typedef struct {
int newmode;
} _startupinfo;
#ifdef __cplusplus
extern "C"
#endif
int __cdecl __wgetmainargs(
int* Argc,
wchar_t*** Argv,
wchar_t*** Env,
int DoWildCard,
_startupinfo* StartInfo
);
int main(int ansi_argc, const char* ansi_argv[])
{
int utf16_argc;
wchar_t** utf16_argv;
wchar_t** utf16_envp; /* Unused but required */
_startupinfo startinfo = {0}; /* 0 == don't change new mode */
/* Get wmain's UTF-16 arguments. Make sure we expand wildcards. */
if (__wgetmainargs(&utf16_argc, &utf16_argv, &utf16_envp, 1, &startinfo) < 0)
/* In the very unlikely case of an error, use the ANSI arguments. */
return XSUM_main(ansi_argc, ansi_argv);
/* Call XSUM_wmain with our UTF-16 arguments */
return XSUM_wmain(utf16_argc, utf16_argv);
}
#endif /* !XSUM_WIN32_USE_WMAIN */
#endif /* !XSUM_NO_MAIN */
#endif /* XSUM_WIN32_USE_WCHAR */
/*
* Determines whether the file at filename is a directory.
*/
XSUM_API int XSUM_isDirectory(const char* filename)
{
XSUM_stat_t statbuf;
int r = XSUM_stat(filename, &statbuf);
#ifdef _MSC_VER
if (!r && (statbuf.st_mode & _S_IFDIR)) return 1;
#else
if (!r && S_ISDIR(statbuf.st_mode)) return 1;
#endif
return 0;
}
/*
* Returns the filesize of the file at filename.
*/
XSUM_API XSUM_U64 XSUM_getFileSize(const char* filename)
{
XSUM_stat_t statbuf;
int r = XSUM_stat(filename, &statbuf);
if (r || !S_ISREG(statbuf.st_mode)) return 0; /* No good... */
return (XSUM_U64)statbuf.st_size;
}
/*
* xxhsum - Command line interface for xxhash algorithms
* Copyright (C) 2013-2021 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
#ifndef XSUM_OS_SPECIFIC_H
#define XSUM_OS_SPECIFIC_H
#include "xsum_config.h"
#include <stdio.h>
#include <stdarg.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* Declared here to be implemented in user code.
*
* Functions like main(), but is passed UTF-8 arguments even on Windows.
*/
XSUM_API int XSUM_main(int argc, const char* argv[]);
/*
* Returns whether stream is a console.
*
* Functionally equivalent to isatty(fileno(stream)).
*/
XSUM_API int XSUM_isConsole(FILE* stream);
/*
* Sets stream to pure binary mode (a.k.a. no CRLF conversions).
*/
XSUM_API void XSUM_setBinaryMode(FILE* stream);
/*
* Returns whether the file at filename is a directory.
*/
XSUM_API int XSUM_isDirectory(const char* filename);
/*
* Returns the file size of the file at filename.
*/
XSUM_API XSUM_U64 XSUM_getFileSize(const char* filename);
/*
* UTF-8 stdio wrappers primarily for Windows
*/
/*
* fopen() wrapper. Accepts UTF-8 filenames on Windows.
*
* Specifically, on Windows, the arguments will be converted to UTF-16
* and passed to _wfopen().
*/
XSUM_API FILE* XSUM_fopen(const char* filename, const char* mode);
/*
* vfprintf() wrapper which prints UTF-8 strings to Windows consoles
* if applicable.
*/
XSUM_ATTRIBUTE((__format__(__printf__, 2, 0)))
XSUM_API int XSUM_vfprintf(FILE* stream, const char* format, va_list ap);
#ifdef __cplusplus
}
#endif
#endif /* XSUM_OS_SPECIFIC_H */
/*
* xxhsum - Command line interface for xxhash algorithms
* Copyright (C) 2013-2021 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
#include "xsum_output.h"
#include "xsum_os_specific.h" /* XSUM_API */
int XSUM_logLevel = 2;
XSUM_ATTRIBUTE((__format__(__printf__, 1, 2)))
XSUM_API int XSUM_log(const char* format, ...)
{
int ret;
va_list ap;
va_start(ap, format);
ret = XSUM_vfprintf(stderr, format, ap);
va_end(ap);
return ret;
}
XSUM_ATTRIBUTE((__format__(__printf__, 1, 2)))
XSUM_API int XSUM_output(const char* format, ...)
{
int ret;
va_list ap;
va_start(ap, format);
ret = XSUM_vfprintf(stdout, format, ap);
va_end(ap);
return ret;
}
XSUM_ATTRIBUTE((__format__(__printf__, 2, 3)))
XSUM_API int XSUM_logVerbose(int minLevel, const char* format, ...)
{
if (XSUM_logLevel >= minLevel) {
int ret;
va_list ap;
va_start(ap, format);
ret = XSUM_vfprintf(stderr, format, ap);
va_end(ap);
return ret;
}
return 0;
}
/*
* xxhsum - Command line interface for xxhash algorithms
* Copyright (C) 2013-2021 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
#ifndef XSUM_OUTPUT_H
#define XSUM_OUTPUT_H
#include "xsum_config.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* How verbose the output is.
*/
extern int XSUM_logLevel;
/*
* Same as fprintf(stderr, format, ...)
*/
XSUM_ATTRIBUTE((__format__(__printf__, 1, 2)))
XSUM_API int XSUM_log(const char *format, ...);
/*
* Like XSUM_log, but only outputs if XSUM_logLevel >= minLevel.
*/
XSUM_ATTRIBUTE((__format__(__printf__, 2, 3)))
XSUM_API int XSUM_logVerbose(int minLevel, const char *format, ...);
/*
* Same as printf(format, ...)
*/
XSUM_ATTRIBUTE((__format__(__printf__, 1, 2)))
XSUM_API int XSUM_output(const char *format, ...);
#ifdef __cplusplus
}
#endif
#endif /* XSUM_OUTPUT_H */
/*
* xxhsum - Command line interface for xxhash algorithms
* Copyright (C) 2013-2021 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
#include "xsum_sanity_check.h"
#include "xsum_output.h" /* XSUM_log */
#ifndef XXH_STATIC_LINKING_ONLY
# define XXH_STATIC_LINKING_ONLY
#endif
#include "../xxhash.h"
#include <stdlib.h> /* exit */
#include <assert.h>
#include <string.h> /* memcmp */
/* use #define to make them constant, required for initialization */
#define PRIME32 2654435761U
#define PRIME64 11400714785074694797ULL
/*
* Fills a test buffer with pseudorandom data.
*
* This is used in the sanity check - its values must not be changed.
*/
XSUM_API void XSUM_fillTestBuffer(XSUM_U8* buffer, size_t len)
{
XSUM_U64 byteGen = PRIME32;
size_t i;
assert(buffer != NULL);
for (i=0; i<len; i++) {
buffer[i] = (XSUM_U8)(byteGen>>56);
byteGen *= PRIME64;
}
}
/* ************************************************
* Self-test:
* ensure results consistency across platforms
*********************************************** */
#if XSUM_NO_TESTS
XSUM_API void XSUM_sanityCheck(void)
{
XSUM_log("This version of xxhsum is not verified.\n");
}
#else
/*
* Test data vectors
*/
typedef struct {
XSUM_U32 len;
XSUM_U32 seed;
XSUM_U32 Nresult;
} XSUM_testdata32_t;
typedef struct {
XSUM_U32 len;
XSUM_U64 seed;
XSUM_U64 Nresult;
} XSUM_testdata64_t;
typedef struct {
XSUM_U32 len;
XSUM_U64 seed;
XXH128_hash_t Nresult;
} XSUM_testdata128_t;
#define SECRET_SAMPLE_NBBYTES 5
typedef struct {
XSUM_U32 seedLen;
XSUM_U32 secretLen;
XSUM_U8 byte[SECRET_SAMPLE_NBBYTES];
} XSUM_testdata_sample_t;
/* XXH32 */
static const XSUM_testdata32_t XSUM_XXH32_testdata[] = {
{ 0, 0, 0x02CC5D05U },
{ 0, PRIME32, 0x36B78AE7U },
{ 1, 0, 0xCF65B03EU },
{ 1, PRIME32, 0xB4545AA4U },
{ 14, 0, 0x1208E7E2U },
{ 14, PRIME32, 0x6AF1D1FEU },
{ 222, 0, 0x5BD11DBDU },
{ 222, PRIME32, 0x58803C5FU }
};
/* XXH64 */
static const XSUM_testdata64_t XSUM_XXH64_testdata[] = {
{ 0, 0, 0xEF46DB3751D8E999ULL },
{ 0, PRIME32, 0xAC75FDA2929B17EFULL },
{ 1, 0, 0xE934A84ADB052768ULL },
{ 1, PRIME32, 0x5014607643A9B4C3ULL },
{ 4, 0, 0x9136A0DCA57457EEULL },
{ 14, 0, 0x8282DCC4994E35C8ULL },
{ 14, PRIME32, 0xC3BD6BF63DEB6DF0ULL },
{ 222, 0, 0xB641AE8CB691C174ULL },
{ 222, PRIME32, 0x20CB8AB7AE10C14AULL }
};
/*
* XXH3:
* Due to being a more complex hash function with specializations for certain
* lengths, a more extensive test is used for XXH3.
*/
/* XXH3_64bits, seeded */
static const XSUM_testdata64_t XSUM_XXH3_testdata[] = {
{ 0, 0, 0x2D06800538D394C2ULL }, /* empty string */
{ 0, PRIME64, 0xA8A6B918B2F0364AULL },
{ 1, 0, 0xC44BDFF4074EECDBULL }, /* 1 - 3 */
{ 1, PRIME64, 0x032BE332DD766EF8ULL },
{ 6, 0, 0x27B56A84CD2D7325ULL }, /* 4 - 8 */
{ 6, PRIME64, 0x84589C116AB59AB9ULL },
{ 12, 0, 0xA713DAF0DFBB77E7ULL }, /* 9 - 16 */
{ 12, PRIME64, 0xE7303E1B2336DE0EULL },
{ 24, 0, 0xA3FE70BF9D3510EBULL }, /* 17 - 32 */
{ 24, PRIME64, 0x850E80FC35BDD690ULL },
{ 48, 0, 0x397DA259ECBA1F11ULL }, /* 33 - 64 */
{ 48, PRIME64, 0xADC2CBAA44ACC616ULL },
{ 80, 0, 0xBCDEFBBB2C47C90AULL }, /* 65 - 96 */
{ 80, PRIME64, 0xC6DD0CB699532E73ULL },
{ 195, 0, 0xCD94217EE362EC3AULL }, /* 129-240 */
{ 195, PRIME64, 0xBA68003D370CB3D9ULL },
{ 403, 0, 0xCDEB804D65C6DEA4ULL }, /* one block, last stripe is overlapping */
{ 403, PRIME64, 0x6259F6ECFD6443FDULL },
{ 512, 0, 0x617E49599013CB6BULL }, /* one block, finishing at stripe boundary */
{ 512, PRIME64, 0x3CE457DE14C27708ULL },
{ 2048, 0, 0xDD59E2C3A5F038E0ULL }, /* 2 blocks, finishing at block boundary */
{ 2048, PRIME64, 0x66F81670669ABABCULL },
{ 2099, 0, 0xC6B9D9B3FC9AC765ULL }, /* 2 blocks + 1 partial block, to detect off-by-one scrambling issues, like #816 */
{ 2099, PRIME64, 0x184F316843663974ULL },
{ 2240, 0, 0x6E73A90539CF2948ULL }, /* 3 blocks, finishing at stripe boundary */
{ 2240, PRIME64, 0x757BA8487D1B5247ULL },
{ 2367, 0, 0xCB37AEB9E5D361EDULL }, /* 3 blocks, last stripe is overlapping */
{ 2367, PRIME64, 0xD2DB3415B942B42AULL }
};
/* XXH3_64bits, custom secret */
static const XSUM_testdata64_t XSUM_XXH3_withSecret_testdata[] = {
{ 0, 0, 0x3559D64878C5C66CULL }, /* empty string */
{ 1, 0, 0x8A52451418B2DA4DULL }, /* 1 - 3 */
{ 6, 0, 0x82C90AB0519369ADULL }, /* 4 - 8 */
{ 12, 0, 0x14631E773B78EC57ULL }, /* 9 - 16 */
{ 24, 0, 0xCDD5542E4A9D9FE8ULL }, /* 17 - 32 */
{ 48, 0, 0x33ABD54D094B2534ULL }, /* 33 - 64 */
{ 80, 0, 0xE687BA1684965297ULL }, /* 65 - 96 */
{ 195, 0, 0xA057273F5EECFB20ULL }, /* 129-240 */
{ 403, 0, 0x14546019124D43B8ULL }, /* one block, last stripe is overlapping */
{ 512, 0, 0x7564693DD526E28DULL }, /* one block, finishing at stripe boundary */
{ 2048, 0, 0xD32E975821D6519FULL }, /* >= 2 blodcks, at least one scrambling */
{ 2367, 0, 0x293FA8E5173BB5E7ULL }, /* >= 2 blocks, at least one scrambling, last stripe unaligned */
{ 64*10*3, 0, 0x751D2EC54BC6038BULL } /* exactly 3 full blocks, not a multiple of 256 */
};
/* XXH3_128bits, seeded */
static const XSUM_testdata128_t XSUM_XXH128_testdata[] = {
{ 0, 0, { 0x6001C324468D497FULL, 0x99AA06D3014798D8ULL } }, /* empty string */
{ 0, PRIME32, { 0x5444F7869C671AB0ULL, 0x92220AE55E14AB50ULL } },
{ 1, 0, { 0xC44BDFF4074EECDBULL, 0xA6CD5E9392000F6AULL } }, /* 1 - 3 */
{ 1, PRIME32, { 0xB53D5557E7F76F8DULL, 0x89B99554BA22467CULL } },
{ 6, 0, { 0x3E7039BDDA43CFC6ULL, 0x082AFE0B8162D12AULL } }, /* 4 - 8 */
{ 6, PRIME32, { 0x269D8F70BE98856EULL, 0x5A865B5389ABD2B1ULL } },
{ 12, 0, { 0x061A192713F69AD9ULL, 0x6E3EFD8FC7802B18ULL } }, /* 9 - 16 */
{ 12, PRIME32, { 0x9BE9F9A67F3C7DFBULL, 0xD7E09D518A3405D3ULL } },
{ 24, 0, { 0x1E7044D28B1B901DULL, 0x0CE966E4678D3761ULL } }, /* 17 - 32 */
{ 24, PRIME32, { 0xD7304C54EBAD40A9ULL, 0x3162026714A6A243ULL } },
{ 48, 0, { 0xF942219AED80F67BULL, 0xA002AC4E5478227EULL } }, /* 33 - 64 */
{ 48, PRIME32, { 0x7BA3C3E453A1934EULL, 0x163ADDE36C072295ULL } },
{ 81, 0, { 0x5E8BAFB9F95FB803ULL, 0x4952F58181AB0042ULL } }, /* 65 - 96 */
{ 81, PRIME32, { 0x703FBB3D7A5F755CULL, 0x2724EC7ADC750FB6ULL } },
{ 222, 0, { 0xF1AEBD597CEC6B3AULL, 0x337E09641B948717ULL } }, /* 129-240 */
{ 222, PRIME32, { 0xAE995BB8AF917A8DULL, 0x91820016621E97F1ULL } },
{ 403, 0, { 0xCDEB804D65C6DEA4ULL, 0x1B6DE21E332DD73DULL } }, /* one block, last stripe is overlapping */
{ 403, PRIME64, { 0x6259F6ECFD6443FDULL, 0xBED311971E0BE8F2ULL } },
{ 512, 0, { 0x617E49599013CB6BULL, 0x18D2D110DCC9BCA1ULL } }, /* one block, finishing at stripe boundary */
{ 512, PRIME64, { 0x3CE457DE14C27708ULL, 0x925D06B8EC5B8040ULL } },
{ 2048, 0, { 0xDD59E2C3A5F038E0ULL, 0xF736557FD47073A5ULL } }, /* 2 blocks, finishing at block boundary */
{ 2048, PRIME32, { 0x230D43F30206260BULL, 0x7FB03F7E7186C3EAULL } },
{ 2240, 0, { 0x6E73A90539CF2948ULL, 0xCCB134FBFA7CE49DULL } }, /* 3 blocks, finishing at stripe boundary */
{ 2240, PRIME32, { 0xED385111126FBA6FULL, 0x50A1FE17B338995FULL } },
{ 2367, 0, { 0xCB37AEB9E5D361EDULL, 0xE89C0F6FF369B427ULL } }, /* 3 blocks, last stripe is overlapping */
{ 2367, PRIME32, { 0x6F5360AE69C2F406ULL, 0xD23AAE4B76C31ECBULL } }
};
/* XXH128, custom secret */
static const XSUM_testdata128_t XSUM_XXH128_withSecret_testdata[] = {
{ 0, 0, { 0x005923CCEECBE8AEULL, 0x5F70F4EA232F1D38ULL } }, /* empty string */
{ 1, 0, { 0x8A52451418B2DA4DULL, 0x3A66AF5A9819198EULL } }, /* 1 - 3 */
{ 6, 0, { 0x0B61C8ACA7D4778FULL, 0x376BD91B6432F36DULL } }, /* 4 - 8 */
{ 12, 0, { 0xAF82F6EBA263D7D8ULL, 0x90A3C2D839F57D0FULL } } /* 9 - 16 */
};
#define SECRET_SIZE_MAX 9867
static const XSUM_testdata_sample_t XSUM_XXH3_generateSecret_testdata[] = {
{ 0, 192, { 0xE7, 0x8C, 0x77, 0x77, 0x00 } },
{ 1, 240, { 0x2B, 0x3E, 0xDE, 0xC1, 0x00 } },
{ XXH3_SECRET_SIZE_MIN - 1, 277, { 0xE8, 0x39, 0x6C, 0xCC, 0x7B } },
{ XXH3_SECRET_DEFAULT_SIZE + 500, SECRET_SIZE_MAX, { 0xD6, 0x1C, 0x41, 0x17, 0xB3 } }
};
static void XSUM_checkResult32(XXH32_hash_t r1, XXH32_hash_t r2)
{
static int nbTests = 1;
if (r1!=r2) {
XSUM_log("\rError: 32-bit hash test %i: Internal sanity check failed!\n", nbTests);
XSUM_log("\rGot 0x%08X, expected 0x%08X.\n", (unsigned)r1, (unsigned)r2);
XSUM_log("\rNote: If you modified the hash functions, make sure to either update the values\n"
"or temporarily recompile with XSUM_NO_TESTS=1.\n");
exit(1);
}
nbTests++;
}
static void XSUM_checkResult64(XXH64_hash_t r1, XXH64_hash_t r2)
{
static int nbTests = 1;
if (r1!=r2) {
XSUM_log("\rError: 64-bit hash test %i: Internal sanity check failed!\n", nbTests);
XSUM_log("\rGot 0x%08X%08XULL, expected 0x%08X%08XULL.\n",
(unsigned)(r1>>32), (unsigned)r1, (unsigned)(r2>>32), (unsigned)r2);
XSUM_log("\rNote: If you modified the hash functions, make sure to either update the values\n"
"or temporarily recompile with XSUM_NO_TESTS=1.\n");
exit(1);
}
nbTests++;
}
static void XSUM_checkResult128(XXH128_hash_t r1, XXH128_hash_t r2)
{
static int nbTests = 1;
if ((r1.low64 != r2.low64) || (r1.high64 != r2.high64)) {
XSUM_log("\rError: 128-bit hash test %i: Internal sanity check failed.\n", nbTests);
XSUM_log("\rGot { 0x%08X%08XULL, 0x%08X%08XULL }, expected { 0x%08X%08XULL, 0x%08X%08XULL } \n",
(unsigned)(r1.low64>>32), (unsigned)r1.low64, (unsigned)(r1.high64>>32), (unsigned)r1.high64,
(unsigned)(r2.low64>>32), (unsigned)r2.low64, (unsigned)(r2.high64>>32), (unsigned)r2.high64 );
XSUM_log("\rNote: If you modified the hash functions, make sure to either update the values\n"
"or temporarily recompile with XSUM_NO_TESTS=1.\n");
exit(1);
}
nbTests++;
}
static void XSUM_testXXH32(const void* data, const XSUM_testdata32_t* testData)
{
XXH32_state_t *state = XXH32_createState();
size_t pos;
size_t len = testData->len;
XSUM_U32 seed = testData->seed;
XSUM_U32 Nresult = testData->Nresult;
if (len == 0) {
data = NULL;
} else {
assert(data != NULL);
}
assert(state != NULL);
XSUM_checkResult32(XXH32(data, len, seed), Nresult);
(void)XXH32_reset(state, seed);
(void)XXH32_update(state, data, len);
XSUM_checkResult32(XXH32_digest(state), Nresult);
(void)XXH32_reset(state, seed);
for (pos=0; pos<len; pos++)
(void)XXH32_update(state, ((const char*)data)+pos, 1);
XSUM_checkResult32(XXH32_digest(state), Nresult);
XXH32_freeState(state);
}
static void XSUM_testXXH64(const void* data, const XSUM_testdata64_t* testData)
{
XXH64_state_t *state = XXH64_createState();
size_t pos;
size_t len = (size_t)testData->len;
XSUM_U64 seed = testData->seed;
XSUM_U64 Nresult = testData->Nresult;
if (len == 0) {
data = NULL;
} else {
assert(data != NULL);
}
assert(state != NULL);
XSUM_checkResult64(XXH64(data, len, seed), Nresult);
(void)XXH64_reset(state, seed);
(void)XXH64_update(state, data, len);
XSUM_checkResult64(XXH64_digest(state), Nresult);
(void)XXH64_reset(state, seed);
for (pos=0; pos<len; pos++)
(void)XXH64_update(state, ((const char*)data)+pos, 1);
XSUM_checkResult64(XXH64_digest(state), Nresult);
XXH64_freeState(state);
}
/*
* Used to get "random" (but actually 100% reproducible) lengths for
* XSUM_XXH3_randomUpdate.
*/
static XSUM_U32 XSUM_rand(void)
{
static XSUM_U64 seed = PRIME32;
seed *= PRIME64;
return (XSUM_U32)(seed >> 40);
}
/*
* Technically, XXH3_64bits_update is identical to XXH3_128bits_update as of
* v0.8.0, but we treat them as separate.
*/
typedef XXH_errorcode (*XSUM_XXH3_update_t)(XXH3_state_t* state, const void* input, size_t length);
/*
* Runs the passed XXH3_update variant on random lengths. This is to test the
* more complex logic of the update function, catching bugs like this one:
* https://github.com/Cyan4973/xxHash/issues/378
*/
static void XSUM_XXH3_randomUpdate(XXH3_state_t* state, const void* data,
size_t len, XSUM_XXH3_update_t update_fn)
{
size_t p = 0;
while (p < len) {
size_t const modulo = len > 2 ? len : 2;
size_t l = (size_t)(XSUM_rand()) % modulo;
if (p + l > len) l = len - p;
(void)update_fn(state, (const char*)data+p, l);
p += l;
}
}
static void XSUM_testXXH3(const void* data, const XSUM_testdata64_t* testData)
{
size_t len = testData->len;
XSUM_U64 seed = testData->seed;
XSUM_U64 Nresult = testData->Nresult;
if (len == 0) {
data = NULL;
} else {
assert(data != NULL);
}
{ XSUM_U64 const Dresult = XXH3_64bits_withSeed(data, len, seed);
XSUM_checkResult64(Dresult, Nresult);
}
/* check that the no-seed variant produces same result as seed==0 */
if (seed == 0) {
XSUM_U64 const Dresult = XXH3_64bits(data, len);
XSUM_checkResult64(Dresult, Nresult);
}
/* check that the combination of
* XXH3_generateSecret_fromSeed() and XXH3_64bits_withSecretandSeed()
* results in exactly the same hash generation as XXH3_64bits_withSeed() */
{ char secretBuffer[XXH3_SECRET_DEFAULT_SIZE+1];
char* const secret = secretBuffer + 1; /* intentional unalignment */
XXH3_generateSecret_fromSeed(secret, seed);
{ XSUM_U64 const Dresult = XXH3_64bits_withSecretandSeed(data, len, secret, XXH3_SECRET_DEFAULT_SIZE, seed);
XSUM_checkResult64(Dresult, Nresult);
} }
/* streaming API test */
{ XXH3_state_t* const state = XXH3_createState();
assert(state != NULL);
/* single ingestion */
(void)XXH3_64bits_reset_withSeed(state, seed);
(void)XXH3_64bits_update(state, data, len);
XSUM_checkResult64(XXH3_64bits_digest(state), Nresult);
/* random ingestion */
(void)XXH3_64bits_reset_withSeed(state, seed);
XSUM_XXH3_randomUpdate(state, data, len, &XXH3_64bits_update);
XSUM_checkResult64(XXH3_64bits_digest(state), Nresult);
/* byte by byte ingestion */
{ size_t pos;
(void)XXH3_64bits_reset_withSeed(state, seed);
for (pos=0; pos<len; pos++)
(void)XXH3_64bits_update(state, ((const char*)data)+pos, 1);
XSUM_checkResult64(XXH3_64bits_digest(state), Nresult);
}
/* check that streaming with a combination of
* XXH3_generateSecret_fromSeed() and XXH3_64bits_reset_withSecretandSeed()
* results in exactly the same hash generation as XXH3_64bits_reset_withSeed() */
{ char secretBuffer[XXH3_SECRET_DEFAULT_SIZE+1];
char* const secret = secretBuffer + 1; /* intentional unalignment */
XXH3_generateSecret_fromSeed(secret, seed);
/* single ingestion */
(void)XXH3_64bits_reset_withSecretandSeed(state, secret, XXH3_SECRET_DEFAULT_SIZE, seed);
(void)XXH3_64bits_update(state, data, len);
XSUM_checkResult64(XXH3_64bits_digest(state), Nresult);
}
XXH3_freeState(state);
}
}
#ifndef XXH3_MIDSIZE_MAX
# define XXH3_MIDSIZE_MAX 240
#endif
static void XSUM_testXXH3_withSecret(const void* data, const void* secret,
size_t secretSize, const XSUM_testdata64_t* testData)
{
size_t len = (size_t)testData->len;
XSUM_U64 Nresult = testData->Nresult;
if (len == 0) {
data = NULL;
} else {
assert(data != NULL);
}
{ XSUM_U64 const Dresult = XXH3_64bits_withSecret(data, len, secret, secretSize);
XSUM_checkResult64(Dresult, Nresult);
}
/* check that XXH3_64bits_withSecretandSeed()
* results in exactly the same return value as XXH3_64bits_withSecret() */
if (len > XXH3_MIDSIZE_MAX)
{ XSUM_U64 const Dresult = XXH3_64bits_withSecretandSeed(data, len, secret, secretSize, 0);
XSUM_checkResult64(Dresult, Nresult);
}
/* streaming API test */
{ XXH3_state_t *state = XXH3_createState();
assert(state != NULL);
(void)XXH3_64bits_reset_withSecret(state, secret, secretSize);
(void)XXH3_64bits_update(state, data, len);
XSUM_checkResult64(XXH3_64bits_digest(state), Nresult);
/* random ingestion */
(void)XXH3_64bits_reset_withSecret(state, secret, secretSize);
XSUM_XXH3_randomUpdate(state, data, len, &XXH3_64bits_update);
XSUM_checkResult64(XXH3_64bits_digest(state), Nresult);
/* byte by byte ingestion */
{ size_t pos;
(void)XXH3_64bits_reset_withSecret(state, secret, secretSize);
for (pos=0; pos<len; pos++)
(void)XXH3_64bits_update(state, ((const char*)data)+pos, 1);
XSUM_checkResult64(XXH3_64bits_digest(state), Nresult);
}
/* check that XXH3_64bits_reset_withSecretandSeed()
* results in exactly the same return value as XXH3_64bits_reset_withSecret() */
if (len > XXH3_MIDSIZE_MAX) {
/* single ingestion */
(void)XXH3_64bits_reset_withSecretandSeed(state, secret, secretSize, 0);
(void)XXH3_64bits_update(state, data, len);
XSUM_checkResult64(XXH3_64bits_digest(state), Nresult);
}
XXH3_freeState(state);
}
}
static void XSUM_testXXH128(const void* data, const XSUM_testdata128_t* testData)
{
size_t len = (size_t)testData->len;
XSUM_U64 seed = testData->seed;
XXH128_hash_t const Nresult = testData->Nresult;
if (len == 0) {
data = NULL;
} else {
assert(data != NULL);
}
{ XXH128_hash_t const Dresult = XXH3_128bits_withSeed(data, len, seed);
XSUM_checkResult128(Dresult, Nresult);
}
/* check that XXH128() is identical to XXH3_128bits_withSeed() */
{ XXH128_hash_t const Dresult2 = XXH128(data, len, seed);
XSUM_checkResult128(Dresult2, Nresult);
}
/* check that the no-seed variant produces same result as seed==0 */
if (seed == 0) {
XXH128_hash_t const Dresult = XXH3_128bits(data, len);
XSUM_checkResult128(Dresult, Nresult);
}
/* check that the combination of
* XXH3_generateSecret_fromSeed() and XXH3_128bits_withSecretandSeed()
* results in exactly the same hash generation as XXH3_64bits_withSeed() */
{ char secretBuffer[XXH3_SECRET_DEFAULT_SIZE+1];
char* const secret = secretBuffer + 1; /* intentional unalignment */
XXH3_generateSecret_fromSeed(secret, seed);
{ XXH128_hash_t const Dresult = XXH3_128bits_withSecretandSeed(data, len, secret, XXH3_SECRET_DEFAULT_SIZE, seed);
XSUM_checkResult128(Dresult, Nresult);
} }
/* streaming API test */
{ XXH3_state_t *state = XXH3_createState();
assert(state != NULL);
/* single ingestion */
(void)XXH3_128bits_reset_withSeed(state, seed);
(void)XXH3_128bits_update(state, data, len);
XSUM_checkResult128(XXH3_128bits_digest(state), Nresult);
/* random ingestion */
(void)XXH3_128bits_reset_withSeed(state, seed);
XSUM_XXH3_randomUpdate(state, data, len, &XXH3_128bits_update);
XSUM_checkResult128(XXH3_128bits_digest(state), Nresult);
/* byte by byte ingestion */
{ size_t pos;
(void)XXH3_128bits_reset_withSeed(state, seed);
for (pos=0; pos<len; pos++)
(void)XXH3_128bits_update(state, ((const char*)data)+pos, 1);
XSUM_checkResult128(XXH3_128bits_digest(state), Nresult);
}
/* check that streaming with a combination of
* XXH3_generateSecret_fromSeed() and XXH3_128bits_reset_withSecretandSeed()
* results in exactly the same hash generation as XXH3_128bits_reset_withSeed() */
{ char secretBuffer[XXH3_SECRET_DEFAULT_SIZE+1];
char* const secret = secretBuffer + 1; /* intentional unalignment */
XXH3_generateSecret_fromSeed(secret, seed);
/* single ingestion */
(void)XXH3_128bits_reset_withSecretandSeed(state, secret, XXH3_SECRET_DEFAULT_SIZE, seed);
(void)XXH3_128bits_update(state, data, len);
XSUM_checkResult128(XXH3_128bits_digest(state), Nresult);
}
XXH3_freeState(state);
}
}
static void XSUM_testXXH128_withSecret(const void* data, const void* secret, size_t secretSize, const XSUM_testdata128_t* testData)
{
size_t len = testData->len;
XXH128_hash_t Nresult = testData->Nresult;
if (len == 0) {
data = NULL;
} else {
assert(data != NULL);
}
{ XXH128_hash_t const Dresult = XXH3_128bits_withSecret(data, len, secret, secretSize);
XSUM_checkResult128(Dresult, Nresult);
}
/* check that XXH3_128bits_withSecretandSeed()
* results in exactly the same return value as XXH3_128bits_withSecret() */
if (len > XXH3_MIDSIZE_MAX)
{ XXH128_hash_t const Dresult = XXH3_128bits_withSecretandSeed(data, len, secret, secretSize, 0);
XSUM_checkResult128(Dresult, Nresult);
}
/* streaming API test */
{ XXH3_state_t* const state = XXH3_createState();
assert(state != NULL);
(void)XXH3_128bits_reset_withSecret(state, secret, secretSize);
(void)XXH3_128bits_update(state, data, len);
XSUM_checkResult128(XXH3_128bits_digest(state), Nresult);
/* random ingestion */
(void)XXH3_128bits_reset_withSecret(state, secret, secretSize);
XSUM_XXH3_randomUpdate(state, data, len, &XXH3_128bits_update);
XSUM_checkResult128(XXH3_128bits_digest(state), Nresult);
/* byte by byte ingestion */
{ size_t pos;
(void)XXH3_128bits_reset_withSecret(state, secret, secretSize);
for (pos=0; pos<len; pos++)
(void)XXH3_128bits_update(state, ((const char*)data)+pos, 1);
XSUM_checkResult128(XXH3_128bits_digest(state), Nresult);
}
/* check that XXH3_128bits_reset_withSecretandSeed()
* results in exactly the same return value as XXH3_128bits_reset_withSecret() */
if (len > XXH3_MIDSIZE_MAX) {
/* single ingestion */
(void)XXH3_128bits_reset_withSecretandSeed(state, secret, secretSize, 0);
(void)XXH3_128bits_update(state, data, len);
XSUM_checkResult128(XXH3_128bits_digest(state), Nresult);
}
XXH3_freeState(state);
}
}
static void XSUM_testSecretGenerator(const void* customSeed, const XSUM_testdata_sample_t* testData)
{
static int nbTests = 1;
const int sampleIndex[SECRET_SAMPLE_NBBYTES] = { 0, 62, 131, 191, 241 }; /* position of sampled bytes */
XSUM_U8 secretBuffer[SECRET_SIZE_MAX] = {0};
XSUM_U8 samples[SECRET_SAMPLE_NBBYTES];
int i;
assert(testData->secretLen <= SECRET_SIZE_MAX);
XXH3_generateSecret(secretBuffer, testData->secretLen, customSeed, testData->seedLen);
for (i=0; i<SECRET_SAMPLE_NBBYTES; i++) {
samples[i] = secretBuffer[sampleIndex[i]];
}
if (memcmp(samples, testData->byte, sizeof(testData->byte))) {
XSUM_log("\rError: Secret generation test %i: Internal sanity check failed. \n", nbTests);
XSUM_log("\rGot { 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X }, expected { 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X } \n",
samples[0], samples[1], samples[2], samples[3], samples[4],
testData->byte[0], testData->byte[1], testData->byte[2], testData->byte[3], testData->byte[4] );
exit(1);
}
nbTests++;
}
/*!
* XSUM_sanityCheck():
* Runs a sanity check before the benchmark.
*
* Exits on an incorrect output.
*/
XSUM_API void XSUM_sanityCheck(void)
{
size_t i;
#define SANITY_BUFFER_SIZE 2367
XSUM_U8 sanityBuffer[SANITY_BUFFER_SIZE];
const void* const secret = sanityBuffer + 7;
const size_t secretSize = XXH3_SECRET_SIZE_MIN + 11;
assert(sizeof(sanityBuffer) >= 7 + secretSize);
XSUM_fillTestBuffer(sanityBuffer, sizeof(sanityBuffer));
/* XXH32 */
for (i = 0; i < (sizeof(XSUM_XXH32_testdata)/sizeof(XSUM_XXH32_testdata[0])); i++) {
XSUM_testXXH32(sanityBuffer, &XSUM_XXH32_testdata[i]);
}
/* XXH64 */
for (i = 0; i < (sizeof(XSUM_XXH64_testdata)/sizeof(XSUM_XXH64_testdata[0])); i++) {
XSUM_testXXH64(sanityBuffer, &XSUM_XXH64_testdata[i]);
}
/* XXH3_64bits, seeded */
for (i = 0; i < (sizeof(XSUM_XXH3_testdata)/sizeof(XSUM_XXH3_testdata[0])); i++) {
XSUM_testXXH3(sanityBuffer, &XSUM_XXH3_testdata[i]);
}
/* XXH3_64bits, custom secret */
for (i = 0; i < (sizeof(XSUM_XXH3_withSecret_testdata)/sizeof(XSUM_XXH3_withSecret_testdata[0])); i++) {
XSUM_testXXH3_withSecret(sanityBuffer, secret, secretSize, &XSUM_XXH3_withSecret_testdata[i]);
}
/* XXH128 */
for (i = 0; i < (sizeof(XSUM_XXH128_testdata)/sizeof(XSUM_XXH128_testdata[0])); i++) {
XSUM_testXXH128(sanityBuffer, &XSUM_XXH128_testdata[i]);
}
/* XXH128 with custom Secret */
for (i = 0; i < (sizeof(XSUM_XXH128_withSecret_testdata)/sizeof(XSUM_XXH128_withSecret_testdata[0])); i++) {
XSUM_testXXH128_withSecret(sanityBuffer, secret, secretSize, &XSUM_XXH128_withSecret_testdata[i]);
}
/* secret generator */
for (i = 0; i < (sizeof(XSUM_XXH3_generateSecret_testdata)/sizeof(XSUM_XXH3_generateSecret_testdata[0])); i++) {
assert(XSUM_XXH3_generateSecret_testdata[i].seedLen <= SANITY_BUFFER_SIZE);
XSUM_testSecretGenerator(sanityBuffer, &XSUM_XXH3_generateSecret_testdata[i]);
}
XSUM_logVerbose(3, "\r%70s\r", ""); /* Clean display line */
XSUM_logVerbose(3, "Sanity check -- all tests ok\n");
}
#endif /* !XSUM_NO_TESTS */
/*
* xxhsum - Command line interface for xxhash algorithms
* Copyright (C) 2013-2021 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
#ifndef XSUM_SANITY_CHECK_H
#define XSUM_SANITY_CHECK_H
#include "xsum_config.h" /* XSUM_API, XSUM_U8 */
#include <stddef.h> /* size_t */
#ifdef __cplusplus
extern "C" {
#endif
/*
* Runs a series of self-tests.
*
* Exits if any of these tests fail, printing a message to stderr.
*
* If XSUM_NO_TESTS is defined to non-zero,
* this will instead print a warning if this is called (e.g. via xxhsum -b).
*/
XSUM_API void XSUM_sanityCheck(void);
/*
* Fills a test buffer with pseudorandom data.
*
* This is used in the sanity check and the benchmarks.
* Its values must not be changed.
*/
XSUM_API void XSUM_fillTestBuffer(XSUM_U8* buffer, size_t len);
#ifdef __cplusplus
}
#endif
#endif /* XSUM_SANITY_CHECK_H */
.TH "XXHSUM" "1" "December 2021" "xxhsum 0.8.1" "User Commands"
.SH "NAME"
\fBxxhsum\fR \- print or check xxHash non\-cryptographic checksums
.SH "SYNOPSIS"
\fBxxhsum [<OPTION>] \|\.\|\.\|\. [<FILE>] \|\.\|\.\|\.\fR \fBxxhsum \-b [<OPTION>] \|\.\|\.\|\.\fR
.P
\fBxxh32sum\fR is equivalent to \fBxxhsum \-H0\fR, \fBxxh64sum\fR is equivalent to \fBxxhsum \-H1\fR, \fBxxh128sum\fR is equivalent to \fBxxhsum \-H2\fR
.SH "DESCRIPTION"
Print or check xxHash (32, 64 or 128 bits) checksums\. When no \fIFILE\fR, read standard input, except if it\'s the console\. When \fIFILE\fR is \fB\-\fR, read standard input even if it\'s the console\.
.P
\fBxxhsum\fR supports a command line syntax similar but not identical to md5sum(1)\. Differences are: \fBxxhsum\fR doesn\'t have text/binary mode switch (\fB\-b\fR, \fB\-t\fR); \fBxxhsum\fR always treats files as binary file; \fBxxhsum\fR has a hash selection switch (\fB\-H\fR);
.P
As xxHash is a fast non\-cryptographic checksum algorithm, \fBxxhsum\fR should not be used for security related purposes\.
.P
\fBxxhsum \-b\fR invokes benchmark mode\. See \fIOPTIONS\fR and \fIEXAMPLES\fR for details\.
.SH "OPTIONS"
.TP
\fB\-V\fR, \fB\-\-version\fR
Displays xxhsum version and exits
.TP
\fB\-H\fR\fIHASHTYPE\fR
Hash selection\. \fIHASHTYPE\fR means \fB0\fR=XXH32, \fB1\fR=XXH64, \fB2\fR=XXH128, \fB3\fR=XXH3\. Note that \fB\-H3\fR triggers \fB\-\-tag\fR, which can\'t be skipped (this is to reduce risks of confusion with \fB\-H2\fR (\fBXXH64\fR))\. Alternatively, \fIHASHTYPE\fR \fB32\fR=XXH32, \fB64\fR=XXH64, \fB128\fR=XXH128\. Default value is \fB1\fR (64bits)
.TP
\fB\-\-tag\fR
Output in the BSD style\.
.TP
\fB\-\-little\-endian\fR
Set output hexadecimal checksum value as little endian convention\. By default, value is displayed as big endian\.
.TP
\fB\-h\fR, \fB\-\-help\fR
Displays help and exits
.P
\fBThe following four options are useful only when verifying checksums (\fB\-c\fR)\fR
.TP
\fB\-c\fR, \fB\-\-check\fR \fIFILE\fR
Read xxHash sums from \fIFILE\fR and check them
.TP
\fB\-q\fR, \fB\-\-quiet\fR
Don\'t print OK for each successfully verified file
.TP
\fB\-\-strict\fR
Return an error code if any line in the file is invalid, not just if some checksums are wrong\. This policy is disabled by default, though UI will prompt an informational message if any line in the file is detected invalid\.
.TP
\fB\-\-status\fR
Don\'t output anything\. Status code shows success\.
.TP
\fB\-w\fR, \fB\-\-warn\fR
Emit a warning message about each improperly formatted checksum line\.
.P
\fBThe following options are useful only benchmark purpose\fR
.TP
\fB\-b\fR
Benchmark mode\. See \fIEXAMPLES\fR for details\.
.TP
\fB\-b#\fR
Specify ID of variant to be tested\. Multiple variants can be selected, separated by a \',\' comma\.
.TP
\fB\-B\fR\fIBLOCKSIZE\fR
Only useful for benchmark mode (\fB\-b\fR)\. See \fIEXAMPLES\fR for details\. \fIBLOCKSIZE\fR specifies benchmark mode\'s test data block size in bytes\. Default value is 102400
.TP
\fB\-i\fR\fIITERATIONS\fR
Only useful for benchmark mode (\fB\-b\fR)\. See \fIEXAMPLES\fR for details\. \fIITERATIONS\fR specifies number of iterations in benchmark\. Single iteration lasts approximately 1000 milliseconds\. Default value is 3
.SH "EXIT STATUS"
\fBxxhsum\fR exit \fB0\fR on success, \fB1\fR if at least one file couldn\'t be read or doesn\'t have the same checksum as the \fB\-c\fR option\.
.SH "EXAMPLES"
Output xxHash (64bit) checksum values of specific files to standard output
.IP "" 4
.nf
$ xxhsum \-H1 foo bar baz
.fi
.IP "" 0
.P
Output xxHash (32bit and 64bit) checksum values of specific files to standard output, and redirect it to \fBxyz\.xxh32\fR and \fBqux\.xxh64\fR
.IP "" 4
.nf
$ xxhsum \-H0 foo bar baz > xyz\.xxh32
$ xxhsum \-H1 foo bar baz > qux\.xxh64
.fi
.IP "" 0
.P
Read xxHash sums from specific files and check them
.IP "" 4
.nf
$ xxhsum \-c xyz\.xxh32 qux\.xxh64
.fi
.IP "" 0
.P
Benchmark xxHash algorithm\. By default, \fBxxhsum\fR benchmarks xxHash main variants on a synthetic sample of 100 KB, and print results into standard output\. The first column is the algorithm, the second column is the source data size in bytes, the third column is the number of hashes generated per second (throughput), and finally the last column translates speed in megabytes per second\.
.IP "" 4
.nf
$ xxhsum \-b
.fi
.IP "" 0
.P
In the following example, the sample to hash is set to 16384 bytes, the variants to be benched are selected by their IDs, and each benchmark test is repeated 10 times, for increased accuracy\.
.IP "" 4
.nf
$ xxhsum \-b1,2,3 \-i10 \-B16384
.fi
.IP "" 0
.SH "BUGS"
Report bugs at: https://github\.com/Cyan4973/xxHash/issues/
.SH "AUTHOR"
Yann Collet
.SH "SEE ALSO"
md5sum(1)
xxhsum(1) -- print or check xxHash non-cryptographic checksums
==============================================================
SYNOPSIS
--------
`xxhsum [<OPTION>] ... [<FILE>] ...`
`xxhsum -b [<OPTION>] ...`
`xxh32sum` is equivalent to `xxhsum -H0`,
`xxh64sum` is equivalent to `xxhsum -H1`,
`xxh128sum` is equivalent to `xxhsum -H2`.
DESCRIPTION
-----------
Print or check xxHash (32, 64 or 128 bits) checksums.
When no <FILE>, read standard input, except if it's the console.
When <FILE> is `-`, read standard input even if it's the console.
`xxhsum` supports a command line syntax similar but not identical to md5sum(1).
Differences are:
`xxhsum` doesn't have text/binary mode switch (`-b`, `-t`);
`xxhsum` always treats files as binary file;
`xxhsum` has a hash selection switch (`-H`);
As xxHash is a fast non-cryptographic checksum algorithm,
`xxhsum` should not be used for security related purposes.
`xxhsum -b` invokes benchmark mode. See [OPTIONS](#OPTIONS) and [EXAMPLES](#EXAMPLES) for details.
OPTIONS
-------
* `-V`, `--version`:
Displays xxhsum version and exits
* `-H`<HASHTYPE>:
Hash selection. <HASHTYPE> means `0`=XXH32, `1`=XXH64, `2`=XXH128, `3`=XXH3.
Note that `-H3` triggers `--tag`, which can't be skipped
(this is to reduce risks of confusion with `-H2` (`XXH64`)).
Alternatively, <HASHTYPE> `32`=XXH32, `64`=XXH64, `128`=XXH128.
Default value is `1` (XXH64)
* `--tag`:
Output in the BSD style.
* `--little-endian`:
Set output hexadecimal checksum value as little endian convention.
By default, value is displayed as big endian.
* `-h`, `--help`:
Displays help and exits
**The following four options are useful only when verifying checksums (`-c`)**
* `-c`, `--check` <FILE>:
Read xxHash sums from <FILE> and check them
* `-q`, `--quiet`:
Don't print OK for each successfully verified file
* `--strict`:
Return an error code if any line in the file is invalid,
not just if some checksums are wrong.
This policy is disabled by default,
though UI will prompt an informational message
if any line in the file is detected invalid.
* `--status`:
Don't output anything. Status code shows success.
* `-w`, `--warn`:
Emit a warning message about each improperly formatted checksum line.
**The following options are useful only benchmark purpose**
* `-b`:
Benchmark mode. See [EXAMPLES](#EXAMPLES) for details.
* `-b#`:
Specify ID of variant to be tested.
Multiple variants can be selected, separated by a ',' comma.
* `-B`<BLOCKSIZE>:
Only useful for benchmark mode (`-b`). See [EXAMPLES](#EXAMPLES) for details.
<BLOCKSIZE> specifies benchmark mode's test data block size in bytes.
Default value is 102400
* `-i`<ITERATIONS>:
Only useful for benchmark mode (`-b`). See [EXAMPLES](#EXAMPLES) for details.
<ITERATIONS> specifies number of iterations in benchmark. Single iteration
lasts approximately 1000 milliseconds. Default value is 3
EXIT STATUS
-----------
`xxhsum` exit `0` on success, `1` if at least one file couldn't be read or
doesn't have the same checksum as the `-c` option.
EXAMPLES
--------
Output xxHash (64bit) checksum values of specific files to standard output
$ xxhsum -H1 foo bar baz
Output xxHash (32bit and 64bit) checksum values of specific files to standard
output, and redirect it to `xyz.xxh32` and `qux.xxh64`
$ xxhsum -H0 foo bar baz > xyz.xxh32
$ xxhsum -H1 foo bar baz > qux.xxh64
Read xxHash sums from specific files and check them
$ xxhsum -c xyz.xxh32 qux.xxh64
Benchmark xxHash algorithm.
By default, `xxhsum` benchmarks xxHash main variants
on a synthetic sample of 100 KB,
and print results into standard output.
The first column is the algorithm,
the second column is the source data size in bytes,
the third column is the number of hashes generated per second (throughput),
and finally the last column translates speed in megabytes per second.
$ xxhsum -b
In the following example,
the sample to hash is set to 16384 bytes,
the variants to be benched are selected by their IDs,
and each benchmark test is repeated 10 times, for increased accuracy.
$ xxhsum -b1,2,3 -i10 -B16384
BUGS
----
Report bugs at: https://github.com/Cyan4973/xxHash/issues/
AUTHOR
------
Yann Collet
SEE ALSO
--------
md5sum(1)
/*
* xxhsum - Command line interface for xxhash algorithms
* Copyright (C) 2013-2021 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
/*
* xxhsum:
* Provides hash value of a file content, or a list of files, or stdin
* Display convention is Big Endian, for both 32 and 64 bits algorithms
*/
/* Transitional headers */
#include "xsum_arch.h" /* XSUM_PROGRAM_VERSION */
#include "xsum_os_specific.h" /* XSUM_setBinaryMode */
#include "xsum_output.h" /* XSUM_output */
#include "xsum_sanity_check.h" /* XSUM_sanityCheck */
#include "xsum_bench.h" /* NBLOOPS_DEFAULT */
#ifdef XXH_INLINE_ALL
# include "xsum_os_specific.c"
# include "xsum_output.c"
# include "xsum_sanity_check.c"
# include "xsum_bench.c"
#endif
/* ************************************
* Includes
**************************************/
#include <stdlib.h> /* malloc, calloc, free, exit */
#include <string.h> /* strerror, strcmp, memcpy */
#include <assert.h> /* assert */
#include <errno.h> /* errno */
#define XXH_STATIC_LINKING_ONLY /* *_state_t */
#include "../xxhash.h"
#ifdef XXHSUM_DISPATCH
# include "../xxh_x86dispatch.h"
#endif
static unsigned XSUM_isLittleEndian(void)
{
const union { XSUM_U32 u; XSUM_U8 c[4]; } one = { 1 }; /* don't use static: performance detrimental */
return one.c[0];
}
static const int g_nbBits = (int)(sizeof(void*)*8);
static const char g_lename[] = "little endian";
static const char g_bename[] = "big endian";
#define ENDIAN_NAME (XSUM_isLittleEndian() ? g_lename : g_bename)
static const char author[] = "Yann Collet";
#define WELCOME_MESSAGE(exename) "%s %s by %s \n", exename, XSUM_PROGRAM_VERSION, author
#define FULL_WELCOME_MESSAGE(exename) "%s %s by %s \n" \
"compiled as %i-bit %s %s with " XSUM_CC_VERSION_FMT " \n", \
exename, XSUM_PROGRAM_VERSION, author, \
g_nbBits, XSUM_ARCH, ENDIAN_NAME, XSUM_CC_VERSION
static const char stdinName[] = "-";
static const char stdinFileName[] = "stdin";
typedef enum { algo_xxh32=0, algo_xxh64=1, algo_xxh128=2, algo_xxh3=3 } AlgoSelected;
static AlgoSelected g_defaultAlgo = algo_xxh64; /* required within main() & XSUM_usage() */
typedef enum {
algo_bitmask_xxh32 = 1 << algo_xxh32, /* 1 << 0 */
algo_bitmask_xxh64 = 1 << algo_xxh64, /* 1 << 1 */
algo_bitmask_xxh128 = 1 << algo_xxh128, /* 1 << 2 */
algo_bitmask_xxh3 = 1 << algo_xxh3, /* 1 << 3 */
algo_bitmask_all = algo_bitmask_xxh32 /* All algorithms */
| algo_bitmask_xxh64
| algo_bitmask_xxh128
| algo_bitmask_xxh3
} AlgoBitmask;
/* <16 hex char> <SPC> <SPC> <filename> <'\0'>
* '4096' is typical Linux PATH_MAX configuration. */
#define DEFAULT_LINE_LENGTH (sizeof(XXH64_hash_t) * 2 + 2 + 4096 + 1)
/* Maximum acceptable line length. */
#define MAX_LINE_LENGTH (32 KB)
static size_t XSUM_DEFAULT_SAMPLE_SIZE = 100 KB;
/* ********************************************************
* Filename (un)escaping
**********************************************************/
static int XSUM_filenameNeedsEscape(const char* filename) {
return strchr(filename, '\\')
|| strchr(filename, '\n')
|| strchr(filename, '\r');
}
static int XSUM_lineNeedsUnescape(const char* line) {
/* Skip white-space characters */
while (*line == ' ' || *line == '\t') {
++line;
}
/* Returns true if first non-white-space character is '\\' (0x5c) */
return *line == '\\';
}
static void XSUM_printFilename(const char* filename, int needsEscape) {
if (!needsEscape) {
XSUM_output("%s", filename);
} else {
const char* p;
for (p = filename; *p != '\0'; ++p) {
switch (*p)
{
case '\n':
XSUM_output("\\n");
break;
case '\r':
XSUM_output("\\r");
break;
case '\\':
XSUM_output("\\\\");
break;
default:
XSUM_output("%c", *p);
break;
}
}
}
}
/* Unescape filename in place.
- Replace '\\', 'n' (0x5c, 0x6e) with '\n' (0x0a).
- Replace '\\', 'r' (0x5c, 0x72) with '\r' (0x0d).
- Replace '\\', '\\' (0x5c, 0x5c) with '\\' (0x5c).
- filename may not contain other backslash sequences.
- filename may not ends with backslash.
- filename may not contain NUL (0x00).
Return filename if everything is okay.
Return NULL if something wrong.
*/
static char* XSUM_filenameUnescape(char* filename, size_t filenameLen) {
char *p = filename;
size_t i;
for (i = 0; i < filenameLen; ++i) {
switch (filename[i])
{
case '\\':
++i;
if (i == filenameLen) {
return NULL; /* Don't accept '\\', <EOL> */
}
switch (filename[i])
{
case 'n':
*p++ = '\n';
break;
case 'r':
*p++ = '\r';
break;
case '\\':
*p++ = '\\';
break;
default:
return NULL; /* Don't accept any other backslash sequence */
}
break;
case '\0':
return NULL; /* Don't accept NUL (0x00) */
default:
*p++ = filename[i];
break;
}
}
if (p < filename + filenameLen) {
*p = '\0';
}
return filename;
}
/* ********************************************************
* Algorithm Bitmask
**********************************************************/
/* Compute AlgoBitmask (as a U32) from AlgoSelected */
static XSUM_U32 XSUM_algoBitmask_ComputeAlgoBitmaskFromAlgoSelected(AlgoSelected algoSelected) {
return (XSUM_U32) (1U << algoSelected);
}
/* Returns true (!0) if algoBitmask contains (accepts) parsedLineAlgo */
static int XSUM_algoBitmask_Accepts(XSUM_U32 algoBitmask, AlgoSelected parsedLineAlgo) {
const XSUM_U32 mask = XSUM_algoBitmask_ComputeAlgoBitmaskFromAlgoSelected(parsedLineAlgo);
return (algoBitmask & mask) != 0;
}
/* ********************************************************
* File Hashing
**********************************************************/
#define XXHSUM32_DEFAULT_SEED 0 /* Default seed for algo_xxh32 */
#define XXHSUM64_DEFAULT_SEED 0 /* Default seed for algo_xxh64 */
/* for support of --little-endian display mode */
static void XSUM_display_LittleEndian(const void* ptr, size_t length)
{
const XSUM_U8* const p = (const XSUM_U8*)ptr;
size_t idx;
for (idx=length-1; idx<length; idx--) /* intentional underflow to negative to detect end */
XSUM_output("%02x", p[idx]);
}
static void XSUM_display_BigEndian(const void* ptr, size_t length)
{
const XSUM_U8* const p = (const XSUM_U8*)ptr;
size_t idx;
for (idx=0; idx<length; idx++)
XSUM_output("%02x", p[idx]);
}
typedef union {
XXH32_hash_t hash32;
XXH64_hash_t hash64; /* also for xxh3_64bits */
XXH128_hash_t hash128;
} Multihash;
/*
* XSUM_hashStream:
* Reads data from `inFile`, generating an incremental hash of type hashType,
* using `buffer` of size `blockSize` for temporary storage.
*/
static Multihash
XSUM_hashStream(FILE* inFile,
AlgoSelected hashType,
void* buffer, size_t blockSize)
{
XXH32_state_t state32;
XXH64_state_t state64;
XXH3_state_t state3;
/* Init */
(void)XXH32_reset(&state32, XXHSUM32_DEFAULT_SEED);
(void)XXH64_reset(&state64, XXHSUM64_DEFAULT_SEED);
(void)XXH3_128bits_reset(&state3);
/* Load file & update hash */
{ size_t readSize;
while ((readSize = fread(buffer, 1, blockSize, inFile)) > 0) {
switch(hashType)
{
case algo_xxh32:
(void)XXH32_update(&state32, buffer, readSize);
break;
case algo_xxh64:
(void)XXH64_update(&state64, buffer, readSize);
break;
case algo_xxh128:
(void)XXH3_128bits_update(&state3, buffer, readSize);
break;
case algo_xxh3:
(void)XXH3_64bits_update(&state3, buffer, readSize);
break;
default:
assert(0);
}
}
if (ferror(inFile)) {
XSUM_log("Error: a failure occurred reading the input file.\n");
exit(1);
} }
{ Multihash finalHash = {0};
switch(hashType)
{
case algo_xxh32:
finalHash.hash32 = XXH32_digest(&state32);
break;
case algo_xxh64:
finalHash.hash64 = XXH64_digest(&state64);
break;
case algo_xxh128:
finalHash.hash128 = XXH3_128bits_digest(&state3);
break;
case algo_xxh3:
finalHash.hash64 = XXH3_64bits_digest(&state3);
break;
default:
assert(0);
}
return finalHash;
}
}
/* algo_xxh32, algo_xxh64, algo_xxh128 */
static const char* XSUM_algoName[] = { "XXH32", "XXH64", "XXH128", "XXH3" };
static const char* XSUM_algoLE_name[] = { "XXH32_LE", "XXH64_LE", "XXH128_LE", "XXH3_LE" };
static const size_t XSUM_algoLength[] = { 4, 8, 16, 8 };
#define XSUM_TABLE_ELT_SIZE(table) (sizeof(table) / sizeof(*table))
typedef void (*XSUM_displayHash_f)(const void*, size_t); /* display function signature */
static void XSUM_printLine_BSD_internal(const char* filename,
const void* canonicalHash, const AlgoSelected hashType,
const char* algoString[],
XSUM_displayHash_f f_displayHash)
{
assert(0 <= hashType && (size_t)hashType <= XSUM_TABLE_ELT_SIZE(XSUM_algoName));
{ const char* const typeString = algoString[hashType];
const size_t hashLength = XSUM_algoLength[hashType];
const int needsEscape = XSUM_filenameNeedsEscape(filename);
if (needsEscape) {
XSUM_output("%c", '\\');
}
XSUM_output("%s (", typeString);
XSUM_printFilename(filename, needsEscape);
XSUM_output(") = ");
f_displayHash(canonicalHash, hashLength);
XSUM_output("\n");
} }
static void XSUM_printLine_BSD_LE(const char* filename, const void* canonicalHash, const AlgoSelected hashType)
{
XSUM_printLine_BSD_internal(filename, canonicalHash, hashType, XSUM_algoLE_name, XSUM_display_LittleEndian);
}
static void XSUM_printLine_BSD(const char* filename, const void* canonicalHash, const AlgoSelected hashType)
{
XSUM_printLine_BSD_internal(filename, canonicalHash, hashType, XSUM_algoName, XSUM_display_BigEndian);
}
static void XSUM_printLine_GNU_internal(const char* filename,
const void* canonicalHash, const AlgoSelected hashType,
XSUM_displayHash_f f_displayHash)
{
assert(0 <= hashType && (size_t)hashType <= XSUM_TABLE_ELT_SIZE(XSUM_algoName));
{ const size_t hashLength = XSUM_algoLength[hashType];
const int needsEscape = XSUM_filenameNeedsEscape(filename);
if (needsEscape) {
XSUM_output("%c", '\\');
}
f_displayHash(canonicalHash, hashLength);
XSUM_output(" ");
XSUM_printFilename(filename, needsEscape);
XSUM_output("\n");
} }
static void XSUM_printLine_GNU(const char* filename,
const void* canonicalHash, const AlgoSelected hashType)
{
XSUM_printLine_GNU_internal(filename, canonicalHash, hashType, XSUM_display_BigEndian);
}
static void XSUM_printLine_GNU_LE(const char* filename,
const void* canonicalHash, const AlgoSelected hashType)
{
XSUM_printLine_GNU_internal(filename, canonicalHash, hashType, XSUM_display_LittleEndian);
}
typedef enum { big_endian, little_endian} Display_endianess;
typedef enum { display_gnu, display_bsd } Display_convention;
typedef void (*XSUM_displayLine_f)(const char*, const void*, AlgoSelected); /* line display signature */
static XSUM_displayLine_f XSUM_kDisplayLine_fTable[2][2] = {
{ XSUM_printLine_GNU, XSUM_printLine_GNU_LE },
{ XSUM_printLine_BSD, XSUM_printLine_BSD_LE }
};
static int XSUM_hashFile(const char* fileName,
const AlgoSelected hashType,
const Display_endianess displayEndianess,
const Display_convention convention)
{
size_t const blockSize = 64 KB;
XSUM_displayLine_f const f_displayLine = XSUM_kDisplayLine_fTable[convention][displayEndianess];
FILE* inFile;
Multihash hashValue;
assert(displayEndianess==big_endian || displayEndianess==little_endian);
assert(convention==display_gnu || convention==display_bsd);
/* Check file existence */
if (fileName == stdinName) {
inFile = stdin;
fileName = stdinFileName; /* "stdin" */
XSUM_setBinaryMode(stdin);
} else {
if (XSUM_isDirectory(fileName)) {
XSUM_log("xxhsum: %s: Is a directory \n", fileName);
return 1;
}
inFile = XSUM_fopen( fileName, "rb" );
if (inFile==NULL) {
XSUM_log("Error: Could not open '%s': %s. \n", fileName, strerror(errno));
return 1;
} }
/* Memory allocation & streaming */
{ void* const buffer = malloc(blockSize);
if (buffer == NULL) {
XSUM_log("\nError: Out of memory.\n");
fclose(inFile);
return 1;
}
/* Stream file & update hash */
hashValue = XSUM_hashStream(inFile, hashType, buffer, blockSize);
fclose(inFile);
free(buffer);
}
/* display Hash value in selected format */
switch(hashType)
{
case algo_xxh32:
{ XXH32_canonical_t hcbe32;
(void)XXH32_canonicalFromHash(&hcbe32, hashValue.hash32);
f_displayLine(fileName, &hcbe32, hashType);
break;
}
case algo_xxh64:
{ XXH64_canonical_t hcbe64;
(void)XXH64_canonicalFromHash(&hcbe64, hashValue.hash64);
f_displayLine(fileName, &hcbe64, hashType);
break;
}
case algo_xxh128:
{ XXH128_canonical_t hcbe128;
(void)XXH128_canonicalFromHash(&hcbe128, hashValue.hash128);
f_displayLine(fileName, &hcbe128, hashType);
break;
}
case algo_xxh3:
{ XXH64_canonical_t hcbe64;
(void)XXH64_canonicalFromHash(&hcbe64, hashValue.hash64);
f_displayLine(fileName, &hcbe64, hashType);
break;
}
default:
assert(0); /* not possible */
}
return 0;
}
/*
* XSUM_hashFiles:
* If fnTotal==0, read from stdin instead.
*/
static int XSUM_hashFiles(const char* fnList[], int fnTotal,
AlgoSelected hashType,
Display_endianess displayEndianess,
Display_convention convention)
{
int fnNb;
int result = 0;
if (fnTotal==0)
return XSUM_hashFile(stdinName, hashType, displayEndianess, convention);
for (fnNb=0; fnNb<fnTotal; fnNb++)
result |= XSUM_hashFile(fnList[fnNb], hashType, displayEndianess, convention);
XSUM_logVerbose(2, "\r%70s\r", "");
return result;
}
typedef enum {
GetLine_ok,
GetLine_comment,
GetLine_eof,
GetLine_exceedMaxLineLength,
GetLine_outOfMemory
} GetLineResult;
typedef enum {
CanonicalFromString_ok,
CanonicalFromString_invalidFormat
} CanonicalFromStringResult;
typedef enum {
ParseLine_ok,
ParseLine_invalidFormat
} ParseLineResult;
typedef enum {
LineStatus_hashOk,
LineStatus_hashFailed,
LineStatus_failedToOpen
} LineStatus;
typedef union {
XXH32_canonical_t xxh32;
XXH64_canonical_t xxh64;
XXH128_canonical_t xxh128;
} Canonical;
typedef struct {
Canonical canonical;
const char* filename;
AlgoSelected algo;
} ParsedLine;
typedef struct {
unsigned long nProperlyFormattedLines;
unsigned long nImproperlyFormattedLines;
unsigned long nMismatchedChecksums;
unsigned long nOpenOrReadFailures;
unsigned long nMixedFormatLines;
int quit;
} ParseFileReport;
typedef struct {
const char* inFileName;
FILE* inFile;
int lineMax;
char* lineBuf;
size_t blockSize;
char* blockBuf;
XSUM_U32 strictMode;
XSUM_U32 statusOnly;
XSUM_U32 warn;
XSUM_U32 quiet;
XSUM_U32 algoBitmask;
ParseFileReport report;
} ParseFileArg;
/*
* Reads a line from stream `inFile`.
* Returns GetLine_ok, if it reads line successfully.
* Returns GetLine_comment, if the line is beginning with '#'.
* Returns GetLine_eof, if stream reaches EOF.
* Returns GetLine_exceedMaxLineLength, if line length is longer than MAX_LINE_LENGTH.
* Returns GetLine_outOfMemory, if line buffer memory allocation failed.
*/
static GetLineResult XSUM_getLine(char** lineBuf, int* lineMax, FILE* inFile)
{
GetLineResult result = GetLine_ok;
size_t len = 0;
if ((*lineBuf == NULL) || (*lineMax<1)) {
free(*lineBuf); /* in case it's != NULL */
*lineMax = 0;
*lineBuf = (char*)malloc(DEFAULT_LINE_LENGTH);
if(*lineBuf == NULL) return GetLine_outOfMemory;
*lineMax = DEFAULT_LINE_LENGTH;
}
for (;;) {
const int c = fgetc(inFile);
if (c == EOF) {
/*
* If we meet EOF before first character, returns GetLine_eof,
* otherwise GetLine_ok.
*/
if (len == 0) result = GetLine_eof;
break;
}
/* Make enough space for len+1 (for final NUL) bytes. */
if (len+1 >= (size_t)*lineMax) {
char* newLineBuf = NULL;
size_t newBufSize = (size_t)*lineMax;
newBufSize += (newBufSize/2) + 1; /* x 1.5 */
if (newBufSize > MAX_LINE_LENGTH) newBufSize = MAX_LINE_LENGTH;
if (len+1 >= newBufSize) return GetLine_exceedMaxLineLength;
newLineBuf = (char*) realloc(*lineBuf, newBufSize);
if (newLineBuf == NULL) return GetLine_outOfMemory;
*lineBuf = newLineBuf;
*lineMax = (int)newBufSize;
}
if (c == '\n') break;
(*lineBuf)[len++] = (char) c;
}
(*lineBuf)[len] = '\0';
/* Ignore comment lines, which begin with a '#' character. */
if (result == GetLine_ok && len > 0 && ((*lineBuf)[0] == '#')) {
result = GetLine_comment;
}
return result;
}
/*
* Converts one hexadecimal character to integer.
* Returns -1 if the given character is not hexadecimal.
*/
static int charToHex(char c)
{
int result = -1;
if (c >= '0' && c <= '9') {
result = (int) (c - '0');
} else if (c >= 'A' && c <= 'F') {
result = (int) (c - 'A') + 0x0a;
} else if (c >= 'a' && c <= 'f') {
result = (int) (c - 'a') + 0x0a;
}
return result;
}
/*
* Converts canonical ASCII hexadecimal string `hashStr`
* to the big endian binary representation in unsigned char array `dst`.
*
* Returns CanonicalFromString_invalidFormat if hashStr is not well formatted.
* Returns CanonicalFromString_ok if hashStr is parsed successfully.
*/
static CanonicalFromStringResult XSUM_canonicalFromString(unsigned char* dst,
size_t dstSize,
const char* hashStr,
int reverseBytes)
{
size_t i;
for (i = 0; i < dstSize; ++i) {
int h0, h1;
size_t j = reverseBytes ? dstSize - i - 1 : i;
h0 = charToHex(hashStr[j*2 + 0]);
if (h0 < 0) return CanonicalFromString_invalidFormat;
h1 = charToHex(hashStr[j*2 + 1]);
if (h1 < 0) return CanonicalFromString_invalidFormat;
dst[i] = (unsigned char) ((h0 << 4) | h1);
}
return CanonicalFromString_ok;
}
/*
* Parse single line of xxHash checksum file.
* Returns ParseLine_invalidFormat if the line is not well formatted.
* Returns ParseLine_ok if the line is parsed successfully.
* And members of XSUM_parseLine will be filled by parsed values.
*
* - line must be terminated with '\0' without a trailing newline.
* - Since parsedLine.filename will point within given argument `line`,
* users must keep `line`s content when they are using parsedLine.
* - The line may be modified to carve up the information it contains.
*
* xxHash checksum lines should have the following format:
*
* <8, 16, or 32 hexadecimal char> <space> <space> <filename...> <'\0'>
*
* or:
*
* <algorithm> <' ('> <filename> <') = '> <hexstring> <'\0'>
*/
static ParseLineResult XSUM_parseLine1(ParsedLine* parsedLine, char* line, int rev, int needsUnescape, XSUM_U32 algoBitmask)
{
char* const firstSpace = strchr(line, ' ');
const char* hash_ptr;
size_t hash_len;
parsedLine->filename = NULL;
parsedLine->algo = algo_xxh64; /* default - will be overwritten */
if (firstSpace == NULL || !firstSpace[1]) return ParseLine_invalidFormat;
if (firstSpace[1] == '(') {
char* lastSpace = strrchr(line, ' ');
if (lastSpace - firstSpace < 5) return ParseLine_invalidFormat;
if (lastSpace[-1] != '=' || lastSpace[-2] != ' ' || lastSpace[-3] != ')') return ParseLine_invalidFormat;
lastSpace[-3] = '\0'; /* Terminate the filename */
*firstSpace = '\0';
rev = strstr(line, "_LE") != NULL; /* was output little-endian */
hash_ptr = lastSpace + 1;
hash_len = strlen(hash_ptr);
if (!memcmp(line, "XXH3", 4)) parsedLine->algo = algo_xxh3;
if (!memcmp(line, "XXH32", 5)) parsedLine->algo = algo_xxh32;
if (!memcmp(line, "XXH64", 5)) parsedLine->algo = algo_xxh64;
if (!memcmp(line, "XXH128", 6)) parsedLine->algo = algo_xxh128;
} else {
hash_ptr = line;
hash_len = (size_t)(firstSpace - line);
if (hash_len==8) parsedLine->algo = algo_xxh32;
if (hash_len==16) parsedLine->algo = algo_xxh64;
if (hash_len==32) parsedLine->algo = algo_xxh128;
}
/* Check current CLI accepts the algorithm or not */
if(! XSUM_algoBitmask_Accepts(algoBitmask, parsedLine->algo)) {
return ParseLine_invalidFormat;
}
switch (hash_len)
{
case 8:
if (parsedLine->algo != algo_xxh32) return ParseLine_invalidFormat;
{ XXH32_canonical_t* xxh32c = &parsedLine->canonical.xxh32;
if (XSUM_canonicalFromString(xxh32c->digest, sizeof(xxh32c->digest), hash_ptr, rev)
!= CanonicalFromString_ok) {
return ParseLine_invalidFormat;
}
break;
}
case 16:
if (parsedLine->algo != algo_xxh64 && parsedLine->algo != algo_xxh3) return ParseLine_invalidFormat;
{ XXH64_canonical_t* xxh64c = &parsedLine->canonical.xxh64;
if (XSUM_canonicalFromString(xxh64c->digest, sizeof(xxh64c->digest), hash_ptr, rev)
!= CanonicalFromString_ok) {
return ParseLine_invalidFormat;
}
break;
}
case 32:
if (parsedLine->algo != algo_xxh128) return ParseLine_invalidFormat;
{ XXH128_canonical_t* xxh128c = &parsedLine->canonical.xxh128;
if (XSUM_canonicalFromString(xxh128c->digest, sizeof(xxh128c->digest), hash_ptr, rev)
!= CanonicalFromString_ok) {
return ParseLine_invalidFormat;
}
break;
}
default:
return ParseLine_invalidFormat;
break;
}
/* note : skipping second separation character, which can be anything,
* allowing insertion of custom markers such as '*' */
{
char* const filename = firstSpace + 2;
const size_t filenameLen = strlen(filename);
if (needsUnescape) {
char* const result = XSUM_filenameUnescape(filename, filenameLen);
if (result == NULL) {
return ParseLine_invalidFormat;
}
}
parsedLine->filename = filename;
}
return ParseLine_ok;
}
static ParseLineResult XSUM_parseLine(ParsedLine* parsedLine, char* line, int rev, XSUM_U32 algoBitmask) {
const int needsUnescape = XSUM_lineNeedsUnescape(line);
if (needsUnescape) {
++line;
}
return XSUM_parseLine1(parsedLine, line, rev, needsUnescape, algoBitmask);
}
/*!
* Parse xxHash checksum file.
*/
static void XSUM_parseFile1(ParseFileArg* XSUM_parseFileArg, int rev)
{
const char* const inFileName = XSUM_parseFileArg->inFileName;
ParseFileReport* const report = &XSUM_parseFileArg->report;
unsigned long lineNumber = 0;
memset(report, 0, sizeof(*report));
while (!report->quit) {
LineStatus lineStatus = LineStatus_hashFailed;
ParsedLine parsedLine;
memset(&parsedLine, 0, sizeof(parsedLine));
lineNumber++;
if (lineNumber == 0) {
/* This is unlikely happen, but md5sum.c has this error check. */
XSUM_log("%s: Error: Too many checksum lines\n", inFileName);
report->quit = 1;
break;
}
{ GetLineResult const XSUM_getLineResult = XSUM_getLine(&XSUM_parseFileArg->lineBuf,
&XSUM_parseFileArg->lineMax,
XSUM_parseFileArg->inFile);
/* Ignore comment lines */
if (XSUM_getLineResult == GetLine_comment) {
continue;
}
if (XSUM_getLineResult != GetLine_ok) {
if (XSUM_getLineResult == GetLine_eof) break;
switch (XSUM_getLineResult)
{
case GetLine_ok:
case GetLine_comment:
case GetLine_eof:
/* These cases never happen. See above XSUM_getLineResult related "if"s.
They exist just for make gcc's -Wswitch-enum happy. */
assert(0);
break;
default:
XSUM_log("%s:%lu: Error: Unknown error.\n", inFileName, lineNumber);
break;
case GetLine_exceedMaxLineLength:
XSUM_log("%s:%lu: Error: Line too long.\n", inFileName, lineNumber);
break;
case GetLine_outOfMemory:
XSUM_log("%s:%lu: Error: Out of memory.\n", inFileName, lineNumber);
break;
}
report->quit = 1;
break;
} }
if (XSUM_parseLine(&parsedLine, XSUM_parseFileArg->lineBuf, rev, XSUM_parseFileArg->algoBitmask) != ParseLine_ok) {
report->nImproperlyFormattedLines++;
if (XSUM_parseFileArg->warn) {
XSUM_log("%s:%lu: Error: Improperly formatted checksum line.\n",
inFileName, lineNumber);
}
continue;
}
report->nProperlyFormattedLines++;
do {
int const fnameIsStdin = (strcmp(parsedLine.filename, stdinFileName) == 0); /* "stdin" */
FILE* const fp = fnameIsStdin ? stdin : XSUM_fopen(parsedLine.filename, "rb");
if (fp == stdin) {
XSUM_setBinaryMode(stdin);
}
if (fp == NULL) {
lineStatus = LineStatus_failedToOpen;
break;
}
lineStatus = LineStatus_hashFailed;
{ Multihash const xxh = XSUM_hashStream(fp, parsedLine.algo, XSUM_parseFileArg->blockBuf, XSUM_parseFileArg->blockSize);
switch (parsedLine.algo)
{
case algo_xxh32:
if (xxh.hash32 == XXH32_hashFromCanonical(&parsedLine.canonical.xxh32)) {
lineStatus = LineStatus_hashOk;
}
break;
case algo_xxh64:
case algo_xxh3:
if (xxh.hash64 == XXH64_hashFromCanonical(&parsedLine.canonical.xxh64)) {
lineStatus = LineStatus_hashOk;
}
break;
case algo_xxh128:
if (XXH128_isEqual(xxh.hash128, XXH128_hashFromCanonical(&parsedLine.canonical.xxh128))) {
lineStatus = LineStatus_hashOk;
}
break;
default:
break;
}
}
if (fp != stdin) fclose(fp);
} while (0);
switch (lineStatus)
{
default:
XSUM_log("%s: Error: Unknown error.\n", inFileName);
report->quit = 1;
break;
case LineStatus_failedToOpen:
report->nOpenOrReadFailures++;
if (!XSUM_parseFileArg->statusOnly) {
XSUM_output("%s:%lu: Could not open or read '%s': %s.\n",
inFileName, lineNumber, parsedLine.filename, strerror(errno));
}
break;
case LineStatus_hashOk:
case LineStatus_hashFailed:
{ int b = 1;
if (lineStatus == LineStatus_hashOk) {
/* If --quiet is specified, don't display "OK" */
if (XSUM_parseFileArg->quiet) b = 0;
} else {
report->nMismatchedChecksums++;
}
if (b && !XSUM_parseFileArg->statusOnly) {
const int needsEscape = XSUM_filenameNeedsEscape(parsedLine.filename);
if (needsEscape) {
XSUM_output("%c", '\\');
}
XSUM_printFilename(parsedLine.filename, needsEscape);
XSUM_output(": %s\n", lineStatus == LineStatus_hashOk ? "OK" : "FAILED");
} }
break;
}
} /* while (!report->quit) */
}
/* Parse xxHash checksum file.
* Returns 1, if all procedures were succeeded.
* Returns 0, if any procedures was failed.
*
* If strictMode != 0, return error code if any line is invalid.
* If statusOnly != 0, don't generate any output.
* If warn != 0, print a warning message to stderr.
* If quiet != 0, suppress "OK" line.
*
* "All procedures are succeeded" means:
* - Checksum file contains at least one line and less than SIZE_T_MAX lines.
* - All files are properly opened and read.
* - All hash values match with its content.
* - (strict mode) All lines in checksum file are consistent and well formatted.
*/
static int XSUM_checkFile(const char* inFileName,
const Display_endianess displayEndianess,
XSUM_U32 strictMode,
XSUM_U32 statusOnly,
XSUM_U32 warn,
XSUM_U32 quiet,
XSUM_U32 algoBitmask)
{
int result = 0;
FILE* inFile = NULL;
ParseFileArg XSUM_parseFileArgBody;
ParseFileArg* const XSUM_parseFileArg = &XSUM_parseFileArgBody;
ParseFileReport* const report = &XSUM_parseFileArg->report;
/* note: stdinName is special constant pointer. It is not a string. */
if (inFileName == stdinName) {
/*
* Note: Since we expect text input for xxhash -c mode,
* we don't set binary mode for stdin.
*/
inFileName = stdinFileName; /* "stdin" */
inFile = stdin;
} else {
inFile = XSUM_fopen( inFileName, "rt" );
}
if (inFile == NULL) {
XSUM_log("Error: Could not open '%s': %s\n", inFileName, strerror(errno));
return 0;
}
XSUM_parseFileArg->inFileName = inFileName;
XSUM_parseFileArg->inFile = inFile;
XSUM_parseFileArg->lineMax = DEFAULT_LINE_LENGTH;
XSUM_parseFileArg->lineBuf = (char*) malloc((size_t)XSUM_parseFileArg->lineMax);
XSUM_parseFileArg->blockSize = 64 * 1024;
XSUM_parseFileArg->blockBuf = (char*) malloc(XSUM_parseFileArg->blockSize);
XSUM_parseFileArg->strictMode = strictMode;
XSUM_parseFileArg->statusOnly = statusOnly;
XSUM_parseFileArg->warn = warn;
XSUM_parseFileArg->quiet = quiet;
XSUM_parseFileArg->algoBitmask = algoBitmask;
if ( (XSUM_parseFileArg->lineBuf == NULL)
|| (XSUM_parseFileArg->blockBuf == NULL) ) {
XSUM_log("Error: : memory allocation failed \n");
exit(1);
}
XSUM_parseFile1(XSUM_parseFileArg, displayEndianess != big_endian);
free(XSUM_parseFileArg->blockBuf);
free(XSUM_parseFileArg->lineBuf);
if (inFile != stdin) fclose(inFile);
/* Show error/warning messages. All messages are copied from md5sum.c
*/
if (report->nProperlyFormattedLines == 0) {
XSUM_log("%s: no properly formatted xxHash checksum lines found\n", inFileName);
} else if (!statusOnly) {
if (report->nImproperlyFormattedLines) {
XSUM_output("%lu %s improperly formatted\n"
, report->nImproperlyFormattedLines
, report->nImproperlyFormattedLines == 1 ? "line is" : "lines are");
}
if (report->nOpenOrReadFailures) {
XSUM_output("%lu listed %s could not be read\n"
, report->nOpenOrReadFailures
, report->nOpenOrReadFailures == 1 ? "file" : "files");
}
if (report->nMismatchedChecksums) {
XSUM_output("%lu computed %s did NOT match\n"
, report->nMismatchedChecksums
, report->nMismatchedChecksums == 1 ? "checksum" : "checksums");
} }
/* Result (exit) code logic is copied from
* gnu coreutils/src/md5sum.c digest_check() */
result = report->nProperlyFormattedLines != 0
&& report->nMismatchedChecksums == 0
&& report->nOpenOrReadFailures == 0
&& (!strictMode || report->nImproperlyFormattedLines == 0)
&& report->quit == 0;
return result;
}
static int XSUM_checkFiles(const char* fnList[], int fnTotal,
const Display_endianess displayEndianess,
XSUM_U32 strictMode,
XSUM_U32 statusOnly,
XSUM_U32 warn,
XSUM_U32 quiet,
XSUM_U32 algoBitmask)
{
int ok = 1;
/* Special case for stdinName "-",
* note: stdinName is not a string. It's special pointer. */
if (fnTotal==0) {
ok &= XSUM_checkFile(stdinName, displayEndianess, strictMode, statusOnly, warn, quiet, algoBitmask);
} else {
int fnNb;
for (fnNb=0; fnNb<fnTotal; fnNb++)
ok &= XSUM_checkFile(fnList[fnNb], displayEndianess, strictMode, statusOnly, warn, quiet, algoBitmask);
}
return ok ? 0 : 1;
}
/* ********************************************************
* Main
**********************************************************/
static int XSUM_usage(const char* exename)
{
XSUM_log( WELCOME_MESSAGE(exename) );
XSUM_log( "Print or verify checksums using fast non-cryptographic algorithm xxHash \n\n" );
XSUM_log( "Usage: %s [options] [files] \n\n", exename);
XSUM_log( "When no filename provided or when '-' is provided, uses stdin as input. \n");
XSUM_log( "Options: \n");
XSUM_log( " -H# algorithm selection: 0,1,2,3 or 32,64,128 (default: %i) \n", (int)g_defaultAlgo);
XSUM_log( " -c, --check read xxHash checksum from [files] and check them \n");
XSUM_log( " -h, --help display a long help page about advanced options \n");
return 0;
}
static int XSUM_usage_advanced(const char* exename)
{
XSUM_usage(exename);
XSUM_log( "Advanced :\n");
XSUM_log( " -V, --version Display version information \n");
XSUM_log( " --tag Produce BSD-style checksum lines \n");
XSUM_log( " --little-endian Checksum values use little endian convention (default: big endian) \n");
XSUM_log( " -b Run benchmark \n");
XSUM_log( " -b# Bench only algorithm variant # \n");
XSUM_log( " -i# Number of times to run the benchmark (default: %i) \n", NBLOOPS_DEFAULT);
XSUM_log( " -q, --quiet Don't display version header in benchmark mode \n");
XSUM_log( "\n");
XSUM_log( "The following four options are useful only when verifying checksums (-c): \n");
XSUM_log( " -q, --quiet Don't print OK for each successfully verified file \n");
XSUM_log( " --status Don't output anything, status code shows success \n");
XSUM_log( " --strict Exit non-zero for improperly formatted checksum lines \n");
XSUM_log( " --warn Warn about improperly formatted checksum lines \n");
return 0;
}
static int XSUM_badusage(const char* exename)
{
XSUM_log("Wrong parameters\n\n");
XSUM_usage(exename);
return 1;
}
static void errorOut(const char* msg)
{
XSUM_log("%s \n", msg);
exit(1);
}
static const char* XSUM_lastNameFromPath(const char* path)
{
const char* name = path;
if (strrchr(name, '/')) name = strrchr(name, '/') + 1;
if (strrchr(name, '\\')) name = strrchr(name, '\\') + 1; /* windows */
return name;
}
/*!
* XSUM_readU32FromCharChecked():
* @return 0 if success, and store the result in *value.
* Allows and interprets K, KB, KiB, M, MB and MiB suffix.
* Will also modify `*stringPtr`, advancing it to position where it stopped reading.
* @return 1 if an overflow error occurs
*/
static int XSUM_readU32FromCharChecked(const char** stringPtr, XSUM_U32* value)
{
static const XSUM_U32 max = (((XSUM_U32)(-1)) / 10) - 1;
XSUM_U32 result = 0;
while ((**stringPtr >='0') && (**stringPtr <='9')) {
if (result > max) return 1; /* overflow error */
result *= 10;
result += (XSUM_U32)(**stringPtr - '0');
(*stringPtr)++ ;
}
if ((**stringPtr=='K') || (**stringPtr=='M')) {
XSUM_U32 const maxK = ((XSUM_U32)(-1)) >> 10;
if (result > maxK) return 1; /* overflow error */
result <<= 10;
if (**stringPtr=='M') {
if (result > maxK) return 1; /* overflow error */
result <<= 10;
}
(*stringPtr)++; /* skip `K` or `M` */
if (**stringPtr=='i') (*stringPtr)++;
if (**stringPtr=='B') (*stringPtr)++;
}
*value = result;
return 0;
}
/*!
* XSUM_readU32FromChar():
* @return: unsigned integer value read from input in `char` format.
* allows and interprets K, KB, KiB, M, MB and MiB suffix.
* Will also modify `*stringPtr`, advancing it to position where it stopped reading.
* Note: function will exit() program if digit sequence overflows
*/
static XSUM_U32 XSUM_readU32FromChar(const char** stringPtr) {
XSUM_U32 result;
if (XSUM_readU32FromCharChecked(stringPtr, &result)) {
static const char errorMsg[] = "Error: numeric value too large";
errorOut(errorMsg);
}
return result;
}
XSUM_API int XSUM_main(int argc, const char* argv[])
{
int i, filenamesStart = 0;
const char* const exename = XSUM_lastNameFromPath(argv[0]);
XSUM_U32 benchmarkMode = 0;
XSUM_U32 fileCheckMode = 0;
XSUM_U32 strictMode = 0;
XSUM_U32 statusOnly = 0;
XSUM_U32 warn = 0;
XSUM_U32 algoBitmask = algo_bitmask_all;
int explicitStdin = 0;
XSUM_U32 selectBenchIDs= 0; /* 0 == use default k_testIDs_default, kBenchAll == bench all */
static const XSUM_U32 kBenchAll = 99;
size_t keySize = XSUM_DEFAULT_SAMPLE_SIZE;
AlgoSelected algo = g_defaultAlgo;
Display_endianess displayEndianess = big_endian;
Display_convention convention = display_gnu;
int nbIterations = NBLOOPS_DEFAULT;
/* special case: xxhNNsum default to NN bits checksum */
if (strstr(exename, "xxh32sum") != NULL) { algo = g_defaultAlgo = algo_xxh32; algoBitmask = algo_bitmask_xxh32; }
if (strstr(exename, "xxh64sum") != NULL) { algo = g_defaultAlgo = algo_xxh64; algoBitmask = algo_bitmask_xxh64; }
if (strstr(exename, "xxh128sum") != NULL) { algo = g_defaultAlgo = algo_xxh128; algoBitmask = algo_bitmask_xxh128; }
for (i=1; i<argc; i++) {
const char* argument = argv[i];
assert(argument != NULL);
if (!strcmp(argument, "--check")) { fileCheckMode = 1; continue; }
if (!strcmp(argument, "--benchmark-all")) { benchmarkMode = 1; selectBenchIDs = kBenchAll; continue; }
if (!strcmp(argument, "--bench-all")) { benchmarkMode = 1; selectBenchIDs = kBenchAll; continue; }
if (!strcmp(argument, "--quiet")) { XSUM_logLevel--; continue; }
if (!strcmp(argument, "--little-endian")) { displayEndianess = little_endian; continue; }
if (!strcmp(argument, "--strict")) { strictMode = 1; continue; }
if (!strcmp(argument, "--status")) { statusOnly = 1; continue; }
if (!strcmp(argument, "--warn")) { warn = 1; continue; }
if (!strcmp(argument, "--help")) { return XSUM_usage_advanced(exename); }
if (!strcmp(argument, "--version")) { XSUM_log(FULL_WELCOME_MESSAGE(exename)); XSUM_sanityCheck(); return 0; }
if (!strcmp(argument, "--tag")) { convention = display_bsd; continue; }
if (!strcmp(argument, "--")) {
if (filenamesStart==0 && i!=argc-1) filenamesStart=i+1; /* only supports a continuous list of filenames */
break; /* treat rest of arguments as strictly file names */
}
if (*argument != '-') {
if (filenamesStart==0) filenamesStart=i; /* only supports a continuous list of filenames */
break; /* treat rest of arguments as strictly file names */
}
/* command selection */
argument++; /* note: *argument=='-' */
if (*argument == 0) explicitStdin = 1;
while (*argument != 0) {
switch(*argument)
{
/* Display version */
case 'V':
XSUM_log(FULL_WELCOME_MESSAGE(exename));
XSUM_sanityCheck();
return 0;
/* Display help on XSUM_usage */
case 'h':
return XSUM_usage_advanced(exename);
/* select hash algorithm */
case 'H': argument++;
switch(XSUM_readU32FromChar(&argument)) {
case 0 :
case 32: algo = algo_xxh32; break;
case 1 :
case 64: algo = algo_xxh64; break;
case 2 :
case 128: algo = algo_xxh128; break;
case 3 : /* xxh3 - necessarily uses BSD convention to avoid confusion with XXH64 */
algo = algo_xxh3;
convention = display_bsd;
break;
default:
return XSUM_badusage(exename);
}
break;
/* File check mode */
case 'c':
fileCheckMode=1;
argument++;
break;
/* Warning mode (file check mode only, alias of "--warning") */
case 'w':
warn=1;
argument++;
break;
/* Trigger benchmark mode */
case 'b':
argument++;
benchmarkMode = 1;
do {
if (*argument == ',') argument++;
selectBenchIDs = XSUM_readU32FromChar(&argument); /* select one specific test */
if ((int)selectBenchIDs < g_nbTestFunctions) {
g_testIDs[selectBenchIDs] = 1;
} else {
selectBenchIDs = kBenchAll;
}
} while (*argument == ',');
break;
/* Modify Nb Iterations (benchmark only) */
case 'i':
argument++;
nbIterations = (int)XSUM_readU32FromChar(&argument);
break;
/* Modify Block size (benchmark only) */
case 'B':
argument++;
keySize = XSUM_readU32FromChar(&argument);
break;
/* Modify verbosity of benchmark output (hidden option) */
case 'q':
argument++;
XSUM_logLevel--;
break;
default:
return XSUM_badusage(exename);
}
}
} /* for(i=1; i<argc; i++) */
/* Check benchmark mode */
if (benchmarkMode) {
XSUM_logVerbose(2, FULL_WELCOME_MESSAGE(exename) );
XSUM_sanityCheck();
g_nbIterations = nbIterations;
if (selectBenchIDs == 0) memcpy(g_testIDs, k_testIDs_default, (size_t)g_nbTestFunctions);
if (selectBenchIDs == kBenchAll) memset(g_testIDs, 1, (size_t)g_nbTestFunctions);
if (filenamesStart==0) return XSUM_benchInternal(keySize);
return XSUM_benchFiles(argv+filenamesStart, argc-filenamesStart);
}
/* Check if input is defined as console; trigger an error in this case */
if ( (filenamesStart==0) && XSUM_isConsole(stdin) && !explicitStdin)
return XSUM_badusage(exename);
if (filenamesStart==0) filenamesStart = argc;
if (fileCheckMode) {
return XSUM_checkFiles(argv+filenamesStart, argc-filenamesStart,
displayEndianess, strictMode, statusOnly, warn, (XSUM_logLevel < 2) /*quiet*/, algoBitmask);
} else {
return XSUM_hashFiles(argv+filenamesStart, argc-filenamesStart, algo, displayEndianess, convention);
}
}
# cmake artifacts
CMakeCache.txt
CMakeFiles
Makefile
cmake_install.cmake
# make compilation results
*.dylib
*.a
# To the extent possible under law, the author(s) have dedicated all
# copyright and related and neighboring rights to this software to
# the public domain worldwide. This software is distributed without
# any warranty.
#
# For details, see <https://creativecommons.org/publicdomain/zero/1.0/>.
cmake_minimum_required (VERSION 2.8.12 FATAL_ERROR)
set(XXHASH_DIR "${CMAKE_CURRENT_SOURCE_DIR}/..")
file(STRINGS "${XXHASH_DIR}/xxhash.h" XXHASH_VERSION_MAJOR REGEX "^#define XXH_VERSION_MAJOR +([0-9]+) *$")
string(REGEX REPLACE "^#define XXH_VERSION_MAJOR +([0-9]+) *$" "\\1" XXHASH_VERSION_MAJOR "${XXHASH_VERSION_MAJOR}")
file(STRINGS "${XXHASH_DIR}/xxhash.h" XXHASH_VERSION_MINOR REGEX "^#define XXH_VERSION_MINOR +([0-9]+) *$")
string(REGEX REPLACE "^#define XXH_VERSION_MINOR +([0-9]+) *$" "\\1" XXHASH_VERSION_MINOR "${XXHASH_VERSION_MINOR}")
file(STRINGS "${XXHASH_DIR}/xxhash.h" XXHASH_VERSION_RELEASE REGEX "^#define XXH_VERSION_RELEASE +([0-9]+) *$")
string(REGEX REPLACE "^#define XXH_VERSION_RELEASE +([0-9]+) *$" "\\1" XXHASH_VERSION_RELEASE "${XXHASH_VERSION_RELEASE}")
set(XXHASH_VERSION_STRING "${XXHASH_VERSION_MAJOR}.${XXHASH_VERSION_MINOR}.${XXHASH_VERSION_RELEASE}")
set(XXHASH_LIB_VERSION ${XXHASH_VERSION_STRING})
set(XXHASH_LIB_SOVERSION "${XXHASH_VERSION_MAJOR}")
mark_as_advanced(XXHASH_VERSION_MAJOR XXHASH_VERSION_MINOR XXHASH_VERSION_RELEASE XXHASH_VERSION_STRING XXHASH_LIB_VERSION XXHASH_LIB_SOVERSION)
if("${CMAKE_VERSION}" VERSION_LESS "3.13")
#message(WARNING "CMake ${CMAKE_VERSION} has no CMP0077 policy: options will erase uncached/untyped normal vars!")
else()
cmake_policy (SET CMP0077 NEW)
endif()
if("${CMAKE_VERSION}" VERSION_LESS "3.0")
project(xxHash C)
else()
cmake_policy (SET CMP0048 NEW)
project(xxHash
VERSION ${XXHASH_VERSION_STRING}
LANGUAGES C)
endif()
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Project build type" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE
PROPERTY STRINGS "Debug" "Release" "RelWithDebInfo" "MinSizeRel")
endif()
if(NOT CMAKE_CONFIGURATION_TYPES)
message(STATUS "xxHash build type: ${CMAKE_BUILD_TYPE}")
endif()
# Enable assert() statements in debug builds
if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug")
if("${CMAKE_VERSION}" VERSION_LESS "3.12")
# add_compile_definitions is not available for older cmake => do nothing
else()
add_compile_definitions(XXH_DEBUGLEVEL=1)
endif()
endif()
option(BUILD_SHARED_LIBS "Build shared library" ON)
option(XXHASH_BUILD_XXHSUM "Build the xxhsum binary" ON)
# If XXHASH is being bundled in another project, we don't want to
# install anything. However, we want to let people override this, so
# we'll use the XXHASH_BUNDLED_MODE variable to let them do that; just
# set it to OFF in your project before you add_subdirectory(xxhash/cmake_unofficial).
if(NOT DEFINED XXHASH_BUNDLED_MODE)
if("${PROJECT_SOURCE_DIR}" STREQUAL "${CMAKE_SOURCE_DIR}")
set(XXHASH_BUNDLED_MODE OFF)
else()
set(XXHASH_BUNDLED_MODE ON)
endif()
endif()
set(XXHASH_BUNDLED_MODE ${XXHASH_BUNDLED_MODE} CACHE BOOL "" FORCE)
mark_as_advanced(XXHASH_BUNDLED_MODE)
# Allow people to choose whether to build shared or static libraries
# via the BUILD_SHARED_LIBS option unless we are in bundled mode, in
# which case we always use static libraries.
include(CMakeDependentOption)
CMAKE_DEPENDENT_OPTION(BUILD_SHARED_LIBS "Build shared libraries" ON "NOT XXHASH_BUNDLED_MODE" OFF)
if("${CMAKE_VERSION}" VERSION_LESS "3.10")
# Can not enable DISPATCH mode since it fails to recognize architecture.
else()
CMAKE_HOST_SYSTEM_INFORMATION(RESULT PLATFORM QUERY OS_PLATFORM)
message(STATUS "Architecture: ${PLATFORM}")
endif()
# libxxhash
if((DEFINED DISPATCH) AND (DEFINED PLATFORM))
# Only support DISPATCH option on x86_64.
if("${PLATFORM}" STREQUAL "x86_64")
message(STATUS "Enable xxHash dispatch mode")
add_library(xxhash "${XXHASH_DIR}/xxh_x86dispatch.c"
"${XXHASH_DIR}/xxhash.c"
)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DXXHSUM_DISPATCH=1")
else()
add_library(xxhash "${XXHASH_DIR}/xxhash.c")
endif()
else()
add_library(xxhash "${XXHASH_DIR}/xxhash.c")
endif()
add_library(${PROJECT_NAME}::xxhash ALIAS xxhash)
target_include_directories(xxhash
PUBLIC
$<BUILD_INTERFACE:${XXHASH_DIR}>
$<INSTALL_INTERFACE:include/>)
if (BUILD_SHARED_LIBS)
target_compile_definitions(xxhash PUBLIC XXH_EXPORT)
endif ()
set_target_properties(xxhash PROPERTIES
SOVERSION "${XXHASH_LIB_SOVERSION}"
VERSION "${XXHASH_VERSION_STRING}")
if(XXHASH_BUILD_XXHSUM)
set(XXHSUM_DIR "${XXHASH_DIR}/cli")
# xxhsum
add_executable(xxhsum "${XXHSUM_DIR}/xxhsum.c"
"${XXHSUM_DIR}/xsum_os_specific.c"
"${XXHSUM_DIR}/xsum_output.c"
"${XXHSUM_DIR}/xsum_sanity_check.c"
"${XXHSUM_DIR}/xsum_bench.c"
)
add_executable(${PROJECT_NAME}::xxhsum ALIAS xxhsum)
target_link_libraries(xxhsum PRIVATE xxhash)
target_include_directories(xxhsum PRIVATE "${XXHASH_DIR}")
endif(XXHASH_BUILD_XXHSUM)
# Extra warning flags
include (CheckCCompilerFlag)
if (XXHASH_C_FLAGS)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${XXHASH_C_FLAGS}")
endif()
if(NOT XXHASH_BUNDLED_MODE)
include(GNUInstallDirs)
install(TARGETS xxhash
EXPORT xxHashTargets
RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}"
ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}")
install(FILES "${XXHASH_DIR}/xxhash.h"
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
install(FILES "${XXHASH_DIR}/xxh3.h"
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
if(DISPATCH)
install(FILES "${XXHASH_DIR}/xxh_x86dispatch.h"
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
endif()
if(XXHASH_BUILD_XXHSUM)
install(TARGETS xxhsum
EXPORT xxHashTargets
RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}")
install(FILES "${XXHSUM_DIR}/xxhsum.1"
DESTINATION "${CMAKE_INSTALL_MANDIR}/man1")
endif(XXHASH_BUILD_XXHSUM)
include(CMakePackageConfigHelpers)
set(xxHash_VERSION_CONFIG "${PROJECT_BINARY_DIR}/xxHashConfigVersion.cmake")
set(xxHash_PROJECT_CONFIG "${PROJECT_BINARY_DIR}/xxHashConfig.cmake")
set(xxHash_TARGETS_CONFIG "${PROJECT_BINARY_DIR}/xxHashTargets.cmake")
set(xxHash_CONFIG_INSTALL_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/xxHash/")
write_basic_package_version_file(${xxHash_VERSION_CONFIG}
VERSION ${XXHASH_VERSION_STRING}
COMPATIBILITY AnyNewerVersion)
configure_package_config_file(
${PROJECT_SOURCE_DIR}/xxHashConfig.cmake.in
${xxHash_PROJECT_CONFIG}
INSTALL_DESTINATION ${xxHash_CONFIG_INSTALL_DIR})
if("${CMAKE_VERSION}" VERSION_LESS "3.0")
set(XXHASH_EXPORT_SET xxhash)
if(XXHASH_BUILD_XXHSUM)
set(XXHASH_EXPORT_SET ${XXHASH_EXPORT_SET} xxhsum)
endif()
export(TARGETS ${XXHASH_EXPORT_SET}
FILE ${xxHash_TARGETS_CONFIG}
NAMESPACE ${PROJECT_NAME}::)
else()
export(EXPORT xxHashTargets
FILE ${xxHash_TARGETS_CONFIG}
NAMESPACE ${PROJECT_NAME}::)
endif()
install(FILES ${xxHash_PROJECT_CONFIG} ${xxHash_VERSION_CONFIG}
DESTINATION ${xxHash_CONFIG_INSTALL_DIR})
install(EXPORT xxHashTargets
DESTINATION ${xxHash_CONFIG_INSTALL_DIR}
NAMESPACE ${PROJECT_NAME}::)
# configure and install pkg-config
include(JoinPaths.cmake)
set(PREFIX ${CMAKE_INSTALL_PREFIX})
set(EXECPREFIX "\${prefix}")
join_paths(INCLUDEDIR "\${prefix}" "${CMAKE_INSTALL_INCLUDEDIR}")
join_paths(LIBDIR "\${prefix}" "${CMAKE_INSTALL_LIBDIR}")
set(VERSION "${XXHASH_VERSION_STRING}")
configure_file(${XXHASH_DIR}/libxxhash.pc.in ${CMAKE_BINARY_DIR}/libxxhash.pc @ONLY)
install(FILES ${CMAKE_BINARY_DIR}/libxxhash.pc
DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig)
endif(NOT XXHASH_BUNDLED_MODE)
include(CPack)
# This module provides function for joining paths
# known from most languages
#
# SPDX-License-Identifier: (MIT OR CC0-1.0)
# Copyright 2020 Jan Tojnar
# https://github.com/jtojnar/cmake-snips
#
# Modelled after Python’s os.path.join
# https://docs.python.org/3.7/library/os.path.html#os.path.join
# Windows not supported
function(join_paths joined_path first_path_segment)
set(temp_path "${first_path_segment}")
foreach(current_segment IN LISTS ARGN)
if(NOT ("${current_segment}" STREQUAL ""))
if(IS_ABSOLUTE "${current_segment}")
set(temp_path "${current_segment}")
else()
set(temp_path "${temp_path}/${current_segment}")
endif()
endif()
endforeach()
set(${joined_path} "${temp_path}" PARENT_SCOPE)
endfunction()
## Usage
### Way 1: import targets
Build xxHash targets:
cd </path/to/xxHash/>
mkdir build
cd build
cmake ../cmake_unofficial [options]
cmake --build .
cmake --build . --target install #optional
Where possible options are:
- `-DXXHASH_BUILD_ENABLE_INLINE_API=<ON|OFF>`: adds xxhash.c for the `-DXXH_INLINE_ALL` api. ON by default.
- `-DXXHASH_BUILD_XXHSUM=<ON|OFF>`: build the command line binary. ON by default
- `-DBUILD_SHARED_LIBS=<ON|OFF>`: build dynamic library. ON by default.
- `-DCMAKE_INSTALL_PREFIX=<path>`: use custom install prefix path.
- `-DDISPATCH=<ON|OFF>`: enable dispatch mode. OFF by default.
Add lines into downstream CMakeLists.txt:
find_package(xxHash 0.7 CONFIG REQUIRED)
...
target_link_libraries(MyTarget PRIVATE xxHash::xxhash)
### Way 2: Add subdirectory
Add lines into downstream CMakeLists.txt:
option(BUILD_SHARED_LIBS "Build shared libs" OFF) #optional
...
set(XXHASH_BUILD_ENABLE_INLINE_API OFF) #optional
set(XXHASH_BUILD_XXHSUM OFF) #optional
add_subdirectory(</path/to/xxHash/cmake_unofficial/> </path/to/xxHash/build/> EXCLUDE_FROM_ALL)
...
target_link_libraries(MyTarget PRIVATE xxHash::xxhash)
@PACKAGE_INIT@
include(${CMAKE_CURRENT_LIST_DIR}/xxHashTargets.cmake)
xxHash Specification
=======================
This directory contains material defining the xxHash algorithm.
It's described in [this specification document](xxhash_spec.md).
The algorithm is also be illustrated by a [simple educational library](https://github.com/easyaspi314/xxhash-clean),
written by @easyaspi314 and designed for readability
(as opposed to the reference library which is designed for speed).
module xxhash where
/**
* The 32-bit variant of xxHash. The first argument is the sequence
* of L bytes to hash. The second argument is a seed value.
*/
XXH32 : {L} (fin L) => [L][8] -> [32] -> [32]
XXH32 input seed = XXH32_avalanche acc1
where (stripes16 # stripes4 # stripes1) = input
accR = foldl XXH32_rounds (XXH32_init seed) (split stripes16 : [L/16][16][8])
accL = `(L % 2^^32) + if (`L:Integer) < 16
then seed + PRIME32_5
else XXH32_converge accR
acc4 = foldl XXH32_digest4 accL (split stripes4 : [(L%16)/4][4][8])
acc1 = foldl XXH32_digest1 acc4 (stripes1 : [L%4][8])
/**
* The 64-bit variant of xxHash. The first argument is the sequence
* of L bytes to hash. The second argument is a seed value.
*/
XXH64 : {L} (fin L) => [L][8] -> [64] -> [64]
XXH64 input seed = XXH64_avalanche acc1
where (stripes32 # stripes8 # stripes4 # stripes1) = input
accR = foldl XXH64_rounds (XXH64_init seed) (split stripes32 : [L/32][32][8])
accL = `(L % 2^^64) + if (`L:Integer) < 32
then seed + PRIME64_5
else XXH64_converge accR
acc8 = foldl XXH64_digest8 accL (split stripes8 : [(L%32)/8][8][8])
acc4 = foldl XXH64_digest4 acc8 (split stripes4 : [(L%8)/4][4][8])
acc1 = foldl XXH64_digest1 acc4 (stripes1 : [L%4][8])
private
//Utility functions
/**
* Combines a sequence of bytes into a word using the little-endian
* convention.
*/
toLE bytes = join (reverse bytes)
//32-bit xxHash helper functions
//32-bit prime number constants
PRIME32_1 = 0x9E3779B1 : [32]
PRIME32_2 = 0x85EBCA77 : [32]
PRIME32_3 = 0xC2B2AE3D : [32]
PRIME32_4 = 0x27D4EB2F : [32]
PRIME32_5 = 0x165667B1 : [32]
/**
* The property shows that the hexadecimal representation of the
* PRIME32 constants is the same as the binary representation.
*/
property PRIME32s_as_bits_correct =
(PRIME32_1 == 0b10011110001101110111100110110001) /\
(PRIME32_2 == 0b10000101111010111100101001110111) /\
(PRIME32_3 == 0b11000010101100101010111000111101) /\
(PRIME32_4 == 0b00100111110101001110101100101111) /\
(PRIME32_5 == 0b00010110010101100110011110110001)
/**
* This function initializes the four internal accumulators of XXH32.
*/
XXH32_init : [32] -> [4][32]
XXH32_init seed = [acc1, acc2, acc3, acc4]
where acc1 = seed + PRIME32_1 + PRIME32_2
acc2 = seed + PRIME32_2
acc3 = seed + 0
acc4 = seed - PRIME32_1
/**
* This processes a single lane of the main round function of XXH32.
*/
XXH32_round : [32] -> [32] -> [32]
XXH32_round accN laneN = ((accN + laneN * PRIME32_2) <<< 13) * PRIME32_1
/**
* This is the main round function of XXH32 and processes a stripe,
* i.e. 4 lanes with 4 bytes each.
*/
XXH32_rounds : [4][32] -> [16][8] -> [4][32]
XXH32_rounds accs stripe =
[ XXH32_round accN (toLE laneN) | accN <- accs | laneN <- split stripe ]
/**
* This function combines the four lane accumulators into a single
* 32-bit value.
*/
XXH32_converge : [4][32] -> [32]
XXH32_converge [acc1, acc2, acc3, acc4] =
(acc1 <<< 1) + (acc2 <<< 7) + (acc3 <<< 12) + (acc4 <<< 18)
/**
* This function digests a four byte lane
*/
XXH32_digest4 : [32] -> [4][8] -> [32]
XXH32_digest4 acc lane = ((acc + toLE lane * PRIME32_3) <<< 17) * PRIME32_4
/**
* This function digests a single byte lane
*/
XXH32_digest1 : [32] -> [8] -> [32]
XXH32_digest1 acc lane = ((acc + (0 # lane) * PRIME32_5) <<< 11) * PRIME32_1
/**
* This function ensures that all input bits have a chance to impact
* any bit in the output digest, resulting in an unbiased
* distribution.
*/
XXH32_avalanche : [32] -> [32]
XXH32_avalanche acc0 = acc5
where acc1 = acc0 ^ (acc0 >> 15)
acc2 = acc1 * PRIME32_2
acc3 = acc2 ^ (acc2 >> 13)
acc4 = acc3 * PRIME32_3
acc5 = acc4 ^ (acc4 >> 16)
//64-bit xxHash helper functions
//64-bit prime number constants
PRIME64_1 = 0x9E3779B185EBCA87 : [64]
PRIME64_2 = 0xC2B2AE3D27D4EB4F : [64]
PRIME64_3 = 0x165667B19E3779F9 : [64]
PRIME64_4 = 0x85EBCA77C2B2AE63 : [64]
PRIME64_5 = 0x27D4EB2F165667C5 : [64]
/**
* The property shows that the hexadecimal representation of the
* PRIME64 constants is the same as the binary representation.
*/
property PRIME64s_as_bits_correct =
(PRIME64_1 == 0b1001111000110111011110011011000110000101111010111100101010000111) /\
(PRIME64_2 == 0b1100001010110010101011100011110100100111110101001110101101001111) /\
(PRIME64_3 == 0b0001011001010110011001111011000110011110001101110111100111111001) /\
(PRIME64_4 == 0b1000010111101011110010100111011111000010101100101010111001100011) /\
(PRIME64_5 == 0b0010011111010100111010110010111100010110010101100110011111000101)
/**
* This function initializes the four internal accumulators of XXH64.
*/
XXH64_init : [64] -> [4][64]
XXH64_init seed = [acc1, acc2, acc3, acc4]
where acc1 = seed + PRIME64_1 + PRIME64_2
acc2 = seed + PRIME64_2
acc3 = seed + 0
acc4 = seed - PRIME64_1
/**
* This processes a single lane of the main round function of XXH64.
*/
XXH64_round : [64] -> [64] -> [64]
XXH64_round accN laneN = ((accN + laneN * PRIME64_2) <<< 31) * PRIME64_1
/**
* This is the main round function of XXH64 and processes a stripe,
* i.e. 4 lanes with 8 bytes each.
*/
XXH64_rounds : [4][64] -> [32][8] -> [4][64]
XXH64_rounds accs stripe =
[ XXH64_round accN (toLE laneN) | accN <- accs | laneN <- split stripe ]
/**
* This is a helper function, used to merge the four lane accumulators.
*/
mergeAccumulator : [64] -> [64] -> [64]
mergeAccumulator acc accN = (acc ^ XXH64_round 0 accN) * PRIME64_1 + PRIME64_4
/**
* This function combines the four lane accumulators into a single
* 64-bit value.
*/
XXH64_converge : [4][64] -> [64]
XXH64_converge [acc1, acc2, acc3, acc4] =
foldl mergeAccumulator ((acc1 <<< 1) + (acc2 <<< 7) + (acc3 <<< 12) + (acc4 <<< 18)) [acc1, acc2, acc3, acc4]
/**
* This function digests an eight byte lane
*/
XXH64_digest8 : [64] -> [8][8] -> [64]
XXH64_digest8 acc lane = ((acc ^ XXH64_round 0 (toLE lane)) <<< 27) * PRIME64_1 + PRIME64_4
/**
* This function digests a four byte lane
*/
XXH64_digest4 : [64] -> [4][8] -> [64]
XXH64_digest4 acc lane = ((acc ^ (0 # toLE lane) * PRIME64_1) <<< 23) * PRIME64_2 + PRIME64_3
/**
* This function digests a single byte lane
*/
XXH64_digest1 : [64] -> [8] -> [64]
XXH64_digest1 acc lane = ((acc ^ (0 # lane) * PRIME64_5) <<< 11) * PRIME64_1
/**
* This function ensures that all input bits have a chance to impact
* any bit in the output digest, resulting in an unbiased
* distribution.
*/
XXH64_avalanche : [64] -> [64]
XXH64_avalanche acc0 = acc5
where acc1 = acc0 ^ (acc0 >> 33)
acc2 = acc1 * PRIME64_2
acc3 = acc2 ^ (acc2 >> 29)
acc4 = acc3 * PRIME64_3
acc5 = acc4 ^ (acc4 >> 32)
xxHash fast digest algorithm
======================
### Notices
Copyright (c) Yann Collet
Permission is granted to copy and distribute this document
for any purpose and without charge,
including translations into other languages
and incorporation into compilations,
provided that the copyright notice and this notice are preserved,
and that any substantive changes or deletions from the original
are clearly marked.
Distribution of this document is unlimited.
### Version
0.1.1 (10/10/18)
Table of Contents
---------------------
- [Introduction](#introduction)
- [XXH32 algorithm description](#xxh32-algorithm-description)
- [XXH64 algorithm description](#xxh64-algorithm-description)
- [Performance considerations](#performance-considerations)
- [Reference Implementation](#reference-implementation)
Introduction
----------------
This document describes the xxHash digest algorithm for both 32-bit and 64-bit variants, named `XXH32` and `XXH64`. The algorithm takes an input a message of arbitrary length and an optional seed value, then produces an output of 32 or 64-bit as "fingerprint" or "digest".
xxHash is primarily designed for speed. It is labeled non-cryptographic, and is not meant to avoid intentional collisions (same digest for 2 different messages), or to prevent producing a message with a predefined digest.
XXH32 is designed to be fast on 32-bit machines.
XXH64 is designed to be fast on 64-bit machines.
Both variants produce different output.
However, a given variant shall produce exactly the same output, irrespective of the cpu / os used. In particular, the result remains identical whatever the endianness and width of the cpu is.
### Operation notations
All operations are performed modulo {32,64} bits. Arithmetic overflows are expected.
`XXH32` uses 32-bit modular operations. `XXH64` uses 64-bit modular operations.
- `+`: denotes modular addition
- `*`: denotes modular multiplication
- `X <<< s`: denotes the value obtained by circularly shifting (rotating) `X` left by `s` bit positions.
- `X >> s`: denotes the value obtained by shifting `X` right by s bit positions. Upper `s` bits become `0`.
- `X xor Y`: denotes the bit-wise XOR of `X` and `Y` (same width).
XXH32 Algorithm Description
-------------------------------------
### Overview
We begin by supposing that we have a message of any length `L` as input, and that we wish to find its digest. Here `L` is an arbitrary nonnegative integer; `L` may be zero. The following steps are performed to compute the digest of the message.
The algorithm collect and transform input in _stripes_ of 16 bytes. The transforms are stored inside 4 "accumulators", each one storing an unsigned 32-bit value. Each accumulator can be processed independently in parallel, speeding up processing for cpu with multiple execution units.
The algorithm uses 32-bits addition, multiplication, rotate, shift and xor operations. Many operations require some 32-bits prime number constants, all defined below:
```c
static const u32 PRIME32_1 = 0x9E3779B1U; // 0b10011110001101110111100110110001
static const u32 PRIME32_2 = 0x85EBCA77U; // 0b10000101111010111100101001110111
static const u32 PRIME32_3 = 0xC2B2AE3DU; // 0b11000010101100101010111000111101
static const u32 PRIME32_4 = 0x27D4EB2FU; // 0b00100111110101001110101100101111
static const u32 PRIME32_5 = 0x165667B1U; // 0b00010110010101100110011110110001
```
These constants are prime numbers, and feature a good mix of bits 1 and 0, neither too regular, nor too dissymmetric. These properties help dispersion capabilities.
### Step 1. Initialize internal accumulators
Each accumulator gets an initial value based on optional `seed` input. Since the `seed` is optional, it can be `0`.
```c
u32 acc1 = seed + PRIME32_1 + PRIME32_2;
u32 acc2 = seed + PRIME32_2;
u32 acc3 = seed + 0;
u32 acc4 = seed - PRIME32_1;
```
#### Special case: input is less than 16 bytes
When the input is too small (< 16 bytes), the algorithm will not process any stripes. Consequently, it will not make use of parallel accumulators.
In this case, a simplified initialization is performed, using a single accumulator:
```c
u32 acc = seed + PRIME32_5;
```
The algorithm then proceeds directly to step 4.
### Step 2. Process stripes
A stripe is a contiguous segment of 16 bytes.
It is evenly divided into 4 _lanes_, of 4 bytes each.
The first lane is used to update accumulator 1, the second lane is used to update accumulator 2, and so on.
Each lane read its associated 32-bit value using __little-endian__ convention.
For each {lane, accumulator}, the update process is called a _round_, and applies the following formula:
```c
accN = accN + (laneN * PRIME32_2);
accN = accN <<< 13;
accN = accN * PRIME32_1;
```
This shuffles the bits so that any bit from input _lane_ impacts several bits in output _accumulator_. All operations are performed modulo 2^32.
Input is consumed one full stripe at a time. Step 2 is looped as many times as necessary to consume the whole input, except for the last remaining bytes which cannot form a stripe (< 16 bytes).
When that happens, move to step 3.
### Step 3. Accumulator convergence
All 4 lane accumulators from the previous steps are merged to produce a single remaining accumulator of the same width (32-bit). The associated formula is as follows:
```c
acc = (acc1 <<< 1) + (acc2 <<< 7) + (acc3 <<< 12) + (acc4 <<< 18);
```
### Step 4. Add input length
The input total length is presumed known at this stage. This step is just about adding the length to accumulator, so that it participates to final mixing.
```c
acc = acc + (u32)inputLength;
```
Note that, if input length is so large that it requires more than 32-bits, only the lower 32-bits are added to the accumulator.
### Step 5. Consume remaining input
There may be up to 15 bytes remaining to consume from the input.
The final stage will digest them according to following pseudo-code:
```c
while (remainingLength >= 4) {
lane = read_32bit_little_endian(input_ptr);
acc = acc + lane * PRIME32_3;
acc = (acc <<< 17) * PRIME32_4;
input_ptr += 4; remainingLength -= 4;
}
while (remainingLength >= 1) {
lane = read_byte(input_ptr);
acc = acc + lane * PRIME32_5;
acc = (acc <<< 11) * PRIME32_1;
input_ptr += 1; remainingLength -= 1;
}
```
This process ensures that all input bytes are present in the final mix.
### Step 6. Final mix (avalanche)
The final mix ensures that all input bits have a chance to impact any bit in the output digest, resulting in an unbiased distribution. This is also called avalanche effect.
```c
acc = acc xor (acc >> 15);
acc = acc * PRIME32_2;
acc = acc xor (acc >> 13);
acc = acc * PRIME32_3;
acc = acc xor (acc >> 16);
```
### Step 7. Output
The `XXH32()` function produces an unsigned 32-bit value as output.
For systems which require to store and/or display the result in binary or hexadecimal format, the canonical format is defined to reproduce the same value as the natural decimal format, hence follows __big-endian__ convention (most significant byte first).
XXH64 Algorithm Description
-------------------------------------
### Overview
`XXH64`'s algorithm structure is very similar to `XXH32` one. The major difference is that `XXH64` uses 64-bit arithmetic, speeding up memory transfer for 64-bit compliant systems, but also relying on cpu capability to efficiently perform 64-bit operations.
The algorithm collects and transforms input in _stripes_ of 32 bytes. The transforms are stored inside 4 "accumulators", each one storing an unsigned 64-bit value. Each accumulator can be processed independently in parallel, speeding up processing for cpu with multiple execution units.
The algorithm uses 64-bit addition, multiplication, rotate, shift and xor operations. Many operations require some 64-bit prime number constants, all defined below:
```c
static const u64 PRIME64_1 = 0x9E3779B185EBCA87ULL; // 0b1001111000110111011110011011000110000101111010111100101010000111
static const u64 PRIME64_2 = 0xC2B2AE3D27D4EB4FULL; // 0b1100001010110010101011100011110100100111110101001110101101001111
static const u64 PRIME64_3 = 0x165667B19E3779F9ULL; // 0b0001011001010110011001111011000110011110001101110111100111111001
static const u64 PRIME64_4 = 0x85EBCA77C2B2AE63ULL; // 0b1000010111101011110010100111011111000010101100101010111001100011
static const u64 PRIME64_5 = 0x27D4EB2F165667C5ULL; // 0b0010011111010100111010110010111100010110010101100110011111000101
```
These constants are prime numbers, and feature a good mix of bits 1 and 0, neither too regular, nor too dissymmetric. These properties help dispersion capabilities.
### Step 1. Initialize internal accumulators
Each accumulator gets an initial value based on optional `seed` input. Since the `seed` is optional, it can be `0`.
```c
u64 acc1 = seed + PRIME64_1 + PRIME64_2;
u64 acc2 = seed + PRIME64_2;
u64 acc3 = seed + 0;
u64 acc4 = seed - PRIME64_1;
```
#### Special case: input is less than 32 bytes
When the input is too small (< 32 bytes), the algorithm will not process any stripes. Consequently, it will not make use of parallel accumulators.
In this case, a simplified initialization is performed, using a single accumulator:
```c
u64 acc = seed + PRIME64_5;
```
The algorithm then proceeds directly to step 4.
### Step 2. Process stripes
A stripe is a contiguous segment of 32 bytes.
It is evenly divided into 4 _lanes_, of 8 bytes each.
The first lane is used to update accumulator 1, the second lane is used to update accumulator 2, and so on.
Each lane read its associated 64-bit value using __little-endian__ convention.
For each {lane, accumulator}, the update process is called a _round_, and applies the following formula:
```c
round(accN,laneN):
accN = accN + (laneN * PRIME64_2);
accN = accN <<< 31;
return accN * PRIME64_1;
```
This shuffles the bits so that any bit from input _lane_ impacts several bits in output _accumulator_. All operations are performed modulo 2^64.
Input is consumed one full stripe at a time. Step 2 is looped as many times as necessary to consume the whole input, except for the last remaining bytes which cannot form a stripe (< 32 bytes).
When that happens, move to step 3.
### Step 3. Accumulator convergence
All 4 lane accumulators from previous steps are merged to produce a single remaining accumulator of same width (64-bit). The associated formula is as follows.
Note that accumulator convergence is more complex than 32-bit variant, and requires to define another function called _mergeAccumulator()_:
```c
mergeAccumulator(acc,accN):
acc = acc xor round(0, accN);
acc = acc * PRIME64_1;
return acc + PRIME64_4;
```
which is then used in the convergence formula:
```c
acc = (acc1 <<< 1) + (acc2 <<< 7) + (acc3 <<< 12) + (acc4 <<< 18);
acc = mergeAccumulator(acc, acc1);
acc = mergeAccumulator(acc, acc2);
acc = mergeAccumulator(acc, acc3);
acc = mergeAccumulator(acc, acc4);
```
### Step 4. Add input length
The input total length is presumed known at this stage. This step is just about adding the length to accumulator, so that it participates to final mixing.
```c
acc = acc + inputLength;
```
### Step 5. Consume remaining input
There may be up to 31 bytes remaining to consume from the input.
The final stage will digest them according to following pseudo-code:
```c
while (remainingLength >= 8) {
lane = read_64bit_little_endian(input_ptr);
acc = acc xor round(0, lane);
acc = (acc <<< 27) * PRIME64_1;
acc = acc + PRIME64_4;
input_ptr += 8; remainingLength -= 8;
}
if (remainingLength >= 4) {
lane = read_32bit_little_endian(input_ptr);
acc = acc xor (lane * PRIME64_1);
acc = (acc <<< 23) * PRIME64_2;
acc = acc + PRIME64_3;
input_ptr += 4; remainingLength -= 4;
}
while (remainingLength >= 1) {
lane = read_byte(input_ptr);
acc = acc xor (lane * PRIME64_5);
acc = (acc <<< 11) * PRIME64_1;
input_ptr += 1; remainingLength -= 1;
}
```
This process ensures that all input bytes are present in the final mix.
### Step 6. Final mix (avalanche)
The final mix ensures that all input bits have a chance to impact any bit in the output digest, resulting in an unbiased distribution. This is also called avalanche effect.
```c
acc = acc xor (acc >> 33);
acc = acc * PRIME64_2;
acc = acc xor (acc >> 29);
acc = acc * PRIME64_3;
acc = acc xor (acc >> 32);
```
### Step 7. Output
The `XXH64()` function produces an unsigned 64-bit value as output.
For systems which require to store and/or display the result in binary or hexadecimal format, the canonical format is defined to reproduce the same value as the natural decimal format, hence follows __big-endian__ convention (most significant byte first).
Performance considerations
----------------------------------
The xxHash algorithms are simple and compact to implement. They provide a system independent "fingerprint" or digest of a message of arbitrary length.
The algorithm allows input to be streamed and processed in multiple steps. In such case, an internal buffer is needed to ensure data is presented to the algorithm in full stripes.
On 64-bit systems, the 64-bit variant `XXH64` is generally faster to compute, so it is a recommended variant, even when only 32-bit are needed.
On 32-bit systems though, positions are reversed: `XXH64` performance is reduced, due to its usage of 64-bit arithmetic. `XXH32` becomes a faster variant.
Reference Implementation
----------------------------------------
A reference library written in C is available at https://www.xxhash.com.
The web page also links to multiple other implementations written in many different languages.
It links to the [github project page](https://github.com/Cyan4973/xxHash) where an [issue board](https://github.com/Cyan4973/xxHash/issues) can be used for further public discussions on the topic.
Version changes
--------------------
v0.7.3: Minor fixes
v0.1.1: added a note on rationale for selection of constants
v0.1.0: initial release
# xxHash - Extremely fast hash algorithm
# Copyright (C) 2012-2021, Yann Collet, Facebook
# BSD 2-Clause License (https://www.opensource.org/licenses/bsd-license.php)
prefix=@PREFIX@
exec_prefix=@EXECPREFIX@
includedir=@INCLUDEDIR@
libdir=@LIBDIR@
Name: xxhash
Description: extremely fast hash algorithm
URL: http://www.xxhash.com/
Version: @VERSION@
Libs: -L${libdir} -lxxhash
Cflags: -I${includedir}
# build artifacts
*.o
benchHash
benchHash32
benchHash_avx2
benchHash_hw
# test files
test*
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
/*
* Hash benchmark module
* Part of the xxHash project
* Copyright (C) 2019-2021 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
/* benchmark hash functions */
#include <stdlib.h> // malloc
#include <assert.h>
#include <string.h>
#include "benchHash.h"
static void initBuffer(void* buffer, size_t size)
{
const unsigned long long k1 = 11400714785074694791ULL; /* 0b1001111000110111011110011011000110000101111010111100101010000111 */
const unsigned long long k2 = 14029467366897019727ULL; /* 0b1100001010110010101011100011110100100111110101001110101101001111 */
unsigned long long acc = k2;
unsigned char* const p = (unsigned char*)buffer;
for (size_t s = 0; s < size; s++) {
acc *= k1;
p[s] = (unsigned char)(acc >> 56);
}
}
#define MARGIN_FOR_LATENCY 1024
#define START_MASK (MARGIN_FOR_LATENCY-1)
typedef size_t (*sizeFunction_f)(size_t targetSize);
/*
* bench_hash_internal():
* Benchmarks hashfn repeateadly over single input of size `size`
* return: nb of hashes per second
*/
static double
bench_hash_internal(BMK_benchFn_t hashfn, void* payload,
size_t nbBlocks, sizeFunction_f selectSize, size_t size,
unsigned total_time_ms, unsigned iter_time_ms)
{
BMK_timedFnState_shell shell;
BMK_timedFnState_t* const txf = BMK_initStatic_timedFnState(&shell, sizeof(shell), total_time_ms, iter_time_ms);
assert(txf != NULL);
size_t const srcSize = (size_t)size;
size_t const srcBufferSize = srcSize + MARGIN_FOR_LATENCY;
void* const srcBuffer = malloc(srcBufferSize);
assert(srcBuffer != NULL);
initBuffer(srcBuffer, srcBufferSize);
#define FAKE_DSTSIZE 32
size_t const dstSize = FAKE_DSTSIZE;
char dstBuffer_static[FAKE_DSTSIZE] = {0};
#define NB_BLOCKS_MAX 1024
const void* srcBuffers[NB_BLOCKS_MAX];
size_t srcSizes[NB_BLOCKS_MAX];
void* dstBuffers[NB_BLOCKS_MAX];
size_t dstCapacities[NB_BLOCKS_MAX];
assert(nbBlocks < NB_BLOCKS_MAX);
assert(size > 0);
for (size_t n=0; n < nbBlocks; n++) {
srcBuffers[n] = srcBuffer;
srcSizes[n] = selectSize(size);
dstBuffers[n] = dstBuffer_static;
dstCapacities[n] = dstSize;
}
BMK_benchParams_t params = {
.benchFn = hashfn,
.benchPayload = payload,
.initFn = NULL,
.initPayload = NULL,
.errorFn = NULL,
.blockCount = nbBlocks,
.srcBuffers = srcBuffers,
.srcSizes = srcSizes,
.dstBuffers = dstBuffers,
.dstCapacities = dstCapacities,
.blockResults = NULL
};
BMK_runOutcome_t result;
memset(&result, 0, sizeof(result));
while (!BMK_isCompleted_TimedFn(txf)) {
result = BMK_benchTimedFn(txf, params);
assert(BMK_isSuccessful_runOutcome(result));
}
BMK_runTime_t const runTime = BMK_extract_runTime(result);
free(srcBuffer);
assert(runTime.nanoSecPerRun != 0);
return (1000000000U / runTime.nanoSecPerRun) * nbBlocks;
}
static size_t rand_1_N(size_t N) { return ((size_t)rand() % N) + 1; }
static size_t identity(size_t s) { return s; }
static size_t
benchLatency(const void* src, size_t srcSize,
void* dst, size_t dstCapacity,
void* customPayload)
{
(void)dst; (void)dstCapacity;
BMK_benchFn_t benchfn = (BMK_benchFn_t)customPayload;
static size_t hash = 0;
const void* const start = (const char*)src + (hash & START_MASK);
return hash = benchfn(start, srcSize, dst, dstCapacity, NULL);
}
#ifndef SIZE_TO_HASH_PER_ROUND
# define SIZE_TO_HASH_PER_ROUND 200000
#endif
#ifndef NB_HASH_ROUNDS_MAX
# define NB_HASH_ROUNDS_MAX 1000
#endif
double bench_hash(BMK_benchFn_t hashfn,
BMK_benchMode benchMode,
size_t size, BMK_sizeMode sizeMode,
unsigned total_time_ms, unsigned iter_time_ms)
{
sizeFunction_f const sizef = (sizeMode == BMK_fixedSize) ? identity : rand_1_N;
BMK_benchFn_t const benchfn = (benchMode == BMK_throughput) ? hashfn : benchLatency;
BMK_benchFn_t const payload = (benchMode == BMK_throughput) ? NULL : hashfn;
size_t nbBlocks = (SIZE_TO_HASH_PER_ROUND / size) + 1;
if (nbBlocks > NB_HASH_ROUNDS_MAX) nbBlocks = NB_HASH_ROUNDS_MAX;
return bench_hash_internal(benchfn, payload,
nbBlocks, sizef, size,
total_time_ms, iter_time_ms);
}
/*
* Hash benchmark module
* Part of the xxHash project
* Copyright (C) 2019-2021 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
#ifndef BENCH_HASH_H_983426678
#define BENCH_HASH_H_983426678
#if defined (__cplusplus)
extern "C" {
#endif
/* === Dependencies === */
#include "benchfn.h" /* BMK_benchFn_t */
/* === Declarations === */
typedef enum { BMK_throughput, BMK_latency } BMK_benchMode;
typedef enum { BMK_fixedSize, /* hash always `size` bytes */
BMK_randomSize, /* hash a random nb of bytes, between 1 and `size` (inclusive) */
} BMK_sizeMode;
/*
* bench_hash():
* Returns speed expressed as nb hashes per second.
* total_time_ms: time spent benchmarking the hash function with given parameters
* iter_time_ms: time spent for one round. If multiple rounds are run,
* bench_hash() will report the speed of best round.
*/
double bench_hash(BMK_benchFn_t hashfn,
BMK_benchMode benchMode,
size_t size, BMK_sizeMode sizeMode,
unsigned total_time_ms, unsigned iter_time_ms);
#if defined (__cplusplus)
}
#endif
#endif /* BENCH_HASH_H_983426678 */
/*
* Copyright (C) 2016-2021 Yann Collet, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under both the BSD-style license (found in the
* LICENSE file in the root directory of this source tree) and the GPLv2 (found
* in the COPYING file in the root directory of this source tree).
* You may select, at your option, one of the above-listed licenses.
*/
/* *************************************
* Includes
***************************************/
#include <stdlib.h> /* malloc, free */
#include <string.h> /* memset */
#undef NDEBUG /* assert must not be disabled */
#include <assert.h> /* assert */
#include "timefn.h" /* UTIL_time_t, UTIL_getTime */
#include "benchfn.h"
/* *************************************
* Constants
***************************************/
#define TIMELOOP_MICROSEC SEC_TO_MICRO /* 1 second */
#define TIMELOOP_NANOSEC (1*1000000000ULL) /* 1 second */
#define KB *(1 <<10)
#define MB *(1 <<20)
#define GB *(1U<<30)
/* *************************************
* Debug errors
***************************************/
#if defined(DEBUG) && (DEBUG >= 1)
# include <stdio.h> /* fprintf */
# define DISPLAY(...) fprintf(stderr, __VA_ARGS__)
# define DEBUGOUTPUT(...) { if (DEBUG) DISPLAY(__VA_ARGS__); }
#else
# define DEBUGOUTPUT(...)
#endif
/* error without displaying */
#define RETURN_QUIET_ERROR(retValue, ...) { \
DEBUGOUTPUT("%s: %i: \n", __FILE__, __LINE__); \
DEBUGOUTPUT("Error : "); \
DEBUGOUTPUT(__VA_ARGS__); \
DEBUGOUTPUT(" \n"); \
return retValue; \
}
/* *************************************
* Benchmarking an arbitrary function
***************************************/
int BMK_isSuccessful_runOutcome(BMK_runOutcome_t outcome)
{
return outcome.error_tag_never_ever_use_directly == 0;
}
/* warning : this function will stop program execution if outcome is invalid !
* check outcome validity first, using BMK_isValid_runResult() */
BMK_runTime_t BMK_extract_runTime(BMK_runOutcome_t outcome)
{
assert(outcome.error_tag_never_ever_use_directly == 0);
return outcome.internal_never_ever_use_directly;
}
size_t BMK_extract_errorResult(BMK_runOutcome_t outcome)
{
assert(outcome.error_tag_never_ever_use_directly != 0);
return outcome.error_result_never_ever_use_directly;
}
static BMK_runOutcome_t BMK_runOutcome_error(size_t errorResult)
{
BMK_runOutcome_t b;
memset(&b, 0, sizeof(b));
b.error_tag_never_ever_use_directly = 1;
b.error_result_never_ever_use_directly = errorResult;
return b;
}
static BMK_runOutcome_t BMK_setValid_runTime(BMK_runTime_t runTime)
{
BMK_runOutcome_t outcome;
memset(&outcome, 0, sizeof(outcome));
outcome.error_tag_never_ever_use_directly = 0;
outcome.internal_never_ever_use_directly = runTime;
return outcome;
}
/* initFn will be measured once, benchFn will be measured `nbLoops` times */
/* initFn is optional, provide NULL if none */
/* benchFn must return a size_t value that errorFn can interpret */
/* takes # of blocks and list of size & stuff for each. */
/* can report result of benchFn for each block into blockResult. */
/* blockResult is optional, provide NULL if this information is not required */
/* note : time per loop can be reported as zero if run time < timer resolution */
BMK_runOutcome_t BMK_benchFunction(BMK_benchParams_t p,
unsigned nbLoops)
{
/* init */
{ size_t i;
for (i = 0; i < p.blockCount; i++) {
memset(p.dstBuffers[i], 0xE5, p.dstCapacities[i]); /* warm up and erase result buffer */
} }
/* benchmark */
{ UTIL_time_t const clockStart = UTIL_getTime();
size_t dstSize = 0;
unsigned loopNb, blockNb;
nbLoops += !nbLoops; /* minimum nbLoops is 1 */
if (p.initFn != NULL) p.initFn(p.initPayload);
for (loopNb = 0; loopNb < nbLoops; loopNb++) {
for (blockNb = 0; blockNb < p.blockCount; blockNb++) {
size_t const res = p.benchFn(p.srcBuffers[blockNb], p.srcSizes[blockNb],
p.dstBuffers[blockNb], p.dstCapacities[blockNb],
p.benchPayload);
if (loopNb == 0) {
if (p.blockResults != NULL) p.blockResults[blockNb] = res;
if ((p.errorFn != NULL) && (p.errorFn(res))) {
RETURN_QUIET_ERROR(BMK_runOutcome_error(res),
"Function benchmark failed on block %u (of size %u) with error %i",
blockNb, (unsigned)p.srcSizes[blockNb], (int)res);
}
dstSize += res;
} }
} /* for (loopNb = 0; loopNb < nbLoops; loopNb++) */
{ PTime const totalTime = UTIL_clockSpanNano(clockStart);
BMK_runTime_t rt;
rt.nanoSecPerRun = (double)totalTime / nbLoops;
rt.sumOfReturn = dstSize;
return BMK_setValid_runTime(rt);
} }
}
/* ==== Benchmarking any function, providing intermediate results ==== */
struct BMK_timedFnState_s {
PTime timeSpent_ns;
PTime timeBudget_ns;
PTime runBudget_ns;
BMK_runTime_t fastestRun;
unsigned nbLoops;
UTIL_time_t coolTime;
}; /* typedef'd to BMK_timedFnState_t within bench.h */
BMK_timedFnState_t* BMK_createTimedFnState(unsigned total_ms, unsigned run_ms)
{
BMK_timedFnState_t* const r = (BMK_timedFnState_t*)malloc(sizeof(*r));
if (r == NULL) return NULL; /* malloc() error */
BMK_resetTimedFnState(r, total_ms, run_ms);
return r;
}
void BMK_freeTimedFnState(BMK_timedFnState_t* state) { free(state); }
BMK_timedFnState_t*
BMK_initStatic_timedFnState(void* buffer, size_t size, unsigned total_ms, unsigned run_ms)
{
typedef char check_size[ 2 * (sizeof(BMK_timedFnState_shell) >= sizeof(struct BMK_timedFnState_s)) - 1]; /* static assert : a compilation failure indicates that BMK_timedFnState_shell is not large enough */
typedef struct { check_size c; BMK_timedFnState_t tfs; } tfs_align; /* force tfs to be aligned at its next best position */
size_t const tfs_alignment = offsetof(tfs_align, tfs); /* provides the minimal alignment restriction for BMK_timedFnState_t */
BMK_timedFnState_t* const r = (BMK_timedFnState_t*)buffer;
if (buffer == NULL) return NULL;
if (size < sizeof(struct BMK_timedFnState_s)) return NULL;
if ((size_t)buffer % tfs_alignment) return NULL; /* buffer must be properly aligned */
BMK_resetTimedFnState(r, total_ms, run_ms);
return r;
}
void BMK_resetTimedFnState(BMK_timedFnState_t* timedFnState, unsigned total_ms, unsigned run_ms)
{
if (!total_ms) total_ms = 1 ;
if (!run_ms) run_ms = 1;
if (run_ms > total_ms) run_ms = total_ms;
timedFnState->timeSpent_ns = 0;
timedFnState->timeBudget_ns = (PTime)total_ms * TIMELOOP_NANOSEC / 1000;
timedFnState->runBudget_ns = (PTime)run_ms * TIMELOOP_NANOSEC / 1000;
timedFnState->fastestRun.nanoSecPerRun = (double)TIMELOOP_NANOSEC * 2000000000; /* hopefully large enough : must be larger than any potential measurement */
timedFnState->fastestRun.sumOfReturn = (size_t)(-1LL);
timedFnState->nbLoops = 1;
timedFnState->coolTime = UTIL_getTime();
}
/* Tells if nb of seconds set in timedFnState for all runs is spent.
* note : this function will return 1 if BMK_benchFunctionTimed() has actually errored. */
int BMK_isCompleted_TimedFn(const BMK_timedFnState_t* timedFnState)
{
return (timedFnState->timeSpent_ns >= timedFnState->timeBudget_ns);
}
#undef MIN
#define MIN(a,b) ( (a) < (b) ? (a) : (b) )
#define MINUSABLETIME (TIMELOOP_NANOSEC / 2) /* 0.5 seconds */
BMK_runOutcome_t BMK_benchTimedFn(BMK_timedFnState_t* cont,
BMK_benchParams_t p)
{
PTime const runBudget_ns = cont->runBudget_ns;
PTime const runTimeMin_ns = runBudget_ns / 2;
BMK_runTime_t bestRunTime = cont->fastestRun;
for (;;) {
BMK_runOutcome_t const runResult = BMK_benchFunction(p, cont->nbLoops);
if (!BMK_isSuccessful_runOutcome(runResult)) { /* error : move out */
return runResult;
}
{ BMK_runTime_t const newRunTime = BMK_extract_runTime(runResult);
double const loopDuration_ns = newRunTime.nanoSecPerRun * cont->nbLoops;
cont->timeSpent_ns += (unsigned long long)loopDuration_ns;
/* estimate nbLoops for next run to last approximately 1 second */
if (loopDuration_ns > (runBudget_ns / 50)) {
double const fastestRun_ns = MIN(bestRunTime.nanoSecPerRun, newRunTime.nanoSecPerRun);
cont->nbLoops = (unsigned)(runBudget_ns / fastestRun_ns) + 1;
} else {
/* previous run was too short : blindly increase workload by x multiplier */
const unsigned multiplier = 10;
assert(cont->nbLoops < ((unsigned)-1) / multiplier); /* avoid overflow */
cont->nbLoops *= multiplier;
}
if (loopDuration_ns < runTimeMin_ns) {
/* When benchmark run time is too small : don't report results.
* increased risks of rounding errors */
continue;
}
if (newRunTime.nanoSecPerRun < bestRunTime.nanoSecPerRun) {
bestRunTime = newRunTime;
}
}
break;
} /* while (!completed) */
return BMK_setValid_runTime(bestRunTime);
}
/*
* Copyright (C) 2016-2021 Yann Collet, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under both the BSD-style license (found in the
* LICENSE file in the root directory of this source tree) and the GPLv2 (found
* in the COPYING file in the root directory of this source tree).
* You may select, at your option, one of the above-listed licenses.
*/
/* benchfn :
* benchmark any function on a set of input
* providing result in nanoSecPerRun
* or detecting and returning an error
*/
#if defined (__cplusplus)
extern "C" {
#endif
#ifndef BENCH_FN_H_23876
#define BENCH_FN_H_23876
/* === Dependencies === */
#include <stddef.h> /* size_t */
/* ==== Benchmark any function, iterated on a set of blocks ==== */
/* BMK_runTime_t: valid result return type */
typedef struct {
double nanoSecPerRun; /* time per iteration (over all blocks) */
size_t sumOfReturn; /* sum of return values */
} BMK_runTime_t;
/* BMK_runOutcome_t:
* type expressing the outcome of a benchmark run by BMK_benchFunction(),
* which can be either valid or invalid.
* benchmark outcome can be invalid if errorFn is provided.
* BMK_runOutcome_t must be considered "opaque" : never access its members directly.
* Instead, use its assigned methods :
* BMK_isSuccessful_runOutcome, BMK_extract_runTime, BMK_extract_errorResult.
* The structure is only described here to allow its allocation on stack. */
typedef struct {
BMK_runTime_t internal_never_ever_use_directly;
size_t error_result_never_ever_use_directly;
int error_tag_never_ever_use_directly;
} BMK_runOutcome_t;
/* prototypes for benchmarked functions */
typedef size_t (*BMK_benchFn_t)(const void* src, size_t srcSize, void* dst, size_t dstCapacity, void* customPayload);
typedef size_t (*BMK_initFn_t)(void* initPayload);
typedef unsigned (*BMK_errorFn_t)(size_t);
/* BMK_benchFunction() parameters are provided via the following structure.
* A structure is preferable for readability,
* as the number of parameters required is fairly large.
* No initializer is provided, because it doesn't make sense to provide some "default" :
* all parameters must be specified by the caller.
* optional parameters are labelled explicitly, and accept value NULL when not used */
typedef struct {
BMK_benchFn_t benchFn; /* the function to benchmark, over the set of blocks */
void* benchPayload; /* pass custom parameters to benchFn :
* (*benchFn)(srcBuffers[i], srcSizes[i], dstBuffers[i], dstCapacities[i], benchPayload) */
BMK_initFn_t initFn; /* (*initFn)(initPayload) is run once per run, at the beginning. */
void* initPayload; /* Both arguments can be NULL, in which case nothing is run. */
BMK_errorFn_t errorFn; /* errorFn will check each return value of benchFn over each block, to determine if it failed or not.
* errorFn can be NULL, in which case no check is performed.
* errorFn must return 0 when benchFn was successful, and >= 1 if it detects an error.
* Execution is stopped as soon as an error is detected.
* the triggering return value can be retrieved using BMK_extract_errorResult(). */
size_t blockCount; /* number of blocks to operate benchFn on.
* It's also the size of all array parameters :
* srcBuffers, srcSizes, dstBuffers, dstCapacities, blockResults */
const void *const * srcBuffers; /* read-only array of buffers to be operated on by benchFn */
const size_t* srcSizes; /* read-only array containing sizes of srcBuffers */
void *const * dstBuffers; /* array of buffers to be written into by benchFn. This array is not optional, it must be provided even if unused by benchfn. */
const size_t* dstCapacities; /* read-only array containing capacities of dstBuffers. This array must be present. */
size_t* blockResults; /* Optional: store the return value of benchFn for each block. Use NULL if this result is not requested. */
} BMK_benchParams_t;
/* BMK_benchFunction() :
* This function benchmarks benchFn and initFn, providing a result.
*
* params : see description of BMK_benchParams_t above.
* nbLoops: defines number of times benchFn is run over the full set of blocks.
* Minimum value is 1. A 0 is interpreted as a 1.
*
* @return: can express either an error or a successful result.
* Use BMK_isSuccessful_runOutcome() to check if benchmark was successful.
* If yes, extract the result with BMK_extract_runTime(),
* it will contain :
* .sumOfReturn : the sum of all return values of benchFn through all of blocks
* .nanoSecPerRun : time per run of benchFn + (time for initFn / nbLoops)
* .sumOfReturn is generally intended for functions which return a # of bytes written into dstBuffer,
* in which case, this value will be the total amount of bytes written into dstBuffer.
*
* blockResults : when provided (!= NULL), and when benchmark is successful,
* params.blockResults contains all return values of `benchFn` over all blocks.
* when provided (!= NULL), and when benchmark failed,
* params.blockResults contains return values of `benchFn` over all blocks preceding and including the failed block.
*/
BMK_runOutcome_t BMK_benchFunction(BMK_benchParams_t params, unsigned nbLoops);
/* check first if the benchmark was successful or not */
int BMK_isSuccessful_runOutcome(BMK_runOutcome_t outcome);
/* If the benchmark was successful, extract the result.
* note : this function will abort() program execution if benchmark failed !
* always check if benchmark was successful first !
*/
BMK_runTime_t BMK_extract_runTime(BMK_runOutcome_t outcome);
/* when benchmark failed, it means one invocation of `benchFn` failed.
* The failure was detected by `errorFn`, operating on return values of `benchFn`.
* Returns the faulty return value.
* note : this function will abort() program execution if benchmark did not failed.
* always check if benchmark failed first !
*/
size_t BMK_extract_errorResult(BMK_runOutcome_t outcome);
/* ==== Benchmark any function, returning intermediate results ==== */
/* state information tracking benchmark session */
typedef struct BMK_timedFnState_s BMK_timedFnState_t;
/* BMK_benchTimedFn() :
* Similar to BMK_benchFunction(), most arguments being identical.
* Automatically determines `nbLoops` so that each result is regularly produced at interval of about run_ms.
* Note : minimum `nbLoops` is 1, therefore a run may last more than run_ms, and possibly even more than total_ms.
* Usage - initialize timedFnState, select benchmark duration (total_ms) and each measurement duration (run_ms)
* call BMK_benchTimedFn() repetitively, each measurement is supposed to last about run_ms
* Check if total time budget is spent or exceeded, using BMK_isCompleted_TimedFn()
*/
BMK_runOutcome_t BMK_benchTimedFn(BMK_timedFnState_t* timedFnState,
BMK_benchParams_t params);
/* Tells if duration of all benchmark runs has exceeded total_ms
*/
int BMK_isCompleted_TimedFn(const BMK_timedFnState_t* timedFnState);
/* BMK_createTimedFnState() and BMK_resetTimedFnState() :
* Create/Set BMK_timedFnState_t for next benchmark session,
* which shall last a minimum of total_ms milliseconds,
* producing intermediate results, paced at interval of (approximately) run_ms.
*/
BMK_timedFnState_t* BMK_createTimedFnState(unsigned total_ms, unsigned run_ms);
void BMK_resetTimedFnState(BMK_timedFnState_t* timedFnState, unsigned total_ms, unsigned run_ms);
void BMK_freeTimedFnState(BMK_timedFnState_t* state);
/* BMK_timedFnState_shell and BMK_initStatic_timedFnState() :
* Makes it possible to statically allocate a BMK_timedFnState_t on stack.
* BMK_timedFnState_shell is only there to allocate space,
* never ever access its members.
* BMK_timedFnState_t() actually accepts any buffer.
* It will check if provided buffer is large enough and is correctly aligned,
* and will return NULL if conditions are not respected.
*/
#define BMK_TIMEDFNSTATE_SIZE 64
typedef union {
char never_access_space[BMK_TIMEDFNSTATE_SIZE];
long long alignment_enforcer; /* must be aligned on 8-bytes boundaries */
} BMK_timedFnState_shell;
BMK_timedFnState_t* BMK_initStatic_timedFnState(void* buffer, size_t size, unsigned total_ms, unsigned run_ms);
#endif /* BENCH_FN_H_23876 */
#if defined (__cplusplus)
}
#endif
/*
* CSV Display module for the hash benchmark program
* Part of the xxHash project
* Copyright (C) 2019-2021 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at :
* - xxHash homepage : https://www.xxhash.com
* - xxHash source repository : https://github.com/Cyan4973/xxHash
*/
/* === Dependencies === */
#include <stdlib.h> /* rand */
#include <stdio.h> /* printf */
#include <assert.h>
#include "benchHash.h"
#include "bhDisplay.h"
/* === benchmark large input === */
#define MB_UNIT 1000000
#define BENCH_LARGE_ITER_MS 490
#define BENCH_LARGE_TOTAL_MS 1010
static void bench_oneHash_largeInput(Bench_Entry hashDesc, int minlog, int maxlog)
{
printf("%-7s", hashDesc.name);
for (int sizelog=minlog; sizelog<=maxlog; sizelog++) {
size_t const inputSize = (size_t)1 << sizelog;
double const nbhps = bench_hash(hashDesc.hash, BMK_throughput,
inputSize, BMK_fixedSize,
BENCH_LARGE_TOTAL_MS, BENCH_LARGE_ITER_MS);
printf(",%6.0f", nbhps * inputSize / MB_UNIT); fflush(NULL);
}
printf("\n");
}
void bench_largeInput(Bench_Entry const* hashDescTable, int nbHashes, int minlog, int maxlog)
{
assert(maxlog < 31);
assert(minlog >= 0);
printf("benchmarking large inputs : from %u bytes (log%i) to %u MB (log%i) \n",
1U << minlog, minlog,
(1U << maxlog) >> 20, maxlog);
for (int i=0; i<nbHashes; i++)
bench_oneHash_largeInput(hashDescTable[i], minlog, maxlog);
}
/* === Benchmark small inputs === */
#define BENCH_SMALL_ITER_MS 170
#define BENCH_SMALL_TOTAL_MS 490
static void bench_throughput_oneHash_smallInputs(Bench_Entry hashDesc, size_t sizeMin, size_t sizeMax)
{
printf("%-7s", hashDesc.name);
for (size_t s=sizeMin; s<sizeMax+1; s++) {
double const nbhps = bench_hash(hashDesc.hash, BMK_throughput,
s, BMK_fixedSize,
BENCH_SMALL_TOTAL_MS, BENCH_SMALL_ITER_MS);
printf(",%10.0f", nbhps); fflush(NULL);
}
printf("\n");
}
void bench_throughput_smallInputs(Bench_Entry const* hashDescTable, int nbHashes, size_t sizeMin, size_t sizeMax)
{
printf("Throughput small inputs of fixed size (from %zu to %zu bytes): \n",
sizeMin, sizeMax);
for (int i=0; i<nbHashes; i++)
bench_throughput_oneHash_smallInputs(hashDescTable[i], sizeMin, sizeMax);
}
/* === Latency measurements (small keys) === */
static void bench_latency_oneHash_smallInputs(Bench_Entry hashDesc, size_t size_min, size_t size_max)
{
printf("%-7s", hashDesc.name);
for (size_t s=size_min; s<size_max+1; s++) {
double const nbhps = bench_hash(hashDesc.hash, BMK_latency,
s, BMK_fixedSize,
BENCH_SMALL_TOTAL_MS, BENCH_SMALL_ITER_MS);
printf(",%10.0f", nbhps); fflush(NULL);
}
printf("\n");
}
void bench_latency_smallInputs(Bench_Entry const* hashDescTable, int nbHashes, size_t size_min, size_t size_max)
{
printf("Latency for small inputs of fixed size : \n");
for (int i=0; i<nbHashes; i++)
bench_latency_oneHash_smallInputs(hashDescTable[i], size_min, size_max);
}
/* === Random input Length === */
static void bench_randomInputLength_withOneHash(Bench_Entry hashDesc, size_t size_min, size_t size_max)
{
printf("%-7s", hashDesc.name);
for (size_t s=size_min; s<size_max+1; s++) {
srand((unsigned)s); /* ensure random sequence of length will be the same for a given s */
double const nbhps = bench_hash(hashDesc.hash, BMK_throughput,
s, BMK_randomSize,
BENCH_SMALL_TOTAL_MS, BENCH_SMALL_ITER_MS);
printf(",%10.0f", nbhps); fflush(NULL);
}
printf("\n");
}
void bench_throughput_randomInputLength(Bench_Entry const* hashDescTable, int nbHashes, size_t size_min, size_t size_max)
{
printf("benchmarking random size inputs [1-N] : \n");
for (int i=0; i<nbHashes; i++)
bench_randomInputLength_withOneHash(hashDescTable[i], size_min, size_max);
}
/* === Latency with Random input Length === */
static void bench_latency_oneHash_randomInputLength(Bench_Entry hashDesc, size_t size_min, size_t size_max)
{
printf("%-7s", hashDesc.name);
for (size_t s=size_min; s<size_max+1; s++) {
srand((unsigned)s); /* ensure random sequence of length will be the same for a given s */
double const nbhps = bench_hash(hashDesc.hash, BMK_latency,
s, BMK_randomSize,
BENCH_SMALL_TOTAL_MS, BENCH_SMALL_ITER_MS);
printf(",%10.0f", nbhps); fflush(NULL);
}
printf("\n");
}
void bench_latency_randomInputLength(Bench_Entry const* hashDescTable, int nbHashes, size_t size_min, size_t size_max)
{
printf("Latency for small inputs of random size [1-N] : \n");
for (int i=0; i<nbHashes; i++)
bench_latency_oneHash_randomInputLength(hashDescTable[i], size_min, size_max);
}
/*
* CSV Display module for the hash benchmark program
* Part of the xxHash project
* Copyright (C) 2019-2021 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
#ifndef BH_DISPLAY_H_192088098
#define BH_DISPLAY_H_192088098
#if defined (__cplusplus)
extern "C" {
#endif
/* === Dependencies === */
#include "benchfn.h" /* BMK_benchFn_t */
/* === Declarations === */
typedef struct {
const char* name;
BMK_benchFn_t hash;
} Bench_Entry;
void bench_largeInput(Bench_Entry const* hashDescTable, int nbHashes, int sizeLogMin, int sizeLogMax);
void bench_throughput_smallInputs(Bench_Entry const* hashDescTable, int nbHashes, size_t sizeMin, size_t sizeMax);
void bench_throughput_randomInputLength(Bench_Entry const* hashDescTable, int nbHashes, size_t sizeMin, size_t sizeMax);
void bench_latency_smallInputs(Bench_Entry const* hashDescTable, int nbHashes, size_t sizeMin, size_t sizeMax);
void bench_latency_randomInputLength(Bench_Entry const* hashDescTable, int nbHashes, size_t sizeMin, size_t sizeMax);
#if defined (__cplusplus)
}
#endif
#endif /* BH_DISPLAY_H_192088098 */
/*
* List hash algorithms to benchmark
* Part of xxHash project
* Copyright (C) 2019-2021 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
/* === Dependencies === */
#include <stddef.h> /* size_t */
/* ==================================================
* Non-portable hash algorithms
* =============================================== */
#ifdef HARDWARE_SUPPORT
/*
* List any hash algorithms that depend on specific hardware support,
* including for example:
* - Hardware crc32c
* - Hardware AES support
* - Carryless Multipliers (clmul)
* - AVX2
*/
#endif
/* ==================================================
* List of hashes
* ==================================================
* Each hash must be wrapped in a thin redirector conformant with the BMK_benchfn_t.
* BMK_benchfn_t is generic, not specifically designed for hashes.
* For hashes, the following parameters are expected to be useless:
* dst, dstCapacity, customPayload.
*
* The result of each hash is assumed to be provided as function return value.
* This condition is important for latency measurements.
*/
/* === xxHash === */
#define XXH_INLINE_ALL
#include "xxhash.h"
size_t XXH32_wrapper(const void* src, size_t srcSize, void* dst, size_t dstCapacity, void* customPayload)
{
(void)dst; (void)dstCapacity; (void)customPayload;
return (size_t) XXH32(src, srcSize, 0);
}
size_t XXH64_wrapper(const void* src, size_t srcSize, void* dst, size_t dstCapacity, void* customPayload)
{
(void)dst; (void)dstCapacity; (void)customPayload;
return (size_t) XXH64(src, srcSize, 0);
}
size_t xxh3_wrapper(const void* src, size_t srcSize, void* dst, size_t dstCapacity, void* customPayload)
{
(void)dst; (void)dstCapacity; (void)customPayload;
return (size_t) XXH3_64bits(src, srcSize);
}
size_t XXH128_wrapper(const void* src, size_t srcSize, void* dst, size_t dstCapacity, void* customPayload)
{
(void)dst; (void)dstCapacity; (void)customPayload;
return (size_t) XXH3_128bits(src, srcSize).low64;
}
/* ==================================================
* Table of hashes
* =============================================== */
#include "bhDisplay.h" /* Bench_Entry */
#ifndef HARDWARE_SUPPORT
# define NB_HASHES 4
#else
# define NB_HASHES 4
#endif
Bench_Entry const hashCandidates[NB_HASHES] = {
{ "xxh3" , xxh3_wrapper },
{ "XXH32" , XXH32_wrapper },
{ "XXH64" , XXH64_wrapper },
{ "XXH128", XXH128_wrapper },
#ifdef HARDWARE_SUPPORT
/* list here codecs which require specific hardware support, such SSE4.1, PCLMUL, AVX2, etc. */
#endif
};
/*
* Main program to benchmark hash functions
* Part of the xxHash project
* Copyright (C) 2019-2021 Yann Collet
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
/* === dependencies === */
#include <stdio.h> /* printf */
#include <limits.h> /* INT_MAX */
#include "bhDisplay.h" /* bench_x */
/* === defines list of hashes `hashCandidates` and NB_HASHES *** */
#include "hashes.h"
/* === parse command line === */
#undef NDEBUG
#include <assert.h>
/*!
* readIntFromChar():
* Allows and interprets K, KB, KiB, M, MB and MiB suffix.
* Will also modify `*stringPtr`, advancing it to position where it stopped reading.
*/
static int readIntFromChar(const char** stringPtr)
{
static int const max = (INT_MAX / 10) - 1;
int result = 0;
while ((**stringPtr >='0') && (**stringPtr <='9')) {
assert(result < max);
result *= 10;
result += (unsigned)(**stringPtr - '0');
(*stringPtr)++ ;
}
if ((**stringPtr=='K') || (**stringPtr=='M')) {
int const maxK = INT_MAX >> 10;
assert(result < maxK);
result <<= 10;
if (**stringPtr=='M') {
assert(result < maxK);
result <<= 10;
}
(*stringPtr)++; /* skip `K` or `M` */
if (**stringPtr=='i') (*stringPtr)++;
if (**stringPtr=='B') (*stringPtr)++;
}
return result;
}
/**
* isCommand():
* Checks if string is the same as longCommand.
* If yes, @return 1, otherwise @return 0
*/
static int isCommand(const char* string, const char* longCommand)
{
assert(string);
assert(longCommand);
size_t const comSize = strlen(longCommand);
return !strncmp(string, longCommand, comSize);
}
/*
* longCommandWArg():
* Checks if *stringPtr is the same as longCommand.
* If yes, @return 1 and advances *stringPtr to the position which immediately
* follows longCommand.
* @return 0 and doesn't modify *stringPtr otherwise.
*/
static int longCommandWArg(const char** stringPtr, const char* longCommand)
{
assert(stringPtr);
assert(longCommand);
size_t const comSize = strlen(longCommand);
int const result = isCommand(*stringPtr, longCommand);
if (result) *stringPtr += comSize;
return result;
}
/* === default values - can be redefined at compilation time === */
#ifndef SMALL_SIZE_MIN_DEFAULT
# define SMALL_SIZE_MIN_DEFAULT 1
#endif
#ifndef SMALL_SIZE_MAX_DEFAULT
# define SMALL_SIZE_MAX_DEFAULT 127
#endif
#ifndef LARGE_SIZELOG_MIN_DEFAULT
# define LARGE_SIZELOG_MIN_DEFAULT 9
#endif
#ifndef LARGE_SIZELOG_MAX_DEFAULT
# define LARGE_SIZELOG_MAX_DEFAULT 27
#endif
static int display_hash_names(void)
{
int i;
printf("available hashes : \n");
for (i=0; i<NB_HASHES; i++) {
printf("%s, ", hashCandidates[i].name);
}
printf("\b\b \n");
return 0;
}
/*
* @return: hashID (necessarily between 0 and NB_HASHES) if present
* -1 on error (hname not present)
*/
static int hashID(const char* hname)
{
int id;
assert(hname);
for (id=0; id < NB_HASHES; id++) {
assert(hashCandidates[id].name);
if (strlen(hname) != strlen(hashCandidates[id].name)) continue;
if (isCommand(hname, hashCandidates[id].name)) return id;
}
return -1;
}
static int help(const char* exename)
{
printf("Usage: %s [options]... [hash]\n", exename);
printf("Runs various benchmarks at various lengths for the listed hash functions\n");
printf("and outputs them in a CSV format.\n\n");
printf("Options: \n");
printf(" --list Name available hash algorithms and exit \n");
printf(" --mins=LEN Starting length for small size bench (default: %i) \n", SMALL_SIZE_MIN_DEFAULT);
printf(" --maxs=LEN End length for small size bench (default: %i) \n", SMALL_SIZE_MAX_DEFAULT);
printf(" --minl=LEN Starting log2(length) for large size bench (default: %i) \n", LARGE_SIZELOG_MIN_DEFAULT);
printf(" --maxl=LEN End log2(length) for large size bench (default: %i) \n", LARGE_SIZELOG_MAX_DEFAULT);
printf(" [hash] Optional, bench all available hashes if not provided \n");
return 0;
}
static int badusage(const char* exename)
{
printf("Bad command ... \n");
help(exename);
return 1;
}
int main(int argc, const char* argv[])
{
const char* const exename = argv[0];
int hashNb = 0;
int nb_h_test = NB_HASHES;
int largeTest_log_min = LARGE_SIZELOG_MIN_DEFAULT;
int largeTest_log_max = LARGE_SIZELOG_MAX_DEFAULT;
size_t smallTest_size_min = SMALL_SIZE_MIN_DEFAULT;
size_t smallTest_size_max = SMALL_SIZE_MAX_DEFAULT;
int arg_nb;
for (arg_nb = 1; arg_nb < argc; arg_nb++) {
const char** arg = argv + arg_nb;
if (isCommand(*arg, "-h")) { assert(argc >= 1); return help(exename); }
if (isCommand(*arg, "--list")) { return display_hash_names(); }
if (longCommandWArg(arg, "--n=")) { nb_h_test = readIntFromChar(arg); continue; } /* hidden command */
if (longCommandWArg(arg, "--minl=")) { largeTest_log_min = readIntFromChar(arg); continue; }
if (longCommandWArg(arg, "--maxl=")) { largeTest_log_max = readIntFromChar(arg); continue; }
if (longCommandWArg(arg, "--mins=")) { smallTest_size_min = (size_t)readIntFromChar(arg); continue; }
if (longCommandWArg(arg, "--maxs=")) { smallTest_size_max = (size_t)readIntFromChar(arg); continue; }
/* not a command: must be a hash name */
hashNb = hashID(*arg);
if (hashNb >= 0) {
nb_h_test = 1;
} else {
/* not a hash name: error */
return badusage(exename);
}
}
/* border case (requires (mis)using hidden command `--n=#`) */
if (hashNb + nb_h_test > NB_HASHES) {
printf("wrong hash selection \n");
return 1;
}
printf(" === benchmarking %i hash functions === \n", nb_h_test);
if (largeTest_log_max >= largeTest_log_min) {
bench_largeInput(hashCandidates+hashNb, nb_h_test, largeTest_log_min, largeTest_log_max);
}
if (smallTest_size_max >= smallTest_size_min) {
bench_throughput_smallInputs(hashCandidates+hashNb, nb_h_test, smallTest_size_min, smallTest_size_max);
bench_throughput_randomInputLength(hashCandidates+hashNb, nb_h_test, smallTest_size_min, smallTest_size_max);
bench_latency_smallInputs(hashCandidates+hashNb, nb_h_test, smallTest_size_min, smallTest_size_max);
bench_latency_randomInputLength(hashCandidates+hashNb, nb_h_test, smallTest_size_min, smallTest_size_max);
}
return 0;
}
/*
* Copyright (C) 2019-2021 Yann Collet, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under both the BSD-style license (found in the
* LICENSE file in the root directory of this source tree) and the GPLv2 (found
* in the COPYING file in the root directory of this source tree).
* You may select, at your option, one of the above-listed licenses.
*/
/* === Dependencies === */
#include "timefn.h"
/*-****************************************
* Time functions
******************************************/
#if defined(_WIN32) /* Windows */
#include <stdlib.h> /* abort */
#include <stdio.h> /* perror */
UTIL_time_t UTIL_getTime(void) { UTIL_time_t x; QueryPerformanceCounter(&x); return x; }
PTime UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd)
{
static LARGE_INTEGER ticksPerSecond;
static int init = 0;
if (!init) {
if (!QueryPerformanceFrequency(&ticksPerSecond)) {
perror("timefn::QueryPerformanceFrequency");
abort();
}
init = 1;
}
return 1000000ULL*(clockEnd.QuadPart - clockStart.QuadPart)/ticksPerSecond.QuadPart;
}
PTime UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd)
{
static LARGE_INTEGER ticksPerSecond;
static int init = 0;
if (!init) {
if (!QueryPerformanceFrequency(&ticksPerSecond)) {
perror("timefn::QueryPerformanceFrequency");
abort();
}
init = 1;
}
return 1000000000ULL*(clockEnd.QuadPart - clockStart.QuadPart)/ticksPerSecond.QuadPart;
}
#elif defined(__APPLE__) && defined(__MACH__)
UTIL_time_t UTIL_getTime(void) { return mach_absolute_time(); }
PTime UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd)
{
static mach_timebase_info_data_t rate;
static int init = 0;
if (!init) {
mach_timebase_info(&rate);
init = 1;
}
return (((clockEnd - clockStart) * (PTime)rate.numer) / ((PTime)rate.denom))/1000ULL;
}
PTime UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd)
{
static mach_timebase_info_data_t rate;
static int init = 0;
if (!init) {
mach_timebase_info(&rate);
init = 1;
}
return ((clockEnd - clockStart) * (PTime)rate.numer) / ((PTime)rate.denom);
}
#elif (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* C11 */) \
&& defined(TIME_UTC) /* C11 requires timespec_get, but FreeBSD 11 lacks it, while still claiming C11 compliance */
#include <stdlib.h> /* abort */
#include <stdio.h> /* perror */
UTIL_time_t UTIL_getTime(void)
{
/* time must be initialized, othersize it may fail msan test.
* No good reason, likely a limitation of timespec_get() for some target */
UTIL_time_t time = UTIL_TIME_INITIALIZER;
if (timespec_get(&time, TIME_UTC) != TIME_UTC) {
perror("timefn::timespec_get");
abort();
}
return time;
}
static UTIL_time_t UTIL_getSpanTime(UTIL_time_t begin, UTIL_time_t end)
{
UTIL_time_t diff;
if (end.tv_nsec < begin.tv_nsec) {
diff.tv_sec = (end.tv_sec - 1) - begin.tv_sec;
diff.tv_nsec = (end.tv_nsec + 1000000000ULL) - begin.tv_nsec;
} else {
diff.tv_sec = end.tv_sec - begin.tv_sec;
diff.tv_nsec = end.tv_nsec - begin.tv_nsec;
}
return diff;
}
PTime UTIL_getSpanTimeMicro(UTIL_time_t begin, UTIL_time_t end)
{
UTIL_time_t const diff = UTIL_getSpanTime(begin, end);
PTime micro = 0;
micro += 1000000ULL * diff.tv_sec;
micro += diff.tv_nsec / 1000ULL;
return micro;
}
PTime UTIL_getSpanTimeNano(UTIL_time_t begin, UTIL_time_t end)
{
UTIL_time_t const diff = UTIL_getSpanTime(begin, end);
PTime nano = 0;
nano += 1000000000ULL * diff.tv_sec;
nano += diff.tv_nsec;
return nano;
}
#else /* relies on standard C90 (note : clock_t measurements can be wrong when using multi-threading) */
UTIL_time_t UTIL_getTime(void) { return clock(); }
PTime UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd) { return 1000000ULL * (clockEnd - clockStart) / CLOCKS_PER_SEC; }
PTime UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd) { return 1000000000ULL * (clockEnd - clockStart) / CLOCKS_PER_SEC; }
#endif
/* returns time span in microseconds */
PTime UTIL_clockSpanMicro(UTIL_time_t clockStart )
{
UTIL_time_t const clockEnd = UTIL_getTime();
return UTIL_getSpanTimeMicro(clockStart, clockEnd);
}
/* returns time span in microseconds */
PTime UTIL_clockSpanNano(UTIL_time_t clockStart )
{
UTIL_time_t const clockEnd = UTIL_getTime();
return UTIL_getSpanTimeNano(clockStart, clockEnd);
}
void UTIL_waitForNextTick(void)
{
UTIL_time_t const clockStart = UTIL_getTime();
UTIL_time_t clockEnd;
do {
clockEnd = UTIL_getTime();
} while (UTIL_getSpanTimeNano(clockStart, clockEnd) == 0);
}
/*
* Copyright (c) 2016-2021 Yann Collet, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under both the BSD-style license (found in the
* LICENSE file in the root directory of this source tree) and the GPLv2 (found
* in the COPYING file in the root directory of this source tree).
* You may select, at your option, one of the above-listed licenses.
*/
#ifndef TIME_FN_H_MODULE_287987
#define TIME_FN_H_MODULE_287987
#if defined (__cplusplus)
extern "C" {
#endif
/*-****************************************
* Dependencies
******************************************/
#include <sys/types.h> /* utime */
#if defined(_MSC_VER)
# include <sys/utime.h> /* utime */
#else
# include <utime.h> /* utime */
#endif
#include <time.h> /* clock_t, clock, CLOCKS_PER_SEC */
/*-****************************************
* Local Types
******************************************/
#if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )
# include <stdint.h>
typedef uint64_t PTime; /* Precise Time */
#else
typedef unsigned long long PTime; /* does not support compilers without long long support */
#endif
/*-****************************************
* Time functions
******************************************/
#if defined(_WIN32) /* Windows */
#include <Windows.h> /* LARGE_INTEGER */
typedef LARGE_INTEGER UTIL_time_t;
#define UTIL_TIME_INITIALIZER { { 0, 0 } }
#elif defined(__APPLE__) && defined(__MACH__)
#include <mach/mach_time.h>
typedef PTime UTIL_time_t;
#define UTIL_TIME_INITIALIZER 0
#elif (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) /* C11 */) \
&& defined(TIME_UTC) /* C11 requires timespec_get, but FreeBSD 11 lacks it, while still claiming C11 compliance */
typedef struct timespec UTIL_time_t;
#define UTIL_TIME_INITIALIZER { 0, 0 }
#else /* relies on standard C90 (note : clock_t measurements can be wrong when using multi-threading) */
typedef clock_t UTIL_time_t;
#define UTIL_TIME_INITIALIZER 0
#endif
UTIL_time_t UTIL_getTime(void);
PTime UTIL_getSpanTimeMicro(UTIL_time_t clockStart, UTIL_time_t clockEnd);
PTime UTIL_getSpanTimeNano(UTIL_time_t clockStart, UTIL_time_t clockEnd);
#define SEC_TO_MICRO ((PTime)1000000)
PTime UTIL_clockSpanMicro(UTIL_time_t clockStart);
PTime UTIL_clockSpanNano(UTIL_time_t clockStart);
void UTIL_waitForNextTick(void);
#if defined (__cplusplus)
}
#endif
#endif /* TIME_FN_H_MODULE_287987 */
#!/bin/bash
# Exit immediately if any command fails.
# https://stackoverflow.com/a/2871034
set -euxo
# Default
./xxhsum ./Makefile > ./.test.xxh
echo '# Test comment line' | cat - ./.test.xxh > temp && mv temp ./.test.xxh
./xxhsum --check ./.test.xxh
# XXH32
./xxhsum -H32 ./Makefile > ./.test.xxh32
echo '# Test comment line' | cat - ./.test.xxh32 > temp && mv temp ./.test.xxh32
./xxhsum --check ./.test.xxh32
# XXH64
./xxhsum -H64 ./Makefile > ./.test.xxh64
echo '# Test comment line' | cat - ./.test.xxh64 > temp && mv temp ./.test.xxh64
./xxhsum --check ./.test.xxh64
# XXH128
./xxhsum -H128 ./Makefile > ./.test.xxh128
echo '# Test comment line' | cat - ./.test.xxh128 > temp && mv temp ./.test.xxh128
./xxhsum --check ./.test.xxh128
rm ./.test.xxh
rm ./.test.xxh32
rm ./.test.xxh64
rm ./.test.xxh128
#build artefacts
collisionsTest
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
__collisionsTest__ is a brute force hash analyzer
which will measure a 64-bit hash algorithm's collision rate
by generating billions of hashes,
and comparing the result to an "ideal" target.
The test requires a very large amount of memory.
By default, it will generate 24 billion of 64-bit hashes,
requiring __192 GB of RAM__ for their storage.
The number of hashes can be modified using command `--nbh=`.
Be aware that testing the collision ratio of 64-bit hashes
requires a very large amount of hashes (several billion) for meaningful measurements.
To reduce RAM usage, an optional filter can be requested, with `--filter`.
It reduces the nb of candidates to analyze, hence associated RAM budget.
Note that the filter itself requires a lot of RAM
(32 GB by default, can be modified using `--filterlog=`,
a too small filter will not be efficient, aim at ~2 bytes per hash),
and reading and writing into filter cost a significant CPU budget,
so this method is slower.
It also doesn't allow advanced analysis of partial bitfields,
since most hashes will be discarded and not stored.
When using the filter, the RAM budget consists of the filter and a list of candidates,
which will be a fraction of the original hash list.
Using default settings (24 billion hashes, 32 GB filter),
the number of potential candidates should be reduced to less than 2 billion,
requiring ~14 GB for their storage.
Such a result also depends on hash algorithm's efficiency.
The number of effective candidates is likely to be lower, at ~ 1 billion,
but storage must allocate an upper bound.
For the default test, the expected "optimal" collision rate for a 64-bit hash function is ~18 collisions.
#### How to build
```
make
```
Note: the code is a mix of C99 and C++14,
it's not compatible with a C90-only compiler.
#### Build modifier
- `SLAB5`: use alternative pattern generator, friendlier for weak hash algorithms
- `POOL_MT`: if `=0`, disable multi-threading code (enabled by default)
#### How to integrate any hash in the tester
The build script will compile files found in `./allcodecs`.
Put the source code here.
This also works if the hash is a single `*.h` file.
The glue happens in `hashes.h`.
In this file, there are 2 sections:
- Adds the required `#include "header.h"`, and creates a wrapper
to respect the format expected by the function pointer.
- Adds the wrapper, along with the name and an indication of the output width,
to the table, at the end of `hashes.h`
Build with `make`. Locate your new hash with `./collisionsTest -h`,
it should be listed.
#### Usage
```
usage: ./collisionsTest [hashName] [opt]
list of hashNames: (...)
Optional parameters:
--nbh=NB Select nb of hashes to generate (25769803776 by default)
--filter Enable the filter. Slower, but reduces memory usage for same nb of hashes.
--threadlog=NB Use 2^NB threads
--len=NB Select length of input (255 bytes by default)
```
#### Some advises on how to setup a collisions test
Most tests are primarily driven by the amount of RAM available.
Here's a method to decide the size of the test.
Presuming that RAM budget is not plentiful, for this example 32 GB,
the `--filter` mode is actually compulsory to measure anything meaningful.
Let's plan 50% of memory for the filter, that's 16 GB.
This will be good enough to filter about 10% less hashes than this size.
Let's round down to 14 G.
By requesting 14G, the expectation is that the program will automatically
size the filter to 16 GB, and expect to store ~1G candidates,
leaving enough room to breeze for the system.
The command line becomes:
```
./collisionsTest --nbh=14G --filter NameOfHash
```
#### Examples:
Here are a few results produced with this tester:
| Algorithm | Input Len | Nb Hashes | Expected | Nb Collisions | Notes |
| --- | --- | --- | --- | --- | --- |
| __XXH3__ | 255 | 100 Gi | 312.5 | 326 | |
| __XXH64__ | 255 | 100 Gi | 312.5 | 294 | |
| __XXH128__ low64 | 512 | 100 Gi | 312.5 | 321 | |
| __XXH128__ high64| 512 | 100 Gi | 312.5 | 325 | |
| __XXH128__ | 255 | 100 Gi | 0.0 | 0 | a 128-bit hash is expected to generate 0 collisions |
Test on small inputs:
| Algorithm | Input Len | Nb Hashes | Expected | Nb Collisions | Notes |
| --- | --- | --- | --- | --- | --- |
| __XXH64__ | 8 | 100 Gi | 312.5 | __0__ | `XXH64` is bijective for `len==8` |
| __XXH3__ | 8 | 100 Gi | 312.5 | __0__ | `XXH3` is also bijective for `len==8` |
| __XXH3__ | 16 | 100 Gi | 312.5 | 332 | |
| __XXH3__ | 32 | 14 Gi | 6.1 | 3 | |
| __XXH128__ | 16 | 25 Gi | 0.0 | 0 | test range 9-16 |
| __XXH128__ | 32 | 25 Gi | 0.0 | 0 | test range 17-128 |
| __XXH128__ | 100 | 13 Gi | 0.0 | 0 | test range 17-128 |
| __XXH128__ | 200 | 13 Gi | 0.0 | 0 | test range 129-240 |
Put in this directory all hash algorithms to test
/*
* dummy.c, a fake hash algorithm, just to test integration capabilities.
* Part of the xxHash project
* Copyright (C) 2020 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
#include <dummy.h>
unsigned badsum32(const void* input, size_t len, unsigned seed)
{
unsigned sum = seed;
const unsigned char* in8 = input;
size_t c;
for (c=0; c<len; c++)
sum += in8[c];
return sum;
}
/*
* dummy.c,
* A fake hash algorithm, just to test integration capabilities.
* Part of the xxHash project
* Copyright (C) 2020 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
#ifndef DUMMY_H_987987
#define DUMMY_H_987987
#if defined (__cplusplus)
extern "C" {
#endif
#include <stddef.h> /* size_t */
unsigned badsum32(const void* input, size_t len, unsigned seed);
#if defined (__cplusplus)
}
#endif
#endif /* DUMMY_H_987987 */
/*
* List of hashes for the brute force collision tester
* Part of xxHash project
* Copyright (C) 2019-2021 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
#ifndef HASHES_H_1235465
#define HASHES_H_1235465
#include <stddef.h> /* size_t */
#include <stdint.h> /* uint64_t */
#define XXH_INLINE_ALL /* XXH128_hash_t */
#include "xxhash.h"
/* return type */
typedef union {
uint64_t h64;
XXH128_hash_t h128;
} UniHash;
UniHash uniHash32(uint64_t v32)
{ UniHash unih;
unih.h64 = v32;
return unih;
}
UniHash uniHash64(uint64_t v64)
{ UniHash unih;
unih.h64 = v64;
return unih;
}
UniHash uniHash128(XXH128_hash_t v128)
{ UniHash unih;
unih.h128 = v128;
return unih;
}
/* === xxHash === */
UniHash XXH3_wrapper (const void* data, size_t size)
{
return uniHash64( XXH3_64bits(data, size) );
}
UniHash XXH128_wrapper (const void* data, size_t size)
{
return uniHash128( XXH3_128bits(data, size) );
}
UniHash XXH128l_wrapper (const void* data, size_t size)
{
return uniHash64( XXH3_128bits(data, size).low64 );
}
UniHash XXH128h_wrapper (const void* data, size_t size)
{
return uniHash64( XXH3_128bits(data, size).high64 );
}
UniHash XXH64_wrapper (const void* data, size_t size)
{
return uniHash64 ( XXH64(data, size, 0) );
}
UniHash XXH32_wrapper (const void* data, size_t size)
{
return uniHash32( XXH32(data, size, 0) );
}
/* === Dummy integration example === */
#include "dummy.h"
UniHash badsum32_wrapper (const void* data, size_t size)
{
return uniHash32( badsum32(data, size, 0) );
}
/* === Table === */
typedef UniHash (*hashfn) (const void* data, size_t size);
typedef struct {
const char* name;
hashfn fn;
int bits;
} hashDescription;
#define HASH_FN_TOTAL 7
hashDescription hashfnTable[HASH_FN_TOTAL] = {
{ "xxh3" , XXH3_wrapper, 64 },
{ "xxh64" , XXH64_wrapper, 64 },
{ "xxh128", XXH128_wrapper, 128 },
{ "xxh128l", XXH128l_wrapper, 64 },
{ "xxh128h", XXH128h_wrapper, 64 },
{ "xxh32" , XXH32_wrapper, 32 },
{ "badsum32",badsum32_wrapper, 32 },
};
#endif /* HASHES_H_1235465 */
/*
* Brute force collision tester for 64-bit hashes
* Part of the xxHash project
* Copyright (C) 2019-2021 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
/*
* The collision tester will generate 24 billion hashes (by default),
* and count how many collisions were produced by the 64-bit hash algorithm.
* The optimal amount of collisions for 64-bit is ~18 collisions.
* A good hash should be close to this figure.
*
* This program requires a lot of memory:
* - Either store hash values directly => 192 GB
* - Or use a filter:
* - 32 GB (by default) for the filter itself
* - + ~14 GB for the list of hashes (depending on the filter's outcome)
* Due to these memory constraints, it requires a 64-bit system.
*/
/* === Dependencies === */
#include <stdint.h> /* uint64_t */
#include <stdlib.h> /* malloc, free, qsort, exit */
#include <string.h> /* memset */
#include <stdio.h> /* printf, fflush */
#undef NDEBUG /* ensure assert is _not_ disabled */
#include <assert.h>
#include "hashes.h" /* UniHash, hashfn, hashfnTable */
#include "sort.hh" /* sort64 */
typedef enum { ht32, ht64, ht128 } Htype_e;
/* === Debug === */
#define EXIT(...) { printf(__VA_ARGS__); printf("\n"); exit(1); }
static void hexRaw(const void* buffer, size_t size)
{
const unsigned char* p = (const unsigned char*)buffer;
for (size_t i=0; i<size; i++) {
printf("%02X", p[i]);
}
}
void printHash(const void* table, size_t n, Htype_e htype)
{
if ((htype == ht64) || (htype == ht32)){
uint64_t const h64 = ((const uint64_t*)table)[n];
hexRaw(&h64, sizeof(h64));
} else {
assert(htype == ht128);
XXH128_hash_t const h128 = ((const XXH128_hash_t*)table)[n];
hexRaw(&h128, sizeof(h128));
}
}
/* === Generate Random unique Samples to hash === */
/*
* These functions will generate and update a sample to hash.
* initSample() will fill a buffer with random bytes,
* updateSample() will modify one slab in the input buffer.
* updateSample() guarantees it will produce unique samples,
* but it needs to know the total number of samples.
*/
static const uint64_t prime64_1 = 11400714785074694791ULL; /* 0b1001111000110111011110011011000110000101111010111100101010000111 */
static const uint64_t prime64_2 = 14029467366897019727ULL; /* 0b1100001010110010101011100011110100100111110101001110101101001111 */
static const uint64_t prime64_3 = 1609587929392839161ULL; /* 0b0001011001010110011001111011000110011110001101110111100111111001 */
static uint64_t avalanche64(uint64_t h64)
{
h64 ^= h64 >> 33;
h64 *= prime64_2;
h64 ^= h64 >> 29;
h64 *= prime64_3;
h64 ^= h64 >> 32;
return h64;
}
static unsigned char randomByte(uint64_t n)
{
uint64_t n64 = avalanche64(n+1);
n64 *= prime64_1;
return (unsigned char)(n64 >> 56);
}
typedef enum { sf_slab5, sf_sparse } sf_genMode;
#ifdef SLAB5
/*
* Slab5 sample generation.
* This algorithm generates unique inputs flipping on average 16 bits per candidate.
* It is generally much more friendly for most hash algorithms, especially
* weaker ones, as it shuffles more the input.
* The algorithm also avoids overfitting the per4 or per8 ingestion patterns.
*/
#define SLAB_SIZE 5
typedef struct {
void* buffer;
size_t size;
sf_genMode mode;
size_t prngSeed;
uint64_t hnb;
} sampleFactory;
static void init_sampleFactory(sampleFactory* sf, uint64_t htotal)
{
uint64_t const minNbSlabs = ((htotal-1) >> 32) + 1;
uint64_t const minSize = minNbSlabs * SLAB_SIZE;
if (sf->size < minSize)
EXIT("sample size must be >= %i bytes for this amount of hashes",
(int)minSize);
unsigned char* const p = (unsigned char*)sf->buffer;
for (size_t n=0; n < sf->size; n++)
p[n] = randomByte(n);
sf->hnb = 0;
}
static sampleFactory*
create_sampleFactory(size_t size, uint64_t htotal, uint64_t seed)
{
sampleFactory* const sf = malloc(sizeof(sampleFactory));
if (!sf) EXIT("not enough memory");
void* const buffer = malloc(size);
if (!buffer) EXIT("not enough memory");
sf->buffer = buffer;
sf->size = size;
sf->mode = sf_slab5;
sf->prngSeed = seed;
init_sampleFactory(sf, htotal);
return sf;
}
static void free_sampleFactory(sampleFactory* sf)
{
if (!sf) return;
free(sf->buffer);
free(sf);
}
static inline void update_sampleFactory(sampleFactory* sf)
{
size_t const nbSlabs = sf->size / SLAB_SIZE;
size_t const SlabNb = sf->hnb % nbSlabs;
sf->hnb++;
char* const ptr = (char*)sf->buffer;
size_t const start = (SlabNb * SLAB_SIZE) + 1;
uint32_t val32;
memcpy(&val32, ptr+start, sizeof(val32));
static const uint32_t prime32_5 = 374761393U;
val32 += prime32_5;
memcpy(ptr+start, &val32, sizeof(val32));
}
#else
/*
* Sparse sample generation.
* This is the default pattern generator.
* It only flips one bit at a time (mostly).
* Low hamming distance scenario is more difficult for weak hash algorithms.
* Note that CRC is immune to this scenario, since they are specifically
* designed to detect low hamming distances.
* Prefer the Slab5 pattern generator for collisions on CRC algorithms.
*/
#define SPARSE_LEVEL_MAX 15
/* Nb of combinations of m bits in a register of n bits */
static double Cnm(int n, int m)
{
assert(n > 0);
assert(m > 0);
assert(m <= n);
double acc = 1;
for (int i=0; i<m; i++) {
acc *= n - i;
acc /= 1 + i;
}
return acc;
}
static int enoughCombos(size_t size, uint64_t htotal)
{
if (size < 2) return 0; /* ensure no multiplication by negative */
uint64_t acc = 0;
uint64_t const srcBits = size * 8; assert(srcBits < INT_MAX);
int nbBitsSet = 0;
while (acc < htotal) {
nbBitsSet++;
if (nbBitsSet >= SPARSE_LEVEL_MAX) return 0;
acc += (uint64_t)Cnm((int)srcBits, nbBitsSet);
}
return 1;
}
typedef struct {
void* buffer;
size_t size;
sf_genMode mode;
/* sparse */
size_t bitIdx[SPARSE_LEVEL_MAX];
int level;
size_t maxBitIdx;
/* slab5 */
size_t nbSlabs;
size_t current;
uint64_t prngSeed;
} sampleFactory;
static void init_sampleFactory(sampleFactory* sf, uint64_t htotal)
{
if (!enoughCombos(sf->size, htotal)) {
EXIT("sample size must be larger for this amount of hashes");
}
memset(sf->bitIdx, 0, sizeof(sf->bitIdx));
sf->level = 0;
unsigned char* const p = (unsigned char*)sf->buffer;
for (size_t n=0; n<sf->size; n++)
p[n] = randomByte(sf->prngSeed + n);
}
static sampleFactory*
create_sampleFactory(size_t size, uint64_t htotal, uint64_t seed)
{
sampleFactory* const sf = malloc(sizeof(sampleFactory));
if (!sf) EXIT("not enough memory");
void* const buffer = malloc(size);
if (!buffer) EXIT("not enough memory");
sf->buffer = buffer;
sf->size = size;
sf->mode = sf_sparse;
sf->maxBitIdx = size * 8;
sf->prngSeed = seed;
init_sampleFactory(sf, htotal);
return sf;
}
static void free_sampleFactory(sampleFactory* sf)
{
if (!sf) return;
free(sf->buffer);
free(sf);
}
static void flipbit(void* buffer, uint64_t bitID)
{
size_t const pos = (size_t)(bitID >> 3);
unsigned char const mask = (unsigned char)(1 << (bitID & 7));
unsigned char* const p = (unsigned char*)buffer;
p[pos] ^= mask;
}
static int updateBit(void* buffer, size_t* bitIdx, int level, size_t max)
{
if (level==0) return 0; /* can't progress further */
flipbit(buffer, bitIdx[level]); /* erase previous bits */
if (bitIdx[level] < max-1) { /* simple case: go to next bit */
bitIdx[level]++;
flipbit(buffer, bitIdx[level]); /* set new bit */
return 1;
}
/* reached last bit: need to update a bit from lower level */
if (!updateBit(buffer, bitIdx, level-1, max-1)) return 0;
bitIdx[level] = bitIdx[level-1] + 1;
flipbit(buffer, bitIdx[level]); /* set new bit */
return 1;
}
static inline void update_sampleFactory(sampleFactory* sf)
{
if (!updateBit(sf->buffer, sf->bitIdx, sf->level, sf->maxBitIdx)) {
/* no more room => move to next level */
sf->level++;
assert(sf->level < SPARSE_LEVEL_MAX);
/* set new bits */
for (int i=1; i <= sf->level; i++) {
sf->bitIdx[i] = (size_t)(i-1);
flipbit(sf->buffer, sf->bitIdx[i]);
}
}
}
#endif /* pattern generator selection */
/* === Candidate Filter === */
typedef unsigned char Filter;
Filter* create_Filter(int bflog)
{
assert(bflog < 64 && bflog > 1);
size_t bfsize = (size_t)1 << bflog;
Filter* bf = malloc(bfsize);
assert(((void)"Filter creation failed", bf));
memset(bf, 0, bfsize);
return bf;
}
void free_Filter(Filter* bf)
{
free(bf);
}
#ifdef FILTER_1_PROBE
/*
* Attach hash to a slot
* return: Nb of potential collision candidates detected
* 0: position not yet occupied
* 2: position previously occupied by a single candidate
* 1: position already occupied by multiple candidates
*/
inline int Filter_insert(Filter* bf, int bflog, uint64_t hash)
{
int const slotNb = hash & 3;
int const shift = slotNb * 2 ;
size_t const bfmask = ((size_t)1 << bflog) - 1;
size_t const pos = (hash >> 2) & bfmask;
int const existingCandidates = ((((unsigned char*)bf)[pos]) >> shift) & 3;
static const int addCandidates[4] = { 0, 2, 1, 1 };
static const int nextValue[4] = { 1, 2, 3, 3 };
((unsigned char*)bf)[pos] |= (unsigned char)(nextValue[existingCandidates] << shift);
return addCandidates[existingCandidates];
}
/*
* Check if provided 64-bit hash is a collision candidate
* Requires the slot to be occupied by at least 2 candidates.
* return >0 if hash is a collision candidate
* 0 otherwise (slot unoccupied, or only one candidate)
* note: unoccupied slots should not happen in this algorithm,
* since all hashes are supposed to have been inserted at least once.
*/
inline int Filter_check(const Filter* bf, int bflog, uint64_t hash)
{
int const slotNb = hash & 3;
int const shift = slotNb * 2;
size_t const bfmask = ((size_t)1 << bflog) - 1;
size_t const pos = (hash >> 2) & bfmask;
return (((const unsigned char*)bf)[pos]) >> (shift+1) & 1;
}
#else
/*
* 2-probes strategy,
* more efficient at filtering candidates,
* requires filter size to be > nb of hashes
*/
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#define MAX(a,b) ((a) > (b) ? (a) : (b))
/*
* Attach hash to 2 slots
* return: Nb of potential candidates detected
* 0: position not yet occupied
* 2: position previously occupied by a single candidate (at most)
* 1: position already occupied by multiple candidates
*/
static inline int Filter_insert(Filter* bf, int bflog, uint64_t hash)
{
hash = avalanche64(hash);
unsigned const slot1 = hash & 255;
hash >>= 8;
unsigned const slot2 = hash & 255;
hash >>= 8;
size_t const fclmask = ((size_t)1 << (bflog-6)) - 1;
size_t const cacheLineNb = (size_t)hash & fclmask;
size_t const pos1 = (cacheLineNb << 6) + (slot1 >> 2);
unsigned const shift1 = (slot1 & 3) * 2;
unsigned const ex1 = (bf[pos1] >> shift1) & 3;
size_t const pos2 = (cacheLineNb << 6) + (slot2 >> 2);
unsigned const shift2 = (slot2 & 3) * 2;
unsigned const ex2 = (bf[pos2] >> shift2) & 3;
unsigned const existing = MIN(ex1, ex2);
static const int addCandidates[4] = { 0, 2, 1, 1 };
static const unsigned nextValue[4] = { 1, 2, 3, 3 };
bf[pos1] &= (Filter)(~(3 << shift1)); /* erase previous value */
unsigned const max1 = MAX(ex1, nextValue[existing]);
bf[pos1] |= (Filter)(max1 << shift1);
unsigned const max2 = MAX(ex2, nextValue[existing]);
bf[pos2] |= (Filter)(max2 << shift2);
return addCandidates[existing];
}
/*
* Check if provided 64-bit hash is a collision candidate
* Requires the slot to be occupied by at least 2 candidates.
* return >0 if hash is a collision candidate
* 0 otherwise (slot unoccupied, or only one candidate)
* note: unoccupied slots should not happen in this algorithm,
* since all hashes are supposed to have been inserted at least once.
*/
static inline int Filter_check(const Filter* bf, int bflog, uint64_t hash)
{
hash = avalanche64(hash);
unsigned const slot1 = hash & 255;
hash >>= 8;
unsigned const slot2 = hash & 255;
hash >>= 8;
size_t const fclmask = ((size_t)1 << (bflog-6)) - 1;
size_t const cacheLineNb = (size_t)hash & fclmask;
size_t const pos1 = (cacheLineNb << 6) + (slot1 >> 2);
unsigned const shift1 = (slot1 & 3) * 2;
unsigned const ex1 = (bf[pos1] >> shift1) & 3;
size_t const pos2 = (cacheLineNb << 6) + (slot2 >> 2);
unsigned const shift2 = (slot2 & 3) * 2;
unsigned const ex2 = (bf[pos2] >> shift2) & 3;
return (ex1 >= 2) && (ex2 >= 2);
}
#endif // FILTER_1_PROBE
/* === Display === */
#include <time.h> /* clock_t, clock, time_t, time, difftime */
void update_indicator(uint64_t v, uint64_t total)
{
static clock_t start = 0;
if (start==0) start = clock();
clock_t const updateRate = CLOCKS_PER_SEC / 2;
clock_t const clockSpan = (clock_t)(clock() - start);
if (clockSpan > updateRate) {
start = clock();
assert(v <= total);
assert(total > 0);
double share = ((double)v / (double)total) * 100;
printf("%6.2f%% (%llu) \r", share, (unsigned long long)v);
fflush(NULL);
}
}
/* note: not thread safe */
const char* displayDelay(double delay_s)
{
static char delayString[50];
memset(delayString, 0, sizeof(delayString));
int const mn = ((int)delay_s / 60) % 60;
int const h = (int)delay_s / 3600;
int const sec = (int)delay_s % 60;
char* p = delayString;
if (h) sprintf(p, "%i h ", h);
if (mn || h) {
p = delayString + strlen(delayString);
sprintf(p, "%i mn ", mn);
}
p = delayString + strlen(delayString);
sprintf(p, "%is ", sec);
return delayString;
}
/* === Math === */
static double power(uint64_t base, int p)
{
double value = 1;
assert(p>=0);
for (int i=0; i<p; i++) {
value *= (double)base;
}
return value;
}
static double estimateNbCollisions(uint64_t nbH, int nbBits)
{
return ((double)nbH * (double)(nbH-1)) / power(2, nbBits+1);
}
static int highestBitSet(uint64_t v)
{
assert(v!=0);
int bitId = 0;
while (v >>= 1) bitId++;
return bitId;
}
/* === Filter and search collisions === */
#undef NDEBUG /* ensure assert is not disabled */
#include <assert.h>
/* will recommend 24 billion samples for 64-bit hashes,
* expecting 18 collisions for a good 64-bit hash */
#define NB_BITS_MAX 64 /* can't store nor analyze hash wider than 64-bits for the time being */
uint64_t select_nbh(int nbBits)
{
assert(nbBits > 0);
if (nbBits > NB_BITS_MAX) nbBits = NB_BITS_MAX;
double targetColls = (double)((128 + 17) - (nbBits * 2));
uint64_t nbH = 24;
while (estimateNbCollisions(nbH, nbBits) < targetColls) nbH *= 2;
return nbH;
}
typedef struct {
uint64_t nbCollisions;
} searchCollisions_results;
typedef struct {
uint64_t nbH;
uint64_t mask;
uint64_t maskSelector;
size_t sampleSize;
uint64_t prngSeed;
int filterLog; /* <0 = disable filter; 0 = auto-size; */
int hashID;
int display;
int nbThreads;
searchCollisions_results* resultPtr;
} searchCollisions_parameters;
#define DISPLAY(...) { if (display) printf(__VA_ARGS__); }
static int isEqual(void* hTablePtr, size_t index1, size_t index2, Htype_e htype)
{
if ((htype == ht64) || (htype == ht32)) {
uint64_t const h1 = ((const uint64_t*)hTablePtr)[index1];
uint64_t const h2 = ((const uint64_t*)hTablePtr)[index2];
return (h1 == h2);
} else {
assert(htype == ht128);
XXH128_hash_t const h1 = ((const XXH128_hash_t*)hTablePtr)[index1];
XXH128_hash_t const h2 = ((const XXH128_hash_t*)hTablePtr)[index2];
return XXH128_isEqual(h1, h2);
}
}
static int isHighEqual(void* hTablePtr, size_t index1, size_t index2, Htype_e htype, int rShift)
{
uint64_t h1, h2;
if ((htype == ht64) || (htype == ht32)) {
h1 = ((const uint64_t*)hTablePtr)[index1];
h2 = ((const uint64_t*)hTablePtr)[index2];
} else {
assert(htype == ht128);
h1 = ((const XXH128_hash_t*)hTablePtr)[index1].high64;
h2 = ((const XXH128_hash_t*)hTablePtr)[index2].high64;
assert(rShift >= 64);
rShift -= 64;
}
assert(0 <= rShift && rShift < 64);
return (h1 >> rShift) == (h2 >> rShift);
}
/* assumption: (htype*)hTablePtr[index] is valid */
static void addHashCandidate(void* hTablePtr, UniHash h, Htype_e htype, size_t index)
{
if ((htype == ht64) || (htype == ht32)) {
((uint64_t*)hTablePtr)[index] = h.h64;
} else {
assert(htype == ht128);
((XXH128_hash_t*)hTablePtr)[index] = h.h128;
}
}
static int getNbBits_fromHtype(Htype_e htype) {
switch(htype) {
case ht32: return 32;
case ht64: return 64;
case ht128:return 128;
default: EXIT("hash size not supported");
}
}
static Htype_e getHtype_fromHbits(int nbBits) {
switch(nbBits) {
case 32 : return ht32;
case 64 : return ht64;
case 128: return ht128;
default: EXIT("hash size not supported");
}
}
static size_t search_collisions(
searchCollisions_parameters param)
{
uint64_t totalH = param.nbH;
const uint64_t hMask = param.mask;
const uint64_t hSelector = param.maskSelector;
int bflog = param.filterLog;
const int filter = (param.filterLog >= 0);
const size_t sampleSize = param.sampleSize;
const int hashID = param.hashID;
const Htype_e htype = getHtype_fromHbits(hashfnTable[hashID].bits);
const int display = param.display;
/* init */
sampleFactory* const sf = create_sampleFactory(sampleSize, totalH, param.prngSeed);
if (!sf) EXIT("not enough memory");
//const char* const hname = hashfnTable[hashID].name;
hashfn const hfunction = hashfnTable[hashID].fn;
int const hwidth = hashfnTable[hashID].bits;
if (totalH == 0) totalH = select_nbh(hwidth);
if (bflog == 0) bflog = highestBitSet(totalH) + 1; /* auto-size filter */
uint64_t const bfsize = (1ULL << bflog);
/* === filter hashes (optional) === */
Filter* bf = NULL;
uint64_t nbPresents = totalH;
if (filter) {
time_t const filterTBegin = time(NULL);
DISPLAY(" Creating filter (%i GB) \n", (int)(bfsize >> 30));
bf = create_Filter(bflog);
if (!bf) EXIT("not enough memory for filter");
DISPLAY(" Generate %llu hashes from samples of %u bytes \n",
(unsigned long long)totalH, (unsigned)sampleSize);
nbPresents = 0;
for (uint64_t n=0; n < totalH; n++) {
if (display && ((n&0xFFFFF) == 1) )
update_indicator(n, totalH);
update_sampleFactory(sf);
UniHash const h = hfunction(sf->buffer, sampleSize);
if ((h.h64 & hMask) != hSelector) continue;
nbPresents += (uint64_t)Filter_insert(bf, bflog, h.h64);
}
if (nbPresents==0) {
DISPLAY(" Analysis completed: No collision detected \n");
if (param.resultPtr) param.resultPtr->nbCollisions = 0;
free_Filter(bf);
free_sampleFactory(sf);
return 0;
}
{ double const filterDelay = difftime(time(NULL), filterTBegin);
DISPLAY(" Generation and filter completed in %s, detected up to %llu candidates \n",
displayDelay(filterDelay), (unsigned long long) nbPresents);
} }
/* === store hash candidates: duplicates will be present here === */
time_t const storeTBegin = time(NULL);
size_t const hashByteSize = (htype == ht128) ? 16 : 8;
size_t const tableSize = (size_t)((nbPresents+1) * hashByteSize);
assert(tableSize > nbPresents); /* check tableSize calculation overflow */
DISPLAY(" Storing hash candidates (%i MB) \n", (int)(tableSize >> 20));
/* Generate and store hashes */
void* const hashCandidates = malloc(tableSize);
if (!hashCandidates) EXIT("not enough memory to store candidates");
init_sampleFactory(sf, totalH);
size_t nbCandidates = 0;
for (uint64_t n=0; n < totalH; n++) {
if (display && ((n&0xFFFFF) == 1) ) update_indicator(n, totalH);
update_sampleFactory(sf);
UniHash const h = hfunction(sf->buffer, sampleSize);
if ((h.h64 & hMask) != hSelector) continue;
if (filter) {
if (Filter_check(bf, bflog, h.h64)) {
assert(nbCandidates < nbPresents);
addHashCandidate(hashCandidates, h, htype, nbCandidates++);
}
} else {
assert(nbCandidates < nbPresents);
addHashCandidate(hashCandidates, h, htype, nbCandidates++);
}
}
if (nbCandidates < nbPresents) {
/* Try to mitigate gnuc_quicksort behavior, by reducing allocated memory,
* since gnuc_quicksort uses a lot of additional memory for mergesort */
void* const checkPtr = realloc(hashCandidates, nbCandidates * hashByteSize);
assert(checkPtr != NULL);
assert(checkPtr == hashCandidates); /* simplification: since we are reducing the size,
* we hope to keep the same ptr position.
* Otherwise, hashCandidates must be mutable. */
DISPLAY(" List of hashes reduced to %u MB from %u MB (saved %u MB) \n",
(unsigned)((nbCandidates * hashByteSize) >> 20),
(unsigned)(tableSize >> 20),
(unsigned)((tableSize - (nbCandidates * hashByteSize)) >> 20) );
}
double const storeTDelay = difftime(time(NULL), storeTBegin);
DISPLAY(" Stored %llu hash candidates in %s \n",
(unsigned long long) nbCandidates, displayDelay(storeTDelay));
free_Filter(bf);
free_sampleFactory(sf);
/* === step 3: look for duplicates === */
time_t const sortTBegin = time(NULL);
DISPLAY(" Sorting candidates... ");
fflush(NULL);
if ((htype == ht64) || (htype == ht32)) {
/*
* Use C++'s std::sort, as it's faster than C stdlib's qsort, and
* doesn't suffer from gnuc_libsort's memory expansion
*/
sort64(hashCandidates, nbCandidates);
} else {
assert(htype == ht128);
sort128(hashCandidates, nbCandidates); /* sort with custom comparator */
}
double const sortTDelay = difftime(time(NULL), sortTBegin);
DISPLAY(" Completed in %s \n", displayDelay(sortTDelay));
/* scan and count duplicates */
time_t const countBegin = time(NULL);
DISPLAY(" Looking for duplicates: ");
fflush(NULL);
size_t collisions = 0;
for (size_t n=1; n<nbCandidates; n++) {
if (isEqual(hashCandidates, n, n-1, htype)) {
#if defined(COL_DISPLAY_DUPLICATES)
printf("collision: ");
printHash(hashCandidates, n, htype);
printf(" / ");
printHash(hashCandidates, n-1, htype);
printf(" \n");
#endif
collisions++;
} }
if (!filter /* all candidates */ && display /*single thead*/ ) {
/* check partial bitfields (high bits) */
DISPLAY(" \n");
int const hashBits = getNbBits_fromHtype(htype);
double worstRatio = 0.;
int worstNbHBits = 0;
for (int nbHBits = 1; nbHBits < hashBits; nbHBits++) {
uint64_t const nbSlots = (uint64_t)1 << nbHBits;
double const expectedCollisions = estimateNbCollisions(nbCandidates, nbHBits);
if ( (nbSlots > nbCandidates * 100) /* within range for meaningful collision analysis results */
&& (expectedCollisions > 18.0) ) {
int const rShift = hashBits - nbHBits;
size_t HBits_collisions = 0;
for (size_t n=1; n<nbCandidates; n++) {
if (isHighEqual(hashCandidates, n, n-1, htype, rShift)) {
HBits_collisions++;
} }
double const collisionRatio = (double)HBits_collisions / expectedCollisions;
if (collisionRatio > 2.0) DISPLAY("WARNING !!! ===> ");
DISPLAY(" high %i bits: %zu collision (%.1f expected): x%.2f \n",
nbHBits, HBits_collisions, expectedCollisions, collisionRatio);
if (collisionRatio > worstRatio) {
worstNbHBits = nbHBits;
worstRatio = collisionRatio;
} } }
DISPLAY("Worst collision ratio at %i high bits: x%.2f \n",
worstNbHBits, worstRatio);
}
double const countDelay = difftime(time(NULL), countBegin);
DISPLAY(" Completed in %s \n", displayDelay(countDelay));
/* clean and exit */
free (hashCandidates);
#if 0 /* debug */
for (size_t n=0; n<nbCandidates; n++)
printf("0x%016llx \n", (unsigned long long)hashCandidates[n]);
#endif
if (param.resultPtr) param.resultPtr->nbCollisions = collisions;
return collisions;
}
#if defined(__MACH__) || defined(__linux__)
#include <sys/resource.h>
static size_t getProcessMemUsage(int children)
{
struct rusage stats;
if (getrusage(children ? RUSAGE_CHILDREN : RUSAGE_SELF, &stats) == 0)
return (size_t)stats.ru_maxrss;
return 0;
}
#else
static size_t getProcessMemUsage(int ignore) { (void)ignore; return 0; }
#endif
void time_collisions(searchCollisions_parameters param)
{
uint64_t totalH = param.nbH;
int hashID = param.hashID;
int display = param.display;
/* init */
assert(0 <= hashID && hashID < HASH_FN_TOTAL);
//const char* const hname = hashfnTable[hashID].name;
int const hwidth = hashfnTable[hashID].bits;
if (totalH == 0) totalH = select_nbh(hwidth);
double const targetColls = estimateNbCollisions(totalH, hwidth);
/* Start the timer to measure start/end of hashing + collision detection. */
time_t const programTBegin = time(NULL);
/* Generate hashes, and count collisions */
size_t const collisions = search_collisions(param);
/* display results */
double const programTDelay = difftime(time(NULL), programTBegin);
size_t const programBytesSelf = getProcessMemUsage(0);
size_t const programBytesChildren = getProcessMemUsage(1);
DISPLAY("\n\n");
DISPLAY("===> Found %llu collisions (x%.2f, %.1f expected) in %s\n",
(unsigned long long)collisions,
(double)collisions / targetColls,
targetColls,
displayDelay(programTDelay));
if (programBytesSelf)
DISPLAY("===> MaxRSS(self) %zuMB, MaxRSS(children) %zuMB\n",
programBytesSelf>>20,
programBytesChildren>>20);
DISPLAY("------------------------------------------ \n");
}
// wrapper for pthread interface
void MT_searchCollisions(void* payload)
{
search_collisions(*(searchCollisions_parameters*)payload);
}
/* === Command Line === */
/*!
* readU64FromChar():
* Allows and interprets K, KB, KiB, M, MB and MiB suffix.
* Will also modify `*stringPtr`, advancing it to the position where it stopped reading.
*/
static uint64_t readU64FromChar(const char** stringPtr)
{
static uint64_t const max = (((uint64_t)(-1)) / 10) - 1;
uint64_t result = 0;
while ((**stringPtr >='0') && (**stringPtr <='9')) {
assert(result < max);
result *= 10;
result += (unsigned)(**stringPtr - '0');
(*stringPtr)++ ;
}
if ((**stringPtr=='K') || (**stringPtr=='M') || (**stringPtr=='G')) {
uint64_t const maxK = ((uint64_t)(-1)) >> 10;
assert(result < maxK);
result <<= 10;
if ((**stringPtr=='M') || (**stringPtr=='G')) {
assert(result < maxK);
result <<= 10;
if (**stringPtr=='G') {
assert(result < maxK);
result <<= 10;
}
}
(*stringPtr)++; /* skip `K` or `M` */
if (**stringPtr=='i') (*stringPtr)++;
if (**stringPtr=='B') (*stringPtr)++;
}
return result;
}
/**
* longCommandWArg():
* Checks if *stringPtr is the same as longCommand.
* If yes, @return 1 and advances *stringPtr to the position which immediately follows longCommand.
* @return 0 and doesn't modify *stringPtr otherwise.
*/
static int longCommandWArg(const char** stringPtr, const char* longCommand)
{
assert(longCommand); assert(stringPtr); assert(*stringPtr);
size_t const comSize = strlen(longCommand);
int const result = !strncmp(*stringPtr, longCommand, comSize);
if (result) *stringPtr += comSize;
return result;
}
#include "pool.h"
/*
* As some hashes use different algorithms depending on input size,
* it can be necessary to test multiple input sizes
* to paint an accurate picture of collision performance
*/
#define SAMPLE_SIZE_DEFAULT 256
#define HASHFN_ID_DEFAULT 0
void help(const char* exeName)
{
printf("usage: %s [hashName] [opt] \n\n", exeName);
printf("list of hashNames:");
printf("%s ", hashfnTable[0].name);
for (int i=1; i < HASH_FN_TOTAL; i++) {
printf(", %s ", hashfnTable[i].name);
}
printf(" \n");
printf("Default hashName is %s\n", hashfnTable[HASHFN_ID_DEFAULT].name);
printf(" \n");
printf("Optional parameters: \n");
printf(" --nbh=NB Select nb of hashes to generate (%llu by default) \n", (unsigned long long)select_nbh(64));
printf(" --filter Activates the filter. Slower, but reduces memory usage for the same nb of hashes.\n");
printf(" --threadlog=NB Use 2^NB threads.\n");
printf(" --len=MB Set length of the input (%i bytes by default) \n", SAMPLE_SIZE_DEFAULT);
}
int bad_argument(const char* exeName)
{
printf("incorrect command: \n");
help(exeName);
return 1;
}
int main(int argc, const char** argv)
{
if (sizeof(size_t) < 8) return 1; // cannot work on systems without ability to allocate objects >= 4 GB
assert(argc > 0);
const char* const exeName = argv[0];
uint64_t totalH = 0; /* auto, based on nbBits */
int bflog = 0; /* auto */
int filter = 0; /* disabled */
size_t sampleSize = SAMPLE_SIZE_DEFAULT;
int hashID = HASHFN_ID_DEFAULT;
int threadlog = 0;
uint64_t prngSeed = 0;
int arg_nb;
for (arg_nb = 1; arg_nb < argc; arg_nb++) {
const char** arg = argv + arg_nb;
if (!strcmp(*arg, "-h")) { help(exeName); return 0; }
if (longCommandWArg(arg, "-T")) { threadlog = (int)readU64FromChar(arg); continue; }
if (!strcmp(*arg, "--filter")) { filter=1; continue; }
if (!strcmp(*arg, "--no-filter")) { filter=0; continue; }
if (longCommandWArg(arg, "--seed")) { prngSeed = readU64FromChar(arg); continue; }
if (longCommandWArg(arg, "--nbh=")) { totalH = readU64FromChar(arg); continue; }
if (longCommandWArg(arg, "--filter=")) { filter=1; bflog = (int)readU64FromChar(arg); assert(bflog < 64); continue; }
if (longCommandWArg(arg, "--filterlog=")) { filter=1; bflog = (int)readU64FromChar(arg); assert(bflog < 64); continue; }
if (longCommandWArg(arg, "--size=")) { sampleSize = (size_t)readU64FromChar(arg); continue; }
if (longCommandWArg(arg, "--len=")) { sampleSize = (size_t)readU64FromChar(arg); continue; }
if (longCommandWArg(arg, "--threadlog=")) { threadlog = (int)readU64FromChar(arg); continue; }
/* argument understood as hash name (must be correct) */
int hnb;
for (hnb=0; hnb < HASH_FN_TOTAL; hnb++) {
if (!strcmp(*arg, hashfnTable[hnb].name)) { hashID = hnb; break; }
}
if (hnb == HASH_FN_TOTAL) return bad_argument(exeName);
}
/* init */
const char* const hname = hashfnTable[hashID].name;
int const hwidth = hashfnTable[hashID].bits;
if (totalH == 0) totalH = select_nbh(hwidth);
double const targetColls = estimateNbCollisions(totalH, hwidth);
if (bflog == 0) bflog = highestBitSet(totalH) + 1; /* auto-size filter */
if (!filter) bflog = -1; // disable filter
if (sizeof(size_t) < 8)
EXIT("This program has not been validated on architectures other than "
"64bit \n");
printf(" *** Collision tester for 64+ bit hashes *** \n\n");
printf("Testing %s algorithm (%i-bit) \n", hname, hwidth);
printf("This program will allocate a lot of memory,\n");
printf("generate %llu %i-bit hashes from samples of %u bytes, \n",
(unsigned long long)totalH, hwidth, (unsigned)sampleSize);
printf("and attempt to produce %.0f collisions. \n\n", targetColls);
int const nbThreads = 1 << threadlog;
if (nbThreads <= 0) EXIT("Invalid --threadlog value.");
if (nbThreads == 1) {
searchCollisions_parameters params;
params.nbH = totalH;
params.mask = 0;
params.maskSelector = 0;
params.sampleSize = sampleSize;
params.filterLog = bflog;
params.hashID = hashID;
params.display = 1;
params.resultPtr = NULL;
params.prngSeed = prngSeed;
params.nbThreads = 1;
time_collisions(params);
} else { /* nbThreads > 1 */
/* use multithreading */
if (threadlog >= 30) EXIT("too many threads requested");
if ((uint64_t)nbThreads > (totalH >> 16))
EXIT("too many threads requested");
if (bflog > 0 && threadlog > (bflog-10))
EXIT("too many threads requested");
printf("using %i threads ... \n", nbThreads);
/* allocation */
time_t const programTBegin = time(NULL);
POOL_ctx* const pt = POOL_create((size_t)nbThreads, 1);
if (!pt) EXIT("not enough memory for threads");
searchCollisions_results* const MTresults = calloc (sizeof(searchCollisions_results), (size_t)nbThreads);
if (!MTresults) EXIT("not enough memory");
searchCollisions_parameters* const MTparams = calloc (sizeof(searchCollisions_parameters), (size_t)nbThreads);
if (!MTparams) EXIT("not enough memory");
/* distribute jobs */
for (int tnb=0; tnb<nbThreads; tnb++) {
MTparams[tnb].nbH = totalH;
MTparams[tnb].mask = (uint64_t)nbThreads - 1;
MTparams[tnb].sampleSize = sampleSize;
MTparams[tnb].filterLog = bflog ? bflog - threadlog : 0;
MTparams[tnb].hashID = hashID;
MTparams[tnb].display = 0;
MTparams[tnb].resultPtr = MTresults+tnb;
MTparams[tnb].prngSeed = prngSeed;
MTparams[tnb].maskSelector = (uint64_t)tnb;
POOL_add(pt, MT_searchCollisions, MTparams + tnb);
}
POOL_free(pt); /* actually joins and free */
/* Gather results */
uint64_t nbCollisions=0;
for (int tnb=0; tnb<nbThreads; tnb++) {
nbCollisions += MTresults[tnb].nbCollisions;
}
double const programTDelay = difftime(time(NULL), programTBegin);
size_t const programBytesSelf = getProcessMemUsage(0);
size_t const programBytesChildren = getProcessMemUsage(1);
printf("\n\n");
printf("===> Found %llu collisions (x%.2f, %.1f expected) in %s\n",
(unsigned long long)nbCollisions,
(double)nbCollisions / targetColls,
targetColls,
displayDelay(programTDelay));
if (programBytesSelf)
printf("===> MaxRSS(self) %zuMB, MaxRSS(children) %zuMB\n",
programBytesSelf>>20,
programBytesChildren>>20);
printf("------------------------------------------ \n");
/* Clean up */
free(MTparams);
free(MTresults);
}
return 0;
}
/*
* Copyright (C) 2016-2021 Yann Collet, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under both the BSD-style license (found in the
* LICENSE file in the root directory of this source tree) and the GPLv2 (found
* in the COPYING file in the root directory of this source tree).
* You may select, at your option, one of the above-listed licenses.
*/
/* ====== Dependencies ======= */
#include <stddef.h> /* size_t */
#include <stdlib.h> /* malloc, calloc, free */
#include <string.h> /* memcpy */
#include <assert.h>
#include "pool.h"
/* ====== Compiler specifics ====== */
#if defined(_MSC_VER)
# pragma warning(disable : 4204) /* disable: C4204: non-constant aggregate initializer */
#endif
/* === Build Macro === */
#ifndef POOL_MT // can be defined on command line
# define POOL_MT 1
#endif
/* === Implementation === */
#if POOL_MT
#include "threading.h" /* pthread adaptation */
/* A job is a function and an opaque argument */
typedef struct POOL_job_s {
POOL_function function;
void *opaque;
} POOL_job;
struct POOL_ctx_s {
/* Keep track of the threads */
ZSTD_pthread_t* threads;
size_t threadCapacity;
size_t threadLimit;
/* The queue is a circular buffer */
POOL_job *queue;
size_t queueHead;
size_t queueTail;
size_t queueSize;
/* The number of threads working on jobs */
size_t numThreadsBusy;
/* Indicates if the queue is empty */
int queueEmpty;
/* The mutex protects the queue */
ZSTD_pthread_mutex_t queueMutex;
/* Condition variable for pushers to wait on when the queue is full */
ZSTD_pthread_cond_t queuePushCond;
/* Condition variables for poppers to wait on when the queue is empty */
ZSTD_pthread_cond_t queuePopCond;
/* Indicates if the queue is shutting down */
int shutdown;
};
/* POOL_thread() :
* Work thread for the thread pool.
* Waits for jobs and executes them.
* @returns : NULL on failure else non-null.
*/
static void* POOL_thread(void* opaque)
{
POOL_ctx* const ctx = (POOL_ctx*)opaque;
if (!ctx) { return NULL; }
for (;;) {
/* Lock the mutex and wait for a non-empty queue or until shutdown */
ZSTD_pthread_mutex_lock(&ctx->queueMutex);
while ( ctx->queueEmpty
|| (ctx->numThreadsBusy >= ctx->threadLimit) ) {
if (ctx->shutdown) {
/* even if !queueEmpty, (possible if numThreadsBusy >= threadLimit),
* a few threads will be shutdown while !queueEmpty,
* but enough threads will remain active to finish the queue */
ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
return opaque;
}
ZSTD_pthread_cond_wait(&ctx->queuePopCond, &ctx->queueMutex);
}
/* Pop a job off the queue */
{ POOL_job const job = ctx->queue[ctx->queueHead];
ctx->queueHead = (ctx->queueHead + 1) % ctx->queueSize;
ctx->numThreadsBusy++;
ctx->queueEmpty = ctx->queueHead == ctx->queueTail;
/* Unlock the mutex, signal a pusher, and run the job */
ZSTD_pthread_cond_signal(&ctx->queuePushCond);
ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
job.function(job.opaque);
/* If the intended queue size was 0, signal after finishing job */
ZSTD_pthread_mutex_lock(&ctx->queueMutex);
ctx->numThreadsBusy--;
if (ctx->queueSize == 1) {
ZSTD_pthread_cond_signal(&ctx->queuePushCond);
}
ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
}
} /* for (;;) */
assert(0); /* Unreachable */
}
POOL_ctx* POOL_create(size_t numThreads, size_t queueSize)
{
POOL_ctx* ctx;
/* Check parameters */
if (!numThreads) { return NULL; }
/* Allocate the context and zero initialize */
ctx = (POOL_ctx*)calloc(1, sizeof(POOL_ctx));
if (!ctx) { return NULL; }
/* Initialize the job queue.
* It needs one extra space since one space is wasted to differentiate
* empty and full queues.
*/
ctx->queueSize = queueSize + 1;
ctx->queue = (POOL_job*)malloc(ctx->queueSize * sizeof(POOL_job));
ctx->queueHead = 0;
ctx->queueTail = 0;
ctx->numThreadsBusy = 0;
ctx->queueEmpty = 1;
(void)ZSTD_pthread_mutex_init(&ctx->queueMutex, NULL);
(void)ZSTD_pthread_cond_init(&ctx->queuePushCond, NULL);
(void)ZSTD_pthread_cond_init(&ctx->queuePopCond, NULL);
ctx->shutdown = 0;
/* Allocate space for the thread handles */
ctx->threads = (ZSTD_pthread_t*)malloc(numThreads * sizeof(ZSTD_pthread_t));
ctx->threadCapacity = 0;
/* Check for errors */
if (!ctx->threads || !ctx->queue) { POOL_free(ctx); return NULL; }
/* Initialize the threads */
{ size_t i;
for (i = 0; i < numThreads; ++i) {
if (ZSTD_pthread_create(&ctx->threads[i], NULL, &POOL_thread, ctx)) {
ctx->threadCapacity = i;
POOL_free(ctx);
return NULL;
} }
ctx->threadCapacity = numThreads;
ctx->threadLimit = numThreads;
}
return ctx;
}
/*! POOL_join() :
Shutdown the queue, wake any sleeping threads, and join all of the threads.
*/
static void POOL_join(POOL_ctx* ctx) {
/* Shut down the queue */
ZSTD_pthread_mutex_lock(&ctx->queueMutex);
ctx->shutdown = 1;
ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
/* Wake up sleeping threads */
ZSTD_pthread_cond_broadcast(&ctx->queuePushCond);
ZSTD_pthread_cond_broadcast(&ctx->queuePopCond);
/* Join all of the threads */
{ size_t i;
for (i = 0; i < ctx->threadCapacity; ++i) {
ZSTD_pthread_join(ctx->threads[i], NULL); /* note : could fail */
} }
}
void POOL_free(POOL_ctx *ctx) {
if (!ctx) { return; }
POOL_join(ctx);
ZSTD_pthread_mutex_destroy(&ctx->queueMutex);
ZSTD_pthread_cond_destroy(&ctx->queuePushCond);
ZSTD_pthread_cond_destroy(&ctx->queuePopCond);
free(ctx->queue);
free(ctx->threads);
free(ctx);
}
size_t POOL_sizeof(POOL_ctx *ctx) {
if (ctx==NULL) return 0; /* supports sizeof NULL */
return sizeof(*ctx)
+ ctx->queueSize * sizeof(POOL_job)
+ ctx->threadCapacity * sizeof(ZSTD_pthread_t);
}
/* @return : 0 on success, 1 on error */
static int POOL_resize_internal(POOL_ctx* ctx, size_t numThreads)
{
if (numThreads <= ctx->threadCapacity) {
if (!numThreads) return 1;
ctx->threadLimit = numThreads;
return 0;
}
/* numThreads > threadCapacity */
{ ZSTD_pthread_t* const threadPool = (ZSTD_pthread_t*)malloc(numThreads * sizeof(ZSTD_pthread_t));
if (!threadPool) return 1;
/* replace existing thread pool */
memcpy(threadPool, ctx->threads, ctx->threadCapacity * sizeof(*threadPool));
free(ctx->threads);
ctx->threads = threadPool;
/* Initialize additional threads */
{ size_t threadId;
for (threadId = ctx->threadCapacity; threadId < numThreads; ++threadId) {
if (ZSTD_pthread_create(&threadPool[threadId], NULL, &POOL_thread, ctx)) {
ctx->threadCapacity = threadId;
return 1;
} }
} }
/* successfully expanded */
ctx->threadCapacity = numThreads;
ctx->threadLimit = numThreads;
return 0;
}
/* @return : 0 on success, 1 on error */
int POOL_resize(POOL_ctx* ctx, size_t numThreads)
{
int result;
if (ctx==NULL) return 1;
ZSTD_pthread_mutex_lock(&ctx->queueMutex);
result = POOL_resize_internal(ctx, numThreads);
ZSTD_pthread_cond_broadcast(&ctx->queuePopCond);
ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
return result;
}
/**
* Returns 1 if the queue is full and 0 otherwise.
*
* When queueSize is 1 (pool was created with an intended queueSize of 0),
* then a queue is empty if there is a thread free _and_ no job is waiting.
*/
static int isQueueFull(POOL_ctx const* ctx) {
if (ctx->queueSize > 1) {
return ctx->queueHead == ((ctx->queueTail + 1) % ctx->queueSize);
} else {
return (ctx->numThreadsBusy == ctx->threadLimit) ||
!ctx->queueEmpty;
}
}
static void POOL_add_internal(POOL_ctx* ctx, POOL_function function, void *opaque)
{
POOL_job const job = {function, opaque};
assert(ctx != NULL);
if (ctx->shutdown) return;
ctx->queueEmpty = 0;
ctx->queue[ctx->queueTail] = job;
ctx->queueTail = (ctx->queueTail + 1) % ctx->queueSize;
ZSTD_pthread_cond_signal(&ctx->queuePopCond);
}
void POOL_add(POOL_ctx* ctx, POOL_function function, void* opaque)
{
assert(ctx != NULL);
ZSTD_pthread_mutex_lock(&ctx->queueMutex);
/* Wait until there is space in the queue for the new job */
while (isQueueFull(ctx) && (!ctx->shutdown)) {
ZSTD_pthread_cond_wait(&ctx->queuePushCond, &ctx->queueMutex);
}
POOL_add_internal(ctx, function, opaque);
ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
}
int POOL_tryAdd(POOL_ctx* ctx, POOL_function function, void* opaque)
{
assert(ctx != NULL);
ZSTD_pthread_mutex_lock(&ctx->queueMutex);
if (isQueueFull(ctx)) {
ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
return 0;
}
POOL_add_internal(ctx, function, opaque);
ZSTD_pthread_mutex_unlock(&ctx->queueMutex);
return 1;
}
#else /* POOL_MT not defined */
/* ========================== */
/* No multi-threading support */
/* ========================== */
/* We don't need any data, but if it is empty, malloc() might return NULL. */
struct POOL_ctx_s {
int dummy;
};
static POOL_ctx g_ctx;
POOL_ctx* POOL_create(size_t numThreads, size_t queueSize) {
(void)numThreads;
(void)queueSize;
return &g_ctx;
}
void POOL_free(POOL_ctx* ctx) {
assert(!ctx || ctx == &g_ctx);
(void)ctx;
}
int POOL_resize(POOL_ctx* ctx, size_t numThreads) {
(void)ctx; (void)numThreads;
return 0;
}
void POOL_add(POOL_ctx* ctx, POOL_function function, void* opaque) {
(void)ctx;
function(opaque);
}
int POOL_tryAdd(POOL_ctx* ctx, POOL_function function, void* opaque) {
(void)ctx;
function(opaque);
return 1;
}
size_t POOL_sizeof(POOL_ctx* ctx) {
if (ctx==NULL) return 0; /* supports sizeof NULL */
assert(ctx == &g_ctx);
return sizeof(*ctx);
}
#endif /* ZSTD_MULTITHREAD */
/*
* Copyright (c) 2016-2021 Yann Collet, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under both the BSD-style license (found in the
* LICENSE file in the root directory of this source tree) and the GPLv2 (found
* in the COPYING file in the root directory of this source tree).
* You may select, at your option, one of the above-listed licenses.
*/
#ifndef POOL_H
#define POOL_H
#if defined (__cplusplus)
extern "C" {
#endif
#include <stddef.h> /* size_t */
typedef struct POOL_ctx_s POOL_ctx;
/*! POOL_create() :
* Create a thread pool with at most `numThreads` threads.
* `numThreads` must be at least 1.
* The maximum number of queued jobs before blocking is `queueSize`.
* @return : POOL_ctx pointer on success, else NULL.
*/
POOL_ctx* POOL_create(size_t numThreads, size_t queueSize);
/*! POOL_free() :
* Free a thread pool returned by POOL_create().
*/
void POOL_free(POOL_ctx* ctx);
/*! POOL_resize() :
* Expands or shrinks pool's number of threads.
* This is more efficient than releasing + creating a new context,
* since it tries to preserve and re-use existing threads.
* `numThreads` must be at least 1.
* @return : 0 when resize was successful,
* !0 (typically 1) if there is an error.
* note : only numThreads can be resized, queueSize remains unchanged.
*/
int POOL_resize(POOL_ctx* ctx, size_t numThreads);
/*! POOL_sizeof() :
* @return threadpool memory usage
* note : compatible with NULL (returns 0 in this case)
*/
size_t POOL_sizeof(POOL_ctx* ctx);
/*! POOL_function :
* The function type that can be added to a thread pool.
*/
typedef void (*POOL_function)(void*);
/*! POOL_add() :
* Add the job `function(opaque)` to the thread pool. `ctx` must be valid.
* Possibly blocks until there is room in the queue.
* Note : The function may be executed asynchronously,
* therefore, `opaque` must live until function has been completed.
*/
void POOL_add(POOL_ctx* ctx, POOL_function function, void* opaque);
/*! POOL_tryAdd() :
* Add the job `function(opaque)` to thread pool _if_ a worker is available.
* Returns immediately even if not (does not block).
* @return : 1 if successful, 0 if not.
*/
int POOL_tryAdd(POOL_ctx* ctx, POOL_function function, void* opaque);
#if defined (__cplusplus)
}
#endif
#endif
/*
* sort.cc - C++ sort functions
* Copyright (C) 2019-2021 Yann Collet
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
/*
* C++ sort functions tend to run faster than C ones due to templates allowing
* inline optimizations.
* Also, glibc's qsort() seems to inflate memory usage, resulting in OOM
* crashes on the test server.
*/
#include <algorithm> // std::sort
#define XXH_INLINE_ALL // XXH128_cmp
#include <xxhash.h>
#include "sort.hh"
void sort64(uint64_t* table, size_t size)
{
std::sort(table, table + size);
}
#include <stdlib.h> // qsort
void sort128(XXH128_hash_t* table, size_t size)
{
#if 0
// C++ sort using a custom function object
struct {
bool operator()(XXH128_hash_t a, XXH128_hash_t b) const
{
return XXH128_cmp(&a, &b);
}
} customLess;
std::sort(table, table + size, customLess);
#else
qsort(table, size, sizeof(*table), XXH128_cmp);
#endif
}
/*
* sort.hh - headers for C++ sort functions
* Copyright (C) 2019-2021 Yann Collet
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at :
* - xxHash homepage : https://www.xxhash.com
* - xxHash source repository : https://github.com/Cyan4973/xxHash
*/
#ifdef __cplusplus
extern "C" {
#endif
#include <stddef.h> // size
#include <stdint.h> // uint64_t
#define XXH_STATIC_LINKING_ONLY // XXH128_hash_t
#include "xxhash.h"
void sort64(uint64_t* table, size_t size);
void sort128(XXH128_hash_t* table, size_t size);
#ifdef __cplusplus
} // extern C
#endif
/**
* Copyright (c) 2016 Tino Reichardt
* All rights reserved.
*
* This source code is licensed under both the BSD-style license (found in the
* LICENSE file in the root directory of this source tree) and the GPLv2 (found
* in the COPYING file in the root directory of this source tree).
*
* You can contact the author at:
* - zstdmt source repository: https://github.com/mcmilk/zstdmt
*/
/**
* This file will hold wrapper for systems, which do not support pthreads
*/
/* === Build Macro === */
#ifndef POOL_MT // can be defined on command line
# define POOL_MT 1
#endif
/* create fake symbol to avoid empty translation unit warning */
int g_ZSTD_threading_useles_symbol;
#if POOL_MT && defined(_WIN32)
/**
* Windows minimalist Pthread Wrapper
*/
/* === Dependencies === */
#include <process.h>
#include <errno.h>
#include "threading.h"
/* === Implementation === */
static unsigned __stdcall worker(void *arg)
{
ZSTD_pthread_t* const thread = (ZSTD_pthread_t*) arg;
thread->arg = thread->start_routine(thread->arg);
return 0;
}
int ZSTD_pthread_create(ZSTD_pthread_t* thread, const void* unused,
void* (*start_routine) (void*), void* arg)
{
(void)unused;
thread->arg = arg;
thread->start_routine = start_routine;
thread->handle = (HANDLE) _beginthreadex(NULL, 0, worker, thread, 0, NULL);
if (!thread->handle)
return errno;
else
return 0;
}
int ZSTD_pthread_join(ZSTD_pthread_t thread, void **value_ptr)
{
DWORD result;
if (!thread.handle) return 0;
result = WaitForSingleObject(thread.handle, INFINITE);
switch (result) {
case WAIT_OBJECT_0:
if (value_ptr) *value_ptr = thread.arg;
return 0;
case WAIT_ABANDONED:
return EINVAL;
default:
return (int)GetLastError();
}
}
#endif /* POOL_MT */
/**
* Copyright (c) 2016 Tino Reichardt
* All rights reserved.
*
* This source code is licensed under both the BSD-style license (found in the
* LICENSE file in the root directory of this source tree) and the GPLv2 (found
* in the COPYING file in the root directory of this source tree).
*
* You can contact the author at:
* - zstdmt source repository: https://github.com/mcmilk/zstdmt
*/
#ifndef THREADING_H_938743
#define THREADING_H_938743
#if defined (__cplusplus)
extern "C" {
#endif
/* === Build Macro === */
#ifndef POOL_MT // can be defined on command line
# define POOL_MT 1
#endif
/* === Implementation === */
#if POOL_MT && defined(_WIN32)
/**
* Define windows version before include
*/
#undef WINVER
#define WINVER 0x0600
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0600
#ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <stdio.h>
/* mutex */
#define ZSTD_pthread_mutex_t CRITICAL_SECTION
#define ZSTD_pthread_mutex_init(a, b) ((void)(b), InitializeCriticalSection((a)), 0)
#define ZSTD_pthread_mutex_destroy(a) DeleteCriticalSection((a))
#define ZSTD_pthread_mutex_lock(a) EnterCriticalSection((a))
#define ZSTD_pthread_mutex_unlock(a) LeaveCriticalSection((a))
/* condition variable */
#define ZSTD_pthread_cond_t CONDITION_VARIABLE
#define ZSTD_pthread_cond_init(a, b) ((void)(b), InitializeConditionVariable((a)), 0)
#define ZSTD_pthread_cond_destroy(a) ((void)(a))
#define ZSTD_pthread_cond_wait(a, b) SleepConditionVariableCS((a), (b), INFINITE)
#define ZSTD_pthread_cond_signal(a) WakeConditionVariable((a))
#define ZSTD_pthread_cond_broadcast(a) WakeAllConditionVariable((a))
/* ZSTD_pthread_create() and ZSTD_pthread_join() */
typedef struct {
HANDLE handle;
void* (*start_routine)(void*);
void* arg;
} ZSTD_pthread_t;
int ZSTD_pthread_create(ZSTD_pthread_t* thread, const void* unused,
void* (*start_routine) (void*), void* arg);
int ZSTD_pthread_join(ZSTD_pthread_t thread, void** value_ptr);
/**
* add here more wrappers as required
*/
#elif POOL_MT /* posix assumed ; need a better detection method */
/* === POSIX Systems === */
# include <pthread.h>
#define ZSTD_pthread_mutex_t pthread_mutex_t
#define ZSTD_pthread_mutex_init(a, b) pthread_mutex_init((a), (b))
#define ZSTD_pthread_mutex_destroy(a) pthread_mutex_destroy((a))
#define ZSTD_pthread_mutex_lock(a) pthread_mutex_lock((a))
#define ZSTD_pthread_mutex_unlock(a) pthread_mutex_unlock((a))
#define ZSTD_pthread_cond_t pthread_cond_t
#define ZSTD_pthread_cond_init(a, b) pthread_cond_init((a), (b))
#define ZSTD_pthread_cond_destroy(a) pthread_cond_destroy((a))
#define ZSTD_pthread_cond_wait(a, b) pthread_cond_wait((a), (b))
#define ZSTD_pthread_cond_signal(a) pthread_cond_signal((a))
#define ZSTD_pthread_cond_broadcast(a) pthread_cond_broadcast((a))
#define ZSTD_pthread_t pthread_t
#define ZSTD_pthread_create(a, b, c, d) pthread_create((a), (b), (c), (d))
#define ZSTD_pthread_join(a, b) pthread_join((a),(b))
#else /* POOL_MT == 0 */
/* No multithreading support */
typedef int ZSTD_pthread_mutex_t;
#define ZSTD_pthread_mutex_init(a, b) ((void)(a), (void)(b), 0)
#define ZSTD_pthread_mutex_destroy(a) ((void)(a))
#define ZSTD_pthread_mutex_lock(a) ((void)(a))
#define ZSTD_pthread_mutex_unlock(a) ((void)(a))
typedef int ZSTD_pthread_cond_t;
#define ZSTD_pthread_cond_init(a, b) ((void)(a), (void)(b), 0)
#define ZSTD_pthread_cond_destroy(a) ((void)(a))
#define ZSTD_pthread_cond_wait(a, b) ((void)(a), (void)(b))
#define ZSTD_pthread_cond_signal(a) ((void)(a))
#define ZSTD_pthread_cond_broadcast(a) ((void)(a))
/* do not use ZSTD_pthread_t */
#endif /* POOL_MT */
#if defined (__cplusplus)
}
#endif
#endif /* THREADING_H_938743 */
#!/bin/bash
# Exit immediately if any command fails.
# https://stackoverflow.com/a/2871034
set -euxo pipefail
echo filename-escape-test-string > $'filename-escape-foo\nbar'
./xxhsum $'filename-escape-foo\nbar' | tee filename-escape-xxh64.txt
cat filename-escape-xxh64.txt
./xxhsum -c filename-escape-xxh64.txt
hexdump -C filename-escape-xxh64.txt
./xxhsum --tag $'filename-escape-foo\nbar' | tee filename-escape-xxh64-tag.txt
cat filename-escape-xxh64-tag.txt
./xxhsum -c filename-escape-xxh64-tag.txt
hexdump -C filename-escape-xxh64-tag.txt
rm filename-escape-xxh64-tag.txt
rm filename-escape-xxh64.txt
rm $'filename-escape-foo\nbar'
/*
* Generates a Unicode test for xxhsum without using Unicode in the source files.
*
* Copyright (C) 2020 Devin Hussey (easyaspi314)
*
* BSD 2-Clause License (https://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.
*/
/*
* Certain terminals don't properly handle UTF-8 (i.e. rxvt and command prompt
* in the default codepage), and that can cause issues when editing text.
*
* We use this C file to generate a file with a Unicode filename, a file with
* a checksum of said file, and both a Windows batch script and a Unix shell
* script to test the file.
*/
#define _CRT_SECURE_NO_WARNINGS /* Silence warnings on MSVC */
#include <stdio.h>
/* Use a Japanese filename, something that can't be cheated with ANSI.
* yuniko-do.unicode (literally unicode.unicode) */
/* Use raw hex values to ensure that the output is well-formed UTF-8. It is also more C90 compliant. */
static const char FILENAME[] = {
(char)0xe3, (char)0x83, (char)0xa6, /* U+30e6: Katakana letter yu */
(char)0xe3, (char)0x83, (char)0x8b, /* U+30cb: Katakana letter ni */
(char)0xe3, (char)0x82, (char)0xb3, /* U+30b3: Katakana letter ko */
(char)0xe3, (char)0x83, (char)0xbc, /* U+30fc: Katakana-Hiragana prolonged sound mark (dash) */
(char)0xe3, (char)0x83, (char)0x89, /* U+30c9: Katakana letter do */
'.','u','n','i','c','o','d','e','\0' /* ".unicode" (so we can glob in make clean and .gitignore) */
};
#ifdef _WIN32
/* The same text as above, but encoded in Windows UTF-16. */
static const wchar_t WFILENAME[] = { 0x30e6, 0x30cb, 0x30b3, 0x30fc, 0x30c9, L'.', L'u', L'n', L'i', L'c', L'o', L'd', L'e', L'\0' };
#endif
int main(void)
{
FILE *f, *script, *checksum;
/* Create our Unicode file. Use _wfopen on Windows as fopen doesn't support Unicode filenames. */
#ifdef _WIN32
if (!(f = _wfopen(WFILENAME, L"wb"))) return 1;
#else
if (!(f = fopen(FILENAME, "wb"))) return 1;
#endif
fprintf(f, "test\n");
fclose(f);
/* XXH64 checksum file with the precalculated checksum for said file. */
if (!(checksum = fopen("unicode_test.xxh64", "wb")))
return 1;
fprintf(checksum, "2d7f1808da1fa63c %s\n", FILENAME);
fclose(checksum);
/* Create two scripts for both Windows and Unix. */
/* Generate a Windows batch script. Always insert CRLF manually. */
if (!(script = fopen("unicode_test.bat", "wb")))
return 1;
/* Disable echoing the commands. We do that ourselves the naive way. */
fprintf(script, "@echo off\r\n");
/* Change to codepage 65001 to enable UTF-8 support. */
fprintf(script, "chcp 65001 >NUL 2>&1\r\n");
/* First test a Unicode filename */
fprintf(script, "echo Testing filename provided on command line...\r\n");
fprintf(script, "echo xxhsum.exe \"%s\"\r\n", FILENAME);
fprintf(script, "xxhsum.exe \"%s\"\r\n", FILENAME);
/* Bail on error */
fprintf(script, "if %%ERRORLEVEL%% neq 0 (\r\n");
fprintf(script, " exit /B %%ERRORLEVEL%%\r\n");
fprintf(script, ")\r\n");
/* Then test a checksum file. */
fprintf(script, "echo Testing a checksum file...\r\n");
fprintf(script, "echo xxhsum.exe -c unicode_test.xxh64\r\n");
fprintf(script, "xxhsum.exe -c unicode_test.xxh64\r\n");
fprintf(script, "exit /B %%ERRORLEVEL%%\r\n");
fclose(script);
/* Generate a Unix shell script */
if (!(script = fopen("unicode_test.sh", "wb")))
return 1;
fprintf(script, "#!/bin/sh\n");
/*
* Some versions of MSYS, MinGW and Cygwin do not support UTF-8, and the ones that
* don't may error with something like this:
*
* Error: Could not open '<mojibake>.unicode': No such file or directory.
*
* which is an internal error that happens when it tries to convert MinGW/Cygwin
* paths to Windows paths.
*
* In that case, we bail to cmd.exe and the batch script, which supports UTF-8
* on Windows 7 and later.
*/
fprintf(script, "case $(uname) in\n");
/* MinGW/MSYS converts /c to C:\ unless you have a double slash,
* Cygwin does not. */
fprintf(script, " *CYGWIN*)\n");
fprintf(script, " exec cmd.exe /c unicode_test.bat\n");
fprintf(script, " ;;\n");
fprintf(script, " *MINGW*|*MSYS*)\n");
fprintf(script, " exec cmd.exe //c unicode_test.bat\n");
fprintf(script, " ;;\n");
fprintf(script, "esac\n");
/* First test a Unicode filename */
fprintf(script, "echo Testing filename provided on command line...\n");
fprintf(script, "echo './xxhsum \"%s\" || exit $?'\n", FILENAME);
fprintf(script, "./xxhsum \"%s\" || exit $?\n", FILENAME);
/* Then test a checksum file. */
fprintf(script, "echo Testing a checksum file...\n");
fprintf(script, "echo './xxhsum -c unicode_test.xxh64 || exit $?'\n");
fprintf(script, "./xxhsum -c unicode_test.xxh64 || exit $?\n");
fclose(script);
return 0;
}
/*
* Multi-include test program
* Validates that xxhash.h can be included multiple times and in any order
*
* Copyright (C) 2020 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
#include <stdio.h> /* printf */
/* Normal include, gives access to public symbols */
#include "../xxhash.h"
/* Multiple consecutive inclusions are handled properly. */
#include "../xxhash.h"
/*
* Advanced include, gives access to experimental symbols
* This test ensures that xxhash.h can be included multiple times
* and in any order. The tested order is more difficult:
* without care, the declaration of experimental symbols could be skipped.
*/
#define XXH_STATIC_LINKING_ONLY
#include "../xxhash.h"
/*
* Inlining: redefine all identifiers, keep them private to the unit.
* Note: Without specific efforts, the identifier names would collide.
*
* To be linked with and without xxhash.o
* to test the symbol's presence and naming collisions.
*/
#define XXH_INLINE_ALL
#include "../xxhash.h"
/*
* Multiple consecutive inclusions with XXH_INLINE_ALL are handled properly.
*/
#define XXH_INLINE_ALL
#include "../xxhash.h"
void hash_advanced(void)
{
XXH3_state_t state; /* this type is part of experimental API */
XXH3_64bits_reset(&state);
const char input[] = "Hello World !";
XXH3_64bits_update(&state, input, sizeof(input));
XXH64_hash_t const h = XXH3_64bits_digest(&state);
printf("hash '%s': %08x%08x \n", input, (unsigned)(h >> 32), (unsigned)h);
}
int main(void)
{
hash_advanced();
}
/*
* Multi-include test program
* ensure that pixel, bool and vector are not redefined
*
* Copyright (C) 2020 Yann Collet
*
* GPL v2 License
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* You can contact the author at:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
/* gcc's altivec.h, included for the VSX code path,
* may, in some circumstances, redefine
* bool, vector and pixel keywords.
*
* This unit checks if it happens.
* It's a compile test.
* The test is mostly meaningful for PPC target using altivec.h
* hence XXH_VECTOR == XXH_VSX
*/
#define BOOL_VALUE 32123456
#define bool BOOL_VALUE
#define VECTOR_VALUE 374464784
#define vector VECTOR_VALUE
#define PIXEL_VALUE 5846841
#define pixel PIXEL_VALUE
#define XXH_INLINE_ALL
#include "../xxhash.h"
#if (bool != BOOL_VALUE)
# error "bool macro was redefined !"
#endif
#if (vector != VECTOR_VALUE)
# error "vector macro was redefined !"
#endif
#if (pixel != PIXEL_VALUE)
# error "pixel macro was redefined !"
#endif
int g_nonEmptyUnit = 0;
// xxHash/tests/sanity_test.c
// SPDX-License-Identifier: GPL-2.0-only
//
// Building
// ========
//
// cc sanity_test.c && ./a.out
//
/*
notes or changes:
main()
------
- All test methods (XXH32, XXH64, ...) are context free.
- It means that there's no restriction by order of tests and # of test. (Ready for multi-threaded / distributed test)
- To achieve it, some test has dedicated 'randSeed' to decouple dependency between tests.
- Note that for() loop is not ready for distributed test.
- randSeed still needs to be computed step by step in the for() loop so far.
*/
#define XXH_STATIC_LINKING_ONLY
#define XXH_IMPLEMENTATION /* access definitions */
#include "../cli/xsum_arch.h"
#include "../cli/xsum_os_specific.h"
#include "../cli/xsum_output.h"
#include "../cli/xsum_output.c"
#define XSUM_NO_MAIN 1
#include "../cli/xsum_os_specific.h"
#include "../cli/xsum_os_specific.c"
#include "../xxhash.h"
#include "sanity_test_vectors.h"
#include <assert.h> /* assert */
/* use #define to make them constant, required for initialization */
#define PRIME32 2654435761U
#define PRIME64 11400714785074694797ULL
#define SANITY_BUFFER_SIZE (4096 + 64 + 1)
/**/
static int abortByError = 1;
/**/
static void abortSanityTest() {
/* ??? : Should we show this message? */
XSUM_log("\rNote: If you modified the hash functions, make sure to either update tests/sanity_test_vectors.h with the following command\n"
"\r make -C tests sanity_test_vectors.h\n");
XSUM_log("\rAbort.\n");
exit(1);
}
/* TODO : Share this function with sanity_check.c and xsum_sanity_check.c */
/*
* Fills a test buffer with pseudorandom data.
*
* This is used in the sanity check - its values must not be changed.
*/
static void fillTestBuffer(XSUM_U8* buffer, size_t bufferLenInBytes)
{
XSUM_U64 byteGen = PRIME32;
size_t i;
assert(buffer != NULL);
for (i = 0; i < bufferLenInBytes; ++i) {
buffer[i] = (XSUM_U8)(byteGen>>56);
byteGen *= PRIME64;
}
}
/* TODO : Share this function with sanity_check.c and xsum_sanity_check.c */
/*
* Create (malloc) and fill buffer with pseudorandom data for sanity check.
*
* Use releaseSanityBuffer() to delete the buffer.
*/
static XSUM_U8* createSanityBuffer(size_t bufferLenInBytes)
{
XSUM_U8* buffer = (XSUM_U8*) malloc(bufferLenInBytes);
assert(buffer != NULL);
fillTestBuffer(buffer, bufferLenInBytes);
return buffer;
}
/* TODO : Share this function with sanity_check.c and xsum_sanity_check.c */
/*
* Delete (free) the buffer which has been genereated by createSanityBuffer()
*/
static void releaseSanityBuffer(XSUM_U8* buffer)
{
assert(buffer != NULL);
free(buffer);
}
/* TODO : Share this function with xsum_sanity_check.c */
/**/
static void checkResult32(XXH32_hash_t r1, XXH32_hash_t r2, const char* testName, size_t testNb, size_t lineNb)
{
if(r1 == r2) {
return;
}
XSUM_log("\rError: %s #%zd, line #%zd: Sanity check failed!\n", testName, testNb, lineNb);
XSUM_log("\rGot 0x%08X, expected 0x%08X.\n", (unsigned)r1, (unsigned)r2);
if(abortByError) {
abortSanityTest();
}
}
/* TODO : Share this function with xsum_sanity_check.c */
/**/
static void checkResult64(XXH64_hash_t r1, XXH64_hash_t r2, const char* testName, size_t testNb, size_t lineNb)
{
if(r1 == r2) {
return;
}
XSUM_log("\rError: %s #%zd, line #%zd: Sanity check failed!\n", testName, testNb, lineNb);
XSUM_log("\rGot 0x%08X%08XULL, expected 0x%08X%08XULL.\n",
(unsigned)(r1>>32), (unsigned)r1, (unsigned)(r2>>32), (unsigned)r2);
if(abortByError) {
abortSanityTest();
}
}
/* TODO : Share this function with xsum_sanity_check.c */
/**/
static void checkResult128(XXH128_hash_t r1, XXH128_hash_t r2, const char* testName, size_t testNb, size_t lineNb)
{
if ((r1.low64 == r2.low64) && (r1.high64 == r2.high64)) {
return;
}
XSUM_log("\rError: %s #%zd, line #%zd: Sanity check failed!\n", testName, testNb, lineNb);
XSUM_log("\rGot { 0x%08X%08XULL, 0x%08X%08XULL }, expected { 0x%08X%08XULL, 0x%08X%08XULL } \n",
(unsigned)(r1.low64>>32), (unsigned)r1.low64, (unsigned)(r1.high64>>32), (unsigned)r1.high64,
(unsigned)(r2.low64>>32), (unsigned)r2.low64, (unsigned)(r2.high64>>32), (unsigned)r2.high64 );
if(abortByError) {
abortSanityTest();
}
}
/* TODO : Share this function with xsum_sanity_check.c */
/**/
static void checkResultTestDataSample(const XSUM_U8* r1, const XSUM_U8* r2, const char* testName, size_t testNb, size_t lineNb)
{
if(memcmp(r1, r2, SECRET_SAMPLE_NBBYTES) == 0) {
return;
}
XSUM_log("\rError: %s #%zd, line #%zd: Sanity check failed!\n", testName, testNb, lineNb);
XSUM_log("\rGot { 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X }, expected { 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X } \n",
r1[0], r1[1], r1[2], r1[3], r1[4],
r2[0], r2[1], r2[2], r2[3], r2[4] );
if(abortByError) {
abortSanityTest();
}
}
/* TODO : Share this function with xsum_sanity_check.c */
/**/
static void testXXH32(
const void* data,
const XSUM_testdata32_t* testData,
const char* testName,
size_t testNb
) {
size_t const len = testData->len;
XSUM_U32 const seed = testData->seed;
XSUM_U32 const Nresult = testData->Nresult;
XXH32_state_t * const state = XXH32_createState();
if (len == 0) {
data = NULL;
} else {
assert(data != NULL);
}
assert(state != NULL);
checkResult32(XXH32(data, len, seed), Nresult, testName, testNb, __LINE__);
(void)XXH32_reset(state, seed);
(void)XXH32_update(state, data, len);
checkResult32(XXH32_digest(state), Nresult, testName, testNb, __LINE__);
(void)XXH32_reset(state, seed);
{
size_t pos;
for (pos = 0; pos < len; ++pos) {
(void)XXH32_update(state, ((const char*)data)+pos, 1);
}
}
checkResult32(XXH32_digest(state), Nresult, testName, testNb, __LINE__);
XXH32_freeState(state);
}
/* TODO : Share this function with xsum_sanity_check.c */
/**/
static void testXXH64(
const void* data,
const XSUM_testdata64_t* testData,
const char* testName,
size_t testNb
)
{
size_t const len = (size_t)testData->len;
XSUM_U64 const seed = testData->seed;
XSUM_U64 const Nresult = testData->Nresult;
XXH64_state_t * const state = XXH64_createState();
if (len == 0) {
data = NULL;
} else {
assert(data != NULL);
}
assert(state != NULL);
checkResult64(XXH64(data, len, seed), Nresult, testName, testNb, __LINE__);
(void)XXH64_reset(state, seed);
(void)XXH64_update(state, data, len);
checkResult64(XXH64_digest(state), Nresult, testName, testNb, __LINE__);
(void)XXH64_reset(state, seed);
{
size_t pos;
for (pos = 0; pos < len; ++pos) {
(void)XXH64_update(state, ((const char*)data)+pos, 1);
}
}
checkResult64(XXH64_digest(state), Nresult, testName, testNb, __LINE__);
XXH64_freeState(state);
}
/* TODO : Share this function with xsum_sanity_check.c */
/*
* Used to get "random" (but actually 100% reproducible) lengths for
* XSUM_XXH3_randomUpdate.
*/
static XSUM_U32 SANITY_TEST_rand(XSUM_U64* pRandSeed)
{
XSUM_U64 seed = *pRandSeed;
seed *= PRIME64;
*pRandSeed = seed;
return (XSUM_U32)(seed >> 40);
}
/* TODO : Share this function with xsum_sanity_check.c */
/**/
static XSUM_U64 SANITY_TEST_computeRandSeed(size_t step)
{
XSUM_U64 randSeed = PRIME32;
size_t i = 0;
for(i = 0; i < step; ++i) {
SANITY_TEST_rand(&randSeed);
}
return randSeed;
}
/* TODO : Share this definition with xsum_sanity_check.c */
/*
* Technically, XXH3_64bits_update is identical to XXH3_128bits_update as of
* v0.8.0, but we treat them as separate.
*/
typedef XXH_errorcode (*SANITY_TEST_XXH3_update_t)(XXH3_state_t* state, const void* input, size_t length);
/* TODO : Share this function with xsum_sanity_check.c */
/*
* Runs the passed XXH3_update variant on random lengths. This is to test the
* more complex logic of the update function, catching bugs like this one:
* https://github.com/Cyan4973/xxHash/issues/378
*/
static void SANITY_TEST_XXH3_randomUpdate(
XXH3_state_t* state,
const void* data,
size_t len,
XSUM_U64* pRandSeed,
SANITY_TEST_XXH3_update_t update_fn
)
{
size_t p = 0;
while (p < len) {
size_t const modulo = len > 2 ? len : 2;
size_t l = (size_t)(SANITY_TEST_rand(pRandSeed)) % modulo;
if (p + l > len) l = len - p;
(void)update_fn(state, (const char*)data+p, l);
p += l;
}
}
/* TODO : Share this function with xsum_sanity_check.c */
/**/
static void testXXH3(
const void* data,
const XSUM_testdata64_t* testData,
XSUM_U64* pRandSeed,
const char* testName,
size_t testNb
)
{
size_t const len = testData->len;
XSUM_U64 const seed = testData->seed;
XSUM_U64 const Nresult = testData->Nresult;
if (len == 0) {
data = NULL;
} else {
assert(data != NULL);
}
{ XSUM_U64 const Dresult = XXH3_64bits_withSeed(data, len, seed);
checkResult64(Dresult, Nresult, testName, testNb, __LINE__);
}
/* check that the no-seed variant produces same result as seed==0 */
if (seed == 0) {
XSUM_U64 const Dresult = XXH3_64bits(data, len);
checkResult64(Dresult, Nresult, testName, testNb, __LINE__);
}
/* check that the combination of
* XXH3_generateSecret_fromSeed() and XXH3_64bits_withSecretandSeed()
* results in exactly the same hash generation as XXH3_64bits_withSeed() */
{ char secretBuffer[XXH3_SECRET_DEFAULT_SIZE+1];
char* const secret = secretBuffer + 1; /* intentional unalignment */
XXH3_generateSecret_fromSeed(secret, seed);
{ XSUM_U64 const Dresult = XXH3_64bits_withSecretandSeed(data, len, secret, XXH3_SECRET_DEFAULT_SIZE, seed);
checkResult64(Dresult, Nresult, testName, testNb, __LINE__);
} }
/* streaming API test */
{ XXH3_state_t* const state = XXH3_createState();
assert(state != NULL);
/* single ingestion */
(void)XXH3_64bits_reset_withSeed(state, seed);
(void)XXH3_64bits_update(state, data, len);
checkResult64(XXH3_64bits_digest(state), Nresult, testName, testNb, __LINE__);
/* random ingestion */
(void)XXH3_64bits_reset_withSeed(state, seed);
SANITY_TEST_XXH3_randomUpdate(state, data, len, pRandSeed, &XXH3_64bits_update);
checkResult64(XXH3_64bits_digest(state), Nresult, testName, testNb, __LINE__);
/* byte by byte ingestion */
{ size_t pos;
(void)XXH3_64bits_reset_withSeed(state, seed);
for (pos=0; pos<len; pos++)
(void)XXH3_64bits_update(state, ((const char*)data)+pos, 1);
checkResult64(XXH3_64bits_digest(state), Nresult, testName, testNb, __LINE__);
}
/* check that streaming with a combination of
* XXH3_generateSecret_fromSeed() and XXH3_64bits_reset_withSecretandSeed()
* results in exactly the same hash generation as XXH3_64bits_reset_withSeed() */
{ char secretBuffer[XXH3_SECRET_DEFAULT_SIZE+1];
char* const secret = secretBuffer + 1; /* intentional unalignment */
XXH3_generateSecret_fromSeed(secret, seed);
/* single ingestion */
(void)XXH3_64bits_reset_withSecretandSeed(state, secret, XXH3_SECRET_DEFAULT_SIZE, seed);
(void)XXH3_64bits_update(state, data, len);
checkResult64(XXH3_64bits_digest(state), Nresult, testName, testNb, __LINE__);
}
XXH3_freeState(state);
}
}
/* TODO : Share this function with xsum_sanity_check.c */
/**/
static void testXXH3_withSecret(
const void* data,
const void* secret,
size_t secretSize,
const XSUM_testdata64_t* testData,
XSUM_U64* pRandSeed,
const char* testName,
size_t testNb
)
{
size_t const len = (size_t)testData->len;
XSUM_U64 const Nresult = testData->Nresult;
if (len == 0) {
data = NULL;
} else {
assert(data != NULL);
}
{ XSUM_U64 const Dresult = XXH3_64bits_withSecret(data, len, secret, secretSize);
checkResult64(Dresult, Nresult, testName, testNb, __LINE__);
}
/* check that XXH3_64bits_withSecretandSeed()
* results in exactly the same return value as XXH3_64bits_withSecret() */
if (len > XXH3_MIDSIZE_MAX)
{ XSUM_U64 const Dresult = XXH3_64bits_withSecretandSeed(data, len, secret, secretSize, 0);
checkResult64(Dresult, Nresult, testName, testNb, __LINE__);
}
/* streaming API test */
{ XXH3_state_t * const state = XXH3_createState();
assert(state != NULL);
(void)XXH3_64bits_reset_withSecret(state, secret, secretSize);
(void)XXH3_64bits_update(state, data, len);
checkResult64(XXH3_64bits_digest(state), Nresult, testName, testNb, __LINE__);
/* random ingestion */
(void)XXH3_64bits_reset_withSecret(state, secret, secretSize);
SANITY_TEST_XXH3_randomUpdate(state, data, len, pRandSeed, &XXH3_64bits_update);
checkResult64(XXH3_64bits_digest(state), Nresult, testName, testNb, __LINE__);
/* byte by byte ingestion */
{ size_t pos;
(void)XXH3_64bits_reset_withSecret(state, secret, secretSize);
for (pos=0; pos<len; pos++)
(void)XXH3_64bits_update(state, ((const char*)data)+pos, 1);
checkResult64(XXH3_64bits_digest(state), Nresult, testName, testNb, __LINE__);
}
/* check that XXH3_64bits_reset_withSecretandSeed()
* results in exactly the same return value as XXH3_64bits_reset_withSecret() */
if (len > XXH3_MIDSIZE_MAX) {
/* single ingestion */
(void)XXH3_64bits_reset_withSecretandSeed(state, secret, secretSize, 0);
(void)XXH3_64bits_update(state, data, len);
checkResult64(XXH3_64bits_digest(state), Nresult, testName, testNb, __LINE__);
}
XXH3_freeState(state);
}
}
/* TODO : Share this function with xsum_sanity_check.c */
/**/
static void testXXH128(
const void* data,
const XSUM_testdata128_t* testData,
XSUM_U64* pRandSeed,
const char* testName,
size_t testNb
)
{
size_t const len = (size_t)testData->len;
XSUM_U64 const seed = testData->seed;
XXH128_hash_t const Nresult = testData->Nresult;
if (len == 0) {
data = NULL;
} else {
assert(data != NULL);
}
{ XXH128_hash_t const Dresult = XXH3_128bits_withSeed(data, len, seed);
checkResult128(Dresult, Nresult, testName, testNb, __LINE__);
}
/* check that XXH128() is identical to XXH3_128bits_withSeed() */
{ XXH128_hash_t const Dresult2 = XXH128(data, len, seed);
checkResult128(Dresult2, Nresult, testName, testNb, __LINE__);
}
/* check that the no-seed variant produces same result as seed==0 */
if (seed == 0) {
XXH128_hash_t const Dresult = XXH3_128bits(data, len);
checkResult128(Dresult, Nresult, testName, testNb, __LINE__);
}
/* check that the combination of
* XXH3_generateSecret_fromSeed() and XXH3_128bits_withSecretandSeed()
* results in exactly the same hash generation as XXH3_64bits_withSeed() */
{ char secretBuffer[XXH3_SECRET_DEFAULT_SIZE+1];
char* const secret = secretBuffer + 1; /* intentional unalignment */
XXH3_generateSecret_fromSeed(secret, seed);
{ XXH128_hash_t const Dresult = XXH3_128bits_withSecretandSeed(data, len, secret, XXH3_SECRET_DEFAULT_SIZE, seed);
checkResult128(Dresult, Nresult, testName, testNb, __LINE__);
} }
/* streaming API test */
{ XXH3_state_t * const state = XXH3_createState();
assert(state != NULL);
/* single ingestion */
(void)XXH3_128bits_reset_withSeed(state, seed);
(void)XXH3_128bits_update(state, data, len);
checkResult128(XXH3_128bits_digest(state), Nresult, testName, testNb, __LINE__);
/* random ingestion */
(void)XXH3_128bits_reset_withSeed(state, seed);
SANITY_TEST_XXH3_randomUpdate(state, data, len, pRandSeed, &XXH3_128bits_update);
checkResult128(XXH3_128bits_digest(state), Nresult, testName, testNb, __LINE__);
/* byte by byte ingestion */
{ size_t pos;
(void)XXH3_128bits_reset_withSeed(state, seed);
for (pos=0; pos<len; pos++)
(void)XXH3_128bits_update(state, ((const char*)data)+pos, 1);
checkResult128(XXH3_128bits_digest(state), Nresult, testName, testNb, __LINE__);
}
/* check that streaming with a combination of
* XXH3_generateSecret_fromSeed() and XXH3_128bits_reset_withSecretandSeed()
* results in exactly the same hash generation as XXH3_128bits_reset_withSeed() */
{ char secretBuffer[XXH3_SECRET_DEFAULT_SIZE+1];
char* const secret = secretBuffer + 1; /* intentional unalignment */
XXH3_generateSecret_fromSeed(secret, seed);
/* single ingestion */
(void)XXH3_128bits_reset_withSecretandSeed(state, secret, XXH3_SECRET_DEFAULT_SIZE, seed);
(void)XXH3_128bits_update(state, data, len);
checkResult128(XXH3_128bits_digest(state), Nresult, testName, testNb, __LINE__);
}
XXH3_freeState(state);
}
}
/* TODO : Share this function with xsum_sanity_check.c */
/**/
static void testXXH128_withSecret(
const void* data,
const void* secret,
size_t secretSize,
const XSUM_testdata128_t* testData,
XSUM_U64* pRandSeed,
const char* testName,
size_t testNb
)
{
size_t const len = testData->len;
XXH128_hash_t const Nresult = testData->Nresult;
if (len == 0) {
data = NULL;
} else {
assert(data != NULL);
}
{ XXH128_hash_t const Dresult = XXH3_128bits_withSecret(data, len, secret, secretSize);
checkResult128(Dresult, Nresult, testName, testNb, __LINE__);
}
/* check that XXH3_128bits_withSecretandSeed()
* results in exactly the same return value as XXH3_128bits_withSecret() */
if (len > XXH3_MIDSIZE_MAX)
{ XXH128_hash_t const Dresult = XXH3_128bits_withSecretandSeed(data, len, secret, secretSize, 0);
checkResult128(Dresult, Nresult, testName, testNb, __LINE__);
}
/* streaming API test */
{ XXH3_state_t* const state = XXH3_createState();
assert(state != NULL);
(void)XXH3_128bits_reset_withSecret(state, secret, secretSize);
(void)XXH3_128bits_update(state, data, len);
checkResult128(XXH3_128bits_digest(state), Nresult, testName, testNb, __LINE__);
/* random ingestion */
(void)XXH3_128bits_reset_withSecret(state, secret, secretSize);
SANITY_TEST_XXH3_randomUpdate(state, data, len, pRandSeed, &XXH3_128bits_update);
checkResult128(XXH3_128bits_digest(state), Nresult, testName, testNb, __LINE__);
/* byte by byte ingestion */
{ size_t pos;
(void)XXH3_128bits_reset_withSecret(state, secret, secretSize);
for (pos=0; pos<len; pos++)
(void)XXH3_128bits_update(state, ((const char*)data)+pos, 1);
checkResult128(XXH3_128bits_digest(state), Nresult, testName, testNb, __LINE__);
}
/* check that XXH3_128bits_reset_withSecretandSeed()
* results in exactly the same return value as XXH3_128bits_reset_withSecret() */
if (len > XXH3_MIDSIZE_MAX) {
/* single ingestion */
(void)XXH3_128bits_reset_withSecretandSeed(state, secret, secretSize, 0);
(void)XXH3_128bits_update(state, data, len);
checkResult128(XXH3_128bits_digest(state), Nresult, testName, testNb, __LINE__);
}
XXH3_freeState(state);
}
}
/* TODO : Share this function with xsum_sanity_check.c */
/**/
static void testSecretGenerator(
const void* customSeed,
const XSUM_testdata_sample_t* testData,
const char* testName,
size_t testNb
)
{
/* TODO : Share this array with sanity_check.c and xsum_sanity_check.c */
static const int sampleIndex[SECRET_SAMPLE_NBBYTES] = { 0, 62, 131, 191, 241 }; /* position of sampled bytes */
XSUM_U8 secretBuffer[SECRET_SIZE_MAX] = {0};
XSUM_U8 samples[SECRET_SAMPLE_NBBYTES];
int i;
assert(testData->secretLen <= SECRET_SIZE_MAX);
XXH3_generateSecret(secretBuffer, testData->secretLen, customSeed, testData->seedLen);
for (i=0; i<SECRET_SAMPLE_NBBYTES; i++) {
samples[i] = secretBuffer[sampleIndex[i]];
}
checkResultTestDataSample(samples, testData->byte, testName, testNb, __LINE__);
}
/**/
int main(int argc, const char* argv[])
{
(void) argc;
(void) argv;
size_t testCount = 0;
size_t const sanityBufferSizeInBytes = SANITY_BUFFER_SIZE;
XSUM_U8* const sanityBuffer = createSanityBuffer(sanityBufferSizeInBytes);
const void* const secret = sanityBuffer + 7;
size_t const secretSize = XXH3_SECRET_SIZE_MIN + 11;
assert(sanityBufferSizeInBytes >= 7 + secretSize);
{
/* XXH32 */
size_t const n = sizeof(XSUM_XXH32_testdata) / sizeof(XSUM_XXH32_testdata[0]);
size_t i;
for (i = 0; i < n; ++i, ++testCount) {
testXXH32(
sanityBuffer,
&XSUM_XXH32_testdata[i],
"XSUM_XXH32_testdata",
i
);
}
}
{
/* XXH64 */
size_t const n = sizeof(XSUM_XXH64_testdata) / sizeof(XSUM_XXH64_testdata[0]);
size_t i;
for (i = 0; i < n; ++i, ++testCount) {
testXXH64(
sanityBuffer,
&XSUM_XXH64_testdata[i],
"XSUM_XXH64_testdata",
i
);
}
}
{
/* XXH3_64bits, seeded */
size_t const randCount = 0;
XSUM_U64 randSeed = SANITY_TEST_computeRandSeed(randCount);
size_t const n = sizeof(XSUM_XXH3_testdata) / sizeof(XSUM_XXH3_testdata[0]);
size_t i;
for (i = 0; i < n; ++i, ++testCount) {
testXXH3(
sanityBuffer,
&XSUM_XXH3_testdata[i],
&randSeed,
"XSUM_XXH3_testdata",
i
);
}
}
{
/* XXH3_64bits, custom secret */
size_t const randCount = 22730;
XSUM_U64 randSeed = SANITY_TEST_computeRandSeed(randCount);
size_t const n = sizeof(XSUM_XXH3_withSecret_testdata) / sizeof(XSUM_XXH3_withSecret_testdata[0]);
size_t i;
for (i = 0; i < n; ++i, ++testCount) {
testXXH3_withSecret(
sanityBuffer,
secret,
secretSize,
&XSUM_XXH3_withSecret_testdata[i],
&randSeed,
"XSUM_XXH3_withSecret_testdata",
i
);
testCount++;
}
}
{
/* XXH128 */
size_t const randCount = 34068;
XSUM_U64 randSeed = SANITY_TEST_computeRandSeed(randCount);
size_t const n = (sizeof(XSUM_XXH128_testdata)/sizeof(XSUM_XXH128_testdata[0]));
size_t i;
for (i = 0; i < n; ++i, ++testCount) {
testXXH128(
sanityBuffer,
&XSUM_XXH128_testdata[i],
&randSeed,
"XSUM_XXH128_testdata",
i
);
}
}
{
/* XXH128 with custom Secret */
size_t const randCount = 68019;
XSUM_U64 randSeed = SANITY_TEST_computeRandSeed(randCount);
size_t const n = (sizeof(XSUM_XXH128_withSecret_testdata)/sizeof(XSUM_XXH128_withSecret_testdata[0]));
size_t i;
for (i = 0; i < n; ++i, ++testCount) {
testXXH128_withSecret(
sanityBuffer,
secret,
secretSize,
&XSUM_XXH128_withSecret_testdata[i],
&randSeed,
"XSUM_XXH128_withSecret_testdata",
i
);
}
}
{
/* secret generator */
size_t const n = sizeof(XSUM_XXH3_generateSecret_testdata) / sizeof(XSUM_XXH3_generateSecret_testdata[0]);
size_t i;
for (i = 0; i < n; ++i, ++testCount) {
assert(XSUM_XXH3_generateSecret_testdata[i].seedLen <= SANITY_BUFFER_SIZE);
testSecretGenerator(
sanityBuffer,
&XSUM_XXH3_generateSecret_testdata[i],
"XSUM_XXH3_generateSecret_testdata",
i
);
}
}
releaseSanityBuffer(sanityBuffer);
XSUM_log("\rOK. (passes %zd tests)\n", testCount);
return EXIT_SUCCESS;
}
This source diff could not be displayed because it is too large. You can view the blob instead.
// xxHash/tests/sanity_test_vectors_generator.c
// SPDX-License-Identifier: GPL-2.0-only
//
// So far, this program just generates sanity_test_vectors.h
//
// Building
// ========
//
// cc sanity_test_vectors_generator.c && ./a.out
// less sanity_test_vectors.h
//
#define XXH_STATIC_LINKING_ONLY
#define XXH_IMPLEMENTATION /* access definitions */
#include "../cli/xsum_arch.h"
#include "../cli/xsum_os_specific.h"
#include "../xxhash.h"
#include <assert.h> /* assert */
/* use #define to make them constant, required for initialization */
#define PRIME32 2654435761U
#define PRIME64 11400714785074694797ULL
#define SANITY_BUFFER_SIZE (4096 + 64 + 1)
/* TODO : Share these test vector definitions with sanity_check.c and xsum_sanity_check.c */
/*
* Test data vectors
*/
typedef struct {
XSUM_U32 len;
XSUM_U32 seed;
XSUM_U32 Nresult;
} XSUM_testdata32_t;
typedef struct {
XSUM_U32 len;
XSUM_U64 seed;
XSUM_U64 Nresult;
} XSUM_testdata64_t;
typedef struct {
XSUM_U32 len;
XSUM_U64 seed;
XXH128_hash_t Nresult;
} XSUM_testdata128_t;
#define SECRET_SAMPLE_NBBYTES 5
typedef struct {
XSUM_U32 seedLen;
XSUM_U32 secretLen;
XSUM_U8 byte[SECRET_SAMPLE_NBBYTES];
} XSUM_testdata_sample_t;
#ifndef SECRET_SIZE_MAX
# define SECRET_SIZE_MAX 9867
#endif
/* TODO : Share these generators with sanity_check.c and xsum_sanity_check.c */
/* Test vector generators */
static XSUM_testdata32_t tvgen_XXH32(const XSUM_U8* buf, size_t len, XSUM_U32 seed) {
XSUM_testdata32_t v;
v.len = len;
v.seed = seed;
v.Nresult = XXH32(buf, len, seed);
return v;
}
static XSUM_testdata64_t tvgen_XXH64(const XSUM_U8* buf, size_t len, XSUM_U64 seed) {
XSUM_testdata64_t v;
v.len = len;
v.seed = seed;
v.Nresult = XXH64(buf, len, seed);
return v;
}
static XSUM_testdata64_t tvgen_XXH3_64bits_withSeed(const XSUM_U8* buf, size_t len, XSUM_U64 seed) {
XSUM_testdata64_t v;
v.len = len;
v.seed = seed;
v.Nresult = XXH3_64bits_withSeed(buf, len, seed);
return v;
}
static XSUM_testdata64_t tvgen_XXH3_64bits_withSecret(const XSUM_U8* buf, size_t len, const void* secret, size_t secretSize) {
XSUM_testdata64_t v;
v.len = len;
v.seed = 0;
v.Nresult = XXH3_64bits_withSecret(buf, len, secret, secretSize);
return v;
}
static XSUM_testdata128_t tvgen_XXH3_128bits_withSeed(const XSUM_U8* buf, size_t len, XSUM_U64 seed) {
XSUM_testdata128_t v;
v.len = len;
v.seed = seed;
v.Nresult = XXH3_128bits_withSeed(buf, len, seed);
return v;
}
static XSUM_testdata128_t tvgen_XXH3_128bits_withSecret(const XSUM_U8* buf, size_t len, const void* secret, size_t secretSize) {
XSUM_testdata128_t v;
v.len = len;
v.seed = 0;
v.Nresult = XXH3_128bits_withSecret(buf, len, secret, secretSize);
return v;
}
static XSUM_testdata_sample_t tvgen_XXH3_generateSecret(
void* secretBuffer,
size_t secretSize,
const void* customSeed,
size_t customSeedSize
) {
XXH3_generateSecret(secretBuffer, secretSize, customSeed, customSeedSize);
XSUM_testdata_sample_t v;
v.seedLen = customSeedSize;
v.secretLen = secretSize;
/* TODO : Share this array with sanity_check.c and xsum_sanity_check.c */
/* position of sampled bytes */
static const int sampleIndex[SECRET_SAMPLE_NBBYTES] = { 0, 62, 131, 191, 241 };
for(int i = 0; i < SECRET_SAMPLE_NBBYTES; ++i) {
const XSUM_U8* const secretBufferAsU8 = (const XSUM_U8*) secretBuffer;
v.byte[i] = secretBufferAsU8[sampleIndex[i]];
}
return v;
}
/* Test vector serializers */
static void fprintf_XSUM_testdata32_t(FILE* fp, XSUM_testdata32_t const v) {
fprintf(fp, "{ %4d, 0x%08XU, 0x%08XU },", v.len, v.seed, v.Nresult);
}
static void fprintf_XSUM_testdata64_t(FILE* fp, XSUM_testdata64_t const v) {
fprintf(fp, "{ %4d, 0x%016zXULL, 0x%016zXULL },", v.len, v.seed, v.Nresult);
}
static void fprintf_XSUM_testdata128_t(FILE* fp, XSUM_testdata128_t const v) {
fprintf(fp, "{ %4d, 0x%016zXULL, { 0x%016zXULL, 0x%016zXULL } },",
v.len, v.seed, v.Nresult.low64, v.Nresult.high64);
}
static void fprintf_XSUM_testdata_sample_t(FILE* fp, XSUM_testdata_sample_t const v) {
fprintf(fp,"{ %4d, %4d, { 0x%02X, 0x%02X, 0x%02X, 0x%02X, 0x%02X } },",
v.seedLen, v.secretLen, v.byte[0], v.byte[1], v.byte[2], v.byte[3], v.byte[4]);
}
/* TODO : Share this function with sanity_check.c and xsum_sanity_check.c */
/*
* Fills a test buffer with pseudorandom data.
*
* This is used in the sanity check - its values must not be changed.
*/
static void fillTestBuffer(XSUM_U8* buffer, size_t bufferLenInBytes)
{
XSUM_U64 byteGen = PRIME32;
size_t i;
assert(buffer != NULL);
for (i = 0; i < bufferLenInBytes; ++i) {
buffer[i] = (XSUM_U8)(byteGen>>56);
byteGen *= PRIME64;
}
}
/* TODO : Share this function with sanity_check.c and xsum_sanity_check.c */
/*
* Create (malloc) and fill buffer with pseudorandom data for sanity check.
*
* Use releaseSanityBuffer() to delete the buffer.
*/
static XSUM_U8* createSanityBuffer(size_t bufferLenInBytes)
{
XSUM_U8* const buffer = (XSUM_U8*) malloc(bufferLenInBytes);
assert(buffer != NULL);
fillTestBuffer(buffer, bufferLenInBytes);
return buffer;
}
/* TODO : Share this function with sanity_check.c and xsum_sanity_check.c */
/*
* Delete (free) the buffer which has been genereated by createSanityBuffer()
*/
static void releaseSanityBuffer(XSUM_U8* buffer)
{
assert(buffer != NULL);
free(buffer);
}
/* Generate test vectors for XXH32() */
static void generate_sanity_test_vectors_xxh32(FILE* fp, size_t maxLen) {
const char* const arrayTypeName = "XSUM_testdata32_t";
const char* const arrayName = "XSUM_XXH32_testdata";
fprintf(fp, "static const %s %s[] = {\n", arrayTypeName, arrayName);
XSUM_U8* const sanityBuffer = createSanityBuffer(maxLen);
size_t index = 0;
for(size_t len = 0; len < maxLen; ++len) {
static const size_t seeds[] = { 0, PRIME32 };
for(size_t iSeed = 0; iSeed < sizeof(seeds)/sizeof(seeds[0]); ++iSeed) {
size_t const seed = seeds[iSeed];
XSUM_testdata32_t const v = tvgen_XXH32(sanityBuffer, len, seed);
fprintf(fp, " ");
fprintf_XSUM_testdata32_t(fp, v);
fprintf(fp, " /* %s[%zd] */\n", arrayName, index++);
}
}
releaseSanityBuffer(sanityBuffer);
fprintf(fp, "};\n");
}
/* Generate test vectors for XXH64() */
static void generate_sanity_test_vectors_xxh64(FILE* fp, size_t maxLen) {
const char* const arrayTypeName = "XSUM_testdata64_t";
const char* const arrayName = "XSUM_XXH64_testdata";
fprintf(fp, "static const %s %s[] = {\n", arrayTypeName, arrayName);
XSUM_U8* const sanityBuffer = createSanityBuffer(maxLen);
size_t index = 0;
for(size_t len = 0; len < maxLen; ++len) {
static const size_t seeds[] = { 0, PRIME32 };
for(size_t iSeed = 0; iSeed < sizeof(seeds)/sizeof(seeds[0]); ++iSeed) {
size_t const seed = seeds[iSeed];
XSUM_testdata64_t const v = tvgen_XXH64(sanityBuffer, len, seed);
fprintf(fp, " ");
fprintf_XSUM_testdata64_t(fp, v);
fprintf(fp, " /* %s[%zd] */\n", arrayName, index++);
}
}
releaseSanityBuffer(sanityBuffer);
fprintf(fp, "};\n");
}
/* Generate test vectors for XXH3_64bits_withSeed() */
static void generate_sanity_test_vectors_xxh3(FILE* fp, size_t maxLen) {
const char* const arrayTypeName = "XSUM_testdata64_t";
const char* const arrayName = "XSUM_XXH3_testdata";
fprintf(fp, "static const %s %s[] = {\n", arrayTypeName, arrayName);
XSUM_U8* const sanityBuffer = createSanityBuffer(maxLen);
size_t index = 0;
for(size_t len = 0; len < maxLen; ++len) {
static const size_t seeds[] = { 0, PRIME64 };
for(size_t iSeed = 0; iSeed < sizeof(seeds)/sizeof(seeds[0]); ++iSeed) {
size_t const seed = seeds[iSeed];
XSUM_testdata64_t const v = tvgen_XXH3_64bits_withSeed(sanityBuffer, len, seed);
fprintf(fp, " ");
fprintf_XSUM_testdata64_t(fp, v);
fprintf(fp, " /* %s[%zd] */\n", arrayName, index++);
}
}
releaseSanityBuffer(sanityBuffer);
fprintf(fp, "};\n");
}
/* Generate test vectors for XXH3_64bits_withSecret() */
static void generate_sanity_test_vectors_xxh3_withSecret(FILE* fp, size_t maxLen) {
const char* const arrayTypeName = "XSUM_testdata64_t";
const char* const arrayName = "XSUM_XXH3_withSecret_testdata";
fprintf(fp, "static const %s %s[] = {\n", arrayTypeName, arrayName);
XSUM_U8* const sanityBuffer = createSanityBuffer(maxLen);
const void* const secret = sanityBuffer + 7;
size_t const secretSize = XXH3_SECRET_SIZE_MIN + 11;
assert(maxLen >= 7 + secretSize);
size_t index = 0;
for(size_t len = 0; len < maxLen; ++len) {
XSUM_testdata64_t const v = tvgen_XXH3_64bits_withSecret(sanityBuffer, len, secret, secretSize);
fprintf(fp, " ");
fprintf_XSUM_testdata64_t(fp, v);
fprintf(fp, " /* %s[%zd] */\n", arrayName, index++);
}
releaseSanityBuffer(sanityBuffer);
fprintf(fp, "};\n");
}
/* Generate test vectors for XXH3_128bits_withSeed() */
static void generate_sanity_test_vectors_xxh128(FILE* fp, size_t maxLen) {
const char* const arrayTypeName = "XSUM_testdata128_t";
const char* const arrayName = "XSUM_XXH128_testdata";
fprintf(fp, "static const %s %s[] = {\n", arrayTypeName, arrayName);
XSUM_U8* const sanityBuffer = createSanityBuffer(maxLen);
size_t index = 0;
for(size_t len = 0; len < maxLen; ++len) {
static const size_t seeds[] = { 0, PRIME32, PRIME64 };
for(size_t iSeed = 0; iSeed < sizeof(seeds)/sizeof(seeds[0]); ++iSeed) {
XSUM_U64 const seed = seeds[iSeed];
XSUM_testdata128_t const v = tvgen_XXH3_128bits_withSeed(sanityBuffer, len, seed);
fprintf(fp, " ");
fprintf_XSUM_testdata128_t(fp, v);
fprintf(fp, " /* %s[%zd] */\n", arrayName, index++);
}
}
fprintf(fp, "};\n");
releaseSanityBuffer(sanityBuffer);
}
/* Generate test vectors for XXH3_128bits_withSecret() */
static void generate_sanity_test_vectors_xxh128_withSecret(FILE* fp, size_t maxLen) {
const char* const arrayTypeName = "XSUM_testdata128_t";
const char* const arrayName = "XSUM_XXH128_withSecret_testdata";
fprintf(fp, "static const %s %s[] = {\n", arrayTypeName, arrayName);
XSUM_U8* const sanityBuffer = createSanityBuffer(maxLen);
const void* const secret = sanityBuffer + 7;
size_t const secretSize = XXH3_SECRET_SIZE_MIN + 11;
assert(maxLen >= 7 + secretSize);
size_t index = 0;
for(size_t len = 0; len < maxLen; ++len) {
XSUM_testdata128_t const v = tvgen_XXH3_128bits_withSecret(sanityBuffer, len, secret, secretSize);
fprintf(fp, " ");
fprintf_XSUM_testdata128_t(fp, v);
fprintf(fp, " /* %s[%zd] */\n", arrayName, index++);
}
fprintf(fp, "};\n");
releaseSanityBuffer(sanityBuffer);
}
/* Generate test vectors for XXH3_generateSecret() */
static void generate_sanity_test_vectors_xxh3_generateSecret(FILE* fp, size_t maxLen) {
const char* const arrayTypeName = "XSUM_testdata_sample_t";
const char* const arrayName = "XSUM_XXH3_generateSecret_testdata";
fprintf(fp, "static const %s %s[] = {\n", arrayTypeName, arrayName);
XSUM_U8* const sanityBuffer = createSanityBuffer(maxLen);
const void* const customSeed = sanityBuffer;
static const size_t seedLens[] = {
0,
1,
XXH3_SECRET_SIZE_MIN - 1,
XXH3_SECRET_DEFAULT_SIZE + 500
};
static const size_t secretLens[] = {
192,
240,
277,
SECRET_SIZE_MAX
};
size_t index = 0;
for(size_t iSeedLen = 0; iSeedLen < sizeof(seedLens)/sizeof(seedLens[0]); ++iSeedLen) {
for(size_t iSecretLen = 0; iSecretLen < sizeof(secretLens)/sizeof(secretLens[0]); ++iSecretLen) {
size_t const seedLen = seedLens[iSeedLen];
size_t const secretLen = secretLens[iSecretLen];
XSUM_U8 secretBuffer[SECRET_SIZE_MAX] = {0};
assert(seedLen <= maxLen);
assert(secretLen <= SECRET_SIZE_MAX);
XSUM_testdata_sample_t const v = tvgen_XXH3_generateSecret(
secretBuffer,
secretLen,
customSeed,
seedLen
);
fprintf(fp, " ");
fprintf_XSUM_testdata_sample_t(fp, v);
fprintf(fp, " /* %s[%zd] */\n", arrayName, index++);
}
}
fprintf(fp, "};\n");
releaseSanityBuffer(sanityBuffer);
}
/* Generate test vectors */
void generate_sanity_test_vectors(size_t maxLen) {
const char* filename = "sanity_test_vectors.h";
fprintf(stderr, "Generating %s\n", filename);
FILE* fp = fopen(filename, "w");
fprintf(fp,
"typedef struct {\n"
" XSUM_U32 len;\n"
" XSUM_U32 seed;\n"
" XSUM_U32 Nresult;\n"
"} XSUM_testdata32_t;\n"
"\n"
"typedef struct {\n"
" XSUM_U32 len;\n"
" XSUM_U64 seed;\n"
" XSUM_U64 Nresult;\n"
"} XSUM_testdata64_t;\n"
"\n"
"typedef struct {\n"
" XSUM_U32 len;\n"
" XSUM_U64 seed;\n"
" XXH128_hash_t Nresult;\n"
"} XSUM_testdata128_t;\n"
"\n"
"#ifndef SECRET_SAMPLE_NBBYTES\n"
"#define SECRET_SAMPLE_NBBYTES 5\n"
"#endif\n"
"\n"
"typedef struct {\n"
" XSUM_U32 seedLen;\n"
" XSUM_U32 secretLen;\n"
" XSUM_U8 byte[SECRET_SAMPLE_NBBYTES];\n"
"} XSUM_testdata_sample_t;\n"
"\n"
"#ifndef SECRET_SIZE_MAX\n"
"#define SECRET_SIZE_MAX 9867\n"
"#endif\n"
"\n"
);
generate_sanity_test_vectors_xxh32(fp, maxLen);
generate_sanity_test_vectors_xxh64(fp, maxLen);
generate_sanity_test_vectors_xxh3(fp, maxLen);
generate_sanity_test_vectors_xxh3_withSecret(fp, maxLen);
generate_sanity_test_vectors_xxh128(fp, maxLen);
generate_sanity_test_vectors_xxh128_withSecret(fp, maxLen);
generate_sanity_test_vectors_xxh3_generateSecret(fp, maxLen);
fclose(fp);
}
/**/
int main(int argc, const char* argv[])
{
(void) argc;
(void) argv;
const size_t sanityBufferSizeInBytes = SANITY_BUFFER_SIZE;
generate_sanity_test_vectors(sanityBufferSizeInBytes);
return EXIT_SUCCESS;
}
#!/bin/bash
# `unicode_lint.sh' determines whether source files under ${dirs} directories
# contain Unicode characters, and fails if any do.
#
# We don't recommend to call this script directly.
# Instead of it, use `make lint-unicode` via root directory Makefile.
# ${dirs} : target directories
dirs=(./ ./cli ./tests ./tests/bench ./tests/collisions)
SCRIPT_DIR="`dirname "${BASH_SOURCE[0]}"`"
cd ${SCRIPT_DIR}/..
echo "Ensure no unicode character is present in source files *.{c,h}"
pass=true
# Scan each directory in ${dirs} for Unicode in source (*.c, *.h) files
i=0
while [ $i -lt ${#dirs[@]} ]
do
dir=${dirs[$i]}
echo dir=$dir
result=$(
find ${dir} -regex '.*\.\(c\|h\)$' -exec grep -P -n "[^\x00-\x7F]" {} \; -exec echo "{}: FAIL" \;
)
if [[ $result ]]; then
echo "$result"
pass=false
fi
i=`expr $i + 1`
done
# Result
if [ "$pass" = true ]; then
echo "All tests successful: no unicode character detected"
echo "Result: PASS"
exit 0
else
echo "Result: FAIL"
exit 1
fi
/*
* xxHash - Extremely Fast Hash algorithm
* Development source file for `xxh3`
* Copyright (C) 2019-2021 Yann Collet
*
* BSD 2-Clause License (https://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:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
/*
* Note: This file used to host the source code of XXH3_* variants.
* during the development period.
* The source code is now properly integrated within xxhash.h.
*
* xxh3.h is no longer useful,
* but it is still provided for compatibility with source code
* which used to include it directly.
*
* Programs are now highly discouraged to include xxh3.h.
* Include `xxhash.h` instead, which is the officially supported interface.
*
* In the future, xxh3.h will start to generate warnings, then errors,
* then it will be removed from source package and from include directory.
*/
/* Simulate the same impact as including the old xxh3.h source file */
#define XXH_INLINE_ALL
#include "xxhash.h"
/*
* xxHash - Extremely Fast Hash algorithm
* Copyright (C) 2020-2021 Yann Collet
*
* BSD 2-Clause License (https://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:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
/*!
* @file xxh_x86dispatch.c
*
* Automatic dispatcher code for the @ref XXH3_family on x86-based targets.
*
* Optional add-on.
*
* **Compile this file with the default flags for your target.** Do not compile
* with flags like `-mavx*`, `-march=native`, or `/arch:AVX*`, there will be
* an error. See @ref XXH_X86DISPATCH_ALLOW_AVX for details.
*
* @defgroup dispatch x86 Dispatcher
* @{
*/
#if defined (__cplusplus)
extern "C" {
#endif
#if !(defined(__x86_64__) || defined(__i386__) || defined(_M_IX86) || defined(_M_X64))
# error "Dispatching is currently only supported on x86 and x86_64."
#endif
/*!
* @def XXH_X86DISPATCH_ALLOW_AVX
* @brief Disables the AVX sanity check.
*
* xxh_x86dispatch.c is intended to be compiled for the minimum target, and
* it selectively enables SSE2, AVX2, and AVX512 when it is needed.
*
* Compiling with options like `-mavx*`, `-march=native`, or `/arch:AVX*`
* _globally_ will always enable this feature, and therefore makes it
* undefined behavior to execute on any CPU without said feature.
*
* Even if the source code isn't directly using AVX intrinsics in a function,
* the compiler can still generate AVX code from autovectorization and by
* "upgrading" SSE2 intrinsics to use the VEX prefixes (a.k.a. AVX128).
*
* Define XXH_X86DISPATCH_ALLOW_AVX to ignore this check,
* thus accepting that the produced binary will not work correctly
* on any CPU with less features than the ones stated at compilation time.
*/
#ifdef XXH_DOXYGEN
# define XXH_X86DISPATCH_ALLOW_AVX
#endif
#if defined(__AVX__) && !defined(XXH_X86DISPATCH_ALLOW_AVX)
# error "Error: if xxh_x86dispatch.c is compiled with AVX enabled, the resulting binary will crash on sse2-only cpus !! " \
"If you nonetheless want to do that, please enable the XXH_X86DISPATCH_ALLOW_AVX build variable"
#endif
#ifdef __has_include
# define XXH_HAS_INCLUDE(header) __has_include(header)
#else
# define XXH_HAS_INCLUDE(header) 0
#endif
/*!
* @def XXH_DISPATCH_SCALAR
* @brief Enables/dispatching the scalar code path.
*
* If this is defined to 0, SSE2 support is assumed. This reduces code size
* when the scalar path is not needed.
*
* This is automatically defined to 0 when...
* - SSE2 support is enabled in the compiler
* - Targeting x86_64
* - Targeting Android x86
* - Targeting macOS
*/
#ifndef XXH_DISPATCH_SCALAR
# if defined(__SSE2__) || (defined(_M_IX86_FP) && _M_IX86_FP >= 2) /* SSE2 on by default */ \
|| defined(__x86_64__) || defined(_M_X64) /* x86_64 */ \
|| defined(__ANDROID__) || defined(__APPLEv__) /* Android or macOS */
# define XXH_DISPATCH_SCALAR 0 /* disable */
# else
# define XXH_DISPATCH_SCALAR 1
# endif
#endif
/*!
* @def XXH_DISPATCH_AVX2
* @brief Enables/disables dispatching for AVX2.
*
* This is automatically detected if it is not defined.
* - GCC 4.7 and later are known to support AVX2, but >4.9 is required for
* to get the AVX2 intrinsics and typedefs without -mavx -mavx2.
* - Visual Studio 2013 Update 2 and later are known to support AVX2.
* - The GCC/Clang internal header `<avx2intrin.h>` is detected. While this is
* not allowed to be included directly, it still appears in the builtin
* include path and is detectable with `__has_include`.
*
* @see XXH_AVX2
*/
#ifndef XXH_DISPATCH_AVX2
# if (defined(__GNUC__) && (__GNUC__ > 4)) /* GCC 5.0+ */ \
|| (defined(_MSC_VER) && _MSC_VER >= 1900) /* VS 2015+ */ \
|| (defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 180030501) /* VS 2013 Update 2 */ \
|| XXH_HAS_INCLUDE(<avx2intrin.h>) /* GCC/Clang internal header */
# define XXH_DISPATCH_AVX2 1 /* enable dispatch towards AVX2 */
# else
# define XXH_DISPATCH_AVX2 0
# endif
#endif /* XXH_DISPATCH_AVX2 */
/*!
* @def XXH_DISPATCH_AVX512
* @brief Enables/disables dispatching for AVX512.
*
* Automatically detected if one of the following conditions is met:
* - GCC 4.9 and later are known to support AVX512.
* - Visual Studio 2017 and later are known to support AVX2.
* - The GCC/Clang internal header `<avx512fintrin.h>` is detected. While this
* is not allowed to be included directly, it still appears in the builtin
* include path and is detectable with `__has_include`.
*
* @see XXH_AVX512
*/
#ifndef XXH_DISPATCH_AVX512
# if (defined(__GNUC__) \
&& (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9))) /* GCC 4.9+ */ \
|| (defined(_MSC_VER) && _MSC_VER >= 1910) /* VS 2017+ */ \
|| XXH_HAS_INCLUDE(<avx512fintrin.h>) /* GCC/Clang internal header */
# define XXH_DISPATCH_AVX512 1 /* enable dispatch towards AVX512 */
# else
# define XXH_DISPATCH_AVX512 0
# endif
#endif /* XXH_DISPATCH_AVX512 */
/*!
* @def XXH_TARGET_SSE2
* @brief Allows a function to be compiled with SSE2 intrinsics.
*
* Uses `__attribute__((__target__("sse2")))` on GCC to allow SSE2 to be used
* even with `-mno-sse2`.
*
* @def XXH_TARGET_AVX2
* @brief Like @ref XXH_TARGET_SSE2, but for AVX2.
*
* @def XXH_TARGET_AVX512
* @brief Like @ref XXH_TARGET_SSE2, but for AVX512.
*/
#if defined(__GNUC__)
# include <emmintrin.h> /* SSE2 */
# if XXH_DISPATCH_AVX2 || XXH_DISPATCH_AVX512
# include <immintrin.h> /* AVX2, AVX512F */
# endif
# define XXH_TARGET_SSE2 __attribute__((__target__("sse2")))
# define XXH_TARGET_AVX2 __attribute__((__target__("avx2")))
# define XXH_TARGET_AVX512 __attribute__((__target__("avx512f")))
#elif defined(_MSC_VER)
# include <intrin.h>
# define XXH_TARGET_SSE2
# define XXH_TARGET_AVX2
# define XXH_TARGET_AVX512
#else
# error "Dispatching is currently not supported for your compiler."
#endif
#ifdef XXH_DISPATCH_DEBUG
/* debug logging */
# include <stdio.h>
# define XXH_debugPrint(str) { fprintf(stderr, "DEBUG: xxHash dispatch: %s \n", str); fflush(NULL); }
#else
# define XXH_debugPrint(str) ((void)0)
# undef NDEBUG /* avoid redefinition */
# define NDEBUG
#endif
#include <assert.h>
#define XXH_INLINE_ALL
#define XXH_X86DISPATCH
#include "xxhash.h"
#ifndef XXH_HAS_ATTRIBUTE
# ifdef __has_attribute
# define XXH_HAS_ATTRIBUTE(...) __has_attribute(__VA_ARGS__)
# else
# define XXH_HAS_ATTRIBUTE(...) 0
# endif
#endif
#if XXH_HAS_ATTRIBUTE(constructor)
# define XXH_CONSTRUCTOR __attribute__((constructor))
# define XXH_DISPATCH_MAYBE_NULL 0
#else
# define XXH_CONSTRUCTOR
# define XXH_DISPATCH_MAYBE_NULL 1
#endif
/*
* Support both AT&T and Intel dialects
*
* GCC doesn't convert AT&T syntax to Intel syntax, and will error out if
* compiled with -masm=intel. Instead, it supports dialect switching with
* curly braces: { AT&T syntax | Intel syntax }
*
* Clang's integrated assembler automatically converts AT&T syntax to Intel if
* needed, making the dialect switching useless (it isn't even supported).
*
* Note: Comments are written in the inline assembly itself.
*/
#ifdef __clang__
# define XXH_I_ATT(intel, att) att "\n\t"
#else
# define XXH_I_ATT(intel, att) "{" att "|" intel "}\n\t"
#endif
/*!
* @internal
* @brief Runs CPUID.
*
* @param eax , ecx The parameters to pass to CPUID, %eax and %ecx respectively.
* @param abcd The array to store the result in, `{ eax, ebx, ecx, edx }`
*/
static void XXH_cpuid(xxh_u32 eax, xxh_u32 ecx, xxh_u32* abcd)
{
#if defined(_MSC_VER)
__cpuidex(abcd, eax, ecx);
#else
xxh_u32 ebx, edx;
# if defined(__i386__) && defined(__PIC__)
__asm__(
"# Call CPUID\n\t"
"#\n\t"
"# On 32-bit x86 with PIC enabled, we are not allowed to overwrite\n\t"
"# EBX, so we use EDI instead.\n\t"
XXH_I_ATT("mov edi, ebx", "movl %%ebx, %%edi")
XXH_I_ATT("cpuid", "cpuid" )
XXH_I_ATT("xchg edi, ebx", "xchgl %%ebx, %%edi")
: "=D" (ebx),
# else
__asm__(
"# Call CPUID\n\t"
XXH_I_ATT("cpuid", "cpuid")
: "=b" (ebx),
# endif
"+a" (eax), "+c" (ecx), "=d" (edx));
abcd[0] = eax;
abcd[1] = ebx;
abcd[2] = ecx;
abcd[3] = edx;
#endif
}
/*
* Modified version of Intel's guide
* https://software.intel.com/en-us/articles/how-to-detect-new-instruction-support-in-the-4th-generation-intel-core-processor-family
*/
#if XXH_DISPATCH_AVX2 || XXH_DISPATCH_AVX512
/*!
* @internal
* @brief Runs `XGETBV`.
*
* While the CPU may support AVX2, the operating system might not properly save
* the full YMM/ZMM registers.
*
* xgetbv is used for detecting this: Any compliant operating system will define
* a set of flags in the xcr0 register indicating how it saves the AVX registers.
*
* You can manually disable this flag on Windows by running, as admin:
*
* bcdedit.exe /set xsavedisable 1
*
* and rebooting. Run the same command with 0 to re-enable it.
*/
static xxh_u64 XXH_xgetbv(void)
{
#if defined(_MSC_VER)
return _xgetbv(0); /* min VS2010 SP1 compiler is required */
#else
xxh_u32 xcr0_lo, xcr0_hi;
__asm__(
"# Call XGETBV\n\t"
"#\n\t"
"# Older assemblers (e.g. macOS's ancient GAS version) don't support\n\t"
"# the XGETBV opcode, so we encode it by hand instead.\n\t"
"# See <https://github.com/asmjit/asmjit/issues/78> for details.\n\t"
".byte 0x0f, 0x01, 0xd0\n\t"
: "=a" (xcr0_lo), "=d" (xcr0_hi) : "c" (0));
return xcr0_lo | ((xxh_u64)xcr0_hi << 32);
#endif
}
#endif
#define XXH_SSE2_CPUID_MASK (1 << 26)
#define XXH_OSXSAVE_CPUID_MASK ((1 << 26) | (1 << 27))
#define XXH_AVX2_CPUID_MASK (1 << 5)
#define XXH_AVX2_XGETBV_MASK ((1 << 2) | (1 << 1))
#define XXH_AVX512F_CPUID_MASK (1 << 16)
#define XXH_AVX512F_XGETBV_MASK ((7 << 5) | (1 << 2) | (1 << 1))
/*!
* @internal
* @brief Returns the best XXH3 implementation.
*
* Runs various CPUID/XGETBV tests to try and determine the best implementation.
*
* @return The best @ref XXH_VECTOR implementation.
* @see XXH_VECTOR_TYPES
*/
static int XXH_featureTest(void)
{
xxh_u32 abcd[4];
xxh_u32 max_leaves;
int best = XXH_SCALAR;
#if XXH_DISPATCH_AVX2 || XXH_DISPATCH_AVX512
xxh_u64 xgetbv_val;
#endif
#if defined(__GNUC__) && defined(__i386__)
xxh_u32 cpuid_supported;
__asm__(
"# For the sake of ruthless backwards compatibility, check if CPUID\n\t"
"# is supported in the EFLAGS on i386.\n\t"
"# This is not necessary on x86_64 - CPUID is mandatory.\n\t"
"# The ID flag (bit 21) in the EFLAGS register indicates support\n\t"
"# for the CPUID instruction. If a software procedure can set and\n\t"
"# clear this flag, the processor executing the procedure supports\n\t"
"# the CPUID instruction.\n\t"
"# <https://c9x.me/x86/html/file_module_x86_id_45.html>\n\t"
"#\n\t"
"# Routine is from <https://wiki.osdev.org/CPUID>.\n\t"
"# Save EFLAGS\n\t"
XXH_I_ATT("pushfd", "pushfl" )
"# Store EFLAGS\n\t"
XXH_I_ATT("pushfd", "pushfl" )
"# Invert the ID bit in stored EFLAGS\n\t"
XXH_I_ATT("xor dword ptr[esp], 0x200000", "xorl $0x200000, (%%esp)")
"# Load stored EFLAGS (with ID bit inverted)\n\t"
XXH_I_ATT("popfd", "popfl" )
"# Store EFLAGS again (ID bit may or not be inverted)\n\t"
XXH_I_ATT("pushfd", "pushfl" )
"# eax = modified EFLAGS (ID bit may or may not be inverted)\n\t"
XXH_I_ATT("pop eax", "popl %%eax" )
"# eax = whichever bits were changed\n\t"
XXH_I_ATT("xor eax, dword ptr[esp]", "xorl (%%esp), %%eax" )
"# Restore original EFLAGS\n\t"
XXH_I_ATT("popfd", "popfl" )
"# eax = zero if ID bit can't be changed, else non-zero\n\t"
XXH_I_ATT("and eax, 0x200000", "andl $0x200000, %%eax" )
: "=a" (cpuid_supported) :: "cc");
if (XXH_unlikely(!cpuid_supported)) {
XXH_debugPrint("CPUID support is not detected!");
return best;
}
#endif
/* Check how many CPUID pages we have */
XXH_cpuid(0, 0, abcd);
max_leaves = abcd[0];
/* Shouldn't happen on hardware, but happens on some QEMU configs. */
if (XXH_unlikely(max_leaves == 0)) {
XXH_debugPrint("Max CPUID leaves == 0!");
return best;
}
/* Check for SSE2, OSXSAVE and xgetbv */
XXH_cpuid(1, 0, abcd);
/*
* Test for SSE2. The check is redundant on x86_64, but it doesn't hurt.
*/
if (XXH_unlikely((abcd[3] & XXH_SSE2_CPUID_MASK) != XXH_SSE2_CPUID_MASK))
return best;
XXH_debugPrint("SSE2 support detected.");
best = XXH_SSE2;
#if XXH_DISPATCH_AVX2 || XXH_DISPATCH_AVX512
/* Make sure we have enough leaves */
if (XXH_unlikely(max_leaves < 7))
return best;
/* Test for OSXSAVE and XGETBV */
if ((abcd[2] & XXH_OSXSAVE_CPUID_MASK) != XXH_OSXSAVE_CPUID_MASK)
return best;
/* CPUID check for AVX features */
XXH_cpuid(7, 0, abcd);
xgetbv_val = XXH_xgetbv();
#if XXH_DISPATCH_AVX2
/* Validate that AVX2 is supported by the CPU */
if ((abcd[1] & XXH_AVX2_CPUID_MASK) != XXH_AVX2_CPUID_MASK)
return best;
/* Validate that the OS supports YMM registers */
if ((xgetbv_val & XXH_AVX2_XGETBV_MASK) != XXH_AVX2_XGETBV_MASK) {
XXH_debugPrint("AVX2 supported by the CPU, but not the OS.");
return best;
}
/* AVX2 supported */
XXH_debugPrint("AVX2 support detected.");
best = XXH_AVX2;
#endif
#if XXH_DISPATCH_AVX512
/* Check if AVX512F is supported by the CPU */
if ((abcd[1] & XXH_AVX512F_CPUID_MASK) != XXH_AVX512F_CPUID_MASK) {
XXH_debugPrint("AVX512F not supported by CPU");
return best;
}
/* Validate that the OS supports ZMM registers */
if ((xgetbv_val & XXH_AVX512F_XGETBV_MASK) != XXH_AVX512F_XGETBV_MASK) {
XXH_debugPrint("AVX512F supported by the CPU, but not the OS.");
return best;
}
/* AVX512F supported */
XXH_debugPrint("AVX512F support detected.");
best = XXH_AVX512;
#endif
#endif
return best;
}
/* === Vector implementations === */
/*!
* @internal
* @brief Defines the various dispatch functions.
*
* TODO: Consolidate?
*
* @param suffix The suffix for the functions, e.g. sse2 or scalar
* @param target XXH_TARGET_* or empty.
*/
#define XXH_DEFINE_DISPATCH_FUNCS(suffix, target) \
\
/* === XXH3, default variants === */ \
\
XXH_NO_INLINE target XXH64_hash_t \
XXHL64_default_##suffix(XXH_NOESCAPE const void* XXH_RESTRICT input, \
size_t len) \
{ \
return XXH3_hashLong_64b_internal( \
input, len, XXH3_kSecret, sizeof(XXH3_kSecret), \
XXH3_accumulate_##suffix, XXH3_scrambleAcc_##suffix \
); \
} \
\
/* === XXH3, Seeded variants === */ \
\
XXH_NO_INLINE target XXH64_hash_t \
XXHL64_seed_##suffix(XXH_NOESCAPE const void* XXH_RESTRICT input, size_t len, \
XXH64_hash_t seed) \
{ \
return XXH3_hashLong_64b_withSeed_internal( \
input, len, seed, XXH3_accumulate_##suffix, \
XXH3_scrambleAcc_##suffix, XXH3_initCustomSecret_##suffix \
); \
} \
\
/* === XXH3, Secret variants === */ \
\
XXH_NO_INLINE target XXH64_hash_t \
XXHL64_secret_##suffix(XXH_NOESCAPE const void* XXH_RESTRICT input, \
size_t len, XXH_NOESCAPE const void* secret, \
size_t secretLen) \
{ \
return XXH3_hashLong_64b_internal( \
input, len, secret, secretLen, \
XXH3_accumulate_##suffix, XXH3_scrambleAcc_##suffix \
); \
} \
\
/* === XXH3 update variants === */ \
\
XXH_NO_INLINE target XXH_errorcode \
XXH3_update_##suffix(XXH_NOESCAPE XXH3_state_t* state, \
XXH_NOESCAPE const void* input, size_t len) \
{ \
return XXH3_update(state, (const xxh_u8*)input, len, \
XXH3_accumulate_##suffix, XXH3_scrambleAcc_##suffix); \
} \
\
/* === XXH128 default variants === */ \
\
XXH_NO_INLINE target XXH128_hash_t \
XXHL128_default_##suffix(XXH_NOESCAPE const void* XXH_RESTRICT input, \
size_t len) \
{ \
return XXH3_hashLong_128b_internal( \
input, len, XXH3_kSecret, sizeof(XXH3_kSecret), \
XXH3_accumulate_##suffix, XXH3_scrambleAcc_##suffix \
); \
} \
\
/* === XXH128 Secret variants === */ \
\
XXH_NO_INLINE target XXH128_hash_t \
XXHL128_secret_##suffix(XXH_NOESCAPE const void* XXH_RESTRICT input, \
size_t len, \
XXH_NOESCAPE const void* XXH_RESTRICT secret, \
size_t secretLen) \
{ \
return XXH3_hashLong_128b_internal( \
input, len, (const xxh_u8*)secret, secretLen, \
XXH3_accumulate_##suffix, XXH3_scrambleAcc_##suffix); \
} \
\
/* === XXH128 Seeded variants === */ \
\
XXH_NO_INLINE target XXH128_hash_t \
XXHL128_seed_##suffix(XXH_NOESCAPE const void* XXH_RESTRICT input, size_t len,\
XXH64_hash_t seed) \
{ \
return XXH3_hashLong_128b_withSeed_internal(input, len, seed, \
XXH3_accumulate_##suffix, XXH3_scrambleAcc_##suffix, \
XXH3_initCustomSecret_##suffix); \
}
/* End XXH_DEFINE_DISPATCH_FUNCS */
#if XXH_DISPATCH_SCALAR
XXH_DEFINE_DISPATCH_FUNCS(scalar, /* nothing */)
#endif
XXH_DEFINE_DISPATCH_FUNCS(sse2, XXH_TARGET_SSE2)
#if XXH_DISPATCH_AVX2
XXH_DEFINE_DISPATCH_FUNCS(avx2, XXH_TARGET_AVX2)
#endif
#if XXH_DISPATCH_AVX512
XXH_DEFINE_DISPATCH_FUNCS(avx512, XXH_TARGET_AVX512)
#endif
#undef XXH_DEFINE_DISPATCH_FUNCS
/* ==== Dispatchers ==== */
typedef XXH64_hash_t (*XXH3_dispatchx86_hashLong64_default)(XXH_NOESCAPE const void* XXH_RESTRICT, size_t);
typedef XXH64_hash_t (*XXH3_dispatchx86_hashLong64_withSeed)(XXH_NOESCAPE const void* XXH_RESTRICT, size_t, XXH64_hash_t);
typedef XXH64_hash_t (*XXH3_dispatchx86_hashLong64_withSecret)(XXH_NOESCAPE const void* XXH_RESTRICT, size_t, XXH_NOESCAPE const void* XXH_RESTRICT, size_t);
typedef XXH_errorcode (*XXH3_dispatchx86_update)(XXH_NOESCAPE XXH3_state_t*, XXH_NOESCAPE const void*, size_t);
typedef struct {
XXH3_dispatchx86_hashLong64_default hashLong64_default;
XXH3_dispatchx86_hashLong64_withSeed hashLong64_seed;
XXH3_dispatchx86_hashLong64_withSecret hashLong64_secret;
XXH3_dispatchx86_update update;
} XXH_dispatchFunctions_s;
#define XXH_NB_DISPATCHES 4
/*!
* @internal
* @brief Table of dispatchers for @ref XXH3_64bits().
*
* @pre The indices must match @ref XXH_VECTOR_TYPE.
*/
static const XXH_dispatchFunctions_s XXH_kDispatch[XXH_NB_DISPATCHES] = {
#if XXH_DISPATCH_SCALAR
/* Scalar */ { XXHL64_default_scalar, XXHL64_seed_scalar, XXHL64_secret_scalar, XXH3_update_scalar },
#else
/* Scalar */ { NULL, NULL, NULL, NULL },
#endif
/* SSE2 */ { XXHL64_default_sse2, XXHL64_seed_sse2, XXHL64_secret_sse2, XXH3_update_sse2 },
#if XXH_DISPATCH_AVX2
/* AVX2 */ { XXHL64_default_avx2, XXHL64_seed_avx2, XXHL64_secret_avx2, XXH3_update_avx2 },
#else
/* AVX2 */ { NULL, NULL, NULL, NULL },
#endif
#if XXH_DISPATCH_AVX512
/* AVX512 */ { XXHL64_default_avx512, XXHL64_seed_avx512, XXHL64_secret_avx512, XXH3_update_avx512 }
#else
/* AVX512 */ { NULL, NULL, NULL, NULL }
#endif
};
/*!
* @internal
* @brief The selected dispatch table for @ref XXH3_64bits().
*/
static XXH_dispatchFunctions_s XXH_g_dispatch = { NULL, NULL, NULL, NULL };
typedef XXH128_hash_t (*XXH3_dispatchx86_hashLong128_default)(XXH_NOESCAPE const void* XXH_RESTRICT, size_t);
typedef XXH128_hash_t (*XXH3_dispatchx86_hashLong128_withSeed)(XXH_NOESCAPE const void* XXH_RESTRICT, size_t, XXH64_hash_t);
typedef XXH128_hash_t (*XXH3_dispatchx86_hashLong128_withSecret)(XXH_NOESCAPE const void* XXH_RESTRICT, size_t, const void* XXH_RESTRICT, size_t);
typedef struct {
XXH3_dispatchx86_hashLong128_default hashLong128_default;
XXH3_dispatchx86_hashLong128_withSeed hashLong128_seed;
XXH3_dispatchx86_hashLong128_withSecret hashLong128_secret;
XXH3_dispatchx86_update update;
} XXH_dispatch128Functions_s;
/*!
* @internal
* @brief Table of dispatchers for @ref XXH3_128bits().
*
* @pre The indices must match @ref XXH_VECTOR_TYPE.
*/
static const XXH_dispatch128Functions_s XXH_kDispatch128[XXH_NB_DISPATCHES] = {
#if XXH_DISPATCH_SCALAR
/* Scalar */ { XXHL128_default_scalar, XXHL128_seed_scalar, XXHL128_secret_scalar, XXH3_update_scalar },
#else
/* Scalar */ { NULL, NULL, NULL, NULL },
#endif
/* SSE2 */ { XXHL128_default_sse2, XXHL128_seed_sse2, XXHL128_secret_sse2, XXH3_update_sse2 },
#if XXH_DISPATCH_AVX2
/* AVX2 */ { XXHL128_default_avx2, XXHL128_seed_avx2, XXHL128_secret_avx2, XXH3_update_avx2 },
#else
/* AVX2 */ { NULL, NULL, NULL, NULL },
#endif
#if XXH_DISPATCH_AVX512
/* AVX512 */ { XXHL128_default_avx512, XXHL128_seed_avx512, XXHL128_secret_avx512, XXH3_update_avx512 }
#else
/* AVX512 */ { NULL, NULL, NULL, NULL }
#endif
};
/*!
* @internal
* @brief The selected dispatch table for @ref XXH3_64bits().
*/
static XXH_dispatch128Functions_s XXH_g_dispatch128 = { NULL, NULL, NULL, NULL };
/*!
* @internal
* @brief Runs a CPUID check and sets the correct dispatch tables.
*/
static XXH_CONSTRUCTOR void XXH_setDispatch(void)
{
int vecID = XXH_featureTest();
XXH_STATIC_ASSERT(XXH_AVX512 == XXH_NB_DISPATCHES-1);
assert(XXH_SCALAR <= vecID && vecID <= XXH_AVX512);
#if !XXH_DISPATCH_SCALAR
assert(vecID != XXH_SCALAR);
#endif
#if !XXH_DISPATCH_AVX512
assert(vecID != XXH_AVX512);
#endif
#if !XXH_DISPATCH_AVX2
assert(vecID != XXH_AVX2);
#endif
XXH_g_dispatch = XXH_kDispatch[vecID];
XXH_g_dispatch128 = XXH_kDispatch128[vecID];
}
/* ==== XXH3 public functions ==== */
static XXH64_hash_t
XXH3_hashLong_64b_defaultSecret_selection(const void* input, size_t len,
XXH64_hash_t seed64, const xxh_u8* secret, size_t secretLen)
{
(void)seed64; (void)secret; (void)secretLen;
if (XXH_DISPATCH_MAYBE_NULL && XXH_g_dispatch.hashLong64_default == NULL)
XXH_setDispatch();
return XXH_g_dispatch.hashLong64_default(input, len);
}
XXH64_hash_t XXH3_64bits_dispatch(XXH_NOESCAPE const void* input, size_t len)
{
return XXH3_64bits_internal(input, len, 0, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_64b_defaultSecret_selection);
}
static XXH64_hash_t
XXH3_hashLong_64b_withSeed_selection(const void* input, size_t len,
XXH64_hash_t seed64, const xxh_u8* secret, size_t secretLen)
{
(void)secret; (void)secretLen;
if (XXH_DISPATCH_MAYBE_NULL && XXH_g_dispatch.hashLong64_seed == NULL)
XXH_setDispatch();
return XXH_g_dispatch.hashLong64_seed(input, len, seed64);
}
XXH64_hash_t XXH3_64bits_withSeed_dispatch(XXH_NOESCAPE const void* input, size_t len, XXH64_hash_t seed)
{
return XXH3_64bits_internal(input, len, seed, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_64b_withSeed_selection);
}
static XXH64_hash_t
XXH3_hashLong_64b_withSecret_selection(const void* input, size_t len,
XXH64_hash_t seed64, const xxh_u8* secret, size_t secretLen)
{
(void)seed64;
if (XXH_DISPATCH_MAYBE_NULL && XXH_g_dispatch.hashLong64_secret == NULL)
XXH_setDispatch();
return XXH_g_dispatch.hashLong64_secret(input, len, secret, secretLen);
}
XXH64_hash_t XXH3_64bits_withSecret_dispatch(XXH_NOESCAPE const void* input, size_t len, XXH_NOESCAPE const void* secret, size_t secretLen)
{
return XXH3_64bits_internal(input, len, 0, secret, secretLen, XXH3_hashLong_64b_withSecret_selection);
}
XXH_errorcode
XXH3_64bits_update_dispatch(XXH_NOESCAPE XXH3_state_t* state, XXH_NOESCAPE const void* input, size_t len)
{
if (XXH_DISPATCH_MAYBE_NULL && XXH_g_dispatch.update == NULL)
XXH_setDispatch();
return XXH_g_dispatch.update(state, (const xxh_u8*)input, len);
}
/* ==== XXH128 public functions ==== */
static XXH128_hash_t
XXH3_hashLong_128b_defaultSecret_selection(const void* input, size_t len,
XXH64_hash_t seed64, const void* secret, size_t secretLen)
{
(void)seed64; (void)secret; (void)secretLen;
if (XXH_DISPATCH_MAYBE_NULL && XXH_g_dispatch128.hashLong128_default == NULL)
XXH_setDispatch();
return XXH_g_dispatch128.hashLong128_default(input, len);
}
XXH128_hash_t XXH3_128bits_dispatch(XXH_NOESCAPE const void* input, size_t len)
{
return XXH3_128bits_internal(input, len, 0, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_128b_defaultSecret_selection);
}
static XXH128_hash_t
XXH3_hashLong_128b_withSeed_selection(const void* input, size_t len,
XXH64_hash_t seed64, const void* secret, size_t secretLen)
{
(void)secret; (void)secretLen;
if (XXH_DISPATCH_MAYBE_NULL && XXH_g_dispatch128.hashLong128_seed == NULL)
XXH_setDispatch();
return XXH_g_dispatch128.hashLong128_seed(input, len, seed64);
}
XXH128_hash_t XXH3_128bits_withSeed_dispatch(XXH_NOESCAPE const void* input, size_t len, XXH64_hash_t seed)
{
return XXH3_128bits_internal(input, len, seed, XXH3_kSecret, sizeof(XXH3_kSecret), XXH3_hashLong_128b_withSeed_selection);
}
static XXH128_hash_t
XXH3_hashLong_128b_withSecret_selection(const void* input, size_t len,
XXH64_hash_t seed64, const void* secret, size_t secretLen)
{
(void)seed64;
if (XXH_DISPATCH_MAYBE_NULL && XXH_g_dispatch128.hashLong128_secret == NULL)
XXH_setDispatch();
return XXH_g_dispatch128.hashLong128_secret(input, len, secret, secretLen);
}
XXH128_hash_t XXH3_128bits_withSecret_dispatch(XXH_NOESCAPE const void* input, size_t len, XXH_NOESCAPE const void* secret, size_t secretLen)
{
return XXH3_128bits_internal(input, len, 0, secret, secretLen, XXH3_hashLong_128b_withSecret_selection);
}
XXH_errorcode
XXH3_128bits_update_dispatch(XXH_NOESCAPE XXH3_state_t* state, XXH_NOESCAPE const void* input, size_t len)
{
if (XXH_DISPATCH_MAYBE_NULL && XXH_g_dispatch128.update == NULL)
XXH_setDispatch();
return XXH_g_dispatch128.update(state, (const xxh_u8*)input, len);
}
#if defined (__cplusplus)
}
#endif
/*! @} */
/*
* xxHash - XXH3 Dispatcher for x86-based targets
* Copyright (C) 2020-2021 Yann Collet
*
* BSD 2-Clause License (https://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:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
#ifndef XXH_X86DISPATCH_H_13563687684
#define XXH_X86DISPATCH_H_13563687684
#include "xxhash.h" /* XXH64_hash_t, XXH3_state_t */
#if defined (__cplusplus)
extern "C" {
#endif
XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_dispatch(XXH_NOESCAPE const void* input, size_t len);
XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_withSeed_dispatch(XXH_NOESCAPE const void* input, size_t len, XXH64_hash_t seed);
XXH_PUBLIC_API XXH64_hash_t XXH3_64bits_withSecret_dispatch(XXH_NOESCAPE const void* input, size_t len, XXH_NOESCAPE const void* secret, size_t secretLen);
XXH_PUBLIC_API XXH_errorcode XXH3_64bits_update_dispatch(XXH_NOESCAPE XXH3_state_t* state, XXH_NOESCAPE const void* input, size_t len);
XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_dispatch(XXH_NOESCAPE const void* input, size_t len);
XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_withSeed_dispatch(XXH_NOESCAPE const void* input, size_t len, XXH64_hash_t seed);
XXH_PUBLIC_API XXH128_hash_t XXH3_128bits_withSecret_dispatch(XXH_NOESCAPE const void* input, size_t len, XXH_NOESCAPE const void* secret, size_t secretLen);
XXH_PUBLIC_API XXH_errorcode XXH3_128bits_update_dispatch(XXH_NOESCAPE XXH3_state_t* state, XXH_NOESCAPE const void* input, size_t len);
#if defined (__cplusplus)
}
#endif
/* automatic replacement of XXH3 functions.
* can be disabled by setting XXH_DISPATCH_DISABLE_REPLACE */
#ifndef XXH_DISPATCH_DISABLE_REPLACE
# undef XXH3_64bits
# define XXH3_64bits XXH3_64bits_dispatch
# undef XXH3_64bits_withSeed
# define XXH3_64bits_withSeed XXH3_64bits_withSeed_dispatch
# undef XXH3_64bits_withSecret
# define XXH3_64bits_withSecret XXH3_64bits_withSecret_dispatch
# undef XXH3_64bits_update
# define XXH3_64bits_update XXH3_64bits_update_dispatch
# undef XXH128
# define XXH128 XXH3_128bits_withSeed_dispatch
# undef XXH3_128bits
# define XXH3_128bits XXH3_128bits_dispatch
# undef XXH3_128bits_withSeed
# define XXH3_128bits_withSeed XXH3_128bits_withSeed_dispatch
# undef XXH3_128bits_withSecret
# define XXH3_128bits_withSecret XXH3_128bits_withSecret_dispatch
# undef XXH3_128bits_update
# define XXH3_128bits_update XXH3_128bits_update_dispatch
#endif /* XXH_DISPATCH_DISABLE_REPLACE */
#endif /* XXH_X86DISPATCH_H_13563687684 */
/*
* xxHash - Extremely Fast Hash algorithm
* Copyright (C) 2012-2021 Yann Collet
*
* BSD 2-Clause License (https://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:
* - xxHash homepage: https://www.xxhash.com
* - xxHash source repository: https://github.com/Cyan4973/xxHash
*/
/*
* xxhash.c instantiates functions defined in xxhash.h
*/
#define XXH_STATIC_LINKING_ONLY /* access advanced declarations */
#define XXH_IMPLEMENTATION /* access definitions */
#include "xxhash.h"
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment