You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

987 lines
41 KiB

7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*! \file cereal.hpp
  2. \brief Main cereal functionality */
  3. /*
  4. Copyright (c) 2014, Randolph Voorhies, Shane Grant
  5. All rights reserved.
  6. Redistribution and use in source and binary forms, with or without
  7. modification, are permitted provided that the following conditions are met:
  8. * Redistributions of source code must retain the above copyright
  9. notice, this list of conditions and the following disclaimer.
  10. * Redistributions in binary form must reproduce the above copyright
  11. notice, this list of conditions and the following disclaimer in the
  12. documentation and/or other materials provided with the distribution.
  13. * Neither the name of cereal nor the
  14. names of its contributors may be used to endorse or promote products
  15. derived from this software without specific prior written permission.
  16. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  17. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY
  20. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #ifndef CEREAL_CEREAL_HPP_
  28. #define CEREAL_CEREAL_HPP_
  29. #include <type_traits>
  30. #include <string>
  31. #include <memory>
  32. #include <unordered_map>
  33. #include <unordered_set>
  34. #include <vector>
  35. #include <cstddef>
  36. #include <cstdint>
  37. #include <functional>
  38. #include "cereal/macros.hpp"
  39. #include "cereal/details/traits.hpp"
  40. #include "cereal/details/helpers.hpp"
  41. #include "cereal/types/base_class.hpp"
  42. namespace cereal
  43. {
  44. // ######################################################################
  45. //! Creates a name value pair
  46. /*! @relates NameValuePair
  47. @ingroup Utility */
  48. template <class T> inline
  49. NameValuePair<T> make_nvp( std::string const & name, T && value )
  50. {
  51. return {name.c_str(), std::forward<T>(value)};
  52. }
  53. //! Creates a name value pair
  54. /*! @relates NameValuePair
  55. @ingroup Utility */
  56. template <class T> inline
  57. NameValuePair<T> make_nvp( const char * name, T && value )
  58. {
  59. return {name, std::forward<T>(value)};
  60. }
  61. //! Creates a name value pair for the variable T with the same name as the variable
  62. /*! @relates NameValuePair
  63. @ingroup Utility */
  64. #define CEREAL_NVP(T) ::cereal::make_nvp(#T, T)
  65. // ######################################################################
  66. //! Convenience function to create binary data for both const and non const pointers
  67. /*! @param data Pointer to beginning of the data
  68. @param size The size in bytes of the data
  69. @relates BinaryData
  70. @ingroup Utility */
  71. template <class T> inline
  72. BinaryData<T> binary_data( T && data, size_t size )
  73. {
  74. return {std::forward<T>(data), size};
  75. }
  76. // ######################################################################
  77. //! Creates a size tag from some variable.
  78. /*! Will normally be used to serialize size (e.g. size()) information for
  79. variable size containers. If you have a variable sized container,
  80. the very first thing it serializes should be its size, wrapped in
  81. a SizeTag.
  82. @relates SizeTag
  83. @ingroup Utility */
  84. template <class T> inline
  85. SizeTag<T> make_size_tag( T && sz )
  86. {
  87. return {std::forward<T>(sz)};
  88. }
  89. // ######################################################################
  90. //! Called before a type is serialized to set up any special archive state
  91. //! for processing some type
  92. /*! If designing a serializer that needs to set up any kind of special
  93. state or output extra information for a type, specialize this function
  94. for the archive type and the types that require the extra information.
  95. @ingroup Internal */
  96. template <class Archive, class T> inline
  97. void prologue( Archive & /* archive */, T const & /* data */)
  98. { }
  99. //! Called after a type is serialized to tear down any special archive state
  100. //! for processing some type
  101. /*! @ingroup Internal */
  102. template <class Archive, class T> inline
  103. void epilogue( Archive & /* archive */, T const & /* data */)
  104. { }
  105. // ######################################################################
  106. //! Special flags for archives
  107. /*! AllowEmptyClassElision
  108. This allows for empty classes to be serialized even if they do not provide
  109. a serialization function. Classes with no data members are considered to be
  110. empty. Be warned that if this is enabled and you attempt to serialize an
  111. empty class with improperly formed serialize or load/save functions, no
  112. static error will occur - the error will propogate silently and your
  113. intended serialization functions may not be called. You can manually
  114. ensure that your classes that have custom serialization are correct
  115. by using the traits is_output_serializable and is_input_serializable
  116. in cereal/details/traits.hpp.
  117. @ingroup Internal */
  118. enum Flags { AllowEmptyClassElision = 1 };
  119. // ######################################################################
  120. //! Registers a specific Archive type with cereal
  121. /*! This registration should be done once per archive. A good place to
  122. put this is immediately following the definition of your archive.
  123. Archive registration is only strictly necessary if you wish to
  124. support pointers to polymorphic data types. All archives that
  125. come with cereal are already registered.
  126. @ingroup Internal */
  127. #define CEREAL_REGISTER_ARCHIVE(Archive) \
  128. namespace cereal { namespace detail { \
  129. template <class T, class BindingTag> \
  130. typename polymorphic_serialization_support<Archive, T>::type \
  131. instantiate_polymorphic_binding( T*, Archive*, BindingTag, adl_tag ); \
  132. } } /* end namespaces */
  133. // ######################################################################
  134. //! Defines a class version for some type
  135. /*! Versioning information is optional and adds some small amount of
  136. overhead to serialization. This overhead will occur both in terms of
  137. space in the archive (the version information for each class will be
  138. stored exactly once) as well as runtime (versioned serialization functions
  139. must check to see if they need to load or store version information).
  140. Versioning is useful if you plan on fundamentally changing the way some
  141. type is serialized in the future. Versioned serialization functions
  142. cannot be used to load non-versioned data.
  143. By default, all types have an assumed version value of zero. By
  144. using this macro, you may change the version number associated with
  145. some type. cereal will then use this value as a second parameter
  146. to your serialization functions.
  147. The interface for the serialization functions is nearly identical
  148. to non-versioned serialization with the addition of a second parameter,
  149. const std::uint32_t version, which will be supplied with the correct
  150. version number. Serializing the version number on a save happens
  151. automatically.
  152. Versioning cannot be mixed with non-versioned serialization functions.
  153. Having both types will result result in a compile time error. Data
  154. serialized without versioning cannot be loaded by a serialization
  155. function with added versioning support.
  156. Example interface for versioning on a non-member serialize function:
  157. @code{cpp}
  158. CEREAL_CLASS_VERSION( Mytype, 77 ); // register class version
  159. template <class Archive>
  160. void serialize( Archive & ar, Mytype & t, const std::uint32_t version )
  161. {
  162. // When performing a load, the version associated with the class
  163. // is whatever it was when that data was originally serialized
  164. //
  165. // When we save, we'll use the version that is defined in the macro
  166. if( version >= some_number )
  167. // do this
  168. else
  169. // do that
  170. }
  171. @endcode
  172. Interfaces for other forms of serialization functions is similar. This
  173. macro should be placed at global scope.
  174. @ingroup Utility */
  175. #define CEREAL_CLASS_VERSION(TYPE, VERSION_NUMBER) \
  176. namespace cereal { namespace detail { \
  177. template <> struct Version<TYPE> \
  178. { \
  179. static const std::uint32_t version; \
  180. static std::uint32_t registerVersion() \
  181. { \
  182. ::cereal::detail::StaticObject<Versions>::getInstance().mapping.emplace( \
  183. std::type_index(typeid(TYPE)).hash_code(), VERSION_NUMBER ); \
  184. return VERSION_NUMBER; \
  185. } \
  186. static void unused() { (void)version; } \
  187. }; /* end Version */ \
  188. const std::uint32_t Version<TYPE>::version = \
  189. Version<TYPE>::registerVersion(); \
  190. } } // end namespaces
  191. // ######################################################################
  192. //! The base output archive class
  193. /*! This is the base output archive for all output archives. If you create
  194. a custom archive class, it should derive from this, passing itself as
  195. a template parameter for the ArchiveType.
  196. The base class provides all of the functionality necessary to
  197. properly forward data to the correct serialization functions.
  198. Individual archives should use a combination of prologue and
  199. epilogue functions together with specializations of serialize, save,
  200. and load to alter the functionality of their serialization.
  201. @tparam ArchiveType The archive type that derives from OutputArchive
  202. @tparam Flags Flags to control advanced functionality. See the Flags
  203. enum for more information.
  204. @ingroup Internal */
  205. template<class ArchiveType, std::uint32_t Flags = 0>
  206. class OutputArchive : public detail::OutputArchiveBase
  207. {
  208. public:
  209. //! Construct the output archive
  210. /*! @param derived A pointer to the derived ArchiveType (pass this from the derived archive) */
  211. OutputArchive(ArchiveType * const derived) : self(derived), itsCurrentPointerId(1), itsCurrentPolymorphicTypeId(1)
  212. { }
  213. OutputArchive & operator=( OutputArchive const & ) = delete;
  214. //! Serializes all passed in data
  215. /*! This is the primary interface for serializing data with an archive */
  216. template <class ... Types> inline
  217. ArchiveType & operator()( Types && ... args )
  218. {
  219. self->process( std::forward<Types>( args )... );
  220. return *self;
  221. }
  222. /*! @name Boost Transition Layer
  223. Functionality that mirrors the syntax for Boost. This is useful if you are transitioning
  224. a large project from Boost to cereal. The preferred interface for cereal is using operator(). */
  225. //! @{
  226. //! Indicates this archive is not intended for loading
  227. /*! This ensures compatibility with boost archive types. If you are transitioning
  228. from boost, you can check this value within a member or external serialize function
  229. (i.e., Archive::is_loading::value) to disable behavior specific to loading, until
  230. you can transition to split save/load or save_minimal/load_minimal functions */
  231. using is_loading = std::false_type;
  232. //! Indicates this archive is intended for saving
  233. /*! This ensures compatibility with boost archive types. If you are transitioning
  234. from boost, you can check this value within a member or external serialize function
  235. (i.e., Archive::is_saving::value) to enable behavior specific to loading, until
  236. you can transition to split save/load or save_minimal/load_minimal functions */
  237. using is_saving = std::true_type;
  238. //! Serializes passed in data
  239. /*! This is a boost compatability layer and is not the preferred way of using
  240. cereal. If you are transitioning from boost, use this until you can
  241. transition to the operator() overload */
  242. template <class T> inline
  243. ArchiveType & operator&( T && arg )
  244. {
  245. self->process( std::forward<T>( arg ) );
  246. return *self;
  247. }
  248. //! Serializes passed in data
  249. /*! This is a boost compatability layer and is not the preferred way of using
  250. cereal. If you are transitioning from boost, use this until you can
  251. transition to the operator() overload */
  252. template <class T> inline
  253. ArchiveType & operator<<( T && arg )
  254. {
  255. self->process( std::forward<T>( arg ) );
  256. return *self;
  257. }
  258. //! @}
  259. //! Registers a shared pointer with the archive
  260. /*! This function is used to track shared pointer targets to prevent
  261. unnecessary saves from taking place if multiple shared pointers
  262. point to the same data.
  263. @internal
  264. @param addr The address (see shared_ptr get()) pointed to by the shared pointer
  265. @return A key that uniquely identifies the pointer */
  266. inline std::uint32_t registerSharedPointer( void const * addr )
  267. {
  268. // Handle null pointers by just returning 0
  269. if(addr == 0) return 0;
  270. auto id = itsSharedPointerMap.find( addr );
  271. if( id == itsSharedPointerMap.end() )
  272. {
  273. auto ptrId = itsCurrentPointerId++;
  274. itsSharedPointerMap.insert( {addr, ptrId} );
  275. return ptrId | detail::msb_32bit; // mask MSB to be 1
  276. }
  277. else
  278. return id->second;
  279. }
  280. //! Registers a polymorphic type name with the archive
  281. /*! This function is used to track polymorphic types to prevent
  282. unnecessary saves of identifying strings used by the polymorphic
  283. support functionality.
  284. @internal
  285. @param name The name to associate with a polymorphic type
  286. @return A key that uniquely identifies the polymorphic type name */
  287. inline std::uint32_t registerPolymorphicType( char const * name )
  288. {
  289. auto id = itsPolymorphicTypeMap.find( name );
  290. if( id == itsPolymorphicTypeMap.end() )
  291. {
  292. auto polyId = itsCurrentPolymorphicTypeId++;
  293. itsPolymorphicTypeMap.insert( {name, polyId} );
  294. return polyId | detail::msb_32bit; // mask MSB to be 1
  295. }
  296. else
  297. return id->second;
  298. }
  299. private:
  300. //! Serializes data after calling prologue, then calls epilogue
  301. template <class T> inline
  302. void process( T && head )
  303. {
  304. prologue( *self, head );
  305. self->processImpl( head );
  306. epilogue( *self, head );
  307. }
  308. //! Unwinds to process all data
  309. template <class T, class ... Other> inline
  310. void process( T && head, Other && ... tail )
  311. {
  312. self->process( std::forward<T>( head ) );
  313. self->process( std::forward<Other>( tail )... );
  314. }
  315. //! Serialization of a virtual_base_class wrapper
  316. /*! \sa virtual_base_class */
  317. template <class T> inline
  318. ArchiveType & processImpl(virtual_base_class<T> const & b)
  319. {
  320. traits::detail::base_class_id id(b.base_ptr);
  321. if(itsBaseClassSet.count(id) == 0)
  322. {
  323. itsBaseClassSet.insert(id);
  324. self->processImpl( *b.base_ptr );
  325. }
  326. return *self;
  327. }
  328. //! Serialization of a base_class wrapper
  329. /*! \sa base_class */
  330. template <class T> inline
  331. ArchiveType & processImpl(base_class<T> const & b)
  332. {
  333. self->processImpl( *b.base_ptr );
  334. return *self;
  335. }
  336. //! Helper macro that expands the requirements for activating an overload
  337. /*! Requirements:
  338. Has the requested serialization function
  339. Does not have version and unversioned at the same time
  340. Is output serializable AND
  341. is specialized for this type of function OR
  342. has no specialization at all */
  343. #define PROCESS_IF(name) \
  344. traits::EnableIf<traits::has_##name<T, ArchiveType>::value, \
  345. !traits::has_invalid_output_versioning<T, ArchiveType>::value, \
  346. (traits::is_output_serializable<T, ArchiveType>::value && \
  347. (traits::is_specialized_##name<T, ArchiveType>::value || \
  348. !traits::is_specialized<T, ArchiveType>::value))> = traits::sfinae
  349. //! Member serialization
  350. template <class T, PROCESS_IF(member_serialize)> inline
  351. ArchiveType & processImpl(T const & t)
  352. {
  353. access::member_serialize(*self, const_cast<T &>(t));
  354. return *self;
  355. }
  356. //! Non member serialization
  357. template <class T, PROCESS_IF(non_member_serialize)> inline
  358. ArchiveType & processImpl(T const & t)
  359. {
  360. CEREAL_SERIALIZE_FUNCTION_NAME(*self, const_cast<T &>(t));
  361. return *self;
  362. }
  363. //! Member split (save)
  364. template <class T, PROCESS_IF(member_save)> inline
  365. ArchiveType & processImpl(T const & t)
  366. {
  367. access::member_save(*self, t);
  368. return *self;
  369. }
  370. //! Non member split (save)
  371. template <class T, PROCESS_IF(non_member_save)> inline
  372. ArchiveType & processImpl(T const & t)
  373. {
  374. CEREAL_SAVE_FUNCTION_NAME(*self, t);
  375. return *self;
  376. }
  377. //! Member split (save_minimal)
  378. template <class T, PROCESS_IF(member_save_minimal)> inline
  379. ArchiveType & processImpl(T const & t)
  380. {
  381. self->process( access::member_save_minimal(*self, t) );
  382. return *self;
  383. }
  384. //! Non member split (save_minimal)
  385. template <class T, PROCESS_IF(non_member_save_minimal)> inline
  386. ArchiveType & processImpl(T const & t)
  387. {
  388. self->process( CEREAL_SAVE_MINIMAL_FUNCTION_NAME(*self, t) );
  389. return *self;
  390. }
  391. //! Empty class specialization
  392. template <class T, traits::EnableIf<(Flags & AllowEmptyClassElision),
  393. !traits::is_output_serializable<T, ArchiveType>::value,
  394. std::is_empty<T>::value> = traits::sfinae> inline
  395. ArchiveType & processImpl(T const &)
  396. {
  397. return *self;
  398. }
  399. //! No matching serialization
  400. /*! Invalid if we have invalid output versioning or
  401. we are not output serializable, and either
  402. don't allow empty class ellision or allow it but are not serializing an empty class */
  403. template <class T, traits::EnableIf<traits::has_invalid_output_versioning<T, ArchiveType>::value ||
  404. (!traits::is_output_serializable<T, ArchiveType>::value &&
  405. (!(Flags & AllowEmptyClassElision) || ((Flags & AllowEmptyClassElision) && !std::is_empty<T>::value)))> = traits::sfinae> inline
  406. ArchiveType & processImpl(T const &)
  407. {
  408. static_assert(traits::detail::count_output_serializers<T, ArchiveType>::value != 0,
  409. "cereal could not find any output serialization functions for the provided type and archive combination. \n\n "
  410. "Types must either have a serialize function, load/save pair, or load_minimal/save_minimal pair (you may not mix these). \n "
  411. "Serialize functions generally have the following signature: \n\n "
  412. "template<class Archive> \n "
  413. " void serialize(Archive & ar) \n "
  414. " { \n "
  415. " ar( member1, member2, member3 ); \n "
  416. " } \n\n " );
  417. static_assert(traits::detail::count_output_serializers<T, ArchiveType>::value < 2,
  418. "cereal found more than one compatible output serialization function for the provided type and archive combination. \n\n "
  419. "Types must either have a serialize function, load/save pair, or load_minimal/save_minimal pair (you may not mix these). \n "
  420. "Use specialization (see access.hpp) if you need to disambiguate between serialize vs load/save functions. \n "
  421. "Note that serialization functions can be inherited which may lead to the aforementioned ambiguities. \n "
  422. "In addition, you may not mix versioned with non-versioned serialization functions. \n\n ");
  423. return *self;
  424. }
  425. //! Registers a class version with the archive and serializes it if necessary
  426. /*! If this is the first time this class has been serialized, we will record its
  427. version number and serialize that.
  428. @tparam T The type of the class being serialized
  429. @param version The version number associated with it */
  430. template <class T> inline
  431. std::uint32_t registerClassVersion()
  432. {
  433. static const auto hash = std::type_index(typeid(T)).hash_code();
  434. const auto insertResult = itsVersionedTypes.insert( hash );
  435. const auto lock = detail::StaticObject<detail::Versions>::lock();
  436. const auto version =
  437. detail::StaticObject<detail::Versions>::getInstance().find( hash, detail::Version<T>::version );
  438. if( insertResult.second ) // insertion took place, serialize the version number
  439. process( make_nvp<ArchiveType>("cereal_class_version", version) );
  440. return version;
  441. }
  442. //! Member serialization
  443. /*! Versioning implementation */
  444. template <class T, PROCESS_IF(member_versioned_serialize)> inline
  445. ArchiveType & processImpl(T const & t)
  446. {
  447. access::member_serialize(*self, const_cast<T &>(t), registerClassVersion<T>());
  448. return *self;
  449. }
  450. //! Non member serialization
  451. /*! Versioning implementation */
  452. template <class T, PROCESS_IF(non_member_versioned_serialize)> inline
  453. ArchiveType & processImpl(T const & t)
  454. {
  455. CEREAL_SERIALIZE_FUNCTION_NAME(*self, const_cast<T &>(t), registerClassVersion<T>());
  456. return *self;
  457. }
  458. //! Member split (save)
  459. /*! Versioning implementation */
  460. template <class T, PROCESS_IF(member_versioned_save)> inline
  461. ArchiveType & processImpl(T const & t)
  462. {
  463. access::member_save(*self, t, registerClassVersion<T>());
  464. return *self;
  465. }
  466. //! Non member split (save)
  467. /*! Versioning implementation */
  468. template <class T, PROCESS_IF(non_member_versioned_save)> inline
  469. ArchiveType & processImpl(T const & t)
  470. {
  471. CEREAL_SAVE_FUNCTION_NAME(*self, t, registerClassVersion<T>());
  472. return *self;
  473. }
  474. //! Member split (save_minimal)
  475. /*! Versioning implementation */
  476. template <class T, PROCESS_IF(member_versioned_save_minimal)> inline
  477. ArchiveType & processImpl(T const & t)
  478. {
  479. self->process( access::member_save_minimal(*self, t, registerClassVersion<T>()) );
  480. return *self;
  481. }
  482. //! Non member split (save_minimal)
  483. /*! Versioning implementation */
  484. template <class T, PROCESS_IF(non_member_versioned_save_minimal)> inline
  485. ArchiveType & processImpl(T const & t)
  486. {
  487. self->process( CEREAL_SAVE_MINIMAL_FUNCTION_NAME(*self, t, registerClassVersion<T>()) );
  488. return *self;
  489. }
  490. #undef PROCESS_IF
  491. private:
  492. ArchiveType * const self;
  493. //! A set of all base classes that have been serialized
  494. std::unordered_set<traits::detail::base_class_id, traits::detail::base_class_id_hash> itsBaseClassSet;
  495. //! Maps from addresses to pointer ids
  496. std::unordered_map<void const *, std::uint32_t> itsSharedPointerMap;
  497. //! The id to be given to the next pointer
  498. std::uint32_t itsCurrentPointerId;
  499. //! Maps from polymorphic type name strings to ids
  500. std::unordered_map<char const *, std::uint32_t> itsPolymorphicTypeMap;
  501. //! The id to be given to the next polymorphic type name
  502. std::uint32_t itsCurrentPolymorphicTypeId;
  503. //! Keeps track of classes that have versioning information associated with them
  504. std::unordered_set<size_type> itsVersionedTypes;
  505. }; // class OutputArchive
  506. // ######################################################################
  507. //! The base input archive class
  508. /*! This is the base input archive for all input archives. If you create
  509. a custom archive class, it should derive from this, passing itself as
  510. a template parameter for the ArchiveType.
  511. The base class provides all of the functionality necessary to
  512. properly forward data to the correct serialization functions.
  513. Individual archives should use a combination of prologue and
  514. epilogue functions together with specializations of serialize, save,
  515. and load to alter the functionality of their serialization.
  516. @tparam ArchiveType The archive type that derives from InputArchive
  517. @tparam Flags Flags to control advanced functionality. See the Flags
  518. enum for more information.
  519. @ingroup Internal */
  520. template<class ArchiveType, std::uint32_t Flags = 0>
  521. class InputArchive : public detail::InputArchiveBase
  522. {
  523. public:
  524. //! Construct the output archive
  525. /*! @param derived A pointer to the derived ArchiveType (pass this from the derived archive) */
  526. InputArchive(ArchiveType * const derived) :
  527. self(derived),
  528. itsBaseClassSet(),
  529. itsSharedPointerMap(),
  530. itsPolymorphicTypeMap(),
  531. itsVersionedTypes()
  532. { }
  533. InputArchive & operator=( InputArchive const & ) = delete;
  534. //! Serializes all passed in data
  535. /*! This is the primary interface for serializing data with an archive */
  536. template <class ... Types> inline
  537. ArchiveType & operator()( Types && ... args )
  538. {
  539. process( std::forward<Types>( args )... );
  540. return *self;
  541. }
  542. /*! @name Boost Transition Layer
  543. Functionality that mirrors the syntax for Boost. This is useful if you are transitioning
  544. a large project from Boost to cereal. The preferred interface for cereal is using operator(). */
  545. //! @{
  546. //! Indicates this archive is intended for loading
  547. /*! This ensures compatibility with boost archive types. If you are transitioning
  548. from boost, you can check this value within a member or external serialize function
  549. (i.e., Archive::is_loading::value) to enable behavior specific to loading, until
  550. you can transition to split save/load or save_minimal/load_minimal functions */
  551. using is_loading = std::true_type;
  552. //! Indicates this archive is not intended for saving
  553. /*! This ensures compatibility with boost archive types. If you are transitioning
  554. from boost, you can check this value within a member or external serialize function
  555. (i.e., Archive::is_saving::value) to disable behavior specific to loading, until
  556. you can transition to split save/load or save_minimal/load_minimal functions */
  557. using is_saving = std::false_type;
  558. //! Serializes passed in data
  559. /*! This is a boost compatability layer and is not the preferred way of using
  560. cereal. If you are transitioning from boost, use this until you can
  561. transition to the operator() overload */
  562. template <class T> inline
  563. ArchiveType & operator&( T && arg )
  564. {
  565. self->process( std::forward<T>( arg ) );
  566. return *self;
  567. }
  568. //! Serializes passed in data
  569. /*! This is a boost compatability layer and is not the preferred way of using
  570. cereal. If you are transitioning from boost, use this until you can
  571. transition to the operator() overload */
  572. template <class T> inline
  573. ArchiveType & operator>>( T && arg )
  574. {
  575. self->process( std::forward<T>( arg ) );
  576. return *self;
  577. }
  578. //! @}
  579. //! Retrieves a shared pointer given a unique key for it
  580. /*! This is used to retrieve a previously registered shared_ptr
  581. which has already been loaded.
  582. @param id The unique id that was serialized for the pointer
  583. @return A shared pointer to the data
  584. @throw Exception if the id does not exist */
  585. inline std::shared_ptr<void> getSharedPointer(std::uint32_t const id)
  586. {
  587. if(id == 0) return std::shared_ptr<void>(nullptr);
  588. auto iter = itsSharedPointerMap.find( id );
  589. if(iter == itsSharedPointerMap.end())
  590. throw Exception("Error while trying to deserialize a smart pointer. Could not find id " + std::to_string(id));
  591. return iter->second;
  592. }
  593. //! Registers a shared pointer to its unique identifier
  594. /*! After a shared pointer has been allocated for the first time, it should
  595. be registered with its loaded id for future references to it.
  596. @param id The unique identifier for the shared pointer
  597. @param ptr The actual shared pointer */
  598. inline void registerSharedPointer(std::uint32_t const id, std::shared_ptr<void> ptr)
  599. {
  600. std::uint32_t const stripped_id = id & ~detail::msb_32bit;
  601. itsSharedPointerMap[stripped_id] = ptr;
  602. }
  603. //! Retrieves the string for a polymorphic type given a unique key for it
  604. /*! This is used to retrieve a string previously registered during
  605. a polymorphic load.
  606. @param id The unique id that was serialized for the polymorphic type
  607. @return The string identifier for the tyep */
  608. inline std::string getPolymorphicName(std::uint32_t const id)
  609. {
  610. auto name = itsPolymorphicTypeMap.find( id );
  611. if(name == itsPolymorphicTypeMap.end())
  612. {
  613. throw Exception("Error while trying to deserialize a polymorphic pointer. Could not find type id " + std::to_string(id));
  614. }
  615. return name->second;
  616. }
  617. //! Registers a polymorphic name string to its unique identifier
  618. /*! After a polymorphic type has been loaded for the first time, it should
  619. be registered with its loaded id for future references to it.
  620. @param id The unique identifier for the polymorphic type
  621. @param name The name associated with the tyep */
  622. inline void registerPolymorphicName(std::uint32_t const id, std::string const & name)
  623. {
  624. std::uint32_t const stripped_id = id & ~detail::msb_32bit;
  625. itsPolymorphicTypeMap.insert( {stripped_id, name} );
  626. }
  627. private:
  628. //! Serializes data after calling prologue, then calls epilogue
  629. template <class T> inline
  630. void process( T && head )
  631. {
  632. prologue( *self, head );
  633. self->processImpl( head );
  634. epilogue( *self, head );
  635. }
  636. //! Unwinds to process all data
  637. template <class T, class ... Other> inline
  638. void process( T && head, Other && ... tail )
  639. {
  640. process( std::forward<T>( head ) );
  641. process( std::forward<Other>( tail )... );
  642. }
  643. //! Serialization of a virtual_base_class wrapper
  644. /*! \sa virtual_base_class */
  645. template <class T> inline
  646. ArchiveType & processImpl(virtual_base_class<T> & b)
  647. {
  648. traits::detail::base_class_id id(b.base_ptr);
  649. if(itsBaseClassSet.count(id) == 0)
  650. {
  651. itsBaseClassSet.insert(id);
  652. self->processImpl( *b.base_ptr );
  653. }
  654. return *self;
  655. }
  656. //! Serialization of a base_class wrapper
  657. /*! \sa base_class */
  658. template <class T> inline
  659. ArchiveType & processImpl(base_class<T> & b)
  660. {
  661. self->processImpl( *b.base_ptr );
  662. return *self;
  663. }
  664. //! Helper macro that expands the requirements for activating an overload
  665. /*! Requirements:
  666. Has the requested serialization function
  667. Does not have version and unversioned at the same time
  668. Is input serializable AND
  669. is specialized for this type of function OR
  670. has no specialization at all */
  671. #define PROCESS_IF(name) \
  672. traits::EnableIf<traits::has_##name<T, ArchiveType>::value, \
  673. !traits::has_invalid_input_versioning<T, ArchiveType>::value, \
  674. (traits::is_input_serializable<T, ArchiveType>::value && \
  675. (traits::is_specialized_##name<T, ArchiveType>::value || \
  676. !traits::is_specialized<T, ArchiveType>::value))> = traits::sfinae
  677. //! Member serialization
  678. template <class T, PROCESS_IF(member_serialize)> inline
  679. ArchiveType & processImpl(T & t)
  680. {
  681. access::member_serialize(*self, t);
  682. return *self;
  683. }
  684. //! Non member serialization
  685. template <class T, PROCESS_IF(non_member_serialize)> inline
  686. ArchiveType & processImpl(T & t)
  687. {
  688. CEREAL_SERIALIZE_FUNCTION_NAME(*self, t);
  689. return *self;
  690. }
  691. //! Member split (load)
  692. template <class T, PROCESS_IF(member_load)> inline
  693. ArchiveType & processImpl(T & t)
  694. {
  695. access::member_load(*self, t);
  696. return *self;
  697. }
  698. //! Non member split (load)
  699. template <class T, PROCESS_IF(non_member_load)> inline
  700. ArchiveType & processImpl(T & t)
  701. {
  702. CEREAL_LOAD_FUNCTION_NAME(*self, t);
  703. return *self;
  704. }
  705. //! Member split (load_minimal)
  706. template <class T, PROCESS_IF(member_load_minimal)> inline
  707. ArchiveType & processImpl(T & t)
  708. {
  709. using OutArchiveType = typename traits::detail::get_output_from_input<ArchiveType>::type;
  710. typename traits::has_member_save_minimal<T, OutArchiveType>::type value;
  711. self->process( value );
  712. access::member_load_minimal(*self, t, value);
  713. return *self;
  714. }
  715. //! Non member split (load_minimal)
  716. template <class T, PROCESS_IF(non_member_load_minimal)> inline
  717. ArchiveType & processImpl(T & t)
  718. {
  719. using OutArchiveType = typename traits::detail::get_output_from_input<ArchiveType>::type;
  720. typename traits::has_non_member_save_minimal<T, OutArchiveType>::type value;
  721. self->process( value );
  722. CEREAL_LOAD_MINIMAL_FUNCTION_NAME(*self, t, value);
  723. return *self;
  724. }
  725. //! Empty class specialization
  726. template <class T, traits::EnableIf<(Flags & AllowEmptyClassElision),
  727. !traits::is_input_serializable<T, ArchiveType>::value,
  728. std::is_empty<T>::value> = traits::sfinae> inline
  729. ArchiveType & processImpl(T const &)
  730. {
  731. return *self;
  732. }
  733. //! No matching serialization
  734. /*! Invalid if we have invalid input versioning or
  735. we are not input serializable, and either
  736. don't allow empty class ellision or allow it but are not serializing an empty class */
  737. template <class T, traits::EnableIf<traits::has_invalid_input_versioning<T, ArchiveType>::value ||
  738. (!traits::is_input_serializable<T, ArchiveType>::value &&
  739. (!(Flags & AllowEmptyClassElision) || ((Flags & AllowEmptyClassElision) && !std::is_empty<T>::value)))> = traits::sfinae> inline
  740. ArchiveType & processImpl(T const &)
  741. {
  742. static_assert(traits::detail::count_input_serializers<T, ArchiveType>::value != 0,
  743. "cereal could not find any input serialization functions for the provided type and archive combination. \n\n "
  744. "Types must either have a serialize function, load/save pair, or load_minimal/save_minimal pair (you may not mix these). \n "
  745. "Serialize functions generally have the following signature: \n\n "
  746. "template<class Archive> \n "
  747. " void serialize(Archive & ar) \n "
  748. " { \n "
  749. " ar( member1, member2, member3 ); \n "
  750. " } \n\n " );
  751. static_assert(traits::detail::count_input_serializers<T, ArchiveType>::value < 2,
  752. "cereal found more than one compatible input serialization function for the provided type and archive combination. \n\n "
  753. "Types must either have a serialize function, load/save pair, or load_minimal/save_minimal pair (you may not mix these). \n "
  754. "Use specialization (see access.hpp) if you need to disambiguate between serialize vs load/save functions. \n "
  755. "Note that serialization functions can be inherited which may lead to the aforementioned ambiguities. \n "
  756. "In addition, you may not mix versioned with non-versioned serialization functions. \n\n ");
  757. return *self;
  758. }
  759. //! Befriend for versioning in load_and_construct
  760. template <class A, class B, bool C, bool D, bool E, bool F> friend struct detail::Construct;
  761. //! Registers a class version with the archive and serializes it if necessary
  762. /*! If this is the first time this class has been serialized, we will record its
  763. version number and serialize that.
  764. @tparam T The type of the class being serialized
  765. @param version The version number associated with it */
  766. template <class T> inline
  767. std::uint32_t loadClassVersion()
  768. {
  769. static const auto hash = std::type_index(typeid(T)).hash_code();
  770. auto lookupResult = itsVersionedTypes.find( hash );
  771. if( lookupResult != itsVersionedTypes.end() ) // already exists
  772. return lookupResult->second;
  773. else // need to load
  774. {
  775. std::uint32_t version;
  776. process( make_nvp<ArchiveType>("cereal_class_version", version) );
  777. itsVersionedTypes.emplace_hint( lookupResult, hash, version );
  778. return version;
  779. }
  780. }
  781. //! Member serialization
  782. /*! Versioning implementation */
  783. template <class T, PROCESS_IF(member_versioned_serialize)> inline
  784. ArchiveType & processImpl(T & t)
  785. {
  786. const auto version = loadClassVersion<T>();
  787. access::member_serialize(*self, t, version);
  788. return *self;
  789. }
  790. //! Non member serialization
  791. /*! Versioning implementation */
  792. template <class T, PROCESS_IF(non_member_versioned_serialize)> inline
  793. ArchiveType & processImpl(T & t)
  794. {
  795. const auto version = loadClassVersion<T>();
  796. CEREAL_SERIALIZE_FUNCTION_NAME(*self, t, version);
  797. return *self;
  798. }
  799. //! Member split (load)
  800. /*! Versioning implementation */
  801. template <class T, PROCESS_IF(member_versioned_load)> inline
  802. ArchiveType & processImpl(T & t)
  803. {
  804. const auto version = loadClassVersion<T>();
  805. access::member_load(*self, t, version);
  806. return *self;
  807. }
  808. //! Non member split (load)
  809. /*! Versioning implementation */
  810. template <class T, PROCESS_IF(non_member_versioned_load)> inline
  811. ArchiveType & processImpl(T & t)
  812. {
  813. const auto version = loadClassVersion<T>();
  814. CEREAL_LOAD_FUNCTION_NAME(*self, t, version);
  815. return *self;
  816. }
  817. //! Member split (load_minimal)
  818. /*! Versioning implementation */
  819. template <class T, PROCESS_IF(member_versioned_load_minimal)> inline
  820. ArchiveType & processImpl(T & t)
  821. {
  822. using OutArchiveType = typename traits::detail::get_output_from_input<ArchiveType>::type;
  823. const auto version = loadClassVersion<T>();
  824. typename traits::has_member_versioned_save_minimal<T, OutArchiveType>::type value;
  825. self->process(value);
  826. access::member_load_minimal(*self, t, value, version);
  827. return *self;
  828. }
  829. //! Non member split (load_minimal)
  830. /*! Versioning implementation */
  831. template <class T, PROCESS_IF(non_member_versioned_load_minimal)> inline
  832. ArchiveType & processImpl(T & t)
  833. {
  834. using OutArchiveType = typename traits::detail::get_output_from_input<ArchiveType>::type;
  835. const auto version = loadClassVersion<T>();
  836. typename traits::has_non_member_versioned_save_minimal<T, OutArchiveType>::type value;
  837. self->process(value);
  838. CEREAL_LOAD_MINIMAL_FUNCTION_NAME(*self, t, value, version);
  839. return *self;
  840. }
  841. #undef PROCESS_IF
  842. private:
  843. ArchiveType * const self;
  844. //! A set of all base classes that have been serialized
  845. std::unordered_set<traits::detail::base_class_id, traits::detail::base_class_id_hash> itsBaseClassSet;
  846. //! Maps from pointer ids to metadata
  847. std::unordered_map<std::uint32_t, std::shared_ptr<void>> itsSharedPointerMap;
  848. //! Maps from name ids to names
  849. std::unordered_map<std::uint32_t, std::string> itsPolymorphicTypeMap;
  850. //! Maps from type hash codes to version numbers
  851. std::unordered_map<std::size_t, std::uint32_t> itsVersionedTypes;
  852. }; // class InputArchive
  853. } // namespace cereal
  854. // This include needs to come after things such as binary_data, make_nvp, etc
  855. #include "cereal/types/common.hpp"
  856. #endif // CEREAL_CEREAL_HPP_