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.

764 lines
35 KiB

7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*! \file polymorphic_impl.hpp
  2. \brief Internal polymorphism support
  3. \ingroup Internal */
  4. /*
  5. Copyright (c) 2014, Randolph Voorhies, Shane Grant
  6. All rights reserved.
  7. Redistribution and use in source and binary forms, with or without
  8. modification, are permitted provided that the following conditions are met:
  9. * Redistributions of source code must retain the above copyright
  10. notice, this list of conditions and the following disclaimer.
  11. * Redistributions in binary form must reproduce the above copyright
  12. notice, this list of conditions and the following disclaimer in the
  13. documentation and/or other materials provided with the distribution.
  14. * Neither the name of cereal nor the
  15. names of its contributors may be used to endorse or promote products
  16. derived from this software without specific prior written permission.
  17. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  18. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  19. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  20. DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY
  21. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  22. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  23. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  24. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  26. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. */
  28. /* This code is heavily inspired by the boost serialization implementation by the following authors
  29. (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
  30. Use, modification and distribution is subject to the Boost Software
  31. License, Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt)
  32. See http://www.boost.org for updates, documentation, and revision history.
  33. (C) Copyright 2006 David Abrahams - http://www.boost.org.
  34. See /boost/serialization/export.hpp, /boost/archive/detail/register_archive.hpp,
  35. and /boost/serialization/void_cast.hpp for their implementation. Additional details
  36. found in other files split across serialization and archive.
  37. */
  38. #ifndef CEREAL_DETAILS_POLYMORPHIC_IMPL_HPP_
  39. #define CEREAL_DETAILS_POLYMORPHIC_IMPL_HPP_
  40. #include "cereal/details/polymorphic_impl_fwd.hpp"
  41. #include "cereal/details/static_object.hpp"
  42. #include "cereal/types/memory.hpp"
  43. #include "cereal/types/string.hpp"
  44. #include <functional>
  45. #include <typeindex>
  46. #include <map>
  47. #include <limits>
  48. #include <set>
  49. #include <stack>
  50. //! Binds a polymorhic type to all registered archives
  51. /*! This binds a polymorphic type to all compatible registered archives that
  52. have been registered with CEREAL_REGISTER_ARCHIVE. This must be called
  53. after all archives are registered (usually after the archives themselves
  54. have been included). */
  55. #define CEREAL_BIND_TO_ARCHIVES(...) \
  56. namespace cereal { \
  57. namespace detail { \
  58. template<> \
  59. struct init_binding<__VA_ARGS__> { \
  60. static bind_to_archives<__VA_ARGS__> const & b; \
  61. static void unused() { (void)b; } \
  62. }; \
  63. bind_to_archives<__VA_ARGS__> const & init_binding<__VA_ARGS__>::b = \
  64. ::cereal::detail::StaticObject< \
  65. bind_to_archives<__VA_ARGS__> \
  66. >::getInstance().bind(); \
  67. }} /* end namespaces */
  68. namespace cereal
  69. {
  70. /* Polymorphic casting support */
  71. namespace detail
  72. {
  73. //! Base type for polymorphic void casting
  74. /*! Contains functions for casting between registered base and derived types.
  75. This is necessary so that cereal can properly cast between polymorphic types
  76. even though void pointers are used, which normally have no type information.
  77. Runtime type information is used instead to index a compile-time made mapping
  78. that can perform the proper cast. In the case of multiple levels of inheritance,
  79. cereal will attempt to find the shortest path by using registered relationships to
  80. perform the cast.
  81. This class will be allocated as a StaticObject and only referenced by pointer,
  82. allowing a templated derived version of it to define strongly typed functions
  83. that cast between registered base and derived types. */
  84. struct PolymorphicCaster
  85. {
  86. PolymorphicCaster() = default;
  87. PolymorphicCaster( const PolymorphicCaster & ) = default;
  88. PolymorphicCaster & operator=( const PolymorphicCaster & ) = default;
  89. PolymorphicCaster( PolymorphicCaster && ) CEREAL_NOEXCEPT {}
  90. PolymorphicCaster & operator=( PolymorphicCaster && ) CEREAL_NOEXCEPT { return *this; }
  91. virtual ~PolymorphicCaster() CEREAL_NOEXCEPT = default;
  92. //! Downcasts to the proper derived type
  93. virtual void const * downcast( void const * const ptr ) const = 0;
  94. //! Upcast to proper base type
  95. virtual void * upcast( void * const ptr ) const = 0;
  96. //! Upcast to proper base type, shared_ptr version
  97. virtual std::shared_ptr<void> upcast( std::shared_ptr<void> const & ptr ) const = 0;
  98. };
  99. //! Holds registered mappings between base and derived types for casting
  100. /*! This will be allocated as a StaticObject and holds a map containing
  101. all registered mappings between base and derived types. */
  102. struct PolymorphicCasters
  103. {
  104. //! Maps from base type index to a map from derived type index to caster
  105. std::map<std::type_index, std::map<std::type_index, std::vector<PolymorphicCaster const*>>> map;
  106. std::multimap<std::type_index, std::type_index> reverseMap;
  107. //! Error message used for unregistered polymorphic casts
  108. #define UNREGISTERED_POLYMORPHIC_CAST_EXCEPTION(LoadSave) \
  109. throw cereal::Exception("Trying to " #LoadSave " a registered polymorphic type with an unregistered polymorphic cast.\n" \
  110. "Could not find a path to a base class (" + util::demangle(baseInfo.name()) + ") for type: " + ::cereal::util::demangledName<Derived>() + "\n" \
  111. "Make sure you either serialize the base class at some point via cereal::base_class or cereal::virtual_base_class.\n" \
  112. "Alternatively, manually register the association with CEREAL_REGISTER_POLYMORPHIC_RELATION.");
  113. //! Checks if the mapping object that can perform the upcast or downcast
  114. /*! Uses the type index from the base and derived class to find the matching
  115. registered caster. If no matching caster exists, returns false. */
  116. static bool exists( std::type_index const & baseIndex, std::type_index const & derivedIndex )
  117. {
  118. // First phase of lookup - match base type index
  119. auto const & baseMap = StaticObject<PolymorphicCasters>::getInstance().map;
  120. auto baseIter = baseMap.find( baseIndex );
  121. if (baseIter == baseMap.end())
  122. return false;
  123. // Second phase - find a match from base to derived
  124. auto & derivedMap = baseIter->second;
  125. auto derivedIter = derivedMap.find( derivedIndex );
  126. if (derivedIter == derivedMap.end())
  127. return false;
  128. return true;
  129. }
  130. //! Gets the mapping object that can perform the upcast or downcast
  131. /*! Uses the type index from the base and derived class to find the matching
  132. registered caster. If no matching caster exists, calls the exception function.
  133. The returned PolymorphicCaster is capable of upcasting or downcasting between the two types. */
  134. template <class F> inline
  135. static std::vector<PolymorphicCaster const *> const & lookup( std::type_index const & baseIndex, std::type_index const & derivedIndex, F && exceptionFunc )
  136. {
  137. // First phase of lookup - match base type index
  138. auto const & baseMap = StaticObject<PolymorphicCasters>::getInstance().map;
  139. auto baseIter = baseMap.find( baseIndex );
  140. if( baseIter == baseMap.end() )
  141. exceptionFunc();
  142. // Second phase - find a match from base to derived
  143. auto & derivedMap = baseIter->second;
  144. auto derivedIter = derivedMap.find( derivedIndex );
  145. if( derivedIter == derivedMap.end() )
  146. exceptionFunc();
  147. return derivedIter->second;
  148. }
  149. //! Performs a downcast to the derived type using a registered mapping
  150. template <class Derived> inline
  151. static const Derived * downcast( const void * dptr, std::type_info const & baseInfo )
  152. {
  153. auto const & mapping = lookup( baseInfo, typeid(Derived), [&](){ UNREGISTERED_POLYMORPHIC_CAST_EXCEPTION(save) } );
  154. for( auto const * map : mapping )
  155. dptr = map->downcast( dptr );
  156. return static_cast<Derived const *>( dptr );
  157. }
  158. //! Performs an upcast to the registered base type using the given a derived type
  159. /*! The return is untyped because the final casting to the base type must happen in the polymorphic
  160. serialization function, where the type is known at compile time */
  161. template <class Derived> inline
  162. static void * upcast( Derived * const dptr, std::type_info const & baseInfo )
  163. {
  164. auto const & mapping = lookup( baseInfo, typeid(Derived), [&](){ UNREGISTERED_POLYMORPHIC_CAST_EXCEPTION(load) } );
  165. void * uptr = dptr;
  166. for( auto mIter = mapping.rbegin(), mEnd = mapping.rend(); mIter != mEnd; ++mIter )
  167. uptr = (*mIter)->upcast( uptr );
  168. return uptr;
  169. }
  170. //! Upcasts for shared pointers
  171. template <class Derived> inline
  172. static std::shared_ptr<void> upcast( std::shared_ptr<Derived> const & dptr, std::type_info const & baseInfo )
  173. {
  174. auto const & mapping = lookup( baseInfo, typeid(Derived), [&](){ UNREGISTERED_POLYMORPHIC_CAST_EXCEPTION(load) } );
  175. std::shared_ptr<void> uptr = dptr;
  176. for( auto mIter = mapping.rbegin(), mEnd = mapping.rend(); mIter != mEnd; ++mIter )
  177. uptr = (*mIter)->upcast( uptr );
  178. return uptr;
  179. }
  180. #undef UNREGISTERED_POLYMORPHIC_CAST_EXCEPTION
  181. };
  182. //! Strongly typed derivation of PolymorphicCaster
  183. template <class Base, class Derived>
  184. struct PolymorphicVirtualCaster : PolymorphicCaster
  185. {
  186. //! Inserts an entry in the polymorphic casting map for this pairing
  187. /*! Creates an explicit mapping between Base and Derived in both upwards and
  188. downwards directions, allowing void pointers to either to be properly cast
  189. assuming dynamic type information is available */
  190. PolymorphicVirtualCaster()
  191. {
  192. const auto baseKey = std::type_index(typeid(Base));
  193. const auto derivedKey = std::type_index(typeid(Derived));
  194. // First insert the relation Base->Derived
  195. const auto lock = StaticObject<PolymorphicCasters>::lock();
  196. auto & baseMap = StaticObject<PolymorphicCasters>::getInstance().map;
  197. auto lb = baseMap.lower_bound(baseKey);
  198. {
  199. auto & derivedMap = baseMap.insert( lb, {baseKey, {}} )->second;
  200. auto lbd = derivedMap.lower_bound(derivedKey);
  201. auto & derivedVec = derivedMap.insert( lbd, { std::move(derivedKey), {}} )->second;
  202. derivedVec.push_back( this );
  203. }
  204. // Insert reverse relation Derived->Base
  205. auto & reverseMap = StaticObject<PolymorphicCasters>::getInstance().reverseMap;
  206. reverseMap.insert( {derivedKey, baseKey} );
  207. // Find all chainable unregistered relations
  208. /* The strategy here is to process only the nodes in the class hierarchy graph that have been
  209. affected by the new insertion. The aglorithm iteratively processes a node an ensures that it
  210. is updated with all new shortest length paths. It then rocesses the parents of the active node,
  211. with the knowledge that all children have already been processed.
  212. Note that for the following, we'll use the nomenclature of parent and child to not confuse with
  213. the inserted base derived relationship */
  214. {
  215. // Checks whether there is a path from parent->child and returns a <dist, path> pair
  216. // dist is set to MAX if the path does not exist
  217. auto checkRelation = [](std::type_index const & parentInfo, std::type_index const & childInfo) ->
  218. std::pair<size_t, std::vector<PolymorphicCaster const *>>
  219. {
  220. if( PolymorphicCasters::exists( parentInfo, childInfo ) )
  221. {
  222. auto const & path = PolymorphicCasters::lookup( parentInfo, childInfo, [](){} );
  223. return {path.size(), path};
  224. }
  225. else
  226. return {std::numeric_limits<size_t>::max(), {}};
  227. };
  228. std::stack<std::type_index> parentStack; // Holds the parent nodes to be processed
  229. std::set<std::type_index> dirtySet; // Marks child nodes that have been changed
  230. std::set<std::type_index> processedParents; // Marks parent nodes that have been processed
  231. // Begin processing the base key and mark derived as dirty
  232. parentStack.push( baseKey );
  233. dirtySet.insert( derivedKey );
  234. while( !parentStack.empty() )
  235. {
  236. using Relations = std::multimap<std::type_index, std::pair<std::type_index, std::vector<PolymorphicCaster const *>>>;
  237. Relations unregisteredRelations; // Defer insertions until after main loop to prevent iterator invalidation
  238. const auto parent = parentStack.top();
  239. parentStack.pop();
  240. // Update paths to all children marked dirty
  241. for( auto const & childPair : baseMap[parent] )
  242. {
  243. const auto child = childPair.first;
  244. if( dirtySet.count( child ) && baseMap.count( child ) )
  245. {
  246. auto parentChildPath = checkRelation( parent, child );
  247. // Search all paths from the child to its own children (finalChild),
  248. // looking for a shorter parth from parent to finalChild
  249. for( auto const & finalChildPair : baseMap[child] )
  250. {
  251. const auto finalChild = finalChildPair.first;
  252. auto parentFinalChildPath = checkRelation( parent, finalChild );
  253. auto childFinalChildPath = checkRelation( child, finalChild );
  254. const size_t newLength = 1u + parentChildPath.first;
  255. if( newLength < parentFinalChildPath.first )
  256. {
  257. std::vector<PolymorphicCaster const *> path = parentChildPath.second;
  258. path.insert( path.end(), childFinalChildPath.second.begin(), childFinalChildPath.second.end() );
  259. // Check to see if we have a previous uncommitted path in unregisteredRelations
  260. // that is shorter. If so, ignore this path
  261. auto hintRange = unregisteredRelations.equal_range( parent );
  262. auto hint = hintRange.first;
  263. for( ; hint != hintRange.second; ++hint )
  264. if( hint->second.first == finalChild )
  265. break;
  266. const bool uncommittedExists = hint != unregisteredRelations.end();
  267. if( uncommittedExists && (hint->second.second.size() <= newLength) )
  268. continue;
  269. auto newPath = std::pair<std::type_index, std::vector<PolymorphicCaster const *>>{finalChild, std::move(path)};
  270. // Insert the new path if it doesn't exist, otherwise this will just lookup where to do the
  271. // replacement
  272. #ifdef CEREAL_OLDER_GCC
  273. auto old = unregisteredRelations.insert( hint, std::make_pair(parent, newPath) );
  274. #else // NOT CEREAL_OLDER_GCC
  275. auto old = unregisteredRelations.emplace_hint( hint, parent, newPath );
  276. #endif // NOT CEREAL_OLDER_GCC
  277. // If there was an uncommitted path, we need to perform a replacement
  278. if( uncommittedExists )
  279. old->second = newPath;
  280. }
  281. } // end loop over child's children
  282. } // end if dirty and child has children
  283. } // end loop over children
  284. // Insert chained relations
  285. for( auto const & it : unregisteredRelations )
  286. {
  287. auto & derivedMap = baseMap.find( it.first )->second;
  288. derivedMap[it.second.first] = it.second.second;
  289. reverseMap.insert( {it.second.first, it.first} );
  290. }
  291. // Mark current parent as modified
  292. dirtySet.insert( parent );
  293. // Insert all parents of the current parent node that haven't yet been processed
  294. auto parentRange = reverseMap.equal_range( parent );
  295. for( auto pIter = parentRange.first; pIter != parentRange.second; ++pIter )
  296. {
  297. const auto pParent = pIter->second;
  298. if( !processedParents.count( pParent ) )
  299. {
  300. parentStack.push( pParent );
  301. processedParents.insert( pParent );
  302. }
  303. }
  304. } // end loop over parent stack
  305. } // end chainable relations
  306. } // end PolymorphicVirtualCaster()
  307. //! Performs the proper downcast with the templated types
  308. void const * downcast( void const * const ptr ) const override
  309. {
  310. return dynamic_cast<Derived const*>( static_cast<Base const*>( ptr ) );
  311. }
  312. //! Performs the proper upcast with the templated types
  313. void * upcast( void * const ptr ) const override
  314. {
  315. return dynamic_cast<Base*>( static_cast<Derived*>( ptr ) );
  316. }
  317. //! Performs the proper upcast with the templated types (shared_ptr version)
  318. std::shared_ptr<void> upcast( std::shared_ptr<void> const & ptr ) const override
  319. {
  320. return std::dynamic_pointer_cast<Base>( std::static_pointer_cast<Derived>( ptr ) );
  321. }
  322. };
  323. //! Registers a polymorphic casting relation between a Base and Derived type
  324. /*! Registering a relation allows cereal to properly cast between the two types
  325. given runtime type information and void pointers.
  326. Registration happens automatically via cereal::base_class and cereal::virtual_base_class
  327. instantiations. For cases where neither is called, see the CEREAL_REGISTER_POLYMORPHIC_RELATION
  328. macro */
  329. template <class Base, class Derived>
  330. struct RegisterPolymorphicCaster
  331. {
  332. static PolymorphicCaster const * bind( std::true_type /* is_polymorphic<Base> */)
  333. {
  334. return &StaticObject<PolymorphicVirtualCaster<Base, Derived>>::getInstance();
  335. }
  336. static PolymorphicCaster const * bind( std::false_type /* is_polymorphic<Base> */ )
  337. { return nullptr; }
  338. //! Performs registration (binding) between Base and Derived
  339. /*! If the type is not polymorphic, nothing will happen */
  340. static PolymorphicCaster const * bind()
  341. { return bind( typename std::is_polymorphic<Base>::type() ); }
  342. };
  343. }
  344. /* General polymorphism support */
  345. namespace detail
  346. {
  347. //! Binds a compile time type with a user defined string
  348. template <class T>
  349. struct binding_name {};
  350. //! A structure holding a map from type_indices to output serializer functions
  351. /*! A static object of this map should be created for each registered archive
  352. type, containing entries for every registered type that describe how to
  353. properly cast the type to its real type in polymorphic scenarios for
  354. shared_ptr, weak_ptr, and unique_ptr. */
  355. template <class Archive>
  356. struct OutputBindingMap
  357. {
  358. //! A serializer function
  359. /*! Serializer functions return nothing and take an archive as
  360. their first parameter (will be cast properly inside the function,
  361. a pointer to actual data (contents of smart_ptr's get() function)
  362. as their second parameter, and the type info of the owning smart_ptr
  363. as their final parameter */
  364. typedef std::function<void(void*, void const *, std::type_info const &)> Serializer;
  365. //! Struct containing the serializer functions for all pointer types
  366. struct Serializers
  367. {
  368. Serializer shared_ptr, //!< Serializer function for shared/weak pointers
  369. unique_ptr; //!< Serializer function for unique pointers
  370. };
  371. //! A map of serializers for pointers of all registered types
  372. std::map<std::type_index, Serializers> map;
  373. };
  374. //! An empty noop deleter
  375. template<class T> struct EmptyDeleter { void operator()(T *) const {} };
  376. //! A structure holding a map from type name strings to input serializer functions
  377. /*! A static object of this map should be created for each registered archive
  378. type, containing entries for every registered type that describe how to
  379. properly cast the type to its real type in polymorphic scenarios for
  380. shared_ptr, weak_ptr, and unique_ptr. */
  381. template <class Archive>
  382. struct InputBindingMap
  383. {
  384. //! Shared ptr serializer function
  385. /*! Serializer functions return nothing and take an archive as
  386. their first parameter (will be cast properly inside the function,
  387. a shared_ptr (or unique_ptr for the unique case) of any base
  388. type, and the type id of said base type as the third parameter.
  389. Internally it will properly be loaded and cast to the correct type. */
  390. typedef std::function<void(void*, std::shared_ptr<void> &, std::type_info const &)> SharedSerializer;
  391. //! Unique ptr serializer function
  392. typedef std::function<void(void*, std::unique_ptr<void, EmptyDeleter<void>> &, std::type_info const &)> UniqueSerializer;
  393. //! Struct containing the serializer functions for all pointer types
  394. struct Serializers
  395. {
  396. SharedSerializer shared_ptr; //!< Serializer function for shared/weak pointers
  397. UniqueSerializer unique_ptr; //!< Serializer function for unique pointers
  398. };
  399. //! A map of serializers for pointers of all registered types
  400. std::map<std::string, Serializers> map;
  401. };
  402. // forward decls for archives from cereal.hpp
  403. class InputArchiveBase;
  404. class OutputArchiveBase;
  405. //! Creates a binding (map entry) between an input archive type and a polymorphic type
  406. /*! Bindings are made when types are registered, assuming that at least one
  407. archive has already been registered. When this struct is created,
  408. it will insert (at run time) an entry into a map that properly handles
  409. casting for serializing polymorphic objects */
  410. template <class Archive, class T> struct InputBindingCreator
  411. {
  412. //! Initialize the binding
  413. InputBindingCreator()
  414. {
  415. auto & map = StaticObject<InputBindingMap<Archive>>::getInstance().map;
  416. auto lock = StaticObject<InputBindingMap<Archive>>::lock();
  417. auto key = std::string(binding_name<T>::name());
  418. auto lb = map.lower_bound(key);
  419. if (lb != map.end() && lb->first == key)
  420. return;
  421. typename InputBindingMap<Archive>::Serializers serializers;
  422. serializers.shared_ptr =
  423. [](void * arptr, std::shared_ptr<void> & dptr, std::type_info const & baseInfo)
  424. {
  425. Archive & ar = *static_cast<Archive*>(arptr);
  426. std::shared_ptr<T> ptr;
  427. ar( CEREAL_NVP_("ptr_wrapper", ::cereal::memory_detail::make_ptr_wrapper(ptr)) );
  428. dptr = PolymorphicCasters::template upcast<T>( ptr, baseInfo );
  429. };
  430. serializers.unique_ptr =
  431. [](void * arptr, std::unique_ptr<void, EmptyDeleter<void>> & dptr, std::type_info const & baseInfo)
  432. {
  433. Archive & ar = *static_cast<Archive*>(arptr);
  434. std::unique_ptr<T> ptr;
  435. ar( CEREAL_NVP_("ptr_wrapper", ::cereal::memory_detail::make_ptr_wrapper(ptr)) );
  436. dptr.reset( PolymorphicCasters::template upcast<T>( ptr.release(), baseInfo ));
  437. };
  438. map.insert( lb, { std::move(key), std::move(serializers) } );
  439. }
  440. };
  441. //! Creates a binding (map entry) between an output archive type and a polymorphic type
  442. /*! Bindings are made when types are registered, assuming that at least one
  443. archive has already been registered. When this struct is created,
  444. it will insert (at run time) an entry into a map that properly handles
  445. casting for serializing polymorphic objects */
  446. template <class Archive, class T> struct OutputBindingCreator
  447. {
  448. //! Writes appropriate metadata to the archive for this polymorphic type
  449. static void writeMetadata(Archive & ar)
  450. {
  451. // Register the polymorphic type name with the archive, and get the id
  452. char const * name = binding_name<T>::name();
  453. std::uint32_t id = ar.registerPolymorphicType(name);
  454. // Serialize the id
  455. ar( CEREAL_NVP_("polymorphic_id", id) );
  456. // If the msb of the id is 1, then the type name is new, and we should serialize it
  457. if( id & detail::msb_32bit )
  458. {
  459. std::string namestring(name);
  460. ar( CEREAL_NVP_("polymorphic_name", namestring) );
  461. }
  462. }
  463. //! Holds a properly typed shared_ptr to the polymorphic type
  464. class PolymorphicSharedPointerWrapper
  465. {
  466. public:
  467. /*! Wrap a raw polymorphic pointer in a shared_ptr to its true type
  468. The wrapped pointer will not be responsible for ownership of the held pointer
  469. so it will not attempt to destroy it; instead the refcount of the wrapped
  470. pointer will be tied to a fake 'ownership pointer' that will do nothing
  471. when it ultimately goes out of scope.
  472. The main reason for doing this, other than not to destroy the true object
  473. with our wrapper pointer, is to avoid meddling with the internal reference
  474. count in a polymorphic type that inherits from std::enable_shared_from_this.
  475. @param dptr A void pointer to the contents of the shared_ptr to serialize */
  476. PolymorphicSharedPointerWrapper( T const * dptr ) : refCount(), wrappedPtr( refCount, dptr )
  477. { }
  478. //! Get the wrapped shared_ptr */
  479. inline std::shared_ptr<T const> const & operator()() const { return wrappedPtr; }
  480. private:
  481. std::shared_ptr<void> refCount; //!< The ownership pointer
  482. std::shared_ptr<T const> wrappedPtr; //!< The wrapped pointer
  483. };
  484. //! Does the actual work of saving a polymorphic shared_ptr
  485. /*! This function will properly create a shared_ptr from the void * that is passed in
  486. before passing it to the archive for serialization.
  487. In addition, this will also preserve the state of any internal enable_shared_from_this mechanisms
  488. @param ar The archive to serialize to
  489. @param dptr Pointer to the actual data held by the shared_ptr */
  490. static inline void savePolymorphicSharedPtr( Archive & ar, T const * dptr, std::true_type /* has_shared_from_this */ )
  491. {
  492. ::cereal::memory_detail::EnableSharedStateHelper<T> state( const_cast<T *>(dptr) );
  493. PolymorphicSharedPointerWrapper psptr( dptr );
  494. ar( CEREAL_NVP_("ptr_wrapper", memory_detail::make_ptr_wrapper( psptr() ) ) );
  495. }
  496. //! Does the actual work of saving a polymorphic shared_ptr
  497. /*! This function will properly create a shared_ptr from the void * that is passed in
  498. before passing it to the archive for serialization.
  499. This version is for types that do not inherit from std::enable_shared_from_this.
  500. @param ar The archive to serialize to
  501. @param dptr Pointer to the actual data held by the shared_ptr */
  502. static inline void savePolymorphicSharedPtr( Archive & ar, T const * dptr, std::false_type /* has_shared_from_this */ )
  503. {
  504. PolymorphicSharedPointerWrapper psptr( dptr );
  505. ar( CEREAL_NVP_("ptr_wrapper", memory_detail::make_ptr_wrapper( psptr() ) ) );
  506. }
  507. //! Initialize the binding
  508. OutputBindingCreator()
  509. {
  510. auto & map = StaticObject<OutputBindingMap<Archive>>::getInstance().map;
  511. auto key = std::type_index(typeid(T));
  512. auto lb = map.lower_bound(key);
  513. if (lb != map.end() && lb->first == key)
  514. return;
  515. typename OutputBindingMap<Archive>::Serializers serializers;
  516. serializers.shared_ptr =
  517. [&](void * arptr, void const * dptr, std::type_info const & baseInfo)
  518. {
  519. Archive & ar = *static_cast<Archive*>(arptr);
  520. writeMetadata(ar);
  521. auto ptr = PolymorphicCasters::template downcast<T>( dptr, baseInfo );
  522. #ifdef _MSC_VER
  523. savePolymorphicSharedPtr( ar, ptr, ::cereal::traits::has_shared_from_this<T>::type() ); // MSVC doesn't like typename here
  524. #else // not _MSC_VER
  525. savePolymorphicSharedPtr( ar, ptr, typename ::cereal::traits::has_shared_from_this<T>::type() );
  526. #endif // _MSC_VER
  527. };
  528. serializers.unique_ptr =
  529. [&](void * arptr, void const * dptr, std::type_info const & baseInfo)
  530. {
  531. Archive & ar = *static_cast<Archive*>(arptr);
  532. writeMetadata(ar);
  533. std::unique_ptr<T const, EmptyDeleter<T const>> const ptr( PolymorphicCasters::template downcast<T>( dptr, baseInfo ) );
  534. ar( CEREAL_NVP_("ptr_wrapper", memory_detail::make_ptr_wrapper(ptr)) );
  535. };
  536. map.insert( { std::move(key), std::move(serializers) } );
  537. }
  538. };
  539. //! Used to help out argument dependent lookup for finding potential overloads
  540. //! of instantiate_polymorphic_binding
  541. struct adl_tag {};
  542. //! Tag for init_binding, bind_to_archives and instantiate_polymorphic_binding. Due to the use of anonymous
  543. //! namespace it becomes a different type in each translation unit.
  544. namespace { struct polymorphic_binding_tag {}; }
  545. //! Causes the static object bindings between an archive type and a serializable type T
  546. template <class Archive, class T>
  547. struct create_bindings
  548. {
  549. static const InputBindingCreator<Archive, T> &
  550. load(std::true_type)
  551. {
  552. return cereal::detail::StaticObject<InputBindingCreator<Archive, T>>::getInstance();
  553. }
  554. static const OutputBindingCreator<Archive, T> &
  555. save(std::true_type)
  556. {
  557. return cereal::detail::StaticObject<OutputBindingCreator<Archive, T>>::getInstance();
  558. }
  559. inline static void load(std::false_type) {}
  560. inline static void save(std::false_type) {}
  561. };
  562. //! When specialized, causes the compiler to instantiate its parameter
  563. template <void(*)()>
  564. struct instantiate_function {};
  565. /*! This struct is used as the return type of instantiate_polymorphic_binding
  566. for specific Archive types. When the compiler looks for overloads of
  567. instantiate_polymorphic_binding, it will be forced to instantiate this
  568. struct during overload resolution, even though it will not be part of a valid
  569. overload */
  570. template <class Archive, class T>
  571. struct polymorphic_serialization_support
  572. {
  573. #if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
  574. //! Creates the appropriate bindings depending on whether the archive supports
  575. //! saving or loading
  576. virtual CEREAL_DLL_EXPORT void instantiate() CEREAL_USED;
  577. #else // NOT _MSC_VER
  578. //! Creates the appropriate bindings depending on whether the archive supports
  579. //! saving or loading
  580. static CEREAL_DLL_EXPORT void instantiate() CEREAL_USED;
  581. //! This typedef causes the compiler to instantiate this static function
  582. typedef instantiate_function<instantiate> unused;
  583. #endif // _MSC_VER
  584. };
  585. // instantiate implementation
  586. template <class Archive, class T>
  587. CEREAL_DLL_EXPORT void polymorphic_serialization_support<Archive,T>::instantiate()
  588. {
  589. create_bindings<Archive,T>::save( std::integral_constant<bool,
  590. std::is_base_of<detail::OutputArchiveBase, Archive>::value &&
  591. traits::is_output_serializable<T, Archive>::value>{} );
  592. create_bindings<Archive,T>::load( std::integral_constant<bool,
  593. std::is_base_of<detail::InputArchiveBase, Archive>::value &&
  594. traits::is_input_serializable<T, Archive>::value>{} );
  595. }
  596. //! Begins the binding process of a type to all registered archives
  597. /*! Archives need to be registered prior to this struct being instantiated via
  598. the CEREAL_REGISTER_ARCHIVE macro. Overload resolution will then force
  599. several static objects to be made that allow us to bind together all
  600. registered archive types with the parameter type T. */
  601. template <class T, class Tag = polymorphic_binding_tag>
  602. struct bind_to_archives
  603. {
  604. //! Binding for non abstract types
  605. void bind(std::false_type) const
  606. {
  607. instantiate_polymorphic_binding(static_cast<T*>(nullptr), 0, Tag{}, adl_tag{});
  608. }
  609. //! Binding for abstract types
  610. void bind(std::true_type) const
  611. { }
  612. //! Binds the type T to all registered archives
  613. /*! If T is abstract, we will not serialize it and thus
  614. do not need to make a binding */
  615. bind_to_archives const & bind() const
  616. {
  617. static_assert( std::is_polymorphic<T>::value,
  618. "Attempting to register non polymorphic type" );
  619. bind( std::is_abstract<T>() );
  620. return *this;
  621. }
  622. };
  623. //! Used to hide the static object used to bind T to registered archives
  624. template <class T, class Tag = polymorphic_binding_tag>
  625. struct init_binding;
  626. //! Base case overload for instantiation
  627. /*! This will end up always being the best overload due to the second
  628. parameter always being passed as an int. All other overloads will
  629. accept pointers to archive types and have lower precedence than int.
  630. Since the compiler needs to check all possible overloads, the
  631. other overloads created via CEREAL_REGISTER_ARCHIVE, which will have
  632. lower precedence due to requring a conversion from int to (Archive*),
  633. will cause their return types to be instantiated through the static object
  634. mechanisms even though they are never called.
  635. See the documentation for the other functions to try and understand this */
  636. template <class T, typename BindingTag>
  637. void instantiate_polymorphic_binding( T*, int, BindingTag, adl_tag ) {}
  638. } // namespace detail
  639. } // namespace cereal
  640. #endif // CEREAL_DETAILS_POLYMORPHIC_IMPL_HPP_