diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000000000000000000000000000000000000..6f170626fd0ccea43c9caef31d00480274de18bb --- /dev/null +++ b/.clang-format @@ -0,0 +1,12 @@ +--- +BasedOnStyle: WebKit + +AllowShortIfStatementsOnASingleLine: false +AllowShortFunctionsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +BreakBeforeBraces: Allman +ColumnLimit: 100 +IndentWidth: 4 +NamespaceIndentation: None +SortIncludes: false +--- diff --git a/.gitignore b/.gitignore index 378eac25d311703f3f2cd456d8036da525cd0366..c98012c0574bd8e5b645ec283f3c8a874dd66113 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,21 @@ +*.pyc +.*.swp +*.Po +*.Plo +*.lo +*.o +*.so +*.la +*.a +*.cxx +*.log +.libs/* +.deps/* +*.tar.Z +*.tar.bz2 +*.tar.gz build +docs/source/doxygen +docs/source/api/class +docs/source/api/struct +docs/source/_static/dotfiles diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..8061d128b1e94a7ccc8b663dc299cbf09c483242 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,40 @@ +stages: + - lint + - test + - docs + +lint: + stage: lint + image: 3pia/pxl:latest + script: + - find core io hep modules pxlrun \( -name "*.hh" -o -name "*.cc" \) ! -name "minijson*" ! -name "AssocVector.hh" | xargs clang-format -style=file -i + - if [ -z "$( git diff --name-only )" ]; then echo "code format check succeeded"; exit 0; fi + - 2>&1 echo "code format check failed, found errors in the following files:" + - 2>&1 git diff --name-only + - 2>&1 echo + - 2>&1 echo "possible changes:" + - 2>&1 git --no-pager diff + - exit 1 + +test: + stage: test + image: 3pia/pxl:latest + script: + - mkdir -p build + - cd build + - cmake .. + - make + - make test + +docs: + stage: docs + when: manual + image: 3pia/pxl:latest + script: + - cd docs + - ./docs.sh build + artifacts: + paths: + - docs/build + name: "${CI_BUILD_NAME}_${CI_BUILD_REF_NAME}" + expire_in: 1 day diff --git a/.hgignore b/.hgignore deleted file mode 100644 index db9ff427ac59b8d7f07efbb52e84d7182a0b34e7..0000000000000000000000000000000000000000 --- a/.hgignore +++ /dev/null @@ -1,98 +0,0 @@ -#my global hghignore file -syntax: glob - -*.pyc -.*.swp - -#C++ -*.Po -*.Plo -*.lo -*.o -*.so -*.la -*.a -.libs/* -.deps/* -hg-checklink* - -#CMakeStuff -CMakeFiles/* -cmake_install.cmake -CMakeCache.txt -_CPack_Packages/* -CPackConfig.cmake -CPackSourceConfig.cmake -*.tar.Z -*.tar.bz2 -*.tar.gz - -# autotools stuff -Makefile.in -Makefile -aclocal.m4 -autom4te.cache -compile -config.guess -config.h -config.h.in -config.log -config.status -config.sub -configure -depcomp -install-sh -intltool-* -libtool -ltmain.sh -missing -mkinstalldirs -stamp-h1 - - -#automatically generated files -*.html -*.png -*.gif -*.css -*.pc -bin/* - -*.cxx -*.log - -pypxl/*.py -CTestTestfile.cmake -scripting/swigpyrun.h - -# ??? -DartConfiguration.tcl -CTestCostData.txt -analysisTestOut.xml - -syntax: regexp -^doc/pxl/xml$ -syntax: regexp -^doc/pxl/Doxyfile$ -syntax: regexp -^pypxl/pxl$ - -glob:doc/pxl/html/* -glob:doc/pypxl/html/* -glob:test/pypxl_test*.py -glob:test/test_healpix_pythonInterface.py - -glob:Doxyfile - -syntax: regexp -^build$ -syntax: regexp -^pypxl/xml$ -glob:test/pypxltest.py -glob:pypxl/*PYTHON_wrap.h -glob:pypxl/*.i -glob:pypxl/Doxyfile -glob:include/pxl/core/config.hh - -syntax: glob -.*project \ No newline at end of file diff --git a/AUTHORS b/AUTHORS deleted file mode 100644 index 3f1edbd88139d469fd6f46db71c3e4fea2787f22..0000000000000000000000000000000000000000 --- a/AUTHORS +++ /dev/null @@ -1,20 +0,0 @@ -Current PXL Developers: - Robert Fischer - Andreas Hinzmann - Dennis Klingebiel - Matthias Komm - Gero Mueller - Jan Steggemann - Tobias Winchen - -Current PXL Project Managers: - Martin Erdmann - -Former PXL Developers/Advisors: - Oxana Actis - Steffen Kappler (project leader) - Matthias Kirsch - Tatsiana Klimkovich - Matthias Plum - Guenter Quast - Christophe Saout diff --git a/CMakeLists.txt b/CMakeLists.txt index 2932ec238dc4b14a61e8cce16ab1720df033b51d..1b5b493273b3bb6f1adbf7c2de79b391e2cae456 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,62 +1,101 @@ -CMAKE_MINIMUM_REQUIRED(VERSION 2.6) -PROJECT(PXL) +# +# project setup +# + +cmake_minimum_required(VERSION 2.6) +project(PXL) + +list(APPEND CMAKE_MODULE_PATH "$ENV{CMAKE_MODULE_PATH}" "${CMAKE_SOURCE_DIR}/cmake") + # -# define PXL Version +# define the version # -SET(PXLMAJORRELEASEVERSION 3) -SET(PXLMINORRELEASEVERSION 5) -SET(BUGFIXRELEASE 4) -SET(PXLVERSION ${PXLMAJORRELEASEVERSION}.${PXLMINORRELEASEVERSION}.${BUGFIXRELEASE}) -SET(PXLMAINVERSION ${PXLMAJORRELEASEVERSION}.${PXLMINORRELEASEVERSION}) +# read from version file +file(READ "${CMAKE_SOURCE_DIR}/version.txt" VERSION_STRING) +string(REGEX MATCHALL "([0-9a-zA-Z]+)" VERSION_LIST "${VERSION_STRING}") +list(GET VERSION_LIST 0 PXL_VERSION_MAJOR) +list(GET VERSION_LIST 1 PXL_VERSION_MINOR) +list(GET VERSION_LIST 2 PXL_VERSION_PATCH) +set(PXL_VERSION "${PXL_VERSION_MAJOR}.${PXL_VERSION_MINOR}.${PXL_VERSION_PATCH}") +set(PXL_VERSION_LIB "${PXL_VERSION_MAJOR}.${PXL_VERSION_MINOR}") -IF(NOT CMAKE_BUILD_TYPE) - SET(CMAKE_BUILD_TYPE Release) -ENDIF() -MESSAGE(STATUS "Build Type: ${CMAKE_BUILD_TYPE}") +message(STATUS "building PXL v${PXL_VERSION}") + + +# +# define directories +# -OPTION(ENABLESWIGDOCSTRINGS "Automatically generate docstrings with swig" ON) -OPTION(ENABLETESTING "Build tests and enable test target" ON) +message(STATUS "INSTALL_PREFIX : ${CMAKE_INSTALL_PREFIX}") + +if(NOT PXL_BIN_DIR) + set(PXL_BIN_DIR ${CMAKE_INSTALL_PREFIX}/bin) +endif() +message(STATUS "PXL_BIN_DIR : ${PXL_BIN_DIR}") + +if(NOT PXL_LIB_DIR) + set(PXL_LIB_DIR ${CMAKE_INSTALL_PREFIX}/lib) +endif() +message(STATUS "PXL_LIB_DIR : ${PXL_LIB_DIR}") + +if(NOT PXL_INCLUDE_DIR) + set(PXL_INCLUDE_DIR ${CMAKE_INSTALL_PREFIX}/include) +endif() +message(STATUS "PXL_INCLUDE_DIR: ${PXL_INCLUDE_DIR}") + +if(NOT PXL_SHARE_DIR) + set(PXL_SHARE_DIR ${CMAKE_INSTALL_PREFIX}/share) +endif() +message(STATUS "PXL_SHARE_DIR : ${PXL_SHARE_DIR}") -OPTION(ENABLE_COVERAGE_TEST "Build tests and enable test target" OFF) -IF (ENABLE_COVERAGE_TEST) - MESSAGE(STATUS "Enable coverage test") - SET(CMAKE_CXX_FLAGS "-fprofile-arcs -ftest-coverage ${CMAKE_CXX_FLAGS}") - SET(CMAKE_EXE_LINKER_FLAGS "-lgcov ${CMAKE_EXE_LINKER_FLAGS}") +if(NOT PXL_PLUGIN_DIR) + set(PXL_PLUGIN_DIR ${CMAKE_INSTALL_PREFIX}/lib/pxl-${PXL_VERSION_LIB}) endif() +message(STATUS "PXL_PLUGIN_DIR : ${PXL_PLUGIN_DIR}") -OPTION(USE_PYTHON "enable python bindings and modules" ON) -IF(USE_PYTHON) - ADD_DEFINITIONS(-DPXL_USE_PYTHON) - FIND_PACKAGE(SWIG REQUIRED) +# +# duplicates to be compliant to autotools *.in files +# + +set(prefix ${CMAKE_INSTALL_PREFIX}) +set(exec_prefix ${CMAKE_INSTALL_PREFIX}) +set(libdir ${PXL_LIB_DIR}) +set(includedir ${PXL_INCLUDE_DIR}) +set(datadir ${CMAKE_INSTALL_PREFIX}/share/pxl) - INCLUDE (Python.cmake) - IF(${PYTHON_DOT_VERSION} VERSION_LESS 2.6) - MESSAGE(SEND_ERROR " PXL requires Python 2.6 or later. If you have python 2.6 or newer installed but it is not your default python version, you can provide the location of the newer python interpreter e.g. via - $cmake -DPYTHON_EXECUTABLE=/usr/bin/python2.6") - ENDIF() - IF(NOT PYTHON_EXECUTABLE) - MESSAGE(FATAL_ERROR "PYTHON EXECUTEABLE NOT FOUND! You can set the location of the python interpreter e.g. via - $cmake -DPYTHON_EXECUTABLE=/usr/bin/python2.6") - ENDIF() -ENDIF() +# +# furher package setup +# -FIND_PACKAGE(Doxygen) +if(NOT CMAKE_BUILD_TYPE) + set(CMAKE_BUILD_TYPE Release) +endif() +message(STATUS "Build Type: ${CMAKE_BUILD_TYPE}") + +option(ENABLETESTING "Build tests and enable test target" ON) + +option(ENABLE_COVERAGE_TEST "Build tests and enable test target" OFF) +if(ENABLE_COVERAGE_TEST) + message(STATUS "Enable coverage test") + set(CMAKE_CXX_FLAGS "-fprofile-arcs -ftest-coverage ${CMAKE_CXX_FLAGS}") + set(CMAKE_EXE_LINKER_FLAGS "-lgcov ${CMAKE_EXE_LINKER_FLAGS}") +endif() -ADD_DEFINITIONS(-DPXL_EXPORT) +add_definitions(-DPXL_EXPORT) -INCLUDE(CheckIncludeFile) +include(CheckIncludeFile) -MACRO(PXL_CHECK_HEADER filename define) - CHECK_INCLUDE_FILE(${filename} ${define}) - IF(${define}) - ADD_DEFINITIONS(-D${define}) - ENDIF(${define}) -ENDMACRO(PXL_CHECK_HEADER filename define) +macro(PXL_CHECK_HEADER filename define) + CHECK_INCLUDE_FILE(${filename} ${define}) + if(${define}) + add_definitions(-D${define}) + endif() +endmacro() PXL_CHECK_HEADER(winsock2.h HAVE_WINSOCK2_H) PXL_CHECK_HEADER(sys/socket.h HAVE_SYS_SOCKET_H) @@ -67,209 +106,178 @@ PXL_CHECK_HEADER(sys/time.h HAVE_SYS_TIME_H) PXL_CHECK_HEADER(netdb.h HAVE_NETDB_H) PXL_CHECK_HEADER(Ws2tcpip.h HAVE_WS2TCPIP_H) -# -# define include directory -# - -SET(PXLINCLUDEDIR ${CMAKE_INSTALL_PREFIX}/include) - -SET(PXLLIBSDIR ${CMAKE_INSTALL_PREFIX}/lib) -# -# define the plugindirectory - -# -SET(PXLPLUGINDIR ${CMAKE_INSTALL_PREFIX}/lib/pxl-${PXLMAINVERSION}) -# -# define use healpix option -# -OPTION(USE_HEALPIX "Build the healpix library, which is under GPL" TRUE) +find_package(Threads) -# -# the install directories -# -#SET(BIN_INSTALLDIR ${CMAKE_INSTALL_PREFIX}/bin) -#SET(LIB_INSTALLDIR ${CMAKE_INSTALL_PREFIX}/lib) -#SET(HEADER_INSTALLDIR ${CMAKE_INSTALL_PREFIX}/include) +if(MSVC) + add_definitions( "/wd4290 /wd4251 /nologo" ) + add_definitions(-D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE -D_SCL_SECURE_NO_WARNINGS) +endif() -FIND_PACKAGE(Threads) +# setup stdint.h +if(MSVC) + find_path(STDINT_H_PATH stdint.h external/stdint) + message(STATUS "Use stdint.h from " ${STDINT_H_PATH}) + include_directories(${STDINT_H_PATH}) +endif() -IF(MSVC) - ADD_DEFINITIONS( "/wd4290 /wd4251 /nologo" ) - ADD_DEFINITIONS(-D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE -D_SCL_SECURE_NO_WARNINGS) -ENDIF(MSVC) # -# DUPLICATIONS TO WORK WITH autotools *.in files +# check for debug flags # -SET(PXL_VERSION ${PXLVERSION}) -SET(PXL_LIB_VERSION ${PXLMAINVERSION}) -SET(includedir ${PXLINCLUDEDIR}) -SET(libdir ${PXLLIBSDIR}) -SET(datadir ${CMAKE_INSTALL_PREFIX}/share/pxl) -SET(exec_prefix ${CMAKE_INSTALL_PREFIX}) -SET(prefix ${CMAKE_INSTALL_PREFIX}) -# setup stdint.h -IF(MSVC) - FIND_PATH(STDINT_H_PATH stdint.h lib/stdint) - MESSAGE(STATUS "Use stdint.h from " ${STDINT_H_PATH}) - INCLUDE_DIRECTORIES(${STDINT_H_PATH}) -ENDIF() +option(DEFINE_DEBUG "Build the project using debugging code" OFF) +if(DEFINE_DEBUG) + message(STATUS "Adding Debug flag...") + add_definitions(-DDEBUG) + set(CMAKE_BUILD_TYPE Debug) + message(STATUS "Build type is " ${CMAKE_BUILD_TYPE}) +endif() +set(EXECUTABLE_OUTPUT_PATH "${CMAKE_BINARY_DIR}/bin") +set(LIBRARY_OUTPUT_PATH "${CMAKE_BINARY_DIR}/bin") + +if(MSVC) + set(OUTPUT_PATH "${CMAKE_BINARY_DIR}/bin/Release") +else() + set(OUTPUT_PATH "${CMAKE_BINARY_DIR}/bin") +endif() +message(STATUS "Output Path: ${OUTPUT_PATH}") -# -# check for debug flag -# -OPTION(DEFINE_DEBUG "Build the project using debugging code" OFF) -IF(DEFINE_DEBUG) - MESSAGE(STATUS "Adding Debug flag...") - ADD_DEFINITIONS(-DDEBUG) - SET(CMAKE_BUILD_TYPE Debug) - MESSAGE(STATUS "Build type is " ${CMAKE_BUILD_TYPE}) -ENDIF() - -SET(EXECUTABLE_OUTPUT_PATH "${CMAKE_BINARY_DIR}/bin") -SET(LIBRARY_OUTPUT_PATH "${CMAKE_BINARY_DIR}/bin") - -IF(MSVC) - SET(OUTPUT_PATH "${CMAKE_BINARY_DIR}/bin/Release") -ELSE() - SET(OUTPUT_PATH "${CMAKE_BINARY_DIR}/bin") -ENDIF() -MESSAGE(STATUS "Output Path: ${OUTPUT_PATH}") # # define common macro for installing libraries # -MACRO(PXL_INSTALL_LIBRARY name) - SET_TARGET_PROPERTIES(${name} PROPERTIES VERSION ${PXLMAINVERSION}) - IF(WIN32) - INSTALL(TARGETS ${name} ARCHIVE DESTINATION ${CMAKE_INSTALL_PREFIX}/lib) - INSTALL(TARGETS ${name} RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}) - ELSE() - INSTALL(TARGETS ${name} LIBRARY DESTINATION ${CMAKE_INSTALL_PREFIX}/lib) - INSTALL(DIRECTORY include/pxl DESTINATION ${PXLINCLUDEDIR} FILES_MATCHING PATTERN "*.hh" PATTERN "Py*.*" EXCLUDE) - - # - # automatically generate pkgconfig file and install it - # - IF(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${name}.pc.in) - CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/${name}.pc.in ${CMAKE_CURRENT_BINARY_DIR}/${name}.pc) - INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/${name}.pc DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/pkgconfig) - ENDIF() - ENDIF() -ENDMACRO(PXL_INSTALL_LIBRARY name) + +macro(PXL_INSTALL_LIBRARY name) + set_target_properties(${name} PROPERTIES VERSION ${PXL_VERSION_LIB}) + if(WIN32) + install(TARGETS ${name} ARCHIVE DESTINATION ${CMAKE_INSTALL_PREFIX}/lib) + install(TARGETS ${name} RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}) + else() + install(TARGETS ${name} LIBRARY DESTINATION ${CMAKE_INSTALL_PREFIX}/lib) + install(DIRECTORY include/pxl DESTINATION ${PXL_INCLUDE_DIR} FILES_MATCHING PATTERN "*.hh" PATTERN "Py*.*" EXCLUDE) + + # + # automatically generate pkgconfig file and install it + # + if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${name}.pc.in) + configure_file(${CMAKE_CURRENT_SOURCE_DIR}/${name}.pc.in ${CMAKE_CURRENT_BINARY_DIR}/${name}.pc) + install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${name}.pc DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/pkgconfig) + endif() + endif() +endmacro() + # # define common macro for installing executables # -MACRO(PXL_INSTALL_EXECUTABLE name) - IF(WIN32) - INSTALL(TARGETS ${name} RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}) - ELSE() - INSTALL(TARGETS ${name} RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}/bin) - ENDIF() -ENDMACRO(PXL_INSTALL_EXECUTABLE name) - -INCLUDE(Xcode.cmake) - -INCLUDE(FindLibSSH.cmake) -IF(LIB_SSH_FOUND) - ADD_DEFINITIONS(-DPXL_ENABLE_SFTP) - SET(PXL_ENABLE_SFTP TRUE) -ENDIF() - -INCLUDE(FindDCAP.cmake) -IF(LIB_DCAP_FOUND) - MESSAGE(STATUS "Enable DCAP") - ADD_DEFINITIONS(-DPXL_ENABLE_DCAP) - SET(PXL_ENABLE_DCAP TRUE) -ENDIF() + +macro(PXL_INSTALL_EXECUTABLE name) + if(WIN32) + INSTALL(TARGETS ${name} RUNTIME DESTINATION ${CMAKE_INSTALL_PREFIX}) + else() + INSTALL(TARGETS ${name} RUNTIME DESTINATION ${PXL_BIN_DIR}) + endif() +endmacro() + + +if(APPLE) + # using MACOSX_RPATH is enabled by default (policy CMP0042) + # set the variable to an arbitrary value to supress warnings + # run "cmake --help-policy CMP0042" for more info + set(CMAKE_MACOSX_RPATH 1) +endif() + + +find_package(LibSSH) +if(LIB_SSH_FOUND) + add_definitions(-DPXL_ENABLE_SFTP) + set(PXL_ENABLE_SFTP TRUE) +endif() + +find_package(DCAP) +if(LIB_DCAP_FOUND) + message(STATUS "Enable DCAP") + add_definitions(-DPXL_ENABLE_DCAP) + set(PXL_ENABLE_DCAP TRUE) +endif() # -# add externals to include directory +# add externals to include directory # -INCLUDE_DIRECTORIES(${PXL_SOURCE_DIR}/lib) + +include_directories(${PXL_SOURCE_DIR}/external) + # # add sub projects # -IF(ENABLETESTING) - ENABLE_TESTING() - ADD_SUBDIRECTORY(test) - ADD_SUBDIRECTORY(lib/gtest) -ENDIF() + +if(ENABLETESTING) + enable_testing() + add_subdirectory(test) + add_subdirectory(external/gtest) +endif() # # find zlib # -SET(ZLIB_INCLUDE_DIR) -FIND_PACKAGE(ZLIB) -IF(ZLIB_FOUND) - MESSAGE(STATUS "Use system zlib") -ELSE() - ADD_SUBDIRECTORY(lib/zlib) - MESSAGE(STATUS "Use internal zlib") - SET(ZLIB_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/lib/zlib" "${CMAKE_BINARY_DIR}/lib/zlib") - SET(ZLIB_LIBRARIES zlib) -ENDIF() - -IF(WIN32 AND NOT CYGWIN) - SET(DEF_INSTALL_CMAKE_DIR CMake) -ELSE() - SET(DEF_INSTALL_CMAKE_DIR "lib/cmake/pxl-${PXLMAINVERSION}") -ENDIF() -SET(INSTALL_CMAKE_DIR ${DEF_INSTALL_CMAKE_DIR}) - -CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/PXLConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/PXLConfig.cmake @ONLY) -INSTALL(FILES - "${CMAKE_CURRENT_BINARY_DIR}/PXLConfig.cmake" - DESTINATION "${INSTALL_CMAKE_DIR}" COMPONENT dev) - - -ADD_SUBDIRECTORY(core) -ADD_SUBDIRECTORY(doc) -ADD_SUBDIRECTORY(hep) -ADD_SUBDIRECTORY(xml) -ADD_SUBDIRECTORY(astro) -ADD_SUBDIRECTORY(algorithms) -ADD_SUBDIRECTORY(modules) -ADD_SUBDIRECTORY(pxlrun) -ADD_SUBDIRECTORY(examples) -ADD_SUBDIRECTORY(skeletons) - -IF(USE_PYTHON) - ADD_SUBDIRECTORY(scripting) - ADD_SUBDIRECTORY(pypxl) -ENDIF() - -INCLUDE(WindowsInstaller.cmake) - -IF(UNIX) - # setup make dist - ADD_CUSTOM_TARGET(dist - cd ${CMAKE_SOURCE_DIR} && - hg archive -X .hgtags -X .hg_archival.txt -X .hgignore -t tar -p pxl-${PXLVERSION} - | - gzip > ${CMAKE_BINARY_DIR}/pxl-${PXLVERSION}.tar.gz) - - # setup make distcheck - ADD_CUSTOM_TARGET(distcheck - cd ${CMAKE_BINARY_DIR} && - rm -rf pxl-${PXLVERSION} && - gzip -df pxl-${PXLVERSION}.tar.gz && - tar -xf pxl-${PXLVERSION}.tar && - cd pxl-${PXLVERSION}/ && - cmake . && make && make test && - cd ${CMAKE_BINARY_DIR} && - tar -rf pxl-${PXLVERSION}.tar pxl-${PXLVERSION}/doc/ && - gzip ${CMAKE_BINARY_DIR}/pxl-${PXLVERSION}.tar) - ADD_DEPENDENCIES(distcheck dist) -ENDIF() +set(ZLIB_INCLUDE_DIR) +find_package(ZLIB) +if(ZLIB_FOUND) + message(STATUS "Use system zlib") +else() + add_subdirectory(external/zlib) + message(STATUS "Use internal zlib") + set(ZLIB_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/external/zlib" "${CMAKE_BINARY_DIR}/external/zlib") + set(ZLIB_LIBRARIES zlib) +endif() + +if(WIN32 AND NOT CYGWIN) + set(DEF_INSTALL_CMAKE_DIR CMake) +else() + set(DEF_INSTALL_CMAKE_DIR "lib/cmake/pxl-${PXL_VERSION_LIB}") +endif() +set(INSTALL_CMAKE_DIR ${DEF_INSTALL_CMAKE_DIR}) + +add_subdirectory(core) +add_subdirectory(io) +add_subdirectory(hep) +add_subdirectory(modules) +add_subdirectory(pxlrun) + +if(MSVC) + include(${CMAKE_SOURCE_DIR}/cmake/WindowsInstaller.cmake) +endif() + +if(UNIX) + # setup make dist + add_custom_target(dist + cd ${CMAKE_SOURCE_DIR} && + git archive --format tar.gz HEAD > ${CMAKE_BINARY_DIR}/pxl-${PXL_VERSION}.tar.gz + ) + + # setup make distcheck + add_custom_target(distcheck + cd ${CMAKE_BINARY_DIR} && + rm -rf pxl-${PXL_VERSION} && + gzip -df pxl-${PXL_VERSION}.tar.gz && + tar -xf pxl-${PXL_VERSION}.tar && + cd pxl-${PXL_VERSION}/ && + cmake . && make && make test && + cd ${CMAKE_BINARY_DIR} && + tar -rf pxl-${PXL_VERSION}.tar pxl-${PXL_VERSION}/doc/ && + gzip ${CMAKE_BINARY_DIR}/pxl-${PXL_VERSION}.tar + ) + add_dependencies(distcheck dist) +endif() # # install additional files # -INSTALL(FILES ${CMAKE_SOURCE_DIR}/setup.sh DESTINATION ${CMAKE_INSTALL_PREFIX}) +install(FILES ${CMAKE_SOURCE_DIR}/setup.sh DESTINATION ${CMAKE_INSTALL_PREFIX}) +install(FILES ${CMAKE_SOURCE_DIR}/cmake/FindPXL.cmake DESTINATION ${PXL_SHARE_DIR}) diff --git a/CMakeMacroParseArguments.cmake b/CMakeMacroParseArguments.cmake deleted file mode 100644 index 4cea370b83580f4cdddd6aaf91b2ddf0c40774d5..0000000000000000000000000000000000000000 --- a/CMakeMacroParseArguments.cmake +++ /dev/null @@ -1,90 +0,0 @@ -# This file defines the following macro for developers needing to parse -# arguments passed to a CMake macro using names. -# -# PARSE_ARGUMENTS - parse arguments supplied to a macro -# -# The PARSE_ARGUMENTS macro will take the arguments of another macro and define -# several variables. The first argument to PARSE_ARGUMENTS is a prefix to put -# on all variables it creates. The second argument is a list of names, and the -# third argument is a list of options. Both of these lists should be quoted. -# The rest of PARSE_ARGUMENTS are arguments from another macro to be parsed. -# -# PARSE_ARGUMENTS(prefix arg_names options arg1 arg2...) -# -# For each item in options, PARSE_ARGUMENTS will create a variable with that -# name, prefixed with prefix_. So, for example, if prefix is MY_MACRO and -# options is OPTION1;OPTION2, then PARSE_ARGUMENTS will create the variables -# MY_MACRO_OPTION1 and MY_MACRO_OPTION2. These variables will be set to true -# if the option exists in the command line or false otherwise. -# -# For each item in arg_names, PARSE_ARGUMENTS will create a variable with that -# name, prefixed with prefix_. Each variable will be filled with the arguments -# that occur after the given arg_name is encountered up to the next arg_name -# or the end of the arguments. All options are removed from these lists. -# PARSE_ARGUMENTS also creates a prefix_DEFAULT_ARGS variable containing the -# list of all arguments up to the first arg_name encountered. -# -# Here is a simple, albeit impractical, example of using PARSE_ARGUMENTS that -# demonstrates its behavior. -# -# SET(arguments -# hello OPTION3 world -# LIST3 foo bar -# OPTION2 -# LIST1 fuz baz -# ) -# PARSE_ARGUMENTS(ARG "LIST1;LIST2;LIST3" "OPTION1;OPTION2;OPTION3" ${arguments}) -# -# PARSE_ARGUMENTS creates 7 variables and sets them as follows: -# -# * ARG_DEFAULT_ARGS: hello;world -# * ARG_LIST1: fuz;baz -# * ARG_LIST2: -# * ARG_LIST3: foo;bar -# * ARG_OPTION1: FALSE -# * ARG_OPTION2: TRUE -# * ARG_OPTION3: TRUE -# -# If you don't have any options, use an empty string in its place. -# -# PARSE_ARGUMENTS(ARG "LIST1;LIST2;LIST3" "" ${arguments}) -# -# Likewise if you have no lists. -# -# PARSE_ARGUMENTS(ARG "" "OPTION1;OPTION2;OPTION3" ${arguments}) -# -# -# Code and description copied from: -# http://www.cmake.org/Wiki/CMakeMacroParseArguments - -MACRO(PARSE_ARGUMENTS prefix arg_names option_names) - SET(DEFAULT_ARGS) - FOREACH(arg_name ${arg_names}) - SET(${prefix}_${arg_name}) - ENDFOREACH(arg_name) - FOREACH(option ${option_names}) - SET(${prefix}_${option} FALSE) - ENDFOREACH(option) - - SET(current_arg_name DEFAULT_ARGS) - SET(current_arg_list) - FOREACH(arg ${ARGN}) - SET(larg_names ${arg_names}) - LIST(FIND larg_names "${arg}" is_arg_name) - IF (is_arg_name GREATER -1) - SET(${prefix}_${current_arg_name} ${current_arg_list}) - SET(current_arg_name ${arg}) - SET(current_arg_list) - ELSE (is_arg_name GREATER -1) - SET(loption_names ${option_names}) - LIST(FIND loption_names "${arg}" is_option) - IF (is_option GREATER -1) - SET(${prefix}_${arg} TRUE) - ELSE (is_option GREATER -1) - SET(current_arg_list ${current_arg_list} ${arg}) - ENDIF (is_option GREATER -1) - ENDIF (is_arg_name GREATER -1) - ENDFOREACH(arg) - SET(${prefix}_${current_arg_name} ${current_arg_list}) -ENDMACRO(PARSE_ARGUMENTS) - diff --git a/COPYING b/COPYING deleted file mode 100644 index 101ca3300a2aa7947e7c4a6252992588874c94f5..0000000000000000000000000000000000000000 --- a/COPYING +++ /dev/null @@ -1,328 +0,0 @@ -PXL is free software; you can redistribute it and/or modify -it under the terms of the GNU Lesser General Public License as published by -the Free Software Foundation; either version 3 of the License, or -(at your option) any later version. - -This package 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 Lesser General Public License -along with this package; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - - - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. - ------------------------------------------------------------------- -This Software uses the Mersenne Twister algorithm for generating random -numbers. It therfore ships the file MersenneTwister.hh, which is based -on the MersenneTwister.h, published under following license: - -MersenneTwister.h -Mersenne Twister random number generator -- a C++ class MTRand -Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus -Richard J. Wagner v1.0 15 May 2003 rjwagner@writeme.com - -The Mersenne Twister is an algorithm for generating random numbers. It -was designed with consideration of the flaws in various other generators. -The period, 2^19937-1, and the order of equidistribution, 623 dimensions, -are far greater. The generator is also fast; it avoids multiplication and -division, and it benefits from caches and pipelines. For more information -see the inventors' web page at http://www.math.keio.ac.jp/~matumoto/emt.html - -Reference -M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-Dimensionally -Equidistributed Uniform Pseudo-Random Number Generator", ACM Transactions on -Modeling and Computer Simulation, Vol. 8, No. 1, January 1998, pp 3-30. - -Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, -Copyright (C) 2000 - 2003, Richard J. Wagner -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - 3. The names of its contributors may not be used to endorse or promote - products derived from this software without specific prior written - permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -The original code included the following notice: - - When you use this, send an email to: matumoto@math.keio.ac.jp - with an appropriate reference to your work. - -It would be nice to CC: rjwagner@writeme.com and Cokus@math.washington.edu -when you write. - ------------------------------------------------------------------- -This software ships expat, a small XML parser library written in C -(http://expat.sourceforge.net/). - -Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd - and Clark Cooper -Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Expat maintainers. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be included -in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -~ - ------------------------------------------------------------------- -This software uses simpleopt for command line parsing. Simpleopt is -published under the following license: - -The licence text below is the boilerplate "MIT Licence" used from: -http://www.opensource.org/licenses/mit-license.php - -Copyright (c) 2006-2007, Brodie Thiesfield - -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. - ------------------------------------------------------------------- -We use a modified version of UseDoxygen by Tobias Rautenkranz -(http://tobias.rautenkranz.ch/cmake/doxygen/) to generate doxygen -documentation with cmake. UseDoxygen.cmake is published with the -following copyright statement: - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - -1. Redistributions of source code must retain the copyright - notice, this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. -3. The name of the author may not be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, -INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT -NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ------------------------------------------------------------------- diff --git a/ChangeLog b/ChangeLog deleted file mode 100644 index fd360ac2e2d5678a942592790cc50878a9715d81..0000000000000000000000000000000000000000 --- a/ChangeLog +++ /dev/null @@ -1,324 +0,0 @@ -This is a summary of the most relevant changes. For a complete list of -changes see https://forge.physik.rwth-aachen.de/projects/pxl - - -pxl 3.5.4, important changes since 3.5.3 ------------------------------------------------------------------- - - * Allow multiple paths in PXL_PLUGIN_PATH - * Add getDescription to modules - * Fix some Variant operators - * Allow Variant vectors in user records - * Introduce USE_PYTHON option - * Fix LorentzVector operators - - -pxl 3.5.3, important changes since 3.5.2 ------------------------------------------------------------------- - - * fix SWIG comments - * Implement python context management for OutputFile, InputFile - * Make ObjectOwner, ObjectManager, Event and BasicContainer, InputFile iterable in pypxl. - * Add writeEvery option for OutputModule. - -pxl 3.5.2, important changes since 3.5.1 ------------------------------------------------------------------- - - * add stdin/stdout File IO via schema std: - * Add getName method to MessageDispatcher. - * safe integer casts in Variant - * fix c11 and swig bugs - * Add SubscriberModule that implements MessageHandler and adds some convenience. - -pxl 3.5.1, important changes since 3.5.0 ------------------------------------------------------------------- - - * fix Module::getVersion: add missing virtual - -pxl 3.5.0, important changes since 3.4.0 ------------------------------------------------------------------- - - * fix Variant toFloat/toDouble for boolean - * Allow numpy arrays as alien arrays in BasicNVector - * Add rapidity functions to LorentzVector, extend test_core.cc. - * use class parameter in PyModule to find class - * upgrades gtest to latest version 1.7.0 to be compatible with OS X 10.9 - * modifies Python.cmake to make it compatible with OS X 10.9 - * Improve error message on wrong python version - * Remove obsolete usage of pkgconfig in FindPXL - * Added option for select module isntall path in FindPXL - * UserRecord now throws runtime_error if non-exisitng entry is erased. This is now consistent with other methods. Closes: #1240 - * Add support for multiple numpy floats. Closes: #1219 - * make all modules available in python - * add onPublish callback to pymodule - * fix CMAKE python lib finding - * add publish/subscribe to analysis - - -pxl 3.4.0, important changes since 3.3.3 ------------------------------------------------------------------- - - * Install pkg-config files again, Closes: #1007 - * check for pkgconfig files, fixes #913 - * Improved debug output - * Check for non string returns in PyModuleModule. Closes: #732. - * Throw exception in InputFile if open non existing file. Closes: #852 - * Added cmake option to disbale build of python docstrings - * clears existing value vector before adding new values when setting module option of type vector of strings (fixes vispa ticket #943) - * Added test for correct removal on connections in analysis if module is removed. - * Remove status messages on reload of script in PyModule - * Return ./ as parent directory instead of empty string, Closes: #892 - * Make SoftRelations between two objects of same name unique, Closes: #902 - * Fix treatment of start and end index in output file; closes #398 and #848 - * fixes #893, allow empty source names in PyModules - * Fix Script::objectToString for python <2.7 - * fix Doxygen generation for Variant - * add mission to, fix #889 - * fixes #810 (adds convenience methods for Relative: getDaughter() and getMothers() - * Fix auto decay reconstruction - * Not interpreting PyObject as unicode in Script::objectToString, Closes: #875, #872 - * CMake throws fatal error if pytohn not found, Closes: #858 - * Added Fisher distribution of vectors on sphere to random - * Return tuple in pythonwrapping of HealpixMap::getPixelsInCone,Closes: #729 - * Added missing clone method to healpixmap, Closes: #744 - * randNorm default: variance = 1 instead of 0 (standard normal distribution) - * added index=-1 to randPowerLaw and randBrokenPowerLaw - * Fixed FTBFS if missing dcap due to double .cc in CmakeLists - * refactor variant, improve usage - * fix windows build - * add sftp file - * introduce abstract file class - * improve Stream, add Stream tests - * fix -builtin use on older SWIG versions - * make swig interfaces backward compatible (1.3.29) - * refactor i/o stream - -pxl 3.3.3, important changes since 3.3.2 ------------------------------------------------------------------- - - * fix dcache file implementation - -pxl 3.3.2, important changes since 3.3.1 ------------------------------------------------------------------- - - * fix installation of pxl-doxy.i - -pxl 3.3.1, important changes since 3.3.0 ------------------------------------------------------------------- - - * fix swig 2.0.9 bug - * fix swig interfaces for all versions - * update bundled expat version to 2.1.0 - * update bundled zlib version to 1.2.8 - * fix pxlrc crash on windows - -pxl 3.3.0, important changes since 3.2.0 ------------------------------------------------------------------- - - * Added numpy array interface to BasicNVector and BasicMatrix. - * Added USAGE_TEXT_SELECTION to modules, Closes: #405 - * Add setVector and addVector methods to particle to increase consistency with getVector - * Do not execute beginJob, endJob, beginRun, endRun on disabled modules. Closes: #1079 - * Fixed Native_toVariant conversion for type(value)==long, Closes: #1026 - * Remove non-existing object from BasicContainer throws exception. Closes: #856 - * Added function to expand enviroment variables - * Use expansion of enviroment variables in analyis find file and outpmodule. Closes: #1041. - * Remove empty strings from python search path to avoid security issue - * Add path of python module to local python search path. Closes: #1037 - * moved skeletons from Vispa to pxl, Closes: #1097 - * Write analysis to tmpfile first and copy on close to avoid corrupted xml files. Closes: #1070 - * Allow python list of variant-able data types in userrecord. Closes #1089 - * Added missing DLL_EXPORT. Should fix windows builds - * Do not require pkgcfg - * Print error summary on finish of pxlrun - * Colored ConsoleHandler - * Add getDataPath option to pxlrun - * Use pxlrun instread of pkg-config to provide info on user plugin dir - * Added conveniance macro to insll pxl modules to FindPXL - * Add more informations about the pxl installation to pxlrun, and use this in FindPXL - * Add RootSerializable - * Add Zmumu example with efficiency correction using a RootSerializable - * Added missing functionality python interface of SoftRelations - * Added method to remove objects of type from BasicContainer, Closes: #1153 - * Improved error message on missing python modules. Closes #1150 - * Understand numpy datatypes in userRecord, Closes: #1126 - * Add option to add additional directories to search path in pxlrun, Closes: #1168 - * Added pxlconfiguration file, Closes: #1169 - * add system wide pxlrc, PXL_SYSTEM_RC compiler flag - * use console colors only when tty is present -> no colors in files. - * Removed check on compression mode in ChunkWriter - * move autodecayreconstructor from pxl into own package (fixes #1248) - * remove neutrino pz solutions and move them to auto decay reconstruction module - * Added example for user defined types - * Add reference-based deltaX methods to LorentzVector and Basic3Vector, which should significantly simplify C++ code and avoid statemens such as fv1.deltaR(&fv2) - * Reset number of objects after file section has been written - * Allow compression level of zero - * Install swig .i files needed for user defined data types, like root serializable - * Fixed healpix order 0, Closes: #1280 - * make loadDefaultPlugins available from within python, Closes: #1250 - - -pxl 3.2.0, important changes since 3.1.0 ------------------------------------------------------------------- - - * Install pkg-config files again, Closes: #1007 - * check for pkgconfig files, fixes #913 - * Improved debug output - * Check for non string returns in PyModuleModule. Closes: #732. - * Throw exception in InputFile if open non existing file. Closes: #852 - * Added cmake option to disbale build of python docstrings - * clears existing value vector before adding new values when setting module option of type vector of strings (fixes vispa ticket #943) - * Added test for correct removal on connections in analysis if module is removed. - * Remove status messages on reload of script in PyModule - * Return ./ as parent directory instead of empty string, Closes: #892 - * Make SoftRelations between two objects of same name unique, Closes: #902 - * Fix treatment of start and end index in output file; closes #398 and #848 - * fixes #893, allow empty source names in PyModules - * Fix Script::objectToString for python <2.7 - * fix Doxygen generation for Variant - * add mission to, fix #889 - * fixes #810 (adds convenience methods for Relative: getDaughter() and getMothers() - * Fix auto decay reconstruction - * Not interpreting PyObject as unicode in Script::objectToString, Closes: #875, #872 - * CMake throws fatal error if pytohn not found, Closes: #858 - * Added Fisher distribution of vectors on sphere to random - * Return tuple in pythonwrapping of HealpixMap::getPixelsInCone,Closes: #729 - * Added missing clone method to healpixmap, Closes: #744 - * randNorm default: variance = 1 instead of 0 (standard normal distribution) - * added index=-1 to randPowerLaw and randBrokenPowerLaw - * Fixed FTBFS if missing dcap due to double .cc in CmakeLists - * refactor variant, improve usage - * fix windows build - * add sftp file - * introduce abstract file class - * improve Stream, add Stream tests - * fix -builtin use on older SWIG versions - * make swig interfaces backward compatible (1.3.29) - * refactor i/o stream - -pxl 3.1.0, important changes since 3.0.3 ------------------------------------------------------------------- - - * Throw exception when write operation fails (Closes: #694) - * fix order of input files #718 - * bring variant into defined state - * use Variant inside Module for Options. - * Fixed angle calculation in Basic3Vector for cases of parallel and antiparallel vectors - * Astro: Normalize vector in set setGalacticDirectionVector, Closes: #666 - * Increased safety in usage of alien arrays in BasicNVector, Closes: #651 - * Make BasicContainer python iterable, Closes: #714 - * Return const ref instead of const pointer to modules and connection lists in analysis - * Fix pypxl on swig2.0 - * fixed default build type to Release - * fixed cmake python search on mingw - * Fixed setting of string vector analysis, Closes: #655 - * fix memory leak in scripting loader - * Fixed memory leak in BasicNVector - * Fixed potential memory leak in analysis - -pxl 3.0.3, important changes since 3.0 ------------------------------------------------------------------- - - * Fixed potential memory leak in BasicNVector and BasicMatrix - * fixed OutputModule - * Removed potential error hiding NULL pointer check in AstroObject - * Fixed memory leak in input module and added warning for empty filenames - * Fixed angular distance floating point precision for rare circumstances - * Possible fix for angular distance floating point precision on mac - * Fixed angular distance calculation on mac - * added BasicNVector.norm(L) - * add check if option is available when getting option values - * Fixed pypxl on SL5 - * Potential fix for workaround swig::stop_iteration, restores python default dlopen behaviour - * Don't allow PyModules without python code - * Improved python bindings of healpixmap, python style getNeighbors - * Fixed python bindings of HealpixMap::getNumberOfPixels - * uniformDistributionINHealpix - * Improved seperation of healpix due to license issues, added option USE_HEALPIX - * improved unzip performance - * AstroBasicObject has default direction - * REmoved buggy random direction in pixel from healpixmap: - * Updated Variant. Can store a vector of variants now - * Fixed __getitem__, __setitem__ in python wrap of BasicMatrix - * Improved python interface BasicMatrix, gives correct shape and len - * Module::setOption throws exception if option not added first. Closes #401 - * Added XYZ setters for SGC and Equatorial Coordinates - * Added norm to Basic3Vector, Closes: #678 - * Added getAngleTo to Basic3Vector - * Added rotate to Basic3Vector - -pxl 3.0.0, 21.06.10 ------------------------------------------------------------------- - * API Changes: - The complete Api has been reviewed and adjusted. For a complete list - of changes see the changelog http://pxl.hg.sourceforge.net/hgweb/pxl/pxl/log, - or the doxygen documentation - - core/ base&io: - * base and io have been merged into core - BasicContainer - * Added typedef std::map ContainerIndex - * Changed return type inline const map_t& getIndexEntry() const -> inline const ContainerIndex& getIndex() const - Event - * Renamed setObject -> insertObject - Filter - * Renamed Comparator -> ComparatorInterface - * Renamed FilterCriterion - > FilterCriterionInterface - LorentzVector - * Removed inline void setMass(double m) - Object - * Renamed inline bool getLocked() -> inline bool isLocked() const - * Renamed inline int getWorkflag() -> inline int getWorkFlag() - * Renamed inline void setWorkflag(int v) -> inline void setWorkFlag(int v) - UserRecord - * Renamed UserRecord -> UserRecords - - astro: - AstroBasicObject - * Removed of setZenith and setAzimuth method - * Renamed setLongitudeLatitude -> setGalacticLongitudeLatitude - - hep: - Collision: - * Removed typedef weak_ptr CollisionWkPtr - Particle: - * Renamed getParticleId() -> getPdgNumber() - * Renamed setParticleId() -> setPdgNumber() - * Renamed setVector() -> getVector() - AnalysisFork: - * Changed parameters: virtual void beginJob(const ObjectOwner* input = 0) -> virtual void beginJob(const Serializable* input = 0) - * Changed parameters: virtual void beginRun(const ObjectOwner* input = 0) -> virtual void beginRun(const Serializable* input = 0) - * Changed parameters: virtual void endJob(const ObjectOwner* input = 0) -> virtual void endJob(const Serializable* input = 0) - * Changed parameters: virtual void endRun(const ObjectOwner* input = 0) -> virtual void endRun(const Serializable* input = 0) - * Changed parameters: virtual void finishEvent(const ObjectOwner* input = 0) -> virtual void finishEvent(const Event* event = 0) - * Changed parameters: virtual void analyseEvent(const ObjectOwner* - * input = 0) -> virtual void analyseEvent(const Event* event = 0) - - * Starting with pxl 3.0.0 the buildsystem is cmake - - * Mechanism to include user classes in pxlrun, Closes: #152 - * Introduction of logging system, Closes: #105 - * python scripts are now classes, Closes: #137, #138 - * pxlrun can execute multiple analysis, one after the other, Closes: #210 - * pypxl returns objects of correct type, Closes: #195, #184, #185 - * Method to store meta information in analysis xml file, Closes: #207 - * Support for astronomical coordinate systems, Closes: #202, #203, #204 - * Random generator is now availeable from python, Closes: #181 - * Fixed operator overloading in python, Closes: #160, #100 - * Userrecord can carry serializables, Closes: - * Introduced Analysis Class, Closes: #148 - * Make InputFile.close() save if not InputFile.good(), Closes: #132 - * In layout of orphans, increase distance to borders, Closes: #113 - * Introduced N Dimensional Vector and Matrix, Closes: #101, #102 - * Make ad-hoc AutoLayout work for several large decay trees, Closes: #98 - * Create and submit ILC filler, Closes: #18 - * design meta info for scriptfilter modules, Closes: #31 - * pxlrun can change module parameters via cmdline, Closes: #146 - * Remove layout from particle, Closes: #175 - * Document Id, InformationChunk, Layout, Relations, Closes: #176 - * Version information in pxl.hh, Closes: #144 - - - - - diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..85c7c6967647e2e085d7fb803c38695d049bc3e2 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,636 @@ +# GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright (C) 2007 [Free Software Foundation, Inc.](http://fsf.org/) + +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + +## Preamble + +The GNU General Public License is a free, copyleft license for software and +other kinds of works. + +The licenses for most software and other practical works are designed to take +away your freedom to share and change the works. By contrast, the GNU General +Public License is intended to guarantee your freedom to share and change all +versions of a program--to make sure it remains free software for all its users. +We, the Free Software Foundation, use the GNU General Public License for most +of our software; it applies also to any other work released this way by its +authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our +General Public Licenses are designed to make sure that you have the freedom to +distribute copies of free software (and charge for them if you wish), that you +receive source code or can get it if you want it, that you can change the +software or use pieces of it in new free programs, and that you know you can do +these things. + +To protect your rights, we need to prevent others from denying you these rights +or asking you to surrender the rights. Therefore, you have certain +responsibilities if you distribute copies of the software, or if you modify it: +responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for +a fee, you must pass on to the recipients the same freedoms that you received. +You must make sure that they, too, receive or can get the source code. And you +must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: + + 1. assert copyright on the software, and + 2. offer you this License giving you legal permission to copy, distribute + and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that +there is no warranty for this free software. For both users' and authors' sake, +the GPL requires that modified versions be marked as changed, so that their +problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified +versions of the software inside them, although the manufacturer can do so. This +is fundamentally incompatible with the aim of protecting users' freedom to +change the software. The systematic pattern of such abuse occurs in the area of +products for individuals to use, which is precisely where it is most +unacceptable. Therefore, we have designed this version of the GPL to prohibit +the practice for those products. If such problems arise substantially in other +domains, we stand ready to extend this provision to those domains in future +versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States +should not allow patents to restrict development and use of software on +general-purpose computers, but in those that do, we wish to avoid the special +danger that patents applied to a free program could make it effectively +proprietary. To prevent this, the GPL assures that patents cannot be used to +render the program non-free. + +The precise terms and conditions for copying, distribution and modification +follow. + +## TERMS AND CONDITIONS + +### 0. Definitions. + +*This License* refers to version 3 of the GNU General Public License. + +*Copyright* also means copyright-like laws that apply to other kinds of works, +such as semiconductor masks. + +*The Program* refers to any copyrightable work licensed under this License. +Each licensee is addressed as *you*. *Licensees* and *recipients* may be +individuals or organizations. + +To *modify* a work means to copy from or adapt all or part of the work in a +fashion requiring copyright permission, other than the making of an exact copy. +The resulting work is called a *modified version* of the earlier work or a work +*based on* the earlier work. + +A *covered work* means either the unmodified Program or a work based on the +Program. + +To *propagate* a work means to do anything with it that, without permission, +would make you directly or secondarily liable for infringement under applicable +copyright law, except executing it on a computer or modifying a private copy. +Propagation includes copying, distribution (with or without modification), +making available to the public, and in some countries other activities as well. + +To *convey* a work means any kind of propagation that enables other parties to +make or receive copies. Mere interaction with a user through a computer +network, with no transfer of a copy, is not conveying. + +An interactive user interface displays *Appropriate Legal Notices* to the +extent that it includes a convenient and prominently visible feature that + + 1. displays an appropriate copyright notice, and + 2. tells the user that there is no warranty for the work (except to the + extent that warranties are provided), that licensees may convey the work + under this License, and how to view a copy of this License. + +If the interface presents a list of user commands or options, such as a menu, a +prominent item in the list meets this criterion. + +### 1. Source Code. + +The *source code* for a work means the preferred form of the work for making +modifications to it. *Object code* means any non-source form of a work. + +A *Standard Interface* means an interface that either is an official standard +defined by a recognized standards body, or, in the case of interfaces specified +for a particular programming language, one that is widely used among developers +working in that language. + +The *System Libraries* of an executable work include anything, other than the +work as a whole, that (a) is included in the normal form of packaging a Major +Component, but which is not part of that Major Component, and (b) serves only +to enable use of the work with that Major Component, or to implement a Standard +Interface for which an implementation is available to the public in source code +form. A *Major Component*, in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system (if any) on +which the executable work runs, or a compiler used to produce the work, or an +object code interpreter used to run it. + +The *Corresponding Source* for a work in object code form means all the source +code needed to generate, install, and (for an executable work) run the object +code and to modify the work, including scripts to control those activities. +However, it does not include the work's System Libraries, or general-purpose +tools or generally available free programs which are used unmodified in +performing those activities but which are not part of the work. For example, +Corresponding Source includes interface definition files associated with source +files for the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, such as +by intimate data communication or control flow between those subprograms and +other parts of the work. + +The Corresponding Source need not include anything that users can regenerate +automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +### 2. Basic Permissions. + +All rights granted under this License are granted for the term of copyright on +the Program, and are irrevocable provided the stated conditions are met. This +License explicitly affirms your unlimited permission to run the unmodified +Program. The output from running a covered work is covered by this License only +if the output, given its content, constitutes a covered work. This License +acknowledges your rights of fair use or other equivalent, as provided by +copyright law. + +You may make, run and propagate covered works that you do not convey, without +conditions so long as your license otherwise remains in force. You may convey +covered works to others for the sole purpose of having them make modifications +exclusively for you, or provide you with facilities for running those works, +provided that you comply with the terms of this License in conveying all +material for which you do not control copyright. Those thus making or running +the covered works for you must do so exclusively on your behalf, under your +direction and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes it +unnecessary. + +### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological measure +under any applicable law fulfilling obligations under article 11 of the WIPO +copyright treaty adopted on 20 December 1996, or similar laws prohibiting or +restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention is +effected by exercising rights under this License with respect to the covered +work, and you disclaim any intention to limit operation or modification of the +work as a means of enforcing, against the work's users, your or third parties' +legal rights to forbid circumvention of technological measures. + +### 4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you receive it, +in any medium, provided that you conspicuously and appropriately publish on +each copy an appropriate copyright notice; keep intact all notices stating that +this License and any non-permissive terms added in accord with section 7 apply +to the code; keep intact all notices of the absence of any warranty; and give +all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may +offer support or warranty protection for a fee. + +### 5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to produce it +from the Program, in the form of source code under the terms of section 4, +provided that you also meet all of these conditions: + + - a) The work must carry prominent notices stating that you modified it, and + giving a relevant date. + - b) The work must carry prominent notices stating that it is released under + this License and any conditions added under section 7. This requirement + modifies the requirement in section 4 to *keep intact all notices*. + - c) You must license the entire work, as a whole, under this License to + anyone who comes into possession of a copy. This License will therefore + apply, along with any applicable section 7 additional terms, to the whole + of the work, and all its parts, regardless of how they are packaged. This + License gives no permission to license the work in any other way, but it + does not invalidate such permission if you have separately received it. + - d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your work need + not make them do so. + +A compilation of a covered work with other separate and independent works, +which are not by their nature extensions of the covered work, and which are not +combined with it such as to form a larger program, in or on a volume of a +storage or distribution medium, is called an *aggregate* if the compilation and +its resulting copyright are not used to limit the access or legal rights of the +compilation's users beyond what the individual works permit. Inclusion of a +covered work in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +### 6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of sections 4 +and 5, provided that you also convey the machine-readable Corresponding Source +under the terms of this License, in one of these ways: + + - a) Convey the object code in, or embodied in, a physical product (including + a physical distribution medium), accompanied by the Corresponding Source + fixed on a durable physical medium customarily used for software + interchange. + - b) Convey the object code in, or embodied in, a physical product (including + a physical distribution medium), accompanied by a written offer, valid for + at least three years and valid for as long as you offer spare parts or + customer support for that product model, to give anyone who possesses the + object code either + 1. a copy of the Corresponding Source for all the software in the product + that is covered by this License, on a durable physical medium + customarily used for software interchange, for a price no more than your + reasonable cost of physically performing this conveying of source, or + 2. access to copy the Corresponding Source from a network server at no + charge. + - c) Convey individual copies of the object code with a copy of the written + offer to provide the Corresponding Source. This alternative is allowed only + occasionally and noncommercially, and only if you received the object code + with such an offer, in accord with subsection 6b. + - d) Convey the object code by offering access from a designated place + (gratis or for a charge), and offer equivalent access to the Corresponding + Source in the same way through the same place at no further charge. You + need not require recipients to copy the Corresponding Source along with the + object code. If the place to copy the object code is a network server, the + Corresponding Source may be on a different server operated by you or a + third party) that supports equivalent copying facilities, provided you + maintain clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the Corresponding + Source, you remain obligated to ensure that it is available for as long as + needed to satisfy these requirements. + - e) Convey the object code using peer-to-peer transmission, provided you + inform other peers where the object code and Corresponding Source of the + work are being offered to the general public at no charge under subsection + 6d. + +A separable portion of the object code, whose source code is excluded from the +Corresponding Source as a System Library, need not be included in conveying the +object code work. + +A *User Product* is either + + 1. a *consumer product*, which means any tangible personal property which is + normally used for personal, family, or household purposes, or + 2. anything designed or sold for incorporation into a dwelling. + +In determining whether a product is a consumer product, doubtful cases shall be +resolved in favor of coverage. For a particular product received by a +particular user, *normally used* refers to a typical or common use of that +class of product, regardless of the status of the particular user or of the way +in which the particular user actually uses, or expects or is expected to use, +the product. A product is a consumer product regardless of whether the product +has substantial commercial, industrial or non-consumer uses, unless such uses +represent the only significant mode of use of the product. + +*Installation Information* for a User Product means any methods, procedures, +authorization keys, or other information required to install and execute +modified versions of a covered work in that User Product from a modified +version of its Corresponding Source. The information must suffice to ensure +that the continued functioning of the modified object code is in no case +prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as part of a +transaction in which the right of possession and use of the User Product is +transferred to the recipient in perpetuity or for a fixed term (regardless of +how the transaction is characterized), the Corresponding Source conveyed under +this section must be accompanied by the Installation Information. But this +requirement does not apply if neither you nor any third party retains the +ability to install modified object code on the User Product (for example, the +work has been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates for a +work that has been modified or installed by the recipient, or for the User +Product in which it has been modified or installed. Access to a network may be +denied when the modification itself materially and adversely affects the +operation of the network or violates the rules and protocols for communication +across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord +with this section must be in a format that is publicly documented (and with an +implementation available to the public in source code form), and must require +no special password or key for unpacking, reading or copying. + +### 7. Additional Terms. + +*Additional permissions* are terms that supplement the terms of this License by +making exceptions from one or more of its conditions. Additional permissions +that are applicable to the entire Program shall be treated as though they were +included in this License, to the extent that they are valid under applicable +law. If additional permissions apply only to part of the Program, that part may +be used separately under those permissions, but the entire Program remains +governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any +additional permissions from that copy, or from any part of it. (Additional +permissions may be written to require their own removal in certain cases when +you modify the work.) You may place additional permissions on material, added +by you to a covered work, for which you have or can give appropriate copyright +permission. + +Notwithstanding any other provision of this License, for material you add to a +covered work, you may (if authorized by the copyright holders of that material) +supplement the terms of this License with terms: + + - a) Disclaiming warranty or limiting liability differently from the terms of + sections 15 and 16 of this License; or + - b) Requiring preservation of specified reasonable legal notices or author + attributions in that material or in the Appropriate Legal Notices displayed + by works containing it; or + - c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in reasonable + ways as different from the original version; or + - d) Limiting the use for publicity purposes of names of licensors or authors + of the material; or + - e) Declining to grant rights under trademark law for use of some trade + names, trademarks, or service marks; or + - f) Requiring indemnification of licensors and authors of that material by + anyone who conveys the material (or modified versions of it) with + contractual assumptions of liability to the recipient, for any liability + that these contractual assumptions directly impose on those licensors and + authors. + +All other non-permissive additional terms are considered *further restrictions* +within the meaning of section 10. If the Program as you received it, or any +part of it, contains a notice stating that it is governed by this License along +with a term that is a further restriction, you may remove that term. If a +license document contains a further restriction but permits relicensing or +conveying under this License, you may add to a covered work material governed +by the terms of that license document, provided that the further restriction +does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, +in the relevant source files, a statement of the additional terms that apply to +those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a +separately written license, or stated as exceptions; the above requirements +apply either way. + +### 8. Termination. + +You may not propagate or modify a covered work except as expressly provided +under this License. Any attempt otherwise to propagate or modify it is void, +and will automatically terminate your rights under this License (including any +patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a +particular copyright holder is reinstated + + - a) provisionally, unless and until the copyright holder explicitly and + finally terminates your license, and + - b) permanently, if the copyright holder fails to notify you of the + violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated +permanently if the copyright holder notifies you of the violation by some +reasonable means, this is the first time you have received notice of violation +of this License (for any work) from that copyright holder, and you cure the +violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses +of parties who have received copies or rights from you under this License. If +your rights have been terminated and not permanently reinstated, you do not +qualify to receive new licenses for the same material under section 10. + +### 9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run a copy +of the Program. Ancillary propagation of a covered work occurring solely as a +consequence of using peer-to-peer transmission to receive a copy likewise does +not require acceptance. However, nothing other than this License grants you +permission to propagate or modify any covered work. These actions infringe +copyright if you do not accept this License. Therefore, by modifying or +propagating a covered work, you indicate your acceptance of this License to do +so. + +### 10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically receives a +license from the original licensors, to run, modify and propagate that work, +subject to this License. You are not responsible for enforcing compliance by +third parties with this License. + +An *entity transaction* is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered work +results from an entity transaction, each party to that transaction who receives +a copy of the work also receives whatever licenses to the work the party's +predecessor in interest had or could give under the previous paragraph, plus a +right to possession of the Corresponding Source of the work from the +predecessor in interest, if the predecessor has it or can get it with +reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights +granted or affirmed under this License. For example, you may not impose a +license fee, royalty, or other charge for exercise of rights granted under this +License, and you may not initiate litigation (including a cross-claim or +counterclaim in a lawsuit) alleging that any patent claim is infringed by +making, using, selling, offering for sale, or importing the Program or any +portion of it. + +### 11. Patents. + +A *contributor* is a copyright holder who authorizes use under this License of +the Program or a work on which the Program is based. The work thus licensed is +called the contributor's *contributor version*. + +A contributor's *essential patent claims* are all patent claims owned or +controlled by the contributor, whether already acquired or hereafter acquired, +that would be infringed by some manner, permitted by this License, of making, +using, or selling its contributor version, but do not include claims that would +be infringed only as a consequence of further modification of the contributor +version. For purposes of this definition, *control* includes the right to grant +patent sublicenses in a manner consistent with the requirements of this +License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent +license under the contributor's essential patent claims, to make, use, sell, +offer for sale, import and otherwise run, modify and propagate the contents of +its contributor version. + +In the following three paragraphs, a *patent license* is any express agreement +or commitment, however denominated, not to enforce a patent (such as an express +permission to practice a patent or covenant not to sue for patent +infringement). To *grant* such a patent license to a party means to make such +an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the +Corresponding Source of the work is not available for anyone to copy, free of +charge and under the terms of this License, through a publicly available +network server or other readily accessible means, then you must either + + 1. cause the Corresponding Source to be so available, or + 2. arrange to deprive yourself of the benefit of the patent license for this + particular work, or + 3. arrange, in a manner consistent with the requirements of this License, to + extend the patent license to downstream recipients. + +*Knowingly relying* means you have actual knowledge that, but for the patent +license, your conveying the covered work in a country, or your recipient's use +of the covered work in a country, would infringe one or more identifiable +patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you +convey, or propagate by procuring conveyance of, a covered work, and grant a +patent license to some of the parties receiving the covered work authorizing +them to use, propagate, modify or convey a specific copy of the covered work, +then the patent license you grant is automatically extended to all recipients +of the covered work and works based on it. + +A patent license is *discriminatory* if it does not include within the scope of +its coverage, prohibits the exercise of, or is conditioned on the non-exercise +of one or more of the rights that are specifically granted under this License. +You may not convey a covered work if you are a party to an arrangement with a +third party that is in the business of distributing software, under which you +make payment to the third party based on the extent of your activity of +conveying the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory patent +license + + - a) in connection with copies of the covered work conveyed by you (or copies + made from those copies), or + - b) primarily for and in connection with specific products or compilations + that contain the covered work, unless you entered into that arrangement, or + that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied +license or other defenses to infringement that may otherwise be available to +you under applicable patent law. + +### 12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not excuse +you from the conditions of this License. If you cannot convey a covered work so +as to satisfy simultaneously your obligations under this License and any other +pertinent obligations, then as a consequence you may not convey it at all. For +example, if you agree to terms that obligate you to collect a royalty for +further conveying from those to whom you convey the Program, the only way you +could satisfy both those terms and this License would be to refrain entirely +from conveying the Program. + +### 13. Use with the GNU Affero General Public License. + +Notwithstanding any other provision of this License, you have permission to +link or combine any covered work with a work licensed under version 3 of the +GNU Affero General Public License into a single combined work, and to convey +the resulting work. The terms of this License will continue to apply to the +part which is the covered work, but the special requirements of the GNU Affero +General Public License, section 13, concerning interaction through a network +will apply to the combination as such. + +### 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions of the GNU +General Public License from time to time. Such new versions will be similar in +spirit to the present version, but may differ in detail to address new problems +or concerns. + +Each version is given a distinguishing version number. If the Program specifies +that a certain numbered version of the GNU General Public License *or any later +version* applies to it, you have the option of following the terms and +conditions either of that numbered version or of any later version published by +the Free Software Foundation. If the Program does not specify a version number +of the GNU General Public License, you may choose any version ever published by +the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the +GNU General Public License can be used, that proxy's public statement of +acceptance of a version permanently authorizes you to choose that version for +the Program. + +Later license versions may give you additional or different permissions. +However, no additional obligations are imposed on any author or copyright +holder as a result of your choosing to follow a later version. + +### 15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE +LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER +PARTIES PROVIDE THE PROGRAM *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER +EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE +QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE +DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR +CORRECTION. + +### 16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY +COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS +PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, +INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE +THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED +INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE +PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY +HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +### 17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided above cannot +be given local legal effect according to their terms, reviewing courts shall +apply local law that most closely approximates an absolute waiver of all civil +liability in connection with the Program, unless a warranty or assumption of +liability accompanies a copy of the Program in return for a fee. + +## END OF TERMS AND CONDITIONS ### + +### How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible +use to the public, the best way to achieve this is to make it free software +which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach +them to the start of each source file to most effectively state the exclusion +of warranty; and each file should have at least the *copyright* line and a +pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 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, see . + +Also add information on how to contact you by electronic and paper mail. + +If the program does terminal interaction, make it output a short notice like +this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w` and `show c` should show the appropriate +parts of the General Public License. Of course, your program's commands might +be different; for a GUI interface, you would use an *about box*. + +You should also get your employer (if you work as a programmer) or school, if +any, to sign a *copyright disclaimer* for the program, if necessary. For more +information on this, and how to apply and follow the GNU GPL, see +[http://www.gnu.org/licenses/](http://www.gnu.org/licenses/). + +The GNU General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may consider +it more useful to permit linking proprietary applications with the library. If +this is what you want to do, use the GNU Lesser General Public License instead +of this License. But first, please read +[http://www.gnu.org/philosophy/why-not-lgpl.html](http://www.gnu.org/philosophy/why-not-lgpl.html). diff --git a/PXLConfig.cmake.in b/PXLConfig.cmake.in deleted file mode 100644 index fc48f7c4a934d1e1e4c3499fef77f0967d5e16ac..0000000000000000000000000000000000000000 --- a/PXLConfig.cmake.in +++ /dev/null @@ -1,60 +0,0 @@ -# - Config file for the pxl package -# It defines the following variables -# PXL_INCLUDE_DIRS - include directories for pxl -# PXL_LIBRARIES - libraries to link against -# PXL_EXECUTABLE - the bar executable - -SET(PXL_LIBRARY_PATH "@CMAKE_INSTALL_PREFIX@/lib") -SET(PXL_LIBRARIES "pxl-core") -SET(PXL_INCLUDE_DIRS "@PXLINCLUDEDIR@") - -SET(PXL_AVAILABLE_COMPONENTS core hep astro modules scripting algorithms) - -FOREACH(comp ${PXL_FIND_COMPONENTS}) - if (NOT ";${PXL_AVAILABLE_COMPONENTS};" MATCHES ";${comp};" ) - set(PXL_FOUND False) - set(PXL_NOTFOUND_MESSAGE "Specified unsupported component: ${comp}") - MESSAGE(STATUS "Specified unsupported component: ${comp}") - else() - if (NOT ";${PXL_LIBRARIES};" MATCHES ";pxl-${comp};" ) - LIST(APPEND PXL_LIBRARIES "pxl-${comp}") - endif() - MESSAGE(STATUS "Add PXL component: ${comp}") - endif() -ENDFOREACH() - - -# define options -OPTION(PXL_USER_PLUGIN "Install PXL modules in user plugin path" ON) - -SET (PXL_USER_PLUGIN_PATH "$ENV{HOME}/.pxl-@PXLMAINVERSION@/plugins") -SET (PXL_INSTALL_PLUGIN_PATH "@CMAKE_INSTALL_PREFIX@/lib/pxl-@PXLMAINVERSION@/plugins") - -# when PXL_PLUGIN_INSTALL_PATH is undefined, try to assign a good default -IF(NOT DEFINED PXL_PLUGIN_INSTALL_PATH) - IF(PXL_USER_PLUGIN) - SET (PXL_PLUGIN_INSTALL_PATH ${PXL_USER_PLUGIN_PATH}) - ELSE(PXL_USER_PLUGIN) - SET (PXL_PLUGIN_INSTALL_PATH ${PXL_INSTALL_PLUGIN_PATH}) - ENDIF(PXL_USER_PLUGIN) -ENDIF(NOT DEFINED PXL_PLUGIN_INSTALL_PATH) - -MESSAGE(STATUS "Install PXL plugins to " ${PXL_PLUGIN_INSTALL_PATH}) - - -# macro to add a new module to cmake -MACRO(ADD_PXL_PLUGIN name files) - LINK_DIRECTORIES(${PXL_LIBRARY_PATH}) - INCLUDE_DIRECTORIES(${PXL_INCLUDE_DIRS}) - IF(APPLE) - ADD_LIBRARY(${name} SHARED MODULE ${files}) - ELSE(APPLE) - ADD_LIBRARY(${name} SHARED ${files}) - ENDIF(APPLE) - - TARGET_LINK_LIBRARIES(${name} ${PXL_LIBRARIES}) - - SET_TARGET_PROPERTIES(${name} PROPERTIES COMPILE_FLAGS -fPIC) - INSTALL(TARGETS ${name} LIBRARY DESTINATION ${PXL_PLUGIN_INSTALL_PATH}) -ENDMACRO() - diff --git a/Python.cmake b/Python.cmake deleted file mode 100644 index 3b950b0c06a37fca1c618bdc4cd8f751ec175b63..0000000000000000000000000000000000000000 --- a/Python.cmake +++ /dev/null @@ -1,102 +0,0 @@ -# SETUP PYTHON - -# get default python inerpreter -FIND_PROGRAM( PYTHON_EXECUTABLE python REQUIRED - PATHS [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\2.7\\InstallPath] [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\2.6\\InstallPath] [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\2.5\\InstallPath] -) - -SET(PYTHONINTERP_FOUND TRUE) - -# find python include path -execute_process( - COMMAND ${PYTHON_EXECUTABLE} -c "import sys; from distutils import sysconfig; sys.stdout.write(sysconfig.get_python_inc())" - OUTPUT_VARIABLE PYTHON_INCLUDE_PATH - OUTPUT_STRIP_TRAILING_WHITESPACE -) - -FIND_FILE(PYTHON_H_FOUND Python.h PATHS ${PYTHON_INCLUDE_PATH} NO_DEFAULT_PATH) -IF(NOT PYTHON_H_FOUND) - MESSAGE(SEND_ERROR "Python.h not found") -ENDIF() - -IF(APPLE) - - # apple changed linking to Python in OS X 10.9 (Mavericks) - # until 10.8: use Python.framework as part of the SDK (-framework Python) - # since 10.9: link to Python like any other UNIX - - # extract (minor) version number from SDK name (major version always 10 for OS X) - STRING(REGEX REPLACE ".*MacOSX([0-9]+)[.]([0-9]+)[.]sdk" "\\2" OSX_SDK_MINOR_VERSION "${CMAKE_OSX_SYSROOT}" ) - - MESSAGE("${CMAKE_OSX_SYSROOT}") - MESSAGE("Found OS X SDK minor version: ${OSX_SDK_MINOR_VERSION}") - - IF(OSX_SDK_MINOR_VERSION LESS 8) - MESSAGE(STATUS "Running on Mac OS X < 10.9: Linking to Python as framework") - SET(OSX_USE_PYTHON_FRAMEWORK "True") - - INCLUDE(CMakeFindFrameworks) - # Search for the python framework on Apple. - MESSAGE(INFO "Looking for python framework as on apple system" ) - CMAKE_FIND_FRAMEWORKS(Python) - SET (PYTHON_LIBRARIES "-framework Python" CACHE FILEPATH "Python Framework" FORCE) - - ELSE(OSX_SDK_MINOR_VERSION LESS 8) - SET(OSX_USE_PYTHON_FRAMEWORK "False") - MESSAGE(STATUS "Running on Mac OS X >= 10.9: Linking to Python in UNIX default way") - - ENDIF(OSX_SDK_MINOR_VERSION LESS 8) - -ENDIF(APPLE) - -IF(MSVC) - execute_process( - COMMAND ${PYTHON_EXECUTABLE} -c "import sys; from distutils import sysconfig; import os; prefix= sysconfig.get_config_var('prefix'); ver = sysconfig.get_python_version().replace('.', ''); lib = os.path.join(prefix,'libs\\python'+ver+'.lib'); sys.stdout.write(lib)" - OUTPUT_VARIABLE PYTHON_LIBRARIES - OUTPUT_STRIP_TRAILING_WHITESPACE - ) -ENDIF(MSVC) - -IF (MINGW) - execute_process( - COMMAND ${PYTHON_EXECUTABLE} -c "import sys; from distutils import sysconfig; import os; prefix= sysconfig.get_config_var('prefix'); ver = sysconfig.get_python_version().replace('.', ''); lib = os.path.join(prefix,'libs\\libpython'+ver+'.a'); sys.stdout.write(lib)" - OUTPUT_VARIABLE PYTHON_LIBRARIES - OUTPUT_STRIP_TRAILING_WHITESPACEsysconfig.get_config_var('LIBDIR') - ) -ENDIF(MINGW) - -IF(NOT OSX_USE_PYTHON_FRAMEWORK AND NOT MSVC AND NOT MINGW) - execute_process( - COMMAND ${PYTHON_EXECUTABLE} -c "import sys; from distutils import sysconfig; import os; libname = sysconfig.get_config_var('LDLIBRARY'); libdir = sysconfig.get_config_var('LIBPL'); lib = os.path.join(libdir,libname); out = lib if os.path.exists(lib) else os.path.join(libdir, sysconfig.get_config_var('LIBRARY')); sys.stdout.write(out);" - OUTPUT_VARIABLE PYTHON_LIBRARIES - OUTPUT_STRIP_TRAILING_WHITESPACE - ) -ENDIF(NOT OSX_USE_PYTHON_FRAMEWORK AND NOT MSVC AND NOT MINGW) - -#find the site package destinaton -execute_process( - COMMAND ${PYTHON_EXECUTABLE} -c "import sys; from distutils import sysconfig; sys.stdout.write(sysconfig.get_python_lib(1,0,prefix='${CMAKE_INSTALL_PREFIX}'))" - OUTPUT_VARIABLE PYTHON_SITE_PACKAGES - OUTPUT_STRIP_TRAILING_WHITESPACE -) - -execute_process( - COMMAND ${PYTHON_EXECUTABLE} -c "import sys; sys.stdout.write(str(sys.version_info[0]))" - OUTPUT_VARIABLE PYTHON_MAJOR_VERSION - OUTPUT_STRIP_TRAILING_WHITESPACE -) - -execute_process( - COMMAND ${PYTHON_EXECUTABLE} -c "import sys; sys.stdout.write(str(sys.version_info[1]))" - OUTPUT_VARIABLE PYTHON_MINOR_VERSION - OUTPUT_STRIP_TRAILING_WHITESPACE -) - -SET(PYTHON_VERSION "${PYTHON_MAJOR_VERSION}${PYTHON_MINOR_VERSION}") -SET(PYTHON_DOT_VERSION "${PYTHON_MAJOR_VERSION}.${PYTHON_MINOR_VERSION}") - -MESSAGE(STATUS "Found Python executeable: " ${PYTHON_EXECUTABLE}) -MESSAGE(STATUS "Found Python include path: " ${PYTHON_INCLUDE_PATH}) -MESSAGE(STATUS "Found Python library: " ${PYTHON_LIBRARIES}) -MESSAGE(STATUS "Using Python site-package directory: " ${PYTHON_SITE_PACKAGES}) -MESSAGE(STATUS "Using Python Version: " ${PYTHON_DOT_VERSION} "/" ${PYTHON_VERSION}) diff --git a/README b/README deleted file mode 100644 index aaeb8fb0a7f945ee3a9c36cd0ef34ad16ac3caac..0000000000000000000000000000000000000000 --- a/README +++ /dev/null @@ -1,120 +0,0 @@ ------------------------------------------------------------------------------- - - Physics eXtension Library (PXL) - C++ Toolkit for Physics Analysis, Relation Management - and Hypothesis Evolution in High Energy and Astroparticle Physics - Copyright (C) 2006-2015 M. Erdmann - Web: https://vispa.physik.rwth-aachen.de/pxl - Contact: vispa@lists.rwth-aachen.de - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA - ------------------------------------------------------------------------------- - -### Requirements: - PXL is known to run on Linux, MacOSX and Windows. This is the source - version of PXL - if you don't want to compile PXL yourself check our - website for binary installers for your operating system. - - cmake is required to build PXL, see below. - -### Optional: - For PyPxl to work, you need Python in a version between 2.4 and 2.7. - Swig (http://www.swig.org), version >= 1.3.36, is required as well - if pxl is compiled from the repository. - - To generate documentation, doxygen is necessary. - - -### Basic installation of the stable PXL release from source - - PXL is built using CMAKE - for more information see www.cmake.org - Use - - $cmake . # or ccmake . or qcmake, or ... - - to configure and generate the Makefile and - - $make to build PXL - - For installation into /usr/local/ or your specified location type - - $make install - - Don't forget to adjust your PATH, PYTHONPATH, and LD_LIBRARY_PATH - environment variables if you decided to use a different location or - decided to not use make install at all. - - You can also generate doxygen documentation (if doxygen is available) with - - $make doc - - - -### Installation from Mercurial: - - For installation from Mercurial PXL requires: - - zlib - python, version 2.4-3.2 (not needed for core packages only) - swig, version >= 1.3.36 (not needed for core packages only) - cmake - - The latest developer version can be cloned from - - https://forge.physik.rwth-aachen.de/hg/pxl - ssh://forge.physik.rwth-aachen.de/hg/pxl - https://forge.physik.rwth-aachen.de/public-hg/pxl (read-only) - (see https://forge.physik.rwth-aachen.de/projects/pxl/repository) - - -### Installation on Mac OS X: - - The installation should work as described for Unix systems (tested - for Snow Leopard and Lion) with cmake. There are also Xcode project - files provided to compile with Xcode. - - If you are running an earlier version of Mac OS X and - the instructions above do not work, the following information - may be useful. - - You might need to install pkgconfig - (http://pkg-config.freedesktop.org/wiki/), version >= 0.9.0 (not - necessary for Lion or Snow Leopard) - - PXL does not directly support universal/fat binaries, but Xcode does - and can be used for this purpose using the provided project files. - Although not described here, similar steps should work for the power - pc architectures as well. - - Compilation and installation work as described above (cmake). - - Setting the ARCHFLAGS environmental variable may prevent warning - messages when PXL is linked against Python that comes with - earlier versions of Mac OS X. - - Choose one of the following architectures: - - - 32 bit Intel - export CXXFLAGS="-arch i386" - export ARCHFLAGS="-arch i386" - - - 64 bit Intel - export CXXFLAGS="-arch x86_64" - export ARCHFLAGS="-arch x86_64" - - - - diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b6761a06fd8b2269523afcb0de10ef689ae0b367 --- /dev/null +++ b/README.md @@ -0,0 +1,70 @@ +# Physics eXtension Library (PXL) + +C++ toolkit for physics analysis. + +Copyright (C) 2006-2019 Martin Erdmann + +Web: https://vispa.physik.rwth-aachen.de/pxl + +Contact: vispa@lists.rwth-aachen.de + + +### Requirements + +PXL is known to run on Linux, MacOSX and Windows. This is the source version of PXL - if you don't want to compile PXL yourself check our website for binary installers for your operating system. + +make is required to build PXL, see below. + + +##### Optional + +To generate the documentation, [doxygen](http://www.doxygen.org) and [breathe](https://breathe.readthedocs.io) are required. + + +### Basic installation of the stable PXL release from source + +PXL is built using CMAKE - for more information see www.cmake.org. Use + +```shell +cmake . +make +make install +``` + +Don't forget to adjust your PATH and LD_LIBRARY_PATH environment variables if you decided to use a different location or decided to not use make install at all. + +You can also generate doxygen documentation (if doxygen is available) with + +```shell +make doc +``` + + +### Authors + +Current PXL Project Managers: + +- Martin Erdmann + +Current PXL Developers: + +- Benjamin Fischer +- Yannik Rath +- Marcel Rieger + +Former PXL Developers/Advisors: + +- Oxana Actis +- Andreas Hinzmann +- Steffen Kappler (project leader) +- Matthias Kirsch +- Tatsiana Klimkovich +- Dennis Klingebiel +- Matthias Komm +- Matthias Plum +- Guenter Quast +- Christophe Saout +- Jan Steggemann +- Tobias Winchen +- Robert Fischer +- Gero Mueller diff --git a/WindowsInstaller.cmake b/WindowsInstaller.cmake deleted file mode 100644 index 6d477b107e5af3245a276cefa5dca71b7d1730e0..0000000000000000000000000000000000000000 --- a/WindowsInstaller.cmake +++ /dev/null @@ -1,26 +0,0 @@ -IF (MSVC) - GET_FILENAME_COMPONENT(WIX_INSTALL_ROOT "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows Installer XML\\3.0;InstallRoot]" ABSOLUTE CACHE) - MESSAGE(STATUS "Windows Installer XML: ${WIX_INSTALL_ROOT}") - - FIND_PROGRAM( CANDLE_EXECUTABLE candle - PATHS ${WIX_INSTALL_ROOT} - REQUIRED - ) - - FIND_PROGRAM( LIGHT_EXECUTABLE light - PATHS ${WIX_INSTALL_ROOT} - ) - - CONFIGURE_FILE(pypxl.wxs.in ${CMAKE_BINARY_DIR}/pypxl.wxs) - - add_custom_target( windows_installer_candle - ${CANDLE_EXECUTABLE} ${CMAKE_BINARY_DIR}/pypxl.wxs - DEPENDS ${CMAKE_BINARY_DIR}/pypxl.wxs - ) - add_dependencies(windows_installer_candle pxlrun pxl-modules) - - add_custom_target( windows_installer - ${LIGHT_EXECUTABLE} -ext WixUIExtension ${CMAKE_BINARY_DIR}/pypxl.wixobj -o ${CMAKE_BINARY_DIR}/PyPXL-Py${PYTHON_DOT_VERSION}-${PXLVERSION}.msi - ) - add_dependencies(windows_installer windows_installer_candle) -ENDIF(MSVC) \ No newline at end of file diff --git a/Xcode.cmake b/Xcode.cmake deleted file mode 100644 index a01f3e5266534c2318f709c804c5aa9e2564db22..0000000000000000000000000000000000000000 --- a/Xcode.cmake +++ /dev/null @@ -1,48 +0,0 @@ -# XCODE -# -# define macro to set library properties for Mac OS X -# FRAMEWORK create OS X library framework -# INSTALL_NAME_DIR value for Xcode INSTALL_PATH variable -# BUILD_WITH_INSTALL_RPATH make sure INSTALL_PATH gets set -# - -IF(APPLE AND ${CMAKE_GENERATOR} STREQUAL "Xcode") - SET(GENERATE_FOR_XCODE ON) -ELSE(APPLE AND ${CMAKE_GENERATOR} STREQUAL "Xcode") - SET(GENERATE_FOR_XCODE OFF) -ENDIF(APPLE AND ${CMAKE_GENERATOR} STREQUAL "Xcode") - -IF(GENERATE_FOR_XCODE) - OPTION(FRAMEWORK_SUPPORT "If ON shared libraries will be created as frameworks on Mac OS X" ON) - OPTION(FRAMEWORK_BUILD_WITH_INSTALL_RPATH "Sets install_name property of shared libraries on Mac OS X" ON) -ENDIF(GENERATE_FOR_XCODE) - -MACRO(SET_XCODE_FRAMEWORK_PROPERTIES name) - IF(GENERATE_FOR_XCODE) - SET_TARGET_PROPERTIES(${name} PROPERTIES - FRAMEWORK ${FRAMEWORK_SUPPORT} - XCODE_ATTRIBUTE_DYLIB_COMPATIBILITY_VERSION "${PXLMAJORRELEASEVERSION}.${PXLMINORRELEASEVERSION}" - MACOSX_FRAMEWORK_SHORT_VERSION_STRING "${PXLMAJORRELEASEVERSION}.${PXLMINORRELEASEVERSION}" - BUILD_WITH_INSTALL_RPATH ${FRAMEWORK_BUILD_WITH_INSTALL_RPATH} - INSTALL_NAME_DIR "./" - INSTALL_RPATH_USE_LINK_PATH ON) - ENDIF(GENERATE_FOR_XCODE) -ENDMACRO(SET_XCODE_FRAMEWORK_PROPERTIES name) - -# -# create universal binaries on OS X -# make sure libraries are compatible with OS X Snow Leopard (10.6) -# -IF(GENERATE_FOR_XCODE) - SET(CMAKE_OSX_ARCHITECTURES "i386;x86_64") - SET(CMAKE_OSX_SYSROOT /Developer/SDKs/MacOSX10.6.sdk) -ENDIF(GENERATE_FOR_XCODE) - -# -# display status information to user -# -MESSAGE(STATUS "GENERATE_FOR_XCODE = ${GENERATE_FOR_XCODE}") -IF(GENERATE_FOR_XCODE) - MESSAGE(STATUS "FRAMEWORK_SUPPORT = ${FRAMEWORK_SUPPORT}") - MESSAGE(STATUS "FRAMEWORK_BUILD_WITH_INSTALL_RPATH = ${FRAMEWORK_BUILD_WITH_INSTALL_RPATH}") -ENDIF(GENERATE_FOR_XCODE) \ No newline at end of file diff --git a/algorithms/CMakeLists.txt b/algorithms/CMakeLists.txt deleted file mode 100644 index ad33c8ab0b7efc30fc1a36e252adb873dcca82eb..0000000000000000000000000000000000000000 --- a/algorithms/CMakeLists.txt +++ /dev/null @@ -1,36 +0,0 @@ -# -# use local include directory -# -include_directories ( - include - ${PXL_SOURCE_DIR}/hep/include - ${PXL_SOURCE_DIR}/core/include - ${CMAKE_BINARY_DIR}/include -) - -# -# add library using the sources -# -add_library(pxl-algorithms SHARED - src/AutoLayout.cc -) - -# -# hep depends on pxl, hep and scripting -# -add_dependencies(pxl-algorithms pxl-core pxl-hep) - -# -# link to pxl, hep and scripting -# -target_link_libraries (pxl-algorithms pxl-core pxl-hep) - -# -# setup install path -# -PXL_INSTALL_LIBRARY(pxl-algorithms) - -# -# set library properties for Mac OS X -# -SET_XCODE_FRAMEWORK_PROPERTIES(pxl-algorithms) \ No newline at end of file diff --git a/algorithms/algorithms.vcproj b/algorithms/algorithms.vcproj deleted file mode 100644 index 8df1a84483b4b316f5b232068234da803660dec0..0000000000000000000000000000000000000000 --- a/algorithms/algorithms.vcproj +++ /dev/null @@ -1,210 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/algorithms/include/pxl/algorithms/AutoLayout.hh b/algorithms/include/pxl/algorithms/AutoLayout.hh deleted file mode 100644 index 05bd34587421e60e2138f6443f8d85c778ea6177..0000000000000000000000000000000000000000 --- a/algorithms/include/pxl/algorithms/AutoLayout.hh +++ /dev/null @@ -1,273 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_ALGORITHMS_AUTOLAYOUT_HH -#define PXL_ALGORITHMS_AUTOLAYOUT_HH - -#include -#include -#include -#include - -#include "pxl/core/macros.hh" - -namespace pxl { - -class PXL_DLL_EXPORT Vector2 -{ -public: - typedef double value_t; - - value_t x, y; - - Vector2() : - x(0.0), y(0.0) - { - } - Vector2(const Vector2& copy) : - x(copy.x), y(copy.y) - { - } - Vector2(value_t a, value_t b) : - x(a), y(b) - { - } - - inline Vector2 operator +(const Vector2& op) const - { - return Vector2(x + op.x, y + op.y); - } - - inline const Vector2& operator +=(const Vector2& op) - { - x += op.x; - y += op.y; - return *this; - } - - inline Vector2 operator -(const Vector2& op) const - { - return Vector2(x - op.x, y - op.y); - } - - inline const Vector2& operator -=(const Vector2& op) - { - x -= op.x; - y -= op.y; - return *this; - } - - inline Vector2 operator *(value_t op) const - { - return Vector2(x * op, y * op); - } - - inline void normalize() - { - value_t ol = 1.0/length(); - x *= ol; - y *= ol; - } - - inline void scale(value_t d) - { - value_t l = d/length(); - x *= l; - y *= l; - } - - inline Vector2 scaled(value_t d) - { - value_t l = d/length(); - return Vector2(x * l, y * l); - } - - inline Vector2 normalized() - { - value_t ol = 1.0/length(); - return Vector2(x * ol, y * ol); - } - - inline value_t length() const - { - return sqrt(x*x+y*y); - } - - inline value_t length2() const - { - return (x*x+y*y); - } - - inline void zero() - { - x = 0.0; - y = 0.0; - } - - bool parallelTo(const Vector2 &b); -}; - - -class PXL_DLL_EXPORT Line -{ -public: - Vector2 a, b; - - Line() - { - - } - - Line(const Vector2& v1, const Vector2& v2) : - a(v1), b(v2) - { - - } - - bool intersection(const Line& line, Vector2& intersection); -}; - - -class PXL_DLL_EXPORT Rect2 -{ -public: - Vector2 ll; - Vector2 ur; - - Rect2() : - ll(std::numeric_limits::max(), std::numeric_limits< - Vector2::value_t>::max()), ur(std::numeric_limits< - Vector2::value_t>::min(), - std::numeric_limits::min()) - { - - } - - Rect2(const Vector2& point) : - ll(point), ur(point) - { - - } - - void expand(const Vector2& point); - - void expand(const Rect2& rect) - { - expand(rect.ll); - expand(rect.ur); - } - - bool contains(const Vector2& point, double margin = 0) const; - - bool overlaps(const Rect2& rhs) const; -}; - -/* class Eventview -{ - std::vector view; -};*/ -class PXL_DLL_EXPORT Node -{ -public: - Vector2 velocity; - Vector2 force; - double mass; - bool active; - Rect2 rect; - bool updated; - Node* lastvisit; - - bool isMotherOf(Node *node); - bool isDaughterOf(Node *node); - void updateRect(); - - int numberchildren; - int boxednodes; - -// std::vector childrenpositionx; -// std::vector childrenpositiony; - - - - - Node(); - - Vector2 position; - std::vector mothers; - std::vector children; - bool isVertex; - -}; - -/** - algorithm for automatic layouting of decay trees - */ - -class PXL_DLL_EXPORT AutoLayout -{ - double _friction; - double _spring; - double _proximity; - double _gravity; - double _mass; - double _overlap; - int _steps; - int _levels; - -public: - std::vector allNodes; - std::vector initialNodes; - std::vector activeNodes; - std::vector orphans; - - double margin; - double grid; - double border; - - AutoLayout(); - ~AutoLayout(); - - void init(const std::vector& nodes); - void layout(bool forceBased); - void layoutSteps(); - void step(); - - void reset(); - void applyGravity(); - void applyProximityForces(); - void applySpringForce (Node* a, Node* b, double length); - void applySpringForces(); - void applyFrictionForces(); - void applyInitialConstraints(); - void resolveBackpointingChildren(); - void applyProximityForces(Node* lhs, Node* rhs); - void applyProximityForcesTree(Node* parent, Node* node); - - void resolveOverlap(Node *a1, Node *b1, Node *a2, Node *b2); - void resolveOverlaps(); - bool isStable(); - void placeInitials(); -// void commitPositions(); - void activateChildren(); - - int countChildren(Node* Node); - void layoutChildren(Node* Node, double scale); - void box(Node* Node, double scale); - bool box_resolveOverlaps(Node* Node, double scale); - bool box_resolveOverlap(Node *a1, Node *b1, Node *a2, Node *b2, double scale); - void layout_children(Node* Node); - void layout_orphans(); - - void fillNodeGrid(std::vector >& nodeGrid, Node* node, unsigned int depth); - void new_initial(); - void drawbox(); -}; - -} // namespace pxl - -#endif // PXL_AUTOLAYOUT_HH diff --git a/algorithms/pxl-algorithms.pc.in b/algorithms/pxl-algorithms.pc.in deleted file mode 100644 index 279ed03f4a74264031ea24aaed64e8d296b1d8f8..0000000000000000000000000000000000000000 --- a/algorithms/pxl-algorithms.pc.in +++ /dev/null @@ -1,12 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: PXL Algorithms -Description: Physics eXtension Library - Algorithms Classes -Version: @PXL_VERSION@ -URL: https://vispa.physik.rwth-aachen.de/pxl -Requires: pxl = @PXL_VERSION@ -Libs: -L${libdir} -lpxl-algorithms -Cflags: -I${includedir} diff --git a/algorithms/src/AutoLayout.cc b/algorithms/src/AutoLayout.cc deleted file mode 100644 index ac7389fefdf69483c9a5d463ecf13ead33a7c344..0000000000000000000000000000000000000000 --- a/algorithms/src/AutoLayout.cc +++ /dev/null @@ -1,1106 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include "pxl/algorithms/AutoLayout.hh" - -#include - -namespace pxl { - -bool Vector2::parallelTo(const Vector2 &b) -{ - if (x == 0) - { - if (b.x == 0) - return true; - else - return false; - } - - if (b.x == 0) - return false; - - if (y / x == b.y / b.x) - return true; - - return false; -} - - -bool Line::intersection(const Line& line, Vector2& intersection) -{ - Vector2 r1 = b - a; - Vector2 r2 = line.b - line.a; - Vector2 s = line.a - a; - - double t2 = (r1.x*s.y - r1.y*s.x)/ (r1.y*r2.x - r1.x*r2.y); - - double t1 = (s.x + t2 * r2.x) / r1.x; - - intersection = line.a + r2 * t2; - - if ((t1 > 0.0001) && (t1 < 0.999) && (t2 > 0.0001) && (t2 < 0.999)) - return true; - else - return false; -} - - -void Rect2::expand(const Vector2& point) -{ - ll.x = std::min(ll.x, point.x); - ll.y = std::min(ll.y, point.y); - - ur.x = std::max(ur.x, point.x); - ur.y = std::max(ur.y, point.y); -} - -bool Rect2::contains(const Vector2& point, double margin) const -{ - if (point.x < (ll.x - margin)) - return false; - if (point.y < (ll.y - margin)) - return false; - - if (point.x > (ur.x + margin)) - return false; - if (point.y > (ur.y + margin)) - return false; - - return true; -} - -bool Rect2::overlaps(const Rect2& rhs) const -{ - if (ur.x < rhs.ll.x) - return false; - - if (ur.y < rhs.ll.y) - return false; - - if (ll.x > rhs.ur.x) - return false; - - if (ll.y > rhs.ur.y) - return false; - - return true; -} - - -Node::Node() : mass(10.0) -{ -} - -AutoLayout::AutoLayout() : - _friction(0.9), _spring(0.2), _proximity(0.5), - _gravity(10.0), _mass(0.1), _overlap(10.0), _steps(400), - _levels (100000), margin(50.0), grid(100.0), border(100.) -{ -#if 1 - /* for finding cirrect values */ -/* std::ifstream file("/root/Desktop/autolayout.txt"); - file >> _friction; - file >> _spring; - file >> _proximity; - file >> _gravity; - file >> _mass; - file >> _overlap; - file >> _steps; - file >> _levels; - file >>grid; - file >>margin; - */ - -#endif -} - -AutoLayout::~AutoLayout() -{ -} - -void AutoLayout::init(const std::vector& nodes) -{ - allNodes.clear(); - initialNodes.clear(); - activeNodes.clear(); - - allNodes.resize(nodes.size()); - std::copy(nodes.begin(), nodes.end(), allNodes.begin()); - - for (std::vector::iterator i = allNodes.begin(); i != allNodes.end(); i++) - { - if ((*i)->mothers.size() == 0) - { - (*i)->active = true; - initialNodes.push_back(*i); - activeNodes.push_back(*i); - } - else - { - (*i)->active = false; - } - - } - - //while (allNodes.size() > activeNodes.size()) - //activateChildren(); -} -void Node::updateRect() -{ - if (updated) - return; - - rect = Rect2(position); - - std::vector::iterator i; - for (i = children.begin(); i != children.end(); i++) - { - if ((*i)->active == false) - continue; - - (*i)->updateRect(); - rect.expand((*i)->rect); - } - - updated = true; -} - -void AutoLayout::reset() -{ - for (std::vector::iterator i = allNodes.begin(); i != allNodes.end(); i++) - { - (*i)->force.zero(); - (*i)->updated = false; - } - - for (std::vector::iterator i = initialNodes.begin(); i != initialNodes.end(); i++) - (*i)->updateRect(); -} - -bool Node::isMotherOf(Node *node) -{ - std::vector::iterator i; - - for (i = children.begin(); i != children.end(); i++) - { - if (*i == node) - return true; - } - - return false; -} - -bool Node::isDaughterOf(Node *node) -{ - std::vector::iterator i; - - for (i = mothers.begin(); i != mothers.end(); i++) - { - if (*i == node) - return true; - } - - return false; -} - -void AutoLayout::applyGravity() -{ - std::vector::iterator i; - for (i = allNodes.begin(); i != allNodes.end(); i++) - { - (*i)->force.x += _gravity; - } -} -/* - void AutoLayout::applyProximityForces(Node* a, Node* b) - { - if (a->rect.overlaps(b->rect) == false) - return; - - for (std::vector::iterator i = initialNodes.begin(); i != initialNodes.end(); i++) - { - } - } - */ - -void AutoLayout::applyProximityForces(Node* lhs, Node* rhs) -{ - if (rhs == lhs) - return; - - Vector2 r = rhs->position - lhs->position; - double distance = r.length(); - Vector2 direction; - - if (distance < 1.0) - { - lhs->position += Vector2(0, 1); - direction = Vector2(0.0, 1); - } - else - direction = r.normalized(); - - double force = -fabs(grid - distance) * _proximity; - - if (distance < grid) - { - lhs->force.y += direction.y * force; - rhs->force.y -= direction.y * force; - } -} - -void AutoLayout::applyProximityForcesTree(Node* parent, Node* node) -{ - if (parent->rect.contains(node->position, grid) && (parent->lastvisit - != node)) - { - applyProximityForces(parent, node); - for (std::vector::iterator i = parent->children.begin(); i - != parent->children.end(); i++) - { - Node* child = *i; - if (child->active == false) - continue; - applyProximityForcesTree(child, node); - } - parent->lastvisit = node; - } -} - -void AutoLayout::applyProximityForces() -{ - for (std::vector::iterator i = allNodes.begin(); i != allNodes.end(); i++) - { - Node* node = *i; - - if (node->active == false) - continue; - - for (std::vector::iterator j = initialNodes.begin(); j - != initialNodes.end(); j++) - { - Node* initial = *j; - applyProximityForcesTree(initial, node); - } - } -} - -void AutoLayout::applySpringForce (Node* a, Node* b, double length) -{ - Vector2 r = b->position - a->position; - double distance = r.length(); - - Vector2 direction; - if (distance == 0.0) - direction = Vector2(1.0, 0.0); - else - direction = r.normalized(); - - double force = _spring * (distance - (length/2.0)); - - a->force.y += (direction * force).y; - b->force -= direction * force; -} - -void AutoLayout::applySpringForces() -{ - std::vector::iterator i; - for (i = activeNodes.begin(); i != activeNodes.end(); i++) - { - Node* mother = *i; - -// Node* sib = 0; - std::vector::iterator j; - for (j = mother->children.begin(); j != mother->children.end(); j++) - { - Node* daughter = *j; - - if (daughter->active == false) - continue; - - double range = grid; - if ((daughter->position.x - mother->position.x) > 0) - range = sqrt(grid*grid + pow(grid*(daughter->position.y - mother->position.y)/(daughter->position.x - mother->position.x), 2)); - applySpringForce (mother, daughter, range); - /* - if (sib) - applySpringForce (daughter, sib, grid); - - sib = daughter; -*/ - } - } -} - -void AutoLayout::applyFrictionForces() -{ - std::vector::iterator i; - for (i = allNodes.begin(); i != allNodes.end(); i++) - { - (*i)->force -= (*i)->velocity * _friction; - } -} - -void AutoLayout::applyInitialConstraints() -{ - std::vector::iterator i; - for (i = initialNodes.begin(); i != initialNodes.end(); i++) - { - (*i)->force.x = 0; - } -} - -void AutoLayout::step() -{ - std::vector::iterator i; - for (i = activeNodes.begin(); i != activeNodes.end(); i++) - { - (*i)->position += (*i)->velocity * 0.1; - if ((*i)->force.length() > 100.0) - (*i)->force.scale(100.0); - (*i)->velocity += (*i)->force * (0.1 / (*i)->mass); - } -} - -void AutoLayout::resolveOverlap(Node *a1, Node *b1, Node *a2, Node *b2) -{ - Line a(a1->position, b1->position); - Line b(a2->position, b2->position); - - Vector2 intersection; - if (a.intersection(b, intersection)) - { - //std::cout << "intersection: " << intersection.x << " " << intersection.y << std::endl; -/* - Vector2 v = (a1->position - b1->position - a2->position + b2->position) * _overlap; - b1->force += v; - b2->force -= v; -*/ - //b1->force += (a1->position - b1->position).scaled(_overlap); - //b2->force += (a2->position - b2->position).scaled(_overlap); - //b1->position = a1->position - (a1->position - intersection) * 0.9; - Vector2 v1 = b1->position - a1->position; - Vector2 v2 = b2->position - a2->position; - if (v1.length2() > v2.length2()) - { - v2.scale (_overlap); - b2->force -= v2; - b1->force += v2; - } - else - { - v1.scale (_overlap); - b2->force += v1; - b1->force -= v1; - } - //b1->position = intersection; - //b2->position = intersection; - } -} - -void AutoLayout::resolveOverlaps() -{ - std::vector::iterator i; - for (i = allNodes.begin(); i != allNodes.end(); i++) - { - Node *a = *i; - if (a->active == false) - continue; - - std::vector::iterator j; - for (j = a->children.begin(); j != a->children.end(); j++) - { - Node *b = *j; - - if (b->active == false) - continue; - - std::vector::iterator k = i; - for (k++; k != allNodes.end(); k++) - { - Node *c = *k; - - if (c->active == false) - continue; - - if (c->isDaughterOf(a)) - continue; - - std::vector::iterator l; - for (l = c->children.begin(); l != c->children.end(); l++) - { - Node *d = *l; - - if (d->active == false) - continue; - - resolveOverlap(a, b, c, d); - } - } - } - } -} - -void AutoLayout::resolveBackpointingChildren() -{ - for (std::vector::iterator i = allNodes.begin(); i != allNodes.end(); i++) - { - Node *mother = *i; - - if (mother->active == false) - continue; - - for (std::vector::iterator j = mother->children.begin(); j - != mother->children.end(); j++) - { - Node *daughter = *j; - - if (daughter->active == false) - continue; - - if (daughter->position.x < mother->position.x) - { - daughter->position.x = mother->position.x; - //if (daughter->velocity.x < 0) - daughter->force.x += 10; - } - } - } -} - -bool AutoLayout::isStable() -{ - std::vector::iterator i; - for (i = activeNodes.begin(); i != activeNodes.end(); i++) - { - if ((*i)->force.length() > 0.1 || (*i)->velocity.length() > 0.1) - return false; - } - - return true; -} - -void AutoLayout::placeInitials() -{ - for (std::vector::iterator i = initialNodes.begin(); i != initialNodes.end(); i++) - { - (*i)->position.x = margin; - // (*i)->position.y = 0; - } -} - - -// new algorithm -int AutoLayout::countChildren(Node* object) -{ - object->numberchildren = 0; - - if (object->children.size() != 0) - { - std::vector::iterator l; - - for (l = object->children.begin(); l != object->children.end(); l++) - { - object->numberchildren += countChildren(*l) + 1; - } - } - return object->numberchildren; -} - -void AutoLayout::layoutChildren(Node* object, double scale) -{ - box(object,1.0); - box_resolveOverlaps(object,scale); -/* - int k = 0; - std::vector::iterator j; - - for (j = object->children.begin(); j != object->children.end(); j++) - { - k = k + (*j)->boxednodes; - } - - - if (object->numberchildren != 0 && (object->children.size() + k) == object->numberchildren) - { - std::cout<<"children.size == object->numberchildren"<children.begin(); j != object->children.end(); j++) - { -// object->childrenpositionx.push_back((*j)->position.x - object->position.x); -// object->childrenpositiony.push_back((*j)->position.y - object->position.y); - } - boxes.push_back(object); - } - else - { - for (j = object->children.begin(); j != object->children.end(); j++) - { - layoutChildren((*j), scale); - } - - } - - box_resolveOverlaps(object,scale); -*/ -} - -bool cmp(Node* object1, Node* object2) -{ - return object1->children.size() > object2->children.size(); -} -bool cmp2(Node* object1, Node* object2) -{ - return object1->numberchildren > object2->numberchildren; -} - -void AutoLayout::box(Node* object, double scale) -{ - double g = grid * 0.9 ;//* 0.5*object->children.size(); - double y = g/2.0; - int n = 0; - - size_t d; - - double step = g / (object->children.size()-1); - - std::vector::iterator j; - std::vector::iterator l; - std::vector v; - std::vector w; - std::vector a; - std::vector b; - - for (j = object->children.begin(); j != object->children.end(); j++) - { - v.push_back(*j); - } - - - std::sort( v.begin(), v.end(), cmp); - - - for(d = 0; d != v.size(); d++ ) - { - if(d%2 == 0 ) - a.push_back(v[d]); - else - b.push_back(v[d]); - } - - for(d = 0; d != a.size(); d++ ) - { - w.push_back(a[d]); - } - for(d = 0; d != b.size(); d++ ) - { - w.push_back(b[b.size()-1-d]); - } - - for (j = w.begin(); j != w.end(); j++) - { - Node* child = *j; - - if (object->children.size() == 1) - child->position = object->position + Vector2(grid,0); - else - { - child->position = object->position + Vector2(grid,scale*(-y + n*step)); - n++; - } - } - - - object->boxednodes = object->numberchildren; - -} - - -bool AutoLayout::box_resolveOverlaps(Node* object, double scale) -{ - int n = 0; - bool overlap; - std::vector::iterator i; - for (i = allNodes.begin(); i != allNodes.end(); i++) - { - Node *a = *i; - std::vector::iterator j; - for (j = a->children.begin(); j != a->children.end(); j++) - { - Node *b = *j; - std::vector::iterator k = i; - for (k++; k != allNodes.end(); k++) - { - Node *c = *k; - - if (c->isDaughterOf(a)) - continue; - - std::vector::iterator l; - for (l = c->children.begin(); l != c->children.end(); l++) - { - Node *d = *l; - overlap = box_resolveOverlap(a, b, c, d, scale); - - - do - { - overlap = box_resolveOverlap(a, b, c, d, scale*(1+n*0.03)); - n++; - -// std::cout << "Overlap= "<< overlap << std::endl; -// std::cout << "n= "<< n << std::endl; - -// return true; -// break; - } - while (overlap == true );//&& n!= 500); - - if(overlap == true) - { -// box_resolveOverlaps(object, 1.5*scale); - } - - } - } - - } - } - return false; -} -bool AutoLayout::box_resolveOverlap(Node *a1, Node *b1, Node *a2, Node *b2, double scale) -{ - Line a(a1->position, b1->position); - Line b(a2->position, b2->position); - - Vector2 intersection; - if (a.intersection(b, intersection)) - { - std::vector::iterator i; - std::vector::iterator j; - - for (i = allNodes.begin(); i != allNodes.end(); i++) - { - - Node *c = *i; - - if (c->isMotherOf(a1)) - { - box(c, scale*1.2); - layout_children(c); - return true; - } - } - - } - - - return false; -} -void AutoLayout::layout_children(Node* object) -{ - std::vector::iterator j; - for (j = object->children.begin(); j != object->children.end(); j++) - { - box(*j, 1); - if((*j)->children.size() != 0) - { - layout_children(*j); - } - } -} - -void AutoLayout::fillNodeGrid(std::vector >& nodeGrid, Node* node, unsigned int depth) -{ - // create vector if not present yet - if (nodeGrid.size() <= depth) - { - nodeGrid.push_back(std::vector()); - } - - // fill current node (if not present yet) - - if (std::find(nodeGrid[depth].begin(), nodeGrid[depth].end(), node) == nodeGrid[depth].end()) - nodeGrid[depth].push_back(node); - - depth++; - - //loop over daughters and fill those - for (std::vector::iterator child = node->children.begin(); child != node->children.end(); ++child) - { - fillNodeGrid(nodeGrid, *child, depth); - } - - depth--; -} - -/// Initial layout -void AutoLayout::new_initial() -{ - std::vector > nodeGrid; - - // fill the node grid - for (std::vector::iterator i = allNodes.begin(); i != allNodes.end(); i++) - { - // start at all nodes without mothers and with daughters - if ((*i)->mothers.size()==0 && (*i)->children.size() > 0 ) - { - if ( ! ( (*i)->children.size() == 1 && (*i)->children[0]->children.size() == 0) ) - fillNodeGrid(nodeGrid, *i, 0); - } - } - - if (nodeGrid.size()==0) - return; - - // find longest row - size_t index_lr = 0; - size_t maxSize=0; - - for (size_t n_x = 0; n_x < nodeGrid.size(); ++n_x) - { - size_t size = nodeGrid[n_x].size(); - if (size > maxSize) - { - maxSize = size; - index_lr = n_x; - } - } - - grid = grid * (1/(1+sqrt(0.1*((double) maxSize)))); - - // layout longest row - for (unsigned int n_y = 0; n_y < nodeGrid[index_lr].size(); ++n_y) - { - Node* currentNode = nodeGrid[index_lr][n_y]; - currentNode->position.x = margin + 2. * margin * ((double) index_lr); - // add safety margin according to size of sum of remaining daughter rows - currentNode->position.y = grid * ((double) n_y + ((double) nodeGrid.size()-index_lr)/2. ) + border; - } - - // layout mother rows, beginning at previous row - for (size_t n_x = index_lr-1; n_x < nodeGrid.size(); --n_x) - { - double previous_y = -grid; - for (unsigned int n_y = 0; n_y < nodeGrid[n_x].size(); ++n_y) - { - Node* currentNode = nodeGrid[n_x][n_y]; - currentNode->position.x = margin + 2. * margin * ((double) n_x); - - double mean_y_daughters = 0.; - size_t n_mothers = 1; - for (size_t n_child = 0; n_child < currentNode->children.size(); ++n_child) - { - mean_y_daughters += currentNode->children[n_child]->position.y; - if (currentNode->children[n_child]->mothers.size()>1) - n_mothers = currentNode->children[n_child]->mothers.size(); - } - mean_y_daughters = mean_y_daughters / ((double) currentNode->children.size()); - - //place mother at mean y position of all daughters, but at least one grid below previous one - previous_y = std::max( std::max(0., previous_y + grid - 0.00001), mean_y_daughters + ((1. - (double) n_mothers)/2.)*grid ); // simple double-rounding protection - - currentNode->position.y = previous_y; - } - } - - // layout children rows, beginning at next row - for (size_t n_x = index_lr+1; n_x < nodeGrid.size(); ++n_x) - { - double previous_y = -grid; - for (unsigned int n_y = 0; n_y < nodeGrid[n_x].size(); ++n_y) - { - Node* currentNode = nodeGrid[n_x][n_y]; - currentNode->position.x = margin + 2. * margin * ((double) n_x); - - double mean_y_mothers = 0.; - size_t n_sisters = 0; - // normally, only one mother should be present - for (size_t n_mother = 0; n_mother < currentNode->mothers.size(); ++n_mother) - { - mean_y_mothers += currentNode->mothers[n_mother]->position.y; - n_sisters += currentNode->mothers[n_mother]->children.size(); - } - if (currentNode->mothers.size() > 0) - n_sisters = n_sisters/currentNode->mothers.size(); - if (currentNode->mothers.size() > 0) - mean_y_mothers = mean_y_mothers / ((double) currentNode->mothers.size()); - - //place 1st daughter 1/2 (or 1/n_chilren) grid position above mean y position of all mothers, but at least one grid below previous one - previous_y = std::max( std::max(0., previous_y + grid - 0.00001), mean_y_mothers + ((1. -(double) n_sisters)/2.)*grid ); // simple double-rounding protection - currentNode->position.y = previous_y; - } - } - -/* - for (std::vector::iterator i = allNodes.begin(); i != allNodes.end(); i++) - { - countChildren(*i); - (*i)->boxednodes = 0; - } - - for (unsigned int n = 0 ; n != 1; n++) - { - for (std::vector::iterator i = allNodes.begin(); i != allNodes.end(); i++) - { - (*i)->active = true; - } - - std::sort( allNodes.begin(), allNodes.end(), cmp2); - - - layoutChildren(allNodes[0+n], 1.0); - } -*/ -} - -void AutoLayout::drawbox() -{ -} - -void AutoLayout::layout_orphans() -{ - double bottom = border; - std::vector::iterator j; - - double max_y = -99999999999999.; - - for (j = allNodes.begin(); j != allNodes.end(); j++) - { - -/* if ((*j)->position.y > bottom) - { - bottom = (*j)->position.y; - } -*/ - if ((*j)->children.size() == 1 && (*j)->mothers.size() == 0) - { - if ((*j)->children[0]->children.size() == 0) - { - orphans.push_back(*j); - } - } - else - { - if ((*j)->children.size() == 0 && (*j)->mothers.size() == 1) - if ((*j)->mothers[0]->mothers.size()==0) - continue; - if ((*j)->position.y > max_y) - max_y = (*j)->position.y; - } - } - - bottom += max_y; - - int columns = (int)std::ceil(std::sqrt(orphans.size()/2.0)); - int col = 0; - std::vector::iterator i; - - for (i = orphans.begin(); i != orphans.end(); i++) - { - (*i)->position.x = (margin + (col * 2 * margin)); - (*i)->position.y = (bottom); - (*i)->children[0]->position.x = (margin + (col * 2 * margin)) + 70; - (*i)->children[0]->position.y = (bottom); - col ++; - - if (col == columns) - { - bottom += margin; - col = 0; - } - } - -} -// End new algorithm - -void AutoLayout::activateChildren() -{ - -// int n = 1, m = 1; - std::vector v; - - std::vector::iterator i; - - for (i = allNodes.begin(); i != allNodes.end(); i++) - { - //v.push_back(*i); - countChildren(*i); - - } - for (i = allNodes.begin(); i != allNodes.end(); i++) - { - //Node* node2 = *i; - //v.push_back(*i); - } - - - for (i = activeNodes.begin(); i != activeNodes.end(); i++) - { - Node* node = *i; - double g = grid * 0.9; - double y = -g/2.0; - - const double step = g / node->children.size(); - - if (node->children.size() == 0) - y = 0.0; - - std::vector::iterator j; - - - for (j = node->children.begin(); j != node->children.end(); j++) - { - y += step; - Node* child = *j; - - if (child->active == false) - { - child->active = true; - - v.push_back(*j); - - - /* - if (child->numberchildren > 3) - { - - child->position = node->position + Vector2(grid, (50/m)*y*pow(-1,n)); - n++; - m++; -// std::cout<< countChildren(*j) << std::endl; - - } - else - */ - child->position = node->position + Vector2(grid, y); - - - - } - } - - } - - activeNodes.clear(); - for (i = allNodes.begin(); i != allNodes.end(); i++) - { - - - if ((*i)->active) - activeNodes.push_back(*i); - } - - - _levels --; -} - - - -void AutoLayout::layoutSteps() -{ - for (int i = 0; i < _steps; i++) - { - reset(); - resolveOverlaps(); - //resolveBackpointingChildren(); - applyGravity(); - applyProximityForces(); - applyFrictionForces(); - applySpringForces(); - applyInitialConstraints(); - step(); - - if (isStable()) - { - if (activeNodes.size() == allNodes.size()) - { - //std::cout << "all nodes stable: " << allNodes.size() << ", activeNodes: " << activeNodes.size() << std::endl; - break; - } - else - { - //std::cout << "all nodes activate: " << allNodes.size() << ", activeNodes: " << activeNodes.size() << std::endl; - activateChildren(); - i = 0; - } - } - else if (i == (_steps-1) && (activeNodes.size() != allNodes.size()) && (_levels >= 0)) - { - i = 0; - //std::cout << "all nodes: " << allNodes.size() << ", activeNodes: " << activeNodes.size() << std::endl; - activateChildren(); - } - } - -} -void AutoLayout::layout(bool forceBased) -{ - if (forceBased) - { - placeInitials(); - layoutSteps(); - layout_orphans(); - } - else - { - new_initial(); - layout_orphans(); - } - -} - -/* -void AutoLayout::commitPositions() -{ - double offset = 1.0e32; - - std::vector::iterator i; - - for (i = allNodes.begin(); i != allNodes.end(); i++) - { - if ((*i)->position.y < offset) - offset = (*i)->position.y; - } - - double bottom = 0; - for (i = allNodes.begin(); i != allNodes.end(); i++) - { - (*i)->commitPositions(margin - offset); - double y = (*i)->position.y + margin - offset; - if (y > bottom) - bottom = y; - } - - // layout orphans - bottom += margin; - int columns = (int)std::ceil(std::sqrt(orphans.size()/2.0)); - int col = 0; - std::vector::iterator j; - for (j = orphans.begin(); j != orphans.end(); j++) - { - pxl::Relative *object = *j; - object->layout()->setA(margin + (col * 2 * margin)); - object->layout()->setB(bottom); - object->layout()->setC(margin + (col * 2 * margin + margin)); - object->layout()->setD(bottom); - - col ++; - - if (col == columns) - { - bottom += margin; - col = 0; - } - } -} -*/ - -} // namespace pxl diff --git a/astro/CMakeLists.txt b/astro/CMakeLists.txt deleted file mode 100644 index 66ab6d6944538ea39be648321b7df93c267c1516..0000000000000000000000000000000000000000 --- a/astro/CMakeLists.txt +++ /dev/null @@ -1,64 +0,0 @@ -# -# use local include directory -# -include_directories ( - include - ${PXL_SOURCE_DIR}/core/include - ${CMAKE_BINARY_DIR}/include -) - -# -# add library using the sources -# -add_library (pxl-astro SHARED - src/Astro.cc - src/AstroBasicObject.cc - src/AstroObject.cc - src/RegionOfInterest.cc - src/UHECR.cc - src/UHECRSource.cc - src/CoordinateTransformations.cc -) - - -# -# astro depends only on pxl core -# -add_dependencies(pxl-astro pxl-core) - -# -# link to pxl -# -target_link_libraries (pxl-astro pxl-core) - -# -# setup install path -# -PXL_INSTALL_LIBRARY(pxl-astro) - - -# -# set library properties for Mac OS X -# -SET_XCODE_FRAMEWORK_PROPERTIES(pxl-astro) - - -# -# pxl-healpix includes the healpix part, which is under GPL -# -OPTION(USE_HEALPIX "Build the healpix library, which is under GPL" TRUE) - -if (USE_HEALPIX) - add_library (pxl-healpix SHARED - src/Healpix.cc - src/HealpixMap.cc - ) - add_dependencies(pxl-healpix pxl-astro pxl-core) - target_link_libraries (pxl-healpix pxl-astro pxl-core) - - PXL_INSTALL_LIBRARY(pxl-healpix) - SET_XCODE_FRAMEWORK_PROPERTIES(pxl-healpix) -endif(USE_HEALPIX) - - - diff --git a/astro/astro.vcproj b/astro/astro.vcproj deleted file mode 100644 index e5593889b9a7effa7b479534cc38ac23af8b01c2..0000000000000000000000000000000000000000 --- a/astro/astro.vcproj +++ /dev/null @@ -1,237 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/astro/include/pxl/astro.hh b/astro/include/pxl/astro.hh deleted file mode 100644 index 02d366a92a3abf77be4edfd293ec6cfc5f64dd72..0000000000000000000000000000000000000000 --- a/astro/include/pxl/astro.hh +++ /dev/null @@ -1,21 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef astro_hh -#define astro_hh - -#include "pxl/astro/Astro.hh" -#include "pxl/astro/AstroBasicObject.hh" -#include "pxl/astro/AstroObject.hh" -#include "pxl/astro/UHECR.hh" -#include "pxl/astro/RegionOfInterest.hh" -#include "pxl/astro/UHECRSource.hh" -#include "pxl/astro/CoordinateTransformations.hh" - -#endif // ----- #ifndef ASTRO_INC ----- - diff --git a/astro/include/pxl/astro/AstroBasicObject.hh b/astro/include/pxl/astro/AstroBasicObject.hh deleted file mode 100644 index 6351ffbe2bbc494b7b080beb6f8398bd8c713a6f..0000000000000000000000000000000000000000 --- a/astro/include/pxl/astro/AstroBasicObject.hh +++ /dev/null @@ -1,234 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_ASTRO_ASTRO_BASIC_OBJECT_HH -#define PXL_ASTRO_ASTRO_BASIC_OBJECT_HH -#include "pxl/core/macros.hh" - -#include "pxl/core/Basic3Vector.hh" -#include "pxl/core/Serializable.hh" -#include "pxl/core/ObjectFactory.hh" -#include "pxl/core/Id.hh" -#include "pxl/astro/CoordinateTransformations.hh" - -namespace pxl -{ -class BasicContainer; - -/** - This Class contains basic astrophysical objects, observed at a - direction at a given time. The direction is stored as a vector with 3 - comonents in galactic coordinates, using longitude (-pi..pi) and - latitude (-pi/2 .. pi/2). Equatorial Coordinates are calculated on the - fly and returned as right ascension (-pi..pi) and declination (-pi/2 - .. pi/2). - */ -class PXL_DLL_EXPORT AstroBasicObject : public Serializable -{ -public: - AstroBasicObject() : Serializable(), _time(0),_vector(1,0,0),_dAngularResolution(0),_dDummy(0) - { - } - - AstroBasicObject(double longitude, double latitude) : Serializable(), _time(0),_vector(1,0,0),_dAngularResolution(0),_dDummy(0) - { - setGalacticCoordinates(longitude,latitude); - } - - AstroBasicObject(const Basic3Vector& vector) : Serializable(), _time(0),_vector(vector),_dAngularResolution(0),_dDummy(0) - { - } - - - AstroBasicObject(const AstroBasicObject& original) : - Serializable(), _time(original._time), - _vector(original._vector),_dAngularResolution(original._dAngularResolution), _dDummy(original._dDummy) - { - } - - explicit AstroBasicObject(const AstroBasicObject* original) : - Serializable(), _time(original->_time), - _vector(original->_vector),_dAngularResolution(original->_dAngularResolution), _dDummy(original->_dDummy) - { - } - - virtual ~AstroBasicObject() - { - } - - - /// Prints out some information about the AstroBasicObject - virtual std::ostream& print(int level=1, std::ostream& os=std::cout, int pan=1) const; - - /// Set position in galactic corrdinates - void setGalacticCoordinates(double longitude,double latitude); - - void setSuperGalacticCoordinates(double longitude,double latitude); - - /// Set position in equatorial coordinates - void setEquatorialCoordinates(double ra,double d, CoordinateTransformations::Epoque_T epoque=CoordinateTransformations::J2000); - - void setEquatorialCoordinates( unsigned int hours, unsigned int minutes, double seconds, - int degree, int moa, double soa, CoordinateTransformations::Epoque_T epoque); - - /// Sets an error for the angular resolution - inline void setAngularResolution(double value) - { - _dAngularResolution = value; - } - - /// returns the error on the longitude - inline double getAngularResolution() - { - return _dAngularResolution; - } - - ///Sets a time asoziated with the observation in Unix time format - inline void setTime(const time_t &time) - { - _time = time; - } - - ///Returns the Declination - double getRightAscension(CoordinateTransformations::Epoque_T epoque=CoordinateTransformations::J2000) const; - - ///Returns the Declination - double getDeclination(CoordinateTransformations::Epoque_T epoque=CoordinateTransformations::J2000) const; - - ///Returns the longitude in super galactic coordinates - double getSuperGalacticLongitude() const; - - ///Returns the latitude in super galactic coordinates - double getSuperGalacticLatitude() const; - - ///Returns the longitude in galactic coordinates - double getGalacticLongitude() const; - - ///Returns the latitude in galactic coordinates - double getGalacticLatitude() const; - - ///Sets the components of the direction of the object - void setSuperGalacticXYZ(double x, double y, double z) - { - Basic3Vector v(x,y,z); - v.normalize(); - setSuperGalacticDirectionVector(v); - } - - ///Sets the components of the direction of the object - void setEquatorialXYZ(double x, double y, double z) - { - Basic3Vector v(x,y,z); - v.normalize(); - setEquatorialDirectionVector(v); - } - - ///Sets the components of the direction of the object - void setGalacticXYZ(double x, double y, double z) - { - _vector.setXYZ(x,y,z); - //normalize vector - _vector.normalize(); - } - - ///Sets the direction vector of the object in Galactic Coordinates - void setGalacticDirectionVector(const Basic3Vector& vector) - { - _vector = vector; - _vector/=sqrt(_vector*_vector); - } - - ///Returns the 3component Vector of the direction of the object in - ///galactic cordinates - inline const Basic3Vector& getGalacticDirectionVector() const - { - return _vector; - } - - ///Sets the direction vector of the object in super galactic coordinates - inline void setSuperGalacticDirectionVector(const Basic3Vector& vector) - { - _vector = vector; - _vector = CoordinateTransformations::convertSuperGalactic2Galactic(_vector); - _vector/=sqrt(_vector*_vector); - } - - ///Returns the 3component Vector of the direction of the object in - ///super galactic coordinates - inline Basic3Vector getSuperGalacticDirectionVector() const - { - Basic3Vector _result = CoordinateTransformations::convertGalactic2SuperGalactic(_vector); - return _result; - } - - - ///Sets the direction vector of the object in equatorial coordinates - inline void setEquatorialDirectionVector(const Basic3Vector& vector) - { - _vector = vector; - _vector = CoordinateTransformations::convertEquatorial2Galactic(_vector); - _vector/=sqrt(_vector*_vector); - } - - ///Returns the 3component Vector of the direction of the object in - ///equatorial coordinates - inline Basic3Vector getEquatorialDirectionVector() const - { - Basic3Vector _result = CoordinateTransformations::convertGalactic2Equatorial(_vector); - return _result; - } - - - ///Returns a UNIX time assoziated witnh the object - inline time_t getTime() const - { - return _time; - } - - /// Returns the angular distance to given object - double angularDistanceTo(const AstroBasicObject &obj) const; - /// - double angularDistanceTo(const Basic3Vector &obj) const; - /// Returns the angular distance to given object - double angularDistanceTo(const AstroBasicObject *obj) const; - - /// Returns the Type Id of the Serializable derivative - virtual const Id& getTypeId() const - { - return getStaticTypeId(); - } - - /// Returns the Type Id of the Serializable derivative - static const Id& getStaticTypeId() - { - static const Id id("033dfe86-1a17-767a-8dd9-2877496dab5f"); - return id; - } - - /// Serializes the Object - virtual void serialize(const OutputStream &out) const; - - /// Deserializes the Object - virtual void deserialize(const InputStream &in); - - /// Creates a deep copy and returns a C++ pointer to the newly-created object. - virtual Serializable* clone() const - { - return new AstroBasicObject(*this); - } - -private: - time_t _time; /// A UNIX time asoziated with the obhject - Basic3Vector _vector; /// The direction of the Object - double _dAngularResolution; /// Angluar error - double _dDummy; /// Currently not used double, not removed due to compatibility -}; - -} - -#endif // ----- #ifndef ASTROBASICOBJECT_INC ----- diff --git a/astro/include/pxl/astro/AstroObject.hh b/astro/include/pxl/astro/AstroObject.hh deleted file mode 100644 index c2e59aa092590d05454e7198775b184317c2cd9f..0000000000000000000000000000000000000000 --- a/astro/include/pxl/astro/AstroObject.hh +++ /dev/null @@ -1,126 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_ASTRO_ASTRO_OBJECT_HH -#define PXL_ASTRO_ASTRO_OBJECT_HH -#include "pxl/core/macros.hh" - -#include "pxl/core/UserRecord.hh" -#include "pxl/core/SoftRelations.hh" -#include "pxl/astro/AstroBasicObject.hh" - -namespace pxl -{ -/** - AstroBasicObject with UserRecord and SoftRelations. - */ - -class PXL_DLL_EXPORT AstroObject : public AstroBasicObject, public UserRecordHelper -{ -public: - AstroObject() : AstroBasicObject() - { - } - - /// Copy constructor. SoftRelations are not copied since they only exist - /// between individual objects - AstroObject(const AstroObject& original) : - AstroBasicObject(original), UserRecordHelper(original) - { - } - - /// Copy constructor. SoftRelations are not copied since they only exist - /// between individual objects - explicit AstroObject(const AstroObject* original) : - AstroBasicObject(original), UserRecordHelper(*original) - { - - } - - AstroObject(const AstroBasicObject& original) : - AstroBasicObject(original) - { - } - - explicit AstroObject(const AstroBasicObject* original) : - AstroBasicObject(original) - { - } - - AstroObject(double longitude, double latitude) : AstroBasicObject(longitude, latitude) - { - } - - AstroObject(const Basic3Vector& vector) : AstroBasicObject(vector) - { - } - - - virtual ~AstroObject() - { - } - - virtual void serialize(const OutputStream &out) const; - - virtual void deserialize(const InputStream &in); - - ///returns the type id of the AstroObject - virtual const Id& getTypeId() const - { - return getStaticTypeId(); - } - - ///returns the type id of the AstroObject - static const Id& getStaticTypeId() - { - static const Id id("115a29d6-ecfe-37bc-b647-937d49705165"); - return id; - } - - /// Creates a deep copy and returns a C++ pointer to the newly-created object. - virtual Serializable* clone() const - { - return new AstroObject(*this); - } - - /// Create a bi-directional softlink between two astroobjects - void linkSoft(AstroObject* astroobject, const std::string& type); - /// Create a bi-directional softlink between two astroobjects - void linkSoft(AstroObject& astroobject, const std::string& type); - - ///Removes the Softlink from the object - void unlinkSoft(AstroObject* astroobject, const std::string& type); - ///Removes the Softlink from the object - void unlinkSoft(AstroObject& astroobject, const std::string& type); - - ///Returns the Soft relations of the object - const SoftRelations& getSoftRelations() const - { - return _softRelations; - } - - ///Returns the Soft relations of the object - SoftRelations& getSoftRelations() - { - return _softRelations; - } - - -private: - SoftRelations _softRelations; - - // Make AstroObject private since it's not clear how copied - // SoftRelations should be managed - AstroObject& operator=(const AstroObject& original) - { - return *this; - } -}; - -} -#endif diff --git a/astro/include/pxl/astro/CoordinateTransformations.hh b/astro/include/pxl/astro/CoordinateTransformations.hh deleted file mode 100644 index 15b8e1129d0ce46f125e7074753184e4affd43f2..0000000000000000000000000000000000000000 --- a/astro/include/pxl/astro/CoordinateTransformations.hh +++ /dev/null @@ -1,56 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_ASTRO_COORDINATETRANSFORMATIONS_HH -#define PXL_ASTRO_COORDINATETRANSFORMATIONS_HH -#include "pxl/core/macros.hh" - -#include -#include -#include "pxl/core/Basic3Vector.hh" -#include "pxl/core/BasicMatrix.hh" -namespace pxl -{ -/// Implements various transformations for astronomical coordinates -class PXL_DLL_EXPORT CoordinateTransformations -{ -private: - ///Rotation matrices for conversion - static double _R1950[9]; - static double _R2000[9]; - static double _SG[9]; - -public: - enum Epoque_T - { - J1950, J2000 - }; - - /// Rotates the direction given by vec from Galactic coordinates to equatorial coordinates - static Basic3Vector convertGalactic2Equatorial(const Basic3Vector& vec, - Epoque_T epoque = J2000); - static Basic3Vector convertEquatorial2Galactic(const Basic3Vector& vec, - Epoque_T epoque = J2000); - - static Basic3Vector convertSuperGalactic2Equatorial(const Basic3Vector& vec, - Epoque_T epoque = J2000); - static Basic3Vector convertEquatorial2SuperGalactic(const Basic3Vector& vec, - Epoque_T epoque = J2000); - - static Basic3Vector convertGalactic2SuperGalactic(const Basic3Vector& vec); - - static Basic3Vector convertSuperGalactic2Galactic(const Basic3Vector& vec); - static double timeAngle2Radian(unsigned int hours, unsigned int minutes, - double seconds); - static double minutesOfArc2Radian(int degree, int minutes, double seconds); - -}; -} - -#endif - diff --git a/astro/include/pxl/astro/Healpix.hh b/astro/include/pxl/astro/Healpix.hh deleted file mode 100644 index d194a42a4e0b8d087f9ae6adc67e0f832bf5a2e9..0000000000000000000000000000000000000000 --- a/astro/include/pxl/astro/Healpix.hh +++ /dev/null @@ -1,26 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a GPL-2 or later license - -//------------------------------------------- - -#ifndef INITIALIZE_HEALPIX_HH -#define INITIALIZE_HEALPIX_HH - -#include "pxl/core/macros.hh" - -namespace pxl -{ -class PXL_DLL_EXPORT Healpix -{ -public: - static void initialize(); - static void shutdown(); - -}; - -} - -#endif /* INITIALIZE_HEALPIX_HH_*/ diff --git a/astro/include/pxl/astro/HealpixMap.hh b/astro/include/pxl/astro/HealpixMap.hh deleted file mode 100644 index 527b11733433c95b574a7ec10d3163054969dd7c..0000000000000000000000000000000000000000 --- a/astro/include/pxl/astro/HealpixMap.hh +++ /dev/null @@ -1,206 +0,0 @@ -// HealpixMap.hh, 12.06.10 -// -// This defines the class HealPixMap which provides a very -// basic Hierarchical Equal Area isoLatitude Pixelization (HEALPIX) of a -// sphere, based on the original NASA implementation which is available -// on http://healpix.jpl.nasa.gov. -// -// This part of PXL is published unter the GNU GPL v3 as it is based on NASA -// Healpix, which is published under the GNU GPL v2. It therefore cannot -// be combined with PXL without making the resulting license GPL. -// -// This 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 3 of the License, or -// (at your option) any later version. -// -// This Software 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 software; if not, write to the Free Software -// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -// - -#ifndef PXL_ASTRO_HEALPIXMAP_HH -#define PXL_ASTRO_HEALPIXMAP_HH -#include "pxl/core/macros.hh" - -#include -#include -#include -#include -#include "pxl/core/macros.hh" -#include "pxl/core/Basic3Vector.hh" -#include "pxl/core/BasicNVector.hh" -#include "pxl/core/UserRecord.hh" - -namespace pxl -{ - -class PXL_DLL_EXPORT HealpixMap : public BasicNVector, public UserRecordHelper -{ -public: - - HealpixMap() : BasicNVector(), _order(0), _npix(0), _ncap(0), _nside(0), _npface(0), _fact1(0), _fact2(0) - { - _calculateInternalConstants(); - this->setSize(_npix); - } - - HealpixMap(const HealpixMap& original) : BasicNVector(original), UserRecordHelper(original), _order(original._order), - _npix(original._npix), _ncap(original._ncap), _nside(original._nside), _npface(original._npface), - _fact1(original._fact1), _fact2(original._fact2) - { - } - - explicit HealpixMap(const HealpixMap* original) : BasicNVector(original), UserRecordHelper(*original), _order(original->_order), - _npix(original->_npix), _ncap(original->_ncap), _nside(original->_nside), _npface(original->_npface), - _fact1(original->_fact1), _fact2(original->_fact2) - { - } - - /// Creates a deep copy and returns a C++ pointer to the newly-created object. - virtual Serializable* clone() const - { - return new HealpixMap(*this); - } - - HealpixMap(int order); - - void serialize(const OutputStream &out) const; - void deserialize(const InputStream &in); - - ///returns the type id of the HealpixMap - virtual const Id& getTypeId() const - { - return getStaticTypeId(); - } - - ///returns the type id of the AstroObject - static const Id& getStaticTypeId() - { - // 9ffee9f7-942d-d259-ea98-6ddd0001f549 was used as Id before - // Octobre 2013. The numbering system was changed between the two - // versions; it is now compatible with healpy. - static const Id id("58488649-3229-4c28-a024-f01a8038cd5d"); - return id; - } - - int getOrder() const - { - return _order; - } - - int getNumberOfPixels() const - { - return _npix; - } - - static int getNumberOfPixels(unsigned int i); - - /// Returns pixelnumber of pixel - int vector2Pixel (const Basic3Vector &vec) const; - - /// Get pixelnumbers of neighbors - void getNeighbors(int pix, std::vector &result) const; - - /// Returns Pixels in a cone around Basic3Vector with radius r - this - /// is the equivalent to healpixbase query_disc - void getPixelsInCone(const Basic3Vector& coneCenter, double radius, std::vector& listpix) const; - - /// returns a vector pointing to center of the given pixel - Basic3Vector pixel2Vector(int pixel) const; - - /// sets Vector if pixels match - void setVector(const BasicNVector &v) - { - if (v.getSize() != _npix) - throw std::runtime_error("Vector size doesnt match number of pixels"); - BasicNVector::operator=(v); - } - - inline const HealpixMap& operator+=(const HealpixMap& vec) - { - BasicNVector::operator+=(vec); return *this; - } - - inline const HealpixMap& operator-=(const HealpixMap& vec) - { - BasicNVector::operator-=(vec); return *this; - } - - HealpixMap operator-(const HealpixMap&) const; - HealpixMap operator+(const HealpixMap&) const; - - const HealpixMap& operator*=(double skalar) - { - BasicNVector::operator*=(skalar); return *this; - }; - const HealpixMap& operator/=(double skalar) - { - BasicNVector::operator/=(skalar); return *this; - }; - -private: - unsigned int _order; // The Healpix Order (Sometimes refered to as _NSide) - int _npix; // The number of pixels - int _ncap; - int _nside; - int _npface; - double _fact1; - double _fact2; - void _calculateInternalConstants(); - - // needed for neighbor calculation - void ring2xyf (int pix, int &ix, int &iy, int &face_num) const; - int xyf2ring (int ix, int iy, int face_num) const; - - // Returns the remainder of the division v1/v2. - // The result is non-negative. - // v1 can be positive or negative; v2 must be positive. - double fmodulo (double v1, double v2) const - { - return (v1>=0) ? ((v1 I imodulo (I v1, I v2) const - { return (v1>=0) ? ((v1 unsigned int isqrt (I arg) const - { - using namespace std; - if (sizeof(I)<=4) - return unsigned (sqrt(arg+0.5)); - long double arg2 = arg; - return unsigned (sqrt(arg2+0.5)); - } - - // Returns atan2(y,x) if x!=0 or y!=0; else returns 0. - double safe_atan2 (double y, double x) const - { - using namespace std; - return ((x==0.) && (y==0.)) ? 0.0 : atan2(y,x); - } - - // Returns the largest integer which is smaller than (or equal to) arg. - template I ifloor (F arg) const - { - return (arg>=0) ? I(arg) : I(arg)-1; - } - - void in_ring(int iz, double phi0, double dphi, std::vector &listir) const; - - int ring_above (double z) const; - -}; - -} - -#endif diff --git a/astro/include/pxl/astro/RegionOfInterest.hh b/astro/include/pxl/astro/RegionOfInterest.hh deleted file mode 100644 index 126f2473637bd5115bf1c914f7744f3167d9b02e..0000000000000000000000000000000000000000 --- a/astro/include/pxl/astro/RegionOfInterest.hh +++ /dev/null @@ -1,138 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_ASTRO_REGION_OF_INTEREST_HH -#define PXL_ASTRO_REGION_OF_INTEREST_HH -#include "pxl/core/macros.hh" - -#include "pxl/astro/AstroObject.hh" -#include -#include - -namespace pxl -{ -/** - RegionOfInterest are interesting regions in the sky, which can be - named and related to other AstroObjects with SoftRelations. The region - is defined by a cone center, the position of the RegionOfInterest, and - an angular distance,i.e. the "radius" of the cone. - */ - -class PXL_DLL_EXPORT RegionOfInterest: public AstroObject -{ -public: - - RegionOfInterest() : AstroObject(), _coneRadius(0.0), _name("ROI") - { - } - - RegionOfInterest(const RegionOfInterest& original) : - AstroObject(original), _coneRadius(original._coneRadius), _name(original._name) - { - } - - explicit RegionOfInterest(const RegionOfInterest* original) : - AstroObject(original), _coneRadius(original->_coneRadius), _name(original->_name) - { - } - - RegionOfInterest(const AstroBasicObject& original,double coneRadius=0.0, std::string name="ROI") : - AstroObject(original), _coneRadius(coneRadius), _name(name) - { - } - - explicit RegionOfInterest(const AstroBasicObject* original, double coneRadius=0.0, const std::string &name = "ROI") : - AstroObject(original), _coneRadius(coneRadius), _name(name) - { - } - - RegionOfInterest(double longitude, double latitude, double coneRadius=0.0, const std::string &name= "ROI") : AstroObject(longitude, latitude), _coneRadius(coneRadius), _name(name) - { - } - - RegionOfInterest(const Basic3Vector& vector, double coneRadius=0.0, const std::string &name= "ROI") : AstroObject(vector), _coneRadius(coneRadius), _name(name) - { - } - - virtual ~RegionOfInterest() - { - } - - virtual void serialize(const OutputStream &out) const; - - virtual void deserialize(const InputStream &in); - - virtual const Id& getTypeId() const - { - return getStaticTypeId(); - } - - static const Id& getStaticTypeId() - { - static const Id id("201e9d8b-561a-c349-bb65997c49e757a6"); - return id; - } - - /// Creates a deep copy and returns a C++ pointer to the newly-created object. - virtual Serializable* clone() const - { - return new RegionOfInterest(*this); - } - - /// Prints out some information about the Region Of Interst - virtual std::ostream& print(int level=1, std::ostream& os=std::cout, int pan=1) const; - - ///Returns the size of the RegionOfInterest - inline double getConeRadius() const - { - return _coneRadius; - } - - ///Returns the name of the region of interest - inline std::string getName() const - { - return _name; - } - - /// Sets the size of the region of interest - inline void setConeRadius(double coneRadius) - { - _coneRadius= coneRadius; - } - - ///Names the region of interest - inline void setName(std::string name) - { - _name = name; - } - - /// Return value is true, if the object is within the cone radius - bool objectInCone(const AstroBasicObject& obj) const; - /// Return value is true, if the object is nearer than the cone radius - bool objectInCone(const AstroBasicObject* obj) const; - - /// Creates a soft link between the RegionOfInterest, if the object is - /// nearer than the cone size of the RegionOfInterest - bool linkIfObjectInCone(AstroObject& obj,std::string name="") ; - /// Creates a soft link between the RegionOfInterest, if the object is - /// nearer than the cone size of the RegionOfInterest - bool linkIfObjectInCone(AstroObject* obj,std::string name="") ; - -private: - double _coneRadius; /// The Cone Size of the ROI - std::string _name; /// The name of the ROI - - RegionOfInterest& operator=(const RegionOfInterest& original) - { - return *this; - } -}; -} -//namespace pxl - -#endif diff --git a/astro/include/pxl/astro/UHECR.hh b/astro/include/pxl/astro/UHECR.hh deleted file mode 100644 index 0e7ce06d6a374ce73c40ec03feb0561f831e5a2d..0000000000000000000000000000000000000000 --- a/astro/include/pxl/astro/UHECR.hh +++ /dev/null @@ -1,131 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_ASTRO_UHECR_HH -#define PXL_ASTRO_UHECR_HH -#include "pxl/core/macros.hh" - -#include "pxl/astro/AstroObject.hh" -#include - -namespace pxl -{ -/** - A class for Ultra-High-Energy Cosmic Rays, with energy, mass and charge - */ - -class PXL_DLL_EXPORT UHECR : public AstroObject -{ -public: - - UHECR() : AstroObject(), _energy(0.), _denergy(0.), _mass(0.), _charge(0.) - { - } - - UHECR(const UHECR& original) : - AstroObject(original), _energy(original._energy), _denergy(original._denergy), _mass(original._mass), _charge(original._charge) - { - } - - explicit UHECR(const UHECR* original) : - AstroObject(original), _energy(original->_energy), _denergy(original->_denergy), _mass(original->_mass), _charge(original->_charge) - { - } - - UHECR(double longitude, double latitude, double energy=0.) : AstroObject(longitude, latitude), _energy(energy) - { - } - - UHECR(const Basic3Vector& vector, double energy=0.) : AstroObject(vector), _energy(energy) - { - } - - - virtual ~UHECR() - { - } - - virtual void serialize(const OutputStream &out) const; - - virtual void deserialize(const InputStream &in); - - virtual const Id& getTypeId() const - { - return getStaticTypeId(); - } - - static const Id& getStaticTypeId() - { - static const Id id("a4d8433f-fa90-06e9-9c28-8d784974c1f9"); - return id; - } - - /// Creates a deep copy and returns a C++ pointer to the newly-created object. - virtual Serializable* clone() const - { - return new UHECR(*this); - } - - /// Prints out some information about the CR - virtual std::ostream& print(int level=1, std::ostream& os=std::cout, int pan=1) const; - - inline double getEnergyError() const - { - return _denergy; - } - - inline double getEnergy() const - { - return _energy; - } - - inline double getCharge() const - { - return _charge; - } - - inline double getMass() const - { - return _mass; - } - - inline void setEnergy(double energy) - { - _energy= energy; - } - - inline void setEnergyError(double denergy) - { - _denergy= denergy; - } - - inline void setMass(double mass) - { - _mass = mass; - } - - inline void setCharge(double charge) - { - _charge = charge; - } - -private: - double _energy; - double _denergy; - double _mass; - double _charge; - - UHECR& operator=(const UHECR& original) - { - return *this; - } -}; -} -//namespace pxl - -#endif diff --git a/astro/include/pxl/astro/UHECRSource.hh b/astro/include/pxl/astro/UHECRSource.hh deleted file mode 100644 index b2f305664100675bc94615a4fc0b9964d8aaf3e5..0000000000000000000000000000000000000000 --- a/astro/include/pxl/astro/UHECRSource.hh +++ /dev/null @@ -1,145 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_ASTRO_SOURCE_HH -#define PXL_ASTRO_SOURCE_HH -#include "pxl/core/macros.hh" - -#include "pxl/astro/AstroObject.hh" -#include -#include - -namespace pxl -{ -/** - UHECRSource are objects in the sky, which can be - named and related to other AstroObjects with SoftRelations,but have a distance and a luminosity - */ - -class PXL_DLL_EXPORT UHECRSource: public AstroObject -{ -public: - - UHECRSource() : AstroObject(), _luminosity(1.0), _distance(1.0), _name("Source") - { - } - - UHECRSource(const UHECRSource& original) : - AstroObject(original), _luminosity(original._luminosity), _distance(original._distance), - _name(original._name) - { - } - - explicit UHECRSource(const UHECRSource* original) : - AstroObject(original),_luminosity(original->_luminosity), _distance(original->_distance), - _name(original->_name) - { - } - - UHECRSource(double longitude, double latitude, double distance=1., double luminosity=1.) : AstroObject(longitude, latitude), _luminosity(luminosity), _distance(distance), _name("Source") - { - } - - UHECRSource(const Basic3Vector& vector, double distance=1., double luminosity=1.) : AstroObject(vector), _luminosity(luminosity), _distance(distance), _name("Source") - { - } - - virtual ~UHECRSource() - { - } - - virtual void serialize(const OutputStream &out) const; - - virtual void deserialize(const InputStream &in); - - virtual const Id& getTypeId() const - { - return getStaticTypeId(); - } - - static const Id& getStaticTypeId() - { - static const Id id("0855b033-8b1a-c7e0-c816e0044b041bff"); - return id; - } - - /// Creates a deep copy and returns a C++ pointer to the newly-created object. - virtual Serializable* clone() const - { - return new UHECRSource(*this); - } - - /// Prints out some information about the CR - virtual std::ostream& print(int level=1, std::ostream& os=std::cout, int pan=1) const; - - inline double getLuminosity() const - { - return _luminosity; - } - - inline double getDistance() const - { - return _distance; - } - - inline std::string getName() const - { - return _name; - } - - inline void setDistance(double distance) - { - _distance = distance; - } - - inline void setLuminosity(double luminosity) - { - _luminosity = luminosity; - } - - void setName(std::string name) - { - _name = name; - } - - void setGalacticXYZ(double x, double y, double z) - { - AstroBasicObject::setGalacticXYZ(x,y,z); - //Set Distance - _distance = sqrt(x*x + y*y + z*z); - } - - void setSuperGalacticXYZ(double x, double y, double z) - { - AstroBasicObject::setSuperGalacticXYZ(x,y,z); - //Set Distance - _distance = sqrt(x*x + y*y + z*z); - } - - void setEquatorialXYZ(double x, double y, double z) - { - AstroBasicObject::setEquatorialXYZ(x,y,z); - //Set Distance - _distance = sqrt(x*x + y*y + z*z); - } - - -private: - double _luminosity; - double _distance; - std::string _name; - - UHECRSource& operator=(const UHECRSource& original) - { - return *this; - } -}; -} -//namespace pxl - -#endif diff --git a/astro/include/pxl/healpix.hh b/astro/include/pxl/healpix.hh deleted file mode 100644 index d9b8e22c3989030db01c239e5f644bb2b27d2353..0000000000000000000000000000000000000000 --- a/astro/include/pxl/healpix.hh +++ /dev/null @@ -1,16 +0,0 @@ - //------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef healpix_hh -#define healpix_hh - -#include "pxl/astro/Healpix.hh" -#include "pxl/astro/HealpixMap.hh" - -#endif // ----- #ifndef healpix_hh - diff --git a/astro/pxl-astro.pc.in b/astro/pxl-astro.pc.in deleted file mode 100644 index 5897db7cfe6833297b463a1dc46d36089bdd4471..0000000000000000000000000000000000000000 --- a/astro/pxl-astro.pc.in +++ /dev/null @@ -1,12 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: PXL Astro -Description: Physics eXtension Library - Astro Classes -Version: @PXL_VERSION@ -URL: https://vispa.physik.rwth-aachen.de/pxl -Requires: pxl-core = @PXL_VERSION@ -Libs: -L${libdir} -lpxl-astro -Cflags: -I${includedir} diff --git a/astro/pxl-healpix.pc.in b/astro/pxl-healpix.pc.in deleted file mode 100644 index 397de0a11bec20da82498b1324e8d37e6ea4f841..0000000000000000000000000000000000000000 --- a/astro/pxl-healpix.pc.in +++ /dev/null @@ -1,12 +0,0 @@ -prefix=@prefix@ -exec_prefix=@exec_prefix@ -libdir=@libdir@ -includedir=@includedir@ - -Name: PXL Healpix -Description: Physics eXtension Library - Healpix -Version: @PXL_VERSION@ -URL: https://vispa.physik.rwth-aachen.de/pxl -Requires: pxl-core = @PXL_VERSION@, pxl-astro = @PXL_VERSION@ -Libs: -L${libdir} -lpxl-astro -lpxl-healpix -Cflags: -I${includedir} diff --git a/astro/src/Astro.cc b/astro/src/Astro.cc deleted file mode 100644 index c4a6866251786b90640d9e6cadbf8805a56a8fe9..0000000000000000000000000000000000000000 --- a/astro/src/Astro.cc +++ /dev/null @@ -1,51 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include "pxl/core.hh" -#include "pxl/astro.hh" - -namespace pxl -{ - -static bool _initialized = false; - -static ObjectProducerTemplate _AstroBasicObjectProducer; -static ObjectProducerTemplate _AstroObjectProducer; -static ObjectProducerTemplate _RegionOfInterestProducer; -static ObjectProducerTemplate _UHECRProducer; -static ObjectProducerTemplate _UHECRSourceProducer; - -void Astro::initialize() -{ - if (_initialized) - return; - - _AstroBasicObjectProducer.initialize(); - _AstroObjectProducer.initialize(); - _RegionOfInterestProducer.initialize(); - _UHECRProducer.initialize(); - _UHECRSourceProducer.initialize(); - - _initialized = true; -} - -void Astro::shutdown() -{ - if (_initialized == false) - return; - - _AstroBasicObjectProducer.shutdown(); - _AstroObjectProducer.shutdown(); - _RegionOfInterestProducer.shutdown(); - _UHECRProducer.shutdown(); - _UHECRSourceProducer.shutdown(); - - _initialized = false; -} - -} // namespace pxl diff --git a/astro/src/AstroBasicObject.cc b/astro/src/AstroBasicObject.cc deleted file mode 100644 index f6b6e92496484c0255bd9fa30c1bbc30776800f9..0000000000000000000000000000000000000000 --- a/astro/src/AstroBasicObject.cc +++ /dev/null @@ -1,136 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include "pxl/astro/AstroBasicObject.hh" -#include -namespace pxl -{ - - - void AstroBasicObject::serialize(const OutputStream &out) const - { - Serializable::serialize(out); - _vector.serialize(out); - out.writeDouble(_dAngularResolution); - out.writeDouble(_dDummy); - out.writeLong((long)_time); - } - - void AstroBasicObject::deserialize(const InputStream &in) - { - Serializable::deserialize(in); - _vector.deserialize(in); - in.readDouble(_dAngularResolution); - in.readDouble(_dDummy); - long t; - in.readLong(t); - _time = t; - } - - std::ostream& AstroBasicObject::print(int level, std::ostream& os, int pan) const - { - os << " Galactic Latitude : " << getGalacticLatitude() << std::endl; - os << "Galactic Longitude : " << getGalacticLongitude() << std::endl; - return os; - } - - - void AstroBasicObject::setGalacticCoordinates(double longitude,double latitude) - { - _vector.setX(cos(longitude) * cos(latitude)); - _vector.setY(sin(longitude) * cos(latitude)); - _vector.setZ(sin(latitude)); - // normalize vector! - _vector/=sqrt(_vector*_vector); - } - - - void AstroBasicObject::setEquatorialCoordinates( - unsigned int hours, unsigned int minutes, double seconds, - int degree, int moa, double soa, - CoordinateTransformations::Epoque_T epoque) - { - setEquatorialCoordinates( - CoordinateTransformations::timeAngle2Radian(hours, minutes, seconds), - CoordinateTransformations::minutesOfArc2Radian(degree,moa,soa), - epoque); - } - - void AstroBasicObject::setEquatorialCoordinates(double rightascension, double declination, CoordinateTransformations::Epoque_T epoque) - { - _vector.setX(cos(rightascension) * cos(declination)); - _vector.setY(sin(rightascension) * cos(declination)); - _vector.setZ(sin(declination)); - _vector = CoordinateTransformations::convertEquatorial2Galactic(_vector); - _vector/=sqrt(_vector*_vector); - } - - double AstroBasicObject::getRightAscension(CoordinateTransformations::Epoque_T epoque) const - { - Basic3Vector t = CoordinateTransformations::convertGalactic2Equatorial(_vector, epoque); - double ra = atan2(t.getY(),t.getX()); - // RightAscension si between 0 and 2*pi - if (ra < 0) - ra+=2*M_PI; - return ra; - - } - -void AstroBasicObject::setSuperGalacticCoordinates(double longitude,double latitude) - { - _vector.setX(cos(longitude) * cos(latitude)); - _vector.setY(sin(longitude) * cos(latitude)); - _vector.setZ(sin(latitude)); - _vector = CoordinateTransformations::convertSuperGalactic2Galactic(_vector); - _vector/=sqrt(_vector*_vector); - } - - double AstroBasicObject::getDeclination(CoordinateTransformations::Epoque_T epoque) const - { - Basic3Vector t = CoordinateTransformations::convertGalactic2Equatorial(_vector, epoque); - return asin(t.getZ()/sqrt(t*t)); - } - - double AstroBasicObject::getSuperGalacticLongitude() const - { - Basic3Vector t = CoordinateTransformations::convertGalactic2SuperGalactic(_vector); - return atan2(t.getY(),t.getX()); - } - - double AstroBasicObject::getSuperGalacticLatitude() const - { - Basic3Vector t = CoordinateTransformations::convertGalactic2SuperGalactic(_vector); - return asin(t.getZ()/sqrt(t*t)); - } - - double AstroBasicObject::getGalacticLongitude() const - { - return atan2(_vector.getY(),_vector.getX()); - } - - double AstroBasicObject::getGalacticLatitude() const - { - return asin(_vector.getZ()); - } - - double AstroBasicObject::angularDistanceTo(const AstroBasicObject &obj) const - { - return angularDistanceTo(obj._vector); - } - - double AstroBasicObject::angularDistanceTo(const Basic3Vector &obj) const - { - return _vector.getAngleTo(obj); - } - - double AstroBasicObject::angularDistanceTo(const AstroBasicObject *obj) const - { - return angularDistanceTo(obj->_vector); - } - -} diff --git a/astro/src/AstroObject.cc b/astro/src/AstroObject.cc deleted file mode 100644 index 61902bfe931987586a9c69d97aa4a144338cc84d..0000000000000000000000000000000000000000 --- a/astro/src/AstroObject.cc +++ /dev/null @@ -1,57 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include "pxl/astro/AstroObject.hh" - -namespace pxl -{ - - -void AstroObject::serialize(const OutputStream &out) const -{ - AstroBasicObject::serialize(out); - UserRecordHelper::serialize(out); - _softRelations.serialize(out); -} - -void AstroObject::deserialize(const InputStream &in) -{ - AstroBasicObject::deserialize(in); - UserRecordHelper::deserialize(in); - _softRelations.deserialize(in); -} - -void AstroObject::linkSoft(AstroObject* astroobject, const std::string& type) -{ - if (!_softRelations.has(astroobject, type)) - { - _softRelations.set(astroobject, type); - astroobject->linkSoft(this, type); - } -} - -void AstroObject::unlinkSoft(AstroObject* astroobject, const std::string& type) -{ - _softRelations.remove(astroobject, type); - astroobject->_softRelations.remove(this, type); -} - -void AstroObject::linkSoft(AstroObject &astroobject, const std::string& type) -{ - linkSoft(&astroobject, type); -} - -void AstroObject::unlinkSoft(AstroObject &astroobject, const std::string& type) -{ - unlinkSoft(&astroobject, type); -} - - - - -} diff --git a/astro/src/CoordinateTransformations.cc b/astro/src/CoordinateTransformations.cc deleted file mode 100644 index e7deaa029bef5dfa7c4ee749cbcbe913cb1c6d0c..0000000000000000000000000000000000000000 --- a/astro/src/CoordinateTransformations.cc +++ /dev/null @@ -1,119 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include "pxl/astro/CoordinateTransformations.hh" -namespace pxl -{ - -// Rotation matrices for conversion x_galactic = R * x_equatorial, -// with R in Epoque 1950 or 2000, according to: -// Murray, C.A., 1989. The transformation of coordinates between -// systems of B1950.0 and J2000.0 and the principal galactic axes -// referred to J2000.0, Astron. Astrophys, 218, p.325-329 -// http://adsabs.harvard.edu/abs/1989A&A...218..325M -double CoordinateTransformations::_R1950[] = -{ -0.066988739, -0.872755766, -0.483538915, +0.492728466, -0.450346958, - 0.744584633, -0.867600811, -0.188374602, 0.460199785 }; -double CoordinateTransformations::_R2000[] = -{ -0.054875539, -0.873437105, -0.483834992, +0.494109454, -0.444829594, - 0.746982249, -0.867666136, -0.198076390, 0.455983795 }; - -// Rotation matrix for conversion x_supergalactic = R * x_galactic, -// is calculated as described in the appendix of -// John L. Tonry et. al., 2000, The Surface Brightness Fluctuation Survey of Galaxy Distances. II. Local and Large-Scale Flows, doi: 10.1086/308409, The Astrophysical Journal -// http://iopscience.iop.org/0004-637X/530/2/625 -double CoordinateTransformations::_SG[] = -{ -0.73574257480437488, +0.67726129641389432, +0.0000000000000000, - -0.07455377836523376, -0.08099147130697673, +0.9939225903997749, - +0.67314530210920764, +0.73127116581696450, +0.1100812622247821 }; - -Basic3Vector CoordinateTransformations::convertGalactic2Equatorial(const Basic3Vector& vec, - Epoque_T epoque) -{ - BasicMatrix R; - R.setColumnBasedStorage(); - if (epoque == J1950) - { - R.use(3, 3, _R1950); - } - else if (epoque == J2000) - { - R.use(3, 3, _R2000); - } - - Basic3Vector out = R * vec; - return out; -} - -Basic3Vector CoordinateTransformations::convertEquatorial2Galactic(const Basic3Vector& vec, - Epoque_T epoque) -{ - BasicMatrix R; - R.setRowBasedStorage(); - if (epoque == J1950) - { - R.use(3, 3, _R1950); - } - else if (epoque == J2000) - { - R.use(3, 3, _R2000); - } - - Basic3Vector out = R * vec; - return out; -} - -Basic3Vector CoordinateTransformations::convertEquatorial2SuperGalactic(const Basic3Vector& vec, - Epoque_T epoque) -{ - Basic3Vector vt = CoordinateTransformations::convertEquatorial2Galactic(vec, epoque); - return CoordinateTransformations::convertGalactic2SuperGalactic(vt); -} - - -Basic3Vector CoordinateTransformations::convertSuperGalactic2Equatorial(const Basic3Vector& vec, - Epoque_T epoque ) -{ - Basic3Vector vt = CoordinateTransformations::convertSuperGalactic2Galactic(vec); - return CoordinateTransformations::convertGalactic2Equatorial(vt, epoque); -} - - -Basic3Vector CoordinateTransformations::convertGalactic2SuperGalactic(const Basic3Vector& vec) -{ - BasicMatrix R; - R.setRowBasedStorage(); - R.use(3, 3, _SG); - Basic3Vector out = R * vec; - return out; -} - -Basic3Vector CoordinateTransformations::convertSuperGalactic2Galactic(const Basic3Vector& vec) -{ - BasicMatrix R; - R.setColumnBasedStorage(); - R.use(3, 3, _SG); - Basic3Vector out = R * vec; - return out; -} - -double CoordinateTransformations::timeAngle2Radian(unsigned int hours, unsigned int minutes, - double seconds) -{ - return (1. / 12. * hours + 1. / 720. * minutes + 1 / 43200. * seconds) - * M_PI; - -} -double CoordinateTransformations:: minutesOfArc2Radian(int degree, int minutes, double seconds) -{ - double s = (degree < 0 ? -1. : 1.); - return s * (std::abs(degree) + 1. / 60 * minutes + 1. / 3600 * seconds) - / 180. * M_PI; -} -} - diff --git a/astro/src/Healpix.cc b/astro/src/Healpix.cc deleted file mode 100644 index 59b966110b1be5edded24fb445b386d5a26eff59..0000000000000000000000000000000000000000 --- a/astro/src/Healpix.cc +++ /dev/null @@ -1,40 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a GPL-2 or later license - -//------------------------------------------- - -#include "pxl/core.hh" -#include "pxl/astro/Healpix.hh" -#include "pxl/healpix.hh" - -namespace pxl -{ - -static bool _initialized = false; - -static ObjectProducerTemplate _HealpixMapProducer; - -void Healpix::initialize() -{ - if (_initialized) - return; - - _HealpixMapProducer.initialize(); - - _initialized = true; -} - -void Healpix::shutdown() -{ - if (_initialized == false) - return; - - _HealpixMapProducer.shutdown(); - - _initialized = false; -} - -} // namespace pxl diff --git a/astro/src/HealpixMap.cc b/astro/src/HealpixMap.cc deleted file mode 100644 index 7e22645a9aa6c06ae885eec9213e451e1a343ed8..0000000000000000000000000000000000000000 --- a/astro/src/HealpixMap.cc +++ /dev/null @@ -1,454 +0,0 @@ -#include "pxl/astro/HealpixMap.hh" - -namespace pxl -{ -void HealpixMap::_calculateInternalConstants() -{ - _nside = 1<<_order; // _nside = 2**order - _npface = _nside << _order; // _nside * 2**order == nside**2 - _ncap = (_npface-_nside)<<1; //(nside**2-nside) * 2**1 - _npix = 12*_npface; - _fact2 = 4./_npix; - _fact1 = (_nside<<1)*_fact2; // 2*nside * fact2 -} - -int HealpixMap::getNumberOfPixels(unsigned int order) -{ - int nside = 1<setSize(_npix); -} // HealpixMap - -void HealpixMap::serialize(const OutputStream &out) const -{ - BasicNVector::serialize(out); - UserRecordHelper::serialize(out); - out.writeUnsignedInt(_order); -} - -void HealpixMap::deserialize(const InputStream &in) -{ - BasicNVector::deserialize(in); - UserRecordHelper::deserialize(in); - in.readUnsignedInt(_order); - _calculateInternalConstants(); -} - -int HealpixMap::vector2Pixel (const Basic3Vector &vec) const -{ - double z = vec.getZ()/sqrt(vec*vec); - double phi = safe_atan2(vec.getY(),vec.getX()); - - double za = std::fabs(z); - double tt = fmodulo(phi,2*M_PI) * 2/M_PI; // in [0,4) - - if (za<=2./3.) // Equatorial region - { - double temp1 = _nside*(0.5+tt); - double temp2 = _nside*z*0.75; - int jp = int(temp1-temp2); // index of ascending edge line - int jm = int(temp1+temp2); // index of descending edge line - - // ring number counted from z=2/3 - int ir = _nside+ 1 + jp - jm; // in {1,2n+1} - int kshift = 1-(ir&1); // kshift=1 if ir even, 0 otherwise - - int ip = (jp+jm- _nside+kshift+1)/2; // in {0,4n-1} - ip = imodulo(ip,4* _nside); - - return _ncap + (ir-1)*4* _nside+ ip; - } - else // North & South polar caps - { - double tp = tt-int(tt); - double tmp = _nside*sqrt(3*(1-za)); - - int jp = int(tp*tmp); // increasing edge line index - int jm = int((1.0-tp)*tmp); // decreasing edge line index - - int ir = jp+jm+1; // ring number counted from the closest pole - int ip = int(tt*ir); // in {0,4*ir-1} - ip = imodulo(ip,4*ir); - - if (z>0) - { - return 2*ir*(ir-1) + ip; - } - else - { - return _npix - 2*ir*(ir+1) + ip; - } - } -} // vector2Pixel - - -void HealpixMap::getNeighbors(int pix, std::vector &result) const -{ - result.resize(8); - static const int xoffset[] = { -1,-1, 0, 1, 1, 1, 0,-1 }; - static const int yoffset[] = { 0, 1, 1, 1, 0,-1,-1,-1 }; - static const int facearray[][12] = - { { 8, 9,10,11,-1,-1,-1,-1,10,11, 8, 9 }, // S - { 5, 6, 7, 4, 8, 9,10,11, 9,10,11, 8 }, // SE - { -1,-1,-1,-1, 5, 6, 7, 4,-1,-1,-1,-1 }, // E - { 4, 5, 6, 7,11, 8, 9,10,11, 8, 9,10 }, // SW - { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11 }, // center - { 1, 2, 3, 0, 0, 1, 2, 3, 5, 6, 7, 4 }, // NE - { -1,-1,-1,-1, 7, 4, 5, 6,-1,-1,-1,-1 }, // W - { 3, 0, 1, 2, 3, 0, 1, 2, 4, 5, 6, 7 }, // NW - { 2, 3, 0, 1,-1,-1,-1,-1, 0, 1, 2, 3 } }; // N - static const int swaparray[][12] = - { { 0,0,0,0,0,0,0,0,3,3,3,3 }, // S - { 0,0,0,0,0,0,0,0,6,6,6,6 }, // SE - { 0,0,0,0,0,0,0,0,0,0,0,0 }, // E - { 0,0,0,0,0,0,0,0,5,5,5,5 }, // SW - { 0,0,0,0,0,0,0,0,0,0,0,0 }, // center - { 5,5,5,5,0,0,0,0,0,0,0,0 }, // NE - { 0,0,0,0,0,0,0,0,0,0,0,0 }, // W - { 6,6,6,6,0,0,0,0,0,0,0,0 }, // NW - { 3,3,3,3,0,0,0,0,0,0,0,0 } }; // N - - int ix, iy, face_num; - // We only have the ring scheme! - //(scheme_==RING) ? - // ring2xyf(pix,ix,iy,face_num) : nest2xyf(pix,ix,iy,face_num); - ring2xyf(pix,ix,iy,face_num); - - // Some undecipherable math happens here - const int nsm1 = _nside-1; - if ((ix>0)&&(ix0)&&(iy=_nside) - { x-=_nside; nbnum+=1; } - if (y<0) - { y+=_nside; nbnum-=3; } - else if (y>=_nside) - { y-=_nside; nbnum+=3; } - - int f = facearray[nbnum][face_num]; - if (f>=0) - { - if (swaparray[nbnum][face_num]&1) x=_nside-x-1; - if (swaparray[nbnum][face_num]&2) y=_nside-y-1; - if (swaparray[nbnum][face_num]&4) std::swap(x,y); - - result[i] = xyf2ring(x,y,f); - } - else - result[i] = -1; - } - } -} // neighbors - - -void HealpixMap::getPixelsInCone(const Basic3Vector& coneCenter, double radius, std::vector& listpix) const -{ - double phi = safe_atan2(coneCenter.getY(),coneCenter.getX()); - double theta = acos(coneCenter.getZ()); - listpix.clear(); - - double dth1 = _fact2; - double dth2 = _fact1; - double cosang = cos(radius); - - double z0 = cos(theta); - double xa = 1./sqrt((1-z0)*(1+z0)); - - double rlat1 = theta - radius; - double zmax = cos(rlat1); - int irmin = ring_above (zmax)+1; - - if (rlat1<=0) // north pole in the disc - for (int m=1; m=M_PI) - {// south pole in the disc - for (int m=irmax+1; m<(4*_nside); ++m) - { // rings completely in the disc - in_ring (m, 0, M_PI, listpix); - } - } -} // getPixelsInCone - - -Basic3Vector HealpixMap::pixel2Vector(int pixel) const -{ - double z, phi; - - if (pixel<_ncap) // North Polar cap - { - int iring = int(0.5*(1+isqrt(1+2*pixel))); //counted from North pole - int iphi = (pixel+1) - 2*iring*(iring-1); - - z = 1.0 - (iring*iring)*_fact2; - phi = (iphi-0.5) * M_PI/2/iring; - } - else if (pixel<(_npix-_ncap)) // Equatorial region - { - int ip = pixel - _ncap; - int iring = ip/(4*_nside) + _nside; // counted from North pole - int iphi = ip%(4*_nside) + 1; - // 1 if iring+nside is odd, 1/2 otherwise - double fodd = ((iring+_nside)&1) ? 1 : 0.5; - - int nl2 = 2*_nside; - z = (nl2-iring)*_fact1; - phi = (iphi-fodd) * M_PI/nl2; - } - else // South Polar cap - { - int ip = _npix - pixel; - int iring = int(0.5*(1+isqrt(2*ip-1))); //counted from South pole - int iphi = 4*iring + 1 - (ip - 2*iring*(iring-1)); - - z = -1.0 + (iring*iring)*_fact2; - phi = (iphi-0.5) * M_PI/2/iring; - } - - Basic3Vector res; - double sintheta = sqrt((1.-z)*(1.+z)); - res.setX(sintheta*cos(phi)); - res.setY(sintheta*sin(phi)); - res.setZ(z); - return res; -} // pix2vec - - -void HealpixMap::ring2xyf (int pix, int &ix, int &iy, int &face_num) const -{ - static const int jrll[] = { 2,2,2,2,3,3,3,3,4,4,4,4 }; - static const int jpll[] = { 1,3,5,7,0,2,4,6,1,3,5,7 }; - - int iring, iphi, kshift, nr; - - int nl2 = 2*_nside; - - if (pix<_ncap) // North Polar cap - { - iring = int(0.5*(1+isqrt(1+2*pix))); //counted from North pole - iphi = (pix+1) - 2*iring*(iring-1); - kshift = 0; - nr = iring; - face_num=0; - int tmp = iphi-1; - if (tmp>=(2*iring)) - { - face_num=2; - tmp-=2*iring; - } - if (tmp>=iring) ++face_num; - } - else if (pix<(_npix-_ncap)) // Equatorial region - { - int ip = pix - _ncap; - iring = (ip>>(_order+2)) + _nside; // counted from North pole - iphi = (ip&(4*_nside-1)) + 1; - kshift = (iring+_nside)&1; - nr = _nside; - unsigned int ire = iring-_nside+1; - unsigned int irm = nl2+2-ire; - int ifm, ifp; - ifm = (iphi - ire/2 + _nside -1) >> _order; - ifp = (iphi - irm/2 + _nside -1) >> _order; - - if (ifp == ifm) // faces 4 to 7 - face_num = (ifp==4) ? 4 : ifp+4; - else if (ifp=(2*nr)) - { - face_num=10; - tmp-=2*nr; - } - if (tmp>=nr) ++face_num; - } - - int irt = iring - (jrll[face_num]*_nside) + 1; - int ipt = 2*iphi- jpll[face_num]*nr - kshift -1; - if (ipt>=nl2) ipt-=8*_nside; - - ix = (ipt-irt) >>1; - iy =(-(ipt+irt))>>1; -} //ring2xyf - - -int HealpixMap::xyf2ring (int ix, int iy, int face_num) const -{ - - static const int jrll[] = { 2,2,2,2,3,3,3,3,4,4,4,4 }; - static const int jpll[] = { 1,3,5,7,0,2,4,6,1,3,5,7 }; - - int nl4 = 4*_nside; - int jr = (jrll[face_num]*_nside) - ix - iy - 1; - - int nr, kshift, n_before; - if (jr<_nside) - { - nr = jr; - n_before = 2*nr*(nr-1); - kshift = 0; - } - else if (jr > 3*_nside) - { - nr = nl4-jr; - n_before = _npix - 2*(nr+1)*nr; - kshift = 0; - } - else - { - nr = _nside; - n_before = _ncap + (jr-_nside)*nl4; - kshift = (jr-_nside)&1; - } - - int jp = (jpll[face_num]*nr + ix - iy + 1 + kshift) / 2; - if (jp>nl4) - jp-=nl4; - else - if (jp<1) jp+=nl4; - - return n_before + jp - 1; -} //xyf2ring - - -void HealpixMap::in_ring(int iz, double phi0, double dphi, std::vector &listir) const -{ - int nr, ir, ipix1; - double shift=0.5; - - if (iz<_nside) // north pole - { - ir = iz; - nr = ir*4; - ipix1 = 2*ir*(ir-1);// lowest pixel number in the ring - } - else if (iz>(3*_nside)) // south pole - { - ir = 4*_nside - iz; - nr = ir*4; - ipix1 = _npix - 2*ir*(ir+1); // lowest pixel number in the ring - } - else // equatorial region - { - ir = iz - _nside + 1; // within {1, 2*nside + 1} - nr = _nside*4; - if ((ir&1)==0) shift = 0; - ipix1 = _ncap + (ir-1)*nr; // lowest pixel number in the ring - } - int ipix2 = ipix1 + nr - 1;// highest pixel number in the ring - - - // ----------- constructs the pixel list -------------- - if (dphi > (M_PI-1e-7)) - { - for (int i=ipix1; i<=ipix2; ++i) - { - listir.push_back(i); - } - } - else - { - int ip_lo = ifloor(nr*0.5 / M_PI*(phi0-dphi) - shift)+1; - int ip_hi = ifloor(nr*0.5 / M_PI*(phi0+dphi) - shift); - int pixnum = ip_lo+ipix1; - if (pixnumipix2) - { - pixnum -= nr; - } - listir.push_back(pixnum); - } - } -} // end ring - - -int HealpixMap::ring_above (double z) const -{ - double az=std::fabs(z); - if (az>2./3) // polar caps - { - int iring = int(_nside*sqrt(3*(1-az))); - return (z>0) ? iring : 4*_nside-iring-1; - } - else // ----- equatorial region --------- - return int(_nside*(2-1.5*z)); -} - -HealpixMap HealpixMap::operator-(const HealpixMap& vec) const -{ - HealpixMap out(*this); - out -= vec; - return out; -} - -HealpixMap HealpixMap::operator+(const HealpixMap& vec) const -{ - HealpixMap out(*this); - out += vec; - return out; -} - -} // namespace pxl diff --git a/astro/src/RegionOfInterest.cc b/astro/src/RegionOfInterest.cc deleted file mode 100644 index 546f876b183cd84b0d36f80d1065a123055dd61b..0000000000000000000000000000000000000000 --- a/astro/src/RegionOfInterest.cc +++ /dev/null @@ -1,61 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include "pxl/astro/RegionOfInterest.hh" - -namespace pxl -{ - -std::ostream& RegionOfInterest::print(int level, std::ostream& os, int pan) const -{ - os << "Name: " << getName() << std::endl; - os << " Latitude : " << getGalacticLatitude() << std::endl; - os << " Longitude : " << getGalacticLongitude() << std::endl; - os << " ConeRadius: " << getConeRadius() << std::endl; - return os; -} - -void RegionOfInterest::serialize(const OutputStream &out) const -{ - AstroObject::serialize(out); - out.writeDouble(_coneRadius); - out.writeString(_name); -} - -void RegionOfInterest::deserialize(const InputStream &in) -{ - AstroObject::deserialize(in); - in.readDouble(_coneRadius); - in.readString(_name); -} - -bool RegionOfInterest::objectInCone(const AstroBasicObject& obj) const -{ - return objectInCone(&obj); -} - -bool RegionOfInterest::objectInCone(const AstroBasicObject* obj) const -{ - return (this->angularDistanceTo(obj) < _coneRadius); -} - -bool RegionOfInterest::linkIfObjectInCone(AstroObject& obj, std::string name) -{ - return linkIfObjectInCone(&obj, name); -} - -bool RegionOfInterest::linkIfObjectInCone(AstroObject* obj, std::string name) -{ - if (this->angularDistanceTo(obj) < _coneRadius) - { - this->linkSoft(obj, name); - return true; - } - return false; -} -} diff --git a/astro/src/UHECR.cc b/astro/src/UHECR.cc deleted file mode 100644 index 7dc89468ace7d5bf4f8d02e9840f4eec9474d5d2..0000000000000000000000000000000000000000 --- a/astro/src/UHECR.cc +++ /dev/null @@ -1,40 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include "pxl/astro/UHECR.hh" - -namespace pxl -{ - -std::ostream& UHECR::print(int level, std::ostream& os, int pan) const -{ - os << " Latitude : " << getGalacticLatitude() << std::endl; - os << "Longitude : " << getGalacticLongitude() << std::endl; - os << " Energy : " << getEnergy() << std::endl; - return os; -} - -void UHECR::serialize(const OutputStream &out) const -{ - AstroObject::serialize(out); - out.writeDouble(_energy); - out.writeDouble(_denergy); - out.writeDouble(_mass); - out.writeDouble(_charge); -} - -void UHECR::deserialize(const InputStream &in) -{ - AstroObject::deserialize(in); - in.readDouble(_energy); - in.readDouble(_denergy); - in.readDouble(_mass); - in.readDouble(_charge); -} - -} diff --git a/astro/src/UHECRSource.cc b/astro/src/UHECRSource.cc deleted file mode 100644 index 7882b6626ec343602eb153bbb4f143f3c84f5ae3..0000000000000000000000000000000000000000 --- a/astro/src/UHECRSource.cc +++ /dev/null @@ -1,40 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include "pxl/astro/UHECRSource.hh" - -namespace pxl -{ - -std::ostream& UHECRSource::print(int level, std::ostream& os, int pan) const -{ - os << "Name: " << getName() << std::endl; - os << " Latitude : " << getGalacticLatitude() << std::endl; - os << " Longitude : " << getGalacticLongitude() << std::endl; - os << " Distance : " << getDistance() << std::endl; - os << " Rel. Lum. : " << getLuminosity() << std::endl; - return os; -} - -void UHECRSource::serialize(const OutputStream &out) const -{ - AstroObject::serialize(out); - out.writeDouble(_distance); - out.writeDouble(_luminosity); - out.writeString(_name); -} - -void UHECRSource::deserialize(const InputStream &in) -{ - AstroObject::deserialize(in); - in.readDouble(_distance); - in.readDouble(_luminosity); - in.readString(_name); -} - -} diff --git a/FindDCAP.cmake b/cmake/FindDCAP.cmake similarity index 100% rename from FindDCAP.cmake rename to cmake/FindDCAP.cmake diff --git a/FindLibSSH.cmake b/cmake/FindLibSSH.cmake similarity index 100% rename from FindLibSSH.cmake rename to cmake/FindLibSSH.cmake diff --git a/FindPXL.cmake b/cmake/FindPXL.cmake similarity index 97% rename from FindPXL.cmake rename to cmake/FindPXL.cmake index 456083ab053c5cb700c0961685a798094c8e3b56..8a8c5fee9cf3eb9de9a5217898c2e75e5fac331f 100644 --- a/FindPXL.cmake +++ b/cmake/FindPXL.cmake @@ -2,7 +2,7 @@ # PXL_INCLUDE_DIRS - the PXL include directories # PXL_LIBRARIES_DIR - link these to use PXL # PXL_PLUGIN_INSTALL_PATH - path to the default plugins -# (e.g. $HOME/.pxl-VERSION/plugins) +# (e.g. $HOME/.pxl-PXL_VERSION_LIB/plugins) # # Note that this only configures the pxl-core system to add a pxl # plugin, use the PXL_add_plugin(name), where name is e.g. pxl-hep diff --git a/cmake/WindowsInstaller.cmake b/cmake/WindowsInstaller.cmake new file mode 100644 index 0000000000000000000000000000000000000000..e91e6ca850fcadb58393114d691dd74bfd166acc --- /dev/null +++ b/cmake/WindowsInstaller.cmake @@ -0,0 +1,19 @@ +get_filename_component(WIX_INSTALL_ROOT "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows Installer XML\\3.0;InstallRoot]" ABSOLUTE CACHE) +message(STATUS "Windows Installer XML: ${WIX_INSTALL_ROOT}") + +find_program(CANDLE_EXECUTABLE candle PATHS ${WIX_INSTALL_ROOT} REQUIRED) + +find_program(LIGHT_EXECUTABLE light PATHS ${WIX_INSTALL_ROOT}) + +configure_file(${CMAKE_SOURCE_DIR}/cmake/pypxl.wxs.in ${CMAKE_BINARY_DIR}/pypxl.wxs) + +add_custom_target(windows_installer_candle + ${CANDLE_EXECUTABLE} ${CMAKE_BINARY_DIR}/pypxl.wxs + DEPENDS ${CMAKE_BINARY_DIR}/pypxl.wxs +) +add_dependencies(windows_installer_candle pxlrun pxl-modules) + +add_custom_target(windows_installer + ${LIGHT_EXECUTABLE} -ext WixUIExtension ${CMAKE_BINARY_DIR}/pypxl.wixobj -o ${CMAKE_BINARY_DIR}/PyPXL-Py${PYTHON_DOT_VERSION}-${PXLVERSION}.msi +) +add_dependencies(windows_installer windows_installer_candle) diff --git a/core/CMakeLists.txt b/core/CMakeLists.txt index 30dc213790860eb7d5c423716058190106087cfb..5a77b133f93f9c25f8a6f0d11848f62aafbc428e 100644 --- a/core/CMakeLists.txt +++ b/core/CMakeLists.txt @@ -1,102 +1,61 @@ # # use local include directory # -include_directories (include ${ZLIB_INCLUDE_DIR} ${CMAKE_BINARY_DIR}/include) - -set(PXL_CORE_EXTRA_FILES) -if (PXL_ENABLE_SFTP) - list(APPEND PXL_CORE_EXTRA_FILES "src/sFTPFileImpl.cc") - include_directories (${LIB_SSH_INCLUDE_DIR}) - -endif() - -if (PXL_ENABLE_DCAP) - list(APPEND PXL_CORE_EXTRA_FILES "src/dCapFileImpl.cc") - include_directories (${LIB_DCAP_INCLUDE_DIR}) - -endif() +include_directories(include ${CMAKE_BINARY_DIR}/include) # # add library using the sources # -add_library (pxl-core SHARED - src/Basic3Vector.cc - src/BasicContainer.cc - src/BasicMatrix.cc - src/BasicNVector.cc - src/Core.cc - src/Configuration.cc - src/ConfigLoader.cc - src/Event.cc - src/File.cc - src/functions.cc - src/Id.cc - src/InformationChunk.cc - src/logging.cc - src/LorentzVector.cc - src/MessageDispatcher.cc - src/Object.cc - src/ObjectManager.cc - src/ObjectOwner.cc - src/Random.cc - src/Relations.cc - src/Relative.cc - src/SoftRelations.cc - src/UserRecord.cc - src/Variant.cc - src/WkPtrBase.cc - src/ChunkReader.cc - src/ChunkWriter.cc - src/InputHandler.cc - src/Tokenizer.cc - src/ObjectFactory.cc - src/OutputFile.cc - src/OutputHandler.cc - src/PluginManager.cc - src/FileFactory.cc - src/LocalFileImpl.cc - src/StdFileImpl.cc - src/NamedTMPFile.cc - ${PXL_CORE_EXTRA_FILES} +add_library(pxl-core SHARED + src/Core.cc + src/Configuration.cc + src/ConfigLoader.cc + src/Functions.cc + src/Id.cc + src/JsonParser.cc + src/Logging.cc + src/LorentzVector.cc + src/MessageDispatcher.cc + src/Object.cc + src/ObjectOwner.cc + src/Random.cc + src/Relations.cc + src/Relative.cc + src/PluginManager.cc + src/SerializableFactory.cc + src/SoftRelations.cc + src/Tokenizer.cc + src/UserRecords.cc + src/Variant.cc + src/Vector3.cc + src/WeakPtr.cc ) # # link to pxl # -target_link_libraries(pxl-core ${ZLIB_LIBRARIES}) +# target_link_libraries(pxl-core ${ZLIB_LIBRARIES}) -add_definitions(-DPXL_PLUGIN_LIBEXEC_DIR=${PXLPLUGINDIR}) +add_definitions(-DPXL_PLUGIN_LIBEXEC_DIR=${PXL_PLUGIN_DIR}) CONFIGURE_FILE(config.hh.in ${CMAKE_BINARY_DIR}/include/pxl/core/config.hh) INSTALL(FILES ${CMAKE_BINARY_DIR}/include/pxl/core/config.hh DESTINATION ${includedir}/pxl/core) + # # add winmm for timer function on Windows # -if (WIN32) - target_link_libraries (pxl-core winmm ws2_32) -else (WIN32) - target_link_libraries (pxl-core dl) -endif (WIN32) +if(WIN32) + target_link_libraries(pxl-core winmm ws2_32) +else(WIN32) + target_link_libraries(pxl-core dl) +endif(WIN32) -if (UNIX AND NOT APPLE) +if(UNIX AND NOT APPLE) add_definitions(-D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE) endif() -if(PXL_ENABLE_SFTP) - target_link_libraries (pxl-core ${LIB_SSH_LIBRARIES} ) -endif() - -if(PXL_ENABLE_DCAP) - target_link_libraries (pxl-core ${LIB_DCAP_LIBRARIES} ) -endif() - # # setup install path # -PXL_INSTALL_LIBRARY(pxl-core) - -# -# set library properties for Mac OS X -# -SET_XCODE_FRAMEWORK_PROPERTIES(pxl-core) +PXL_INSTALL_LIBRARY(pxl-core) diff --git a/core/config.hh.in b/core/config.hh.in index 269b4db18a4856faaf31e460df3621d80f273463..626b255f5c7bbee37fcf584d5638fca375e9ccd5 100644 --- a/core/config.hh.in +++ b/core/config.hh.in @@ -1,7 +1,7 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- @@ -9,13 +9,14 @@ #ifndef PXL_CONFIG_HH #define PXL_CONFIG_HH -#define PXL_MAJOR_VERSION "${PXLMAJORRELEASEVERSION}" -#define PXL_MINOR_VERSION "${PXLMINORRELEASEVERSION}" -#define PXL_FULL_VERSION "${PXLVERSION}" +#define PXL_VERSION_MAJOR "${PXL_VERSION_MAJOR}" +#define PXL_VERSION_MINOR "${PXL_VERSION_MINOR}" +#define PXL_VERSION_PATCH "${PXL_VERSION_PATCH}" +#define PXL_VERSION_LIB "${PXL_VERSION_LIB}" +#define PXL_VERSION "${PXL_VERSION}" -#define PXL_MAJOR_VERSION_VALUE ${PXLMAJORRELEASEVERSION} -#define PXL_MINOR_VERSION_VALUE ${PXLMINORRELEASEVERSION} +#define PXL_VERSION_MAJOR_INT ${PXL_VERSION_MAJOR} +#define PXL_VERSION_MINOR_INT ${PXL_VERSION_MINOR} +#define PXL_VERSION_PATCH_INT ${PXL_VERSION_PATCH} -#define PXL_LIB_VERSION "${PXLMAJORRELEASEVERSION}.${PXLMINORRELEASEVERSION}" - -#endif \ No newline at end of file +#endif diff --git a/core/include/pxl/core.hh b/core/include/pxl/core.hh index 1899af9f373a2e5a0f23fdd6f8421ce8ff847cb3..798a95a6f6a93da321fdc5568107aebcbac80ad7 100644 --- a/core/include/pxl/core.hh +++ b/core/include/pxl/core.hh @@ -1,7 +1,7 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- @@ -9,47 +9,29 @@ #ifndef PXL_CORE_HH #define PXL_CORE_HH -#include "pxl/core/Basic3Vector.hh" -#include "pxl/core/BasicNVector.hh" -#include "pxl/core/BasicMatrix.hh" -#include "pxl/core/Core.hh" #include "pxl/core/Configuration.hh" -#include "pxl/core/RotationMatrix.hh" -#include "pxl/core/LorentzVector.hh" -#include "pxl/core/BasicContainer.hh" -#include "pxl/core/Event.hh" -#include "pxl/core/File.hh" -#include "pxl/core/Filter.hh" -#include "pxl/core/functions.hh" +#include "pxl/core/Core.hh" +#include "pxl/core/Functions.hh" #include "pxl/core/Id.hh" -#include "pxl/core/InformationChunk.hh" -#include "pxl/core/logging.hh" +#include "pxl/core/InfoObject.hh" +#include "pxl/core/Logging.hh" +#include "pxl/core/LorentzVector.hh" +#include "pxl/core/Macros.hh" #include "pxl/core/MessageDispatcher.hh" -#include "pxl/core/macros.hh" -#include "pxl/core/Random.hh" #include "pxl/core/Object.hh" -#include "pxl/core/ObjectManager.hh" #include "pxl/core/ObjectOwner.hh" +#include "pxl/core/PluginManager.hh" +#include "pxl/core/Random.hh" #include "pxl/core/Relations.hh" #include "pxl/core/Relative.hh" -#include "pxl/core/SoftRelations.hh" -#include "pxl/core/UserRecord.hh" -#include "pxl/core/Variant.hh" -#include "pxl/core/weak_ptr.hh" -#include "pxl/core/WkPtrBase.hh" -#include "pxl/core/ChunkReader.hh" -#include "pxl/core/ChunkWriter.hh" -#include "pxl/core/GenericInputHandler.hh" -#include "pxl/core/GenericOutputHandler.hh" -#include "pxl/core/InputFile.hh" -#include "pxl/core/InputHandler.hh" -#include "pxl/core/ObjectFactory.hh" -#include "pxl/core/OutputFile.hh" -#include "pxl/core/OutputHandler.hh" -#include "pxl/core/PluginManager.hh" #include "pxl/core/Serializable.hh" +#include "pxl/core/SerializableFactory.hh" +#include "pxl/core/SoftRelations.hh" #include "pxl/core/Stream.hh" #include "pxl/core/Tokenizer.hh" -#include "pxl/core/NamedTMPFile.hh" +#include "pxl/core/UserRecords.hh" +#include "pxl/core/Variant.hh" +#include "pxl/core/Vector3.hh" +#include "pxl/core/WeakPtr.hh" -#endif // PXL_BASE_HH +#endif // PXL_CORE_HH diff --git a/core/include/pxl/core/AssocVector.hh b/core/include/pxl/core/AssocVector.hh new file mode 100644 index 0000000000000000000000000000000000000000..ad904a90588ee2772e37d8f856b4235d9d7df11e --- /dev/null +++ b/core/include/pxl/core/AssocVector.hh @@ -0,0 +1,381 @@ +//////////////////////////////////////////////////////////////////////////////// +// The Loki Library +// Copyright (c) 2001 by Andrei Alexandrescu +// This code accompanies the book: +// Alexandrescu, Andrei. "Modern C++ Design: Generic Programming and Design +// Patterns Applied". Copyright (c) 2001. Addison-Wesley. +// +// 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. +//////////////////////////////////////////////////////////////////////////////// +#ifndef LOKI_ASSOCVECTOR_INC_ +#define LOKI_ASSOCVECTOR_INC_ + +// $Id$ + + +#include +#include +#include +#include +#include +#include + + +namespace loki +{ +//////////////////////////////////////////////////////////////////////////////// +// class template AssocVectorCompare +// Used by AssocVector +//////////////////////////////////////////////////////////////////////////////// + + namespace Private + { + template + class AssocVectorCompare : public C + { + typedef std::pair + Data; + typedef typename C::first_argument_type first_argument_type; + + public: + AssocVectorCompare() + {} + + AssocVectorCompare(const C& src) : C(src) + {} + + bool operator()(const first_argument_type& lhs, + const first_argument_type& rhs) const + { return C::operator()(lhs, rhs); } + + bool operator()(const Data& lhs, const Data& rhs) const + { return operator()(lhs.first, rhs.first); } + + bool operator()(const Data& lhs, + const first_argument_type& rhs) const + { return operator()(lhs.first, rhs); } + + bool operator()(const first_argument_type& lhs, + const Data& rhs) const + { return operator()(lhs, rhs.first); } + }; + } + +//////////////////////////////////////////////////////////////////////////////// +// class template AssocVector +// An associative vector built as a syntactic drop-in replacement for std::map +// BEWARE: AssocVector doesn't respect all map's guarantees, the most important +// being: +// * iterators are invalidated by insert and erase operations +// * the complexity of insert/erase is O(N) not O(log N) +// * value_type is std::pair not std::pair +// * iterators are random +//////////////////////////////////////////////////////////////////////////////// + + + template + < + class K, + class V, + class C = std::less, + class A = std::allocator< std::pair > + > + class AssocVector + : private std::vector< std::pair, A > + , private Private::AssocVectorCompare + { + typedef std::vector, A> Base; + typedef Private::AssocVectorCompare MyCompare; + + public: + typedef K key_type; + typedef V mapped_type; + typedef typename Base::value_type value_type; + + typedef C key_compare; + typedef A allocator_type; + typedef typename A::reference reference; + typedef typename A::const_reference const_reference; + typedef typename Base::iterator iterator; + typedef typename Base::const_iterator const_iterator; + typedef typename Base::size_type size_type; + typedef typename Base::difference_type difference_type; + typedef typename A::pointer pointer; + typedef typename A::const_pointer const_pointer; + typedef typename Base::reverse_iterator reverse_iterator; + typedef typename Base::const_reverse_iterator const_reverse_iterator; + + class value_compare + : public std::binary_function + , private key_compare + { + friend class AssocVector; + + protected: + value_compare(key_compare pred) : key_compare(pred) + {} + + public: + bool operator()(const value_type& lhs, const value_type& rhs) const + { return key_compare::operator()(lhs.first, rhs.first); } + }; + + // 23.3.1.1 construct/copy/destroy + + explicit AssocVector(const key_compare& comp = key_compare(), + const A& alloc = A()) + : Base(alloc), MyCompare(comp) + {} + + template + AssocVector(InputIterator first, InputIterator last, + const key_compare& comp = key_compare(), + const A& alloc = A()) + : Base( alloc ), MyCompare( comp ) + { + typedef ::std::vector< ::std::pair< K, V >, A > BaseType; + typedef ::std::map< K, V, C, A > TempMap; + typedef ::std::back_insert_iterator< Base > MyInserter; + MyCompare & me = *this; + const A tempAlloc; + // Make a temporary map similar to this type to prevent any duplicate elements. + TempMap temp( first, last, me, tempAlloc ); + Base::reserve( temp.size() ); + BaseType & target = static_cast< BaseType & >( *this ); + MyInserter myInserter = ::std::back_inserter( target ); + ::std::copy( temp.begin(), temp.end(), myInserter ); + } + + AssocVector& operator=(const AssocVector& rhs) + { + AssocVector(rhs).swap(*this); + return *this; + } + + // iterators: + // The following are here because MWCW gets 'using' wrong + iterator begin() { return Base::begin(); } + const_iterator begin() const { return Base::begin(); } + iterator end() { return Base::end(); } + const_iterator end() const { return Base::end(); } + reverse_iterator rbegin() { return Base::rbegin(); } + const_reverse_iterator rbegin() const { return Base::rbegin(); } + reverse_iterator rend() { return Base::rend(); } + const_reverse_iterator rend() const { return Base::rend(); } + + // capacity: + bool empty() const { return Base::empty(); } + size_type size() const { return Base::size(); } + size_type max_size() { return Base::max_size(); } + + // 23.3.1.2 element access: + mapped_type& operator[](const key_type& key) + { return insert(value_type(key, mapped_type())).first->second; } + + // modifiers: + std::pair insert(const value_type& val) + { + bool found(true); + iterator i(lower_bound(val.first)); + + if (i == end() || this->operator()(val.first, i->first)) + { + i = Base::insert(i, val); + found = false; + } + return std::make_pair(i, !found); + } + //Section [23.1.2], Table 69 + //http://developer.apple.com/documentation/DeveloperTools/gcc-3.3/libstdc++/23_containers/howto.html#4 + iterator insert(iterator pos, const value_type& val) + { + if( (pos == begin() || this->operator()(*(pos-1),val)) && + (pos == end() || this->operator()(val, *pos)) ) + { + return Base::insert(pos, val); + } + return insert(val).first; + } + + template + void insert(InputIterator first, InputIterator last) + { for (; first != last; ++first) insert(*first); } + + void erase(iterator pos) + { Base::erase(pos); } + + size_type erase(const key_type& k) + { + iterator i(find(k)); + if (i == end()) return 0; + erase(i); + return 1; + } + + void erase(iterator first, iterator last) + { Base::erase(first, last); } + + void swap(AssocVector& other) + { + Base::swap(other); + MyCompare& me = *this; + MyCompare& rhs = other; + std::swap(me, rhs); + } + + void clear() + { Base::clear(); } + + // observers: + key_compare key_comp() const + { return *this; } + + value_compare value_comp() const + { + const key_compare& comp = *this; + return value_compare(comp); + } + + // 23.3.1.3 map operations: + iterator find(const key_type& k) + { + iterator i(lower_bound(k)); + if (i != end() && this->operator()(k, i->first)) + { + i = end(); + } + return i; + } + + const_iterator find(const key_type& k) const + { + const_iterator i(lower_bound(k)); + if (i != end() && this->operator()(k, i->first)) + { + i = end(); + } + return i; + } + + size_type count(const key_type& k) const + { return find(k) != end(); } + + iterator lower_bound(const key_type& k) + { + MyCompare& me = *this; + return std::lower_bound(begin(), end(), k, me); + } + + const_iterator lower_bound(const key_type& k) const + { + const MyCompare& me = *this; + return std::lower_bound(begin(), end(), k, me); + } + + iterator upper_bound(const key_type& k) + { + MyCompare& me = *this; + return std::upper_bound(begin(), end(), k, me); + } + + const_iterator upper_bound(const key_type& k) const + { + const MyCompare& me = *this; + return std::upper_bound(begin(), end(), k, me); + } + + std::pair equal_range(const key_type& k) + { + MyCompare& me = *this; + return std::equal_range(begin(), end(), k, me); + } + + std::pair equal_range( + const key_type& k) const + { + const MyCompare& me = *this; + return std::equal_range(begin(), end(), k, me); + } + + template + friend bool operator==(const AssocVector& lhs, + const AssocVector& rhs); + + bool operator<(const AssocVector& rhs) const + { + const Base& me = *this; + const Base& yo = rhs; + return me < yo; + } + + template + friend bool operator!=(const AssocVector& lhs, + const AssocVector& rhs); + + template + friend bool operator>(const AssocVector& lhs, + const AssocVector& rhs); + + template + friend bool operator>=(const AssocVector& lhs, + const AssocVector& rhs); + + template + friend bool operator<=(const AssocVector& lhs, + const AssocVector& rhs); + }; + + template + inline bool operator==(const AssocVector& lhs, + const AssocVector& rhs) + { + const std::vector, A>& me = lhs; + return me == rhs; + } + + template + inline bool operator!=(const AssocVector& lhs, + const AssocVector& rhs) + { return !(lhs == rhs); } + + template + inline bool operator>(const AssocVector& lhs, + const AssocVector& rhs) + { return rhs < lhs; } + + template + inline bool operator>=(const AssocVector& lhs, + const AssocVector& rhs) + { return !(lhs < rhs); } + + template + inline bool operator<=(const AssocVector& lhs, + const AssocVector& rhs) + { return !(rhs < lhs); } + + + // specialized algorithms: + template + void swap(AssocVector& lhs, AssocVector& rhs) + { lhs.swap(rhs); } + +} // namespace loki + +#endif // end file guardian + diff --git a/core/include/pxl/core/Basic3Vector.hh b/core/include/pxl/core/Basic3Vector.hh deleted file mode 100644 index 25a12f4298930f97dadf5f00509ccf87938cdeda..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/Basic3Vector.hh +++ /dev/null @@ -1,273 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_BASE_BASIC3VECTOR_HH -#define PXL_BASE_BASIC3VECTOR_HH -#include "pxl/core/macros.hh" - -#include -#include -#include "pxl/core/Stream.hh" -#include - -class runtime_error; - - -namespace pxl -{ - -/** - This class provides a simple threevector with basic algebra. The methods provided are self-explanatory. - Note that theta is defined as 0 in z-direction, as usual in collider physics. - */ -class PXL_DLL_EXPORT Basic3Vector -{ -public: - Basic3Vector() - { - _v[0] = 0; - _v[1] = 0; - _v[2] = 0; - } - Basic3Vector(const Basic3Vector& orig) - { - _v[0] = orig._v[0]; - _v[1] = orig._v[1]; - _v[2] = orig._v[2]; - } - explicit Basic3Vector(const Basic3Vector* orig) - { - _v[0] = orig->_v[0]; - _v[1] = orig->_v[1]; - _v[2] = orig->_v[2]; - } - Basic3Vector(double x, double y, double z) - { - _v[0] = x; - _v[1] = y; - _v[2] = z; - } - - Basic3Vector(const double x[3]) - { - _v[0] = x[0]; - _v[1] = x[1]; - _v[2] = x[2]; - } - - virtual ~Basic3Vector() - { - } - - virtual void serialize(const OutputStream &out) const - { - out.writeDouble(_v[0]); - out.writeDouble(_v[1]); - out.writeDouble(_v[2]); - } - - virtual void deserialize(const InputStream &in) - { - in.readDouble(_v[0]); - in.readDouble(_v[1]); - in.readDouble(_v[2]); - } - - inline void setX(double x) - { - _v[0] = x; - } - inline void setY(double y) - { - _v[1] = y; - } - inline void setZ(double z) - { - _v[2] = z; - } - - inline void setXYZ(double x, double y, double z) - { - _v[0] = x; - _v[1] = y; - _v[2] = z; - } - - inline void setElement(int i, double val) - { - if (i < 0 || 1> 2) - throw std::runtime_error("Basic3Vector index out of range"); - _v[i] = val; - } - - inline double getElement(int i) const - { - if (i < 0 || 1> 2) - throw std::runtime_error("Basic3Vector index out of range"); - return _v[i]; - } - - inline double* getArray() - /// Returns a pointer to the C Array double[3] for the three - /// components of the vector - { - return _v; - } - - const double* getConstArray() const - /// Returns a pointer to the C Array double[3] for the three - /// components of the vector - { - return _v; - } - - void setCArray(double val[3]) - { - _v[0] = val[0]; - _v[1] = val[1]; - _v[2] = val[2]; - } - - void setRhoPhi(double perp, double phi); - - void setRhoPhiZ(double perp, double phi, double z); - - void setRThetaPhi(double r, double theta, double phi); - - inline double getX() const - { - return _v[0]; - } - inline double getY() const - { - return _v[1]; - } - inline double getZ() const - { - return _v[2]; - } - - bool isNullPerp() const; - - bool isNull() const; - - double getPerp2() const; - - double getPerp() const; - - double getPhi() const; - - double getMag2() const; - - double getMag() const; - - double getCosTheta() const; - - double getCos2Theta() const; - - double getTheta() const; - - /// Returns unit vector in spherical coordinates - Basic3Vector getETheta() const; - - ///Returns unit vector in spherical coordinates - Basic3Vector getEPhi() const; - - double deltaRho(const Basic3Vector* fv) const - { - return deltaRho(*fv); - } - - double deltaPhi(const Basic3Vector* fv) const - { - return deltaPhi(*fv); - } - - double deltaTheta(const Basic3Vector* fv) const - { - return deltaPhi(*fv); - } - - double deltaRho(const Basic3Vector& fv) const; - - double deltaPhi(const Basic3Vector& fv) const; - - double deltaTheta(const Basic3Vector& fv) const; - - const Basic3Vector& operator=(const Basic3Vector& vec); - - const Basic3Vector& operator+=(const Basic3Vector& vec); - - const Basic3Vector& operator-=(const Basic3Vector& vec); - - const Basic3Vector& operator*=(double scalar); - - const Basic3Vector& operator/=(double scalar); - - Basic3Vector operator+(const Basic3Vector& vec); - - /// Returns a copy of (this minus vec). - Basic3Vector operator-(const Basic3Vector& vec); - - /// Returns a copy of (this divided by passed scalar). - Basic3Vector operator/(double scalar) const; - - /// scalar product - double operator*( const Basic3Vector& vec) const; - - /// cross product - inline Basic3Vector cross(const Basic3Vector &p) const - { - return Basic3Vector(_v[1]*p._v[2]-p._v[1]*_v[2], _v[2]*p._v[0]-p._v[2]*_v[0], _v[0]*p._v[1]-p._v[0]*_v[1]); - } - - /// Return a copy of this Basic3Vector where all components are multiplied with -1. - inline Basic3Vector operator-() const - { - return Basic3Vector(-1.*_v[0], -1.*_v[1], -1.*_v[2]); - } - inline double& operator()(size_t i) - { - if (i > 2) - throw std::runtime_error("Basic3Vector index out of range"); - return _v[i]; - } - - /// returns the given norm, -1 for infinity norm - double norm(uint32_t norm) const; - - bool isUnitVector() const; - - /// Returns angle between the vector and vec - double getAngleTo(const Basic3Vector& vec) const; - - /// Rotates the vector around axis by the angle rad - void rotate(const Basic3Vector& axis, double angle); - - /// normalizes the vector to 1 - void normalize(); - -private: - double _v[3]; - -}; - -// non-member operators -PXL_DLL_EXPORT bool operator==(const Basic3Vector& obj1, - const Basic3Vector& obj2); -PXL_DLL_EXPORT bool operator!=(const Basic3Vector& obj1, - const Basic3Vector& obj2); - -PXL_DLL_EXPORT Basic3Vector operator*(const double scalar, - const Basic3Vector& vec); -PXL_DLL_EXPORT Basic3Vector operator*(const Basic3Vector& vec, - const double scalar); - -} // namespace pxl - -#endif // PXL_BASE_BASIC3VECTOR_HH diff --git a/core/include/pxl/core/BasicContainer.hh b/core/include/pxl/core/BasicContainer.hh deleted file mode 100644 index b5c19fa367b981212c2c821a594e866ed1b2bdee..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/BasicContainer.hh +++ /dev/null @@ -1,261 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_BASE_BASICCONTAINER_HH -#define PXL_BASE_BASICCONTAINER_HH -#include "pxl/core/macros.hh" - -#include -#include - -#include "pxl/core/UserRecord.hh" - -#include "pxl/core/Serializable.hh" -#include "pxl/core/ObjectFactory.hh" - -namespace pxl -{ - -/** - A Container for all objects that inherit from pxl::Serializable. This should be a rudiment version of the pxl::ObjectOwner. - */ -class PXL_DLL_EXPORT BasicContainer: public Serializable, - public UserRecordHelper -{ -public: - /// The Index for the BasicContainer - typedef std::map map_t; - - BasicContainer() : - Serializable() - { - } - - BasicContainer(const BasicContainer& basicContainer) : - Serializable(basicContainer), UserRecordHelper(basicContainer), - _container(), _index(), _uuidSearchMap() - { - this->init(basicContainer); - } - - explicit BasicContainer(const BasicContainer* basicContainer) : - Serializable(*basicContainer), UserRecordHelper(*basicContainer), - _container(), _index(), _uuidSearchMap() - { - this->init(*basicContainer); - } - - BasicContainer& operator=(const BasicContainer& original) - { - if (this != &original) - { - clearContainer(); - this->init(original); - } - return *this; - } - - void init(const BasicContainer& basicContainer); - - /// This destructor deletes all contained objects. - virtual ~BasicContainer() - { - this->clearContainer(); - } - - /// Creates a deep copy and returns a C++ pointer to the newly-created object. - virtual Serializable* clone() const - { - return new BasicContainer(*this); - } - - /// Allows read access to the contained STL vector of - /// Relative pointers to, e.g., use STL algorithms. - const std::vector& getObjects() const - { - return _container; - } - - /// Creates a new instance of \p objecttype; - /// objecttype must be a class inheriting from pxl::Serializable; - /// the newly-created instance is owned and will be deleted by this object owner. - template objecttype* create() - { - objecttype* pitem = new objecttype; - _container.push_back(static_cast (pitem)); - _uuidSearchMap.insert(std::pair(pitem->getId(), - pitem)); - return pitem; - } - - /// Creates a copy of \p original by invoking the - /// copy constructor of \p objecttype; / \p objecttype must be a class - /// inheriting from pxl::Serializable; / the newly-created instance - /// is owned and will be deleted by this object owner. - template objecttype* create(const objecttype* original) - { - objecttype* pitem = new objecttype(*original); - _container.push_back(static_cast (pitem)); - _uuidSearchMap.insert(std::pair(pitem->getId(), - pitem)); - return pitem; - } - - /// Inserts \p value in the container of this object owner - /// and takes deletion responsability. - void insertObject(Serializable* value); - - /// Deletes \p value. - void remove(Serializable* value); - - ///Deletes all objects of \p objecttype; returns number of deleted - ///objects - size_t removeObjectsOfType(const Id& typeId); - - template size_t removeObjectsOfType() - { - return removeObjectsOfType(objecttype::getStaticTypeId()); - } - - /// Takes \p value from the container. - void take(Serializable* value); - - /// Returns true if \p value is owned by this object owner. - bool has(const Serializable* value) const; - - /// Clears the object owner and deletes all owned objects. - void clearContainer(); - - /// Typedef for standard const_iterator. - typedef std::vector::const_iterator const_iterator; - typedef std::vector::iterator iterator; - - /// This returns the const iterator to the first element of the contained vector. - inline const_iterator begin() const - { - return _container.begin(); - } - - /// This returns the iterator to the first element of the contained vector. - inline iterator begin() - { - return _container.begin(); - } - - /// This returns the const iterator to the end of the contained vector. - inline const_iterator end() const - { - return _container.end(); - } - - /// This returns the iterator to the end of the contained vector. - inline iterator end() - { - return _container.end(); - } - - /// Returns the number of elements the BasicContainer holds. - inline size_t size() const - { - return _container.size(); - } - - /// This method searches the index for the \p key and returns a - ///dynamically casted / C++ pointer of type \p objecttype* to the - ///corresponding object; / in case the key is not found a null pointer is - ///returned. - template inline objecttype* findObject( - const std::string& key) const // goes via Index & casts - - { - map_t::const_iterator it = _index.find(key); - if (it != _index.end()) - return dynamic_cast (it->second); - return 0; - } - - inline Serializable* findObject(const std::string& key) const - { - map_t::const_iterator it = _index.find(key); - if (it != _index.end()) - return it->second; - return 0; - } - - /// Returns a Serializable pointer for a contained object with the passed ID. - /// In case the Serializable is not in the container, 0 is returned. - Serializable* getById(Id id) const - { - std::map::const_iterator found = - _uuidSearchMap.find(id); - if (found != _uuidSearchMap.end()) - return found->second; - return 0; - } - - /// Fills into the passed vector weak pointers to the objects of the - /// type specified by the template argument. - template size_t getObjectsOfType( - std::vector& vec) const - { - size_t size = vec.size(); - for (BasicContainer::const_iterator iter = begin(); iter != end(); ++iter) - { - objecttype* obj = dynamic_cast (*iter); - if (obj != 0) - vec.push_back(obj); - } - return vec.size() - size; - } - - virtual const Id& getTypeId() const - { - return getStaticTypeId(); - } - - static const Id& getStaticTypeId() - { - static const Id id("38ebda57-df6f-a577-b811-0bba49745b09"); - return id; - } - - virtual void serialize(const OutputStream &out) const; - - virtual void deserialize(const InputStream &in); - - ////////////////////////////////////////////// - //User Record - ////////////////////////////////////////////// - - - /// This method provides direct read access to the index. - inline const map_t& getIndexEntry() const - { - return _index; - } - - inline void removeIndexEntry(const std::string& key) - { - _index.erase(key); - } - - /// This method clears the index; please notice: it does not remove the objects themselves. - inline void clearIndex() - { - _index.clear(); - } - -private: - std::vector _container; - map_t _index; - std::map _uuidSearchMap; -}; - -} // namespace pxl - -#endif // PXL_BASE_BASICCONTAINER_HH diff --git a/core/include/pxl/core/BasicMatrix.hh b/core/include/pxl/core/BasicMatrix.hh deleted file mode 100644 index 75903697a862f45196fd0523bea5adfd5e317960..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/BasicMatrix.hh +++ /dev/null @@ -1,289 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_BASE_BASICMATRIX_HH -#define PXL_BASE_BASICMATRIX_HH -#include "pxl/core/macros.hh" - -#include -#include -#include -#include - -#include "pxl/core/BasicNVector.hh" -#include "pxl/core/Basic3Vector.hh" -#include "pxl/core/Stream.hh" -#include "pxl/core/Serializable.hh" -#include "pxl/core/ObjectFactory.hh" -namespace pxl -{ - -/** - * Storage Order - */ -typedef enum -{ - ROWMAJOR, COLUMNMAJOR -} StorageOrder; - - -/** - This class provides a Matrix of arbitrary dimensions for data storage - or algebra in R**NxM - - The Matrix is stored as BLAS compatible array of doubles. The default storage order is the C default of Row-Major - order, meaning, that a Matrix is stored row by row - double M[] = { 1,2,3, - 4,5,6 - } - The Same matrix in Column Order would be stored as - double M[] = {1,4,2,5,3,6}; - - size1, usually defined by index i, denotes the row in row-based order, - respectivelty the column in column-based order. In row-based order - element i,j is hence element i*size2+j of the array, and in column-based - order element i,j is also element i*size2+j of the array. - **/ -class PXL_DLL_EXPORT BasicMatrix : public Serializable -{ -public: - BasicMatrix() : Serializable() ,_size1(0), _size2(0), _storageType(ROWMAJOR), _alienarray(false), _data(NULL) - { - } - BasicMatrix(size_t size1, size_t size2, std::string name = "BasicMatrix") : Serializable(), _size1(size1), _size2(size2), _storageType(ROWMAJOR), _alienarray(false), _name(name) - { - _data = new double[size1*size2]; - std::fill_n(_data, size1*size2, 0 ); - } - - BasicMatrix(size_t size1, size_t size2, StorageOrder storage, const std::string name = "BasicMatrix") : Serializable(), _size1(size1), _size2(size2), _storageType(storage), _alienarray(false), _name(name) - { - _data = new double[size1*size2]; - std::fill_n(_data, size1*size2, 0 ); - } - - BasicMatrix(const BasicMatrix& orig) : Serializable(orig) - { - _size1 = orig._size1; - _size2 = orig._size2; - _data = new double[_size1*_size2]; - _alienarray = false; - _storageType = orig._storageType; - for (size_t i=0;i<_size1*_size2;i++) - { - _data[i] = orig.getConstArray()[i]; - } - } - - explicit BasicMatrix(const BasicMatrix* orig) : Serializable(*orig) - { - _size1 = orig->_size1; - _size2 = orig->_size2; - _data = new double[_size1*_size2]; - _alienarray = false; - _storageType = orig->_storageType; - for (size_t i=0;i<_size1*_size2;i++) - { - _data[i] = orig->getConstArray()[i]; - } - } - - BasicMatrix(size_t size1, size_t size2, double *data, StorageOrder storage, const std::string name = "BasicMatrix") : Serializable(), _size1(size1), _size2(size2), _storageType(storage), _alienarray(true), _name(name), _data(data) - { - } - - virtual ~BasicMatrix() - { - if ((_data) && (!_alienarray)) - delete[] _data; - } - - void setName(const std::string &name) - { - _name = name; - } - - const std::string &getName() const - { - return _name; - } - /// Uses an external array as data array - void use(size_t size1, size_t size2, double *data); - - /// Check whether an external array is used - bool isAlien() const - { - return _alienarray; - } - - /// Interpret matrix as rowmajor - void setRowBasedStorage() - { - _storageType = ROWMAJOR; - } - - /// Interpret matrix as columnmajor - void setColumnBasedStorage() - { - _storageType = COLUMNMAJOR; - } - - bool isRowBasedStorage() const; - bool isColumnBasedStorage() const; - - ///Returns first dimension of matrix - size_t getSize1() const - { - return _size1; - } - - ///Returns second dimension of matrix - size_t getSize2() const - { - return _size2; - } - - ///Returns numbers of rows of matrix - size_t getNumberOfRows() const - { - if (_storageType==ROWMAJOR) - return _size1; - else - return _size2; - } - - ///Returns numbers of columns of matrix - size_t getNumberOfColumns() const - { - if (_storageType==ROWMAJOR) - return _size2; - else - return _size1; - } - - // Resizes the array. The data stored gets lost - void resize(size_t i, size_t j); - - /// Only reshapes the matrix but preserves the data in the array - void reshape(size_t i, size_t j); - - /// Returns element m_i,j of the matrix - double getElement(size_t i,size_t j) const - { - if (i >= _size1) - { - if (this->isRowBasedStorage()) - throw std::runtime_error("Index exceeds number of rows"); - else - throw std::runtime_error("Index exceeds number of columns"); - } - if (j >= _size2) - { - if (this->isColumnBasedStorage()) - throw std::runtime_error("Index exceeds number of rows"); - else - throw std::runtime_error("Index exceeds number of columns"); - } - - return _data[i*_size2+j]; - } - - ///Sets element m_i,j - void setElement(size_t i,size_t j, double val) - { - if (i >= _size1) - { - if (this->isRowBasedStorage()) - throw std::runtime_error("Index exceeds number of rows"); - else - throw std::runtime_error("Index exceeds number of columns"); - } - if (j >= _size2) - { - if (this->isColumnBasedStorage()) - throw std::runtime_error("Index exceeds number of rows"); - else - throw std::runtime_error("Index exceeds number of columns"); - } - - _data[i*_size2+j] = val; - } - - /// Returns a pointer to the internal array storing the matrix, e.g. - /// for access using blas or lapack implementations - double* getArray() - { - return _data; - } - - /// Returns a const pointer to the internal array storing the matrix, e.g. - /// for access using blas or lapack implementations - const double* getConstArray() const - { - return _data; - } - - const BasicMatrix& operator=(const BasicMatrix& M); - BasicMatrix operator+(const BasicMatrix& M); - BasicMatrix operator-(const BasicMatrix& M); - const BasicMatrix& operator+=(const BasicMatrix& M); - const BasicMatrix& operator-=(const BasicMatrix& M); - const BasicMatrix& operator*=(double skalar); - const BasicMatrix& operator/=(double skalar); - const BasicMatrix operator/(double skalar) const; - - ///Returns element m_i,j of M - double& operator()(size_t i, size_t j); - - virtual std::ostream& print(int level=1, std::ostream& os=std::cout, int pan=1) const; - - virtual Serializable* clone() const - { - return new BasicMatrix(*this); - } - - virtual void serialize(const OutputStream &out) const; - - virtual void deserialize(const InputStream &in); - - static const Id& getStaticTypeId() - { - static const Id id("85ebd9cb-08ae-6c7b-2257-45604aae6f55"); - return id; - } - - virtual const Id& getTypeId() const - { - return getStaticTypeId(); - } -private: - size_t _size1; - size_t _size2; - StorageOrder _storageType; - bool _alienarray; // true if working with an not self allocated array - if so, memory is not freed! - std::string _name; -protected: - double* _data; - -}; -PXL_DLL_EXPORT bool operator==(const BasicMatrix& obj1, const BasicMatrix& obj2); -PXL_DLL_EXPORT bool operator!=(const BasicMatrix& obj1, const BasicMatrix& obj2); - -PXL_DLL_EXPORT BasicMatrix operator*(double skalar, const BasicMatrix& vec); -PXL_DLL_EXPORT BasicMatrix operator*(const BasicMatrix& vec, double skalar); - -// Fundamental Matrix Vector Products - -PXL_DLL_EXPORT BasicNVector operator*(const BasicMatrix& M, const BasicNVector& vec); -PXL_DLL_EXPORT Basic3Vector operator*(const BasicMatrix& M, const Basic3Vector& vec); - - - -} // namespace pxl - -#endif // PXL_BASE_BASICMATRIX_HH diff --git a/core/include/pxl/core/BasicNVector.hh b/core/include/pxl/core/BasicNVector.hh deleted file mode 100644 index 0692e06da9f31553e1b6d1cd1e7a810850829ae2..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/BasicNVector.hh +++ /dev/null @@ -1,205 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_BASE_BASICNVECTOR_HH -#define PXL_BASE_BASICNVECTOR_HH -#include "pxl/core/macros.hh" - -#include -#include -#include -#include -#include - -#include "pxl/core/Stream.hh" -#include "pxl/core/Serializable.hh" -#include "pxl/core/Basic3Vector.hh" -#include "pxl/core/ObjectFactory.hh" - -namespace pxl -{ - -/** - This class provides a vector of arbitrary length for data storage or algebra in R**N - */ -class PXL_DLL_EXPORT BasicNVector : public Serializable -{ -public: - - BasicNVector() : Serializable(), _data(NULL), _size1(0), _alienarray(false), _name("BasicNVector") - { - } - - BasicNVector(size_t size) : Serializable(), _data(NULL), _size1(size), _alienarray(false), _name("BasicNVector") - { - _data = new double[size]; - std::fill_n(_data, size, 0 ); - } - - BasicNVector(const BasicNVector& orig): Serializable(orig) - { - _size1 = orig.getSize(); - _data = new double[_size1]; - _alienarray = false; - for (size_t i=0;i<_size1;i++) - { - _data[i] = orig.getElement(i); - } - _name = "BasicNVector"; - } - - BasicNVector(const Basic3Vector& vec) : Serializable() - { - _size1 = 3; - _data = new double[_size1]; - _alienarray = false; - _data[0] = vec.getX(); - _data[1] = vec.getY(); - _data[2] = vec.getZ(); - _name = "BasicNVector"; - } - - explicit BasicNVector(const BasicNVector* orig): Serializable(*orig) - { - _size1 = orig->getSize(); - _data = new double[_size1]; - _alienarray = false; - for (size_t i=0;i<_size1;i++) - { - _data[i] = orig->getElement(i); - } - _name = "BasicNVector"; - } - - BasicNVector(size_t size, double *data, const std::string name = "BasicNVector"): Serializable() - - { - _size1 = size; - _data = data; - _alienarray = true; - _name = name; - } - - virtual ~BasicNVector() - { - if (_data && (!_alienarray)) - { - delete[] _data; - } - } - - /// Uses the given array as data array without copying it - /// If the array is deleted, the BasicNVector will segfault - void use(size_t size, double *data); - - /// Stop using an externally allocated array as internal data storage - void unUseArray(); - - /// resets the size (and allocates memory if not yet done) - void setSize(size_t size); - - size_t getSize() const - { - return _size1; - } - - void setName(const std::string &name) - { - _name = name; - } - - const std::string &getName() const - { - return _name; - } - - double getElement(size_t i) const - { - if (i<_size1) - { - return _data[i]; - } - else - { - throw std::runtime_error("Index out of range"); - } - } - - void setElement(size_t i,double value) - { - if (i<_size1) - _data[i] = value; - else - throw std::runtime_error("Index out of range"); - } - - virtual std::ostream& print(int level=1, std::ostream& os=std::cout, int pan=1) const; - - double* getArray() - { - return _data; - } - - const double* getConstArray() const - { - return _data; - } - - virtual Serializable* clone() const - { - return new BasicNVector(*this); - } - - static const Id& getStaticTypeId() - { - static const Id id("b95fb401-e0a7-87b6-1737-9ce54aae6f29"); - return id; - } - - virtual const Id& getTypeId() const - { - return getStaticTypeId(); - } - - virtual void serialize(const OutputStream &out) const; - - virtual void deserialize(const InputStream &in); - - const BasicNVector& operator=(const BasicNVector& vec); - BasicNVector operator+(const BasicNVector& vec); - BasicNVector operator-(const BasicNVector& vec); - const BasicNVector& operator+=(const BasicNVector& vec); - const BasicNVector& operator-=(const BasicNVector& vec); - const BasicNVector& operator*=(double skalar); - const BasicNVector& operator/=(double skalar); - const BasicNVector operator/(double skalar) const; - - double& operator()(size_t i); - //// Scalar product - double operator*( const BasicNVector& vec) const; - double norm(uint32_t norm); - -private: - double* _data; - size_t _size1; - bool _alienarray; - std::string _name; - -}; -// non-member operators -PXL_DLL_EXPORT bool operator==(const BasicNVector& obj1, - const BasicNVector& obj2); -PXL_DLL_EXPORT bool operator!=(const BasicNVector& obj1, - const BasicNVector& obj2); - -PXL_DLL_EXPORT BasicNVector operator*(double skalar, const BasicNVector& vec); -PXL_DLL_EXPORT BasicNVector operator*(const BasicNVector& vec, double skalar); - -} // namespace pxl - -#endif // PXL_BASE_BASICNVECTOR_HH diff --git a/core/include/pxl/core/ChunkReader.hh b/core/include/pxl/core/ChunkReader.hh deleted file mode 100644 index 454151b251bf0e6ca4e16bfbc574bf40d3682794..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/ChunkReader.hh +++ /dev/null @@ -1,222 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_IO_CHUNK_READER_HH -#define PXL_IO_CHUNK_READER_HH -#include "pxl/core/macros.hh" - -#include -#include -#include - -#include "pxl/core/Stream.hh" -#include "pxl/core/File.hh" - -#define iotl__iStreamer__lengthUnzipBuffer 65536 - -namespace pxl -{ - -namespace skipSpace -{ - -enum skipMode -{ - off = 0, - on -}; - -} - - -/// This class implemenents various methods for reading from PXL I/O and -/// bases on the event structure defined in the ChunkWriter class. -/// The entry point for the user is the class InputFile. - - -using namespace skipSpace; - -class PXL_DLL_EXPORT ChunkReader -{ -public: - - /// The status flag can take one out four values, either before an - /// event (pre-header), or before a block, then either within an information chunk, - /// or an event, or something unknown - enum statusFlag - { - preHeader = 0, - evPreBlock, - infoPreBlock, - preBlock - }; - - /// The readMode indicates if anything is read, just events, or only information chunks - enum readMode - { - all = 0, - event, - infoChunk - }; - - /// The infoMode can be passed as a flag to indicate that a string condition - /// must be fulfilled to read a block, an event, or an information chunk - enum infoMode - { - ignore = 0, - evaluate - }; - - /// The fileMode flag says if the read-in istream is seekable, or not. It needs to be modified by - /// implementing classes. - enum fileMode - { - nonSeekable = 0, - seekable - }; - - ChunkReader(FileImpl& stream, fileMode seekMode = seekable) : - _stream(stream), _status(preHeader), _sectionCount(0), _seekMode(seekMode) - { - _inputBuffer = new unsigned char[iotl__iStreamer__lengthUnzipBuffer]; - _outputBuffer = new unsigned char[iotl__iStreamer__lengthUnzipBuffer]; - } - - ~ChunkReader() - { - delete[] _inputBuffer; - delete[] _outputBuffer; - } - - void reset() - { - _sectionCount = 0; - _status = preHeader; - _buffer.clear(); - } - - unsigned long getSectionCount() - { - return _sectionCount; - } - - /// Reads in the next event header. - bool readHeader(readMode mode, skipMode skip, infoMode checkInfo, - const std::string& infoCondition); - - /// Reads in the next block. - bool readBlock(skipMode skip, infoMode checkInfo, - const std::string& infoCondition) ; - - /// Skips an event/information chunk. - bool skip(); - - /// Goes back one event or information chunk. - bool previous(); - - /// Reads in the header of the next event. False is returned if not successful. - bool next(skipMode skip = on, infoMode checkInfo = ignore, - const std::string& infoCondition = "") - { - return readHeader(all, skip, checkInfo, infoCondition); - } - - - /// Reads the next block and puts data into the input stream. False is returned if not successful. - bool nextBlock(skipMode skip = on, infoMode checkInfo = ignore, - const std::string& infoCondition = "") - { - return readBlock(skip, checkInfo, infoCondition); - } - - /// Access to the data read in the individual blocks. - inline const InputStream& getInputStream() - { - return _buffer; - } - - - bool isBlock() - { - return (_stream.peek()=='B'); - } - - bool isEnd() - { - return (_stream.peek()=='e'); - } - - /// Method used internally to get the status, indicating the position in the I/O file. - inline statusFlag getStatus() const - { - return _status; - } - - inline void setStatus(statusFlag flag) - { - _status=flag; - } - - void endEvent() - { - if (_status!=preHeader) - while (nextBlock()) - ; - } - - /// Returns the size of the associated file. - size_t getSize() const; - - /// Returns the current position in the associated file. - size_t getPosition() const - { - return _stream.tell(); - } - - bool eof() const - { - return _stream.peek()==EOF; - } - -protected: - /// Helper method to perform the unzipping. - int unzipEventData(uint32_t nBytes) ; - - /// Reads in a char from file and returns this. - inline char nextBlockId() - { - char identifier; - _stream.read(&identifier, 1); - return identifier; - } - -private: - ChunkReader(const ChunkReader& original) : _stream(original._stream) - { - } - - ChunkReader& operator= (const ChunkReader& other) - { - return *this; - } - - - FileImpl& _stream; - BufferInput _buffer; - /// Status flag. 0 at end of event, 1 at end of block. - statusFlag _status; - unsigned long _sectionCount; - fileMode _seekMode; - - unsigned char* _inputBuffer; - unsigned char* _outputBuffer; -}; - -} //namespace pxl - -#endif // PXL_IO_CHUNK_READER_HH diff --git a/core/include/pxl/core/ChunkWriter.hh b/core/include/pxl/core/ChunkWriter.hh deleted file mode 100644 index 06af6898c4b276ecd4ad6e3167f5eb575f92f64b..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/ChunkWriter.hh +++ /dev/null @@ -1,105 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_IO_CHUNKWRITER_HH -#define PXL_IO_CHUNKWRITER_HH -#include "pxl/core/macros.hh" - -#include -#include -#include -#include - -#include "pxl/core/Stream.hh" -#include "pxl/core/File.hh" - -namespace pxl -{ - -// io -/** - This class implemenents methods for writing to PXL I/O files. - PXL I/O allows the storage of complete physics events and information chunks. - Each event or information chunk makes up a section in the output file. - Each section consists of a header, and a number of blocks which can be compressed individually. - The compression is incorporated via zlib. - The entry point for the standard user is the class OutputFile. - */ -class PXL_DLL_EXPORT ChunkWriter -{ -public: - ChunkWriter(FileImpl& stream, char compressionMode = '1') : - _stream(stream), _nBytes(0), _compressionMode(compressionMode) - { - } - - ~ChunkWriter() - { - } - - /// Writes the current block to the output file stream. - bool write() - { - return write(""); - } - - /// Writes a new file section, indicating the content by the section marker char, and the passed information string. - bool newFileSection(const std::string& info, char cSectionMarker = 'E'); - - /// Writes a new block marker. - inline bool newBlock() - { - // begin block marker: - return writeFlag('B'); - } - - /// Writes an end-of-file-section marker and the number of bytes stored in the event. - bool endFileSection(); - - /// Writes the current stream. An information string, and a compression mode char (allowed values between '0' and '9') are passed. - bool write(std::string info) ; - - const BufferOutput& getOutputStream() - { - return _buffer; - } - - void setCompressionMode(char compressionMode) - { - _compressionMode = compressionMode; - } - - void setCompressionMode(int compressionMode) - { - if (0 <= compressionMode && compressionMode <= 9) - _compressionMode = '0' + compressionMode; - else - throw std::runtime_error("Invalid compression mode"); - } - -protected: - /// Write char flag. - bool writeFlag(char cEvtMarker); - -private: - ChunkWriter(const ChunkWriter& original) : _stream(original._stream) - { - } - - ChunkWriter& operator= (const ChunkWriter& other) - { - return *this; - } - - FileImpl& _stream; - BufferOutput _buffer; - int32_t _nBytes; - char _compressionMode; -}; -} -#endif /*PXL_IO_CHUNKWRITER_HH*/ diff --git a/core/include/pxl/core/ConfigLoader.hh b/core/include/pxl/core/ConfigLoader.hh index 5783ea995170d7c1d8362238c82de36318fd50eb..50d31ff56c3d3d018b52833ca8826b9c3fdf3638 100644 --- a/core/include/pxl/core/ConfigLoader.hh +++ b/core/include/pxl/core/ConfigLoader.hh @@ -1,28 +1,27 @@ - //------------------------------------------- +//------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- -#ifndef PXL_CORE_CONFIGLOADER -#define PXL_CORE_CONFIGLOADER - - -#include "pxl/core/macros.hh" +#ifndef PXL_CORE_CONFIGLOADER_HH +#define PXL_CORE_CONFIGLOADER_HH #include "simpleini/SimpleIni.h" +#include "pxl/core/Macros.hh" + namespace pxl { /// Add all items from a CSimpleIniA object to the pcl Configuration instance -void PXL_DLL_EXPORT fillConfigFromSimpleIni(const CSimpleIniA &iniFile); +void PXL_DLL_EXPORT fillConfigFromSimpleIni(const CSimpleIniA& iniFile); + /// loads configurations from /etc/pxlrc and HOME/.pxlrc void PXL_DLL_EXPORT loadDefaultConfigurations(); +} // namespace pxl -} // namespace - -#endif //PXL_CORE_CONFIGLOADER +#endif // PXL_CORE_CONFIGLOADER_HH diff --git a/core/include/pxl/core/Configuration.hh b/core/include/pxl/core/Configuration.hh index 312103f3d8d95d32ac09bcbcc90475972a4a1b92..95d9c8cb24a57bf13538111e077803e8c8b238a2 100644 --- a/core/include/pxl/core/Configuration.hh +++ b/core/include/pxl/core/Configuration.hh @@ -1,56 +1,53 @@ - //------------------------------------------- +//------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- -#ifndef PXL_CORE_CONFIGURATION -#define PXL_CORE_CONFIGURATION +#ifndef PXL_CORE_CONFIGURATION_HH +#define PXL_CORE_CONFIGURATION_HH #include #include +#include "pxl/core/Macros.hh" #include "pxl/core/Variant.hh" -#include "pxl/core/macros.hh" - namespace pxl { class PXL_DLL_EXPORT Configuration { - private: - std::map< std::string, std::multimap > _data; +public: + typedef std::pair itemType; - public: + typedef std::multimap multimapType; + typedef multimapType::const_iterator multiMapConstIterator; + typedef multimapType::iterator multimapIterator; - typedef std::pair itemType; + typedef std::map mapType; + typedef mapType::const_iterator mapConstIterator; + typedef mapType::iterator mapIterator; - typedef std::multimap multimapType; - typedef multimapType::const_iterator multiMapConstIterator; - typedef multimapType::iterator multimapIterator; + Configuration(){}; - typedef std::map mapType; - typedef mapType::const_iterator mapConstIterator; - typedef mapType::iterator mapIterator; - Configuration() - { - - }; - - static Configuration &instance(); + static Configuration& instance(); - /// add key, item to section, create section if necessary - void addItem(const std::string §ion, const std::string &key, const Variant &item); + /// add key, item to section, create section if necessary + void addItem(const std::string& section, const std::string& key, const Variant& item); - /// Returns first item with key in section - const Variant &getItem(const std::string §ion, const std::string &key); + /// Returns first item with key in section + const Variant& getItem(const std::string& section, const std::string& key); - /// Returns multimap for the section - multimapType& getSection(const std::string §ion); + /// Returns multimap for the section + multimapType& getSection(const std::string& section); + +private: + std::map > _data; }; + } // namespace -#endif //PXL_CORE_CONFIGURATION +#endif // PXL_CORE_CONFIGURATION_HH diff --git a/core/include/pxl/core/Core.hh b/core/include/pxl/core/Core.hh index db4837c8a28d929c892cc409e1790bcc6fd4b59d..99db7561bca418889663072cd96507b228656ac1 100644 --- a/core/include/pxl/core/Core.hh +++ b/core/include/pxl/core/Core.hh @@ -1,15 +1,15 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- -#ifndef PXL_CORE_CLASS_HH -#define PXL_CORE_CLASS_HH +#ifndef PXL_CORE_CORE_HH +#define PXL_CORE_CORE_HH -#include "pxl/core/macros.hh" +#include "pxl/core/Macros.hh" namespace pxl { @@ -17,10 +17,10 @@ namespace pxl class PXL_DLL_EXPORT Core { public: - static void initialize(); - static void shutdown(); + static void initialize(); + static void shutdown(); }; -} +} // namespace pxl -#endif /* INITIALIZE_HH_ */ +#endif // PXL_CORE_CORE_HH diff --git a/core/include/pxl/core/Event.hh b/core/include/pxl/core/Event.hh deleted file mode 100644 index 298540fe4aa88b8b6e8f0ad82c36fa37e5b93586..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/Event.hh +++ /dev/null @@ -1,189 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_BASE_EVENT_HH -#define PXL_BASE_EVENT_HH -#include "pxl/core/macros.hh" - -#include - -#include "pxl/core/ObjectOwner.hh" -#include "pxl/core/UserRecord.hh" -#include "pxl/core/Serializable.hh" -#include "pxl/core/ObjectFactory.hh" - -namespace pxl -{ - -class PXL_DLL_EXPORT Event: public Serializable, public UserRecordHelper -{ -public: - Event() : - Serializable() - { - } - - Event(const Event& event) : - Serializable(event), UserRecordHelper(event), _objects(event._objects) - { - } - - explicit Event(const Event* event) : - Serializable(*event), UserRecordHelper(*event), _objects( - event->_objects) - { - } - - virtual ~Event() - { - } - - virtual const Id& getTypeId() const - { - return getStaticTypeId(); - } - - static const Id& getStaticTypeId(); - - virtual void serialize(const OutputStream &out) const; - virtual void deserialize(const InputStream &in); - - /// Creates a deep copy and returns a C++ pointer to the newly-created object. - virtual Serializable* clone() const - { - return new Event(*this); - } - - /// Creates a new instance of \p objecttype; - /// objecttype must be a class inheriting from pxl::Relative; - /// the newly-created instance is owned and will be deleted by the object owner. - template datatype* create() - { - return _objects.create (); - } - - // crateIndexed - /// Acts like create() and registers the newly-created instance under \p key in the index. - template datatype* createIndexed(const std::string& key) - { - datatype* obj = _objects.create (); - setIndex(key, obj); - return obj; - } - - /// Inserts \p obj in the container of the object owner and takes deletion responsability. - inline void insertObject(Relative* obj) - { - _objects.insert(obj); - } - - /// Inserts \p obj with the \p key in the container of the object owner and takes deletion responsability. - inline void insertObject(Relative* obj, const std::string& key) - { - _objects.insert(obj); - setIndex(key, obj); - } - - /// Registers the object \p obj with the \p key in the index and returns true in case of success; - /// please note that obj must be owned by this object owner and \p key must not be a zero length string. - inline bool setIndex(const std::string& key, Relative* obj) - { - return _objects.setIndexEntry(key, obj); - } - - /// Provides access to the object owner. - inline ObjectOwner& getObjectOwner() - { - return _objects; - } - - /// Provides const access to the object owner. - inline const ObjectOwner& getObjectOwner() const - { - return _objects; - } - - /// Inserts pointer references to all objects which have the type of the template argument - /// (or inherit from it) into the passed vector, which has to be a vector of pointers to the template - /// argument class. - template inline void getObjectsOfType(std::vector< - objecttype*>& vec) const - { - _objects.getObjectsOfType (vec); - } - - /// Returns a const reference to the underlying vector with pointers to all contained objects. - inline const std::vector& getObjects() const - { - return _objects.getObjects(); - } - - /// Deletes the object \p obj. - inline void removeObject(Relative* obj) - { - _objects.remove(obj); - } - - /// Takes the object \p obj from the object owner. - inline void takeObject(Relative* obj) - { - _objects.take(obj); - } - - /// Clears the object owner and deletes all owned objects. - inline void clearObjects() - { - _objects.clearContainer(); - } - - /// Searches the index for the \p key and returns a dynamically casted - /// C++ pointer of type \p objecttype* to the corresponding object; - /// in case key is not found a null pointer is returned. - template inline objecttype* findObject( - const std::string key) const - { - return _objects.findObject (key); - } - - /// Searches the copy history to locate the copy of \p original and - /// returns a dynamically casted C++ pointer of type \p objecttype* to the corresponding copy; - /// in case no copy can be traced a null pointer is returned. - template inline objecttype* findCopyOf( - const Relative* original) const - { - return _objects.findCopyOf (original); - } - - /// Provides direct access to the index. - inline const std::map& getIndex() const - { - return _objects.getIndexEntry(); - } - - /// Removes the index entry with the \p key; please notice: it does not remove the object itself. - inline void removeIndex(const std::string& key) - { - _objects.removeIndexEntry(key); - } - - /// Clears the index; please notice: it does not remove the objects themself. - inline void clearIndex() - { - _objects.clearIndex(); - } - - virtual std::ostream - & print(int level = 1, std::ostream& os = std::cout, int pan = 1) const; - -private: - ObjectOwner _objects; -}; - -} // namespace pxl - -#endif // PXL_BASE_EVENT_HH diff --git a/core/include/pxl/core/File.hh b/core/include/pxl/core/File.hh deleted file mode 100644 index 6009fc672d26540342b2222844f5743170788a74..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/File.hh +++ /dev/null @@ -1,88 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_FILE_HH_ -#define PXL_FILE_HH_ - -#include "pxl/core/macros.hh" -#include "pxl/core/functions.hh" - -#include -#include -#include - -namespace pxl -{ - -enum SeekDirectionEnum -{ - SeekBegin, SeekCurrent, SeekEnd -}; - -enum OpenModeEnum -{ - OpenRead = 1, OpenWrite = 2, OpenOverwrite = 4 -}; - -class PXL_DLL_EXPORT FileImpl -{ -public: - - virtual ~FileImpl() - { - } - - virtual bool open(const std::string &filename, int32_t mode) = 0; - virtual void close() = 0; - virtual bool isEof() = 0; - virtual bool isBad() = 0; - virtual bool isOpen() = 0; - virtual void clear() = 0; - virtual bool isGood() = 0; - virtual int64_t tell() = 0; - virtual void seek(int64_t pos, int32_t d = SeekBegin) = 0; - virtual int32_t peek() = 0; - virtual int64_t read(char *s, size_t count) = 0; - virtual int64_t write(const char *s, size_t count) = 0; - virtual void ignore(int64_t count) = 0; - - virtual void destroy() = 0; -}; - -class PXL_DLL_EXPORT File: public FileImpl -{ - FileImpl *impl; -public: - - File(); - - File(const std::string &filename, int32_t mode = OpenRead); - ~File(); - - virtual bool open(const std::string &filename, int32_t mode = OpenRead); - - virtual void close(); - - virtual bool isEof(); - - virtual bool isBad(); - virtual bool isOpen(); - virtual void clear(); - virtual bool isGood(); - virtual int64_t tell(); - virtual void seek(int64_t pos, int32_t d = SeekBegin); - virtual int32_t peek(); - virtual int64_t read(char *s, size_t count); - virtual int64_t write(const char *s, size_t count); - virtual void ignore(int64_t count); - virtual void destroy(); -}; - -} - -#endif /* PXL_FILE_HH_ */ diff --git a/core/include/pxl/core/FileFactory.hh b/core/include/pxl/core/FileFactory.hh deleted file mode 100644 index b7f58d70e44b042f1ee0865481f661000ba4111c..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/FileFactory.hh +++ /dev/null @@ -1,77 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_FILE_FACTORY_HH -#define PXL_FILE_FACTORY_HH -#include "pxl/core/macros.hh" - -#include - -#include "pxl/core/Id.hh" -#include "pxl/core/File.hh" - -namespace pxl -{ - -class FileProducerInterface; - -class PXL_DLL_EXPORT FileFactory -{ -private: - - FileFactory(); - - std::map _Producers; - -public: - - static FileFactory& instance(); - - FileImpl *create(const std::string& id); - - void registerProducer(const std::string& id, - const FileProducerInterface* producer); - void unregisterProducer(const FileProducerInterface* producer); - - bool hasSchema(const std::string& schema); -}; - -class FileProducerInterface -{ -public: - virtual ~FileProducerInterface() - { - } - - virtual FileImpl *create() const = 0; -}; - -template -class FileProducerTemplate: public FileProducerInterface -{ -public: - - void initialize(const std::string &schema) - { - FileFactory::instance().registerProducer(schema, this); - } - - void shutdown() - { - FileFactory::instance().unregisterProducer(this); - } - - FileImpl *create() const - { - return new T(); - } -}; - -} // namespace pxl - -#endif // PXL_IO_OBJECT_FACTORY_HH diff --git a/core/include/pxl/core/Filter.hh b/core/include/pxl/core/Filter.hh deleted file mode 100644 index b47b718bdfbaacc93f6c74ece5949af6bf66b539..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/Filter.hh +++ /dev/null @@ -1,93 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_BASE_FILTER_HH -#define PXL_BASE_FILTER_HH -#include "pxl/core/macros.hh" - -#include -#include - -#include "pxl/core/ObjectOwner.hh" - -namespace pxl -{ - -/** - This class template provides a generic interface for a comparison - object which can be used in a filter to sort the objects of type - \p comparetype. - */ -template class ComparatorInterface -{ -public: - virtual bool operator()(const comparetype*, const comparetype*) = 0; - virtual ~ComparatorInterface() - { - } -}; - -/** - This class template provides a generic interface for a filter - criterion which can be used in a filter to filter out objects - of type \p comparetype. - */ -template class FilterCriterionInterface -{ -public: - virtual bool operator()(const objecttype&) const = 0; - virtual ~FilterCriterionInterface() - { - } -}; - -/** - This class template provides a sorted filter for PXL objects; - it handles objects of type \p objecttype sorted by the criterion \p compare. - The user can create own filters by instantiating this class with an object type - and a criterion. - Then, the apply method can be used with a specific, user-defined filter criterion. - */ -template class Filter -{ -public: - virtual ~Filter() - { - } - - /// This method applies the filter by running over the \p objects container and fills - /// the passed vector with pointers to the objects passing the filter criterion - /// \p criterion. - /// Returns the number of filled objects. - virtual size_t apply(const ObjectOwner& objects, - std::vector& fillVector, - const FilterCriterionInterface& criterion) - { - size_t size = fillVector.size(); - - // fill map: - for (ObjectOwnerTypeIterator iter(objects); iter - !=objects.end(); ++iter) - { - if (!criterion(**iter)) - continue; - - fillVector.push_back(*iter); - } - //::iterator, compare> - compare comp; - std::sort(fillVector.begin(), fillVector.end(), comp); - return fillVector.size()-size; - } - -}; - - -} // namespace pxl - -#endif // PXL_BASE_FILTER_HH diff --git a/core/include/pxl/core/functions.hh b/core/include/pxl/core/Functions.hh similarity index 54% rename from core/include/pxl/core/functions.hh rename to core/include/pxl/core/Functions.hh index 85cce83c08a7144e37037cc9d72e95c35c0f0cbe..b950cef77d290a227ca4b55845e103de2d8e6bf6 100644 --- a/core/include/pxl/core/functions.hh +++ b/core/include/pxl/core/Functions.hh @@ -1,23 +1,24 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- -#ifndef PXL_BASE_FUNCTIONS_HH -#define PXL_BASE_FUNCTIONS_HH +#ifndef PXL_CORE_FUNCTIONS_HH +#define PXL_CORE_FUNCTIONS_HH #include #include -#include "pxl/core/macros.hh" +#include "pxl/core/Macros.hh" namespace pxl { -/// @internal This function returns a platform-specific CPU timestamp; internally used for performance tests. +/// @internal This function returns a platform-specific CPU timestamp; internally used for +/// performance tests. PXL_DLL_EXPORT double getCpuTime(); /** @@ -25,21 +26,21 @@ PXL_DLL_EXPORT double getCpuTime(); * @param s String to be trimmed. * @param t String containing whitespaces. Default: space, tab, carriage return and newline. */ -std::string PXL_DLL_EXPORT trim_right(const std::string &s, const std::string &t); +std::string PXL_DLL_EXPORT trim_right(const std::string& s, const std::string& t); /** * Function to remove whitespaces from the beginning of the string. * @param s String to be trimmed. * @param t String containing whitespaces. Default: space, tab, carriage return and newline. */ -std::string PXL_DLL_EXPORT trim_left(const std::string &s, const std::string &t); +std::string PXL_DLL_EXPORT trim_left(const std::string& s, const std::string& t); /** * Function to remove whitespaces from the beginning and the end of the string. * @param s String to be trimmed. * @param t String containing whitespaces. Default: space, tab, carriage return and newline. */ -std::string PXL_DLL_EXPORT trim(const std::string &s, const std::string &t); -std::string PXL_DLL_EXPORT trim(const std::string &s); +std::string PXL_DLL_EXPORT trim(const std::string& s, const std::string& t); +std::string PXL_DLL_EXPORT trim(const std::string& s); /** * Splits a string into pieces, and returns them in an array. @@ -48,51 +49,55 @@ std::string PXL_DLL_EXPORT trim(const std::string &s); * @param t String containing whitespaces. Default: space, tab, carriage return and newline. * @param trim_spaces Flag to decide if pieces should be trimmed. Default: false. */ -void PXL_DLL_EXPORT explode(const std::string &s, std::vector &v, - const bool trim_spaces, const std::string &t); +void PXL_DLL_EXPORT explode(const std::string& s, std::vector& v, + const bool trim_spaces, const std::string& t); /** * Function to assemble strings from a vector into one strng. * @param v Vector which conatins the string pieces. * @param t String which is places between peaces. Default: one space " ". * @return Assembled string. */ -PXL_DLL_EXPORT std::string implode(const std::vector &v, const std::string &t); +PXL_DLL_EXPORT std::string implode(const std::vector& v, const std::string& t); /** * Function to expand enviroment variables in a string. - * @param input String + * @param input String * @return input string with expanded variables. */ -std::string PXL_DLL_EXPORT expandEnvironmentVariables(const std::string &input); +std::string PXL_DLL_EXPORT expandEnvironmentVariables(const std::string& input); +PXL_DLL_EXPORT std::string& replace( + std::string& context, const std::string& from, const std::string& to); -PXL_DLL_EXPORT std::string& replace(std::string& context, const std::string& from, const std::string& to); +std::string PXL_DLL_EXPORT getParentDirectory(const std::string& path); +bool PXL_DLL_EXPORT createDirectory(const std::string& path); +bool PXL_DLL_EXPORT isAbsolutePath(const std::string& path); +bool PXL_DLL_EXPORT isDirectory(const std::string& path); +bool PXL_DLL_EXPORT isFile(const std::string& path); +std::string PXL_DLL_EXPORT clearPathName(const std::string& path); +void PXL_DLL_EXPORT splitSchema(const std::string& url, std::string& schema, std::string& path); -std::string PXL_DLL_EXPORT getParentDirectory(const std::string &path); -bool PXL_DLL_EXPORT createDirectory(const std::string &path); -bool PXL_DLL_EXPORT isAbsolutePath(const std::string &path); -bool PXL_DLL_EXPORT isDirectory(const std::string &path); -bool PXL_DLL_EXPORT isFile(const std::string &path); -std::string PXL_DLL_EXPORT clearPathName(const std::string &path); -void PXL_DLL_EXPORT splitSchema(const std::string &url, std::string &schema, std::string &path); - -template -inline void safe_delete(T* &p) +template inline void safe_delete(T*& p) { - if (p) - { - delete p; - p = 0; - } + if (p) + { + delete p; + p = 0; + } } -inline const char *safe_string(const char *ptr) { - if (ptr == 0) - return ""; - else - return ptr; +inline const char* safe_string(const char* ptr) +{ + if (ptr == 0) + { + return ""; + } + else + { + return ptr; + } } } // namespace pxl -#endif // PXL_BASE_FUNCTIONS_HH +#endif // PXL_CORE_FUNCTIONS_HH diff --git a/core/include/pxl/core/GenericInputHandler.hh b/core/include/pxl/core/GenericInputHandler.hh deleted file mode 100644 index 6676793801cb03ebe2f76383a57d7169f5a149de..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/GenericInputHandler.hh +++ /dev/null @@ -1,65 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_IO_GENERICINPUTHANDLER_HH -#define PXL_IO_GENERICINPUTHANDLER_HH -#include "pxl/core/macros.hh" - -#include - -#include "pxl/core/InputHandler.hh" -#include "pxl/core/ChunkReader.hh" - -namespace pxl -{ -// io -/** - This class offers a generic handling of the PXL I/O. Various methods to access - the PXL I/O content are offered. - */ -class GenericInputHandler : public InputHandler -{ -public: - - GenericInputHandler(ChunkReader& reader) : - InputHandler(), _reader(&reader) - { - } - - virtual ~GenericInputHandler() - { - } - - virtual ChunkReader& getChunkReader() - { - if (!_reader) - throw std::runtime_error("GenericInputHandler::getChunkReader(): ChunkReader pointer invalid."); - return *_reader; - } - - virtual void setChunkReader(ChunkReader* reader) - { - _reader=reader; - } - -private: - GenericInputHandler(const GenericInputHandler& original) - { - } - - GenericInputHandler& operator= (const GenericInputHandler& other) - { - return *this; - } - - ChunkReader* _reader; -}; - -} //namespace pxl - -#endif /*PXL_IO_GENERICINPUTHANDLER_HH*/ diff --git a/core/include/pxl/core/GenericOutputHandler.hh b/core/include/pxl/core/GenericOutputHandler.hh deleted file mode 100644 index 83b2996da036167eeebc003b58c49232debd904c..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/GenericOutputHandler.hh +++ /dev/null @@ -1,67 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_IO_GENERICOUTPUTHANDLER_HH -#define PXL_IO_GENERICOUTPUTHANDLER_HH -#include "pxl/core/macros.hh" - -#include - -#include "pxl/core/OutputHandler.hh" -#include "pxl/core/ChunkWriter.hh" - -namespace pxl -{ - -// io -/** - This class allows the user an easy handling of the PXL output using any ChunkWriter. Methods to write event headers, - the PXL event class, and information chunks are offered by inheritance from the OutputHandler. - */ - -class GenericOutputHandler : public OutputHandler -{ -public: - GenericOutputHandler(ChunkWriter& writer) : - OutputHandler(), _writer(&writer) - { - } - - virtual ~GenericOutputHandler() - { - } - - virtual ChunkWriter& getChunkWriter() - { - if (!_writer) - throw std::runtime_error("GenericOutputHandler::getChunkWriter(): ChunkWriter pointer invalid."); - return *_writer; - } - - virtual void setChunkWriter(ChunkWriter* writer) - { - _writer=writer; - } - -private: - GenericOutputHandler(const GenericOutputHandler& original) - { - } - - GenericOutputHandler& operator= (const GenericOutputHandler& other) - { - return *this; - } - - - ChunkWriter* _writer; -}; - -}//namespace pxl - -#endif /*PXL_IO_GENERICOUTPUTHANDLER_HH*/ diff --git a/core/include/pxl/core/Id.hh b/core/include/pxl/core/Id.hh index b1aa5870a5f5566786604d0c54f4daa68ec9e474..9825f6c1b6df39dc4630768211ee48f9d947f7f8 100644 --- a/core/include/pxl/core/Id.hh +++ b/core/include/pxl/core/Id.hh @@ -1,82 +1,80 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- -#ifndef PXL_BASE_ID_HH -#define PXL_BASE_ID_HH -#include "pxl/core/macros.hh" - -#include "pxl/core/Random.hh" -#include "pxl/core/macros.hh" +#ifndef PXL_CORE_ID_HH +#define PXL_CORE_ID_HH #include +#include "pxl/core/Macros.hh" +#include "pxl/core/Random.hh" #include "pxl/core/Stream.hh" -namespace pxl { +namespace pxl +{ /** - This class contains an implementation of a unique + This class contains an implementation of a unique identification (or UUID) for various objects used in PXL, e.g. Object Id or Type Id. A new Id can be created with the static method create(). */ class PXL_DLL_EXPORT Id { -private: - unsigned char bytes[16]; /// Storage for the actual 16-digit ID. - public: - /// Constructor, creates a new UUID. - Id(); - - /// Constructor, reads a UUID from the InputStream \p in.. - Id (const InputStream& in); - - /// Constructor from a char array \p id. - explicit Id(const char* id); - - /// Constructor from a string \p id. - explicit Id(const std::string& id); - - /// Constructor with explicit passing of a Random object \p rand. - Id(Random& rand); - - /// Geneate an ID with explicit passing of a Random object \p rand. - void generate(Random& rand); - - /// Generate an ID. - void generate(); - - /// Sets the ID to 0 (i.e. all components to 0). - void reset(); - - /// Create a new UUID. Standard way of creating a new Id. - static Id create(); - - bool operator ==(const Id& id) const; - bool operator !=(const Id& id) const; - - /// Less-than-operator, provides ordering of IDs. - bool operator <(const Id& op) const; - - /// Returns a string representation of the ID. - std::string toString() const; - - /// Write this Id to the OutputStream \p out - void serialize(const OutputStream &out) const; - - /// Fill the content of this Id from the InputStream \p in - void deserialize(const InputStream &in); + /// Constructor, creates a new UUID. + Id(); + + /// Constructor, reads a UUID from the InputStream \p in.. + Id(const InputStream& in); + + /// Constructor from a char array \p id. + explicit Id(const char* id); + + /// Constructor from a string \p id. + explicit Id(const std::string& id); + + /// Constructor with explicit passing of a Random object \p rand. + Id(Random& rand); + + /// Geneate an ID with explicit passing of a Random object \p rand. + void generate(Random& rand); + + /// Generate an ID. + void generate(); + + /// Sets the ID to 0 (i.e. all components to 0). + void reset(); + + /// Create a new UUID. Standard way of creating a new Id. + static Id create(); + + bool operator==(const Id& id) const; + bool operator!=(const Id& id) const; + + /// Less-than-operator, provides ordering of IDs. + bool operator<(const Id& op) const; + + /// Returns a string representation of the ID. + std::string toString() const; + + /// Write this Id to the OutputStream \p out + void serialize(const OutputStream& out) const; + + /// Fill the content of this Id from the InputStream \p in + void deserialize(const InputStream& in); + +private: + unsigned char bytes[16]; /// Storage for the actual 16-digit ID. }; -PXL_DLL_EXPORT std::ostream& operator <<(std::ostream& os, const Id &id); +PXL_DLL_EXPORT std::ostream& operator<<(std::ostream& os, const Id& id); } // namespace pxl -#endif // PXL_BASE_ID_HH - +#endif // PXL_CORE_ID_HH diff --git a/core/include/pxl/core/InfoObject.hh b/core/include/pxl/core/InfoObject.hh new file mode 100644 index 0000000000000000000000000000000000000000..a068132bf7f9b61dc8095fa910307b1c382e16fe --- /dev/null +++ b/core/include/pxl/core/InfoObject.hh @@ -0,0 +1,58 @@ +//------------------------------------------- +// Project: Physics eXtension Library (PXL) - +// http://vispa.physik.rwth-aachen.de/ - +// Copyright (C) 2006-2019 Martin Erdmann - +// RWTH Aachen, Germany - +// Licensed under a LGPL-2 or later license - +//------------------------------------------- + +#ifndef PXL_CORE_INFOOBJECT_HH +#define PXL_CORE_INFOOBJECT_HH + +#include + +#include "pxl/core/Macros.hh" +#include "pxl/core/Object.hh" +#include "pxl/core/Serializable.hh" +#include "pxl/core/WeakPtr.hh" + +namespace pxl +{ + +/** + This class holds generic information and is intended to subdivide + PXL I/O files into different sections by offering a place to store + information about the following items in the file. + The InfoObject has a name, and all information is stored and + can be accessed via the contained user records. + */ +class PXL_DLL_EXPORT InfoObject : public Object +{ +public: + /// The unique class ID (UUID) of the InfoObject. + static const Id& getStaticTypeId() + { + static const Id id("7be73236-5038-4988-ba8e-9f65a26c4e72"); + return id; + } + + virtual const Id& getTypeId() const + { + return getStaticTypeId(); + } + + /// Creates a deep copy and returns a C++ pointer to the newly-created object. + virtual Serializable* clone() const + { + return new InfoObject(*this); + } + + virtual WeakPtr* createWkPtr() + { + return new weak_ptr(this); + } +}; + +} // namespace pxl + +#endif // PXL_CORE_INFOOBJECT_HH diff --git a/core/include/pxl/core/InformationChunk.hh b/core/include/pxl/core/InformationChunk.hh deleted file mode 100644 index 0d91f9ac390b56ea4dfaeff9784bab03263d61ed..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/InformationChunk.hh +++ /dev/null @@ -1,76 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_BASE_INFORMATIONCHUNK_HH -#define PXL_BASE_INFORMATIONCHUNK_HH -#include "pxl/core/macros.hh" - -#include - -#include "pxl/core/Serializable.hh" -#include "pxl/core/UserRecord.hh" - -namespace pxl -{ -/** - This class holds generic information and is intended to subdivide - PXL I/O files into different sections by offering a place to store - information about the following items in the file. - The InformationChunk has a name, and all information is stored and - can be accessed via the contained user records. - */ -class PXL_DLL_EXPORT InformationChunk: public Serializable, - public UserRecordHelper -{ -public: - - /// Get the unique class ID (UUID) of the InformationChunk. - virtual const Id& getTypeId() const - { - return getStaticTypeId(); - } - - /// The unique class ID (UUID) of the InformationChunk. - static const Id& getStaticTypeId() - { - static const Id id("7be73236-5038-4988-ba8e-9f65a26c4e72"); - return id; - } - - /// Write data to the OutputStream \p out. - virtual void serialize(const OutputStream &out) const; - - /// Read data from the InputStream \p in. - virtual void deserialize(const InputStream &in); - - /// Creates a deep copy and returns a C++ pointer to the newly-created object. - virtual Serializable* clone() const - { - return new InformationChunk(*this); - } - - /// Set the name of the InformationChunk - void setName(const std::string& name) - { - _name = name; - } - - /// Get the name of the InformationChunk - inline const std::string& getName() const - { - return _name; - } - -private: - std::string _name; /// Name of the information chunk. - -}; - -} //namespace pxl - -#endif /*PXL_BASE_INFORMATIONCHUNK_HH*/ diff --git a/core/include/pxl/core/InputFile.hh b/core/include/pxl/core/InputFile.hh deleted file mode 100644 index 6d81460d7e2cba705bdf08367bdd84bb08a1fe12..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/InputFile.hh +++ /dev/null @@ -1,119 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_IO_INPUTFILE_HH -#define PXL_IO_INPUTFILE_HH -#include "pxl/core/macros.hh" - -#include -#include - -#include "pxl/core/InputHandler.hh" -#include "pxl/core/ChunkReader.hh" -#include "pxl/core/File.hh" -#include "pxl/core/logging.hh" - -#define PXL_LOG_MODULE_NAME "pxl::InputFile" - -namespace pxl -{ - -// io -/** - This class offers an easy handling of the PXL I/O. Various methods to access - the content of I/O files are offered. - */ -class InputFile: public InputHandler -{ -public: - - InputFile() : - InputHandler(), _stream(), _reader(_stream) - { - } - - InputFile(const std::string& filename) : - InputHandler(), _stream(), _reader(_stream, - ChunkReader::seekable) - { - this->open(filename); - } - - virtual void open(const std::string& filename) - { - if (_stream.isOpen()) - _stream.close(); - _stream.clear(); - reset(); - if (!_stream.open(filename.c_str(), OpenRead)) - { - PXL_LOG_ERROR << "Error opening file " << filename; - throw std::runtime_error("Error opening file"); - } - if (_stream.isBad()) - { - PXL_LOG_ERROR << "Bad file " << filename; - throw std::runtime_error("Bad file"); - } - _stream.seek(0, SeekBegin); - _reader.setStatus(ChunkReader::preHeader); - } - - virtual void close() - { - if (_stream.isOpen()) - _stream.close(); - reset(); - _reader.setStatus(ChunkReader::preHeader); - } - - virtual ~InputFile() - { - if (_stream.isOpen()) - _stream.close(); - } - - virtual ChunkReader& getChunkReader() - { - return _reader; - } - - virtual bool good() - { - return _stream.isGood(); - } - - virtual bool eof() - { - return _stream.isEof(); - } - - virtual bool bad() - { - return _stream.isBad(); - } - -private: - InputFile(const InputFile& original) : - _stream(), _reader(_stream, ChunkReader::seekable) - { - } - - InputFile& operator=(const InputFile& other) - { - return *this; - } - - File _stream; - ChunkReader _reader; - -}; - -} //namespace pxl - -#endif /*PXL_IO_INPUTFILE_HH*/ diff --git a/core/include/pxl/core/InputHandler.hh b/core/include/pxl/core/InputHandler.hh deleted file mode 100644 index 454f5696479f1510fc5114af327748caba45535d..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/InputHandler.hh +++ /dev/null @@ -1,210 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_IO_INPUTHANDLER_HH -#define PXL_IO_INPUTHANDLER_HH -#include "pxl/core/macros.hh" - -#include -#include - -#include "pxl/core/ChunkReader.hh" -#include "pxl/core/Id.hh" -#include "pxl/core/BasicContainer.hh" -#include "pxl/core/Event.hh" -#include "pxl/core/InformationChunk.hh" - -namespace pxl -{ -// io -/** - This abstract class offers the basic functionality for reading the PXL physics event structure. - Derived classes can handle concrete I/O operations. - */ -using namespace skipSpace; - -class PXL_DLL_EXPORT InputHandler -{ -public: - - InputHandler() : _objectCount(0) - { - } - - virtual ~InputHandler() - { - } - - virtual ChunkReader& getChunkReader() = 0; - - /// Returns the number of file sections from the current ChunkReader. - /// File sections are counted regardless of their actual content (InformationChunk, Event, etc). - unsigned long getSectionCount() - { - return getChunkReader().getSectionCount(); - } - - /// Reads in the header of the next file section (e.g. event or information chunk) - bool nextFileSection() - { - if (getChunkReader().next()) - return true; - return false; - } - - /// Reads in the next file section if the information condition is fulfilled. Else, false is returned. - bool nextFileSectionIf(const std::string& info, skipMode doSkip = on) - { - if (getChunkReader().next(doSkip, ChunkReader::evaluate, info)) - return true; - return false; - } - - - /// Use this method in case the file contains pxl::Events after a next-statement. - /// A pxl::Event is passed to this method and filled with the current event. - /// If the file section header has not been read or other objects occur, - /// false is returned. - bool readEvent(Event* event); - - /// Use this method in case the file contains pxl::Events after a next-statement. - /// A pxl::Event is passed to this method and filled with the current event. - /// If the file section header has not been read or other objects occur, - /// false is returned. - bool readEventIf(Event* event, const std::string& blockInfo, - skipMode doSkip = on); - - /// Use this method in case the file contains pxl::BasicContainers after a next-statement. - /// A pxl::BasicContainer is passed to this method and filled with the current container. - /// If the file section header has not been read or other objects occur, - /// false is returned. - bool readBasicContainer(BasicContainer* basicContainer); - - /// Use this method in case the file contains pxl::BasicContainers after a next-statement. - /// A pxl::BasicContainer is passed to this method and filled with the current container. - /// If the file section header has not been read, the info condition is not fulfilled, - /// or other objects occur, false is returned. - bool readBasicContainerIf(BasicContainer* basicContainer, const std::string& blockInfo, - skipMode doSkip = on); - - /// A pxl::InformationChunk is passed to this method and filled if the next block contains an information chunk. - /// Else, false is returned. - bool readInformationChunk(InformationChunk* chunk); - - /// A pxl::InformationChunk is passed to this method and filled if the info condition is fulfilled and there is an information chunk. - /// Else, false is returned. - bool readInformationChunkIf(InformationChunk* event, - const std::string& blockInfo, skipMode doSkip = on); - - - /// Skips one file section. - bool skip() - { - return getChunkReader().skip(); - } - - /// Goes to the previous file section. - bool previous() - { - return getChunkReader().previous(); - } - - /// With this method, n file sections can be skipped in forward or backward direction. - /// The number of actually skipped file sections is returned (positive or negative). - int skipFileSections(int n); - - /// seek to the desired file section (with 0 being the first file section) - bool seekToFileSection(int index); - - /// Reads in the next block. - bool readBlock() - { - return getChunkReader().nextBlock(); - } - - /// Reads in the next block if the info condition is fulfilled. - bool readBlockIf(const std::string& blockInfo, - skipMode doSkip = on); - - /// Explicitly reads an object of type objecttype. - /// Caution: This method should only be used if the type of the following object is known by hard. - /// Else use the readNextObject method. This method may be deprecated in the future. - template bool readObject(objecttype* obj) ; - - /// Seek to the desired object (with 0 being the first object). - /// Current implementation inefficient due to missing file index. - Serializable* seekToObject(size_t index) ; - - /// This method reads in the next object from the file, regardless of file section boundaries. - /// In case there are no more objects to be read, a zero pointer is returned. - /// Attention: This method returns an object which was created with new. The user takes - /// deletion responsibility. - Serializable* readNextObject() ; - - /// This method reads in the previous object from the file, regardless of file section boundaries. - /// Attention: This method returns an object which was created with new. The user takes - /// deletion responsibility. - Serializable* readPreviousObject() ; - - /// This method fills the objects from the read-in block into the passed vector. The number of added objects is returned. - /// Attention: The objects in the vector are created with new, the user takes deletion responsibility. - int readObjects(std::vector& objects) ; - - /// This method fills the objects from the read-in block into the passed pxl::BasicContainer. The number of added objects is returned. - /// Deletion responsibility is taken by the BasicContainer. - int readObjects(BasicContainer* container) ; - - /// This method fills the objects from the read-in block into the passed pxl::Event. The number of added objects is returned. - /// Only derivatives of pxl::Relative are filled, other items are skipped. - /// Deletion responsibility is taken by the Event. - int readObjects(Event* event) ; - - /// Returns the number of read objects - size_t objectCount() const - { - return _objectCount; - } - - /// Resets InputHandler in case a new file/stream is opened. - void reset() - { - _objectCount = 0; - getChunkReader().reset(); - } - - /// Returns the size of the associated file. - size_t getSize() - { - return getChunkReader().getSize(); - } - - /// Returns the current position in the associated file. - size_t getPosition() - { - return getChunkReader().getPosition(); - } - - -private: - InputHandler(const InputHandler& original) - { - } - - InputHandler& operator= (const InputHandler& other) - { - return *this; - } - - size_t _objectCount; - -}; - -} -//namespace pxl - -#endif //PXL_IO_INPUTHANDLER_HH diff --git a/core/include/pxl/core/Logging.hh b/core/include/pxl/core/Logging.hh new file mode 100644 index 0000000000000000000000000000000000000000..4820310e3f624cbd48f4027ca88be6e8d3618d83 --- /dev/null +++ b/core/include/pxl/core/Logging.hh @@ -0,0 +1,276 @@ +//------------------------------------------- +// Project: Physics eXtension Library (PXL) - +// http://vispa.physik.rwth-aachen.de/ - +// Copyright (C) 2006-2019 Martin Erdmann - +// RWTH Aachen, Germany - +// Licensed under a LGPL-2 or later license - +//------------------------------------------- + +#ifndef PXL_CORE_LOGGING_HH +#define PXL_CORE_LOGGING_HH + +#include +#include +#include +#include +#include + +#include "pxl/core/Functions.hh" +#include "pxl/core/Macros.hh" + +namespace pxl +{ + +enum LogLevel +{ + LOG_LEVEL_ALL, + LOG_LEVEL_DEBUG, + LOG_LEVEL_INFO, + LOG_LEVEL_WARNING, + LOG_LEVEL_ERROR, + LOG_LEVEL_NONE +}; + +PXL_DLL_EXPORT LogLevel intToLogLevel(int i); +PXL_DLL_EXPORT const std::string& LogLevelToString(LogLevel level); + +class PXL_DLL_EXPORT LogHandler +{ +public: + virtual ~LogHandler() + { + } + + virtual void handle( + LogLevel level, time_t timestamp, const std::string& module, const std::string& message) + = 0; +}; + +class PXL_DLL_EXPORT ConsoleLogHandler : public LogHandler +{ + std::vector enabledModules; + std::vector disabledModules; + std::string warningColor, errorColor, endColor; + +public: + ConsoleLogHandler(); + + virtual ~ConsoleLogHandler() + { + } + + void handle( + LogLevel level, time_t timestamp, const std::string& module, const std::string& message); +}; + +class PXL_DLL_EXPORT LogDispatcher +{ +public: + typedef std::vector > handlers_t; + + LogDispatcher(); + + void pushIndent(char c) + { + indent.append(1, c); + } + + void popIndent() + { + indent.resize(indent.length() - 1); + } + + const std::string& getIndent() + { + return indent; + } + + void setHandler(LogHandler* handler, LogLevel loglevel); + + void removeHandler(LogHandler* handler); + + void dispatch(LogLevel level, const std::string& module, const std::string& message); + + LogLevel getLowestLogLevel(); + + void disableConsoleLogHandler(); + void enableConsoleLogHandler(LogLevel level); + + static LogDispatcher& instance(); + +private: + handlers_t handlers; + LogLevel lowestLogLevel; + ConsoleLogHandler consoleLogHandler; + std::string indent; + + void updateLowestLogLevel(); +}; + +class PXL_DLL_EXPORT Logger +{ +public: + Logger(const char* module_name) + : module(module_name) + { + } + + void log(LogLevel level, const std::string& msg) + { + if (LogDispatcher::instance().getLowestLogLevel() <= level) + { + LogDispatcher::instance().dispatch( + level, module, LogDispatcher::instance().getIndent() + msg); + } + } + + template void operator()(LogLevel level, const T0& t0) + { + if (LogDispatcher::instance().getLowestLogLevel() <= level) + { + std::stringstream stream; + stream << LogDispatcher::instance().getIndent(); + stream << t0; + LogDispatcher::instance().dispatch(level, module, stream.str()); + } + } + + template void operator()(LogLevel level, const T0& t0, const T1& t1) + { + if (LogDispatcher::instance().getLowestLogLevel() <= level) + { + std::stringstream stream; + stream << LogDispatcher::instance().getIndent(); + stream << t0; + stream << " "; + stream << t1; + LogDispatcher::instance().dispatch(level, module, stream.str()); + } + } + + template + void operator()(LogLevel level, const T0& t0, const T1& t1, const T2& t2) + { + if (LogDispatcher::instance().getLowestLogLevel() <= level) + { + std::stringstream stream; + stream << LogDispatcher::instance().getIndent(); + stream << t0 << " " << t1 << " " << t2; + LogDispatcher::instance().dispatch(level, module, stream.str()); + } + } + + template + void operator()(LogLevel level, const T0& t0, const T1& t1, const T2& t2, const T3& t3) + { + if (LogDispatcher::instance().getLowestLogLevel() <= level) + { + std::stringstream stream; + stream << LogDispatcher::instance().getIndent(); + stream << t0 << " " << t1 << " " << t2 << " " << t3; + LogDispatcher::instance().dispatch(level, module, stream.str()); + } + } + + template + void operator()( + LogLevel level, const T0& t0, const T1& t1, const T2& t2, const T3& t3, const T4& t4) + { + if (LogDispatcher::instance().getLowestLogLevel() <= level) + { + std::stringstream stream; + stream << LogDispatcher::instance().getIndent(); + stream << t0 << " " << t1 << " " << t2 << " " << t3 << " " << t4; + LogDispatcher::instance().dispatch(level, module, stream.str()); + } + } + + template + void operator()(LogLevel level, const T0& t0, const T1& t1, const T2& t2, const T3& t3, + const T4& t4, const T5& t5) + { + if (LogDispatcher::instance().getLowestLogLevel() <= level) + { + std::stringstream stream; + stream << LogDispatcher::instance().getIndent(); + stream << t0 << " " << t1 << " " << t2 << " " << t3 << " " << t4 << " " << t5; + LogDispatcher::instance().dispatch(level, module, stream.str()); + } + } + + template + void operator()(LogLevel level, const T0& t0, const T1& t1, const T2& t2, const T3& t3, + const T4& t4, const T5& t5, const T6& t6) + { + if (LogDispatcher::instance().getLowestLogLevel() <= level) + { + std::stringstream stream; + stream << LogDispatcher::instance().getIndent(); + stream << t0 << " " << t1 << " " << t2 << " " << t3 << " " << t4 << " " << t5 << " " + << t6; + LogDispatcher::instance().dispatch(level, module, stream.str()); + } + } + +private: + std::string module; +}; + +class LogBuffer +{ +public: + LogBuffer(LogLevel level, const char* module); + ~LogBuffer(); + + inline operator std::ostream&() + { + return stream; + } + + template inline LogBuffer& operator<<(T& data) + { + stream << data; + return *this; + } + + inline LogBuffer& operator<<(std::ostream& (*func)(std::ostream&)) + { + stream << func; + return *this; + } + +private: + std::stringstream stream; + LogLevel level; + const char* module; +}; + +} // namespace pxl + +#define PXL_LOG_DEBUG \ + if (pxl::LogDispatcher::instance().getLowestLogLevel() > pxl::LOG_LEVEL_DEBUG) \ + { \ + } \ + else \ + pxl::LogBuffer(pxl::LOG_LEVEL_DEBUG, PXL_LOG_MODULE_NAME) +#define PXL_LOG_INFO \ + if (pxl::LogDispatcher::instance().getLowestLogLevel() > pxl::LOG_LEVEL_INFO) \ + { \ + } \ + else \ + pxl::LogBuffer(pxl::LOG_LEVEL_INFO, PXL_LOG_MODULE_NAME) +#define PXL_LOG_WARNING \ + if (pxl::LogDispatcher::instance().getLowestLogLevel() > pxl::LOG_LEVEL_WARNING) \ + { \ + } \ + else \ + pxl::LogBuffer(pxl::LOG_LEVEL_WARNING, PXL_LOG_MODULE_NAME) +#define PXL_LOG_ERROR \ + if (pxl::LogDispatcher::instance().getLowestLogLevel() > pxl::LOG_LEVEL_ERROR) \ + { \ + } \ + else \ + pxl::LogBuffer(pxl::LOG_LEVEL_ERROR, PXL_LOG_MODULE_NAME) + +#endif // PXL_CORE_LOGGING_HH diff --git a/core/include/pxl/core/LorentzVector.hh b/core/include/pxl/core/LorentzVector.hh index e64abd544a371a2f8afa9ab3d0bff8d31be45753..c6b2b54f20a534bfcb60bd7ff861067a53a061f4 100644 --- a/core/include/pxl/core/LorentzVector.hh +++ b/core/include/pxl/core/LorentzVector.hh @@ -1,305 +1,356 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- -#ifndef PXL_BASE_LORENTZVECTOR_HH -#define PXL_BASE_LORENTZVECTOR_HH -#include "pxl/core/macros.hh" +#ifndef PXL_CORE_LORENTZVECTOR_HH +#define PXL_CORE_LORENTZVECTOR_HH #include -#include "pxl/core/Basic3Vector.hh" #include "pxl/core/Stream.hh" +#include "pxl/core/Vector3.hh" +#include "pxl/core/Macros.hh" namespace pxl { -// pol /** - This class provides a simple Lorentz-fourvector with basic algebra. The methods provided are self-explanatory. + This class provides a simple Lorentz-fourvector with basic algebra. The methods provided are + self-explanatory. */ -class PXL_DLL_EXPORT LorentzVector : public Basic3Vector +class PXL_DLL_EXPORT LorentzVector { public: - LorentzVector() : Basic3Vector(0, 0, 0), _t(0) - { - } - - LorentzVector(const Basic3Vector &orig, double t = 0) : - Basic3Vector(orig), _t(t) - { - } - LorentzVector(const LorentzVector &orig) : - Basic3Vector(orig), _t(orig._t) - { - - } - explicit LorentzVector(const LorentzVector* orig) : - Basic3Vector(orig), _t(orig->_t) - { - } - - LorentzVector(double x, double y, double z, double t = 0) : - Basic3Vector(x, y, z), _t(t) - { - } - - virtual ~LorentzVector() - { - } - - virtual void serialize(const OutputStream &out) const - { - Basic3Vector::serialize(out); - out.writeDouble(_t); - } - - virtual void deserialize(const InputStream &in) - { - Basic3Vector::deserialize(in); - in.readDouble(_t); - } - - // setX inherited - // setY inherited - // setZ inherited - inline void setT(double t) - { - _t = t; - } - - inline void setPx(double px) - { - setX(px); - } - inline void setPy(double py) - { - setY(py); - } - inline void setPz(double pz) - { - setZ(pz); - } - - inline void setE(double e) - { - _t = e; - } - - // getX inherited - // getY inherited - // getZ inherited - inline double getT() const - { - return _t; - } - - inline double getPx() const - { - return getX(); - } - - inline double getPy() const - { - return getY(); - } - - inline double getPz() const - { - return getZ(); - } - - inline double getE() const - { - return _t; - } - - /// returns squared mass - inline double getMass2() const - { - return _t*_t - getMag2(); - } - - inline double getMass() const - { - double m2 = getMass2(); - return m2 < 0.0 ? 0.0 : std::sqrt(m2); - } - - // getPerp inherited - - /// returns transverse momentum - inline double getPt() const - { - return getPerp(); - } - - double getP() const - { - return getMag(); - } - - // getPhi inherited - // getTheta inherited - // deltaRho inherited - // deltaPhi inherited - // deltaTheta inherited - - /// returns the pseudorapidity - inline double getEta() const - { - return -std::log(std::tan(getTheta()*0.5)); - } - - /// returns the rapidity - inline double getRapidity() const - { - return 0.5 * std::log((getE()+getP())/(getE()-getP())); - } - - /// returns the rapidity relative to the beam axis - inline double getBeamlineRapidity() const - { - return 0.5 * std::log((getE()+getPz())/(getE()-getPz())); - } - - /// returns transverse energy squared - inline double getEt2() const - { - double pt2 = getPerp2(); - return pt2 == 0.0 ? 0.0 : _t*_t * pt2 / getMag2(); - } - - /// returns transverse energy - inline double getEt() const - { - return std::sqrt(getEt2()); - } - - /// returns sqrt(dEta**2 + dPhi**2) between this LorentzVector and parameter value - /// Note: This version with a passed pointer is deprecated - inline double deltaR(const LorentzVector* fv) const - { - return deltaR(*fv); - } - - /// returns sqrt(dEta**2 + dPhi**2) between this LorentzVector and parameter value - double deltaR(const LorentzVector& fv) const - { - double dDeta = deltaEta(fv); - double dDphi = deltaPhi(fv); - return std::sqrt(dDeta*dDeta + dDphi*dDphi); - } - - /// returns the difference in pseudorapidity between this and parameter value - /// Note: This version with a passed pointer is deprecated - inline double deltaEta(const LorentzVector* fv) const - { - return deltaEta(*fv); - } - - /// returns the difference in pseudorapidity between this and parameter value - double deltaEta(const LorentzVector& fv) const - { - return getEta() - fv.getEta(); - } - - /// returns the difference in rapidity between this and parameter value - inline double deltaRapidity(const LorentzVector& fv) const - { - return getRapidity() - fv.getRapidity(); - } - - /// returns the difference in beamline rapidity between this and parameter value - inline double deltaBeamlineRapidity(const LorentzVector& fv) const - { - return getBeamlineRapidity() - fv.getBeamlineRapidity(); - } - - /// returns spatial components divided by time component - inline Basic3Vector getBoostVector() const - { - return Basic3Vector(getX()/getT(), getY()/getT(), getZ()/getT()); - } - - /// LorentzBoost: Boost this vector with given vector boostvector - inline void boost(const Basic3Vector & boostvector) - { - boost(boostvector.getX(), boostvector.getY(), boostvector.getZ()); - } - - /// LorentzBoost: Boost this vector with given vector boostvector components - void boost(double b_x, double b_y, double b_z); - - /// set x,y and z components of this LorentzVector to vec - inline const LorentzVector& operator=(const Basic3Vector& vec) - { - Basic3Vector::operator=(vec); return *this; - } - - /// set this LorentzVector to vec - inline const LorentzVector& operator=(const LorentzVector& vec) - { - Basic3Vector::operator=(vec); _t = vec._t; return *this; - } - - /// this = this plus vec - inline const LorentzVector& operator+=(const LorentzVector& vec) - { - Basic3Vector::operator+=(vec); _t += vec._t; return *this; - } - - /// this = this minus vec - inline const LorentzVector& operator-=(const LorentzVector& vec) - { - Basic3Vector::operator-=(vec); _t -= vec._t; return *this; - } - - /// this = this * scalar - inline const LorentzVector& operator*=(double scalar) - { - Basic3Vector::operator*=(scalar); _t *= scalar; return *this; - } - - /// this = this / scalar - inline const LorentzVector& operator/=(double scalar) - { - Basic3Vector::operator/=(scalar); _t /= scalar; return *this; - } - - /// return a copy of this where all components are multiplied with -1. - LorentzVector operator-() const; - - /// return a copy of (this minus vec) - LorentzVector operator-(const LorentzVector&) const; - - /// return a copy of (this plus vec) - LorentzVector operator+(const LorentzVector&) const; - - /// scalar product - double operator*(const LorentzVector& vec) const; + LorentzVector() + : _E(0) + , _p(0, 0, 0) + { + } + + LorentzVector(double E, double px, double py, double pz) + : _E(E) + , _p(px, py, pz) + { + } + + LorentzVector(double px, double py, double pz) + : _E(0) + , _p(px, py, pz) + { + _E = getP(); + } + + LorentzVector(const LorentzVector& lvec) + : _E(lvec.getE()) + , _p(Vector3(lvec.getPVector())) + { + } + + explicit LorentzVector(const LorentzVector* lvec) + : _E(lvec->getE()) + , _p(Vector3(lvec->getPVector())) + { + } + + virtual ~LorentzVector() + { + } + + virtual void serialize(const OutputStream& out) const + { + out.writeDouble(_E); + _p.serialize(out); + } + + virtual void deserialize(const InputStream& in) + { + in.readDouble(_E); + _p.deserialize(in); + } + + inline void setE(double E) + { + _E = E; + } + + inline void setPx(double px) + { + _p.setX(px); + } + + inline void setPy(double py) + { + _p.setY(py); + } + + inline void setPz(double pz) + { + _p.setZ(pz); + } + + inline void setPVector(double px, double py, double pz) + { + setPx(px); + setPy(py); + setPz(pz); + } + + inline void setPVector(const Vector3& vec) + { + setPVector(vec.getX(), vec.getY(), vec.getZ()); + } + + inline double getE() const + { + return _E; + } + + inline double getE2() const + { + return _E * _E; + } + + inline Vector3& getPVector() + { + return _p; + } + + inline const Vector3& getPVector() const + { + return _p; + } + + inline double getPx() const + { + return _p.getX(); + } + + inline double getPy() const + { + return _p.getY(); + } + + inline double getPz() const + { + return _p.getZ(); + } + + inline double getPt2() const + { + return _p.getPerp2(); + } + + inline double getPt() const + { + return _p.getPerp(); + } + + inline double getP2() const + { + return _p.getMag2(); + } + + inline double getP() const + { + return _p.getMag(); + } + + inline double getMass2() const + { + return getE2() - getP2(); + } + + inline double getMass() const + { + double m2 = getMass2(); + return m2 < 0.0 ? 0.0 : std::sqrt(m2); + } + + inline double getEt2() const + { + double pt2 = getPt2(); + return pt2 == 0.0 ? 0.0 : getE2() * pt2 / getP2(); + } + + inline double getEt() const + { + return std::sqrt(getEt2()); + } + + inline double getPhi() const + { + return _p.getPhi(); + } + + inline double getTheta() const + { + return _p.getTheta(); + } + + inline double deltaPhi(const LorentzVector& lvec) const + { + return _p.deltaPhi(lvec.getPVector()); + } + + inline double deltaPhi(LorentzVector* lvec) const + { + return deltaPhi(*lvec); + } + + inline double deltaTheta(const LorentzVector& lvec) const + { + return _p.deltaTheta(lvec.getPVector()); + } + + inline double deltaTheta(LorentzVector* lvec) const + { + return deltaTheta(*lvec); + } + + inline double getEta() const + { + return -std::log(std::tan(getTheta() * 0.5)); + } + + inline double deltaEta(const LorentzVector* lvec) const + { + return deltaEta(*lvec); + } + + double deltaEta(const LorentzVector& lvec) const + { + return getEta() - lvec.getEta(); + } + + inline double deltaR(const LorentzVector* lvec) const + { + return deltaR(*lvec); + } + + double deltaR(const LorentzVector& lvec) const + { + double dDeta = deltaEta(lvec); + double dDphi = deltaPhi(lvec); + return std::sqrt(dDeta * dDeta + dDphi * dDphi); + } + + inline double getRapidity() const + { + return 0.5 * std::log((getE() + getP()) / (getE() - getP())); + } + + inline double getBeamlineRapidity() const + { + return 0.5 * std::log((getE() + getPz()) / (getE() - getPz())); + } + + inline double deltaRapidity(const LorentzVector& lvec) const + { + return getRapidity() - lvec.getRapidity(); + } + + inline double deltaRapidity(LorentzVector* lvec) const + { + return deltaRapidity(*lvec); + } + + inline double deltaBeamlineRapidity(const LorentzVector& lvec) const + { + return getBeamlineRapidity() - lvec.getBeamlineRapidity(); + } + + inline double deltaBeamlineRapidity(LorentzVector* lvec) const + { + return deltaBeamlineRapidity(*lvec); + } + + inline Vector3 getBoostVector() const + { + return Vector3(getPx() / getE(), getPy() / getE(), getPz() / getE()); + } + + void boost(double bx, double by, double bz); + + inline void boost(const Vector3& vec) + { + boost(vec.getX(), vec.getY(), vec.getZ()); + } + + /// set px, pyy and pz components of this LorentzVector to vec + inline const LorentzVector& operator=(const Vector3& vec) + { + _p = vec; + return *this; + } + + /// set this LorentzVector to lvec + inline const LorentzVector& operator=(const LorentzVector& lvec) + { + _E = lvec.getE(); + _p = lvec.getPVector(); + return *this; + } + + /// this = this plus lvec + inline const LorentzVector& operator+=(const LorentzVector& lvec) + { + _E += lvec.getE(); + _p += lvec.getPVector(); + return *this; + } + + /// this = this minus lvec + inline const LorentzVector& operator-=(const LorentzVector& lvec) + { + _E -= lvec.getE(); + _p -= lvec.getPVector(); + return *this; + } + + /// this = this * scalar + inline const LorentzVector& operator*=(double scalar) + { + _E *= scalar; + _p *= scalar; + return *this; + } + + /// this = this / scalar + inline const LorentzVector& operator/=(double scalar) + { + _E /= scalar; + _p /= scalar; + return *this; + } + + /// return a copy of this where all components are multiplied with -1. + LorentzVector operator-() const; + + /// return a copy of (this plus vec) + LorentzVector operator+(const LorentzVector&) const; + + /// return a copy of (this minus vec) + LorentzVector operator-(const LorentzVector&) const; + + /// scalar product as defined on the Minkowski space + double operator*(const LorentzVector& lvec) const; private: - double _t; - + Vector3 _p; + double _E; }; // non-member operators -PXL_DLL_EXPORT bool operator==(const LorentzVector& obj1, - const LorentzVector& obj2); -PXL_DLL_EXPORT bool operator!=(const LorentzVector& obj1, - const LorentzVector& obj2); +PXL_DLL_EXPORT bool operator==(const LorentzVector& lvec1, const LorentzVector& lvec2); +PXL_DLL_EXPORT bool operator!=(const LorentzVector& lvec1, const LorentzVector& lvec2); -PXL_DLL_EXPORT LorentzVector operator*(const double scalar, - const LorentzVector& vec); -PXL_DLL_EXPORT LorentzVector operator*(const LorentzVector& vec, - const double scalar); +PXL_DLL_EXPORT LorentzVector operator*(const double scalar, const LorentzVector& lvec); +PXL_DLL_EXPORT LorentzVector operator*(const LorentzVector& lvec, const double scalar); } // namespace pxl - -#endif // PXL_BASE_LORENTZVECTOR_HH +#endif // PXL_CORE_LORENTZVECTOR_HH diff --git a/core/include/pxl/core/Macros.hh b/core/include/pxl/core/Macros.hh new file mode 100644 index 0000000000000000000000000000000000000000..f31503171d8d51f074eda373ea08e2c0a95c3db9 --- /dev/null +++ b/core/include/pxl/core/Macros.hh @@ -0,0 +1,58 @@ +//------------------------------------------- +// Project: Physics eXtension Library (PXL) - +// http://vispa.physik.rwth-aachen.de/ - +// Copyright (C) 2006-2019 Martin Erdmann - +// RWTH Aachen, Germany - +// Licensed under a LGPL-2 or later license - +//------------------------------------------- + +#ifndef PXL_CORE_MACROS_HH +#define PXL_CORE_MACROS_HH + +#include + +#include "pxl/core/config.hh" + +#undef PXL_LIKELY +#undef PXL_UNLIKELY +#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ > 4) +#define PXL_NORETURN __attribute__((__noreturn__)) +#define PXL_LIKELY(expr) (__builtin_expect((bool)(expr), true)) +#define PXL_UNLIKELY(expr) (__builtin_expect((bool)(expr), false)) +#else +#define PXL_NORETURN +#define PXL_LIKELY(expr) (expr) +#define PXL_UNLIKELY(expr) (expr) +#endif + +#ifdef offsetof +#define PXL_OFFSETOF(t, f) ((std::ptrdiff_t)offsetof(t, f)) +#else +#define PXL_OFFSETOF(t, f) ((std::ptrdiff_t)((char*)&((t*)0)->f)) +#endif + +#define PXL_BASE(t, f, v) (reinterpret_cast(reinterpret_cast(v) - PXL_OFFSETOF(t, f))) + +#ifdef _MSC_VER +#ifdef PXL_EXPORT +#define PXL_DLL_EXPORT __declspec(dllexport) +#else +#define PXL_DLL_EXPORT __declspec(dllimport) +#endif // PXL_EXPORT +#else +#define PXL_DLL_EXPORT +#endif // _MSC_VER +#ifndef PXL_VERSION +#define PXL_VERSION "trunk" +#endif + +#ifdef WIN32 +#define PXL_PATH_SEPERATOR "\\" +#else +#define PXL_PATH_SEPERATOR "/" +#endif + +#define _STR(x) #x +#define STR(x) _STR(x) + +#endif // PXL_CORE_MACROS_HH diff --git a/core/include/pxl/core/MessageDispatcher.hh b/core/include/pxl/core/MessageDispatcher.hh index 3521d0cd4f57bd291bd7b79f71d4fe0843f28c69..dfad468ac35b4a062a7a3b32ae6b90f2a9592c70 100644 --- a/core/include/pxl/core/MessageDispatcher.hh +++ b/core/include/pxl/core/MessageDispatcher.hh @@ -1,19 +1,19 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- -#ifndef PXL_CORE_MESASSAGE_DISPATCHER_HH -#define PXL_CORE_MESASSAGE_DISPATCHER_HH +#ifndef PXL_CORE_MESASSAGEDISPATCHER_HH +#define PXL_CORE_MESASSAGEDISPATCHER_HH -#include "pxl/core/macros.hh" -#include "pxl/core/Variant.hh" - -#include #include +#include + +#include "pxl/core/Macros.hh" +#include "pxl/core/Variant.hh" namespace pxl { @@ -24,8 +24,8 @@ namespace pxl class PXL_DLL_EXPORT MessageHandler { public: - virtual ~MessageHandler(); - virtual void handleMessage(size_t mid, const Variant ¶meter) = 0; + virtual ~MessageHandler(); + virtual void handleMessage(size_t mid, const Variant& parameter) = 0; }; /** @@ -34,34 +34,33 @@ public: class PXL_DLL_EXPORT MessageDispatcher { public: - MessageDispatcher(); - ~MessageDispatcher(); + MessageDispatcher(); + ~MessageDispatcher(); - static MessageDispatcher& instance(); + static MessageDispatcher& instance(); - size_t publish(std::string mid, const Variant ¶meter); - void publish(size_t mid, const Variant ¶meter); + size_t publish(std::string mid, const Variant& parameter); + void publish(size_t mid, const Variant& parameter); - size_t subscribe(std::string mid, MessageHandler *handler); - void subscribe(size_t mid, MessageHandler *handler); + size_t subscribe(std::string mid, MessageHandler* handler); + void subscribe(size_t mid, MessageHandler* handler); - size_t unsubscribe(std::string mid, MessageHandler *handler); - void unsubscribe(size_t mid, MessageHandler *handler); - void unsubscribe(MessageHandler *handler); + size_t unsubscribe(std::string mid, MessageHandler* handler); + void unsubscribe(size_t mid, MessageHandler* handler); + void unsubscribe(MessageHandler* handler); - size_t getId(const std::string &name); - std::string getName(const size_t &mid); - const std::map getIds() const; + size_t getId(const std::string& name); + std::string getName(const size_t& mid); + const std::map getIds() const; private: - typedef std::vector handler_vector_t; - typedef std::map subscriptions_map_t; - subscriptions_map_t subscriptions; - std::map ids; - size_t lastId; + typedef std::vector handler_vector_t; + typedef std::map subscriptions_map_t; + subscriptions_map_t subscriptions; + std::map ids; + size_t lastId; }; } // namespace pxl -#endif // PXL_CORE_MESASSAGE_DISPATCHER_HH - +#endif // PXL_CORE_MESASSAGEDISPATCHER_HH diff --git a/core/include/pxl/core/NamedTMPFile.hh b/core/include/pxl/core/NamedTMPFile.hh deleted file mode 100644 index 5d4ee8310b032af336097872a5c46912c7806a93..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/NamedTMPFile.hh +++ /dev/null @@ -1,31 +0,0 @@ -#ifndef NAMED_TMP_FILE_HH -#define NAMED_TMP_FILE_HH - -#include "pxl/core/macros.hh" -#include - -#ifdef WIN32 - #include -#else - #include -#endif - -namespace pxl -{ -// holds a tempfile and clears it up on destruction -class PXL_DLL_EXPORT NamedTMPFile -{ -public: - - NamedTMPFile(); - ~NamedTMPFile(); - const std::string& getName(); - -private: - std::string _filename; -}; - -} // namespace - - -#endif //NAMED_TMP_FILE_HH diff --git a/core/include/pxl/core/Object.hh b/core/include/pxl/core/Object.hh index e6315f13a739c114f1189a59dc5c7125e09aac42..31416c3642bc55bbc7be34ee116d50400df8c3de 100644 --- a/core/include/pxl/core/Object.hh +++ b/core/include/pxl/core/Object.hh @@ -1,126 +1,179 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- -#ifndef PXL_BASE_OBJECT_HH -#define PXL_BASE_OBJECT_HH -#include "pxl/core/macros.hh" +#ifndef PXL_CORE_OBJECT_HH +#define PXL_CORE_OBJECT_HH -#include #include #include +#include -#include "pxl/core/Relative.hh" -#include "pxl/core/weak_ptr.hh" -#include "pxl/core/UserRecord.hh" -#include "pxl/core/ObjectFactory.hh" +#include "pxl/core/Macros.hh" +#include "pxl/core/Serializable.hh" +#include "pxl/core/SerializableFactory.hh" +#include "pxl/core/UserRecords.hh" +#include "pxl/core/Variant.hh" namespace pxl { +class ObjectOwner; + /** This class provides common functionalities of PXL physics objects like - data members for storing an object name and flags for status, Monte-Carlo mode and - object locking; more specific information, such as b-tags, jet cone sizes or energy + data members for storing an object name and flags for status. + more specific information, such as b-tags, jet cone sizes or energy corrections, for instance, can be stored in the so-called user records (see UserRecord). An integer workflag facilitates tagging of individual objects. */ -class PXL_DLL_EXPORT Object: public Relative, public UserRecordHelper + +/** + This base class provides common functionalities for all derived PXL objects, + such as weak pointer concept and related service routines. + It has a C++ pointer to the pxl::ObjectOwner it is aggregated in in order to avoid + mother/daughter relations to outside objects to be established. + */ +class PXL_DLL_EXPORT Object : public Serializable { public: - Object() : - Relative(), _locked(0), _workflag(0) - { - } - - Object(const Object& original) : - Relative(original), UserRecordHelper(original), _locked(original._locked), _workflag( - original._workflag) - { - } - - explicit Object(const Object* original) : - Relative(*original), UserRecordHelper(*original), _locked(original->_locked), _workflag( - original->_workflag) - { - } - - virtual const Id& getTypeId() const - { - return getStaticTypeId(); - } - - static const Id& getStaticTypeId() - { - static const Id id("3b3a2442-04f6-400e-8e30-1de2dbc8d628"); - return id; - } - - virtual void serialize(const OutputStream &out) const; - - virtual void deserialize(const InputStream &in); - - /// Creates a deep copy and returns a C++ pointer to the newly-created object. - virtual Serializable* clone() const - { - return new Object(*this); - } - - /// Returns the value of the lock flag. - inline bool isLocked() const - { - return _locked; - } - - /// Returns the value of the workflag. - inline int getWorkFlag() const - { - return _workflag; - } - - /// Sets the value of the lock flag to \p v. - inline void setLocked(bool v) - { - _locked = v; - } - - /// Sets the value of the workflag to \p v. - inline void setWorkFlag(int v) - { - _workflag = v; - } - - /// Prints out object state information on various verbosity levels. - /// @param level verbosity level - /// @param os output _stream, default is std::cout - /// @param pan print indention - /// @return output _stream - virtual std::ostream& print(int level = 1, std::ostream& os = std::cout, - int pan = 0) const; - - virtual std::ostream& printContent(int level = 1, std::ostream& os = - std::cout, int pan = 0) const; - - virtual WkPtrBase* createSelfWkPtr() - { - return new weak_ptr (this); - } + Object() + : Serializable() + , _owner(0) + , _name("default") + , _records() + { + } + + Object(const Object& obj) + : Serializable(obj) + , _owner(0) + , _name(obj._name) + , _records(obj._records) + { + } + + explicit Object(const Object* obj) + : Serializable(*obj) + , _owner(0) + , _name(obj->_name) + , _records(obj->_records) + { + } + + virtual ~Object(); + + static const Id& getStaticTypeId() + { + static const Id id("3b3a2442-04f6-400e-8e30-1de2dbc8d628"); + return id; + } + + virtual const Id& getTypeId() const + { + return getStaticTypeId(); + } + + virtual void serialize(const OutputStream& out) const; + + virtual void deserialize(const InputStream& in); + + virtual Serializable* clone() const + { + return new Object(*this); + } + + virtual WeakPtr* createWkPtr() + { + return new weak_ptr(this); + } + + /// Sets the name to the contents of \p name. + inline void setName(const std::string& name) + { + _name = name; + } + + inline void setUserRecords(const UserRecords& records) + { + _records.replace(records); + } + + inline void setUserRecord(const std::string& key, const Variant& var) + { + _records.set(key, var); + } + + /// Returns the name. + inline const std::string& getName() const + { + return _name; + } + + inline UserRecords& getUserRecords() + { + return _records; + } + + inline Variant& getUserRecord(const std::string& key) + { + return _records.get(key); + } + + inline bool hasUserRecord(const std::string& key) + { + return _records.has(key); + } + + inline void clearUserRecords() + { + _records.clear(); + } + + inline void removeUserRecord(const std::string& key) + { + _records.remove(key); + } + + /// Returns a C++ pointer to the pxl::ObjectOwner it is owned by. + inline ObjectOwner* getOwner() const + { + return _owner; + } + + /// Prints out object state information on various verbosity levels. + virtual std::ostream& print(int level = 1, std::ostream& os = std::cout, int pan = 0) const; + + virtual std::ostream& printContent( + int level = 1, std::ostream& os = std::cout, int pan = 0) const; + + /// Returns a string with the output of the virtual print method. In general, + /// there is no need for re-implementation in derived classes. + virtual const std::string toString() const + { + std::ostringstream ss; + this->print(0, ss); + return ss.str(); + } + +protected: + UserRecords _records; + std::string _name; + ObjectOwner* _owner; private: - bool _locked; - int _workflag; + Object& operator=(const Object& original) + { + return *this; + } - Object& operator=(const Object& original) - { - return *this; - } + friend class ObjectOwner; }; -} -// namespace pxl +} // namespace pxl -#endif // PXL_BASE_OBJECT_HH +#endif // PXL_CORE_OBJECT_HH diff --git a/core/include/pxl/core/ObjectFactory.hh b/core/include/pxl/core/ObjectFactory.hh deleted file mode 100644 index 9f2f7e5e4b7aeac84eff3e5e1ce035498821cf7d..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/ObjectFactory.hh +++ /dev/null @@ -1,82 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_IO_OBJECT_FACTORY_HH -#define PXL_IO_OBJECT_FACTORY_HH -#include "pxl/core/macros.hh" - -#include - -#include "pxl/core/Serializable.hh" -#include "pxl/core/Id.hh" - -// io -/** - This class serves the PXL I/O scheme by managing - the relation of classes to UUIDs. - */ - -namespace pxl -{ - -class ObjectProducerInterface; - -class PXL_DLL_EXPORT ObjectFactory -{ -private: - - ObjectFactory(); - - std::map _Producers; - -public: - - static ObjectFactory& instance(); - - Serializable *create(const Id& id); - - void - registerProducer(const Id& id, - const ObjectProducerInterface* producer); - void unregisterProducer(const ObjectProducerInterface* producer); -}; - -class ObjectProducerInterface -{ -public: - virtual ~ObjectProducerInterface() - { - } - - virtual Serializable *create() const = 0; -}; - -template -class ObjectProducerTemplate: public ObjectProducerInterface -{ -public: - - void initialize() - { - ObjectFactory::instance().registerProducer(T::getStaticTypeId(), this); - } - - void shutdown() - { - ObjectFactory::instance().unregisterProducer(this); - } - - virtual Serializable *create() const - { - return new T(); - } -}; - -} // namespace pxl - -#endif // PXL_IO_OBJECT_FACTORY_HH diff --git a/core/include/pxl/core/ObjectManager.hh b/core/include/pxl/core/ObjectManager.hh deleted file mode 100644 index a594ee9c9efce58df55a77e176b0f95a5ee2cc75..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/ObjectManager.hh +++ /dev/null @@ -1,228 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_BASE_BASICMANAGER_HH -#define PXL_BASE_BASICMANAGER_HH -#include "pxl/core/macros.hh" - -#include - -#include "pxl/core/Object.hh" -#include "pxl/core/ObjectOwner.hh" -#include "pxl/core/weak_ptr.hh" - - -namespace pxl -{ - -// pol - -/** - This class the functionality of the pxl::BasicObjectData class by providing an object owner (see pxl::ObjectOwner) and - corresponding service methods. This way, physics objects (like instances of the classes - pxl::Particle, pxl::Vertex or pxl::Collision as well as other arbitrary pxl::Relative derivatives can be - aggregated and managed. - */ -class PXL_DLL_EXPORT ObjectManager : public Object -{ -public: - ObjectManager() : - Object(), _objects() - { - } - /// This copy constructor performs a deep copy of \p original - /// with all contained objects and their (redirected) relations. - ObjectManager(const ObjectManager& original) : - Object(original), _objects(original._objects) - { - } - /// This copy constructor performs a deep copy of \p original - /// with all contained objects and their (redirected) relations. - explicit ObjectManager(const ObjectManager* original) : - Object(original), _objects(original->_objects) - { - } - - virtual const Id& getTypeId() const - { - return getStaticTypeId(); - } - - static const Id& getStaticTypeId() - { - static const Id id("86cab8f4-6c08-477d-a4e9-bd718d6f899f"); - return id; - } - - virtual void serialize(const OutputStream &out) const - { - Object::serialize(out); - _objects.serialize(out); - } - - virtual void deserialize(const InputStream &in) - { - Object::deserialize(in); - _objects.deserialize(in); - } - - /// Creates a deep copy and returns a C++ pointer to the newly-created object. - virtual Serializable* clone() const - { - return new ObjectManager(*this); - } - - // create - /// Creates a new instance of \p objecttype; - /// objecttype must be a class inheriting from pxl::Relative; - /// the newly-created instance is owned and will be deleted by the object owner. - template datatype* create() - { - return _objects.create(); - } - - // crateIndexed - /// Acts like create() and registers the newly-created instance under \p key in the index. - template datatype* createIndexed(const std::string& key) - { - datatype* obj = _objects.create(); - setIndexEntry(key, obj); - return obj; - } - - /// Inserts \p obj in the container of the object owner and takes deletion responsability. - inline void insertObject(Relative* obj) - { - _objects.insert(obj); - } - - /// Inserts \p obj with the \p key in the container of the object owner and takes deletion responsability. - inline void insertObject(Relative* obj, const std::string& key) - { - _objects.insert(obj); - setIndexEntry(key, obj); - } - - /// Registers the object \p obj with the \p key in the index and returns true in case of success; - /// please notice, that obj must be owned by this object owner and \p key must not be a zero length string. - inline bool setIndexEntry(const std::string& key, Relative* obj) - { - return _objects.setIndexEntry(key, obj); - } - - /// Provides access to the object owner. - inline ObjectOwner& getObjectOwner() - { - return _objects; - } - - /// Provides const access to the object owner. - inline const ObjectOwner& getObjectOwner() const - { - return _objects; - } - - /// Returns a const reference to the underlying vector with pointers to all contained objects. - inline const std::vector& getObjects() const - { - return _objects.getObjects(); - } - - /// Inserts pointer references to all objects which have the type of the template argument - /// (or inherit from it) into the passed vector, which has to be a vector of pointers to the template - /// argument class. - template inline void getObjectsOfType( - std::vector& vec) const - { - _objects.getObjectsOfType(vec); - } - - /// Deletes the object \p obj. - inline void removeObject(Relative* obj) - { - _objects.remove(obj); - } - - /// Takes the object \p obj from the object owner. - inline void takeObject(Relative* obj) - { - _objects.take(obj); - } - - /// Clears the object owner and deletes all owned objects. - inline void clearObjects() - { - _objects.clearContainer(); - } - - /// Searches the index for the \p key and returns a dynamically casted - /// C++ pointer of type \p objecttype* to the corresponding object; - /// in case key is not found a null pointer is returned. - template inline objecttype* findObject( - const std::string key) const - { - return _objects.findObject(key); - } - - /// Searches the copy history to locate the copy of \p original and - /// returns a dynamically casted C++ pointer of type \p objecttype* to the corresponding copy; - /// in case no copy can be traced a null pointer is returned. - template inline objecttype* findCopyOf( - const Relative* original) const - { - return _objects.findCopyOf(original); - } - - /// Provides direct access to the copy history (created by the copy constructor). - inline const std::map& getCopyHistory() const - { - return _objects.getCopyHistory(); - } - - /// Clears the copy history (created by the copy constructor). - inline void clearCopyHistory() - { - _objects.clearCopyHistory(); - } - - /// Provides direct access to the index. - inline const std::map& getIndex() const - { - return _objects.getIndexEntry(); - } - - /// Removes the index entry with the \p key; please notice: it does not remove the object itself. - inline void removeIndexEntry(const std::string& key) - { - _objects.removeIndexEntry(key); - } - - /// Clears the index; please notice: it does not remove the objects themself. - inline void clearIndex() - { - _objects.clearIndex(); - } - - virtual WkPtrBase* createSelfWkPtr() - { - return new weak_ptr(this); - } - -private: - ObjectOwner _objects; - - ObjectManager& operator=(const ObjectManager& original) - { - return *this; - } -}; - -} // namespace pxl - - -#endif // PXL_BASE_BASICMANAGER_HH diff --git a/core/include/pxl/core/ObjectOwner.hh b/core/include/pxl/core/ObjectOwner.hh index 6b3eaf631d276bad8b511bf90c1bf65b5e40a039..e7d954a91dcfe0673d1d311a4f485d29bcde9e30 100644 --- a/core/include/pxl/core/ObjectOwner.hh +++ b/core/include/pxl/core/ObjectOwner.hh @@ -1,69 +1,32 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- -#ifndef PXL_BASE_OBJECT_OWNER -#define PXL_BASE_OBJECT_OWNER -#include "pxl/core/macros.hh" +#ifndef PXL_CORE_OBJECTOWNER_HH +#define PXL_CORE_OBJECTOWNER_HH -#include -#include #include +#include +#include -#include "pxl/core/Relative.hh" -#include "pxl/core/weak_ptr.hh" +#include "pxl/core/Macros.hh" +#include "pxl/core/Object.hh" +#include "pxl/core/Serializable.hh" +#include "pxl/core/WeakPtr.hh" namespace pxl { -class ObjectOwner; - -// - - - - - - - - - - - - - - - - - - - - - - - - - - - -/// For STL-style iteration on selective class: iterator class template; -/// this iterator behaves like a normal STL iterator but ignores all objects -/// that cannot be interpreted as type objecttype (tested by dynamic casts). -/// Use in STL-style, except that either begin gets the objecttype class as template argument, -/// or a constructor of the TypeIterator is used. -template class ObjectOwnerTypeIterator -{ - typedef std::vector::const_iterator const_iterator; - typedef std::vector::iterator iterator; - -public: - /// Copy constructor. - ObjectOwnerTypeIterator(const ObjectOwnerTypeIterator& other); - - /// Constructor from ObjectOwner instance. - ObjectOwnerTypeIterator(const ObjectOwner& container); - - /// Constructor from ObjectOwner instance. - ObjectOwnerTypeIterator(const ObjectOwner* container); - - const ObjectOwnerTypeIterator operator++(int); - - const ObjectOwnerTypeIterator& operator++(); - - inline objecttype* operator*(); - - inline bool operator==(const_iterator iter); - - inline bool operator!=(const_iterator iter); - -private: - const ObjectOwner* _containerRef; - const_iterator _iter; -}; - /** - This class is an active container for Relative derivatives, such as + This class is an active container for Object derivatives, such as Vertex, Particle or EventView; it has the ownership and deletion responsability for the contained objects. The method template create() can be used to create derivatives - of Relative within object owners. The method insert() can be + of Object within object owners. The method insert() can be used to manually add objects, has() tests object ownerships, and remove() explicitely removes objects from the owner and deletes them. The copy constructor of the class ObjectOwner also produces copies of @@ -75,331 +38,291 @@ private: A further, powerful tool for targeted object access is the so-called index, which allows to map objects to unique string identifiers, the key. The method findObject() can be used to directly access objects by their keys or object-ids. - The ObjectOwner extends the functionality of the contained STL vector. It provides a selective iterator, the class template + The ObjectOwner extends the functionality of the contained STL vector. It provides a selective + iterator, the class template ObjectOwner::TypeIterator, that ignores all objects other than the specialized data type. */ -class PXL_DLL_EXPORT ObjectOwner +class PXL_DLL_EXPORT ObjectOwner : public Object { public: - ObjectOwner() : - _container(), _copyHistory(), _index(), _uuidSearchMap() - { - } - /// This copy constructor performs a deep copy of object - /// owner \p original and all contained objects with (redirected) relations. - /// A copy history keeps track of originals and copies - /// and the findCopyOf() method allows quick access to the copies. - ObjectOwner(const ObjectOwner& original) : - _container(), _copyHistory(), _index(), _uuidSearchMap() - { - this->init(original); - } - - /// This copy constructor performs a deep copy of object - /// owner \p original and all contained objects with (redirected) relations. - /// A copy history keeps track of originals and copies - /// and the findCopyOf() method allows quick access to the copies. - explicit ObjectOwner(const ObjectOwner* original) : - _container(), _copyHistory(), _index(), _uuidSearchMap() - { - this->init(*original); - } - /// This destructor deletes all contained objects. - virtual ~ObjectOwner() - { - this->clearContainer(); - } - - ObjectOwner& operator=(const ObjectOwner& original) - { - if (this != &original) - { - this->clearContainer(); - this->init(original); - } - return *this; - } - - virtual void serialize(const OutputStream &out) const; - - virtual void deserialize(const InputStream &in); - - /// Creates a new instance of \p objecttype; - /// objecttype must be a class inheriting from Relative; - /// the newly-created instance is owned and will be deleted by this object owner. - template objecttype* create() - { - objecttype* pitem = new objecttype; - pitem->_refObjectOwner = this; - _container.push_back(static_cast(pitem)); - _uuidSearchMap.insert(std::pair(pitem->getId(), pitem)); - return pitem; - } - - /// Creates a copy of \p original by invoking the copy constructor of \p objecttype; - /// \p objecttype must be a class inheriting from Relative; - /// the newly-created instance is owned and will be deleted by this object owner. - template objecttype* create( - const objecttype* original) - { - objecttype* pitem = new objecttype(*original); - pitem->_refObjectOwner = this; - _container.push_back(static_cast(pitem)); - _uuidSearchMap.insert(std::pair(pitem->getId(), pitem)); - return pitem; - } - - /// Inserts \p value in the container of this object owner and takes deletion responsibility. - void set(Relative* value) - { - insert(value); - } - - /// Inserts \p value in the container of this object owner and takes deletion responsibility. - void insert(Relative* value) ; - - /// Deletes \p value. - void remove(Relative* value); - - /// Takes \p value from the object owner, meaning that - /// the object owner loses the ownership of \p value. - void take(Relative* value); - - /// Returns true if \p value is owned by this object owner. - bool has(const Relative* value) const; - - /// Clears the object owner and deletes all owned objects. - void clearContainer(); - - /// Searches the index for the \p key and returns a dynamically casted - /// C++ pointer of type \p objecttype* to the corresponding object; - /// in case key is not found, a null pointer is returned. - template inline objecttype* findObject( - const std::string& key) const // goes via Index & casts - - { - std::map::const_iterator it = _index.find(key); - if (it!=_index.end()) - return dynamic_cast(it->second); - return 0; - } - - /// Searches the index for the \p key and returns a dynamically casted - /// and returns a Relative pointer to the corresponding object. - /// In case \p key is not found, a null pointer is returned. - inline Relative* findObject(const std::string& key) const - { - std::map::const_iterator it = _index.find(key); - if (it!=_index.end()) - return it->second; - return 0; - } - - /// Returns a Relative pointer for a contained object with the passed ID. - /// In case the Relative is not in the container, 0 is returned. - Relative* getById(Id id) const - { - std::map::const_iterator found = _uuidSearchMap.find(id); - if ( found != _uuidSearchMap.end() ) - return found->second; - return 0; - } - - /// Searches the copy history to locate the copy of \p original and - /// returns a dynamically casted C++ pointer of type \p objecttype* to the corresponding copy; - /// in case no copy can be traced a null pointer is returned. - template objecttype* findCopyOf( - const Relative* original) const // goes via CopyHistory & casts - - { - std::map::const_iterator it = _copyHistory.find(original->id()); - if (it!=_copyHistory.end()) - return dynamic_cast(it->second); - return 0; - } - - /// Provides direct access to the copy history (created by the copy constructor). - inline const std::map& getCopyHistory() const - { - return _copyHistory; - } - /// Clears the copy history (created by the copy constructor). - inline void clearCopyHistory() - { - _copyHistory.clear(); - } - - /// Registers the object \p obj with the \p key in the index and returns true in case of success; - /// in case the key string is present, by default an error message is given. A bool can be set which allows overwriting. - /// Please notice that \p obj must be owned by this object owner and \p key must not be a zero length string. - bool setIndexEntry(const std::string& key, Relative* obj, bool overwrite = false); - - /// Provides direct read access to the index. - inline const std::map& getIndexEntry() const - { - return _index; - } - /// Removes the index entry with the \p key; please notice: it does not remove the object itself. - inline void removeIndexEntry(const std::string& key) - { - _index.erase(key); - } - /// Clears the index; please notice: it does not remove the objects themselves. - inline void clearIndex() - { - _index.clear(); - } - - /// Allows read access to the contained STL vector of Relative pointers to, e.g., use STL algorithms. - const std::vector& getObjects() const - { - return _container; - } - - /// Typedef for standard const_iterator. - typedef std::vector::const_iterator const_iterator; - typedef std::vector::iterator iterator; - - /// This returns the const iterator to the first element of the contained vector. - inline const_iterator begin() const - { - return _container.begin(); - } - - /// This returns the iterator to the first element of the contained vector. - inline iterator begin() - { - return _container.begin(); - } - - /// This returns the const iterator to the end of the contained vector. - inline const_iterator end() const - { - return _container.end(); - } - - /// This returns the iterator to the end of the contained vector. - inline iterator end() - { - return _container.end(); - } - - /// Returns the number of elements the ObjectOwner holds. - inline size_t size() const - { - return _container.size(); - } - - /// Fills into the passed vector weak pointers to the objects of the type specified by the template argument. - template size_t getObjectsOfType(std::vector& vec) const - { - size_t size = vec.size(); - for (ObjectOwner::const_iterator iter = begin(); iter!=end(); ++iter) - { - objecttype* obj = dynamic_cast(*iter); - if (obj!=0) - vec.push_back(obj); - } - return vec.size()-size; - } - - - - /// This templated method provides an STL-style begin()-method to - /// initialise the TypeIterator. - template const ObjectOwnerTypeIterator begin() const - { - ObjectOwnerTypeIterator it(this); - return it; - } - - /// Sorts the container according to the passed function. - /// See the STL sort documentation for more details and examples. - void sort(int (*comp)(Relative*, Relative*)) - { - std::sort(_container.begin(), _container.end(), comp); - } - + typedef std::vector objects_t; + typedef std::map index_t; + + ObjectOwner() + : Object() + , _objects() + , _copyHistory() + , _index() + , _uuidSearchMap() + { + } + + /// This copy constructor performs a deep copy of object + /// owner \p owner and all contained objects with (redirected) relations. + /// A copy history keeps track of originals and copies + /// and the findCopyOf() method allows quick access to the copies. + ObjectOwner(const ObjectOwner& owner) + : Object() + , _objects() + , _copyHistory() + , _index() + , _uuidSearchMap() + { + init(owner); + } + + /// This copy constructor performs a deep copy of object + /// owner \p owner and all contained objects with (redirected) relations. + /// A copy history keeps track of originals and copies + /// and the findCopyOf() method allows quick access to the copies. + explicit ObjectOwner(const ObjectOwner* owner) + : Object() + , _objects() + , _copyHistory() + , _index() + , _uuidSearchMap() + { + init(*owner); + } + /// This destructor deletes all contained objects. + virtual ~ObjectOwner() + { + clearObjects(); + } + + static const Id& getStaticTypeId() + { + static const Id id("5c007b2c-782d-44fd-8de3-fa879b1f2078"); + return id; + } + + virtual const Id& getTypeId() const + { + return getStaticTypeId(); + } + + virtual WeakPtr* createWkPtr() + { + return new weak_ptr(this); + } + + virtual void serialize(const OutputStream& out) const; + + virtual void deserialize(const InputStream& in); + + /// Returns true if \p obj is owned by this object owner. + bool hasObject(const Object* obj) const; + + /// Inserts \p obj in the container of this object owner and takes deletion responsibility. + void insertObject(Object* obj); + + /// Takes \p obj from the object owner, meaning that + /// the object owner loses the ownership of \p obj. + void takeObject(Object* obj); + + /// Creates a new instance of \p objecttype; + /// objecttype must be a class inheriting from Object; + /// the newly-created instance is owned and will be deleted by this object owner. + template objecttype* createObject() + { + objecttype* obj = new objecttype(); + insertObject(obj); + return obj; + } + + /// Acts like create() and registers the newly-created instance under \p key in the index. + template objecttype* createObject(const std::string& key) + { + objecttype* obj = createObject(); + indexObject(obj, key); + return obj; + } + + /// Returns a Object pointer for a contained object with the passed ID. + /// In case the Object is not in the container, 0 is returned. + inline Object* findObject(Id id) const + { + std::map::const_iterator it = _uuidSearchMap.find(id); + if (it != _uuidSearchMap.end()) + { + return it->second; + } + return 0; + } + + template inline objecttype* findObject(Id id) const + { + return dynamic_cast(findObject(id)); + } + + /// Searches the index for the \p key and returns a dynamically casted + /// and returns a Object pointer to the corresponding object. + /// In case \p key is not found, a null pointer is returned. + inline Object* findObject(const std::string& key) const + { + index_t::const_iterator it = _index.find(key); + if (it != _index.end()) + { + return it->second; + } + return 0; + } + + /// Searches the index for the \p key and returns a dynamically casted + /// C++ pointer of type \p objecttype* to the corresponding object; + /// in case key is not found, a null pointer is returned. + template + inline objecttype* findObject(const std::string& key) const // goes via Index & casts + { + index_t::const_iterator it = _index.find(key); + if (it != _index.end()) + { + return dynamic_cast(it->second); + } + return 0; + } + + /// Registers the object \p obj with the \p key in the index and returns true in case of + /// success; + /// in case the key string is present, by default an error message is given. A bool can be set + /// which allows overwriting. + /// Please notice that \p obj must be owned by this object owner and \p key must not be a zero + /// length string. + bool indexObject(Object* obj, const std::string& key, bool overwrite = true); + + /// Removes the index entry with the \p key; please notice: it does not remove the object + /// itself. + inline void removeIndex(const std::string& key) + { + _index.erase(key); + } + + /// Deletes \p obj. + void removeObject(Object* obj, bool destruct = true); + + /// Allows read access to the contained STL vector of Object pointers to, e.g., use STL + /// algorithms. + const std::vector& getObjects() const + { + return _objects; + } + + /// Fills into the passed vector weak pointers to the objects of the type specified by the + /// template argument. + template size_t getObjectsOfType(std::vector& vec) const + { + size_t size = vec.size(); + for (objects_t::const_iterator iter = begin(); iter != end(); ++iter) + { + objecttype* obj = dynamic_cast(*iter); + if (obj) + { + vec.push_back(obj); + } + } + return vec.size() - size; + } + + /// Provides direct read access to the index. + inline const index_t& getIndex() const + { + return _index; + } + + /// Clears the object owner and deletes all owned objects. + void clearObjects(); + + /// Clears the index; please notice: it does not remove the objects themselves. + inline void clearIndex() + { + _index.clear(); + } + + /// Returns the number of elements the ObjectOwner holds. + inline size_t size() const + { + return _objects.size(); + } + + /// Sorts the container according to the passed function. + /// See the STL sort documentation for more details and examples. + void sort(int (*comp)(Object*, Object*)) + { + std::sort(_objects.begin(), _objects.end(), comp); + } + + /// Searches the copy history to locate the copy of \p original and + /// returns a dynamically casted C++ pointer of type \p objecttype* to the corresponding copy; + /// in case no copy can be traced a null pointer is returned. + template objecttype* findCopyOf(const Object* original) const + { + std::map::const_iterator it = _copyHistory.find(original->getId()); + if (it != _copyHistory.end()) + { + return dynamic_cast(it->second); + } + return 0; + } + + /// Provides direct access to the copy history (created by the copy constructor). + inline const std::map& getCopyHistory() const + { + return _copyHistory; + } + /// Clears the copy history (created by the copy constructor). + inline void clearCopyHistory() + { + _copyHistory.clear(); + } + + virtual std::ostream& print(int level = 1, std::ostream& os = std::cout, int pan = 1) const; + + /// This returns the const iterator to the first element of the contained vector. + inline objects_t::const_iterator begin() const + { + return _objects.begin(); + } + + /// This returns the iterator to the first element of the contained vector. + inline objects_t::iterator begin() + { + return _objects.begin(); + } + + /// This returns the const iterator to the end of the contained vector. + inline objects_t::const_iterator end() const + { + return _objects.end(); + } + + /// This returns the iterator to the end of the contained vector. + inline objects_t::iterator end() + { + return _objects.end(); + } + + ObjectOwner& operator=(const ObjectOwner& owner) + { + if (this != &owner) + { + clearObjects(); + init(owner); + } + return *this; + } + +protected: + objects_t _objects; private: - void init(const ObjectOwner& original); - - std::vector _container; - std::map _copyHistory; - std::map _index; - std::map _uuidSearchMap; + void init(const ObjectOwner& original); + index_t _index; + std::map _copyHistory; + std::map _uuidSearchMap; }; -/// Copy constructor. -template -ObjectOwnerTypeIterator::ObjectOwnerTypeIterator(const ObjectOwnerTypeIterator& other) : - _containerRef(other._containerRef), _iter(other._iter) -{ -} - -/// Constructor from ObjectOwner instance. -template -ObjectOwnerTypeIterator::ObjectOwnerTypeIterator(const ObjectOwner& container) : - _containerRef(&container), _iter(container.begin()) -{ - if ( _iter!=_containerRef->end() && dynamic_cast(*_iter)==0) - (*this)++; -} - -/// Constructor from ObjectOwner instance. -template -ObjectOwnerTypeIterator::ObjectOwnerTypeIterator(const ObjectOwner* container) : -_containerRef(container), _iter(container->begin()) -{ - if ( _iter!=_containerRef->end() && dynamic_cast(*_iter)==0) - (*this)++; -} - -template -const ObjectOwnerTypeIterator ObjectOwnerTypeIterator::operator++(int) -{ - ObjectOwnerTypeIterator orig = *this; - if (_iter!=_containerRef->end()) - do - _iter++; - while (_iter!=_containerRef->end() - && dynamic_cast(*_iter)==0); - return orig; -} - -template -const ObjectOwnerTypeIterator& ObjectOwnerTypeIterator::operator++() -{ - if (_iter!=_containerRef->end()) - do - _iter++; - while (_iter!=_containerRef->end() - && dynamic_cast(*_iter)==0); - return *this; -} - -template -inline objecttype* ObjectOwnerTypeIterator::operator*() -{ - return _iter==_containerRef->end() ? 0 - : dynamic_cast(*_iter); -} - -template -inline bool ObjectOwnerTypeIterator::operator==(const_iterator iter) -{ - return (_iter==iter); -} - -template -inline bool ObjectOwnerTypeIterator::operator!=(const_iterator iter) -{ - return (_iter!=iter); -} - - } // namespace pxl -#endif // PXL_BASE_OBJECT_OWNER +#endif // PXL_CORE_OBJECTOWNER_HH diff --git a/core/include/pxl/core/OutputFile.hh b/core/include/pxl/core/OutputFile.hh deleted file mode 100644 index 35dd32cbbfba778222b3c0936f8f198a384e5342..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/OutputFile.hh +++ /dev/null @@ -1,51 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_IO_OUTPUTFILE_HH -#define PXL_IO_OUTPUTFILE_HH -#include "pxl/core/macros.hh" - -#include - -#include "pxl/core/OutputHandler.hh" -#include "pxl/core/ChunkWriter.hh" - -namespace pxl -{ - -// io -/** - This class allows the user an easy handling of the PXL output to file. Methods to write event headers, - the PXL event class, and information chunks are offered by inheritance from the OutputHandler. - */ - -class PXL_DLL_EXPORT OutputFile : public OutputHandler -{ -public: - - OutputFile(const std::string& filename, size_t maxBlockSize = 1048576, size_t maxNObjects = 1000); - virtual ~OutputFile(); - virtual void open(const std::string& filename); - virtual void close(); - virtual ChunkWriter& getChunkWriter(); - - void setCompressionMode(int compressionMode); - -private: - - OutputFile(const OutputFile& original); - - OutputFile& operator= (const OutputFile& other); - - File _stream; - ChunkWriter _writer; -}; - -}//namespace pxl - -#endif /*PXL_IO_OUTPUTFILE_HH*/ diff --git a/core/include/pxl/core/OutputHandler.hh b/core/include/pxl/core/OutputHandler.hh deleted file mode 100644 index be507c90ad2442468d853bc257d2540cfa1aeaa2..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/OutputHandler.hh +++ /dev/null @@ -1,149 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_IO_OUTPUTHANDLER_HH -#define PXL_IO_OUTPUTHANDLER_HH -#include "pxl/core/macros.hh" - -#include - -#include "pxl/core/ChunkWriter.hh" -#include "pxl/core/InformationChunk.hh" -#include "pxl/core/Event.hh" -#include "pxl/core/BasicContainer.hh" - -namespace pxl -{ - -// io -/** - This abstract class allows the user an easy handling of the PXL general output. Methods to write event headers, - the PXL event class, and information chunks are offered. - */ -class PXL_DLL_EXPORT OutputHandler -{ -public: - /// Creates an OutputHandler with a maximum size after which a block is written. - /// Set the maximum size to 0 (or smaller) to not let this happen automatically. - OutputHandler(size_t maxSize = 1048576, size_t maxNObjects = 1000); - - virtual ~OutputHandler(); - - virtual ChunkWriter& getChunkWriter() = 0; - - - /// Queues the passed object for later writing to the output file. - void streamObject(const Serializable* obj) - { - obj->serialize(getChunkWriter().getOutputStream()); - _nObjects++; - if ((_maxSize>0 && getOutputStream().buffer.size() > _maxSize) || (_maxNObjects>0 &&_nObjects > _maxNObjects)) - writeFileSection(); - } - - /// Streams the passed pxl::Event to the output file. - /// A file section is finished if the given maximum section size is reached. - void writeEvent(const Event* event) - { - event->serialize(getChunkWriter().getOutputStream()); - _nObjects++; -// if ((_maxSize>0 && getOutputStream().getSize() > _maxSize) || (_maxNObjects>0 &&_nObjects > _maxNObjects)) -// writeStream(); - // Restore backwards compatible behaviour for VISPA. Will be changed if necessary - // functionality in PXL - writeFileSection(); - - } - - /// Writes the passed pxl::InformationChunk to the output file. - void writeInformationChunk(const InformationChunk* infoChunk) - { - infoChunk->serialize(getChunkWriter().getOutputStream()); - _nObjects++; -// if ((_maxSize>0 && getOutputStream().getSize() > _maxSize) || (_maxNObjects>0 &&_nObjects > _maxNObjects)) -// writeStream(); - // Restore backwards compatible behaviour for VISPA. Will be changed if necessary - // functionality in PXL - writeFileSection(); - } - - /// Writes the passed pxl::BasicContainer to the output file. - void writeBasicContainer(const BasicContainer* basicContainer) - { - basicContainer->serialize(getChunkWriter().getOutputStream()); - _nObjects++; -// if ((_maxSize>0 && getOutputStream().getSize() > _maxSize) || (_maxNObjects>0 &&_nObjects > _maxNObjects)) -// writeStream(); - // Restore backwards compatible behaviour for VISPA. Will be changed if necessary - // functionality in PXL - writeFileSection(); - } - - /// Returns the associated OutputStream - const BufferOutput& getOutputStream() - { - return getChunkWriter().getOutputStream(); - } - - /// Use this method to write an information string describing the new file section (same as event). Otherwise, this method need not necessarily be used. - bool newFileSection(const std::string& info); - - /// Use this method to write out a block to file. This method is not needed if you use the writeFileSection-method. - bool writeStream(const std::string& info = ""); - - /// Use this method to write out a block to disk and finish the current file section. - bool writeFileSection(const std::string& info = ""); - - /// Finishes the section in case the stream not written to file - void finish() - { - if (getOutputStream().buffer.size() > 0) - writeFileSection(); - } - - void setMaxNObjects(size_t maxNObjects) - { - _maxNObjects = maxNObjects; - } - - size_t getMaxNObjects() const - { - return _maxNObjects; - } - - void setMaxSize(size_t maxSize) - { - _maxSize = maxSize; - } - - size_t getMaxSize() const - { - return _maxSize; - } - - -private: - OutputHandler(const OutputHandler& original) - { - } - - OutputHandler& operator= (const OutputHandler& other) - { - return *this; - } - - size_t _maxSize; - bool _newFileSection; - size_t _maxNObjects; - size_t _nObjects; -}; - -} -//namespace pxl - -#endif /*PXL_IO_OUTPUTHANDLER_HH*/ diff --git a/core/include/pxl/core/PluginManager.hh b/core/include/pxl/core/PluginManager.hh index 05e7f9311d2025eada91e031f3d6683494a95ba4..8d7d71546d554b9db994dc9df3dbb32f5a0429f2 100644 --- a/core/include/pxl/core/PluginManager.hh +++ b/core/include/pxl/core/PluginManager.hh @@ -1,59 +1,64 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- -#ifndef PXL_CORE_PLUGIN_MANAGER_H -#define PXL_CORE_PLUGIN_MANAGER_H +#ifndef PXL_CORE_PLUGINMANAGER_HH +#define PXL_CORE_PLUGINMANAGER_HH #include -#include #include +#include -#include "pxl/core/macros.hh" +#include "pxl/core/Macros.hh" namespace pxl { class PXL_DLL_EXPORT PluginManager { - void loadSharedLibrary(const std::string &filename); public: + PluginManager(); + virtual ~PluginManager(); + void shutdown(); - PluginManager(); - virtual ~PluginManager(); - void shutdown(); + static PluginManager& instance(); + static std::string getUserPluginDirectory(); + static std::string getDefaultPluginDirectory(); - static PluginManager &instance(); - static std::string getUserPluginDirectory(); - static std::string getDefaultPluginDirectory(); + void loadPlugin(const std::string& filename); + void loadPluginsFromDirectory(const std::string& name); + void loadPlugins(); + void loadConfiguration(const std::string& filename); - void loadPlugin(const std::string &filename); - void loadPluginsFromDirectory(const std::string &name); - void loadPlugins(); - void loadConfiguration(const std::string &filename); +protected: + void loadSharedLibrary(const std::string& filename); }; } // namespace pxl #ifdef _MSC_VER -#define PXL_PLUGIN_EXPORT __declspec( dllexport ) +#define PXL_PLUGIN_EXPORT __declspec(dllexport) #else #define PXL_PLUGIN_EXPORT #endif -#define PXL_PLUGIN_INIT extern "C" \ - int PXL_PLUGIN_EXPORT pxl_initialize_plugin (int major, int minor) { \ - if (major != PXL_MAJOR_VERSION_VALUE || minor != PXL_MINOR_VERSION_VALUE) { \ - printf("this plugin was build with PXL %d.%d", PXL_MAJOR_VERSION_VALUE,PXL_MINOR_VERSION_VALUE ); \ - return 1; \ - }else { \ - initialize(); \ - return 0; \ - } \ - } \ - -#endif // PXL_PLUGIN_MANAGER_H +#define PXL_PLUGIN_INIT \ + extern "C" int PXL_PLUGIN_EXPORT pxl_initialize_plugin(int major, int minor) \ + { \ + if (major != PXL_VERSION_MAJOR_INT || minor != PXL_VERSION_MINOR_INT) \ + { \ + printf("this plugin was build with PXL %s", PXL_VERSION_LIB); \ + return 1; \ + } \ + else \ + { \ + initialize(); \ + return 0; \ + } \ + } + +#endif // PXL_CORE_PLUGINMANAGER_HH diff --git a/core/include/pxl/core/Random.hh b/core/include/pxl/core/Random.hh index 35cee4855c54d6b05e9ec9182e515c91c0c9fc0d..996b61cbb9639b90034f4b23c4de12a01350aa23 100644 --- a/core/include/pxl/core/Random.hh +++ b/core/include/pxl/core/Random.hh @@ -17,7 +17,7 @@ // Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, // Copyright (C) 2000 - 2003, Richard J. Wagner -// All rights reserved. +// All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions @@ -30,8 +30,8 @@ // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // -// 3. The names of its contributors may not be used to endorse or promote -// products derived from this software without specific prior written +// 3. The names of its contributors may not be used to endorse or promote +// products derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS @@ -57,143 +57,167 @@ // Parts of this file are modified beginning in 29.10.09 for adaption in // PXL. - #ifndef PXL_BASE_RANDOM_HH #define PXL_BASE_RANDOM_HH // Not thread safe (unless auto-initialization is avoided and each thread has // its own Random object) +#include #include #include #include #include -#include -//necessary for win32 +// necessary for win32 #ifndef M_PI - #define M_PI 3.14159265358979323846 +#define M_PI 3.14159265358979323846 #endif +#include "pxl/core/Vector3.hh" +#include "pxl/core/Macros.hh" #include -#include "pxl/core/macros.hh" -#include "pxl/core/Basic3Vector.hh" -namespace pxl{ +namespace pxl +{ -class PXL_DLL_EXPORT Random{ +class PXL_DLL_EXPORT Random +{ public: #ifndef uint32 - typedef unsigned long uint32; // unsigned integer type, at least 32 bits + typedef unsigned long uint32; // unsigned integer type, at least 32 bits #endif - enum { N = 624 }; // length of state vector - enum { SAVE = N + 1 }; // length of array for save() + enum + { + N = 624 + }; // length of state vector + enum + { + SAVE = N + 1 + }; // length of array for save() protected: - enum { M = 397 }; // period parameter - uint32 state[N]; // internal state - uint32 *pNext; // next value to get from state - int left; // number of values left before reload needed - - -//Methods + enum + { + M = 397 + }; // period parameter + uint32 state[N]; // internal state + uint32* pNext; // next value to get from state + int left; // number of values left before reload needed + + // Methods public: - /// initialize with a simple uint32 - Random( const uint32& oneSeed ); - // initialize with an array - Random( uint32 *const bigSeed, uint32 const seedLength = N ); - /// auto-initialize with /dev/urandom or time() and clock() - /// Do NOT use for CRYPTOGRAPHY without securely hashing several returned - /// values together, otherwise the generator state can be learned after - /// reading 624 consecutive values. - Random(); - // Access to 32-bit random numbers - double rand(); ///< real number in [0,1] - double rand( const double& n ); ///< real number in [0,n] - double randExc(); ///< real number in [0,1) - double randExc( const double& n ); ///< real number in [0,n) - double randDblExc(); ///< real number in (0,1) - double randDblExc( const double& n ); ///< real number in (0,n) - /// Pull a 32-bit integer from the generator state - /// Every other access function simply transforms the numbers extracted here - uint32 randInt(); ///< integer in [0,2^32-1] - uint32 randInt( const uint32& n ); ///< integer in [0,n] for n < 2^32 - double operator()() { return rand(); } ///< same as rand() - - /// Access to 53-bit random numbers (capacity of IEEE double precision) - double rand53(); // real number in [0,1) - ///Exponential distribution in (0,inf) - double randExponential(); - /// Normal distributed random number - double randNorm( const double& mean = 0.0, const double& variance = 1.0 ); - /// Uniform distribution in [min, max] - double randUniform(double min, double max); - /// Rayleigh distributed random number - double randRayleigh(double sigma); - /// Fisher distributed random number - double randFisher(double k); - /// Fisher distributed unit vector on a sphere - Basic3Vector randFisher(const Basic3Vector &meanDirection, double kappa); - Basic3Vector randFisher(const Basic3Vector *meanDirection, double kappa); - - - /// Power-Law distribution, not possible for index == -1 - double randPowerLaw(double index, double min, double max) ; - /// Broken power-law distribution - double randBrokenPowerLaw(double index1, double index2, double breakpoint, double min, double max ) ; - /// Random point on a unit-sphere - Basic3Vector randUnitVectorOnSphere(); - - /// Seed the generator with a simple uint32 - void seed( const uint32 oneSeed ); - /// Seed the generator with an array of uint32's - /// There are 2^19937-1 possible initial states. This function allows - /// all of those to be accessed by providing at least 19937 bits (with a - /// default seed length of N = 624 uint32's). Any bits above the lower 32 - /// in each element are discarded. - /// Just call seed() if you want to get array from /dev/urandom - void seed( uint32 *const bigSeed, const uint32 seedLength = N ); - /// Seed the generator with an array from /dev/urandom if available - /// Otherwise use a hash of time() and clock() values - void seed(); - - // Saving and loading generator state - void save( uint32* saveArray ) const; // to array of size SAVE - void load( uint32 *const loadArray ); // from such array - friend std::ostream& operator<<( std::ostream& os, const Random& mtrand ); - friend std::istream& operator>>( std::istream& is, Random& mtrand ); + /// initialize with a simple uint32 + Random(const uint32& oneSeed); + // initialize with an array + Random(uint32* const bigSeed, uint32 const seedLength = N); + /// auto-initialize with /dev/urandom or time() and clock() + /// Do NOT use for CRYPTOGRAPHY without securely hashing several returned + /// values together, otherwise the generator state can be learned after + /// reading 624 consecutive values. + Random(); + // Access to 32-bit random numbers + double rand(); ///< real number in [0,1] + double rand(const double& n); ///< real number in [0,n] + double randExc(); ///< real number in [0,1) + double randExc(const double& n); ///< real number in [0,n) + double randDblExc(); ///< real number in (0,1) + double randDblExc(const double& n); ///< real number in (0,n) + /// Pull a 32-bit integer from the generator state + /// Every other access function simply transforms the numbers extracted here + uint32 randInt(); ///< integer in [0,2^32-1] + uint32 randInt(const uint32& n); ///< integer in [0,n] for n < 2^32 + double operator()() + { + return rand(); + } ///< same as rand() + + /// Access to 53-bit random numbers (capacity of IEEE double precision) + double rand53(); // real number in [0,1) + /// Exponential distribution in (0,inf) + double randExponential(); + /// Normal distributed random number + double randNorm(const double& mean = 0.0, const double& variance = 1.0); + /// Uniform distribution in [min, max] + double randUniform(double min, double max); + /// Rayleigh distributed random number + double randRayleigh(double sigma); + /// Fisher distributed random number + double randFisher(double k); + /// Fisher distributed unit vector on a sphere + Vector3 randFisher(const Vector3& meanDirection, double kappa); + Vector3 randFisher(const Vector3* meanDirection, double kappa); + + /// Power-Law distribution, not possible for index == -1 + double randPowerLaw(double index, double min, double max); + /// Broken power-law distribution + double randBrokenPowerLaw( + double index1, double index2, double breakpoint, double min, double max); + /// Random point on a unit-sphere + Vector3 randUnitVectorOnSphere(); + + /// Seed the generator with a simple uint32 + void seed(const uint32 oneSeed); + /// Seed the generator with an array of uint32's + /// There are 2^19937-1 possible initial states. This function allows + /// all of those to be accessed by providing at least 19937 bits (with a + /// default seed length of N = 624 uint32's). Any bits above the lower 32 + /// in each element are discarded. + /// Just call seed() if you want to get array from /dev/urandom + void seed(uint32* const bigSeed, const uint32 seedLength = N); + /// Seed the generator with an array from /dev/urandom if available + /// Otherwise use a hash of time() and clock() values + void seed(); + + // Saving and loading generator state + void save(uint32* saveArray) const; // to array of size SAVE + void load(uint32* const loadArray); // from such array + friend std::ostream& operator<<(std::ostream& os, const Random& mtrand); + friend std::istream& operator>>(std::istream& is, Random& mtrand); protected: - /// Initialize generator state with seed - /// See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier. - /// In previous versions, most significant bits (MSBs) of the seed affect - /// only MSBs of the state array. Modified 9 Jan 2002 by Makoto Matsumoto. - void initialize( const uint32 oneSeed ); - - /// Generate N new values in state - /// Made clearer and faster by Matthew Bellew (matthew.bellew@home.com) - void reload(); - uint32 hiBit( const uint32& u ) const { return u & 0x80000000UL; } - uint32 loBit( const uint32& u ) const { return u & 0x00000001UL; } - uint32 loBits( const uint32& u ) const { return u & 0x7fffffffUL; } - uint32 mixBits( const uint32& u, const uint32& v ) const - { return hiBit(u) | loBits(v); } + /// Initialize generator state with seed + /// See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier. + /// In previous versions, most significant bits (MSBs) of the seed affect + /// only MSBs of the state array. Modified 9 Jan 2002 by Makoto Matsumoto. + void initialize(const uint32 oneSeed); + + /// Generate N new values in state + /// Made clearer and faster by Matthew Bellew (matthew.bellew@home.com) + void reload(); + uint32 hiBit(const uint32& u) const + { + return u & 0x80000000UL; + } + uint32 loBit(const uint32& u) const + { + return u & 0x00000001UL; + } + uint32 loBits(const uint32& u) const + { + return u & 0x7fffffffUL; + } + uint32 mixBits(const uint32& u, const uint32& v) const + { + return hiBit(u) | loBits(v); + } #ifdef _MSC_VER - #pragma warning( push ) - #pragma warning( disable : 4146 ) +#pragma warning(push) +#pragma warning(disable : 4146) #endif - uint32 twist( const uint32& m, const uint32& s0, const uint32& s1 ) const - { return m ^ (mixBits(s0,s1)>>1) ^ (-loBit(s1) & 0x9908b0dfUL); } + uint32 twist(const uint32& m, const uint32& s0, const uint32& s1) const + { + return m ^ (mixBits(s0, s1) >> 1) ^ (-loBit(s1) & 0x9908b0dfUL); + } #ifdef _MSC_VER - #pragma warning( pop ) +#pragma warning(pop) #endif - /// Get a uint32 from t and c - /// Better than uint32(x) in case x is floating point in [0,1] - /// Based on code by Lawrence Kirby (fred@genesis.demon.co.uk) - static uint32 hash( time_t t, clock_t c ); + /// Get a uint32 from t and c + /// Better than uint32(x) in case x is floating point in [0,1] + /// Based on code by Lawrence Kirby (fred@genesis.demon.co.uk) + static uint32 hash(time_t t, clock_t c); }; -} //namespace pxl -#endif // PXL_BASE_RANDOM_HH - +} // namespace pxl +#endif // PXL_BASE_RANDOM_HH diff --git a/core/include/pxl/core/RandomAccessInputFile.hh b/core/include/pxl/core/RandomAccessInputFile.hh deleted file mode 100644 index 398170f3aacc80616acaa6f8ac3cd7719c1e439a..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/RandomAccessInputFile.hh +++ /dev/null @@ -1,144 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_IO_RANDOMACCESSINPUTFILE_HH -#define PXL_IO_RANDOMACCESSINPUTFILE_HH - -#include -#include - -#include "pxl/core/InputFile.hh" - -namespace pxl -{ -// io -/** - This class offers an easy handling of the PXL I/O. Various methods to access - the content of I/O files are offered. - */ -class RandomAccessInputFile : public InputFile -{ -public: - - RandomAccessInputFile() : - InputFile(), - _currentIndex(0), - _eventCount(0), - _knowEventCount(false) - { - } - - RandomAccessInputFile(const std::string& filename) : - InputFile(filename), - _currentIndex(0), - _eventCount(0), - _knowEventCount(false) - { - } - - ~RandomAccessInputFile() - { - close(); - } - - void open(const std::string& filename) - { - _currentIndex = 0; - _eventCount = 0; - _knowEventCount = false; - _filename = filename; - InputFile::open(filename); - } - - void close() - { - InputFile::close(); - _currentIndex = 0; - _eventCount = 0; - _knowEventCount = false; - } - - void reopen() - { - // safe variables to restore it after opening - unsigned int eventCount = _eventCount; - bool knowEventCount = _knowEventCount; - - close(); - - try { - open(_filename); - } catch (std::exception &e) { - return false; - } - - // restore event count information - _eventCount = eventCount; - _knowEventCount = knowEventCount; - } - - bool seekToEvent(unsigned int event) - { - // reopen the file if we need to go back - if (event < _currentIndex) - { - //reopen(); - } - - int toSkip = event - _currentIndex; - int skipped = 0; - - // skip to the needed event - while (skipped < toSkip && _inputFile.skip()) - { - skipped += 1; - _currentIndex += 1; - } - while (skipped > toSkip && _inputFile.previous()) - { - skipped -= 1; - _currentIndex -1= 1; - } - - // update eventCount - if (skipped < toSkip) - { - _eventCount = _currentIndex; - _knowEventCount = true; - } - else if (_currentIndex >= _eventCount) - { - _eventCount = _currentIndex + 1; - } - - if (toSkip == skipped) - return true; - - return false; - } - -private: - RandomAccessInputFile(const RandomAccessInputFile& original) - { - } - - RandomAccessInputFile& operator= (const RandomAccessInputFile& other) - { - return *this; - } - - unsigned long _currentIndex; - unsigned long _eventCount; - bool _knowEventCount; - std::string _filename; - InputFile _inputFile; -}; - -} //namespace pxl - -#endif /*PXL_IO_RANDOMACCESSINPUTFILE_HH*/ diff --git a/core/include/pxl/core/Relations.hh b/core/include/pxl/core/Relations.hh index 1b083585d40ba0f2239af3c17ef1604581c4826e..bd46b1072484059db4d95c772f82d5c72589cb51 100644 --- a/core/include/pxl/core/Relations.hh +++ b/core/include/pxl/core/Relations.hh @@ -1,13 +1,13 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- -#ifndef PXL_BASE_RELATIONS_HH -#define PXL_BASE_RELATIONS_HH +#ifndef PXL_CORE_RELATIONS_HH +#define PXL_CORE_RELATIONS_HH #include #include @@ -22,123 +22,126 @@ namespace pxl class Relative; /** - - The class pxl::Relative owns three instances of pxl::Relations - for managing mother, daughter and flat relations to other pxl::Relative derivatives. - For decay tree integrity reasons, the class pxl::Relative allows to - establish relations only to objects contained in the same object owner - (and in the case of both objects not being contained in owners). + + The class pxl::Relative owns three instances of pxl::Relations + for managing mother, daughter and flat relations to other pxl::Relative derivatives. + For decay tree integrity reasons, the class pxl::Relative allows to + establish relations only to objects contained in the same object owner + (and in the case of both objects not being contained in owners). The Relative only allows const access to the three Relations instances - (mother, daughter, flat) to ensure the integrity of all relations. + (mother, daughter, flat) to ensure the integrity of all relations. */ class PXL_DLL_EXPORT Relations { public: - typedef std::set::const_iterator const_iterator; - typedef std::set::iterator iterator; - - /// Constructor - Relations() - { - } - - /// Write the relations to the OutputStream \p out. - /// Deserialisation of relations is done via the object - /// owner class. - void serialize(const OutputStream &out) const; - - /// Provide direct access to the underlying container. - const std::set& getContainer() const - { - return _relatives; - } - - /// Insert \p relative into the relations. - /// Returns true if successful. - bool set(Relative* relative) - { - return (_relatives.insert(relative)).second; - } - - /// Erase relative from the relations. - /// Returns true if successful. - bool erase(Relative* relative) - { - return (_relatives.erase(relative) > 0); - } - - /// Returns true \p relative is contained in these relations. - bool has(Relative* relative) const - { - return (_relatives.count(relative) > 0 ); - } - - /// Returns the first relative. In case the container is - /// empty, 0 is returned. - Relative* getFirst() const - { - if (_relatives.begin() != _relatives.end()) - return (*_relatives.begin()); - return 0; - } - - /// Fills all relatives which match or inherit from the - /// template type \p objecttype into the passed vector. - /// Returns the number of added objects. - template size_t getObjectsOfType( - std::vector& relatives) const - { - size_t size = relatives.size(); - for (const_iterator iter = _relatives.begin(); iter!=_relatives.end(); ++iter) - { - objecttype* obj = dynamic_cast(*iter); - if (obj) - relatives.push_back(obj); - } - return relatives.size()-size; - } - - /// Returns the size of the relations. - size_t size() const - { - return _relatives.size(); - } - - /// Returns const begin-iterator. - const_iterator begin() const - { - return _relatives.begin(); - } - - /// Returns begin-iterator. - iterator begin() - { - return _relatives.begin(); - } - - /// Returns const end-iterator. - const_iterator end() const - { - return _relatives.end(); - } - - /// Returns end-iterator. - iterator end() - { - return _relatives.end(); - } - - /// Deletes all contained relations. - void clearContainer() - { - _relatives.clear(); - } + typedef std::set relatives_t; + + /// Constructor + Relations() + { + } + + /// Write the relations to the OutputStream \p out. + /// Deserialisation of relations is done via the object + /// owner class. + void serialize(const OutputStream& out) const; + + /// Provide direct access to the underlying container. + const relatives_t& getContainer() const + { + return _relatives; + } + + /// Insert \p relative into the relations. + /// Returns true if successful. + bool set(Relative* relative) + { + return (_relatives.insert(relative)).second; + } + + /// Erase relative from the relations. + /// Returns true if successful. + bool erase(Relative* relative) + { + return (_relatives.erase(relative) > 0); + } + + /// Returns true \p relative is contained in these relations. + bool has(Relative* relative) const + { + return (_relatives.count(relative) > 0); + } + + /// Returns the first relative. In case the container is + /// empty, 0 is returned. + Relative* getFirst() const + { + if (_relatives.begin() != _relatives.end()) + { + return (*_relatives.begin()); + } + return 0; + } + + /// Fills all relatives which match or inherit from the + /// template type \p objecttype into the passed vector. + /// Returns the number of added objects. + template size_t getObjectsOfType(std::vector& relatives) const + { + size_t size = relatives.size(); + for (relatives_t::const_iterator iter = _relatives.begin(); iter != _relatives.end(); + ++iter) + { + objecttype* obj = dynamic_cast(*iter); + if (obj) + { + relatives.push_back(obj); + } + } + return relatives.size() - size; + } + + /// Returns the size of the relations. + size_t size() const + { + return _relatives.size(); + } + + /// Returns const begin-iterator. + relatives_t::const_iterator begin() const + { + return _relatives.begin(); + } + + /// Returns begin-iterator. + relatives_t::iterator begin() + { + return _relatives.begin(); + } + + /// Returns const end-iterator. + relatives_t::const_iterator end() const + { + return _relatives.end(); + } + + /// Returns end-iterator. + relatives_t::iterator end() + { + return _relatives.end(); + } + + /// Deletes all contained relations. + void clearContainer() + { + _relatives.clear(); + } private: - std::set _relatives; /// Sorted container for the related objects. + relatives_t _relatives; /// Sorted container for the related objects. }; } // namespace pxl -#endif // PXL_BASE_RELATIONS_HH +#endif // PXL_CORE_RELATIONS_HH diff --git a/core/include/pxl/core/Relative.hh b/core/include/pxl/core/Relative.hh index a754257eab051983335e926032de3c686cd73963..4bb1918203e1b7dc141ef0cbba9cc418ab29afdf 100644 --- a/core/include/pxl/core/Relative.hh +++ b/core/include/pxl/core/Relative.hh @@ -1,284 +1,234 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- -#ifndef PXL_BASE_RELATIVE_HH -#define PXL_BASE_RELATIVE_HH +#ifndef PXL_CORE_RELATIVE_HH +#define PXL_CORE_RELATIVE_HH #include -#include #include +#include -#include "pxl/core/Serializable.hh" #include "pxl/core/Id.hh" -#include "pxl/core/WkPtrBase.hh" +#include "pxl/core/Object.hh" #include "pxl/core/Relations.hh" +#include "pxl/core/Serializable.hh" #include "pxl/core/SoftRelations.hh" +#include "pxl/core/WeakPtr.hh" namespace pxl { -class ObjectOwner; - -/** - This base class provides common functionalities for all derived PXL objects, - such as mother-daughter relations, weak pointer concept and related service routines. +/** + This base class provides common functionalities for all derived PXL objects, + such as mother-daughter relations, weak pointer concept and related service routines. It has a C++ pointer to the pxl::ObjectOwner it is aggregated in in order to avoid mother/daughter relations to outside objects to be established. */ -class PXL_DLL_EXPORT Relative : public Serializable +class PXL_DLL_EXPORT Relative : public Object { public: - - /// Destructor, ensures safe deletion of all hard relations. - virtual ~Relative(); - - /// Returns the PXL unique object-id (UUID) - inline Id id() const - { - return getId(); - } - - static const Id& getStaticTypeId() - { - static const Id id("5dee644d-906f-4d8e-aecc-d9a644293260"); - return id; - } - - /// Returns the unique ID of this class - virtual const Id& getTypeId() const - { - return getStaticTypeId(); - } - - virtual void serialize(const OutputStream &out) const - { - Serializable::serialize(out); - - _softRelations.serialize(out); - - out.writeString(_name); - - // write out for historic reasons (layout), to be deprecated in pxl 4.0 - out.writeBool(false); - } - - virtual void deserialize(const InputStream &in) - { - Serializable::deserialize(in); - - _softRelations.deserialize(in); - - in.readString(_name); - - // read for historic reasons (layout), to be deprecated in pxl 4.0 - bool hasLayout; - in.readBool(hasLayout); - } - - /// Returns a C++ pointer to the pxl::ObjectOwner it is owned by. - inline ObjectOwner* owner() const - { - return _refObjectOwner; - } - - /// Creates a deep copy and returns a C++ pointer to the newly-created object. - virtual Serializable* clone() const - { - return new Relative(*this); - } - - /// Grants const access to the Relations instance managing mother relations - const Relations& getMotherRelations() const - { - return _motherRelations; - } - /// Grants const access to the pxl::Relations instance managing daughter relations - const Relations& getDaughterRelations() const - { - return _daughterRelations; - } - - /// Grants const access to the pxl::Relations instance managing flat relations - const Relations& getFlatRelations() const - { - return _flatRelations; - } - - /// Returns the first entry of the mother relations. - /// In case the collection is empty, 0 is returned. - Relative* getMother() const - { - return _motherRelations.getFirst(); - } - - /// Returns the first entry of the daughter relations. - /// In case the collection is empty, 0 is returned. - Relative* getDaughter() const - { - return _daughterRelations.getFirst(); - } - - /// Returns all daughter relations. - const std::set& getDaughters() const - { - return _daughterRelations.getContainer(); - } - - /// Returns all mother relations. - const std::set& getMothers() const - { - return _motherRelations.getContainer(); - } - - /// Returns number of daughters - size_t numberOfDaughters() const - { - return _daughterRelations.size(); - } - - /// Returns number of mothers - size_t numberOfMothers() const - { - return _motherRelations.size(); - } - - /// Establishes a mother relation to the \p target object; please notice, that - /// only relations between objects owned by the same object owner will be established. - void linkMother(Relative* target); - /// Establishes a daughter relation to the \p target object; please notice, that - /// only relations between objects owned by the same object owner will be established. - void linkDaughter(Relative* target); - /// Establishes a flat relation to the \p target object; please notice, that - /// only relations between objects owned by the same object owner will be established. - void linkFlat(Relative* target); - - /// Removes an existing daughter relation to the \p target object. - void unlinkMother(Relative* target); - /// Removes an existing daughter relation to the \p target object. - void unlinkDaughter(Relative* target); - /// Removes an existing daughter relation to the \p target object. - void unlinkFlat(Relative* target); - - /// Removes all existing mother relations. - void unlinkMothers(); - /// Removes all existing daughter relations. - void unlinkDaughters(); - /// Removes all existing flat relations. - void unlinkFlat(); - - /// Create a soft relation with name \p type to the Relative \p relative - void linkSoft(Relative* relative, const std::string& type); - - /// Remove a soft relation with name \p type to the Relative \p relative - void unlinkSoft(Relative* relative, const std::string& type); - - /// Get access to the soft relations. - const SoftRelations& getSoftRelations() const - { - return _softRelations; - } - - /// Get access to the soft relations. - SoftRelations& getSoftRelations() - { - return _softRelations; - } - - /// Returns the name. - inline const std::string& getName() const - { - return _name; - } - - /// Sets the name to the contents of \p v. - inline void setName(const std::string& v) - { - _name = v; - } - - /// Recursively invokes its own and the print() methods of all daughter objects. - /// @param level verbosity level - /// @param os output _stream, default is std::cout - /// @param pan print indention - /// @return output _stream - std::ostream& printDecayTree(int level = 0, std::ostream& os = std::cout, - int pan = 1) const; - - /// Prints out object state information on various verbosity levels. - /// @param level verbosity level - /// @param os output _stream, default is std::cout - /// @param pan print indention - /// @return output _stream - virtual std::ostream& print(int level = 1, std::ostream& os = std::cout, - int pan = 0) const; - - /// Creates a weak pointer to itself and returns a pxl::WkPtrBase* to the newly-created weak pointer instance. - virtual WkPtrBase* createSelfWkPtr() - { - throw std::runtime_error("pxl::ObjectBase::createSelfWkPtr(): ATTENTION! Inheriting class must reimplement this virtual method."); - return 0; - } + /// Destructor, ensures safe deletion of all hard relations. + virtual ~Relative(); + + static const Id& getStaticTypeId() + { + static const Id id("5dee644d-906f-4d8e-aecc-d9a644293260"); + return id; + } + + virtual const Id& getTypeId() const + { + return getStaticTypeId(); + } + + virtual void serialize(const OutputStream& out) const + { + Object::serialize(out); + _softRelations.serialize(out); + } + + virtual void deserialize(const InputStream& in) + { + Object::deserialize(in); + _softRelations.deserialize(in); + } + + /// Creates a deep copy and returns a C++ pointer to the newly-created object. + virtual Serializable* clone() const + { + return new Relative(*this); + } + + /// Creates a weak pointer to itself and returns a pxl::WeakPtr* to the newly-created weak + /// pointer instance. + virtual WeakPtr* createWkPtr() + { + throw std::runtime_error("pxl::Relative::createWkPtr(): ATTENTION! Inheriting class " + "must reimplement this virtual method."); + return 0; + } + + /// Grants const access to the Relations instance managing mother relations + const Relations& getMotherRelations() const + { + return _motherRelations; + } + /// Grants const access to the pxl::Relations instance managing daughter relations + const Relations& getDaughterRelations() const + { + return _daughterRelations; + } + + /// Grants const access to the pxl::Relations instance managing flat relations + const Relations& getFlatRelations() const + { + return _flatRelations; + } + + /// Returns the first entry of the mother relations. + /// In case the collection is empty, 0 is returned. + Relative* getMother() const + { + return _motherRelations.getFirst(); + } + + /// Returns the first entry of the daughter relations. + /// In case the collection is empty, 0 is returned. + Relative* getDaughter() const + { + return _daughterRelations.getFirst(); + } + + /// Returns all daughter relations. + const std::set& getDaughters() const + { + return _daughterRelations.getContainer(); + } + + /// Returns all mother relations. + const std::set& getMothers() const + { + return _motherRelations.getContainer(); + } + + /// Returns number of daughters + size_t numberOfDaughters() const + { + return _daughterRelations.size(); + } + + /// Returns number of mothers + size_t numberOfMothers() const + { + return _motherRelations.size(); + } + + /// Establishes a mother relation to the \p target object; please notice, that + /// only relations between objects owned by the same object owner will be established. + void linkMother(Relative* target); + /// Establishes a daughter relation to the \p target object; please notice, that + /// only relations between objects owned by the same object owner will be established. + void linkDaughter(Relative* target); + /// Establishes a flat relation to the \p target object; please notice, that + /// only relations between objects owned by the same object owner will be established. + void linkFlat(Relative* target); + + /// Removes an existing daughter relation to the \p target object. + void unlinkMother(Relative* target); + /// Removes an existing daughter relation to the \p target object. + void unlinkDaughter(Relative* target); + /// Removes an existing daughter relation to the \p target object. + void unlinkFlat(Relative* target); + + /// Removes all existing mother relations. + void unlinkMothers(); + /// Removes all existing daughter relations. + void unlinkDaughters(); + /// Removes all existing flat relations. + void unlinkFlat(); + + /// Create a soft relation with name \p type to the Relative \p relative + void linkSoft(Relative* relative, const std::string& type); + + /// Remove a soft relation with name \p type to the Relative \p relative + void unlinkSoft(Relative* relative, const std::string& type); + + /// Get access to the soft relations. + const SoftRelations& getSoftRelations() const + { + return _softRelations; + } + + /// Get access to the soft relations. + SoftRelations& getSoftRelations() + { + return _softRelations; + } + + /// Recursively invokes its own and the print() methods of all daughter objects. + /// @param level verbosity level + /// @param os output _stream, default is std::cout + /// @param pan print indention + /// @return output _stream + std::ostream& printDecayTree(int level = 0, std::ostream& os = std::cout, int pan = 1) const; + + /// Prints out object state information on various verbosity levels. + /// @param level verbosity level + /// @param os output _stream, default is std::cout + /// @param pan print indention + /// @return output _stream + virtual std::ostream& print(int level = 1, std::ostream& os = std::cout, int pan = 0) const; protected: - /// Default constructor. - Relative() : - Serializable(), _refWkPtrSpec(0), _refObjectOwner(0), - _name("default") - { - } - - /// Copy constructor. Relations are not copied. - Relative(const Relative& original) : - Serializable(), _refWkPtrSpec(0), _refObjectOwner(0), - _name(original._name) - { - } - - /// Copy constructor. Relations are not copied. - explicit Relative(const Relative* original) : - Serializable(), _refWkPtrSpec(0), _refObjectOwner(0), - _name(original->_name) - { - } - - /// Service method for printing relations tree - std::ostream& printPan1st(std::ostream& os, int pan) const; - - /// Service method for printing relations tree - std::ostream& printPan(std::ostream& os, int pan) const; + /// Default constructor. + Relative() + : Object() + { + } + + /// Copy constructor. Relations are not copied. + Relative(const Relative& original) + : Object() + { + } + + /// Copy constructor. Relations are not copied. + explicit Relative(const Relative* original) + : Object() + { + } + + /// Service method for printing relations tree + std::ostream& printPan1st(std::ostream& os, int pan) const; + + /// Service method for printing relations tree + std::ostream& printPan(std::ostream& os, int pan) const; private: - WkPtrBase* _refWkPtrSpec; /// reference to a weak pointer - ObjectOwner* _refObjectOwner; /// reference to our object owner - - Relations _motherRelations; /// mother relations, managed by object owner - Relations _daughterRelations; /// daughter relations, managed by object owner - Relations _flatRelations; /// flat relations, managed by object owner - - SoftRelations _softRelations; /// soft relations + Relations _motherRelations; /// mother relations, managed by object owner + Relations _daughterRelations; /// daughter relations, managed by object owner + Relations _flatRelations; /// flat relations, managed by object owner - std::string _name; /// arbitrary name of this object + SoftRelations _softRelations; /// soft relations - friend class WkPtrBase; - friend class ObjectOwner; + // friend class ObjectOwner; - /// No assignment of Relative derivatives is allowed, the assignment - /// operator is private - Relative& operator=(const Relative& original) - { - return *this; - } + /// No assignment of Relative derivatives is allowed, the assignment + /// operator is private + Relative& operator=(const Relative& original) + { + return *this; + } }; -} -// namespace pxl +} // namespace pxl // operators PXL_DLL_EXPORT std::ostream& operator<<(std::ostream& cxxx, const pxl::Relative& obj); -#endif // PXL_BASE_OBJECTBASE_HH +#endif // PXL_CORE_RELATIVE_HH diff --git a/core/include/pxl/core/RotationMatrix.hh b/core/include/pxl/core/RotationMatrix.hh deleted file mode 100644 index 0cdd7f99714ce1492608083e937e473e1be1516e..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/RotationMatrix.hh +++ /dev/null @@ -1,37 +0,0 @@ -#include "pxl/core/BasicMatrix.hh" -#include -namespace pxl -{ - -/** - * The rotation Matrix is a 3x3 Basic Matrix constructed by an rotation - * axis and an rotation angle - */ -class PXL_DLL_EXPORT RotationMatrix : public BasicMatrix -{ -public: - RotationMatrix() : BasicMatrix(3,3) {}; - RotationMatrix(const RotationMatrix& orig) : BasicMatrix(orig) {}; - - explicit RotationMatrix(const RotationMatrix* orig) : BasicMatrix(*orig) {}; - - RotationMatrix(const Basic3Vector& rotationAxis, double rotationAngle) : BasicMatrix(3,3) - { - double s = std::sin(rotationAngle); - double c = std::cos(rotationAngle); - _data[0] = rotationAxis.getX()*rotationAxis.getX() + (1-rotationAxis.getX()*rotationAxis.getX()) *c ; - _data[1] = rotationAxis.getX()*rotationAxis.getY()*(1-c) - rotationAxis.getZ() * s ; - _data[2] = rotationAxis.getX()*rotationAxis.getZ()*(1-c) + rotationAxis.getY() * s ; - _data[3] = rotationAxis.getX()*rotationAxis.getY()*(1-c) + rotationAxis.getZ() * s ; - _data[4] = rotationAxis.getY()*rotationAxis.getY() + (1-rotationAxis.getY()*rotationAxis.getY()) *c ; - _data[5] = rotationAxis.getY()*rotationAxis.getZ()*(1-c) - rotationAxis.getX() * s ; - _data[6] = rotationAxis.getX()*rotationAxis.getZ()*(1-c) - rotationAxis.getY() * s ; - _data[7] = rotationAxis.getY()*rotationAxis.getZ()*(1-c) + rotationAxis.getX() * s ; - _data[8] = rotationAxis.getZ()*rotationAxis.getZ() + (1-rotationAxis.getZ()*rotationAxis.getZ()) *c; - } - - - -}; - -} diff --git a/core/include/pxl/core/Serializable.hh b/core/include/pxl/core/Serializable.hh index bdfe2d2f699a7929d0bd3f9271da3e5d3e88aa14..372db31f1ceb6c2b519d3066ddd9128161026051 100644 --- a/core/include/pxl/core/Serializable.hh +++ b/core/include/pxl/core/Serializable.hh @@ -1,18 +1,20 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- -#ifndef PXL_IO_SERIALIZABLE_HH -#define PXL_IO_SERIALIZABLE_HH +#ifndef PXL_CORE_SERIALIZABLE_HH +#define PXL_CORE_SERIALIZABLE_HH #include -#include "pxl/core/Stream.hh" + #include "pxl/core/Id.hh" -#include "pxl/core/macros.hh" +#include "pxl/core/Stream.hh" +#include "pxl/core/Macros.hh" +#include "pxl/core/WeakPtr.hh" namespace pxl { @@ -21,93 +23,95 @@ namespace pxl This class is the abstract base class for all objects to be stored in a PXL I/O file. It holds the unique ID (UUID) of each individual object. In addition, a UUID indicating the class type must be implemented in derived classes - each class can be identified via its unique ID. - (De-) Serialization happens via consecutive calls to the serialize/deserialize methods of the + (De-) Serialization happens via consecutive calls to the serialize/deserialize methods of the base classes. */ class PXL_DLL_EXPORT Serializable { public: + /// Constructor. + Serializable() + : _weakPtr(0) + , _id() + { + } + + /// Copy constructor. A copied object gets a new unique ID. + Serializable(const Serializable& ser) + : _weakPtr(0) + , _id() + { + } + + /// Assignment operator, UUID is changed in case this object is changed. + Serializable& operator=(const Serializable& ser) + { + if (this != &ser) + { + _id = Id::create(); + } + return *this; + } + + /// Destructor. + virtual ~Serializable() + { + if (_weakPtr) + { + _weakPtr->notifyDeleted(); + } + } + + /// Id of the object's class (== type). This method must be reimplemented + /// by all derived classes to return a distinct UUID identifying the + /// class, e.g. the Particle. + virtual const Id& getTypeId() const = 0; + + /// Returns the unique ID (UUID) of the individual object. Each individual + /// object can unambiguously be identified by this ID. + const Id& getId() const + { + return _id; + } + + /// This method serializes this object by serializing the type ID and the + /// unique object ID. When extending this method, derived classes must + /// first call the base class method. + virtual void serialize(const OutputStream& out) const + { + // Serialize ID of the type + getTypeId().serialize(out); + // Serialize UUID. + _id.serialize(out); + } + + /// This method deserializes this object. When extending this method, derived + /// classes must first call the base class method. + virtual void deserialize(const InputStream& in) + { + // Deserialize uuid; + _id.deserialize(in); + } + + /// Pure virtual method which should be implemented by all derived classes + /// to return a new copy of the object. + virtual Serializable* clone() const = 0; + + virtual WeakPtr* createWkPtr() + { + return new weak_ptr(this); + } - /// Constructor. - Serializable() - { - } - - /// Copy constructor. A copied object gets a new unique ID. - Serializable(const Serializable& original) : _id() - { - } - - /// Assignment operator, UUID is changed in case this object is changed. - Serializable& operator=(const Serializable& original) - { - if (this != &original) - _id = Id::create(); - return *this; - } - - /// Destructor. - virtual ~Serializable() - { - } - - /// Id of the object's class (== type). This method must be reimplemented - /// by all derived classes to return a distinct UUID identifying the - /// class, e.g. the Particle. - virtual const Id& getTypeId() const = 0; - - /// Returns the unique ID (UUID) of the individual object. Each individual - /// object can unambiguously be identified by this ID. - const Id& getId() const - { - return _id; - } - - /// Pure virtual method which should be implemented by all derived classes - /// to return a new copy of the object. - virtual Serializable* clone() const = 0; - - /// This method serializes this object by serializing the type ID and the - /// unique object ID. When extending this method, derived classes must - /// first call the base class method. - virtual void serialize(const OutputStream &out) const - { - // Serialize ID of the type - getTypeId().serialize(out); - // Serialize UUID. - _id.serialize(out); - } - - /// This method deserializes this object. When extending this method, derived - /// classes must first call the base class method. - virtual void deserialize(const InputStream &in) - { - // Deserialize uuid; - _id.deserialize(in); - } - - /// Print information to the passed ostream \p os. Can be reimplemented by - /// derived classes to print information specific to the derived class. - virtual std::ostream& print(int level=1, std::ostream& os=std::cout, int pan=1) const - { - os << "Serializable [" << getId() <<"]"<< std::endl; - return os; - } - - /// Returns a string with the output of the virtual print method. In general, - /// there is no need for re-implementation in derived classes. - virtual const std::string toString() const - { - std::ostringstream ss; - this->print(0,ss); - return ss.str(); - } private: - /// The unique ID (UUID) of this object. Each object can unambiguously be - /// identified by this ID. - Id _id; + WeakPtr* _weakPtr; + + /// The unique ID (UUID) of this object. Each object can unambiguously be + /// identified by this ID. + Id _id; + + friend class WeakPtr; }; -} +} // namespace pxl -#endif /*PXL_IO_SERIALIZABLE_HH*/ +#endif // PXL_CORE_SERIALIZABLE_HH diff --git a/core/include/pxl/core/SerializableFactory.hh b/core/include/pxl/core/SerializableFactory.hh new file mode 100644 index 0000000000000000000000000000000000000000..e028fe157423d72298e857639724c3efaf9e2078 --- /dev/null +++ b/core/include/pxl/core/SerializableFactory.hh @@ -0,0 +1,70 @@ +//------------------------------------------- +// Project: Physics eXtension Library (PXL) - +// http://vispa.physik.rwth-aachen.de/ - +// Copyright (C) 2006-2019 Martin Erdmann - +// RWTH Aachen, Germany - +// Licensed under a LGPL-2 or later license - +//------------------------------------------- + +#ifndef PXL_CORE_SERIALIZABLEFACTORY_HH +#define PXL_CORE_SERIALIZABLEFACTORY_HH + +#include + +#include "pxl/core/Id.hh" +#include "pxl/core/Macros.hh" +#include "pxl/core/Serializable.hh" + +namespace pxl +{ + +class SerializableProducerInterface; + +class PXL_DLL_EXPORT SerializableFactory +{ +public: + static SerializableFactory& instance(); + + Serializable* create(const Id& id); + + void registerProducer(const Id& id, const SerializableProducerInterface* producer); + void unregisterProducer(const SerializableProducerInterface* producer); + +private: + SerializableFactory(); + + std::map _producers; +}; + +class SerializableProducerInterface +{ +public: + virtual ~SerializableProducerInterface() + { + } + + virtual Serializable* create() const = 0; +}; + +template class SerializableProducerTemplate : public SerializableProducerInterface +{ +public: + void initialize() + { + SerializableFactory::instance().registerProducer(T::getStaticTypeId(), this); + } + + void shutdown() + { + SerializableFactory::instance().unregisterProducer(this); + } + + virtual Serializable* create() const + { + return new T(); + } +}; + +} // namespace pxl + +#endif // PXL_CORE_SERIALIZABLEFACTORY_HH diff --git a/core/include/pxl/core/SoftRelations.hh b/core/include/pxl/core/SoftRelations.hh index ff6ad978b281da5845b880e271aaa518103e5b9e..d02f46ace822554dd215311bd367e2b92efac943 100644 --- a/core/include/pxl/core/SoftRelations.hh +++ b/core/include/pxl/core/SoftRelations.hh @@ -1,311 +1,224 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- -#ifndef PXL_BASE_SOFTRELATIONS_HH -#define PXL_BASE_SOFTRELATIONS_HH +#ifndef PXL_CORE_SOFTRELATIONS_HH +#define PXL_CORE_SOFTRELATIONS_HH #include -#include -#include #include +#include +#include -#include "pxl/core/Stream.hh" -#include "pxl/core/Serializable.hh" #include "pxl/core/Id.hh" - +#include "pxl/core/ObjectOwner.hh" +#include "pxl/core/Serializable.hh" +#include "pxl/core/Stream.hh" namespace pxl { -class ObjectOwner; -class ObjectManager; -class BasicContainer; - /** This class provides the storage of relations to any Serializable derivatives, by means - of the unique Id (UUID) of each object. Each relation has a certain name. + of the unique Id (UUID) of each object. Each relation has a certain name. In contrast to the standard Relations class, relations between objects with different (or no) object owners can be established. The relations are stored as pairs of names (string) and UUIDs (Id). More than one soft relation with the same name is allowed to be established. Since a relation is not stored as a pointer, it can only be retrieved indirectly. This also means that soft relations exist beyond the lifetime of the related objects, unless they are explicitly removed. - An object of type SoftRelation can be added to any class which is supposed to provide such relations, + An object of type SoftRelation can be added to any class which is supposed to provide such + relations, e.g. all derivatives of the Relative such as the Particle. */ class PXL_DLL_EXPORT SoftRelations { public: - typedef std::multimap::const_iterator const_iterator; - typedef std::multimap::iterator iterator; - - /// Writes the current content to the passed stream. - void serialize(const OutputStream &out) const; - - /// Replaces the current content with the content of passed stream, which is read in. - void deserialize(const InputStream &in); - - /// Returns the first Serializable pointer which is contained in the passed object owner \p owner - /// and which is contained in these soft relations. If the name of the soft relation \p name - /// is also passed, the first Serializable which has the soft relation of the according name is returned. - /// Returns 0 in case no match is found. - Serializable* getFirst(const ObjectOwner& owner, const std::string& name = "") const; - - /// Returns the first Serializable pointer which is contained in the passed BasicContainer \p container - /// and which is contained in these soft relations. If the name of the soft relation \p name - /// is also passed, the first Serializable which has the soft relation of the according name is returned. - /// Returns 0 in case no match is found. - Serializable* getFirst(const BasicContainer& container, const std::string& name = "") const; - - /// Fills all Serializables which are both contained in the object owner \p owner as well as in these soft - /// relations with the passed name \p name into the passed vector of Serializable pointers. - /// Returns the number of filled Serializables. - int getSoftRelatives(std::vector& vec, const ObjectOwner& owner, const std::string& name) const; - - /// Fills all Serializables which are both contained in the object owner \p owner as well as in these soft - /// relations into the passed vector of Serializable pointers. - /// Returns the number of filled Serializables. - int getSoftRelatives(std::vector& vec, const ObjectOwner& owner) const; - - /// Fills all Serializables which are both contained in the object owner of object manager \p manager as well as - /// in these soft relations with the passed name \p name into the passed vector of Serializable pointers. - /// Returns the number of filled Serializables. - int getSoftRelatives(std::vector& vec, const ObjectManager& manager, const std::string& name) const; - - /// Fills all Serializables which are both contained in the object owner of object manager \p manager as well as - /// in these soft relations into the passed vector of Serializable pointers. - /// Returns the number of filled Serializables. - int getSoftRelatives(std::vector& vec, const ObjectManager& manager) const; - - /// Fills all Serializables which are both contained in the BasicContainer \p container as well as in these soft - /// relations with the passed name \p name into the passed vector of Serializable pointers. - /// Returns the number of filled Serializables. - int getSoftRelatives(std::vector& vec, const BasicContainer& container, const std::string& name) const; - - /// Fills all Serializables which are both contained in the BasicContainer \p container as well as in these soft - /// relations into the passed vector of Serializable pointers. - /// Returns the number of filled Serializables. - int getSoftRelatives(std::vector& vec, const BasicContainer& container) const; - - /// Fills all Serializables which are both contained in the object owner \p owner as well as in these soft - /// relations with the passed name \p name into the passed vector of objectname pointers. - /// Only objects which match the template type (or derivatives) are filled. - /// Returns the number of filled objects. - template - int getSoftRelativesOfType(std::vector& vec, const ObjectOwner& owner, const std::string& name) const; - - /// Fills all Serializables which are both contained in the object owner \p owner as well as in these soft - /// relations into the passed vector of objecttype pointers. - /// Only objects which match the template name (or derivatives) are filled. - /// Returns the number of filled objects. - template - int getSoftRelativesOfType(std::vector& vec, const ObjectOwner& owner) const; - - /// Fills all Serializables which are both contained in the basic container \p container as well as in these soft - /// relations with the passed name \p name into the passed vector of objecttype pointers. - /// Only objects which match the template type (or derivatives) are filled. - /// Returns the number of filled objects. - template - int getSoftRelativesOfType(std::vector& vec, const BasicContainer& owner, const std::string& name) const; - - /// Fills all Serializables which are both contained in the basic container \p container as well as in these soft - /// relations into the passed vector of objecttype pointers. - /// Only objects which match the template type (or derivatives) are filled. - /// Returns the number of filled objects. - template - int getSoftRelativesOfType(std::vector& vec, const BasicContainer& owner) const; - - /// Removes all Serializables from the passed vecttor which are NOT contained in these soft - /// relations with the passed name \p name. - /// Returns the number of remaining Serializables. - int keepSoftRelatives(std::vector& vec, const std::string& name) const; - - /// Removes all Serializables from the passed vecttor which are NOT contained in these soft - /// relations. - /// Returns the number of remaining Serializables. - int keepSoftRelatives(std::vector& vec) const; - - /// Returns true if the passed Serializable \p relative is contained in these soft relations. - bool has(const Serializable* relative) const; - - /// Returns true if the passed Serializable \p relative is contained in these soft relations - /// with the name \p name. - bool has(const Serializable* relative, const std::string& name) const; - - /// Returns true if the passed UUID \p id is contained in these soft relations - bool has(const Id& id) const; - - /// Returns true if the passed UUID \p id is contained in these soft relations - /// with the name \p name. - bool has(const Id& id, const std::string& name) const; - - /// Returns true if a soft relation with name \p name exists. - bool hasName(const std::string& name) const; - - /// Returns the number of soft relations with name \p name. - int count(const std::string& name) const; - - /// Establishes a soft relation to the passed Serializable \p relative and - /// with the name \p name. - void set(const Serializable* relative, const std::string& name); - - /// Removes all existing soft relations with name \p name - /// to the passed Serializable \p relative. - void remove(const Serializable* relative, const std::string& name); - - /// Removes all existing soft relations to the passed Serializable \p relative. - void remove(const Serializable* relative); - - /// Returns the number of soft relations. - size_t size() const - { - return _relationsMap.size(); - } - - /// Deletes all contained relations. - void clearContainer() - { - _relationsMap.clear(); - } - - /// Gives const access to the underlying container. - const std::multimap& getContainer() const - { - return _relationsMap; - } - - /// Returns a const begin-iterator to the underlying container. - const_iterator begin() const - { - return _relationsMap.begin(); - } - - /// Returns a begin-iterator to the underlying container. - iterator begin() - { - return _relationsMap.begin(); - } - - /// Returns a const end-iterator to the underlying container. - const_iterator end() const - { - return _relationsMap.end(); - } - - /// Returns an end-iterator to the underlying container. - iterator end() - { - return _relationsMap.end(); - } - - /// Prints information about this object to the passed stream. - std::ostream& print(int level = 0, std::ostream& os = std::cout, int pan=1) const; - - const std::string toString() const - { - std::ostringstream ss; - this->print(0,ss); - return ss.str(); - } + typedef std::multimap::const_iterator const_iterator; + typedef std::multimap::iterator iterator; + + /// Writes the current content to the passed stream. + void serialize(const OutputStream& out) const; + + /// Replaces the current content with the content of passed stream, which is read in. + void deserialize(const InputStream& in); + + /// Returns the first Serializable pointer which is contained in the passed object owner \p + /// owner + /// and which is contained in these soft relations. If the name of the soft relation \p name + /// is also passed, the first Serializable which has the soft relation of the according name is + /// returned. + /// Returns 0 in case no match is found. + Serializable* getFirst(const ObjectOwner& owner, const std::string& name = "") const; + + /// Fills all Serializables which are both contained in the object owner \p owner as well as in + /// these soft + /// relations with the passed name \p name into the passed vector of Serializable pointers. + /// Returns the number of filled Serializables. + int getSoftRelatives( + std::vector& vec, const ObjectOwner& owner, const std::string& name) const; + + /// Fills all Serializables which are both contained in the object owner \p owner as well as in + /// these soft + /// relations into the passed vector of Serializable pointers. + /// Returns the number of filled Serializables. + int getSoftRelatives(std::vector& vec, const ObjectOwner& owner) const; + + /// Fills all Serializables which are both contained in the object owner \p owner as well as in + /// these soft + /// relations with the passed name \p name into the passed vector of objectname pointers. + /// Only objects which match the template type (or derivatives) are filled. + /// Returns the number of filled objects. + template + int getSoftRelativesOfType( + std::vector& vec, const ObjectOwner& owner, const std::string& name) const; + + /// Fills all Serializables which are both contained in the object owner \p owner as well as in + /// these soft + /// relations into the passed vector of objecttype pointers. + /// Only objects which match the template name (or derivatives) are filled. + /// Returns the number of filled objects. + template + int getSoftRelativesOfType(std::vector& vec, const ObjectOwner& owner) const; + + /// Removes all Serializables from the passed vecttor which are NOT contained in these soft + /// relations with the passed name \p name. + /// Returns the number of remaining Serializables. + int keepSoftRelatives(std::vector& vec, const std::string& name) const; + + /// Removes all Serializables from the passed vecttor which are NOT contained in these soft + /// relations. + /// Returns the number of remaining Serializables. + int keepSoftRelatives(std::vector& vec) const; + + /// Returns true if the passed Serializable \p relative is contained in these soft relations. + bool has(const Serializable* relative) const; + + /// Returns true if the passed Serializable \p relative is contained in these soft relations + /// with the name \p name. + bool has(const Serializable* relative, const std::string& name) const; + + /// Returns true if the passed UUID \p id is contained in these soft relations + bool has(const Id& id) const; + + /// Returns true if the passed UUID \p id is contained in these soft relations + /// with the name \p name. + bool has(const Id& id, const std::string& name) const; + + /// Returns true if a soft relation with name \p name exists. + bool hasName(const std::string& name) const; + + /// Returns the number of soft relations with name \p name. + int count(const std::string& name) const; + + /// Establishes a soft relation to the passed Serializable \p relative and + /// with the name \p name. + void set(const Serializable* relative, const std::string& name); + + /// Removes all existing soft relations with name \p name + /// to the passed Serializable \p relative. + void remove(const Serializable* relative, const std::string& name); + + /// Removes all existing soft relations to the passed Serializable \p relative. + void remove(const Serializable* relative); + + /// Returns the number of soft relations. + size_t size() const + { + return _relationsMap.size(); + } + + /// Deletes all contained relations. + void clearContainer() + { + _relationsMap.clear(); + } + + /// Gives const access to the underlying container. + const std::multimap& getContainer() const + { + return _relationsMap; + } + + /// Returns a const begin-iterator to the underlying container. + const_iterator begin() const + { + return _relationsMap.begin(); + } + + /// Returns a begin-iterator to the underlying container. + iterator begin() + { + return _relationsMap.begin(); + } + + /// Returns a const end-iterator to the underlying container. + const_iterator end() const + { + return _relationsMap.end(); + } + + /// Returns an end-iterator to the underlying container. + iterator end() + { + return _relationsMap.end(); + } + + /// Prints information about this object to the passed stream. + std::ostream& print(int level = 0, std::ostream& os = std::cout, int pan = 1) const; + + const std::string toString() const + { + std::ostringstream ss; + this->print(0, ss); + return ss.str(); + } private: - std::multimap _relationsMap; /// Map containing the soft relations (name, UUID) - - // Helper functions are needed to allow templates and forward - // declarations here - Serializable* getByIdHelper(const ObjectOwner& owner, const_iterator iter) const; - Serializable* getByIdHelper(const BasicContainer& owner, const_iterator iter) const; + std::multimap _relationsMap; /// Map containing the soft relations (name, UUID) }; - // // Template methods have to be specified in the header! // -template -int SoftRelations::getSoftRelativesOfType(std::vector& vec, - const ObjectOwner& owner, const std::string& name) const -{ - int size = vec.size(); - std::pair iterators = - _relationsMap.equal_range(name); - for (const_iterator iter = iterators.first; iter != iterators.second; ++iter) - { - Serializable* relative = getByIdHelper(owner, iter); - if (relative != 0) - { - objecttype* object = dynamic_cast (relative); - if (object != 0) - vec.push_back(object); - } - } - return vec.size() - size; -} - -template -int SoftRelations::getSoftRelativesOfType(std::vector& vec, - const ObjectOwner& owner) const +template +int SoftRelations::getSoftRelativesOfType( + std::vector& vec, const ObjectOwner& owner, const std::string& name) const { - int size = vec.size(); - for (const_iterator iter = _relationsMap.begin(); iter - != _relationsMap.end(); ++iter) - { - Serializable* relative = getByIdHelper(owner, iter); - if (relative != 0) - { - objecttype* object = dynamic_cast (relative); - if (object != 0) - vec.push_back(object); - } - } - return vec.size() - size; + int size = vec.size(); + std::pair iterators = _relationsMap.equal_range(name); + for (const_iterator it = iterators.first; it != iterators.second; ++it) + { + objecttype* obj = dynamic_cast(owner.findObject(it->second)); + if (obj) + { + vec.push_back(obj); + } + } + return vec.size() - size; } -template -int SoftRelations::getSoftRelativesOfType(std::vector& vec, - const BasicContainer& owner, const std::string& name) const +template +int SoftRelations::getSoftRelativesOfType( + std::vector& vec, const ObjectOwner& owner) const { - int size = vec.size(); - std::pair iterators = - _relationsMap.equal_range(name); - for (const_iterator iter = iterators.first; iter != iterators.second; ++iter) - { - Serializable* relative = getByIdHelper(owner, iter); - if (relative != 0) - { - objecttype* object = dynamic_cast (relative); - if (object != 0) - vec.push_back(object); - } - } - return vec.size() - size; + int size = vec.size(); + for (const_iterator it = _relationsMap.begin(); it != _relationsMap.end(); ++it) + { + objecttype* obj = dynamic_cast(owner.findObject(it->second)); + if (obj) + { + vec.push_back(obj); + } + } + return vec.size() - size; } -template -int SoftRelations::getSoftRelativesOfType(std::vector& vec, - const BasicContainer& owner) const -{ - int size = vec.size(); - for (const_iterator iter = _relationsMap.begin(); iter - != _relationsMap.end(); ++iter) - { - Serializable* relative = getByIdHelper(owner, iter); - if (relative != 0) - { - objecttype* object = dynamic_cast (relative); - if (object != 0) - vec.push_back(object); - } - } - return vec.size() - size; -} - - -} //namespace pxl +} // namespace pxl -#endif /*PXL_BASE_SOFTRELATIONS_HH*/ +#endif // PXL_CORE_SOFTRELATIONS_HH diff --git a/core/include/pxl/core/Stream.hh b/core/include/pxl/core/Stream.hh index 824af0c19605055c6910555f49ecc90d5c73737e..b74a1d20b99a6fd0f551a5ea462d46216bd5762a 100644 --- a/core/include/pxl/core/Stream.hh +++ b/core/include/pxl/core/Stream.hh @@ -1,207 +1,159 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- -#ifndef PXL_IO_STREAM_HH -#define PXL_IO_STREAM_HH +#ifndef PXL_CORE_STREAM_HH +#define PXL_CORE_STREAM_HH -#include #include #include -#include - +#include #include +#include +#include -#include "pxl/core/macros.hh" -#include +#include "pxl/core/Macros.hh" namespace pxl { -template -void swap_endianess(T &t) + +template void swap_endianess(T& t) { #ifdef PXL_BIG_ENDIAN - T swapped; - unsigned char *in = (unsigned char *)&t; - unsigned char *out = (unsigned char *)&swapped; - for (size_t i = 0; i < sizeof(T); i++) - out[i] = in[sizeof(T) - 1 - i]; - t = swapped; + T swapped; + unsigned char* in = (unsigned char*)&t; + unsigned char* out = (unsigned char*)&swapped; + for (size_t i = 0; i < sizeof(T); i++) + { + out[i] = in[sizeof(T) - 1 - i]; + } + t = swapped; #endif } -// io /** This abstract class serves the internal PXL I/O scheme by defining how basic C++ types are written to an output buffer. */ class PXL_DLL_EXPORT OutputStream { - public: - virtual ~OutputStream() - { - } - - virtual void write(const void *data, size_t size) const = 0; - - // helpers - void writeChar(char c) const - { - write(&c, 1); - } - - void writeUnsignedChar(unsigned char c) const - { - write(&c, 1); - } - - void writeString(const std::string& s) const - { - unsigned int len = static_cast(s.size()); - writeUnsignedInt(len); - write(s.data(), len); - } - - void writeFloat(float f) const - { - swap_endianess(f); - write(&f, sizeof(f)); - } - - void writeDouble(double d) const - { - swap_endianess(d); - write(&d, sizeof(d)); - } - void write(int8_t i) const - { - swap_endianess(i); - write(&i, sizeof(i)); - } - - void write(uint8_t i) const - { - swap_endianess(i); - write(&i, sizeof(i)); - } - - void write(int16_t i) const - { - swap_endianess(i); - write(&i, sizeof(i)); - } - - void write(uint16_t i) const - { - swap_endianess(i); - write(&i, sizeof(i)); - } - - void write(int32_t i) const - { - swap_endianess(i); - write(&i, sizeof(i)); - } - - void write(uint32_t i) const - { - swap_endianess(i); - write(&i, sizeof(i)); - } - - void write(int64_t i) const - { - swap_endianess(i); - write(&i, sizeof(i)); - } - - void write(uint64_t i) const - { - swap_endianess(i); - write(&i, sizeof(i)); - } - - ///ToDo: Remove legacy write / read functions - void writeInt(int i) const - { - swap_endianess(i); - write(&i, sizeof(i)); - } - - void writeUnsignedInt(unsigned int i) const - { - swap_endianess(i); - write(&i, sizeof(i)); - } - - void writeLong(long l) const - { - writeInt(static_cast(l)); - } - - void writeUnsignedLong(unsigned long l) const - { - writeUnsignedInt(static_cast(l)); - } - - void writeShort(short s) const - { - swap_endianess(s); - write(&s, sizeof(s)); - } - - void writeUnsignedShort(unsigned short s) const - { - swap_endianess(s); - write(&s, sizeof(s)); - } - - void writeBool(bool b) const - { - char c = b ? 1 : 0; - write(&c, 1); - } - + virtual ~OutputStream() + { + } + + virtual void write(const void* data, size_t size) const = 0; + + // helpers + inline void writeChar(char c) const + { + write(&c, 1); + } + + inline void writeUChar(unsigned char c) const + { + write(&c, 1); + } + + inline void writeBool(bool b) const + { + char c = b ? 1 : 0; + write(&c, 1); + } + + inline void writeInt16(int16_t i) const + { + swap_endianess(i); + write(&i, sizeof(i)); + } + + inline void writeUInt16(uint16_t i) const + { + swap_endianess(i); + write(&i, sizeof(i)); + } + + inline void writeInt32(int32_t i) const + { + swap_endianess(i); + write(&i, sizeof(i)); + } + + inline void writeUInt32(uint32_t i) const + { + swap_endianess(i); + write(&i, sizeof(i)); + } + + inline void writeInt64(int64_t i) const + { + swap_endianess(i); + write(&i, sizeof(i)); + } + + inline void writeUInt64(uint64_t i) const + { + swap_endianess(i); + write(&i, sizeof(i)); + } + + inline void writeFloat(float f) const + { + swap_endianess(f); + write(&f, sizeof(f)); + } + + inline void writeDouble(double d) const + { + swap_endianess(d); + write(&d, sizeof(d)); + } + + void writeString(const std::string& s) const + { + uint32_t len = static_cast(s.size()); + writeUInt32(len); + write(s.data(), len); + } }; /** This class serves the internal PXL I/O scheme by implementing how basic C++ types are written to an output buffer. */ - -class PXL_DLL_EXPORT BufferOutput: public OutputStream +class PXL_DLL_EXPORT BufferOutput : public OutputStream { public: - - mutable std::vector buffer; - - BufferOutput() - { - // optimal size to be determined - buffer.reserve(1048576); - } - - BufferOutput(size_t bufferSize) - { - buffer.reserve(bufferSize); - } - - void clear() - { - buffer.clear(); - } - - void write(const void *data, size_t size) const - { - size_t pos = buffer.size(); - buffer.resize(pos + size); - memcpy(&buffer[pos], data, size); - } + mutable std::vector buffer; + + BufferOutput() + : OutputStream() + { + // optimal size to be determined + buffer.reserve(1048576); + } + + BufferOutput(size_t bufferSize) + : OutputStream() + { + buffer.reserve(bufferSize); + } + + void clear() + { + buffer.clear(); + } + + void write(const void* data, size_t size) const + { + size_t pos = buffer.size(); + buffer.resize(pos + size); + memcpy(&buffer[pos], data, size); + } }; /** @@ -210,193 +162,144 @@ public: */ class PXL_DLL_EXPORT InputStream { - public: - virtual ~InputStream() - { - } - - virtual void read(void *data, size_t size) const = 0; - virtual bool good() const = 0; - - void read(char& i) const - { - read(&i, sizeof(i)); - } - - void read(unsigned char& i) const - { - read(&i, sizeof(i)); - } - - void read(int16_t& i) const - { - read(&i, sizeof(i)); - swap_endianess(i); - } - - void read(uint16_t& i) const - { - read(&i, sizeof(i)); - swap_endianess(i); - } - - void read(int32_t& i) const - { - read(&i, sizeof(i)); - swap_endianess(i); - } - - void read(uint32_t& i) const - { - read(&i, sizeof(i)); - swap_endianess(i); - } - - void read(int64_t& i) const - { - read(&i, sizeof(i)); - swap_endianess(i); - } - - void read(uint64_t& i) const - { - read(&i, sizeof(i)); - swap_endianess(i); - } - - void readChar(char& c) const - { - read(&c, sizeof(c)); - } - - void readUnsignedChar(unsigned char& c) const - { - read(&c, sizeof(c)); - } - - void readInt(int& i) const - { - read(&i, sizeof(i)); - swap_endianess(i); - } - - void readUnsignedInt(unsigned int& i) const - { - read(&i, sizeof(i)); - swap_endianess(i); - } - - void readLong(long& l) const - { - int i; - read(&i, sizeof(i)); - swap_endianess(i); - l = i; - } - - void readUnsignedLong(unsigned long& l) const - { - unsigned int i; - read(&i, sizeof(i)); - swap_endianess(i); - l = i; - } - - void readShort(short& i) const - { - read(&i, sizeof(i)); - swap_endianess(i); - } - - void readUnsignedShort(unsigned short& i) const - { - read(&i, sizeof(i)); - swap_endianess(i); - } - - void readBool(bool& b) const - { - char c; - read(&c, sizeof(c)); - b = (c != 0); - } - - void readString(std::string& s) const - { - unsigned int size = 0; - readUnsignedInt(size); - s.clear(); - s.reserve(size); - std::string::value_type buffer[1024]; - while (size) - { - size_t count = std::min(1024u, size); - read(buffer, count); - s.append(buffer, count); - size -= count; - } - } - - void readFloat(float& i) const - { - read(&i, sizeof(i)); - swap_endianess(i); - } - - void readDouble(double& i) const - { - read(&i, sizeof(i)); - swap_endianess(i); - } + virtual ~InputStream() + { + } + + virtual void read(void* data, size_t size) const = 0; + + virtual bool good() const = 0; + + inline void readChar(char& c) const + { + read(&c, sizeof(c)); + } + + inline void readUChar(unsigned char& c) const + { + read(&c, sizeof(c)); + } + + inline void readBool(bool& b) const + { + char c; + read(&c, sizeof(c)); + b = (c != 0); + } + + inline void readInt16(int16_t& i) const + { + read(&i, sizeof(i)); + swap_endianess(i); + } + + inline void readUInt16(uint16_t& i) const + { + read(&i, sizeof(i)); + swap_endianess(i); + } + + inline void readInt32(int32_t& i) const + { + read(&i, sizeof(i)); + swap_endianess(i); + } + + inline void readUInt32(uint32_t& i) const + { + read(&i, sizeof(i)); + swap_endianess(i); + } + + inline void readInt64(int64_t& i) const + { + read(&i, sizeof(i)); + swap_endianess(i); + } + + inline void readUInt64(uint64_t& i) const + { + read(&i, sizeof(i)); + swap_endianess(i); + } + + inline void readFloat(float& i) const + { + read(&i, sizeof(i)); + swap_endianess(i); + } + + inline void readDouble(double& i) const + { + read(&i, sizeof(i)); + swap_endianess(i); + } + + void readString(std::string& s) const + { + uint32_t size = 0; + readUInt32(size); + s.clear(); + s.reserve(size); + std::string::value_type buffer[1024]; + while (size) + { + size_t count = std::min(1024u, size); + read(buffer, count); + s.append(buffer, count); + size -= count; + } + } }; -// iotl /** This class serves the internal PXL I/O scheme by implementing how basic C++ types are read from an input buffer. */ -class PXL_DLL_EXPORT BufferInput: public InputStream +class PXL_DLL_EXPORT BufferInput : public InputStream { - mutable size_t _readPosition; - public: - - std::vector buffer; - - BufferInput() : - _readPosition(0) - { - - } - - void clear() - { - buffer.clear(); - _readPosition = 0; - } - - bool good() const - { - size_t av = available(); - return (av > 0); - } - - size_t available() const - { - return (buffer.size() - _readPosition); - } - - void read(void *data, size_t size) const - { - if (available() < size) - throw std::runtime_error("buffer underrun!"); - - memcpy(data, &buffer[_readPosition], size); - _readPosition += size; - } + std::vector buffer; + + BufferInput() + : InputStream() + , _readPosition(0) + { + } + + void clear() + { + buffer.clear(); + _readPosition = 0; + } + + bool good() const + { + size_t av = available(); + return (av > 0); + } + + size_t available() const + { + return (buffer.size() - _readPosition); + } + + void read(void* data, size_t size) const + { + if (available() < size) + { + throw std::runtime_error("buffer underrun!"); + } + + memcpy(data, &buffer[_readPosition], size); + _readPosition += size; + } + +private: + mutable size_t _readPosition; }; -} +} // namespace pxl -#endif /*PXL_IO_STREAM_HH*/ +#endif // PXL_CORE_STREAM_HH diff --git a/core/include/pxl/core/Tokenizer.hh b/core/include/pxl/core/Tokenizer.hh index 0b03fa7e6b8bc677d224107cf252b4c7e00b539e..4caa1b0550d0d6e070dd85d21d5b96d34cdeb14f 100644 --- a/core/include/pxl/core/Tokenizer.hh +++ b/core/include/pxl/core/Tokenizer.hh @@ -1,51 +1,53 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- -#ifndef PXL_TOKENIZER_H_ -#define PXL_TOKENIZER_H_ - -#include "pxl/core/macros.hh" +#ifndef PXL_CORE_TOKENIZER_HH +#define PXL_CORE_TOKENIZER_HH #include #include +#include "pxl/core/Macros.hh" + namespace pxl { class PXL_DLL_EXPORT Tokenizer { public: - enum CharType - { - WHITESPACE, ORDINARY, DELIM, LITERAL - }; + enum CharType + { + WHITESPACE, + ORDINARY, + DELIM, + LITERAL + }; - Tokenizer(); - virtual ~Tokenizer(); + Tokenizer(); + virtual ~Tokenizer(); - bool hasNext(); - std::string next(); + bool hasNext(); + std::string next(); - void setCharType(size_t begin, size_t end, CharType type); - void setCharType(size_t chr, CharType type); - void setText(const std::string &str); + void setCharType(size_t begin, size_t end, CharType type); + void setCharType(size_t chr, CharType type); + void setText(const std::string& str); private: - void findToken(); + size_t _pos; + std::string _text; + std::string _token; + bool _tokenAvailable; + std::vector _types; -private: - size_t _pos; - std::string _text; - std::string _token; - bool _tokenAvailable; - std::vector _types; + void findToken(); }; -} +} // namespace pxl -#endif +#endif // PXL_CORE_TOKENIZER_HH diff --git a/core/include/pxl/core/UserRecord.hh b/core/include/pxl/core/UserRecord.hh deleted file mode 100644 index 94c7316e3d6a69fc2fdf35cb79eb7a44f2f79d77..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/UserRecord.hh +++ /dev/null @@ -1,326 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_BASE_USERRECORD_HH -#define PXL_BASE_USERRECORD_HH -#include "pxl/core/macros.hh" - -#include -#include -#include -#include - -#include "pxl/core/Variant.hh" -#include "pxl/core/Stream.hh" -#include "pxl/core/Id.hh" - -namespace pxl -{ -/** - This class is intented to aggregate information complementary to data members in form - of string-variant pairs. - All PXL physics objects own user records and provide methods for quick - access to individual user record entries. - */ -class PXL_DLL_EXPORT UserRecords -{ - -private: - class DataSocket - { - public: - DataSocket() : - _references(1) - { - } - DataSocket(const DataSocket& original) : - _references(1), _data(original._data) - { - } - DataSocket(const DataSocket* original) : - _references(1), _data(original->_data) - { - } - virtual ~DataSocket() - { - } - - // for deep copies - virtual DataSocket* clone() const - { - return new DataSocket(this); - } - - // methods to grant data access - inline std::map* getData() - { - return &_data; - } - inline void setData(const std::map* object) - { - _data = *object; - } - - unsigned int _references; - std::map _data; - - }; //class Datasocket - -public: - typedef std::map map_type; - typedef map_type::const_iterator const_iterator; - typedef map_type::iterator iterator; - - UserRecords() - { - _dataSocket = new DataSocket; - } - UserRecords(const UserRecords& original) - { - _dataSocket = original._dataSocket; - _dataSocket->_references++; - } - explicit UserRecords(const UserRecords* original) - { - _dataSocket = original->_dataSocket; - _dataSocket->_references++; - } - ~UserRecords() - { - dropDataSocket(); - } - - void serialize(const OutputStream &out) const; - void deserialize(const InputStream &in); - - /// This assignment operator acts directly on the aggregated data. - inline UserRecords& operator=(const UserRecords& original) - { - dropDataSocket(); - _dataSocket = original._dataSocket; - _dataSocket->_references++; - return *this; - } - - /// Inserts (or replaces) the user record indetified by \p key. - void set(const std::string& key, const Variant& item) - { - findOrAlloc(key) = item; - } - - /// Searches and returns the user record item indetified by \p key; a pxl::Exception is thrown in case the key is not found. - const Variant &get(const std::string& key) const - { - const Variant* value = find(key); - if (!value) - throw std::runtime_error("pxl::UserRecord::get(...): key '" + key - + "' not found"); - return *value; - } - - /// find the user record entry identified by key. return 0 when no entry is found. - Variant* find(const std::string &key) - { - iterator found = setContainer()->find(key); - if (found == setContainer()->end()) - return 0; - return &found->second; - } - - const Variant* find(const std::string &key) const - { - const_iterator found = getContainer()->find(key); - if (found == getContainer()->end()) - return 0; - return &found->second; - } - - /// Checks if the user record entry identified by key is present. - bool has(const std::string& key) const - { - const_iterator found = getContainer()->find(key); - if (found == getContainer()->end()) - return false; - return true; - } - - /// Checks if user record entry identified by \p key is present. - /// If yes, its value is put into the passed \p item. - template bool get(const std::string& key, datatype& item) const - { - const Variant* value = find(key); - if (!value) - return false; - item = value->to(); - return true; - } - - /// Checks if a user record entry identified by \p key is present, - /// and changes it to the passed value in case it is present. If not, an exception is thrown. - template void change(const std::string& key, - datatype item) - { - iterator found = setContainer()->find(key); - if (found == getContainer()->end()) - throw std::runtime_error( - "pxl::UserRecord::change(...): UserRecord entry '" + key - + "' not found"); - - Variant& value = found->second; - if (value.getTypeInfo() != typeid(datatype)) - throw std::runtime_error( - "pxl::UserRecord::change(...): UserRecord entry '" + key - + "' of wrong type"); - - value = item; - } - - inline void clear() - { - setContainer()->clear(); - } - - inline void erase(const std::string& key) - { - size_t s = setContainer()->erase(key); - if (s == 0) - throw std::runtime_error("Cannot erase unknown key: "+key); - } - - /// Grants read access to the aggregated data. - inline const std::map* getContainer() const - { - return _dataSocket->getData(); - } - - inline const_iterator begin() const - { - return getContainer()->begin(); - } - - inline const_iterator end() const - { - return getContainer()->end(); - } - - inline size_t size() const - { - return getContainer()->size(); - } - - std::ostream - & print(int level = 0, std::ostream& os = std::cout, int pan = 0) const; - const std::string toString() const - { - std::ostringstream ss; - this->print(0, ss); - return ss.str(); - } - -private: - DataSocket* _dataSocket; - - /// Grants write access to the aggregated data; - /// if necessary, the copy-on-write mechanism performs a deep copy of the aggregated data first. - inline std::map* setContainer() - { - if (_dataSocket->_references > 1) - { - _dataSocket->_references--; - _dataSocket = new DataSocket(*_dataSocket); - } - return _dataSocket->getData(); - } - - inline void dropDataSocket() - { - if (_dataSocket->_references-- == 1) - delete _dataSocket; - } - - Variant& findOrAlloc(const std::string &key) - { - iterator insertPos = setContainer()->lower_bound(key); - if (insertPos == getContainer()->end() || insertPos->first != key) - return setContainer()->insert(insertPos, make_pair(key, Variant()))->second; - else - return insertPos->second; - } - - Variant& setFast(iterator insertPos, const std::string &key, - const Variant& item) - { - Variant &v = setContainer()->insert(insertPos, - make_pair(key, Variant()))->second; - v = item; - return v; - } -}; - -class PXL_DLL_EXPORT UserRecordHelper -{ -public: - const UserRecords& getUserRecords() const - { - return _userRecords; - } - - void setUserRecords(const UserRecords& value) - { - _userRecords = value; - } - - UserRecords& getUserRecords() - { - return _userRecords; - } - - inline void setUserRecord(const std::string& key, const Variant& value) - { - _userRecords.set(key, value); - } - - void eraseUserRecord(const std::string& key) - { - _userRecords.erase(key); - } - - const Variant &getUserRecord(const std::string& key) const - - { - return _userRecords.get(key); - } - - template bool getUserRecord(const std::string& key, - datatype& item) const - { - return _userRecords.template get (key, item); - } - - inline bool hasUserRecord(const std::string& key) const - { - return _userRecords.has(key); - } - - void serialize(const OutputStream &out) const - { - _userRecords.serialize(out); - } - - void deserialize(const InputStream &in) - { - _userRecords.deserialize(in); - } - -private: - UserRecords _userRecords; -}; - -} // namespace pxl - -#endif // PXL_BASE_USERRECORD_HH diff --git a/core/include/pxl/core/UserRecords.hh b/core/include/pxl/core/UserRecords.hh new file mode 100644 index 0000000000000000000000000000000000000000..2caa3c1c13025e4c3942445f488e72b69417596e --- /dev/null +++ b/core/include/pxl/core/UserRecords.hh @@ -0,0 +1,121 @@ +//------------------------------------------- +// Project: Physics eXtension Library (PXL) - +// http://vispa.physik.rwth-aachen.de/ - +// Copyright (C) 2006-2019 Martin Erdmann - +// RWTH Aachen, Germany - +// Licensed under a LGPL-2 or later license - +//------------------------------------------- + +#ifndef PXL_CORE_USERRECORDS_HH +#define PXL_CORE_USERRECORDS_HH + +#include "pxl/core/Macros.hh" +#include "pxl/core/Serializable.hh" +#include "pxl/core/Stream.hh" +#include "pxl/core/Variant.hh" + +namespace pxl +{ + +class PXL_DLL_EXPORT UserRecords +{ +private: + Variant _var; + +public: + typedef Variant::mapping_iterator iterator; + typedef Variant::mapping_const_iterator const_iterator; + + UserRecords() + : _var(Variant::TYPE_MAPPING) + { + } + + UserRecords(const UserRecords& records) + : _var(records._var) + { + } + + UserRecords(const UserRecords* records) + : _var(records->_var) + { + } + + virtual ~UserRecords() + { + } + + void serialize(const OutputStream& out) const; + + void deserialize(const InputStream& in); + + inline void set(const std::string& key, const Variant& var) + { + _var[key] = var; + } + + inline Variant& get(const std::string& key) + { + return _var[key]; + } + + inline void replace(const UserRecords& records) + { + _var = records._var; + } + + inline bool has(const std::string& key) + { + return _var.has(key); + } + + inline void clear() + { + _var.clear(Variant::TYPE_MAPPING); + } + + inline void remove(const std::string& key) + { + _var.remove(key); + } + + inline size_t size() const + { + return _var.size(); + } + + inline Variant& toVariant() + { + return _var; + } + + void fromVariant(const Variant& var) + { + _var = var; + _var.asMapping(); + } + + inline iterator begin() + { + return _var.beginMapping(); + } + + inline const_iterator begin() const + { + return _var.beginMapping(); + } + + inline iterator end() + { + return _var.endMapping(); + } + + inline const_iterator end() const + { + return _var.endMapping(); + } +}; + +} // namespace pxl + +#endif // PXL_CORE_USERRECORDS_HH diff --git a/core/include/pxl/core/Variant.hh b/core/include/pxl/core/Variant.hh index f643f5f7de4e667ac8da396de7a780517fc92c1c..9cfd0948d5c5ef4e44202dbd5ae557cd4a584d7c 100644 --- a/core/include/pxl/core/Variant.hh +++ b/core/include/pxl/core/Variant.hh @@ -1,55 +1,162 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- -#ifndef PXL_BASE_VARIANT_HH -#define PXL_BASE_VARIANT_HH - -#include "pxl/core/macros.hh" -#include "pxl/core/functions.hh" -#include "pxl/core/Basic3Vector.hh" -#include "pxl/core/LorentzVector.hh" -#include "pxl/core/Serializable.hh" -#include "pxl/core/Id.hh" +#ifndef PXL_CORE_VARIANT_HH +#define PXL_CORE_VARIANT_HH +#include #include -#include -#include +#include +#include #include -#include #include -#include #include -#include +#include +#include + +#include "pxl/core/AssocVector.hh" +#include "pxl/core/Functions.hh" +#include "pxl/core/Id.hh" +#include "pxl/core/LorentzVector.hh" +#include "pxl/core/Macros.hh" +#include "pxl/core/Serializable.hh" +#include "pxl/core/Vector3.hh" + +namespace minijson +{ -#define VARIANT_ADD_TYPE_DECL_POD(NAME, TYPE, VALUE, FIELD) \ - bool is ## NAME() const { return (type == TYPE); } \ - operator VALUE () const { return to ## NAME(); } \ - VALUE &as ## NAME() { check(TYPE); return data._u_##FIELD; } \ - const VALUE &as ## NAME() const { check(TYPE); return data._u_##FIELD; } \ - static Variant from ## NAME(const VALUE &a) { return Variant(a); } \ - VALUE to ## NAME() const; \ - Variant &operator = (const VALUE &a) { clear(); type = TYPE; data._u_##FIELD = a; return *this; } \ - bool operator != (const VALUE &a) const { check(TYPE); return data._u_##FIELD != a; } \ - bool operator == (const VALUE &a) const { check(TYPE); return data._u_##FIELD == a; } \ - Variant(const VALUE &a) { data._u_##FIELD = a; type = TYPE; } - -#define VARIANT_ADD_TYPE_DECL_PTR_BASE(NAME, TYPE, VALUE, FIELD) \ - bool is ## NAME() const { return (type == TYPE); } \ - VALUE &as ## NAME() { check(TYPE); return *data._u_##FIELD; } \ - const VALUE &as ## NAME() const { check(TYPE); return *data._u_##FIELD; } \ - static Variant from ## NAME(const VALUE &a) { return Variant(a); } \ - -#define VARIANT_ADD_TYPE_DECL_PTR(NAME, TYPE, VALUE, FIELD) \ - bool operator != (const VALUE &a) const { check(TYPE); return *data._u_##FIELD != a; } \ - bool operator == (const VALUE &a) const { check(TYPE); return *data._u_##FIELD == a; } \ - VARIANT_ADD_TYPE_DECL_PTR_BASE(NAME, TYPE, VALUE, FIELD) \ - Variant &operator =(const VALUE &a) { if (type != TYPE) { clear(); data._u_##FIELD = new VALUE; } type = TYPE; (*data._u_##FIELD) = a; return *this; } \ - Variant(const VALUE &a) { data._u_##FIELD = new VALUE(a); type = TYPE; } +class object_writer; +class object_reader; +class array_writer; +class array_reader; + +} // namespace minijson + +// defines copy constructor X(const X&), isX(), asX(), fromX(), toX(), op(), op=, op==, op!= +#define VARIANT_ADD_TYPE_DECL_POD(NAME, TYPE, VALUE, FIELD) \ + Variant(const VALUE& v) \ + { \ + data._u_##FIELD = v; \ + type = TYPE; \ + } \ + bool is##NAME() const \ + { \ + return type == TYPE; \ + } \ + VALUE& as##NAME() \ + { \ + check(TYPE); \ + return data._u_##FIELD; \ + } \ + const VALUE& as##NAME() const \ + { \ + check(TYPE); \ + return data._u_##FIELD; \ + } \ + static Variant from##NAME(const VALUE& v) \ + { \ + return Variant(v); \ + } \ + VALUE to##NAME() const; \ + operator VALUE() const \ + { \ + return to##NAME(); \ + } \ + Variant& operator=(const VALUE& v) \ + { \ + clear(); \ + type = TYPE; \ + data._u_##FIELD = v; \ + return *this; \ + } \ + bool operator==(const VALUE& v) const \ + { \ + check(TYPE); \ + return data._u_##FIELD == v; \ + } \ + bool operator!=(const VALUE& v) const \ + { \ + return !(*this == v); \ + } + +// defines isX(), asX(), fromX() +#define VARIANT_ADD_TYPE_DECL_PTR_BASE(NAME, TYPE, VALUE, FIELD) \ + bool is##NAME() const \ + { \ + return type == TYPE; \ + } \ + VALUE& as##NAME() \ + { \ + check(TYPE); \ + return *data._u_##FIELD; \ + } \ + const VALUE& as##NAME() const \ + { \ + check(TYPE); \ + return *data._u_##FIELD; \ + } \ + static Variant from##NAME(const VALUE& v) \ + { \ + return Variant(v); \ + } + +// defines isX(), asX(), fromX(), and copy constructor X(const X&), op=, op==, op!= +#define VARIANT_ADD_TYPE_DECL_PTR(NAME, TYPE, VALUE, FIELD) \ + VARIANT_ADD_TYPE_DECL_PTR_BASE(NAME, TYPE, VALUE, FIELD) \ + Variant(const VALUE& v) \ + { \ + data._u_##FIELD = new VALUE(v); \ + type = TYPE; \ + } \ + Variant& operator=(const VALUE& v) \ + { \ + if (type != TYPE) \ + { \ + clear(); \ + data._u_##FIELD = new VALUE(); \ + } \ + type = TYPE; \ + (*data._u_##FIELD) = v; \ + return *this; \ + } \ + bool operator==(const VALUE& v) const \ + { \ + check(TYPE); \ + return *data._u_##FIELD == v; \ + } \ + bool operator!=(const VALUE& v) const \ + { \ + return !(*this == v); \ + } + +#define VARIANT_ADD_ITER_DECL_PTR(NAME, TYPE, FIELD) \ + typedef FIELD##_t::iterator FIELD##_iterator; \ + typedef FIELD##_t::const_iterator FIELD##_const_iterator; \ + inline FIELD##_iterator begin##NAME() \ + { \ + check(TYPE); \ + return data._u_##FIELD->begin(); \ + } \ + inline FIELD##_iterator end##NAME() \ + { \ + check(TYPE); \ + return data._u_##FIELD->end(); \ + } \ + inline FIELD##_const_iterator begin##NAME() const \ + { \ + check(TYPE); \ + return data._u_##FIELD->begin(); \ + } \ + inline FIELD##_const_iterator end##NAME() const \ + { \ + check(TYPE); \ + return data._u_##FIELD->end(); \ + } namespace pxl { @@ -57,235 +164,310 @@ namespace pxl class PXL_DLL_EXPORT Variant { public: - enum Type - { - TYPE_NONE = 0, - TYPE_BOOL, - TYPE_CHAR, - TYPE_UCHAR, - TYPE_INT16, - TYPE_UINT16, - TYPE_INT32, - TYPE_UINT32, - TYPE_INT64, - TYPE_UINT64, - TYPE_FLOAT, - TYPE_DOUBLE, - TYPE_STRING, - TYPE_SERIALIZABLE, - TYPE_BASIC3VECTOR, - TYPE_LORENTZVECTOR, - TYPE_VECTOR - }; + typedef std::vector vector_t; + typedef loki::AssocVector mapping_t; + + enum Type + { + TYPE_NONE = 0, + TYPE_BOOL, + TYPE_CHAR, + TYPE_UCHAR, + TYPE_INT16, + TYPE_UINT16, + TYPE_INT32, + TYPE_UINT32, + TYPE_INT64, + TYPE_UINT64, + TYPE_FLOAT, + TYPE_DOUBLE, + TYPE_STRING, + TYPE_VECTOR, + TYPE_MAPPING, + TYPE_VECTOR3, + TYPE_LORENTZVECTOR, + TYPE_SERIALIZABLE + }; + + class bad_conversion : public std::exception + { + public: + const char* what() const throw() + { + return _msg.c_str(); + } + + bad_conversion(Type f, Type t) + { + _msg = "Variant: bad conversion from '"; + _msg += Variant::getTypeName(f); + _msg += "' to '"; + _msg += Variant::getTypeName(t); + _msg += "'"; + } + + ~bad_conversion() throw() + { + } + + private: + std::string _msg; + }; + + Variant() + : type(TYPE_NONE) + { + } + + Variant(Type t) + : type(TYPE_NONE) + { + check(t); + } + + Variant(const Variant& v) + : type(TYPE_NONE) + { + copy(v); + } - class bad_conversion: public std::exception - { - std::string msg; - public: - const char* what() const throw () - { - return msg.c_str(); - } - bad_conversion(Type f, Type t) - { - msg = "Variant: bad conversion from '"; - msg += Variant::getTypeName(f); - msg += "' to '"; - msg += Variant::getTypeName(t); - msg += "'"; - } - ~bad_conversion() throw () - { - } - }; - - Variant(); - ~Variant(); - - Variant(const Variant& a); - - const std::type_info& getTypeInfo() const; - - const char * getTypeName() const - { - return getTypeName(type); - } - - static Type toType(const std::string &name); - - static const char *getTypeName(Type type); - - template - T to() const - { - throw bad_conversion(type, TYPE_NONE); - } - - Type getType() const - { - return type; - } - - bool operator ==(const Variant &a) const; - - bool operator !=(const Variant &a) const; - - bool operator >(const Variant &a) const; - - bool operator >=(const Variant &a) const; - - bool operator <(const Variant &a) const; - - bool operator <=(const Variant &a) const; - - Variant &operator =(const Variant &a) - { - copy(a); - return *this; - } - - bool isValid() - { - return (type != TYPE_NONE); - } - - VARIANT_ADD_TYPE_DECL_POD(Bool, TYPE_BOOL, bool, bool) - - VARIANT_ADD_TYPE_DECL_POD(Char, TYPE_CHAR, char, char) - - VARIANT_ADD_TYPE_DECL_POD(UChar, TYPE_UCHAR, unsigned char, uchar) - - VARIANT_ADD_TYPE_DECL_POD(Int16, TYPE_INT16, int16_t, int16) - - VARIANT_ADD_TYPE_DECL_POD(UInt16, TYPE_UINT16, uint16_t, uint16) - - VARIANT_ADD_TYPE_DECL_POD(Int32, TYPE_INT32, int32_t, int32) - - VARIANT_ADD_TYPE_DECL_POD(UInt32, TYPE_UINT32, uint32_t, uint32) - - VARIANT_ADD_TYPE_DECL_POD(Int64, TYPE_INT64, int64_t, int64) - - VARIANT_ADD_TYPE_DECL_POD(UInt64, TYPE_UINT64, uint64_t, uint64) - - VARIANT_ADD_TYPE_DECL_POD(Float, TYPE_FLOAT, float, float) - - VARIANT_ADD_TYPE_DECL_POD(Double, TYPE_DOUBLE, double, double) - - VARIANT_ADD_TYPE_DECL_PTR(Basic3Vector, TYPE_BASIC3VECTOR, Basic3Vector, Basic3Vector) - - VARIANT_ADD_TYPE_DECL_PTR(LorentzVector, TYPE_LORENTZVECTOR, LorentzVector, LorentzVector) - - VARIANT_ADD_TYPE_DECL_PTR(String, TYPE_STRING, std::string, string) - Variant(const char *s); - std::string toString() const; - static Variant fromString(const std::string &str, Type type); - operator std::string() const - { - return toString(); - } - bool operator !=(const char *a) const - { - check(TYPE_STRING); - return data._u_string->compare(a) != 0; - } - - // serializable - VARIANT_ADD_TYPE_DECL_PTR_BASE(Serializable, TYPE_SERIALIZABLE, Serializable, Serializable) - Variant(const Serializable *a); - Variant(const Serializable &a); - Variant &operator =(const Serializable &a) - { - clear(); - type = TYPE_SERIALIZABLE; - data._u_Serializable = a.clone(); - return *this; - } - - Variant &operator =(const Serializable *a) - { - clear(); - type = TYPE_SERIALIZABLE; - data._u_Serializable = a->clone(); - return *this; - } - - template T cast() - { - check(TYPE_SERIALIZABLE); - return dynamic_cast(data._u_Serializable); - } - - template const T cast() const - { - check(TYPE_SERIALIZABLE); - return dynamic_cast(data._u_Serializable); - } - - bool operator !=(const Serializable *a) const - { - check(TYPE_SERIALIZABLE); - return data._u_Serializable != a; - } - bool operator ==(const Serializable *a) const - { - check(TYPE_SERIALIZABLE); - return data._u_Serializable == a; - } - - // std::vector - Variant(const std::vector &a); - bool isVector() const; - operator std::vector &(); - operator const std::vector &() const; - std::vector &asVector(); - const std::vector &asVector() const; - static Variant fromVector(const std::vector &s); - std::vector toVector() const; - Variant &operator =(const std::vector &a); - bool operator ==(const std::vector &a) const; - bool operator !=(const std::vector &a) const; - Variant &operator[](size_t i); - const Variant &operator[](size_t i) const; - void resize(size_t i); - - // io - void serialize(const OutputStream &out) const; - void deserialize(const InputStream &in); - void clear(); + ~Variant() + { + clear(); + } + + inline Type getType() const + { + return type; + } + + const std::type_info& getTypeInfo() const; + + const char* getTypeName() const + { + return getTypeName(type); + } + + static const char* getTypeName(Type t); + + static Type toType(const std::string& name); + + template T to() const + { + throw bad_conversion(type, TYPE_NONE); + } + + bool isValid() + { + return type != TYPE_NONE; + } + + size_t size() const; + + void serialize(const OutputStream& out) const; + + void deserialize(const InputStream& in); + + void clear(Type t = TYPE_NONE); + + void toJson(std::ostream& out) const; + + void fromJson(std::istream& in); + + static Variant fromString(const std::string& str, Type type); + + Variant& operator=(const Variant& v) + { + copy(v); + return *this; + } + + bool operator==(const Variant& v) const; + + bool operator!=(const Variant& v) const; + + bool operator>(const Variant& v) const; + + bool operator>=(const Variant& v) const; + + bool operator<(const Variant& v) const; + + bool operator<=(const Variant& v) const; + + // bool + VARIANT_ADD_TYPE_DECL_POD(Bool, TYPE_BOOL, bool, bool) + + // char + VARIANT_ADD_TYPE_DECL_POD(Char, TYPE_CHAR, char, char) + + // uchar + VARIANT_ADD_TYPE_DECL_POD(UChar, TYPE_UCHAR, unsigned char, uchar) + + // int16 + VARIANT_ADD_TYPE_DECL_POD(Int16, TYPE_INT16, int16_t, int16) + + // uint16 + VARIANT_ADD_TYPE_DECL_POD(UInt16, TYPE_UINT16, uint16_t, uint16) + + // int32 + VARIANT_ADD_TYPE_DECL_POD(Int32, TYPE_INT32, int32_t, int32) + + // uint32 + VARIANT_ADD_TYPE_DECL_POD(UInt32, TYPE_UINT32, uint32_t, uint32) + + // int64 + VARIANT_ADD_TYPE_DECL_POD(Int64, TYPE_INT64, int64_t, int64) + + // uint64 + VARIANT_ADD_TYPE_DECL_POD(UInt64, TYPE_UINT64, uint64_t, uint64) + + // float + VARIANT_ADD_TYPE_DECL_POD(Float, TYPE_FLOAT, float, float) + + // double + VARIANT_ADD_TYPE_DECL_POD(Double, TYPE_DOUBLE, double, double) + + // string + VARIANT_ADD_TYPE_DECL_PTR(String, TYPE_STRING, std::string, string) + Variant(const char* s); + std::string toString() const; + operator std::string() const + { + return toString(); + } + bool operator==(const char* s) const + { + check(TYPE_STRING); + return data._u_string->compare(s) == 0; + } + bool operator!=(const char* s) const + { + return !(*this == s); + } + Variant& operator=(const char* s) + { + return operator=(std::string(s)); + } + + // vector + VARIANT_ADD_TYPE_DECL_PTR(Vector, TYPE_VECTOR, vector_t, vector) + VARIANT_ADD_ITER_DECL_PTR(Vector, TYPE_VECTOR, vector) + vector_t toVector() const; + void resize(size_t i); + Variant& operator[](size_t i); + const Variant& operator[](size_t i) const; + inline Variant& operator[](int i) + { + return operator[]((size_t)i); + } + const Variant& operator[](int i) const + { + return operator[]((size_t)i); + } + operator vector_t&(); + operator const vector_t&() const; + + // mapping + VARIANT_ADD_TYPE_DECL_PTR(Mapping, TYPE_MAPPING, mapping_t, mapping) + VARIANT_ADD_ITER_DECL_PTR(Mapping, TYPE_MAPPING, mapping) + mapping_t toMapping() const; + Variant& operator[](const char* s); + Variant& operator[](const std::string& s); + const Variant& operator[](const char* s) const; + const Variant& operator[](const std::string& s) const; + operator mapping_t&(); + operator const mapping_t&() const; + inline bool has(const std::string& s) + { + check(TYPE_MAPPING); + return data._u_mapping->find(s) != data._u_mapping->end(); + } + inline void remove(const std::string& s) + { + asMapping().erase(s); + } + + // Vector3 + VARIANT_ADD_TYPE_DECL_PTR(Vector3, TYPE_VECTOR3, Vector3, Vector3) + + // LorentzVector + VARIANT_ADD_TYPE_DECL_PTR(LorentzVector, TYPE_LORENTZVECTOR, LorentzVector, LorentzVector) + + // Serializable + VARIANT_ADD_TYPE_DECL_PTR_BASE(Serializable, TYPE_SERIALIZABLE, Serializable, Serializable) + Variant(const Serializable* v); + Variant(const Serializable& v); + Variant& operator=(const Serializable& v) + { + clear(); + type = TYPE_SERIALIZABLE; + data._u_Serializable = v.clone(); + return *this; + } + Variant& operator=(const Serializable* v) + { + clear(); + type = TYPE_SERIALIZABLE; + data._u_Serializable = v->clone(); + return *this; + } + template T cast() + { + check(TYPE_SERIALIZABLE); + return dynamic_cast(data._u_Serializable); + } + template const T cast() const + { + check(TYPE_SERIALIZABLE); + return dynamic_cast(data._u_Serializable); + } + bool operator==(const Serializable* ser) const + { + check(TYPE_SERIALIZABLE); + return data._u_Serializable == ser; + } + bool operator!=(const Serializable* ser) const + { + return !(*this == ser); + } protected: - Type type; - - typedef std::vector vector_t; - typedef std::map map_t; - union - { - bool _u_bool; - char _u_char; - unsigned char _u_uchar; - int16_t _u_int16; - uint16_t _u_uint16; - int32_t _u_int32; - uint32_t _u_uint32; - int64_t _u_int64; - uint64_t _u_uint64; - double _u_double; - float _u_float; - Serializable *_u_Serializable; - Basic3Vector *_u_Basic3Vector; - LorentzVector *_u_LorentzVector; - vector_t *_u_vector; - std::string *_u_string; - } data; + Type type; + + union { + bool _u_bool; + char _u_char; + unsigned char _u_uchar; + int16_t _u_int16; + uint16_t _u_uint16; + int32_t _u_int32; + uint32_t _u_uint32; + int64_t _u_int64; + uint64_t _u_uint64; + double _u_double; + float _u_float; + std::string* _u_string; + vector_t* _u_vector; + mapping_t* _u_mapping; + Vector3* _u_Vector3; + LorentzVector* _u_LorentzVector; + Serializable* _u_Serializable; + } data; + + void toJson(minijson::object_writer& writer) const; + void toJson(minijson::array_writer& writer) const; private: - void copy(const Variant &a); - void check(const Type t) const; - void check(const Type t); + void copy(const Variant& v); + void check(const Type t) const; + void check(const Type t); }; -#define VARIANT_TO_DECL(NAME, VALUE) \ - template<> inline VALUE Variant::to() const { return to ## NAME(); } \ +#define VARIANT_TO_DECL(NAME, VALUE) \ + template <> inline VALUE Variant::to() const \ + { \ + return to##NAME(); \ + } VARIANT_TO_DECL(Bool, bool) VARIANT_TO_DECL(Char, char) @@ -299,10 +481,11 @@ VARIANT_TO_DECL(UInt64, uint64_t) VARIANT_TO_DECL(Float, float) VARIANT_TO_DECL(String, std::string) VARIANT_TO_DECL(Double, double) -VARIANT_TO_DECL(Vector, std::vector) +VARIANT_TO_DECL(Vector, Variant::vector_t) +VARIANT_TO_DECL(Mapping, Variant::mapping_t) -PXL_DLL_EXPORT std::ostream& operator <<(std::ostream& os, const Variant &v); +PXL_DLL_EXPORT std::ostream& operator<<(std::ostream& os, const Variant& v); } // namespace pxl -#endif // PXL_BASE_VARIANT_HH +#endif // PXL_CORE_VARIANT_HH diff --git a/core/include/pxl/core/Vector3.hh b/core/include/pxl/core/Vector3.hh new file mode 100644 index 0000000000000000000000000000000000000000..c3bd2f28d62dd691788d0cc8ee4b0c2b69e75de4 --- /dev/null +++ b/core/include/pxl/core/Vector3.hh @@ -0,0 +1,271 @@ +//------------------------------------------- +// Project: Physics eXtension Library (PXL) - +// http://vispa.physik.rwth-aachen.de/ - +// Copyright (C) 2006-2019 Martin Erdmann - +// RWTH Aachen, Germany - +// Licensed under a LGPL-2 or later license - +//------------------------------------------- + +#ifndef PXL_CORE_VECTOR3_HH +#define PXL_CORE_VECTOR3_HH + +#include +#include +#include + +#include "pxl/core/Macros.hh" +#include "pxl/core/Stream.hh" + +namespace pxl +{ + +/** + This class provides a simple threevector with basic algebra. The methods provided are + self-explanatory. + Note that theta is defined as 0 in z-direction, as usual in collider physics. + */ +class PXL_DLL_EXPORT Vector3 +{ +public: + Vector3() + { + _v[0] = 0; + _v[1] = 0; + _v[2] = 0; + } + + Vector3(const Vector3& vec) + { + _v[0] = vec._v[0]; + _v[1] = vec._v[1]; + _v[2] = vec._v[2]; + } + + explicit Vector3(const Vector3* vec) + { + _v[0] = vec->_v[0]; + _v[1] = vec->_v[1]; + _v[2] = vec->_v[2]; + } + + Vector3(double x, double y, double z) + { + _v[0] = x; + _v[1] = y; + _v[2] = z; + } + + Vector3(const double x[3]) + { + _v[0] = x[0]; + _v[1] = x[1]; + _v[2] = x[2]; + } + + virtual ~Vector3() + { + } + + virtual void serialize(const OutputStream& out) const + { + out.writeDouble(_v[0]); + out.writeDouble(_v[1]); + out.writeDouble(_v[2]); + } + + virtual void deserialize(const InputStream& in) + { + in.readDouble(_v[0]); + in.readDouble(_v[1]); + in.readDouble(_v[2]); + } + + inline void setX(double x) + { + _v[0] = x; + } + inline void setY(double y) + { + _v[1] = y; + } + inline void setZ(double z) + { + _v[2] = z; + } + + inline void setXYZ(double x, double y, double z) + { + _v[0] = x; + _v[1] = y; + _v[2] = z; + } + + void setArray(double val[3]) + { + setXYZ(val[0], val[1], val[2]); + } + + inline void setElement(int i, double val) + { + if (i < 0 || i > 2) + { + throw std::runtime_error("Vector3 index out of range"); + } + _v[i] = val; + } + + void setRhoPhi(double perp, double phi); + + void setRhoPhiZ(double perp, double phi, double z); + + void setRThetaPhi(double r, double theta, double phi); + + inline double getX() const + { + return _v[0]; + } + + inline double getY() const + { + return _v[1]; + } + + inline double getZ() const + { + return _v[2]; + } + + inline double getElement(int i) const + { + if (i < 0 || i > 2) + { + throw std::runtime_error("Vector3 index out of range"); + } + return _v[i]; + } + + inline double* getArray() + { + return _v; + } + + const double* getConstArray() const + { + return _v; + } + + double getPerp2() const; + + double getPerp() const; + + double getMag2() const; + + double getMag() const; + + double getPhi() const; + + double getTheta() const; + + double getCosTheta() const; + + double getCos2Theta() const; + + /// Returns unit vector in spherical coordinates + Vector3 getETheta() const; + + /// Returns unit vector in spherical coordinates + Vector3 getEPhi() const; + + double deltaPhi(const Vector3& vec) const; + + double deltaPhi(const Vector3* vec) const + { + return deltaPhi(*vec); + } + + double deltaTheta(const Vector3& vec) const; + + double deltaTheta(const Vector3* vec) const + { + return deltaPhi(*vec); + } + + double deltaRho(const Vector3& vec) const; + + double deltaRho(const Vector3* vec) const + { + return deltaRho(*vec); + } + + bool isNullPerp() const; + + bool isNull() const; + + bool isUnitVector() const; + + inline double dot(const Vector3& vec) const + { + return getX() * vec.getX() + getY() * vec.getY() + getZ() * vec.getZ(); + } + + inline Vector3 cross(const Vector3& vec) const + { + return Vector3(getY() * vec.getZ() - vec.getY() * getZ(), + getZ() * vec.getX() - vec.getZ() * getX(), getX() * vec.getY() - vec.getX() * getY()); + } + + /// returns the given norm, -1 for infinity norm + double norm(uint32_t norm) const; + + /// normalizes the vector to 1 + void normalize(); + + /// Returns angle between the vector and vec + double getAngleTo(const Vector3& vec) const; + + const Vector3& operator=(const Vector3& vec); + + const Vector3& operator+=(const Vector3& vec); + + const Vector3& operator-=(const Vector3& vec); + + const Vector3& operator*=(double scalar); + + const Vector3& operator/=(double scalar); + + Vector3 operator+(const Vector3& vec) const; + + /// Returns a copy of (this minus vec). + Vector3 operator-(const Vector3& vec) const; + + /// Returns a copy of (this divided by passed scalar). + Vector3 operator/(double scalar) const; + + /// scalar product + double operator*(const Vector3& vec) const; + + /// Return a copy of this Vector3 where all components are multiplied with -1. + inline Vector3 operator-() const + { + return Vector3(-1. * _v[0], -1. * _v[1], -1. * _v[2]); + } + + inline double operator()(size_t i) const + { + return getElement(i); + } + +private: + double _v[3]; +}; + +// non-member operators +PXL_DLL_EXPORT bool operator==(const Vector3& vec1, const Vector3& vec2); +PXL_DLL_EXPORT bool operator!=(const Vector3& vec1, const Vector3& vec2); + +PXL_DLL_EXPORT Vector3 operator*(const double scalar, const Vector3& vec); +PXL_DLL_EXPORT Vector3 operator*(const Vector3& vec, const double scalar); + +} // namespace pxl + +#endif // PXL_CORE_VECTOR3_HH diff --git a/core/include/pxl/core/WeakPtr.hh b/core/include/pxl/core/WeakPtr.hh new file mode 100644 index 0000000000000000000000000000000000000000..f19931cce94967acaa099c8519dd4ce8c0ec9139 --- /dev/null +++ b/core/include/pxl/core/WeakPtr.hh @@ -0,0 +1,246 @@ +//------------------------------------------- +// Project: Physics eXtension Library (PXL) - +// http://vispa.physik.rwth-aachen.de/ - +// Copyright (C) 2006-2019 Martin Erdmann - +// RWTH Aachen, Germany - +// Licensed under a LGPL-2 or later license - +//------------------------------------------- + +#ifndef PXL_CORE_WEAKPTR_HH +#define PXL_CORE_WEAKPTR_HH + +#include +#include + +#include "pxl/core/Macros.hh" + +namespace pxl +{ + +class Serializable; + +/** + This base class provides common functionalities for all derived PXL weak pointers. + */ +class PXL_DLL_EXPORT WeakPtr +{ +public: + virtual ~WeakPtr() + { + connect(0); + } + + /// This virtual method creates a deep copy and returns a C++ pointer to the newly-created weak + /// pointer instance. + virtual WeakPtr* clone() const + { + return new WeakPtr(*this); + } + + /// This method returns a C++ pointer of type Serializable to the referenced object + inline Serializable* pointer() const + { + return _ser; + } + /// This method returns true, if the referenced object exists. + inline bool valid() const + { + return _ser != 0; + } + + /// This allows pointer-like tests if the weak pointer is valid. + inline operator bool() + { + return valid(); + } + + /// This arrow operator de-references the weak pointer. + inline Serializable* operator->() const + { + return access(); + } + + /// compare the referenced object pointers + inline bool operator==(WeakPtr& ptr) const + { + return (_ser == ptr.pointer()); + } + + /// compare the referenced object pointers + inline bool operator!=(WeakPtr& ptr) const + { + return (_ser != ptr.pointer()); + } + + /// This method attempts a dynamic cast on the referenced object + static inline WeakPtr* cast_dynamic(WeakPtr* ptr) + { + return ptr; + } + + // safe access to object + inline Serializable* access() const + { + if (_ser) + { + return _ser; + } + throw std::runtime_error( + "WeakPtr::access(): FATAL: The object you intend to access does not exist!"); + return 0; + } + +protected: + WeakPtr() + : _notifyChainIn(0) + , _notifyChainOut(0) + , _ser(0) + { + } + + WeakPtr* _notifyChainIn; + WeakPtr* _notifyChainOut; + + Serializable* _ser; + + void notifyDeleted(); + + void connect(Serializable* ser); + + friend class Serializable; +}; + +/** + This class template represents a weak pointer to PXL objects of \p objecttype that aggregate data + of \p datatype. + */ +template class weak_ptr : public WeakPtr +{ +public: + weak_ptr() + : WeakPtr() + { + } + + weak_ptr(objecttype* ser) + : WeakPtr() + { + WeakPtr::connect(ser); + } + + weak_ptr(objecttype& ser) + : WeakPtr() + { + WeakPtr::connect(&ser); + } + + weak_ptr(const weak_ptr& ptr) + : WeakPtr() + { + WeakPtr::connect((objecttype*)ptr._ser); + } + + explicit weak_ptr(const weak_ptr* ptr) + : WeakPtr() + { + WeakPtr::connect((objecttype*)ptr->_ser); + } + + virtual ~weak_ptr() + { + WeakPtr::connect(0); + } + + /// This virtual method creates a deep copy and returns a C++ pointer to the newly-created weak + /// pointer instance. + virtual WeakPtr* clone() const + { + return new weak_ptr(*this); + } + + /// This assignment operator causes the weak pointer to reference the object referenced by \p + /// pptr. + inline void operator=(const weak_ptr& ptr) + { + connect(ptr._ser); + } + + /// This assignment operator causes the weak pointer to reference the object. + inline void operator=(objecttype& ser) + { + connect(&ser); + } + + /// This assignment operator causes the weak pointer to reference the object pointed to by \p + /// objectptr. + inline void operator=(objecttype* ser) + { + connect(ser); + } + + // methods to grant object & data access + /// This method provides direct access to the referenced object. + inline objecttype& object() const + { + return *access(); + } + + /// This arrow operator de-references the weak pointer. + inline objecttype* operator->() const + { + return access(); + } + + /// This arrow operator de-references the weak pointer. + inline objecttype* ptr() const + { + return dynamic_cast(_ser); + } + + inline operator objecttype*() const + { + return dynamic_cast(_ser); + } + + /// This method attempts a dynamic cast on the referenced object + static weak_ptr* cast_dynamic(WeakPtr* ptr) + { + objecttype* ser = dynamic_cast(ptr->pointer()); + if (!ser) + { + return 0; + } + + // FIXME: This is crude but required: + if (PXL_UNLIKELY(reinterpret_cast(ser) != reinterpret_cast(ptr->pointer()))) + throw std::runtime_error( + "WkPtrSpec::cast_dynamic(): Unsupported multiple inheritance configuration."); + return reinterpret_cast*>(ptr); + } + + // safe access to object + inline objecttype* access() const + { + if (_ser) + { + return (objecttype*)_ser; + } + throw std::runtime_error( + "WkPtrSpec::access(): FATAL: The object you intend to access does not exist!"); + return 0; + } +}; + +template objecttype& operator*(weak_ptr& ptr) +{ + return ptr.object(); +} + +template const objecttype& operator*(const weak_ptr& ptr) +{ + return ptr.object(); +} + +} // namespace pxl + +#endif // PXL_CORE_WEAKPTR_HH diff --git a/core/include/pxl/core/WkPtrBase.hh b/core/include/pxl/core/WkPtrBase.hh deleted file mode 100644 index 21a76f99e3e9b830b9d97680730f8751ccda1d85..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/WkPtrBase.hh +++ /dev/null @@ -1,105 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_BASE_WKPTRBASE_HH -#define PXL_BASE_WKPTRBASE_HH - -#include -#include "pxl/core/macros.hh" - -namespace pxl { - -// ptl - -class Relative; - -/** - This base class provides common functionalities for all derived PXL weak pointers. - */ -class PXL_DLL_EXPORT WkPtrBase -{ -public: - virtual ~WkPtrBase() - { - connect(0); - } - - /// This virtual method creates a deep copy and returns a C++ pointer to the newly-created weak pointer instance. - virtual WkPtrBase* clone() const - { - return new WkPtrBase(*this); - } - - /// This method returns a C++ pointer of type Relative to the referenced object - inline Relative* pointer() const - { - return _objectRef; - } - /// This method returns true, if the referenced object exists. - inline bool valid() const - { - return _objectRef != 0; - } - - /// This allows pointer-like tests if the weak pointer is valid. - inline operator bool() - { - return valid(); - } - /// This arrow operator de-references the weak pointer. - inline Relative* operator->() const - { - return access(); - } - /// compare the referenced object pointers - inline bool operator==(WkPtrBase &other) const - { - return (_objectRef == other.pointer()); - } - /// compare the referenced object pointers - inline bool operator!=(WkPtrBase &other) const - { - return (_objectRef != other.pointer()); - } - - /// This method attempts a dynamic cast on the referenced object - static inline WkPtrBase* cast_dynamic(WkPtrBase* orig) - { - return orig; - } - - // safe access to object - inline Relative* access() const - { - if (_objectRef) - return _objectRef; - throw std::runtime_error("WkPtrBase::access(): FATAL: The object you intend to access does not exist!"); - return 0; - } - -protected: - WkPtrBase() : - _notifyChainIn(0), _notifyChainOut(0), _objectRef(0) - { - } - - void notifyDeleted(); - - void connect(Relative* pointer); - - WkPtrBase* _notifyChainIn; - WkPtrBase* _notifyChainOut; - - Relative* _objectRef; - - friend class Relative; -}; - -} // namespace pxl - -#endif // PXL_BASE_WK_PTR_BASE_HH diff --git a/core/include/pxl/core/logging.hh b/core/include/pxl/core/logging.hh deleted file mode 100644 index cae01110d9da2e1fae38f63d71d9fe885a124b19..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/logging.hh +++ /dev/null @@ -1,263 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_BASE_LOGGING_HH -#define PXL_BASE_LOGGING_HH - -#include "pxl/core/macros.hh" -#include "pxl/core/functions.hh" - -#include -#include -#include -#include -#include - -namespace pxl -{ - -enum LogLevel -{ - LOG_LEVEL_ALL, - LOG_LEVEL_DEBUG, - LOG_LEVEL_INFO, - LOG_LEVEL_WARNING, - LOG_LEVEL_ERROR, - LOG_LEVEL_NONE -}; - -PXL_DLL_EXPORT LogLevel intToLogLevel(int i); -PXL_DLL_EXPORT const std::string &LogLevelToString(LogLevel level); - -class PXL_DLL_EXPORT LogHandler -{ -public: - virtual ~LogHandler() - { - } - - virtual void handle(LogLevel level, time_t timestamp, - const std::string &module, const std::string &message) = 0; -}; - -class PXL_DLL_EXPORT ConsoleLogHandler: public LogHandler -{ - std::vector enabledModules; - std::vector disabledModules; - std::string warningColor, errorColor, endColor; -public: - - ConsoleLogHandler(); - - virtual ~ConsoleLogHandler() - { - } - - void handle(LogLevel level, time_t timestamp, const std::string &module, - const std::string &message); -}; - -class PXL_DLL_EXPORT LogDispatcher -{ -public: - - typedef std::vector > handlers_t; - -private: - - handlers_t handlers; - LogLevel lowestLogLevel; - ConsoleLogHandler consoleLogHandler; - std::string indent; - - void updateLowestLogLevel(); - -public: - LogDispatcher(); - - void pushIndent(char c) - { - indent.append(1, c); - } - - void popIndent() - { - indent.resize(indent.length() - 1); - } - - const std::string &getIndent() - { - return indent; - } - - void setHandler(LogHandler *handler, LogLevel loglevel); - - void removeHandler(LogHandler *handler); - - void dispatch(LogLevel level, const std::string &module, - const std::string &message); - - LogLevel getLowestLogLevel(); - - void disableConsoleLogHandler(); - void enableConsoleLogHandler(LogLevel level); - - static LogDispatcher& instance(); -}; - -class PXL_DLL_EXPORT Logger -{ -private: - std::string module; -public: - - Logger(const char *module_name) : - module(module_name) - { - - } - - void log(LogLevel level, const std::string &msg) - { - if (LogDispatcher::instance().getLowestLogLevel() <= level) - { - LogDispatcher::instance().dispatch(level, module, - LogDispatcher::instance().getIndent() + msg); - } - } - - template - void operator()(LogLevel level, const T0 &t0) - { - if (LogDispatcher::instance().getLowestLogLevel() <= level) - { - std::stringstream stream; - stream << LogDispatcher::instance().getIndent(); - stream << t0; - LogDispatcher::instance().dispatch(level, module, stream.str()); - } - } - - template - void operator()(LogLevel level, const T0 &t0, const T1 &t1) - { - if (LogDispatcher::instance().getLowestLogLevel() <= level) - { - std::stringstream stream; - stream << LogDispatcher::instance().getIndent(); - stream << t0; - stream << " "; - stream << t1; - LogDispatcher::instance().dispatch(level, module, stream.str()); - } - } - - template - void operator()(LogLevel level, const T0 &t0, const T1 &t1, const T2 &t2) - { - if (LogDispatcher::instance().getLowestLogLevel() <= level) - { - std::stringstream stream; - stream << LogDispatcher::instance().getIndent(); - stream << t0 << " " << t1 << " " << t2; - LogDispatcher::instance().dispatch(level, module, stream.str()); - } - } - - template - void operator()(LogLevel level, const T0 &t0, const T1 &t1, const T2 &t2, - const T3 &t3) - { - if (LogDispatcher::instance().getLowestLogLevel() <= level) - { - std::stringstream stream; - stream << LogDispatcher::instance().getIndent(); - stream << t0 << " " << t1 << " " << t2 << " " << t3; - LogDispatcher::instance().dispatch(level, module, stream.str()); - } - } - - template - void operator()(LogLevel level, const T0 &t0, const T1 &t1, const T2 &t2, - const T3 &t3, const T4 &t4) - { - if (LogDispatcher::instance().getLowestLogLevel() <= level) - { - std::stringstream stream; - stream << LogDispatcher::instance().getIndent(); - stream << t0 << " " << t1 << " " << t2 << " " << t3 << " " << t4; - LogDispatcher::instance().dispatch(level, module, stream.str()); - } - } - - template - void operator()(LogLevel level, const T0 &t0, const T1 &t1, const T2 &t2, - const T3 &t3, const T4 &t4, const T5 &t5) - { - if (LogDispatcher::instance().getLowestLogLevel() <= level) - { - std::stringstream stream; - stream << LogDispatcher::instance().getIndent(); - stream << t0 << " " << t1 << " " << t2 << " " << t3 << " " << t4 - << " " << t5; - LogDispatcher::instance().dispatch(level, module, stream.str()); - } - } - - template - void operator()(LogLevel level, const T0 &t0, const T1 &t1, const T2 &t2, - const T3 &t3, const T4 &t4, const T5 &t5, const T6 &t6) - { - if (LogDispatcher::instance().getLowestLogLevel() <= level) - { - std::stringstream stream; - stream << LogDispatcher::instance().getIndent(); - stream << t0 << " " << t1 << " " << t2 << " " << t3 << " " << t4 - << " " << t5 << " " << t6; - LogDispatcher::instance().dispatch(level, module, stream.str()); - } - } -}; - -class LogBuffer -{ - std::stringstream stream; - LogLevel level; - const char *module; -public: - LogBuffer(LogLevel level, const char *module); - ~LogBuffer(); - - inline operator std::ostream &() - { - return stream; - } - - template inline LogBuffer& operator<<(T& data) - { - stream << data; - return *this; - } - - inline LogBuffer& operator<<(std::ostream& (*func)(std::ostream&)) - { - stream << func; - return *this; - } -}; - -} // namespace pxl - -#define PXL_LOG_ERROR if (pxl::LogDispatcher::instance().getLowestLogLevel() > pxl::LOG_LEVEL_ERROR) {} else pxl::LogBuffer(pxl::LOG_LEVEL_ERROR, PXL_LOG_MODULE_NAME) -#define PXL_LOG_WARNING if (pxl::LogDispatcher::instance().getLowestLogLevel() > pxl::LOG_LEVEL_WARNING) {} else pxl::LogBuffer(pxl::LOG_LEVEL_WARNING, PXL_LOG_MODULE_NAME) -#define PXL_LOG_INFO if (pxl::LogDispatcher::instance().getLowestLogLevel() > pxl::LOG_LEVEL_INFO) {} else pxl::LogBuffer(pxl::LOG_LEVEL_INFO, PXL_LOG_MODULE_NAME) -#define PXL_LOG_DEBUG if (pxl::LogDispatcher::instance().getLowestLogLevel() > pxl::LOG_LEVEL_DEBUG) {} else pxl::LogBuffer(pxl::LOG_LEVEL_DEBUG, PXL_LOG_MODULE_NAME) - -#endif // PXL_BASE_LOGGING_HH diff --git a/core/include/pxl/core/macros.hh b/core/include/pxl/core/macros.hh deleted file mode 100644 index cd2611452cec8b5fbcd38e8fec2547525f08029a..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/macros.hh +++ /dev/null @@ -1,58 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_BASE_MACROS_HH -#define PXL_BASE_MACROS_HH - -#include - -#include "pxl/core/config.hh" - -#undef PXL_LIKELY -#undef PXL_UNLIKELY -#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ > 4) -# define PXL_NORETURN __attribute__((__noreturn__)) -# define PXL_LIKELY(expr) (__builtin_expect((bool)(expr), true)) -# define PXL_UNLIKELY(expr) (__builtin_expect((bool)(expr), false)) -#else -# define PXL_NORETURN -# define PXL_LIKELY(expr) (expr) -# define PXL_UNLIKELY(expr) (expr) -#endif - -#ifdef offsetof -# define PXL_OFFSETOF(t, f) ((std::ptrdiff_t)offsetof(t, f)) -#else -# define PXL_OFFSETOF(t, f) ((std::ptrdiff_t)((char *) &((t*)0)->f)) -#endif - -#define PXL_BASE(t, f, v) (reinterpret_cast(reinterpret_cast(v) - PXL_OFFSETOF(t, f))) - -#ifdef _MSC_VER -#ifdef PXL_EXPORT -#define PXL_DLL_EXPORT __declspec( dllexport ) -#else -#define PXL_DLL_EXPORT __declspec( dllimport ) -#endif // PXL_EXPORT -#else -#define PXL_DLL_EXPORT -#endif // _MSC_VER -#ifndef PXL_VERSION -#define PXL_VERSION "trunk" -#endif - -#ifdef WIN32 -#define PXL_PATH_SEPERATOR "\\" -#else -#define PXL_PATH_SEPERATOR "/" -#endif - -#define _STR(x) #x -#define STR(x) _STR(x) - -#endif // PXL_BASE_MACROS_HH diff --git a/core/include/pxl/core/weak_ptr.hh b/core/include/pxl/core/weak_ptr.hh deleted file mode 100644 index 7c55945e0b48afb223b217590818acc291290215..0000000000000000000000000000000000000000 --- a/core/include/pxl/core/weak_ptr.hh +++ /dev/null @@ -1,143 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#ifndef PXL_BASE_WEAK_PTR_HH -#define PXL_BASE_WEAK_PTR_HH - -#include -#include - -#include "pxl/core/macros.hh" -#include "pxl/core/WkPtrBase.hh" - -namespace pxl -{ - -// ptl - -/** - This class template represents a weak pointer to PXL objects of \p objecttype that aggregate data of \p datatype. - */ -template class weak_ptr : public WkPtrBase -{ -public: - weak_ptr() : - WkPtrBase() - { - } - weak_ptr(objecttype* ptr) : - WkPtrBase() - { - WkPtrBase::connect(ptr); - } - weak_ptr(objecttype& object) : - WkPtrBase() - { - WkPtrBase::connect(&object); - } - weak_ptr(const weak_ptr& original) : - WkPtrBase() - { - WkPtrBase::connect((objecttype*) original._objectRef); - } - explicit weak_ptr(const weak_ptr* original) : - WkPtrBase() - { - WkPtrBase::connect((objecttype*) original->_objectRef); - } - - virtual ~weak_ptr() - { - WkPtrBase::connect(0); - } - - /// This virtual method creates a deep copy and returns a C++ pointer to the newly-created weak pointer instance. - virtual WkPtrBase* clone() const - { - return new weak_ptr(*this); - } - - /// This assignment operator causes the weak pointer to reference the object referenced by \p pptr. - inline void operator=(const weak_ptr& pptr) - { - connect(pptr._objectRef); - } - /// This assignment operator causes the weak pointer to reference the object. - inline void operator=(objecttype& object) - { - connect(&object); - } - /// This assignment operator causes the weak pointer to reference the object pointed to by \p objectptr. - inline void operator=(objecttype* objectptr) - { - connect(objectptr); - } - - // methods to grant object & data access - /// This method provides direct access to the referenced object. - inline objecttype& object() const - { - return *access(); - } - - /// This arrow operator de-references the weak pointer. - inline objecttype* operator->() const - { - return access(); - } - - /// This arrow operator de-references the weak pointer. - inline objecttype* ptr() const - { - return dynamic_cast(_objectRef); - } - - inline operator objecttype*() const - { - return dynamic_cast(_objectRef); - } - - /// This method attempts a dynamic cast on the referenced object - static weak_ptr* cast_dynamic(WkPtrBase* orig) - { - objecttype *object = dynamic_cast(orig->pointer()); - if (!object) - return 0; - // FIXME: This is crude but required: - if (PXL_UNLIKELY(reinterpret_cast(object) - != reinterpret_cast(orig->pointer()))) - throw std::runtime_error("WkPtrSpec::cast_dynamic(): Unsupported multiple inheritance configuration."); - return reinterpret_cast*>(orig); - } - - // safe access to object - inline objecttype* access() const - { - if (_objectRef) - return (objecttype*)_objectRef; - throw std::runtime_error("WkPtrSpec::access(): FATAL: The object you intend to access does not exist!"); - return 0; - } - -}; - -template objecttype& operator*(weak_ptr& wkPtr) -{ - return wkPtr.object(); -} - -template const objecttype& operator*( - const weak_ptr& wkPtr) -{ - return wkPtr.object(); -} - -} // namespace pxl - - -#endif // PXL_BASE_WEAK_PTR_HH diff --git a/core/pxl-core.pc.in b/core/pxl-core.pc.in index c058c05d19ad3d88dccb9229b2eb21252e466eb5..b480c6ee2dd3a542ae0e0008aa61c9167ff0d192 100644 --- a/core/pxl-core.pc.in +++ b/core/pxl-core.pc.in @@ -3,10 +3,8 @@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ - -Name: PXL -Description: Physics eXtension Library +Name: pxl-core +Description: Physics eXtension Library - core package Version: @PXL_VERSION@ -URL: http://vispa.physik.rwth-aachen.de Libs: -L${libdir} -lpxl-core -Cflags: -I${includedir}/ +Cflags: -I${includedir} diff --git a/core/src/Basic3Vector.cc b/core/src/Basic3Vector.cc deleted file mode 100644 index f74ff4202cd3977b5c0d584985b4782fbd3ba496..0000000000000000000000000000000000000000 --- a/core/src/Basic3Vector.cc +++ /dev/null @@ -1,298 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include - -#include "pxl/core/Basic3Vector.hh" -#include "pxl/core/RotationMatrix.hh" - -#ifndef EPSILON -#define EPSILON 1.0e-9 -#endif - -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif - -namespace pxl -{ - -bool operator==(const Basic3Vector& obj1, const Basic3Vector& obj2) -{ - return ((std::fabs(obj1.getX() - obj2.getX()) < DBL_EPSILON) && (std::fabs(obj1.getY() - obj2.getY()) < DBL_EPSILON) && (std::fabs(obj1.getZ() - obj2.getZ()) < DBL_EPSILON)); -} - -bool operator!=(const Basic3Vector& obj1, const Basic3Vector& obj2) -{ - return !(obj1==obj2); - //obj1.getX() != obj2.getX() || obj1.getY() != obj2.getY() || obj1.getZ() != obj2.getZ(); -} - -bool Basic3Vector::isUnitVector() const -{ - if ((std::abs(sqrt(_v[0] * _v[0] + _v[1] * _v[1] + _v[2] * _v[2]) - 1.0)) - <= DBL_EPSILON) - { - return true; - } - else - { - return false; - } -} - -void Basic3Vector::setRhoPhi(double perp, double phi) -{ - _v[0] = std::cos(phi) * perp; - _v[1] = std::sin(phi) * perp; -} - -void Basic3Vector::setRhoPhiZ(double perp, double phi, double z) -{ - setRhoPhi(perp, phi); - _v[2] = z; -} - -void Basic3Vector::setRThetaPhi(double r, double theta, double phi) -{ - setRhoPhiZ(std::sin(theta) * r, phi, std::cos(theta) * r); -} - -bool Basic3Vector::isNullPerp() const -{ - return _v[0] > -EPSILON && _v[0] < EPSILON && _v[1] > -EPSILON && _v[1] - < EPSILON; -} - -bool Basic3Vector::isNull() const -{ - return isNullPerp() && _v[2] > -EPSILON && _v[2] < EPSILON; -} - -double Basic3Vector::getPerp2() const -{ - return _v[0] * _v[0] + _v[1] * _v[1]; -} -double Basic3Vector::getPerp() const -{ - return std::sqrt(getPerp2()); -} - -double Basic3Vector::getPhi() const -{ - return isNullPerp() ? 0.0 : std::atan2(_v[1], _v[0]); -} -double Basic3Vector::getMag2() const -{ - return _v[0] * _v[0] + _v[1] * _v[1] + _v[2] * _v[2]; -} -double Basic3Vector::getMag() const -{ - return std::sqrt(getMag2()); -} - -double Basic3Vector::getCosTheta() const -{ - double mag = getMag(); - return mag < EPSILON ? 1.0 : _v[2] / mag; -} - -double Basic3Vector::getCos2Theta() const -{ - double mag2 = getMag2(); - return mag2 < EPSILON ? 1.0 : _v[2] * _v[2] / mag2; -} - -double Basic3Vector::getTheta() const -{ - return isNull() ? 0.0 : std::atan2(getPerp(), _v[2]); -} - - -double Basic3Vector::deltaRho(const Basic3Vector& fv) const -{ - double dDtheta = deltaTheta(fv); - double dDphi = deltaPhi(fv); - return std::sqrt(dDtheta * dDtheta + dDphi * dDphi); -} - -double Basic3Vector::deltaPhi(const Basic3Vector& fv) const -{ - double dDphi = getPhi() - fv.getPhi(); - while (dDphi > M_PI) - dDphi -= 2 * M_PI; - while (dDphi < -M_PI) - dDphi += 2 * M_PI; - return dDphi; -} - -double Basic3Vector::deltaTheta(const Basic3Vector& fv) const -{ - double dDtheta = getTheta() - fv.getTheta(); - while (dDtheta > M_PI) - dDtheta -= 2 * M_PI; - while (dDtheta < -M_PI) - dDtheta += 2 * M_PI; - return dDtheta; -} - -Basic3Vector operator*(double scalar, const Basic3Vector& vec) -{ - Basic3Vector out; - out.setX(vec.getX() * scalar); - out.setY(vec.getY() * scalar); - out.setZ(vec.getZ() * scalar); - return out; -} - -Basic3Vector operator*(const Basic3Vector& vec, double scalar) -{ - return operator*(scalar, vec); -} - -Basic3Vector Basic3Vector::getETheta() const -{ - Basic3Vector out; - out.setX(cos(this->getTheta()) * cos(this->getPhi())); - out.setY(cos(this->getTheta()) * sin(this->getPhi())); - out.setZ(-1 * sin(this->getTheta())); - return out; -} - -Basic3Vector Basic3Vector::getEPhi() const -{ - Basic3Vector out; - out.setX(-1 * sin(this->getPhi())); - out.setY(cos(this->getPhi())); - out.setZ(0); - return out; -} - -const Basic3Vector& Basic3Vector::operator=(const Basic3Vector& vec) -{ - _v[0] = vec._v[0]; - _v[1] = vec._v[1]; - _v[2] = vec._v[2]; - return *this; -} - -const Basic3Vector& Basic3Vector::operator+=(const Basic3Vector& vec) -{ - _v[0] += vec._v[0]; - _v[1] += vec._v[1]; - _v[2] += vec._v[2]; - return *this; -} - -const Basic3Vector& Basic3Vector::operator-=(const Basic3Vector& vec) -{ - _v[0] -= vec._v[0]; - _v[1] -= vec._v[1]; - _v[2] -= vec._v[2]; - return *this; -} - -const Basic3Vector& Basic3Vector::operator*=(double scalar) -{ - _v[0] *= scalar; - _v[1] *= scalar; - _v[2] *= scalar; - return *this; -} - -const Basic3Vector& Basic3Vector::operator/=(double scalar) -{ - _v[0] /= scalar; - _v[1] /= scalar; - _v[2] /= scalar; - return *this; -} - -Basic3Vector Basic3Vector::operator/(double scalar) const -{ - Basic3Vector out; - out.setX(_v[0] / scalar); - out.setY(_v[1] / scalar); - out.setZ(_v[2] / scalar); - return out; -} - -// Scalar product -double Basic3Vector::operator*(const Basic3Vector& vec) const -{ - return getX() * vec.getX() + getY() * vec.getY() + getZ() * vec.getZ(); -} - -Basic3Vector Basic3Vector::operator+(const Basic3Vector& vec) -{ - Basic3Vector out = *this; - out += vec; - return out; -} - -Basic3Vector Basic3Vector::operator-(const Basic3Vector& vec) -{ - Basic3Vector out = *this; - out -= vec; - return out; -} - -void Basic3Vector::normalize() -{ - *this/=this->getMag(); -} - - -double Basic3Vector::norm(uint32_t norm) const -{ - if (norm == 0xffffffff) - return 3.; - else if (norm == 0) - throw std::runtime_error("norm of 0 not defined"); - - double n = 0; - if (norm == 1) - { - for (size_t i = 0; i < 3; i++) - n += fabs(_v[i]); - } - else if (norm == 2) - { - for (size_t i = 0; i < 3; i++) - n += (_v[i] * _v[i]); - n = sqrt(n); - } - else - { - for (size_t i = 0; i < 3; i++) - n += pow(fabs(_v[i]), (double)norm); - n = pow (n, 1.0 / double(norm)); - } - - return n; -} - - -double Basic3Vector::getAngleTo(const Basic3Vector& vec) const -{ - - double cosdistance = (*this)*vec / this->getMag() / vec.getMag(); - // In some directions cosdistance is > 1 on some compilers - // This ensures that the correct result is returned - return (cosdistance >= 1.) ? 0 : ((cosdistance <= -1.) ? M_PI :acos(cosdistance)) ; -} - - -void Basic3Vector::rotate(const Basic3Vector& axis, double angle) -{ - RotationMatrix R(axis/axis.getMag(), angle); - *this= R*(*this); -} - -} // namespace pxl -#undef EPSILON diff --git a/core/src/BasicContainer.cc b/core/src/BasicContainer.cc deleted file mode 100644 index 45d68aa0db8f71a215b08a26b1ffb09273b047b1..0000000000000000000000000000000000000000 --- a/core/src/BasicContainer.cc +++ /dev/null @@ -1,207 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include "pxl/core/BasicContainer.hh" - -namespace pxl -{ - -void BasicContainer::init(const BasicContainer& original) -{ - std::map copyHistory; - - for (const_iterator iter = original._container.begin(); - iter != original._container.end(); ++iter) - { - - Serializable* pOld = *iter; - Serializable* pNew = pOld->clone(); - - insertObject(pNew); - copyHistory.insert(std::pair(pOld->getId(), pNew)); - } - - // redirect index: - for (map_t::const_iterator iter = original._index.begin(); - iter != original._index.end(); ++iter) - { - - Serializable* pOld = iter->second; - - Serializable* pNew = 0; - std::map::const_iterator found = copyHistory.find( - pOld->getId()); - if (found != copyHistory.end()) - pNew = found->second; - - if (pNew) - _index.insert(map_t::const_iterator::value_type(iter->first, pNew)); - } -} - -void BasicContainer::clearContainer() -{ - for (iterator iter = _container.begin(); iter != _container.end(); iter++) - { - delete (*iter); - } - _container.clear(); - _index.clear(); - _uuidSearchMap.clear(); -} - -void BasicContainer::insertObject(Serializable* value) -{ - _container.push_back(value); - _uuidSearchMap.insert(std::pair(value->getId(), value)); -} - -void BasicContainer::remove(Serializable* value) -{ - for (map_t::const_iterator iter = _index.begin(); iter != _index.end(); - iter++) - { - if (value == iter->second) - _index.erase(iter->first); - } - - _uuidSearchMap.erase(value->getId()); - - for (iterator iter = _container.begin(); iter != _container.end(); iter++) - { - if (value == (*iter)) - { - delete *iter; - _container.erase(iter); - return; - } - } - throw std::runtime_error("Trying to remove non-existing object from container"); -} - -size_t BasicContainer::removeObjectsOfType(const Id &typeId) -{ - size_t n = 0; - - BasicContainer::iterator iter = _container.begin(); - while (iter!=_container.end()) - { - if ((*iter)->getTypeId() == typeId) - { - n++; - _uuidSearchMap.erase((*iter)->getId()); - _index.erase((*iter)->getId().toString()); - delete *iter; - iter = _container.erase(iter); - } - else - { - ++iter; - } - } - return n; -} - -void BasicContainer::take(Serializable* value) -{ - for (map_t::const_iterator iter = _index.begin(); iter != _index.end(); - iter++) - { - if (value == iter->second) - _index.erase(iter->first); - } - - _uuidSearchMap.erase(value->getId()); - - for (iterator iter = _container.begin(); iter != _container.end(); iter++) - { - if (value == (*iter)) - { - _container.erase(iter); - break; - } - } -} - -bool BasicContainer::has(const Serializable* value) const -{ - return _uuidSearchMap.find(value->getId()) != _uuidSearchMap.end(); -} - -void BasicContainer::serialize(const OutputStream &out) const -{ - Serializable::serialize(out); - //write length of vector - out.writeUnsignedInt(size()); - //serialize container objects - for (const_iterator iter = begin(); iter != end(); ++iter) - { - (*iter)->serialize(out); - } - //serialize Container Index - out.writeUnsignedInt(_index.size()); - for (map_t::const_iterator iter = _index.begin(); iter != _index.end(); - ++iter) - { - out.writeString(iter->first); - (iter->second->getId()).serialize(out); - - } - //serialize user record - UserRecordHelper::serialize(out); -} - -void BasicContainer::deserialize(const InputStream &in) -{ - Serializable::deserialize(in); -// std::map objIdMap; - unsigned int size = 0; - in.readUnsignedInt(size); - //deserialize content - for (size_t i = 0; i < size; ++i) - { - Id typeId(in); - Serializable* object = - dynamic_cast(ObjectFactory::instance().create( - typeId)); - if (object) - { - object->deserialize(in); - insertObject(object); - //fill temporary map to store id's -// objIdMap.insert(std::pair(object->getId(), object)); - } - else - { - std::string errorMessage = "BasicContainer::deserialize(const InputStream &in) : unknown object (TypeID: " + typeId.toString() + ") in container!"; - throw std::runtime_error(errorMessage); - } - } - - //read index - in.readUnsignedInt(size); - for (size_t i = 0; i < size; ++i) - { - std::string name; - in.readString(name); - Id id(in); - for (size_t j = 0; j < _container.size(); ++j) - { - if (id == _container[j]->getId()) - _index.insert( - std::pair(name, - _container[j])); - } -// _index.insert(std::pair(name, objIdMap.find(id)->second)); - } - //deserialize user record - UserRecordHelper::deserialize(in); - -} - -} // namespace pxl diff --git a/core/src/BasicMatrix.cc b/core/src/BasicMatrix.cc deleted file mode 100644 index c132f1cd203d3944162d72af529a20ce4c2020f7..0000000000000000000000000000000000000000 --- a/core/src/BasicMatrix.cc +++ /dev/null @@ -1,378 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include "pxl/core/BasicMatrix.hh" -#include -namespace pxl -{ - -void BasicMatrix::serialize(const OutputStream &out) const -{ - Serializable::serialize(out); - out.writeUnsignedInt(_size1); - out.writeUnsignedInt(_size1); - out.writeUnsignedInt(_storageType); - for (size_t i=0; i<_size1*_size2;i++) - { - out.writeDouble(_data[i]); - } - out.writeString(_name); -} - -void BasicMatrix::deserialize(const InputStream &in) -{ - Serializable::deserialize(in); - unsigned int dummy; - in.readUnsignedInt(dummy); - _size1 = dummy; - in.readUnsignedInt(dummy); - _size2 = dummy; - in.readUnsignedInt(dummy); - _storageType = (StorageOrder)dummy; - if (_data && (!_alienarray)) - delete[] _data; - _data = new double[_size1*_size2]; - _alienarray = false; - - for (size_t i=0; i<_size1*_size2;i++) - { - in.readDouble(_data[i]); - } - in.readString(_name); -} - -void BasicMatrix::use(size_t size1, size_t size2, double *data) -{ - if ((_data) && (!_alienarray)) - delete[] _data; - _alienarray = true; - _data = data; - _size1 = size1; - _size2 = size2; -} - - -bool BasicMatrix::isRowBasedStorage() const -{ - switch(_storageType) - { - case ROWMAJOR: - return true; - break; - case COLUMNMAJOR: - return false; - break; - default: - throw std::runtime_error("Something went very wrong! Matrix neither in Row nor Column Storage!"); - } -} - - -bool BasicMatrix::isColumnBasedStorage() const -{ - switch(_storageType) - { - case ROWMAJOR: - return false; - break; - case COLUMNMAJOR: - return true; - break; - default: - throw std::runtime_error("Something went very wrong! Matrix neither in Row nor Column Storage!"); - } -} - - -void BasicMatrix::resize(size_t i, size_t j) -{ - if (_data) - delete _data; - _data = new double[i*j]; - _size1 = i; - _size2 = j; -} - - -void BasicMatrix::reshape(size_t i, size_t j) -{ - if ((i*j)!=(_size1*_size2)) - { - throw std::runtime_error("Number of elements doens't match!"); - } - _size1 = i; - _size2 = j; -} - - -const BasicMatrix& BasicMatrix::operator=(const BasicMatrix& M) -{ - _size1 = M.getSize1(); - _size2 = M.getSize2(); - _data = new double[_size1 * _size2]; - if (M.isColumnBasedStorage()) - { - this->setColumnBasedStorage(); - } - else - { - this->setRowBasedStorage(); - } - //const double* vecdata= vec.getConstArray(); - //memcpy(_data,vecdata,_size1); - for (size_t i=0; i<_size1*_size2;i++) - { - _data[i] = M.getConstArray()[i]; - } - return *this; -} - - -const BasicMatrix& BasicMatrix::operator+=(const BasicMatrix& M) -{ - if ((M.getSize1() != _size1) || (M.getSize2() != _size2)) - { - throw std::runtime_error("Size Mismatch! Only Matrices of same size can be added."); - } - if (this->isColumnBasedStorage() == M.isColumnBasedStorage()) - { - for (size_t i=0; i<_size1;i++) - { - for (size_t j=0; j<_size2;j++) - { - (_data)[i*_size2+j] += M.getElement(i,j); - } - } - } - else - { // different storage scheme! - for (size_t i=0; i<_size1;i++) - { - for (size_t j=0; j<_size2;j++) - { - (_data)[i*_size2 + j] += M.getElement(j,i); - } - } - } - return *this; -} - - -const BasicMatrix& BasicMatrix::operator-=(const BasicMatrix& M) -{ - if ((M.getSize1() != _size1) || (M.getSize2() != _size2)) - { - throw std::runtime_error("Size Mismatch! Only Matrices of same size can be added."); - } - if (this->isColumnBasedStorage() == M.isColumnBasedStorage()) - { - for (size_t i=0; i<_size1;i++) - { - for (size_t j=0; j<_size2;j++) - { - (_data)[i*_size2+j] -= M.getElement(i,j); - } - } - } - else - { // different storage scheme! - for (size_t i=0; i<_size1;i++) - { - for (size_t j=0; j<_size2;j++) - { - (_data)[i*_size2+j] -= M.getElement(j,i); - } - } - } - return *this; -} - - -BasicMatrix BasicMatrix::operator+(const BasicMatrix& M) -{ - BasicMatrix out = *this; - out += M; - return out; -} - - -BasicMatrix BasicMatrix::operator-(const BasicMatrix& M ) -{ - BasicMatrix out = *this; - out -= M; - return out; -} - - -const BasicMatrix& BasicMatrix::operator*=(double skalar) -{ - for (size_t i=0; i<_size1*_size2;i++) - { - (_data)[i] *= skalar; - } - return *this; -} - - -const BasicMatrix& BasicMatrix::operator/=(double skalar) -{ - for (size_t i=0; i<_size1*_size2;i++) - { - (_data)[i] /= skalar; - } - return *this; -} - - -const BasicMatrix BasicMatrix::operator/(double skalar) const -{ - BasicMatrix out = *this; - out /= skalar; - return out; -} - -double& BasicMatrix::operator()(size_t i, size_t j) -{ - if ((i >= _size1) || (j >= _size2)) - throw std::runtime_error("Index out of range"); - else - { - return _data[i*_size2 + j]; - } -} - -std::ostream& BasicMatrix::print(int level, std::ostream& os, int pan) const -{ - os.precision(2); - os << std::scientific; - if (this->isRowBasedStorage()) - { - for (size_t i=0; i<_size1; i++) - { - for (size_t j=0; j<_size2; j++) - { - os << this->getElement(i,j) << " "; - } - os << std::endl; - } - } - else - { // Column Based - for (size_t j=0; j<_size2; j++) - { - for (size_t i=0; i<_size1; i++) - { - os << this->getElement(i,j) << " "; - } - os << std::endl; - } - } - return os; -} - -BasicMatrix operator*(const BasicMatrix &M, double skalar) -{ - BasicMatrix R(M); - R*=skalar; - return R; -} - -BasicMatrix operator*(double skalar, const BasicMatrix &M) -{ - BasicMatrix R(M); - R*=skalar; - return R; -} - -bool operator==(const BasicMatrix& obj1, const BasicMatrix& obj2) -{ - if ((obj1.getSize1() != obj2.getSize1()) || (obj1.getSize2() != obj2.getSize2())) - { - return false; - } - else - { - bool result = true; - size_t iter = 0; - while (result && (iter < obj1.getSize1()*obj1.getSize2())) - { - result = (obj1.getConstArray()[iter] == obj2.getConstArray()[iter]); - iter++; - } - return result; - } -} - -bool operator!=(const BasicMatrix& obj1, const BasicMatrix& obj2) -{ - return !(obj1==obj2); -} - -BasicNVector operator*(const BasicMatrix& M, const BasicNVector& vec) -{ - - if (vec.getSize() != M.getNumberOfColumns()) - { - throw std::runtime_error("Size Mismatch in matrix-vector multiplication"); - } - - BasicNVector out(M.getNumberOfRows()); - for (size_t i=0;igetElement(i) << std::endl; - } - return os; -} - -double BasicNVector::norm(uint32_t norm) { - if (norm == 0xffffffff) - return (double)_size1; - else if (norm == 0) - throw std::runtime_error("norm of 0 not defined"); - - double n = 0; - if (norm == 1) - { - for (size_t i = 0; i < _size1; i++) - n += fabs(_data[i]); - } - else if (norm == 2) - { - for (size_t i = 0; i < _size1; i++) - n += (_data[i] * _data[i]); - n = sqrt(n); - } - else - { - for (size_t i = 0; i < _size1; i++) - n += pow(fabs(_data[i]), (double)norm); - n = pow (n, 1.0 / double(norm)); - } - return n; -} - -void BasicNVector::setSize(size_t size) -{ - if (_alienarray) - { - throw std::runtime_error("BasicNVector:: Trying to resize an unowned array!"); - } - if (!_data) - { - _data = new double[size]; - std::fill_n(_data, size, 0 ); - } - else if (size > _size1) - { - // allocate new arra, copy data and free memory - double *tmp = _data; - _data = new double[size]; - std::fill_n(_data, size, 0 ); - memcpy(_data,tmp, _size1*sizeof(double)); - //std::fill_n(_data+_size1*sizeof(double), size-_size1, 0 ); - delete[] tmp; - } - _size1 = size; -} - - - - -} // namespace pxl diff --git a/core/src/ChunkReader.cc b/core/src/ChunkReader.cc deleted file mode 100644 index 652948034018087302aea1d9694355339baaf8b7..0000000000000000000000000000000000000000 --- a/core/src/ChunkReader.cc +++ /dev/null @@ -1,317 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include -#include -#include - -#include "pxl/core/ChunkReader.hh" - -namespace pxl -{ - -bool ChunkReader::skip() -{ - if (_stream.peek()==EOF) - return false; - - //skip event header - if (_status == preHeader) - { - ++_sectionCount; - _stream.ignore(1); - // read info size - int32_t infoSize = 0; - _stream.read((char *)&infoSize, 4); - _stream.ignore(infoSize); - } - - //skip all blocks - while (nextBlockId()=='B' && !_stream.isEof() ) - { - // read info size - int32_t infoSize = 0; - _stream.read((char *)&infoSize, 4); - _stream.ignore(infoSize); - _stream.ignore(1); - - // read chunk size - int32_t chunkSize = 0; - _stream.read((char *)&chunkSize, 4); - _stream.ignore(chunkSize); - } - - _stream.ignore(4); - _status = preHeader; - - return true; -} - -bool ChunkReader::previous() -{ - if (_seekMode == nonSeekable) - return false; - - if (_status != preHeader) - { - endEvent(); - previous(); - } - std::streampos pos = _stream.tell(); - - int32_t eventSize; - pos -= 4; - if (pos<0) - return false; - _stream.seek(pos); - _stream.read((char*)&eventSize, 4); - - pos -= eventSize; - if (pos<0) - return false; - _stream.seek(pos); - _status = preHeader; - - --_sectionCount; - - return true; -} - -/// Reads next block from file to stream. If mode is -1, the information condition string is evaluated, -/// i.e. the block is read only if the string equals the one in the input. -bool ChunkReader::readBlock(skipMode skip, infoMode checkInfo, - const std::string& infoCondition) -{ - //if event header not read, return - if (_status == preHeader) - return false; - - //return false if end of file - if (_stream.peek()==EOF) - return false; - - //check if beginning of block - char id = nextBlockId(); - - if (id!='B') - { - if (id=='e') //end of event - { - _status = preHeader; - _stream.ignore(4); - return false; - } - else - { - std::stringstream ss; - ss << "pxl::ChunkReader::readBlock(): Unknown char identifier: " << id; - throw std::runtime_error(ss.str()); - } - } - - int32_t infoSize = 0; - _stream.read((char *)&infoSize, 4); - - bool readStream = true; - - if (checkInfo == evaluate) - { - char* infoBuffer = new char[infoSize+1]; - infoBuffer[infoSize]=0; - _stream.read(infoBuffer, infoSize); - std::string info; - info.assign(infoBuffer); - //the mode is set to -2 if the info condition is not fulfilled. - //rest of block must be skipped and false be returned. - if (infoCondition!=info) - readStream = false; - delete infoBuffer; - } - else - _stream.ignore(infoSize); - - char compressionMode; - _stream.read(&compressionMode, 1); - - // read chunk size - uint32_t chunkSize = 0; - _stream.read((char *)&chunkSize, 4); - - if (_stream.isBad() || _stream.isEof()) - return false; - - if (readStream == false) - { - _stream.ignore(chunkSize); - if (skip == on) - return readBlock(skip, checkInfo, infoCondition); - else - return false; - } - else - { - // read chunk into buffer - if (compressionMode==' ') - { - //_buffer.destroy(); - _buffer.clear(); - _buffer.buffer.resize(chunkSize); - _stream.read(&_buffer.buffer[0], chunkSize); - if (_stream.isBad() || _stream.isEof() ) - return false; - } - else if (compressionMode=='Z') - { - //_buffer.destroy(); - _buffer.clear(); - unzipEventData(chunkSize); - } - else - { - throw std::runtime_error("pxl::ChunkReader::readBlock(): Invalid compression mode."); - } - } - return true; -} - -bool ChunkReader::readHeader(readMode mode, skipMode doSkip, - infoMode checkInfo, const std::string& infoCondition) -{ - // if position is not before the header, end the previous event - endEvent(); - - ++_sectionCount; - - if (_stream.peek()==EOF || _stream.isBad() ) - return false; - - _status = preBlock; - // Check for nextId? char nextId = - nextBlockId(); - - // get size of info string - int32_t infoSize = 0; - _stream.read((char *)&infoSize, 4); - - //if info string is to be checked - if (checkInfo==evaluate) - { - char* infoBuffer = new char[infoSize+1]; - infoBuffer[infoSize]=0; - _stream.read(infoBuffer, infoSize); - std::string info; - info.assign(infoBuffer); - delete infoBuffer; - if (infoCondition!=info) - { - if (doSkip == on) - return readHeader(mode, doSkip, checkInfo, infoCondition); - else - return false; - } - } - else - _stream.ignore(infoSize); - - if (_stream.isEof() || _stream.isBad() ) - return false; - - return true; -} - -int ChunkReader::unzipEventData(uint32_t nBytes) -{ - size_t buffer_size_step = nBytes * 3; - - uint32_t ret, length = 0; - z_stream strm; - strm.zalloc = Z_NULL; - strm.zfree = Z_NULL; - strm.opaque = Z_NULL; - strm.avail_in = 0; - strm.next_in = Z_NULL; - - ret = inflateInit(&strm); - if (ret != Z_OK) - return 0; - - // decompress until deflate stream ends or end of file - do - { - int size = nBytes; - if (size > iotl__iStreamer__lengthUnzipBuffer) - { - size = iotl__iStreamer__lengthUnzipBuffer; - } - - strm.avail_in = _stream.read((char*)_inputBuffer, size); - if (_stream.isBad()) - { - inflateEnd(&strm); - return 0; - } - - nBytes -= strm.avail_in; - - if (_stream.isEof()) - nBytes = 0; - - if (strm.avail_in == 0) - break; - - strm.next_in = _inputBuffer; - - // run inflate() on input until output buffer not full - do { - if ((_buffer.buffer.size() - length) < buffer_size_step) - _buffer.buffer.resize(_buffer.buffer.size() + buffer_size_step); - - strm.avail_out = _buffer.buffer.size() - length; - strm.next_out = (Bytef *)(&_buffer.buffer[length]); - - ret = inflate(&strm, Z_NO_FLUSH); - switch (ret) - { - case Z_STREAM_ERROR: - throw std::runtime_error("pxl::ChunkReader::unzipEventData(): Internal inflate stream error."); - case Z_NEED_DICT: - ret = Z_DATA_ERROR; // fall through - case Z_DATA_ERROR: - case Z_MEM_ERROR: - inflateEnd(&strm); - return 0; - default: - break; - } - - size_t have = _buffer.buffer.size() - length - strm.avail_out; - length += have; - } while (strm.avail_out == 0); - } while (nBytes > 0); // done when inflate() says it's done - - inflateEnd(&strm); - _buffer.buffer.resize(length); - - return length; -} - - -/// Returns the size of the associated file. -size_t ChunkReader::getSize() const -{ - std::streampos pos = _stream.tell(); - _stream.seek (0, SeekEnd); - - size_t length = _stream.tell(); - _stream.seek (pos); - - return length; -} - -} - diff --git a/core/src/ChunkWriter.cc b/core/src/ChunkWriter.cc deleted file mode 100644 index e1af50359d0bbcefe5da5df650722f932d8d75f9..0000000000000000000000000000000000000000 --- a/core/src/ChunkWriter.cc +++ /dev/null @@ -1,142 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include -#include - -#include "pxl/core/ChunkWriter.hh" - -namespace pxl -{ - -bool ChunkWriter::newFileSection(const std::string& info, char cSectionMarker) -{ - _stream.write(&cSectionMarker, 1); - if (_stream.isBad()) - { - throw std::runtime_error("Cannot write to file"); - } - _nBytes+=1; - - // info block: - const char* cInfo = info.c_str(); - int32_t lengthInfo = info.length(); - _stream.write((char *) &lengthInfo, 4); - _nBytes+=4; - _stream.write(cInfo, lengthInfo); - _nBytes+=lengthInfo; - if (_stream.isBad()) - { - throw std::runtime_error("Cannot write to file"); - } - return true; -} - -bool ChunkWriter::endFileSection() -{ - // end event marker: - writeFlag('e'); - _stream.write((char* ) &_nBytes, 4); - _nBytes=0; - if (_stream.isBad()) - { - throw std::runtime_error("Cannot write to file"); - } - return true; -} - -/// Write char flag. -bool ChunkWriter::writeFlag(char cEvtMarker) -{ - _stream.write(&cEvtMarker, 1); - _nBytes+=1; - if (_stream.isBad()) - { - throw std::runtime_error("Cannot write to file"); - } - return true; -} - - -bool ChunkWriter::write(std::string info) -{ - // write out block information - const char* cInfo = info.c_str(); - int32_t lengthInfo = info.length(); - _stream.write((char *) &lengthInfo, 4); - _nBytes+=4; - _stream.write(cInfo, lengthInfo); - _nBytes+=lengthInfo; - - // write out compression mode - char compressed = 'Z'; - if (_compressionMode == ' ') compressed = ' '; - _stream.write((char *) &compressed, 1); - _nBytes+=1; - - // zip block: - const char* cBuffer = &_buffer.buffer[0]; - int32_t lengthBuffer = _buffer.buffer.size(); - - const char* cZip = cBuffer; - int32_t lengthZip = lengthBuffer; - - char* cZipSpace = 0; - unsigned long lengthZipSpace = 0; - - if (_compressionMode == ' ') - { - // no compression requires no action... - } - else if (_compressionMode >= '0' && _compressionMode <= '9') - { - // data compression a la Gero, i.e. compression level = 6: - lengthZipSpace = long(double(lengthBuffer) * 1.05 + 16); - cZipSpace = new char[lengthZipSpace]; - - int status = compress2((Bytef*)cZipSpace, (uLongf*)&lengthZipSpace, - (const Bytef*)cBuffer, lengthBuffer, _compressionMode - '0'); - switch (status) - { - case Z_MEM_ERROR: - throw std::runtime_error("pxl::ChunkWriter::write(): zlib: not enough memory"); - break; - case Z_BUF_ERROR: - throw std::runtime_error("pxl::ChunkWriter::write(): zlib: buffer too small"); - break; - case Z_STREAM_ERROR: - throw std::runtime_error("pxl::ChunkWriter::write(): zlib: level parameter invalid"); - break; - default: - break; - } - - cZip = cZipSpace; - lengthZip = lengthZipSpace; - } - else - throw std::runtime_error("pxl::FileChunkWriter::write(): Invalid compression mode."); - - _stream.write((char *) &lengthZip, 4); - _nBytes+=4; - _stream.write(cZip, lengthZip); - _nBytes+=lengthZip; - - if (cZipSpace) - delete[] cZipSpace; - - _buffer.clear(); - - if (_stream.isBad()) - { - throw std::runtime_error("Cannot write to file"); - } - return true; -} - -} //namespace pxl diff --git a/core/src/ConfigLoader.cc b/core/src/ConfigLoader.cc index 0078003e7b17de81b938ffc5a83140d2258e60d8..700c5a1bbe9137c9b40943b26edbedee6f14db05 100644 --- a/core/src/ConfigLoader.cc +++ b/core/src/ConfigLoader.cc @@ -1,16 +1,16 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- #include "pxl/core/Tokenizer.hh" -#include "pxl/core/logging.hh" +#include "pxl/core/Logging.hh" -#include "pxl/core/Configuration.hh" #include "pxl/core/ConfigLoader.hh" +#include "pxl/core/Configuration.hh" #include @@ -27,81 +27,80 @@ namespace pxl { /// Add all items from a CSimpleIniA object to the pcl Config instance -void fillConfigFromSimpleIni(const CSimpleIniA &iniFile) +void fillConfigFromSimpleIni(const CSimpleIniA& iniFile) { - Configuration pxlConfig = Configuration::instance(); - - Tokenizer tok; - tok.setCharType(',', Tokenizer::DELIM); - CSimpleIniA::TNamesDepend values; - iniFile.GetAllValues("paths", "pythonModulePaths", values); - for (CSimpleIniA::TNamesDepend::iterator iter = values.begin(); iter!=values.end(); ++iter) - { - tok.setText((*iter).pItem); - while (tok.hasNext()) - { - std::string s = tok.next(); - pxlConfig.addItem("paths","pythonModulePath",s ); - } - } - - iniFile.GetAllValues("paths", "analysisSearchPaths", values); - for (CSimpleIniA::TNamesDepend::iterator iter = values.begin(); iter!=values.end(); ++iter) - { - tok.setText((*iter).pItem); - while (tok.hasNext()) - { - std::string s = tok.next(); - pxlConfig.addItem("paths","analysisSearchPaths",s ); - } - } - - iniFile.GetAllValues("paths", "pluginDirectory", values); - for (CSimpleIniA::TNamesDepend::iterator iter = values.begin(); iter!=values.end(); ++iter) - { - tok.setText((*iter).pItem); - while (tok.hasNext()) - { - std::string s = tok.next(); - pxlConfig.addItem("paths", "pluginDirectory", s); - } - } + Configuration pxlConfig = Configuration::instance(); + + Tokenizer tok; + tok.setCharType(',', Tokenizer::DELIM); + CSimpleIniA::TNamesDepend values; + iniFile.GetAllValues("paths", "pythonModulePaths", values); + for (CSimpleIniA::TNamesDepend::iterator iter = values.begin(); iter != values.end(); ++iter) + { + tok.setText((*iter).pItem); + while (tok.hasNext()) + { + std::string s = tok.next(); + pxlConfig.addItem("paths", "pythonModulePath", s); + } + } + + iniFile.GetAllValues("paths", "analysisSearchPaths", values); + for (CSimpleIniA::TNamesDepend::iterator iter = values.begin(); iter != values.end(); ++iter) + { + tok.setText((*iter).pItem); + while (tok.hasNext()) + { + std::string s = tok.next(); + pxlConfig.addItem("paths", "analysisSearchPaths", s); + } + } + + iniFile.GetAllValues("paths", "pluginDirectory", values); + for (CSimpleIniA::TNamesDepend::iterator iter = values.begin(); iter != values.end(); ++iter) + { + tok.setText((*iter).pItem); + while (tok.hasNext()) + { + std::string s = tok.next(); + pxlConfig.addItem("paths", "pluginDirectory", s); + } + } } -void fillConfigFromSimpleIni(const std::string &iniFile) +void fillConfigFromSimpleIni(const std::string& iniFile) { - } /// loads configurations from /etc/pxlrc and HOME/.pxlrc void loadDefaultConfigurations() { - CSimpleIniA iniFile(false, true, false ); - SI_Error rc; - #ifdef PXL_SYSTEM_RC - rc = iniFile.LoadFile(PXL_SYSTEM_RC); - if (rc < 0) - { - PXL_LOG_INFO << "Error reading: " << PXL_SYSTEM_RC; - } - #endif - - const char *home = getenv(HOME_ENV); - if (!home) - { - PXL_LOG_WARNING << "home path not set: " << HOME_ENV; - return; - } - - std::string rcFile = home; - rcFile += "/.pxlrc"; - rc = iniFile.LoadFile(rcFile.c_str()); - if (rc < 0) - { - PXL_LOG_INFO << "Error reading: " << rcFile; - } - - fillConfigFromSimpleIni(iniFile); + CSimpleIniA iniFile(false, true, false); + SI_Error rc; +#ifdef PXL_SYSTEM_RC + rc = iniFile.LoadFile(PXL_SYSTEM_RC); + if (rc < 0) + { + PXL_LOG_INFO << "Error reading: " << PXL_SYSTEM_RC; + } +#endif + + const char* home = getenv(HOME_ENV); + if (!home) + { + PXL_LOG_WARNING << "home path not set: " << HOME_ENV; + return; + } + + std::string rcFile = home; + rcFile += "/.pxlrc"; + rc = iniFile.LoadFile(rcFile.c_str()); + if (rc < 0) + { + PXL_LOG_INFO << "Error reading: " << rcFile; + } + + fillConfigFromSimpleIni(iniFile); } } // namespace diff --git a/core/src/Configuration.cc b/core/src/Configuration.cc index ad8ca040847ddee64697d81c5accfd9d426da330..d10162eb87b74f679b8b065f9fbf4461e9babb09 100644 --- a/core/src/Configuration.cc +++ b/core/src/Configuration.cc @@ -1,48 +1,42 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- - #include "pxl/core/Configuration.hh" - namespace pxl { - -Configuration &Configuration::instance() +Configuration& Configuration::instance() { - static Configuration configuration; - return configuration; + static Configuration configuration; + return configuration; } - -void Configuration::addItem(const std::string §ion, const std::string &key, const Variant &item) +void Configuration::addItem(const std::string& section, const std::string& key, const Variant& item) { - mapIterator iter = _data.find(section); - if (iter == _data.end()) - { - Configuration::multimapType newSection; - iter = _data.insert(iter, std::pair(section,newSection) ); - } - iter->second.insert(std::pair(key, item)); + mapIterator iter = _data.find(section); + if (iter == _data.end()) + { + Configuration::multimapType newSection; + iter = _data.insert( + iter, std::pair(section, newSection)); + } + iter->second.insert(std::pair(key, item)); } - -const Variant &Configuration::getItem(const std::string §ion, const std::string &key) +const Variant& Configuration::getItem(const std::string& section, const std::string& key) { - return (*_data[section].find(key)).second; + return (*_data[section].find(key)).second; } - -Configuration::multimapType& Configuration::getSection(const std::string §ion) +Configuration::multimapType& Configuration::getSection(const std::string& section) { - return _data[section]; + return _data[section]; } - } // namespace diff --git a/core/src/Core.cc b/core/src/Core.cc index 57aeb4490695a051ff631ab10a57552b39d5cd73..773db8dc6efd8cddae4616cf57d5f82860fce399 100644 --- a/core/src/Core.cc +++ b/core/src/Core.cc @@ -1,86 +1,46 @@ -/* - * init.cc - * - * Created on: 14.07.2010 - * Author: gmueller - */ +//------------------------------------------- +// Project: Physics eXtension Library (PXL) - +// http://vispa.physik.rwth-aachen.de/ - +// Copyright (C) 2006-2019 Martin Erdmann - +// RWTH Aachen, Germany - +// Licensed under a LGPL-2 or later license - +//------------------------------------------- #include "pxl/core.hh" -#include "pxl/core/FileFactory.hh" -#include "LocalFileImpl.hh" -#include "StdFileImpl.hh" - -#ifdef PXL_ENABLE_SFTP -#include "sFTPFileImpl.hh" -#endif -#ifdef PXL_ENABLE_DCAP -#include "dCapFileImpl.hh" -#endif - namespace pxl { static bool _initialized = false; -static ObjectProducerTemplate _BasicContainerProducer; -static ObjectProducerTemplate _BasicMatrixProducer; -static ObjectProducerTemplate _BasicNVectorProducer; -static ObjectProducerTemplate _EventProducer; -static ObjectProducerTemplate _InformationChunkProducer; -static ObjectProducerTemplate _ObjectProducer; -static ObjectProducerTemplate _ObjectManagerProducer; -static FileProducerTemplate _LocalFileProducer; -static FileProducerTemplate _StdFileProducer; -#ifdef PXL_ENABLE_SFTP -static FileProducerTemplate _sFTPFileProducer; -#endif -#ifdef PXL_ENABLE_DCAP -static FileProducerTemplate _dCapFileProducer; -#endif +static SerializableProducerTemplate _ObjectProducer; +static SerializableProducerTemplate _InfoObjectProducer; +static SerializableProducerTemplate _ObjectOwnerProducer; + void Core::initialize() { - if (_initialized) - return; - - _BasicContainerProducer.initialize(); - _BasicMatrixProducer.initialize(); - _BasicNVectorProducer.initialize(); - _EventProducer.initialize(); - _InformationChunkProducer.initialize(); - _ObjectProducer.initialize(); - _ObjectManagerProducer.initialize(); - _LocalFileProducer.initialize("file"); - _StdFileProducer.initialize("std"); -#ifdef PXL_ENABLE_SFTP - _sFTPFileProducer.initialize("ssh"); -#endif -#ifdef PXL_ENABLE_DCAP - _dCapFileProducer.initialize("dcap"); -#endif - _initialized = true; + if (_initialized) + { + return; + } + _initialized = true; + + _InfoObjectProducer.initialize(); + _ObjectProducer.initialize(); + _ObjectOwnerProducer.initialize(); } void Core::shutdown() { - if (_initialized == false) - return; - - _BasicMatrixProducer.shutdown(); - _BasicContainerProducer.shutdown(); - _BasicNVectorProducer.shutdown(); - _EventProducer.shutdown(); - _InformationChunkProducer.shutdown(); - _ObjectProducer.shutdown(); - _ObjectManagerProducer.shutdown(); - _LocalFileProducer.shutdown(); -#ifdef PXL_ENABLE_SFTP - _sFTPFileProducer.shutdown(); -#endif -#ifdef PXL_ENABLE_DCAP - _dCapFileProducer.shutdown(); -#endif - _initialized = false; + if (!_initialized) + { + return; + } + _initialized = false; + + _InfoObjectProducer.shutdown(); + _ObjectProducer.shutdown(); + _ObjectOwnerProducer.shutdown(); } } // namespace pxl diff --git a/core/src/Event.cc b/core/src/Event.cc deleted file mode 100644 index 7c7a978f2ed6760dd1db0b065fc70bc89d0dde56..0000000000000000000000000000000000000000 --- a/core/src/Event.cc +++ /dev/null @@ -1,51 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include "pxl/core/Event.hh" - -namespace pxl -{ - -void Event::serialize(const OutputStream &out) const -{ - Serializable::serialize(out); - _objects.serialize(out); - UserRecordHelper::serialize(out); -} - -void Event::deserialize(const InputStream &in) -{ - Serializable::deserialize(in); - _objects.deserialize(in); - UserRecordHelper::deserialize(in); -} - - -std::ostream& Event::print(int level, std::ostream& os, int pan) const -{ - os << "Event." << std::endl; - - if (level>0) - getUserRecords().print(level, os, pan); - - for (ObjectOwner::const_iterator iter = _objects.begin(); iter - !=_objects.end(); ++iter) - { - if ((*iter)->getMotherRelations().size() == 0) - (*iter)->printDecayTree(0, os, pan); - } - return os; -} - -const Id& Event::getStaticTypeId() -{ - static const Id id("c95f7434-2481-45e2-91dc-9baff0669bb3"); - return id; -} - -} // namespace pxl diff --git a/core/src/File.cc b/core/src/File.cc deleted file mode 100644 index e195bdc31dee4d8179b1fbaccd81ef515df868d8..0000000000000000000000000000000000000000 --- a/core/src/File.cc +++ /dev/null @@ -1,134 +0,0 @@ -#include "pxl/core/File.hh" -#include "pxl/core/logging.hh" -#include "pxl/core/FileFactory.hh" - -#include "LocalFileImpl.hh" - -#undef PXL_LOG_MODULE_NAME -#define PXL_LOG_MODULE_NAME "pxl::File" - -namespace pxl -{ - -File::File() : - impl(0) -{ - -} - -File::File(const std::string &filename, int32_t mode) : - impl(0) -{ - open(filename, mode); -} - -File::~File() -{ - close(); -} - -void File::close() -{ - if (impl) - { - impl->close(); - impl->destroy(); - impl = 0; - } -} - -bool File::isEof() -{ - if (impl == 0) - throw std::runtime_error("invalid File implementation!"); - return impl->isEof(); -} - -bool File::isBad() -{ - if (impl == 0) - return true; - else - return impl->isBad(); -} -bool File::isOpen() -{ - if (impl == 0) - return false; - else - return impl->isOpen(); -} -void File::clear() -{ - if (impl) - impl->clear(); -} -bool File::isGood() -{ - if (impl == 0) - throw std::runtime_error("invalid File implementation!"); - return impl->isGood(); -} -int64_t File::tell() -{ - if (impl == 0) - throw std::runtime_error("invalid File implementation!"); - return impl->tell(); -} -void File::seek(int64_t pos, int32_t d) -{ - if (impl == 0) - throw std::runtime_error("invalid File implementation!"); - impl->seek(pos, d); -} -int32_t File::peek() -{ - if (impl == 0) - throw std::runtime_error("invalid File implementation!"); - return impl->peek(); -} -int64_t File::read(char *s, size_t count) -{ - if (impl == 0) - throw std::runtime_error("invalid File implementation!"); - return impl->read(s, count); -} -int64_t File::write(const char *s, size_t count) -{ - if (impl == 0) - throw std::runtime_error("invalid File implementation!"); - return impl->write(s, count); -} -void File::ignore(int64_t count) -{ - if (impl == 0) - throw std::runtime_error("invalid File implementation!"); - impl->ignore(count); -} -void File::destroy() -{ - delete this; -} - -bool File::open(const std::string &filename, int32_t mode) -{ - std::string expanded = expandEnvironmentVariables(filename); - std::string schema, path; - splitSchema(expanded, schema, path); - if (schema.empty()) - schema = "file"; - - PXL_LOG_INFO << "Open: schema=" << schema << ", path=" << path; - - impl = FileFactory::instance().create(schema); - - if (impl == 0) - { - PXL_LOG_ERROR << "Unknown Schema: " << schema; - return false; - } - - return impl->open(expanded, mode); -} - -} diff --git a/core/src/FileFactory.cc b/core/src/FileFactory.cc deleted file mode 100644 index 2d91eb4f303ebaf99fa5dd68e320332047ab53ed..0000000000000000000000000000000000000000 --- a/core/src/FileFactory.cc +++ /dev/null @@ -1,65 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include "pxl/core/FileFactory.hh" -#include "pxl/core/logging.hh" - -#undef PXL_LOG_MODULE_NAME -#define PXL_LOG_MODULE_NAME "pxl::FileFactory" - -namespace pxl -{ - -FileFactory::FileFactory() -{ -} - -FileFactory& FileFactory::instance() -{ - static FileFactory f; - return f; -} - -FileImpl *FileFactory::create(const std::string& id) -{ - std::map::iterator result; - result = _Producers.find(id); - if (result == _Producers.end()) - return 0; - else - return (*result).second->create(); -} - -void FileFactory::registerProducer(const std::string& id, - const FileProducerInterface* producer) -{ - PXL_LOG_INFO << "register file schema " << id; - _Producers[id] = producer; -} - -void FileFactory::unregisterProducer(const FileProducerInterface* producer) -{ - std::map::iterator i; - for (i = _Producers.begin(); i != _Producers.end(); i++) - { - if (i->second == producer) - { - PXL_LOG_INFO << "unregister file schema " << i->first; - _Producers.erase(i); - return; - } - } -} - -bool FileFactory::hasSchema(const std::string& schema) -{ - return (_Producers.find(schema) != _Producers.end()); -} - -} // namespace pxl - diff --git a/core/src/Functions.cc b/core/src/Functions.cc new file mode 100644 index 0000000000000000000000000000000000000000..88ab37937d742e09c701c2d9b233c4e1997a9c9b --- /dev/null +++ b/core/src/Functions.cc @@ -0,0 +1,274 @@ +//------------------------------------------- +// Project: Physics eXtension Library (PXL) - +// http://vispa.physik.rwth-aachen.de/ - +// Copyright (C) 2006-2019 Martin Erdmann - +// RWTH Aachen, Germany - +// Licensed under a LGPL-2 or later license - +//------------------------------------------- + +#include + +#include +#include + +#ifdef WIN32 +#include "windows.h" +#ifndef S_ISREG +#define S_ISREG(x) (((x)&S_IFMT) == S_IFREG) +#endif +#ifndef S_ISDIR +#define S_ISDIR(x) (((x)&S_IFMT) == S_IFDIR) +#endif +#else +#include +#include +#endif + +#include "pxl/core/Functions.hh" + +namespace pxl +{ + +double getCpuTime() +{ +#ifdef WIN32git + return timeGetTime() / 1000.; +#else + struct timeval tv; + gettimeofday(&tv, NULL); + return ((double)tv.tv_sec + (double)tv.tv_usec / 1000000.0); +#endif +} + +const std::string& getDefaultSpaces() +{ + static std::string spaces(" \t\r\n"); + return spaces; +} + +std::string trim_right(const std::string& s, const std::string& t = getDefaultSpaces()) + +{ + std::string::size_type i(s.find_last_not_of(t)); + + if (i == std::string::npos) + return ""; + else + return std::string(s, 0, i); +} + +std::string trim_left(const std::string& s, const std::string& t = getDefaultSpaces()) +{ + return std::string(s, s.find_first_not_of(t)); +} + +std::string trim(const std::string& s) +{ + return trim(s, getDefaultSpaces()); +} + +std::string trim(const std::string& s, const std::string& t) +{ + std::string::size_type a = s.find_first_not_of(t), b = s.find_last_not_of(t); + + if (a == std::string::npos || b == std::string::npos) + + return std::string(); + + return std::string(s, a, b - a + 1); +} + +void explode( + const std::string& s, std::vector& v, const bool trim_spaces, const std::string& t) +{ + std::string::size_type a, b; + + a = s.find_first_not_of(t); + b = s.find_first_of(t, a); + + while (a != std::string::npos) + { + if (trim_spaces) + v.push_back(trim(s.substr(a, b - a))); + else + v.push_back(s.substr(a, b - a)); + + a = s.find_first_not_of(t, b); + b = s.find_first_of(t, a); + } +} + +std::string implode(const std::vector& v, const std::string& t) +{ + size_t i; + std::string s; + + for (i = 0; i < (v.size() - 1); i++) + { + s.append(v[i]); + s.append(t); + } + + return s + v[i]; +} + +std::string expandEnvironmentVariables(const std::string& input) +{ + std::string result; +#ifdef WIN32 +#define BUFFER_SIZE 32767 + char buffer[BUFFER_SIZE]; + ExpandEnvironmentStrings(input.c_str(), buffer, BUFFER_SIZE); + result = buffer; +#else + wordexp_t p; + wordexp(input.c_str(), &p, 0); + // in principle wordexp can also resolve [a-c]*.foo or similar. Here + // hiowever only the first result is returned, as it is currently + // unclear howto achieve this on windows and also howto handle this + // in e.g. outputfiles. + // A future version might return multiple files as string vector? + result = p.we_wordv[0]; + wordfree(&p); +#endif + return result; +} + +std::string& replace(std::string& context, const std::string& from, const std::string& to) +{ + size_t lookHere = 0; + size_t foundHere; + while ((foundHere = context.find(from, lookHere)) != std::string::npos) + { + context.replace(foundHere, from.size(), to); + lookHere = foundHere + to.size(); + } + return context; +} + +std::string getParentDirectory(const std::string& path) +{ + std::string::size_type p = path.find_last_of("/\\"); + if (p == std::string::npos) + return std::string("./"); + else + return path.substr(0, p); +} + +bool createDirectory(const std::string& path) +{ +#ifdef WIN32 + BOOL result = ::CreateDirectoryA(path.c_str(), 0); + return result == TRUE; +#else + int result = mkdir(path.c_str(), 0x0777); + return (result == 0); +#endif +} + +bool isAbsolutePath(const std::string& _path) +{ + std::string schema, path; + splitSchema(_path, schema, path); + if (!schema.empty()) + return true; + +#if WIN32 + if (path.size() < 3) + return false; + + if (path[1] == ':') + { + char drive = tolower(path[0]); + if (drive < 'a' || drive > 'z') + return false; + } + else if (path[1] == '\\') + { + if (path[0] != '\\') + return false; + } + return true; +#else + if (path.size() >= 1 && path[0] == '/') + return true; + else + return false; +#endif +} + +bool isDirectory(const std::string& path) +{ +#ifdef _MSC_VER + struct _stat buf; + int result = _stat(path.c_str(), &buf); + if (result == 0 && S_ISDIR(buf.st_mode)) + return true; + else + return false; +#else + struct stat buf; + int result = stat(path.c_str(), &buf); + if (result == 0 && S_ISDIR(buf.st_mode)) + return true; + else + return false; +#endif +} + +bool isFile(const std::string& path) +{ +#ifdef _MSC_VER + struct _stat buf; + int result = _stat(path.c_str(), &buf); + if (result == 0 && S_ISREG(buf.st_mode)) + return true; + else + return false; +#else + struct stat buf; + int result = stat(path.c_str(), &buf); + if (result == 0 && S_ISREG(buf.st_mode)) + return true; + else + return false; +#endif +} + +std::string clearPathName(const std::string& path) +{ +#ifdef WIN32 + std::string cleared = path; + for (std::string::iterator i = cleared.begin(); i != cleared.end(); i++) + if (*i == '/') + *i = '\\'; + return cleared; +#else + std::string cleared = path; + for (std::string::iterator i = cleared.begin(); i != cleared.end(); i++) + if (*i == '\\') + *i = '/'; + return cleared; +#endif +} + +void splitSchema(const std::string& url, std::string& schema, std::string& path) +{ + std::string::size_type schema_start_pos = url.find_first_not_of(" \t\n\r"); + std::string::size_type schema_end_pos = url.find_first_of(':'); + + bool noSchmea = schema_end_pos == std::string::npos; + bool windowsPath = (schema_end_pos - schema_start_pos) == 1; + if (noSchmea || windowsPath) + { + schema.clear(); + path = url; + } + else + { + schema = url.substr(schema_start_pos, schema_end_pos - schema_start_pos); + path = url.substr(schema_end_pos + 1); + } +} + +} // namespace pxl diff --git a/core/src/Id.cc b/core/src/Id.cc index a9621e75723a5d43986c932967a222730dae9bc1..aa1bb8d9aa241a48b0f0f2ccfdcff5fa8c8c504d 100644 --- a/core/src/Id.cc +++ b/core/src/Id.cc @@ -1,253 +1,267 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- #include "pxl/core/Id.hh" -namespace pxl { +namespace pxl +{ Id::Id() { - generate(); + generate(); } -Id::Id (const InputStream& in) +Id::Id(const InputStream& in) { - deserialize (in); + deserialize(in); } Id::Id(Random& rand) { - generate(rand); + generate(rand); } void Id::generate(Random& rand) { - for (int i = 0; i < 4; i++) - { - Random::uint32 value = rand.randInt(); - char *c = (char *)&value; - bytes[i*4+0] = c[0]; - bytes[i*4+1] = c[1]; - bytes[i*4+2] = c[2]; - bytes[i*4+3] = c[3]; - } - - /* set version 4 (random)*/ - bytes[7] &= ((1 << 4) - 1); - bytes[7] |= 4 << 4; - - /* set variant (always DCE 1.1 only) */ - bytes[8] &= ((1 << 7) - 1); - bytes[8] |= 2 << 6; + for (int i = 0; i < 4; i++) + { + Random::uint32 value = rand.randInt(); + char* c = (char*)&value; + bytes[i * 4 + 0] = c[0]; + bytes[i * 4 + 1] = c[1]; + bytes[i * 4 + 2] = c[2]; + bytes[i * 4 + 3] = c[3]; + } + + /* set version 4 (random)*/ + bytes[7] &= ((1 << 4) - 1); + bytes[7] |= 4 << 4; + + /* set variant (always DCE 1.1 only) */ + bytes[8] &= ((1 << 7) - 1); + bytes[8] |= 2 << 6; } void Id::generate() { - static Random rand; - generate(rand); + static Random rand; + generate(rand); } Id Id::create() { - Id id; - id.generate(); - return id; + Id id; + id.generate(); + return id; } -bool Id::operator ==(const Id& id) const +bool Id::operator==(const Id& id) const { - for (int i = 0; i < 16; i++) - { - if (bytes[i] != id.bytes[i]) - return false; - } - - return true; + for (int i = 0; i < 16; i++) + { + if (bytes[i] != id.bytes[i]) + { + return false; + } + } + + return true; } -bool Id::operator !=(const Id& id) const +bool Id::operator!=(const Id& id) const { - for (int i = 0; i < 16; i++) - { - if (bytes[i] != id.bytes[i]) - return true; - } - - return false; + for (int i = 0; i < 16; i++) + { + if (bytes[i] != id.bytes[i]) + { + return true; + } + } + + return false; } void Id::reset() { - for (int j = 0; j < 16; j++) - bytes[j] = 0; + for (int j = 0; j < 16; j++) + { + bytes[j] = 0; + } } -bool Id::operator <(const Id& op) const +bool Id::operator<(const Id& op) const { - for (int i = 0; i < 16; i++) - { - if (bytes[i] < op.bytes[i]) - return true; - else if (bytes[i] > op.bytes[i]) - return false; - } - - return false; + for (int i = 0; i < 16; i++) + { + if (bytes[i] < op.bytes[i]) + { + return true; + } + else if (bytes[i] > op.bytes[i]) + { + return false; + } + } + + return false; } - -void Id::serialize(const OutputStream &out) const +void Id::serialize(const OutputStream& out) const { - for (size_t i = 0; i < 16; i++) - out.writeUnsignedChar(bytes[i]); + for (size_t i = 0; i < 16; i++) + { + out.writeChar(bytes[i]); + } } -void Id::deserialize(const InputStream &in) +void Id::deserialize(const InputStream& in) { - for (size_t i = 0; i < 16; i++) - in.readUnsignedChar(bytes[i]); + for (size_t i = 0; i < 16; i++) + { + in.readUChar(bytes[i]); + } } - + Id::Id(const char* id) { - // reset - for (int j = 0; j < 16; j++) - bytes[j] = 0; - - // read 32 char = 16 bytes - unsigned char first = 0, second = 0; - int byte = 0; - const char* source = id; - unsigned char* target = &first; - - while (*source != 0 && byte < 16) - { - // find next a valid character - if (*source >= '0' && *source <= '9') - { - *target = *source -'0'; - } - else if (*source >= 'a' && *source <= 'f') - { - *target = *source -'a' + 10; - } - else if (*source >= 'A' && *source <= 'F') - { - *target = *source -'A' + 10; - } - else - { - source++; - continue; - } - - // - if (target == &first) - target = &second; - else - { - bytes[byte] = ((first << 4) | second); - byte++; - target = &first; - } - - source++; - } + // reset + for (int j = 0; j < 16; j++) + { + bytes[j] = 0; + } + + // read 32 char = 16 bytes + unsigned char first = 0, second = 0; + int byte = 0; + const char* source = id; + unsigned char* target = &first; + + while (*source != 0 && byte < 16) + { + // find next a valid character + if (*source >= '0' && *source <= '9') + { + *target = *source - '0'; + } + else if (*source >= 'a' && *source <= 'f') + { + *target = *source - 'a' + 10; + } + else if (*source >= 'A' && *source <= 'F') + { + *target = *source - 'A' + 10; + } + else + { + source++; + continue; + } + + // + if (target == &first) + target = &second; + else + { + bytes[byte] = ((first << 4) | second); + byte++; + target = &first; + } + + source++; + } } Id::Id(const std::string& id) { - unsigned char first, second; - int byte = 0; - unsigned char* target = &first; - std::string::const_iterator source = id.begin(); - std::string::const_iterator end = id.end(); - - while (source != end && byte < 16) - { - if (*source >= '0' && *source <= '9') - { - *target = *source -'0'; - } - else if (*source >= 'a' && *source <= 'f') - { - *target = *source -'a' + 10; - } - else if (*source >= 'A' && *source <= 'F') - { - *target = *source -'A' + 10; - } - else - { - source++; - continue; - } - - if (target == &first) - target = &second; - else - { - bytes[byte] = ((first << 4) | second); - byte++; - target = &first; - } - - source++; - } -} - -std::ostream& operator <<(std::ostream& os, const Id &id) -{ - os << id.toString(); - return os; + unsigned char first, second; + int byte = 0; + unsigned char* target = &first; + std::string::const_iterator source = id.begin(); + std::string::const_iterator end = id.end(); + + while (source != end && byte < 16) + { + if (*source >= '0' && *source <= '9') + { + *target = *source - '0'; + } + else if (*source >= 'a' && *source <= 'f') + { + *target = *source - 'a' + 10; + } + else if (*source >= 'A' && *source <= 'F') + { + *target = *source - 'A' + 10; + } + else + { + source++; + continue; + } + + if (target == &first) + target = &second; + else + { + bytes[byte] = ((first << 4) | second); + byte++; + target = &first; + } + + source++; + } +} + +std::ostream& operator<<(std::ostream& os, const Id& id) +{ + os << id.toString(); + return os; } std::string Id::toString() const { - static const char hex[] = - { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', - 'e', 'f' }; - - std::string id; - id.reserve(36); - - for (int i = 0; i < 4; i++) - { - id += hex[bytes[i] >> 4]; - id += hex[bytes[i] & 0x0F]; - } - id += '-'; - for (int i = 4; i < 6; i++) - { - id += hex[bytes[i] >> 4]; - id += hex[bytes[i] & 0x0F]; - } - id += '-'; - for (int i = 6; i < 8; i++) - { - id += hex[bytes[i] >> 4]; - id += hex[bytes[i] & 0x0F]; - } - id += '-'; - for (int i = 8; i < 10; i++) - { - id += hex[bytes[i] >> 4]; - id += hex[bytes[i] & 0x0F]; - } - id += '-'; - for (int i = 10; i < 16; i++) - { - id += hex[bytes[i] >> 4]; - id += hex[bytes[i] & 0x0F]; - } - - return id; + static const char hex[] + = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + + std::string id; + id.reserve(36); + + for (int i = 0; i < 4; i++) + { + id += hex[bytes[i] >> 4]; + id += hex[bytes[i] & 0x0F]; + } + id += '-'; + for (int i = 4; i < 6; i++) + { + id += hex[bytes[i] >> 4]; + id += hex[bytes[i] & 0x0F]; + } + id += '-'; + for (int i = 6; i < 8; i++) + { + id += hex[bytes[i] >> 4]; + id += hex[bytes[i] & 0x0F]; + } + id += '-'; + for (int i = 8; i < 10; i++) + { + id += hex[bytes[i] >> 4]; + id += hex[bytes[i] & 0x0F]; + } + id += '-'; + for (int i = 10; i < 16; i++) + { + id += hex[bytes[i] >> 4]; + id += hex[bytes[i] & 0x0F]; + } + + return id; } } // namespace pxl - diff --git a/core/src/InformationChunk.cc b/core/src/InformationChunk.cc deleted file mode 100644 index 145fca7f75c6fc9044763fa9f9c755137caefa62..0000000000000000000000000000000000000000 --- a/core/src/InformationChunk.cc +++ /dev/null @@ -1,28 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include "pxl/core/InformationChunk.hh" -#include "pxl/core/ObjectFactory.hh" - -namespace pxl { - -/// Write data to the OutputStream \p out. -void InformationChunk::serialize(const OutputStream &out) const -{ - Serializable::serialize(out); - UserRecordHelper::serialize(out); -} - -/// Read data from the InputStream \p in. -void InformationChunk::deserialize(const InputStream &in) -{ - Serializable::deserialize(in); - UserRecordHelper::deserialize(in); -} - -} diff --git a/core/src/InputHandler.cc b/core/src/InputHandler.cc deleted file mode 100644 index d981825587a1614f2126fc05667a1e63b8f84065..0000000000000000000000000000000000000000 --- a/core/src/InputHandler.cc +++ /dev/null @@ -1,300 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include - -#include "pxl/core/InputHandler.hh" -#include "pxl/core/ObjectFactory.hh" - -namespace pxl -{ - -/// This method fills the objects from the read-in block into the passed vector. The number of added objects is returned. -int InputHandler::readObjects(std::vector& objects) -{ - int nObjects = 0; - while (getChunkReader().getInputStream().good()) - { - _objectCount++; - - Id id(getChunkReader().getInputStream()); - - Serializable* obj = ObjectFactory::instance().create(id); - if (obj) - { - obj->deserialize(getChunkReader().getInputStream()); - objects.push_back(obj); - nObjects++; - } - else - throw std::runtime_error( - "InputHandler::readObjects(std::vector& objects): unknown object in file: " - + id.toString()); - } - return nObjects; -} - -/// This method fills the objects from the read-in block into the passed pxl::Event. The number of added objects is returned. -/// Caution: Only pxl::Relative derivatives will be restored, e.g. no pxl::Event. -int InputHandler::readObjects(Event* event) -{ - int nObjects = 0; - while (getChunkReader().getInputStream().good()) - { - _objectCount++; - - Id id(getChunkReader().getInputStream()); - - Relative *obj = - dynamic_cast (ObjectFactory::instance().create(id)); - if (obj) - { - obj->deserialize(getChunkReader().getInputStream()); - event->insertObject(obj); - nObjects++; - } - else - throw std::runtime_error( - "InputHandler::readObjects(pxl::Event* event): unknown object in file: " - + id.toString()); - - } - return nObjects; -} - -/// This method fills the objects from the read-in block into the passed pxl::BasicContainer. The number of added objects is returned. -int InputHandler::readObjects(BasicContainer* container) - -{ - int nObjects = 0; - while (getChunkReader().getInputStream().good()) - { - _objectCount++; - - Id id(getChunkReader().getInputStream()); - - Serializable* obj = ObjectFactory::instance().create(id); - if (obj) - { - obj->deserialize(getChunkReader().getInputStream()); - container->insertObject(obj); - nObjects++; - } - else - throw std::runtime_error( - "InputHandler::readObjects(std::vector& objects): unknown object in file: " - + id.toString()); - } - return nObjects; -} - -Serializable* InputHandler::readNextObject() -{ - while (!getChunkReader().getInputStream().good()) - { - if (getChunkReader().getStatus() == ChunkReader::preHeader) - { - if (!getChunkReader().next()) - { - return 0; - } - } - getChunkReader().nextBlock(); - if (getChunkReader().eof()) - return 0; - } - - _objectCount++; - - Id id(getChunkReader().getInputStream()); - Serializable* obj = ObjectFactory::instance().create(id); - if (obj) - { - obj->deserialize(getChunkReader().getInputStream()); - return obj; - } - else - throw std::runtime_error( - "InputHandler::readNextObject(): unknown object in file: " - + id.toString()); - return obj; -} - -Serializable* InputHandler::readPreviousObject() -{ - return seekToObject(_objectCount - 1); -} - -Serializable* InputHandler::seekToObject(size_t index) - -{ - if (index <= _objectCount) - { - /// bool success = - seekToFileSection(0); - //DEACTIVATE for current VISPA version, should be fixed in IO 3.0 - // if (!success) - // throw std::runtime_error("InputHandler::seekToObject: seekToFileSection(0) not successful"); - _objectCount = 0; - } - - if (index > _objectCount) - { - Serializable* obj = 0; - do - { - if (obj != 0) - delete obj; - - obj = readNextObject(); - if (obj == 0) - return 0; - } - while (index > _objectCount); - return obj; - } - - return 0; -} - -bool InputHandler::readEvent(Event* event) -{ - if (getChunkReader().nextBlock() - && getChunkReader().getInputStream().good()) - { - Id id(getChunkReader().getInputStream()); - if (id == event->getStaticTypeId()) - { - event->deserialize(getChunkReader().getInputStream()); - return true; - } - } - return false; -} - -bool InputHandler::readEventIf(Event* event, const std::string& blockInfo, - skipMode doSkip) -{ - if (readBlockIf(blockInfo, doSkip)) - { - Id id(getChunkReader().getInputStream()); - if (id == event->getStaticTypeId()) - { - event->deserialize(getChunkReader().getInputStream()); - return true; - } - } - return false; -} - -bool InputHandler::readBasicContainer(BasicContainer* basicContainer) -{ - if (getChunkReader().nextBlock() - && getChunkReader().getInputStream().good()) - { - Id id(getChunkReader().getInputStream()); - if (id == basicContainer->getStaticTypeId()) - { - basicContainer->deserialize(getChunkReader().getInputStream()); - return true; - } - } - return false; -} - -bool InputHandler::readBasicContainerIf(BasicContainer* basicContainer, - const std::string& blockInfo, skipMode doSkip) -{ - if (readBlockIf(blockInfo, doSkip)) - { - Id id(getChunkReader().getInputStream()); - if (id == basicContainer->getStaticTypeId()) - { - basicContainer->deserialize(getChunkReader().getInputStream()); - return true; - } - } - return false; -} - -bool InputHandler::readInformationChunk(InformationChunk* chunk) -{ - if (getChunkReader().nextBlock() - && getChunkReader().getInputStream().good()) - { - Id id(getChunkReader().getInputStream()); - if (id == chunk->getStaticTypeId()) - { - chunk->deserialize(getChunkReader().getInputStream()); - return true; - } - } - return false; -} - -bool InputHandler::readInformationChunkIf(InformationChunk* event, - const std::string& blockInfo, skipMode doSkip) -{ - if (readBlockIf(blockInfo, doSkip)) - { - Id id(getChunkReader().getInputStream()); - if (id == event->getStaticTypeId()) - { - event->deserialize(getChunkReader().getInputStream()); - return true; - } - } - return false; -} - -int InputHandler::skipFileSections(int n) -{ - int skipped = 0; - for (; n < 0 && getChunkReader().previous(); ++n) - --skipped; - for (; n > 0 && getChunkReader().skip(); --n) - ++skipped; - return skipped; -} - -bool InputHandler::seekToFileSection(int index) -{ - int count = index - getChunkReader().getSectionCount(); - return (skipFileSections(count) == count); -} - -bool InputHandler::readBlockIf(const std::string& blockInfo, skipMode doSkip) -{ - bool success = false; - while (!success && getChunkReader().getStatus() != 0) - { - success = getChunkReader().nextBlock(doSkip, ChunkReader::evaluate, - blockInfo); - } - return success; -} - -/// This method explicitly reads an object of type objecttype. Caution: This method should only be used if the type of the following object is known by hard. -template bool InputHandler::readObject(objecttype* obj) - -{ - if (getChunkReader().getInputStream().good()) - { - Id id(getChunkReader().getInputStream()); - if (id != objecttype::getStaticTypeId()) - throw std::runtime_error( - "InputHandler::readObject(objecttype* obj): unexpected object in file: " - + id.toString()); - obj->deserialize(getChunkReader().getInputStream()); - return true; - } - return false; -} - -} -//namespace pxl diff --git a/core/src/JsonParser.cc b/core/src/JsonParser.cc new file mode 100644 index 0000000000000000000000000000000000000000..5a1707b63e8f866898a9f990aa21370fe6648209 --- /dev/null +++ b/core/src/JsonParser.cc @@ -0,0 +1,103 @@ +//------------------------------------------- +// Project: Physics eXtension Library (PXL) - +// http://vispa.physik.rwth-aachen.de/ - +// Copyright (C) 2006-2019 Martin Erdmann - +// RWTH Aachen, Germany - +// Licensed under a LGPL-2 or later license - +//------------------------------------------- + +#include + +#include "JsonParser.hh" +#include "minijson_reader.hh" + +#include "pxl/core/Variant.hh" + +namespace pxl +{ + +void ArrayParser::operator()(minijson::value value) +{ + if (v.getType() != Variant::TYPE_VECTOR) + { + v.asVector(); + } + + size_t oldSize = v.size(); + v.resize(oldSize + 1); + minijson::value_type t = value.type(); + if (t == minijson::Boolean) + { + v[oldSize].asBool() = value.as_bool(); + } + else if (t == minijson::Number) + { + if (std::strtok((char*)value.as_string(), ".eE") == NULL) + { + v[oldSize].asInt64() = value.as_long(); + } + else + { + v[oldSize].asDouble() = value.as_double(); + } + } + else if (t == minijson::String) + { + v[oldSize].asString() = value.as_string(); + } + else if (t == minijson::Array) + { + minijson::parse_array(ctx, ArrayParser(ctx, v[oldSize])); + } + else if (t == minijson::Object) + { + minijson::parse_object(ctx, ObjectParser(ctx, v[oldSize])); + } + else if (t == minijson::Null) + { + v[oldSize] = Variant(); + } +} + +void ObjectParser::operator()(const char* name, minijson::value value) +{ + if (v.getType() != Variant::TYPE_MAPPING) + { + v.asMapping(); + } + + minijson::value_type t = value.type(); + if (t == minijson::Boolean) + { + v[name].asBool() = value.as_bool(); + } + else if (t == minijson::Number) + { + if (std::strtok((char*)value.as_string(), ".eE") == NULL) + { + v[name].asInt64() = value.as_long(); + } + else + { + v[name].asDouble() = value.as_double(); + } + } + else if (t == minijson::String) + { + v[name].asString() = value.as_string(); + } + else if (t == minijson::Array) + { + minijson::parse_array(ctx, ArrayParser(ctx, v[name])); + } + else if (t == minijson::Object) + { + minijson::parse_object(ctx, ObjectParser(ctx, v[name])); + } + else if (t == minijson::Null) + { + v[name] = Variant(); + } +} + +} // namespace pxl diff --git a/core/src/JsonParser.hh b/core/src/JsonParser.hh new file mode 100644 index 0000000000000000000000000000000000000000..efea414a599625dd37ba3e9c0314ac33b0f499ac --- /dev/null +++ b/core/src/JsonParser.hh @@ -0,0 +1,53 @@ +//------------------------------------------- +// Project: Physics eXtension Library (PXL) - +// http://vispa.physik.rwth-aachen.de/ - +// Copyright (C) 2006-2019 Martin Erdmann - +// RWTH Aachen, Germany - +// Licensed under a LGPL-2 or later license - +//------------------------------------------- + +#ifndef PXL_CORE_JSONPARSER_HH +#define PXL_CORE_JSONPARSER_HH + +#include "minijson_reader.hh" + +#include "pxl/core/Variant.hh" + +namespace pxl +{ + +class PXL_DLL_EXPORT ArrayParser +{ +public: + ArrayParser(minijson::istream_context& ctx, Variant& v) + : ctx(ctx) + , v(v) + { + } + + void operator()(minijson::value value); + +private: + minijson::istream_context& ctx; + Variant& v; +}; + +class PXL_DLL_EXPORT ObjectParser +{ +public: + ObjectParser(minijson::istream_context& ctx, Variant& v) + : ctx(ctx) + , v(v) + { + } + + void operator()(const char* name, minijson::value value); + +private: + minijson::istream_context& ctx; + Variant& v; +}; + +} // namespace pxl + +#endif // PXL_CORE_JSONPARSER_HH diff --git a/core/src/LocalFileImpl.cc b/core/src/LocalFileImpl.cc deleted file mode 100644 index a1c09e4e3eb5180ab394312f4d9b66c27391893a..0000000000000000000000000000000000000000 --- a/core/src/LocalFileImpl.cc +++ /dev/null @@ -1,165 +0,0 @@ -#include "LocalFileImpl.hh" -#include "pxl/core/FileFactory.hh" -#include "pxl/core/functions.hh" - -#include - -namespace pxl -{ - -LocalFileImpl::LocalFileImpl() : - _file(0) -{ - -} - -LocalFileImpl::LocalFileImpl(const std::string &filename, int32_t mode) : - _file(0) -{ - open(filename, mode); -} - -LocalFileImpl::~LocalFileImpl() -{ - close(); -} - -bool LocalFileImpl::open(const std::string &filename, int32_t mode) -{ - close(); - std::string open_mode; - if (mode & OpenRead) - open_mode.append("r"); - else if (mode & OpenWrite) - open_mode.append("w"); - open_mode.append("b"); - - std::string schema, path; - splitSchema(filename, schema, path); -#if defined( _MSC_VER) - errno_t err = fopen_s(&_file, filename.c_str(), open_mode.c_str()); - if (err != 0) - _file = 0; -#elif defined( __APPLE__) - _file = fopen(path.c_str(), open_mode.c_str()); -#else - _file = fopen64(path.c_str(), open_mode.c_str()); -#endif - - _mode = mode; - - return isOpen(); -} - -void LocalFileImpl::close() -{ - if (_file == 0) - return; - fclose(_file); - _file = 0; -} - -bool LocalFileImpl::isEof() -{ - if (_file == 0) - return true; - - return (feof(_file) != 0); -} - -bool LocalFileImpl::isOpen() -{ - return (_file != 0); -} - -bool LocalFileImpl::isBad() -{ - if (_file == 0) - return true; - - return false; -} - -void LocalFileImpl::clear() -{ - -} - -bool LocalFileImpl::isGood() -{ - if (_file == 0) - return false; - - if (feof(_file)) - return false; - - return true; -} - -int64_t LocalFileImpl::tell() -{ - if (_file == 0) - return 0; - -#if defined(_MSC_VER) - return _ftelli64(_file); -#elif defined(__APPLE__) - return ftell(_file); -#else - return ftello64(_file); -#endif -} - -void LocalFileImpl::seek(int64_t pos, int32_t d) -{ - int whence; - if (d == SeekBegin) - whence = SEEK_SET; - else if (d == SeekCurrent) - whence = SEEK_CUR; - else if (d == SeekEnd) - whence = SEEK_END; - else - throw std::runtime_error("Uninitialized value in LocalFileImpl::seek. This never should happen!."); - -#if defined(_MSC_VER) - _fseeki64(_file, pos, SEEK_CUR); -#elif defined(__APPLE__) - fseek(_file, pos, whence); -#else - fseeko64(_file, pos, whence); -#endif -} - -int32_t LocalFileImpl::peek() -{ - int32_t c; - - c = fgetc(_file); - ungetc(c, _file); - - return c; -} - -int64_t LocalFileImpl::read(char *s, size_t count) -{ - return fread(s, sizeof(char), count, _file); -} - -int64_t LocalFileImpl::write(const char *s, size_t count) -{ - return fwrite(s, sizeof(char), count, _file); - -} - -void LocalFileImpl::ignore(int64_t count) -{ - seek(count, SeekCurrent); -} - -void LocalFileImpl::destroy() -{ - delete this; -} - -} diff --git a/core/src/LocalFileImpl.hh b/core/src/LocalFileImpl.hh deleted file mode 100644 index fc89984254138238b01148b88834800d160ddf32..0000000000000000000000000000000000000000 --- a/core/src/LocalFileImpl.hh +++ /dev/null @@ -1,40 +0,0 @@ -#ifndef PXL_LOCAL_FILE_IMPL_HH_ -#define PXL_LOCAL_FILE_IMPL_HH_ - -#include "pxl/core/macros.hh" -#include "pxl/core/File.hh" - -namespace pxl -{ - -class PXL_DLL_EXPORT LocalFileImpl: public FileImpl -{ - FILE *_file; - int32_t _mode; -public: - - LocalFileImpl(); - - LocalFileImpl(const std::string &filename, int32_t mode); - - ~LocalFileImpl(); - - virtual bool open(const std::string &filename, int32_t mode); - virtual void close(); - virtual bool isEof(); - virtual bool isOpen(); - virtual bool isBad(); - virtual void clear(); - virtual bool isGood(); - virtual int64_t tell(); - virtual void seek(int64_t pos, int32_t d); - virtual int32_t peek(); - virtual int64_t read(char *s, size_t count); - virtual int64_t write(const char *s, size_t count); - virtual void ignore(int64_t count); - virtual void destroy(); -}; - -} // namespace pxl - -#endif /* PXL_LOCAL_FILE_IMPL_HH_ */ diff --git a/core/src/Logging.cc b/core/src/Logging.cc new file mode 100644 index 0000000000000000000000000000000000000000..abe33d688ba9a8781a3668dd7a6b419732504d81 --- /dev/null +++ b/core/src/Logging.cc @@ -0,0 +1,324 @@ +//------------------------------------------- +// Project: Physics eXtension Library (PXL) - +// http://vispa.physik.rwth-aachen.de/ - +// Copyright (C) 2006-2019 Martin Erdmann - +// RWTH Aachen, Germany - +// Licensed under a LGPL-2 or later license - +//------------------------------------------- + +#include "pxl/core/Logging.hh" + +#include +#include +#include +#include + +#ifdef __unix__ +#include +#include +#endif + +namespace pxl +{ + +static bool wildcardCompare(const std::string& pattern, const std::string& str) +{ + size_t ps = pattern.size(); + size_t ss = str.size(); + + // wildcard? + bool wildcard = pattern[ps - 1] == '*'; + if (wildcard) + { + ps -= 1; + } + + // too short? + if (ss < ps) + { + return false; + } + + // too long? + if ((wildcard == false) && (ss > ps)) + { + return false; + } + + for (size_t i = 0; i < ps; i++) + { + if (pattern[i] != str[i]) + { + return false; + } + } + + return true; +} + +void ConsoleLogHandler::handle( + LogLevel level, time_t timestamp, const std::string& module, const std::string& message) +{ + // if no enabled modules are specified, enable all + bool enabled = enabledModules.empty(); + for (size_t i = 0; i < enabledModules.size(); i++) + { + if (wildcardCompare(enabledModules[i], module)) + { + enabled = true; + break; + } + } + + if (enabled == false) + return; + + // if no enabled modules are specified, enable all + if (disabledModules.empty() == false) + { + for (size_t i = 0; i < disabledModules.size(); i++) + { + if (wildcardCompare(disabledModules[i], module)) + return; + } + } + + tm* t = localtime(×tamp); + + std::stringstream sstr; + + // print date + sstr << t->tm_year + 1900 << "-"; + if (t->tm_mon + 1 < 10) + { + sstr << "0"; + } + sstr << t->tm_mon + 1 << "-"; + if (t->tm_mday < 10) + { + sstr << "0"; + } + sstr << t->tm_mday << " "; + + // print time + if (t->tm_hour < 10) + { + sstr << "0"; + } + sstr << t->tm_hour << ":"; + if (t->tm_min < 10) + { + sstr << "0"; + } + sstr << t->tm_min << ":"; + if (t->tm_sec < 10) + { + sstr << "0"; + } + sstr << t->tm_sec; + + if (level >= LOG_LEVEL_ERROR) + { + std::cerr << sstr.str() << " [" << errorColor << LogLevelToString(level) << endColor << "] " + << module << " " << message << std::endl; + } + else if (level == LOG_LEVEL_WARNING) + { + std::cerr << sstr.str() << " [" << warningColor << LogLevelToString(level) << endColor + << "] " << module << " " << message << std::endl; + } + else + { + std::cout << sstr.str() << " [" << LogLevelToString(level) << "] " << module << " " + << message << std::endl; + } +} + +ConsoleLogHandler::ConsoleLogHandler() +{ + const char* enabledModulesString = ::getenv("PXL_LOG_ENABLE"); + if (enabledModulesString) + { + pxl::explode(enabledModulesString, enabledModules, true, ","); + } + + const char* disabledModulesString = ::getenv("PXL_LOG_DISABLE"); + if (disabledModulesString) + { + pxl::explode(disabledModulesString, disabledModules, true, ","); + } + +#if __unix__ + if (isatty(fileno(stderr))) + { + warningColor = "\e[0;33m"; + errorColor = "\e[0;31m"; + endColor = "\e[m"; + } +#endif +} + +LogDispatcher::LogDispatcher() + : lowestLogLevel(LOG_LEVEL_ERROR) +{ + int level = LOG_LEVEL_WARNING; + const char* levelEnv = ::getenv("PXL_LOG_LEVEL"); + if (levelEnv) + { + level = atoi(levelEnv); + } + enableConsoleLogHandler(intToLogLevel(level)); +} + +void LogDispatcher::disableConsoleLogHandler() +{ + removeHandler(&consoleLogHandler); +} + +void LogDispatcher::enableConsoleLogHandler(LogLevel level) +{ + setHandler(&consoleLogHandler, level); +} + +void LogDispatcher::updateLowestLogLevel() +{ + lowestLogLevel = LOG_LEVEL_NONE; + for (handlers_t::iterator i = handlers.begin(); i != handlers.end(); i++) + { + if (i->second < lowestLogLevel) + { + lowestLogLevel = i->second; + } + } +} + +void LogDispatcher::setHandler(LogHandler* handler, LogLevel loglevel) +{ + // replace existing handler + for (handlers_t::iterator i = handlers.begin(); i != handlers.end(); i++) + { + if (i->first == handler) + { + i->second = loglevel; + updateLowestLogLevel(); + return; + } + } + + // add handler + handlers.push_back(std::make_pair(handler, loglevel)); + updateLowestLogLevel(); +} + +void LogDispatcher::removeHandler(LogHandler* handler) +{ + for (handlers_t::iterator i = handlers.begin(); i != handlers.end(); i++) + { + if (i->first == handler) + { + handlers.erase(i); + updateLowestLogLevel(); + return; + } + } +} + +void LogDispatcher::dispatch(LogLevel level, const std::string& module, const std::string& message) +{ + time_t timestamp; + time(×tamp); + for (handlers_t::iterator i = handlers.begin(); i != handlers.end(); i++) + { + if (i->second <= level) + { + i->first->handle(level, timestamp, module, message); + } + } +} + +LogLevel LogDispatcher::getLowestLogLevel() +{ + return lowestLogLevel; +} + +LogDispatcher& LogDispatcher::instance() +{ + static LogDispatcher dispatcher; + return dispatcher; +} + +LogLevel intToLogLevel(int i) +{ + if (i <= LOG_LEVEL_ALL) + { + return LOG_LEVEL_ALL; + } + else if (i == LOG_LEVEL_DEBUG) + { + return LOG_LEVEL_DEBUG; + } + else if (i == LOG_LEVEL_INFO) + { + return LOG_LEVEL_INFO; + } + else if (i == LOG_LEVEL_WARNING) + { + return LOG_LEVEL_WARNING; + } + else if (i == LOG_LEVEL_ERROR) + { + return LOG_LEVEL_ERROR; + } + else + { + return LOG_LEVEL_NONE; + } +} + +const std::string& LogLevelToString(LogLevel level) +{ + static std::string _all("ALL "); + static std::string _debug("DEBUG "); + static std::string _info("INFO "); + static std::string _waning("WARNING"); + static std::string _error("ERROR "); + static std::string _none("NONE "); + + if (level == LOG_LEVEL_ALL) + { + return _all; + } + else if (level == LOG_LEVEL_DEBUG) + { + return _debug; + } + else if (level == LOG_LEVEL_INFO) + { + return _info; + } + else if (level == LOG_LEVEL_WARNING) + { + return _waning; + } + else if (level == LOG_LEVEL_ERROR) + { + return _error; + } + else + { + return _none; + } +} + +LogBuffer::LogBuffer(LogLevel level, const char* module) + : level(level) + , module(module) +{ +} + +LogBuffer::~LogBuffer() +{ + LogDispatcher::instance().dispatch(level, module, stream.str()); +} + +} // namespace pxl diff --git a/core/src/LorentzVector.cc b/core/src/LorentzVector.cc index 9b550e9635d6e464cb957ba181535b43da12334a..8a9cec5a568f20805d77b884af2b143117dbdd5e 100644 --- a/core/src/LorentzVector.cc +++ b/core/src/LorentzVector.cc @@ -1,7 +1,7 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- @@ -10,74 +10,83 @@ #include "pxl/core/LorentzVector.hh" +#ifndef EPSILON +#define EPSILON 1.0e-9 +#endif + namespace pxl { -bool operator==(const LorentzVector& obj1, const LorentzVector& obj2) +void LorentzVector::boost(double bx, double by, double bz) { - return obj1.getX() == obj2.getX() && obj1.getY() == obj2.getY() && obj1.getZ() == obj2.getZ() && obj1.getE() - == obj2.getE(); + if (fabs(bx) < EPSILON && fabs(by) < EPSILON && fabs(bz) < EPSILON) + { + return; + } + + // https://en.wikipedia.org/wiki/Lorentz_transformation#Boost_matrix + // b = beta + // g = gamma + double b2 = bx * bx + by * by + bz * bz; + double g = 1.0 / sqrt(1.0 - b2); + double bp = bx * getPx() + by * getPy() + bz * getPz(); + + double a = (g * getE() + (g - 1.0) / b2 * bp); + + setE(g * (getE() + bp)); + setPx(getPx() + bx * a); + setPy(getPy() + by * a); + setPz(getPz() + bz * a); } -bool operator!=(const LorentzVector& obj1, const LorentzVector& obj2) +LorentzVector LorentzVector::operator-() const { - return obj1.getX() != obj2.getX() || obj1.getY() != obj2.getY() || obj1.getZ() != obj2.getZ() || obj1.getE() - != obj2.getE(); + return LorentzVector(getE(), -1. * getPx(), -1. * getPy(), -1. * getPz()); } -LorentzVector operator*(double scalar, const LorentzVector& vec) +LorentzVector LorentzVector::operator+(const LorentzVector& lvec) const { - LorentzVector out; - out.setX(vec.getX() * scalar); - out.setY(vec.getY() * scalar); - out.setZ(vec.getZ() * scalar); - out.setE(vec.getE() * scalar); - return out; + LorentzVector out(*this); + out += lvec; + return out; } -LorentzVector operator*(const LorentzVector& vec, double scalar) +LorentzVector LorentzVector::operator-(const LorentzVector& lvec) const { - return operator*(scalar, vec); + LorentzVector out(*this); + out -= lvec; + return out; } -// Scalar product -double LorentzVector::operator*(const LorentzVector& vec) const +double LorentzVector::operator*(const LorentzVector& lvec) const { - return getT() * vec.getT() - getX() * vec.getX() - getY() * vec.getY() - getZ() * vec.getZ(); + return getE() * lvec.getE() - getPx() * lvec.getPx() - getPy() * lvec.getPy() + - getPz() * lvec.getPz(); } -LorentzVector LorentzVector::operator-(const LorentzVector& vec) const +bool operator==(const LorentzVector& lvec1, const LorentzVector& lvec2) { - LorentzVector out(*this); - out -= vec; - return out; + return std::fabs(lvec1.getE() - lvec2.getE()) < EPSILON + && lvec1.getPVector() == lvec2.getPVector(); } -LorentzVector LorentzVector::operator+(const LorentzVector& vec) const +bool operator!=(const LorentzVector& lvec1, const LorentzVector& lvec2) { - LorentzVector out(*this); - out += vec; - return out; + return !(lvec1 == lvec2); } -LorentzVector LorentzVector::operator-() const +LorentzVector operator*(double scalar, const LorentzVector& lvec) { - return LorentzVector(-1. * getX(), -1. * getY(), -1. * getZ(), -1. * getT()); + LorentzVector out(lvec); + out *= scalar; + return out; } -void LorentzVector::boost(double b_x, double b_y, double b_z) +LorentzVector operator*(const LorentzVector& lvec, double scalar) { - double b2 = b_x * b_x + b_y * b_y + b_z * b_z; - double gamma = 1.0 / sqrt(1.0 - b2); - double bp = b_x * getX() + b_y * getY() + b_z * getZ(); - double gamma2 = b2 > 0 ? (gamma - 1.0)/b2 : 0.0; - - setX(getX() + gamma2 * bp * b_x + gamma * b_x * getT()); - setY(getY() + gamma2 * bp * b_y + gamma * b_y * getT()); - setZ(getZ() + gamma2 * bp * b_z + gamma * b_z * getT()); - setT(gamma*(getT() + bp)); + return scalar * lvec; } - } // namespace pxl +#undef EPSILON diff --git a/core/src/MessageDispatcher.cc b/core/src/MessageDispatcher.cc index d33b622b429c383f956fc7b0b73d2bd945513b3e..83718c09b0df83d34a475a93758b5e35185334fc 100644 --- a/core/src/MessageDispatcher.cc +++ b/core/src/MessageDispatcher.cc @@ -1,13 +1,13 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- #include "pxl/core/MessageDispatcher.hh" -#include "pxl/core/logging.hh" +#include "pxl/core/Logging.hh" #include @@ -17,14 +17,13 @@ namespace pxl { - MessageHandler::~MessageHandler() { - MessageDispatcher::instance().unsubscribe(this); + MessageDispatcher::instance().unsubscribe(this); } -MessageDispatcher::MessageDispatcher() : - lastId(0) +MessageDispatcher::MessageDispatcher() + : lastId(0) { } @@ -34,109 +33,107 @@ MessageDispatcher::~MessageDispatcher() MessageDispatcher& MessageDispatcher::instance() { - static MessageDispatcher f; - return f; + static MessageDispatcher f; + return f; } -size_t MessageDispatcher::publish(std::string mid, const Variant ¶meter) +size_t MessageDispatcher::publish(std::string mid, const Variant& parameter) { - size_t id = getId(mid); - publish(id, parameter); - return id; + size_t id = getId(mid); + publish(id, parameter); + return id; } -void MessageDispatcher::publish(size_t messageid, const Variant ¶meter) +void MessageDispatcher::publish(size_t messageid, const Variant& parameter) { - subscriptions_map_t::iterator iMap = subscriptions.find(messageid); - if (iMap == subscriptions.end()) - return; - - handler_vector_t::iterator iVec = (*iMap).second.begin(); - handler_vector_t::iterator iEnd = (*iMap).second.end(); - for (; iVec != iEnd; iVec++) - { - (*iVec)->handleMessage(messageid, parameter); - } + subscriptions_map_t::iterator iMap = subscriptions.find(messageid); + if (iMap == subscriptions.end()) + return; + + handler_vector_t::iterator iVec = (*iMap).second.begin(); + handler_vector_t::iterator iEnd = (*iMap).second.end(); + for (; iVec != iEnd; iVec++) + { + (*iVec)->handleMessage(messageid, parameter); + } } -size_t MessageDispatcher::subscribe(std::string mid, MessageHandler *handler) +size_t MessageDispatcher::subscribe(std::string mid, MessageHandler* handler) { - size_t id = getId(mid); - subscribe(id, handler); - return id; - + size_t id = getId(mid); + subscribe(id, handler); + return id; } -void MessageDispatcher::subscribe(size_t messageid, MessageHandler *handler) +void MessageDispatcher::subscribe(size_t messageid, MessageHandler* handler) { - handler_vector_t &v = subscriptions[messageid]; - if (std::find(v.begin(), v.end(), handler) == v.end()) - { - PXL_LOG_INFO << "New subsciber to: " << messageid; - v.push_back(handler); - } + handler_vector_t& v = subscriptions[messageid]; + if (std::find(v.begin(), v.end(), handler) == v.end()) + { + PXL_LOG_INFO << "New subsciber to: " << messageid; + v.push_back(handler); + } } -size_t MessageDispatcher::unsubscribe(std::string mid, MessageHandler *handler) +size_t MessageDispatcher::unsubscribe(std::string mid, MessageHandler* handler) { - size_t id = getId(mid); - unsubscribe(id, handler); - return id; + size_t id = getId(mid); + unsubscribe(id, handler); + return id; } -void MessageDispatcher::unsubscribe(size_t messageid, MessageHandler *handler) +void MessageDispatcher::unsubscribe(size_t messageid, MessageHandler* handler) { - PXL_LOG_INFO << "Request unsubscribe"; - handler_vector_t &v = subscriptions[messageid]; - v.erase(std::remove(v.begin(), v.end(), handler), v.end()); + PXL_LOG_INFO << "Request unsubscribe"; + handler_vector_t& v = subscriptions[messageid]; + v.erase(std::remove(v.begin(), v.end(), handler), v.end()); } -void MessageDispatcher::unsubscribe(MessageHandler *handler) +void MessageDispatcher::unsubscribe(MessageHandler* handler) { - subscriptions_map_t::iterator i = subscriptions.begin(); - subscriptions_map_t::iterator end = subscriptions.end(); - for (; i != end; i++) - { - handler_vector_t &v = i->second; - v.erase(std::remove(v.begin(), v.end(), handler), v.end()); - } + subscriptions_map_t::iterator i = subscriptions.begin(); + subscriptions_map_t::iterator end = subscriptions.end(); + for (; i != end; i++) + { + handler_vector_t& v = i->second; + v.erase(std::remove(v.begin(), v.end(), handler), v.end()); + } } -size_t MessageDispatcher::getId(const std::string &name) +size_t MessageDispatcher::getId(const std::string& name) { - std::map::iterator i = ids.find(name); - if (i != ids.end()) - { - return i->second; - } - else - { - lastId++; - PXL_LOG_INFO << "New message id: '" << name << "' -> " << lastId; - ids[name] = lastId; - return lastId; - } + std::map::iterator i = ids.find(name); + if (i != ids.end()) + { + return i->second; + } + else + { + lastId++; + PXL_LOG_INFO << "New message id: '" << name << "' -> " << lastId; + ids[name] = lastId; + return lastId; + } } -std::string MessageDispatcher::getName(const size_t &mid) +std::string MessageDispatcher::getName(const size_t& mid) { - static std::string emptyString = ""; + static std::string emptyString = ""; - for (std::map::iterator i = ids.begin(); i != ids.end(); ++i) - { - if (i->second == mid) - { - return i->first; - } - } + for (std::map::iterator i = ids.begin(); i != ids.end(); ++i) + { + if (i->second == mid) + { + return i->first; + } + } - return emptyString; + return emptyString; } const std::map MessageDispatcher::getIds() const { - return ids; + return ids; } } // namespace pxl - diff --git a/core/src/NamedTMPFile.cc b/core/src/NamedTMPFile.cc deleted file mode 100644 index 33a9f04aee211c91767a1659200c486dfc770f73..0000000000000000000000000000000000000000 --- a/core/src/NamedTMPFile.cc +++ /dev/null @@ -1,56 +0,0 @@ -#include "pxl/core/NamedTMPFile.hh" - -#include -#include - -#include - -namespace pxl -{ - -#ifdef WIN32 - #include - #include - #include - #include - #include - #include - int mkstemp(char *tmpl) -{ - int ret=-1; - mktemp(tmpl); ret=open(tmpl,O_RDWR|O_BINARY|O_CREAT|O_EXCL|_O_SHORT_LIVED, _S_IREAD|_S_IWRITE); - return ret; -} -#endif - - - -NamedTMPFile::~NamedTMPFile() -{ - remove(_filename.c_str()); -} - -NamedTMPFile::NamedTMPFile() -{ - #ifdef WIN32 - char template_name[]="PXL_TMPFILE_XXXXXX"; - #else - char template_name[]="/tmp/cmguiXXXXXX"; - #endif - int i = mkstemp(template_name); - - if (!i) - { - throw std::runtime_error("Cannot create tmpfile"); - } - close(i); - _filename = template_name; -} - -// holds a tempfile and clears it up on destruction -const std::string& NamedTMPFile::getName() -{ - return _filename; -} - -} diff --git a/core/src/Object.cc b/core/src/Object.cc index eaa87947587f5f340d874387e83c978b82af920e..e8c15ff54cf204c936a4735b3ea3822b1c3d8d30 100644 --- a/core/src/Object.cc +++ b/core/src/Object.cc @@ -1,47 +1,58 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- #include "pxl/core/Object.hh" -#include "pxl/core/ObjectFactory.hh" +#include "pxl/core/Logging.hh" -namespace pxl { +#undef PXL_LOG_MODULE_NAME +#define PXL_LOG_MODULE_NAME "pxl::Object" -void Object::serialize(const OutputStream &out) const +namespace pxl { - Relative::serialize(out); - out.writeBool(_locked); - out.writeInt(_workflag); - UserRecordHelper::serialize(out); -} -void Object::deserialize(const InputStream &in) +Object::~Object() { - Relative::deserialize(in); - in.readBool(_locked); - in.readInt(_workflag); - UserRecordHelper::deserialize(in); + // should not throw exception in destructor + if (_owner) + { + PXL_LOG_ERROR << "Error in ~Object(): Object derivative must be deleted by ObjectOwner " + "to guarantee safe object handling!"; + } } +void Object::serialize(const OutputStream& out) const +{ + Serializable::serialize(out); + out.writeString(_name); + _records.serialize(out); } -std::ostream& pxl::Object::print(int level, std::ostream& os, int pan) const + +void Object::deserialize(const InputStream& in) { - printPan1st(os, pan); - os << "pxl::Object with name: " << getName() << "\n"; - if (level>0) printContent(level, os, pan); - return os; + Serializable::deserialize(in); + in.readString(_name); + _records.deserialize(in); } -std::ostream& pxl::Object::printContent(int level, std::ostream& os, int pan) const +std::ostream& Object::print(int level, std::ostream& os, int pan) const { - os << "WorkFlag: " << _workflag << ", locked: " << _locked; - os << std::endl; - getUserRecords().print(level, os, pan); - return os; + os << "pxl::Object with name: " << getName() << "\n"; + if (level > 0) + { + printContent(level, os, pan); + } + return os; } +std::ostream& Object::printContent(int level, std::ostream& os, int pan) const +{ + // _records.print(level, os, pan); + return os; +} +} // namespace pxl diff --git a/core/src/ObjectFactory.cc b/core/src/ObjectFactory.cc deleted file mode 100644 index c7c1998c82a483195605fd1cf5d1b6263cdc959c..0000000000000000000000000000000000000000 --- a/core/src/ObjectFactory.cc +++ /dev/null @@ -1,60 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include "pxl/core/ObjectFactory.hh" -#include "pxl/core/logging.hh" - -#undef PXL_LOG_MODULE_NAME -#define PXL_LOG_MODULE_NAME "pxl::ObjectFactory" - -namespace pxl -{ - -ObjectFactory::ObjectFactory() -{ -} - -ObjectFactory& ObjectFactory::instance() -{ - static ObjectFactory f; - return f; -} - -Serializable *ObjectFactory::create(const Id& id) -{ - std::map::iterator result; - result = _Producers.find(id); - if (result == _Producers.end()) - return 0; - else - return (*result).second->create(); -} - -void ObjectFactory::registerProducer(const Id& id, - const ObjectProducerInterface* producer) -{ - PXL_LOG_INFO << "register object producer for " << id; - _Producers[id] = producer; -} - -void ObjectFactory::unregisterProducer(const ObjectProducerInterface* producer) -{ - std::map::iterator i; - for (i = _Producers.begin(); i != _Producers.end(); i++) - { - if (i->second == producer) - { - PXL_LOG_INFO << "unregister object producer for " << i->first; - _Producers.erase(i); - return; - } - } -} - -} // namespace pxl - diff --git a/core/src/ObjectManager.cc b/core/src/ObjectManager.cc deleted file mode 100644 index 15c2d23d32f833b46aac182c19175e7062c1a007..0000000000000000000000000000000000000000 --- a/core/src/ObjectManager.cc +++ /dev/null @@ -1,11 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include "pxl/core/ObjectManager.hh" - - diff --git a/core/src/ObjectOwner.cc b/core/src/ObjectOwner.cc index 143baebb1624c6e175931799780e7e5a91f7cd32..57ad4a75aee733d780da7ebc1211504506b4e07d 100644 --- a/core/src/ObjectOwner.cc +++ b/core/src/ObjectOwner.cc @@ -1,18 +1,19 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- #include -#include "pxl/core/Relative.hh" +#include "pxl/core/Logging.hh" +#include "pxl/core/Object.hh" #include "pxl/core/ObjectOwner.hh" #include "pxl/core/Relations.hh" -#include "pxl/core/logging.hh" -#include "pxl/core/ObjectFactory.hh" +#include "pxl/core/Relative.hh" +#include "pxl/core/SerializableFactory.hh" #undef PXL_LOG_MODULE_NAME #define PXL_LOG_MODULE_NAME "pxl::ObjectOwner" @@ -20,330 +21,365 @@ namespace pxl { -void ObjectOwner::init(const ObjectOwner& original) +void ObjectOwner::init(const ObjectOwner& owner) { - // copy objects: loop in STL style - for (const_iterator iter = original._container.begin(); iter - != original._container.end(); iter++) - { - - Relative* pOld = *iter; - Relative* pNew = dynamic_cast(pOld->clone()); - - insert(pNew); - - std::map::iterator insertPos = - _copyHistory.lower_bound(pOld->id()); - if (insertPos == _copyHistory.end() || insertPos->first != pOld->id()) - _copyHistory.insert(insertPos, - std::map::iterator::value_type(pOld->id(), pNew)); - else - insertPos->second = pNew; - } - - // FIXME: possibly inefficient, might be done all in one loop - // redirect relations: loop in PTL style - for (const_iterator iter = original._container.begin(); iter - !=original._container.end(); iter++) - { - Relative* pOld = *iter; - Relative* pNew = 0; - std::map::const_iterator found = _copyHistory.find(pOld->id()); - if (found != _copyHistory.end()) - pNew = found->second; - - // mother relations - for (Relations::const_iterator iter = pOld->getMotherRelations().begin(); iter!=pOld->getMotherRelations().end(); ++iter) - { - Relative* pOldRel = *iter; - Relative* pNewRel = 0; - std::map::const_iterator foundRel = - _copyHistory.find(pOldRel->id()); - if (foundRel != _copyHistory.end()) - pNewRel = foundRel->second; - - if (pOldRel) - { - if (pNewRel) - pNew->linkMother(pNewRel); - else - PXL_LOG_WARNING << "ObjectOwner::init(const ObjectOwner&): WARNING: some original objects had relations to objects of other owners."; - - } - else - PXL_LOG_WARNING << "ObjectOwner::init(const ObjectOwner&): WARNING: some originally related objects no longer exist."; - } - - // daughter relations - // have been set automatically above - } - - // redirect index: - for (std::map::const_iterator iter = original._index.begin(); iter - !=original._index.end(); ++iter) - { - - Relative* pOld = iter->second; - - Relative* pNew = 0; - std::map::const_iterator found = _copyHistory.find(pOld->id()); - if (found != _copyHistory.end()) - pNew = found->second; - - if (pNew) - _index.insert(std::map::const_iterator::value_type(iter->first, - pNew)); - else - PXL_LOG_WARNING << "pxl::ObjectOwner::ObjectOwner(...): WARNING: some original indices pointed to objects of other owners."; - } + // copy objects + for (objects_t::const_iterator iter = owner._objects.begin(); iter != owner._objects.end(); + iter++) + { + Object* pOld = *iter; + Object* pNew = dynamic_cast(pOld->clone()); + + insertObject(pNew); + + // look for pOld to add to copy history associated to pNew + std::map::iterator insertPos = _copyHistory.lower_bound(pOld->getId()); + if (insertPos == _copyHistory.end() || insertPos->first != pOld->getId()) + { + // first time pOld is seen, so add it with the old id + _copyHistory.insert(insertPos, std::pair(pOld->getId(), pNew)); + } + else + { + // pOld already seen, update the object to pNew + insertPos->second = pNew; + } + } + + // redirect relations + for (objects_t::const_iterator objIter = owner._objects.begin(); + objIter != owner._objects.end(); objIter++) + { + Object* objOld = *objIter; + Relative* relOld = dynamic_cast(objOld); + if (!relOld) + { + continue; + } + + Relative* relNew = 0; + std::map::const_iterator found = _copyHistory.find(objOld->getId()); + if (found != _copyHistory.end()) + { + relNew = dynamic_cast(found->second); + } + + // mother relations + for (Relations::relatives_t::const_iterator motherIter + = relOld->getMotherRelations().begin(); + motherIter != relOld->getMotherRelations().end(); ++motherIter) + { + Relative* motherOld = *motherIter; + std::map::const_iterator foundRel = _copyHistory.find(motherOld->getId()); + if (foundRel == _copyHistory.end()) + { + PXL_LOG_WARNING << "ObjectOwner::init(const ObjectOwner&): WARNING: some " + "original objects had relations to objects of other owners."; + } + else + { + Relative* motherNew = dynamic_cast(foundRel->second); + relNew->linkMother(motherNew); + } + } + + // daughter relations + // have been set automatically above + } + + // redirect index + for (index_t::const_iterator it = owner._index.begin(); it != owner._index.end(); ++it) + { + + Object* pOld = it->second; + + Object* pNew = 0; + std::map::const_iterator found = _copyHistory.find(pOld->getId()); + if (found != _copyHistory.end()) + { + pNew = found->second; + } + + if (pNew) + { + _index.insert(index_t::const_iterator::value_type(it->first, pNew)); + } + else + { + PXL_LOG_WARNING << "pxl::ObjectOwner::ObjectOwner(...): WARNING: some original indices " + "pointed to objects of other owners."; + } + } } -void ObjectOwner::clearContainer() +void ObjectOwner::serialize(const OutputStream& out) const { - for (iterator iter = _container.begin(); iter != _container.end(); iter++) - { - (*iter)->_refObjectOwner=0; - delete (*iter); - } - _container.clear(); - _copyHistory.clear(); - _index.clear(); - _uuidSearchMap.clear(); + // write the size which serves as a marker for forward seeking + out.writeUInt32(size()); + + for (objects_t::const_iterator it = begin(); it != end(); ++it) + { + (*it)->serialize(out); + + // serialize relations explicitly + Relative* rel = dynamic_cast(*it); + if (rel) + { + rel->getDaughterRelations().serialize(out); + rel->getFlatRelations().serialize(out); + } + } + + // index + out.writeUInt32(_index.size()); + for (index_t::const_iterator it = _index.begin(); it != _index.end(); ++it) + { + out.writeString(it->first); + (it->second->getId()).serialize(out); + } + + // write the size again to have a marker for backward seeking + out.writeUInt32(size()); } -void ObjectOwner::insert(Relative* item) +void ObjectOwner::deserialize(const InputStream& in) { - if (item->_refObjectOwner == this) - return; - if (item->_refObjectOwner) - throw std::runtime_error("Error in ObjectOwner::set: Object already has another object owner."); - item->_refObjectOwner = this; - _container.push_back(item); - _uuidSearchMap.insert(std::pair(item->getId(), item)); + /* Algorithm: + * a) deserialize all objects. those deserialize themselves, and their relations + * as the related objects' uuids. + * b) create temprorary id-object map within the same loop. + * (no need (!) for orphan relations in this new algorithm) + * c) recreate relations (fetching objects from map) + * d) fill index (fetching objects from map) + * [e) shall the CopyHistory be serialised/deserialised? this is hard since + * one would need to have all ObjectOwners in memory, ie the whole event, and do some + * explicit stuff afterwards.] + * no error handling at the moment + */ + + std::map objIdMap; + std::multimap daughterRelationsMap; + std::multimap motherRelationsMap; + std::multimap flatRelationsMap; + + uint32_t size = 0; + in.readUInt32(size); + for (unsigned int i = 0; i < size; ++i) + { + Id typeId(in); + // Contained object must be a Object derivative + Object* object = dynamic_cast(SerializableFactory::instance().create(typeId)); + object->deserialize(in); + insertObject(object); + objIdMap.insert(std::pair(object->getId(), object)); + + // from now on, we're only interrested in relations + Relative* rel = dynamic_cast(object); + if (!rel) + { + continue; + } + + uint32_t dsize = 0; + in.readUInt32(dsize); + for (int j = 0; j < dsize; ++j) + { + Id did(in); + daughterRelationsMap.insert(std::pair(rel, did)); + } + + uint32_t fsize = 0; + in.readUInt32(fsize); + for (int j = 0; j < fsize; ++j) + { + Id fid(in); + flatRelationsMap.insert(std::pair(rel, fid)); + } + } + + // create links after all particles were inserted + for (std::multimap::const_iterator iter = daughterRelationsMap.begin(); + iter != daughterRelationsMap.end(); ++iter) + { + Relative* daughter = (Relative*)(objIdMap.find(iter->second)->second); + iter->first->linkDaughter(daughter); + } + + for (std::multimap::const_iterator iter = flatRelationsMap.begin(); + iter != flatRelationsMap.end(); ++iter) + { + Relative* target = (Relative*)(objIdMap.find(iter->second)->second); + iter->first->linkFlat(target); + } + + // create the index + in.readUInt32(size); + for (size_t i = 0; i < size; ++i) + { + std::string name; + in.readString(name); + Id id(in); + _index.insert(std::pair(name, objIdMap.find(id)->second)); + } } -void ObjectOwner::remove(Relative* item) +bool ObjectOwner::hasObject(const Object* obj) const { - if (item->_refObjectOwner != this) - { - PXL_LOG_WARNING << "Trying to remove Relative from object owner which has different object owner."; - return; - } - - // search & remove possible indices (multiple occurrences possible!) - for (std::map::const_iterator iter = _index.begin(); iter != _index.end(); iter++) - { - if (item == iter->second) - _index.erase(iter->first); - } - - // search & remove possible copy history - for (std::map::const_iterator iter = _copyHistory.begin(); iter - != _copyHistory.end(); iter++) - { - - // FIXME: inefficient - if (item == iter->second) - { - _copyHistory.erase(iter->first); - break; // multiple occurrences *not* possible! - } - } - - _uuidSearchMap.erase(item->getId()); - - item->_refObjectOwner = 0; - for (iterator iter = _container.begin(); iter != _container.end(); iter++) - { - - if (item == (*iter)) - { - delete *iter; - _container.erase(iter); - break; - } - } - + return obj->getOwner() == this; } -void ObjectOwner::take(Relative* item) +void ObjectOwner::insertObject(Object* obj) { - if (item->_refObjectOwner != this) - { - PXL_LOG_WARNING << "Trying to take Relative from object owner which has different object owner."; - return; - } - - // search & remove possible indices (multiple occurrences possible!) - for (std::map::const_iterator iter = _index.begin(); iter != _index.end(); iter++) - { - if (item == iter->second) - _index.erase(iter->first); - } - - // search & remove possible copy history - for (std::map::const_iterator iter = _copyHistory.begin(); iter - != _copyHistory.end(); iter++) - { - if (item == iter->second) - { - _copyHistory.erase(iter->first); - break; // multiple occurrences *not* possible! - } - } - - _uuidSearchMap.erase(item->getId()); - - item->_refObjectOwner=0; - for (iterator iter = _container.begin(); iter != _container.end(); iter++) - { - - if (item == (*iter)) - { - _container.erase(iter); - break; - } - } - + // already held by this owner? + if (obj->getOwner() == this) + { + return; + } + + // already held by other owner? + if (obj->getOwner()) + { + throw std::runtime_error("Error in ObjectOwner::set: Object already has another object " + "owner."); + } + + _objects.push_back(obj); + obj->_owner = this; + _uuidSearchMap.insert(std::pair(obj->getId(), obj)); } -bool ObjectOwner::has(const Relative* item) const +void ObjectOwner::takeObject(Object* obj) { - return item->_refObjectOwner == this; + // already held by this owner? + if (obj->getOwner() == this) + { + return; + } + + // already held by other owner? + if (obj->getOwner()) + { + // remove by current owner with destruct set to false + obj->getOwner()->removeObject(obj, false); + } + + insertObject(obj); } -bool ObjectOwner::setIndexEntry(const std::string& key, Relative* obj, -bool overwrite) +bool ObjectOwner::indexObject(Object* obj, const std::string& key, bool overwrite) { - if (!key.length() || !has(obj)) - { - if (!key.length()) - PXL_LOG_ERROR << "Error in setting index: key has zero length!"; - else - PXL_LOG_ERROR << "Error in setting index: Object does not belong to ObjectOwner."; - return false; - } - - std::map::iterator insertPos = _index.lower_bound(key); - if (insertPos == _index.end() || insertPos->first != key) - _index.insert(insertPos, std::map::iterator::value_type(key, obj)); - else - { - if (overwrite) - insertPos->second = obj; - else - { - PXL_LOG_WARNING << "Warning in setting Index: Key " << key << " already present and bool 'overwrite' set to false."; - return false; - } - } - return true; + if (key.empty()) + { + PXL_LOG_ERROR << "Cannot index object with empty key."; + return false; + } + + if (!hasObject(obj)) + { + PXL_LOG_ERROR << "Cannot index object that is not held by this onwer."; + return false; + } + + index_t::iterator insertPos = _index.lower_bound(key); + if (insertPos == _index.end() || insertPos->first != key) + { + _index.insert(insertPos, std::pair(key, obj)); + } + else + { + if (overwrite) + { + insertPos->second = obj; + } + else + { + PXL_LOG_WARNING << "Cannot overwrite index with key " << key << " when 'overwrite' is" + << "set to false."; + return false; + } + } + + return true; } - -void ObjectOwner::serialize(const OutputStream &out) const +void ObjectOwner::removeObject(Object* obj, bool destruct) { - // contents of vector - out.writeUnsignedInt(size()); - for (const_iterator iter = begin(); iter!=end(); ++iter) - { - (*iter)->serialize(out); - - //serialize relations explicitly - (*iter)->getMotherRelations().serialize(out); - (*iter)->getDaughterRelations().serialize(out); - (*iter)->getFlatRelations().serialize(out); - } - - // index - out.writeUnsignedInt(_index.size()); - for (std::map::const_iterator iter = _index.begin(); iter != _index.end(); ++iter) - { - out.writeString(iter->first); - (iter->second->id()).serialize(out); - } + if (obj->getOwner() != this) + { + PXL_LOG_WARNING << "Cannot remove Object which has different ObjectOwner."; + return; + } + + // remove possible indices + for (index_t::const_iterator it = _index.begin(); it != _index.end(); it++) + { + if (it->second == obj) + { + _index.erase(it->first); + } + } + + // remove possible copy history + for (std::map::const_iterator it = _copyHistory.begin(); it != _copyHistory.end(); + it++) + { + if (it->second == obj) + { + _copyHistory.erase(it->first); + break; + } + } + + // erase the uuid search map entry + _uuidSearchMap.erase(obj->getId()); + + // reset the owner + obj->_owner = 0; + + // remove the actual object + for (objects_t::iterator iter = _objects.begin(); iter != _objects.end(); iter++) + { + if ((*iter) == obj) + { + _objects.erase(iter); + if (destruct) + { + delete obj; + } + break; + } + } +} +void ObjectOwner::clearObjects() +{ + for (objects_t::iterator iter = _objects.begin(); iter != _objects.end(); iter++) + { + (*iter)->_owner = 0; + delete (*iter); + } + + _objects.clear(); + _copyHistory.clear(); + _index.clear(); + _uuidSearchMap.clear(); } -void ObjectOwner::deserialize(const InputStream &in) +std::ostream& ObjectOwner::print(int level, std::ostream& os, int pan) const { - /* Algorithm: - * a) deserialize all objects. those deserialize themselves, and their relations - * as the related objects' uuids. - * b) create temprorary id-object map within the same loop. - * (no need (!) for orphan relations in this new algorithm) - * c) recreate relations (fetching objects from map) - * d) fill index (fetching objects from map) - * [e) shall the CopyHistory be serialised/deserialised? this is hard since - * one would need to have all ObjectOwners in memory, ie the whole event, and do some - * explicit stuff afterwards.] - * no error handling at the moment - */ - - std::map objIdMap; - std::multimap daughterRelationsMap; - std::multimap motherRelationsMap; - std::multimap flatRelationsMap; - - unsigned int size = 0; - in.readUnsignedInt(size); - for (unsigned int i=0; i(ObjectFactory::instance().create(typeId)); - object->deserialize(in); - insert(object); - objIdMap.insert(std::pair(object->id(), object)); - - int msize = 0; - in.readInt(msize); - for (int j=0; j(object, id)); - } - - int dsize = 0; - in.readInt(dsize); - for (int j=0; j(object, id)); - } - int fsize = 0; - in.readInt(fsize); - for (int j=0; j(object, id)); - } - - } - - for (std::multimap::const_iterator iter = daughterRelationsMap.begin(); - iter!=daughterRelationsMap.end(); ++iter) - { - Relative* target = objIdMap.find(iter->second)->second; - iter->first->linkDaughter(target); - } - - for (std::multimap::const_iterator iter = flatRelationsMap.begin(); - iter!=flatRelationsMap.end(); ++iter) - { - Relative* target = objIdMap.find(iter->second)->second; - iter->first->linkFlat(target); - } - - in.readUnsignedInt(size); - - for (unsigned int i=0; i(name, objIdMap.find(id)->second)); - } + os << "ObjectOwner:" << std::endl; + + if (level > 0) + { + // getUserRecords().print(level, os, pan); + } + + for (objects_t::const_iterator iter = begin(); iter != end(); ++iter) + { + (*iter)->print(level, os, pan); + } + + return os; } } // namespace pxl diff --git a/core/src/OutputFile.cc b/core/src/OutputFile.cc deleted file mode 100644 index c14a5110c524df5f4cd6a767dc1f8d7b3f1da39a..0000000000000000000000000000000000000000 --- a/core/src/OutputFile.cc +++ /dev/null @@ -1,64 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include "pxl/core/OutputFile.hh" - -#include - -namespace pxl -{ -OutputFile::OutputFile(const std::string& filename, size_t maxBlockSize, - size_t maxNObjects) : - OutputHandler(maxBlockSize, maxNObjects), _stream(filename, OpenWrite), _writer( - _stream) -{ - if (_stream.isGood() == false) - throw std::runtime_error( - "OutputFile: " + filename + " could not be opened."); -} - -OutputFile::~OutputFile() -{ - close(); -} - -void OutputFile::open(const std::string& filename) -{ - _stream.open(filename.c_str(), OpenWrite); - if (_stream.isGood() == false) - throw std::runtime_error( - "OutputFile: " + filename + " could not be opened."); -} - -void OutputFile::close() -{ - finish(); - _stream.close(); -} - -ChunkWriter& OutputFile::getChunkWriter() -{ - return _writer; -} - -void OutputFile::setCompressionMode(int compressionMode) -{ - _writer.setCompressionMode(compressionMode); -} - -OutputFile::OutputFile(const OutputFile& original) : - _stream(), _writer(_stream) -{ -} - -OutputFile& OutputFile::operator=(const OutputFile& other) -{ - return *this; -} - -} diff --git a/core/src/OutputHandler.cc b/core/src/OutputHandler.cc deleted file mode 100644 index c0c5d35d22f1c7d0807c9bab7e3647b3546e1fde..0000000000000000000000000000000000000000 --- a/core/src/OutputHandler.cc +++ /dev/null @@ -1,70 +0,0 @@ -//------------------------------------------- -// Project: Physics eXtension Library (PXL) - -// http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - -// RWTH Aachen, Germany - -// Licensed under a LGPL-2 or later license - -//------------------------------------------- - -#include "pxl/core/OutputHandler.hh" -#include "pxl/core/Id.hh" -#include "pxl/core/logging.hh" - -#undef PXL_LOG_MODULE_NAME -#define PXL_LOG_MODULE_NAME "pxl::OutputHandler" - -namespace pxl -{ - - -OutputHandler::OutputHandler(size_t maxSize, size_t maxNObjects) : - _maxSize(maxSize), _newFileSection(true), _maxNObjects(maxNObjects), _nObjects( - 0) -{ -} - -OutputHandler::~OutputHandler() -{ -} - -/// Use this method to write an information string describing the new event. Otherwise, this method need not necessarily be used. -bool OutputHandler::newFileSection(const std::string& info) -{ - if (!_newFileSection) - { - PXL_LOG_ERROR << "Finish the current event first."; - return false; - } - getChunkWriter().newFileSection(info); - _newFileSection = false; - return true; -} - -/// Use this method to write out a block to file. This method is not needed if you use the writeEvent-method. -bool OutputHandler::writeStream(const std::string& info) -{ - if (_newFileSection) - { - getChunkWriter().newFileSection(""); - _newFileSection = false; - } - getChunkWriter().newBlock(); - return getChunkWriter().write(info); -} - -/// Use this method to write out a block to disk and finish the current event. -bool OutputHandler::writeFileSection(const std::string& info) -{ - if (_newFileSection) - { - getChunkWriter().newFileSection(""); - _newFileSection = false; - } - getChunkWriter().newBlock(); - getChunkWriter().write(info); - _newFileSection = true; - _nObjects = 0; // reset number of objects - return getChunkWriter().endFileSection(); -} - -} //namespace pxl diff --git a/core/src/PluginManager.cc b/core/src/PluginManager.cc index c3cc901b2178a2ac853ddc52423a6aa014471050..331ac165281c40317fd913f609178004cc831d38 100644 --- a/core/src/PluginManager.cc +++ b/core/src/PluginManager.cc @@ -1,29 +1,29 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- -#include "pxl/core/macros.hh" -#include "pxl/core/logging.hh" #include "pxl/core/PluginManager.hh" #include "pxl/core/Configuration.hh" +#include "pxl/core/Logging.hh" +#include "pxl/core/Macros.hh" #ifdef WIN32 #define WIN32_LEAN_AND_MEAN #define WIN32_EXTRA_LEAN #include #else -#include #include +#include #endif -#include +#include "string.h" #include +#include #include -#include "string.h" #ifdef HAVE_CONFIG_H #include "config.h" @@ -39,30 +39,32 @@ const char PXL_PLUGIN_EXT[] = ".so"; const char HOME_ENV[] = "HOME"; const char PATH_SEPERATOR[] = ":"; #ifdef PXL_PLUGIN_LIBEXEC_DIR - static std::string DEFAULT_PLUGIN_DIR = STR(PXL_PLUGIN_LIBEXEC_DIR); +static std::string DEFAULT_PLUGIN_DIR = STR(PXL_PLUGIN_LIBEXEC_DIR); #else - static std::string DEFAULT_PLUGIN_DIR; +static std::string DEFAULT_PLUGIN_DIR; #endif #endif const char PXL_PLUGIN_DIR[] = "/plugins"; -const char PXL_DIR[] = "/.pxl-" PXL_LIB_VERSION; +const char PXL_DIR[] = "/.pxl-" PXL_VERSION_LIB; #ifdef WIN32 BOOL WINAPI DllMain(HINSTANCE hinstDll, DWORD reason, LPVOID reseerved) { - if (reason == DLL_PROCESS_ATTACH) - { - const size_t size = 1024; - TCHAR buffer[size]; - GetModuleFileName(hinstDll, buffer, size); - DEFAULT_PLUGIN_DIR = buffer; - std::string::size_type r = DEFAULT_PLUGIN_DIR.find_last_of('\\'); - if (r != std::string::npos) - DEFAULT_PLUGIN_DIR.resize(r); - } - - return TRUE; + if (reason == DLL_PROCESS_ATTACH) + { + const size_t size = 1024; + TCHAR buffer[size]; + GetModuleFileName(hinstDll, buffer, size); + DEFAULT_PLUGIN_DIR = buffer; + std::string::size_type r = DEFAULT_PLUGIN_DIR.find_last_of('\\'); + if (r != std::string::npos) + { + DEFAULT_PLUGIN_DIR.resize(r); + } + } + + return TRUE; } #endif @@ -72,273 +74,285 @@ BOOL WINAPI DllMain(HINSTANCE hinstDll, DWORD reason, LPVOID reseerved) namespace pxl { - PluginManager::PluginManager() { } PluginManager::~PluginManager() { - shutdown(); + shutdown(); } -PluginManager &PluginManager::instance() +PluginManager& PluginManager::instance() { - static PluginManager manager; - return manager; + static PluginManager manager; + return manager; } -void PluginManager::loadConfiguration(const std::string &filename) +void PluginManager::loadConfiguration(const std::string& filename) { - std::ifstream file(filename.c_str()); - - std::string pluginname; - while (std::getline(file, pluginname)) - { - std::string::size_type start = pluginname.find_first_not_of(" \t\r\n"); - if (pluginname.size() >= start && pluginname.at(start) != '#') - { - std::string::size_type end = pluginname.find_last_not_of(" \t\r\n"); - std::string filename = std::string(pluginname, start, end + 1); - try - { - loadPlugin(filename); - } catch (std::exception &e) - { - PXL_LOG_WARNING << "Exception in loadPlugin: " << e.what(); - } - } - } + std::ifstream file(filename.c_str()); + + std::string pluginname; + while (std::getline(file, pluginname)) + { + std::string::size_type start = pluginname.find_first_not_of(" \t\r\n"); + if (pluginname.size() >= start && pluginname.at(start) != '#') + { + std::string::size_type end = pluginname.find_last_not_of(" \t\r\n"); + std::string filename = std::string(pluginname, start, end + 1); + try + { + loadPlugin(filename); + } + catch (std::exception& e) + { + PXL_LOG_WARNING << "Exception in loadPlugin: " << e.what(); + } + } + } } std::string PluginManager::getUserPluginDirectory() { - std::string result; - const char* home = getenv(HOME_ENV); - if (home) - { - result.append(home); - result.append(PXL_DIR); - result.append(PXL_PLUGIN_DIR); - } - return result; + std::string result; + const char* home = getenv(HOME_ENV); + if (home) + { + result.append(home); + result.append(PXL_DIR); + result.append(PXL_PLUGIN_DIR); + } + return result; } std::string PluginManager::getDefaultPluginDirectory() { - return DEFAULT_PLUGIN_DIR; + return DEFAULT_PLUGIN_DIR; } void PluginManager::loadPlugins() { - PXL_LOG_INFO << "load plugins from installation path"; - if (DEFAULT_PLUGIN_DIR.size() > 0) - { - std::string filename_home(DEFAULT_PLUGIN_DIR); - filename_home.append(PXL_PLUGIN_DIR); - loadPluginsFromDirectory(filename_home); - } - - PXL_LOG_INFO << "load plugins from home path"; - std::string userPluginDirectory = getUserPluginDirectory(); - if (userPluginDirectory.size() > 0) - { - loadPluginsFromDirectory(userPluginDirectory); - } - - PXL_LOG_INFO << "load plugins from PXL_PLUGIN_PATH path"; - const char* pxlpluginpath = getenv("PXL_PLUGIN_PATH"); - if (pxlpluginpath) - { - std::vector paths; - explode(pxlpluginpath, paths, true, PATH_SEPERATOR); - for (size_t i = 0; i values = m.equal_range("pluginDirectory"); - - for (Configuration::multimapIterator iter = values.first; iter!=values.second; ++iter) - { - loadPluginsFromDirectory((*iter).second); - } - + PXL_LOG_INFO << "load plugins from installation path"; + if (DEFAULT_PLUGIN_DIR.size() > 0) + { + std::string filename_home(DEFAULT_PLUGIN_DIR); + filename_home.append(PXL_PLUGIN_DIR); + loadPluginsFromDirectory(filename_home); + } + + PXL_LOG_INFO << "load plugins from home path"; + std::string userPluginDirectory = getUserPluginDirectory(); + if (userPluginDirectory.size() > 0) + { + loadPluginsFromDirectory(userPluginDirectory); + } + + PXL_LOG_INFO << "load plugins from PXL_PLUGIN_PATH path"; + const char* pxlpluginpath = getenv("PXL_PLUGIN_PATH"); + if (pxlpluginpath) + { + std::vector paths; + explode(pxlpluginpath, paths, true, PATH_SEPERATOR); + for (size_t i = 0; i < paths.size(); i++) + { + PXL_LOG_INFO << " " << paths[i]; + loadPluginsFromDirectory(paths[i]); + } + } + PXL_LOG_INFO << "load plugins from configured paths"; + + Configuration pxlConfig = Configuration::instance(); + Configuration::multimapType m = pxlConfig.getSection("paths"); + std::pair values + = m.equal_range("pluginDirectory"); + + for (Configuration::multimapIterator iter = values.first; iter != values.second; ++iter) + { + loadPluginsFromDirectory((*iter).second); + } } #ifdef WIN32 -void PluginManager::loadPluginsFromDirectory(const std::string &directory) +void PluginManager::loadPluginsFromDirectory(const std::string& directory) { - std::string dir = directory + "\\*.dll"; - logger(LOG_LEVEL_INFO, "load plugins from directory ", directory); - - WIN32_FIND_DATA findFileData; - HANDLE hFind; - hFind = FindFirstFile(dir.c_str(), &findFileData); - - if (hFind == INVALID_HANDLE_VALUE) - { - logger(LOG_LEVEL_DEBUG, "directory ", directory, " does not exist."); - return; - } - - do - { - if ((findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) - { - std::string fname = findFileData.cFileName; - if (fname.size() <= sizeof(PXL_PLUGIN_EXT)) - continue; - - std::string ext = fname.substr(fname.size() - - sizeof(PXL_PLUGIN_EXT) + 1); - if (ext != PXL_PLUGIN_EXT) - continue; - - try - { - std::string filename(directory); - filename.append("/"); - filename.append(findFileData.cFileName); - loadSharedLibrary(filename); - } - catch (std::exception &e) - { - logger(LOG_LEVEL_WARNING, e.what()); - } - - } - } - while (FindNextFile(hFind, &findFileData) != 0); - - FindClose(hFind); + std::string dir = directory + "\\*.dll"; + logger(LOG_LEVEL_INFO, "load plugins from directory ", directory); + + WIN32_FIND_DATA findFileData; + HANDLE hFind; + hFind = FindFirstFile(dir.c_str(), &findFileData); + + if (hFind == INVALID_HANDLE_VALUE) + { + logger(LOG_LEVEL_DEBUG, "directory ", directory, " does not exist."); + return; + } + + do + { + if ((findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) + { + std::string fname = findFileData.cFileName; + if (fname.size() <= sizeof(PXL_PLUGIN_EXT)) + { + continue; + } + + std::string ext = fname.substr(fname.size() - sizeof(PXL_PLUGIN_EXT) + 1); + if (ext != PXL_PLUGIN_EXT) + { + continue; + } + + try + { + std::string filename(directory); + filename.append("/"); + filename.append(findFileData.cFileName); + loadSharedLibrary(filename); + } + catch (std::exception& e) + { + logger(LOG_LEVEL_WARNING, e.what()); + } + } + } while (FindNextFile(hFind, &findFileData) != 0); + + FindClose(hFind); } #else -void PluginManager::loadPluginsFromDirectory(const std::string &directory) +void PluginManager::loadPluginsFromDirectory(const std::string& directory) { - DIR *dir = opendir(directory.c_str()); - - if (dir == NULL) - { - PXL_LOG_DEBUG << "directory " << directory << " does not exist."; - return; - } - else{ - PXL_LOG_INFO << "load plugins from directory " << directory; - } - - struct dirent *dp = readdir(dir); - while (dp != NULL) - { - std::string fname = dp->d_name; - - if (fname.size() <= sizeof(PXL_PLUGIN_EXT)) { - dp = readdir(dir); - continue; - } - - std::string ext = fname.substr(fname.size() - sizeof(PXL_PLUGIN_EXT) + 1); - if (ext != PXL_PLUGIN_EXT) { - dp = readdir(dir); - continue; - } - - try - { - std::string filename(directory); - filename.append("/"); - filename.append(fname); - loadSharedLibrary(filename); - } catch (std::exception &e) - { - PXL_LOG_WARNING << "Exception in loadPlugin: " << e.what(); - } - - dp = readdir(dir); - } - - closedir(dir); + DIR* dir = opendir(directory.c_str()); + + if (dir == NULL) + { + PXL_LOG_DEBUG << "directory " << directory << " does not exist."; + return; + } + else + { + PXL_LOG_INFO << "load plugins from directory " << directory; + } + + struct dirent* dp = readdir(dir); + while (dp != NULL) + { + std::string fname = dp->d_name; + + if (fname.size() <= sizeof(PXL_PLUGIN_EXT)) + { + dp = readdir(dir); + continue; + } + + std::string ext = fname.substr(fname.size() - sizeof(PXL_PLUGIN_EXT) + 1); + if (ext != PXL_PLUGIN_EXT) + { + dp = readdir(dir); + continue; + } + + try + { + std::string filename(directory); + filename.append("/"); + filename.append(fname); + loadSharedLibrary(filename); + } + catch (std::exception& e) + { + PXL_LOG_WARNING << "Exception in loadPlugin: " << e.what(); + } + + dp = readdir(dir); + } + + closedir(dir); } #endif -void PluginManager::loadPlugin(const std::string &name) +void PluginManager::loadPlugin(const std::string& name) { - try - { - // try as is, full path - loadSharedLibrary(name); - return; - } catch (std::exception &e) - { - PXL_LOG_WARNING << "Exception in loadPlugin: " << e.what(); - } - - try - { - // make platform module name - // - std::string filename(name); - filename.append(PXL_PLUGIN_EXT); - loadSharedLibrary(filename); - return; - } catch (std::exception &e) - { - PXL_LOG_WARNING << "Exception in loadPlugin: " << e.what(); - } - - try - { - const char* pxlpluginpath = getenv("PXL_PLUGIN_PATH"); - if (pxlpluginpath) { - std::vector paths; - explode(pxlpluginpath, paths, true, PATH_SEPERATOR); - for (size_t i = 0; i < paths.size(); i++) - { - PXL_LOG_INFO << " " << paths[i]; - loadSharedLibrary(paths[i] + "/" + name + PXL_PLUGIN_EXT); - } - } - } catch (std::exception &e) - { - PXL_LOG_WARNING << "Exception in loadPlugin: " << e.what(); - } - - try - { - // load from home directory - std::string filename_home(getenv(HOME_ENV)); - filename_home.append(PXL_DIR); - filename_home.append(PXL_PLUGIN_DIR); - filename_home.append("/"); - filename_home.append(name); - filename_home.append(PXL_PLUGIN_EXT); - loadSharedLibrary(filename_home); - return; - } catch (std::exception &e) - { - PXL_LOG_WARNING << "Exception in loadPlugin: " << e.what(); - } - - try - { - // load from installation diretory - std::string filename_home(DEFAULT_PLUGIN_DIR); - filename_home.append(PXL_PLUGIN_DIR); - filename_home.append("/"); - filename_home.append(name); - filename_home.append(PXL_PLUGIN_EXT); - loadSharedLibrary(filename_home); - return; - } catch (std::exception &e) - { - PXL_LOG_WARNING << "Exception in loadPlugin: " << e.what(); - } - - throw std::runtime_error("plugin '" + name + "' could not be loaded."); + try + { + // try as is, full path + loadSharedLibrary(name); + return; + } + catch (std::exception& e) + { + PXL_LOG_WARNING << "Exception in loadPlugin: " << e.what(); + } + + try + { + // make platform module name + // + std::string filename(name); + filename.append(PXL_PLUGIN_EXT); + loadSharedLibrary(filename); + return; + } + catch (std::exception& e) + { + PXL_LOG_WARNING << "Exception in loadPlugin: " << e.what(); + } + + try + { + const char* pxlpluginpath = getenv("PXL_PLUGIN_PATH"); + if (pxlpluginpath) + { + std::vector paths; + explode(pxlpluginpath, paths, true, PATH_SEPERATOR); + for (size_t i = 0; i < paths.size(); i++) + { + PXL_LOG_INFO << " " << paths[i]; + loadSharedLibrary(paths[i] + "/" + name + PXL_PLUGIN_EXT); + } + } + } + catch (std::exception& e) + { + PXL_LOG_WARNING << "Exception in loadPlugin: " << e.what(); + } + + try + { + // load from home directory + std::string filename_home(getenv(HOME_ENV)); + filename_home.append(PXL_DIR); + filename_home.append(PXL_PLUGIN_DIR); + filename_home.append("/"); + filename_home.append(name); + filename_home.append(PXL_PLUGIN_EXT); + loadSharedLibrary(filename_home); + return; + } + catch (std::exception& e) + { + PXL_LOG_WARNING << "Exception in loadPlugin: " << e.what(); + } + + try + { + // load from installation diretory + std::string filename_home(DEFAULT_PLUGIN_DIR); + filename_home.append(PXL_PLUGIN_DIR); + filename_home.append("/"); + filename_home.append(name); + filename_home.append(PXL_PLUGIN_EXT); + loadSharedLibrary(filename_home); + return; + } + catch (std::exception& e) + { + PXL_LOG_WARNING << "Exception in loadPlugin: " << e.what(); + } + + throw std::runtime_error("plugin '" + name + "' could not be loaded."); } void PluginManager::shutdown() @@ -350,88 +364,85 @@ typedef int (*INITIALIZE_FUNC)(int major, int minor); #ifdef WIN32 std::string ErrorString(DWORD err) { - std::string Error; - LPTSTR s; - if (::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER - | FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0, (LPTSTR) &s, 0, NULL) - == 0) - { - // failed - Error = "unknown error"; - } - else - { - // success - Error = s; - ::LocalFree(s); - } - - return Error; + std::string Error; + LPTSTR s; + if (::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0, + (LPTSTR)&s, 0, NULL) + == 0) + { + // failed + Error = "unknown error"; + } + else + { + // success + Error = s; + ::LocalFree(s); + } + + return Error; } -void PluginManager::loadSharedLibrary(const std::string &filename) +void PluginManager::loadSharedLibrary(const std::string& filename) { - HMODULE handle = LoadLibrary(filename.c_str()); - if (handle == 0) - { - if (::GetLastError() == ERROR_MOD_NOT_FOUND) - return; - else - throw std::runtime_error( - "PluginManager: error loading module'" + filename - + "', " + ErrorString(::GetLastError())); - } - - INITIALIZE_FUNC init = (INITIALIZE_FUNC) GetProcAddress(handle, - "pxl_initialize_plugin"); - if (init == 0) - { - logger(LOG_LEVEL_WARNING, "plugin ", filename, - " has no 'pxl_initialize_plugin' function!"); - FreeLibrary(handle); - return; - } - - if (init(PXL_MAJOR_VERSION_VALUE, PXL_MINOR_VERSION_VALUE) != 0) - { - logger(LOG_LEVEL_WARNING, "plugin ", filename, - " was build with another version of pxl!"); - FreeLibrary(handle); - return; - } - - logger(LOG_LEVEL_DEBUG, "plugin ", filename, " loaded"); - + HMODULE handle = LoadLibrary(filename.c_str()); + if (handle == 0) + { + if (::GetLastError() == ERROR_MOD_NOT_FOUND) + { + return; + } + else + { + throw std::runtime_error("PluginManager: error loading module'" + filename + "', " + + ErrorString(::GetLastError())); + } + } + + INITIALIZE_FUNC init = (INITIALIZE_FUNC)GetProcAddress(handle, "pxl_initialize_plugin"); + if (init == 0) + { + logger(LOG_LEVEL_WARNING, "plugin ", filename, " has no 'pxl_initialize_plugin' function!"); + FreeLibrary(handle); + return; + } + + if (init(PXL_VERSION_MAJOR_INT, PXL_VERSION_MINOR_INT) != 0) + { + logger(LOG_LEVEL_WARNING, "plugin ", filename, " was build with another version of pxl!"); + FreeLibrary(handle); + return; + } + + logger(LOG_LEVEL_DEBUG, "plugin ", filename, " loaded"); } #else -void PluginManager::loadSharedLibrary(const std::string &filename) +void PluginManager::loadSharedLibrary(const std::string& filename) { - // void (*register_plugins)(std::map &); - - void *handle = dlopen(filename.c_str(), RTLD_LOCAL | RTLD_LAZY); - if (handle == 0) - throw std::runtime_error( - "PluginManager: error while loading module'" - + filename + "':" + dlerror()); - - INITIALIZE_FUNC init = (INITIALIZE_FUNC) dlsym(handle, - "pxl_initialize_plugin"); - if (init == 0) - { - PXL_LOG_WARNING << "plugin " << filename << " has no 'pxl_initialize_plugin' function!"; - dlclose(handle); - return; - } - - if (init(PXL_MAJOR_VERSION_VALUE, PXL_MINOR_VERSION_VALUE) != 0) - { - PXL_LOG_WARNING << "plugin " << filename << " was build with another version of pxl!"; - dlclose(handle); - return; - } - - PXL_LOG_INFO << "plugin " << filename << " loaded"; + void* handle = dlopen(filename.c_str(), RTLD_LOCAL | RTLD_LAZY); + if (handle == 0) + { + throw std::runtime_error( + "PluginManager: error while loading module'" + filename + "':" + dlerror()); + } + + INITIALIZE_FUNC init = (INITIALIZE_FUNC)dlsym(handle, "pxl_initialize_plugin"); + if (init == 0) + { + PXL_LOG_WARNING << "plugin " << filename << " has no 'pxl_initialize_plugin' function!"; + dlclose(handle); + return; + } + + if (init(PXL_VERSION_MAJOR_INT, PXL_VERSION_MINOR_INT) != 0) + { + PXL_LOG_WARNING << "plugin " << filename << " was build with another version of pxl!"; + dlclose(handle); + return; + } + + PXL_LOG_INFO << "plugin " << filename << " loaded"; } #endif diff --git a/core/src/Random.cc b/core/src/Random.cc index 17dccf3482c925c2549d0d081033a749f2c927b3..9e5630acec663bc884caa0ac2707192ef9684930 100644 --- a/core/src/Random.cc +++ b/core/src/Random.cc @@ -17,7 +17,7 @@ // Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, // Copyright (C) 2000 - 2003, Richard J. Wagner -// All rights reserved. +// All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions @@ -30,8 +30,8 @@ // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // -// 3. The names of its contributors may not be used to endorse or promote -// products derived from this software without specific prior written +// 3. The names of its contributors may not be used to endorse or promote +// products derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS @@ -58,392 +58,363 @@ // PXL. #include "pxl/core/Random.hh" -#include "pxl/core/RotationMatrix.hh" namespace pxl { Random::Random(const uint32& oneSeed) { - seed(oneSeed); + seed(oneSeed); } -Random::Random(uint32 * const bigSeed, const uint32 seedLength) +Random::Random(uint32* const bigSeed, const uint32 seedLength) { - seed(bigSeed, seedLength); + seed(bigSeed, seedLength); } Random::Random() { - seed(); + seed(); } double Random::rand() { - return double(randInt()) * (1.0 / 4294967295.0); + return double(randInt()) * (1.0 / 4294967295.0); } double Random::rand(const double& n) { - return rand() * n; + return rand() * n; } double Random::randExc() { - return double(randInt()) * (1.0 / 4294967296.0); + return double(randInt()) * (1.0 / 4294967296.0); } double Random::randExc(const double& n) { - return randExc() * n; + return randExc() * n; } double Random::randDblExc() { - return (double(randInt()) + 0.5) * (1.0 / 4294967296.0); + return (double(randInt()) + 0.5) * (1.0 / 4294967296.0); } double Random::randDblExc(const double& n) { - return randDblExc() * n; + return randDblExc() * n; } double Random::rand53() { - uint32 a = randInt() >> 5, b = randInt() >> 6; - return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0); // by Isaku Wada + uint32 a = randInt() >> 5, b = randInt() >> 6; + return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0); // by Isaku Wada } double Random::randNorm(const double& mean, const double& variance) { - // Return a real number from a normal (Gaussian) distribution with given - // mean and variance by Box-Muller method - double r = sqrt(-2.0 * log(1.0 - randDblExc())) * variance; - double phi = 2.0 * 3.14159265358979323846264338328 * randExc(); - return mean + r * cos(phi); + // Return a real number from a normal (Gaussian) distribution with given + // mean and variance by Box-Muller method + double r = sqrt(-2.0 * log(1.0 - randDblExc())) * variance; + double phi = 2.0 * 3.14159265358979323846264338328 * randExc(); + return mean + r * cos(phi); } double Random::randUniform(double min, double max) { - return min + (max - min) * this->rand(); + return min + (max - min) * this->rand(); } -///returns a rayleigh distributed value +/// returns a rayleigh distributed value double Random::randRayleigh(double sigma) { - return sigma * sqrt(-2.0 * log(1 - this->rand())); + return sigma * sqrt(-2.0 * log(1 - this->rand())); } double Random::randFisher(double k) { - return acos(1. + 1. / k * log(1 - rand() * (1 - exp(-2 * k)))); + return acos(1. + 1. / k * log(1 - rand() * (1 - exp(-2 * k)))); } -Basic3Vector Random::randFisher(const Basic3Vector &meanDirection, double kappa) +Vector3 Random::randUnitVectorOnSphere() { - double alpha = randFisher(kappa); - - Basic3Vector rotDirection= randUnitVectorOnSphere(); - Basic3Vector rotAxis = meanDirection.cross(rotDirection); - rotAxis.normalize(); - - RotationMatrix M(rotAxis, alpha); - Basic3Vector vnew = M * meanDirection; - - return vnew; -} - - -Basic3Vector Random::randFisher(const Basic3Vector *meanDirection, double kappa) -{ - return randFisher(*meanDirection, kappa); -} - - -Basic3Vector Random::randUnitVectorOnSphere() -{ - double z = this->randUniform(-1.0, 1.0); - double t = this->randUniform(-1.0 * M_PI, M_PI); - double r = sqrt(1 - z * z); - return Basic3Vector(r * cos(t), r * sin(t), z); + double z = this->randUniform(-1.0, 1.0); + double t = this->randUniform(-1.0 * M_PI, M_PI); + double r = sqrt(1 - z * z); + return Vector3(r * cos(t), r * sin(t), z); } double Random::randPowerLaw(double index, double min, double max) { - if ((min <= 0) || (max < min)) - { - throw std::runtime_error( - "Power law distribution only possible for 0 < min <= max"); - } - // index = -1 - if ((std::abs(index + 1.0)) < DBL_EPSILON) - { - double part1 = log(max); - double part2 = log(min); - return exp((part1 - part2) * this->rand() + part2); - } - else - { - double part1 = pow(max, index + 1); - double part2 = pow(min, index + 1); - double ex = 1 / (index + 1); - return pow((part1 - part2) * this->rand() + part2, ex); - } -} - -double Random::randBrokenPowerLaw(double index1, double index2, - double breakpoint, double min, double max) -{ - if ((min <= 0) || (max < min)) - { - throw std::runtime_error( - "Power law distribution only possible for 0 < min <= max"); - } - if (min >= breakpoint) - { - return this->randPowerLaw(index2, min, max); - } - else if (max <= breakpoint) - { - return this->randPowerLaw(index2, min, max); - } - else - { - double intPL1; - // check if index1 = -1 - if ((std::abs(index1 + 1.0)) < DBL_EPSILON) - { - intPL1 = log(breakpoint / min); - } - else - { - intPL1 = (pow(breakpoint, index1 + 1) - pow(min, index1 + 1)) - / (index1 + 1); - } - double intPL2; - // check if index2 = -1 - if ((std::abs(index2 + 1.0)) < DBL_EPSILON) - { - intPL2 = log(max / breakpoint) * pow(breakpoint, index1 - index2); - } - else - { - intPL2 = (pow(max, index2 + 1) - pow(breakpoint, index2 + 1)) - * pow(breakpoint, index1 - index2) / (index2 + 1); - } - if (this->rand() > intPL1 / (intPL1 + intPL2)) - return this->randPowerLaw(index2, breakpoint, max); - else - return this->randPowerLaw(index1, min, breakpoint); - } + if ((min <= 0) || (max < min)) + { + throw std::runtime_error("Power law distribution only possible for 0 < min <= max"); + } + // index = -1 + if ((std::abs(index + 1.0)) < DBL_EPSILON) + { + double part1 = log(max); + double part2 = log(min); + return exp((part1 - part2) * this->rand() + part2); + } + else + { + double part1 = pow(max, index + 1); + double part2 = pow(min, index + 1); + double ex = 1 / (index + 1); + return pow((part1 - part2) * this->rand() + part2, ex); + } +} + +double Random::randBrokenPowerLaw( + double index1, double index2, double breakpoint, double min, double max) +{ + if ((min <= 0) || (max < min)) + { + throw std::runtime_error("Power law distribution only possible for 0 < min <= max"); + } + if (min >= breakpoint) + { + return this->randPowerLaw(index2, min, max); + } + else if (max <= breakpoint) + { + return this->randPowerLaw(index2, min, max); + } + else + { + double intPL1; + // check if index1 = -1 + if ((std::abs(index1 + 1.0)) < DBL_EPSILON) + { + intPL1 = log(breakpoint / min); + } + else + { + intPL1 = (pow(breakpoint, index1 + 1) - pow(min, index1 + 1)) / (index1 + 1); + } + double intPL2; + // check if index2 = -1 + if ((std::abs(index2 + 1.0)) < DBL_EPSILON) + { + intPL2 = log(max / breakpoint) * pow(breakpoint, index1 - index2); + } + else + { + intPL2 = (pow(max, index2 + 1) - pow(breakpoint, index2 + 1)) + * pow(breakpoint, index1 - index2) / (index2 + 1); + } + if (this->rand() > intPL1 / (intPL1 + intPL2)) + return this->randPowerLaw(index2, breakpoint, max); + else + return this->randPowerLaw(index1, min, breakpoint); + } } double Random::randExponential() { - double dum; - do - { - dum = this->rand(); - } while (dum < DBL_EPSILON); - return -1.0 * log(dum); + double dum; + do + { + dum = this->rand(); + } while (dum < DBL_EPSILON); + return -1.0 * log(dum); } Random::uint32 Random::randInt() { - if (left == 0) - reload(); - --left; + if (left == 0) + reload(); + --left; - register uint32 s1; - s1 = *pNext++; - s1 ^= (s1 >> 11); - s1 ^= (s1 << 7) & 0x9d2c5680UL; - s1 ^= (s1 << 15) & 0xefc60000UL; - return (s1 ^ (s1 >> 18)); + register uint32 s1; + s1 = *pNext++; + s1 ^= (s1 >> 11); + s1 ^= (s1 << 7) & 0x9d2c5680UL; + s1 ^= (s1 << 15) & 0xefc60000UL; + return (s1 ^ (s1 >> 18)); } Random::uint32 Random::randInt(const uint32& n) { - // Find which bits are used in n - // Optimized by Magnus Jonsson (magnus@smartelectronix.com) - uint32 used = n; - used |= used >> 1; - used |= used >> 2; - used |= used >> 4; - used |= used >> 8; - used |= used >> 16; - - // Draw numbers until one is found in [0,n] - uint32 i; - do - i = randInt() & used; // toss unused bits to shorten search - while (i > n); - return i; -} + // Find which bits are used in n + // Optimized by Magnus Jonsson (magnus@smartelectronix.com) + uint32 used = n; + used |= used >> 1; + used |= used >> 2; + used |= used >> 4; + used |= used >> 8; + used |= used >> 16; -void Random::seed(const uint32 oneSeed) -{ - initialize(oneSeed); - reload(); + // Draw numbers until one is found in [0,n] + uint32 i; + do + i = randInt() & used; // toss unused bits to shorten search + while (i > n); + return i; } -void Random::seed(uint32 * const bigSeed, const uint32 seedLength) +void Random::seed(const uint32 oneSeed) { - initialize(19650218UL); - register int i = 1; - register uint32 j = 0; - register int k = (N > seedLength ? N : seedLength); - for (; k; --k) - { - state[i] = state[i] - ^ ((state[i - 1] ^ (state[i - 1] >> 30)) * 1664525UL); - state[i] += (bigSeed[j] & 0xffffffffUL) + j; - state[i] &= 0xffffffffUL; - ++i; - ++j; - if (i >= N) - { - state[0] = state[N - 1]; - i = 1; - } - if (j >= seedLength) - j = 0; - } - for (k = N - 1; k; --k) - { - state[i] = state[i] - ^ ((state[i - 1] ^ (state[i - 1] >> 30)) * 1566083941UL); - state[i] -= i; - state[i] &= 0xffffffffUL; - ++i; - if (i >= N) - { - state[0] = state[N - 1]; - i = 1; - } - } - state[0] = 0x80000000UL; // MSB is 1, assuring non-zero initial array - reload(); + initialize(oneSeed); + reload(); +} + +void Random::seed(uint32* const bigSeed, const uint32 seedLength) +{ + initialize(19650218UL); + register int i = 1; + register uint32 j = 0; + register int k = (N > seedLength ? N : seedLength); + for (; k; --k) + { + state[i] = state[i] ^ ((state[i - 1] ^ (state[i - 1] >> 30)) * 1664525UL); + state[i] += (bigSeed[j] & 0xffffffffUL) + j; + state[i] &= 0xffffffffUL; + ++i; + ++j; + if (i >= N) + { + state[0] = state[N - 1]; + i = 1; + } + if (j >= seedLength) + j = 0; + } + for (k = N - 1; k; --k) + { + state[i] = state[i] ^ ((state[i - 1] ^ (state[i - 1] >> 30)) * 1566083941UL); + state[i] -= i; + state[i] &= 0xffffffffUL; + ++i; + if (i >= N) + { + state[0] = state[N - 1]; + i = 1; + } + } + state[0] = 0x80000000UL; // MSB is 1, assuring non-zero initial array + reload(); } void Random::seed() { - // First try getting an array from /dev/urandom - FILE* urandom = fopen("/dev/urandom", "rb"); - if (urandom) - { - uint32 bigSeed[N]; - register uint32 *s = bigSeed; - register int i = N; - register bool success = true; - while (success && i--) - success = fread(s++, sizeof(uint32), 1, urandom) != 0; - fclose(urandom); - if (success) - { - seed(bigSeed, N); - return; - } - } - - // Was not successful, so use time() and clock() instead - seed(hash(time(NULL), clock())); + // First try getting an array from /dev/urandom + FILE* urandom = fopen("/dev/urandom", "rb"); + if (urandom) + { + uint32 bigSeed[N]; + register uint32* s = bigSeed; + register int i = N; + register bool success = true; + while (success && i--) + success = fread(s++, sizeof(uint32), 1, urandom) != 0; + fclose(urandom); + if (success) + { + seed(bigSeed, N); + return; + } + } + + // Was not successful, so use time() and clock() instead + seed(hash(time(NULL), clock())); } void Random::initialize(const uint32 seed) { - register uint32 *s = state; - register uint32 *r = state; - register int i = 1; - *s++ = seed & 0xffffffffUL; - for (; i < N; ++i) - { - *s++ = (1812433253UL * (*r ^ (*r >> 30)) + i) & 0xffffffffUL; - r++; - } + register uint32* s = state; + register uint32* r = state; + register int i = 1; + *s++ = seed & 0xffffffffUL; + for (; i < N; ++i) + { + *s++ = (1812433253UL * (*r ^ (*r >> 30)) + i) & 0xffffffffUL; + r++; + } } void Random::reload() { - register uint32 *p = state; - register int i; - for (i = N - M; i--; ++p) - *p = twist(p[M], p[0], p[1]); - for (i = M; --i; ++p) - *p = twist(p[M - N], p[0], p[1]); - *p = twist(p[M - N], p[0], state[0]); - - left = N, pNext = state; + register uint32* p = state; + register int i; + for (i = N - M; i--; ++p) + *p = twist(p[M], p[0], p[1]); + for (i = M; --i; ++p) + *p = twist(p[M - N], p[0], p[1]); + *p = twist(p[M - N], p[0], state[0]); + + left = N, pNext = state; } Random::uint32 Random::hash(time_t t, clock_t c) { - static uint32 differ = 0; // guarantee time-based seeds will change - - uint32 h1 = 0; - unsigned char *p = (unsigned char *) &t; - for (size_t i = 0; i < sizeof(t); ++i) - { - h1 *= UCHAR_MAX + 2U; - h1 += p[i]; - } - uint32 h2 = 0; - p = (unsigned char *) &c; - for (size_t j = 0; j < sizeof(c); ++j) - { - h2 *= UCHAR_MAX + 2U; - h2 += p[j]; - } - return (h1 + differ++) ^ h2; + static uint32 differ = 0; // guarantee time-based seeds will change + + uint32 h1 = 0; + unsigned char* p = (unsigned char*)&t; + for (size_t i = 0; i < sizeof(t); ++i) + { + h1 *= UCHAR_MAX + 2U; + h1 += p[i]; + } + uint32 h2 = 0; + p = (unsigned char*)&c; + for (size_t j = 0; j < sizeof(c); ++j) + { + h2 *= UCHAR_MAX + 2U; + h2 += p[j]; + } + return (h1 + differ++) ^ h2; } void Random::save(uint32* saveArray) const { - register uint32 *sa = saveArray; - register const uint32 *s = state; - register int i = N; - for (; i--; *sa++ = *s++) - { - } - *sa = left; + register uint32* sa = saveArray; + register const uint32* s = state; + register int i = N; + for (; i--; *sa++ = *s++) + { + } + *sa = left; } -void Random::load(uint32 * const loadArray) +void Random::load(uint32* const loadArray) { - register uint32 *s = state; - register uint32 *la = loadArray; - register int i = N; - for (; i--; *s++ = *la++) - { - } - left = *la; - pNext = &state[N - left]; + register uint32* s = state; + register uint32* la = loadArray; + register int i = N; + for (; i--; *s++ = *la++) + { + } + left = *la; + pNext = &state[N - left]; } std::ostream& operator<<(std::ostream& os, const Random& mtrand) { - register const Random::uint32 *s = mtrand.state; - register int i = mtrand.N; - for (; i--; os << *s++ << "\t") - { - } - return os << mtrand.left; + register const Random::uint32* s = mtrand.state; + register int i = mtrand.N; + for (; i--; os << *s++ << "\t") + { + } + return os << mtrand.left; } std::istream& operator>>(std::istream& is, Random& mtrand) { - register Random::uint32 *s = mtrand.state; - register int i = mtrand.N; - for (; i--; is >> *s++) - { - } - is >> mtrand.left; - mtrand.pNext = &mtrand.state[mtrand.N - mtrand.left]; - return is; + register Random::uint32* s = mtrand.state; + register int i = mtrand.N; + for (; i--; is >> *s++) + { + } + is >> mtrand.left; + mtrand.pNext = &mtrand.state[mtrand.N - mtrand.left]; + return is; } - } - diff --git a/core/src/Relations.cc b/core/src/Relations.cc index 5514cef1cbde5f8fb98fc6dc1609b6909f9fbcdc..e08a09ceb908127641ca012ac5d54a3bff0fbfdb 100644 --- a/core/src/Relations.cc +++ b/core/src/Relations.cc @@ -1,7 +1,7 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- @@ -12,13 +12,13 @@ namespace pxl { -void Relations::serialize(const OutputStream &out) const +void Relations::serialize(const OutputStream& out) const { - out.writeInt(size()); - for (const_iterator iter = begin(); iter != end(); ++iter) - { - (*iter)->getId().serialize(out); - } + out.writeUInt32(size()); + for (relatives_t::const_iterator iter = begin(); iter != end(); ++iter) + { + (*iter)->getId().serialize(out); + } } -} +} // namespace pxl diff --git a/core/src/Relative.cc b/core/src/Relative.cc index d8101ee483b09d7cf9f7e342c585a96e0c3b8bea..16614ff0811c858ee630b45494a3780516af8852 100644 --- a/core/src/Relative.cc +++ b/core/src/Relative.cc @@ -1,7 +1,7 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2019 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- @@ -9,198 +9,204 @@ #include #include -#include "pxl/core/Relative.hh" #include "pxl/core/Relations.hh" -#include "pxl/core/logging.hh" - -#undef PXL_LOG_MODULE_NAME -#define PXL_LOG_MODULE_NAME "pxl::Relative" +#include "pxl/core/Relative.hh" namespace pxl { Relative::~Relative() { - // remove all relations: - unlinkMothers(); - unlinkDaughters(); - unlinkFlat(); - if (_refWkPtrSpec) - { - _refWkPtrSpec->notifyDeleted(); - } - - //don't throw exception in destructor: - if (_refObjectOwner) { - PXL_LOG_ERROR << "Error in ~Relative(): Relative derivative must be deleted by ObjectOwner to guarantee safe object handling!"; - } + // remove all relations: + unlinkMothers(); + unlinkDaughters(); + unlinkFlat(); } void Relative::linkSoft(Relative* relative, const std::string& type) { - if (relative) - { - if (!_softRelations.has(relative, type)) - { - _softRelations.set(relative, type); - relative->linkSoft(this, type); - } - } + if (relative) + { + if (!_softRelations.has(relative, type)) + { + _softRelations.set(relative, type); + relative->linkSoft(this, type); + } + } } /// Remove a soft relation with name \p type to the Relative \p relative void Relative::unlinkSoft(Relative* relative, const std::string& type) { - if (relative) - { - _softRelations.remove(relative, type); - relative->_softRelations.remove(this, type); - } + if (relative) + { + _softRelations.remove(relative, type); + relative->_softRelations.remove(this, type); + } } void Relative::linkMother(Relative* target) { - if (target->_refObjectOwner != this->_refObjectOwner) - { - throw std::runtime_error("pxl::ObjectBase::linkDaughter(...): ERROR: mother and daughter have not the same object holder!"); - } + if (getOwner() != target->getOwner()) + { + throw std::runtime_error("pxl::ObjectBase::linkDaughter(...): ERROR: mother and daughter " + "have not the same object holder!"); + } - this->_motherRelations.set(target); - target->_daughterRelations.set(this); + this->_motherRelations.set(target); + target->_daughterRelations.set(this); } void Relative::linkDaughter(Relative* target) { - if (target->_refObjectOwner != this->_refObjectOwner) - { - throw std::runtime_error("pxl::ObjectBase::linkMother(...): ERROR: mother and daughter have not the same object holder!"); - } + if (getOwner() != target->getOwner()) + { + throw std::runtime_error("pxl::ObjectBase::linkMother(...): ERROR: mother and daughter " + "have not the same object holder!"); + } - this->_daughterRelations.set(target); - target->_motherRelations.set(this); + this->_daughterRelations.set(target); + target->_motherRelations.set(this); } void Relative::linkFlat(Relative* target) { - if (target->_refObjectOwner != this->_refObjectOwner) - { - throw std::runtime_error("pxl::ObjectBase::linkFlat(...): ERROR: potential relatives have not the same object holder!"); - } + if (getOwner() != target->getOwner()) + { + throw std::runtime_error("pxl::ObjectBase::linkFlat(...): ERROR: potential relatives have " + "not the same object holder!"); + } - this->_flatRelations.set(target); - target->_flatRelations.set(this); + this->_flatRelations.set(target); + target->_flatRelations.set(this); } void Relative::unlinkMother(Relative* target) { - this->_motherRelations.erase(target); - target->_daughterRelations.erase(this); + this->_motherRelations.erase(target); + target->_daughterRelations.erase(this); } void Relative::unlinkDaughter(Relative* target) { - this->_daughterRelations.erase(target); - target->_motherRelations.erase(this); + this->_daughterRelations.erase(target); + target->_motherRelations.erase(this); } void Relative::unlinkFlat(Relative* target) { - this->_flatRelations.erase(target); - target->_flatRelations.erase(this); + this->_flatRelations.erase(target); + target->_flatRelations.erase(this); } void Relative::unlinkMothers() { - for (Relations::const_iterator iter = _motherRelations.begin(); iter - !=_motherRelations.end(); ++iter) - { - (*iter)->_daughterRelations.erase(this); - } + for (Relations::relatives_t::const_iterator iter = _motherRelations.begin(); + iter != _motherRelations.end(); ++iter) + { + (*iter)->_daughterRelations.erase(this); + } - _motherRelations.clearContainer(); + _motherRelations.clearContainer(); } void Relative::unlinkDaughters() { - for (Relations::const_iterator iter = _daughterRelations.begin(); iter - !=_daughterRelations.end(); ++iter) - { + for (Relations::relatives_t::const_iterator iter = _daughterRelations.begin(); + iter != _daughterRelations.end(); ++iter) + { - (*iter)->_motherRelations.erase(this); - } + (*iter)->_motherRelations.erase(this); + } - _daughterRelations.clearContainer(); + _daughterRelations.clearContainer(); } void Relative::unlinkFlat() { - for (Relations::const_iterator iter = _flatRelations.begin(); iter - !=_flatRelations.end(); ++iter) - { + for (Relations::relatives_t::const_iterator iter = _flatRelations.begin(); + iter != _flatRelations.end(); ++iter) + { - (*iter)->_flatRelations.erase(this); - } + (*iter)->_flatRelations.erase(this); + } - _flatRelations.clearContainer(); + _flatRelations.clearContainer(); } -std::ostream& Relative::printDecayTree(int level, std::ostream& os, int pan) const +std::ostream& Relative::print(int level, std::ostream& os, int pan) const { - int daughters = 0; + printPan1st(os, pan); + os << "pxl::ObjectBase with id: " << getId() << std::endl; - print(level, os, pan); + if (getMotherRelations().size() == 0) + { + printDecayTree(0, os, pan); + } - for (Relations::const_iterator iter = _daughterRelations.begin(); iter - !=_daughterRelations.end(); ++iter) - { - - (*iter)->printDecayTree(level, os, pan + 1); - daughters++; - - } - - if (daughters && pan > 1) - { - for (int p = 0; p < pan; p++) - { - os << "| "; - } - os << "*" << std::endl; - } - - return os; + return os; } -std::ostream& Relative::print(int level, std::ostream& os, int pan) const +std::ostream& Relative::printPan1st(std::ostream& os, int pan) const { - return printPan1st(os, pan) << "pxl::ObjectBase with id: " << id() - << std::endl; + for (int p = 0; p < pan - 2; p++) + { + os << "| "; + } + if (pan - 1 > 0) + { + os << "+--"; + } + if (pan) + { + os << "{ "; + } + + return os; } -std::ostream& Relative::printPan1st(std::ostream& os, int pan) const +std::ostream& Relative::printPan(std::ostream& os, int pan) const { - for (int p = 0; p < pan - 2; p++) - os << "| "; - if (pan - 1 > 0) - os << "+--"; - if (pan) - os << "{ "; - - return os; + for (int p = 0; p < pan - 1; p++) + { + os << "| "; + } + if (pan) + { + os << "| "; + } + return os; } -std::ostream& Relative::printPan(std::ostream& os, int pan) const +std::ostream& Relative::printDecayTree(int level, std::ostream& os, int pan) const { - for (int p = 0; p < pan - 1; p++) - os << "| "; - if (pan) - os << "| "; - return os; + int daughters = 0; + + print(level, os, pan); + + for (Relations::relatives_t::const_iterator iter = _daughterRelations.begin(); + iter != _daughterRelations.end(); ++iter) + { + + (*iter)->printDecayTree(level, os, pan + 1); + daughters++; + } + + if (daughters && pan > 1) + { + for (int p = 0; p < pan; p++) + { + os << "| "; + } + os << "*" << std::endl; + } + + return os; } } // namespace pxl std::ostream& operator<<(std::ostream& cxxx, const pxl::Relative& obj) { - return obj.print(0, cxxx, 0); + return obj.print(0, cxxx, 0); } diff --git a/core/src/SafeInt.hh b/core/src/SafeInt.hh index 191e2f71e44279bf3552298a1362376ae225c277..cdc10a0bf5b3c0b44d1ec6c892d17cb6fffc435a 100644 --- a/core/src/SafeInt.hh +++ b/core/src/SafeInt.hh @@ -6,39 +6,57 @@ This software is licensed under the Microsoft Public License (Ms-PL). For more information about Microsoft open source licenses, refer to http://www.microsoft.com/opensource/licenses.mspx -This license governs use of the accompanying software. If you use the software, you accept this license. +This license governs use of the accompanying software. If you use the software, you accept this +license. If you do not accept the license, do not use the software. Definitions -The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here -as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to +The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning +here +as under U.S. copyright law. A "contribution" is the original software, or any additions or changes +to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. Grant of Rights -(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations -in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to -reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution +(A) Copyright Grant- Subject to the terms of this license, including the license conditions and +limitations +in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license +to +reproduce its contribution, prepare derivative works of its contribution, and distribute its +contribution or any derivative works that you create. -(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in -section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed -patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution +(B) Patent Grant- Subject to the terms of this license, including the license conditions and +limitations in +section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its +licensed +patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its +contribution in the software or derivative works of the contribution in the software. Conditions and Limitations -(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, +(A) No Trademark License- This license does not grant you rights to use any contributors' name, +logo, or trademarks. -(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the +(B) If you bring a patent claim against any contributor over patents that you claim are infringed by +the software, your patent license from such contributor to the software ends automatically. -(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and +(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, +and attribution notices that are present in the software. -(D) If you distribute any portion of the software in source code form, you may do so only under this license - by including a complete copy of this license with your distribution. If you distribute any portion of the - software in compiled or object code form, you may only do so under a license that complies with this license. -(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, - guarantees, or conditions. You may have additional consumer rights under your local laws which this license - cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties +(D) If you distribute any portion of the software in source code form, you may do so only under this +license + by including a complete copy of this license with your distribution. If you distribute any +portion of the + software in compiled or object code form, you may only do so under a license that complies with +this license. +(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no +express warranties, + guarantees, or conditions. You may have additional consumer rights under your local laws which +this license + cannot change. To the extent permitted under your local laws, the contributors exclude the +implied warranties of merchantability, fitness for a particular purpose and non-infringement. @@ -58,9 +76,9 @@ Version 3.0 // Enable compiling with /Wall under VC #if !defined __GNUC__ -#pragma warning( push ) +#pragma warning(push) // Disable warnings coming from headers -#pragma warning( disable:4987 4820 4987 4820 ) +#pragma warning(disable : 4987 4820 4987 4820) #endif #include @@ -68,14 +86,14 @@ Version 3.0 #include #if !defined __GNUC__ && defined _M_AMD64 - #include - #define SAFEINT_USE_INTRINSICS 1 +#include +#define SAFEINT_USE_INTRINSICS 1 #else - #define SAFEINT_USE_INTRINSICS 0 +#define SAFEINT_USE_INTRINSICS 0 #endif #if !defined __GNUC__ -#pragma warning( pop ) +#pragma warning(pop) #endif // Various things needed for GCC @@ -93,21 +111,21 @@ Version 3.0 // If the user made a choice, respect it #if !defined #if !defined NEEDS_NULLPTR_DEFINED - // Visual Studio 2010 and higher support this - #if defined(_MSC_VER) - #if (_MSC_VER < 1600) - #define NEEDS_NULLPTR_DEFINED 1 - #else - #define NEEDS_NULLPTR_DEFINED 0 - #endif - #else - // Let everything else trigger based on whether we have nullptr_t - #if defined nullptr_t - #define NEEDS_NULLPTR_DEFINED 0 - #else - #define NEEDS_NULLPTR_DEFINED 1 - #endif - #endif +// Visual Studio 2010 and higher support this +#if defined(_MSC_VER) +#if (_MSC_VER < 1600) +#define NEEDS_NULLPTR_DEFINED 1 +#else +#define NEEDS_NULLPTR_DEFINED 0 +#endif +#else +// Let everything else trigger based on whether we have nullptr_t +#if defined nullptr_t +#define NEEDS_NULLPTR_DEFINED 0 +#else +#define NEEDS_NULLPTR_DEFINED 1 +#endif +#endif #endif #if NEEDS_NULLPTR_DEFINED @@ -118,35 +136,45 @@ Version 3.0 #pragma GCC diagnostic ignored "-Wunused-local-typedefs" #ifndef C_ASSERT -#define C_ASSERT(e) typedef char __C_ASSERT__[(e)?1:-1] +#define C_ASSERT(e) typedef char __C_ASSERT__[(e) ? 1 : -1] #endif - // Let's test some assumptions // We're assuming two's complement negative numbers -C_ASSERT( -1 == (int)0xffffffff ); +C_ASSERT(-1 == (int)0xffffffff); -/************* Compiler Options ***************************************************************************************************** +/************* Compiler Options +***************************************************************************************************** SafeInt supports several compile-time options that can change the behavior of the class. Compiler options: -SAFEINT_WARN_64BIT_PORTABILITY - this re-enables various warnings that happen when /Wp64 is used. Enabling this option is not +SAFEINT_WARN_64BIT_PORTABILITY - this re-enables various warnings that happen when /Wp64 is +used. Enabling this option is not recommended. -NEEDS_INT_DEFINED - if your compiler does not support __int8, __int16, __int32 and __int64, you can enable this. -SAFEINT_ASSERT_ON_EXCEPTION - it is often easier to stop on an assert and figure out a problem than to try and figure out +NEEDS_INT_DEFINED - if your compiler does not support __int8, __int16, __int32 and +__int64, you can enable this. +SAFEINT_ASSERT_ON_EXCEPTION - it is often easier to stop on an assert and figure out a +problem than to try and figure out how you landed in the catch block. -SafeIntDefaultExceptionHandler - if you'd like to replace the exception handlers SafeInt provides, define your replacement and +SafeIntDefaultExceptionHandler - if you'd like to replace the exception handlers SafeInt +provides, define your replacement and define this. -SAFEINT_DISALLOW_UNSIGNED_NEGATION - Invoking the unary negation operator creates warnings, but if you'd like it to completely fail +SAFEINT_DISALLOW_UNSIGNED_NEGATION - Invoking the unary negation operator creates warnings, but if +you'd like it to completely fail to compile, define this. -ANSI_CONVERSIONS - This changes the class to use default comparison behavior, which may be unsafe. Enabling this +ANSI_CONVERSIONS - This changes the class to use default comparison behavior, +which may be unsafe. Enabling this option is not recommended. -SAFEINT_DISABLE_BINARY_ASSERT - binary AND, OR or XOR operations on mixed size types can produce unexpected results. If you do - this, the default is to assert. Set this if you prefer not to assert under these conditions. -SIZE_T_CAST_NEEDED - some compilers complain if there is not a cast to size_t, others complain if there is one. +SAFEINT_DISABLE_BINARY_ASSERT - binary AND, OR or XOR operations on mixed size types can +produce unexpected results. If you do + this, the default is to assert. Set this if you prefer not to +assert under these conditions. +SIZE_T_CAST_NEEDED - some compilers complain if there is not a cast to size_t, +others complain if there is one. This lets you not have your compiler complain. -SAFEINT_DISABLE_SHIFT_ASSERT - Set this option if you don't want to assert when shifting more bits than the type has. Enabling +SAFEINT_DISABLE_SHIFT_ASSERT - Set this option if you don't want to assert when shifting more +bits than the type has. Enabling this option is not recommended. ************************************************************************************************************************************/ @@ -279,12 +307,16 @@ SAFEINT_DISABLE_SHIFT_ASSERT - Set this option if you don't want to assert * * * Performance update -* The current version of SafeInt uses template specialization to force the compiler to invoke only the -* operator implementation needed for any given pair of types. This will dramatically improve the perf +* The current version of SafeInt uses template specialization to force the compiler to invoke only +the +* operator implementation needed for any given pair of types. This will dramatically improve the +perf * of debug builds. * -* 3.0 update - not only have we maintained the specialization, there were some cases that were overly complex, -* and using some additional cases (e.g. signed __int64 and unsigned __int64) resulted in some simplification. +* 3.0 update - not only have we maintained the specialization, there were some cases that were +overly complex, +* and using some additional cases (e.g. signed __int64 and unsigned __int64) resulted in some +simplification. * Additionally, there was a lot of work done to better optimize the 64-bit multiplication. * * Binary Operators @@ -337,8 +369,10 @@ SAFEINT_DISABLE_SHIFT_ASSERT - Set this option if you don't want to assert * * The "0x02" is actually an int, and it needs to work. * In the case of binary operations on integers smaller than 32-bit, or of mixed type, corner -* cases do exist where you could get unexpected results. In any case where SafeInt returns a different -* result than the underlying operator, it will call assert(). You should examine your code and cast things +* cases do exist where you could get unexpected results. In any case where SafeInt returns a +different +* result than the underlying operator, it will call assert(). You should examine your code and cast +things * properly so that you are not programming with side effects. * * Documented issues: @@ -446,7 +480,8 @@ SAFEINT_DISABLE_SHIFT_ASSERT - Set this option if you don't want to assert * Nov 22, 2009 Forked from MS internal code * Changes needed to support gcc compiler - many thanks to Niels Dekker * for determining not just the issues, but also suggesting fixes. -* Also updating some of the header internals to be the same as the upcoming Visual Studio version. +* Also updating some of the header internals to be the same as the upcoming Visual +Studio version. * * Jan 16, 2010 64-bit gcc has long == __int64, which means that many of the existing 64-bit * templates are over-specialized. This forces a redefinition of all the 64-bit @@ -457,22 +492,30 @@ SAFEINT_DISABLE_SHIFT_ASSERT - Set this option if you don't want to assert * Note about code style - throughout this class, casts will be written using C-style (T), * not C++ style static_cast< T >. This is because the class is nearly always dealing with integer * types, and in this case static_cast and a C cast are equivalent. Given the large number of casts, -* the code is a little more readable this way. In the event a cast is needed where static_cast couldn't -* be substituted, we'll use the new templatized cast to make it explicit what the operation is doing. +* the code is a little more readable this way. In the event a cast is needed where static_cast +couldn't +* be substituted, we'll use the new templatized cast to make it explicit what the operation is +doing. * ************************************************************************************************************ * Version 3.0 changes: * -* 1) The exception type thrown is now replacable, and you can throw your own exception types. This should help +* 1) The exception type thrown is now replacable, and you can throw your own exception types. This +should help * those using well-developed exception classes. * 2) The 64-bit multiplication code has had a lot of perf work done, and should be faster than 2.0. -* 3) There is now limited floating point support. You can initialize a SafeInt with a floating point type, +* 3) There is now limited floating point support. You can initialize a SafeInt with a floating point +type, * and you can cast it out (or assign) to a float as well. -* 4) There is now an Align method. I noticed people use this a lot, and rarely check errors, so now you have one. +* 4) There is now an Align method. I noticed people use this a lot, and rarely check errors, so now +you have one. * -* Another major improvement is the addition of external functions - if you just want to check an operation, this can now happen: -* All of the following can be invoked without dealing with creating a class, or managing exceptions. This is especially handy -* for 64-bit porting, since SafeCast compiles away for a 32-bit cast from size_t to unsigned long, but checks it for 64-bit. +* Another major improvement is the addition of external functions - if you just want to check an +operation, this can now happen: +* All of the following can be invoked without dealing with creating a class, or managing exceptions. +This is especially handy +* for 64-bit porting, since SafeCast compiles away for a 32-bit cast from size_t to unsigned long, +but checks it for 64-bit. * * inline bool SafeCast( const T From, U& To ) throw() * inline bool SafeEquals( const T t, const U u ) throw() @@ -489,9 +532,9 @@ SAFEINT_DISABLE_SHIFT_ASSERT - Set this option if you don't want to assert * */ -//use these if the compiler does not support _intXX +// use these if the compiler does not support _intXX #ifdef NEEDS_INT_DEFINED -#define __int8 char +#define __int8 char #define __int16 short #define __int32 int #define __int64 long long @@ -500,7 +543,7 @@ SAFEINT_DISABLE_SHIFT_ASSERT - Set this option if you don't want to assert // GCC can't tell that the exception function won't return, // but Visual Studio can #if defined __GNUC__ -#define NotReachedReturn(x) return(x) +#define NotReachedReturn(x) return (x) #else #define NotReachedReturn(x) #endif @@ -586,8 +629,11 @@ enum SafeIntError class SafeIntException { public: - SafeIntException() { m_code = SafeIntNoError; } - SafeIntException( SafeIntError code ) + SafeIntException() + { + m_code = SafeIntNoError; + } + SafeIntException(SafeIntError code) { m_code = code; } @@ -595,92 +641,112 @@ public: }; #if defined SAFEINT_ASSERT_ON_EXCEPTION -inline void SafeIntExceptionAssert(){ assert(false); } +inline void SafeIntExceptionAssert() +{ + assert(false); +} #else -inline void SafeIntExceptionAssert(){} +inline void SafeIntExceptionAssert() +{ +} #endif namespace SafeIntInternal { - template < typename E > class SafeIntExceptionHandler; +template class SafeIntExceptionHandler; - template <> class SafeIntExceptionHandler < SafeIntException > - { - public: +template <> class SafeIntExceptionHandler +{ +public: #if defined __GNUC__ - static __attribute__((noreturn)) void SafeIntOnOverflow() + static __attribute__((noreturn)) void SafeIntOnOverflow() #else - static __declspec(noreturn) void __stdcall SafeIntOnOverflow() + static __declspec(noreturn) void __stdcall SafeIntOnOverflow() #endif - { - SafeIntExceptionAssert(); - throw SafeIntException( SafeIntArithmeticOverflow ); - } + { + SafeIntExceptionAssert(); + throw SafeIntException(SafeIntArithmeticOverflow); + } #if defined __GNUC__ - static __attribute__((noreturn)) void SafeIntOnDivZero() + static __attribute__((noreturn)) void SafeIntOnDivZero() #else - static __declspec(noreturn) void __stdcall SafeIntOnDivZero() + static __declspec(noreturn) void __stdcall SafeIntOnDivZero() #endif - { - SafeIntExceptionAssert(); - throw SafeIntException( SafeIntDivideByZero ); - } - }; + { + SafeIntExceptionAssert(); + throw SafeIntException(SafeIntDivideByZero); + } +}; #if defined _WINDOWS_ - class SafeIntWin32Exception +class SafeIntWin32Exception +{ +public: + SafeIntWin32Exception(DWORD dwExceptionCode, DWORD dwExceptionFlags = EXCEPTION_NONCONTINUABLE) { - public: - SafeIntWin32Exception( DWORD dwExceptionCode, DWORD dwExceptionFlags = EXCEPTION_NONCONTINUABLE ) - { - SafeIntExceptionAssert(); - RaiseException( dwExceptionCode, dwExceptionFlags, 0, 0 ); - } - }; + SafeIntExceptionAssert(); + RaiseException(dwExceptionCode, dwExceptionFlags, 0, 0); + } +}; - template <> class SafeIntExceptionHandler < SafeIntWin32Exception > +template <> class SafeIntExceptionHandler +{ +public: + static __declspec(noreturn) void __stdcall SafeIntOnOverflow() { - public: - static __declspec(noreturn) void __stdcall SafeIntOnOverflow() - { - SafeIntExceptionAssert(); - SafeIntWin32Exception( EXCEPTION_INT_OVERFLOW ); - } + SafeIntExceptionAssert(); + SafeIntWin32Exception(EXCEPTION_INT_OVERFLOW); + } - static __declspec(noreturn) void __stdcall SafeIntOnDivZero() - { - SafeIntExceptionAssert(); - SafeIntWin32Exception( EXCEPTION_INT_DIVIDE_BY_ZERO ); - } - }; + static __declspec(noreturn) void __stdcall SafeIntOnDivZero() + { + SafeIntExceptionAssert(); + SafeIntWin32Exception(EXCEPTION_INT_DIVIDE_BY_ZERO); + } +}; #endif } // namespace SafeIntInternal -typedef SafeIntInternal::SafeIntExceptionHandler < SafeIntException > CPlusPlusExceptionHandler; +typedef SafeIntInternal::SafeIntExceptionHandler CPlusPlusExceptionHandler; #if defined _WINDOWS_ -typedef SafeIntInternal::SafeIntExceptionHandler < SafeIntInternal::SafeIntWin32Exception > Win32ExceptionHandler; +typedef SafeIntInternal::SafeIntExceptionHandler + Win32ExceptionHandler; #endif // If the user hasn't defined a default exception handler, // define one now, depending on whether they would like Win32 or C++ exceptions #if !defined SafeIntDefaultExceptionHandler - #if defined SAFEINT_RAISE_EXCEPTION - #if !defined _WINDOWS_ - #error Include windows.h in order to use Win32 exceptions - #endif - - #define SafeIntDefaultExceptionHandler Win32ExceptionHandler - #else - #define SafeIntDefaultExceptionHandler CPlusPlusExceptionHandler - #endif +#if defined SAFEINT_RAISE_EXCEPTION +#if !defined _WINDOWS_ +#error Include windows.h in order to use Win32 exceptions +#endif + +#define SafeIntDefaultExceptionHandler Win32ExceptionHandler +#else +#define SafeIntDefaultExceptionHandler CPlusPlusExceptionHandler +#endif #endif // Turns out we can fool the compiler into not seeing compile-time constants with // a simple template specialization -template < int method > class CompileConst; -template <> class CompileConst { public: static bool Value(){ return true; } }; -template <> class CompileConst { public: static bool Value(){ return false; } }; +template class CompileConst; +template <> class CompileConst +{ +public: + static bool Value() + { + return true; + } +}; +template <> class CompileConst +{ +public: + static bool Value() + { + return false; + } +}; // The following template magic is because we're now not allowed // to cast a float to an enum. This means that if we happen to assign @@ -688,143 +754,345 @@ template <> class CompileConst { public: static bool Value(){ return fals // isFloat = ( (T)( (float)1.1 ) > (T)1 ) // from compiling in the case of an enum, which is the point of the specialization // that follows. -template < typename T > class NumericType; - -template <> class NumericType { public: enum{ isBool = true, isFloat = false, isInt = false }; }; -template <> class NumericType { public: enum{ isBool = false, isFloat = false, isInt = true }; }; -template <> class NumericType { public: enum{ isBool = false, isFloat = false, isInt = true }; }; -template <> class NumericType { public: enum{ isBool = false, isFloat = false, isInt = true }; }; -template <> class NumericType { public: enum{ isBool = false, isFloat = false, isInt = true }; }; -template <> class NumericType { public: enum{ isBool = false, isFloat = false, isInt = true }; }; +template class NumericType; + +template <> class NumericType +{ +public: + enum + { + isBool = true, + isFloat = false, + isInt = false + }; +}; +template <> class NumericType +{ +public: + enum + { + isBool = false, + isFloat = false, + isInt = true + }; +}; +template <> class NumericType +{ +public: + enum + { + isBool = false, + isFloat = false, + isInt = true + }; +}; +template <> class NumericType +{ +public: + enum + { + isBool = false, + isFloat = false, + isInt = true + }; +}; +template <> class NumericType +{ +public: + enum + { + isBool = false, + isFloat = false, + isInt = true + }; +}; +template <> class NumericType +{ +public: + enum + { + isBool = false, + isFloat = false, + isInt = true + }; +}; #if defined SAFEINT_USE_WCHAR_T || _NATIVE_WCHAR_T_DEFINED -template <> class NumericType { public: enum{ isBool = false, isFloat = false, isInt = true }; }; +template <> class NumericType +{ +public: + enum + { + isBool = false, + isFloat = false, + isInt = true + }; +}; #endif -template <> class NumericType { public: enum{ isBool = false, isFloat = false, isInt = true }; }; -template <> class NumericType { public: enum{ isBool = false, isFloat = false, isInt = true }; }; -template <> class NumericType { public: enum{ isBool = false, isFloat = false, isInt = true }; }; -template <> class NumericType { public: enum{ isBool = false, isFloat = false, isInt = true }; }; -template <> class NumericType<__int64> { public: enum{ isBool = false, isFloat = false, isInt = true }; }; -template <> class NumericType { public: enum{ isBool = false, isFloat = false, isInt = true }; }; -template <> class NumericType { public: enum{ isBool = false, isFloat = true, isInt = false }; }; -template <> class NumericType { public: enum{ isBool = false, isFloat = true, isInt = false }; }; -template <> class NumericType { public: enum{ isBool = false, isFloat = true, isInt = false }; }; +template <> class NumericType +{ +public: + enum + { + isBool = false, + isFloat = false, + isInt = true + }; +}; +template <> class NumericType +{ +public: + enum + { + isBool = false, + isFloat = false, + isInt = true + }; +}; +template <> class NumericType +{ +public: + enum + { + isBool = false, + isFloat = false, + isInt = true + }; +}; +template <> class NumericType +{ +public: + enum + { + isBool = false, + isFloat = false, + isInt = true + }; +}; +template <> class NumericType<__int64> +{ +public: + enum + { + isBool = false, + isFloat = false, + isInt = true + }; +}; +template <> class NumericType +{ +public: + enum + { + isBool = false, + isFloat = false, + isInt = true + }; +}; +template <> class NumericType +{ +public: + enum + { + isBool = false, + isFloat = true, + isInt = false + }; +}; +template <> class NumericType +{ +public: + enum + { + isBool = false, + isFloat = true, + isInt = false + }; +}; +template <> class NumericType +{ +public: + enum + { + isBool = false, + isFloat = true, + isInt = false + }; +}; // Catch-all for anything not supported -template < typename T > class NumericType { public: enum{ isBool = false, isFloat = false, isInt = false }; }; +template class NumericType +{ +public: + enum + { + isBool = false, + isFloat = false, + isInt = false + }; +}; // Use this to avoid compile-time const truncation warnings -template < int fSigned, int bits > class MinMax; - -template <> class MinMax< true, 8 > { public: const static __int8 min = (-0x7f - 1); - const static __int8 max = 0x7f; }; -template <> class MinMax< true, 16 > { public: const static __int16 min = ( -0x7fff - 1 ); - const static __int16 max = 0x7fff; }; -template <> class MinMax< true, 32 > { public: const static __int32 min = ( -0x7fffffff -1 ); - const static __int32 max = 0x7fffffff; }; -template <> class MinMax< true, 64 > { public: const static __int64 min = 0x8000000000000000LL; - const static __int64 max = 0x7fffffffffffffffLL; }; - -template <> class MinMax< false, 8 > { public: const static unsigned __int8 min = 0; - const static unsigned __int8 max = 0xff; }; -template <> class MinMax< false, 16 > { public: const static unsigned __int16 min = 0; - const static unsigned __int16 max = 0xffff; }; -template <> class MinMax< false, 32 > { public: const static unsigned __int32 min = 0; - const static unsigned __int32 max = 0xffffffff; }; -template <> class MinMax< false, 64 > { public: const static unsigned __int64 min = 0; - const static unsigned __int64 max = 0xffffffffffffffffULL; }; - -template < typename T > class IntTraits -{ -public: - C_ASSERT( NumericType::isInt ); +template class MinMax; + +template <> class MinMax +{ +public: + const static __int8 min = (-0x7f - 1); + const static __int8 max = 0x7f; +}; +template <> class MinMax +{ +public: + const static __int16 min = (-0x7fff - 1); + const static __int16 max = 0x7fff; +}; +template <> class MinMax +{ +public: + const static __int32 min = (-0x7fffffff - 1); + const static __int32 max = 0x7fffffff; +}; +template <> class MinMax +{ +public: + const static __int64 min = 0x8000000000000000LL; + const static __int64 max = 0x7fffffffffffffffLL; +}; + +template <> class MinMax +{ +public: + const static unsigned __int8 min = 0; + const static unsigned __int8 max = 0xff; +}; +template <> class MinMax +{ +public: + const static unsigned __int16 min = 0; + const static unsigned __int16 max = 0xffff; +}; +template <> class MinMax +{ +public: + const static unsigned __int32 min = 0; + const static unsigned __int32 max = 0xffffffff; +}; +template <> class MinMax +{ +public: + const static unsigned __int64 min = 0; + const static unsigned __int64 max = 0xffffffffffffffffULL; +}; + +template class IntTraits +{ +public: + C_ASSERT(NumericType::isInt); enum { - isSigned = ( (T)(-1) < 0 ), - is64Bit = ( sizeof(T) == 8 ), - is32Bit = ( sizeof(T) == 4 ), - is16Bit = ( sizeof(T) == 2 ), - is8Bit = ( sizeof(T) == 1 ), - isLT32Bit = ( sizeof(T) < 4 ), - isLT64Bit = ( sizeof(T) < 8 ), - isInt8 = ( sizeof(T) == 1 && isSigned ), - isUint8 = ( sizeof(T) == 1 && !isSigned ), - isInt16 = ( sizeof(T) == 2 && isSigned ), - isUint16 = ( sizeof(T) == 2 && !isSigned ), - isInt32 = ( sizeof(T) == 4 && isSigned ), - isUint32 = ( sizeof(T) == 4 && !isSigned ), - isInt64 = ( sizeof(T) == 8 && isSigned ), - isUint64 = ( sizeof(T) == 8 && !isSigned ), - bitCount = ( sizeof(T)*8 ), - isBool = ( (T)2 == (T)1 ) + isSigned = ((T)(-1) < 0), + is64Bit = (sizeof(T) == 8), + is32Bit = (sizeof(T) == 4), + is16Bit = (sizeof(T) == 2), + is8Bit = (sizeof(T) == 1), + isLT32Bit = (sizeof(T) < 4), + isLT64Bit = (sizeof(T) < 8), + isInt8 = (sizeof(T) == 1 && isSigned), + isUint8 = (sizeof(T) == 1 && !isSigned), + isInt16 = (sizeof(T) == 2 && isSigned), + isUint16 = (sizeof(T) == 2 && !isSigned), + isInt32 = (sizeof(T) == 4 && isSigned), + isUint32 = (sizeof(T) == 4 && !isSigned), + isInt64 = (sizeof(T) == 8 && isSigned), + isUint64 = (sizeof(T) == 8 && !isSigned), + bitCount = (sizeof(T) * 8), + isBool = ((T)2 == (T)1) }; // On version 13.10 enums cannot define __int64 values // so we'll use const statics instead! - const static T maxInt = MinMax< isSigned, bitCount >::max; - const static T minInt = MinMax< isSigned, bitCount >::min; + const static T maxInt = MinMax::max; + const static T minInt = MinMax::min; }; -template < typename T > -const T IntTraits< T >::maxInt; -template < typename T > -const T IntTraits< T >::minInt; +template const T IntTraits::maxInt; +template const T IntTraits::minInt; -template < typename T, typename U > class SafeIntCompare +template class SafeIntCompare { public: enum { - isBothSigned = (IntTraits< T >::isSigned && IntTraits< U >::isSigned), - isBothUnsigned = (!IntTraits< T >::isSigned && !IntTraits< U >::isSigned), - isLikeSigned = ((bool)(IntTraits< T >::isSigned) == (bool)(IntTraits< U >::isSigned)), - isCastOK = ((isLikeSigned && sizeof(T) >= sizeof(U)) || - (IntTraits< T >::isSigned && sizeof(T) > sizeof(U))), - isBothLT32Bit = (IntTraits< T >::isLT32Bit && IntTraits< U >::isLT32Bit), - isBothLT64Bit = (IntTraits< T >::isLT64Bit && IntTraits< U >::isLT64Bit) + isBothSigned = (IntTraits::isSigned && IntTraits::isSigned), + isBothUnsigned = (!IntTraits::isSigned && !IntTraits::isSigned), + isLikeSigned = ((bool)(IntTraits::isSigned) == (bool)(IntTraits::isSigned)), + isCastOK = ((isLikeSigned && sizeof(T) >= sizeof(U)) + || (IntTraits::isSigned && sizeof(T) > sizeof(U))), + isBothLT32Bit = (IntTraits::isLT32Bit && IntTraits::isLT32Bit), + isBothLT64Bit = (IntTraits::isLT64Bit && IntTraits::isLT64Bit) }; }; -//all of the arithmetic operators can be solved by the same code within -//each of these regions without resorting to compile-time constant conditionals -//most operators collapse the problem into less than the 22 zones, but this is used -//as the first cut -//using this also helps ensure that we handle all of the possible cases correctly +// all of the arithmetic operators can be solved by the same code within +// each of these regions without resorting to compile-time constant conditionals +// most operators collapse the problem into less than the 22 zones, but this is used +// as the first cut +// using this also helps ensure that we handle all of the possible cases correctly -template < typename T, typename U > class IntRegion +template class IntRegion { public: enum { - //unsigned-unsigned zone - IntZone_UintLT32_UintLT32 = SafeIntCompare< T,U >::isBothUnsigned && SafeIntCompare< T,U >::isBothLT32Bit, - IntZone_Uint32_UintLT64 = SafeIntCompare< T,U >::isBothUnsigned && IntTraits< T >::is32Bit && IntTraits< U >::isLT64Bit, - IntZone_UintLT32_Uint32 = SafeIntCompare< T,U >::isBothUnsigned && IntTraits< T >::isLT32Bit && IntTraits< U >::is32Bit, - IntZone_Uint64_Uint = SafeIntCompare< T,U >::isBothUnsigned && IntTraits< T >::is64Bit, - IntZone_UintLT64_Uint64 = SafeIntCompare< T,U >::isBothUnsigned && IntTraits< T >::isLT64Bit && IntTraits< U >::is64Bit, - //unsigned-signed - IntZone_UintLT32_IntLT32 = !IntTraits< T >::isSigned && IntTraits< U >::isSigned && SafeIntCompare< T,U >::isBothLT32Bit, - IntZone_Uint32_IntLT64 = IntTraits< T >::isUint32 && IntTraits< U >::isSigned && IntTraits< U >::isLT64Bit, - IntZone_UintLT32_Int32 = !IntTraits< T >::isSigned && IntTraits< T >::isLT32Bit && IntTraits< U >::isInt32, - IntZone_Uint64_Int = IntTraits< T >::isUint64 && IntTraits< U >::isSigned && IntTraits< U >::isLT64Bit, - IntZone_UintLT64_Int64 = !IntTraits< T >::isSigned && IntTraits< T >::isLT64Bit && IntTraits< U >::isInt64, - IntZone_Uint64_Int64 = IntTraits< T >::isUint64 && IntTraits< U >::isInt64, - //signed-signed - IntZone_IntLT32_IntLT32 = SafeIntCompare< T,U >::isBothSigned && ::SafeIntCompare< T, U >::isBothLT32Bit, - IntZone_Int32_IntLT64 = SafeIntCompare< T,U >::isBothSigned && IntTraits< T >::is32Bit && IntTraits< U >::isLT64Bit, - IntZone_IntLT32_Int32 = SafeIntCompare< T,U >::isBothSigned && IntTraits< T >::isLT32Bit && IntTraits< U >::is32Bit, - IntZone_Int64_Int64 = SafeIntCompare< T,U >::isBothSigned && IntTraits< T >::isInt64 && IntTraits< U >::isInt64, - IntZone_Int64_Int = SafeIntCompare< T,U >::isBothSigned && IntTraits< T >::is64Bit && IntTraits< U >::isLT64Bit, - IntZone_IntLT64_Int64 = SafeIntCompare< T,U >::isBothSigned && IntTraits< T >::isLT64Bit && IntTraits< U >::is64Bit, - //signed-unsigned - IntZone_IntLT32_UintLT32 = IntTraits< T >::isSigned && !IntTraits< U >::isSigned && SafeIntCompare< T,U >::isBothLT32Bit, - IntZone_Int32_UintLT32 = IntTraits< T >::isInt32 && !IntTraits< U >::isSigned && IntTraits< U >::isLT32Bit, - IntZone_IntLT64_Uint32 = IntTraits< T >::isSigned && IntTraits< T >::isLT64Bit && IntTraits< U >::isUint32, - IntZone_Int64_UintLT64 = IntTraits< T >::isInt64 && !IntTraits< U >::isSigned && IntTraits< U >::isLT64Bit, - IntZone_Int_Uint64 = IntTraits< T >::isSigned && IntTraits< U >::isUint64 && IntTraits< T >::isLT64Bit, - IntZone_Int64_Uint64 = IntTraits< T >::isInt64 && IntTraits< U >::isUint64 + // unsigned-unsigned zone + IntZone_UintLT32_UintLT32 + = SafeIntCompare::isBothUnsigned && SafeIntCompare::isBothLT32Bit, + IntZone_Uint32_UintLT64 + = SafeIntCompare::isBothUnsigned && IntTraits::is32Bit && IntTraits::isLT64Bit, + IntZone_UintLT32_Uint32 + = SafeIntCompare::isBothUnsigned && IntTraits::isLT32Bit && IntTraits::is32Bit, + IntZone_Uint64_Uint = SafeIntCompare::isBothUnsigned && IntTraits::is64Bit, + IntZone_UintLT64_Uint64 + = SafeIntCompare::isBothUnsigned && IntTraits::isLT64Bit && IntTraits::is64Bit, + // unsigned-signed + IntZone_UintLT32_IntLT32 + = !IntTraits::isSigned && IntTraits::isSigned && SafeIntCompare::isBothLT32Bit, + IntZone_Uint32_IntLT64 + = IntTraits::isUint32 && IntTraits::isSigned && IntTraits::isLT64Bit, + IntZone_UintLT32_Int32 + = !IntTraits::isSigned && IntTraits::isLT32Bit && IntTraits::isInt32, + IntZone_Uint64_Int + = IntTraits::isUint64 && IntTraits::isSigned && IntTraits::isLT64Bit, + IntZone_UintLT64_Int64 + = !IntTraits::isSigned && IntTraits::isLT64Bit && IntTraits::isInt64, + IntZone_Uint64_Int64 = IntTraits::isUint64 && IntTraits::isInt64, + // signed-signed + IntZone_IntLT32_IntLT32 + = SafeIntCompare::isBothSigned && ::SafeIntCompare::isBothLT32Bit, + IntZone_Int32_IntLT64 + = SafeIntCompare::isBothSigned && IntTraits::is32Bit && IntTraits::isLT64Bit, + IntZone_IntLT32_Int32 + = SafeIntCompare::isBothSigned && IntTraits::isLT32Bit && IntTraits::is32Bit, + IntZone_Int64_Int64 + = SafeIntCompare::isBothSigned && IntTraits::isInt64 && IntTraits::isInt64, + IntZone_Int64_Int + = SafeIntCompare::isBothSigned && IntTraits::is64Bit && IntTraits::isLT64Bit, + IntZone_IntLT64_Int64 + = SafeIntCompare::isBothSigned && IntTraits::isLT64Bit && IntTraits::is64Bit, + // signed-unsigned + IntZone_IntLT32_UintLT32 + = IntTraits::isSigned && !IntTraits::isSigned && SafeIntCompare::isBothLT32Bit, + IntZone_Int32_UintLT32 + = IntTraits::isInt32 && !IntTraits::isSigned && IntTraits::isLT32Bit, + IntZone_IntLT64_Uint32 + = IntTraits::isSigned && IntTraits::isLT64Bit && IntTraits::isUint32, + IntZone_Int64_UintLT64 + = IntTraits::isInt64 && !IntTraits::isSigned && IntTraits::isLT64Bit, + IntZone_Int_Uint64 + = IntTraits::isSigned && IntTraits::isUint64 && IntTraits::isLT64Bit, + IntZone_Int64_Uint64 = IntTraits::isInt64 && IntTraits::isUint64 }; }; - // In all of the following functions, we have two versions // One for SafeInt, which throws C++ (or possibly SEH) exceptions // The non-throwing versions are for use by the helper functions that return success and failure. @@ -833,7 +1101,6 @@ public: // There's no real alternative to duplicating logic, but keeping the two versions // immediately next to one another will help reduce problems - // useful function to help with getting the magnitude of a negative number enum AbsMethod { @@ -842,63 +1109,62 @@ enum AbsMethod AbsMethodNoop }; -template < typename T > -class GetAbsMethod +template class GetAbsMethod { public: enum { - method = IntTraits< T >::isLT64Bit && IntTraits< T >::isSigned ? AbsMethodInt : - IntTraits< T >::isInt64 ? AbsMethodInt64 : AbsMethodNoop + method = IntTraits::isLT64Bit && IntTraits::isSigned + ? AbsMethodInt + : IntTraits::isInt64 ? AbsMethodInt64 : AbsMethodNoop }; }; // let's go ahead and hard-code a dependency on the // representation of negative numbers to keep compilers from getting overly // happy with optimizing away things like -MIN_INT. -template < typename T, int > class AbsValueHelper; +template class AbsValueHelper; -template < typename T > class AbsValueHelper < T, AbsMethodInt> +template class AbsValueHelper { public: - static unsigned __int32 Abs( T t ) throw() + static unsigned __int32 Abs(T t) throw() { - assert( t < 0 ); + assert(t < 0); return ~(unsigned __int32)t + 1; } }; -template < typename T > class AbsValueHelper < T, AbsMethodInt64 > +template class AbsValueHelper { public: - static unsigned __int64 Abs( T t ) throw() + static unsigned __int64 Abs(T t) throw() { - assert( t < 0 ); + assert(t < 0); return ~(unsigned __int64)t + 1; } }; -template < typename T > class AbsValueHelper < T, AbsMethodNoop > +template class AbsValueHelper { public: - static T Abs( T t ) throw() + static T Abs(T t) throw() { // Why are you calling Abs on an unsigned number ??? - assert( false ); + assert(false); return t; } }; -template < typename T, bool > class NegationHelper; +template class NegationHelper; -template < typename T > class NegationHelper // Signed +template class NegationHelper // Signed { public: - template - static T NegativeThrow( T t ) + template static T NegativeThrow(T t) { // corner case - if( t != IntTraits< T >::minInt ) + if (t != IntTraits::minInt) { // cast prevents unneeded checks in the case of small ints return -t; @@ -906,10 +1172,10 @@ public: E::SafeIntOnOverflow(); } - static bool Negative( T t, T& ret ) throw() + static bool Negative(T t, T& ret) throw() { // corner case - if( t != IntTraits< T >::minInt ) + if (t != IntTraits::minInt) { // cast prevents unneeded checks in the case of small ints ret = -t; @@ -921,10 +1187,9 @@ public: // Helper classes to work keep compilers from // optimizing away negation -template < typename T > class SignedNegation; +template class SignedNegation; -template <> -class SignedNegation +template <> class SignedNegation { public: static signed __int32 Value(unsigned __int64 in) @@ -938,8 +1203,7 @@ public: } }; -template <> -class SignedNegation +template <> class SignedNegation { public: static signed __int64 Value(unsigned __int64 in) @@ -948,50 +1212,49 @@ public: } }; -template < int method > class NegationAssertHelper; +template class NegationAssertHelper; -template<> -class NegationAssertHelper< true > +template <> class NegationAssertHelper { - public: - static void BehaviorWarning() - { - // This will normally upcast to int - // For example -(unsigned short)0xffff == (int)0xffff0001 - // This class will retain the type, and will truncate, which may not be what - // you wanted - // If you want normal operator casting behavior, do this: - // SafeInt ss = 0xffff; - // then: - // -(SafeInt(ss)) - // will then emit a signed int with the correct value and bitfield - assert( false ); - } +public: + static void BehaviorWarning() + { + // This will normally upcast to int + // For example -(unsigned short)0xffff == (int)0xffff0001 + // This class will retain the type, and will truncate, which may not be what + // you wanted + // If you want normal operator casting behavior, do this: + // SafeInt ss = 0xffff; + // then: + // -(SafeInt(ss)) + // will then emit a signed int with the correct value and bitfield + assert(false); + } }; -template<> -class NegationAssertHelper< false > +template <> class NegationAssertHelper { - public: - static void BehaviorWarning(){} +public: + static void BehaviorWarning() + { + } }; -template < typename T > class NegationHelper // unsigned +template class NegationHelper // unsigned { public: - template - static T NegativeThrow( T t ) throw() + template static T NegativeThrow(T t) throw() { - NegationAssertHelper< IntTraits::isLT32Bit >::BehaviorWarning(); + NegationAssertHelper::isLT32Bit>::BehaviorWarning(); #if defined SAFEINT_DISALLOW_UNSIGNED_NEGATION - C_ASSERT( sizeof(T) == 0 ); + C_ASSERT(sizeof(T) == 0); #endif #if !defined __GNUC__ #pragma warning(push) -//this avoids warnings from the unary '-' operator being applied to unsigned numbers -#pragma warning(disable:4146) +// this avoids warnings from the unary '-' operator being applied to unsigned numbers +#pragma warning(disable : 4146) #endif // Note - this could be quenched on gcc // by doing something like: @@ -1004,15 +1267,15 @@ public: #endif } - static bool Negative( T t, T& ret ) + static bool Negative(T t, T& ret) { - if( IntTraits::isLT32Bit ) + if (IntTraits::isLT32Bit) { // See above - assert( false ); + assert(false); } #if defined SAFEINT_DISALLOW_UNSIGNED_NEGATION - C_ASSERT( sizeof(T) == 0 ); + C_ASSERT(sizeof(T) == 0); #endif // Do it this way to avoid warning ret = -t; @@ -1020,7 +1283,7 @@ public: } }; -//core logic to determine casting behavior +// core logic to determine casting behavior enum CastMethod { CastOK = 0, @@ -1034,85 +1297,106 @@ enum CastMethod CastFromBool }; - -template < typename ToType, typename FromType > -class GetCastMethod +template class GetCastMethod { public: enum { - method = ( IntTraits< FromType >::isBool && - !IntTraits< ToType >::isBool ) ? CastFromBool : + method = (IntTraits::isBool && !IntTraits::isBool) + ? CastFromBool + : - ( !IntTraits< FromType >::isBool && - IntTraits< ToType >::isBool ) ? CastToBool : + (!IntTraits::isBool && IntTraits::isBool) + ? CastToBool + : - ( SafeIntCompare< ToType, FromType >::isCastOK ) ? CastOK : + (SafeIntCompare::isCastOK) + ? CastOK + : - ( ( IntTraits< ToType >::isSigned && - !IntTraits< FromType >::isSigned && - sizeof( FromType ) >= sizeof( ToType ) ) || - ( SafeIntCompare< ToType, FromType >::isBothUnsigned && - sizeof( FromType ) > sizeof( ToType ) ) ) ? CastCheckGTMax : + ((IntTraits::isSigned && !IntTraits::isSigned + && sizeof(FromType) >= sizeof(ToType)) + || (SafeIntCompare::isBothUnsigned + && sizeof(FromType) > sizeof(ToType))) + ? CastCheckGTMax + : - ( !IntTraits< ToType >::isSigned && - IntTraits< FromType >::isSigned && - sizeof( ToType ) >= sizeof( FromType ) ) ? CastCheckLTZero : + (!IntTraits::isSigned && IntTraits::isSigned + && sizeof(ToType) >= sizeof(FromType)) + ? CastCheckLTZero + : - ( !IntTraits< ToType >::isSigned ) ? CastCheckMinMaxUnsigned - : CastCheckMinMaxSigned + (!IntTraits::isSigned) ? CastCheckMinMaxUnsigned + : CastCheckMinMaxSigned }; }; -template < typename FromType > class GetCastMethod < float, FromType > +template class GetCastMethod { public: - enum{ method = CastOK }; + enum + { + method = CastOK + }; }; -template < typename FromType > class GetCastMethod < double, FromType > +template class GetCastMethod { public: - enum{ method = CastOK }; + enum + { + method = CastOK + }; }; -template < typename FromType > class GetCastMethod < long double, FromType > +template class GetCastMethod { public: - enum{ method = CastOK }; + enum + { + method = CastOK + }; }; -template < typename ToType > class GetCastMethod < ToType, float > +template class GetCastMethod { public: - enum{ method = CastFromFloat }; + enum + { + method = CastFromFloat + }; }; -template < typename ToType > class GetCastMethod < ToType, double > +template class GetCastMethod { public: - enum{ method = CastFromFloat }; + enum + { + method = CastFromFloat + }; }; -template < typename ToType > class GetCastMethod < ToType, long double > +template class GetCastMethod { public: - enum{ method = CastFromFloat }; + enum + { + method = CastFromFloat + }; }; -template < typename T, typename U, int > class SafeCastHelper; +template class SafeCastHelper; -template < typename T, typename U > class SafeCastHelper < T, U, CastOK > +template class SafeCastHelper { public: - static bool Cast( U u, T& t ) throw() + static bool Cast(U u, T& t) throw() { t = (T)u; return true; } - template < typename E > - static void CastThrow( U u, T& t ) + template static void CastThrow(U u, T& t) { t = (T)u; } @@ -1120,13 +1404,12 @@ public: // special case floats and doubles // tolerate loss of precision -template < typename T, typename U > class SafeCastHelper < T, U, CastFromFloat > +template class SafeCastHelper { public: - static bool Cast( U u, T& t ) throw() + static bool Cast(U u, T& t) throw() { - if( u <= (U)IntTraits< T >::maxInt && - u >= (U)IntTraits< T >::minInt ) + if (u <= (U)IntTraits::maxInt && u >= (U)IntTraits::minInt) { t = (T)u; return true; @@ -1134,11 +1417,9 @@ public: return false; } - template < typename E > - static void CastThrow( U u, T& t ) + template static void CastThrow(U u, T& t) { - if( u <= (U)IntTraits< T >::maxInt && - u >= (U)IntTraits< T >::minInt ) + if (u <= (U)IntTraits::maxInt && u >= (U)IntTraits::minInt) { t = (T)u; return; @@ -1148,131 +1429,125 @@ public: }; // Match on any method where a bool is cast to type T -template < typename T > class SafeCastHelper < T, bool, CastFromBool > +template class SafeCastHelper { public: - static bool Cast( bool b, T& t ) throw() + static bool Cast(bool b, T& t) throw() { - t = (T)( b ? 1 : 0 ); + t = (T)(b ? 1 : 0); return true; } - template < typename E > - static void CastThrow( bool b, T& t ) + template static void CastThrow(bool b, T& t) { - t = (T)( b ? 1 : 0 ); + t = (T)(b ? 1 : 0); } }; -template < typename T > class SafeCastHelper < bool, T, CastToBool > +template class SafeCastHelper { public: - static bool Cast( T t, bool& b ) throw() + static bool Cast(T t, bool& b) throw() { b = !!t; return true; } - template < typename E > - static void CastThrow( bool b, T& t ) + template static void CastThrow(bool b, T& t) { b = !!t; } }; -template < typename T, typename U > class SafeCastHelper < T, U, CastCheckLTZero > +template class SafeCastHelper { public: - static bool Cast( U u, T& t ) throw() + static bool Cast(U u, T& t) throw() { - if( u < 0 ) + if (u < 0) return false; t = (T)u; return true; } - template < typename E > - static void CastThrow( U u, T& t ) + template static void CastThrow(U u, T& t) { - if( u < 0 ) + if (u < 0) E::SafeIntOnOverflow(); t = (T)u; } }; -template < typename T, typename U > class SafeCastHelper < T, U, CastCheckGTMax > +template class SafeCastHelper { public: - static bool Cast( U u, T& t ) throw() + static bool Cast(U u, T& t) throw() { - if( u > (U)IntTraits< T >::maxInt ) + if (u > (U)IntTraits::maxInt) return false; t = (T)u; return true; } - template < typename E > - static void CastThrow( U u, T& t ) + template static void CastThrow(U u, T& t) { - if( u > (U)IntTraits< T >::maxInt ) + if (u > (U)IntTraits::maxInt) E::SafeIntOnOverflow(); t = (T)u; } }; -template < typename T, typename U > class SafeCastHelper < T, U, CastCheckMinMaxUnsigned > +template class SafeCastHelper { public: - static bool Cast( U u, T& t ) throw() + static bool Cast(U u, T& t) throw() { // U is signed - T could be either signed or unsigned - if( u > IntTraits< T >::maxInt || u < 0 ) + if (u > IntTraits::maxInt || u < 0) return false; t = (T)u; return true; } - template < typename E > - static void CastThrow( U u, T& t ) + template static void CastThrow(U u, T& t) { // U is signed - T could be either signed or unsigned - if( u > IntTraits< T >::maxInt || u < 0 ) + if (u > IntTraits::maxInt || u < 0) E::SafeIntOnOverflow(); t = (T)u; } }; -template < typename T, typename U > class SafeCastHelper < T, U, CastCheckMinMaxSigned > +template class SafeCastHelper { public: - static bool Cast( U u, T& t ) throw() + static bool Cast(U u, T& t) throw() { // T, U are signed - if( u > IntTraits< T >::maxInt || u < IntTraits< T >::minInt ) + if (u > IntTraits::maxInt || u < IntTraits::minInt) return false; t = (T)u; return true; } - template < typename E > - static void CastThrow( U u, T& t ) + template static void CastThrow(U u, T& t) { - //T, U are signed - if( u > IntTraits< T >::maxInt || u < IntTraits< T >::minInt ) + // T, U are signed + if (u > IntTraits::maxInt || u < IntTraits::minInt) E::SafeIntOnOverflow(); t = (T)u; } }; -//core logic to determine whether a comparison is valid, or needs special treatment +// core logic to determine whether a comparison is valid, or needs special treatment enum ComparisonMethod { ComparisonMethod_Ok = 0, @@ -1282,27 +1557,26 @@ enum ComparisonMethod ComparisonMethod_UnsignedU }; - // Note - the standard is arguably broken in the case of some integer - // conversion operations - // For example, signed char a = -1 = 0xff - // unsigned int b = 0xffffffff - // If you then test if a < b, a value-preserving cast - // is made, and you're essentially testing - // (unsigned int)a < b == false - // - // I do not think this makes sense - if you perform - // a cast to an __int64, which can clearly preserve both value and signedness - // then you get a different and intuitively correct answer - // IMHO, -1 should be less than 4 billion - // If you prefer to retain the ANSI standard behavior - // insert #define ANSI_CONVERSIONS into your source - // Behavior differences occur in the following cases: - // 8, 16, and 32-bit signed int, unsigned 32-bit int - // any signed int, unsigned 64-bit int - // Note - the signed int must be negative to show the problem - -template < typename T, typename U > -class ValidComparison +// Note - the standard is arguably broken in the case of some integer +// conversion operations +// For example, signed char a = -1 = 0xff +// unsigned int b = 0xffffffff +// If you then test if a < b, a value-preserving cast +// is made, and you're essentially testing +// (unsigned int)a < b == false +// +// I do not think this makes sense - if you perform +// a cast to an __int64, which can clearly preserve both value and signedness +// then you get a different and intuitively correct answer +// IMHO, -1 should be less than 4 billion +// If you prefer to retain the ANSI standard behavior +// insert #define ANSI_CONVERSIONS into your source +// Behavior differences occur in the following cases: +// 8, 16, and 32-bit signed int, unsigned 32-bit int +// any signed int, unsigned 64-bit int +// Note - the signed int must be negative to show the problem + +template class ValidComparison { public: enum @@ -1310,131 +1584,156 @@ public: #ifdef ANSI_CONVERSIONS method = ComparisonMethod_Ok #else - method = ( ( SafeIntCompare< T, U >::isLikeSigned ) ? ComparisonMethod_Ok : - ( ( IntTraits< T >::isSigned && sizeof(T) < 8 && sizeof(U) < 4 ) || - ( IntTraits< U >::isSigned && sizeof(T) < 4 && sizeof(U) < 8 ) ) ? ComparisonMethod_CastInt : - ( ( IntTraits< T >::isSigned && sizeof(U) < 8 ) || - ( IntTraits< U >::isSigned && sizeof(T) < 8 ) ) ? ComparisonMethod_CastInt64 : - ( !IntTraits< T >::isSigned ) ? ComparisonMethod_UnsignedT : - ComparisonMethod_UnsignedU ) + method = ((SafeIntCompare::isLikeSigned) + ? ComparisonMethod_Ok + : ((IntTraits::isSigned && sizeof(T) < 8 && sizeof(U) < 4) + || (IntTraits::isSigned && sizeof(T) < 4 && sizeof(U) < 8)) + ? ComparisonMethod_CastInt + : ((IntTraits::isSigned && sizeof(U) < 8) + || (IntTraits::isSigned && sizeof(T) < 8)) + ? ComparisonMethod_CastInt64 + : (!IntTraits::isSigned) ? ComparisonMethod_UnsignedT + : ComparisonMethod_UnsignedU) #endif }; }; template class EqualityTest; -template < typename T, typename U > class EqualityTest< T, U, ComparisonMethod_Ok > +template class EqualityTest { public: - static bool IsEquals( const T t, const U u ) throw() { return ( t == u ); } + static bool IsEquals(const T t, const U u) throw() + { + return (t == u); + } }; -template < typename T, typename U > class EqualityTest< T, U, ComparisonMethod_CastInt > +template class EqualityTest { public: - static bool IsEquals( const T t, const U u ) throw() { return ( (int)t == (int)u ); } + static bool IsEquals(const T t, const U u) throw() + { + return ((int)t == (int)u); + } }; -template < typename T, typename U > class EqualityTest< T, U, ComparisonMethod_CastInt64 > +template class EqualityTest { public: - static bool IsEquals( const T t, const U u ) throw() { return ( (__int64)t == (__int64)u ); } + static bool IsEquals(const T t, const U u) throw() + { + return ((__int64)t == (__int64)u); + } }; -template < typename T, typename U > class EqualityTest< T, U, ComparisonMethod_UnsignedT > +template class EqualityTest { public: - static bool IsEquals( const T t, const U u ) throw() + static bool IsEquals(const T t, const U u) throw() { - //one operand is 32 or 64-bit unsigned, and the other is signed and the same size or smaller - if( u < 0 ) + // one operand is 32 or 64-bit unsigned, and the other is signed and the same size or + // smaller + if (u < 0) return false; - //else safe to cast to type T - return ( t == (T)u ); + // else safe to cast to type T + return (t == (T)u); } }; -template < typename T, typename U > class EqualityTest< T, U, ComparisonMethod_UnsignedU> +template class EqualityTest { public: - static bool IsEquals( const T t, const U u ) throw() + static bool IsEquals(const T t, const U u) throw() { - //one operand is 32 or 64-bit unsigned, and the other is signed and the same size or smaller - if( t < 0 ) + // one operand is 32 or 64-bit unsigned, and the other is signed and the same size or + // smaller + if (t < 0) return false; - //else safe to cast to type U - return ( (U)t == u ); + // else safe to cast to type U + return ((U)t == u); } }; template class GreaterThanTest; -template < typename T, typename U > class GreaterThanTest< T, U, ComparisonMethod_Ok > +template class GreaterThanTest { public: - static bool GreaterThan( const T t, const U u ) throw() { return ( t > u ); } + static bool GreaterThan(const T t, const U u) throw() + { + return (t > u); + } }; -template < typename T, typename U > class GreaterThanTest< T, U, ComparisonMethod_CastInt > +template class GreaterThanTest { public: - static bool GreaterThan( const T t, const U u ) throw() { return ( (int)t > (int)u ); } + static bool GreaterThan(const T t, const U u) throw() + { + return ((int)t > (int)u); + } }; -template < typename T, typename U > class GreaterThanTest< T, U, ComparisonMethod_CastInt64 > +template class GreaterThanTest { public: - static bool GreaterThan( const T t, const U u ) throw() { return ( (__int64)t > (__int64)u ); } + static bool GreaterThan(const T t, const U u) throw() + { + return ((__int64)t > (__int64)u); + } }; -template < typename T, typename U > class GreaterThanTest< T, U, ComparisonMethod_UnsignedT > +template class GreaterThanTest { public: - static bool GreaterThan( const T t, const U u ) throw() + static bool GreaterThan(const T t, const U u) throw() { - // one operand is 32 or 64-bit unsigned, and the other is signed and the same size or smaller - if( u < 0 ) + // one operand is 32 or 64-bit unsigned, and the other is signed and the same size or + // smaller + if (u < 0) return true; // else safe to cast to type T - return ( t > (T)u ); + return (t > (T)u); } }; -template < typename T, typename U > class GreaterThanTest< T, U, ComparisonMethod_UnsignedU > +template class GreaterThanTest { public: - static bool GreaterThan( const T t, const U u ) throw() + static bool GreaterThan(const T t, const U u) throw() { - // one operand is 32 or 64-bit unsigned, and the other is signed and the same size or smaller - if( t < 0 ) + // one operand is 32 or 64-bit unsigned, and the other is signed and the same size or + // smaller + if (t < 0) return false; // else safe to cast to type U - return ( (U)t > u ); + return ((U)t > u); } }; // Modulus is simpler than comparison, but follows much the same logic // using this set of functions, it can't fail except in a div 0 situation -template class ModulusHelper; +template class ModulusHelper; -template class ModulusHelper +template class ModulusHelper { public: - static SafeIntError Modulus( const T& t, const U& u, T& result ) throw() + static SafeIntError Modulus(const T& t, const U& u, T& result) throw() { - if(u == 0) + if (u == 0) return SafeIntDivideByZero; - //trap corner case - if( CompileConst< IntTraits< U >::isSigned >::Value() ) + // trap corner case + if (CompileConst::isSigned>::Value()) { // Some compilers don't notice that this only compiles when u is signed // Add cast to make them happy - if( u == (U)-1 ) + if (u == (U)-1) { result = 0; return SafeIntNoError; @@ -1445,16 +1744,15 @@ public: return SafeIntNoError; } - template < typename E > - static void ModulusThrow( const T& t, const U& u, T& result ) + template static void ModulusThrow(const T& t, const U& u, T& result) { - if(u == 0) + if (u == 0) E::SafeIntOnDivZero(); - //trap corner case - if( CompileConst< IntTraits< U >::isSigned >::Value() ) + // trap corner case + if (CompileConst::isSigned>::Value()) { - if( u == (U)-1 ) + if (u == (U)-1) { result = 0; return; @@ -1465,18 +1763,18 @@ public: } }; -template class ModulusHelper +template class ModulusHelper { public: - static SafeIntError Modulus( const T& t, const U& u, T& result ) throw() + static SafeIntError Modulus(const T& t, const U& u, T& result) throw() { - if(u == 0) + if (u == 0) return SafeIntDivideByZero; - //trap corner case - if( CompileConst< IntTraits< U >::isSigned >::Value() ) + // trap corner case + if (CompileConst::isSigned>::Value()) { - if( u == (U)-1 ) + if (u == (U)-1) { result = 0; return SafeIntNoError; @@ -1487,16 +1785,15 @@ public: return SafeIntNoError; } - template < typename E > - static void ModulusThrow( const T& t, const U& u, T& result ) + template static void ModulusThrow(const T& t, const U& u, T& result) { - if(u == 0) + if (u == 0) E::SafeIntOnDivZero(); - //trap corner case - if( CompileConst< IntTraits< U >::isSigned >::Value() ) + // trap corner case + if (CompileConst::isSigned>::Value()) { - if( u == (U)-1 ) + if (u == (U)-1) { result = 0; return; @@ -1507,18 +1804,18 @@ public: } }; -template < typename T, typename U > class ModulusHelper< T, U, ComparisonMethod_CastInt64> +template class ModulusHelper { public: - static SafeIntError Modulus( const T& t, const U& u, T& result ) throw() + static SafeIntError Modulus(const T& t, const U& u, T& result) throw() { - if(u == 0) + if (u == 0) return SafeIntDivideByZero; - //trap corner case - if( CompileConst< IntTraits< U >::isSigned >::Value() ) + // trap corner case + if (CompileConst::isSigned>::Value()) { - if( u == (U)-1 ) + if (u == (U)-1) { result = 0; return SafeIntNoError; @@ -1529,15 +1826,14 @@ public: return SafeIntNoError; } - template < typename E > - static void ModulusThrow( const T& t, const U& u, T& result ) + template static void ModulusThrow(const T& t, const U& u, T& result) { - if(u == 0) + if (u == 0) E::SafeIntOnDivZero(); - if( CompileConst< IntTraits< U >::isSigned >::Value() ) + if (CompileConst::isSigned>::Value()) { - if( u == (U)-1 ) + if (u == (U)-1) { result = 0; return; @@ -1549,235 +1845,261 @@ public: }; // T is unsigned __int64, U is any signed int -template < typename T, typename U > class ModulusHelper< T, U, ComparisonMethod_UnsignedT> +template class ModulusHelper { public: - static SafeIntError Modulus( const T& t, const U& u, T& result ) throw() + static SafeIntError Modulus(const T& t, const U& u, T& result) throw() { - if(u == 0) + if (u == 0) return SafeIntDivideByZero; // u could be negative - if so, need to convert to positive // casts below are always safe due to the way modulus works - if(u < 0) - result = (T)(t % AbsValueHelper< U, GetAbsMethod< U >::method >::Abs(u)); + if (u < 0) + result = (T)(t % AbsValueHelper::method>::Abs(u)); else result = (T)(t % u); return SafeIntNoError; } - template < typename E > - static void ModulusThrow( const T& t, const U& u, T& result ) + template static void ModulusThrow(const T& t, const U& u, T& result) { - if(u == 0) + if (u == 0) E::SafeIntOnDivZero(); // u could be negative - if so, need to convert to positive - if(u < 0) - result = (T)(t % AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( u )); + if (u < 0) + result = (T)(t % AbsValueHelper::method>::Abs(u)); else result = (T)(t % u); } }; // U is unsigned __int64, T any signed int -template < typename T, typename U > class ModulusHelper< T, U, ComparisonMethod_UnsignedU> +template class ModulusHelper { public: - static SafeIntError Modulus( const T& t, const U& u, T& result ) throw() + static SafeIntError Modulus(const T& t, const U& u, T& result) throw() { - if(u == 0) + if (u == 0) return SafeIntDivideByZero; - //t could be negative - if so, need to convert to positive - if(t < 0) - result = (T)( ~( AbsValueHelper< T, GetAbsMethod< T >::method >::Abs( t ) % u ) + 1 ); + // t could be negative - if so, need to convert to positive + if (t < 0) + result = (T)(~(AbsValueHelper::method>::Abs(t) % u) + 1); else result = (T)((T)t % u); return SafeIntNoError; } - template < typename E > - static void ModulusThrow( const T& t, const U& u, T& result ) + template static void ModulusThrow(const T& t, const U& u, T& result) { - if(u == 0) + if (u == 0) E::SafeIntOnDivZero(); - //t could be negative - if so, need to convert to positive - if(t < 0) - result = (T)( ~( AbsValueHelper< T, GetAbsMethod< T >::method >::Abs( t ) % u ) + 1); + // t could be negative - if so, need to convert to positive + if (t < 0) + result = (T)(~(AbsValueHelper::method>::Abs(t) % u) + 1); else - result = (T)( (T)t % u ); + result = (T)((T)t % u); } }; -//core logic to determine method to check multiplication +// core logic to determine method to check multiplication enum MultiplicationState { - MultiplicationState_CastInt = 0, // One or both signed, smaller than 32-bit - MultiplicationState_CastInt64, // One or both signed, smaller than 64-bit - MultiplicationState_CastUint, // Both are unsigned, smaller than 32-bit - MultiplicationState_CastUint64, // Both are unsigned, both 32-bit or smaller - MultiplicationState_Uint64Uint, // Both are unsigned, lhs 64-bit, rhs 32-bit or smaller + MultiplicationState_CastInt = 0, // One or both signed, smaller than 32-bit + MultiplicationState_CastInt64, // One or both signed, smaller than 64-bit + MultiplicationState_CastUint, // Both are unsigned, smaller than 32-bit + MultiplicationState_CastUint64, // Both are unsigned, both 32-bit or smaller + MultiplicationState_Uint64Uint, // Both are unsigned, lhs 64-bit, rhs 32-bit or smaller MultiplicationState_Uint64Uint64, // Both are unsigned int64 - MultiplicationState_Uint64Int, // lhs is unsigned int64, rhs int32 - MultiplicationState_Uint64Int64, // lhs is unsigned int64, rhs signed int64 - MultiplicationState_UintUint64, // Both are unsigned, lhs 32-bit or smaller, rhs 64-bit - MultiplicationState_UintInt64, // lhs unsigned 32-bit or less, rhs int64 - MultiplicationState_Int64Uint, // lhs int64, rhs unsigned int32 - MultiplicationState_Int64Int64, // lhs int64, rhs int64 - MultiplicationState_Int64Int, // lhs int64, rhs int32 - MultiplicationState_IntUint64, // lhs int, rhs unsigned int64 - MultiplicationState_IntInt64, // lhs int, rhs int64 - MultiplicationState_Int64Uint64, // lhs int64, rhs uint64 + MultiplicationState_Uint64Int, // lhs is unsigned int64, rhs int32 + MultiplicationState_Uint64Int64, // lhs is unsigned int64, rhs signed int64 + MultiplicationState_UintUint64, // Both are unsigned, lhs 32-bit or smaller, rhs 64-bit + MultiplicationState_UintInt64, // lhs unsigned 32-bit or less, rhs int64 + MultiplicationState_Int64Uint, // lhs int64, rhs unsigned int32 + MultiplicationState_Int64Int64, // lhs int64, rhs int64 + MultiplicationState_Int64Int, // lhs int64, rhs int32 + MultiplicationState_IntUint64, // lhs int, rhs unsigned int64 + MultiplicationState_IntInt64, // lhs int, rhs int64 + MultiplicationState_Int64Uint64, // lhs int64, rhs uint64 MultiplicationState_Error }; -template < typename T, typename U > -class MultiplicationMethod +template class MultiplicationMethod { public: enum { - // unsigned-unsigned - method = (IntRegion< T,U >::IntZone_UintLT32_UintLT32 ? MultiplicationState_CastUint : - (IntRegion< T,U >::IntZone_Uint32_UintLT64 || - IntRegion< T,U >::IntZone_UintLT32_Uint32) ? MultiplicationState_CastUint64 : - SafeIntCompare< T,U >::isBothUnsigned && - IntTraits< T >::isUint64 && IntTraits< U >::isUint64 ? MultiplicationState_Uint64Uint64 : - (IntRegion< T,U >::IntZone_Uint64_Uint) ? MultiplicationState_Uint64Uint : - (IntRegion< T,U >::IntZone_UintLT64_Uint64) ? MultiplicationState_UintUint64 : - // unsigned-signed - (IntRegion< T,U >::IntZone_UintLT32_IntLT32) ? MultiplicationState_CastInt : - (IntRegion< T,U >::IntZone_Uint32_IntLT64 || - IntRegion< T,U >::IntZone_UintLT32_Int32) ? MultiplicationState_CastInt64 : - (IntRegion< T,U >::IntZone_Uint64_Int) ? MultiplicationState_Uint64Int : - (IntRegion< T,U >::IntZone_UintLT64_Int64) ? MultiplicationState_UintInt64 : - (IntRegion< T,U >::IntZone_Uint64_Int64) ? MultiplicationState_Uint64Int64 : - // signed-signed - (IntRegion< T,U >::IntZone_IntLT32_IntLT32) ? MultiplicationState_CastInt : - (IntRegion< T,U >::IntZone_Int32_IntLT64 || - IntRegion< T,U >::IntZone_IntLT32_Int32) ? MultiplicationState_CastInt64 : - (IntRegion< T,U >::IntZone_Int64_Int64) ? MultiplicationState_Int64Int64 : - (IntRegion< T,U >::IntZone_Int64_Int) ? MultiplicationState_Int64Int : - (IntRegion< T,U >::IntZone_IntLT64_Int64) ? MultiplicationState_IntInt64 : - // signed-unsigned - (IntRegion< T,U >::IntZone_IntLT32_UintLT32) ? MultiplicationState_CastInt : - (IntRegion< T,U >::IntZone_Int32_UintLT32 || - IntRegion< T,U >::IntZone_IntLT64_Uint32) ? MultiplicationState_CastInt64 : - (IntRegion< T,U >::IntZone_Int64_UintLT64) ? MultiplicationState_Int64Uint : - (IntRegion< T,U >::IntZone_Int_Uint64) ? MultiplicationState_IntUint64 : - (IntRegion< T,U >::IntZone_Int64_Uint64 ? MultiplicationState_Int64Uint64 : - MultiplicationState_Error ) ) + // unsigned-unsigned + method = (IntRegion::IntZone_UintLT32_UintLT32 + ? MultiplicationState_CastUint + : (IntRegion::IntZone_Uint32_UintLT64 + || IntRegion::IntZone_UintLT32_Uint32) + ? MultiplicationState_CastUint64 + : SafeIntCompare::isBothUnsigned && IntTraits::isUint64 + && IntTraits::isUint64 + ? MultiplicationState_Uint64Uint64 + : (IntRegion::IntZone_Uint64_Uint) + ? MultiplicationState_Uint64Uint + : (IntRegion::IntZone_UintLT64_Uint64) + ? MultiplicationState_UintUint64 + : + // unsigned-signed + (IntRegion::IntZone_UintLT32_IntLT32) + ? MultiplicationState_CastInt + : (IntRegion::IntZone_Uint32_IntLT64 + || IntRegion::IntZone_UintLT32_Int32) + ? MultiplicationState_CastInt64 + : (IntRegion::IntZone_Uint64_Int) + ? MultiplicationState_Uint64Int + : (IntRegion::IntZone_UintLT64_Int64) + ? MultiplicationState_UintInt64 + : (IntRegion::IntZone_Uint64_Int64) + ? MultiplicationState_Uint64Int64 + : + // signed-signed + (IntRegion::IntZone_IntLT32_IntLT32) + ? MultiplicationState_CastInt + : (IntRegion::IntZone_Int32_IntLT64 + || IntRegion::IntZone_IntLT32_Int32) + ? MultiplicationState_CastInt64 + : (IntRegion::IntZone_Int64_Int64) + ? MultiplicationState_Int64Int64 + : (IntRegion::IntZone_Int64_Int) + ? MultiplicationState_Int64Int + : (IntRegion::IntZone_IntLT64_Int64) + ? MultiplicationState_IntInt64 + : + // signed-unsigned + (IntRegion::IntZone_IntLT32_UintLT32) + ? MultiplicationState_CastInt + : (IntRegion:: + IntZone_Int32_UintLT32 + || IntRegion:: + IntZone_IntLT64_Uint32) + ? MultiplicationState_CastInt64 + : (IntRegion::IntZone_Int64_UintLT64) + ? MultiplicationState_Int64Uint + : (IntRegion::IntZone_Int_Uint64) + ? MultiplicationState_IntUint64 + : (IntRegion::IntZone_Int64_Uint64 + ? MultiplicationState_Int64Uint64 + : MultiplicationState_Error)) }; }; template class MultiplicationHelper; -template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_CastInt> +template class MultiplicationHelper { public: - //accepts signed, both less than 32-bit - static bool Multiply( const T& t, const U& u, T& ret ) throw() + // accepts signed, both less than 32-bit + static bool Multiply(const T& t, const U& u, T& ret) throw() { int tmp = t * u; - if( tmp > IntTraits< T >::maxInt || tmp < IntTraits< T >::minInt ) + if (tmp > IntTraits::maxInt || tmp < IntTraits::minInt) return false; ret = (T)tmp; return true; } - template < typename E > - static void MultiplyThrow( const T& t, const U& u, T& ret ) + template static void MultiplyThrow(const T& t, const U& u, T& ret) { int tmp = t * u; - if( tmp > IntTraits< T >::maxInt || tmp < IntTraits< T >::minInt ) + if (tmp > IntTraits::maxInt || tmp < IntTraits::minInt) E::SafeIntOnOverflow(); ret = (T)tmp; } }; -template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_CastUint > +template class MultiplicationHelper { public: - //accepts unsigned, both less than 32-bit - static bool Multiply( const T& t, const U& u, T& ret ) throw() + // accepts unsigned, both less than 32-bit + static bool Multiply(const T& t, const U& u, T& ret) throw() { unsigned int tmp = (unsigned int)(t * u); - if( tmp > IntTraits< T >::maxInt ) + if (tmp > IntTraits::maxInt) return false; ret = (T)tmp; return true; } - template < typename E > - static void MultiplyThrow( const T& t, const U& u, T& ret ) + template static void MultiplyThrow(const T& t, const U& u, T& ret) { - unsigned int tmp = (unsigned int)( t * u ); + unsigned int tmp = (unsigned int)(t * u); - if( tmp > IntTraits< T >::maxInt ) + if (tmp > IntTraits::maxInt) E::SafeIntOnOverflow(); ret = (T)tmp; } }; -template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_CastInt64> +template class MultiplicationHelper { public: - //mixed signed or both signed where at least one argument is 32-bit, and both a 32-bit or less - static bool Multiply( const T& t, const U& u, T& ret ) throw() + // mixed signed or both signed where at least one argument is 32-bit, and both a 32-bit or less + static bool Multiply(const T& t, const U& u, T& ret) throw() { __int64 tmp = (__int64)t * (__int64)u; - if(tmp > (__int64)IntTraits< T >::maxInt || tmp < (__int64)IntTraits< T >::minInt) + if (tmp > (__int64)IntTraits::maxInt || tmp < (__int64)IntTraits::minInt) return false; ret = (T)tmp; return true; } - template < typename E > - static void MultiplyThrow( const T& t, const U& u, T& ret ) + template static void MultiplyThrow(const T& t, const U& u, T& ret) { __int64 tmp = (__int64)t * (__int64)u; - if(tmp > (__int64)IntTraits< T >::maxInt || tmp < (__int64)IntTraits< T >::minInt) + if (tmp > (__int64)IntTraits::maxInt || tmp < (__int64)IntTraits::minInt) E::SafeIntOnOverflow(); ret = (T)tmp; } }; -template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_CastUint64> +template class MultiplicationHelper { public: - //both unsigned where at least one argument is 32-bit, and both are 32-bit or less - static bool Multiply( const T& t, const U& u, T& ret ) throw() + // both unsigned where at least one argument is 32-bit, and both are 32-bit or less + static bool Multiply(const T& t, const U& u, T& ret) throw() { unsigned __int64 tmp = (unsigned __int64)t * (unsigned __int64)u; - if(tmp > (unsigned __int64)IntTraits< T >::maxInt) + if (tmp > (unsigned __int64)IntTraits::maxInt) return false; ret = (T)tmp; return true; } - template < typename E > - static void MultiplyThrow( const T& t, const U& u, T& ret ) + template static void MultiplyThrow(const T& t, const U& u, T& ret) { unsigned __int64 tmp = (unsigned __int64)t * (unsigned __int64)u; - if(tmp > (unsigned __int64)IntTraits< T >::maxInt) + if (tmp > (unsigned __int64)IntTraits::maxInt) E::SafeIntOnOverflow(); ret = (T)tmp; @@ -1786,32 +2108,33 @@ public: // T = left arg and return type // U = right arg -template < typename T, typename U > class LargeIntRegMultiply; +template class LargeIntRegMultiply; #if SAFEINT_USE_INTRINSICS // As usual, unsigned is easy -inline bool IntrinsicMultiplyUint64( const unsigned __int64& a, const unsigned __int64& b, unsigned __int64* pRet ) +inline bool IntrinsicMultiplyUint64( + const unsigned __int64& a, const unsigned __int64& b, unsigned __int64* pRet) { unsigned __int64 ulHigh = 0; - *pRet = _umul128(a , b, &ulHigh); + *pRet = _umul128(a, b, &ulHigh); return ulHigh == 0; } // Signed, is not so easy -inline bool IntrinsicMultiplyInt64( const signed __int64& a, const signed __int64& b, signed __int64* pRet ) +inline bool IntrinsicMultiplyInt64( + const signed __int64& a, const signed __int64& b, signed __int64* pRet) { __int64 llHigh = 0; - *pRet = _mul128(a , b, &llHigh); + *pRet = _mul128(a, b, &llHigh); // Now we need to figure out what we expect // If llHigh is 0, then treat *pRet as unsigned // If llHigh is < 0, then treat *pRet as signed - if( (a ^ b) < 0 ) + if ((a ^ b) < 0) { // Negative result expected - if( llHigh == -1 && *pRet < 0 || - llHigh == 0 && *pRet == 0 ) + if (llHigh == -1 && *pRet < 0 || llHigh == 0 && *pRet == 0) { // Everything is within range return true; @@ -1821,7 +2144,7 @@ inline bool IntrinsicMultiplyInt64( const signed __int64& a, const signed __int6 { // Result should be positive // Check for overflow - if( llHigh == 0 && (unsigned __int64)*pRet <= IntTraits< signed __int64 >::maxInt ) + if (llHigh == 0 && (unsigned __int64)*pRet <= IntTraits::maxInt) return true; } return false; @@ -1829,13 +2152,14 @@ inline bool IntrinsicMultiplyInt64( const signed __int64& a, const signed __int6 #endif -template<> class LargeIntRegMultiply< unsigned __int64, unsigned __int64 > +template <> class LargeIntRegMultiply { public: - static bool RegMultiply( const unsigned __int64& a, const unsigned __int64& b, unsigned __int64* pRet ) throw() + static bool RegMultiply( + const unsigned __int64& a, const unsigned __int64& b, unsigned __int64* pRet) throw() { #if SAFEINT_USE_INTRINSICS - return IntrinsicMultiplyUint64( a, b, pRet ); + return IntrinsicMultiplyUint64(a, b, pRet); #else unsigned __int32 aHigh, aLow, bHigh, bLow; @@ -1845,22 +2169,22 @@ public: // Note - same approach applies for 128 bit math on a 64-bit system aHigh = (unsigned __int32)(a >> 32); - aLow = (unsigned __int32)a; + aLow = (unsigned __int32)a; bHigh = (unsigned __int32)(b >> 32); - bLow = (unsigned __int32)b; + bLow = (unsigned __int32)b; *pRet = 0; - if(aHigh == 0) + if (aHigh == 0) { - if(bHigh != 0) + if (bHigh != 0) { *pRet = (unsigned __int64)aLow * (unsigned __int64)bHigh; } } - else if(bHigh == 0) + else if (bHigh == 0) { - if(aHigh != 0) + if (aHigh != 0) { *pRet = (unsigned __int64)aHigh * (unsigned __int64)bLow; } @@ -1870,18 +2194,18 @@ public: return false; } - if(*pRet != 0) + if (*pRet != 0) { unsigned __int64 tmp; - if((unsigned __int32)(*pRet >> 32) != 0) + if ((unsigned __int32)(*pRet >> 32) != 0) return false; *pRet <<= 32; tmp = (unsigned __int64)aLow * (unsigned __int64)bLow; *pRet += tmp; - if(*pRet < tmp) + if (*pRet < tmp) return false; return true; @@ -1892,11 +2216,12 @@ public: #endif } - template < typename E > - static void RegMultiplyThrow( const unsigned __int64& a, const unsigned __int64& b, unsigned __int64* pRet ) + template + static void RegMultiplyThrow( + const unsigned __int64& a, const unsigned __int64& b, unsigned __int64* pRet) { #if SAFEINT_USE_INTRINSICS - if( !IntrinsicMultiplyUint64( a, b, pRet ) ) + if (!IntrinsicMultiplyUint64(a, b, pRet)) E::SafeIntOnOverflow(); #else unsigned __int32 aHigh, aLow, bHigh, bLow; @@ -1907,22 +2232,22 @@ public: // Note - same approach applies for 128 bit math on a 64-bit system aHigh = (unsigned __int32)(a >> 32); - aLow = (unsigned __int32)a; + aLow = (unsigned __int32)a; bHigh = (unsigned __int32)(b >> 32); - bLow = (unsigned __int32)b; + bLow = (unsigned __int32)b; *pRet = 0; - if(aHigh == 0) + if (aHigh == 0) { - if(bHigh != 0) + if (bHigh != 0) { *pRet = (unsigned __int64)aLow * (unsigned __int64)bHigh; } } - else if(bHigh == 0) + else if (bHigh == 0) { - if(aHigh != 0) + if (aHigh != 0) { *pRet = (unsigned __int64)aHigh * (unsigned __int64)bLow; } @@ -1932,18 +2257,18 @@ public: E::SafeIntOnOverflow(); } - if(*pRet != 0) + if (*pRet != 0) { unsigned __int64 tmp; - if((unsigned __int32)(*pRet >> 32) != 0) + if ((unsigned __int32)(*pRet >> 32) != 0) E::SafeIntOnOverflow(); *pRet <<= 32; tmp = (unsigned __int64)aLow * (unsigned __int64)bLow; *pRet += tmp; - if(*pRet < tmp) + if (*pRet < tmp) E::SafeIntOnOverflow(); return; @@ -1954,13 +2279,14 @@ public: } }; -template<> class LargeIntRegMultiply< unsigned __int64, unsigned __int32 > +template <> class LargeIntRegMultiply { public: - static bool RegMultiply( const unsigned __int64& a, unsigned __int32 b, unsigned __int64* pRet ) throw() + static bool RegMultiply( + const unsigned __int64& a, unsigned __int32 b, unsigned __int64* pRet) throw() { #if SAFEINT_USE_INTRINSICS - return IntrinsicMultiplyUint64( a, (unsigned __int64)b, pRet ); + return IntrinsicMultiplyUint64(a, (unsigned __int64)b, pRet); #else unsigned __int32 aHigh, aLow; @@ -1969,24 +2295,24 @@ public: // => (aHigh * b * 2^32) + (aLow * b) aHigh = (unsigned __int32)(a >> 32); - aLow = (unsigned __int32)a; + aLow = (unsigned __int32)a; *pRet = 0; - if(aHigh != 0) + if (aHigh != 0) { *pRet = (unsigned __int64)aHigh * (unsigned __int64)b; unsigned __int64 tmp; - if((unsigned __int32)(*pRet >> 32) != 0) + if ((unsigned __int32)(*pRet >> 32) != 0) return false; *pRet <<= 32; tmp = (unsigned __int64)aLow * (unsigned __int64)b; *pRet += tmp; - if(*pRet < tmp) + if (*pRet < tmp) return false; return true; @@ -1997,11 +2323,12 @@ public: #endif } - template < typename E > - static void RegMultiplyThrow( const unsigned __int64& a, unsigned __int32 b, unsigned __int64* pRet ) + template + static void RegMultiplyThrow( + const unsigned __int64& a, unsigned __int32 b, unsigned __int64* pRet) { #if SAFEINT_USE_INTRINSICS - if( !IntrinsicMultiplyUint64( a, (unsigned __int64)b, pRet ) ) + if (!IntrinsicMultiplyUint64(a, (unsigned __int64)b, pRet)) E::SafeIntOnOverflow(); #else unsigned __int32 aHigh, aLow; @@ -2011,24 +2338,24 @@ public: // => (aHigh * b * 2^32) + (aLow * b) aHigh = (unsigned __int32)(a >> 32); - aLow = (unsigned __int32)a; + aLow = (unsigned __int32)a; *pRet = 0; - if(aHigh != 0) + if (aHigh != 0) { *pRet = (unsigned __int64)aHigh * (unsigned __int64)b; unsigned __int64 tmp; - if((unsigned __int32)(*pRet >> 32) != 0) + if ((unsigned __int32)(*pRet >> 32) != 0) E::SafeIntOnOverflow(); *pRet <<= 32; tmp = (unsigned __int64)aLow * (unsigned __int64)b; *pRet += tmp; - if(*pRet < tmp) + if (*pRet < tmp) E::SafeIntOnOverflow(); return; @@ -2040,72 +2367,81 @@ public: } }; -template<> class LargeIntRegMultiply< unsigned __int64, signed __int32 > +template <> class LargeIntRegMultiply { public: // Intrinsic not needed - static bool RegMultiply( const unsigned __int64& a, signed __int32 b, unsigned __int64* pRet ) throw() + static bool RegMultiply( + const unsigned __int64& a, signed __int32 b, unsigned __int64* pRet) throw() { - if( b < 0 && a != 0 ) + if (b < 0 && a != 0) return false; #if SAFEINT_USE_INTRINSICS - return IntrinsicMultiplyUint64( a, (unsigned __int64)b, pRet ); + return IntrinsicMultiplyUint64(a, (unsigned __int64)b, pRet); #else - return LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::RegMultiply(a, (unsigned __int32)b, pRet); + return LargeIntRegMultiply::RegMultiply( + a, (unsigned __int32)b, pRet); #endif } - template < typename E > - static void RegMultiplyThrow( const unsigned __int64& a, signed __int32 b, unsigned __int64* pRet ) + template + static void RegMultiplyThrow( + const unsigned __int64& a, signed __int32 b, unsigned __int64* pRet) { - if( b < 0 && a != 0 ) + if (b < 0 && a != 0) E::SafeIntOnOverflow(); #if SAFEINT_USE_INTRINSICS - if( !IntrinsicMultiplyUint64( a, (unsigned __int64)b, pRet ) ) + if (!IntrinsicMultiplyUint64(a, (unsigned __int64)b, pRet)) E::SafeIntOnOverflow(); #else - LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::template RegMultiplyThrow< E >( a, (unsigned __int32)b, pRet ); + LargeIntRegMultiply::template RegMultiplyThrow( + a, (unsigned __int32)b, pRet); #endif } }; -template<> class LargeIntRegMultiply< unsigned __int64, signed __int64 > +template <> class LargeIntRegMultiply { public: - static bool RegMultiply( const unsigned __int64& a, signed __int64 b, unsigned __int64* pRet ) throw() + static bool RegMultiply( + const unsigned __int64& a, signed __int64 b, unsigned __int64* pRet) throw() { - if( b < 0 && a != 0 ) + if (b < 0 && a != 0) return false; #if SAFEINT_USE_INTRINSICS - return IntrinsicMultiplyUint64( a, (unsigned __int64)b, pRet ); + return IntrinsicMultiplyUint64(a, (unsigned __int64)b, pRet); #else - return LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::RegMultiply(a, (unsigned __int64)b, pRet); + return LargeIntRegMultiply::RegMultiply( + a, (unsigned __int64)b, pRet); #endif } - template < typename E > - static void RegMultiplyThrow( const unsigned __int64& a, signed __int64 b, unsigned __int64* pRet ) + template + static void RegMultiplyThrow( + const unsigned __int64& a, signed __int64 b, unsigned __int64* pRet) { - if( b < 0 && a != 0 ) + if (b < 0 && a != 0) E::SafeIntOnOverflow(); #if SAFEINT_USE_INTRINSICS - if( !IntrinsicMultiplyUint64( a, (unsigned __int64)b, pRet ) ) + if (!IntrinsicMultiplyUint64(a, (unsigned __int64)b, pRet)) E::SafeIntOnOverflow(); #else - LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::template RegMultiplyThrow< E >( a, (unsigned __int64)b, pRet ); + LargeIntRegMultiply::template RegMultiplyThrow( + a, (unsigned __int64)b, pRet); #endif } }; -template<> class LargeIntRegMultiply< signed __int32, unsigned __int64 > +template <> class LargeIntRegMultiply { public: // Devolves into ordinary 64-bit calculation - static bool RegMultiply( signed __int32 a, const unsigned __int64& b, signed __int32* pRet ) throw() + static bool RegMultiply( + signed __int32 a, const unsigned __int64& b, signed __int32* pRet) throw() { unsigned __int32 bHigh, bLow; bool fIsNegative = false; @@ -2118,25 +2454,26 @@ public: // If the first part is != 0, fail bHigh = (unsigned __int32)(b >> 32); - bLow = (unsigned __int32)b; + bLow = (unsigned __int32)b; *pRet = 0; - if(bHigh != 0 && a != 0) + if (bHigh != 0 && a != 0) return false; - if( a < 0 ) + if (a < 0) { - a = (signed __int32)AbsValueHelper< signed __int32, GetAbsMethod< signed __int32 >::method >::Abs(a); + a = (signed __int32) + AbsValueHelper::method>::Abs(a); fIsNegative = true; } unsigned __int64 tmp = (unsigned __int32)a * (unsigned __int64)bLow; - if( !fIsNegative ) + if (!fIsNegative) { - if( tmp <= (unsigned __int64)IntTraits< signed __int32 >::maxInt ) + if (tmp <= (unsigned __int64)IntTraits::maxInt) { *pRet = (signed __int32)tmp; return true; @@ -2144,9 +2481,9 @@ public: } else { - if( tmp <= (unsigned __int64)IntTraits< signed __int32 >::maxInt+1 ) + if (tmp <= (unsigned __int64)IntTraits::maxInt + 1) { - *pRet = SignedNegation< signed __int32 >::Value( tmp ); + *pRet = SignedNegation::Value(tmp); return true; } } @@ -2154,8 +2491,8 @@ public: return false; } - template < typename E > - static void RegMultiplyThrow( signed __int32 a, const unsigned __int64& b, signed __int32* pRet ) + template + static void RegMultiplyThrow(signed __int32 a, const unsigned __int64& b, signed __int32* pRet) { unsigned __int32 bHigh, bLow; bool fIsNegative = false; @@ -2165,24 +2502,25 @@ public: // => (aHigh * bHigh * 2^64) + (aLow * bHigh * 2^32) + (aHigh * bLow * 2^32) + (aLow * bLow) bHigh = (unsigned __int32)(b >> 32); - bLow = (unsigned __int32)b; + bLow = (unsigned __int32)b; *pRet = 0; - if(bHigh != 0 && a != 0) + if (bHigh != 0 && a != 0) E::SafeIntOnOverflow(); - if( a < 0 ) + if (a < 0) { - a = (signed __int32)AbsValueHelper< signed __int32, GetAbsMethod< signed __int32 >::method >::Abs(a); + a = (signed __int32) + AbsValueHelper::method>::Abs(a); fIsNegative = true; } unsigned __int64 tmp = (unsigned __int32)a * (unsigned __int64)bLow; - if( !fIsNegative ) + if (!fIsNegative) { - if( tmp <= (unsigned __int64)IntTraits< signed __int32 >::maxInt ) + if (tmp <= (unsigned __int64)IntTraits::maxInt) { *pRet = (signed __int32)tmp; return; @@ -2190,9 +2528,9 @@ public: } else { - if( tmp <= (unsigned __int64)IntTraits< signed __int32 >::maxInt+1 ) + if (tmp <= (unsigned __int64)IntTraits::maxInt + 1) { - *pRet = SignedNegation< signed __int32 >::Value( tmp ); + *pRet = SignedNegation::Value(tmp); return; } } @@ -2201,11 +2539,12 @@ public: } }; -template<> class LargeIntRegMultiply< unsigned __int32, unsigned __int64 > +template <> class LargeIntRegMultiply { public: // Becomes ordinary 64-bit multiplication, intrinsic not needed - static bool RegMultiply( unsigned __int32 a, const unsigned __int64& b, unsigned __int32* pRet ) throw() + static bool RegMultiply( + unsigned __int32 a, const unsigned __int64& b, unsigned __int32* pRet) throw() { // Consider that a*b can be broken up into: // (bHigh * 2^32 + bLow) * a @@ -2213,60 +2552,66 @@ public: // In this case, the result must fit into 32-bits // If bHigh != 0 && a != 0, immediate error. - if( (unsigned __int32)(b >> 32) != 0 && a != 0 ) + if ((unsigned __int32)(b >> 32) != 0 && a != 0) return false; unsigned __int64 tmp = b * (unsigned __int64)a; - if( (unsigned __int32)(tmp >> 32) != 0 ) // overflow + if ((unsigned __int32)(tmp >> 32) != 0) // overflow return false; *pRet = (unsigned __int32)tmp; return true; } - template < typename E > - static void RegMultiplyThrow( unsigned __int32 a, const unsigned __int64& b, unsigned __int32* pRet ) + template + static void RegMultiplyThrow( + unsigned __int32 a, const unsigned __int64& b, unsigned __int32* pRet) { - if( (unsigned __int32)(b >> 32) != 0 && a != 0 ) + if ((unsigned __int32)(b >> 32) != 0 && a != 0) E::SafeIntOnOverflow(); unsigned __int64 tmp = b * (unsigned __int64)a; - if( (unsigned __int32)(tmp >> 32) != 0 ) // overflow + if ((unsigned __int32)(tmp >> 32) != 0) // overflow E::SafeIntOnOverflow(); *pRet = (unsigned __int32)tmp; } }; -template<> class LargeIntRegMultiply< unsigned __int32, signed __int64 > +template <> class LargeIntRegMultiply { public: - static bool RegMultiply( unsigned __int32 a, const signed __int64& b, unsigned __int32* pRet ) throw() + static bool RegMultiply( + unsigned __int32 a, const signed __int64& b, unsigned __int32* pRet) throw() { - if( b < 0 && a != 0 ) + if (b < 0 && a != 0) return false; - return LargeIntRegMultiply< unsigned __int32, unsigned __int64 >::RegMultiply( a, (unsigned __int64)b, pRet ); + return LargeIntRegMultiply::RegMultiply( + a, (unsigned __int64)b, pRet); } - template < typename E > - static void RegMultiplyThrow( unsigned __int32 a, const signed __int64& b, unsigned __int32* pRet ) + template + static void RegMultiplyThrow( + unsigned __int32 a, const signed __int64& b, unsigned __int32* pRet) { - if( b < 0 && a != 0 ) + if (b < 0 && a != 0) E::SafeIntOnOverflow(); - LargeIntRegMultiply< unsigned __int32, unsigned __int64 >::template RegMultiplyThrow< E >( a, (unsigned __int64)b, pRet ); + LargeIntRegMultiply::template RegMultiplyThrow( + a, (unsigned __int64)b, pRet); } }; -template<> class LargeIntRegMultiply< signed __int64, signed __int64 > +template <> class LargeIntRegMultiply { public: - static bool RegMultiply( const signed __int64& a, const signed __int64& b, signed __int64* pRet ) throw() + static bool RegMultiply( + const signed __int64& a, const signed __int64& b, signed __int64* pRet) throw() { #if SAFEINT_USE_INTRINSICS - return IntrinsicMultiplyInt64( a, b, pRet ); + return IntrinsicMultiplyInt64(a, b, pRet); #else bool aNegative = false; bool bNegative = false; @@ -2275,34 +2620,37 @@ public: __int64 a1 = a; __int64 b1 = b; - if( a1 < 0 ) + if (a1 < 0) { aNegative = true; - a1 = (signed __int64)AbsValueHelper< signed __int64, GetAbsMethod< signed __int64 >::method >::Abs(a1); + a1 = (signed __int64) + AbsValueHelper::method>::Abs(a1); } - if( b1 < 0 ) + if (b1 < 0) { bNegative = true; - b1 = (signed __int64)AbsValueHelper< signed __int64, GetAbsMethod< signed __int64 >::method >::Abs(b1); + b1 = (signed __int64) + AbsValueHelper::method>::Abs(b1); } - if( LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::RegMultiply( (unsigned __int64)a1, (unsigned __int64)b1, &tmp ) ) + if (LargeIntRegMultiply::RegMultiply( + (unsigned __int64)a1, (unsigned __int64)b1, &tmp)) { // The unsigned multiplication didn't overflow - if( aNegative ^ bNegative ) + if (aNegative ^ bNegative) { // Result must be negative - if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt ) + if (tmp <= (unsigned __int64)IntTraits::minInt) { - *pRet = SignedNegation< signed __int64 >::Value( tmp ); + *pRet = SignedNegation::Value(tmp); return true; } } else { // Result must be positive - if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt ) + if (tmp <= (unsigned __int64)IntTraits::maxInt) { *pRet = (signed __int64)tmp; return true; @@ -2314,11 +2662,12 @@ public: #endif } - template < typename E > - static void RegMultiplyThrow( const signed __int64& a, const signed __int64& b, signed __int64* pRet ) + template + static void RegMultiplyThrow( + const signed __int64& a, const signed __int64& b, signed __int64* pRet) { #if SAFEINT_USE_INTRINSICS - if( !IntrinsicMultiplyInt64( a, b, pRet ) ) + if (!IntrinsicMultiplyInt64(a, b, pRet)) E::SafeIntOnOverflow(); #else bool aNegative = false; @@ -2328,34 +2677,37 @@ public: __int64 a1 = a; __int64 b1 = b; - if( a1 < 0 ) + if (a1 < 0) { aNegative = true; - a1 = (signed __int64)AbsValueHelper< signed __int64, GetAbsMethod< signed __int64 >::method >::Abs(a1); + a1 = (signed __int64) + AbsValueHelper::method>::Abs(a1); } - if( b1 < 0 ) + if (b1 < 0) { bNegative = true; - b1 = (signed __int64)AbsValueHelper< signed __int64, GetAbsMethod< signed __int64 >::method >::Abs(b1); + b1 = (signed __int64) + AbsValueHelper::method>::Abs(b1); } - LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::template RegMultiplyThrow< E >( (unsigned __int64)a1, (unsigned __int64)b1, &tmp ); + LargeIntRegMultiply::template RegMultiplyThrow( + (unsigned __int64)a1, (unsigned __int64)b1, &tmp); // The unsigned multiplication didn't overflow or we'd be in the exception handler - if( aNegative ^ bNegative ) + if (aNegative ^ bNegative) { // Result must be negative - if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt ) + if (tmp <= (unsigned __int64)IntTraits::minInt) { - *pRet = SignedNegation< signed __int64 >::Value( tmp ); + *pRet = SignedNegation::Value(tmp); return; } } else { // Result must be positive - if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt ) + if (tmp <= (unsigned __int64)IntTraits::maxInt) { *pRet = (signed __int64)tmp; return; @@ -2367,40 +2719,43 @@ public: } }; -template<> class LargeIntRegMultiply< signed __int64, unsigned __int32 > +template <> class LargeIntRegMultiply { public: - static bool RegMultiply( const signed __int64& a, unsigned __int32 b, signed __int64* pRet ) throw() + static bool RegMultiply( + const signed __int64& a, unsigned __int32 b, signed __int64* pRet) throw() { #if SAFEINT_USE_INTRINSICS - return IntrinsicMultiplyInt64( a, (signed __int64)b, pRet ); + return IntrinsicMultiplyInt64(a, (signed __int64)b, pRet); #else bool aNegative = false; unsigned __int64 tmp; __int64 a1 = a; - if( a1 < 0 ) + if (a1 < 0) { aNegative = true; - a1 = (signed __int64)AbsValueHelper< signed __int64, GetAbsMethod< signed __int64 >::method >::Abs(a1); + a1 = (signed __int64) + AbsValueHelper::method>::Abs(a1); } - if( LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::RegMultiply( (unsigned __int64)a1, b, &tmp ) ) + if (LargeIntRegMultiply::RegMultiply( + (unsigned __int64)a1, b, &tmp)) { // The unsigned multiplication didn't overflow - if( aNegative ) + if (aNegative) { // Result must be negative - if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt ) + if (tmp <= (unsigned __int64)IntTraits::minInt) { - *pRet = SignedNegation< signed __int64 >::Value( tmp ); + *pRet = SignedNegation::Value(tmp); return true; } } else { // Result must be positive - if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt ) + if (tmp <= (unsigned __int64)IntTraits::maxInt) { *pRet = (signed __int64)tmp; return true; @@ -2412,39 +2767,41 @@ public: #endif } - template < typename E > - static void RegMultiplyThrow( const signed __int64& a, unsigned __int32 b, signed __int64* pRet ) + template + static void RegMultiplyThrow(const signed __int64& a, unsigned __int32 b, signed __int64* pRet) { #if SAFEINT_USE_INTRINSICS - if( !IntrinsicMultiplyInt64( a, (signed __int64)b, pRet ) ) + if (!IntrinsicMultiplyInt64(a, (signed __int64)b, pRet)) E::SafeIntOnOverflow(); #else bool aNegative = false; unsigned __int64 tmp; __int64 a1 = a; - if( a1 < 0 ) + if (a1 < 0) { aNegative = true; - a1 = (signed __int64)AbsValueHelper< signed __int64, GetAbsMethod< signed __int64 >::method >::Abs(a1); + a1 = (signed __int64) + AbsValueHelper::method>::Abs(a1); } - LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::template RegMultiplyThrow< E >( (unsigned __int64)a1, b, &tmp ); + LargeIntRegMultiply::template RegMultiplyThrow( + (unsigned __int64)a1, b, &tmp); // The unsigned multiplication didn't overflow - if( aNegative ) + if (aNegative) { // Result must be negative - if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt ) + if (tmp <= (unsigned __int64)IntTraits::minInt) { - *pRet = SignedNegation< signed __int64 >::Value( tmp ); + *pRet = SignedNegation::Value(tmp); return; } } else { // Result must be positive - if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt ) + if (tmp <= (unsigned __int64)IntTraits::maxInt) { *pRet = (signed __int64)tmp; return; @@ -2456,13 +2813,13 @@ public: } }; -template<> class LargeIntRegMultiply< signed __int64, signed __int32 > +template <> class LargeIntRegMultiply { public: - static bool RegMultiply( const signed __int64& a, signed __int32 b, signed __int64* pRet ) throw() + static bool RegMultiply(const signed __int64& a, signed __int32 b, signed __int64* pRet) throw() { #if SAFEINT_USE_INTRINSICS - return IntrinsicMultiplyInt64( a, (signed __int64)b, pRet ); + return IntrinsicMultiplyInt64(a, (signed __int64)b, pRet); #else bool aNegative = false; bool bNegative = false; @@ -2471,34 +2828,37 @@ public: __int64 a1 = a; __int64 b1 = b; - if( a1 < 0 ) + if (a1 < 0) { aNegative = true; - a1 = (signed __int64)AbsValueHelper< signed __int64, GetAbsMethod< signed __int64 >::method >::Abs(a1); + a1 = (signed __int64) + AbsValueHelper::method>::Abs(a1); } - if( b1 < 0 ) + if (b1 < 0) { bNegative = true; - b1 = (signed __int64)AbsValueHelper< signed __int64, GetAbsMethod< signed __int64 >::method >::Abs(b1); + b1 = (signed __int64) + AbsValueHelper::method>::Abs(b1); } - if( LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::RegMultiply( (unsigned __int64)a1, (unsigned __int32)b1, &tmp ) ) + if (LargeIntRegMultiply::RegMultiply( + (unsigned __int64)a1, (unsigned __int32)b1, &tmp)) { // The unsigned multiplication didn't overflow - if( aNegative ^ bNegative ) + if (aNegative ^ bNegative) { // Result must be negative - if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt ) + if (tmp <= (unsigned __int64)IntTraits::minInt) { - *pRet = SignedNegation< signed __int64 >::Value( tmp ); + *pRet = SignedNegation::Value(tmp); return true; } } else { // Result must be positive - if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt ) + if (tmp <= (unsigned __int64)IntTraits::maxInt) { *pRet = (signed __int64)tmp; return true; @@ -2510,11 +2870,11 @@ public: #endif } - template < typename E > - static void RegMultiplyThrow( signed __int64 a, signed __int32 b, signed __int64* pRet ) + template + static void RegMultiplyThrow(signed __int64 a, signed __int32 b, signed __int64* pRet) { #if SAFEINT_USE_INTRINSICS - if( !IntrinsicMultiplyInt64( a, (signed __int64)b, pRet ) ) + if (!IntrinsicMultiplyInt64(a, (signed __int64)b, pRet)) E::SafeIntOnOverflow(); #else bool aNegative = false; @@ -2522,34 +2882,37 @@ public: unsigned __int64 tmp; - if( a < 0 ) + if (a < 0) { aNegative = true; - a = (signed __int64)AbsValueHelper< signed __int64, GetAbsMethod< signed __int64 >::method >::Abs(a); + a = (signed __int64) + AbsValueHelper::method>::Abs(a); } - if( b < 0 ) + if (b < 0) { bNegative = true; - b = (signed __int32)AbsValueHelper< signed __int32, GetAbsMethod< signed __int32 >::method >::Abs(b); + b = (signed __int32) + AbsValueHelper::method>::Abs(b); } - LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::template RegMultiplyThrow< E >( (unsigned __int64)a, (unsigned __int32)b, &tmp ); + LargeIntRegMultiply::template RegMultiplyThrow( + (unsigned __int64)a, (unsigned __int32)b, &tmp); // The unsigned multiplication didn't overflow - if( aNegative ^ bNegative ) + if (aNegative ^ bNegative) { // Result must be negative - if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt ) + if (tmp <= (unsigned __int64)IntTraits::minInt) { - *pRet = SignedNegation< signed __int64 >::Value( tmp ); + *pRet = SignedNegation::Value(tmp); return; } } else { // Result must be positive - if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt ) + if (tmp <= (unsigned __int64)IntTraits::maxInt) { *pRet = (signed __int64)tmp; return; @@ -2561,18 +2924,17 @@ public: } }; -template<> class LargeIntRegMultiply< signed __int32, signed __int64 > +template <> class LargeIntRegMultiply { public: - static bool RegMultiply( signed __int32 a, const signed __int64& b, signed __int32* pRet ) throw() + static bool RegMultiply(signed __int32 a, const signed __int64& b, signed __int32* pRet) throw() { #if SAFEINT_USE_INTRINSICS __int64 tmp; - if( IntrinsicMultiplyInt64( a, b, &tmp ) ) + if (IntrinsicMultiplyInt64(a, b, &tmp)) { - if( tmp > IntTraits< signed __int32 >::maxInt || - tmp < IntTraits< signed __int32 >::minInt ) + if (tmp > IntTraits::maxInt || tmp < IntTraits::minInt) { return false; } @@ -2588,34 +2950,37 @@ public: unsigned __int32 tmp; __int64 b1 = b; - if( a < 0 ) + if (a < 0) { aNegative = true; - a = (signed __int32)AbsValueHelper< signed __int32, GetAbsMethod< signed __int32 >::method >::Abs(a); + a = (signed __int32) + AbsValueHelper::method>::Abs(a); } - if( b1 < 0 ) + if (b1 < 0) { bNegative = true; - b1 = (signed __int64)AbsValueHelper< signed __int64, GetAbsMethod< signed __int64 >::method >::Abs(b1); + b1 = (signed __int64) + AbsValueHelper::method>::Abs(b1); } - if( LargeIntRegMultiply< unsigned __int32, unsigned __int64 >::RegMultiply( (unsigned __int32)a, (unsigned __int64)b1, &tmp ) ) + if (LargeIntRegMultiply::RegMultiply( + (unsigned __int32)a, (unsigned __int64)b1, &tmp)) { // The unsigned multiplication didn't overflow - if( aNegative ^ bNegative ) + if (aNegative ^ bNegative) { // Result must be negative - if( tmp <= (unsigned __int32)IntTraits< signed __int32 >::minInt ) + if (tmp <= (unsigned __int32)IntTraits::minInt) { - *pRet = SignedNegation< signed __int32 >::Value( tmp ); + *pRet = SignedNegation::Value(tmp); return true; } } else { // Result must be positive - if( tmp <= (unsigned __int32)IntTraits< signed __int32 >::maxInt ) + if (tmp <= (unsigned __int32)IntTraits::maxInt) { *pRet = (signed __int32)tmp; return true; @@ -2627,16 +2992,15 @@ public: #endif } - template < typename E > - static void RegMultiplyThrow( signed __int32 a, const signed __int64& b, signed __int32* pRet ) + template + static void RegMultiplyThrow(signed __int32 a, const signed __int64& b, signed __int32* pRet) { #if SAFEINT_USE_INTRINSICS __int64 tmp; - if( IntrinsicMultiplyInt64( a, b, &tmp ) ) + if (IntrinsicMultiplyInt64(a, b, &tmp)) { - if( tmp > IntTraits< signed __int32 >::maxInt || - tmp < IntTraits< signed __int32 >::minInt ) + if (tmp > IntTraits::maxInt || tmp < IntTraits::minInt) { E::SafeIntOnOverflow(); } @@ -2652,34 +3016,37 @@ public: unsigned __int32 tmp; signed __int64 b2 = b; - if( a < 0 ) + if (a < 0) { aNegative = true; - a = (signed __int32)AbsValueHelper< signed __int32, GetAbsMethod< signed __int32 >::method >::Abs(a); + a = (signed __int32) + AbsValueHelper::method>::Abs(a); } - if( b < 0 ) + if (b < 0) { bNegative = true; - b2 = (signed __int64)AbsValueHelper< signed __int64, GetAbsMethod< signed __int64 >::method >::Abs(b2); + b2 = (signed __int64) + AbsValueHelper::method>::Abs(b2); } - LargeIntRegMultiply< unsigned __int32, unsigned __int64 >::template RegMultiplyThrow< E >( (unsigned __int32)a, (unsigned __int64)b2, &tmp ); + LargeIntRegMultiply::template RegMultiplyThrow( + (unsigned __int32)a, (unsigned __int64)b2, &tmp); // The unsigned multiplication didn't overflow - if( aNegative ^ bNegative ) + if (aNegative ^ bNegative) { // Result must be negative - if( tmp <= (unsigned __int32)IntTraits< signed __int32 >::minInt ) + if (tmp <= (unsigned __int32)IntTraits::minInt) { - *pRet = SignedNegation< signed __int32 >::Value( tmp ); + *pRet = SignedNegation::Value(tmp); return; } } else { // Result must be positive - if( tmp <= (unsigned __int32)IntTraits< signed __int32 >::maxInt ) + if (tmp <= (unsigned __int32)IntTraits::maxInt) { *pRet = (signed __int32)tmp; return; @@ -2691,39 +3058,42 @@ public: } }; -template<> class LargeIntRegMultiply< signed __int64, unsigned __int64 > +template <> class LargeIntRegMultiply { public: // Leave this one as-is - will call unsigned intrinsic internally - static bool RegMultiply( const signed __int64& a, const unsigned __int64& b, signed __int64* pRet ) throw() + static bool RegMultiply( + const signed __int64& a, const unsigned __int64& b, signed __int64* pRet) throw() { bool aNegative = false; unsigned __int64 tmp; __int64 a1 = a; - if( a1 < 0 ) + if (a1 < 0) { aNegative = true; - a1 = (signed __int64)AbsValueHelper< signed __int64, GetAbsMethod< signed __int64 >::method >::Abs(a1); + a1 = (signed __int64) + AbsValueHelper::method>::Abs(a1); } - if( LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::RegMultiply( (unsigned __int64)a1, (unsigned __int64)b, &tmp ) ) + if (LargeIntRegMultiply::RegMultiply( + (unsigned __int64)a1, (unsigned __int64)b, &tmp)) { // The unsigned multiplication didn't overflow - if( aNegative ) + if (aNegative) { // Result must be negative - if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt ) + if (tmp <= (unsigned __int64)IntTraits::minInt) { - *pRet = SignedNegation< signed __int64 >::Value( tmp ); + *pRet = SignedNegation::Value(tmp); return true; } } else { // Result must be positive - if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt ) + if (tmp <= (unsigned __int64)IntTraits::maxInt) { *pRet = (signed __int64)tmp; return true; @@ -2734,35 +3104,38 @@ public: return false; } - template < typename E > - static void RegMultiplyThrow( const signed __int64& a, const unsigned __int64& b, signed __int64* pRet ) + template + static void RegMultiplyThrow( + const signed __int64& a, const unsigned __int64& b, signed __int64* pRet) { bool aNegative = false; unsigned __int64 tmp; __int64 a1 = a; - if( a1 < 0 ) + if (a1 < 0) { aNegative = true; - a1 = (signed __int64)AbsValueHelper< signed __int64, GetAbsMethod< signed __int64 >::method >::Abs(a1); + a1 = (signed __int64) + AbsValueHelper::method>::Abs(a1); } - if( LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::RegMultiply( (unsigned __int64)a1, (unsigned __int64)b, &tmp ) ) + if (LargeIntRegMultiply::RegMultiply( + (unsigned __int64)a1, (unsigned __int64)b, &tmp)) { // The unsigned multiplication didn't overflow - if( aNegative ) + if (aNegative) { // Result must be negative - if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::minInt ) + if (tmp <= (unsigned __int64)IntTraits::minInt) { - *pRet = SignedNegation< signed __int64 >::Value( tmp ); + *pRet = SignedNegation::Value(tmp); return; } } else { // Result must be positive - if( tmp <= (unsigned __int64)IntTraits< signed __int64 >::maxInt ) + if (tmp <= (unsigned __int64)IntTraits::maxInt) { *pRet = (signed __int64)tmp; return; @@ -2777,65 +3150,70 @@ public: // In all of the following functions where LargeIntRegMultiply methods are called, // we need to properly transition types. The methods need __int64, __int32, etc. // but the variables being passed to us could be long long, long int, or long, depending on -// the compiler. Microsoft compiler knows that long long is the same type as __int64, but gcc doesn't +// the compiler. Microsoft compiler knows that long long is the same type as __int64, but gcc +// doesn't -template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_Uint64Uint64 > +template class MultiplicationHelper { public: // T, U are unsigned __int64 - static bool Multiply( const T& t, const U& u, T& ret ) throw() + static bool Multiply(const T& t, const U& u, T& ret) throw() { - C_ASSERT( IntTraits::isUint64 && IntTraits::isUint64 ); + C_ASSERT(IntTraits::isUint64 && IntTraits::isUint64); unsigned __int64 t1 = t; unsigned __int64 u1 = u; - return LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::RegMultiply( t1, u1, reinterpret_cast(&ret) ); + return LargeIntRegMultiply::RegMultiply( + t1, u1, reinterpret_cast(&ret)); } - template < typename E > + template static void MultiplyThrow(const unsigned __int64& t, const unsigned __int64& u, T& ret) { - C_ASSERT( IntTraits::isUint64 && IntTraits::isUint64 ); + C_ASSERT(IntTraits::isUint64 && IntTraits::isUint64); unsigned __int64 t1 = t; unsigned __int64 u1 = u; - LargeIntRegMultiply< unsigned __int64, unsigned __int64 >::template RegMultiplyThrow< E >( t1, u1, reinterpret_cast(&ret) ); + LargeIntRegMultiply::template RegMultiplyThrow( + t1, u1, reinterpret_cast(&ret)); } }; -template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_Uint64Uint > +template class MultiplicationHelper { public: // T is unsigned __int64 // U is any unsigned int 32-bit or less - static bool Multiply( const T& t, const U& u, T& ret ) throw() + static bool Multiply(const T& t, const U& u, T& ret) throw() { - C_ASSERT( IntTraits::isUint64 ); + C_ASSERT(IntTraits::isUint64); unsigned __int64 t1 = t; - return LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::RegMultiply( t1, (unsigned __int32)u, reinterpret_cast(&ret) ); + return LargeIntRegMultiply::RegMultiply( + t1, (unsigned __int32)u, reinterpret_cast(&ret)); } - template < typename E > - static void MultiplyThrow( const T& t, const U& u, T& ret ) + template static void MultiplyThrow(const T& t, const U& u, T& ret) { - C_ASSERT( IntTraits::isUint64 ); + C_ASSERT(IntTraits::isUint64); unsigned __int64 t1 = t; - LargeIntRegMultiply< unsigned __int64, unsigned __int32 >::template RegMultiplyThrow< E >( t1, (unsigned __int32)u, reinterpret_cast(&ret) ); + LargeIntRegMultiply::template RegMultiplyThrow( + t1, (unsigned __int32)u, reinterpret_cast(&ret)); } }; // converse of the previous function -template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_UintUint64 > +template class MultiplicationHelper { public: // T is any unsigned int up to 32-bit // U is unsigned __int64 static bool Multiply(const T& t, const U& u, T& ret) throw() { - C_ASSERT( IntTraits::isUint64 ); + C_ASSERT(IntTraits::isUint64); unsigned __int64 u1 = u; unsigned __int32 tmp; - if( LargeIntRegMultiply< unsigned __int32, unsigned __int64 >::RegMultiply( t, u1, &tmp ) && - SafeCastHelper< T, unsigned __int32, GetCastMethod< T, unsigned __int32 >::method >::Cast(tmp, ret) ) + if (LargeIntRegMultiply::RegMultiply(t, u1, &tmp) + && SafeCastHelper::method>::Cast(tmp, ret)) { return true; } @@ -2843,75 +3221,80 @@ public: return false; } - template < typename E > - static void MultiplyThrow(const T& t, const U& u, T& ret) + template static void MultiplyThrow(const T& t, const U& u, T& ret) { - C_ASSERT( IntTraits::isUint64 ); + C_ASSERT(IntTraits::isUint64); unsigned __int64 u1 = u; unsigned __int32 tmp; - LargeIntRegMultiply< unsigned __int32, unsigned __int64 >::template RegMultiplyThrow< E >( t, u1, &tmp ); - SafeCastHelper< T, unsigned __int32, GetCastMethod< T, unsigned __int32 >::method >::template CastThrow< E >(tmp, ret); + LargeIntRegMultiply::template RegMultiplyThrow( + t, u1, &tmp); + SafeCastHelper::method>::template CastThrow(tmp, ret); } }; -template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_Uint64Int > +template class MultiplicationHelper { public: // T is unsigned __int64 // U is any signed int, up to 64-bit static bool Multiply(const T& t, const U& u, T& ret) throw() { - C_ASSERT( IntTraits::isUint64 ); + C_ASSERT(IntTraits::isUint64); unsigned __int64 t1 = t; - return LargeIntRegMultiply< unsigned __int64, signed __int32 >::RegMultiply(t1, (signed __int32)u, reinterpret_cast< unsigned __int64* >(&ret)); + return LargeIntRegMultiply::RegMultiply( + t1, (signed __int32)u, reinterpret_cast(&ret)); } - template < typename E > - static void MultiplyThrow(const T& t, const U& u, T& ret) + template static void MultiplyThrow(const T& t, const U& u, T& ret) { - C_ASSERT( IntTraits::isUint64 ); + C_ASSERT(IntTraits::isUint64); unsigned __int64 t1 = t; - LargeIntRegMultiply< unsigned __int64, signed __int32 >::template RegMultiplyThrow< E >(t1, (signed __int32)u, reinterpret_cast< unsigned __int64* >(&ret)); + LargeIntRegMultiply::template RegMultiplyThrow( + t1, (signed __int32)u, reinterpret_cast(&ret)); } }; -template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_Uint64Int64 > +template class MultiplicationHelper { public: // T is unsigned __int64 // U is __int64 static bool Multiply(const T& t, const U& u, T& ret) throw() { - C_ASSERT( IntTraits::isUint64 && IntTraits::isInt64 ); + C_ASSERT(IntTraits::isUint64 && IntTraits::isInt64); unsigned __int64 t1 = t; - __int64 u1 = u; - return LargeIntRegMultiply< unsigned __int64, __int64 >::RegMultiply(t1, u1, reinterpret_cast< unsigned __int64* >(&ret)); + __int64 u1 = u; + return LargeIntRegMultiply::RegMultiply( + t1, u1, reinterpret_cast(&ret)); } - template < typename E > - static void MultiplyThrow(const T& t, const U& u, T& ret) + template static void MultiplyThrow(const T& t, const U& u, T& ret) { - C_ASSERT( IntTraits::isUint64 && IntTraits::isInt64 ); + C_ASSERT(IntTraits::isUint64 && IntTraits::isInt64); unsigned __int64 t1 = t; - __int64 u1 = u; - LargeIntRegMultiply< unsigned __int64, __int64 >::template RegMultiplyThrow< E >(t1, u1, reinterpret_cast< unsigned __int64* >(&ret)); + __int64 u1 = u; + LargeIntRegMultiply::template RegMultiplyThrow( + t1, u1, reinterpret_cast(&ret)); } }; -template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_UintInt64 > +template class MultiplicationHelper { public: // T is unsigned up to 32-bit // U is __int64 static bool Multiply(const T& t, const U& u, T& ret) throw() { - C_ASSERT( IntTraits::isInt64 ); - __int64 u1 = u; + C_ASSERT(IntTraits::isInt64); + __int64 u1 = u; unsigned __int32 tmp; - if( LargeIntRegMultiply< unsigned __int32, __int64 >::RegMultiply( (unsigned __int32)t, u1, &tmp ) && - SafeCastHelper< T, unsigned __int32, GetCastMethod< T, unsigned __int32 >::method >::Cast(tmp, ret) ) + if (LargeIntRegMultiply::RegMultiply( + (unsigned __int32)t, u1, &tmp) + && SafeCastHelper::method>::Cast(tmp, ret)) { return true; } @@ -2919,95 +3302,99 @@ public: return false; } - template < typename E > - static void MultiplyThrow(const T& t, const U& u, T& ret) + template static void MultiplyThrow(const T& t, const U& u, T& ret) { - C_ASSERT( IntTraits::isInt64 ); - __int64 u1 = u; + C_ASSERT(IntTraits::isInt64); + __int64 u1 = u; unsigned __int32 tmp; - LargeIntRegMultiply< unsigned __int32, __int64 >::template RegMultiplyThrow< E >( (unsigned __int32)t, u1, &tmp ); - SafeCastHelper< T, unsigned __int32, GetCastMethod< T, unsigned __int32 >::method >::template CastThrow< E >(tmp, ret); + LargeIntRegMultiply::template RegMultiplyThrow( + (unsigned __int32)t, u1, &tmp); + SafeCastHelper::method>::template CastThrow(tmp, ret); } }; -template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_Int64Uint > +template class MultiplicationHelper { public: // T is __int64 // U is unsigned up to 32-bit - static bool Multiply( const T& t, const U& u, T& ret ) throw() + static bool Multiply(const T& t, const U& u, T& ret) throw() { - C_ASSERT( IntTraits::isInt64 ); - __int64 t1 = t; - return LargeIntRegMultiply< __int64, unsigned __int32 >::RegMultiply( t1, (unsigned __int32)u, reinterpret_cast< __int64* >(&ret) ); + C_ASSERT(IntTraits::isInt64); + __int64 t1 = t; + return LargeIntRegMultiply<__int64, unsigned __int32>::RegMultiply( + t1, (unsigned __int32)u, reinterpret_cast<__int64*>(&ret)); } - template < typename E > - static void MultiplyThrow( const T& t, const U& u, T& ret ) + template static void MultiplyThrow(const T& t, const U& u, T& ret) { - C_ASSERT( IntTraits::isInt64 ); - __int64 t1 = t; - LargeIntRegMultiply< __int64, unsigned __int32 >::template RegMultiplyThrow< E >( t1, (unsigned __int32)u, reinterpret_cast< __int64* >(&ret) ); + C_ASSERT(IntTraits::isInt64); + __int64 t1 = t; + LargeIntRegMultiply<__int64, unsigned __int32>::template RegMultiplyThrow( + t1, (unsigned __int32)u, reinterpret_cast<__int64*>(&ret)); } }; -template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_Int64Int64 > +template class MultiplicationHelper { public: // T, U are __int64 - static bool Multiply( const T& t, const U& u, T& ret ) throw() + static bool Multiply(const T& t, const U& u, T& ret) throw() { - C_ASSERT( IntTraits::isInt64 && IntTraits::isInt64 ); - __int64 t1 = t; - __int64 u1 = u; - return LargeIntRegMultiply< __int64, __int64 >::RegMultiply( t1, u1, reinterpret_cast< __int64* >(&ret) ); + C_ASSERT(IntTraits::isInt64 && IntTraits::isInt64); + __int64 t1 = t; + __int64 u1 = u; + return LargeIntRegMultiply<__int64, __int64>::RegMultiply( + t1, u1, reinterpret_cast<__int64*>(&ret)); } - template < typename E > - static void MultiplyThrow( const T& t, const U& u, T& ret ) + template static void MultiplyThrow(const T& t, const U& u, T& ret) { - C_ASSERT( IntTraits::isInt64 && IntTraits::isInt64 ); - __int64 t1 = t; - __int64 u1 = u; - LargeIntRegMultiply< __int64, __int64 >::template RegMultiplyThrow< E >( t1, u1, reinterpret_cast< __int64* >(&ret)); + C_ASSERT(IntTraits::isInt64 && IntTraits::isInt64); + __int64 t1 = t; + __int64 u1 = u; + LargeIntRegMultiply<__int64, __int64>::template RegMultiplyThrow( + t1, u1, reinterpret_cast<__int64*>(&ret)); } }; -template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_Int64Int > +template class MultiplicationHelper { public: // T is __int64 // U is signed up to 32-bit - static bool Multiply( const T& t, U u, T& ret ) throw() + static bool Multiply(const T& t, U u, T& ret) throw() { - C_ASSERT( IntTraits::isInt64 ); - __int64 t1 = t; - return LargeIntRegMultiply< __int64, __int32 >::RegMultiply( t1, (__int32)u, reinterpret_cast< __int64* >(&ret)); + C_ASSERT(IntTraits::isInt64); + __int64 t1 = t; + return LargeIntRegMultiply<__int64, __int32>::RegMultiply( + t1, (__int32)u, reinterpret_cast<__int64*>(&ret)); } - template < typename E > - static void MultiplyThrow( const __int64& t, U u, T& ret ) + template static void MultiplyThrow(const __int64& t, U u, T& ret) { - C_ASSERT( IntTraits::isInt64 ); - __int64 t1 = t; - LargeIntRegMultiply< __int64, __int32 >::template RegMultiplyThrow< E >(t1, (__int32)u, reinterpret_cast< __int64* >(&ret)); + C_ASSERT(IntTraits::isInt64); + __int64 t1 = t; + LargeIntRegMultiply<__int64, __int32>::template RegMultiplyThrow( + t1, (__int32)u, reinterpret_cast<__int64*>(&ret)); } }; -template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_IntUint64 > +template class MultiplicationHelper { public: // T is signed up to 32-bit // U is unsigned __int64 static bool Multiply(T t, const U& u, T& ret) throw() { - C_ASSERT( IntTraits::isUint64 ); + C_ASSERT(IntTraits::isUint64); unsigned __int64 u1 = u; __int32 tmp; - if( LargeIntRegMultiply< __int32, unsigned __int64 >::RegMultiply( (__int32)t, u1, &tmp ) && - SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::Cast( tmp, ret ) ) + if (LargeIntRegMultiply<__int32, unsigned __int64>::RegMultiply((__int32)t, u1, &tmp) + && SafeCastHelper::method>::Cast(tmp, ret)) { return true; } @@ -3015,54 +3402,57 @@ public: return false; } - template < typename E > - static void MultiplyThrow(T t, const unsigned __int64& u, T& ret) + template static void MultiplyThrow(T t, const unsigned __int64& u, T& ret) { - C_ASSERT( IntTraits::isUint64 ); + C_ASSERT(IntTraits::isUint64); unsigned __int64 u1 = u; __int32 tmp; - LargeIntRegMultiply< __int32, unsigned __int64 >::template RegMultiplyThrow< E >( (__int32)t, u1, &tmp ); - SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::template CastThrow< E >( tmp, ret ); + LargeIntRegMultiply<__int32, unsigned __int64>::template RegMultiplyThrow( + (__int32)t, u1, &tmp); + SafeCastHelper::method>::template CastThrow( + tmp, ret); } }; -template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_Int64Uint64> +template class MultiplicationHelper { public: // T is __int64 // U is unsigned __int64 - static bool Multiply( const T& t, const U& u, T& ret ) throw() + static bool Multiply(const T& t, const U& u, T& ret) throw() { - C_ASSERT( IntTraits::isInt64 && IntTraits::isUint64 ); - __int64 t1 = t; + C_ASSERT(IntTraits::isInt64 && IntTraits::isUint64); + __int64 t1 = t; unsigned __int64 u1 = u; - return LargeIntRegMultiply< __int64, unsigned __int64 >::RegMultiply( t1, u1, reinterpret_cast< __int64* >(&ret) ); + return LargeIntRegMultiply<__int64, unsigned __int64>::RegMultiply( + t1, u1, reinterpret_cast<__int64*>(&ret)); } - template < typename E > - static void MultiplyThrow( const __int64& t, const unsigned __int64& u, T& ret ) + template + static void MultiplyThrow(const __int64& t, const unsigned __int64& u, T& ret) { - C_ASSERT( IntTraits::isInt64 && IntTraits::isUint64 ); - __int64 t1 = t; + C_ASSERT(IntTraits::isInt64 && IntTraits::isUint64); + __int64 t1 = t; unsigned __int64 u1 = u; - LargeIntRegMultiply< __int64, unsigned __int64 >::template RegMultiplyThrow< E >( t1, u1, reinterpret_cast< __int64* >(&ret) ); + LargeIntRegMultiply<__int64, unsigned __int64>::template RegMultiplyThrow( + t1, u1, reinterpret_cast<__int64*>(&ret)); } }; -template < typename T, typename U > class MultiplicationHelper< T, U, MultiplicationState_IntInt64> +template class MultiplicationHelper { public: // T is signed, up to 32-bit // U is __int64 - static bool Multiply( T t, const U& u, T& ret ) throw() + static bool Multiply(T t, const U& u, T& ret) throw() { - C_ASSERT( IntTraits::isInt64 ); + C_ASSERT(IntTraits::isInt64); __int64 u1 = u; __int32 tmp; - if( LargeIntRegMultiply< __int32, __int64 >::RegMultiply( (__int32)t, u1, &tmp ) && - SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::Cast( tmp, ret ) ) + if (LargeIntRegMultiply<__int32, __int64>::RegMultiply((__int32)t, u1, &tmp) + && SafeCastHelper::method>::Cast(tmp, ret)) { return true; } @@ -3070,15 +3460,15 @@ public: return false; } - template < typename E > - static void MultiplyThrow(T t, const U& u, T& ret) + template static void MultiplyThrow(T t, const U& u, T& ret) { - C_ASSERT( IntTraits::isInt64 ); + C_ASSERT(IntTraits::isInt64); __int64 u1 = u; __int32 tmp; - LargeIntRegMultiply< __int32, __int64 >::template RegMultiplyThrow< E >( (__int32)t, u1, &tmp ); - SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::template CastThrow< E >( tmp, ret ); + LargeIntRegMultiply<__int32, __int64>::template RegMultiplyThrow((__int32)t, u1, &tmp); + SafeCastHelper::method>::template CastThrow( + tmp, ret); } }; @@ -3092,82 +3482,84 @@ enum DivisionState DivisionState_SignedSigned }; -template < typename T, typename U > class DivisionMethod +template class DivisionMethod { public: enum { - method = (SafeIntCompare< T, U >::isBothUnsigned ? DivisionState_OK : - (!IntTraits< T >::isSigned && IntTraits< U >::isSigned) ? DivisionState_UnsignedSigned : - (IntTraits< T >::isSigned && - IntTraits< U >::isUint32 && - IntTraits< T >::isLT64Bit) ? DivisionState_SignedUnsigned32 : - (IntTraits< T >::isSigned && IntTraits< U >::isUint64) ? DivisionState_SignedUnsigned64 : - (IntTraits< T >::isSigned && !IntTraits< U >::isSigned) ? DivisionState_SignedUnsigned : - DivisionState_SignedSigned) + method = (SafeIntCompare::isBothUnsigned + ? DivisionState_OK + : (!IntTraits::isSigned && IntTraits::isSigned) + ? DivisionState_UnsignedSigned + : (IntTraits::isSigned && IntTraits::isUint32 && IntTraits::isLT64Bit) + ? DivisionState_SignedUnsigned32 + : (IntTraits::isSigned && IntTraits::isUint64) + ? DivisionState_SignedUnsigned64 + : (IntTraits::isSigned && !IntTraits::isSigned) + ? DivisionState_SignedUnsigned + : DivisionState_SignedSigned) }; }; -template < typename T, typename U, int state > class DivisionHelper; +template class DivisionHelper; -template < typename T, typename U > class DivisionHelper< T, U, DivisionState_OK > +template class DivisionHelper { public: - static SafeIntError Divide( const T& t, const U& u, T& result ) throw() + static SafeIntError Divide(const T& t, const U& u, T& result) throw() { - if( u == 0 ) + if (u == 0) return SafeIntDivideByZero; - if( t == 0 ) + if (t == 0) { result = 0; return SafeIntNoError; } - result = (T)( t/u ); + result = (T)(t / u); return SafeIntNoError; } - template < typename E > - static void DivideThrow( const T& t, const U& u, T& result ) + template static void DivideThrow(const T& t, const U& u, T& result) { - if( u == 0 ) + if (u == 0) E::SafeIntOnDivZero(); - if( t == 0 ) + if (t == 0) { result = 0; return; } - result = (T)( t/u ); + result = (T)(t / u); } }; -template < typename T, typename U > class DivisionHelper< T, U, DivisionState_UnsignedSigned> +template class DivisionHelper { public: - static SafeIntError Divide( const T& t, const U& u, T& result ) throw() + static SafeIntError Divide(const T& t, const U& u, T& result) throw() { - if( u == 0 ) + if (u == 0) return SafeIntDivideByZero; - if( t == 0 ) + if (t == 0) { result = 0; return SafeIntNoError; } - if( u > 0 ) + if (u > 0) { - result = (T)( t/u ); + result = (T)(t / u); return SafeIntNoError; } // it is always an error to try and divide an unsigned number by a negative signed number // unless u is bigger than t - if( AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( u ) > t ) + if (AbsValueHelper::method>::Abs(u) > t) { result = 0; return SafeIntNoError; @@ -3176,28 +3568,27 @@ public: return SafeIntArithmeticOverflow; } - template < typename E > - static void DivideThrow( const T& t, const U& u, T& result ) + template static void DivideThrow(const T& t, const U& u, T& result) { - if( u == 0 ) + if (u == 0) E::SafeIntOnDivZero(); - if( t == 0 ) + if (t == 0) { result = 0; return; } - if( u > 0 ) + if (u > 0) { - result = (T)( t/u ); + result = (T)(t / u); return; } // it is always an error to try and divide an unsigned number by a negative signed number // unless u is bigger than t - if( AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( u ) > t ) + if (AbsValueHelper::method>::Abs(u) > t) { result = 0; return; @@ -3207,15 +3598,15 @@ public: } }; -template < typename T, typename U > class DivisionHelper< T, U, DivisionState_SignedUnsigned32 > +template class DivisionHelper { public: - static SafeIntError Divide( const T& t, const U& u, T& result ) throw() + static SafeIntError Divide(const T& t, const U& u, T& result) throw() { - if( u == 0 ) + if (u == 0) return SafeIntDivideByZero; - if( t == 0 ) + if (t == 0) { result = 0; return SafeIntNoError; @@ -3223,25 +3614,25 @@ public: // Test for t > 0 // If t < 0, must explicitly upcast, or implicit upcast to ulong will cause errors - // As it turns out, 32-bit division is about twice as fast, which justifies the extra conditional + // As it turns out, 32-bit division is about twice as fast, which justifies the extra + // conditional - if( t > 0 ) - result = (T)( t/u ); + if (t > 0) + result = (T)(t / u); else - result = (T)( (__int64)t/(__int64)u ); + result = (T)((__int64)t / (__int64)u); return SafeIntNoError; } - template < typename E > - static void DivideThrow( const T& t, const U& u, T& result ) + template static void DivideThrow(const T& t, const U& u, T& result) { - if( u == 0 ) + if (u == 0) { E::SafeIntOnDivZero(); } - if( t == 0 ) + if (t == 0) { result = 0; return; @@ -3249,43 +3640,44 @@ public: // Test for t > 0 // If t < 0, must explicitly upcast, or implicit upcast to ulong will cause errors - // As it turns out, 32-bit division is about twice as fast, which justifies the extra conditional + // As it turns out, 32-bit division is about twice as fast, which justifies the extra + // conditional - if( t > 0 ) - result = (T)( t/u ); + if (t > 0) + result = (T)(t / u); else - result = (T)( (__int64)t/(__int64)u ); + result = (T)((__int64)t / (__int64)u); } }; -template < typename T, typename U > class DivisionHelper< T, U, DivisionState_SignedUnsigned64 > +template class DivisionHelper { public: - static SafeIntError Divide( const T& t, const unsigned __int64& u, T& result ) throw() + static SafeIntError Divide(const T& t, const unsigned __int64& u, T& result) throw() { - C_ASSERT( IntTraits< U >::isUint64 ); + C_ASSERT(IntTraits::isUint64); - if( u == 0 ) + if (u == 0) { return SafeIntDivideByZero; } - if( t == 0 ) + if (t == 0) { result = 0; return SafeIntNoError; } - if( u <= (unsigned __int64)IntTraits< T >::maxInt ) + if (u <= (unsigned __int64)IntTraits::maxInt) { // Else u can safely be cast to T - if( CompileConst< sizeof( T ) < sizeof( __int64 )>::Value() ) - result = (T)( (int)t/(int)u ); + if (CompileConst::Value()) + result = (T)((int)t / (int)u); else - result = (T)((__int64)t/(__int64)u); + result = (T)((__int64)t / (__int64)u); } else // Corner case - if( t == IntTraits< T >::minInt && u == (unsigned __int64)IntTraits< T >::minInt ) + if (t == IntTraits::minInt && u == (unsigned __int64)IntTraits::minInt) { // Min int divided by it's own magnitude is -1 result = -1; @@ -3297,32 +3689,31 @@ public: return SafeIntNoError; } - template < typename E > - static void DivideThrow( const T& t, const unsigned __int64& u, T& result ) + template static void DivideThrow(const T& t, const unsigned __int64& u, T& result) { - C_ASSERT( IntTraits< U >::isUint64 ); + C_ASSERT(IntTraits::isUint64); - if( u == 0 ) + if (u == 0) { E::SafeIntOnDivZero(); } - if( t == 0 ) + if (t == 0) { result = 0; return; } - if( u <= (unsigned __int64)IntTraits< T >::maxInt ) + if (u <= (unsigned __int64)IntTraits::maxInt) { // Else u can safely be cast to T - if( CompileConst< sizeof( T ) < sizeof( __int64 ) >::Value() ) - result = (T)( (int)t/(int)u ); + if (CompileConst::Value()) + result = (T)((int)t / (int)u); else - result = (T)((__int64)t/(__int64)u); + result = (T)((__int64)t / (__int64)u); } else // Corner case - if( t == IntTraits< T >::minInt && u == (unsigned __int64)IntTraits< T >::minInt ) + if (t == IntTraits::minInt && u == (unsigned __int64)IntTraits::minInt) { // Min int divided by it's own magnitude is -1 result = -1; @@ -3334,89 +3725,87 @@ public: } }; -template < typename T, typename U > class DivisionHelper< T, U, DivisionState_SignedUnsigned> +template class DivisionHelper { public: // T is any signed, U is unsigned and smaller than 32-bit // In this case, standard operator casting is correct - static SafeIntError Divide( const T& t, const U& u, T& result ) throw() + static SafeIntError Divide(const T& t, const U& u, T& result) throw() { - if( u == 0 ) + if (u == 0) { return SafeIntDivideByZero; } - if( t == 0 ) + if (t == 0) { result = 0; return SafeIntNoError; } - result = (T)( t/u ); + result = (T)(t / u); return SafeIntNoError; } - template < typename E > - static void DivideThrow( const T& t, const U& u, T& result ) + template static void DivideThrow(const T& t, const U& u, T& result) { - if( u == 0 ) + if (u == 0) { E::SafeIntOnDivZero(); } - if( t == 0 ) + if (t == 0) { result = 0; return; } - result = (T)( t/u ); + result = (T)(t / u); } }; -template < typename T, typename U > class DivisionHelper< T, U, DivisionState_SignedSigned> +template class DivisionHelper { public: - static SafeIntError Divide( const T& t, const U& u, T& result ) throw() + static SafeIntError Divide(const T& t, const U& u, T& result) throw() { - if( u == 0 ) + if (u == 0) { return SafeIntDivideByZero; } - if( t == 0 ) + if (t == 0) { result = 0; return SafeIntNoError; } // Must test for corner case - if( t == IntTraits< T >::minInt && u == (U)-1 ) + if (t == IntTraits::minInt && u == (U)-1) return SafeIntArithmeticOverflow; - result = (T)( t/u ); + result = (T)(t / u); return SafeIntNoError; } - template < typename E > - static void DivideThrow( const T& t, const U& u, T& result ) + template static void DivideThrow(const T& t, const U& u, T& result) { - if(u == 0) + if (u == 0) { E::SafeIntOnDivZero(); } - if( t == 0 ) + if (t == 0) { result = 0; return; } // Must test for corner case - if( t == IntTraits< T >::minInt && u == (U)-1 ) + if (t == IntTraits::minInt && u == (U)-1) E::SafeIntOnOverflow(); - result = (T)( t/u ); + result = (T)(t / u); } }; @@ -3440,54 +3829,82 @@ enum AdditionState AdditionState_Error }; -template< typename T, typename U > -class AdditionMethod +template class AdditionMethod { public: enum { - //unsigned-unsigned - method = (IntRegion< T,U >::IntZone_UintLT32_UintLT32 ? AdditionState_CastIntCheckMax : - (IntRegion< T,U >::IntZone_Uint32_UintLT64) ? AdditionState_CastUintCheckOverflow : - (IntRegion< T,U >::IntZone_UintLT32_Uint32) ? AdditionState_CastUintCheckOverflowMax : - (IntRegion< T,U >::IntZone_Uint64_Uint) ? AdditionState_CastUint64CheckOverflow : - (IntRegion< T,U >::IntZone_UintLT64_Uint64) ? AdditionState_CastUint64CheckOverflowMax : - //unsigned-signed - (IntRegion< T,U >::IntZone_UintLT32_IntLT32) ? AdditionState_CastIntCheckMinMax : - (IntRegion< T,U >::IntZone_Uint32_IntLT64 || - IntRegion< T,U >::IntZone_UintLT32_Int32) ? AdditionState_CastInt64CheckMinMax : - (IntRegion< T,U >::IntZone_Uint64_Int || - IntRegion< T,U >::IntZone_Uint64_Int64) ? AdditionState_CastUint64CheckMinMax : - (IntRegion< T,U >::IntZone_UintLT64_Int64) ? AdditionState_CastUint64CheckMinMax2 : - //signed-signed - (IntRegion< T,U >::IntZone_IntLT32_IntLT32) ? AdditionState_CastIntCheckMinMax : - (IntRegion< T,U >::IntZone_Int32_IntLT64 || - IntRegion< T,U >::IntZone_IntLT32_Int32) ? AdditionState_CastInt64CheckMinMax : - (IntRegion< T,U >::IntZone_Int64_Int || - IntRegion< T,U >::IntZone_Int64_Int64) ? AdditionState_CastInt64CheckOverflow : - (IntRegion< T,U >::IntZone_IntLT64_Int64) ? AdditionState_CastInt64CheckOverflowMinMax : - //signed-unsigned - (IntRegion< T,U >::IntZone_IntLT32_UintLT32) ? AdditionState_CastIntCheckMax : - (IntRegion< T,U >::IntZone_Int32_UintLT32 || - IntRegion< T,U >::IntZone_IntLT64_Uint32) ? AdditionState_CastInt64CheckMax : - (IntRegion< T,U >::IntZone_Int64_UintLT64) ? AdditionState_CastInt64CheckOverflowMax : - (IntRegion< T,U >::IntZone_Int64_Uint64) ? AdditionState_ManualCheckInt64Uint64 : - (IntRegion< T,U >::IntZone_Int_Uint64) ? AdditionState_ManualCheck : - AdditionState_Error) + // unsigned-unsigned + method + = (IntRegion::IntZone_UintLT32_UintLT32 ? AdditionState_CastIntCheckMax + : (IntRegion::IntZone_Uint32_UintLT64) + ? AdditionState_CastUintCheckOverflow + : (IntRegion::IntZone_UintLT32_Uint32) + ? AdditionState_CastUintCheckOverflowMax + : (IntRegion::IntZone_Uint64_Uint) + ? AdditionState_CastUint64CheckOverflow + : (IntRegion::IntZone_UintLT64_Uint64) + ? AdditionState_CastUint64CheckOverflowMax + : + // unsigned-signed + (IntRegion::IntZone_UintLT32_IntLT32) + ? AdditionState_CastIntCheckMinMax + : (IntRegion::IntZone_Uint32_IntLT64 + || IntRegion::IntZone_UintLT32_Int32) + ? AdditionState_CastInt64CheckMinMax + : (IntRegion::IntZone_Uint64_Int + || IntRegion::IntZone_Uint64_Int64) + ? AdditionState_CastUint64CheckMinMax + : (IntRegion::IntZone_UintLT64_Int64) + ? AdditionState_CastUint64CheckMinMax2 + : + // signed-signed + (IntRegion::IntZone_IntLT32_IntLT32) + ? AdditionState_CastIntCheckMinMax + : (IntRegion::IntZone_Int32_IntLT64 + || IntRegion::IntZone_IntLT32_Int32) + ? AdditionState_CastInt64CheckMinMax + : (IntRegion::IntZone_Int64_Int + || IntRegion::IntZone_Int64_Int64) + ? AdditionState_CastInt64CheckOverflow + : (IntRegion::IntZone_IntLT64_Int64) + ? AdditionState_CastInt64CheckOverflowMinMax + : + // signed-unsigned + (IntRegion::IntZone_IntLT32_UintLT32) + ? AdditionState_CastIntCheckMax + : (IntRegion:: + IntZone_Int32_UintLT32 + || IntRegion:: + IntZone_IntLT64_Uint32) + ? AdditionState_CastInt64CheckMax + : (IntRegion::IntZone_Int64_UintLT64) + ? AdditionState_CastInt64CheckOverflowMax + : (IntRegion::IntZone_Int64_Uint64) + ? AdditionState_ManualCheckInt64Uint64 + : (IntRegion::IntZone_Int_Uint64) + ? AdditionState_ManualCheck + : AdditionState_Error) }; }; -template < typename T, typename U, int method > class AdditionHelper; +template class AdditionHelper; -template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastIntCheckMax > +template class AdditionHelper { public: - static bool Addition( const T& lhs, const U& rhs, T& result ) throw() + static bool Addition(const T& lhs, const U& rhs, T& result) throw() { - //16-bit or less unsigned addition + // 16-bit or less unsigned addition __int32 tmp = lhs + rhs; - if( tmp <= (__int32)IntTraits< T >::maxInt ) + if (tmp <= (__int32)IntTraits::maxInt) { result = (T)tmp; return true; @@ -3496,13 +3913,12 @@ public: return false; } - template < typename E > - static void AdditionThrow( const T& lhs, const U& rhs, T& result ) + template static void AdditionThrow(const T& lhs, const U& rhs, T& result) { - //16-bit or less unsigned addition + // 16-bit or less unsigned addition __int32 tmp = lhs + rhs; - if( tmp <= (__int32)IntTraits< T >::maxInt ) + if (tmp <= (__int32)IntTraits::maxInt) { result = (T)tmp; return; @@ -3512,16 +3928,16 @@ public: } }; -template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastUintCheckOverflow > +template class AdditionHelper { public: - static bool Addition( const T& lhs, const U& rhs, T& result ) throw() + static bool Addition(const T& lhs, const U& rhs, T& result) throw() { // 32-bit or less - both are unsigned unsigned __int32 tmp = (unsigned __int32)lhs + (unsigned __int32)rhs; - //we added didn't get smaller - if( tmp >= lhs ) + // we added didn't get smaller + if (tmp >= lhs) { result = (T)tmp; return true; @@ -3529,14 +3945,13 @@ public: return false; } - template < typename E > - static void AdditionThrow( const T& lhs, const U& rhs, T& result ) + template static void AdditionThrow(const T& lhs, const U& rhs, T& result) { // 32-bit or less - both are unsigned unsigned __int32 tmp = (unsigned __int32)lhs + (unsigned __int32)rhs; - //we added didn't get smaller - if( tmp >= lhs ) + // we added didn't get smaller + if (tmp >= lhs) { result = (T)tmp; return; @@ -3545,16 +3960,16 @@ public: } }; -template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastUintCheckOverflowMax> +template class AdditionHelper { public: - static bool Addition( const T& lhs, const U& rhs, T& result ) throw() + static bool Addition(const T& lhs, const U& rhs, T& result) throw() { // 32-bit or less - both are unsigned unsigned __int32 tmp = (unsigned __int32)lhs + (unsigned __int32)rhs; // We added and it didn't get smaller or exceed maxInt - if( tmp >= lhs && tmp <= IntTraits< T >::maxInt ) + if (tmp >= lhs && tmp <= IntTraits::maxInt) { result = (T)tmp; return true; @@ -3562,14 +3977,13 @@ public: return false; } - template < typename E > - static void AdditionThrow( const T& lhs, const U& rhs, T& result ) + template static void AdditionThrow(const T& lhs, const U& rhs, T& result) { - //32-bit or less - both are unsigned + // 32-bit or less - both are unsigned unsigned __int32 tmp = (unsigned __int32)lhs + (unsigned __int32)rhs; // We added and it didn't get smaller or exceed maxInt - if( tmp >= lhs && tmp <= IntTraits< T >::maxInt ) + if (tmp >= lhs && tmp <= IntTraits::maxInt) { result = (T)tmp; return; @@ -3578,16 +3992,16 @@ public: } }; -template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastUint64CheckOverflow> +template class AdditionHelper { public: - static bool Addition( const T& lhs, const U& rhs, T& result ) throw() + static bool Addition(const T& lhs, const U& rhs, T& result) throw() { // lhs unsigned __int64, rhs unsigned unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)rhs; // We added and it didn't get smaller - if(tmp >= lhs) + if (tmp >= lhs) { result = (T)tmp; return true; @@ -3596,14 +4010,13 @@ public: return false; } - template < typename E > - static void AdditionThrow( const T& lhs, const U& rhs, T& result ) + template static void AdditionThrow(const T& lhs, const U& rhs, T& result) { // lhs unsigned __int64, rhs unsigned unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)rhs; // We added and it didn't get smaller - if(tmp >= lhs) + if (tmp >= lhs) { result = (T)tmp; return; @@ -3613,16 +4026,17 @@ public: } }; -template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastUint64CheckOverflowMax > +template +class AdditionHelper { public: - static bool Addition( const T& lhs, const U& rhs, T& result ) throw() + static bool Addition(const T& lhs, const U& rhs, T& result) throw() { - //lhs unsigned __int64, rhs unsigned + // lhs unsigned __int64, rhs unsigned unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)rhs; // We added and it didn't get smaller - if( tmp >= lhs && tmp <= IntTraits< T >::maxInt ) + if (tmp >= lhs && tmp <= IntTraits::maxInt) { result = (T)tmp; return true; @@ -3631,14 +4045,13 @@ public: return false; } - template < typename E > - static void AdditionThrow( const T& lhs, const U& rhs, T& result ) + template static void AdditionThrow(const T& lhs, const U& rhs, T& result) { - //lhs unsigned __int64, rhs unsigned + // lhs unsigned __int64, rhs unsigned unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)rhs; // We added and it didn't get smaller - if( tmp >= lhs && tmp <= IntTraits< T >::maxInt ) + if (tmp >= lhs && tmp <= IntTraits::maxInt) { result = (T)tmp; return; @@ -3648,15 +4061,15 @@ public: } }; -template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastIntCheckMinMax > +template class AdditionHelper { public: - static bool Addition( const T& lhs, const U& rhs, T& result ) throw() + static bool Addition(const T& lhs, const U& rhs, T& result) throw() { // 16-bit or less - one or both are signed __int32 tmp = lhs + rhs; - if( tmp <= (__int32)IntTraits< T >::maxInt && tmp >= (__int32)IntTraits< T >::minInt ) + if (tmp <= (__int32)IntTraits::maxInt && tmp >= (__int32)IntTraits::minInt) { result = (T)tmp; return true; @@ -3665,13 +4078,12 @@ public: return false; } - template < typename E > - static void AdditionThrow( const T& lhs, const U& rhs, T& result ) + template static void AdditionThrow(const T& lhs, const U& rhs, T& result) { // 16-bit or less - one or both are signed __int32 tmp = lhs + rhs; - if( tmp <= (__int32)IntTraits< T >::maxInt && tmp >= (__int32)IntTraits< T >::minInt ) + if (tmp <= (__int32)IntTraits::maxInt && tmp >= (__int32)IntTraits::minInt) { result = (T)tmp; return; @@ -3681,15 +4093,15 @@ public: } }; -template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastInt64CheckMinMax > +template class AdditionHelper { public: - static bool Addition( const T& lhs, const U& rhs, T& result ) throw() + static bool Addition(const T& lhs, const U& rhs, T& result) throw() { // 32-bit or less - one or both are signed __int64 tmp = (__int64)lhs + (__int64)rhs; - if( tmp <= (__int64)IntTraits< T >::maxInt && tmp >= (__int64)IntTraits< T >::minInt ) + if (tmp <= (__int64)IntTraits::maxInt && tmp >= (__int64)IntTraits::minInt) { result = (T)tmp; return true; @@ -3698,13 +4110,12 @@ public: return false; } - template < typename E > - static void AdditionThrow( const T& lhs, const U& rhs, T& result ) + template static void AdditionThrow(const T& lhs, const U& rhs, T& result) { // 32-bit or less - one or both are signed __int64 tmp = (__int64)lhs + (__int64)rhs; - if( tmp <= (__int64)IntTraits< T >::maxInt && tmp >= (__int64)IntTraits< T >::minInt ) + if (tmp <= (__int64)IntTraits::maxInt && tmp >= (__int64)IntTraits::minInt) { result = (T)tmp; return; @@ -3714,15 +4125,15 @@ public: } }; -template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastInt64CheckMax > +template class AdditionHelper { public: - static bool Addition( const T& lhs, const U& rhs, T& result ) throw() + static bool Addition(const T& lhs, const U& rhs, T& result) throw() { // 32-bit or less - lhs signed, rhs unsigned __int64 tmp = (__int64)lhs + (__int64)rhs; - if( tmp <= IntTraits< T >::maxInt ) + if (tmp <= IntTraits::maxInt) { result = (T)tmp; return true; @@ -3731,13 +4142,12 @@ public: return false; } - template < typename E > - static void AdditionThrow( const T& lhs, const U& rhs, T& result ) + template static void AdditionThrow(const T& lhs, const U& rhs, T& result) { // 32-bit or less - lhs signed, rhs unsigned __int64 tmp = (__int64)lhs + (__int64)rhs; - if( tmp <= IntTraits< T >::maxInt ) + if (tmp <= IntTraits::maxInt) { result = (T)tmp; return; @@ -3747,20 +4157,20 @@ public: } }; -template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastUint64CheckMinMax > +template class AdditionHelper { public: - static bool Addition( const T& lhs, const U& rhs, T& result ) throw() + static bool Addition(const T& lhs, const U& rhs, T& result) throw() { // lhs is unsigned __int64, rhs signed unsigned __int64 tmp; - if( rhs < 0 ) + if (rhs < 0) { // So we're effectively subtracting - tmp = AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( rhs ); + tmp = AbsValueHelper::method>::Abs(rhs); - if( tmp <= lhs ) + if (tmp <= lhs) { result = lhs - tmp; return true; @@ -3772,7 +4182,7 @@ public: tmp = (unsigned __int64)lhs + (unsigned __int64)rhs; // We added and it did not become smaller - if( tmp >= lhs ) + if (tmp >= lhs) { result = (T)tmp; return true; @@ -3782,18 +4192,17 @@ public: return false; } - template < typename E > - static void AdditionThrow( const T& lhs, const U& rhs, T& result ) + template static void AdditionThrow(const T& lhs, const U& rhs, T& result) { // lhs is unsigned __int64, rhs signed unsigned __int64 tmp; - if( rhs < 0 ) + if (rhs < 0) { // So we're effectively subtracting - tmp = AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( rhs ); + tmp = AbsValueHelper::method>::Abs(rhs); - if( tmp <= lhs ) + if (tmp <= lhs) { result = lhs - tmp; return; @@ -3805,7 +4214,7 @@ public: tmp = (unsigned __int64)lhs + (unsigned __int64)rhs; // We added and it did not become smaller - if( tmp >= lhs ) + if (tmp >= lhs) { result = (T)tmp; return; @@ -3816,17 +4225,17 @@ public: } }; -template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastUint64CheckMinMax2> +template class AdditionHelper { public: - static bool Addition( const T& lhs, const U& rhs, T& result ) throw() + static bool Addition(const T& lhs, const U& rhs, T& result) throw() { // lhs is unsigned and < 64-bit, rhs signed __int64 - if( rhs < 0 ) + if (rhs < 0) { - if( lhs >= ~(unsigned __int64)( rhs ) + 1 )//negation is safe, since rhs is 64-bit + if (lhs >= ~(unsigned __int64)(rhs) + 1) // negation is safe, since rhs is 64-bit { - result = (T)( lhs + rhs ); + result = (T)(lhs + rhs); return true; } } @@ -3835,9 +4244,10 @@ public: // now we know that rhs can be safely cast into an unsigned __int64 unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)rhs; - // special case - rhs cannot be larger than 0x7fffffffffffffff, lhs cannot be larger than 0xffffffff + // special case - rhs cannot be larger than 0x7fffffffffffffff, lhs cannot be larger + // than 0xffffffff // it is not possible for the operation above to overflow, so just check max - if( tmp <= IntTraits< T >::maxInt ) + if (tmp <= IntTraits::maxInt) { result = (T)tmp; return true; @@ -3846,15 +4256,14 @@ public: return false; } - template < typename E > - static void AdditionThrow( const T& lhs, const U& rhs, T& result ) + template static void AdditionThrow(const T& lhs, const U& rhs, T& result) { // lhs is unsigned and < 64-bit, rhs signed __int64 - if( rhs < 0 ) + if (rhs < 0) { - if( lhs >= ~(unsigned __int64)( rhs ) + 1) //negation is safe, since rhs is 64-bit + if (lhs >= ~(unsigned __int64)(rhs) + 1) // negation is safe, since rhs is 64-bit { - result = (T)( lhs + rhs ); + result = (T)(lhs + rhs); return; } } @@ -3863,9 +4272,10 @@ public: // now we know that rhs can be safely cast into an unsigned __int64 unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)rhs; - // special case - rhs cannot be larger than 0x7fffffffffffffff, lhs cannot be larger than 0xffffffff + // special case - rhs cannot be larger than 0x7fffffffffffffff, lhs cannot be larger + // than 0xffffffff // it is not possible for the operation above to overflow, so just check max - if( tmp <= IntTraits< T >::maxInt ) + if (tmp <= IntTraits::maxInt) { result = (T)tmp; return; @@ -3875,24 +4285,24 @@ public: } }; -template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastInt64CheckOverflow> +template class AdditionHelper { public: - static bool Addition( const T& lhs, const U& rhs, T& result ) throw() + static bool Addition(const T& lhs, const U& rhs, T& result) throw() { // lhs is signed __int64, rhs signed __int64 tmp = (__int64)((unsigned __int64)lhs + (unsigned __int64)rhs); - if( lhs >= 0 ) + if (lhs >= 0) { // mixed sign cannot overflow - if( rhs >= 0 && tmp < lhs ) + if (rhs >= 0 && tmp < lhs) return false; } else { // lhs negative - if( rhs < 0 && tmp > lhs ) + if (rhs < 0 && tmp > lhs) return false; } @@ -3900,22 +4310,21 @@ public: return true; } - template < typename E > - static void AdditionThrow( const T& lhs, const U& rhs, T& result ) + template static void AdditionThrow(const T& lhs, const U& rhs, T& result) { // lhs is signed __int64, rhs signed __int64 tmp = (__int64)((unsigned __int64)lhs + (unsigned __int64)rhs); - if( lhs >= 0 ) + if (lhs >= 0) { // mixed sign cannot overflow - if( rhs >= 0 && tmp < lhs ) + if (rhs >= 0 && tmp < lhs) E::SafeIntOnOverflow(); } else { // lhs negative - if( rhs < 0 && tmp > lhs ) + if (rhs < 0 && tmp > lhs) E::SafeIntOnOverflow(); } @@ -3923,17 +4332,18 @@ public: } }; -template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastInt64CheckOverflowMinMax> +template +class AdditionHelper { public: - static bool Addition( const T& lhs, const U& rhs, T& result ) throw() + static bool Addition(const T& lhs, const U& rhs, T& result) throw() { - //rhs is signed __int64, lhs signed + // rhs is signed __int64, lhs signed __int64 tmp; - if( AdditionHelper< __int64, __int64, AdditionState_CastInt64CheckOverflow >::Addition( (__int64)lhs, (__int64)rhs, tmp ) && - tmp <= IntTraits< T >::maxInt && - tmp >= IntTraits< T >::minInt ) + if (AdditionHelper<__int64, __int64, AdditionState_CastInt64CheckOverflow>::Addition( + (__int64)lhs, (__int64)rhs, tmp) + && tmp <= IntTraits::maxInt && tmp >= IntTraits::minInt) { result = (T)tmp; return true; @@ -3942,16 +4352,15 @@ public: return false; } - template < typename E > - static void AdditionThrow( const T& lhs, const U& rhs, T& result ) + template static void AdditionThrow(const T& lhs, const U& rhs, T& result) { - //rhs is signed __int64, lhs signed + // rhs is signed __int64, lhs signed __int64 tmp; - AdditionHelper< __int64, __int64, AdditionState_CastInt64CheckOverflow >::AdditionThrow< E >( (__int64)lhs, (__int64)rhs, tmp ); + AdditionHelper<__int64, __int64, AdditionState_CastInt64CheckOverflow>::AdditionThrow( + (__int64)lhs, (__int64)rhs, tmp); - if( tmp <= IntTraits< T >::maxInt && - tmp >= IntTraits< T >::minInt ) + if (tmp <= IntTraits::maxInt && tmp >= IntTraits::minInt) { result = (T)tmp; return; @@ -3961,15 +4370,16 @@ public: } }; -template < typename T, typename U > class AdditionHelper < T, U, AdditionState_CastInt64CheckOverflowMax> +template +class AdditionHelper { public: - static bool Addition( const T& lhs, const U& rhs, T& result ) throw() + static bool Addition(const T& lhs, const U& rhs, T& result) throw() { - //lhs is signed __int64, rhs unsigned < 64-bit + // lhs is signed __int64, rhs unsigned < 64-bit unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)rhs; - if( (__int64)tmp >= lhs ) + if ((__int64)tmp >= lhs) { result = (T)(__int64)tmp; return true; @@ -3978,15 +4388,14 @@ public: return false; } - template < typename E > - static void AdditionThrow( const T& lhs, const U& rhs, T& result ) + template static void AdditionThrow(const T& lhs, const U& rhs, T& result) { // lhs is signed __int64, rhs unsigned < 64-bit // Some compilers get optimization-happy, let's thwart them unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)rhs; - if( (__int64)tmp >= lhs ) + if ((__int64)tmp >= lhs) { result = (T)(__int64)tmp; return; @@ -3996,18 +4405,18 @@ public: } }; -template < typename T, typename U > class AdditionHelper < T, U, AdditionState_ManualCheckInt64Uint64 > +template class AdditionHelper { public: - static bool Addition( const __int64& lhs, const unsigned __int64& rhs, __int64& result ) throw() + static bool Addition(const __int64& lhs, const unsigned __int64& rhs, __int64& result) throw() { - C_ASSERT( IntTraits< T >::isInt64 && IntTraits< U >::isUint64 ); + C_ASSERT(IntTraits::isInt64 && IntTraits::isUint64); // rhs is unsigned __int64, lhs __int64 // cast everything to unsigned, perform addition, then // cast back for check - this is done to stop optimizers from removing the code unsigned __int64 tmp = (unsigned __int64)lhs + rhs; - if( (__int64)tmp >= lhs ) + if ((__int64)tmp >= lhs) { result = (__int64)tmp; return true; @@ -4016,14 +4425,14 @@ public: return false; } - template < typename E > - static void AdditionThrow( const __int64& lhs, const unsigned __int64& rhs, T& result ) + template + static void AdditionThrow(const __int64& lhs, const unsigned __int64& rhs, T& result) { - C_ASSERT( IntTraits< T >::isInt64 && IntTraits< U >::isUint64 ); + C_ASSERT(IntTraits::isInt64 && IntTraits::isUint64); // rhs is unsigned __int64, lhs __int64 unsigned __int64 tmp = (unsigned __int64)lhs + rhs; - if( (__int64)tmp >= lhs ) + if ((__int64)tmp >= lhs) { result = (__int64)tmp; return; @@ -4033,40 +4442,42 @@ public: } }; -template < typename T, typename U > class AdditionHelper < T, U, AdditionState_ManualCheck> +template class AdditionHelper { public: - static bool Addition( const T& lhs, const U& rhs, T& result ) throw() + static bool Addition(const T& lhs, const U& rhs, T& result) throw() { // rhs is unsigned __int64, lhs signed, 32-bit or less - if( (unsigned __int32)( rhs >> 32 ) == 0 ) + if ((unsigned __int32)(rhs >> 32) == 0) { // Now it just happens to work out that the standard behavior does what we want // Adding explicit casts to show exactly what's happening here // Note - this is tweaked to keep optimizers from tossing out the code. unsigned __int32 tmp = (unsigned __int32)rhs + (unsigned __int32)lhs; - if( (__int32)tmp >= lhs && SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::Cast( (__int32)tmp, result ) ) + if ((__int32)tmp >= lhs + && SafeCastHelper::method>::Cast( + (__int32)tmp, result)) return true; } return false; } - template < typename E > - static void AdditionThrow( const T& lhs, const U& rhs, T& result ) + template static void AdditionThrow(const T& lhs, const U& rhs, T& result) { // rhs is unsigned __int64, lhs signed, 32-bit or less - if( (unsigned __int32)( rhs >> 32 ) == 0 ) + if ((unsigned __int32)(rhs >> 32) == 0) { // Now it just happens to work out that the standard behavior does what we want // Adding explicit casts to show exactly what's happening here unsigned __int32 tmp = (unsigned __int32)rhs + (unsigned __int32)lhs; - if( (__int32)tmp >= lhs ) + if ((__int32)tmp >= lhs) { - SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::template CastThrow< E >( (__int32)tmp, result ); + SafeCastHelper::method>::template CastThrow((__int32)tmp, result); return; } } @@ -4102,103 +4513,139 @@ enum SubtractionState SubtractionState_Error }; -template < typename T, typename U > class SubtractionMethod +template class SubtractionMethod { public: enum { - // unsigned-unsigned - method = ((IntRegion< T,U >::IntZone_UintLT32_UintLT32 || - (IntRegion< T,U >::IntZone_Uint32_UintLT64) || - (IntRegion< T,U >::IntZone_UintLT32_Uint32) || - (IntRegion< T,U >::IntZone_Uint64_Uint) || - (IntRegion< T,U >::IntZone_UintLT64_Uint64)) ? SubtractionState_BothUnsigned : - // unsigned-signed - (IntRegion< T,U >::IntZone_UintLT32_IntLT32) ? SubtractionState_CastIntCheckMinMax : - (IntRegion< T,U >::IntZone_Uint32_IntLT64 || - IntRegion< T,U >::IntZone_UintLT32_Int32) ? SubtractionState_CastInt64CheckMinMax : - (IntRegion< T,U >::IntZone_Uint64_Int || - IntRegion< T,U >::IntZone_Uint64_Int64) ? SubtractionState_Uint64Int : - (IntRegion< T,U >::IntZone_UintLT64_Int64) ? SubtractionState_UintInt64 : - // signed-signed - (IntRegion< T,U >::IntZone_IntLT32_IntLT32) ? SubtractionState_CastIntCheckMinMax : - (IntRegion< T,U >::IntZone_Int32_IntLT64 || - IntRegion< T,U >::IntZone_IntLT32_Int32) ? SubtractionState_CastInt64CheckMinMax : - (IntRegion< T,U >::IntZone_Int64_Int || - IntRegion< T,U >::IntZone_Int64_Int64) ? SubtractionState_Int64Int : - (IntRegion< T,U >::IntZone_IntLT64_Int64) ? SubtractionState_IntInt64 : - // signed-unsigned - (IntRegion< T,U >::IntZone_IntLT32_UintLT32) ? SubtractionState_CastIntCheckMin : - (IntRegion< T,U >::IntZone_Int32_UintLT32 || - IntRegion< T,U >::IntZone_IntLT64_Uint32) ? SubtractionState_CastInt64CheckMin : - (IntRegion< T,U >::IntZone_Int64_UintLT64) ? SubtractionState_Int64Uint : - (IntRegion< T,U >::IntZone_Int_Uint64) ? SubtractionState_IntUint64 : - (IntRegion< T,U >::IntZone_Int64_Uint64) ? SubtractionState_Int64Uint64 : - SubtractionState_Error) + // unsigned-unsigned + method + = ((IntRegion::IntZone_UintLT32_UintLT32 || (IntRegion::IntZone_Uint32_UintLT64) + || (IntRegion::IntZone_UintLT32_Uint32) + || (IntRegion::IntZone_Uint64_Uint) + || (IntRegion::IntZone_UintLT64_Uint64)) + ? SubtractionState_BothUnsigned + : + // unsigned-signed + (IntRegion::IntZone_UintLT32_IntLT32) + ? SubtractionState_CastIntCheckMinMax + : (IntRegion::IntZone_Uint32_IntLT64 + || IntRegion::IntZone_UintLT32_Int32) + ? SubtractionState_CastInt64CheckMinMax + : (IntRegion::IntZone_Uint64_Int + || IntRegion::IntZone_Uint64_Int64) + ? SubtractionState_Uint64Int + : (IntRegion::IntZone_UintLT64_Int64) ? SubtractionState_UintInt64 + : + // signed-signed + (IntRegion::IntZone_IntLT32_IntLT32) + ? SubtractionState_CastIntCheckMinMax + : (IntRegion::IntZone_Int32_IntLT64 + || IntRegion::IntZone_IntLT32_Int32) + ? SubtractionState_CastInt64CheckMinMax + : (IntRegion::IntZone_Int64_Int + || IntRegion::IntZone_Int64_Int64) + ? SubtractionState_Int64Int + : (IntRegion::IntZone_IntLT64_Int64) + ? SubtractionState_IntInt64 + : + // signed-unsigned + (IntRegion::IntZone_IntLT32_UintLT32) + ? SubtractionState_CastIntCheckMin + : (IntRegion::IntZone_Int32_UintLT32 + || IntRegion::IntZone_IntLT64_Uint32) + ? SubtractionState_CastInt64CheckMin + : (IntRegion::IntZone_Int64_UintLT64) + ? SubtractionState_Int64Uint + : (IntRegion::IntZone_Int_Uint64) + ? SubtractionState_IntUint64 + : (IntRegion::IntZone_Int64_Uint64) + ? SubtractionState_Int64Uint64 + : SubtractionState_Error) }; }; // this is for the case of U - SafeInt< T, E > -template < typename T, typename U > class SubtractionMethod2 +template class SubtractionMethod2 { public: enum { - // unsigned-unsigned - method = ((IntRegion< T,U >::IntZone_UintLT32_UintLT32 || - (IntRegion< T,U >::IntZone_Uint32_UintLT64) || - (IntRegion< T,U >::IntZone_UintLT32_Uint32) || - (IntRegion< T,U >::IntZone_Uint64_Uint) || - (IntRegion< T,U >::IntZone_UintLT64_Uint64)) ? SubtractionState_BothUnsigned2 : - // unsigned-signed - (IntRegion< T,U >::IntZone_UintLT32_IntLT32) ? SubtractionState_CastIntCheckMinMax2 : - (IntRegion< T,U >::IntZone_Uint32_IntLT64 || - IntRegion< T,U >::IntZone_UintLT32_Int32) ? SubtractionState_CastInt64CheckMinMax2 : - (IntRegion< T,U >::IntZone_Uint64_Int || - IntRegion< T,U >::IntZone_Uint64_Int64) ? SubtractionState_Uint64Int2 : - (IntRegion< T,U >::IntZone_UintLT64_Int64) ? SubtractionState_UintInt642 : - // signed-signed - (IntRegion< T,U >::IntZone_IntLT32_IntLT32) ? SubtractionState_CastIntCheckMinMax2 : - (IntRegion< T,U >::IntZone_Int32_IntLT64 || - IntRegion< T,U >::IntZone_IntLT32_Int32) ? SubtractionState_CastInt64CheckMinMax2 : - (IntRegion< T,U >::IntZone_Int64_Int || - IntRegion< T,U >::IntZone_Int64_Int64) ? SubtractionState_Int64Int2 : - (IntRegion< T,U >::IntZone_IntLT64_Int64) ? SubtractionState_IntInt642 : - // signed-unsigned - (IntRegion< T,U >::IntZone_IntLT32_UintLT32) ? SubtractionState_CastIntCheckMinMax2 : - (IntRegion< T,U >::IntZone_Int32_UintLT32 || - IntRegion< T,U >::IntZone_IntLT64_Uint32) ? SubtractionState_CastInt64CheckMinMax2 : - (IntRegion< T,U >::IntZone_Int64_UintLT64) ? SubtractionState_Int64Uint2 : - (IntRegion< T,U >::IntZone_Int_Uint64) ? SubtractionState_IntUint642 : - (IntRegion< T,U >::IntZone_Int64_Uint64) ? SubtractionState_Int64Uint642 : - SubtractionState_Error) + // unsigned-unsigned + method + = ((IntRegion::IntZone_UintLT32_UintLT32 || (IntRegion::IntZone_Uint32_UintLT64) + || (IntRegion::IntZone_UintLT32_Uint32) + || (IntRegion::IntZone_Uint64_Uint) + || (IntRegion::IntZone_UintLT64_Uint64)) + ? SubtractionState_BothUnsigned2 + : + // unsigned-signed + (IntRegion::IntZone_UintLT32_IntLT32) + ? SubtractionState_CastIntCheckMinMax2 + : (IntRegion::IntZone_Uint32_IntLT64 + || IntRegion::IntZone_UintLT32_Int32) + ? SubtractionState_CastInt64CheckMinMax2 + : (IntRegion::IntZone_Uint64_Int + || IntRegion::IntZone_Uint64_Int64) + ? SubtractionState_Uint64Int2 + : (IntRegion::IntZone_UintLT64_Int64) + ? SubtractionState_UintInt642 + : + // signed-signed + (IntRegion::IntZone_IntLT32_IntLT32) + ? SubtractionState_CastIntCheckMinMax2 + : (IntRegion::IntZone_Int32_IntLT64 + || IntRegion::IntZone_IntLT32_Int32) + ? SubtractionState_CastInt64CheckMinMax2 + : (IntRegion::IntZone_Int64_Int + || IntRegion::IntZone_Int64_Int64) + ? SubtractionState_Int64Int2 + : (IntRegion::IntZone_IntLT64_Int64) + ? SubtractionState_IntInt642 + : + // signed-unsigned + (IntRegion::IntZone_IntLT32_UintLT32) + ? SubtractionState_CastIntCheckMinMax2 + : (IntRegion::IntZone_Int32_UintLT32 + || IntRegion::IntZone_IntLT64_Uint32) + ? SubtractionState_CastInt64CheckMinMax2 + : (IntRegion::IntZone_Int64_UintLT64) + ? SubtractionState_Int64Uint2 + : (IntRegion::IntZone_Int_Uint64) + ? SubtractionState_IntUint642 + : (IntRegion::IntZone_Int64_Uint64) + ? SubtractionState_Int64Uint642 + : SubtractionState_Error) }; }; -template < typename T, typename U, int method > class SubtractionHelper; +template class SubtractionHelper; -template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_BothUnsigned > +template class SubtractionHelper { public: - static bool Subtract( const T& lhs, const U& rhs, T& result ) throw() + static bool Subtract(const T& lhs, const U& rhs, T& result) throw() { // both are unsigned - easy case - if( rhs <= lhs ) + if (rhs <= lhs) { - result = (T)( lhs - rhs ); + result = (T)(lhs - rhs); return true; } return false; } - template < typename E > - static void SubtractThrow( const T& lhs, const U& rhs, T& result ) + template static void SubtractThrow(const T& lhs, const U& rhs, T& result) { // both are unsigned - easy case - if( rhs <= lhs ) + if (rhs <= lhs) { - result = (T)( lhs - rhs ); + result = (T)(lhs - rhs); return; } @@ -4206,30 +4653,29 @@ public: } }; -template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_BothUnsigned2 > +template class SubtractionHelper { public: - static bool Subtract( const T& lhs, const U& rhs, U& result ) throw() + static bool Subtract(const T& lhs, const U& rhs, U& result) throw() { // both are unsigned - easy case // Except we do have to check for overflow - lhs could be larger than result can hold - if( rhs <= lhs ) + if (rhs <= lhs) { T tmp = (T)(lhs - rhs); - return SafeCastHelper< U, T, GetCastMethod::method>::Cast( tmp, result); + return SafeCastHelper::method>::Cast(tmp, result); } return false; } - template < typename E > - static void SubtractThrow( const T& lhs, const U& rhs, U& result ) + template static void SubtractThrow(const T& lhs, const U& rhs, U& result) { // both are unsigned - easy case - if( rhs <= lhs ) + if (rhs <= lhs) { T tmp = (T)(lhs - rhs); - SafeCastHelper< U, T, GetCastMethod::method >::template CastThrow( tmp, result); + SafeCastHelper::method>::template CastThrow(tmp, result); return; } @@ -4237,16 +4683,16 @@ public: } }; -template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_CastIntCheckMinMax > +template class SubtractionHelper { public: - static bool Subtract( const T& lhs, const U& rhs, T& result ) throw() + static bool Subtract(const T& lhs, const U& rhs, T& result) throw() { // both values are 16-bit or less // rhs is signed, so could end up increasing or decreasing __int32 tmp = lhs - rhs; - if( SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::Cast( tmp, result ) ) + if (SafeCastHelper::method>::Cast(tmp, result)) { result = (T)tmp; return true; @@ -4255,50 +4701,51 @@ public: return false; } - template < typename E > - static void SubtractThrow( const T& lhs, const U& rhs, T& result ) + template static void SubtractThrow(const T& lhs, const U& rhs, T& result) { // both values are 16-bit or less // rhs is signed, so could end up increasing or decreasing __int32 tmp = lhs - rhs; - SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::template CastThrow< E >( tmp, result ); + SafeCastHelper::method>::template CastThrow( + tmp, result); } }; -template class SubtractionHelper< U, T, SubtractionState_CastIntCheckMinMax2 > +template +class SubtractionHelper { public: - static bool Subtract( const U& lhs, const T& rhs, T& result ) throw() + static bool Subtract(const U& lhs, const T& rhs, T& result) throw() { // both values are 16-bit or less // rhs is signed, so could end up increasing or decreasing __int32 tmp = lhs - rhs; - return SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::Cast( tmp, result ); + return SafeCastHelper::method>::Cast(tmp, result); } - template < typename E > - static void SubtractThrow( const U& lhs, const T& rhs, T& result ) + template static void SubtractThrow(const U& lhs, const T& rhs, T& result) { // both values are 16-bit or less // rhs is signed, so could end up increasing or decreasing __int32 tmp = lhs - rhs; - SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::template CastThrow< E >( tmp, result ); + SafeCastHelper::method>::template CastThrow( + tmp, result); } }; -template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_CastIntCheckMin > +template class SubtractionHelper { public: - static bool Subtract( const T& lhs, const U& rhs, T& result ) throw() + static bool Subtract(const T& lhs, const U& rhs, T& result) throw() { // both values are 16-bit or less // rhs is unsigned - check only minimum __int32 tmp = lhs - rhs; - if( tmp >= (__int32)IntTraits< T >::minInt ) + if (tmp >= (__int32)IntTraits::minInt) { result = (T)tmp; return true; @@ -4307,14 +4754,13 @@ public: return false; } - template < typename E > - static void SubtractThrow( const T& lhs, const U& rhs, T& result ) + template static void SubtractThrow(const T& lhs, const U& rhs, T& result) { // both values are 16-bit or less // rhs is unsigned - check only minimum __int32 tmp = lhs - rhs; - if( tmp >= (__int32)IntTraits< T >::minInt ) + if (tmp >= (__int32)IntTraits::minInt) { result = (T)tmp; return; @@ -4324,62 +4770,64 @@ public: } }; -template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_CastInt64CheckMinMax > +template +class SubtractionHelper { public: - static bool Subtract( const T& lhs, const U& rhs, T& result ) throw() + static bool Subtract(const T& lhs, const U& rhs, T& result) throw() { // both values are 32-bit or less // rhs is signed, so could end up increasing or decreasing __int64 tmp = (__int64)lhs - (__int64)rhs; - return SafeCastHelper< T, __int64, GetCastMethod< T, __int64 >::method >::Cast( tmp, result ); + return SafeCastHelper::method>::Cast(tmp, result); } - template < typename E > - static void SubtractThrow( const T& lhs, const U& rhs, T& result ) + template static void SubtractThrow(const T& lhs, const U& rhs, T& result) { // both values are 32-bit or less // rhs is signed, so could end up increasing or decreasing __int64 tmp = (__int64)lhs - (__int64)rhs; - SafeCastHelper< T, __int64, GetCastMethod< T, __int64 >::method >::template CastThrow< E >( tmp, result ); + SafeCastHelper::method>::template CastThrow( + tmp, result); } }; -template class SubtractionHelper< U, T, SubtractionState_CastInt64CheckMinMax2 > +template +class SubtractionHelper { public: - static bool Subtract( const U& lhs, const T& rhs, T& result ) throw() + static bool Subtract(const U& lhs, const T& rhs, T& result) throw() { // both values are 32-bit or less // rhs is signed, so could end up increasing or decreasing __int64 tmp = (__int64)lhs - (__int64)rhs; - return SafeCastHelper< T, __int64, GetCastMethod< T, __int64 >::method >::Cast( tmp, result ); + return SafeCastHelper::method>::Cast(tmp, result); } - template < typename E > - static void SubtractThrow( const U& lhs, const T& rhs, T& result ) + template static void SubtractThrow(const U& lhs, const T& rhs, T& result) { // both values are 32-bit or less // rhs is signed, so could end up increasing or decreasing __int64 tmp = (__int64)lhs - (__int64)rhs; - SafeCastHelper< T, __int64, GetCastMethod< T, __int64 >::method >::template CastThrow< E >( tmp, result ); + SafeCastHelper::method>::template CastThrow( + tmp, result); } }; -template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_CastInt64CheckMin > +template class SubtractionHelper { public: - static bool Subtract( const T& lhs, const U& rhs, T& result ) throw() + static bool Subtract(const T& lhs, const U& rhs, T& result) throw() { // both values are 32-bit or less // rhs is unsigned - check only minimum __int64 tmp = (__int64)lhs - (__int64)rhs; - if( tmp >= (__int64)IntTraits< T >::minInt ) + if (tmp >= (__int64)IntTraits::minInt) { result = (T)tmp; return true; @@ -4388,14 +4836,13 @@ public: return false; } - template < typename E > - static void SubtractThrow( const T& lhs, const U& rhs, T& result ) + template static void SubtractThrow(const T& lhs, const U& rhs, T& result) { // both values are 32-bit or less // rhs is unsigned - check only minimum __int64 tmp = (__int64)lhs - (__int64)rhs; - if( tmp >= (__int64)IntTraits< T >::minInt ) + if (tmp >= (__int64)IntTraits::minInt) { result = (T)tmp; return; @@ -4405,18 +4852,18 @@ public: } }; -template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_Uint64Int > +template class SubtractionHelper { public: - static bool Subtract( const T& lhs, const U& rhs, T& result ) throw() + static bool Subtract(const T& lhs, const U& rhs, T& result) throw() { // lhs is an unsigned __int64, rhs signed // must first see if rhs is positive or negative - if( rhs >= 0 ) + if (rhs >= 0) { - if( (unsigned __int64)rhs <= lhs ) + if ((unsigned __int64)rhs <= lhs) { - result = (T)( lhs - (unsigned __int64)rhs ); + result = (T)(lhs - (unsigned __int64)rhs); return true; } } @@ -4424,25 +4871,24 @@ public: { T tmp = lhs; // we're now effectively adding - result = lhs + AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( rhs ); + result = lhs + AbsValueHelper::method>::Abs(rhs); - if(result >= tmp) + if (result >= tmp) return true; } return false; } - template < typename E > - static void SubtractThrow( const T& lhs, const U& rhs, T& result ) + template static void SubtractThrow(const T& lhs, const U& rhs, T& result) { // lhs is an unsigned __int64, rhs signed // must first see if rhs is positive or negative - if( rhs >= 0 ) + if (rhs >= 0) { - if( (unsigned __int64)rhs <= lhs ) + if ((unsigned __int64)rhs <= lhs) { - result = (T)( lhs - (unsigned __int64)rhs ); + result = (T)(lhs - (unsigned __int64)rhs); return; } } @@ -4450,9 +4896,9 @@ public: { T tmp = lhs; // we're now effectively adding - result = lhs + AbsValueHelper< U, GetAbsMethod< U >::method >::Abs( rhs ); + result = lhs + AbsValueHelper::method>::Abs(rhs); - if(result >= tmp) + if (result >= tmp) return; } @@ -4460,27 +4906,27 @@ public: } }; -template < typename U, typename T > class SubtractionHelper< U, T, SubtractionState_Uint64Int2 > +template class SubtractionHelper { public: - static bool Subtract( const U& lhs, const T& rhs, T& result ) throw() + static bool Subtract(const U& lhs, const T& rhs, T& result) throw() { // U is unsigned __int64, T is signed - if( rhs < 0 ) + if (rhs < 0) { // treat this as addition unsigned __int64 tmp; - tmp = lhs + (unsigned __int64)AbsValueHelper< T, GetAbsMethod< T >::method >::Abs( rhs ); + tmp = lhs + (unsigned __int64)AbsValueHelper::method>::Abs(rhs); // must check for addition overflow and max - if( tmp >= lhs && tmp <= IntTraits< T >::maxInt ) + if (tmp >= lhs && tmp <= IntTraits::maxInt) { result = (T)tmp; return true; } } - else if( (unsigned __int64)rhs > lhs ) // now both are positive, so comparison always works + else if ((unsigned __int64)rhs > lhs) // now both are positive, so comparison always works { // result is negative // implies that lhs must fit into T, and result cannot overflow @@ -4493,7 +4939,7 @@ public: // result is positive unsigned __int64 tmp = (unsigned __int64)lhs - (unsigned __int64)rhs; - if( tmp <= IntTraits< T >::maxInt ) + if (tmp <= IntTraits::maxInt) { result = (T)tmp; return true; @@ -4503,25 +4949,24 @@ public: return false; } - template < typename E > - static void SubtractThrow( const U& lhs, const T& rhs, T& result ) + template static void SubtractThrow(const U& lhs, const T& rhs, T& result) { // U is unsigned __int64, T is signed - if( rhs < 0 ) + if (rhs < 0) { // treat this as addition unsigned __int64 tmp; - tmp = lhs + (unsigned __int64)AbsValueHelper< T, GetAbsMethod< T >::method >::Abs( rhs ); + tmp = lhs + (unsigned __int64)AbsValueHelper::method>::Abs(rhs); // must check for addition overflow and max - if( tmp >= lhs && tmp <= IntTraits< T >::maxInt ) + if (tmp >= lhs && tmp <= IntTraits::maxInt) { result = (T)tmp; return; } } - else if( (unsigned __int64)rhs > lhs ) // now both are positive, so comparison always works + else if ((unsigned __int64)rhs > lhs) // now both are positive, so comparison always works { // result is negative // implies that lhs must fit into T, and result cannot overflow @@ -4534,7 +4979,7 @@ public: // result is positive unsigned __int64 tmp = (unsigned __int64)lhs - (unsigned __int64)rhs; - if( tmp <= IntTraits< T >::maxInt ) + if (tmp <= IntTraits::maxInt) { result = (T)tmp; return; @@ -4545,18 +4990,18 @@ public: } }; -template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_UintInt64 > +template class SubtractionHelper { public: - static bool Subtract( const T& lhs, const U& rhs, T& result ) throw() + static bool Subtract(const T& lhs, const U& rhs, T& result) throw() { // lhs is an unsigned int32 or smaller, rhs signed __int64 // must first see if rhs is positive or negative - if( rhs >= 0 ) + if (rhs >= 0) { - if( (unsigned __int64)rhs <= lhs ) + if ((unsigned __int64)rhs <= lhs) { - result = (T)( lhs - (T)rhs ); + result = (T)(lhs - (T)rhs); return true; } } @@ -4565,10 +5010,10 @@ public: // we're now effectively adding // since lhs is 32-bit, and rhs cannot exceed 2^63 // this addition cannot overflow - unsigned __int64 tmp = lhs + ~(unsigned __int64)( rhs ) + 1; // negation safe + unsigned __int64 tmp = lhs + ~(unsigned __int64)(rhs) + 1; // negation safe // but we could exceed MaxInt - if(tmp <= IntTraits< T >::maxInt) + if (tmp <= IntTraits::maxInt) { result = (T)tmp; return true; @@ -4578,16 +5023,15 @@ public: return false; } - template < typename E > - static void SubtractThrow( const T& lhs, const U& rhs, T& result ) + template static void SubtractThrow(const T& lhs, const U& rhs, T& result) { // lhs is an unsigned int32 or smaller, rhs signed __int64 // must first see if rhs is positive or negative - if( rhs >= 0 ) + if (rhs >= 0) { - if( (unsigned __int64)rhs <= lhs ) + if ((unsigned __int64)rhs <= lhs) { - result = (T)( lhs - (T)rhs ); + result = (T)(lhs - (T)rhs); return; } } @@ -4596,10 +5040,10 @@ public: // we're now effectively adding // since lhs is 32-bit, and rhs cannot exceed 2^63 // this addition cannot overflow - unsigned __int64 tmp = lhs + ~(unsigned __int64)( rhs ) + 1; // negation safe + unsigned __int64 tmp = lhs + ~(unsigned __int64)(rhs) + 1; // negation safe // but we could exceed MaxInt - if(tmp <= IntTraits< T >::maxInt) + if (tmp <= IntTraits::maxInt) { result = (T)tmp; return; @@ -4610,25 +5054,25 @@ public: } }; -template class SubtractionHelper< U, T, SubtractionState_UintInt642 > +template class SubtractionHelper { public: - static bool Subtract( const U& lhs, const T& rhs, T& result ) throw() + static bool Subtract(const U& lhs, const T& rhs, T& result) throw() { // U unsigned 32-bit or less, T __int64 - if( rhs >= 0 ) + if (rhs >= 0) { // overflow not possible - result = (T)( (__int64)lhs - rhs ); + result = (T)((__int64)lhs - rhs); return true; } else { // we effectively have an addition // which cannot overflow internally - unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)( -rhs ); + unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)(-rhs); - if( tmp <= (unsigned __int64)IntTraits< T >::maxInt ) + if (tmp <= (unsigned __int64)IntTraits::maxInt) { result = (T)tmp; return true; @@ -4638,23 +5082,22 @@ public: return false; } - template < typename E > - static void SubtractThrow( const U& lhs, const T& rhs, T& result ) + template static void SubtractThrow(const U& lhs, const T& rhs, T& result) { // U unsigned 32-bit or less, T __int64 - if( rhs >= 0 ) + if (rhs >= 0) { // overflow not possible - result = (T)( (__int64)lhs - rhs ); + result = (T)((__int64)lhs - rhs); return; } else { // we effectively have an addition // which cannot overflow internally - unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)( -rhs ); + unsigned __int64 tmp = (unsigned __int64)lhs + (unsigned __int64)(-rhs); - if( tmp <= (unsigned __int64)IntTraits< T >::maxInt ) + if (tmp <= (unsigned __int64)IntTraits::maxInt) { result = (T)tmp; return; @@ -4665,10 +5108,10 @@ public: } }; -template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_Int64Int > +template class SubtractionHelper { public: - static bool Subtract( const T& lhs, const U& rhs, T& result ) throw() + static bool Subtract(const T& lhs, const U& rhs, T& result) throw() { // lhs is an __int64, rhs signed (up to 64-bit) // we have essentially 4 cases: @@ -4683,8 +5126,8 @@ public: // Note - ideally, we can order these so that true conditionals // lead to success, which enables better pipelining // It isn't practical here - if( ( lhs >= 0 && rhs < 0 && tmp < lhs ) || // condition 2 - ( rhs >= 0 && tmp > lhs ) ) // condition 3 + if ((lhs >= 0 && rhs < 0 && tmp < lhs) || // condition 2 + (rhs >= 0 && tmp > lhs)) // condition 3 { return false; } @@ -4693,8 +5136,7 @@ public: return true; } - template < typename E > - static void SubtractThrow( const T& lhs, const U& rhs, T& result ) + template static void SubtractThrow(const T& lhs, const U& rhs, T& result) { // lhs is an __int64, rhs signed (up to 64-bit) // we have essentially 4 cases: @@ -4709,8 +5151,8 @@ public: // Note - ideally, we can order these so that true conditionals // lead to success, which enables better pipelining // It isn't practical here - if( ( lhs >= 0 && rhs < 0 && tmp < lhs ) || // condition 2 - ( rhs >= 0 && tmp > lhs ) ) // condition 3 + if ((lhs >= 0 && rhs < 0 && tmp < lhs) || // condition 2 + (rhs >= 0 && tmp > lhs)) // condition 3 { E::SafeIntOnOverflow(); } @@ -4719,10 +5161,10 @@ public: } }; -template < typename U, typename T > class SubtractionHelper< U, T, SubtractionState_Int64Int2 > +template class SubtractionHelper { public: - static bool Subtract( const U& lhs, const T& rhs, T& result ) throw() + static bool Subtract(const U& lhs, const T& rhs, T& result) throw() { // lhs __int64, rhs any signed int (including __int64) __int64 tmp = lhs - rhs; @@ -4734,12 +5176,11 @@ public: // 3) lhs negative, rhs positive - check result <= lhs // 4) lhs negative, rhs negative - overflow not possible in tmp - if( lhs >= 0 ) + if (lhs >= 0) { // if both positive, overflow to negative not possible // which is why we'll explicitly check maxInt, and not call SafeCast - if( ( IntTraits< T >::isLT64Bit && tmp > IntTraits< T >::maxInt ) || - ( rhs < 0 && tmp < lhs ) ) + if ((IntTraits::isLT64Bit && tmp > IntTraits::maxInt) || (rhs < 0 && tmp < lhs)) { return false; } @@ -4747,8 +5188,7 @@ public: else { // lhs negative - if( ( IntTraits< T >::isLT64Bit && tmp < IntTraits< T >::minInt) || - ( rhs >=0 && tmp > lhs ) ) + if ((IntTraits::isLT64Bit && tmp < IntTraits::minInt) || (rhs >= 0 && tmp > lhs)) { return false; } @@ -4758,8 +5198,7 @@ public: return true; } - template < typename E > - static void SubtractThrow( const U& lhs, const T& rhs, T& result ) + template static void SubtractThrow(const U& lhs, const T& rhs, T& result) { // lhs __int64, rhs any signed int (including __int64) __int64 tmp = lhs - rhs; @@ -4771,12 +5210,12 @@ public: // 3) lhs negative, rhs positive - check result <= lhs // 4) lhs negative, rhs negative - overflow not possible in tmp - if( lhs >= 0 ) + if (lhs >= 0) { // if both positive, overflow to negative not possible // which is why we'll explicitly check maxInt, and not call SafeCast - if( ( CompileConst< IntTraits< T >::isLT64Bit >::Value() && tmp > IntTraits< T >::maxInt ) || - ( rhs < 0 && tmp < lhs ) ) + if ((CompileConst::isLT64Bit>::Value() && tmp > IntTraits::maxInt) + || (rhs < 0 && tmp < lhs)) { E::SafeIntOnOverflow(); } @@ -4784,8 +5223,8 @@ public: else { // lhs negative - if( ( CompileConst< IntTraits< T >::isLT64Bit >::Value() && tmp < IntTraits< T >::minInt) || - ( rhs >=0 && tmp > lhs ) ) + if ((CompileConst::isLT64Bit>::Value() && tmp < IntTraits::minInt) + || (rhs >= 0 && tmp > lhs)) { E::SafeIntOnOverflow(); } @@ -4795,10 +5234,10 @@ public: } }; -template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_IntInt64 > +template class SubtractionHelper { public: - static bool Subtract( const T& lhs, const U& rhs, T& result ) throw() + static bool Subtract(const T& lhs, const U& rhs, T& result) throw() { // lhs is a 32-bit int or less, rhs __int64 // we have essentially 4 cases: @@ -4810,12 +5249,12 @@ public: __int64 tmp = (__int64)((unsigned __int64)lhs - (unsigned __int64)rhs); - if( lhs >= 0 ) + if (lhs >= 0) { // first case - if( rhs >= 0 ) + if (rhs >= 0) { - if( tmp >= IntTraits< T >::minInt ) + if (tmp >= IntTraits::minInt) { result = (T)tmp; return true; @@ -4824,7 +5263,7 @@ public: else { // second case - if( tmp >= lhs && tmp <= IntTraits< T >::maxInt ) + if (tmp >= lhs && tmp <= IntTraits::maxInt) { result = (T)tmp; return true; @@ -4835,9 +5274,9 @@ public: { // lhs < 0 // third case - if( rhs >= 0 ) + if (rhs >= 0) { - if( tmp <= lhs && tmp >= IntTraits< T >::minInt ) + if (tmp <= lhs && tmp >= IntTraits::minInt) { result = (T)tmp; return true; @@ -4846,7 +5285,7 @@ public: else { // fourth case - if( tmp <= IntTraits< T >::maxInt ) + if (tmp <= IntTraits::maxInt) { result = (T)tmp; return true; @@ -4857,8 +5296,7 @@ public: return false; } - template < typename E > - static void SubtractThrow( const T& lhs, const U& rhs, T& result ) + template static void SubtractThrow(const T& lhs, const U& rhs, T& result) { // lhs is a 32-bit int or less, rhs __int64 // we have essentially 4 cases: @@ -4870,12 +5308,12 @@ public: __int64 tmp = (__int64)((unsigned __int64)lhs - (unsigned __int64)rhs); - if( lhs >= 0 ) + if (lhs >= 0) { // first case - if( rhs >= 0 ) + if (rhs >= 0) { - if( tmp >= IntTraits< T >::minInt ) + if (tmp >= IntTraits::minInt) { result = (T)tmp; return; @@ -4884,7 +5322,7 @@ public: else { // second case - if( tmp >= lhs && tmp <= IntTraits< T >::maxInt ) + if (tmp >= lhs && tmp <= IntTraits::maxInt) { result = (T)tmp; return; @@ -4895,9 +5333,9 @@ public: { // lhs < 0 // third case - if( rhs >= 0 ) + if (rhs >= 0) { - if( tmp <= lhs && tmp >= IntTraits< T >::minInt ) + if (tmp <= lhs && tmp >= IntTraits::minInt) { result = (T)tmp; return; @@ -4906,7 +5344,7 @@ public: else { // fourth case - if( tmp <= IntTraits< T >::maxInt ) + if (tmp <= IntTraits::maxInt) { result = (T)tmp; return; @@ -4918,52 +5356,49 @@ public: } }; -template < typename U, typename T > class SubtractionHelper< U, T, SubtractionState_IntInt642 > +template class SubtractionHelper { public: - static bool Subtract( const U& lhs, const T& rhs, T& result ) throw() + static bool Subtract(const U& lhs, const T& rhs, T& result) throw() { // lhs is any signed int32 or smaller, rhs is int64 __int64 tmp = (__int64)lhs - rhs; - if( ( lhs >= 0 && rhs < 0 && tmp < lhs ) || - ( rhs > 0 && tmp > lhs ) ) + if ((lhs >= 0 && rhs < 0 && tmp < lhs) || (rhs > 0 && tmp > lhs)) { return false; - //else OK + // else OK } result = (T)tmp; return true; } - template < typename E > - static void SubtractThrow( const U& lhs, const T& rhs, T& result ) + template static void SubtractThrow(const U& lhs, const T& rhs, T& result) { // lhs is any signed int32 or smaller, rhs is int64 __int64 tmp = (__int64)lhs - rhs; - if( ( lhs >= 0 && rhs < 0 && tmp < lhs ) || - ( rhs > 0 && tmp > lhs ) ) + if ((lhs >= 0 && rhs < 0 && tmp < lhs) || (rhs > 0 && tmp > lhs)) { E::SafeIntOnOverflow(); - //else OK + // else OK } result = (T)tmp; } }; -template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_Int64Uint > +template class SubtractionHelper { public: - static bool Subtract( const T& lhs, const U& rhs, T& result ) throw() + static bool Subtract(const T& lhs, const U& rhs, T& result) throw() { // lhs is a 64-bit int, rhs unsigned int32 or smaller // perform test as unsigned to prevent unwanted optimizations unsigned __int64 tmp = (unsigned __int64)lhs - (unsigned __int64)rhs; - if( (__int64)tmp <= lhs ) + if ((__int64)tmp <= lhs) { result = (T)(__int64)tmp; return true; @@ -4972,14 +5407,13 @@ public: return false; } - template < typename E > - static void SubtractThrow( const T& lhs, const U& rhs, T& result ) + template static void SubtractThrow(const T& lhs, const U& rhs, T& result) { // lhs is a 64-bit int, rhs unsigned int32 or smaller // perform test as unsigned to prevent unwanted optimizations unsigned __int64 tmp = (unsigned __int64)lhs - (unsigned __int64)rhs; - if( (__int64)tmp <= lhs ) + if ((__int64)tmp <= lhs) { result = (T)tmp; return; @@ -4989,16 +5423,16 @@ public: } }; -template < typename U, typename T > class SubtractionHelper< U, T, SubtractionState_Int64Uint2 > +template class SubtractionHelper { public: // lhs is __int64, rhs is unsigned 32-bit or smaller - static bool Subtract( const U& lhs, const T& rhs, T& result ) throw() + static bool Subtract(const U& lhs, const T& rhs, T& result) throw() { // Do this as unsigned to prevent unwanted optimizations unsigned __int64 tmp = (unsigned __int64)lhs - (unsigned __int64)rhs; - if( (__int64)tmp <= IntTraits< T >::maxInt && (__int64)tmp >= IntTraits< T >::minInt ) + if ((__int64)tmp <= IntTraits::maxInt && (__int64)tmp >= IntTraits::minInt) { result = (T)(__int64)tmp; return true; @@ -5007,13 +5441,12 @@ public: return false; } - template < typename E > - static void SubtractThrow( const U& lhs, const T& rhs, T& result ) + template static void SubtractThrow(const U& lhs, const T& rhs, T& result) { // Do this as unsigned to prevent unwanted optimizations unsigned __int64 tmp = (unsigned __int64)lhs - (unsigned __int64)rhs; - if( (__int64)tmp <= IntTraits< T >::maxInt && (__int64)tmp >= IntTraits< T >::minInt ) + if ((__int64)tmp <= IntTraits::maxInt && (__int64)tmp >= IntTraits::minInt) { result = (T)(__int64)tmp; return; @@ -5023,31 +5456,31 @@ public: } }; -template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_IntUint64 > +template class SubtractionHelper { public: - static bool Subtract( const T& lhs, const U& rhs, T& result ) throw() + static bool Subtract(const T& lhs, const U& rhs, T& result) throw() { // lhs is any signed int, rhs unsigned int64 // check against available range // We need the absolute value of IntTraits< T >::minInt // This will give it to us without extraneous compiler warnings - const unsigned __int64 AbsMinIntT = (unsigned __int64)IntTraits< T >::maxInt + 1; + const unsigned __int64 AbsMinIntT = (unsigned __int64)IntTraits::maxInt + 1; - if( lhs < 0 ) + if (lhs < 0) { - if( rhs <= AbsMinIntT - AbsValueHelper< T, GetAbsMethod< T >::method >::Abs( lhs ) ) + if (rhs <= AbsMinIntT - AbsValueHelper::method>::Abs(lhs)) { - result = (T)( lhs - rhs ); + result = (T)(lhs - rhs); return true; } } else { - if( rhs <= AbsMinIntT + (unsigned __int64)lhs ) + if (rhs <= AbsMinIntT + (unsigned __int64)lhs) { - result = (T)( lhs - rhs ); + result = (T)(lhs - rhs); return true; } } @@ -5055,29 +5488,28 @@ public: return false; } - template < typename E > - static void SubtractThrow( const T& lhs, const U& rhs, T& result ) + template static void SubtractThrow(const T& lhs, const U& rhs, T& result) { // lhs is any signed int, rhs unsigned int64 // check against available range // We need the absolute value of IntTraits< T >::minInt // This will give it to us without extraneous compiler warnings - const unsigned __int64 AbsMinIntT = (unsigned __int64)IntTraits< T >::maxInt + 1; + const unsigned __int64 AbsMinIntT = (unsigned __int64)IntTraits::maxInt + 1; - if( lhs < 0 ) + if (lhs < 0) { - if( rhs <= AbsMinIntT - AbsValueHelper< T, GetAbsMethod< T >::method >::Abs( lhs ) ) + if (rhs <= AbsMinIntT - AbsValueHelper::method>::Abs(lhs)) { - result = (T)( lhs - rhs ); + result = (T)(lhs - rhs); return; } } else { - if( rhs <= AbsMinIntT + (unsigned __int64)lhs ) + if (rhs <= AbsMinIntT + (unsigned __int64)lhs) { - result = (T)( lhs - rhs ); + result = (T)(lhs - rhs); return; } } @@ -5086,13 +5518,13 @@ public: } }; -template < typename U, typename T > class SubtractionHelper< U, T, SubtractionState_IntUint642 > +template class SubtractionHelper { public: - static bool Subtract( const U& lhs, const T& rhs, T& result ) throw() + static bool Subtract(const U& lhs, const T& rhs, T& result) throw() { // We run into upcasting problems on comparison - needs 2 checks - if( lhs >= 0 && (T)lhs >= rhs ) + if (lhs >= 0 && (T)lhs >= rhs) { result = (T)((U)lhs - (U)rhs); return true; @@ -5101,11 +5533,10 @@ public: return false; } - template < typename E > - static void SubtractThrow( const U& lhs, const T& rhs, T& result ) + template static void SubtractThrow(const U& lhs, const T& rhs, T& result) { // We run into upcasting problems on comparison - needs 2 checks - if( lhs >= 0 && (T)lhs >= rhs ) + if (lhs >= 0 && (T)lhs >= rhs) { result = (T)((U)lhs - (U)rhs); return; @@ -5113,20 +5544,19 @@ public: E::SafeIntOnOverflow(); } - }; -template < typename T, typename U > class SubtractionHelper< T, U, SubtractionState_Int64Uint64 > +template class SubtractionHelper { public: - static bool Subtract( const __int64& lhs, const unsigned __int64& rhs, __int64& result ) throw() + static bool Subtract(const __int64& lhs, const unsigned __int64& rhs, __int64& result) throw() { - C_ASSERT( IntTraits< T >::isInt64 && IntTraits< U >::isUint64 ); + C_ASSERT(IntTraits::isInt64 && IntTraits::isUint64); // if we subtract, and it gets larger, there's a problem // Perform test as unsigned to prevent unwanted optimizations unsigned __int64 tmp = (unsigned __int64)lhs - rhs; - if( (__int64)tmp <= lhs ) + if ((__int64)tmp <= lhs) { result = (__int64)tmp; return true; @@ -5134,15 +5564,15 @@ public: return false; } - template < typename E > - static void SubtractThrow( const __int64& lhs, const unsigned __int64& rhs, T& result ) + template + static void SubtractThrow(const __int64& lhs, const unsigned __int64& rhs, T& result) { - C_ASSERT( IntTraits< T >::isInt64 && IntTraits< U >::isUint64 ); + C_ASSERT(IntTraits::isInt64 && IntTraits::isUint64); // if we subtract, and it gets larger, there's a problem // Perform test as unsigned to prevent unwanted optimizations unsigned __int64 tmp = (unsigned __int64)lhs - rhs; - if( (__int64)tmp <= lhs ) + if ((__int64)tmp <= lhs) { result = (__int64)tmp; return; @@ -5150,18 +5580,18 @@ public: E::SafeIntOnOverflow(); } - }; -template < typename U, typename T > class SubtractionHelper< U, T, SubtractionState_Int64Uint642 > +template class SubtractionHelper { public: - // If lhs is negative, immediate problem - return must be positive, and subtracting only makes it + // If lhs is negative, immediate problem - return must be positive, and subtracting only makes + // it // get smaller. If rhs > lhs, then it would also go negative, which is the other case - static bool Subtract( const __int64& lhs, const unsigned __int64& rhs, T& result ) throw() + static bool Subtract(const __int64& lhs, const unsigned __int64& rhs, T& result) throw() { - C_ASSERT( IntTraits< T >::isUint64 && IntTraits< U >::isInt64 ); - if( lhs >= 0 && (unsigned __int64)lhs >= rhs ) + C_ASSERT(IntTraits::isUint64 && IntTraits::isInt64); + if (lhs >= 0 && (unsigned __int64)lhs >= rhs) { result = (unsigned __int64)lhs - rhs; return true; @@ -5170,11 +5600,11 @@ public: return false; } - template < typename E > - static void SubtractThrow( const __int64& lhs, const unsigned __int64& rhs, T& result ) + template + static void SubtractThrow(const __int64& lhs, const unsigned __int64& rhs, T& result) { - C_ASSERT( IntTraits< T >::isUint64 && IntTraits< U >::isInt64 ); - if( lhs >= 0 && (unsigned __int64)lhs >= rhs ) + C_ASSERT(IntTraits::isUint64 && IntTraits::isInt64); + if (lhs >= 0 && (unsigned __int64)lhs >= rhs) { result = (unsigned __int64)lhs - rhs; return; @@ -5182,7 +5612,6 @@ public: E::SafeIntOnOverflow(); } - }; enum BinaryState @@ -5193,7 +5622,7 @@ enum BinaryState BinaryState_Int32 }; -template < typename T, typename U > class BinaryMethod +template class BinaryMethod { public: enum @@ -5202,12 +5631,11 @@ public: // return type is smaller than rhs OR // return type is larger and rhs is unsigned // Then binary operations won't produce unexpected results - method = ( sizeof( T ) <= sizeof( U ) || - SafeIntCompare< T, U >::isBothUnsigned || - !IntTraits< U >::isSigned ) ? BinaryState_OK : - IntTraits< U >::isInt8 ? BinaryState_Int8 : - IntTraits< U >::isInt16 ? BinaryState_Int16 - : BinaryState_Int32 + method = (sizeof(T) <= sizeof(U) || SafeIntCompare::isBothUnsigned + || !IntTraits::isSigned) + ? BinaryState_OK + : IntTraits::isInt8 ? BinaryState_Int8 : IntTraits::isInt16 ? BinaryState_Int16 + : BinaryState_Int32 }; }; @@ -5217,126 +5645,135 @@ public: #define BinaryAssert(x) assert(x) #endif -template < typename T, typename U, int method > class BinaryAndHelper; +template class BinaryAndHelper; -template < typename T, typename U > class BinaryAndHelper< T, U, BinaryState_OK > +template class BinaryAndHelper { public: - static T And( T lhs, U rhs ){ return (T)( lhs & rhs ); } + static T And(T lhs, U rhs) + { + return (T)(lhs & rhs); + } }; -template < typename T, typename U > class BinaryAndHelper< T, U, BinaryState_Int8 > +template class BinaryAndHelper { public: - static T And( T lhs, U rhs ) + static T And(T lhs, U rhs) { // cast forces sign extension to be zeros - BinaryAssert( ( lhs & rhs ) == ( lhs & (unsigned __int8)rhs ) ); - return (T)( lhs & (unsigned __int8)rhs ); + BinaryAssert((lhs & rhs) == (lhs & (unsigned __int8)rhs)); + return (T)(lhs & (unsigned __int8)rhs); } }; -template < typename T, typename U > class BinaryAndHelper< T, U, BinaryState_Int16 > +template class BinaryAndHelper { public: - static T And( T lhs, U rhs ) + static T And(T lhs, U rhs) { - //cast forces sign extension to be zeros - BinaryAssert( ( lhs & rhs ) == ( lhs & (unsigned __int16)rhs ) ); - return (T)( lhs & (unsigned __int16)rhs ); + // cast forces sign extension to be zeros + BinaryAssert((lhs & rhs) == (lhs & (unsigned __int16)rhs)); + return (T)(lhs & (unsigned __int16)rhs); } }; -template < typename T, typename U > class BinaryAndHelper< T, U, BinaryState_Int32 > +template class BinaryAndHelper { public: - static T And( T lhs, U rhs ) + static T And(T lhs, U rhs) { - //cast forces sign extension to be zeros - BinaryAssert( ( lhs & rhs ) == ( lhs & (unsigned __int32)rhs ) ); - return (T)( lhs & (unsigned __int32)rhs ); + // cast forces sign extension to be zeros + BinaryAssert((lhs & rhs) == (lhs & (unsigned __int32)rhs)); + return (T)(lhs & (unsigned __int32)rhs); } }; -template < typename T, typename U, int method > class BinaryOrHelper; +template class BinaryOrHelper; -template < typename T, typename U > class BinaryOrHelper< T, U, BinaryState_OK > +template class BinaryOrHelper { public: - static T Or( T lhs, U rhs ){ return (T)( lhs | rhs ); } + static T Or(T lhs, U rhs) + { + return (T)(lhs | rhs); + } }; -template < typename T, typename U > class BinaryOrHelper< T, U, BinaryState_Int8 > +template class BinaryOrHelper { public: - static T Or( T lhs, U rhs ) + static T Or(T lhs, U rhs) { - //cast forces sign extension to be zeros - BinaryAssert( ( lhs | rhs ) == ( lhs | (unsigned __int8)rhs ) ); - return (T)( lhs | (unsigned __int8)rhs ); + // cast forces sign extension to be zeros + BinaryAssert((lhs | rhs) == (lhs | (unsigned __int8)rhs)); + return (T)(lhs | (unsigned __int8)rhs); } }; -template < typename T, typename U > class BinaryOrHelper< T, U, BinaryState_Int16 > +template class BinaryOrHelper { public: - static T Or( T lhs, U rhs ) + static T Or(T lhs, U rhs) { - //cast forces sign extension to be zeros - BinaryAssert( ( lhs | rhs ) == ( lhs | (unsigned __int16)rhs ) ); - return (T)( lhs | (unsigned __int16)rhs ); + // cast forces sign extension to be zeros + BinaryAssert((lhs | rhs) == (lhs | (unsigned __int16)rhs)); + return (T)(lhs | (unsigned __int16)rhs); } }; -template < typename T, typename U > class BinaryOrHelper< T, U, BinaryState_Int32 > +template class BinaryOrHelper { public: - static T Or( T lhs, U rhs ) + static T Or(T lhs, U rhs) { - //cast forces sign extension to be zeros - BinaryAssert( ( lhs | rhs ) == ( lhs | (unsigned __int32)rhs ) ); - return (T)( lhs | (unsigned __int32)rhs ); + // cast forces sign extension to be zeros + BinaryAssert((lhs | rhs) == (lhs | (unsigned __int32)rhs)); + return (T)(lhs | (unsigned __int32)rhs); } }; -template class BinaryXorHelper; +template class BinaryXorHelper; -template < typename T, typename U > class BinaryXorHelper< T, U, BinaryState_OK > +template class BinaryXorHelper { public: - static T Xor( T lhs, U rhs ){ return (T)( lhs ^ rhs ); } + static T Xor(T lhs, U rhs) + { + return (T)(lhs ^ rhs); + } }; -template < typename T, typename U > class BinaryXorHelper< T, U, BinaryState_Int8 > +template class BinaryXorHelper { public: - static T Xor( T lhs, U rhs ) + static T Xor(T lhs, U rhs) { // cast forces sign extension to be zeros - BinaryAssert( ( lhs ^ rhs ) == ( lhs ^ (unsigned __int8)rhs ) ); - return (T)( lhs ^ (unsigned __int8)rhs ); + BinaryAssert((lhs ^ rhs) == (lhs ^ (unsigned __int8)rhs)); + return (T)(lhs ^ (unsigned __int8)rhs); } }; -template < typename T, typename U > class BinaryXorHelper< T, U, BinaryState_Int16 > +template class BinaryXorHelper { public: - static T Xor( T lhs, U rhs ) + static T Xor(T lhs, U rhs) { // cast forces sign extension to be zeros - BinaryAssert( ( lhs ^ rhs ) == ( lhs ^ (unsigned __int16)rhs ) ); - return (T)( lhs ^ (unsigned __int16)rhs ); + BinaryAssert((lhs ^ rhs) == (lhs ^ (unsigned __int16)rhs)); + return (T)(lhs ^ (unsigned __int16)rhs); } }; -template < typename T, typename U > class BinaryXorHelper< T, U, BinaryState_Int32 > +template class BinaryXorHelper { public: - static T Xor( T lhs, U rhs ) + static T Xor(T lhs, U rhs) { // cast forces sign extension to be zeros - BinaryAssert( ( lhs ^ rhs ) == ( lhs ^ (unsigned __int32)rhs ) ); - return (T)( lhs ^ (unsigned __int32)rhs ); + BinaryAssert((lhs ^ rhs) == (lhs ^ (unsigned __int32)rhs)); + return (T)(lhs ^ (unsigned __int32)rhs); } }; @@ -5345,121 +5782,109 @@ public: // External functions that can be used where you only need to check one operation // non-class helper function so that you can check for a cast's validity // and handle errors how you like -template < typename T, typename U > -inline bool SafeCast( const T From, U& To ) +template inline bool SafeCast(const T From, U& To) { - return SafeCastHelper< U, T, GetCastMethod< U, T >::method >::Cast( From, To ); + return SafeCastHelper::method>::Cast(From, To); } -template < typename T, typename U > -inline bool SafeEquals( const T t, const U u ) throw() +template inline bool SafeEquals(const T t, const U u) throw() { - return EqualityTest< T, U, ValidComparison< T, U >::method >::IsEquals( t, u ); + return EqualityTest::method>::IsEquals(t, u); } -template < typename T, typename U > -inline bool SafeNotEquals( const T t, const U u ) throw() +template inline bool SafeNotEquals(const T t, const U u) throw() { - return !EqualityTest< T, U, ValidComparison< T, U >::method >::IsEquals( t, u ); + return !EqualityTest::method>::IsEquals(t, u); } -template < typename T, typename U > -inline bool SafeGreaterThan( const T t, const U u ) throw() +template inline bool SafeGreaterThan(const T t, const U u) throw() { - return GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( t, u ); + return GreaterThanTest::method>::GreaterThan(t, u); } -template < typename T, typename U > -inline bool SafeGreaterThanEquals( const T t, const U u ) throw() +template inline bool SafeGreaterThanEquals(const T t, const U u) throw() { - return !GreaterThanTest< U, T, ValidComparison< U, T >::method >::GreaterThan( u, t ); + return !GreaterThanTest::method>::GreaterThan(u, t); } -template < typename T, typename U > -inline bool SafeLessThan( const T t, const U u ) throw() +template inline bool SafeLessThan(const T t, const U u) throw() { - return GreaterThanTest< U, T, ValidComparison< U, T >::method >::GreaterThan( u, t ); + return GreaterThanTest::method>::GreaterThan(u, t); } -template < typename T, typename U > -inline bool SafeLessThanEquals( const T t, const U u ) throw() +template inline bool SafeLessThanEquals(const T t, const U u) throw() { - return !GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( t, u ); + return !GreaterThanTest::method>::GreaterThan(t, u); } -template < typename T, typename U > -inline bool SafeModulus( const T& t, const U& u, T& result ) throw() +template inline bool SafeModulus(const T& t, const U& u, T& result) throw() { - return ( ModulusHelper< T, U, ValidComparison< T, U >::method >::Modulus( t, u, result ) == SafeIntNoError ); + return (ModulusHelper::method>::Modulus(t, u, result) + == SafeIntNoError); } -template < typename T, typename U > -inline bool SafeMultiply( T t, U u, T& result ) throw() +template inline bool SafeMultiply(T t, U u, T& result) throw() { - return MultiplicationHelper< T, U, MultiplicationMethod< T, U >::method >::Multiply( t, u, result ); + return MultiplicationHelper::method>::Multiply(t, u, result); } -template < typename T, typename U > -inline bool SafeDivide( T t, U u, T& result ) throw() +template inline bool SafeDivide(T t, U u, T& result) throw() { - return ( DivisionHelper< T, U, DivisionMethod< T, U >::method >::Divide( t, u, result ) == SafeIntNoError ); + return ( + DivisionHelper::method>::Divide(t, u, result) == SafeIntNoError); } -template < typename T, typename U > -inline bool SafeAdd( T t, U u, T& result ) throw() +template inline bool SafeAdd(T t, U u, T& result) throw() { - return AdditionHelper< T, U, AdditionMethod< T, U >::method >::Addition( t, u, result ); + return AdditionHelper::method>::Addition(t, u, result); } -template < typename T, typename U > -inline bool SafeSubtract( T t, U u, T& result ) throw() +template inline bool SafeSubtract(T t, U u, T& result) throw() { - return SubtractionHelper< T, U, SubtractionMethod< T, U >::method >::Subtract( t, u, result ); + return SubtractionHelper::method>::Subtract(t, u, result); } /***************** end external functions ************************************/ // Main SafeInt class // Assumes exceptions can be thrown -template < typename T, typename E = SafeIntDefaultExceptionHandler > class SafeInt +template class SafeInt { public: SafeInt() throw() { - C_ASSERT( NumericType< T >::isInt ); + C_ASSERT(NumericType::isInt); m_int = 0; } // Having a constructor for every type of int // avoids having the compiler evade our checks when doing implicit casts - // e.g., SafeInt s = 0x7fffffff; - SafeInt( const T& i ) throw() + SafeInt(const T& i) throw() { - C_ASSERT( NumericType< T >::isInt ); - //always safe + C_ASSERT(NumericType::isInt); + // always safe m_int = i; } // provide explicit boolean converter - SafeInt( bool b ) throw() + SafeInt(bool b) throw() { - C_ASSERT( NumericType< T >::isInt ); - m_int = (T)( b ? 1 : 0 ); + C_ASSERT(NumericType::isInt); + m_int = (T)(b ? 1 : 0); } - template < typename U > - SafeInt(const SafeInt< U, E >& u) + template SafeInt(const SafeInt& u) { - C_ASSERT( NumericType< T >::isInt ); - *this = SafeInt< T, E >( (U)u ); + C_ASSERT(NumericType::isInt); + *this = SafeInt((U)u); } - template < typename U > - SafeInt( const U& i ) + template SafeInt(const U& i) { - C_ASSERT( NumericType< T >::isInt ); + C_ASSERT(NumericType::isInt); // SafeCast will throw exceptions if i won't fit in type T - SafeCastHelper< T, U, GetCastMethod< T, U >::method >::template CastThrow< E >( i, m_int ); + SafeCastHelper::method>::template CastThrow(i, m_int); } // The destructor is intentionally commented out - no destructor @@ -5467,36 +5892,33 @@ public: // inlining characteristics. It wasn't doing anything anyway. // ~SafeInt(){}; - // now start overloading operators // assignment operator // constructors exist for all int types and will ensure safety - template < typename U > - SafeInt< T, E >& operator =( const U& rhs ) + template SafeInt& operator=(const U& rhs) { // use constructor to test size // constructor is optimized to do minimal checking based // on whether T can contain U // note - do not change this - *this = SafeInt< T, E >( rhs ); + *this = SafeInt(rhs); return *this; } - SafeInt< T, E >& operator =( const T& rhs ) throw() + SafeInt& operator=(const T& rhs) throw() { m_int = rhs; return *this; } - template < typename U > - SafeInt< T, E >& operator =( const SafeInt< U, E >& rhs ) + template SafeInt& operator=(const SafeInt& rhs) { - SafeCastHelper< T, U, GetCastMethod< T, U >::method >::template CastThrow< E >( rhs.Ref(), m_int ); + SafeCastHelper::method>::template CastThrow(rhs.Ref(), m_int); return *this; } - SafeInt< T, E >& operator =( const SafeInt< T, E >& rhs ) throw() + SafeInt& operator=(const SafeInt& rhs) throw() { m_int = rhs.m_int; return *this; @@ -5512,49 +5934,55 @@ public: operator char() const { char val; - SafeCastHelper< char, T, GetCastMethod< char, T >::method >::template CastThrow< E >( m_int, val ); + SafeCastHelper::method>::template CastThrow(m_int, val); return val; } operator signed char() const { signed char val; - SafeCastHelper< signed char, T, GetCastMethod< signed char, T >::method >::template CastThrow< E >( m_int, val ); + SafeCastHelper::method>::template CastThrow(m_int, val); return val; } operator unsigned char() const { unsigned char val; - SafeCastHelper< unsigned char, T, GetCastMethod< unsigned char, T >::method >::template CastThrow< E >( m_int, val ); + SafeCastHelper::method>::template CastThrow(m_int, val); return val; } operator __int16() const { __int16 val; - SafeCastHelper< __int16, T, GetCastMethod< __int16, T >::method >::template CastThrow< E >( m_int, val ); + SafeCastHelper<__int16, T, GetCastMethod<__int16, T>::method>::template CastThrow( + m_int, val); return val; } operator unsigned __int16() const { unsigned __int16 val; - SafeCastHelper< unsigned __int16, T, GetCastMethod< unsigned __int16, T >::method >::template CastThrow< E >( m_int, val ); + SafeCastHelper::method>::template CastThrow(m_int, val); return val; } operator __int32() const { __int32 val; - SafeCastHelper< __int32, T, GetCastMethod< __int32, T >::method >::template CastThrow< E >( m_int, val ); + SafeCastHelper<__int32, T, GetCastMethod<__int32, T>::method>::template CastThrow( + m_int, val); return val; } operator unsigned __int32() const { unsigned __int32 val; - SafeCastHelper< unsigned __int32, T, GetCastMethod< unsigned __int32, T >::method >::template CastThrow< E >( m_int, val ); + SafeCastHelper::method>::template CastThrow(m_int, val); return val; } @@ -5563,28 +5991,31 @@ public: operator long() const { long val; - SafeCastHelper< long, T, GetCastMethod< long, T >::method >::template CastThrow< E >( m_int, val ); - return val; + SafeCastHelper::method>::template CastThrow(m_int, val); + return val; } operator unsigned long() const { unsigned long val; - SafeCastHelper< unsigned long, T, GetCastMethod< unsigned long, T >::method >::template CastThrow< E >( m_int, val ); + SafeCastHelper::method>::template CastThrow(m_int, val); return val; } operator __int64() const { __int64 val; - SafeCastHelper< __int64, T, GetCastMethod< __int64, T >::method >::template CastThrow< E >( m_int, val ); + SafeCastHelper<__int64, T, GetCastMethod<__int64, T>::method>::template CastThrow( + m_int, val); return val; } operator unsigned __int64() const { unsigned __int64 val; - SafeCastHelper< unsigned __int64, T, GetCastMethod< unsigned __int64, T >::method >::template CastThrow< E >( m_int, val ); + SafeCastHelper::method>::template CastThrow(m_int, val); return val; } @@ -5595,7 +6026,8 @@ public: operator size_t() const { size_t val; - SafeCastHelper< size_t, T, GetCastMethod< size_t, T >::method >::template CastThrow< E >( m_int, val ); + SafeCastHelper::method>::template CastThrow( + m_int, val); return val; } #endif @@ -5604,20 +6036,23 @@ public: operator float() const { float val; - SafeCastHelper< float, T, GetCastMethod< float, T >::method >::template CastThrow< E >( m_int, val ); + SafeCastHelper::method>::template CastThrow( + m_int, val); return val; } operator double() const { double val; - SafeCastHelper< double, T, GetCastMethod< double, T >::method >::template CastThrow< E >( m_int, val ); + SafeCastHelper::method>::template CastThrow( + m_int, val); return val; } operator long double() const { long double val; - SafeCastHelper< long double, T, GetCastMethod< long double, T >::method >::template CastThrow< E >( m_int, val ); + SafeCastHelper::method>::template CastThrow(m_int, val); return val; } @@ -5625,39 +6060,61 @@ public: // this could be dangerous, but allows you to correctly pass // instances of this class to APIs that take a pointer to an integer // also see overloaded address-of operator below - T* Ptr() throw() { return &m_int; } - const T* Ptr() const throw() { return &m_int; } - const T& Ref() const throw() { return m_int; } + T* Ptr() throw() + { + return &m_int; + } + const T* Ptr() const throw() + { + return &m_int; + } + const T& Ref() const throw() + { + return m_int; + } // Or if SafeInt< T, E >::Ptr() is inconvenient, use the overload // operator & // This allows you to do unsafe things! // It is meant to allow you to more easily // pass a SafeInt into things like ReadFile - T* operator &() throw() { return &m_int; } - const T* operator &() const throw() { return &m_int; } + T* operator&() throw() + { + return &m_int; + } + const T* operator&() const throw() + { + return &m_int; + } // Unary operators - bool operator !() const throw() { return (!m_int) ? true : false; } + bool operator!() const throw() + { + return (!m_int) ? true : false; + } // operator + (unary) // note - normally, the '+' and '-' operators will upcast to a signed int // for T < 32 bits. This class changes behavior to preserve type - const SafeInt< T, E >& operator +() const throw() { return *this; }; + const SafeInt& operator+() const throw() + { + return *this; + }; - //unary - + // unary - - SafeInt< T, E > operator -() const + SafeInt operator-() const { // Note - unsigned still performs the bitwise manipulation // will warn at level 2 or higher if the value is 32-bit or larger - return SafeInt(NegationHelper::isSigned>::template NegativeThrow(m_int)); + return SafeInt( + NegationHelper::isSigned>::template NegativeThrow(m_int)); } // prefix increment operator - SafeInt< T, E >& operator ++() + SafeInt& operator++() { - if( m_int != IntTraits< T >::maxInt ) + if (m_int != IntTraits::maxInt) { ++m_int; return *this; @@ -5666,9 +6123,9 @@ public: } // prefix decrement operator - SafeInt< T, E >& operator --() + SafeInt& operator--() { - if( m_int != IntTraits< T >::minInt ) + if (m_int != IntTraits::minInt) { --m_int; return *this; @@ -5680,11 +6137,11 @@ public: // characteristics // postfix increment operator - SafeInt< T, E > operator ++( int ) // dummy arg to comply with spec + SafeInt operator++(int) // dummy arg to comply with spec { - if( m_int != IntTraits< T >::maxInt ) + if (m_int != IntTraits::maxInt) { - SafeInt< T, E > tmp( m_int ); + SafeInt tmp(m_int); m_int++; return tmp; @@ -5693,11 +6150,11 @@ public: } // postfix decrement operator - SafeInt< T, E > operator --( int ) // dummy arg to comply with spec + SafeInt operator--(int) // dummy arg to comply with spec { - if( m_int != IntTraits< T >::minInt ) + if (m_int != IntTraits::minInt) { - SafeInt< T, E > tmp( m_int ); + SafeInt tmp(m_int); m_int--; return tmp; } @@ -5707,7 +6164,10 @@ public: // One's complement // Note - this operator will normally change size to an int // cast in return improves perf and maintains type - SafeInt< T, E > operator ~() const throw() { return SafeInt< T, E >( (T)~m_int ); } + SafeInt operator~() const throw() + { + return SafeInt((T)~m_int); + } // Binary operators // @@ -5751,181 +6211,192 @@ public: // larger than the lhs operand, and it must be the same sign // as well. It does, however, suffer from the same promotion // problems as comparisons, division and other operations - template < typename U > - SafeInt< T, E > operator %( U rhs ) const + template SafeInt operator%(U rhs) const { T result; - ModulusHelper< T, U, ValidComparison< T, U >::method >::template ModulusThrow< E >( m_int, rhs, result ); - return SafeInt< T, E >( result ); + ModulusHelper::method>::template ModulusThrow( + m_int, rhs, result); + return SafeInt(result); } - SafeInt< T, E > operator %( SafeInt< T, E > rhs ) const + SafeInt operator%(SafeInt rhs) const { T result; - ModulusHelper< T, T, ValidComparison< T, T >::method >::template ModulusThrow< E >( m_int, rhs, result ); - return SafeInt< T, E >( result ); + ModulusHelper::method>::template ModulusThrow( + m_int, rhs, result); + return SafeInt(result); } // Modulus assignment - template < typename U > - SafeInt< T, E >& operator %=( U rhs ) + template SafeInt& operator%=(U rhs) { - ModulusHelper< T, U, ValidComparison< T, U >::method >::template ModulusThrow< E >( m_int, rhs, m_int ); + ModulusHelper::method>::template ModulusThrow( + m_int, rhs, m_int); return *this; } - template < typename U > - SafeInt< T, E >& operator %=( SafeInt< U, E > rhs ) + template SafeInt& operator%=(SafeInt rhs) { - ModulusHelper< T, U, ValidComparison< T, U >::method >::template ModulusThrow< E >( m_int, (U)rhs, m_int ); + ModulusHelper::method>::template ModulusThrow( + m_int, (U)rhs, m_int); return *this; } // Multiplication - template < typename U > - SafeInt< T, E > operator *( U rhs ) const + template SafeInt operator*(U rhs) const { - T ret( 0 ); - MultiplicationHelper< T, U, MultiplicationMethod< T, U >::method >::template MultiplyThrow< E >( m_int, rhs, ret ); - return SafeInt< T, E >( ret ); + T ret(0); + MultiplicationHelper::method>::template MultiplyThrow( + m_int, rhs, ret); + return SafeInt(ret); } - SafeInt< T, E > operator *( SafeInt< T, E > rhs ) const + SafeInt operator*(SafeInt rhs) const { - T ret( 0 ); - MultiplicationHelper< T, T, MultiplicationMethod< T, T >::method >::template MultiplyThrow< E >( m_int, (T)rhs, ret ); - return SafeInt< T, E >( ret ); + T ret(0); + MultiplicationHelper::method>::template MultiplyThrow( + m_int, (T)rhs, ret); + return SafeInt(ret); } // Multiplication assignment - SafeInt< T, E >& operator *=( SafeInt< T, E > rhs ) + SafeInt& operator*=(SafeInt rhs) { - MultiplicationHelper< T, T, MultiplicationMethod< T, T >::method >::template MultiplyThrow< E >( m_int, (T)rhs, m_int ); + MultiplicationHelper::method>::template MultiplyThrow( + m_int, (T)rhs, m_int); return *this; } - template < typename U > - SafeInt< T, E >& operator *=( U rhs ) + template SafeInt& operator*=(U rhs) { - MultiplicationHelper< T, U, MultiplicationMethod< T, U >::method >::template MultiplyThrow< E >( m_int, rhs, m_int ); + MultiplicationHelper::method>::template MultiplyThrow( + m_int, rhs, m_int); return *this; } - template < typename U > - SafeInt< T, E >& operator *=( SafeInt< U, E > rhs ) + template SafeInt& operator*=(SafeInt rhs) { - MultiplicationHelper< T, U, MultiplicationMethod< T, U >::method >::template MultiplyThrow< E >( m_int, rhs.Ref(), m_int ); + MultiplicationHelper::method>::template MultiplyThrow( + m_int, rhs.Ref(), m_int); return *this; } // Division - template < typename U > - SafeInt< T, E > operator /( U rhs ) const + template SafeInt operator/(U rhs) const { - T ret( 0 ); - DivisionHelper< T, U, DivisionMethod< T, U >::method >::template DivideThrow< E >( m_int, rhs, ret ); - return SafeInt< T, E >( ret ); + T ret(0); + DivisionHelper::method>::template DivideThrow( + m_int, rhs, ret); + return SafeInt(ret); } - SafeInt< T, E > operator /( SafeInt< T, E > rhs ) const + SafeInt operator/(SafeInt rhs) const { - T ret( 0 ); - DivisionHelper< T, T, DivisionMethod< T, T >::method >::template DivideThrow< E >( m_int, (T)rhs, ret ); - return SafeInt< T, E >( ret ); + T ret(0); + DivisionHelper::method>::template DivideThrow( + m_int, (T)rhs, ret); + return SafeInt(ret); } // Division assignment - SafeInt< T, E >& operator /=( SafeInt< T, E > i ) + SafeInt& operator/=(SafeInt i) { - DivisionHelper< T, T, DivisionMethod< T, T >::method >::template DivideThrow< E >( m_int, (T)i, m_int ); + DivisionHelper::method>::template DivideThrow( + m_int, (T)i, m_int); return *this; } - template < typename U > SafeInt< T, E >& operator /=( U i ) + template SafeInt& operator/=(U i) { - DivisionHelper< T, U, DivisionMethod< T, U >::method >::template DivideThrow< E >( m_int, i, m_int ); + DivisionHelper::method>::template DivideThrow( + m_int, i, m_int); return *this; } - template < typename U > SafeInt< T, E >& operator /=( SafeInt< U, E > i ) + template SafeInt& operator/=(SafeInt i) { - DivisionHelper< T, U, DivisionMethod< T, U >::method >::template DivideThrow< E >( m_int, (U)i, m_int ); + DivisionHelper::method>::template DivideThrow( + m_int, (U)i, m_int); return *this; } // For addition and subtraction // Addition - SafeInt< T, E > operator +( SafeInt< T, E > rhs ) const + SafeInt operator+(SafeInt rhs) const { - T ret( 0 ); - AdditionHelper< T, T, AdditionMethod< T, T >::method >::template AdditionThrow< E >( m_int, (T)rhs, ret ); - return SafeInt< T, E >( ret ); + T ret(0); + AdditionHelper::method>::template AdditionThrow( + m_int, (T)rhs, ret); + return SafeInt(ret); } - template < typename U > - SafeInt< T, E > operator +( U rhs ) const + template SafeInt operator+(U rhs) const { - T ret( 0 ); - AdditionHelper< T, U, AdditionMethod< T, U >::method >::template AdditionThrow< E >( m_int, rhs, ret ); - return SafeInt< T, E >( ret ); + T ret(0); + AdditionHelper::method>::template AdditionThrow( + m_int, rhs, ret); + return SafeInt(ret); } - //addition assignment - SafeInt< T, E >& operator +=( SafeInt< T, E > rhs ) + // addition assignment + SafeInt& operator+=(SafeInt rhs) { - AdditionHelper< T, T, AdditionMethod< T, T >::method >::template AdditionThrow< E >( m_int, (T)rhs, m_int ); + AdditionHelper::method>::template AdditionThrow( + m_int, (T)rhs, m_int); return *this; } - template < typename U > - SafeInt< T, E >& operator +=( U rhs ) + template SafeInt& operator+=(U rhs) { - AdditionHelper< T, U, AdditionMethod< T, U >::method >::template AdditionThrow< E >( m_int, rhs, m_int ); + AdditionHelper::method>::template AdditionThrow( + m_int, rhs, m_int); return *this; } - template < typename U > - SafeInt< T, E >& operator +=( SafeInt< U, E > rhs ) + template SafeInt& operator+=(SafeInt rhs) { - AdditionHelper< T, U, AdditionMethod< T, U >::method >::template AdditionThrow< E >( m_int, (U)rhs, m_int ); + AdditionHelper::method>::template AdditionThrow( + m_int, (U)rhs, m_int); return *this; } // Subtraction - template < typename U > - SafeInt< T, E > operator -( U rhs ) const + template SafeInt operator-(U rhs) const { - T ret( 0 ); - SubtractionHelper< T, U, SubtractionMethod< T, U >::method >::template SubtractThrow< E >( m_int, rhs, ret ); - return SafeInt< T, E >( ret ); + T ret(0); + SubtractionHelper::method>::template SubtractThrow( + m_int, rhs, ret); + return SafeInt(ret); } - SafeInt< T, E > operator -(SafeInt< T, E > rhs) const + SafeInt operator-(SafeInt rhs) const { - T ret( 0 ); - SubtractionHelper< T, T, SubtractionMethod< T, T >::method >::template SubtractThrow< E >( m_int, (T)rhs, ret ); - return SafeInt< T, E >( ret ); + T ret(0); + SubtractionHelper::method>::template SubtractThrow( + m_int, (T)rhs, ret); + return SafeInt(ret); } // Subtraction assignment - SafeInt< T, E >& operator -=( SafeInt< T, E > rhs ) + SafeInt& operator-=(SafeInt rhs) { - SubtractionHelper< T, T, SubtractionMethod< T, T >::method >::template SubtractThrow< E >( m_int, (T)rhs, m_int ); + SubtractionHelper::method>::template SubtractThrow( + m_int, (T)rhs, m_int); return *this; } - template < typename U > - SafeInt< T, E >& operator -=( U rhs ) + template SafeInt& operator-=(U rhs) { - SubtractionHelper< T, U, SubtractionMethod< T, U >::method >::template SubtractThrow< E >( m_int, rhs, m_int ); + SubtractionHelper::method>::template SubtractThrow( + m_int, rhs, m_int); return *this; } - template < typename U > - SafeInt< T, E >& operator -=( SafeInt< U, E > rhs ) + template SafeInt& operator-=(SafeInt rhs) { - SubtractionHelper< T, U, SubtractionMethod< T, U >::method >::template SubtractThrow< E >( m_int, (U)rhs, m_int ); + SubtractionHelper::method>::template SubtractThrow( + m_int, (U)rhs, m_int); return *this; } @@ -5934,170 +6405,162 @@ public: // to allow for cases where the SafeInt is the rhs value // Less than - template < typename U > - bool operator <( U rhs ) const throw() + template bool operator<(U rhs) const throw() { - return GreaterThanTest< U, T, ValidComparison< U, T >::method >::GreaterThan( rhs, m_int ); + return GreaterThanTest::method>::GreaterThan(rhs, m_int); } - bool operator <( SafeInt< T, E > rhs ) const throw() + bool operator<(SafeInt rhs) const throw() { return m_int < (T)rhs; } // Greater than or eq. - template < typename U > - bool operator >=( U rhs ) const throw() + template bool operator>=(U rhs) const throw() { - return !GreaterThanTest< U, T, ValidComparison< U, T >::method >::GreaterThan( rhs, m_int ); + return !GreaterThanTest::method>::GreaterThan(rhs, m_int); } - bool operator >=( SafeInt< T, E > rhs ) const throw() + bool operator>=(SafeInt rhs) const throw() { return m_int >= (T)rhs; } // Greater than - template < typename U > - bool operator >( U rhs ) const throw() + template bool operator>(U rhs) const throw() { - return GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( m_int, rhs ); + return GreaterThanTest::method>::GreaterThan(m_int, rhs); } - bool operator >( SafeInt< T, E > rhs ) const throw() + bool operator>(SafeInt rhs) const throw() { return m_int > (T)rhs; } // Less than or eq. - template < typename U > - bool operator <=( U rhs ) const throw() + template bool operator<=(U rhs) const throw() { - return !GreaterThanTest< T, U, ValidComparison< T, U >::method >::GreaterThan( m_int, rhs ); + return !GreaterThanTest::method>::GreaterThan(m_int, rhs); } - bool operator <=( SafeInt< T, E > rhs ) const throw() + bool operator<=(SafeInt rhs) const throw() { return m_int <= (T)rhs; } // Equality - template < typename U > - bool operator ==( U rhs ) const throw() + template bool operator==(U rhs) const throw() { - return EqualityTest< T, U, ValidComparison< T, U >::method >::IsEquals( m_int, rhs ); + return EqualityTest::method>::IsEquals(m_int, rhs); } // Need an explicit override for type bool - bool operator ==( bool rhs ) const throw() + bool operator==(bool rhs) const throw() { - return ( m_int == 0 ? false : true ) == rhs; + return (m_int == 0 ? false : true) == rhs; } - bool operator ==( SafeInt< T, E > rhs ) const throw() { return m_int == (T)rhs; } + bool operator==(SafeInt rhs) const throw() + { + return m_int == (T)rhs; + } // != operators - template < typename U > - bool operator !=( U rhs ) const throw() + template bool operator!=(U rhs) const throw() { - return !EqualityTest< T, U, ValidComparison< T, U >::method >::IsEquals( m_int, rhs ); + return !EqualityTest::method>::IsEquals(m_int, rhs); } - bool operator !=( bool b ) const throw() + bool operator!=(bool b) const throw() { - return ( m_int == 0 ? false : true ) != b; + return (m_int == 0 ? false : true) != b; } - bool operator !=( SafeInt< T, E > rhs ) const throw() { return m_int != (T)rhs; } + bool operator!=(SafeInt rhs) const throw() + { + return m_int != (T)rhs; + } - // Shift operators - // Note - shift operators ALWAYS return the same type as the lhs - // specific version for SafeInt< T, E > not needed - - // code path is exactly the same as for SafeInt< U, E > as rhs +// Shift operators +// Note - shift operators ALWAYS return the same type as the lhs +// specific version for SafeInt< T, E > not needed - +// code path is exactly the same as for SafeInt< U, E > as rhs - // Left shift - // Also, shifting > bitcount is undefined - trap in debug +// Left shift +// Also, shifting > bitcount is undefined - trap in debug #ifdef SAFEINT_DISABLE_SHIFT_ASSERT - #define ShiftAssert(x) +#define ShiftAssert(x) #else - #define ShiftAssert(x) assert(x) +#define ShiftAssert(x) assert(x) #endif - template < typename U > - SafeInt< T, E > operator <<( U bits ) const throw() + template SafeInt operator<<(U bits) const throw() { - ShiftAssert( !IntTraits< U >::isSigned || bits >= 0 ); - ShiftAssert( bits < (int)IntTraits< T >::bitCount ); + ShiftAssert(!IntTraits::isSigned || bits >= 0); + ShiftAssert(bits < (int)IntTraits::bitCount); - return SafeInt< T, E >( (T)( m_int << bits ) ); + return SafeInt((T)(m_int << bits)); } - template < typename U > - SafeInt< T, E > operator <<( SafeInt< U, E > bits ) const throw() + template SafeInt operator<<(SafeInt bits) const throw() { - ShiftAssert( !IntTraits< U >::isSigned || (U)bits >= 0 ); - ShiftAssert( (U)bits < (int)IntTraits< T >::bitCount ); + ShiftAssert(!IntTraits::isSigned || (U)bits >= 0); + ShiftAssert((U)bits < (int)IntTraits::bitCount); - return SafeInt< T, E >( (T)( m_int << (U)bits ) ); + return SafeInt((T)(m_int << (U)bits)); } // Left shift assignment - template < typename U > - SafeInt< T, E >& operator <<=( U bits ) throw() + template SafeInt& operator<<=(U bits) throw() { - ShiftAssert( !IntTraits< U >::isSigned || bits >= 0 ); - ShiftAssert( bits < (int)IntTraits< T >::bitCount ); + ShiftAssert(!IntTraits::isSigned || bits >= 0); + ShiftAssert(bits < (int)IntTraits::bitCount); m_int <<= bits; return *this; } - template < typename U > - SafeInt< T, E >& operator <<=( SafeInt< U, E > bits ) throw() + template SafeInt& operator<<=(SafeInt bits) throw() { - ShiftAssert( !IntTraits< U >::isSigned || (U)bits >= 0 ); - ShiftAssert( (U)bits < (int)IntTraits< T >::bitCount ); + ShiftAssert(!IntTraits::isSigned || (U)bits >= 0); + ShiftAssert((U)bits < (int)IntTraits::bitCount); m_int <<= (U)bits; return *this; } // Right shift - template < typename U > - SafeInt< T, E > operator >>( U bits ) const throw() + template SafeInt operator>>(U bits) const throw() { - ShiftAssert( !IntTraits< U >::isSigned || bits >= 0 ); - ShiftAssert( bits < (int)IntTraits< T >::bitCount ); + ShiftAssert(!IntTraits::isSigned || bits >= 0); + ShiftAssert(bits < (int)IntTraits::bitCount); - return SafeInt< T, E >( (T)( m_int >> bits ) ); + return SafeInt((T)(m_int >> bits)); } - template < typename U > - SafeInt< T, E > operator >>( SafeInt< U, E > bits ) const throw() + template SafeInt operator>>(SafeInt bits) const throw() { - ShiftAssert( !IntTraits< U >::isSigned || (U)bits >= 0 ); - ShiftAssert( bits < (int)IntTraits< T >::bitCount ); + ShiftAssert(!IntTraits::isSigned || (U)bits >= 0); + ShiftAssert(bits < (int)IntTraits::bitCount); - return SafeInt< T, E >( (T)(m_int >> (U)bits) ); + return SafeInt((T)(m_int >> (U)bits)); } // Right shift assignment - template < typename U > - SafeInt< T, E >& operator >>=( U bits ) throw() + template SafeInt& operator>>=(U bits) throw() { - ShiftAssert( !IntTraits< U >::isSigned || bits >= 0 ); - ShiftAssert( bits < (int)IntTraits< T >::bitCount ); + ShiftAssert(!IntTraits::isSigned || bits >= 0); + ShiftAssert(bits < (int)IntTraits::bitCount); m_int >>= bits; return *this; } - template < typename U > - SafeInt< T, E >& operator >>=( SafeInt< U, E > bits ) throw() + template SafeInt& operator>>=(SafeInt bits) throw() { - ShiftAssert( !IntTraits< U >::isSigned || (U)bits >= 0 ); - ShiftAssert( (U)bits < (int)IntTraits< T >::bitCount ); + ShiftAssert(!IntTraits::isSigned || (U)bits >= 0); + ShiftAssert((U)bits < (int)IntTraits::bitCount); m_int >>= (U)bits; return *this; @@ -6108,13 +6571,12 @@ public: // demand a type T, or something that fits into a type T // Bitwise & - SafeInt< T, E > operator &( SafeInt< T, E > rhs ) const throw() + SafeInt operator&(SafeInt rhs) const throw() { - return SafeInt< T, E >( m_int & (T)rhs ); + return SafeInt(m_int & (T)rhs); } - template < typename U > - SafeInt< T, E > operator &( U rhs ) const throw() + template SafeInt operator&(U rhs) const throw() { // we want to avoid setting bits by surprise // consider the case of lhs = int, value = 0xffffffff @@ -6128,128 +6590,120 @@ public: // was causing unexpected behavior. Fix is to properly cast your inputs // so that it works like you meant, not unexpectedly - return SafeInt< T, E >( BinaryAndHelper< T, U, BinaryMethod< T, U >::method >::And( m_int, rhs ) ); + return SafeInt(BinaryAndHelper::method>::And(m_int, rhs)); } // Bitwise & assignment - SafeInt< T, E >& operator &=( SafeInt< T, E > rhs ) throw() + SafeInt& operator&=(SafeInt rhs) throw() { m_int &= (T)rhs; return *this; } - template < typename U > - SafeInt< T, E >& operator &=( U rhs ) throw() + template SafeInt& operator&=(U rhs) throw() { - m_int = BinaryAndHelper< T, U, BinaryMethod< T, U >::method >::And( m_int, rhs ); + m_int = BinaryAndHelper::method>::And(m_int, rhs); return *this; } - template < typename U > - SafeInt< T, E >& operator &=( SafeInt< U, E > rhs ) throw() + template SafeInt& operator&=(SafeInt rhs) throw() { - m_int = BinaryAndHelper< T, U, BinaryMethod< T, U >::method >::And( m_int, (U)rhs ); + m_int = BinaryAndHelper::method>::And(m_int, (U)rhs); return *this; } // XOR - SafeInt< T, E > operator ^( SafeInt< T, E > rhs ) const throw() + SafeInt operator^(SafeInt rhs) const throw() { - return SafeInt< T, E >( (T)( m_int ^ (T)rhs ) ); + return SafeInt((T)(m_int ^ (T)rhs)); } - template < typename U > - SafeInt< T, E > operator ^( U rhs ) const throw() + template SafeInt operator^(U rhs) const throw() { // If you land in the assert, this is because the bitwise operator // was causing unexpected behavior. Fix is to properly cast your inputs // so that it works like you meant, not unexpectedly - return SafeInt< T, E >( BinaryXorHelper< T, U, BinaryMethod< T, U >::method >::Xor( m_int, rhs ) ); + return SafeInt(BinaryXorHelper::method>::Xor(m_int, rhs)); } // XOR assignment - SafeInt< T, E >& operator ^=( SafeInt< T, E > rhs ) throw() + SafeInt& operator^=(SafeInt rhs) throw() { m_int ^= (T)rhs; return *this; } - template < typename U > - SafeInt< T, E >& operator ^=( U rhs ) throw() + template SafeInt& operator^=(U rhs) throw() { - m_int = BinaryXorHelper< T, U, BinaryMethod< T, U >::method >::Xor( m_int, rhs ); + m_int = BinaryXorHelper::method>::Xor(m_int, rhs); return *this; } - template < typename U > - SafeInt< T, E >& operator ^=( SafeInt< U, E > rhs ) throw() + template SafeInt& operator^=(SafeInt rhs) throw() { - m_int = BinaryXorHelper< T, U, BinaryMethod< T, U >::method >::Xor( m_int, (U)rhs ); + m_int = BinaryXorHelper::method>::Xor(m_int, (U)rhs); return *this; } // bitwise OR - SafeInt< T, E > operator |( SafeInt< T, E > rhs ) const throw() + SafeInt operator|(SafeInt rhs) const throw() { - return SafeInt< T, E >( (T)( m_int | (T)rhs ) ); + return SafeInt((T)(m_int | (T)rhs)); } - template < typename U > - SafeInt< T, E > operator |( U rhs ) const throw() + template SafeInt operator|(U rhs) const throw() { - return SafeInt< T, E >( BinaryOrHelper< T, U, BinaryMethod< T, U >::method >::Or( m_int, rhs ) ); + return SafeInt(BinaryOrHelper::method>::Or(m_int, rhs)); } // bitwise OR assignment - SafeInt< T, E >& operator |=( SafeInt< T, E > rhs ) throw() + SafeInt& operator|=(SafeInt rhs) throw() { m_int |= (T)rhs; return *this; } - template < typename U > - SafeInt< T, E >& operator |=( U rhs ) throw() + template SafeInt& operator|=(U rhs) throw() { - m_int = BinaryOrHelper< T, U, BinaryMethod< T, U >::method >::Or( m_int, rhs ); + m_int = BinaryOrHelper::method>::Or(m_int, rhs); return *this; } - template < typename U > - SafeInt< T, E >& operator |=( SafeInt< U, E > rhs ) throw() + template SafeInt& operator|=(SafeInt rhs) throw() { - m_int = BinaryOrHelper< T, U, BinaryMethod< T, U >::method >::Or( m_int, (U)rhs ); + m_int = BinaryOrHelper::method>::Or(m_int, (U)rhs); return *this; } // Miscellaneous helper functions - SafeInt< T, E > Min( SafeInt< T, E > test, const T floor = IntTraits< T >::minInt ) const throw() + SafeInt Min(SafeInt test, const T floor = IntTraits::minInt) const throw() { T tmp = test < m_int ? (T)test : m_int; return tmp < floor ? floor : tmp; } - SafeInt< T, E > Max( SafeInt< T, E > test, const T upper = IntTraits< T >::maxInt ) const throw() + SafeInt Max(SafeInt test, const T upper = IntTraits::maxInt) const throw() { T tmp = test > m_int ? (T)test : m_int; return tmp > upper ? upper : tmp; } - void Swap( SafeInt< T, E >& with ) throw() + void Swap(SafeInt& with) throw() { - T temp( m_int ); + T temp(m_int); m_int = with.m_int; with.m_int = temp; } - static SafeInt< T, E > SafeAtoI( const char* input ) + static SafeInt SafeAtoI(const char* input) { - return SafeTtoI( input ); + return SafeTtoI(input); } - static SafeInt< T, E > SafeWtoI( const wchar_t* input ) + static SafeInt SafeWtoI(const wchar_t* input) { - return SafeTtoI( input ); + return SafeTtoI(input); } enum alignBits @@ -6264,11 +6718,10 @@ public: align256 = 8 }; - template < alignBits bits > - const SafeInt< T, E >& Align() + template const SafeInt& Align() { // Zero is always aligned - if( m_int == 0 ) + if (m_int == 0) return *this; // We don't support aligning negative numbers at this time @@ -6276,46 +6729,63 @@ public: // or signed numbers on bitCount-1 (e.g., 7 bits = 128, signed char max = 127). // Also makes no sense to try to align on negative or no bits. - ShiftAssert( ( ( IntTraits::isSigned && bits < (int)IntTraits< T >::bitCount - 1 ) - || ( !IntTraits::isSigned && bits < (int)IntTraits< T >::bitCount ) ) && - bits >= 0 && ( !IntTraits::isSigned || m_int > 0 ) ); + ShiftAssert(((IntTraits::isSigned && bits < (int)IntTraits::bitCount - 1) + || (!IntTraits::isSigned && bits < (int)IntTraits::bitCount)) + && bits >= 0 && (!IntTraits::isSigned || m_int > 0)); - const T AlignValue = ( (T)1 << bits ) - 1; + const T AlignValue = ((T)1 << bits) - 1; - m_int = (T)( ( m_int + AlignValue ) & ~AlignValue ); + m_int = (T)((m_int + AlignValue) & ~AlignValue); - if( m_int <= 0 ) + if (m_int <= 0) E::SafeIntOnOverflow(); return *this; } // Commonly needed alignments: - const SafeInt< T, E >& Align2() { return Align< align2 >(); } - const SafeInt< T, E >& Align4() { return Align< align4 >(); } - const SafeInt< T, E >& Align8(