Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2024-04-06 12:02:32

0001 /*****************************************************************************/
0002 /**

0003  * \file portable_iarchive.hpp

0004  * \brief Provides an archive to read from portable binary files.

0005  * \author christian.pfligersdorffer@gmx.at

0006  * \version 5.1

0007  *

0008  * This pair of archives brings the advantages of binary streams to the cross

0009  * platform boost::serialization user. While being almost as fast as the native

0010  * binary archive it allows its files to be exchanged between cpu architectures

0011  * using different byte order (endianness). Speaking of speed: in serializing

0012  * numbers the (portable) binary approach is approximately ten times faster than

0013  * the ascii implementation (that is inherently portable)!

0014  *

0015  * Based on the portable archive example by Robert Ramey this implementation

0016  * uses Beman Dawes endian library and fp_utilities from Johan Rade, both being

0017  * in boost since 1.36. Prior to that you need to add them both (header only)

0018  * to your boost directory before you're able to use the archives provided. 

0019  * Our archives have been tested successfully for boost versions 1.33 to 1.49!

0020  *

0021  * \note Correct behaviour has so far been confirmed using PowerPC-32, x86-32

0022  *       and x86-64 platforms featuring different byte order. So there is a good

0023  *       chance it will instantly work for your specific setup. If you encounter

0024  *       problems or have suggestions please contact the author.

0025  *

0026  * \note Version 5.1 is now compatible with boost up to version 1.59. Thanks to

0027  *       ecotax for pointing to the issue with shared_ptr_helper.

0028  *

0029  * \note Version 5.0 is now compatible with boost up to version 1.49 and enables

0030  *       serialization of std::wstring by converting it to/from utf8 (thanks to

0031  *       Arash Abghari for this suggestion). With that all unit tests from the

0032  *       serialization library pass again with the notable exception of user

0033  *       defined primitive types. Those are not supported and as a result any

0034  *       user defined type to be used with the portable archives are required 

0035  *       to be at least object_serializable.

0036  *

0037  * \note Version 4.2 maintains compatibility with the latest boost 1.45 and adds

0038  *       serialization of special floating point values inf and NaN as proposed

0039  *       by Francois Mauger.

0040  *

0041  * \note Version 4.1 makes the archives work together with boost 1.40 and 1.41.

0042  *       Thanks to Francois Mauger for his suggestions.

0043  *

0044  * \note Version 4 removes one level of the inheritance hierarchy and directly

0045  *       builds upon binary primitive and basic binary archive, thereby fixing

0046  *       the last open issue regarding array serialization. Thanks to Robert

0047  *       Ramey for the hint.

0048  *

0049  * \note A few fixes introduced in version 3.1 let the archives pass all of the

0050  *       serialization tests. Thanks to Sergey Morozov for running the tests.

0051  *       Wouter Bijlsma pointed out where to find the fp_utilities and endian

0052  *       libraries headers inside the boost distribution. I would never have

0053  *       found them so thank him it works out of the box since boost 1.36.

0054  *

0055  * \note With Version 3.0 the archives have been made portable across different

0056  *       boost versions. For that purpose a header is added to the data that

0057  *       supplies the underlying serialization library version. Backwards

0058  *       compatibility is maintained by assuming library version boost 1.33 if

0059  *       the iarchive is created using the no_header flag. Whether a header is

0060  *       present or not can be guessed by peeking into the stream: the header's

0061  *       first byte is the magic number 127 coinciding with 'e'|'o'|'s' :-)

0062  *

0063  * \note Version 2.1 removes several compiler warnings and enhances floating

0064  *       point diagnostics to inform the user if some preconditions are violated

0065  *       on his platform. We do not strive for the universally portable solution

0066  *       in binary floating point serialization as desired by some boost users.

0067  *       Instead we support only the most widely used IEEE 754 format and try to

0068  *       detect when requirements are not met and hence our approach must fail.

0069  *       Contributions we made by Johan Rade and Ákos Maróy.

0070  *

0071  * \note Version 2.0 fixes a serious bug that effectively transformed most

0072  *       of negative integral values into positive values! For example the two

0073  *       numbers -12 and 234 were stored in the same 8-bit pattern and later

0074  *       always restored to 234. This was fixed in this version in a way that

0075  *       does not change the interpretation of existing archives that did work

0076  *       because there were no negative numbers. The other way round archives

0077  *       created by version 2.0 and containing negative numbers will raise an

0078  *       integer type size exception when reading it with version 1.0. Thanks

0079  *       to Markus Frohnmaier for testing the archives and finding the bug.

0080  *

0081  * \copyright The boost software license applies.

0082  */
0083 /*****************************************************************************/
0084 
0085 #ifndef CondFormats_Serialization_portable_iarchive_hpp
0086 #define CondFormats_Serialization_portable_iarchive_hpp
0087 
0088 #include <istream>
0089 
0090 // basic headers

0091 #include <boost/version.hpp>
0092 #include <boost/utility/enable_if.hpp>
0093 #include <boost/archive/basic_binary_iprimitive.hpp>
0094 #include <boost/archive/basic_binary_iarchive.hpp>
0095 
0096 #if BOOST_VERSION >= 103500 && BOOST_VERSION < 105600
0097 #include <boost/archive/shared_ptr_helper.hpp>
0098 #endif
0099 
0100 // funny polymorphics

0101 #if BOOST_VERSION < 103500
0102 #include <boost/archive/detail/polymorphic_iarchive_impl.hpp>
0103 #define POLYMORPHIC(T) boost::archive::detail::polymorphic_iarchive_impl<T>
0104 
0105 #elif BOOST_VERSION < 103600
0106 #include <boost/archive/detail/polymorphic_iarchive_dispatch.hpp>
0107 #define POLYMORPHIC(T) boost::archive::detail::polymorphic_iarchive_dispatch<T>
0108 
0109 #else
0110 #include <boost/archive/detail/polymorphic_iarchive_route.hpp>
0111 #define POLYMORPHIC(T) boost::archive::detail::polymorphic_iarchive_route<T>
0112 #endif
0113 
0114 // endian and fpclassify

0115 #include <boost/math/special_functions/fpclassify.hpp>
0116 #include <boost/endian/conversion.hpp>
0117 
0118 // namespace alias

0119 #if BOOST_VERSION < 103800
0120 namespace fp = boost::math;
0121 #elif BOOST_VERSION >= 106900
0122 namespace fp = boost::math;
0123 #else
0124 namespace fp = boost::spirit::math;
0125 #endif
0126 
0127 #if BOOST_VERSION >= 104500 && !defined BOOST_NO_STD_WSTRING
0128 // used for wstring to utf8 conversion

0129 #include <boost/program_options/config.hpp>
0130 #include <boost/program_options/detail/convert.hpp>
0131 #endif
0132 
0133 // generic type traits for numeric types

0134 #include <boost/type_traits/is_integral.hpp>
0135 #include <boost/type_traits/is_unsigned.hpp>
0136 #include <boost/type_traits/is_arithmetic.hpp>
0137 #include <boost/type_traits/is_floating_point.hpp>
0138 
0139 #include "portable_archive_exception.hpp"
0140 
0141 // hint from Johan Rade: on VMS there is still support for

0142 // the VAX floating point format and this macro detects it

0143 #if defined(__vms) && defined(__DECCXX) && !__IEEE_FLOAT
0144 #error "VAX floating point format is not supported!"
0145 #endif
0146 
0147 namespace eos {
0148 
0149   // forward declaration

0150   class portable_iarchive;
0151 
0152   typedef boost::archive::basic_binary_iprimitive<portable_iarchive
0153 #if BOOST_VERSION < 103400
0154                                                   ,
0155                                                   std::istream
0156 #else
0157                                                   ,
0158                                                   std::istream::char_type,
0159                                                   std::istream::traits_type
0160 #endif
0161                                                   >
0162       portable_iprimitive;
0163 
0164   /**

0165      * \brief Portable binary input archive using little endian format.

0166      *

0167      * This archive addresses integer size, endianness and floating point types so

0168      * that data can be transferred across different systems. There may still be

0169      * constraints as to what systems are compatible and the user will have to take

0170      * care that e.g. a very large int being saved on a 64 bit machine will result

0171      * in a portable_archive_exception if loaded into an int on a 32 bit system.

0172      * A possible workaround to this would be to use fixed types like

0173      * boost::uint64_t in your serialization structures.

0174      *

0175      * \note The class is based on the portable binary example by Robert Ramey and

0176      *       uses Beman Dawes endian library plus fp_utilities by Johan Rade.

0177      */
0178   class portable_iarchive : public portable_iprimitive
0179 
0180       // the example derives from common_oarchive but that lacks the

0181       // load_override functions so we chose to stay one level higher

0182       ,
0183                             public boost::archive::basic_binary_iarchive<portable_iarchive>
0184 #if BOOST_VERSION >= 103500 && BOOST_VERSION < 105600
0185       // mix-in helper class for serializing shared_ptr

0186       ,
0187                             public boost::archive::detail::shared_ptr_helper
0188 #endif
0189   {
0190     // only needed for Robert's hack in basic_binary_iarchive::init

0191     friend class boost::archive::basic_binary_iarchive<portable_iarchive>;
0192 
0193     // workaround for gcc: use a dummy struct

0194     // as additional argument type for overloading

0195     template <int>
0196     struct dummy {
0197       dummy(int) {}
0198     };
0199 
0200     // loads directly from stream

0201     inline signed char load_signed_char() {
0202       signed char c;
0203       portable_iprimitive::load(c);
0204       return c;
0205     }
0206 
0207     // archive initialization

0208     void init(unsigned flags) {
0209       using namespace boost::archive;
0210       archive_version_type input_library_version(3);
0211 
0212       // it is vital to have version information!

0213       // if we don't have any we assume boost 1.33

0214       if (flags & no_header)
0215         set_library_version(input_library_version);
0216 
0217       // extract and check the magic eos byte

0218       else if (load_signed_char() != magic_byte)
0219         throw archive_exception(archive_exception::invalid_signature);
0220 
0221       else {
0222         // extract version information

0223         operator>>(input_library_version);
0224 
0225         // throw if file version is newer than we are

0226         if (input_library_version > archive_version)
0227           throw archive_exception(archive_exception::unsupported_version);
0228 
0229         // else set the library version accordingly

0230         else
0231           set_library_version(input_library_version);
0232       }
0233     }
0234 
0235   public:
0236     /**

0237          * \brief Constructor on a stream using ios::binary mode!

0238          *

0239          * We cannot call basic_binary_iprimitive::init which tries to detect

0240          * if the binary archive stems from a different platform by examining

0241          * type sizes.

0242          *

0243          * We could have called basic_binary_iarchive::init which would create

0244          * the boost::serialization standard archive header containing also the

0245          * library version. Due to efficiency we stick with our own.

0246          */
0247     portable_iarchive(std::istream& is, unsigned flags = 0)
0248 #if BOOST_VERSION < 103400
0249         : portable_iprimitive(is, flags & boost::archive::no_codecvt)
0250 #else
0251         : portable_iprimitive(*is.rdbuf(), flags & boost::archive::no_codecvt)
0252 #endif
0253           ,
0254           boost::archive::basic_binary_iarchive<portable_iarchive>(flags) {
0255       init(flags);
0256     }
0257 
0258 #if BOOST_VERSION >= 103400
0259     portable_iarchive(std::streambuf& sb, unsigned flags = 0)
0260         : portable_iprimitive(sb, flags & boost::archive::no_codecvt),
0261           boost::archive::basic_binary_iarchive<portable_iarchive>(flags) {
0262       init(flags);
0263     }
0264 #endif
0265 
0266     //! Load narrow strings.

0267     void load(std::string& s) { portable_iprimitive::load(s); }
0268 
0269 #ifndef BOOST_NO_STD_WSTRING
0270     /**

0271          * \brief Load wide strings.

0272          *

0273          * This is rather tricky to get right for true portability as there

0274          * are so many different character encodings around. However, wide

0275          * strings that are encoded in one of the Unicode schemes only need

0276          * to be _transcoded_ which is a lot easier actually.

0277          *

0278          * We generate the output string to be encoded in the system's native

0279          * format, ie. UTF-16 on Windows and UTF-32 on Linux machines. Don't

0280          * know about Mac here so I can't really say about that.

0281          */
0282     void load(std::wstring& s) {
0283       std::string utf8;
0284       load(utf8);
0285       s = boost::from_utf8(utf8);
0286     }
0287 #endif
0288 
0289     /**

0290          * \brief Loading bool type.

0291          *

0292          * Byte pattern is same as with integer types, so this function

0293          * is somewhat redundant but treating bool as integer generates

0294          * a lot of compiler warnings.

0295          *

0296          * \note If you cannot compile your application and it says something

0297          * about load(bool) cannot convert your type A& into bool& then you

0298          * should check your BOOST_CLASS_IMPLEMENTATION setting for A, as

0299          * portable_archive is not able to handle custom primitive types in

0300          * a general manner.

0301          */
0302     void load(bool& b) {
0303       switch (signed char c = load_signed_char()) {
0304         case 0:
0305           b = false;
0306           break;
0307         case 1:
0308           b = load_signed_char();
0309           break;
0310         default:
0311           throw portable_archive_exception(c);
0312       }
0313     }
0314 
0315     /**

0316          * \brief Load integer types.

0317          *

0318          * First we load the size information ie. the number of bytes that 

0319          * hold the actual data. Then we retrieve the data and transform it

0320          * to the original value by using load_little_endian.

0321          */
0322     template <typename T>
0323     typename boost::enable_if<boost::is_integral<T> >::type load(T& t, dummy<2> = 0) {
0324       // get the number of bytes in the stream

0325       if (signed char size = load_signed_char()) {
0326         // check for negative value in unsigned type

0327         if (size < 0 && boost::is_unsigned<T>::value)
0328           throw portable_archive_exception();
0329 
0330         // check that our type T is large enough

0331         else if ((unsigned)abs(size) > sizeof(T))
0332           throw portable_archive_exception(size);
0333 
0334         // reconstruct the value

0335         T temp = size < 0 ? -1 : 0;
0336         load_binary(&temp, abs(size));
0337 
0338         // load the value from little endian - it is then converted

0339         // to the target type T and fits it because size <= sizeof(T)

0340         t = boost::endian::little_to_native(temp);
0341       }
0342 
0343       else
0344         t = 0;  // zero optimization

0345     }
0346 
0347     /** 

0348          * \brief Load floating point types.

0349          * 

0350          * We simply rely on fp_traits_non_native to set the bit pattern from the (unsigned)

0351          * integral type that was stored in the stream. Francois Mauger provided

0352          * standardized behaviour for special values like inf and NaN, that need to

0353          * be serialized in his application.

0354          *

0355          * \note by Johan Rade (author of the floating point utilities library):

0356          * Be warned that the math::detail::fp_traits_non_native<T,U>::get_bits() function

0357          * is *not* guaranteed to give you all bits of the floating point number. It

0358          * will give you all bits if and only if there is an integer type that has

0359          * the same size as the floating point you are copying from. It will not

0360          * give you all bits for double if there is no uint64_t. It will not give

0361          * you all bits for long double if sizeof(long double) > 8 or there is no

0362          * uint64_t. 

0363          * 

0364          * The member fp_traits<T>::type::coverage will tell you whether all bits

0365          * are copied. This is a typedef for either math::detail::all_bits or

0366          * math::detail::not_all_bits. 

0367          * 

0368          * If the function does not copy all bits, then it will copy the most

0369          * significant bits. So if you serialize and deserialize the way you

0370          * describe, and fp_traits<T>::type::coverage is math::detail::not_all_bits,

0371          * then your floating point numbers will be truncated. This will introduce

0372          * small rounding off errors. 

0373          */
0374     template <typename T>
0375     typename boost::enable_if<boost::is_floating_point<T> >::type load(T& t, dummy<3> = 0) {
0376       typedef typename fp::detail::size_to_precision<sizeof(T), ::std::is_floating_point<T>::value>::type precision;
0377       typedef typename fp::detail::fp_traits_non_native<T, precision> traits;
0378 
0379       // if you end here there are three possibilities:

0380       // 1. you're serializing a long double which is not portable

0381       // 2. you're serializing a double but have no 64 bit integer

0382       // 3. your machine is using an unknown floating point format

0383       // after reading the note above you still might decide to

0384       // deactivate this static assert and try if it works out.

0385       typename traits::bits bits;
0386       static_assert(sizeof(bits) == sizeof(T));
0387       static_assert(std::numeric_limits<T>::is_iec559);
0388 
0389       load(bits);
0390       traits::set_bits(t, bits);
0391 
0392       // if the no_infnan flag is set we must throw here

0393       if (get_flags() & no_infnan && !fp::isfinite(t))
0394         throw portable_archive_exception(t);
0395 
0396       // if you end here your floating point type does not support

0397       // denormalized numbers. this might be the case even though

0398       // your type conforms to IEC 559 (and thus to IEEE 754)

0399       if (std::numeric_limits<T>::has_denorm == std::denorm_absent && fp::fpclassify(t) == (int)FP_SUBNORMAL)  // GCC4

0400         throw portable_archive_exception(t);
0401     }
0402 
0403     // in boost 1.44 version_type was splitted into library_version_type and

0404     // item_version_type, plus a whole bunch of additional strong typedefs.

0405     template <typename T>
0406     typename boost::disable_if<boost::is_arithmetic<T> >::type load(T& t, dummy<4> = 0) {
0407       // we provide a generic load routine for all types that feature

0408       // conversion operators into an unsigned integer value like those

0409       // created through BOOST_STRONG_TYPEDEF(X, some unsigned int) like

0410       // library_version_type, collection_size_type, item_version_type,

0411       // class_id_type, object_id_type, version_type and tracking_type

0412       load((typename boost::uint_t<sizeof(T) * CHAR_BIT>::least&)(t));
0413     }
0414   };
0415 
0416   // polymorphic portable binary iarchive typedef

0417   typedef POLYMORPHIC(portable_iarchive) polymorphic_portable_iarchive;
0418 #undef POLYMORPHIC
0419 
0420 }  // namespace eos

0421 
0422 // this is required by export which registers all of your

0423 // classes with all the inbuilt archives plus our archive.

0424 #if BOOST_VERSION < 103500
0425 #define BOOST_ARCHIVE_CUSTOM_IARCHIVE_TYPES eos::portable_iarchive
0426 #else
0427 BOOST_SERIALIZATION_REGISTER_ARCHIVE(eos::portable_iarchive)
0428 BOOST_SERIALIZATION_REGISTER_ARCHIVE(eos::polymorphic_portable_iarchive)
0429 #endif
0430 
0431 // if you include this header multiple times and your compiler is picky

0432 // about multiple template instantiations (eg. gcc is) then you need to

0433 // define NO_EXPLICIT_TEMPLATE_INSTANTIATION before every include but one

0434 // or you move the instantiation section into an implementation file

0435 // #ifndef NO_EXPLICIT_TEMPLATE_INSTANTIATION

0436 //

0437 // #include <boost/archive/impl/basic_binary_iarchive.ipp>

0438 // #include <boost/archive/impl/basic_binary_iprimitive.ipp>

0439 //

0440 // #if BOOST_VERSION < 104000

0441 // #include <boost/archive/impl/archive_pointer_iserializer.ipp>

0442 // #elif !defined BOOST_ARCHIVE_SERIALIZER_INCLUDED

0443 // #include <boost/archive/impl/archive_serializer_map.ipp>

0444 // #define BOOST_ARCHIVE_SERIALIZER_INCLUDED

0445 // #endif

0446 //

0447 // namespace boost {

0448 //   namespace archive {

0449 //

0450 //     // explicitly instantiate for this type of binary stream

0451 //     template class basic_binary_iarchive<eos::portable_iarchive>;

0452 //

0453 //     template class basic_binary_iprimitive<eos::portable_iarchive

0454 // #if BOOST_VERSION < 103400

0455 //                                            ,

0456 //                                            std::istream

0457 // #else

0458 //                                            ,

0459 //                                            std::istream::char_type,

0460 //                                            std::istream::traits_type

0461 // #endif

0462 //                                            >;

0463 //

0464 // #if BOOST_VERSION < 104000

0465 //     template class detail::archive_pointer_iserializer<eos::portable_iarchive>;

0466 // #else

0467 //     template class detail::archive_serializer_map<eos::portable_iarchive>;

0468 //     //template class detail::archive_serializer_map<eos::polymorphic_portable_iarchive>;

0469 // #endif

0470 //

0471 //   }  // namespace archive

0472 // }  // namespace boost

0473 //

0474 // #endif

0475 
0476 #endif