commit inicial

parents
{
"url_datos_dge": "https://datosabiertos.salud.gob.mx/gobmx/salud/datos_abiertos/datos_abiertos_covid19.zip",
"instalacion": "/tmp/kafka_covid19",
"kafka":
{
"bootstrap_server": "http://baset.c3.unam.mx:9092",
"kafka_connect": "http://baset.c3.unam.mx:8083",
"rest_proxy": "http://baset.c3.unam.mx:8082",
"conector": "covid19",
"topic": "covid19",
"retencion": -1
},
"cronjob":
{
"nombre": "Kafka COVID-19",
"hora": "1:00"
},
"dia_especial":
{
"autodetectar": true,
"eliminados": 1000000
}
}
\ No newline at end of file
import sys
import json
import tempfile
from typing import Dict
from pathlib import Path
# Codigos de salida
SALIR_EXITO = 0
SALIR_ERROR = 1
# Carpetas globales
CARPETA_TEMPORAL = Path(tempfile.gettempdir())
CARPETA_ACTUAL = Path(__file__).parent.resolve()
# Archivo de ajustes
ARCHIVO_AJUSTES = CARPETA_ACTUAL / 'Ajustes.json'
# Se carga el archivo de ajustes en la variable AJUSTES
with open(ARCHIVO_AJUSTES, 'r') as archivo_json:
AJUSTES: Dict[str, object] = json.load(archivo_json)
def error(mensaje: str, salir = True):
''' Muestra un mensaje de error y opcionalmente termina el programa '''
print(f'ERROR: {mensaje}')
# Se termina el programa si se solicita
if salir:
sys.exit(SALIR_ERROR)
def ajuste(ruta_ajuste: str) -> object:
''' Regresa el valor de un ajuste '''
try:
ajuste = AJUSTES
ruta = ruta_ajuste.split('.')
for campo in ruta:
ajuste = ajuste[campo]
return ajuste
except:
error(f'El ajuste \'{ruta_ajuste}\' no existe')
def ruta_kafka(servicio: str):
''' Regresa el url del servicio de Kafka solicitado '''
return ajuste(f'kafka.{servicio}')
# Carpetas generales
CARPETA_CSVDIFF = CARPETA_ACTUAL / 'CSVDiff'
CARPETA_INSTALACION = Path(ajuste('instalacion')).expanduser()
# Archivos locales
ARCHIVO_SCRIPT = CARPETA_ACTUAL / 'Script.py'
ARCHIVO_AJUSTES_PY = CARPETA_ACTUAL / 'Ajustes.py'
ARCHIVO_FILEPULSE = CARPETA_ACTUAL / 'FilePulse.json'
ARCHIVO_COVID_BASE = CARPETA_ACTUAL / 'datos_abiertos_20000101.zip'
# Archivos instalación
INSTALACION_BUILD = CARPETA_INSTALACION / 'build'
INSTALACION_CSVDIFF = INSTALACION_BUILD / 'CSVDiff'
INSTALACION_SCRIPT = CARPETA_INSTALACION / 'Script.py'
INSTALACION_DATOS_COVID = CARPETA_INSTALACION / 'datos_covid'
INSTALACION_DIFERENCIAS = CARPETA_INSTALACION / 'diferencias'
\ No newline at end of file
# Minimum CMake Version
cmake_minimum_required (VERSION 3.0.0)
# Project Name
project (CSVDiff)
# Directories
set (CURRENT_DIR ${CMAKE_CURRENT_SOURCE_DIR})
set (EXTERN_DIR ${CURRENT_DIR}/Extern)
# Macro | Import Library
macro (import_library LIBRARY_NAME)
add_subdirectory (${EXTERN_DIR}/${LIBRARY_NAME})
endmacro ()
# Macro | Add Header Library
macro (add_header_library LIBRARY)
add_library (${LIBRARY} INTERFACE ${EXTERN_DIR}/${LIBRARY}.h)
target_include_directories (${LIBRARY} INTERFACE ${EXTERN_DIR})
endmacro ()
# Languaje Standard
set (CMAKE_C_STANDARD 11)
set (CMAKE_C_EXTENSIONS ON)
# Compile Options
add_compile_options (-O3 -Wall -Wextra -pedantic -march=native -mtune=native)
add_compile_options (-Wno-newline-eof -Wno-gnu-zero-variadic-macro-arguments)
# Threads
find_package (Threads REQUIRED)
# pico_string
add_header_library (pico_string)
# pico_csv
add_header_library (pico_csv)
# argparse
import_library (argparse)
# xxHash
set (XXHASH_BUNDLED_MODE ON)
set (XXHASH_BUILD_XXHSUM OFF)
import_library (xxHash/cmake_unofficial)
# Executable
add_executable (${PROJECT_NAME} ${PROJECT_NAME}.c)
# Local Libraries
target_link_libraries (${PROJECT_NAME} PRIVATE -static)
target_link_libraries (${PROJECT_NAME} PRIVATE -latomic)
target_link_libraries (${PROJECT_NAME} PRIVATE Threads::Threads)
# Extern Libraries
target_link_libraries (${PROJECT_NAME} PRIVATE pico_csv)
target_link_libraries (${PROJECT_NAME} PRIVATE argparse)
target_link_libraries (${PROJECT_NAME} PRIVATE xxHash::xxhash)
\ No newline at end of file
name: ci
on:
push:
branches:
- master
pull_request:
branches:
- master
jobs:
pull:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
compiler:
- gcc
- clang
steps:
- name: Checkout the code
uses: actions/checkout@v2
- name: Run with the compiler ${{ matrix.compiler }}
run: |
sudo apt-get install -y $compiler
CC=$compiler make test
env:
compiler: ${{ matrix.compiler }}
build/
tags
test_argparse
*.[ao]
*.dylib
*.so
.vscode
\ No newline at end of file
cmake_minimum_required(VERSION 3.0)
project(argparse VERSION 0.1.0 LANGUAGES C)
if(NOT CMAKE_C_FLAGS)
set(CMAKE_C_FLAGS "-O3")
endif()
if(NOT CMAKE_C_FLAGS_DEBUG)
set(CMAKE_C_FLAGS_DEBUG "-g -ggdb")
endif()
set(sources argparse.c)
option(ARGPARSE_SHARED "Build shared library" ON)
option(ARGPARSE_STATIC "Build static library" ON)
if(ARGPARSE_SHARED)
add_library(argparse_shared SHARED ${sources})
target_include_directories(argparse_shared PUBLIC .)
set_target_properties(argparse_shared PROPERTIES OUTPUT_NAME argparse)
endif()
if(ARGPARSE_STATIC)
add_library(argparse STATIC ${sources})
target_include_directories(argparse PUBLIC .)
endif()
if(NOT (ARGPARSE_STATIC OR ARGPARSE_SHARED))
add_library(argparse OBJECT ${sources})
endif()
option(ENABLE_TESTS "Enable tests" OFF)
if((ENABLE_TESTS OR CMAKE_TESTING_ENABLED) AND UNIX)
enable_testing()
add_executable(test_argparse test_argparse.c ${sources})
add_test(NAME argparse_test COMMAND ${CMAKE_SOURCE_DIR}/test.sh)
add_custom_command(
TARGET test_argparse
COMMENT "Running tests"
POST_BUILD WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
COMMAND ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> --output-on-failures)
endif()
# FAQs
## Why removing parsed command-line switches/options?
It destroys the original `argv` array, not compatible with other arguments parsing
library.
This is because this library is used for short-lived programs, e.g. cli tools
at beginning. It's very convenient to process remain arguments if we remove
parsed command-line arguments, e.g. `<comamnd> [-[s]|--switch]... arguments`.
If you want keep original `argc/argv`, you can make a copy, then pass them to
`argparse_parse`, e.g.
```c
int copy_argc = argc;
const char **copy_argv = argv;
copy_argv = malloc(copy_argc * sizeof(char *));
for (int i = 0; i < argc; i++) {
copy_argv[i] = (char *)argv[i];
}
argparse_parse(&argparse, copy_argc, copy_argv);
```
Issues:
- https://github.com/cofyc/argparse/issues/3
- https://github.com/cofyc/argparse/issues/9
## Why using `intptr_t` to hold associated data? Why not `void *`?
I choose `intptr_t` because it's a integer type which also can be used to hold
a pointer value. Most of the time, we only need a integer to hold
user-provided value, see `OPT_BIT` as example. If you want to provide a pointer
which points to a large amount of data, you can cast it to `intptr_t` and cast
it back to original pointer in callback function.
The MIT License (MIT)
Copyright (c) 2012-2013 Yecheng Fu <cofyc.jackson@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# Defaults
CFLAGS ?= -O3 -g -ggdb
LDFLAGS ?=
CROSS_COMPILE =
BASIC_CFLAGS = -Wall -Wextra -fPIC
BASIC_LDFLAGS =
# We use ALL_* variants
ALL_CFLAGS = $(BASIC_CFLAGS) $(CFLAGS)
ALL_LDFLAGS = $(BASIC_LDFLAGS) $(LDFLAGS)
LIBNAME=libargparse
DYLIBSUFFIX=so
STLIBSUFFIX=a
DYLIBNAME=$(LIBNAME).$(DYLIBSUFFIX)
DYLIB_MAKE_CMD=$(CROSS_COMPILE)gcc -shared -o $(DYLIBNAME) $(ALL_LDFLAGS)
STLIBNAME=$(LIBNAME).$(STLIBSUFFIX)
STLIB_MAKE_CMD=$(CROSS_COMPILE)ar rcs $(STLIBNAME)
# Platform-specific overrides
uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not')
ifeq ($(uname_S),Darwin)
DYLIBSUFFIX=dylib
DYLIB_MAKE_CMD=$(CROSS_COMPILE)gcc -shared -o $(DYLIBNAME) $(ALL_LDFLAGS)
endif
all: $(DYLIBNAME) $(STLIBNAME)
OBJS += argparse.o
OBJS += test_argparse.o
$(OBJS): %.o: %.c argparse.h
$(CROSS_COMPILE)gcc -o $*.o -c $(ALL_CFLAGS) $<
$(DYLIBNAME): argparse.o
$(DYLIB_MAKE_CMD) $^
$(STLIBNAME): argparse.o
$(STLIB_MAKE_CMD) $^
test: test_argparse
@echo "###### Unit Test #####"
@./test.sh
test_argparse: $(OBJS)
$(CROSS_COMPILE)gcc $(ALL_CFLAGS) -o $@ $^ $(ALL_LDFLAGS)
clean:
rm -rf test_argparse
rm -rf *.[ao]
rm -rf *.so
rm -rf *.dylib
# argparse [![Build Status](https://travis-ci.org/cofyc/argparse.png)](https://travis-ci.org/cofyc/argparse)
argparse - A command line arguments parsing library in C (compatible with C++).
## Description
This module is inspired by parse-options.c (git) and python's argparse
module.
Arguments parsing is common task in cli program, but traditional `getopt`
libraries are not easy to use. This library provides high-level arguments
parsing solutions.
The program defines what arguments it requires, and `argparse` will figure
out how to parse those out of `argc` and `argv`, it also automatically
generates help and usage messages and issues errors when users give the
program invalid arguments.
## Features
- handles both optional and positional arguments
- produces highly informative usage messages
- issues errors when given invalid arguments
There are basically three types of options:
- boolean options
- options with mandatory argument
- options with optional argument
There are basically two forms of options:
- short option consist of one dash (`-`) and one alphanumeric character.
- long option begin with two dashes (`--`) and some alphanumeric characters.
Short options may be bundled, e.g. `-a -b` can be specified as `-ab`.
Options are case-sensitive.
Options and non-option arguments can clearly be separated using the `--` option.
## Examples
```c
#include <stdio.h>
#include "argparse.h"
static const char *const usage[] = {
"test_argparse [options] [[--] args]",
"test_argparse [options]",
NULL,
};
#define PERM_READ (1<<0)
#define PERM_WRITE (1<<1)
#define PERM_EXEC (1<<2)
int
main(int argc, const char **argv)
{
int force = 0;
int test = 0;
int num = 0;
const char *path = NULL;
int perms = 0;
struct argparse_option options[] = {
OPT_HELP(),
OPT_GROUP("Basic options"),
OPT_BOOLEAN('f', "force", &force, "force to do"),
OPT_BOOLEAN('t', "test", &test, "test only"),
OPT_STRING('p', "path", &path, "path to read"),
OPT_INTEGER('n', "num", &num, "selected num"),
OPT_GROUP("Bits options"),
OPT_BIT(0, "read", &perms, "read perm", NULL, PERM_READ, OPT_NONEG),
OPT_BIT(0, "write", &perms, "write perm", NULL, PERM_WRITE),
OPT_BIT(0, "exec", &perms, "exec perm", NULL, PERM_EXEC),
OPT_END(),
};
struct argparse argparse;
argparse_init(&argparse, options, usage, 0);
argparse_describe(&argparse, "\nA brief description of what the program does and how it works.", "\nAdditional description of the program after the description of the arguments.");
argc = argparse_parse(&argparse, argc, argv);
if (force != 0)
printf("force: %d\n", force);
if (test != 0)
printf("test: %d\n", test);
if (path != NULL)
printf("path: %s\n", path);
if (num != 0)
printf("num: %d\n", num);
if (argc != 0) {
printf("argc: %d\n", argc);
int i;
for (i = 0; i < argc; i++) {
printf("argv[%d]: %s\n", i, *(argv + i));
}
}
if (perms) {
printf("perms: %d\n", perms);
}
return 0;
}
```
/**
* Copyright (C) 2012-2015 Yecheng Fu <cofyc.jackson at gmail dot com>
* All rights reserved.
*
* Use of this source code is governed by a MIT-style license that can be found
* in the LICENSE file.
*/
#ifndef ARGPARSE_H
#define ARGPARSE_H
/* For c++ compatibility */
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
struct argparse;
struct argparse_option;
typedef int argparse_callback (struct argparse *self,
const struct argparse_option *option);
enum argparse_flag {
ARGPARSE_STOP_AT_NON_OPTION = 1 << 0,
ARGPARSE_IGNORE_UNKNOWN_ARGS = 1 << 1,
};
enum argparse_option_type {
/* special */
ARGPARSE_OPT_END,
ARGPARSE_OPT_GROUP,
/* options with no arguments */
ARGPARSE_OPT_BOOLEAN,
ARGPARSE_OPT_BIT,
/* options with arguments (optional or required) */
ARGPARSE_OPT_INTEGER,
ARGPARSE_OPT_FLOAT,
ARGPARSE_OPT_STRING,
};
enum argparse_option_flags {
OPT_NONEG = 1, /* disable negation */
};
/**
* argparse option
*
* `type`:
* holds the type of the option, you must have an ARGPARSE_OPT_END last in your
* array.
*
* `short_name`:
* the character to use as a short option name, '\0' if none.
*
* `long_name`:
* the long option name, without the leading dash, NULL if none.
*
* `value`:
* stores pointer to the value to be filled.
*
* `help`:
* the short help message associated to what the option does.
* Must never be NULL (except for ARGPARSE_OPT_END).
*
* `callback`:
* function is called when corresponding argument is parsed.
*
* `data`:
* associated data. Callbacks can use it like they want.
*
* `flags`:
* option flags.
*/
struct argparse_option {
enum argparse_option_type type;
const char short_name;
const char *long_name;
void *value;
const char *help;
argparse_callback *callback;
intptr_t data;
int flags;
};
/**
* argpparse
*/
struct argparse {
// user supplied
const struct argparse_option *options;
const char *const *usages;
int flags;
const char *description; // a description after usage
const char *epilog; // a description at the end
// internal context
int argc;
const char **argv;
const char **out;
int cpidx;
const char *optvalue; // current option value
};
// built-in callbacks
int argparse_help_cb(struct argparse *self,
const struct argparse_option *option);
// built-in option macros
#define OPT_END() { ARGPARSE_OPT_END, 0, NULL, NULL, 0, NULL, 0, 0 }
#define OPT_BOOLEAN(...) { ARGPARSE_OPT_BOOLEAN, __VA_ARGS__ }
#define OPT_BIT(...) { ARGPARSE_OPT_BIT, __VA_ARGS__ }
#define OPT_INTEGER(...) { ARGPARSE_OPT_INTEGER, __VA_ARGS__ }
#define OPT_FLOAT(...) { ARGPARSE_OPT_FLOAT, __VA_ARGS__ }
#define OPT_STRING(...) { ARGPARSE_OPT_STRING, __VA_ARGS__ }
#define OPT_GROUP(h) { ARGPARSE_OPT_GROUP, 0, NULL, NULL, h, NULL, 0, 0 }
#define OPT_HELP() OPT_BOOLEAN('h', "help", NULL, \
"show this help message and exit", \
argparse_help_cb, 0, OPT_NONEG)
int argparse_init(struct argparse *self, struct argparse_option *options,
const char *const *usages, int flags);
void argparse_describe(struct argparse *self, const char *description,
const char *epilog);
int argparse_parse(struct argparse *self, int argc, const char **argv);
void argparse_usage(struct argparse *self);
#ifdef __cplusplus
}
#endif
#endif
#!/bin/bash
_version='1.02'
_plan_set=0
_no_plan=0
_skip_all=0
_test_died=0
_expected_tests=0
_executed_tests=0
_failed_tests=0
TODO=
usage(){
cat <<'USAGE'
tap-functions: A TAP-producing BASH library
PLAN:
plan_no_plan
plan_skip_all [REASON]
plan_tests NB_TESTS
TEST:
ok RESULT [NAME]
okx COMMAND
is RESULT EXPECTED [NAME]
isnt RESULT EXPECTED [NAME]
like RESULT PATTERN [NAME]
unlike RESULT PATTERN [NAME]
pass [NAME]
fail [NAME]
SKIP:
skip [CONDITION] [REASON] [NB_TESTS=1]
skip $feature_not_present "feature not present" 2 || {
is $a "a"
is $b "b"
}
TODO:
Specify TODO mode by setting $TODO:
TODO="not implemented yet"
ok $result "some not implemented test"
unset TODO
OTHER:
diag MSG
EXAMPLE:
#!/bin/bash
. tap-functions
plan_tests 7
me=$USER
is $USER $me "I am myself"
like $HOME $me "My home is mine"
like "`id`" $me "My id matches myself"
/bin/ls $HOME 1>&2
ok $? "/bin/ls $HOME"
# Same thing using okx shortcut
okx /bin/ls $HOME
[[ "`id -u`" != "0" ]]
i_am_not_root=$?
skip $i_am_not_root "Must be root" || {
okx ls /root
}
TODO="figure out how to become root..."
okx [ "$HOME" == "/root" ]
unset TODO
USAGE
exit
}
opt=
set_u=
while getopts ":sx" opt ; do
case $_opt in
u) set_u=1 ;;
*) usage ;;
esac
done
shift $(( OPTIND - 1 ))
# Don't allow uninitialized variables if requested
[[ -n "$set_u" ]] && set -u
unset opt set_u
# Used to call _cleanup on shell exit
trap _exit EXIT
plan_no_plan(){
(( _plan_set != 0 )) && "You tried to plan twice!"
_plan_set=1
_no_plan=1
return 0
}
plan_skip_all(){
local reason=${1:-''}
(( _plan_set != 0 )) && _die "You tried to plan twice!"
_print_plan 0 "Skip $reason"
_skip_all=1
_plan_set=1
_exit 0
return 0
}
plan_tests(){
local tests=${1:?}
(( _plan_set != 0 )) && _die "You tried to plan twice!"
(( tests == 0 )) && _die "You said to run 0 tests! You've got to run something."
_print_plan $tests
_expected_tests=$tests
_plan_set=1
return $tests
}
_print_plan(){
local tests=${1:?}
local directive=${2:-''}
echo -n "1..$tests"
[[ -n "$directive" ]] && echo -n " # $directive"
echo
}
pass(){
local name=$1
ok 0 "$name"
}
fail(){
local name=$1
ok 1 "$name"
}
# This is the workhorse method that actually
# prints the tests result.
ok(){
local result=${1:?}
local name=${2:-''}
(( _plan_set == 0 )) && _die "You tried to run a test without a plan! Gotta have a plan."
_executed_tests=$(( $_executed_tests + 1 ))
if [[ -n "$name" ]] ; then
if _matches "$name" "^[0-9]+$" ; then
diag " You named your test '$name'. You shouldn't use numbers for your test names."
diag " Very confusing."
fi
fi
if (( result != 0 )) ; then
echo -n "not "
_failed_tests=$(( _failed_tests + 1 ))
fi
echo -n "ok $_executed_tests"
if [[ -n "$name" ]] ; then
local ename=${name//\#/\\#}
echo -n " - $ename"
fi
if [[ -n "$TODO" ]] ; then
echo -n " # TODO $TODO" ;
if (( result != 0 )) ; then
_failed_tests=$(( _failed_tests - 1 ))
fi
fi
echo
if (( result != 0 )) ; then
local file='tap-functions'
local func=
local line=
local i=0
local bt=$(caller $i)
while _matches "$bt" "tap-functions$" ; do
i=$(( $i + 1 ))
bt=$(caller $i)
done
local backtrace=
eval $(caller $i | (read line func file ; echo "backtrace=\"$file:$func() at line $line.\""))
local t=
[[ -n "$TODO" ]] && t="(TODO) "
if [[ -n "$name" ]] ; then
diag " Failed ${t}test '$name'"
diag " in $backtrace"
else
diag " Failed ${t}test in $backtrace"
fi
fi
return $result
}
okx(){
local command="$@"
local line=
diag "Output of '$command':"
$command | while read line ; do
diag "$line"
done
ok ${PIPESTATUS[0]} "$command"
}
_equals(){
local result=${1:?}
local expected=${2:?}
if [[ "$result" == "$expected" ]] ; then
return 0
else
return 1
fi
}
# Thanks to Aaron Kangas for the patch to allow regexp matching
# under bash < 3.
_bash_major_version=${BASH_VERSION%%.*}
_matches(){
local result=${1:?}
local pattern=${2:?}
if [[ -z "$result" || -z "$pattern" ]] ; then
return 1
else
if (( _bash_major_version >= 3 )) ; then
eval '[[ "$result" =~ "$pattern" ]]'
else
echo "$result" | egrep -q "$pattern"
fi
fi
}
_is_diag(){
local result=${1:?}
local expected=${2:?}
diag " got: '$result'"
diag " expected: '$expected'"
}
is(){
local result=${1:?}
local expected=${2:?}
local name=${3:-''}
_equals "$result" "$expected"
(( $? == 0 ))
ok $? "$name"
local r=$?
(( r != 0 )) && _is_diag "$result" "$expected"
return $r
}
isnt(){
local result=${1:?}
local expected=${2:?}
local name=${3:-''}
_equals "$result" "$expected"
(( $? != 0 ))
ok $? "$name"
local r=$?
(( r != 0 )) && _is_diag "$result" "$expected"
return $r
}
like(){
local result=${1:?}
local pattern=${2:?}
local name=${3:-''}
_matches "$result" "$pattern"
(( $? == 0 ))
ok $? "$name"
local r=$?
(( r != 0 )) && diag " '$result' doesn't match '$pattern'"
return $r
}
unlike(){
local result=${1:?}
local pattern=${2:?}
local name=${3:-''}
_matches "$result" "$pattern"
(( $? != 0 ))
ok $? "$name"
local r=$?
(( r != 0 )) && diag " '$result' matches '$pattern'"
return $r
}
skip(){
local condition=${1:?}
local reason=${2:-''}
local n=${3:-1}
if (( condition == 0 )) ; then
local i=
for (( i=0 ; i<$n ; i++ )) ; do
_executed_tests=$(( _executed_tests + 1 ))
echo "ok $_executed_tests # skip: $reason"
done
return 0
else
return
fi
}
diag(){
local msg=${1:?}
if [[ -n "$msg" ]] ; then
echo "# $msg"
fi
return 1
}
_die(){
local reason=${1:-'<unspecified error>'}
echo "$reason" >&2
_test_died=1
_exit 255
}
BAIL_OUT(){
local reason=${1:-''}
echo "Bail out! $reason" >&2
_exit 255
}
_cleanup(){
local rc=0
if (( _plan_set == 0 )) ; then
diag "Looks like your test died before it could output anything."
return $rc
fi
if (( _test_died != 0 )) ; then
diag "Looks like your test died just after $_executed_tests."
return $rc
fi
if (( _skip_all == 0 && _no_plan != 0 )) ; then
_print_plan $_executed_tests
fi
local s=
if (( _no_plan == 0 && _expected_tests < _executed_tests )) ; then
s= ; (( _expected_tests > 1 )) && s=s
local extra=$(( _executed_tests - _expected_tests ))
diag "Looks like you planned $_expected_tests test$s but ran $extra extra."
rc=-1 ;
fi
if (( _no_plan == 0 && _expected_tests > _executed_tests )) ; then
s= ; (( _expected_tests > 1 )) && s=s
diag "Looks like you planned $_expected_tests test$s but only ran $_executed_tests."
fi
if (( _failed_tests > 0 )) ; then
s= ; (( _failed_tests > 1 )) && s=s
diag "Looks like you failed $_failed_tests test$s of $_executed_tests."
fi
return $rc
}
_exit_status(){
if (( _no_plan != 0 || _plan_set == 0 )) ; then
return $_failed_tests
fi
if (( _expected_tests < _executed_tests )) ; then
return $(( _executed_tests - _expected_tests ))
fi
return $(( _failed_tests + ( _expected_tests - _executed_tests )))
}
_exit(){
local rc=${1:-''}
if [[ -z "$rc" ]] ; then
_exit_status
rc=$?
fi
_cleanup
local alt_rc=$?
(( alt_rc != 0 )) && rc=$alt_rc
trap - EXIT
exit $rc
}
#!/bin/bash
. $(dirname ${BASH_SOURCE[0]})/tap-functions
plan_no_plan
is "$(./test_argparse -f --path=/path/to/file a 2>&1)" 'force: 1
path: /path/to/file
argc: 1
argv[0]: a'
is "$(./test_argparse -f -f --force --no-force 2>&1)" 'force: 2'
is "$(./test_argparse -i 2>&1)" 'error: option `-i` requires a value'
is "$(./test_argparse -i 2 2>&1)" 'int_num: 2'
is "$(./test_argparse -i2 2>&1)" 'int_num: 2'
is "$(./test_argparse -ia 2>&1)" 'error: option `-i` expects an integer value'
is "$(./test_argparse -i 0xFFFFFFFFFFFFFFFFF 2>&1)" \
'error: option `-i` numerical result out of range'
is "$(./test_argparse -s 2.4 2>&1)" 'flt_num: 2.4'
is "$(./test_argparse -s2.4 2>&1)" 'flt_num: 2.4'
is "$(./test_argparse -sa 2>&1)" 'error: option `-s` expects a numerical value'
is "$(./test_argparse -s 1e999 2>&1)" \
'error: option `-s` numerical result out of range'
is "$(./test_argparse -f -- do -f -h 2>&1)" 'force: 1
argc: 3
argv[0]: do
argv[1]: -f
argv[2]: -h'
is "$(./test_argparse -tf 2>&1)" 'force: 1
test: 1'
is "$(./test_argparse --read --write 2>&1)" 'perms: 3'
help_usage='Usage: test_argparse [options] [[--] args]
or: test_argparse [options]
A brief description of what the program does and how it works.
-h, --help show this help message and exit
Basic options
-f, --force force to do
-t, --test test only
-p, --path=<str> path to read
-i, --int=<int> selected integer
-s, --float=<flt> selected float
Bits options
--read read perm
--write write perm
--exec exec perm
Additional description of the program after the description of the arguments.'
is "$(./test_argparse -h)" "$help_usage"
is "$(./test_argparse --help)" "$help_usage"
is "$(./test_argparse --no-help 2>&1)" 'error: unknown option `--no-help`'$'\n'"$help_usage"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "argparse.h"
static const char *const usages[] = {
"test_argparse [options] [[--] args]",
"test_argparse [options]",
NULL,
};
#define PERM_READ (1<<0)
#define PERM_WRITE (1<<1)
#define PERM_EXEC (1<<2)
int
main(int argc, const char **argv)
{
int force = 0;
int test = 0;
int int_num = 0;
float flt_num = 0.f;
const char *path = NULL;
int perms = 0;
struct argparse_option options[] = {
OPT_HELP(),
OPT_GROUP("Basic options"),
OPT_BOOLEAN('f', "force", &force, "force to do", NULL, 0, 0),
OPT_BOOLEAN('t', "test", &test, "test only", NULL, 0, 0),
OPT_STRING('p', "path", &path, "path to read", NULL, 0, 0),
OPT_INTEGER('i', "int", &int_num, "selected integer", NULL, 0, 0),
OPT_FLOAT('s', "float", &flt_num, "selected float", NULL, 0, 0),
OPT_GROUP("Bits options"),
OPT_BIT(0, "read", &perms, "read perm", NULL, PERM_READ, OPT_NONEG),
OPT_BIT(0, "write", &perms, "write perm", NULL, PERM_WRITE, 0),
OPT_BIT(0, "exec", &perms, "exec perm", NULL, PERM_EXEC, 0),
OPT_END(),
};
struct argparse argparse;
argparse_init(&argparse, options, usages, 0);
argparse_describe(&argparse, "\nA brief description of what the program does and how it works.", "\nAdditional description of the program after the description of the arguments.");
argc = argparse_parse(&argparse, argc, argv);
if (force != 0)
printf("force: %d\n", force);
if (test != 0)
printf("test: %d\n", test);
if (path != NULL)
printf("path: %s\n", path);
if (int_num != 0)
printf("int_num: %d\n", int_num);
if (flt_num != 0)
printf("flt_num: %g\n", flt_num);
if (argc != 0) {
printf("argc: %d\n", argc);
int i;
for (i = 0; i < argc; i++) {
printf("argv[%d]: %s\n", i, *(argv + i));
}
}
if (perms) {
printf("perms: %d\n", perms);
}
return 0;
}
// Pico String Library
// by. Foxuper
#ifndef PICO_STRING_H
#define PICO_STRING_H
#include <stdint.h>
// String
typedef char *pstr;
// String Information
typedef struct pstri
{
uint64_t length;
uint64_t capacity;
}
pstri;
extern pstr pstr_new (char *string);
extern pstr pstr_psnew (pstr string);
extern pstr pstr_new_exp (void *string, uint64_t length);
extern void pstr_delete (pstr string);
extern pstri pstr_info (pstr string);
extern pstr pstr_cpy (pstr string, char *source);
extern pstr pstr_pscpy (pstr string, pstr source);
extern pstr pstr_cpy_exp (pstr string, void *source, uint64_t source_len);
extern pstr pstr_cat (pstr string, char *source);
extern pstr pstr_pscat (pstr string, pstr source);
extern pstr pstr_cat_exp (pstr string, void *source, uint64_t source_len);
extern int pstr_cmp (pstr string_a, char *string_b);
extern int pstr_pscmp (pstr string_a, pstr string_b);
extern int pstr_cmp_exp (pstr string_a, void *string_b, uint64_t len_b);
#endif // PICO_STRING_H
#ifdef PICO_STRING_IMPLEMENTATION
// Private includes
#include <assert.h>
#include <stdlib.h>
// Header type bit definitions
#define TYPE_BITMASK 0x07
#define TYPE_BITCOUNT 3
// String type
enum pstrt
{
PSTRH0,
PSTRH8,
PSTRH16,
PSTRH32,
PSTRH64,
PSTRHNULL
};
typedef uint8_t pstrt;
// String headers (packed)
#pragma pack(push, 1)
typedef struct pstrh0 { /* ----------------------------- */ pstrt type; } pstrh0;
typedef struct pstrh8 { uint8_t length; uint8_t capacity; pstrt type; } pstrh8;
typedef struct pstrh16 { uint16_t length; uint16_t capacity; pstrt type; } pstrh16;
typedef struct pstrh32 { uint32_t length; uint32_t capacity; pstrt type; } pstrh32;
typedef struct pstrh64 { uint64_t length; uint64_t capacity; pstrt type; } pstrh64;
#pragma pack(pop)
// Asserting string header sizes
static_assert(sizeof(pstrh0) == 1, "[pico_string] strheadt size is incorrect");
static_assert(sizeof(pstrh8) == 3, "[pico_string] strhead8 size is incorrect");
static_assert(sizeof(pstrh16) == 5, "[pico_string] strhead16 size is incorrect");
static_assert(sizeof(pstrh32) == 9, "[pico_string] strhead32 size is incorrect");
static_assert(sizeof(pstrh64) == 17, "[pico_string] strhead64 size is incorrect");
// Private functions
static void *init_header (void *memory, pstrt type, uint64_t length, uint64_t capacity);
static uint64_t header_size (pstrt type);
static pstrt required_type (uint64_t length);
static void pstr_set_len (pstr string, uint64_t length);
static pstr increase_cap (pstr string, uint64_t added_length);
// ---------------- Private definitions ------------------
#define PSTR_HEADER(T, string) \
((pstrh ## T *) (string - sizeof(pstrh ## T)))
#define PSTR_TYPE(string) \
(PSTR_HEADER(0, string)->type & TYPE_BITMASK)
#define GET_INFO_0 \
uint64_t length = PSTR_HEADER(0, string)->type >> TYPE_BITCOUNT; \
return (pstri) {length, length};
#define GET_INFO(T) \
pstrh ## T *header = PSTR_HEADER(T, string); \
return (pstri) {header->length, header->capacity}
#define HEADER_INIT_0 \
*((pstrh0 *) memory) = (pstrh0) {capacity << TYPE_BITCOUNT | type}; \
return (uint8_t *) memory + sizeof(pstrh0);
#define HEADER_INIT(T) \
*((pstrh ## T *) memory) = (pstrh ## T) {length, capacity, type}; \
return (uint8_t *) memory + sizeof(pstrh ## T)
// -------------------------------------------------------
pstr pstr_new (char *string)
{
return pstr_new_exp(string, string ? strlen(string) : 0);
}
pstr pstr_psnew (pstr string)
{
return pstr_new_exp(string, string ? pstr_info(string).length : 0);
}
pstr pstr_new_exp (void *string, uint64_t length)
{
pstrt type = required_type(length);
pstr new_string = malloc(header_size(type) + length + 1);
if (new_string)
{
uint64_t capacity = length;
length = string ? length : 0;
new_string = init_header(new_string, type, length, capacity);
if (string != NULL)
memcpy(new_string, string, length);
new_string[length] = '\0';
}
return new_string;
}
void pstr_delete (pstr string)
{
if (string == NULL) return;
uint64_t size = header_size(PSTR_TYPE(string));
free(string - size);
}
pstri pstr_info (pstr string)
{
switch (PSTR_TYPE(string))
{
case PSTRH0: { GET_INFO_0; }
case PSTRH8: { GET_INFO(8); }
case PSTRH16: { GET_INFO(16); }
case PSTRH32: { GET_INFO(32); }
case PSTRH64: { GET_INFO(64); }
}
return (pstri) {0, 0};
}
pstr pstr_cpy (pstr string, char *source)
{
return pstr_cpy_exp(string, source, strlen(source));
}
pstr pstr_pscpy (pstr string, pstr source)
{
return pstr_cpy_exp(string, source, pstr_info(source).length);
}
pstr pstr_cpy_exp (pstr string, void *source, uint64_t source_len)
{
pstri info = pstr_info(string);
if (info.capacity < source_len)
string = increase_cap(string, source_len - info.length);
if (string != NULL)
{
memcpy(string, source, source_len);
pstr_set_len(string, source_len);
string[source_len] = '\0';
}
return string;
}
pstr pstr_cat (pstr string, char *source)
{
return pstr_cat_exp(string, source, strlen(source));
}
pstr pstr_pscat (pstr string, pstr source)
{
return pstr_cat_exp(string, source, pstr_info(source).length);
}
pstr pstr_cat_exp (pstr string, void *source, uint64_t source_len)
{
pstri info = pstr_info(string);
string = increase_cap(string, source_len);
if (string != NULL)
{
memcpy(string + info.length, source, source_len);
pstr_set_len(string, info.length + source_len);
string[info.length + source_len] = '\0';
}
return string;
}
int pstr_cmp (pstr string_a, char *string_b)
{
return pstr_cmp_exp(string_a, string_b, strlen(string_b));
}
int pstr_pscmp (pstr string_a, pstr string_b)
{
return pstr_cmp_exp(string_a, string_b, pstr_info(string_b).length);
}
int pstr_cmp_exp (pstr string_a, void *string_b, uint64_t len_b)
{
uint64_t len_a = pstr_info(string_a).length;
int comparison = memcmp(string_a, string_b, (len_a < len_b) ? len_a : len_b);
return (comparison == 0) ? ((len_a > len_b) - (len_a < len_b)) : comparison;
}
static void *init_header (void *memory, pstrt type, uint64_t length, uint64_t capacity)
{
switch (type)
{
case PSTRH0: HEADER_INIT_0;
case PSTRH8: HEADER_INIT(8);
case PSTRH16: HEADER_INIT(16);
case PSTRH32: HEADER_INIT(32);
case PSTRH64: HEADER_INIT(64);
}
return NULL;
}
static uint64_t header_size (pstrt type)
{
switch (type & TYPE_BITMASK)
{
case PSTRH0: return sizeof(pstrh0);
case PSTRH8: return sizeof(pstrh8);
case PSTRH16: return sizeof(pstrh16);
case PSTRH32: return sizeof(pstrh32);
case PSTRH64: return sizeof(pstrh64);
}
return 0;
}
static pstrt required_type (uint64_t length)
{
if (length <= 0x1F) return PSTRH0;
if (length <= 0xFF) return PSTRH8;
if (length <= 0xFFFF) return PSTRH16;
if (length <= 0xFFFFFFFF) return PSTRH32;
return PSTRH64;
}
static void pstr_set_len (pstr string, uint64_t length)
{
if (PSTR_TYPE(string) == PSTRH0)
length = (length << TYPE_BITCOUNT) | PSTRH0;
switch (PSTR_TYPE(string))
{
case PSTRH0: PSTR_HEADER(0, string)->type = length; break;
case PSTRH8: PSTR_HEADER(8, string)->length = length; break;
case PSTRH16: PSTR_HEADER(16, string)->length = length; break;
case PSTRH32: PSTR_HEADER(32, string)->length = length; break;
case PSTRH64: PSTR_HEADER(64, string)->length = length; break;
}
}
static pstr increase_cap (pstr string, uint64_t added_length)
{
pstri info = pstr_info(string);
uint64_t new_capacity = info.length + added_length;
pstrt old_type = PSTR_TYPE(string);
pstrt new_type = required_type(new_capacity);
if (new_capacity > info.capacity)
{
if (old_type == new_type)
{
uint64_t size = header_size(old_type);
string = realloc(string - size, size + new_capacity + 1);
return init_header(string, new_type, info.length, new_capacity);
}
else
{
pstr new_string = pstr_new_exp(NULL, new_capacity);
if (new_string)
{
memcpy(new_string, string, info.length);
pstr_set_len(new_string, info.length);
new_string[info.length] = '\0';
}
pstr_delete(string);
return new_string;
}
}
return string;
}
#endif // PICO_STRING_IMPLEMENTATION
\ No newline at end of file
# Set the default behavior
* text eol=lf
# Explicitly declare source files
*.c text eol=lf
*.h text eol=lf
# Denote files that should not be modified.
*.odt binary
# objects
*.o
*.obj
*.s
# libraries
libxxhash.*
!libxxhash.pc.in
# Executables
*.exe
xxh32sum
xxh64sum
xxh128sum
xxhsum
xxhsum32
xxhsum_privateXXH
xxhsum_inlinedXXH
dispatch
tests/generate_unicode_test
# local conf
.clang_complete
# Mac OS-X artefacts
*.dSYM
.DS_Store
# Wasm / emcc / emscripten artefacts
*.html
*.wasm
*.js
# CMake build directories
build*/
# project managers artifacts
.projectile
# analyzer artifacts
infer-out
# test artifacts
.test*
tmp*
tests/*.unicode
tests/unicode_test*
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.0"
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_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-2020 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.
#---------------------------------#
# 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
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-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
*/
/*
* 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)
# 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)
# 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. */
# if 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_ARMV7VE)
# define XSUM_ARCH_UNALIGNED " + unaligned"
# else
# define XSUM_ARCH_UNALIGNED ""
# endif
# if defined(__ARM_NEON) || defined(__ARM_NEON__)
# define XSUM_ARCH_NEON " + NEON"
# else
# define XSUM_ARCH_NEON ""
# endif
# define XSUM_ARCH "ARMv" XSUM_EXPAND_AND_QUOTE(__ARM_ARCH) 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
*/
#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-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 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-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 "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-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 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-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 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" "November 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 bit width 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\. 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 bit width 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.
Alternatively, <HASHTYPE> `32`=XXH32, `64`=XXH64, `128`=XXH128.
Default value is `1` (64bits)
* `--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)
# 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")
add_compile_definitions(XXH_DEBUGLEVEL=1)
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)
# libxxhash
add_library(xxhash "${XXHASH_DIR}/xxhash.c")
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(XXHASH_BUILD_XXHSUM)
install(TARGETS xxhsum
EXPORT xxHashTargets
RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}")
install(FILES "${XXHASH_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
set(PREFIX ${CMAKE_INSTALL_PREFIX})
set(EXECPREFIX "\${prefix}")
set(INCLUDEDIR "${CMAKE_INSTALL_INCLUDEDIR}")
set(LIBDIR "${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)
## 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.
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 - Extremely fast hash algorithm
# Copyright (C) 2012-2020, Yann Collet, Facebook
# BSD 2-Clause License (https://www.opensource.org/licenses/bsd-license.php)
prefix=@PREFIX@
exec_prefix=@EXECPREFIX@
includedir=${prefix}/@INCLUDEDIR@
libdir=${exec_prefix}/@LIBDIR@
Name: xxhash
Description: extremely fast hash algorithm
URL: http://www.xxhash.com/
Version: @VERSION@
Libs: -L${libdir} -lxxhash
Cflags: -I${includedir}
# ################################################################
# xxHash Makefile
# Copyright (C) 2012-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
# ################################################################
CFLAGS += -Wall -Wextra -Wundef -g
CP = cp
NM = nm
GREP = grep
XXHSUM_DIR = ..
XXHSUM = $(XXHSUM_DIR)/xxhsum
# Define *.exe as extension for Windows systems
ifneq (,$(filter Windows%,$(OS)))
EXT =.exe
else
EXT =
endif
ifneq (,$(filter %UTF-8,$(LANG)))
ENABLE_UNICODE ?= 1
else
ENABLE_UNICODE ?= 0
endif
.PHONY: default
default: all
.PHONY: all
all: test
.PHONY: test
test: test_multiInclude test_unicode
.PHONY: test_multiInclude
test_multiInclude:
@$(MAKE) clean
# compile without xxhash.o, ensure symbols exist within target
# Note: built using only default rules
$(MAKE) multiInclude
@$(MAKE) clean
# compile with xxhash.o, to detect duplicated symbols
$(MAKE) multiInclude_withxxhash
@$(MAKE) clean
# compile with XXH_NAMESPACE before XXH_INLINE_ALL
CPPFLAGS=-DXXH_NAMESPACE=TESTN_ $(MAKE) multiInclude
# no symbol prefixed TESTN_ should exist
! $(NM) multiInclude | $(GREP) TESTN_
$(MAKE) clean
# compile xxhash.o with XXH_NAMESPACE
CPPFLAGS=-DXXH_NAMESPACE=TESTN_ $(MAKE) multiInclude_withxxhash
# symbols prefixed TESTN_ should exist in xxhash.o (though not be invoked)
$(NM) multiInclude_withxxhash | $(GREP) TESTN_
$(MAKE) clean
.PHONY: test_ppc_redefine
test_ppc_redefine: ppc_define.c
@$(MAKE) clean
$(CC) $(CPPFLAGS) $(CFLAGS) -c $^
.PHONY: $(XXHSUM)
$(XXHSUM):
$(MAKE) -C $(XXHSUM_DIR) xxhsum
$(CP) $(XXHSUM) .
# Make sure that Unicode filenames work.
# https://github.com/Cyan4973/xxHash/issues/293
.PHONY: test_unicode
ifeq (0,$(ENABLE_UNICODE))
test_unicode:
@echo "Skipping Unicode test, your terminal doesn't appear to support UTF-8."
@echo "Try with ENABLE_UNICODE=1"
else
test_unicode: $(XXHSUM) generate_unicode_test.c
# Generate a Unicode filename test dynamically
# to keep UTF-8 out of the source tree.
$(CC) $(CFLAGS) $(LDFLAGS) generate_unicode_test.c -o generate_unicode_test$(EXT)
./generate_unicode_test$(EXT)
$(SHELL) ./unicode_test.sh
endif
xxhash.o: ../xxhash.c ../xxhash.h
$(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) -c -o $@ $<
multiInclude_withxxhash: multiInclude.o xxhash.o
$(CC) $(CFLAGS) $(CPPFLAGS) $(LDFLAGS) -o $@ $^
clean:
@$(RM) *.o
@$(RM) multiInclude multiInclude_withxxhash
@$(RM) *.unicode generate_unicode_test$(EXT) unicode_test.* xxhsum*
# build artifacts
*.o
benchHash
benchHash32
benchHash_avx2
benchHash_hw
# test files
test*
# ################################################################
# xxHash benchHash Makefile
# Copyright (C) 2019-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
# ################################################################
# benchHash: A generic benchmark for hash algorithms
# measuring throughput, latency and bandwidth
# ################################################################
CPPFLAGS += -I../.. # directory of xxHash source files
CFLAGS ?= -O3
CFLAGS += -Wall -Wextra -Wstrict-aliasing=1 \
-std=c99
CFLAGS += $(MOREFLAGS) # custom way to add flags
CXXFLAGS ?= -O3
LDFLAGS += $(MOREFLAGS)
OBJ_LIST = main.o bhDisplay.o benchHash.o benchfn.o timefn.o
default: benchHash
all: benchHash
benchHash32: CFLAGS += -m32
benchHash32: CXXFLAGS += -m32
benchHash_avx2: CFLAGS += -mavx2
benchHash_avx2: CXXFLAGS += -mavx2
benchHash_hw: CPPFLAGS += -DHARDWARE_SUPPORT
benchHash_hw: CFLAGS += -mavx2 -maes
benchHash_hw: CXXFLAGS += -mavx2 -mpclmul -std=c++14
benchHash benchHash32 benchHash_avx2 benchHash_nosimd benchHash_hw: $(OBJ_LIST)
$(CXX) $(CPPFLAGS) $(CXXFLAGS) $^ $(LDFLAGS) -o $@
main.o: bhDisplay.h hashes.h
bhDisplay.o: bhDisplay.h benchHash.h
benchHash.o: benchHash.h
clean:
$(RM) *.o benchHash benchHash32 benchHash_avx2 benchHash_hw
/*
* Hash benchmark module
* Part of the xxHash project
* Copyright (C) 2019-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
*/
/* benchmark hash functions */
#include <stdlib.h> // malloc
#include <assert.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;
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-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 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-2020 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;
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-2020 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-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
*/
/* === 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-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 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-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
*/
/* === 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-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
*/
/* === 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-2020 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);
}
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
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