From 4a619b3cf11a0e7652beffbab56fcb887443515f Mon Sep 17 00:00:00 2001 From: marcel Date: Wed, 11 May 2016 18:06:34 +0200 Subject: [PATCH 001/130] Remove astro subpackage. --- CMakeLists.txt | 1 - astro/CMakeLists.txt | 64 --- astro/astro.vcproj | 237 --------- astro/include/pxl/astro.hh | 21 - astro/include/pxl/astro/Astro.hh | 26 - astro/include/pxl/astro/AstroBasicObject.hh | 234 --------- astro/include/pxl/astro/AstroObject.hh | 126 ----- .../pxl/astro/CoordinateTransformations.hh | 56 --- astro/include/pxl/astro/Healpix.hh | 26 - astro/include/pxl/astro/HealpixMap.hh | 206 -------- astro/include/pxl/astro/RegionOfInterest.hh | 138 ------ astro/include/pxl/astro/UHECR.hh | 131 ----- astro/include/pxl/astro/UHECRSource.hh | 145 ------ astro/include/pxl/healpix.hh | 16 - astro/pxl-astro.pc.in | 12 - astro/pxl-healpix.pc.in | 12 - astro/src/Astro.cc | 51 -- astro/src/AstroBasicObject.cc | 136 ------ astro/src/AstroObject.cc | 57 --- astro/src/CoordinateTransformations.cc | 119 ----- astro/src/Healpix.cc | 40 -- astro/src/HealpixMap.cc | 454 ------------------ astro/src/RegionOfInterest.cc | 61 --- astro/src/UHECR.cc | 40 -- astro/src/UHECRSource.cc | 40 -- test/pypxl_testAstro.py.in | 34 -- test/pypxl_testAstro.py3.in | 29 -- test/test_astro.cc | 336 ------------- 28 files changed, 2848 deletions(-) delete mode 100644 astro/CMakeLists.txt delete mode 100644 astro/astro.vcproj delete mode 100644 astro/include/pxl/astro.hh delete mode 100644 astro/include/pxl/astro/Astro.hh delete mode 100644 astro/include/pxl/astro/AstroBasicObject.hh delete mode 100644 astro/include/pxl/astro/AstroObject.hh delete mode 100644 astro/include/pxl/astro/CoordinateTransformations.hh delete mode 100644 astro/include/pxl/astro/Healpix.hh delete mode 100644 astro/include/pxl/astro/HealpixMap.hh delete mode 100644 astro/include/pxl/astro/RegionOfInterest.hh delete mode 100644 astro/include/pxl/astro/UHECR.hh delete mode 100644 astro/include/pxl/astro/UHECRSource.hh delete mode 100644 astro/include/pxl/healpix.hh delete mode 100644 astro/pxl-astro.pc.in delete mode 100644 astro/pxl-healpix.pc.in delete mode 100644 astro/src/Astro.cc delete mode 100644 astro/src/AstroBasicObject.cc delete mode 100644 astro/src/AstroObject.cc delete mode 100644 astro/src/CoordinateTransformations.cc delete mode 100644 astro/src/Healpix.cc delete mode 100644 astro/src/HealpixMap.cc delete mode 100644 astro/src/RegionOfInterest.cc delete mode 100644 astro/src/UHECR.cc delete mode 100644 astro/src/UHECRSource.cc delete mode 100755 test/pypxl_testAstro.py.in delete mode 100755 test/pypxl_testAstro.py3.in delete mode 100644 test/test_astro.cc diff --git a/CMakeLists.txt b/CMakeLists.txt index c1b13d45..3e928014 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -232,7 +232,6 @@ ADD_SUBDIRECTORY(core) ADD_SUBDIRECTORY(doc) ADD_SUBDIRECTORY(hep) ADD_SUBDIRECTORY(xml) -ADD_SUBDIRECTORY(astro) ADD_SUBDIRECTORY(algorithms) ADD_SUBDIRECTORY(modules) ADD_SUBDIRECTORY(pxlrun) diff --git a/astro/CMakeLists.txt b/astro/CMakeLists.txt deleted file mode 100644 index 66ab6d69..00000000 --- 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 e5593889..00000000 --- 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 02d366a9..00000000 --- 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/Astro.hh b/astro/include/pxl/astro/Astro.hh deleted file mode 100644 index abc567a7..00000000 --- a/astro/include/pxl/astro/Astro.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 LGPL-2 or later license - -//------------------------------------------- - -#ifndef INITIALIZE_ASTRO_HH_ -#define INITIALIZE_ASTRO_HH_ - -#include "pxl/core/macros.hh" - -namespace pxl -{ -class PXL_DLL_EXPORT Astro -{ -public: - static void initialize(); - static void shutdown(); - -}; - -} - -#endif /* INITIALIZE_ASTRO_HH_ */ diff --git a/astro/include/pxl/astro/AstroBasicObject.hh b/astro/include/pxl/astro/AstroBasicObject.hh deleted file mode 100644 index 6351ffbe..00000000 --- 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 c2e59aa0..00000000 --- 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 15b8e112..00000000 --- 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 d194a42a..00000000 --- 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 527b1173..00000000 --- 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 126f2473..00000000 --- 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 0e7ce06d..00000000 --- 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 b2f30566..00000000 --- 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 d9b8e22c..00000000 --- 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 5897db7c..00000000 --- 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 397de0a1..00000000 --- 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 c4a68662..00000000 --- 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 f6b6e924..00000000 --- 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 61902bfe..00000000 --- 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 e7deaa02..00000000 --- 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 59b96611..00000000 --- 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 7e22645a..00000000 --- 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 546f876b..00000000 --- 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 7dc89468..00000000 --- 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 7882b662..00000000 --- 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/test/pypxl_testAstro.py.in b/test/pypxl_testAstro.py.in deleted file mode 100755 index 749441a2..00000000 --- a/test/pypxl_testAstro.py.in +++ /dev/null @@ -1,34 +0,0 @@ -#! @PYTHON_EXECUTABLE@ -#------------------------------------------- -# Project: Physics eXtension Library (PXL) - -# http://vispa.physik.rwth-aachen.de/ - -# Copyright (C) 2006-2012 - -# RWTH Aachen, Germany - -# Licensed under a LGPL-2 or later license - -#------------------------------------------- -import unittest -import sys -import os -sys.path.insert(0,'@OUTPUT_PATH@'); - -from pxl.astro import * -from pxl.core import Basic3Vector - -class TestAstroBasicObject(unittest.TestCase): - def runTest(self): - a = AstroBasicObject() - b = Basic3Vector(1,0,0) - a.setGalacticDirectionVector(b) - self.assertTrue(isinstance(a.getGalacticDirectionVector(),Basic3Vector)) - self.assertTrue(isinstance(a.getGalacticLongitude(),float)) - self.assertTrue(isinstance(a.getGalacticLatitude(),float)) - self.assertTrue(isinstance(a.getSuperGalacticLongitude(),float)) - self.assertTrue(isinstance(a.getSuperGalacticLatitude(),float)) - -class TestCoordinateTransformations(unittest.TestCase): - def runTest(self): - self.assertTrue(isinstance(CoordinateTransformations_minutesOfArc2Radian(-1,42,23),float)) - self.assertTrue(isinstance(CoordinateTransformations_timeAngle2Radian(13,21,6.7),float)) - -if __name__ == '__main__': - unittest.main() diff --git a/test/pypxl_testAstro.py3.in b/test/pypxl_testAstro.py3.in deleted file mode 100755 index b4edcecf..00000000 --- a/test/pypxl_testAstro.py3.in +++ /dev/null @@ -1,29 +0,0 @@ -#! @PYTHON_EXECUTABLE@ - -#------------------------------------------- -# 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 - -#------------------------------------------- - -import sys -import os -sys.path.insert(0,'@OUTPUT_PATH@'); - -from pxl.astro import * -from pxl.core import Basic3Vector - -a = AstroBasicObject() -b = Basic3Vector(1,0,0) -a.setGalacticDirectionVector(b) -assert(isinstance(a.getGalacticDirectionVector(),Basic3Vector)) -assert(isinstance(a.getGalacticLongitude(),float)) -assert(isinstance(a.getGalacticLatitude(),float)) -assert(isinstance(a.getSuperGalacticLongitude(),float)) -assert(isinstance(a.getSuperGalacticLatitude(),float)) - -assert(isinstance(CoordinateTransformations_minutesOfArc2Radian(-1,42,23),float)) -assert(isinstance(CoordinateTransformations_timeAngle2Radian(13,21,6.7),float)) - diff --git a/test/test_astro.cc b/test/test_astro.cc deleted file mode 100644 index d2fa2287..00000000 --- a/test/test_astro.cc +++ /dev/null @@ -1,336 +0,0 @@ -#include "gtest/gtest.h" -#include "pxl/astro.hh" -#include "test_share.hh" - -#include "core_tests/SerializableTests.hh" - -using namespace pxl; -TEST(AstroBasicObject, DefaultConstructor) -{ - const AstroBasicObject a; - Basic3Vector v = a.getGalacticDirectionVector(); - EXPECT_DOUBLE_EQ(v.getX(), 1); - EXPECT_DOUBLE_EQ(v.getY(), 0); - EXPECT_DOUBLE_EQ(v.getZ(), 0); -} - -TEST(AstroBasicObject, angularDistance) -{ - AstroBasicObject a; - a.setGalacticXYZ(1,0,0); - AstroBasicObject b; - b.setGalacticXYZ(0,1,0); - EXPECT_DOUBLE_EQ(a.angularDistanceTo(b), M_PI/2); - EXPECT_DOUBLE_EQ(a.angularDistanceTo(&b), M_PI/2); - - a.setGalacticXYZ(1,0,0); - b.setGalacticXYZ(-1,0,0); - EXPECT_DOUBLE_EQ(a.angularDistanceTo(b), M_PI); - - a.setGalacticXYZ(1,0,0); - b.setGalacticXYZ(1,0,0); - EXPECT_DOUBLE_EQ(a.angularDistanceTo(b), 0); - -} - -TEST(AstroBasicObject, TestCoordinateSettersAndGetters) -{ - AstroBasicObject a; - a.setGalacticCoordinates(1.2,0.6); - EXPECT_DOUBLE_EQ(a.getGalacticLongitude(), 1.2); - EXPECT_DOUBLE_EQ(a.getGalacticLatitude(), 0.6); - EXPECT_TRUE(a.getGalacticDirectionVector().isUnitVector()); - EXPECT_TRUE(a.getSuperGalacticDirectionVector().isUnitVector()); - - a.setSuperGalacticCoordinates(-0.2,-0.7); - EXPECT_DOUBLE_EQ(a.getSuperGalacticLongitude(), -0.2); - EXPECT_DOUBLE_EQ(a.getSuperGalacticLatitude(), -0.7); - EXPECT_TRUE(a.getGalacticDirectionVector().isUnitVector()); - - a.setEquatorialCoordinates(0.2,1.2); - EXPECT_NEAR(a.getRightAscension(), 0.2,1E-6); - EXPECT_NEAR(a.getDeclination(), 1.2,1E-6); - - EXPECT_TRUE(a.getGalacticDirectionVector().isUnitVector()); - EXPECT_TRUE(a.getSuperGalacticDirectionVector().isUnitVector()); - - pxl::Basic3Vector v(1,0,0); - a.setGalacticDirectionVector(v); - EXPECT_TRUE(v == a.getGalacticDirectionVector()); -} - -TEST(AstroBasicObject, SerializeDeserialize) -{ - Core::initialize(); - Astro::initialize(); - AstroBasicObject a; - a.setGalacticCoordinates(1.2,0.6); - AstroBasicObject *b = dynamic_cast (ioTest(&a)); - EXPECT_NEAR(a.getGalacticLongitude(), b->getGalacticLongitude(),1E-6); - EXPECT_NEAR(a.getGalacticLatitude(), b->getGalacticLatitude(),1E-6); - delete b; -} - -TEST(AstroObject, softRelations) -{ - AstroObject a; - AstroObject b; - a.linkSoft(&b, "foo"); - EXPECT_TRUE(a.getSoftRelations().has(&b,"foo")); - EXPECT_TRUE(b.getSoftRelations().has(&a,"foo")); - EXPECT_FALSE(a.getSoftRelations().has(&b,"bar")); - a.unlinkSoft(b,"foo"); - EXPECT_FALSE(a.getSoftRelations().has(&b,"foo")); - EXPECT_FALSE(b.getSoftRelations().has(&a,"foo")); -} - - -TEST(AstroObject, UniqueSoftrelations) -{ - pxl::AstroObject r1,r2; - r1.linkSoft(r2, "Foo"); - r1.linkSoft(r2, "Foo"); - r2.linkSoft(r1, "Foo"); - r2.linkSoft(r1, "Foo"); - EXPECT_EQ(r1.getSoftRelations().size(),1); -} - - -TEST(RegionOfInterest, objectInCone) -{ - RegionOfInterest roi; - roi.setGalacticCoordinates(1,0); - roi.setConeRadius(0.15); - - AstroBasicObject a; - a.setGalacticCoordinates(1.1,0); - AstroBasicObject b; - b.setGalacticCoordinates(1.2,0); - EXPECT_TRUE(roi.objectInCone(a)); - EXPECT_FALSE(roi.objectInCone(b)); - - roi.setGalacticCoordinates(0,M_PI/2); - a.setGalacticCoordinates(0,M_PI/2); - EXPECT_TRUE(roi.objectInCone(a)); - EXPECT_FALSE(roi.objectInCone(b)); - - roi.setGalacticCoordinates(0,-M_PI/2); - a.setGalacticCoordinates(0,-M_PI/2); - b.setGalacticCoordinates(0,M_PI/2); - EXPECT_TRUE(roi.objectInCone(a)); - EXPECT_FALSE(roi.objectInCone(b)); -} - -TEST(RegionOfInterest, linkIfObjectInCone) -{ - RegionOfInterest roi; - roi.setGalacticCoordinates(1,0); - roi.setConeRadius(0.15); - - AstroObject a; - a.setGalacticCoordinates(1.1,0); - AstroObject b; - b.setGalacticCoordinates(1.2,0); - roi.linkIfObjectInCone(a); - roi.linkIfObjectInCone(b); - EXPECT_TRUE(roi.getSoftRelations().has(&a)); - EXPECT_TRUE(a.getSoftRelations().has(&roi)); - EXPECT_FALSE(roi.getSoftRelations().has(&b)); - EXPECT_FALSE(b.getSoftRelations().has(&roi)); -} - -TEST(RegionOfInterest, SerializeDeserialize) -{ - Astro::initialize(); - RegionOfInterest a; - a.setConeRadius(0.4); - RegionOfInterest *b = dynamic_cast (ioTest(&a)); - EXPECT_TRUE(a.getConeRadius() == b->getConeRadius()); - delete b; -} - -TEST(UHECR, SerializeDeserialize) -{ - Astro::initialize(); - UHECR a; - a.setEnergy(0.4); - a.setMass(0.3); - a.setEnergyError(4); - a.setCharge(40); - - UHECR *b = dynamic_cast (ioTest(&a)); - EXPECT_TRUE(a.getEnergy() == b->getEnergy()); - EXPECT_TRUE(a.getEnergyError() == b->getEnergyError()); - EXPECT_TRUE(a.getMass() == b->getMass()); - EXPECT_TRUE(a.getCharge() == b->getCharge()); - delete b; -} - -TEST(UHECRSource, SerializeDeserialize) -{ - Astro::initialize(); - UHECRSource a; - a.setName("CenB"); - a.setDistance(0.4); - a.setLuminosity(1.3); - - UHECRSource *b = dynamic_cast (ioTest(&a)); - EXPECT_TRUE(a.getDistance() == b->getDistance()); - EXPECT_TRUE(a.getLuminosity() == b->getLuminosity()); - EXPECT_STREQ(a.getName().c_str(), b->getName().c_str()); - delete b; -} - -class CoordinatesTester : public testing::Test -{ - protected: - void TestCoordinatesObject(std::string name, double longitude, double latitude, double rightAscension, double declination, double superGalacticLongitude, double superGalacticLatitude, double accuracy, CoordinateTransformations::Epoque_T epoque=CoordinateTransformations::J2000) - { - if (longitude > M_PI) - { - longitude-=2*M_PI; - } - if (superGalacticLongitude > M_PI) - { - superGalacticLongitude-=2*M_PI; - } - - AstroBasicObject aGalactic; - AstroBasicObject aSuperGalactic; - AstroBasicObject aEquatorial; - - aGalactic.setGalacticCoordinates(longitude,latitude); - aSuperGalactic.setSuperGalacticCoordinates(superGalacticLongitude, superGalacticLatitude); - aEquatorial.setEquatorialCoordinates(rightAscension, declination, epoque); - - EXPECT_NEAR(aGalactic.getSuperGalacticLongitude(), superGalacticLongitude, accuracy); - EXPECT_NEAR(aGalactic.getSuperGalacticLatitude(), superGalacticLatitude, accuracy); - EXPECT_NEAR(aGalactic.getRightAscension(), rightAscension, accuracy); - EXPECT_NEAR(aGalactic.getDeclination(), declination, accuracy); - - EXPECT_NEAR(aSuperGalactic.getGalacticLongitude(), longitude, accuracy); - EXPECT_NEAR(aSuperGalactic.getGalacticLatitude(), latitude, accuracy); - EXPECT_NEAR(aSuperGalactic.getRightAscension(), rightAscension, accuracy); - EXPECT_NEAR(aSuperGalactic.getDeclination(), declination, accuracy); - - EXPECT_NEAR(aEquatorial.getSuperGalacticLongitude(), superGalacticLongitude, accuracy); - EXPECT_NEAR(aEquatorial.getSuperGalacticLatitude(), superGalacticLatitude, accuracy); - EXPECT_NEAR(aEquatorial.getGalacticLongitude(), longitude, accuracy); - EXPECT_NEAR(aEquatorial.getGalacticLatitude(), latitude, accuracy); - - EXPECT_PRED_FORMAT2(::testing::DoubleLE, aGalactic.angularDistanceTo(aSuperGalactic), accuracy); - EXPECT_PRED_FORMAT2(::testing::DoubleLE, aGalactic.angularDistanceTo(aEquatorial), accuracy); - EXPECT_PRED_FORMAT2(::testing::DoubleLE, aSuperGalactic.angularDistanceTo(aEquatorial), accuracy); - } -}; - - -TEST_F(CoordinatesTester, CoordinateTransformations) -{ - TestCoordinatesObject("Galactic Center", - 0, - 0, - CoordinateTransformations::timeAngle2Radian(17,45,37.224), - CoordinateTransformations::minutesOfArc2Radian(-28,56,10.23), - -174.21384/180.*M_PI, - 42.3102/180.*M_PI, - 1E-5, - CoordinateTransformations::J2000 - ); - - TestCoordinatesObject("Virgo Cluster", - (279.676-360)/180.*M_PI, - 74.460/180*M_PI, - CoordinateTransformations::timeAngle2Radian(12,26,34), - CoordinateTransformations::minutesOfArc2Radian(12,43,00), - 102.260/180*M_PI, - -3.254/180*M_PI, - 1E-3, - CoordinateTransformations::J2000 - ); -//Objects from the 2 Micron All-Sky Survey Redshift Survey -//2MRS, Huchra et al. 2007 -//http://www.cfa.harvard.edu/~huchra/seminar/lsc/ - TestCoordinatesObject("000138.30+2329011 ", - 109.092/180.*M_PI, - -38.111/180*M_PI, - CoordinateTransformations::timeAngle2Radian(00,01,38.30), - CoordinateTransformations::minutesOfArc2Radian(23,29,1.1), - (316.635-360)/180*M_PI, - 17.611/180*M_PI, - 0.1, - CoordinateTransformations::J2000 - ); - - - TestCoordinatesObject("115514.64-3741464", - (291.318-360.)/180.*M_PI, - 23.972/180*M_PI, - 178.811/180.*M_PI, - -37.696/180.*M_PI, - (151.377)/180*M_PI, - -20.741/180*M_PI, - 0.1, - CoordinateTransformations::J2000 - ); - - TestCoordinatesObject("235925.50+2044595", - (291.318-360.)/180.*M_PI, - 23.972/180*M_PI, - 178.811/180.*M_PI, - -37.696/180.*M_PI, - (151.377)/180*M_PI, - -20.741/180*M_PI, - 0.1, - CoordinateTransformations::J2000 - ); - - -} - -TEST(CoordinateTransformations, equatorialEpoques) -{ -//data from VCV Catloguei -// test MS 23575-6352 -AstroBasicObject j2000; -AstroBasicObject j1950; - -j2000.setEquatorialCoordinates(0, 0, 8.0, -63,35,36,CoordinateTransformations::J2000); -j1950.setEquatorialCoordinates(23, 57 , 33.5, -63, 52, 18,CoordinateTransformations::J1950); -EXPECT_NEAR(j2000.angularDistanceTo(j1950), 0,0.01); - -} - - -TEST(SoftRelations, getSoftRelativesOfType) -{ - AstroObject *a = new AstroObject(); - RegionOfInterest *r = new RegionOfInterest(); - r->linkSoft(a, "Foo"); - - BasicContainer b; - b.insertObject(a); - b.insertObject(r); - Serializable* f = b.getById(a->getId()); - ASSERT_EQ(f,a); - Serializable* rf = b.getById(r->getId()); - ASSERT_EQ(rf,r); - - std::vector v; - r->getSoftRelations().getSoftRelativesOfType(v, b); - ASSERT_EQ(1, v.size()); - ASSERT_TRUE(v[0] == a); - -} - - - - -// -// Tests for all serializables in astro -typedef Types SerealizableAstroImplementations; -INSTANTIATE_TYPED_TEST_CASE_P(SerealizablesInAstro, // Instance name - SerializableTest, // Test case name - SerealizableAstroImplementations); - - -- GitLab From 5d408f64749bdc07225df133f9ee2d0d919dfed7 Mon Sep 17 00:00:00 2001 From: marcel Date: Wed, 11 May 2016 18:13:36 +0200 Subject: [PATCH 002/130] Remove BasicMatrix and BasicNVector. --- core/include/pxl/core/Basic3Vector.hh | 273 ------------------- core/include/pxl/core/BasicMatrix.hh | 289 -------------------- core/include/pxl/core/BasicNVector.hh | 205 -------------- core/src/BasicContainer.cc | 207 -------------- core/src/BasicMatrix.cc | 378 -------------------------- core/src/BasicNVector.cc | 298 -------------------- 6 files changed, 1650 deletions(-) delete mode 100644 core/include/pxl/core/Basic3Vector.hh delete mode 100644 core/include/pxl/core/BasicMatrix.hh delete mode 100644 core/include/pxl/core/BasicNVector.hh delete mode 100644 core/src/BasicContainer.cc delete mode 100644 core/src/BasicMatrix.cc delete mode 100644 core/src/BasicNVector.cc diff --git a/core/include/pxl/core/Basic3Vector.hh b/core/include/pxl/core/Basic3Vector.hh deleted file mode 100644 index 25a12f42..00000000 --- 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/BasicMatrix.hh b/core/include/pxl/core/BasicMatrix.hh deleted file mode 100644 index 75903697..00000000 --- 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 0692e06d..00000000 --- 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/src/BasicContainer.cc b/core/src/BasicContainer.cc deleted file mode 100644 index 45d68aa0..00000000 --- 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 c132f1cd..00000000 --- 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 -- GitLab From d92c6beec58f036ac326b35d86cdde507dc95e84 Mon Sep 17 00:00:00 2001 From: marcel Date: Wed, 11 May 2016 18:13:53 +0200 Subject: [PATCH 003/130] Rename Basic3Vector to Vector3. --- core/include/pxl/core.hh | 4 +- core/include/pxl/core/BasicContainer.hh | 261 --------------------- core/include/pxl/core/Vector3.hh | 275 +++++++++++++++++++++++ core/src/{Basic3Vector.cc => Vector3.cc} | 0 4 files changed, 276 insertions(+), 264 deletions(-) delete mode 100644 core/include/pxl/core/BasicContainer.hh create mode 100644 core/include/pxl/core/Vector3.hh rename core/src/{Basic3Vector.cc => Vector3.cc} (100%) diff --git a/core/include/pxl/core.hh b/core/include/pxl/core.hh index 1899af9f..2fab09f1 100644 --- a/core/include/pxl/core.hh +++ b/core/include/pxl/core.hh @@ -9,9 +9,6 @@ #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" @@ -35,6 +32,7 @@ #include "pxl/core/SoftRelations.hh" #include "pxl/core/UserRecord.hh" #include "pxl/core/Variant.hh" +#include "pxl/core/Vector3.hh" #include "pxl/core/weak_ptr.hh" #include "pxl/core/WkPtrBase.hh" #include "pxl/core/ChunkReader.hh" diff --git a/core/include/pxl/core/BasicContainer.hh b/core/include/pxl/core/BasicContainer.hh deleted file mode 100644 index b5c19fa3..00000000 --- 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/Vector3.hh b/core/include/pxl/core/Vector3.hh new file mode 100644 index 00000000..114ab861 --- /dev/null +++ b/core/include/pxl/core/Vector3.hh @@ -0,0 +1,275 @@ +//------------------------------------------- +// Project: Physics eXtension Library (PXL) - +// http://vispa.physik.rwth-aachen.de/ - +// Copyright (C) 2006-2016 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" + + +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_CORE_VECTOR3_HH diff --git a/core/src/Basic3Vector.cc b/core/src/Vector3.cc similarity index 100% rename from core/src/Basic3Vector.cc rename to core/src/Vector3.cc -- GitLab From 3fac4dfac379d77801eee425381308856bea5918 Mon Sep 17 00:00:00 2001 From: Marcel Rieger Date: Thu, 12 May 2016 18:24:42 +0200 Subject: [PATCH 004/130] Remove .hgignore, add .gitignore. --- .gitignore | 18 ++++++++++ .hgignore | 98 ------------------------------------------------------ 2 files changed, 18 insertions(+), 98 deletions(-) create mode 100644 .gitignore delete mode 100644 .hgignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..46943f4f --- /dev/null +++ b/.gitignore @@ -0,0 +1,18 @@ +*.pyc +.*.swp +*.Po +*.Plo +*.lo +*.o +*.so +*.la +*.a +*.cxx +*.log +.libs/* +.deps/* +*.tar.Z +*.tar.bz2 +*.tar.gz + +build diff --git a/.hgignore b/.hgignore deleted file mode 100644 index db9ff427..00000000 --- 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 -- GitLab From 33f53350b91d3875b3bde7337a1d5c35ee0f4550 Mon Sep 17 00:00:00 2001 From: Marcel Rieger Date: Mon, 29 Aug 2016 14:31:04 +0200 Subject: [PATCH 005/130] Update disclaimer. --- .clang-format | 5 +++++ README | 2 +- algorithms/include/pxl/algorithms.hh | 2 +- algorithms/include/pxl/algorithms/AutoLayout.hh | 2 +- algorithms/src/AutoLayout.cc | 2 +- core/config.hh.in | 2 +- core/include/pxl/core.hh | 2 +- core/include/pxl/core/ChunkReader.hh | 2 +- core/include/pxl/core/ChunkWriter.hh | 2 +- core/include/pxl/core/ConfigLoader.hh | 2 +- core/include/pxl/core/Configuration.hh | 2 +- core/include/pxl/core/Core.hh | 2 +- core/include/pxl/core/Event.hh | 2 +- core/include/pxl/core/File.hh | 2 +- core/include/pxl/core/FileFactory.hh | 2 +- core/include/pxl/core/Filter.hh | 2 +- core/include/pxl/core/GenericInputHandler.hh | 2 +- core/include/pxl/core/GenericOutputHandler.hh | 2 +- core/include/pxl/core/Id.hh | 2 +- core/include/pxl/core/InformationChunk.hh | 2 +- core/include/pxl/core/InputFile.hh | 2 +- core/include/pxl/core/InputHandler.hh | 2 +- core/include/pxl/core/LorentzVector.hh | 2 +- core/include/pxl/core/MessageDispatcher.hh | 2 +- core/include/pxl/core/Object.hh | 2 +- core/include/pxl/core/ObjectFactory.hh | 2 +- core/include/pxl/core/ObjectManager.hh | 2 +- core/include/pxl/core/ObjectOwner.hh | 2 +- core/include/pxl/core/OutputFile.hh | 2 +- core/include/pxl/core/OutputHandler.hh | 2 +- core/include/pxl/core/PluginManager.hh | 2 +- core/include/pxl/core/RandomAccessInputFile.hh | 2 +- core/include/pxl/core/Relations.hh | 2 +- core/include/pxl/core/Relative.hh | 2 +- core/include/pxl/core/Serializable.hh | 2 +- core/include/pxl/core/SoftRelations.hh | 2 +- core/include/pxl/core/Stream.hh | 2 +- core/include/pxl/core/Tokenizer.hh | 2 +- core/include/pxl/core/UserRecord.hh | 2 +- core/include/pxl/core/Variant.hh | 2 +- core/include/pxl/core/WkPtrBase.hh | 2 +- core/include/pxl/core/functions.hh | 2 +- core/include/pxl/core/logging.hh | 2 +- core/include/pxl/core/macros.hh | 2 +- core/include/pxl/core/weak_ptr.hh | 2 +- core/src/ChunkReader.cc | 2 +- core/src/ChunkWriter.cc | 2 +- core/src/ConfigLoader.cc | 2 +- core/src/Configuration.cc | 2 +- core/src/Event.cc | 2 +- core/src/FileFactory.cc | 2 +- core/src/Id.cc | 2 +- core/src/InformationChunk.cc | 2 +- core/src/InputHandler.cc | 2 +- core/src/LorentzVector.cc | 2 +- core/src/MessageDispatcher.cc | 2 +- core/src/Object.cc | 2 +- core/src/ObjectFactory.cc | 2 +- core/src/ObjectManager.cc | 2 +- core/src/ObjectOwner.cc | 2 +- core/src/OutputFile.cc | 2 +- core/src/OutputHandler.cc | 2 +- core/src/PluginManager.cc | 2 +- core/src/Relations.cc | 2 +- core/src/Relative.cc | 2 +- core/src/SoftRelations.cc | 2 +- core/src/UserRecord.cc | 2 +- core/src/Variant.cc | 2 +- core/src/Vector3.cc | 2 +- core/src/WkPtrBase.cc | 2 +- core/src/dCapFileImpl.hh | 2 +- core/src/functions.cc | 2 +- core/src/logging.cc | 2 +- core/src/sFTPFileImpl.hh | 2 +- doc/pxl/main.doc | 2 +- doc/pypxl/main.doc | 2 +- examples/ExampleUserObject.cpp | 2 +- examples/ExampleUserObject.h | 2 +- examples/exampleModule.cpp | 2 +- examples/pxlexample.cc | 2 +- examples/pypxlexample.py | 2 +- hep/include/pxl/hep.hh | 2 +- hep/include/pxl/hep/AnalysisFork.hh | 2 +- hep/include/pxl/hep/AnalysisProcess.hh | 2 +- hep/include/pxl/hep/Collision.hh | 2 +- hep/include/pxl/hep/CommonParticle.hh | 2 +- hep/include/pxl/hep/CommonVertex.hh | 2 +- hep/include/pxl/hep/EventView.hh | 2 +- hep/include/pxl/hep/Hep.hh | 2 +- hep/include/pxl/hep/Particle.hh | 2 +- hep/include/pxl/hep/ParticleFilter.hh | 2 +- hep/include/pxl/hep/Vertex.hh | 2 +- hep/src/AnalysisFork.cc | 2 +- hep/src/AnalysisProcess.cc | 2 +- hep/src/Collision.cc | 2 +- hep/src/EventView.cc | 2 +- hep/src/Hep.cc | 2 +- hep/src/Particle.cc | 2 +- hep/src/Vertex.cc | 2 +- modules/include/pxl/modules.hh | 2 +- modules/include/pxl/modules/Analysis.hh | 2 +- modules/include/pxl/modules/InputModule.hh | 2 +- modules/include/pxl/modules/Module.hh | 2 +- modules/include/pxl/modules/ModuleFactory.hh | 2 +- modules/include/pxl/modules/Modules.hh | 2 +- modules/include/pxl/modules/OutputModule.hh | 2 +- modules/include/pxl/modules/PyAnalyseModule.hh | 2 +- modules/include/pxl/modules/PyDecideModule.hh | 2 +- modules/include/pxl/modules/PyGeneratorModule.hh | 2 +- modules/include/pxl/modules/PyModule.hh | 2 +- modules/include/pxl/modules/PyModuleModule.hh | 2 +- modules/include/pxl/modules/PySwitchModule.hh | 2 +- modules/include/pxl/modules/SubscriberModule.hh | 2 +- modules/src/Analysis.cc | 2 +- modules/src/InputModule.cc | 2 +- modules/src/Module.cc | 2 +- modules/src/ModuleFactory.cc | 2 +- modules/src/Modules.cc | 2 +- modules/src/OutputModule.cc | 2 +- modules/src/PyAnalyseModule.cc | 2 +- modules/src/PyDecideModule.cc | 2 +- modules/src/PyGeneratorModule.cc | 2 +- modules/src/PyModule.cc | 2 +- modules/src/PyModuleModule.cc | 2 +- modules/src/PySwitchModule.cc | 2 +- modules/src/SubscriberModule.cc | 2 +- pxlrun/src/main.cc | 2 +- scripting/include/pxl/scripting.hh | 2 +- scripting/include/pxl/scripting/DefaultScriptFilter.hh | 2 +- scripting/include/pxl/scripting/EventViewScriptFilter.hh | 2 +- scripting/include/pxl/scripting/ParticleScriptFilter.hh | 2 +- scripting/include/pxl/scripting/Script.hh | 2 +- scripting/src/DefaultScriptFilter.cc | 2 +- scripting/src/EventViewScriptFilter.cc | 2 +- scripting/src/ParticleScriptFilter.cc | 2 +- scripting/src/Script.cc | 2 +- test/HepTest.cc | 2 +- test/pypxl_testCore.py3.in | 2 +- test/pypxl_testHep.py3.in | 2 +- test/pypxl_testModules.py3.in | 2 +- test/pypxl_testXml.py3.in | 2 +- xml/include/pxl/xml/AnalysisXmlExport.hh | 2 +- xml/include/pxl/xml/AnalysisXmlImport.hh | 2 +- xml/include/pxl/xml/AnalysisXmlWriter.hh | 2 +- xml/include/pxl/xml/ModuleXmlHandler.hh | 2 +- xml/include/pxl/xml/UserRecordsXmlHandler.hh | 2 +- xml/include/pxl/xml/UserRecordsXmlWriter.hh | 2 +- xml/include/pxl/xml/XmlHandler.hh | 2 +- xml/include/pxl/xml/XmlStream.hh | 2 +- xml/src/AnalysisXmlExport.cc | 2 +- xml/src/AnalysisXmlImport.cc | 2 +- xml/src/AnalysisXmlWriter.cc | 2 +- xml/src/ModuleXmlHandler.cc | 2 +- xml/src/UserRecordsXmlHandler.cc | 2 +- xml/src/UserRecordsXmlWriter.cc | 2 +- xml/src/XmlHandler.cc | 2 +- xml/src/XmlStream.cc | 2 +- 157 files changed, 161 insertions(+), 156 deletions(-) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000..42c3b269 --- /dev/null +++ b/.clang-format @@ -0,0 +1,5 @@ +--- +BasedOnStyle: WebKit +IndentWidth: 4 +ColumnLimit: 100 +--- diff --git a/README b/README index aaeb8fb0..7dd9659a 100644 --- a/README +++ b/README @@ -3,7 +3,7 @@ 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 + Copyright (C) 2006-2016 M. Erdmann Web: https://vispa.physik.rwth-aachen.de/pxl Contact: vispa@lists.rwth-aachen.de diff --git a/algorithms/include/pxl/algorithms.hh b/algorithms/include/pxl/algorithms.hh index 21d4d3d3..77d44d09 100644 --- a/algorithms/include/pxl/algorithms.hh +++ b/algorithms/include/pxl/algorithms.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/algorithms/include/pxl/algorithms/AutoLayout.hh b/algorithms/include/pxl/algorithms/AutoLayout.hh index 05bd3458..c8048982 100644 --- a/algorithms/include/pxl/algorithms/AutoLayout.hh +++ b/algorithms/include/pxl/algorithms/AutoLayout.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/algorithms/src/AutoLayout.cc b/algorithms/src/AutoLayout.cc index ac7389fe..7932d1cc 100644 --- a/algorithms/src/AutoLayout.cc +++ b/algorithms/src/AutoLayout.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/config.hh.in b/core/config.hh.in index 269b4db1..9bebb476 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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core.hh b/core/include/pxl/core.hh index 2fab09f1..2a100550 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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/ChunkReader.hh b/core/include/pxl/core/ChunkReader.hh index 454151b2..477651c0 100644 --- a/core/include/pxl/core/ChunkReader.hh +++ b/core/include/pxl/core/ChunkReader.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/ChunkWriter.hh b/core/include/pxl/core/ChunkWriter.hh index 06af6898..e3673d0c 100644 --- a/core/include/pxl/core/ChunkWriter.hh +++ b/core/include/pxl/core/ChunkWriter.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/ConfigLoader.hh b/core/include/pxl/core/ConfigLoader.hh index 5783ea99..fa7ecc0c 100644 --- a/core/include/pxl/core/ConfigLoader.hh +++ b/core/include/pxl/core/ConfigLoader.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/Configuration.hh b/core/include/pxl/core/Configuration.hh index 312103f3..f9947764 100644 --- a/core/include/pxl/core/Configuration.hh +++ b/core/include/pxl/core/Configuration.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/Core.hh b/core/include/pxl/core/Core.hh index db4837c8..93949e35 100644 --- a/core/include/pxl/core/Core.hh +++ b/core/include/pxl/core/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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/Event.hh b/core/include/pxl/core/Event.hh index 298540fe..2096668e 100644 --- a/core/include/pxl/core/Event.hh +++ b/core/include/pxl/core/Event.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/File.hh b/core/include/pxl/core/File.hh index 6009fc67..1cf65f58 100644 --- a/core/include/pxl/core/File.hh +++ b/core/include/pxl/core/File.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/FileFactory.hh b/core/include/pxl/core/FileFactory.hh index b7f58d70..db2f5ded 100644 --- a/core/include/pxl/core/FileFactory.hh +++ b/core/include/pxl/core/FileFactory.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/Filter.hh b/core/include/pxl/core/Filter.hh index b47b718b..318aa062 100644 --- a/core/include/pxl/core/Filter.hh +++ b/core/include/pxl/core/Filter.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/GenericInputHandler.hh b/core/include/pxl/core/GenericInputHandler.hh index 66767938..4ee8508f 100644 --- a/core/include/pxl/core/GenericInputHandler.hh +++ b/core/include/pxl/core/GenericInputHandler.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/GenericOutputHandler.hh b/core/include/pxl/core/GenericOutputHandler.hh index 83b2996d..9723b0ed 100644 --- a/core/include/pxl/core/GenericOutputHandler.hh +++ b/core/include/pxl/core/GenericOutputHandler.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/Id.hh b/core/include/pxl/core/Id.hh index b1aa5870..4887ba0a 100644 --- a/core/include/pxl/core/Id.hh +++ b/core/include/pxl/core/Id.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/InformationChunk.hh b/core/include/pxl/core/InformationChunk.hh index 0d91f9ac..7b6dd402 100644 --- a/core/include/pxl/core/InformationChunk.hh +++ b/core/include/pxl/core/InformationChunk.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/InputFile.hh b/core/include/pxl/core/InputFile.hh index 6d81460d..01b6b3fb 100644 --- a/core/include/pxl/core/InputFile.hh +++ b/core/include/pxl/core/InputFile.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/InputHandler.hh b/core/include/pxl/core/InputHandler.hh index 454f5696..f38433fc 100644 --- a/core/include/pxl/core/InputHandler.hh +++ b/core/include/pxl/core/InputHandler.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/LorentzVector.hh b/core/include/pxl/core/LorentzVector.hh index e64abd54..3d693f7e 100644 --- a/core/include/pxl/core/LorentzVector.hh +++ b/core/include/pxl/core/LorentzVector.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/MessageDispatcher.hh b/core/include/pxl/core/MessageDispatcher.hh index 3521d0cd..546cf417 100644 --- a/core/include/pxl/core/MessageDispatcher.hh +++ b/core/include/pxl/core/MessageDispatcher.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/Object.hh b/core/include/pxl/core/Object.hh index e6315f13..64f8a242 100644 --- a/core/include/pxl/core/Object.hh +++ b/core/include/pxl/core/Object.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/ObjectFactory.hh b/core/include/pxl/core/ObjectFactory.hh index 9f2f7e5e..ab013fbe 100644 --- a/core/include/pxl/core/ObjectFactory.hh +++ b/core/include/pxl/core/ObjectFactory.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/ObjectManager.hh b/core/include/pxl/core/ObjectManager.hh index a594ee9c..f6b206eb 100644 --- a/core/include/pxl/core/ObjectManager.hh +++ b/core/include/pxl/core/ObjectManager.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/ObjectOwner.hh b/core/include/pxl/core/ObjectOwner.hh index 6b3eaf63..239b260c 100644 --- a/core/include/pxl/core/ObjectOwner.hh +++ b/core/include/pxl/core/ObjectOwner.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/OutputFile.hh b/core/include/pxl/core/OutputFile.hh index 35dd32cb..b132c300 100644 --- a/core/include/pxl/core/OutputFile.hh +++ b/core/include/pxl/core/OutputFile.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/OutputHandler.hh b/core/include/pxl/core/OutputHandler.hh index be507c90..084ddf2a 100644 --- a/core/include/pxl/core/OutputHandler.hh +++ b/core/include/pxl/core/OutputHandler.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/PluginManager.hh b/core/include/pxl/core/PluginManager.hh index 05e7f931..e0dca845 100644 --- a/core/include/pxl/core/PluginManager.hh +++ b/core/include/pxl/core/PluginManager.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/RandomAccessInputFile.hh b/core/include/pxl/core/RandomAccessInputFile.hh index 398170f3..bf9c5671 100644 --- a/core/include/pxl/core/RandomAccessInputFile.hh +++ b/core/include/pxl/core/RandomAccessInputFile.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/Relations.hh b/core/include/pxl/core/Relations.hh index 1b083585..98e4f1f0 100644 --- a/core/include/pxl/core/Relations.hh +++ b/core/include/pxl/core/Relations.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/Relative.hh b/core/include/pxl/core/Relative.hh index a754257e..a6e07865 100644 --- a/core/include/pxl/core/Relative.hh +++ b/core/include/pxl/core/Relative.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/Serializable.hh b/core/include/pxl/core/Serializable.hh index bdfe2d2f..29eac224 100644 --- a/core/include/pxl/core/Serializable.hh +++ b/core/include/pxl/core/Serializable.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/SoftRelations.hh b/core/include/pxl/core/SoftRelations.hh index ff6ad978..e6e842db 100644 --- a/core/include/pxl/core/SoftRelations.hh +++ b/core/include/pxl/core/SoftRelations.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/Stream.hh b/core/include/pxl/core/Stream.hh index 824af0c1..c21b6903 100644 --- a/core/include/pxl/core/Stream.hh +++ b/core/include/pxl/core/Stream.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/Tokenizer.hh b/core/include/pxl/core/Tokenizer.hh index 0b03fa7e..50fe44ed 100644 --- a/core/include/pxl/core/Tokenizer.hh +++ b/core/include/pxl/core/Tokenizer.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/UserRecord.hh b/core/include/pxl/core/UserRecord.hh index 94c7316e..3063c336 100644 --- a/core/include/pxl/core/UserRecord.hh +++ b/core/include/pxl/core/UserRecord.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/Variant.hh b/core/include/pxl/core/Variant.hh index f643f5f7..35fbe9b3 100644 --- a/core/include/pxl/core/Variant.hh +++ b/core/include/pxl/core/Variant.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/WkPtrBase.hh b/core/include/pxl/core/WkPtrBase.hh index 21a76f99..81d26787 100644 --- a/core/include/pxl/core/WkPtrBase.hh +++ b/core/include/pxl/core/WkPtrBase.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/functions.hh b/core/include/pxl/core/functions.hh index 85cce83c..3a8d1100 100644 --- a/core/include/pxl/core/functions.hh +++ b/core/include/pxl/core/functions.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/logging.hh b/core/include/pxl/core/logging.hh index cae01110..56c6a80e 100644 --- a/core/include/pxl/core/logging.hh +++ b/core/include/pxl/core/logging.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/macros.hh b/core/include/pxl/core/macros.hh index cd261145..0a040b7b 100644 --- a/core/include/pxl/core/macros.hh +++ b/core/include/pxl/core/macros.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/include/pxl/core/weak_ptr.hh b/core/include/pxl/core/weak_ptr.hh index 7c55945e..d8a27e86 100644 --- a/core/include/pxl/core/weak_ptr.hh +++ b/core/include/pxl/core/weak_ptr.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/ChunkReader.cc b/core/src/ChunkReader.cc index 65294803..01f87268 100644 --- a/core/src/ChunkReader.cc +++ b/core/src/ChunkReader.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/ChunkWriter.cc b/core/src/ChunkWriter.cc index e1af5035..79f5def9 100644 --- a/core/src/ChunkWriter.cc +++ b/core/src/ChunkWriter.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/ConfigLoader.cc b/core/src/ConfigLoader.cc index 0078003e..3a06331d 100644 --- a/core/src/ConfigLoader.cc +++ b/core/src/ConfigLoader.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/Configuration.cc b/core/src/Configuration.cc index ad8ca040..1c3eb575 100644 --- a/core/src/Configuration.cc +++ b/core/src/Configuration.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/Event.cc b/core/src/Event.cc index 7c7a978f..1baafca7 100644 --- a/core/src/Event.cc +++ b/core/src/Event.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/FileFactory.cc b/core/src/FileFactory.cc index 2d91eb4f..1a0ccfd9 100644 --- a/core/src/FileFactory.cc +++ b/core/src/FileFactory.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/Id.cc b/core/src/Id.cc index a9621e75..2a5bf84a 100644 --- a/core/src/Id.cc +++ b/core/src/Id.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/InformationChunk.cc b/core/src/InformationChunk.cc index 145fca7f..45124458 100644 --- a/core/src/InformationChunk.cc +++ b/core/src/InformationChunk.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/InputHandler.cc b/core/src/InputHandler.cc index d9818255..a7b30899 100644 --- a/core/src/InputHandler.cc +++ b/core/src/InputHandler.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/LorentzVector.cc b/core/src/LorentzVector.cc index 9b550e96..3c476ff2 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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/MessageDispatcher.cc b/core/src/MessageDispatcher.cc index d33b622b..6eb05b9a 100644 --- a/core/src/MessageDispatcher.cc +++ b/core/src/MessageDispatcher.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/Object.cc b/core/src/Object.cc index eaa87947..53947bf2 100644 --- a/core/src/Object.cc +++ b/core/src/Object.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/ObjectFactory.cc b/core/src/ObjectFactory.cc index c7c1998c..daa30e73 100644 --- a/core/src/ObjectFactory.cc +++ b/core/src/ObjectFactory.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/ObjectManager.cc b/core/src/ObjectManager.cc index 15c2d23d..da16e5ee 100644 --- a/core/src/ObjectManager.cc +++ b/core/src/ObjectManager.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/ObjectOwner.cc b/core/src/ObjectOwner.cc index 143baebb..3ec00166 100644 --- a/core/src/ObjectOwner.cc +++ b/core/src/ObjectOwner.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/OutputFile.cc b/core/src/OutputFile.cc index c14a5110..77ab9ef8 100644 --- a/core/src/OutputFile.cc +++ b/core/src/OutputFile.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/OutputHandler.cc b/core/src/OutputHandler.cc index c0c5d35d..fb682759 100644 --- a/core/src/OutputHandler.cc +++ b/core/src/OutputHandler.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/PluginManager.cc b/core/src/PluginManager.cc index c3cc901b..b2636734 100644 --- a/core/src/PluginManager.cc +++ b/core/src/PluginManager.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/Relations.cc b/core/src/Relations.cc index 5514cef1..7162d933 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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/Relative.cc b/core/src/Relative.cc index d8101ee4..1a0996a7 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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/SoftRelations.cc b/core/src/SoftRelations.cc index db37a3a2..bf684c93 100644 --- a/core/src/SoftRelations.cc +++ b/core/src/SoftRelations.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/UserRecord.cc b/core/src/UserRecord.cc index a99a0e79..60866ef1 100644 --- a/core/src/UserRecord.cc +++ b/core/src/UserRecord.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/Variant.cc b/core/src/Variant.cc index 2264e939..8ed6f85b 100644 --- a/core/src/Variant.cc +++ b/core/src/Variant.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/Vector3.cc b/core/src/Vector3.cc index f74ff420..a813bc09 100644 --- a/core/src/Vector3.cc +++ b/core/src/Vector3.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/WkPtrBase.cc b/core/src/WkPtrBase.cc index 35ba44a3..89369d5c 100644 --- a/core/src/WkPtrBase.cc +++ b/core/src/WkPtrBase.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/dCapFileImpl.hh b/core/src/dCapFileImpl.hh index f8d6252b..fd7ef510 100644 --- a/core/src/dCapFileImpl.hh +++ b/core/src/dCapFileImpl.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/functions.cc b/core/src/functions.cc index 37c3e9b7..e6fdaf15 100644 --- a/core/src/functions.cc +++ b/core/src/functions.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/logging.cc b/core/src/logging.cc index 326b2e4a..6a23bc59 100644 --- a/core/src/logging.cc +++ b/core/src/logging.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/core/src/sFTPFileImpl.hh b/core/src/sFTPFileImpl.hh index d7c3b220..c5f3b268 100644 --- a/core/src/sFTPFileImpl.hh +++ b/core/src/sFTPFileImpl.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/doc/pxl/main.doc b/doc/pxl/main.doc index 8a5a79c4..d463b4e1 100644 --- a/doc/pxl/main.doc +++ b/doc/pxl/main.doc @@ -82,7 +82,7 @@ Physics eXtension Library (PXL) C++ Toolkit for Fourvector Analysis, Relation Management and Hypothesis Evolution in High Energy Physics -Copyright (C) 2006-2015 Martin Erdmann - +Copyright (C) 2006-2016 Martin Erdmann - E-mail contact: vispa@lists.rwth-aachen.de \n Website: http://vispa.physik.rwth-aachen.de diff --git a/doc/pypxl/main.doc b/doc/pypxl/main.doc index 7dcc30d6..ce77d72e 100644 --- a/doc/pypxl/main.doc +++ b/doc/pypxl/main.doc @@ -83,7 +83,7 @@ Physics eXtension Library (PXL) C++ Toolkit for Fourvector Analysis, Relation Management and Hypothesis Evolution in High Energy Physics -Copyright (C) 2006-2015 Martin Erdmann - +Copyright (C) 2006-2016 Martin Erdmann - E-mail contact: vispa@lists.rwth-aachen.de \n Website: http://vispa.physik.rwth-aachen.de diff --git a/examples/ExampleUserObject.cpp b/examples/ExampleUserObject.cpp index f1c8f05f..d42acfde 100644 --- a/examples/ExampleUserObject.cpp +++ b/examples/ExampleUserObject.cpp @@ -1,7 +1,7 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/examples/ExampleUserObject.h b/examples/ExampleUserObject.h index dc288173..11b4ab32 100644 --- a/examples/ExampleUserObject.h +++ b/examples/ExampleUserObject.h @@ -1,7 +1,7 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://pxl.sourceforge.net - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2016 Martin Erdmann - // RWTH Aachen, Germany - // Contact: pxl-users@lists.sourceforge.net - //------------------------------------------- diff --git a/examples/exampleModule.cpp b/examples/exampleModule.cpp index 35fccf8b..d03c5ec3 100755 --- a/examples/exampleModule.cpp +++ b/examples/exampleModule.cpp @@ -1,7 +1,7 @@ //------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - -// Copyright (C) 2006-2015 Martin Erdmann - +// Copyright (C) 2006-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/examples/pxlexample.cc b/examples/pxlexample.cc index ec729291..fe8e7c18 100644 --- a/examples/pxlexample.cc +++ b/examples/pxlexample.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/examples/pypxlexample.py b/examples/pypxlexample.py index 89710a34..35bc0363 100755 --- a/examples/pypxlexample.py +++ b/examples/pypxlexample.py @@ -3,7 +3,7 @@ #------------------------------------------- # Project: Physics eXtension Library (PXL) - # http://vispa.physik.rwth-aachen.de/ - -# Copyright (C) 2006-2015 Martin Erdmann - +# Copyright (C) 2006-2016 Martin Erdmann - # RWTH Aachen, Germany - # Licensed under a LGPL-2 or later license - #------------------------------------------- diff --git a/hep/include/pxl/hep.hh b/hep/include/pxl/hep.hh index 6be610e9..c4056d64 100644 --- a/hep/include/pxl/hep.hh +++ b/hep/include/pxl/hep.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/hep/include/pxl/hep/AnalysisFork.hh b/hep/include/pxl/hep/AnalysisFork.hh index e95d4445..bde6064b 100644 --- a/hep/include/pxl/hep/AnalysisFork.hh +++ b/hep/include/pxl/hep/AnalysisFork.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/hep/include/pxl/hep/AnalysisProcess.hh b/hep/include/pxl/hep/AnalysisProcess.hh index a2083adc..9bb48755 100644 --- a/hep/include/pxl/hep/AnalysisProcess.hh +++ b/hep/include/pxl/hep/AnalysisProcess.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/hep/include/pxl/hep/Collision.hh b/hep/include/pxl/hep/Collision.hh index 5e503df5..52f75b67 100644 --- a/hep/include/pxl/hep/Collision.hh +++ b/hep/include/pxl/hep/Collision.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/hep/include/pxl/hep/CommonParticle.hh b/hep/include/pxl/hep/CommonParticle.hh index 926888f0..f4d498f6 100644 --- a/hep/include/pxl/hep/CommonParticle.hh +++ b/hep/include/pxl/hep/CommonParticle.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/hep/include/pxl/hep/CommonVertex.hh b/hep/include/pxl/hep/CommonVertex.hh index af6ef3c6..9837a02b 100644 --- a/hep/include/pxl/hep/CommonVertex.hh +++ b/hep/include/pxl/hep/CommonVertex.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/hep/include/pxl/hep/EventView.hh b/hep/include/pxl/hep/EventView.hh index 296238e2..dfd90746 100644 --- a/hep/include/pxl/hep/EventView.hh +++ b/hep/include/pxl/hep/EventView.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/hep/include/pxl/hep/Hep.hh b/hep/include/pxl/hep/Hep.hh index 28de01a7..042c3436 100644 --- a/hep/include/pxl/hep/Hep.hh +++ b/hep/include/pxl/hep/Hep.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/hep/include/pxl/hep/Particle.hh b/hep/include/pxl/hep/Particle.hh index 68cf3660..c54376e6 100644 --- a/hep/include/pxl/hep/Particle.hh +++ b/hep/include/pxl/hep/Particle.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/hep/include/pxl/hep/ParticleFilter.hh b/hep/include/pxl/hep/ParticleFilter.hh index 29b0dba0..51721db6 100644 --- a/hep/include/pxl/hep/ParticleFilter.hh +++ b/hep/include/pxl/hep/ParticleFilter.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/hep/include/pxl/hep/Vertex.hh b/hep/include/pxl/hep/Vertex.hh index 6dd6158d..be0b34f1 100644 --- a/hep/include/pxl/hep/Vertex.hh +++ b/hep/include/pxl/hep/Vertex.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/hep/src/AnalysisFork.cc b/hep/src/AnalysisFork.cc index 4916cf55..941d280c 100644 --- a/hep/src/AnalysisFork.cc +++ b/hep/src/AnalysisFork.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/hep/src/AnalysisProcess.cc b/hep/src/AnalysisProcess.cc index f824ae32..8cf004c9 100644 --- a/hep/src/AnalysisProcess.cc +++ b/hep/src/AnalysisProcess.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/hep/src/Collision.cc b/hep/src/Collision.cc index b7fc03d5..fbb13694 100644 --- a/hep/src/Collision.cc +++ b/hep/src/Collision.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/hep/src/EventView.cc b/hep/src/EventView.cc index 2c8b9940..058d2cf3 100644 --- a/hep/src/EventView.cc +++ b/hep/src/EventView.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/hep/src/Hep.cc b/hep/src/Hep.cc index 83402f19..6b893d03 100644 --- a/hep/src/Hep.cc +++ b/hep/src/Hep.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/hep/src/Particle.cc b/hep/src/Particle.cc index 416888d8..d30c7110 100644 --- a/hep/src/Particle.cc +++ b/hep/src/Particle.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/hep/src/Vertex.cc b/hep/src/Vertex.cc index 2e6c54a8..9fefb6eb 100644 --- a/hep/src/Vertex.cc +++ b/hep/src/Vertex.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/include/pxl/modules.hh b/modules/include/pxl/modules.hh index c59ea76a..f9424830 100644 --- a/modules/include/pxl/modules.hh +++ b/modules/include/pxl/modules.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/include/pxl/modules/Analysis.hh b/modules/include/pxl/modules/Analysis.hh index 5b6ebf48..6f9d6621 100644 --- a/modules/include/pxl/modules/Analysis.hh +++ b/modules/include/pxl/modules/Analysis.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/include/pxl/modules/InputModule.hh b/modules/include/pxl/modules/InputModule.hh index 56354945..01f54569 100644 --- a/modules/include/pxl/modules/InputModule.hh +++ b/modules/include/pxl/modules/InputModule.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/include/pxl/modules/Module.hh b/modules/include/pxl/modules/Module.hh index 50b11a0b..e0324ad7 100644 --- a/modules/include/pxl/modules/Module.hh +++ b/modules/include/pxl/modules/Module.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/include/pxl/modules/ModuleFactory.hh b/modules/include/pxl/modules/ModuleFactory.hh index 6af967c0..11ae299b 100644 --- a/modules/include/pxl/modules/ModuleFactory.hh +++ b/modules/include/pxl/modules/ModuleFactory.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/include/pxl/modules/Modules.hh b/modules/include/pxl/modules/Modules.hh index 076d7a7a..afce2268 100644 --- a/modules/include/pxl/modules/Modules.hh +++ b/modules/include/pxl/modules/Modules.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/include/pxl/modules/OutputModule.hh b/modules/include/pxl/modules/OutputModule.hh index 39671327..68ad7882 100644 --- a/modules/include/pxl/modules/OutputModule.hh +++ b/modules/include/pxl/modules/OutputModule.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/include/pxl/modules/PyAnalyseModule.hh b/modules/include/pxl/modules/PyAnalyseModule.hh index 2e21b2c1..d3897fbd 100644 --- a/modules/include/pxl/modules/PyAnalyseModule.hh +++ b/modules/include/pxl/modules/PyAnalyseModule.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/include/pxl/modules/PyDecideModule.hh b/modules/include/pxl/modules/PyDecideModule.hh index e8310414..5e7aac33 100644 --- a/modules/include/pxl/modules/PyDecideModule.hh +++ b/modules/include/pxl/modules/PyDecideModule.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/include/pxl/modules/PyGeneratorModule.hh b/modules/include/pxl/modules/PyGeneratorModule.hh index d32e885b..5f6a1496 100644 --- a/modules/include/pxl/modules/PyGeneratorModule.hh +++ b/modules/include/pxl/modules/PyGeneratorModule.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/include/pxl/modules/PyModule.hh b/modules/include/pxl/modules/PyModule.hh index f56a2b61..afb8e1fa 100644 --- a/modules/include/pxl/modules/PyModule.hh +++ b/modules/include/pxl/modules/PyModule.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/include/pxl/modules/PyModuleModule.hh b/modules/include/pxl/modules/PyModuleModule.hh index 2b261654..df06ed61 100644 --- a/modules/include/pxl/modules/PyModuleModule.hh +++ b/modules/include/pxl/modules/PyModuleModule.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/include/pxl/modules/PySwitchModule.hh b/modules/include/pxl/modules/PySwitchModule.hh index 809e8d2c..2e3e8ed8 100644 --- a/modules/include/pxl/modules/PySwitchModule.hh +++ b/modules/include/pxl/modules/PySwitchModule.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/include/pxl/modules/SubscriberModule.hh b/modules/include/pxl/modules/SubscriberModule.hh index ec73a520..98e06ac6 100644 --- a/modules/include/pxl/modules/SubscriberModule.hh +++ b/modules/include/pxl/modules/SubscriberModule.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/src/Analysis.cc b/modules/src/Analysis.cc index c6a1fe8b..8f02e53f 100644 --- a/modules/src/Analysis.cc +++ b/modules/src/Analysis.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/src/InputModule.cc b/modules/src/InputModule.cc index e27df070..ba9d4408 100644 --- a/modules/src/InputModule.cc +++ b/modules/src/InputModule.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/src/Module.cc b/modules/src/Module.cc index 74038267..6f47c8f1 100644 --- a/modules/src/Module.cc +++ b/modules/src/Module.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/src/ModuleFactory.cc b/modules/src/ModuleFactory.cc index eed6bda9..1fff680c 100644 --- a/modules/src/ModuleFactory.cc +++ b/modules/src/ModuleFactory.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/src/Modules.cc b/modules/src/Modules.cc index f03aa330..6fa233b8 100644 --- a/modules/src/Modules.cc +++ b/modules/src/Modules.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/src/OutputModule.cc b/modules/src/OutputModule.cc index a6596449..64d54eb7 100644 --- a/modules/src/OutputModule.cc +++ b/modules/src/OutputModule.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/src/PyAnalyseModule.cc b/modules/src/PyAnalyseModule.cc index 39267525..1440e9d5 100644 --- a/modules/src/PyAnalyseModule.cc +++ b/modules/src/PyAnalyseModule.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/src/PyDecideModule.cc b/modules/src/PyDecideModule.cc index f355f7ae..c5edbe67 100644 --- a/modules/src/PyDecideModule.cc +++ b/modules/src/PyDecideModule.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/src/PyGeneratorModule.cc b/modules/src/PyGeneratorModule.cc index 421f3f30..6cabea47 100644 --- a/modules/src/PyGeneratorModule.cc +++ b/modules/src/PyGeneratorModule.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/src/PyModule.cc b/modules/src/PyModule.cc index 817f9250..1fe21ed7 100644 --- a/modules/src/PyModule.cc +++ b/modules/src/PyModule.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/src/PyModuleModule.cc b/modules/src/PyModuleModule.cc index f6c0760a..b44c0d14 100644 --- a/modules/src/PyModuleModule.cc +++ b/modules/src/PyModuleModule.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/src/PySwitchModule.cc b/modules/src/PySwitchModule.cc index 8b8df99d..a1cf0ef9 100644 --- a/modules/src/PySwitchModule.cc +++ b/modules/src/PySwitchModule.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/modules/src/SubscriberModule.cc b/modules/src/SubscriberModule.cc index e982a9f3..b8e94f30 100644 --- a/modules/src/SubscriberModule.cc +++ b/modules/src/SubscriberModule.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/pxlrun/src/main.cc b/pxlrun/src/main.cc index 2db55bd6..3077b3e3 100644 --- a/pxlrun/src/main.cc +++ b/pxlrun/src/main.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/scripting/include/pxl/scripting.hh b/scripting/include/pxl/scripting.hh index 5bb295f2..96b49a88 100644 --- a/scripting/include/pxl/scripting.hh +++ b/scripting/include/pxl/scripting.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/scripting/include/pxl/scripting/DefaultScriptFilter.hh b/scripting/include/pxl/scripting/DefaultScriptFilter.hh index 281b17d2..f7f95f80 100644 --- a/scripting/include/pxl/scripting/DefaultScriptFilter.hh +++ b/scripting/include/pxl/scripting/DefaultScriptFilter.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/scripting/include/pxl/scripting/EventViewScriptFilter.hh b/scripting/include/pxl/scripting/EventViewScriptFilter.hh index 8753c97a..8ab345f8 100644 --- a/scripting/include/pxl/scripting/EventViewScriptFilter.hh +++ b/scripting/include/pxl/scripting/EventViewScriptFilter.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/scripting/include/pxl/scripting/ParticleScriptFilter.hh b/scripting/include/pxl/scripting/ParticleScriptFilter.hh index a880cb73..7fa89088 100644 --- a/scripting/include/pxl/scripting/ParticleScriptFilter.hh +++ b/scripting/include/pxl/scripting/ParticleScriptFilter.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/scripting/include/pxl/scripting/Script.hh b/scripting/include/pxl/scripting/Script.hh index bed3a2c2..0fa823cb 100644 --- a/scripting/include/pxl/scripting/Script.hh +++ b/scripting/include/pxl/scripting/Script.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/scripting/src/DefaultScriptFilter.cc b/scripting/src/DefaultScriptFilter.cc index bd3824b2..011ebdd6 100644 --- a/scripting/src/DefaultScriptFilter.cc +++ b/scripting/src/DefaultScriptFilter.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/scripting/src/EventViewScriptFilter.cc b/scripting/src/EventViewScriptFilter.cc index 0d95eb74..c3bea039 100644 --- a/scripting/src/EventViewScriptFilter.cc +++ b/scripting/src/EventViewScriptFilter.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/scripting/src/ParticleScriptFilter.cc b/scripting/src/ParticleScriptFilter.cc index 2d0891a6..b5a59dd7 100644 --- a/scripting/src/ParticleScriptFilter.cc +++ b/scripting/src/ParticleScriptFilter.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/scripting/src/Script.cc b/scripting/src/Script.cc index 5cf5043f..699be2de 100644 --- a/scripting/src/Script.cc +++ b/scripting/src/Script.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/test/HepTest.cc b/test/HepTest.cc index d31345f3..384c184a 100644 --- a/test/HepTest.cc +++ b/test/HepTest.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/test/pypxl_testCore.py3.in b/test/pypxl_testCore.py3.in index 234e3388..9226e52f 100755 --- a/test/pypxl_testCore.py3.in +++ b/test/pypxl_testCore.py3.in @@ -3,7 +3,7 @@ #------------------------------------------- # Project: Physics eXtension Library (PXL) - # http://vispa.physik.rwth-aachen.de/ - -# Copyright (C) 2006-2015 Martin Erdmann - +# Copyright (C) 2006-2016 Martin Erdmann - # RWTH Aachen, Germany - # Licensed under a LGPL-2 or later license - #------------------------------------------- diff --git a/test/pypxl_testHep.py3.in b/test/pypxl_testHep.py3.in index 4fd2126f..7a13e607 100755 --- a/test/pypxl_testHep.py3.in +++ b/test/pypxl_testHep.py3.in @@ -3,7 +3,7 @@ #------------------------------------------- # Project: Physics eXtension Library (PXL) - # http://vispa.physik.rwth-aachen.de/ - -# Copyright (C) 2006-2015 Martin Erdmann - +# Copyright (C) 2006-2016 Martin Erdmann - # RWTH Aachen, Germany - # Licensed under a LGPL-2 or later license - #------------------------------------------- diff --git a/test/pypxl_testModules.py3.in b/test/pypxl_testModules.py3.in index 7cad88ad..db9ab036 100755 --- a/test/pypxl_testModules.py3.in +++ b/test/pypxl_testModules.py3.in @@ -3,7 +3,7 @@ #------------------------------------------- # Project: Physics eXtension Library (PXL) - # http://vispa.physik.rwth-aachen.de/ - -# Copyright (C) 2006-2015 Martin Erdmann - +# Copyright (C) 2006-2016 Martin Erdmann - # RWTH Aachen, Germany - # Licensed under a LGPL-2 or later license - #------------------------------------------- diff --git a/test/pypxl_testXml.py3.in b/test/pypxl_testXml.py3.in index d8cc380e..97dc5159 100755 --- a/test/pypxl_testXml.py3.in +++ b/test/pypxl_testXml.py3.in @@ -3,7 +3,7 @@ #------------------------------------------- # Project: Physics eXtension Library (PXL) - # http://vispa.physik.rwth-aachen.de/ - -# Copyright (C) 2006-2015 Martin Erdmann - +# Copyright (C) 2006-2016 Martin Erdmann - # RWTH Aachen, Germany - # Licensed under a LGPL-2 or later license - #------------------------------------------- diff --git a/xml/include/pxl/xml/AnalysisXmlExport.hh b/xml/include/pxl/xml/AnalysisXmlExport.hh index dc3426e6..69c06e1a 100755 --- a/xml/include/pxl/xml/AnalysisXmlExport.hh +++ b/xml/include/pxl/xml/AnalysisXmlExport.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/xml/include/pxl/xml/AnalysisXmlImport.hh b/xml/include/pxl/xml/AnalysisXmlImport.hh index fa09f8bf..5e45af6f 100644 --- a/xml/include/pxl/xml/AnalysisXmlImport.hh +++ b/xml/include/pxl/xml/AnalysisXmlImport.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/xml/include/pxl/xml/AnalysisXmlWriter.hh b/xml/include/pxl/xml/AnalysisXmlWriter.hh index 44999b05..dcb9f3fa 100644 --- a/xml/include/pxl/xml/AnalysisXmlWriter.hh +++ b/xml/include/pxl/xml/AnalysisXmlWriter.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/xml/include/pxl/xml/ModuleXmlHandler.hh b/xml/include/pxl/xml/ModuleXmlHandler.hh index 98f11113..7134f380 100644 --- a/xml/include/pxl/xml/ModuleXmlHandler.hh +++ b/xml/include/pxl/xml/ModuleXmlHandler.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/xml/include/pxl/xml/UserRecordsXmlHandler.hh b/xml/include/pxl/xml/UserRecordsXmlHandler.hh index 9fd21188..a1eeb5ec 100644 --- a/xml/include/pxl/xml/UserRecordsXmlHandler.hh +++ b/xml/include/pxl/xml/UserRecordsXmlHandler.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/xml/include/pxl/xml/UserRecordsXmlWriter.hh b/xml/include/pxl/xml/UserRecordsXmlWriter.hh index ca2f9f13..73c23d86 100644 --- a/xml/include/pxl/xml/UserRecordsXmlWriter.hh +++ b/xml/include/pxl/xml/UserRecordsXmlWriter.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/xml/include/pxl/xml/XmlHandler.hh b/xml/include/pxl/xml/XmlHandler.hh index 6ddedc8a..58979600 100644 --- a/xml/include/pxl/xml/XmlHandler.hh +++ b/xml/include/pxl/xml/XmlHandler.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/xml/include/pxl/xml/XmlStream.hh b/xml/include/pxl/xml/XmlStream.hh index bc1cd0c1..51baefc6 100644 --- a/xml/include/pxl/xml/XmlStream.hh +++ b/xml/include/pxl/xml/XmlStream.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/xml/src/AnalysisXmlExport.cc b/xml/src/AnalysisXmlExport.cc index 405b3b02..3fd5c1e1 100755 --- a/xml/src/AnalysisXmlExport.cc +++ b/xml/src/AnalysisXmlExport.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/xml/src/AnalysisXmlImport.cc b/xml/src/AnalysisXmlImport.cc index 108ba6c9..05d0a9a9 100644 --- a/xml/src/AnalysisXmlImport.cc +++ b/xml/src/AnalysisXmlImport.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/xml/src/AnalysisXmlWriter.cc b/xml/src/AnalysisXmlWriter.cc index afdcefe2..3a60794c 100644 --- a/xml/src/AnalysisXmlWriter.cc +++ b/xml/src/AnalysisXmlWriter.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/xml/src/ModuleXmlHandler.cc b/xml/src/ModuleXmlHandler.cc index 7a1f2f7b..eb025001 100644 --- a/xml/src/ModuleXmlHandler.cc +++ b/xml/src/ModuleXmlHandler.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/xml/src/UserRecordsXmlHandler.cc b/xml/src/UserRecordsXmlHandler.cc index 3234cb59..7d198c97 100644 --- a/xml/src/UserRecordsXmlHandler.cc +++ b/xml/src/UserRecordsXmlHandler.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/xml/src/UserRecordsXmlWriter.cc b/xml/src/UserRecordsXmlWriter.cc index 519078af..2cca4e2b 100644 --- a/xml/src/UserRecordsXmlWriter.cc +++ b/xml/src/UserRecordsXmlWriter.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/xml/src/XmlHandler.cc b/xml/src/XmlHandler.cc index d0286a80..7db71a9b 100644 --- a/xml/src/XmlHandler.cc +++ b/xml/src/XmlHandler.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- diff --git a/xml/src/XmlStream.cc b/xml/src/XmlStream.cc index b8955902..aafb796f 100644 --- a/xml/src/XmlStream.cc +++ b/xml/src/XmlStream.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-2016 Martin Erdmann - // RWTH Aachen, Germany - // Licensed under a LGPL-2 or later license - //------------------------------------------- -- GitLab From 47be70989b45f88e49323181eeb643924d521d92 Mon Sep 17 00:00:00 2001 From: Marcel Rieger Date: Mon, 29 Aug 2016 14:42:44 +0200 Subject: [PATCH 006/130] Apply clang formatter with WebKit style. --- algorithms/include/pxl/algorithms.hh | 5 +- .../include/pxl/algorithms/AutoLayout.hh | 425 +- algorithms/src/AutoLayout.cc | 1641 ++-- core/include/pxl/core.hh | 46 +- core/include/pxl/core/ChunkReader.hh | 311 +- core/include/pxl/core/ChunkWriter.hh | 135 +- core/include/pxl/core/ConfigLoader.hh | 11 +- core/include/pxl/core/Configuration.hh | 51 +- core/include/pxl/core/Core.hh | 11 +- core/include/pxl/core/Event.hh | 290 +- core/include/pxl/core/File.hh | 101 +- core/include/pxl/core/FileFactory.hh | 57 +- core/include/pxl/core/Filter.hh | 87 +- core/include/pxl/core/GenericInputHandler.hh | 57 +- core/include/pxl/core/GenericOutputHandler.hh | 60 +- core/include/pxl/core/Id.hh | 92 +- core/include/pxl/core/InformationChunk.hh | 61 +- core/include/pxl/core/InputFile.hh | 149 +- core/include/pxl/core/InputHandler.hh | 328 +- core/include/pxl/core/LorentzVector.hh | 499 +- core/include/pxl/core/MessageDispatcher.hh | 54 +- core/include/pxl/core/NamedTMPFile.hh | 22 +- core/include/pxl/core/Object.hh | 160 +- core/include/pxl/core/ObjectFactory.hh | 53 +- core/include/pxl/core/ObjectManager.hh | 346 +- core/include/pxl/core/ObjectOwner.hh | 563 +- core/include/pxl/core/OutputFile.hh | 40 +- core/include/pxl/core/OutputHandler.hh | 221 +- core/include/pxl/core/PluginManager.hh | 60 +- core/include/pxl/core/Random.hh | 218 +- .../include/pxl/core/RandomAccessInputFile.hh | 211 +- core/include/pxl/core/Relations.hh | 186 +- core/include/pxl/core/Relative.hh | 430 +- core/include/pxl/core/RotationMatrix.hh | 51 +- core/include/pxl/core/Serializable.hh | 161 +- core/include/pxl/core/SoftRelations.hh | 496 +- core/include/pxl/core/Stream.hh | 634 +- core/include/pxl/core/Tokenizer.hh | 38 +- core/include/pxl/core/UserRecord.hh | 507 +- core/include/pxl/core/Variant.hh | 552 +- core/include/pxl/core/Vector3.hh | 382 +- core/include/pxl/core/WkPtrBase.hh | 120 +- core/include/pxl/core/functions.hh | 65 +- core/include/pxl/core/logging.hh | 384 +- core/include/pxl/core/macros.hh | 26 +- core/include/pxl/core/weak_ptr.hh | 196 +- core/src/ChunkReader.cc | 530 +- core/src/ChunkWriter.cc | 213 +- core/src/ConfigLoader.cc | 129 +- core/src/Configuration.cc | 40 +- core/src/Core.cc | 59 +- core/src/Event.cc | 46 +- core/src/File.cc | 137 +- core/src/FileFactory.cc | 53 +- core/src/Id.cc | 341 +- core/src/InformationChunk.cc | 13 +- core/src/InputHandler.cc | 420 +- core/src/LocalFileImpl.cc | 163 +- core/src/LocalFileImpl.hh | 54 +- core/src/LorentzVector.cc | 64 +- core/src/MessageDispatcher.cc | 150 +- core/src/NamedTMPFile.cc | 62 +- core/src/Object.cc | 40 +- core/src/ObjectFactory.cc | 51 +- core/src/ObjectManager.cc | 2 - core/src/ObjectOwner.cc | 570 +- core/src/OutputFile.cc | 50 +- core/src/OutputHandler.cc | 71 +- core/src/PluginManager.cc | 618 +- core/src/Random.cc | 523 +- core/src/Relations.cc | 15 +- core/src/Relative.cc | 196 +- core/src/SafeInt.hh | 4953 +++++------ core/src/SoftRelations.cc | 385 +- core/src/StdFileImpl.cc | 141 +- core/src/StdFileImpl.hh | 52 +- core/src/Tokenizer.cc | 170 +- core/src/UserRecord.cc | 514 +- core/src/Variant.cc | 2173 ++--- core/src/Vector3.cc | 278 +- core/src/WkPtrBase.cc | 68 +- core/src/dCapFileImpl.cc | 129 +- core/src/dCapFileImpl.hh | 52 +- core/src/functions.cc | 334 +- core/src/logging.cc | 404 +- core/src/sFTPFileImpl.cc | 766 +- core/src/sFTPFileImpl.hh | 70 +- examples/pxl_GSLBLAS_example.cc | 53 +- examples/pxlexample.cc | 1789 ++-- hep/include/pxl/hep.hh | 10 +- hep/include/pxl/hep/AnalysisFork.hh | 181 +- hep/include/pxl/hep/AnalysisProcess.hh | 175 +- hep/include/pxl/hep/Collision.hh | 88 +- hep/include/pxl/hep/CommonParticle.hh | 133 +- hep/include/pxl/hep/CommonVertex.hh | 34 +- hep/include/pxl/hep/EventView.hh | 111 +- hep/include/pxl/hep/Hep.hh | 11 +- hep/include/pxl/hep/Particle.hh | 456 +- hep/include/pxl/hep/ParticleFilter.hh | 98 +- hep/include/pxl/hep/Vertex.hh | 254 +- hep/src/AnalysisFork.cc | 97 +- hep/src/AnalysisProcess.cc | 27 +- hep/src/Collision.cc | 3 +- hep/src/EventView.cc | 15 +- hep/src/Hep.cc | 39 +- hep/src/Particle.cc | 75 +- hep/src/Vertex.cc | 18 +- lib/gtest/src/gtest-all.cc | 2 +- lib/gtest/src/gtest-death-test.cc | 2345 +++-- lib/gtest/src/gtest-filepath.cc | 595 +- lib/gtest/src/gtest-port.cc | 1433 +-- lib/gtest/src/gtest-printers.cc | 563 +- lib/gtest/src/gtest-test-part.cc | 83 +- lib/gtest/src/gtest-typed-test.cc | 119 +- lib/gtest/src/gtest.cc | 7757 ++++++++--------- lib/gtest/src/gtest_main.cc | 9 +- modules/include/pxl/modules.hh | 6 +- modules/include/pxl/modules/Analysis.hh | 151 +- modules/include/pxl/modules/InputModule.hh | 47 +- modules/include/pxl/modules/Module.hh | 355 +- modules/include/pxl/modules/ModuleFactory.hh | 63 +- modules/include/pxl/modules/Modules.hh | 11 +- modules/include/pxl/modules/OutputModule.hh | 48 +- .../include/pxl/modules/PyAnalyseModule.hh | 13 +- modules/include/pxl/modules/PyDecideModule.hh | 13 +- .../include/pxl/modules/PyGeneratorModule.hh | 31 +- modules/include/pxl/modules/PyModule.hh | 60 +- modules/include/pxl/modules/PyModuleModule.hh | 16 +- modules/include/pxl/modules/PySwitchModule.hh | 16 +- .../include/pxl/modules/SubscriberModule.hh | 42 +- modules/src/Analysis.cc | 727 +- modules/src/InputModule.cc | 246 +- modules/src/Module.cc | 634 +- modules/src/ModuleFactory.cc | 91 +- modules/src/Modules.cc | 43 +- modules/src/OutputModule.cc | 203 +- modules/src/PyAnalyseModule.cc | 109 +- modules/src/PyDecideModule.cc | 125 +- modules/src/PyGeneratorModule.cc | 141 +- modules/src/PyModule.cc | 443 +- modules/src/PyModuleModule.cc | 131 +- modules/src/PySwitchModule.cc | 101 +- modules/src/SubscriberModule.cc | 277 +- pxlrun/src/main.cc | 551 +- scripting/include/pxl/scripting.hh | 2 +- .../pxl/scripting/DefaultScriptFilter.hh | 31 +- .../pxl/scripting/EventViewScriptFilter.hh | 14 +- .../pxl/scripting/ParticleScriptFilter.hh | 14 +- scripting/include/pxl/scripting/Script.hh | 75 +- scripting/src/DefaultScriptFilter.cc | 69 +- scripting/src/EventViewScriptFilter.cc | 41 +- scripting/src/ParticleScriptFilter.cc | 46 +- scripting/src/Script.cc | 666 +- test/HepTest.cc | 2028 ++--- test/core_tests/SerializableTests.hh | 52 +- test/moduletest.cc | 106 +- test/test_core.cc | 1032 ++- test/test_healpix.cc | 222 +- test/test_hep.cc | 43 +- test/test_modules.cc | 699 +- test/test_scripting.cc | 39 +- test/test_share.hh | 26 +- test/test_xml.cc | 123 +- xml/include/pxl/xml.hh | 4 +- xml/include/pxl/xml/AnalysisXmlExport.hh | 36 +- xml/include/pxl/xml/AnalysisXmlImport.hh | 42 +- xml/include/pxl/xml/AnalysisXmlWriter.hh | 10 +- xml/include/pxl/xml/ModuleXmlHandler.hh | 133 +- xml/include/pxl/xml/UserRecordsXmlHandler.hh | 62 +- xml/include/pxl/xml/UserRecordsXmlWriter.hh | 12 +- xml/include/pxl/xml/XmlHandler.hh | 51 +- xml/include/pxl/xml/XmlStream.hh | 64 +- xml/src/AnalysisXmlExport.cc | 109 +- xml/src/AnalysisXmlImport.cc | 506 +- xml/src/AnalysisXmlWriter.cc | 287 +- xml/src/ModuleXmlHandler.cc | 215 +- xml/src/UserRecordsXmlHandler.cc | 59 +- xml/src/UserRecordsXmlWriter.cc | 45 +- xml/src/XmlHandler.cc | 156 +- xml/src/XmlStream.cc | 107 +- 180 files changed, 25173 insertions(+), 29012 deletions(-) mode change 100755 => 100644 xml/include/pxl/xml/AnalysisXmlExport.hh mode change 100755 => 100644 xml/src/AnalysisXmlExport.cc diff --git a/algorithms/include/pxl/algorithms.hh b/algorithms/include/pxl/algorithms.hh index 77d44d09..41c128e2 100644 --- a/algorithms/include/pxl/algorithms.hh +++ b/algorithms/include/pxl/algorithms.hh @@ -6,10 +6,9 @@ // Licensed under a LGPL-2 or later license - //------------------------------------------- -#ifndef PXL_ALGORITHMS_HH -#define PXL_ALGORITHMS_HH +#ifndef PXL_ALGORITHMS_HH +#define PXL_ALGORITHMS_HH #include "pxl/algorithms/AutoLayout.hh" #endif // PXL_ALGORITHMS_HH - diff --git a/algorithms/include/pxl/algorithms/AutoLayout.hh b/algorithms/include/pxl/algorithms/AutoLayout.hh index c8048982..8dd8b9dd 100644 --- a/algorithms/include/pxl/algorithms/AutoLayout.hh +++ b/algorithms/include/pxl/algorithms/AutoLayout.hh @@ -9,263 +9,236 @@ #ifndef PXL_ALGORITHMS_AUTOLAYOUT_HH #define PXL_ALGORITHMS_AUTOLAYOUT_HH -#include #include -#include #include +#include +#include #include "pxl/core/macros.hh" namespace pxl { -class PXL_DLL_EXPORT Vector2 -{ +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); + 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 -{ +class PXL_DLL_EXPORT Line { public: - Vector2 a, b; - - Line() - { + Vector2 a, b; - } + Line() {} - Line(const Vector2& v1, const Vector2& v2) : - a(v1), b(v2) - { + Line(const Vector2& v1, const Vector2& v2) + : a(v1) + , b(v2) + { + } - } - - bool intersection(const Line& line, Vector2& intersection); + bool intersection(const Line& line, Vector2& intersection); }; - -class PXL_DLL_EXPORT Rect2 -{ +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; + Vector2 ll; + Vector2 ur; + + Rect2() + : ll(std::numeric_limits::max(), + std::numeric_limits::max()) + , ur(std::numeric_limits::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; + std::vector view; };*/ -class PXL_DLL_EXPORT Node -{ +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; - + 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; +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(); + 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 diff --git a/algorithms/src/AutoLayout.cc b/algorithms/src/AutoLayout.cc index 7932d1cc..9f1951f3 100644 --- a/algorithms/src/AutoLayout.cc +++ b/algorithms/src/AutoLayout.cc @@ -12,210 +12,203 @@ namespace pxl { -bool Vector2::parallelTo(const Vector2 &b) +bool Vector2::parallelTo(const Vector2& b) { - if (x == 0) - { - if (b.x == 0) - return true; - else - return false; - } + if (x == 0) { + if (b.x == 0) + return true; + else + return false; + } - if (b.x == 0) - return false; + if (b.x == 0) + return false; - if (y / x == b.y / b.x) - return true; + if (y / x == b.y / b.x) + return true; - return false; + 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; + 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 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; + double t1 = (s.x + t2 * r2.x) / r1.x; - intersection = line.a + r2 * t2; + intersection = line.a + r2 * t2; - if ((t1 > 0.0001) && (t1 < 0.999) && (t2 > 0.0001) && (t2 < 0.999)) - return true; - else - return false; + 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); + 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); + 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 < (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; + if (point.x > (ur.x + margin)) + return false; + if (point.y > (ur.y + margin)) + return false; - return true; + return true; } bool Rect2::overlaps(const Rect2& rhs) const { - if (ur.x < rhs.ll.x) - return false; + if (ur.x < rhs.ll.x) + return false; - if (ur.y < rhs.ll.y) - return false; + if (ur.y < rhs.ll.y) + return false; - if (ll.x > rhs.ur.x) - return false; + if (ll.x > rhs.ur.x) + return false; - if (ll.y > rhs.ur.y) - return false; + if (ll.y > rhs.ur.y) + return false; - return true; + return true; } - -Node::Node() : mass(10.0) +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.) +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 */ +/* 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; - */ + file >> _friction; + file >> _spring; + file >> _proximity; + file >> _gravity; + file >> _mass; + file >> _overlap; + file >> _steps; + file >> _levels; + file >>grid; + file >>margin; + */ #endif } -AutoLayout::~AutoLayout() -{ -} +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(); + 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; + if (updated) + return; - rect = Rect2(position); + rect = Rect2(position); - std::vector::iterator i; - for (i = children.begin(); i != children.end(); i++) - { - if ((*i)->active == false) - continue; + std::vector::iterator i; + for (i = children.begin(); i != children.end(); i++) { + if ((*i)->active == false) + continue; - (*i)->updateRect(); - rect.expand((*i)->rect); - } + (*i)->updateRect(); + rect.expand((*i)->rect); + } - updated = true; + 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(); + 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) +bool Node::isMotherOf(Node* node) { - std::vector::iterator i; + std::vector::iterator i; - for (i = children.begin(); i != children.end(); i++) - { - if (*i == node) - return true; - } + for (i = children.begin(); i != children.end(); i++) { + if (*i == node) + return true; + } - return false; + return false; } -bool Node::isDaughterOf(Node *node) +bool Node::isDaughterOf(Node* node) { - std::vector::iterator i; + std::vector::iterator i; - for (i = mothers.begin(); i != mothers.end(); i++) - { - if (*i == node) - return true; - } + for (i = mothers.begin(); i != mothers.end(); i++) { + if (*i == node) + return true; + } - return false; + return false; } void AutoLayout::applyGravity() { - std::vector::iterator i; - for (i = allNodes.begin(); i != allNodes.end(); i++) - { - (*i)->force.x += _gravity; - } + std::vector::iterator i; + for (i = allNodes.begin(); i != allNodes.end(); i++) { + (*i)->force.x += _gravity; + } } /* void AutoLayout::applyProximityForces(Node* a, Node* b) @@ -231,875 +224,785 @@ void AutoLayout::applyGravity() 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; - } + 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; - } + 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); - } - } + 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) +void AutoLayout::applySpringForce(Node* a, Node* b, double length) { - Vector2 r = b->position - a->position; - double distance = r.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(); + Vector2 direction; + if (distance == 0.0) + direction = Vector2(1.0, 0.0); + else + direction = r.normalized(); - double force = _spring * (distance - (length/2.0)); + double force = _spring * (distance - (length / 2.0)); - a->force.y += (direction * force).y; - b->force -= direction * force; + 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; + 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; - } + 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; - } + 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); - } + 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::resolveOverlap(Node *a1, Node *b1, Node *a2, Node *b2) +void AutoLayout::resolveOverlaps() { - Line a(a1->position, b1->position); - Line b(a2->position, b2->position); + std::vector::iterator i; + for (i = allNodes.begin(); i != allNodes.end(); i++) { + Node* a = *i; + if (a->active == false) + continue; - 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; - } -} + std::vector::iterator j; + for (j = a->children.begin(); j != a->children.end(); j++) { + Node* b = *j; -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); - } - } - } - } + 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; - } - } - } + 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; + 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; - } + 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; + 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); -*/ + 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(); + return object1->children.size() > object2->children.size(); } bool cmp2(Node* object1, Node* object2) { - return object1->numberchildren > object2->numberchildren; + 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 g = grid * 0.9; //* 0.5*object->children.size(); + double y = g / 2.0; + int n = 0; - double step = g / (object->children.size()-1); + size_t d; - std::vector::iterator j; - std::vector::iterator l; - std::vector v; - std::vector w; - std::vector a; - std::vector b; + double step = g / (object->children.size() - 1); - for (j = object->children.begin(); j != object->children.end(); j++) - { - v.push_back(*j); - } + 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); + 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 != 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(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; - 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; + 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; + 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); - } - } + 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) +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--; -} + // create vector if not present yet + if (nodeGrid.size() <= depth) { + nodeGrid.push_back(std::vector()); + } -/// 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; - } + // fill current node (if not present yet) - for (unsigned int n = 0 ; n != 1; n++) - { - for (std::vector::iterator i = allNodes.begin(); i != allNodes.end(); i++) - { - (*i)->active = true; - } + if (std::find(nodeGrid[depth].begin(), nodeGrid[depth].end(), node) == nodeGrid[depth].end()) + nodeGrid[depth].push_back(node); - std::sort( allNodes.begin(), allNodes.end(), cmp2); + depth++; + // loop over daughters and fill those + for (std::vector::iterator child = node->children.begin(); child != node->children.end(); + ++child) { + fillNodeGrid(nodeGrid, *child, depth); + } - layoutChildren(allNodes[0+n], 1.0); - } -*/ + depth--; } -void AutoLayout::drawbox() +/// 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; - } - } - + 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; + // int n = 1, m = 1; + std::vector v; - for (i = allNodes.begin(); i != allNodes.end(); i++) - { - //v.push_back(*i); - countChildren(*i); + std::vector::iterator i; - } - for (i = allNodes.begin(); i != allNodes.end(); i++) - { - //Node* node2 = *i; - //v.push_back(*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; - 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(); - const double step = g / node->children.size(); + if (node->children.size() == 0) + y = 0.0; - if (node->children.size() == 0) - y = 0.0; + std::vector::iterator j; - 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; - for (j = node->children.begin(); j != node->children.end(); j++) - { - y += step; - Node* child = *j; + v.push_back(*j); - if (child->active == false) - { - child->active = true; + /* + if (child->numberchildren > 3) + { - v.push_back(*j); - - - /* - if (child->numberchildren > 3) - { - - child->position = node->position + Vector2(grid, (50/m)*y*pow(-1,n)); - n++; - m++; + 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); - + } + 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); + } - } - - activeNodes.clear(); - for (i = allNodes.begin(); i != allNodes.end(); i++) - { - - - if ((*i)->active) - activeNodes.push_back(*i); - } - - - _levels --; + _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(); - } - } - + 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(); - } - + 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; - } - } + 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; + } + } } */ diff --git a/core/include/pxl/core.hh b/core/include/pxl/core.hh index 2a100550..55fc02b5 100644 --- a/core/include/pxl/core.hh +++ b/core/include/pxl/core.hh @@ -9,45 +9,45 @@ #ifndef PXL_CORE_HH #define PXL_CORE_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/ChunkReader.hh" +#include "pxl/core/ChunkWriter.hh" +#include "pxl/core/Configuration.hh" +#include "pxl/core/Core.hh" #include "pxl/core/Event.hh" #include "pxl/core/File.hh" #include "pxl/core/Filter.hh" -#include "pxl/core/functions.hh" +#include "pxl/core/GenericInputHandler.hh" +#include "pxl/core/GenericOutputHandler.hh" #include "pxl/core/Id.hh" #include "pxl/core/InformationChunk.hh" -#include "pxl/core/logging.hh" +#include "pxl/core/InputFile.hh" +#include "pxl/core/InputHandler.hh" +#include "pxl/core/LorentzVector.hh" #include "pxl/core/MessageDispatcher.hh" -#include "pxl/core/macros.hh" -#include "pxl/core/Random.hh" +#include "pxl/core/NamedTMPFile.hh" #include "pxl/core/Object.hh" +#include "pxl/core/ObjectFactory.hh" #include "pxl/core/ObjectManager.hh" #include "pxl/core/ObjectOwner.hh" +#include "pxl/core/OutputFile.hh" +#include "pxl/core/OutputHandler.hh" +#include "pxl/core/PluginManager.hh" +#include "pxl/core/Random.hh" #include "pxl/core/Relations.hh" #include "pxl/core/Relative.hh" +#include "pxl/core/RotationMatrix.hh" +#include "pxl/core/Serializable.hh" #include "pxl/core/SoftRelations.hh" +#include "pxl/core/Stream.hh" +#include "pxl/core/Tokenizer.hh" #include "pxl/core/UserRecord.hh" #include "pxl/core/Variant.hh" #include "pxl/core/Vector3.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/Stream.hh" -#include "pxl/core/Tokenizer.hh" -#include "pxl/core/NamedTMPFile.hh" +#include "pxl/core/functions.hh" +#include "pxl/core/logging.hh" +#include "pxl/core/macros.hh" +#include "pxl/core/weak_ptr.hh" #endif // PXL_BASE_HH diff --git a/core/include/pxl/core/ChunkReader.hh b/core/include/pxl/core/ChunkReader.hh index 477651c0..0fbd8384 100644 --- a/core/include/pxl/core/ChunkReader.hh +++ b/core/include/pxl/core/ChunkReader.hh @@ -14,209 +14,154 @@ #include #include -#include "pxl/core/Stream.hh" #include "pxl/core/File.hh" +#include "pxl/core/Stream.hh" #define iotl__iStreamer__lengthUnzipBuffer 65536 -namespace pxl -{ +namespace pxl { -namespace skipSpace -{ - -enum skipMode -{ - off = 0, - on -}; +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. +/// 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 -{ +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; - } + /// 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) ; + /// 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; - } + /// 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; + 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 +} // namespace pxl #endif // PXL_IO_CHUNK_READER_HH diff --git a/core/include/pxl/core/ChunkWriter.hh b/core/include/pxl/core/ChunkWriter.hh index e3673d0c..26581c4a 100644 --- a/core/include/pxl/core/ChunkWriter.hh +++ b/core/include/pxl/core/ChunkWriter.hh @@ -11,95 +11,84 @@ #include "pxl/core/macros.hh" #include -#include #include #include +#include -#include "pxl/core/Stream.hh" #include "pxl/core/File.hh" +#include "pxl/core/Stream.hh" -namespace pxl -{ +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 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. + The entry point for the standard user is the class OutputFile. */ -class PXL_DLL_EXPORT ChunkWriter -{ +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"); - } - + 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); - + /// 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; + 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 fa7ecc0c..19f809e3 100644 --- a/core/include/pxl/core/ConfigLoader.hh +++ b/core/include/pxl/core/ConfigLoader.hh @@ -1,4 +1,4 @@ - //------------------------------------------- +//------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - // Copyright (C) 2006-2016 Martin Erdmann - @@ -9,20 +9,17 @@ #ifndef PXL_CORE_CONFIGLOADER #define PXL_CORE_CONFIGLOADER - #include "pxl/core/macros.hh" #include "simpleini/SimpleIni.h" -namespace pxl -{ +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 -#endif //PXL_CORE_CONFIGLOADER +#endif // PXL_CORE_CONFIGLOADER diff --git a/core/include/pxl/core/Configuration.hh b/core/include/pxl/core/Configuration.hh index f9947764..6f7d4b9a 100644 --- a/core/include/pxl/core/Configuration.hh +++ b/core/include/pxl/core/Configuration.hh @@ -1,4 +1,4 @@ - //------------------------------------------- +//------------------------------------------- // Project: Physics eXtension Library (PXL) - // http://vispa.physik.rwth-aachen.de/ - // Copyright (C) 2006-2016 Martin Erdmann - @@ -15,42 +15,37 @@ #include "pxl/core/Variant.hh" #include "pxl/core/macros.hh" +namespace pxl { -namespace pxl -{ +class PXL_DLL_EXPORT Configuration { +private: + std::map > _data; -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; + Configuration(){ - typedef std::multimap multimapType; - typedef multimapType::const_iterator multiMapConstIterator; - typedef multimapType::iterator multimapIterator; + }; - 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); }; } // namespace -#endif //PXL_CORE_CONFIGURATION +#endif // PXL_CORE_CONFIGURATION diff --git a/core/include/pxl/core/Core.hh b/core/include/pxl/core/Core.hh index 93949e35..3a50d003 100644 --- a/core/include/pxl/core/Core.hh +++ b/core/include/pxl/core/Core.hh @@ -11,16 +11,13 @@ #include "pxl/core/macros.hh" -namespace pxl -{ +namespace pxl { -class PXL_DLL_EXPORT Core -{ +class PXL_DLL_EXPORT Core { public: - static void initialize(); - static void shutdown(); + static void initialize(); + static void shutdown(); }; - } #endif /* INITIALIZE_HH_ */ diff --git a/core/include/pxl/core/Event.hh b/core/include/pxl/core/Event.hh index 2096668e..f06c5092 100644 --- a/core/include/pxl/core/Event.hh +++ b/core/include/pxl/core/Event.hh @@ -12,176 +12,140 @@ #include +#include "pxl/core/ObjectFactory.hh" #include "pxl/core/ObjectOwner.hh" -#include "pxl/core/UserRecord.hh" #include "pxl/core/Serializable.hh" -#include "pxl/core/ObjectFactory.hh" +#include "pxl/core/UserRecord.hh" -namespace pxl -{ +namespace pxl { -class PXL_DLL_EXPORT Event: public Serializable, public UserRecordHelper -{ +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; + 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& 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; + ObjectOwner _objects; }; } // namespace pxl diff --git a/core/include/pxl/core/File.hh b/core/include/pxl/core/File.hh index 1cf65f58..24f58f18 100644 --- a/core/include/pxl/core/File.hh +++ b/core/include/pxl/core/File.hh @@ -9,80 +9,67 @@ #ifndef PXL_FILE_HH_ #define PXL_FILE_HH_ -#include "pxl/core/macros.hh" #include "pxl/core/functions.hh" +#include "pxl/core/macros.hh" -#include -#include #include +#include +#include -namespace pxl -{ +namespace pxl { -enum SeekDirectionEnum -{ - SeekBegin, SeekCurrent, SeekEnd -}; +enum SeekDirectionEnum { SeekBegin, SeekCurrent, SeekEnd }; -enum OpenModeEnum -{ - OpenRead = 1, OpenWrite = 2, OpenOverwrite = 4 -}; +enum OpenModeEnum { OpenRead = 1, OpenWrite = 2, OpenOverwrite = 4 }; -class PXL_DLL_EXPORT FileImpl -{ +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; + 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: +class PXL_DLL_EXPORT File : public FileImpl { + FileImpl* impl; - File(); +public: + File(); - File(const std::string &filename, int32_t mode = OpenRead); - ~File(); + File(const std::string& filename, int32_t mode = OpenRead); + ~File(); - virtual bool open(const std::string &filename, int32_t mode = OpenRead); + virtual bool open(const std::string& filename, int32_t mode = OpenRead); - virtual void close(); + virtual void close(); - virtual bool isEof(); + 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(); + 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 index db2f5ded..2481ee40 100644 --- a/core/include/pxl/core/FileFactory.hh +++ b/core/include/pxl/core/FileFactory.hh @@ -12,64 +12,47 @@ #include -#include "pxl/core/Id.hh" #include "pxl/core/File.hh" +#include "pxl/core/Id.hh" -namespace pxl -{ +namespace pxl { class FileProducerInterface; -class PXL_DLL_EXPORT FileFactory -{ +class PXL_DLL_EXPORT FileFactory { private: + FileFactory(); - FileFactory(); - - std::map _Producers; + std::map _Producers; public: + static FileFactory& instance(); - static FileFactory& instance(); + FileImpl* create(const std::string& id); - FileImpl *create(const std::string& id); + void registerProducer(const std::string& id, const FileProducerInterface* producer); + void unregisterProducer(const FileProducerInterface* producer); - void registerProducer(const std::string& id, - const FileProducerInterface* producer); - void unregisterProducer(const FileProducerInterface* producer); - - bool hasSchema(const std::string& schema); + bool hasSchema(const std::string& schema); }; -class FileProducerInterface -{ +class FileProducerInterface { public: - virtual ~FileProducerInterface() - { - } + virtual ~FileProducerInterface() {} - virtual FileImpl *create() const = 0; + virtual FileImpl* create() const = 0; }; -template -class FileProducerTemplate: public FileProducerInterface -{ +template class FileProducerTemplate : public FileProducerInterface { public: + void initialize(const std::string& schema) + { + FileFactory::instance().registerProducer(schema, this); + } - void initialize(const std::string &schema) - { - FileFactory::instance().registerProducer(schema, this); - } - - void shutdown() - { - FileFactory::instance().unregisterProducer(this); - } + void shutdown() { FileFactory::instance().unregisterProducer(this); } - FileImpl *create() const - { - return new T(); - } + FileImpl* create() const { return new T(); } }; } // namespace pxl diff --git a/core/include/pxl/core/Filter.hh b/core/include/pxl/core/Filter.hh index 318aa062..517e4bac 100644 --- a/core/include/pxl/core/Filter.hh +++ b/core/include/pxl/core/Filter.hh @@ -10,84 +10,69 @@ #define PXL_BASE_FILTER_HH #include "pxl/core/macros.hh" -#include #include +#include #include "pxl/core/ObjectOwner.hh" -namespace pxl -{ +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. + \p comparetype. */ -template class ComparatorInterface -{ +template class ComparatorInterface { public: - virtual bool operator()(const comparetype*, const comparetype*) = 0; - virtual ~ComparatorInterface() - { - } + 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. + criterion which can be used in a filter to filter out objects + of type \p comparetype. */ -template class FilterCriterionInterface -{ +template class FilterCriterionInterface { public: - virtual bool operator()(const objecttype&) const = 0; - virtual ~FilterCriterionInterface() - { - } + 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. + 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 -{ +template class Filter { public: - virtual ~Filter() - { - } + 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(); + /// 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; - } + // 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/GenericInputHandler.hh b/core/include/pxl/core/GenericInputHandler.hh index 4ee8508f..6560d354 100644 --- a/core/include/pxl/core/GenericInputHandler.hh +++ b/core/include/pxl/core/GenericInputHandler.hh @@ -12,54 +12,43 @@ #include -#include "pxl/core/InputHandler.hh" #include "pxl/core/ChunkReader.hh" +#include "pxl/core/InputHandler.hh" -namespace pxl -{ +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 -{ +class GenericInputHandler : public InputHandler { public: + GenericInputHandler(ChunkReader& reader) + : InputHandler() + , _reader(&reader) + { + } - GenericInputHandler(ChunkReader& reader) : - InputHandler(), _reader(&reader) - { - } + virtual ~GenericInputHandler() {} - virtual ~GenericInputHandler() - { - } + virtual ChunkReader& getChunkReader() + { + if (!_reader) + throw std::runtime_error( + "GenericInputHandler::getChunkReader(): ChunkReader pointer invalid."); + return *_reader; + } - virtual ChunkReader& getChunkReader() - { - if (!_reader) - throw std::runtime_error("GenericInputHandler::getChunkReader(): ChunkReader pointer invalid."); - return *_reader; - } - - virtual void setChunkReader(ChunkReader* reader) - { - _reader=reader; - } + virtual void setChunkReader(ChunkReader* reader) { _reader = reader; } private: - GenericInputHandler(const GenericInputHandler& original) - { - } - - GenericInputHandler& operator= (const GenericInputHandler& other) - { - return *this; - } - - ChunkReader* _reader; + GenericInputHandler(const GenericInputHandler& original) {} + + GenericInputHandler& operator=(const GenericInputHandler& other) { return *this; } + + ChunkReader* _reader; }; -} //namespace pxl +} // namespace pxl #endif /*PXL_IO_GENERICINPUTHANDLER_HH*/ diff --git a/core/include/pxl/core/GenericOutputHandler.hh b/core/include/pxl/core/GenericOutputHandler.hh index 9723b0ed..c01b1c72 100644 --- a/core/include/pxl/core/GenericOutputHandler.hh +++ b/core/include/pxl/core/GenericOutputHandler.hh @@ -12,56 +12,46 @@ #include -#include "pxl/core/OutputHandler.hh" #include "pxl/core/ChunkWriter.hh" +#include "pxl/core/OutputHandler.hh" -namespace pxl -{ +namespace pxl { // io /** - This class allows the user an easy handling of the PXL output using any ChunkWriter. Methods to write event headers, + 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 -{ +class GenericOutputHandler : public OutputHandler { public: - GenericOutputHandler(ChunkWriter& writer) : - OutputHandler(), _writer(&writer) - { - } + GenericOutputHandler(ChunkWriter& writer) + : OutputHandler() + , _writer(&writer) + { + } - virtual ~GenericOutputHandler() - { - } + virtual ~GenericOutputHandler() {} - virtual ChunkWriter& getChunkWriter() - { - if (!_writer) - throw std::runtime_error("GenericOutputHandler::getChunkWriter(): ChunkWriter pointer invalid."); - return *_writer; - } + virtual ChunkWriter& getChunkWriter() + { + if (!_writer) + throw std::runtime_error( + "GenericOutputHandler::getChunkWriter(): ChunkWriter pointer invalid."); + return *_writer; + } - virtual void setChunkWriter(ChunkWriter* writer) - { - _writer=writer; - } + virtual void setChunkWriter(ChunkWriter* writer) { _writer = writer; } private: - GenericOutputHandler(const GenericOutputHandler& original) - { - } - - GenericOutputHandler& operator= (const GenericOutputHandler& other) - { - return *this; - } - - - ChunkWriter* _writer; + GenericOutputHandler(const GenericOutputHandler& original) {} + + GenericOutputHandler& operator=(const GenericOutputHandler& other) { return *this; } + + ChunkWriter* _writer; }; -}//namespace pxl +} // namespace pxl #endif /*PXL_IO_GENERICOUTPUTHANDLER_HH*/ diff --git a/core/include/pxl/core/Id.hh b/core/include/pxl/core/Id.hh index 4887ba0a..9530bb58 100644 --- a/core/include/pxl/core/Id.hh +++ b/core/include/pxl/core/Id.hh @@ -20,63 +20,61 @@ 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 -{ +class PXL_DLL_EXPORT Id { private: - unsigned char bytes[16]; /// Storage for the actual 16-digit ID. + 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); }; -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 - diff --git a/core/include/pxl/core/InformationChunk.hh b/core/include/pxl/core/InformationChunk.hh index 7b6dd402..09cd7b4a 100644 --- a/core/include/pxl/core/InformationChunk.hh +++ b/core/include/pxl/core/InformationChunk.hh @@ -15,8 +15,7 @@ #include "pxl/core/Serializable.hh" #include "pxl/core/UserRecord.hh" -namespace pxl -{ +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 @@ -24,53 +23,37 @@ namespace pxl 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 -{ +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(); } - /// 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; + } - /// 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; - /// 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); - /// 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); } - /// 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; } - /// 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; - } + /// Get the name of the InformationChunk + inline const std::string& getName() const { return _name; } private: - std::string _name; /// Name of the information chunk. - + std::string _name; /// Name of the information chunk. }; -} //namespace pxl +} // namespace pxl #endif /*PXL_BASE_INFORMATIONCHUNK_HH*/ diff --git a/core/include/pxl/core/InputFile.hh b/core/include/pxl/core/InputFile.hh index 01b6b3fb..1881d406 100644 --- a/core/include/pxl/core/InputFile.hh +++ b/core/include/pxl/core/InputFile.hh @@ -13,107 +13,90 @@ #include #include -#include "pxl/core/InputHandler.hh" #include "pxl/core/ChunkReader.hh" #include "pxl/core/File.hh" +#include "pxl/core/InputHandler.hh" #include "pxl/core/logging.hh" #define PXL_LOG_MODULE_NAME "pxl::InputFile" -namespace pxl -{ +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 -{ +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(); - } + 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; - } + InputFile(const InputFile& original) + : _stream() + , _reader(_stream, ChunkReader::seekable) + { + } - File _stream; - ChunkReader _reader; + InputFile& operator=(const InputFile& other) { return *this; } + File _stream; + ChunkReader _reader; }; -} //namespace pxl +} // namespace pxl #endif /*PXL_IO_INPUTFILE_HH*/ diff --git a/core/include/pxl/core/InputHandler.hh b/core/include/pxl/core/InputHandler.hh index f38433fc..8939f603 100644 --- a/core/include/pxl/core/InputHandler.hh +++ b/core/include/pxl/core/InputHandler.hh @@ -13,14 +13,13 @@ #include #include -#include "pxl/core/ChunkReader.hh" -#include "pxl/core/Id.hh" #include "pxl/core/BasicContainer.hh" +#include "pxl/core/ChunkReader.hh" #include "pxl/core/Event.hh" +#include "pxl/core/Id.hh" #include "pxl/core/InformationChunk.hh" -namespace pxl -{ +namespace pxl { // io /** This abstract class offers the basic functionality for reading the PXL physics event structure. @@ -28,183 +27,156 @@ namespace pxl */ using namespace skipSpace; -class PXL_DLL_EXPORT InputHandler -{ +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(); - } - + 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; - -}; + InputHandler(const InputHandler& original) {} + InputHandler& operator=(const InputHandler& other) { return *this; } + + size_t _objectCount; +}; } -//namespace pxl +// namespace pxl -#endif //PXL_IO_INPUTHANDLER_HH +#endif // PXL_IO_INPUTHANDLER_HH diff --git a/core/include/pxl/core/LorentzVector.hh b/core/include/pxl/core/LorentzVector.hh index 3d693f7e..528ff4f0 100644 --- a/core/include/pxl/core/LorentzVector.hh +++ b/core/include/pxl/core/LorentzVector.hh @@ -15,291 +15,244 @@ #include "pxl/core/Basic3Vector.hh" #include "pxl/core/Stream.hh" -namespace pxl -{ +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 Basic3Vector { 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() + : 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; private: - double _t; - + double _t; }; // 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& obj1, const LorentzVector& obj2); +PXL_DLL_EXPORT bool operator!=(const LorentzVector& obj1, const LorentzVector& obj2); -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& vec); +PXL_DLL_EXPORT LorentzVector operator*(const LorentzVector& vec, const double scalar); } // namespace pxl - #endif // PXL_BASE_LORENTZVECTOR_HH diff --git a/core/include/pxl/core/MessageDispatcher.hh b/core/include/pxl/core/MessageDispatcher.hh index 546cf417..2ea6aced 100644 --- a/core/include/pxl/core/MessageDispatcher.hh +++ b/core/include/pxl/core/MessageDispatcher.hh @@ -9,59 +9,55 @@ #ifndef PXL_CORE_MESASSAGE_DISPATCHER_HH #define PXL_CORE_MESASSAGE_DISPATCHER_HH -#include "pxl/core/macros.hh" #include "pxl/core/Variant.hh" +#include "pxl/core/macros.hh" -#include #include +#include -namespace pxl -{ +namespace pxl { /** React on published messages */ -class PXL_DLL_EXPORT MessageHandler -{ +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; }; /** Allows to exchange messages. */ -class PXL_DLL_EXPORT MessageDispatcher -{ +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 - diff --git a/core/include/pxl/core/NamedTMPFile.hh b/core/include/pxl/core/NamedTMPFile.hh index 5d4ee831..555b39e9 100644 --- a/core/include/pxl/core/NamedTMPFile.hh +++ b/core/include/pxl/core/NamedTMPFile.hh @@ -5,27 +5,23 @@ #include #ifdef WIN32 - #include +#include #else - #include +#include #endif -namespace pxl -{ +namespace pxl { // holds a tempfile and clears it up on destruction -class PXL_DLL_EXPORT NamedTMPFile -{ +class PXL_DLL_EXPORT NamedTMPFile { public: - - NamedTMPFile(); - ~NamedTMPFile(); - const std::string& getName(); + NamedTMPFile(); + ~NamedTMPFile(); + const std::string& getName(); private: - std::string _filename; + std::string _filename; }; } // namespace - -#endif //NAMED_TMP_FILE_HH +#endif // NAMED_TMP_FILE_HH diff --git a/core/include/pxl/core/Object.hh b/core/include/pxl/core/Object.hh index 64f8a242..a281e138 100644 --- a/core/include/pxl/core/Object.hh +++ b/core/include/pxl/core/Object.hh @@ -10,17 +10,16 @@ #define PXL_BASE_OBJECT_HH #include "pxl/core/macros.hh" -#include #include #include +#include +#include "pxl/core/ObjectFactory.hh" #include "pxl/core/Relative.hh" -#include "pxl/core/weak_ptr.hh" #include "pxl/core/UserRecord.hh" -#include "pxl/core/ObjectFactory.hh" +#include "pxl/core/weak_ptr.hh" -namespace pxl -{ +namespace pxl { /** This class provides common functionalities of PXL physics objects like @@ -29,97 +28,76 @@ namespace pxl 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 -{ +class PXL_DLL_EXPORT Object : public Relative, public UserRecordHelper { 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() + : 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); } private: - bool _locked; - int _workflag; + bool _locked; + int _workflag; - Object& operator=(const Object& original) - { - return *this; - } + Object& operator=(const Object& original) { return *this; } }; - } // namespace pxl diff --git a/core/include/pxl/core/ObjectFactory.hh b/core/include/pxl/core/ObjectFactory.hh index ab013fbe..b24734d3 100644 --- a/core/include/pxl/core/ObjectFactory.hh +++ b/core/include/pxl/core/ObjectFactory.hh @@ -12,8 +12,8 @@ #include -#include "pxl/core/Serializable.hh" #include "pxl/core/Id.hh" +#include "pxl/core/Serializable.hh" // io /** @@ -21,60 +21,39 @@ the relation of classes to UUIDs. */ -namespace pxl -{ +namespace pxl { class ObjectProducerInterface; -class PXL_DLL_EXPORT ObjectFactory -{ +class PXL_DLL_EXPORT ObjectFactory { private: + ObjectFactory(); - ObjectFactory(); - - std::map _Producers; + std::map _Producers; public: + static ObjectFactory& instance(); - static ObjectFactory& instance(); + Serializable* create(const Id& id); - Serializable *create(const Id& id); - - void - registerProducer(const Id& id, - const ObjectProducerInterface* producer); - void unregisterProducer(const ObjectProducerInterface* producer); + void registerProducer(const Id& id, const ObjectProducerInterface* producer); + void unregisterProducer(const ObjectProducerInterface* producer); }; -class ObjectProducerInterface -{ +class ObjectProducerInterface { public: - virtual ~ObjectProducerInterface() - { - } + virtual ~ObjectProducerInterface() {} - virtual Serializable *create() const = 0; + virtual Serializable* create() const = 0; }; -template -class ObjectProducerTemplate: public ObjectProducerInterface -{ +template class ObjectProducerTemplate : public ObjectProducerInterface { public: + void initialize() { ObjectFactory::instance().registerProducer(T::getStaticTypeId(), this); } - void initialize() - { - ObjectFactory::instance().registerProducer(T::getStaticTypeId(), this); - } - - void shutdown() - { - ObjectFactory::instance().unregisterProducer(this); - } + void shutdown() { ObjectFactory::instance().unregisterProducer(this); } - virtual Serializable *create() const - { - return new T(); - } + virtual Serializable* create() const { return new T(); } }; } // namespace pxl diff --git a/core/include/pxl/core/ObjectManager.hh b/core/include/pxl/core/ObjectManager.hh index f6b206eb..653d3374 100644 --- a/core/include/pxl/core/ObjectManager.hh +++ b/core/include/pxl/core/ObjectManager.hh @@ -16,213 +16,171 @@ #include "pxl/core/ObjectOwner.hh" #include "pxl/core/weak_ptr.hh" - -namespace pxl -{ +namespace pxl { // pol /** - This class the functionality of the pxl::BasicObjectData class by providing an object owner (see pxl::ObjectOwner) and + 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 + 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 -{ +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); - } + 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; + ObjectOwner _objects; - ObjectManager& operator=(const ObjectManager& original) - { - return *this; - } + 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 239b260c..895f18c3 100644 --- a/core/include/pxl/core/ObjectOwner.hh +++ b/core/include/pxl/core/ObjectOwner.hh @@ -10,15 +10,14 @@ #define PXL_BASE_OBJECT_OWNER #include "pxl/core/macros.hh" -#include -#include #include +#include +#include #include "pxl/core/Relative.hh" #include "pxl/core/weak_ptr.hh" -namespace pxl -{ +namespace pxl { class ObjectOwner; @@ -28,34 +27,33 @@ class ObjectOwner; /// 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; +template class ObjectOwnerTypeIterator { + typedef std::vector::const_iterator const_iterator; + typedef std::vector::iterator iterator; public: - /// Copy constructor. - ObjectOwnerTypeIterator(const ObjectOwnerTypeIterator& other); + /// Copy constructor. + ObjectOwnerTypeIterator(const ObjectOwnerTypeIterator& other); - /// Constructor from ObjectOwner instance. - ObjectOwnerTypeIterator(const ObjectOwner& container); + /// Constructor from ObjectOwner instance. + ObjectOwnerTypeIterator(const ObjectOwner& container); - /// Constructor from ObjectOwner instance. - ObjectOwnerTypeIterator(const ObjectOwner* container); + /// Constructor from ObjectOwner instance. + ObjectOwnerTypeIterator(const ObjectOwner* container); - const ObjectOwnerTypeIterator operator++(int); + const ObjectOwnerTypeIterator operator++(int); - const ObjectOwnerTypeIterator& operator++(); + const ObjectOwnerTypeIterator& operator++(); - inline objecttype* operator*(); + inline objecttype* operator*(); - inline bool operator==(const_iterator iter); + inline bool operator==(const_iterator iter); - inline bool operator!=(const_iterator iter); + inline bool operator!=(const_iterator iter); private: - const ObjectOwner* _containerRef; - const_iterator _iter; + const ObjectOwner* _containerRef; + const_iterator _iter; }; /** @@ -75,331 +73,298 @@ 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: - 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); - } - + 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); + } private: - void init(const ObjectOwner& original); - - std::vector _container; - std::map _copyHistory; - std::map _index; - std::map _uuidSearchMap; + void init(const ObjectOwner& original); + std::vector _container; + std::map _copyHistory; + std::map _index; + std::map _uuidSearchMap; }; /// Copy constructor. template -ObjectOwnerTypeIterator::ObjectOwnerTypeIterator(const ObjectOwnerTypeIterator& other) : - _containerRef(other._containerRef), _iter(other._iter) +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()) +ObjectOwnerTypeIterator::ObjectOwnerTypeIterator(const ObjectOwner& container) + : _containerRef(&container) + , _iter(container.begin()) { - if ( _iter!=_containerRef->end() && dynamic_cast(*_iter)==0) - (*this)++; + if (_iter != _containerRef->end() && dynamic_cast(*_iter) == 0) + (*this)++; } /// Constructor from ObjectOwner instance. template -ObjectOwnerTypeIterator::ObjectOwnerTypeIterator(const ObjectOwner* container) : -_containerRef(container), _iter(container->begin()) +ObjectOwnerTypeIterator::ObjectOwnerTypeIterator(const ObjectOwner* container) + : _containerRef(container) + , _iter(container->begin()) { - if ( _iter!=_containerRef->end() && dynamic_cast(*_iter)==0) - (*this)++; + 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; + 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; + if (_iter != _containerRef->end()) + do + _iter++; + while (_iter != _containerRef->end() && dynamic_cast(*_iter) == 0); + return *this; } -template -inline objecttype* ObjectOwnerTypeIterator::operator*() +template inline objecttype* ObjectOwnerTypeIterator::operator*() { - return _iter==_containerRef->end() ? 0 - : dynamic_cast(*_iter); + return _iter == _containerRef->end() ? 0 : dynamic_cast(*_iter); } template inline bool ObjectOwnerTypeIterator::operator==(const_iterator iter) { - return (_iter==iter); + return (_iter == iter); } template inline bool ObjectOwnerTypeIterator::operator!=(const_iterator iter) { - return (_iter!=iter); + return (_iter != iter); } - } // namespace pxl #endif // PXL_BASE_OBJECT_OWNER diff --git a/core/include/pxl/core/OutputFile.hh b/core/include/pxl/core/OutputFile.hh index b132c300..9e61ac5c 100644 --- a/core/include/pxl/core/OutputFile.hh +++ b/core/include/pxl/core/OutputFile.hh @@ -12,40 +12,38 @@ #include -#include "pxl/core/OutputHandler.hh" #include "pxl/core/ChunkWriter.hh" +#include "pxl/core/OutputHandler.hh" -namespace pxl -{ +namespace pxl { // io /** - This class allows the user an easy handling of the PXL output to file. Methods to write event headers, + 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 -{ +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); - 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(const OutputFile& original); + + OutputFile& operator=(const OutputFile& other); - OutputFile& operator= (const OutputFile& other); - - File _stream; - ChunkWriter _writer; + File _stream; + ChunkWriter _writer; }; -}//namespace pxl +} // namespace pxl #endif /*PXL_IO_OUTPUTFILE_HH*/ diff --git a/core/include/pxl/core/OutputHandler.hh b/core/include/pxl/core/OutputHandler.hh index 084ddf2a..15602988 100644 --- a/core/include/pxl/core/OutputHandler.hh +++ b/core/include/pxl/core/OutputHandler.hh @@ -12,138 +12,119 @@ #include +#include "pxl/core/BasicContainer.hh" #include "pxl/core/ChunkWriter.hh" -#include "pxl/core/InformationChunk.hh" #include "pxl/core/Event.hh" -#include "pxl/core/BasicContainer.hh" +#include "pxl/core/InformationChunk.hh" -namespace pxl -{ +namespace pxl { // io /** - This abstract class allows the user an easy handling of the PXL general output. Methods to write event headers, + 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 -{ +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; - } - + /// 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; -}; + OutputHandler(const OutputHandler& original) {} + OutputHandler& operator=(const OutputHandler& other) { return *this; } + + size_t _maxSize; + bool _newFileSection; + size_t _maxNObjects; + size_t _nObjects; +}; } -//namespace pxl +// namespace pxl #endif /*PXL_IO_OUTPUTHANDLER_HH*/ diff --git a/core/include/pxl/core/PluginManager.hh b/core/include/pxl/core/PluginManager.hh index e0dca845..a1cd9c86 100644 --- a/core/include/pxl/core/PluginManager.hh +++ b/core/include/pxl/core/PluginManager.hh @@ -10,50 +10,50 @@ #define PXL_CORE_PLUGIN_MANAGER_H #include -#include #include +#include #include "pxl/core/macros.hh" -namespace pxl -{ - -class PXL_DLL_EXPORT PluginManager -{ - void loadSharedLibrary(const std::string &filename); -public: - - PluginManager(); - virtual ~PluginManager(); - void shutdown(); +namespace pxl { - static PluginManager &instance(); - static std::string getUserPluginDirectory(); - static std::string getDefaultPluginDirectory(); +class PXL_DLL_EXPORT PluginManager { + void loadSharedLibrary(const std::string& filename); - void loadPlugin(const std::string &filename); - void loadPluginsFromDirectory(const std::string &name); - void loadPlugins(); - void loadConfiguration(const std::string &filename); +public: + PluginManager(); + virtual ~PluginManager(); + void shutdown(); + + 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); }; } // 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; \ - } \ - } \ +#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 diff --git a/core/include/pxl/core/Random.hh b/core/include/pxl/core/Random.hh index 35cee485..94908ff0 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,141 @@ // 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 -#include "pxl/core/macros.hh" #include "pxl/core/Basic3Vector.hh" +#include "pxl/core/macros.hh" +#include -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 + 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 + // 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 + 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); 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 index bf9c5671..18acc99e 100644 --- a/core/include/pxl/core/RandomAccessInputFile.hh +++ b/core/include/pxl/core/RandomAccessInputFile.hh @@ -14,131 +14,114 @@ #include "pxl/core/InputFile.hh" -namespace pxl -{ +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 -{ +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; + } - 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; - } + { + // 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; + 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 +} // namespace pxl #endif /*PXL_IO_RANDOMACCESSINPUTFILE_HH*/ diff --git a/core/include/pxl/core/Relations.hh b/core/include/pxl/core/Relations.hh index 98e4f1f0..6c9c5b5d 100644 --- a/core/include/pxl/core/Relations.hh +++ b/core/include/pxl/core/Relations.hh @@ -15,128 +15,92 @@ #include "pxl/core/Id.hh" #include "pxl/core/Stream.hh" -namespace pxl -{ +namespace pxl { // We only work with Relative pointers here. The class Relative // containts three instances of the relations. 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 -{ +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::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(); } private: - std::set _relatives; /// Sorted container for the related objects. + std::set _relatives; /// Sorted container for the related objects. }; } // namespace pxl diff --git a/core/include/pxl/core/Relative.hh b/core/include/pxl/core/Relative.hh index a6e07865..0d994314 100644 --- a/core/include/pxl/core/Relative.hh +++ b/core/include/pxl/core/Relative.hh @@ -10,271 +10,219 @@ #define PXL_BASE_RELATIVE_HH #include -#include #include +#include -#include "pxl/core/Serializable.hh" #include "pxl/core/Id.hh" -#include "pxl/core/WkPtrBase.hh" #include "pxl/core/Relations.hh" +#include "pxl/core/Serializable.hh" #include "pxl/core/SoftRelations.hh" +#include "pxl/core/WkPtrBase.hh" -namespace pxl -{ +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 Serializable { 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); + } - /// 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; - } + /// 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; + } 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() + : 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; private: - WkPtrBase* _refWkPtrSpec; /// reference to a weak pointer - ObjectOwner* _refObjectOwner; /// reference to our object owner + 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 + 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 + SoftRelations _softRelations; /// soft relations - std::string _name; /// arbitrary name of this object + std::string _name; /// arbitrary name of this object - friend class WkPtrBase; - friend class ObjectOwner; + friend class WkPtrBase; + 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 diff --git a/core/include/pxl/core/RotationMatrix.hh b/core/include/pxl/core/RotationMatrix.hh index 0cdd7f99..b9e31d7b 100644 --- a/core/include/pxl/core/RotationMatrix.hh +++ b/core/include/pxl/core/RotationMatrix.hh @@ -1,37 +1,38 @@ #include "pxl/core/BasicMatrix.hh" #include -namespace pxl -{ +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 -{ +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; - } - + 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 29eac224..3eb09ae7 100644 --- a/core/include/pxl/core/Serializable.hh +++ b/core/include/pxl/core/Serializable.hh @@ -9,105 +9,96 @@ #ifndef PXL_IO_SERIALIZABLE_HH #define PXL_IO_SERIALIZABLE_HH -#include -#include "pxl/core/Stream.hh" #include "pxl/core/Id.hh" +#include "pxl/core/Stream.hh" #include "pxl/core/macros.hh" +#include -namespace pxl -{ +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 -{ +class PXL_DLL_EXPORT Serializable { public: + /// 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(); + } - /// 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; + /// The unique ID (UUID) of this object. Each object can unambiguously be + /// identified by this ID. + Id _id; }; - } #endif /*PXL_IO_SERIALIZABLE_HH*/ diff --git a/core/include/pxl/core/SoftRelations.hh b/core/include/pxl/core/SoftRelations.hh index e6e842db..be87a02f 100644 --- a/core/include/pxl/core/SoftRelations.hh +++ b/core/include/pxl/core/SoftRelations.hh @@ -10,302 +10,284 @@ #define PXL_BASE_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/Serializable.hh" +#include "pxl/core/Stream.hh" - -namespace pxl -{ +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 -{ +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; + + /// 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(); + } private: - std::multimap _relationsMap; /// Map containing the soft relations (name, UUID) + 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; + // 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; }; - // // Template methods have to be specified in the header! // -template -int SoftRelations::getSoftRelativesOfType(std::vector& vec, - const ObjectOwner& owner, const std::string& name) const +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; + 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 { - 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(); + 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; } -template -int SoftRelations::getSoftRelativesOfType(std::vector& vec, - const BasicContainer& owner, const std::string& name) const +template +int SoftRelations::getSoftRelativesOfType( + std::vector& vec, const BasicContainer& 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; + 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 BasicContainer& owner) const +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; + 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*/ diff --git a/core/include/pxl/core/Stream.hh b/core/include/pxl/core/Stream.hh index c21b6903..a838d261 100644 --- a/core/include/pxl/core/Stream.hh +++ b/core/include/pxl/core/Stream.hh @@ -9,9 +9,9 @@ #ifndef PXL_IO_STREAM_HH #define PXL_IO_STREAM_HH -#include #include #include +#include #include #include @@ -19,18 +19,16 @@ #include "pxl/core/macros.hh" #include -namespace pxl -{ -template -void swap_endianess(T &t) +namespace pxl { +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 } @@ -39,134 +37,121 @@ void swap_endianess(T &t) 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 -{ +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 + 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); + } }; /** @@ -174,181 +159,157 @@ public: 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); } - 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); - } + 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); + } }; /** This abstract class serves the internal PXL I/O scheme by defining how basic C++ types are read from an input buffer. */ -class PXL_DLL_EXPORT InputStream -{ +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; + + 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); + } }; // iotl @@ -356,47 +317,40 @@ public: 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 -{ - mutable size_t _readPosition; +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() + : _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; + } }; - } #endif /*PXL_IO_STREAM_HH*/ diff --git a/core/include/pxl/core/Tokenizer.hh b/core/include/pxl/core/Tokenizer.hh index 50fe44ed..b72320d7 100644 --- a/core/include/pxl/core/Tokenizer.hh +++ b/core/include/pxl/core/Tokenizer.hh @@ -14,38 +14,32 @@ #include #include -namespace pxl -{ +namespace pxl { -class PXL_DLL_EXPORT Tokenizer -{ +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(); + void findToken(); private: - size_t _pos; - std::string _text; - std::string _token; - bool _tokenAvailable; - std::vector _types; + size_t _pos; + std::string _text; + std::string _token; + bool _tokenAvailable; + std::vector _types; }; - } #endif diff --git a/core/include/pxl/core/UserRecord.hh b/core/include/pxl/core/UserRecord.hh index 3063c336..6304da65 100644 --- a/core/include/pxl/core/UserRecord.hh +++ b/core/include/pxl/core/UserRecord.hh @@ -10,315 +10,248 @@ #define PXL_BASE_USERRECORD_HH #include "pxl/core/macros.hh" -#include #include -#include #include +#include +#include -#include "pxl/core/Variant.hh" -#include "pxl/core/Stream.hh" #include "pxl/core/Id.hh" +#include "pxl/core/Stream.hh" +#include "pxl/core/Variant.hh" -namespace pxl -{ +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 -{ +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 + 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(); - } + 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; - } + 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 -{ +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); - } + 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; + UserRecords _userRecords; }; } // namespace pxl diff --git a/core/include/pxl/core/Variant.hh b/core/include/pxl/core/Variant.hh index 35fbe9b3..b4894585 100644 --- a/core/include/pxl/core/Variant.hh +++ b/core/include/pxl/core/Variant.hh @@ -9,283 +9,313 @@ #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/Id.hh" #include "pxl/core/LorentzVector.hh" #include "pxl/core/Serializable.hh" -#include "pxl/core/Id.hh" +#include "pxl/core/functions.hh" +#include "pxl/core/macros.hh" +#include #include -#include -#include +#include +#include #include -#include #include -#include #include -#include +#include +#include -#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; } - -namespace pxl -{ - -class PXL_DLL_EXPORT Variant -{ +#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; \ + } + +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 - }; + 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 + }; + + 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; + } - 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(); + // 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(); 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; + + 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; private: - void copy(const Variant &a); - void check(const Type t) const; - void check(const Type t); + void copy(const Variant& a); + 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) @@ -301,7 +331,7 @@ VARIANT_TO_DECL(String, std::string) VARIANT_TO_DECL(Double, double) VARIANT_TO_DECL(Vector, std::vector) -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 diff --git a/core/include/pxl/core/Vector3.hh b/core/include/pxl/core/Vector3.hh index 114ab861..0d271597 100644 --- a/core/include/pxl/core/Vector3.hh +++ b/core/include/pxl/core/Vector3.hh @@ -9,266 +9,230 @@ #ifndef PXL_CORE_VECTOR3_HH #define PXL_CORE_VECTOR3_HH -#include #include +#include #include -#include "pxl/core/macros.hh" #include "pxl/core/Stream.hh" - +#include "pxl/core/macros.hh" class runtime_error; - -namespace pxl -{ +namespace pxl { /** - This class provides a simple threevector with basic algebra. The methods provided are self-explanatory. + 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 -{ +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]; - } + 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]); + } - bool isNullPerp() const; + inline void setX(double x) { _v[0] = x; } + inline void setY(double y) { _v[1] = y; } + inline void setZ(double z) { _v[2] = z; } - bool isNull() const; + inline void setXYZ(double x, double y, double z) + { + _v[0] = x; + _v[1] = y; + _v[2] = z; + } - double getPerp2() const; + inline void setElement(int i, double val) + { + if (i < 0 || 1 > 2) + throw std::runtime_error("Basic3Vector index out of range"); + _v[i] = val; + } - double getPerp() const; + inline double getElement(int i) const + { + if (i < 0 || 1 > 2) + throw std::runtime_error("Basic3Vector index out of range"); + return _v[i]; + } - double getPhi() const; + 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; + } - double getMag2() const; + void setCArray(double val[3]) + { + _v[0] = val[0]; + _v[1] = val[1]; + _v[2] = val[2]; + } - double getMag() const; + void setRhoPhi(double perp, double phi); - double getCosTheta() const; + void setRhoPhiZ(double perp, double phi, double z); - double getCos2Theta() const; + void setRThetaPhi(double r, double theta, double phi); - double getTheta() const; + inline double getX() const { return _v[0]; } + inline double getY() const { return _v[1]; } + inline double getZ() const { return _v[2]; } - /// Returns unit vector in spherical coordinates - Basic3Vector getETheta() const; + bool isNullPerp() const; - ///Returns unit vector in spherical coordinates - Basic3Vector getEPhi() const; + bool isNull() const; - double deltaRho(const Basic3Vector* fv) const - { - return deltaRho(*fv); - } + double getPerp2() const; - double deltaPhi(const Basic3Vector* fv) const - { - return deltaPhi(*fv); - } + double getPerp() const; - double deltaTheta(const Basic3Vector* fv) const - { - return deltaPhi(*fv); - } + double getPhi() const; - double deltaRho(const Basic3Vector& fv) const; + double getMag2() const; - double deltaPhi(const Basic3Vector& fv) const; + double getMag() const; - double deltaTheta(const Basic3Vector& fv) const; + double getCosTheta() const; - const Basic3Vector& operator=(const Basic3Vector& vec); + double getCos2Theta() const; - const Basic3Vector& operator+=(const Basic3Vector& vec); + double getTheta() const; - const Basic3Vector& operator-=(const Basic3Vector& vec); + /// Returns unit vector in spherical coordinates + Basic3Vector getETheta() const; - const Basic3Vector& operator*=(double scalar); + /// Returns unit vector in spherical coordinates + Basic3Vector getEPhi() const; - const Basic3Vector& operator/=(double scalar); + double deltaRho(const Basic3Vector* fv) const { return deltaRho(*fv); } - Basic3Vector operator+(const Basic3Vector& vec); + double deltaPhi(const Basic3Vector* fv) const { return deltaPhi(*fv); } - /// Returns a copy of (this minus vec). - Basic3Vector operator-(const Basic3Vector& vec); + double deltaTheta(const Basic3Vector* fv) const { return deltaPhi(*fv); } - /// Returns a copy of (this divided by passed scalar). - Basic3Vector operator/(double scalar) const; + double deltaRho(const Basic3Vector& fv) const; - /// scalar product - double operator*( const Basic3Vector& vec) const; + double deltaPhi(const Basic3Vector& fv) 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]); - } + double deltaTheta(const Basic3Vector& fv) const; - /// 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]; - } + const Basic3Vector& operator=(const Basic3Vector& vec); - /// returns the given norm, -1 for infinity norm - double norm(uint32_t norm) const; + const Basic3Vector& operator+=(const Basic3Vector& vec); - bool isUnitVector() const; + const Basic3Vector& operator-=(const Basic3Vector& vec); - /// Returns angle between the vector and vec - double getAngleTo(const Basic3Vector& vec) const; + const Basic3Vector& operator*=(double scalar); - /// Rotates the vector around axis by the angle rad - void rotate(const Basic3Vector& axis, double angle); + const Basic3Vector& operator/=(double scalar); - /// normalizes the vector to 1 - void normalize(); + Basic3Vector operator+(const Basic3Vector& vec); -private: - double _v[3]; + /// 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); +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 diff --git a/core/include/pxl/core/WkPtrBase.hh b/core/include/pxl/core/WkPtrBase.hh index 81d26787..f19f8f4e 100644 --- a/core/include/pxl/core/WkPtrBase.hh +++ b/core/include/pxl/core/WkPtrBase.hh @@ -9,8 +9,8 @@ #ifndef PXL_BASE_WKPTRBASE_HH #define PXL_BASE_WKPTRBASE_HH -#include #include "pxl/core/macros.hh" +#include namespace pxl { @@ -18,86 +18,62 @@ namespace pxl { class Relative; -/** - This base class provides common functionalities for all derived PXL weak pointers. +/** + This base class provides common functionalities for all derived PXL weak pointers. */ -class PXL_DLL_EXPORT WkPtrBase -{ +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; - } + 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) - { - } + WkPtrBase() + : _notifyChainIn(0) + , _notifyChainOut(0) + , _objectRef(0) + { + } - void notifyDeleted(); + void notifyDeleted(); - void connect(Relative* pointer); + void connect(Relative* pointer); - WkPtrBase* _notifyChainIn; - WkPtrBase* _notifyChainOut; + WkPtrBase* _notifyChainIn; + WkPtrBase* _notifyChainOut; - Relative* _objectRef; + Relative* _objectRef; - friend class Relative; + friend class Relative; }; } // namespace pxl diff --git a/core/include/pxl/core/functions.hh b/core/include/pxl/core/functions.hh index 3a8d1100..ca4ebac1 100644 --- a/core/include/pxl/core/functions.hh +++ b/core/include/pxl/core/functions.hh @@ -14,10 +14,10 @@ #include "pxl/core/macros.hh" -namespace pxl -{ +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 +25,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,49 +48,48 @@ 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 diff --git a/core/include/pxl/core/logging.hh b/core/include/pxl/core/logging.hh index 56c6a80e..4e4fa839 100644 --- a/core/include/pxl/core/logging.hh +++ b/core/include/pxl/core/logging.hh @@ -9,255 +9,229 @@ #ifndef PXL_BASE_LOGGING_HH #define PXL_BASE_LOGGING_HH -#include "pxl/core/macros.hh" #include "pxl/core/functions.hh" +#include "pxl/core/macros.hh" -#include -#include #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 +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); +PXL_DLL_EXPORT const std::string& LogLevelToString(LogLevel level); -class PXL_DLL_EXPORT LogHandler -{ +class PXL_DLL_EXPORT LogHandler { public: - virtual ~LogHandler() - { - } + virtual ~LogHandler() {} - virtual void handle(LogLevel level, time_t timestamp, - const std::string &module, const std::string &message) = 0; + 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: +class PXL_DLL_EXPORT ConsoleLogHandler : public LogHandler { + std::vector enabledModules; + std::vector disabledModules; + std::string warningColor, errorColor, endColor; - ConsoleLogHandler(); +public: + ConsoleLogHandler(); - virtual ~ConsoleLogHandler() - { - } + virtual ~ConsoleLogHandler() {} - void handle(LogLevel level, time_t timestamp, const std::string &module, - const std::string &message); + void handle( + LogLevel level, time_t timestamp, const std::string& module, const std::string& message); }; -class PXL_DLL_EXPORT LogDispatcher -{ +class PXL_DLL_EXPORT LogDispatcher { public: - - typedef std::vector > handlers_t; + typedef std::vector > handlers_t; private: + handlers_t handlers; + LogLevel lowestLogLevel; + ConsoleLogHandler consoleLogHandler; + std::string indent; - handlers_t handlers; - LogLevel lowestLogLevel; - ConsoleLogHandler consoleLogHandler; - std::string indent; - - void updateLowestLogLevel(); + void updateLowestLogLevel(); public: - LogDispatcher(); + LogDispatcher(); - void pushIndent(char c) - { - indent.append(1, c); - } + void pushIndent(char c) { indent.append(1, c); } - void popIndent() - { - indent.resize(indent.length() - 1); - } + void popIndent() { indent.resize(indent.length() - 1); } - const std::string &getIndent() - { - return indent; - } + const std::string& getIndent() { return indent; } - void setHandler(LogHandler *handler, LogLevel loglevel); + void setHandler(LogHandler* handler, LogLevel loglevel); - void removeHandler(LogHandler *handler); + void removeHandler(LogHandler* handler); - void dispatch(LogLevel level, const std::string &module, - const std::string &message); + void dispatch(LogLevel level, const std::string& module, const std::string& message); - LogLevel getLowestLogLevel(); + LogLevel getLowestLogLevel(); - void disableConsoleLogHandler(); - void enableConsoleLogHandler(LogLevel level); + void disableConsoleLogHandler(); + void enableConsoleLogHandler(LogLevel level); - static LogDispatcher& instance(); + static LogDispatcher& instance(); }; -class PXL_DLL_EXPORT Logger -{ +class PXL_DLL_EXPORT Logger { private: - std::string module; -public: + std::string module; - 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()); - } - } +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; +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; - } + 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) +#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 index 0a040b7b..70993f6f 100644 --- a/core/include/pxl/core/macros.hh +++ b/core/include/pxl/core/macros.hh @@ -16,28 +16,28 @@ #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)) +#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) +#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)) +#define PXL_OFFSETOF(t, f) ((std::ptrdiff_t)offsetof(t, f)) #else -# define PXL_OFFSETOF(t, f) ((std::ptrdiff_t)((char *) &((t*)0)->f)) +#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))) +#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 ) +#define PXL_DLL_EXPORT __declspec(dllexport) #else -#define PXL_DLL_EXPORT __declspec( dllimport ) +#define PXL_DLL_EXPORT __declspec(dllimport) #endif // PXL_EXPORT #else #define PXL_DLL_EXPORT @@ -52,7 +52,7 @@ #define PXL_PATH_SEPERATOR "/" #endif -#define _STR(x) #x -#define STR(x) _STR(x) +#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 index d8a27e86..8409030f 100644 --- a/core/include/pxl/core/weak_ptr.hh +++ b/core/include/pxl/core/weak_ptr.hh @@ -12,132 +12,106 @@ #include #include -#include "pxl/core/macros.hh" #include "pxl/core/WkPtrBase.hh" +#include "pxl/core/macros.hh" -namespace pxl -{ +namespace pxl { // ptl -/** - This class template represents a weak pointer to PXL objects of \p objecttype that aggregate data of \p datatype. +/** + 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 -{ +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; - } - + 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) +template objecttype& operator*(weak_ptr& wkPtr) { - return wkPtr.object(); + return wkPtr.object(); } -template const objecttype& operator*( - const weak_ptr& wkPtr) +template const objecttype& operator*(const weak_ptr& wkPtr) { - return wkPtr.object(); + return wkPtr.object(); } } // namespace pxl - #endif // PXL_BASE_WEAK_PTR_HH diff --git a/core/src/ChunkReader.cc b/core/src/ChunkReader.cc index 01f87268..f7d5512e 100644 --- a/core/src/ChunkReader.cc +++ b/core/src/ChunkReader.cc @@ -6,312 +6,286 @@ // Licensed under a LGPL-2 or later license - //------------------------------------------- -#include #include +#include #include #include "pxl/core/ChunkReader.hh" -namespace pxl -{ +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; + 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; + 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, +/// 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) +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; + // 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) +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; + // 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) +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; + 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); + std::streampos pos = _stream.tell(); + _stream.seek(0, SeekEnd); - size_t length = _stream.tell(); - _stream.seek (pos); + size_t length = _stream.tell(); + _stream.seek(pos); - return length; + return length; } - } - diff --git a/core/src/ChunkWriter.cc b/core/src/ChunkWriter.cc index 79f5def9..117249b2 100644 --- a/core/src/ChunkWriter.cc +++ b/core/src/ChunkWriter.cc @@ -11,132 +11,121 @@ #include "pxl/core/ChunkWriter.hh" -namespace pxl -{ +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; + _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; + // 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; + _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) +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; + // 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 +} // namespace pxl diff --git a/core/src/ConfigLoader.cc b/core/src/ConfigLoader.cc index 3a06331d..2314b631 100644 --- a/core/src/ConfigLoader.cc +++ b/core/src/ConfigLoader.cc @@ -9,8 +9,8 @@ #include "pxl/core/Tokenizer.hh" #include "pxl/core/logging.hh" -#include "pxl/core/Configuration.hh" #include "pxl/core/ConfigLoader.hh" +#include "pxl/core/Configuration.hh" #include @@ -23,85 +23,72 @@ const char HOME_ENV[] = "HOME"; #undef PXL_LOG_MODULE_NAME #define PXL_LOG_MODULE_NAME "pxl::ConfigLoader" -namespace pxl -{ +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 1c3eb575..c30bc01d 100644 --- a/core/src/Configuration.cc +++ b/core/src/Configuration.cc @@ -6,43 +6,35 @@ // Licensed under a LGPL-2 or later license - //------------------------------------------- - #include "pxl/core/Configuration.hh" +namespace pxl { -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 57aeb449..04e01011 100644 --- a/core/src/Core.cc +++ b/core/src/Core.cc @@ -7,9 +7,9 @@ #include "pxl/core.hh" -#include "pxl/core/FileFactory.hh" #include "LocalFileImpl.hh" #include "StdFileImpl.hh" +#include "pxl/core/FileFactory.hh" #ifdef PXL_ENABLE_SFTP #include "sFTPFileImpl.hh" @@ -18,8 +18,7 @@ #include "dCapFileImpl.hh" #endif -namespace pxl -{ +namespace pxl { static bool _initialized = false; @@ -40,47 +39,47 @@ static FileProducerTemplate _dCapFileProducer; #endif void Core::initialize() { - if (_initialized) - return; + if (_initialized) + return; - _BasicContainerProducer.initialize(); - _BasicMatrixProducer.initialize(); - _BasicNVectorProducer.initialize(); - _EventProducer.initialize(); - _InformationChunkProducer.initialize(); - _ObjectProducer.initialize(); - _ObjectManagerProducer.initialize(); - _LocalFileProducer.initialize("file"); - _StdFileProducer.initialize("std"); + _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"); + _sFTPFileProducer.initialize("ssh"); #endif #ifdef PXL_ENABLE_DCAP - _dCapFileProducer.initialize("dcap"); + _dCapFileProducer.initialize("dcap"); #endif - _initialized = true; + _initialized = true; } void Core::shutdown() { - if (_initialized == false) - return; + if (_initialized == false) + return; - _BasicMatrixProducer.shutdown(); - _BasicContainerProducer.shutdown(); - _BasicNVectorProducer.shutdown(); - _EventProducer.shutdown(); - _InformationChunkProducer.shutdown(); - _ObjectProducer.shutdown(); - _ObjectManagerProducer.shutdown(); - _LocalFileProducer.shutdown(); + _BasicMatrixProducer.shutdown(); + _BasicContainerProducer.shutdown(); + _BasicNVectorProducer.shutdown(); + _EventProducer.shutdown(); + _InformationChunkProducer.shutdown(); + _ObjectProducer.shutdown(); + _ObjectManagerProducer.shutdown(); + _LocalFileProducer.shutdown(); #ifdef PXL_ENABLE_SFTP - _sFTPFileProducer.shutdown(); + _sFTPFileProducer.shutdown(); #endif #ifdef PXL_ENABLE_DCAP - _dCapFileProducer.shutdown(); + _dCapFileProducer.shutdown(); #endif - _initialized = false; + _initialized = false; } } // namespace pxl diff --git a/core/src/Event.cc b/core/src/Event.cc index 1baafca7..e7589be0 100644 --- a/core/src/Event.cc +++ b/core/src/Event.cc @@ -8,44 +8,40 @@ #include "pxl/core/Event.hh" -namespace pxl -{ +namespace pxl { -void Event::serialize(const OutputStream &out) const +void Event::serialize(const OutputStream& out) const { - Serializable::serialize(out); - _objects.serialize(out); - UserRecordHelper::serialize(out); + Serializable::serialize(out); + _objects.serialize(out); + UserRecordHelper::serialize(out); } -void Event::deserialize(const InputStream &in) +void Event::deserialize(const InputStream& in) { - Serializable::deserialize(in); - _objects.deserialize(in); - UserRecordHelper::deserialize(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; + 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; + 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 index e195bdc3..c4b58ef6 100644 --- a/core/src/File.cc +++ b/core/src/File.cc @@ -1,134 +1,123 @@ #include "pxl/core/File.hh" -#include "pxl/core/logging.hh" #include "pxl/core/FileFactory.hh" +#include "pxl/core/logging.hh" #include "LocalFileImpl.hh" #undef PXL_LOG_MODULE_NAME #define PXL_LOG_MODULE_NAME "pxl::File" -namespace pxl -{ +namespace pxl { -File::File() : - impl(0) +File::File() + : impl(0) { - } -File::File(const std::string &filename, int32_t mode) : - impl(0) +File::File(const std::string& filename, int32_t mode) + : impl(0) { - open(filename, mode); + open(filename, mode); } -File::~File() -{ - close(); -} +File::~File() { close(); } void File::close() { - if (impl) - { - impl->close(); - impl->destroy(); - impl = 0; - } + if (impl) { + impl->close(); + impl->destroy(); + impl = 0; + } } bool File::isEof() { - if (impl == 0) - throw std::runtime_error("invalid File implementation!"); - return impl->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(); + if (impl == 0) + return true; + else + return impl->isBad(); } bool File::isOpen() { - if (impl == 0) - return false; - else - return impl->isOpen(); + if (impl == 0) + return false; + else + return impl->isOpen(); } void File::clear() { - if (impl) - impl->clear(); + if (impl) + impl->clear(); } bool File::isGood() { - if (impl == 0) - throw std::runtime_error("invalid File implementation!"); - return impl->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(); + 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); + 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(); + if (impl == 0) + throw std::runtime_error("invalid File implementation!"); + return impl->peek(); } -int64_t File::read(char *s, size_t count) +int64_t File::read(char* s, size_t count) { - if (impl == 0) - throw std::runtime_error("invalid File implementation!"); - return impl->read(s, 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) +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); + 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; + 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) +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"; + 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; + PXL_LOG_INFO << "Open: schema=" << schema << ", path=" << path; - impl = FileFactory::instance().create(schema); + impl = FileFactory::instance().create(schema); - if (impl == 0) - { - PXL_LOG_ERROR << "Unknown Schema: " << schema; - return false; - } + if (impl == 0) { + PXL_LOG_ERROR << "Unknown Schema: " << schema; + return false; + } - return impl->open(expanded, mode); + return impl->open(expanded, mode); } - } diff --git a/core/src/FileFactory.cc b/core/src/FileFactory.cc index 1a0ccfd9..2d398126 100644 --- a/core/src/FileFactory.cc +++ b/core/src/FileFactory.cc @@ -12,54 +12,47 @@ #undef PXL_LOG_MODULE_NAME #define PXL_LOG_MODULE_NAME "pxl::FileFactory" -namespace pxl -{ +namespace pxl { -FileFactory::FileFactory() -{ -} +FileFactory::FileFactory() {} FileFactory& FileFactory::instance() { - static FileFactory f; - return f; + static FileFactory f; + return f; } -FileImpl *FileFactory::create(const std::string& id) +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(); + 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) +void FileFactory::registerProducer(const std::string& id, const FileProducerInterface* producer) { - PXL_LOG_INFO << "register file schema " << id; - _Producers[id] = 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; - } - } + 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()); + return (_Producers.find(schema) != _Producers.end()); } } // namespace pxl - diff --git a/core/src/Id.cc b/core/src/Id.cc index 2a5bf84a..47896c9c 100644 --- a/core/src/Id.cc +++ b/core/src/Id.cc @@ -10,244 +10,205 @@ namespace pxl { -Id::Id() -{ - generate(); -} +Id::Id() { generate(); } -Id::Id (const InputStream& in) -{ - deserialize (in); -} +Id::Id(const InputStream& in) { deserialize(in); } -Id::Id(Random& rand) -{ - generate(rand); -} +Id::Id(Random& 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; - } + for (int i = 0; i < 16; i++) { + if (bytes[i] != id.bytes[i]) + return false; + } - return true; + 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; - } + for (int i = 0; i < 16; i++) { + if (bytes[i] != id.bytes[i]) + return true; + } - return false; + 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.writeUnsignedChar(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.readUnsignedChar(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++; - } + 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) +std::ostream& operator<<(std::ostream& os, const Id& id) { - os << id.toString(); - return os; + 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 index 45124458..448fb8b8 100644 --- a/core/src/InformationChunk.cc +++ b/core/src/InformationChunk.cc @@ -12,17 +12,16 @@ namespace pxl { /// Write data to the OutputStream \p out. -void InformationChunk::serialize(const OutputStream &out) const +void InformationChunk::serialize(const OutputStream& out) const { - Serializable::serialize(out); - UserRecordHelper::serialize(out); + Serializable::serialize(out); + UserRecordHelper::serialize(out); } /// Read data from the InputStream \p in. -void InformationChunk::deserialize(const InputStream &in) +void InformationChunk::deserialize(const InputStream& in) { - Serializable::deserialize(in); - UserRecordHelper::deserialize(in); + Serializable::deserialize(in); + UserRecordHelper::deserialize(in); } - } diff --git a/core/src/InputHandler.cc b/core/src/InputHandler.cc index a7b30899..9c407d8a 100644 --- a/core/src/InputHandler.cc +++ b/core/src/InputHandler.cc @@ -11,290 +11,250 @@ #include "pxl/core/InputHandler.hh" #include "pxl/core/ObjectFactory.hh" -namespace pxl -{ +namespace pxl { -/// This method fills the objects from the read-in block into the passed vector. The number of added objects is returned. +/// 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; + 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. +/// 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 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; + 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. +/// 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; + 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::readPreviousObject() +Serializable* InputHandler::readNextObject() { - return seekToObject(_objectCount - 1); + 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; + 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; + 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) +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; + 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; + 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) +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; + 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; + 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) +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; + 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; + 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); + 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; + 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) - +/// 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; + 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 +// namespace pxl diff --git a/core/src/LocalFileImpl.cc b/core/src/LocalFileImpl.cc index a1c09e4e..5848f91b 100644 --- a/core/src/LocalFileImpl.cc +++ b/core/src/LocalFileImpl.cc @@ -4,162 +4,141 @@ #include -namespace pxl -{ +namespace pxl { -LocalFileImpl::LocalFileImpl() : - _file(0) +LocalFileImpl::LocalFileImpl() + : _file(0) { - } -LocalFileImpl::LocalFileImpl(const std::string &filename, int32_t mode) : - _file(0) +LocalFileImpl::LocalFileImpl(const std::string& filename, int32_t mode) + : _file(0) { - open(filename, mode); + open(filename, mode); } -LocalFileImpl::~LocalFileImpl() -{ - close(); -} +LocalFileImpl::~LocalFileImpl() { close(); } -bool LocalFileImpl::open(const std::string &filename, int32_t mode) +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()); + 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()); + _file = fopen64(path.c_str(), open_mode.c_str()); #endif - _mode = mode; + _mode = mode; - return isOpen(); + return isOpen(); } void LocalFileImpl::close() { - if (_file == 0) - return; - fclose(_file); - _file = 0; + if (_file == 0) + return; + fclose(_file); + _file = 0; } bool LocalFileImpl::isEof() { - if (_file == 0) - return true; + if (_file == 0) + return true; - return (feof(_file) != 0); + return (feof(_file) != 0); } -bool LocalFileImpl::isOpen() -{ - return (_file != 0); -} +bool LocalFileImpl::isOpen() { return (_file != 0); } bool LocalFileImpl::isBad() { - if (_file == 0) - return true; + if (_file == 0) + return true; - return false; + return false; } -void LocalFileImpl::clear() -{ - -} +void LocalFileImpl::clear() {} bool LocalFileImpl::isGood() { - if (_file == 0) - return false; + if (_file == 0) + return false; - if (feof(_file)) - return false; + if (feof(_file)) + return false; - return true; + return true; } int64_t LocalFileImpl::tell() { - if (_file == 0) - return 0; + if (_file == 0) + return 0; #if defined(_MSC_VER) - return _ftelli64(_file); + return _ftelli64(_file); #elif defined(__APPLE__) - return ftell(_file); + return ftell(_file); #else - return ftello64(_file); + 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!."); + 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); + _fseeki64(_file, pos, SEEK_CUR); #elif defined(__APPLE__) - fseek(_file, pos, whence); + fseek(_file, pos, whence); #else - fseeko64(_file, pos, whence); + fseeko64(_file, pos, whence); #endif } int32_t LocalFileImpl::peek() { - int32_t c; + int32_t c; - c = fgetc(_file); - ungetc(c, _file); + c = fgetc(_file); + ungetc(c, _file); - return c; -} - -int64_t LocalFileImpl::read(char *s, size_t count) -{ - return fread(s, sizeof(char), count, _file); + return c; } -int64_t LocalFileImpl::write(const char *s, size_t count) -{ - return fwrite(s, sizeof(char), count, _file); - -} +int64_t LocalFileImpl::read(char* s, size_t count) { return fread(s, sizeof(char), count, _file); } -void LocalFileImpl::ignore(int64_t count) +int64_t LocalFileImpl::write(const char* s, size_t count) { - seek(count, SeekCurrent); + return fwrite(s, sizeof(char), count, _file); } -void LocalFileImpl::destroy() -{ - delete this; -} +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 index fc899842..68426054 100644 --- a/core/src/LocalFileImpl.hh +++ b/core/src/LocalFileImpl.hh @@ -1,38 +1,36 @@ #ifndef PXL_LOCAL_FILE_IMPL_HH_ #define PXL_LOCAL_FILE_IMPL_HH_ -#include "pxl/core/macros.hh" #include "pxl/core/File.hh" +#include "pxl/core/macros.hh" -namespace pxl -{ +namespace pxl { -class PXL_DLL_EXPORT LocalFileImpl: public FileImpl -{ - FILE *_file; - int32_t _mode; -public: +class PXL_DLL_EXPORT LocalFileImpl : public FileImpl { + FILE* _file; + int32_t _mode; - 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(); +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 diff --git a/core/src/LorentzVector.cc b/core/src/LorentzVector.cc index 3c476ff2..26002ba3 100644 --- a/core/src/LorentzVector.cc +++ b/core/src/LorentzVector.cc @@ -10,74 +10,68 @@ #include "pxl/core/LorentzVector.hh" -namespace pxl -{ +namespace pxl { bool operator==(const LorentzVector& obj1, const LorentzVector& obj2) { - return obj1.getX() == obj2.getX() && obj1.getY() == obj2.getY() && obj1.getZ() == obj2.getZ() && obj1.getE() - == obj2.getE(); + return obj1.getX() == obj2.getX() && obj1.getY() == obj2.getY() && obj1.getZ() == obj2.getZ() + && obj1.getE() == obj2.getE(); } bool operator!=(const LorentzVector& obj1, const LorentzVector& obj2) { - return obj1.getX() != obj2.getX() || obj1.getY() != obj2.getY() || obj1.getZ() != obj2.getZ() || obj1.getE() - != obj2.getE(); + return obj1.getX() != obj2.getX() || obj1.getY() != obj2.getY() || obj1.getZ() != obj2.getZ() + || obj1.getE() != obj2.getE(); } LorentzVector operator*(double scalar, const LorentzVector& vec) { - 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; + out.setX(vec.getX() * scalar); + out.setY(vec.getY() * scalar); + out.setZ(vec.getZ() * scalar); + out.setE(vec.getE() * scalar); + return out; } -LorentzVector operator*(const LorentzVector& vec, double scalar) -{ - return operator*(scalar, vec); -} +LorentzVector operator*(const LorentzVector& vec, double scalar) { return operator*(scalar, vec); } // Scalar product double LorentzVector::operator*(const LorentzVector& vec) const { - return getT() * vec.getT() - getX() * vec.getX() - getY() * vec.getY() - getZ() * vec.getZ(); + return getT() * vec.getT() - getX() * vec.getX() - getY() * vec.getY() - getZ() * vec.getZ(); } LorentzVector LorentzVector::operator-(const LorentzVector& vec) const { - LorentzVector out(*this); - out -= vec; - return out; + LorentzVector out(*this); + out -= vec; + return out; } LorentzVector LorentzVector::operator+(const LorentzVector& vec) const { - LorentzVector out(*this); - out += vec; - return out; + LorentzVector out(*this); + out += vec; + return out; } LorentzVector LorentzVector::operator-() const { - return LorentzVector(-1. * getX(), -1. * getY(), -1. * getZ(), -1. * getT()); + return LorentzVector(-1. * getX(), -1. * getY(), -1. * getZ(), -1. * getT()); } void LorentzVector::boost(double b_x, double b_y, double b_z) { - 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)); + 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)); } - } // namespace pxl - diff --git a/core/src/MessageDispatcher.cc b/core/src/MessageDispatcher.cc index 6eb05b9a..34342ae9 100644 --- a/core/src/MessageDispatcher.cc +++ b/core/src/MessageDispatcher.cc @@ -14,129 +14,109 @@ #undef PXL_LOG_MODULE_NAME #define PXL_LOG_MODULE_NAME "pxl::MessageDispatcher" -namespace pxl -{ +namespace pxl { +MessageHandler::~MessageHandler() { MessageDispatcher::instance().unsubscribe(this); } -MessageHandler::~MessageHandler() +MessageDispatcher::MessageDispatcher() + : lastId(0) { - MessageDispatcher::instance().unsubscribe(this); } -MessageDispatcher::MessageDispatcher() : - lastId(0) -{ -} - -MessageDispatcher::~MessageDispatcher() -{ -} +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; -} +const std::map MessageDispatcher::getIds() const { return ids; } } // namespace pxl - diff --git a/core/src/NamedTMPFile.cc b/core/src/NamedTMPFile.cc index 33a9f04a..31d79398 100644 --- a/core/src/NamedTMPFile.cc +++ b/core/src/NamedTMPFile.cc @@ -5,52 +5,42 @@ #include -namespace pxl -{ +namespace pxl { #ifdef WIN32 - #include - #include - #include - #include - #include - #include - int mkstemp(char *tmpl) +#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; + 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() { 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; +#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; +const std::string& NamedTMPFile::getName() { return _filename; } } - -} diff --git a/core/src/Object.cc b/core/src/Object.cc index 53947bf2..972be806 100644 --- a/core/src/Object.cc +++ b/core/src/Object.cc @@ -11,37 +11,35 @@ namespace pxl { -void Object::serialize(const OutputStream &out) const +void Object::serialize(const OutputStream& out) const { - Relative::serialize(out); - out.writeBool(_locked); - out.writeInt(_workflag); - UserRecordHelper::serialize(out); + Relative::serialize(out); + out.writeBool(_locked); + out.writeInt(_workflag); + UserRecordHelper::serialize(out); } -void Object::deserialize(const InputStream &in) +void Object::deserialize(const InputStream& in) { - Relative::deserialize(in); - in.readBool(_locked); - in.readInt(_workflag); - UserRecordHelper::deserialize(in); + Relative::deserialize(in); + in.readBool(_locked); + in.readInt(_workflag); + UserRecordHelper::deserialize(in); } - } std::ostream& pxl::Object::print(int level, std::ostream& os, int pan) const { - printPan1st(os, pan); - os << "pxl::Object with name: " << getName() << "\n"; - if (level>0) printContent(level, os, pan); - return os; + printPan1st(os, pan); + os << "pxl::Object with name: " << getName() << "\n"; + if (level > 0) + printContent(level, os, pan); + return os; } std::ostream& pxl::Object::printContent(int level, std::ostream& os, int pan) const { - os << "WorkFlag: " << _workflag << ", locked: " << _locked; - os << std::endl; - getUserRecords().print(level, os, pan); - return os; + os << "WorkFlag: " << _workflag << ", locked: " << _locked; + os << std::endl; + getUserRecords().print(level, os, pan); + return os; } - - diff --git a/core/src/ObjectFactory.cc b/core/src/ObjectFactory.cc index daa30e73..92e3caf5 100644 --- a/core/src/ObjectFactory.cc +++ b/core/src/ObjectFactory.cc @@ -12,49 +12,42 @@ #undef PXL_LOG_MODULE_NAME #define PXL_LOG_MODULE_NAME "pxl::ObjectFactory" -namespace pxl -{ +namespace pxl { -ObjectFactory::ObjectFactory() -{ -} +ObjectFactory::ObjectFactory() {} ObjectFactory& ObjectFactory::instance() { - static ObjectFactory f; - return f; + static ObjectFactory f; + return f; } -Serializable *ObjectFactory::create(const Id& id) +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(); + 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) +void ObjectFactory::registerProducer(const Id& id, const ObjectProducerInterface* producer) { - PXL_LOG_INFO << "register object producer for " << id; - _Producers[id] = 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; - } - } + 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 index da16e5ee..9bd180b8 100644 --- a/core/src/ObjectManager.cc +++ b/core/src/ObjectManager.cc @@ -7,5 +7,3 @@ //------------------------------------------- #include "pxl/core/ObjectManager.hh" - - diff --git a/core/src/ObjectOwner.cc b/core/src/ObjectOwner.cc index 3ec00166..3648c112 100644 --- a/core/src/ObjectOwner.cc +++ b/core/src/ObjectOwner.cc @@ -8,342 +8,310 @@ #include -#include "pxl/core/Relative.hh" +#include "pxl/core/ObjectFactory.hh" #include "pxl/core/ObjectOwner.hh" #include "pxl/core/Relations.hh" +#include "pxl/core/Relative.hh" #include "pxl/core/logging.hh" -#include "pxl/core/ObjectFactory.hh" #undef PXL_LOG_MODULE_NAME #define PXL_LOG_MODULE_NAME "pxl::ObjectOwner" -namespace pxl -{ +namespace pxl { void ObjectOwner::init(const ObjectOwner& original) { - // 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: 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."; + } } void ObjectOwner::clearContainer() { - for (iterator iter = _container.begin(); iter != _container.end(); iter++) - { - (*iter)->_refObjectOwner=0; - delete (*iter); - } - _container.clear(); - _copyHistory.clear(); - _index.clear(); - _uuidSearchMap.clear(); + for (iterator iter = _container.begin(); iter != _container.end(); iter++) { + (*iter)->_refObjectOwner = 0; + delete (*iter); + } + _container.clear(); + _copyHistory.clear(); + _index.clear(); + _uuidSearchMap.clear(); } -void ObjectOwner::insert(Relative* item) +void ObjectOwner::insert(Relative* item) { - 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)); + 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)); } void ObjectOwner::remove(Relative* item) { - 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; - } - } - + 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; + } + } } void ObjectOwner::take(Relative* item) { - 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; - } - } - + 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; + } + } } -bool ObjectOwner::has(const Relative* item) const -{ - return item->_refObjectOwner == this; -} +bool ObjectOwner::has(const Relative* item) const { return item->_refObjectOwner == this; } -bool ObjectOwner::setIndexEntry(const std::string& key, Relative* obj, -bool overwrite) +bool ObjectOwner::setIndexEntry(const std::string& key, Relative* obj, 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.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; } - -void ObjectOwner::serialize(const OutputStream &out) const +void ObjectOwner::serialize(const OutputStream& out) const { - // 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); - } - + // 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); + } } -void ObjectOwner::deserialize(const InputStream &in) +void ObjectOwner::deserialize(const InputStream& in) { - /* 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)); - } + /* 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 < size; ++i) { + Id typeId(in); + // Contained object must be a Relative derivative + Relative* object = dynamic_cast(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 < msize; ++j) { + Id id(in); + motherRelationsMap.insert(std::pair(object, id)); + } + + int dsize = 0; + in.readInt(dsize); + for (int j = 0; j < dsize; ++j) { + Id id(in); + daughterRelationsMap.insert(std::pair(object, id)); + } + int fsize = 0; + in.readInt(fsize); + for (int j = 0; j < fsize; ++j) { + Id id(in); + flatRelationsMap.insert(std::pair(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 < size; ++i) { + std::string name; + in.readString(name); + Id id(in); + _index.insert(std::pair(name, objIdMap.find(id)->second)); + } } } // namespace pxl diff --git a/core/src/OutputFile.cc b/core/src/OutputFile.cc index 77ab9ef8..b8820056 100644 --- a/core/src/OutputFile.cc +++ b/core/src/OutputFile.cc @@ -10,55 +10,43 @@ #include -namespace pxl +namespace pxl { +OutputFile::OutputFile(const std::string& filename, size_t maxBlockSize, size_t maxNObjects) + : OutputHandler(maxBlockSize, maxNObjects) + , _stream(filename, OpenWrite) + , _writer(_stream) { -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."); + if (_stream.isGood() == false) + throw std::runtime_error("OutputFile: " + filename + " could not be opened."); } -OutputFile::~OutputFile() -{ - close(); -} +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."); + _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(); + finish(); + _stream.close(); } -ChunkWriter& OutputFile::getChunkWriter() -{ - return _writer; -} +ChunkWriter& OutputFile::getChunkWriter() { return _writer; } void OutputFile::setCompressionMode(int compressionMode) { - _writer.setCompressionMode(compressionMode); -} - -OutputFile::OutputFile(const OutputFile& original) : - _stream(), _writer(_stream) -{ + _writer.setCompressionMode(compressionMode); } -OutputFile& OutputFile::operator=(const OutputFile& other) +OutputFile::OutputFile(const OutputFile& original) + : _stream() + , _writer(_stream) { - return *this; } +OutputFile& OutputFile::operator=(const OutputFile& other) { return *this; } } diff --git a/core/src/OutputHandler.cc b/core/src/OutputHandler.cc index fb682759..d39ce158 100644 --- a/core/src/OutputHandler.cc +++ b/core/src/OutputHandler.cc @@ -13,58 +13,55 @@ #undef PXL_LOG_MODULE_NAME #define PXL_LOG_MODULE_NAME "pxl::OutputHandler" -namespace pxl -{ - +namespace pxl { -OutputHandler::OutputHandler(size_t maxSize, size_t maxNObjects) : - _maxSize(maxSize), _newFileSection(true), _maxNObjects(maxNObjects), _nObjects( - 0) +OutputHandler::OutputHandler(size_t maxSize, size_t maxNObjects) + : _maxSize(maxSize) + , _newFileSection(true) + , _maxNObjects(maxNObjects) + , _nObjects(0) { } -OutputHandler::~OutputHandler() -{ -} +OutputHandler::~OutputHandler() {} -/// Use this method to write an information string describing the new event. Otherwise, this method need not necessarily be used. +/// 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; + 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. +/// 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); + 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(); + if (_newFileSection) { + getChunkWriter().newFileSection(""); + _newFileSection = false; + } + getChunkWriter().newBlock(); + getChunkWriter().write(info); + _newFileSection = true; + _nObjects = 0; // reset number of objects + return getChunkWriter().endFileSection(); } -} //namespace pxl +} // namespace pxl diff --git a/core/src/PluginManager.cc b/core/src/PluginManager.cc index b2636734..4c71036d 100644 --- a/core/src/PluginManager.cc +++ b/core/src/PluginManager.cc @@ -6,24 +6,24 @@ // 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,9 +39,9 @@ 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 @@ -51,387 +51,325 @@ const char PXL_DIR[] = "/.pxl-" PXL_LIB_VERSION; #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 #undef PXL_LOG_MODULE_NAME #define PXL_LOG_MODULE_NAME "pxl::PluginManager" -namespace pxl -{ +namespace pxl { +PluginManager::PluginManager() {} -PluginManager::PluginManager() -{ -} - -PluginManager::~PluginManager() -{ - shutdown(); -} +PluginManager::~PluginManager() { 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; -} +std::string PluginManager::getDefaultPluginDirectory() { 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() -{ -} +void PluginManager::shutdown() {} 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_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"); } #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 (*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"; } #endif diff --git a/core/src/Random.cc b/core/src/Random.cc index 17dccf34..9a8aa9a6 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 @@ -60,390 +60,317 @@ #include "pxl/core/Random.hh" #include "pxl/core/RotationMatrix.hh" -namespace pxl -{ +namespace pxl { -Random::Random(const uint32& oneSeed) -{ - seed(oneSeed); -} +Random::Random(const uint32& oneSeed) { seed(oneSeed); } -Random::Random(uint32 * const bigSeed, const uint32 seedLength) -{ - seed(bigSeed, seedLength); -} +Random::Random(uint32* const bigSeed, const uint32 seedLength) { seed(bigSeed, seedLength); } -Random::Random() -{ - seed(); -} +Random::Random() { seed(); } -double Random::rand() -{ - return double(randInt()) * (1.0 / 4294967295.0); -} +double Random::rand() { return double(randInt()) * (1.0 / 4294967295.0); } -double Random::rand(const double& n) -{ - return rand() * n; -} +double Random::rand(const double& n) { return rand() * n; } -double Random::randExc() -{ - return double(randInt()) * (1.0 / 4294967296.0); -} +double Random::randExc() { return double(randInt()) * (1.0 / 4294967296.0); } -double Random::randExc(const double& n) -{ - return randExc() * n; -} +double Random::randExc(const double& n) { return randExc() * n; } -double Random::randDblExc() -{ - return (double(randInt()) + 0.5) * (1.0 / 4294967296.0); -} +double Random::randDblExc() { return (double(randInt()) + 0.5) * (1.0 / 4294967296.0); } -double Random::randDblExc(const double& n) -{ - return randDblExc() * n; -} +double Random::randDblExc(const double& 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(); -} +double Random::randUniform(double min, double max) { return min + (max - min) * this->rand(); } -///returns a rayleigh distributed value -double Random::randRayleigh(double sigma) -{ - return sigma * sqrt(-2.0 * log(1 - this->rand())); -} +/// returns a rayleigh distributed value +double Random::randRayleigh(double sigma) { 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) +Basic3Vector Random::randFisher(const Basic3Vector& meanDirection, double kappa) { - double alpha = randFisher(kappa); + double alpha = randFisher(kappa); - Basic3Vector rotDirection= randUnitVectorOnSphere(); - Basic3Vector rotAxis = meanDirection.cross(rotDirection); - rotAxis.normalize(); + Basic3Vector rotDirection = randUnitVectorOnSphere(); + Basic3Vector rotAxis = meanDirection.cross(rotDirection); + rotAxis.normalize(); - RotationMatrix M(rotAxis, alpha); - Basic3Vector vnew = M * meanDirection; + RotationMatrix M(rotAxis, alpha); + Basic3Vector vnew = M * meanDirection; - return vnew; + return vnew; } - -Basic3Vector Random::randFisher(const Basic3Vector *meanDirection, double kappa) +Basic3Vector Random::randFisher(const Basic3Vector* meanDirection, double kappa) { - return randFisher(*meanDirection, 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 Basic3Vector(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 7162d933..b7e131ff 100644 --- a/core/src/Relations.cc +++ b/core/src/Relations.cc @@ -9,16 +9,13 @@ #include "pxl/core/Relations.hh" #include "pxl/core/Relative.hh" -namespace pxl -{ +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.writeInt(size()); + for (const_iterator iter = begin(); iter != end(); ++iter) { + (*iter)->getId().serialize(out); + } } - } diff --git a/core/src/Relative.cc b/core/src/Relative.cc index 1a0996a7..625693e6 100644 --- a/core/src/Relative.cc +++ b/core/src/Relative.cc @@ -9,198 +9,186 @@ #include #include -#include "pxl/core/Relative.hh" #include "pxl/core/Relations.hh" +#include "pxl/core/Relative.hh" #include "pxl/core/logging.hh" #undef PXL_LOG_MODULE_NAME #define PXL_LOG_MODULE_NAME "pxl::Relative" -namespace pxl -{ +namespace pxl { Relative::~Relative() { - // remove all relations: - unlinkMothers(); - unlinkDaughters(); - unlinkFlat(); - if (_refWkPtrSpec) - { - _refWkPtrSpec->notifyDeleted(); - } + // 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!"; - } + // 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!"; + } } 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 (target->_refObjectOwner != this->_refObjectOwner) { + 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 (target->_refObjectOwner != this->_refObjectOwner) { + 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 (target->_refObjectOwner != this->_refObjectOwner) { + 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::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::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::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 { - int daughters = 0; + int daughters = 0; - print(level, os, pan); + print(level, os, pan); - for (Relations::const_iterator iter = _daughterRelations.begin(); iter - !=_daughterRelations.end(); ++iter) - { + for (Relations::const_iterator iter = _daughterRelations.begin(); + iter != _daughterRelations.end(); ++iter) { - (*iter)->printDecayTree(level, os, pan + 1); - daughters++; + (*iter)->printDecayTree(level, os, pan + 1); + daughters++; + } - } + if (daughters && pan > 1) { + for (int p = 0; p < pan; p++) { + os << "| "; + } + os << "*" << std::endl; + } - 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 { - return printPan1st(os, pan) << "pxl::ObjectBase with id: " << id() - << std::endl; + return printPan1st(os, pan) << "pxl::ObjectBase with id: " << id() << std::endl; } std::ostream& Relative::printPan1st(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 - 2; p++) + os << "| "; + if (pan - 1 > 0) + os << "+--"; + if (pan) + os << "{ "; + + return os; } std::ostream& Relative::printPan(std::ostream& os, int pan) const { - for (int p = 0; p < pan - 1; p++) - os << "| "; - if (pan) - os << "| "; - return os; + for (int p = 0; p < pan - 1; p++) + os << "| "; + if (pan) + os << "| "; + 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 191e2f71..a80272fd 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 @@ -509,12 +552,7 @@ SAFEINT_DISABLE_SHIFT_ASSERT - Set this option if you don't want to assert // Currently implemented code values: // ERROR_ARITHMETIC_OVERFLOW // EXCEPTION_INT_DIVIDE_BY_ZERO -enum SafeIntError -{ - SafeIntNoError = 0, - SafeIntArithmeticOverflow, - SafeIntDivideByZero -}; +enum SafeIntError { SafeIntNoError = 0, SafeIntArithmeticOverflow, SafeIntDivideByZero }; /* * Error handler classes @@ -583,104 +621,103 @@ enum SafeIntError * Overall, this is probably the best approach. * */ -class SafeIntException -{ +class SafeIntException { public: SafeIntException() { m_code = SafeIntNoError; } - SafeIntException( SafeIntError code ) - { - m_code = code; - } + SafeIntException(SafeIntError code) { m_code = code; } SafeIntError m_code; }; #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; +namespace SafeIntInternal { +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 +725,229 @@ 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 -{ +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 ) + 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) }; // 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) + enum { + 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 - -template < typename T, typename U > 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 +// 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 class IntRegion { +public: + enum { + // 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,84 +956,71 @@ 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 -{ - AbsMethodInt, - AbsMethodInt64, - AbsMethodNoop -}; +enum AbsMethod { AbsMethodInt, AbsMethodInt64, AbsMethodNoop }; -template < typename T > -class GetAbsMethod -{ +template class GetAbsMethod { public: - enum - { - method = IntTraits< T >::isLT64Bit && IntTraits< T >::isSigned ? AbsMethodInt : - IntTraits< T >::isInt64 ? AbsMethodInt64 : AbsMethodNoop + enum { + 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; } 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; return true; @@ -921,77 +1031,63 @@ 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) { return (signed __int32)(~(unsigned __int32)in + 1); } - static signed __int32 Value(unsigned __int32 in) - { - return (signed __int32)(~in + 1); - } + static signed __int32 Value(unsigned __int32 in) { return (signed __int32)(~in + 1); } }; -template <> -class SignedNegation -{ +template <> class SignedNegation { public: - static signed __int64 Value(unsigned __int64 in) - { - return (signed __int64)(~in + 1); - } + static signed __int64 Value(unsigned __int64 in) { return (signed __int64)(~in + 1); } }; -template < int method > class NegationAssertHelper; +template class NegationAssertHelper; -template<> -class NegationAssertHelper< true > -{ - 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 { +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 > -{ - public: - static void BehaviorWarning(){} +template <> class NegationAssertHelper { +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 +1100,14 @@ 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,9 +1115,8 @@ public: } }; -//core logic to determine casting behavior -enum CastMethod -{ +// core logic to determine casting behavior +enum CastMethod { CastOK = 0, CastCheckLTZero, CastCheckGTMax, @@ -1034,112 +1128,97 @@ enum CastMethod CastFromBool }; - -template < typename ToType, typename FromType > -class GetCastMethod -{ +template class GetCastMethod { public: - enum - { - method = ( IntTraits< FromType >::isBool && - !IntTraits< ToType >::isBool ) ? CastFromBool : + enum { + 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 ) - { - t = (T)u; - } + template static void CastThrow(U u, T& t) { t = (T)u; } }; // 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; } 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,133 +1227,114 @@ 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 ) - { - t = (T)( b ? 1 : 0 ); - } + template static void CastThrow(bool b, T& t) { 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 ) - { - b = !!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 -enum ComparisonMethod -{ +// core logic to determine whether a comparison is valid, or needs special treatment +enum ComparisonMethod { ComparisonMethod_Ok = 0, ComparisonMethod_CastInt, ComparisonMethod_CastInt64, @@ -1282,160 +1342,151 @@ 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 -{ -public: - enum - { +// 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 { #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,17 +1496,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(); - //trap corner case - if( CompileConst< IntTraits< U >::isSigned >::Value() ) - { - if( u == (U)-1 ) - { + // trap corner case + if (CompileConst::isSigned>::Value()) { + if (u == (U)-1) { result = 0; return; } @@ -1465,19 +1513,16 @@ 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() ) - { - if( u == (U)-1 ) - { + // trap corner case + if (CompileConst::isSigned>::Value()) { + if (u == (U)-1) { result = 0; return SafeIntNoError; } @@ -1487,17 +1532,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(); - //trap corner case - if( CompileConst< IntTraits< U >::isSigned >::Value() ) - { - if( u == (U)-1 ) - { + // trap corner case + if (CompileConst::isSigned>::Value()) { + if (u == (U)-1) { result = 0; return; } @@ -1507,19 +1549,16 @@ 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() ) - { - if( u == (U)-1 ) - { + // trap corner case + if (CompileConst::isSigned>::Value()) { + if (u == (U)-1) { result = 0; return SafeIntNoError; } @@ -1529,16 +1568,13 @@ 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( u == (U)-1 ) - { + if (CompileConst::isSigned>::Value()) { + if (u == (U)-1) { result = 0; return; } @@ -1549,235 +1585,252 @@ 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 -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 +// 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_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 -{ -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 ) ) +template class MultiplicationMethod { +public: + enum { + // 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,42 +1839,39 @@ 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; } - } - else - { + } else { // 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 +1879,13 @@ 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,43 +1895,35 @@ 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(bHigh != 0) - { + if (aHigh == 0) { + if (bHigh != 0) { *pRet = (unsigned __int64)aLow * (unsigned __int64)bHigh; } - } - else if(bHigh == 0) - { - if(aHigh != 0) - { + } else if (bHigh == 0) { + if (aHigh != 0) { *pRet = (unsigned __int64)aHigh * (unsigned __int64)bLow; } - } - else - { + } else { 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 +1934,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,43 +1950,35 @@ 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(bHigh != 0) - { + if (aHigh == 0) { + if (bHigh != 0) { *pRet = (unsigned __int64)aLow * (unsigned __int64)bHigh; } - } - else if(bHigh == 0) - { - if(aHigh != 0) - { + } else if (bHigh == 0) { + if (aHigh != 0) { *pRet = (unsigned __int64)aHigh * (unsigned __int64)bLow; } - } - else - { + } else { 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 +1989,13 @@ 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 +2004,23 @@ 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 +2031,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 +2046,23 @@ 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 +2074,78 @@ 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,35 +2158,30 @@ 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( tmp <= (unsigned __int64)IntTraits< signed __int32 >::maxInt ) - { + if (!fIsNegative) { + if (tmp <= (unsigned __int64)IntTraits::maxInt) { *pRet = (signed __int32)tmp; return true; } - } - else - { - if( tmp <= (unsigned __int64)IntTraits< signed __int32 >::maxInt+1 ) - { - *pRet = SignedNegation< signed __int32 >::Value( tmp ); + } else { + if (tmp <= (unsigned __int64)IntTraits::maxInt + 1) { + *pRet = SignedNegation::Value(tmp); return true; } } @@ -2154,8 +2189,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,34 +2200,29 @@ 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 ) - { - a = (signed __int32)AbsValueHelper< signed __int32, GetAbsMethod< signed __int32 >::method >::Abs(a); + if (a < 0) { + a = (signed __int32) + AbsValueHelper::method>::Abs(a); fIsNegative = true; } unsigned __int64 tmp = (unsigned __int32)a * (unsigned __int64)bLow; - if( !fIsNegative ) - { - if( tmp <= (unsigned __int64)IntTraits< signed __int32 >::maxInt ) - { + if (!fIsNegative) { + if (tmp <= (unsigned __int64)IntTraits::maxInt) { *pRet = (signed __int32)tmp; return; } - } - else - { - if( tmp <= (unsigned __int64)IntTraits< signed __int32 >::maxInt+1 ) - { - *pRet = SignedNegation< signed __int32 >::Value( tmp ); + } else { + if (tmp <= (unsigned __int64)IntTraits::maxInt + 1) { + *pRet = SignedNegation::Value(tmp); return; } } @@ -2201,11 +2231,11 @@ 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 +2243,64 @@ 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,35 +2309,30 @@ 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 ) - { - *pRet = SignedNegation< signed __int64 >::Value( tmp ); + if (tmp <= (unsigned __int64)IntTraits::minInt) { + *pRet = SignedNegation::Value(tmp); return true; } - } - else - { + } 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 +2343,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,35 +2358,31 @@ 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 ) - { - *pRet = SignedNegation< signed __int64 >::Value( tmp ); + if (tmp <= (unsigned __int64)IntTraits::minInt) { + *pRet = SignedNegation::Value(tmp); return; } - } - else - { + } 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,41 +2393,36 @@ 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 ) - { - *pRet = SignedNegation< signed __int64 >::Value( tmp ); + if (tmp <= (unsigned __int64)IntTraits::minInt) { + *pRet = SignedNegation::Value(tmp); return true; } - } - else - { + } 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,40 +2433,36 @@ 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 ) - { - *pRet = SignedNegation< signed __int64 >::Value( tmp ); + if (tmp <= (unsigned __int64)IntTraits::minInt) { + *pRet = SignedNegation::Value(tmp); return; } - } - else - { + } 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 +2473,12 @@ 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,35 +2487,30 @@ 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 ) - { - *pRet = SignedNegation< signed __int64 >::Value( tmp ); + if (tmp <= (unsigned __int64)IntTraits::minInt) { + *pRet = SignedNegation::Value(tmp); return true; } - } - else - { + } 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 +2521,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,35 +2533,31 @@ 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 ) - { - *pRet = SignedNegation< signed __int64 >::Value( tmp ); + if (tmp <= (unsigned __int64)IntTraits::minInt) { + *pRet = SignedNegation::Value(tmp); return; } - } - else - { + } 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,19 +2568,16 @@ 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( tmp > IntTraits< signed __int32 >::maxInt || - tmp < IntTraits< signed __int32 >::minInt ) - { + if (IntrinsicMultiplyInt64(a, b, &tmp)) { + if (tmp > IntTraits::maxInt + || tmp < IntTraits::minInt) { return false; } @@ -2588,35 +2592,30 @@ 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 ) - { - *pRet = SignedNegation< signed __int32 >::Value( tmp ); + if (tmp <= (unsigned __int32)IntTraits::minInt) { + *pRet = SignedNegation::Value(tmp); return true; } - } - else - { + } 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,17 +2626,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( tmp > IntTraits< signed __int32 >::maxInt || - tmp < IntTraits< signed __int32 >::minInt ) - { + if (IntrinsicMultiplyInt64(a, b, &tmp)) { + if (tmp > IntTraits::maxInt + || tmp < IntTraits::minInt) { E::SafeIntOnOverflow(); } @@ -2652,35 +2649,31 @@ 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 ) - { - *pRet = SignedNegation< signed __int32 >::Value( tmp ); + if (tmp <= (unsigned __int32)IntTraits::minInt) { + *pRet = SignedNegation::Value(tmp); return; } - } - else - { + } 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,40 +2684,35 @@ 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 ) - { - *pRet = SignedNegation< signed __int64 >::Value( tmp ); + if (tmp <= (unsigned __int64)IntTraits::minInt) { + *pRet = SignedNegation::Value(tmp); return true; } - } - else - { + } 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,36 +2722,32 @@ 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 ) - { - *pRet = SignedNegation< signed __int64 >::Value( tmp ); + if (tmp <= (unsigned __int64)IntTraits::minInt) { + *pRet = SignedNegation::Value(tmp); return; } - } - else - { + } 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,313 +2761,316 @@ 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; } 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; } 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; } 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; } 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); } }; -enum DivisionState -{ +enum DivisionState { DivisionState_OK, DivisionState_UnsignedSigned, DivisionState_SignedUnsigned32, @@ -3092,83 +3079,76 @@ enum DivisionState DivisionState_SignedSigned }; -template < typename T, typename U > 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) +template class DivisionMethod { +public: + enum { + 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 ) - { - result = (T)( t/u ); + if (u > 0) { + 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,29 +3156,25 @@ 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 ) - { - result = (T)( t/u ); + if (u > 0) { + 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,221 +3183,189 @@ 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; } // 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; } // 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); - } - else // Corner case - if( t == IntTraits< T >::minInt && u == (unsigned __int64)IntTraits< T >::minInt ) - { + result = (T)((__int64)t / (__int64)u); + } else // Corner case + if (t == IntTraits::minInt && u == (unsigned __int64)IntTraits::minInt) { // Min int divided by it's own magnitude is -1 result = -1; - } - else - { + } else { result = 0; } 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); - } - else // Corner case - if( t == IntTraits< T >::minInt && u == (unsigned __int64)IntTraits< T >::minInt ) - { + result = (T)((__int64)t / (__int64)u); + } else // Corner case + if (t == IntTraits::minInt && u == (unsigned __int64)IntTraits::minInt) { // Min int divided by it's own magnitude is -1 result = -1; - } - else - { + } else { result = 0; } } }; -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); } }; -enum AdditionState -{ +enum AdditionState { AdditionState_CastIntCheckMax, AdditionState_CastUintCheckOverflow, AdditionState_CastUintCheckOverflowMax, @@ -3440,55 +3384,79 @@ enum AdditionState AdditionState_Error }; -template< typename T, typename U > -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) +template class AdditionMethod { +public: + enum { + // 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,14 +3464,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,32 +3478,28 @@ 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; } 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,32 +3507,29 @@ 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; } 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,17 +3537,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,15 +3554,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,17 +3569,16 @@ 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,15 +3586,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,16 +3601,14 @@ 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,14 +3616,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,16 +3630,14 @@ 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,14 +3645,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,16 +3659,14 @@ 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,14 +3674,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,33 +3688,27 @@ 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; } - } - else - { + } else { // now we know that rhs can be safely cast into an unsigned __int64 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,31 +3717,25 @@ 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; } - } - else - { + } else { // now we know that rhs can be safely cast into an unsigned __int64 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,29 +3745,25 @@ 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( lhs >= ~(unsigned __int64)( rhs ) + 1 )//negation is safe, since rhs is 64-bit + if (rhs < 0) { + if (lhs >= ~(unsigned __int64)(rhs) + 1) // negation is safe, since rhs is 64-bit { - result = (T)( lhs + rhs ); + result = (T)(lhs + rhs); return true; } - } - else - { + } else { // 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,27 +3771,23 @@ 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( lhs >= ~(unsigned __int64)( rhs ) + 1) //negation is safe, since rhs is 64-bit + if (rhs < 0) { + if (lhs >= ~(unsigned __int64)(rhs) + 1) // negation is safe, since rhs is 64-bit { - result = (T)( lhs + rhs ); + result = (T)(lhs + rhs); return; } - } - else - { + } else { // 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 +3796,20 @@ 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 - { + } else { // lhs negative - if( rhs < 0 && tmp > lhs ) + if (rhs < 0 && tmp > lhs) return false; } @@ -3900,22 +3817,18 @@ 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 - { + } else { // lhs negative - if( rhs < 0 && tmp > lhs ) + if (rhs < 0 && tmp > lhs) E::SafeIntOnOverflow(); } @@ -3923,18 +3836,17 @@ 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,17 +3854,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,16 +3871,15 @@ 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,16 +3887,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,19 +3903,17 @@ 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,15 +3921,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 +3937,38 @@ 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 ) - { - SafeCastHelper< T, __int32, GetCastMethod< T, __int32 >::method >::template CastThrow< E >( (__int32)tmp, result ); + if ((__int32)tmp >= lhs) { + SafeCastHelper::method>::template CastThrow((__int32)tmp, result); return; } } @@ -4074,8 +3976,7 @@ public: } }; -enum SubtractionState -{ +enum SubtractionState { SubtractionState_BothUnsigned, SubtractionState_CastIntCheckMinMax, SubtractionState_CastIntCheckMin, @@ -4102,103 +4003,132 @@ enum SubtractionState SubtractionState_Error }; -template < typename T, typename U > 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) +template class SubtractionMethod { +public: + enum { + // 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 -{ -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) +template class SubtractionMethod2 { +public: + enum { + // 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 ) - { - result = (T)( lhs - rhs ); + if (rhs <= lhs) { + 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 ) - { - result = (T)( lhs - rhs ); + if (rhs <= lhs) { + result = (T)(lhs - rhs); return; } @@ -4206,30 +4136,26 @@ 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,17 +4163,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,51 +4180,49 @@ 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,15 +4230,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,63 +4245,62 @@ 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,15 +4308,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,54 +4323,44 @@ 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( (unsigned __int64)rhs <= lhs ) - { - result = (T)( lhs - (unsigned __int64)rhs ); + if (rhs >= 0) { + if ((unsigned __int64)rhs <= lhs) { + result = (T)(lhs - (unsigned __int64)rhs); return true; } - } - else - { + } else { 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( (unsigned __int64)rhs <= lhs ) - { - result = (T)( lhs - (unsigned __int64)rhs ); + if (rhs >= 0) { + if ((unsigned __int64)rhs <= lhs) { + result = (T)(lhs - (unsigned __int64)rhs); return; } - } - else - { + } else { 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,41 +4368,34 @@ 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 // Also allows us to drop to 32-bit math, which is faster on a 32-bit system result = (T)lhs - (T)rhs; return true; - } - else - { + } else { // 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,39 +4404,32 @@ 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 // Also allows us to drop to 32-bit math, which is faster on a 32-bit system result = (T)lhs - (T)rhs; return; - } - else - { + } else { // 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,31 +4439,25 @@ 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( (unsigned __int64)rhs <= lhs ) - { - result = (T)( lhs - (T)rhs ); + if (rhs >= 0) { + if ((unsigned __int64)rhs <= lhs) { + result = (T)(lhs - (T)rhs); return true; } - } - else - { + } else { // 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,29 +4466,23 @@ 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( (unsigned __int64)rhs <= lhs ) - { - result = (T)( lhs - (T)rhs ); + if (rhs >= 0) { + if ((unsigned __int64)rhs <= lhs) { + result = (T)(lhs - (T)rhs); return; } - } - else - { + } else { // 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,26 +4492,21 @@ 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 - { + } 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,24 +4515,19 @@ 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 - { + } 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 +4537,9 @@ 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 +4554,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 +4564,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 +4579,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 +4589,9 @@ 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,22 +4603,16 @@ 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; } - } - else - { + } 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 +4621,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,22 +4633,17 @@ 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(); } - } - else - { + } 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 +4652,9 @@ 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,44 +4666,31 @@ public: __int64 tmp = (__int64)((unsigned __int64)lhs - (unsigned __int64)rhs); - if( lhs >= 0 ) - { + if (lhs >= 0) { // first case - if( rhs >= 0 ) - { - if( tmp >= IntTraits< T >::minInt ) - { + if (rhs >= 0) { + if (tmp >= IntTraits::minInt) { result = (T)tmp; return true; } - } - else - { + } else { // second case - if( tmp >= lhs && tmp <= IntTraits< T >::maxInt ) - { + if (tmp >= lhs && tmp <= IntTraits::maxInt) { result = (T)tmp; return true; } } - } - else - { + } else { // lhs < 0 // third case - if( rhs >= 0 ) - { - if( tmp <= lhs && tmp >= IntTraits< T >::minInt ) - { + if (rhs >= 0) { + if (tmp <= lhs && tmp >= IntTraits::minInt) { result = (T)tmp; return true; } - } - else - { + } else { // fourth case - if( tmp <= IntTraits< T >::maxInt ) - { + if (tmp <= IntTraits::maxInt) { result = (T)tmp; return true; } @@ -4857,8 +4700,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,44 +4712,31 @@ public: __int64 tmp = (__int64)((unsigned __int64)lhs - (unsigned __int64)rhs); - if( lhs >= 0 ) - { + if (lhs >= 0) { // first case - if( rhs >= 0 ) - { - if( tmp >= IntTraits< T >::minInt ) - { + if (rhs >= 0) { + if (tmp >= IntTraits::minInt) { result = (T)tmp; return; } - } - else - { + } else { // second case - if( tmp >= lhs && tmp <= IntTraits< T >::maxInt ) - { + if (tmp >= lhs && tmp <= IntTraits::maxInt) { result = (T)tmp; return; } } - } - else - { + } else { // lhs < 0 // third case - if( rhs >= 0 ) - { - if( tmp <= lhs && tmp >= IntTraits< T >::minInt ) - { + if (rhs >= 0) { + if (tmp <= lhs && tmp >= IntTraits::minInt) { result = (T)tmp; return; } - } - else - { + } else { // fourth case - if( tmp <= IntTraits< T >::maxInt ) - { + if (tmp <= IntTraits::maxInt) { result = (T)tmp; return; } @@ -4918,53 +4747,45 @@ 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,15 +4793,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,17 +4808,15 @@ 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,14 +4824,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 +4838,25 @@ 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( rhs <= AbsMinIntT - AbsValueHelper< T, GetAbsMethod< T >::method >::Abs( lhs ) ) - { - result = (T)( lhs - rhs ); + if (lhs < 0) { + if (rhs <= AbsMinIntT - AbsValueHelper::method>::Abs(lhs)) { + result = (T)(lhs - rhs); return true; } - } - else - { - if( rhs <= AbsMinIntT + (unsigned __int64)lhs ) - { - result = (T)( lhs - rhs ); + } else { + if (rhs <= AbsMinIntT + (unsigned __int64)lhs) { + result = (T)(lhs - rhs); return true; } } @@ -5055,29 +4864,23 @@ 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( rhs <= AbsMinIntT - AbsValueHelper< T, GetAbsMethod< T >::method >::Abs( lhs ) ) - { - result = (T)( lhs - rhs ); + if (lhs < 0) { + if (rhs <= AbsMinIntT - AbsValueHelper::method>::Abs(lhs)) { + result = (T)(lhs - rhs); return; } - } - else - { - if( rhs <= AbsMinIntT + (unsigned __int64)lhs ) - { - result = (T)( lhs - rhs ); + } else { + if (rhs <= AbsMinIntT + (unsigned __int64)lhs) { + result = (T)(lhs - rhs); return; } } @@ -5086,14 +4889,12 @@ 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,68 +4902,60 @@ 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; } 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; } 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; } 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,44 +4963,33 @@ 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; } E::SafeIntOnOverflow(); } - }; -enum BinaryState -{ - BinaryState_OK, - BinaryState_Int8, - BinaryState_Int16, - BinaryState_Int32 -}; +enum BinaryState { BinaryState_OK, BinaryState_Int8, BinaryState_Int16, BinaryState_Int32 }; -template < typename T, typename U > class BinaryMethod -{ +template class BinaryMethod { public: - enum - { + enum { // If both operands are unsigned OR // 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 +4999,114 @@ 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