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.

897 lines
36 KiB

7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*! \file xml.hpp
  2. \brief XML input and output archives */
  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_ARCHIVES_XML_HPP_
  28. #define CEREAL_ARCHIVES_XML_HPP_
  29. #include "cereal/cereal.hpp"
  30. #include "cereal/details/util.hpp"
  31. #include "cereal/external/rapidxml/rapidxml.hpp"
  32. #include "cereal/external/rapidxml/rapidxml_print.hpp"
  33. #include "cereal/external/base64.hpp"
  34. #include <sstream>
  35. #include <stack>
  36. #include <vector>
  37. #include <limits>
  38. #include <string>
  39. #include <cstring>
  40. #include <cmath>
  41. namespace cereal
  42. {
  43. namespace xml_detail
  44. {
  45. #ifndef CEREAL_XML_STRING_VALUE
  46. //! The default name for the root node in a cereal xml archive.
  47. /*! You can define CEREAL_XML_STRING_VALUE to be different assuming you do so
  48. before this file is included. */
  49. #define CEREAL_XML_STRING_VALUE "cereal"
  50. #endif // CEREAL_XML_STRING_VALUE
  51. //! The name given to the root node in a cereal xml archive
  52. static const char * CEREAL_XML_STRING = CEREAL_XML_STRING_VALUE;
  53. //! Returns true if the character is whitespace
  54. inline bool isWhitespace( char c )
  55. {
  56. return c == ' ' || c == '\t' || c == '\n' || c == '\r';
  57. }
  58. }
  59. // ######################################################################
  60. //! An output archive designed to save data to XML
  61. /*! This archive uses RapidXML to build an in memory XML tree of the
  62. data it serializes before outputting it to its stream upon destruction.
  63. This archive should be used in an RAII fashion, letting
  64. the automatic destruction of the object cause the flush to its stream.
  65. XML archives provides a human readable output but at decreased
  66. performance (both in time and space) compared to binary archives.
  67. XML benefits greatly from name-value pairs, which if present, will
  68. name the nodes in the output. If these are not present, each level
  69. of the output tree will be given an automatically generated delimited name.
  70. The precision of the output archive controls the number of decimals output
  71. for floating point numbers and should be sufficiently large (i.e. at least 20)
  72. if there is a desire to have binary equality between the numbers output and
  73. those read in. In general you should expect a loss of precision when going
  74. from floating point to text and back.
  75. XML archives can optionally print the type of everything they serialize, which
  76. adds an attribute to each node.
  77. XML archives do not output the size information for any dynamically sized structure
  78. and instead infer it from the number of children for a node. This means that data
  79. can be hand edited for dynamic sized structures and will still be readable. This
  80. is accomplished through the cereal::SizeTag object, which will also add an attribute
  81. to its parent field.
  82. \ingroup Archives */
  83. class XMLOutputArchive : public OutputArchive<XMLOutputArchive>, public traits::TextArchive
  84. {
  85. public:
  86. /*! @name Common Functionality
  87. Common use cases for directly interacting with an XMLOutputArchive */
  88. //! @{
  89. //! A class containing various advanced options for the XML archive
  90. class Options
  91. {
  92. public:
  93. //! Default options
  94. static Options Default(){ return Options(); }
  95. //! Default options with no indentation
  96. static Options NoIndent(){ return Options( std::numeric_limits<double>::max_digits10, false ); }
  97. //! Specify specific options for the XMLOutputArchive
  98. /*! @param precision The precision used for floating point numbers
  99. @param indent Whether to indent each line of XML
  100. @param outputType Whether to output the type of each serialized object as an attribute */
  101. explicit Options( int precision = std::numeric_limits<double>::max_digits10,
  102. bool indent = true,
  103. bool outputType = false ) :
  104. itsPrecision( precision ),
  105. itsIndent( indent ),
  106. itsOutputType( outputType ) { }
  107. private:
  108. friend class XMLOutputArchive;
  109. int itsPrecision;
  110. bool itsIndent;
  111. bool itsOutputType;
  112. };
  113. //! Construct, outputting to the provided stream upon destruction
  114. /*! @param stream The stream to output to. Note that XML is only guaranteed to flush
  115. its output to the stream upon destruction.
  116. @param options The XML specific options to use. See the Options struct
  117. for the values of default parameters */
  118. XMLOutputArchive( std::ostream & stream, Options const & options = Options::Default() ) :
  119. OutputArchive<XMLOutputArchive>(this),
  120. itsStream(stream),
  121. itsOutputType( options.itsOutputType ),
  122. itsIndent( options.itsIndent )
  123. {
  124. // rapidxml will delete all allocations when xml_document is cleared
  125. auto node = itsXML.allocate_node( rapidxml::node_declaration );
  126. node->append_attribute( itsXML.allocate_attribute( "version", "1.0" ) );
  127. node->append_attribute( itsXML.allocate_attribute( "encoding", "utf-8" ) );
  128. itsXML.append_node( node );
  129. // allocate root node
  130. auto root = itsXML.allocate_node( rapidxml::node_element, xml_detail::CEREAL_XML_STRING );
  131. itsXML.append_node( root );
  132. itsNodes.emplace( root );
  133. // set attributes on the streams
  134. itsStream << std::boolalpha;
  135. itsStream.precision( options.itsPrecision );
  136. itsOS << std::boolalpha;
  137. itsOS.precision( options.itsPrecision );
  138. }
  139. //! Destructor, flushes the XML
  140. ~XMLOutputArchive() CEREAL_NOEXCEPT
  141. {
  142. const int flags = itsIndent ? 0x0 : rapidxml::print_no_indenting;
  143. rapidxml::print( itsStream, itsXML, flags );
  144. itsXML.clear();
  145. }
  146. //! Saves some binary data, encoded as a base64 string, with an optional name
  147. /*! This can be called directly by users and it will automatically create a child node for
  148. the current XML node, populate it with a base64 encoded string, and optionally name
  149. it. The node will be finished after it has been populated. */
  150. void saveBinaryValue( const void * data, size_t size, const char * name = nullptr )
  151. {
  152. itsNodes.top().name = name;
  153. startNode();
  154. auto base64string = base64::encode( reinterpret_cast<const unsigned char *>( data ), size );
  155. saveValue( base64string );
  156. if( itsOutputType )
  157. itsNodes.top().node->append_attribute( itsXML.allocate_attribute( "type", "cereal binary data" ) );
  158. finishNode();
  159. };
  160. //! @}
  161. /*! @name Internal Functionality
  162. Functionality designed for use by those requiring control over the inner mechanisms of
  163. the XMLOutputArchive */
  164. //! @{
  165. //! Creates a new node that is a child of the node at the top of the stack
  166. /*! Nodes will be given a name that has either been pre-set by a name value pair,
  167. or generated based upon a counter unique to the parent node. If you want to
  168. give a node a specific name, use setNextName prior to calling startNode.
  169. The node will then be pushed onto the node stack. */
  170. void startNode()
  171. {
  172. // generate a name for this new node
  173. const auto nameString = itsNodes.top().getValueName();
  174. // allocate strings for all of the data in the XML object
  175. auto namePtr = itsXML.allocate_string( nameString.data(), nameString.length() + 1 );
  176. // insert into the XML
  177. auto node = itsXML.allocate_node( rapidxml::node_element, namePtr, nullptr, nameString.size() );
  178. itsNodes.top().node->append_node( node );
  179. itsNodes.emplace( node );
  180. }
  181. //! Designates the most recently added node as finished
  182. void finishNode()
  183. {
  184. itsNodes.pop();
  185. }
  186. //! Sets the name for the next node created with startNode
  187. void setNextName( const char * name )
  188. {
  189. itsNodes.top().name = name;
  190. }
  191. //! Saves some data, encoded as a string, into the current top level node
  192. /*! The data will be be named with the most recent name if one exists,
  193. otherwise it will be given some default delimited value that depends upon
  194. the parent node */
  195. template <class T> inline
  196. void saveValue( T const & value )
  197. {
  198. itsOS.clear(); itsOS.seekp( 0, std::ios::beg );
  199. itsOS << value << std::ends;
  200. auto strValue = itsOS.str();
  201. // itsOS.str() may contain data from previous calls after the first '\0' that was just inserted
  202. // and this data is counted in the length call. We make sure to remove that section so that the
  203. // whitespace validation is done properly
  204. strValue.resize(std::strlen(strValue.c_str()));
  205. // If the first or last character is a whitespace, add xml:space attribute
  206. const auto len = strValue.length();
  207. if ( len > 0 && ( xml_detail::isWhitespace( strValue[0] ) || xml_detail::isWhitespace( strValue[len - 1] ) ) )
  208. {
  209. itsNodes.top().node->append_attribute( itsXML.allocate_attribute( "xml:space", "preserve" ) );
  210. }
  211. // allocate strings for all of the data in the XML object
  212. auto dataPtr = itsXML.allocate_string(strValue.c_str(), strValue.length() + 1 );
  213. // insert into the XML
  214. itsNodes.top().node->append_node( itsXML.allocate_node( rapidxml::node_data, nullptr, dataPtr ) );
  215. }
  216. //! Overload for uint8_t prevents them from being serialized as characters
  217. void saveValue( uint8_t const & value )
  218. {
  219. saveValue( static_cast<uint32_t>( value ) );
  220. }
  221. //! Overload for int8_t prevents them from being serialized as characters
  222. void saveValue( int8_t const & value )
  223. {
  224. saveValue( static_cast<int32_t>( value ) );
  225. }
  226. //! Causes the type to be appended as an attribute to the most recently made node if output type is set to true
  227. template <class T> inline
  228. void insertType()
  229. {
  230. if( !itsOutputType )
  231. return;
  232. // generate a name for this new node
  233. const auto nameString = util::demangledName<T>();
  234. // allocate strings for all of the data in the XML object
  235. auto namePtr = itsXML.allocate_string( nameString.data(), nameString.length() + 1 );
  236. itsNodes.top().node->append_attribute( itsXML.allocate_attribute( "type", namePtr ) );
  237. }
  238. //! Appends an attribute to the current top level node
  239. void appendAttribute( const char * name, const char * value )
  240. {
  241. auto namePtr = itsXML.allocate_string( name );
  242. auto valuePtr = itsXML.allocate_string( value );
  243. itsNodes.top().node->append_attribute( itsXML.allocate_attribute( namePtr, valuePtr ) );
  244. }
  245. protected:
  246. //! A struct that contains metadata about a node
  247. struct NodeInfo
  248. {
  249. NodeInfo( rapidxml::xml_node<> * n = nullptr,
  250. const char * nm = nullptr ) :
  251. node( n ),
  252. counter( 0 ),
  253. name( nm )
  254. { }
  255. rapidxml::xml_node<> * node; //!< A pointer to this node
  256. size_t counter; //!< The counter for naming child nodes
  257. const char * name; //!< The name for the next child node
  258. //! Gets the name for the next child node created from this node
  259. /*! The name will be automatically generated using the counter if
  260. a name has not been previously set. If a name has been previously
  261. set, that name will be returned only once */
  262. std::string getValueName()
  263. {
  264. if( name )
  265. {
  266. auto n = name;
  267. name = nullptr;
  268. return {n};
  269. }
  270. else
  271. return "value" + std::to_string( counter++ ) + "\0";
  272. }
  273. }; // NodeInfo
  274. //! @}
  275. private:
  276. std::ostream & itsStream; //!< The output stream
  277. rapidxml::xml_document<> itsXML; //!< The XML document
  278. std::stack<NodeInfo> itsNodes; //!< A stack of nodes added to the document
  279. std::ostringstream itsOS; //!< Used to format strings internally
  280. bool itsOutputType; //!< Controls whether type information is printed
  281. bool itsIndent; //!< Controls whether indenting is used
  282. }; // XMLOutputArchive
  283. // ######################################################################
  284. //! An output archive designed to load data from XML
  285. /*! This archive uses RapidXML to build an in memory XML tree of the
  286. data in the stream it is given before loading any types serialized.
  287. As with the output XML archive, the preferred way to use this archive is in
  288. an RAII fashion, ensuring its destruction after all data has been read.
  289. Input XML should have been produced by the XMLOutputArchive. Data can
  290. only be added to dynamically sized containers - the input archive will
  291. determine their size by looking at the number of child nodes. Data that
  292. did not originate from an XMLOutputArchive is not officially supported,
  293. but may be possible to use if properly formatted.
  294. The XMLInputArchive does not require that nodes are loaded in the same
  295. order they were saved by XMLOutputArchive. Using name value pairs (NVPs),
  296. it is possible to load in an out of order fashion or otherwise skip/select
  297. specific nodes to load.
  298. The default behavior of the input archive is to read sequentially starting
  299. with the first node and exploring its children. When a given NVP does
  300. not match the read in name for a node, the archive will search for that
  301. node at the current level and load it if it exists. After loading an out of
  302. order node, the archive will then proceed back to loading sequentially from
  303. its new position.
  304. Consider this simple example where loading of some data is skipped:
  305. @code{cpp}
  306. // imagine the input file has someData(1-9) saved in order at the top level node
  307. ar( someData1, someData2, someData3 ); // XML loads in the order it sees in the file
  308. ar( cereal::make_nvp( "hello", someData6 ) ); // NVP given does not
  309. // match expected NVP name, so we search
  310. // for the given NVP and load that value
  311. ar( someData7, someData8, someData9 ); // with no NVP given, loading resumes at its
  312. // current location, proceeding sequentially
  313. @endcode
  314. \ingroup Archives */
  315. class XMLInputArchive : public InputArchive<XMLInputArchive>, public traits::TextArchive
  316. {
  317. public:
  318. /*! @name Common Functionality
  319. Common use cases for directly interacting with an XMLInputArchive */
  320. //! @{
  321. //! Construct, reading in from the provided stream
  322. /*! Reads in an entire XML document from some stream and parses it as soon
  323. as serialization starts
  324. @param stream The stream to read from. Can be a stringstream or a file. */
  325. XMLInputArchive( std::istream & stream ) :
  326. InputArchive<XMLInputArchive>( this ),
  327. itsData( std::istreambuf_iterator<char>( stream ), std::istreambuf_iterator<char>() )
  328. {
  329. try
  330. {
  331. itsData.push_back('\0'); // rapidxml will do terrible things without the data being null terminated
  332. itsXML.parse<rapidxml::parse_trim_whitespace | rapidxml::parse_no_data_nodes | rapidxml::parse_declaration_node>( reinterpret_cast<char *>( itsData.data() ) );
  333. }
  334. catch( rapidxml::parse_error const & )
  335. {
  336. //std::cerr << "-----Original-----" << std::endl;
  337. //stream.seekg(0);
  338. //std::cout << std::string( std::istreambuf_iterator<char>( stream ), std::istreambuf_iterator<char>() ) << std::endl;
  339. //std::cerr << "-----Error-----" << std::endl;
  340. //std::cerr << e.what() << std::endl;
  341. //std::cerr << e.where<char>() << std::endl;
  342. throw Exception("XML Parsing failed - likely due to invalid characters or invalid naming");
  343. }
  344. // Parse the root
  345. auto root = itsXML.first_node( xml_detail::CEREAL_XML_STRING );
  346. if( root == nullptr )
  347. throw Exception("Could not detect cereal root node - likely due to empty or invalid input");
  348. else
  349. itsNodes.emplace( root );
  350. }
  351. ~XMLInputArchive() CEREAL_NOEXCEPT = default;
  352. //! Loads some binary data, encoded as a base64 string, optionally specified by some name
  353. /*! This will automatically start and finish a node to load the data, and can be called directly by
  354. users.
  355. Note that this follows the same ordering rules specified in the class description in regards
  356. to loading in/out of order */
  357. void loadBinaryValue( void * data, size_t size, const char * name = nullptr )
  358. {
  359. setNextName( name );
  360. startNode();
  361. std::string encoded;
  362. loadValue( encoded );
  363. auto decoded = base64::decode( encoded );
  364. if( size != decoded.size() )
  365. throw Exception("Decoded binary data size does not match specified size");
  366. std::memcpy( data, decoded.data(), decoded.size() );
  367. finishNode();
  368. };
  369. //! @}
  370. /*! @name Internal Functionality
  371. Functionality designed for use by those requiring control over the inner mechanisms of
  372. the XMLInputArchive */
  373. //! @{
  374. //! Prepares to start reading the next node
  375. /*! This places the next node to be parsed onto the nodes stack.
  376. By default our strategy is to start with the document root node and then
  377. recursively iterate through all children in the order they show up in the document.
  378. We don't need to know NVPs do to this; we'll just blindly load in the order things appear in.
  379. We check to see if the specified NVP matches what the next automatically loaded node is. If they
  380. match, we just continue as normal, going in order. If they don't match, we attempt to find a node
  381. named after the NVP that is being loaded. If that NVP does not exist, we throw an exception. */
  382. void startNode()
  383. {
  384. auto next = itsNodes.top().child; // By default we would move to the next child node
  385. auto const expectedName = itsNodes.top().name; // this is the expected name from the NVP, if provided
  386. // If we were given an NVP name, look for it in the current level of the document.
  387. // We only need to do this if either we have exhausted the siblings of the current level or
  388. // the NVP name does not match the name of the node we would normally read next
  389. if( expectedName && ( next == nullptr || std::strcmp( next->name(), expectedName ) != 0 ) )
  390. {
  391. next = itsNodes.top().search( expectedName );
  392. if( next == nullptr )
  393. throw Exception("XML Parsing failed - provided NVP (" + std::string(expectedName) + ") not found");
  394. }
  395. itsNodes.emplace( next );
  396. }
  397. //! Finishes reading the current node
  398. void finishNode()
  399. {
  400. // remove current
  401. itsNodes.pop();
  402. // advance parent
  403. itsNodes.top().advance();
  404. // Reset name
  405. itsNodes.top().name = nullptr;
  406. }
  407. //! Retrieves the current node name
  408. //! will return @c nullptr if the node does not have a name
  409. const char * getNodeName() const
  410. {
  411. return itsNodes.top().getChildName();
  412. }
  413. //! Sets the name for the next node created with startNode
  414. void setNextName( const char * name )
  415. {
  416. itsNodes.top().name = name;
  417. }
  418. //! Loads a bool from the current top node
  419. template <class T, traits::EnableIf<std::is_unsigned<T>::value,
  420. std::is_same<T, bool>::value> = traits::sfinae> inline
  421. void loadValue( T & value )
  422. {
  423. std::istringstream is( itsNodes.top().node->value() );
  424. is.setf( std::ios::boolalpha );
  425. is >> value;
  426. }
  427. //! Loads a char (signed or unsigned) from the current top node
  428. template <class T, traits::EnableIf<std::is_integral<T>::value,
  429. !std::is_same<T, bool>::value,
  430. sizeof(T) == sizeof(char)> = traits::sfinae> inline
  431. void loadValue( T & value )
  432. {
  433. value = *reinterpret_cast<T*>( itsNodes.top().node->value() );
  434. }
  435. //! Load an int8_t from the current top node (ensures we parse entire number)
  436. void loadValue( int8_t & value )
  437. {
  438. int32_t val; loadValue( val ); value = static_cast<int8_t>( val );
  439. }
  440. //! Load a uint8_t from the current top node (ensures we parse entire number)
  441. void loadValue( uint8_t & value )
  442. {
  443. uint32_t val; loadValue( val ); value = static_cast<uint8_t>( val );
  444. }
  445. //! Loads a type best represented as an unsigned long from the current top node
  446. template <class T, traits::EnableIf<std::is_unsigned<T>::value,
  447. !std::is_same<T, bool>::value,
  448. !std::is_same<T, char>::value,
  449. !std::is_same<T, unsigned char>::value,
  450. sizeof(T) < sizeof(long long)> = traits::sfinae> inline
  451. void loadValue( T & value )
  452. {
  453. value = static_cast<T>( std::stoul( itsNodes.top().node->value() ) );
  454. }
  455. //! Loads a type best represented as an unsigned long long from the current top node
  456. template <class T, traits::EnableIf<std::is_unsigned<T>::value,
  457. !std::is_same<T, bool>::value,
  458. sizeof(T) >= sizeof(long long)> = traits::sfinae> inline
  459. void loadValue( T & value )
  460. {
  461. value = static_cast<T>( std::stoull( itsNodes.top().node->value() ) );
  462. }
  463. //! Loads a type best represented as an int from the current top node
  464. template <class T, traits::EnableIf<std::is_signed<T>::value,
  465. !std::is_same<T, char>::value,
  466. sizeof(T) <= sizeof(int)> = traits::sfinae> inline
  467. void loadValue( T & value )
  468. {
  469. value = static_cast<T>( std::stoi( itsNodes.top().node->value() ) );
  470. }
  471. //! Loads a type best represented as a long from the current top node
  472. template <class T, traits::EnableIf<std::is_signed<T>::value,
  473. (sizeof(T) > sizeof(int)),
  474. sizeof(T) <= sizeof(long)> = traits::sfinae> inline
  475. void loadValue( T & value )
  476. {
  477. value = static_cast<T>( std::stol( itsNodes.top().node->value() ) );
  478. }
  479. //! Loads a type best represented as a long long from the current top node
  480. template <class T, traits::EnableIf<std::is_signed<T>::value,
  481. (sizeof(T) > sizeof(long)),
  482. sizeof(T) <= sizeof(long long)> = traits::sfinae> inline
  483. void loadValue( T & value )
  484. {
  485. value = static_cast<T>( std::stoll( itsNodes.top().node->value() ) );
  486. }
  487. //! Loads a type best represented as a float from the current top node
  488. void loadValue( float & value )
  489. {
  490. try
  491. {
  492. value = std::stof( itsNodes.top().node->value() );
  493. }
  494. catch( std::out_of_range const & )
  495. {
  496. // special case for denormalized values
  497. std::istringstream is( itsNodes.top().node->value() );
  498. is >> value;
  499. if( std::fpclassify( value ) != FP_SUBNORMAL )
  500. throw;
  501. }
  502. }
  503. //! Loads a type best represented as a double from the current top node
  504. void loadValue( double & value )
  505. {
  506. try
  507. {
  508. value = std::stod( itsNodes.top().node->value() );
  509. }
  510. catch( std::out_of_range const & )
  511. {
  512. // special case for denormalized values
  513. std::istringstream is( itsNodes.top().node->value() );
  514. is >> value;
  515. if( std::fpclassify( value ) != FP_SUBNORMAL )
  516. throw;
  517. }
  518. }
  519. //! Loads a type best represented as a long double from the current top node
  520. void loadValue( long double & value )
  521. {
  522. try
  523. {
  524. value = std::stold( itsNodes.top().node->value() );
  525. }
  526. catch( std::out_of_range const & )
  527. {
  528. // special case for denormalized values
  529. std::istringstream is( itsNodes.top().node->value() );
  530. is >> value;
  531. if( std::fpclassify( value ) != FP_SUBNORMAL )
  532. throw;
  533. }
  534. }
  535. //! Loads a string from the current node from the current top node
  536. template<class CharT, class Traits, class Alloc> inline
  537. void loadValue( std::basic_string<CharT, Traits, Alloc> & str )
  538. {
  539. std::basic_istringstream<CharT, Traits> is( itsNodes.top().node->value() );
  540. str.assign( std::istreambuf_iterator<CharT, Traits>( is ),
  541. std::istreambuf_iterator<CharT, Traits>() );
  542. }
  543. //! Loads the size of the current top node
  544. template <class T> inline
  545. void loadSize( T & value )
  546. {
  547. value = getNumChildren( itsNodes.top().node );
  548. }
  549. protected:
  550. //! Gets the number of children (usually interpreted as size) for the specified node
  551. static size_t getNumChildren( rapidxml::xml_node<> * node )
  552. {
  553. size_t size = 0;
  554. node = node->first_node(); // get first child
  555. while( node != nullptr )
  556. {
  557. ++size;
  558. node = node->next_sibling();
  559. }
  560. return size;
  561. }
  562. //! A struct that contains metadata about a node
  563. /*! Keeps track of some top level node, its number of
  564. remaining children, and the current active child node */
  565. struct NodeInfo
  566. {
  567. NodeInfo( rapidxml::xml_node<> * n = nullptr ) :
  568. node( n ),
  569. child( n->first_node() ),
  570. size( XMLInputArchive::getNumChildren( n ) ),
  571. name( nullptr )
  572. { }
  573. //! Advances to the next sibling node of the child
  574. /*! If this is the last sibling child will be null after calling */
  575. void advance()
  576. {
  577. if( size > 0 )
  578. {
  579. --size;
  580. child = child->next_sibling();
  581. }
  582. }
  583. //! Searches for a child with the given name in this node
  584. /*! @param searchName The name to search for (must be null terminated)
  585. @return The node if found, nullptr otherwise */
  586. rapidxml::xml_node<> * search( const char * searchName )
  587. {
  588. if( searchName )
  589. {
  590. size_t new_size = XMLInputArchive::getNumChildren( node );
  591. const size_t name_size = rapidxml::internal::measure( searchName );
  592. for( auto new_child = node->first_node(); new_child != nullptr; new_child = new_child->next_sibling() )
  593. {
  594. if( rapidxml::internal::compare( new_child->name(), new_child->name_size(), searchName, name_size, true ) )
  595. {
  596. size = new_size;
  597. child = new_child;
  598. return new_child;
  599. }
  600. --new_size;
  601. }
  602. }
  603. return nullptr;
  604. }
  605. //! Returns the actual name of the next child node, if it exists
  606. const char * getChildName() const
  607. {
  608. return child ? child->name() : nullptr;
  609. }
  610. rapidxml::xml_node<> * node; //!< A pointer to this node
  611. rapidxml::xml_node<> * child; //!< A pointer to its current child
  612. size_t size; //!< The remaining number of children for this node
  613. const char * name; //!< The NVP name for next child node
  614. }; // NodeInfo
  615. //! @}
  616. private:
  617. std::vector<char> itsData; //!< The raw data loaded
  618. rapidxml::xml_document<> itsXML; //!< The XML document
  619. std::stack<NodeInfo> itsNodes; //!< A stack of nodes read from the document
  620. };
  621. // ######################################################################
  622. // XMLArchive prologue and epilogue functions
  623. // ######################################################################
  624. // ######################################################################
  625. //! Prologue for NVPs for XML output archives
  626. /*! NVPs do not start or finish nodes - they just set up the names */
  627. template <class T> inline
  628. void prologue( XMLOutputArchive &, NameValuePair<T> const & )
  629. { }
  630. //! Prologue for NVPs for XML input archives
  631. template <class T> inline
  632. void prologue( XMLInputArchive &, NameValuePair<T> const & )
  633. { }
  634. // ######################################################################
  635. //! Epilogue for NVPs for XML output archives
  636. /*! NVPs do not start or finish nodes - they just set up the names */
  637. template <class T> inline
  638. void epilogue( XMLOutputArchive &, NameValuePair<T> const & )
  639. { }
  640. //! Epilogue for NVPs for XML input archives
  641. template <class T> inline
  642. void epilogue( XMLInputArchive &, NameValuePair<T> const & )
  643. { }
  644. // ######################################################################
  645. //! Prologue for SizeTags for XML output archives
  646. /*! SizeTags do not start or finish nodes */
  647. template <class T> inline
  648. void prologue( XMLOutputArchive & ar, SizeTag<T> const & )
  649. {
  650. ar.appendAttribute( "size", "dynamic" );
  651. }
  652. template <class T> inline
  653. void prologue( XMLInputArchive &, SizeTag<T> const & )
  654. { }
  655. //! Epilogue for SizeTags for XML output archives
  656. /*! SizeTags do not start or finish nodes */
  657. template <class T> inline
  658. void epilogue( XMLOutputArchive &, SizeTag<T> const & )
  659. { }
  660. template <class T> inline
  661. void epilogue( XMLInputArchive &, SizeTag<T> const & )
  662. { }
  663. // ######################################################################
  664. //! Prologue for all other types for XML output archives (except minimal types)
  665. /*! Starts a new node, named either automatically or by some NVP,
  666. that may be given data by the type about to be archived
  667. Minimal types do not start or end nodes */
  668. template <class T, traits::DisableIf<traits::has_minimal_base_class_serialization<T, traits::has_minimal_output_serialization, XMLOutputArchive>::value ||
  669. traits::has_minimal_output_serialization<T, XMLOutputArchive>::value> = traits::sfinae> inline
  670. void prologue( XMLOutputArchive & ar, T const & )
  671. {
  672. ar.startNode();
  673. ar.insertType<T>();
  674. }
  675. //! Prologue for all other types for XML input archives (except minimal types)
  676. template <class T, traits::DisableIf<traits::has_minimal_base_class_serialization<T, traits::has_minimal_input_serialization, XMLInputArchive>::value ||
  677. traits::has_minimal_input_serialization<T, XMLInputArchive>::value> = traits::sfinae> inline
  678. void prologue( XMLInputArchive & ar, T const & )
  679. {
  680. ar.startNode();
  681. }
  682. // ######################################################################
  683. //! Epilogue for all other types other for XML output archives (except minimal types)
  684. /*! Finishes the node created in the prologue
  685. Minimal types do not start or end nodes */
  686. template <class T, traits::DisableIf<traits::has_minimal_base_class_serialization<T, traits::has_minimal_output_serialization, XMLOutputArchive>::value ||
  687. traits::has_minimal_output_serialization<T, XMLOutputArchive>::value> = traits::sfinae> inline
  688. void epilogue( XMLOutputArchive & ar, T const & )
  689. {
  690. ar.finishNode();
  691. }
  692. //! Epilogue for all other types other for XML output archives (except minimal types)
  693. template <class T, traits::DisableIf<traits::has_minimal_base_class_serialization<T, traits::has_minimal_input_serialization, XMLInputArchive>::value ||
  694. traits::has_minimal_input_serialization<T, XMLInputArchive>::value> = traits::sfinae> inline
  695. void epilogue( XMLInputArchive & ar, T const & )
  696. {
  697. ar.finishNode();
  698. }
  699. // ######################################################################
  700. // Common XMLArchive serialization functions
  701. // ######################################################################
  702. //! Saving NVP types to XML
  703. template <class T> inline
  704. void CEREAL_SAVE_FUNCTION_NAME( XMLOutputArchive & ar, NameValuePair<T> const & t )
  705. {
  706. ar.setNextName( t.name );
  707. ar( t.value );
  708. }
  709. //! Loading NVP types from XML
  710. template <class T> inline
  711. void CEREAL_LOAD_FUNCTION_NAME( XMLInputArchive & ar, NameValuePair<T> & t )
  712. {
  713. ar.setNextName( t.name );
  714. ar( t.value );
  715. }
  716. // ######################################################################
  717. //! Saving SizeTags to XML
  718. template <class T> inline
  719. void CEREAL_SAVE_FUNCTION_NAME( XMLOutputArchive &, SizeTag<T> const & )
  720. { }
  721. //! Loading SizeTags from XML
  722. template <class T> inline
  723. void CEREAL_LOAD_FUNCTION_NAME( XMLInputArchive & ar, SizeTag<T> & st )
  724. {
  725. ar.loadSize( st.size );
  726. }
  727. // ######################################################################
  728. //! Saving for POD types to xml
  729. template <class T, traits::EnableIf<std::is_arithmetic<T>::value> = traits::sfinae> inline
  730. void CEREAL_SAVE_FUNCTION_NAME(XMLOutputArchive & ar, T const & t)
  731. {
  732. ar.saveValue( t );
  733. }
  734. //! Loading for POD types from xml
  735. template <class T, traits::EnableIf<std::is_arithmetic<T>::value> = traits::sfinae> inline
  736. void CEREAL_LOAD_FUNCTION_NAME(XMLInputArchive & ar, T & t)
  737. {
  738. ar.loadValue( t );
  739. }
  740. // ######################################################################
  741. //! saving string to xml
  742. template<class CharT, class Traits, class Alloc> inline
  743. void CEREAL_SAVE_FUNCTION_NAME(XMLOutputArchive & ar, std::basic_string<CharT, Traits, Alloc> const & str)
  744. {
  745. ar.saveValue( str );
  746. }
  747. //! loading string from xml
  748. template<class CharT, class Traits, class Alloc> inline
  749. void CEREAL_LOAD_FUNCTION_NAME(XMLInputArchive & ar, std::basic_string<CharT, Traits, Alloc> & str)
  750. {
  751. ar.loadValue( str );
  752. }
  753. } // namespace cereal
  754. // register archives for polymorphic support
  755. CEREAL_REGISTER_ARCHIVE(cereal::XMLOutputArchive)
  756. CEREAL_REGISTER_ARCHIVE(cereal::XMLInputArchive)
  757. // tie input and output archives together
  758. CEREAL_SETUP_ARCHIVE_TRAITS(cereal::XMLInputArchive, cereal::XMLOutputArchive)
  759. #endif // CEREAL_ARCHIVES_XML_HPP_